diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/files.cmake b/BlueBerry/Bundles/org.blueberry.core.commands/files.cmake index 1ee3011459..163e67c47c 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/files.cmake +++ b/BlueBerry/Bundles/org.blueberry.core.commands/files.cmake @@ -1,59 +1,67 @@ set(MOC_H_FILES + src/berryAbstractHandler.h + src/internal/berryPluginActivator.h ) set(SRC_CPP_FILES berryAbstractHandler.cpp + berryAbstractHandlerWithState.cpp berryCommand.cpp berryCommandCategory.cpp berryCommandCategoryEvent.cpp berryCommandEvent.cpp berryCommandManager.cpp berryCommandManagerEvent.cpp berryExecutionEvent.cpp berryHandlerEvent.cpp berryICommandCategoryListener.cpp berryICommandListener.cpp berryICommandManagerListener.cpp berryIExecutionListener.cpp berryIExecutionListenerWithChecks.cpp + berryIHandler.h berryIHandlerListener.cpp berryINamedHandleStateIds.cpp + berryIObjectWithState.h + berryIParameter.h berryIParameterTypeListener.cpp + berryIParameterValueConverter.cpp + berryIParameterValues.cpp berryIStateListener.cpp berryNamedHandleObjectWithState.cpp berryParameterization.cpp berryParameterizedCommand.cpp berryParameterType.cpp berryParameterTypeEvent.cpp berryState.cpp util/berryCommandTracing.cpp ) set(COMMON_CPP_FILES berryAbstractBitSetEvent.cpp berryAbstractHandleObjectEvent.cpp berryAbstractNamedHandleEvent.cpp berryCommandExceptions.cpp berryHandleObject.cpp berryHandleObjectManager.cpp berryNamedHandleObject.cpp ) set(INTERNAL_CPP_FILES berryCommandUtils.cpp berryPluginActivator.cpp ) foreach(file ${SRC_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/${file}) endforeach(file ${SRC_CPP_FILES}) foreach(file ${COMMON_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/common/${file}) endforeach(file ${COMMON_CPP_FILES}) foreach(file ${INTERNAL_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/internal/${file}) endforeach(file ${INTERNAL_CPP_FILES}) diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandler.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandler.cpp index 512a980a11..a7bfb6823b 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandler.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandler.cpp @@ -1,48 +1,85 @@ /*=================================================================== 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 "berryAbstractHandler.h" +#include "berryHandlerEvent.h" + namespace berry { AbstractHandler::AbstractHandler() : baseEnabled(true) { } -bool AbstractHandler::IsEnabled() +void AbstractHandler::AddHandlerListener(IHandlerListener *handlerListener) +{ + handlerListeners.AddListener(handlerListener); +} + +void AbstractHandler::Dispose() +{ + // Do nothing. +} + +bool AbstractHandler::IsEnabled() const { return baseEnabled; } -bool AbstractHandler::IsHandled() +void AbstractHandler::SetEnabled(const Object::Pointer& /*evaluationContext*/) +{ +} + +bool AbstractHandler::IsHandled() const { return true; } +void AbstractHandler::RemoveHandlerListener(IHandlerListener *handlerListener) +{ + handlerListeners.RemoveListener(handlerListener); +} + +void AbstractHandler::FireHandlerChanged(const SmartPointer& handlerEvent) +{ + if (handlerEvent.IsNull()) + { + throw ctkInvalidArgumentException("Cannot fire a null handler event"); + } + + handlerListeners.handlerChanged(handlerEvent); +} + void AbstractHandler::SetBaseEnabled(bool state) { if (baseEnabled == state) { return; } baseEnabled = state; - //fireHandlerChanged(new HandlerEvent(this, true, false)); + HandlerEvent::Pointer event(new HandlerEvent(IHandler::Pointer(this), true, false)); + FireHandlerChanged(event); +} + +bool AbstractHandler::HasListeners() const +{ + return handlerListeners.handlerChanged.HasListeners(); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandler.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandler.h index 57e6140f9b..6679f6c7f8 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandler.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandler.h @@ -1,172 +1,163 @@ /*=================================================================== 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 BERRYABSTRACTHANDLER_H_ #define BERRYABSTRACTHANDLER_H_ #include "berryIHandler.h" +#include "berryIHandlerListener.h" + #include namespace berry { /** *

* This class is a partial implementation of IHandler. This * abstract implementation provides support for handler listeners. You should * subclass from this class unless you want to implement your own listener * support. Subclasses should call * {@link AbstractHandler#fireHandlerChanged(HandlerEvent)}when the handler * changes. Subclasses can also override {@link AbstractHandler#isEnabled()} and * {@link AbstractHandler#isHandled()}. *

- * - * @since 3.1 */ -class BERRY_COMMANDS AbstractHandler : public IHandler { // ,public EventManager { +class BERRY_COMMANDS AbstractHandler : public QObject, public IHandler { // ,public EventManager { + + Q_OBJECT + Q_INTERFACES(berry::IHandler) public: berryObjectMacro(AbstractHandler); private: /** * Track this base class enabled state. - * - * @since 3.4 */ bool baseEnabled; + IHandlerListener::Events handlerListeners; public: AbstractHandler(); /** * @see IHandler#addHandlerListener(IHandlerListener) */ -// void AddHandlerListener(final IHandlerListener handlerListener) { -// addListenerObject(handlerListener); -// } + void AddHandlerListener(IHandlerListener* handlerListener); /** * The default implementation does nothing. Subclasses who attach listeners * to other objects are encouraged to detach them in this method. * - * @see org.blueberry.core.commands.IHandler#dispose() + * @see IHandler#Dispose() */ - ~AbstractHandler() { - // Do nothing. - } + void Dispose(); /** * Whether this handler is capable of executing at this time. Subclasses may * override this method. If clients override this method they should also * consider overriding {@link #setEnabled(Object)} so they can be notified * about framework execution contexts. * * @return true * @see #setEnabled(Object) * @see #setBaseEnabled(boolean) */ - bool IsEnabled(); + bool IsEnabled() const; + + /** + * Called by the framework to allow the handler to update its enabled state + * by extracting the same information available at execution time. Clients + * may override if they need to extract information from the application + * context. + * + * @param evaluationContext + * the application context. May be null + * @see #SetBaseEnabled(bool) + */ + void SetEnabled(const Object::Pointer& evaluationContext); /** * Whether this handler is capable of handling delegated responsibilities at * this time. Subclasses may override this method. * * @return true */ - bool IsHandled(); + bool IsHandled() const; /** * @see IHandler#removeHandlerListener(IHandlerListener) */ -// void RemoveHandlerListener(final IHandlerListener handlerListener) { -// removeListenerObject(handlerListener); -// } - + void RemoveHandlerListener(IHandlerListener* handlerListener); protected: /** * Fires an event to all registered listeners describing changes to this * instance. *

* Subclasses may extend the definition of this method (i.e., if a different * type of listener can be attached to a subclass). This is used primarily * for support of AbstractHandler in * org.blueberry.ui.workbench, and clients should be wary of * overriding this behaviour. If this method is overridden, then the first * line of the method should be "super.fireHandlerChanged(handlerEvent);". *

* * @param handlerEvent * the event describing changes to this instance. Must not be * null. */ -// void FireHandlerChanged(final HandlerEvent handlerEvent) { -// if (handlerEvent == null) { -// throw new NullPointerException(); -// } -// -// final Object[] listeners = getListeners(); -// for (int i = 0; i < listeners.length; i++) { -// final IHandlerListener listener = (IHandlerListener) listeners[i]; -// listener.handlerChanged(handlerEvent); -// } -// } - - + void FireHandlerChanged(const SmartPointer& handlerEvent); /** * Allow the default {@link #isEnabled()} to answer our enabled state. It * will fire a HandlerEvent if necessary. If clients use this method they * should also consider overriding {@link #setEnabled(Object)} so they can * be notified about framework execution contexts. * * @param state * the enabled state - * @since 3.4 */ void SetBaseEnabled(bool state); /** *

* Returns true iff there is one or more IHandlerListeners attached to this * AbstractHandler. *

*

* Subclasses may extend the definition of this method (i.e., if a different * type of listener can be attached to a subclass). This is used primarily * for support of AbstractHandler in - * org.blueberry.ui.workbench, and clients should be wary of + * org.blueberry.ui.qt, and clients should be wary of * overriding this behaviour. If this method is overridden, then the return * value should include "super.hasListeners() ||". *

* * @return true iff there is one or more IHandlerListeners attached to this * AbstractHandler */ -// bool HasListeners() { -// return isListenerAttached(); -// } - + virtual bool HasListeners() const; }; } #endif /*BERRYABSTRACTHANDLER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandlerWithState.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandlerWithState.cpp new file mode 100644 index 0000000000..8e3827ad1a --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandlerWithState.cpp @@ -0,0 +1,62 @@ +/*=================================================================== + +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 "berryAbstractHandlerWithState.h" + +#include "berryState.h" + +namespace berry { + +void AbstractHandlerWithState::AddState(const QString& stateId, const SmartPointer& state) +{ + if (state.IsNull()) + { + throw ctkInvalidArgumentException("Cannot add a null state"); + } + + states.insert(stateId, state); + state->AddListener(this); + HandleStateChange(state, Object::Pointer(0)); +} + +SmartPointer AbstractHandlerWithState::GetState(const QString& stateId) const +{ + QHash::const_iterator i = states.find(stateId); + if (i != states.end()) return *i; + return State::Pointer(0); +} + +QList AbstractHandlerWithState::GetStateIds() const +{ + return states.keys(); +} + +void AbstractHandlerWithState::RemoveState(const QString& stateId) +{ + if (stateId.isNull()) + { + throw ctkInvalidArgumentException("Cannot remove a null state"); + } + + QHash::iterator i = states.find(stateId); + if (i != states.end()) + { + (*i)->RemoveListener(this); + states.erase(i); + } +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandlerWithState.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandlerWithState.h new file mode 100644 index 0000000000..07fba499ca --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandlerWithState.h @@ -0,0 +1,101 @@ +/*=================================================================== + +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 BERRYABSTRACTHANDLERWITHSTATE_H +#define BERRYABSTRACTHANDLERWITHSTATE_H + +#include "berryAbstractHandler.h" +#include "berryIObjectWithState.h" +#include "berryIStateListener.h" + +#include + +namespace berry { + +class State; + +/** + *

+ * An abstract implementation of {@link IObjectWithState}. This provides basic + * handling for adding and remove state. When state is added, the handler + * attaches itself as a listener and fire a handleStateChange event to notify + * this handler. When state is removed, the handler removes itself as a + * listener. + *

+ *

+ * Clients may extend this class. + *

+ */ +class BERRY_COMMANDS AbstractHandlerWithState : public AbstractHandler, public IObjectWithState, + protected IStateListener +{ + +private: + + /** + * The map of states currently held by this handler. If this handler has no + * state (generally, when inactive), then this will be null. + */ + QHash > states; + +public: + + berryObjectMacro(berry::AbstractHandlerWithState) + + /** + *

+ * Adds a state to this handler. This will add this handler as a listener to + * the state, and then fire a handleStateChange so that the handler can + * respond to the incoming state. + *

+ *

+ * Clients may extend this method, but they should call this super method + * first before doing anything else. + *

+ * + * @param stateId + * The identifier indicating the type of state being added; must + * not be null. + * @param state + * The state to add; must not be null. + */ + void AddState(const QString& stateId, const SmartPointer& state); + + SmartPointer GetState(const QString& stateId) const; + + QList GetStateIds() const; + + /** + *

+ * Removes a state from this handler. This will remove this handler as a + * listener to the state. No event is fired to notify the handler of this + * change. + *

+ *

+ * Clients may extend this method, but they should call this super method + * first before doing anything else. + *

+ * + * @param stateId + * The identifier of the state to remove; must not be + * null. + */ + void RemoveState(const QString& stateId); +}; + +} + +#endif // BERRYABSTRACTHANDLERWITHSTATE_H diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommand.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommand.cpp index 654256f3ff..c1bfc88bd3 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommand.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommand.cpp @@ -1,560 +1,559 @@ /*=================================================================== 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 "berryCommand.h" #include "berryIParameter.h" #include "berryITypedParameter.h" #include "berryIHandler.h" #include "berryIHandlerListener.h" #include "berryIParameterValueConverter.h" #include "berryHandlerEvent.h" #include "berryCommandEvent.h" #include "berryExecutionEvent.h" #include "berryCommandCategory.h" +#include "berryState.h" #include "util/berryCommandTracing.h" #include "internal/berryCommandUtils.h" #include namespace berry { -bool Command::DEBUG_COMMAND_EXECUTION = false; +bool Command::DEBUG_COMMAND_EXECUTION = true; -bool Command::DEBUG_HANDLERS = false; +bool Command::DEBUG_HANDLERS = true; QString Command::DEBUG_HANDLERS_COMMAND_ID = ""; Command::Command(const QString& id) : NamedHandleObjectWithState(id) { } void Command::AddCommandListener(ICommandListener* commandListener) { if (!commandListener) { throw ctkInvalidArgumentException("Cannot add a null command listener"); } commandEvents.AddListener(commandListener); } void Command::AddExecutionListener(IExecutionListener* executionListener) { if (!executionListener) { throw ctkInvalidArgumentException("Cannot add a null execution listener"); } executionEvents.AddListener(executionListener); } -void Command::AddState(const QString& id, const State::Pointer state) +void Command::AddState(const QString& id, const State::Pointer& state) { NamedHandleObjectWithState::AddState(id, state); state->SetId(id); if (IObjectWithState::Pointer stateHandler = handler.Cast()) { stateHandler->AddState(id, state); } } bool Command::operator<(const Object* object) const { const Command* castedObject = dynamic_cast(object); int compareTo = CommandUtils::CompareObj(category, castedObject->category); if (compareTo == 0) { compareTo = CommandUtils::Compare(defined, castedObject->defined); if (compareTo == 0) { compareTo = CommandUtils::Compare(description, castedObject->description); if (compareTo == 0) { compareTo = CommandUtils::CompareObj(handler, castedObject->handler); if (compareTo == 0) { compareTo = CommandUtils::Compare(id, castedObject->id); if (compareTo == 0) { compareTo = CommandUtils::Compare(name, castedObject->name); if (compareTo == 0) { compareTo = CommandUtils::Compare(parameters, castedObject->parameters); } } } } } } return compareTo < 0; } void Command::Define(const QString& name, const QString& description, const CommandCategory::Pointer category, const QList& parameters, const ParameterType::Pointer& returnType, const QString& helpContextId) { if (name == "") { throw ctkInvalidArgumentException("The name of a command cannot be empty"); } if (!category) { throw ctkInvalidArgumentException("The category of a command cannot be null"); } const bool definedChanged = !this->defined; this->defined = true; const bool nameChanged = this->name != name; this->name = name; const bool descriptionChanged = this->description != description; this->description = description; const bool categoryChanged = this->category != category; this->category = category; const bool parametersChanged = !CommandUtils::Equals(this->parameters, parameters); this->parameters = parameters; const bool returnTypeChanged = this->returnType != returnType; this->returnType = returnType; const bool helpContextIdChanged = this->helpContextId != helpContextId; this->helpContextId = helpContextId; CommandEvent::Pointer event(new CommandEvent(Command::Pointer(this), categoryChanged, definedChanged, descriptionChanged, false, nameChanged, parametersChanged, returnTypeChanged, helpContextIdChanged)); this->FireCommandChanged(event); } Object::Pointer Command::ExecuteWithChecks(const ExecutionEvent::ConstPointer event) { this->FirePreExecute(event); const IHandler::Pointer handler(this->handler); if (!this->IsDefined()) { const NotDefinedException exception( "Trying to execute a command that is not defined. " + this->GetId()); this->FireNotDefined(&exception); throw exception; } // Perform the execution, if there is a handler. if (handler && handler->IsHandled()) { this->SetEnabled(event->GetApplicationContext()); if (!this->IsEnabled()) { const NotEnabledException exception( "Trying to execute the disabled command " + this->GetId()); this->FireNotEnabled(&exception); throw exception; } try { const Object::Pointer returnValue(handler->Execute(event)); this->FirePostExecuteSuccess(returnValue); return returnValue; } catch (const ExecutionException* e) { this->FirePostExecuteFailure(e); throw e; } } const NotHandledException e( "There is no handler to execute for command " + this->GetId()); this->FireNotHandled(&e); throw e; } void Command::FireCommandChanged(const CommandEvent::ConstPointer commandEvent) { if (!commandEvent) { throw ctkInvalidArgumentException("Cannot fire a null event"); } try { commandEvents.commandChanged(commandEvent); } catch (...) { //TODO log exceptions? } } void Command::FireNotDefined(const NotDefinedException* e) { // Debugging output if (DEBUG_COMMAND_EXECUTION) { CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR + "not defined: id=" + this->GetId() + "; exception=" + e->what()); } executionEvents.notDefined(this->GetId(), e); } void Command::FireNotEnabled(const NotEnabledException* e) { // Debugging output if (DEBUG_COMMAND_EXECUTION) { CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR + "not enabled: id=" + this->GetId() + "; exception=" + e->what()); } executionEvents.notEnabled(this->GetId(), e); } void Command::FireNotHandled(const NotHandledException* e) { // Debugging output if (DEBUG_COMMAND_EXECUTION) { CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR + "not handled: id=" + this->GetId() + "; exception=" + e->what()); } executionEvents.notHandled(this->GetId(), e); } void Command::FirePostExecuteFailure(const ExecutionException* e) { // Debugging output if (DEBUG_COMMAND_EXECUTION) { CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR + "failure: id=" + this->GetId() + "; exception=" + e->what()); } executionEvents.postExecuteFailure(this->GetId(), e); } void Command::FirePostExecuteSuccess(const Object::Pointer returnValue) { // Debugging output if (DEBUG_COMMAND_EXECUTION) { CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR - + "success: id=" + this->GetId() + "; returnValue=" + returnValue->ToString()); + + "success: id=" + this->GetId() + "; returnValue=" + + (returnValue.IsNull() ? QString("NULL") : returnValue->ToString())); } executionEvents.postExecuteSuccess(this->GetId(), returnValue); } void Command::FirePreExecute(const ExecutionEvent::ConstPointer event) { // Debugging output if (DEBUG_COMMAND_EXECUTION) { CommandTracing::PrintTrace("COMMANDS", "execute" + CommandTracing::SEPARATOR + "starting: id=" + this->GetId() + "; event=" + event->ToString()); } executionEvents.preExecute(this->GetId(), event); } IHandler::Pointer Command::GetHandler() const { return handler; } QString Command::GetHelpContextId() const { return helpContextId; } IParameter::Pointer Command::GetParameter(const QString& parameterId) const { if (!this->IsDefined()) { throw NotDefinedException( "Cannot get a parameter from an undefined command. " + id); } - for (unsigned int i = 0; i < parameters.size(); i++) + for (int i = 0; i < parameters.size(); i++) { IParameter::Pointer parameter(parameters[i]); if (parameter->GetId() == parameterId) { return parameter; } } return IParameter::Pointer(0); } QList > Command::GetParameters() const { if (!this->IsDefined()) { throw NotDefinedException( "Cannot get the parameters from an undefined command. " + id); } return parameters; } ParameterType::Pointer Command::GetParameterType(const QString& parameterId) const { const IParameter::Pointer parameter(this->GetParameter(parameterId)); if (ITypedParameter::Pointer parameterWithType = parameter.Cast()) { return parameterWithType->GetParameterType(); } return ParameterType::Pointer(0); } ParameterType::Pointer Command::GetReturnType() const { if (!this->IsDefined()) { throw NotDefinedException( "Cannot get the return type of an undefined command. " + id); } return returnType; } bool Command::IsEnabled() const { if (!handler) { return false; } return handler->IsEnabled(); } -void Command::SetEnabled(Object::ConstPointer evaluationContext) +void Command::SetEnabled(const Object::Pointer& evaluationContext) { - handler->SetEnabled(evaluationContext); + if (handler) + { + handler->SetEnabled(evaluationContext); + } } bool Command::IsHandled() const { if (!handler) { return false; } return handler->IsHandled(); } void Command::RemoveCommandListener(ICommandListener *commandListener) { if (!commandListener) { throw ctkInvalidArgumentException( "Cannot remove a null command listener"); } commandEvents.RemoveListener(commandListener); } /** * Removes a listener from this command. * * @param executionListener * The listener to be removed; must not be null. * */ void Command::RemoveExecutionListener(IExecutionListener* executionListener) { if (!executionListener) { throw Poco::NullPointerException( "Cannot remove a null execution listener"); } executionEvents.RemoveListener(executionListener); } void Command::RemoveState(const QString& stateId) { if (IObjectWithState::Pointer stateHandler = handler.Cast()) { stateHandler->RemoveState(stateId); } NamedHandleObjectWithState::RemoveState(stateId); } bool Command::SetHandler(const IHandler::Pointer handler) { if (handler == this->handler) { return false; } // Swap the state around. - const QStringList stateIds(this->GetStateIds()); - for (unsigned int i = 0; i < stateIds.size(); ++i) + const QList stateIds(this->GetStateIds()); + for (int i = 0; i < stateIds.size(); ++i) { const QString stateId = stateIds[i]; if (IObjectWithState::Pointer stateHandler = this->handler.Cast()) { stateHandler->RemoveState(stateId); } if (IObjectWithState::Pointer stateHandler = handler.Cast()) { const State::Pointer stateToAdd(this->GetState(stateId)); stateHandler->AddState(stateId, stateToAdd); } } bool enabled = this->IsEnabled(); if (this->handler) { this->handler->RemoveHandlerListener(this->GetHandlerListener()); } // Update the handler, and flush the string representation. this->handler = handler; if (this->handler) { this->handler->AddHandlerListener(this->GetHandlerListener()); } this->str = ""; // Debugging output if ((DEBUG_HANDLERS) && ((DEBUG_HANDLERS_COMMAND_ID.isEmpty()) || (DEBUG_HANDLERS_COMMAND_ID == id))) { QString buffer("Command('"); buffer += id + "') has changed to "; if (!handler) { buffer += "no handler"; } else { buffer += "\'" + handler->ToString() + "' as its handler"; } CommandTracing::PrintTrace("HANDLERS", buffer); } // Send notification CommandEvent::Pointer cmdEvent(new CommandEvent(Command::Pointer(this), false, false, false, true, false, false, false, false, enabled != this->IsEnabled())); this->FireCommandChanged(cmdEvent); return true; } -SmartPointer Command::GetHandlerListener() +IHandlerListener* Command::GetHandlerListener() { - if (!handlerListener) - { - struct HandlerListener : public IHandlerListener - { - HandlerListener(Command* command) : command(command) {} - - void HandlerChanged(SmartPointer handlerEvent) - { - bool enabledChanged = handlerEvent->IsEnabledChanged(); - bool handledChanged = handlerEvent->IsHandledChanged(); - CommandEvent::Pointer cmdEvent(new CommandEvent(Command::Pointer(command), false, - false, false, handledChanged, false, false, false, - false, enabledChanged)); - command->FireCommandChanged(cmdEvent); - } + return this; +} - private: - Command* command; - }; - handlerListener = new HandlerListener(this); - } - return handlerListener; +void Command::HandlerChanged(const SmartPointer& handlerEvent) +{ + bool enabledChanged = handlerEvent->IsEnabledChanged(); + bool handledChanged = handlerEvent->IsHandledChanged(); + CommandEvent::Pointer cmdEvent(new CommandEvent(Command::Pointer(this), false, + false, false, handledChanged, false, false, false, + false, enabledChanged)); + this->FireCommandChanged(cmdEvent); } QString Command::ToString() const { if (str.isEmpty()) { QTextStream buffer(&str); buffer << "Command(" << id << ',' << name << ",\n\t\t"; buffer << description << ",\n\t\t" << (category ? category->ToString() : QString("")); buffer << ",\n\t\t" << (handler ? handler->ToString() : ""); buffer << ",\n\t\t" << "["; - for (unsigned int i = 0; i < parameters.size(); ++i) + for (int i = 0; i < parameters.size(); ++i) { buffer << parameters[i]->GetId(); } buffer << "]," << (returnType ? returnType->ToString() : ""); buffer << "," << defined << ")"; } return str; } void Command::Undefine() { bool enabledChanged = this->IsEnabled(); str = ""; const bool definedChanged = defined; defined = false; const bool nameChanged = !name.isEmpty(); name = ""; const bool descriptionChanged = !description.isEmpty(); description = ""; const bool categoryChanged = category; category = 0; const bool parametersChanged = !parameters.empty(); parameters.clear(); const bool returnTypeChanged = returnType; returnType = 0; - const QStringList stateIds(this->GetStateIds()); - if (IObjectWithState::Pointer handlerWithState = handler.Cast()) { - for (unsigned int i = 0; i < stateIds.size(); i++) { + const QList stateIds(this->GetStateIds()); + if (IObjectWithState::Pointer handlerWithState = handler.Cast()) + { + for (int i = 0; i < stateIds.size(); i++) + { const QString stateId(stateIds[i]); handlerWithState->RemoveState(stateId); const State::Pointer state(this->GetState(stateId)); this->RemoveState(stateId); //state.dispose(); } - } else { - for (unsigned int i = 0; i < stateIds.size(); ++i) { + } + else + { + for (int i = 0; i < stateIds.size(); ++i) + { const QString stateId(stateIds[i]); const State::Pointer state(this->GetState(stateId)); this->RemoveState(stateId); //state.dispose(); } } CommandEvent::Pointer cmdEvent(new CommandEvent(Command::Pointer(this), categoryChanged, definedChanged, descriptionChanged, false, nameChanged, parametersChanged, returnTypeChanged, false, enabledChanged)); this->FireCommandChanged(cmdEvent); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommand.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommand.h index 5acd59a49b..7ad522c1e6 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommand.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommand.h @@ -1,513 +1,513 @@ /*=================================================================== 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 BERRYCOMMAND_H_ #define BERRYCOMMAND_H_ #include "berryNamedHandleObjectWithState.h" #include +#include #include #include #include namespace berry { class CommandCategory; class ExecutionEvent; struct IHandler; -struct IHandlerListener; /** *

* A command is an abstract representation for some semantic behaviour. It is * not the actual implementation of this behaviour, nor is it the visual * appearance of this behaviour in the user interface. Instead, it is a bridge * between the two. *

*

* The concept of a command is based on the command design pattern. The notable * difference is how the command delegates responsibility for execution. Rather * than allowing concrete subclasses, it uses a handler mechanism (see the * handlers extension point). This provides another level of * indirection. *

*

* A command will exist in two states: defined and undefined. A command is * defined if it is declared in the XML of a resolved plug-in. If the plug-in is * unloaded or the command is simply not declared, then it is undefined. Trying * to reference an undefined command will succeed, but trying to access any of * its functionality will fail with a NotDefinedException. If * you need to know when a command changes from defined to undefined (or vice * versa), then attach a command listener. *

*

* Commands are mutable and will change as their definition changes. *

* */ -class BERRY_COMMANDS Command : public NamedHandleObjectWithState +class BERRY_COMMANDS Command : public NamedHandleObjectWithState, private IHandlerListener { // implements Comparable { public: berryObjectMacro(Command); /** * This flag can be set to true if commands should print * information to System.out when executing. */ static bool DEBUG_COMMAND_EXECUTION; /** * This flag can be set to true if commands should print * information to System.out when changing handlers. */ static bool DEBUG_HANDLERS; /** * This flag can be set to a particular command identifier if only that * command should print information to System.out when * changing handlers. */ static QString DEBUG_HANDLERS_COMMAND_ID; private: /** * The category to which this command belongs. This value should not be * null unless the command is undefined. */ SmartPointer category; /** * A collection of objects listening to the execution of this command. */ IExecutionListenerWithChecks::Events executionEvents; //ListenerList executionListeners; /** * A collection of objects listening to changes of this command. */ ICommandListener::Events commandEvents; /** * The handler currently associated with this command. This value may be * null if there is no handler currently. */ SmartPointer handler; /** * The help context identifier for this command. This can be * null if there is no help currently associated with the * command. */ QString helpContextId; /** * The ordered array of parameters understood by this command. This value * may be null if there are no parameters, or if the command * is undefined. It may also be empty. */ QList > parameters; /** * The type of the return value of this command. This value may be * null if the command does not declare a return type. */ SmartPointer returnType; - /** - * Our command will listen to the active handler for enablement changes so - * that they can be fired from the command itself. - */ - SmartPointer handlerListener; - protected: /** * Constructs a new instance of Command based on the given * identifier. When a command is first constructed, it is undefined. * Commands should only be constructed by the CommandManager * to ensure that the identifier remains unique. * * @param id * The identifier for the command. This value must not be * null, and must be unique amongst all commands. */ Command(const QString& id); friend class CommandManager; public: /** * Adds a listener to this command that will be notified when this command's * state changes. * * @param commandListener * The listener to be added; must not be null. */ void AddCommandListener(ICommandListener* commandListener); /** * Adds a listener to this command that will be notified when this command * is about to execute. * * @param executionListener * The listener to be added; must not be null. */ void AddExecutionListener(IExecutionListener* executionListener); /** *

* Adds a state to this command. This will add this state to the active * handler, if the active handler is an instance of {@link IObjectWithState}. *

*

* A single instance of {@link State} cannot be registered with multiple * commands. Each command requires its own unique instance. *

* * @param id * The identifier of the state to add; must not be * null. * @param state * The state to add; must not be null. */ - void AddState(const QString& id, const State::Pointer state); + void AddState(const QString& id, const SmartPointer& state); /** * Compares this command with another command by comparing each of its * non-transient attributes. * * @param object * The object with which to compare; must be an instance of * Command. * @return false if the object is * equal to or greater than this command. */ bool operator<(const Object* object) const; /** *

* Defines this command by giving it a name, and possibly a description as * well. The defined property automatically becomes true. *

*

* Notification is sent to all listeners that something has changed. *

* * @param name * The name of this command; must not be null. * @param description * The description for this command; may be null. * @param category * The category for this command; must not be null. * @param parameters * The parameters understood by this command. This value may be * either null or empty if the command does not * accept parameters. * @param returnType * The type of value returned by this command. This value may be * null if the command does not declare a return * type. * @param helpContextId * The identifier of the help context to associate with this * command; may be null if this command does not * have any help associated with it. */ void Define(const QString& name, const QString& description, const SmartPointer category, const QList >& parameters = QList >(), const SmartPointer& returnType = SmartPointer(0), const QString& helpContextId = ""); /** * Executes this command by delegating to the current handler, if any. If * the debugging flag is set, then this method prints information about * which handler is selected for performing this command. This does checks * to see if the command is enabled and defined. If it is not both enabled * and defined, then the execution listeners will be notified and an * exception thrown. * * @param event * An event containing all the information about the current * state of the application; must not be null. * @return The result of the execution; may be null. This * result will be available to the client executing the command, and * execution listeners. * @throws ExecutionException * If the handler has problems executing this command. * @throws NotDefinedException * If the command you are trying to execute is not defined. * @throws NotEnabledException * If the command you are trying to execute is not enabled. * @throws NotHandledException * If there is no handler. */ Object::Pointer ExecuteWithChecks(const SmartPointer event); private: /** * Notifies the listeners for this command that it has changed in some way. * * @param commandEvent * The event to send to all of the listener; must not be * null. */ void FireCommandChanged(const SmartPointer commandEvent); /** * Notifies the execution listeners for this command that an attempt to * execute has failed because the command is not defined. * * @param e * The exception that is about to be thrown; never * null. * @since 3.2 */ void FireNotDefined(const NotDefinedException* e); /** * Notifies the execution listeners for this command that an attempt to * execute has failed because there is no handler. * * @param e * The exception that is about to be thrown; never * null. */ void FireNotEnabled(const NotEnabledException* e); /** * Notifies the execution listeners for this command that an attempt to * execute has failed because there is no handler. * * @param e * The exception that is about to be thrown; never * null. */ void FireNotHandled(const NotHandledException* e); /** * Notifies the execution listeners for this command that an attempt to * execute has failed during the execution. * * @param e * The exception that has been thrown; never null. * After this method completes, the exception will be thrown * again. */ void FirePostExecuteFailure(const ExecutionException* e); /** * Notifies the execution listeners for this command that an execution has * completed successfully. * * @param returnValue * The return value from the command; may be null. */ void FirePostExecuteSuccess(const Object::Pointer returnValue); /** * Notifies the execution listeners for this command that an attempt to * execute is about to start. * * @param event * The execution event that will be used; never null. */ void FirePreExecute(const SmartPointer event); public: /** * Returns the current handler for this command. This is used by the command * manager for determining the appropriate help context identifiers and by * the command service to allow handlers to update elements. *

* This value can change at any time and should never be cached. *

* * @return The current handler for this command; may be null. */ SmartPointer GetHandler() const; /** * Returns the help context identifier associated with this command. This * method should not be called by clients. Clients should use * {@link CommandManager#getHelpContextId(Command)} instead. * * @return The help context identifier for this command; may be * null if there is none. */ QString GetHelpContextId() const; /** * Returns the parameter with the provided id or null if this * command does not have a parameter with the id. * * @param parameterId * The id of the parameter to retrieve. * @return The parameter with the provided id or null if this * command does not have a parameter with the id. * @throws NotDefinedException * If the handle is not currently defined. */ SmartPointer GetParameter(const QString& parameterId) const; /** * Returns the parameters for this command. This call triggers provides a * copy of the array, so excessive calls to this method should be avoided. * * @return The parameters for this command. This value might be * null, if the command has no parameters. * @throws NotDefinedException * If the handle is not currently defined. */ QList > GetParameters() const; /** * Returns the {@link ParameterType} for the parameter with the provided id * or null if this command does not have a parameter type * with the id. * * @param parameterId * The id of the parameter to retrieve the {@link ParameterType} * of. * @return The {@link ParameterType} for the parameter with the provided id * or null if this command does not have a parameter * type with the provided id. * @throws NotDefinedException * If the handle is not currently defined. */ SmartPointer GetParameterType(const QString& parameterId) const; /** * Returns the {@link ParameterType} for the return value of this command or * null if this command does not declare a return value * parameter type. * * @return The {@link ParameterType} for the return value of this command or * null if this command does not declare a return * value parameter type. * @throws NotDefinedException * If the handle is not currently defined. */ SmartPointer GetReturnType() const; /** * Returns whether this command has a handler, and whether this handler is * also handled and enabled. * * @return true if the command is handled; false * otherwise. */ bool IsEnabled() const; /** * Called be the framework to allow the handler to update its enabled state. * * @param evaluationContext * the state to evaluate against. May be null * which indicates that the handler can query whatever model that * is necessary. This context must not be cached. */ - void SetEnabled(Object::ConstPointer evaluationContext); + void SetEnabled(const Object::Pointer& evaluationContext); /** * Returns whether this command has a handler, and whether this handler is * also handled. * * @return true if the command is handled; false * otherwise. */ bool IsHandled() const; /** * Removes a listener from this command. * * @param commandListener * The listener to be removed; must not be null. * */ void RemoveCommandListener(ICommandListener* commandListener); /** * Removes a listener from this command. * * @param executionListener * The listener to be removed; must not be null. * */ void RemoveExecutionListener(IExecutionListener* executionListener); /** *

* Removes a state from this command. This will remove the state from the * active handler, if the active handler is an instance of * {@link IObjectWithState}. *

* * @param stateId * The identifier of the state to remove; must not be * null. */ void RemoveState(const QString& stateId); /** * Changes the handler for this command. This will remove all the state from * the currently active handler (if any), and add it to handler. * If debugging is turned on, then this will also print information about * the change to System.out. * * @param handler * The new handler; may be null if none. * @return true if the handler changed; false * otherwise. */ bool SetHandler(const SmartPointer handler); private: /** * @return the handler listener */ - SmartPointer GetHandlerListener(); + IHandlerListener* GetHandlerListener(); + + /** + * Our command will listen to the active handler for enablement changes so + * that they can be fired from the command itself. + */ + void HandlerChanged(const SmartPointer& handlerEvent); public: /** * The string representation of this command -- for debugging purposes only. * This string should not be shown to an end user. * * @return The string representation; never null. */ QString ToString() const; /** * Makes this command become undefined. This has the side effect of changing * the name and description to null. This also removes all * state and disposes of it. Notification is sent to all listeners. */ void Undefine(); }; } #endif /*BERRYCOMMAND_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandCategory.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandCategory.cpp index 9aae3f08ca..8f7e8bdadf 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandCategory.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandCategory.cpp @@ -1,106 +1,107 @@ /*=================================================================== 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 "berryCommandCategory.h" #include "berryCommandCategoryEvent.h" #include #include namespace berry { void CommandCategory::AddCategoryListener(ICommandCategoryListener* categoryListener) { if (categoryListener == 0) { throw ctkInvalidArgumentException("Category listener cannot be null"); } categoryEvents.AddListener(categoryListener); } -void CommandCategory::Define(const QString& name, const QString& description) { +void CommandCategory::Define(const QString& name, const QString& description) +{ if (name.isEmpty()) { throw Poco::InvalidArgumentException( "The name of a command cannot be empty"); //$NON-NLS-1$ } const bool definedChanged = !this->defined; this->defined = true; const bool nameChanged = !(this->name == name); this->name = name; const bool descriptionChanged = !(this->description == description); this->description = description; const CommandCategoryEvent::Pointer categoryEvent(new CommandCategoryEvent(CommandCategory::Pointer(this), definedChanged, descriptionChanged, nameChanged)); this->FireCategoryChanged(categoryEvent); } void CommandCategory::RemoveCategoryListener(ICommandCategoryListener* categoryListener) { if (categoryListener == 0) { throw ctkInvalidArgumentException("CommandCategory listener cannot be null"); } categoryEvents.RemoveListener(categoryListener); } QString CommandCategory::ToString() const { if (str.isEmpty()) { QTextStream stringBuffer(&str); stringBuffer << "Category(" << id << "," << name << "," << description << "," << defined << ")"; } return str; } void CommandCategory::Undefine() { str = ""; const bool definedChanged = defined; defined = false; const bool nameChanged = !name.isEmpty(); name = ""; const bool descriptionChanged = !description.isEmpty(); description = ""; const CommandCategoryEvent::Pointer categoryEvent(new CommandCategoryEvent(CommandCategory::Pointer(this), definedChanged, descriptionChanged, nameChanged)); this->FireCategoryChanged(categoryEvent); } CommandCategory::CommandCategory(const QString& id) : NamedHandleObject(id) { } void CommandCategory::FireCategoryChanged(const CommandCategoryEvent::Pointer categoryEvent) { if (!categoryEvent) { throw ctkInvalidArgumentException("Command category event cannot be null"); } categoryEvents.categoryChanged(categoryEvent); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandCategory.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandCategory.h index 5330b842c8..4cce4b0022 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandCategory.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandCategory.h @@ -1,127 +1,127 @@ /*=================================================================== 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 BERRYCOMMANDCATEGORY_H_ #define BERRYCOMMANDCATEGORY_H_ #include "common/berryNamedHandleObject.h" #include "berryICommandCategoryListener.h" +#include + namespace berry { /** *

* A logical group for a set of commands. A command belongs to exactly one * category. The category has no functional effect, but may be used in graphical * tools that want to group the set of commands somehow. *

- * - * @since 3.1 */ -class CommandCategory: public NamedHandleObject +class BERRY_COMMANDS CommandCategory: public NamedHandleObject { public: berryObjectMacro(CommandCategory); /** * Adds a listener to this category that will be notified when this * category's state changes. * * @param categoryListener * The listener to be added; must not be null. */ void AddCategoryListener(ICommandCategoryListener* categoryListener); /** *

* Defines this category by giving it a name, and possibly a description as * well. The defined property automatically becomes true. *

*

* Notification is sent to all listeners that something has changed. *

* * @param name * The name of this command; must not be null. * @param description * The description for this command; may be null. */ void Define(const QString& name, const QString& description); /** * Removes a listener from this category. * * @param categoryListener * The listener to be removed; must not be null. * */ void RemoveCategoryListener(ICommandCategoryListener* categoryListener); /* * (non-Javadoc) * * @see org.eclipse.core.commands.common.HandleObject#toString() */ QString ToString() const; /* * (non-Javadoc) * * @see org.eclipse.core.commands.common.HandleObject#undefine() */ void Undefine(); protected: friend class CommandManager; /** * Constructs a new instance of Category based on the given * identifier. When a category is first constructed, it is undefined. * Category should only be constructed by the CommandManager * to ensure that identifier remain unique. * * @param id * The identifier for the category. This value must not be * null, and must be unique amongst all * categories. */ CommandCategory(const QString& id); private: /** * Notifies the listeners for this category that it has changed in some way. * * @param categoryEvent * The event to send to all of the listener; must not be * null. */ void FireCategoryChanged(const SmartPointer categoryEvent); /** * A collection of objects listening to changes to this category. This * collection is null if there are no listeners. */ ICommandCategoryListener::Events categoryEvents; }; } #endif /* BERRYCOMMANDCATEGORY_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandEvent.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandEvent.cpp index 2226149afd..de06fab9aa 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandEvent.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandEvent.cpp @@ -1,109 +1,110 @@ /*=================================================================== 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 "berryCommandEvent.h" #include "berryCommand.h" #include "berryCommandCategory.h" +#include "berryState.h" #include "berryIParameterValueConverter.h" #include "berryIHandler.h" namespace berry { const int CommandEvent::CHANGED_CATEGORY = CommandEvent::LAST_USED_BIT << 1; const int CommandEvent::CHANGED_HANDLED = CommandEvent::LAST_USED_BIT << 2; const int CommandEvent::CHANGED_PARAMETERS = CommandEvent::LAST_USED_BIT << 3; const int CommandEvent::CHANGED_RETURN_TYPE = CommandEvent::LAST_USED_BIT << 4; const int CommandEvent::CHANGED_HELP_CONTEXT_ID = CommandEvent::LAST_USED_BIT << 5; const int CommandEvent::CHANGED_ENABLED = CommandEvent::LAST_USED_BIT << 6; CommandEvent::CommandEvent(const Command::Pointer command, bool categoryChanged, bool definedChanged, bool descriptionChanged, bool handledChanged, bool nameChanged, bool parametersChanged, bool returnTypeChanged, bool helpContextIdChanged, bool enabledChanged) : AbstractNamedHandleEvent(definedChanged, descriptionChanged, nameChanged), command(command) { if (!command) { throw Poco::NullPointerException("The command cannot be null"); } if (categoryChanged) { changedValues |= CHANGED_CATEGORY; } if (handledChanged) { changedValues |= CHANGED_HANDLED; } if (parametersChanged) { changedValues |= CHANGED_PARAMETERS; } if (returnTypeChanged) { changedValues |= CHANGED_RETURN_TYPE; } if (helpContextIdChanged) { changedValues |= CHANGED_HELP_CONTEXT_ID; } if (enabledChanged) { changedValues |= CHANGED_ENABLED; } } Command::Pointer CommandEvent::GetCommand() const { return command; } bool CommandEvent::IsCategoryChanged() const { return ((changedValues & CHANGED_CATEGORY) != 0); } bool CommandEvent::IsHandledChanged() const { return ((changedValues & CHANGED_HANDLED) != 0); } bool CommandEvent::IsHelpContextIdChanged() const { return ((changedValues & CHANGED_HELP_CONTEXT_ID) != 0); } bool CommandEvent::IsParametersChanged() const { return ((changedValues & CHANGED_PARAMETERS) != 0); } bool CommandEvent::IsReturnTypeChanged() const { return ((changedValues & CHANGED_RETURN_TYPE) != 0); } bool CommandEvent::IsEnabledChanged() const { return ((changedValues & CHANGED_ENABLED) != 0); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandManager.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandManager.cpp index cb655fcfd6..93f8016f45 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandManager.cpp @@ -1,661 +1,661 @@ /*=================================================================== 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 "berryCommandManager.h" #include "berryIParameter.h" #include "berryIHandler.h" #include "berryParameterType.h" #include "berryParameterizedCommand.h" #include "berryParameterization.h" #include "berryCommand.h" #include "berryCommandCategory.h" +#include "berryState.h" #include "berryExecutionEvent.h" #include "berryCommandEvent.h" #include "berryCommandCategoryEvent.h" #include "berryCommandManagerEvent.h" #include "berryParameterTypeEvent.h" namespace berry { CommandManager::ExecutionListener::ExecutionListener(CommandManager* commandManager) : commandManager(commandManager) { } void CommandManager::ExecutionListener::NotDefined(const QString& commandId, const NotDefinedException* exception) { commandManager->executionEvents.notDefined(commandId, exception); } void CommandManager::ExecutionListener::NotEnabled(const QString& commandId, const NotEnabledException* exception) { commandManager->executionEvents.notEnabled(commandId, exception); } void CommandManager::ExecutionListener::NotHandled(const QString& commandId, const NotHandledException* exception) { commandManager->executionEvents.notHandled(commandId, exception); } void CommandManager::ExecutionListener::PostExecuteFailure(const QString& commandId, const ExecutionException* exception) { commandManager->executionEvents.postExecuteFailure(commandId, exception); } void CommandManager::ExecutionListener::PostExecuteSuccess(const QString& commandId, - const Object::Pointer returnValue) + const Object::Pointer& returnValue) { commandManager->executionEvents.postExecuteSuccess(commandId, returnValue); } void CommandManager::ExecutionListener::PreExecute(const QString& commandId, - const ExecutionEvent::ConstPointer event) + const ExecutionEvent::ConstPointer& event) { commandManager->executionEvents.preExecute(commandId, event); } CommandManager::CommandCategoryListener::CommandCategoryListener(CommandManager* commandManager) : commandManager(commandManager) { } -void CommandManager::CommandCategoryListener::CategoryChanged(const CommandCategoryEvent::ConstPointer categoryEvent) +void CommandManager::CommandCategoryListener::CategoryChanged(const CommandCategoryEvent::ConstPointer& categoryEvent) { if (categoryEvent->IsDefinedChanged()) { const CommandCategory::Pointer category(categoryEvent->GetCategory()); const QString categoryId(category->GetId()); const bool categoryIdAdded = category->IsDefined(); if (categoryIdAdded) { commandManager->definedCategoryIds.insert(categoryId); } else { commandManager->definedCategoryIds.remove(categoryId); } CommandManagerEvent::Pointer event(new CommandManagerEvent(*commandManager, "", false, false, categoryId, categoryIdAdded, true)); commandManager->FireCommandManagerChanged(event); } } CommandManager::CommandListener::CommandListener(CommandManager* commandManager) : commandManager(commandManager) { } -void CommandManager::CommandListener::CommandChanged(const SmartPointer commandEvent) +void CommandManager::CommandListener::CommandChanged(const SmartPointer& commandEvent) { if (commandEvent->IsDefinedChanged()) { const Command::Pointer command(commandEvent->GetCommand()); const QString commandId = command->GetId(); const bool commandIdAdded = command->IsDefined(); if (commandIdAdded) { commandManager->definedHandleObjects.insert(command); } else { commandManager->definedHandleObjects.remove(command); } CommandManagerEvent::Pointer event(new CommandManagerEvent(*commandManager, commandId, commandIdAdded, true, "", false, false)); commandManager->FireCommandManagerChanged(event); } } CommandManager::ParameterTypeListener::ParameterTypeListener(CommandManager* commandManager) : commandManager(commandManager) { } void CommandManager::ParameterTypeListener::ParameterTypeChanged( - const ParameterTypeEvent::ConstPointer parameterTypeEvent) + const ParameterTypeEvent::ConstPointer& parameterTypeEvent) { if (parameterTypeEvent->IsDefinedChanged()) { const ParameterType::Pointer parameterType(parameterTypeEvent ->GetParameterType()); const QString parameterTypeId = parameterType->GetId(); const bool parameterTypeIdAdded = parameterType->IsDefined(); if (parameterTypeIdAdded) { commandManager->definedParameterTypeIds.insert(parameterTypeId); } else { commandManager->definedParameterTypeIds.remove(parameterTypeId); } CommandManagerEvent::Pointer event(new CommandManagerEvent(*commandManager, parameterTypeId, parameterTypeIdAdded, true)); commandManager->FireCommandManagerChanged(event); } } const QString CommandManager::AUTOGENERATED_CATEGORY_ID = "org.blueberry.core.commands.categories.autogenerated"; const char CommandManager::ESCAPE_CHAR = '%'; const char CommandManager::ID_VALUE_CHAR = '='; const char CommandManager::PARAMETER_END_CHAR = ')'; const char CommandManager::PARAMETER_SEPARATOR_CHAR = ','; const char CommandManager::PARAMETER_START_CHAR = '('; CommandManager::CommandManager() : categoryListener(new CommandCategoryListener(this)), commandListener(new CommandListener(this)), parameterTypeListener(new ParameterTypeListener(this)) { } void CommandManager::AddCommandManagerListener(ICommandManagerListener* listener) { commandManagerEvents.AddListener(listener); } void CommandManager::AddExecutionListener(IExecutionListener *listener) { if (listener == 0) { throw ctkInvalidArgumentException( "Cannot add a null execution listener"); } if (executionEvents.IsEmpty()) { // Add an execution listener to every command. - executionListener = new ExecutionListener(this); + executionListener.reset(new ExecutionListener(this)); for (HandleObjectsByIdMap::Iterator itr = handleObjectsById.begin(); itr != handleObjectsById.end(); ++itr) { Command::Pointer command = itr.value().Cast(); if (command) { - command->AddExecutionListener(executionListener.GetPointer()); + command->AddExecutionListener(executionListener.data()); } } } executionEvents.AddListener(listener); } void CommandManager::DefineUncategorizedCategory(const QString& name, const QString& description) { CommandCategory::Pointer category(this->GetCategory(AUTOGENERATED_CATEGORY_ID)); category->Define(name, description); } SmartPointer CommandManager::Deserialize( const QString& serializedParameterizedCommand) { const int lparenPosition = this->UnescapedIndexOf( serializedParameterizedCommand, PARAMETER_START_CHAR); QString commandIdEscaped; QString serializedParameters; if (lparenPosition == -1) { commandIdEscaped = serializedParameterizedCommand; } else { commandIdEscaped = serializedParameterizedCommand.left(lparenPosition); if (serializedParameterizedCommand .at(serializedParameterizedCommand.size() - 1) != PARAMETER_END_CHAR) { throw SerializationException( "Parentheses must be balanced in serialized ParameterizedCommand"); } serializedParameters = serializedParameterizedCommand.mid( lparenPosition + 1, // skip PARAMETER_START_CHAR serializedParameterizedCommand.size() - lparenPosition - 2); // skip // PARAMETER_END_CHAR } const QString commandId(this->Unescape(commandIdEscaped)); Command::Pointer command(this->GetCommand(commandId)); const QList parameters(command->GetParameters()); const QListparameterizations(this->GetParameterizations( serializedParameters, parameters)); ParameterizedCommand::Pointer pCmd(new ParameterizedCommand(command, parameterizations)); return pCmd; } QList > CommandManager::GetAllCommands() const { QList result; for (HandleObjectsByIdMap::ConstIterator itr = handleObjectsById.begin(); itr != handleObjectsById.end(); ++itr) { if (Command::Pointer cmd = itr.value().Cast()) { result.push_back(cmd); } } return result; } SmartPointer CommandManager::GetCategory(const QString& categoryId) { if (categoryId.isEmpty()) { return this->GetCategory(AUTOGENERATED_CATEGORY_ID); } this->CheckId(categoryId); CommandCategory::Pointer category(categoriesById[categoryId]); if (!category) { category = new CommandCategory(categoryId); categoriesById[categoryId] = category; - category->AddCategoryListener(categoryListener.GetPointer()); + category->AddCategoryListener(categoryListener.data()); } return category; } SmartPointer CommandManager::GetCommand(const QString& commandId) { this->CheckId(commandId); Command::Pointer command(handleObjectsById[commandId].Cast()); if (!command) { command = new Command(commandId); handleObjectsById[commandId] = command; - command->AddCommandListener(commandListener.GetPointer()); + command->AddCommandListener(commandListener.data()); if (executionListener) { - command->AddExecutionListener(executionListener.GetPointer()); + command->AddExecutionListener(executionListener.data()); } } return command; } QList CommandManager::GetDefinedCategories() { QList categories; for (QSet::Iterator itr = definedCategoryIds.begin(); itr != definedCategoryIds.end(); ++itr) { categories.push_back(this->GetCategory(*itr)); } return categories; } QSet CommandManager::GetDefinedCategoryIds() const { return definedCategoryIds; } QSet CommandManager::GetDefinedCommandIds() const { return this->GetDefinedHandleObjectIds(); } QList > CommandManager::GetDefinedCommands() const { QList result; for (HandleObjectsSet::ConstIterator itr = definedHandleObjects.begin(); itr != definedHandleObjects.end(); ++itr) { if (Command::Pointer cmd = itr->Cast()) result.push_back(cmd); } return result; } QSet CommandManager::GetDefinedParameterTypeIds() const { return definedParameterTypeIds; } QList > CommandManager::GetDefinedParameterTypes() { QList parameterTypes; for (QSet::ConstIterator itr = definedParameterTypeIds.begin(); itr != definedParameterTypeIds.end(); ++itr) { parameterTypes.push_back(this->GetParameterType(*itr)); } return parameterTypes; } QString CommandManager::GetHelpContextId(const SmartPointer command) const { // Check if the command is defined. if (!command->IsDefined()) { throw NotDefinedException("The command is not defined. " + command->GetId()); } // Check the handler. const IHandler::Pointer handler(command->GetHandler()); if (handler) { const IHandler::WeakPtr weakHandler(handler); QHash, QString>::ConstIterator itr = helpContextIdsByHandler.find(weakHandler); if (itr != helpContextIdsByHandler.end() && !itr.value().isEmpty()) { return itr.value(); } } // Simply return whatever the command has as a help context identifier. return command->GetHelpContextId(); } SmartPointer CommandManager::GetParameterType(const QString& parameterTypeId) { this->CheckId(parameterTypeId); ParameterType::Pointer parameterType(parameterTypesById[parameterTypeId]); if (!parameterType) { parameterType = new ParameterType(parameterTypeId); parameterTypesById[parameterTypeId] = parameterType; - parameterType->AddListener(parameterTypeListener.GetPointer()); + parameterType->AddListener(parameterTypeListener.data()); } return parameterType; } void CommandManager::RemoveCommandManagerListener(ICommandManagerListener *listener) { commandManagerEvents.RemoveListener(listener); } void CommandManager::RemoveExecutionListener(IExecutionListener *listener) { if (!listener) { throw ctkInvalidArgumentException("Cannot remove a null listener"); } if (executionEvents.IsEmpty()) { return; } executionEvents.RemoveListener(listener); if (executionEvents.IsEmpty()) { // Remove the execution listener from every command. for (HandleObjectsByIdMap::Iterator commandItr = handleObjectsById.begin(); commandItr != handleObjectsById.end(); ++commandItr) { Command::Pointer command(commandItr.value().Cast()); - command->RemoveExecutionListener(executionListener.GetPointer()); + command->RemoveExecutionListener(executionListener.data()); } - executionListener = 0; - + executionListener.reset(); } } void CommandManager::SetHandlersByCommandId(const QHash > &handlersByCommandId) { // Make that all the reference commands are created. for (QHash >::const_iterator commandItr = handlersByCommandId.begin(); commandItr != handlersByCommandId.end(); ++commandItr) { this->GetCommand(commandItr.key()); } // Now, set-up the handlers on all of the existing commands. for (HandleObjectsByIdMap::Iterator commandItr = handleObjectsById.begin(); commandItr != handleObjectsById.end(); ++commandItr) { const Command::Pointer command(commandItr.value().Cast()); const QString commandId(command->GetId()); QHash >::const_iterator handlerItr = handlersByCommandId.find(commandId); if (handlerItr != handlersByCommandId.end()) { command->SetHandler(handlerItr.value()); } else { command->SetHandler(IHandler::Pointer(0)); } } } void CommandManager::SetHelpContextId(const SmartPointer handler, const QString& helpContextId) { if (!handler) { throw ctkInvalidArgumentException("The handler cannot be null"); } IHandler::WeakPtr weakHandler(handler); if (helpContextId.isEmpty()) { helpContextIdsByHandler.remove(weakHandler); } else { helpContextIdsByHandler[weakHandler] = helpContextId; } } void CommandManager::FireNotEnabled(const QString& commandId, const NotEnabledException* exception) { executionEvents.notEnabled(commandId, exception); } void CommandManager::FireNotDefined(const QString& commandId, const NotDefinedException* exception) { executionEvents.notDefined(commandId, exception); } void CommandManager::FirePreExecute(const QString& commandId, const SmartPointer event) { executionEvents.preExecute(commandId, event); } void CommandManager::FirePostExecuteSuccess(const QString& commandId, Object::Pointer returnValue) { executionEvents.postExecuteSuccess(commandId, returnValue); } void CommandManager::FirePostExecuteFailure(const QString& commandId, const ExecutionException* exception) { executionEvents.postExecuteFailure(commandId, exception); } QString CommandManager::Unescape(const QString& escapedText) { // defer initialization of a StringBuffer until we know we need one QString buffer; int pos = 0; for (QString::const_iterator itr = escapedText.begin(); itr != escapedText.end(); ++itr, ++pos) { QString::value_type c = *itr; if (c != ESCAPE_CHAR) { // normal unescaped character if (!buffer.isEmpty()) { buffer += c; } } else { if (buffer.isEmpty()) { buffer = escapedText.left(pos); } if (++itr != escapedText.end()) { c = *itr; if (c == PARAMETER_START_CHAR || c == PARAMETER_END_CHAR || c == ID_VALUE_CHAR || c == PARAMETER_SEPARATOR_CHAR || c == ESCAPE_CHAR) { buffer += c; } else { QString msg("Invalid character '"); msg += c; msg += "' in escape sequence"; throw SerializationException(msg); } } else { throw SerializationException( "Unexpected termination of escape sequence"); //$NON-NLS-1$ } } } if (buffer.isEmpty()) { return escapedText; } return buffer; } void CommandManager::FireCommandManagerChanged(const SmartPointer event) { if (!event) { throw ctkInvalidArgumentException("Event cannot be null."); } commandManagerEvents.commandManagerChanged(event); } QList CommandManager::GetParameterizations( const QString& serializedParams, const QList >& parameters) const { QString serializedParameters(serializedParams); if (serializedParameters.isEmpty() || parameters.isEmpty()) { return QList(); } QList paramList; int commaPosition; // split off each param by looking for ',' do { commaPosition = this->UnescapedIndexOf(serializedParameters, ','); QString idEqualsValue; if (commaPosition == -1) { // no more parameters after this idEqualsValue = serializedParameters; } else { // take the first parameter... idEqualsValue = serializedParameters.left(commaPosition); // ... and put the rest back into serializedParameters serializedParameters = serializedParameters.mid(commaPosition + 1); } int equalsPosition = this->UnescapedIndexOf(idEqualsValue, '='); QString parameterId; QString parameterValue; if (equalsPosition == -1) { // missing values are null parameterId = this->Unescape(idEqualsValue); } else { parameterId = this->Unescape(idEqualsValue.left(equalsPosition)); parameterValue = this->Unescape(idEqualsValue.mid(equalsPosition + 1)); } - for (unsigned int i = 0; i < parameters.size(); i++) + for (int i = 0; i < parameters.size(); i++) { const IParameter::Pointer parameter(parameters[i]); if (parameter->GetId() == parameterId) { paramList.push_back(Parameterization(parameter, parameterValue)); break; } } } while (commaPosition != -1); return paramList; } int CommandManager::UnescapedIndexOf(const QString& escapedText, const char ch) const { int pos = escapedText.indexOf(ch); // first char can't be escaped if (pos == 0) { return pos; } while (pos != -1) { // look back for the escape character if (escapedText.at(pos - 1) != ESCAPE_CHAR) { return pos; } // scan for the next instance of ch pos = escapedText.indexOf(ch, pos + 1); } return pos; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandManager.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandManager.h index 665fa812b7..0985ea5420 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandManager.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandManager.h @@ -1,630 +1,632 @@ /*=================================================================== 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 BERRYCOMMANDMANAGER_H_ #define BERRYCOMMANDMANAGER_H_ #include "common/berryHandleObjectManager.h" #include "berryIExecutionListenerWithChecks.h" #include "berryICommandListener.h" #include "berryIParameterTypeListener.h" #include "berryICommandCategoryListener.h" #include "berryICommandManagerListener.h" +#include + namespace berry { struct IParameter; struct IHandler; class ParameterType; class ParameterizedCommand; class Parameterization; class Command; class CommandCategory; /** *

* A central repository for commands -- both in the defined and undefined * states. Commands can be created and retrieved using this manager. It is * possible to listen to changes in the collection of commands by attaching a * listener to the manager. *

* * @see CommandManager#getCommand(String) * @since 3.1 */ class BERRY_COMMANDS CommandManager: public HandleObjectManager { private: typedef HandleObjectManager::HandleObjectsSet HandleObjectsSet; typedef HandleObjectManager::HandleObjectsByIdMap HandleObjectsByIdMap; /** * A listener that forwards incoming execution events to execution listeners * on this manager. The execution events will come from any command on this * manager. */ struct ExecutionListener: public IExecutionListenerWithChecks { ExecutionListener(CommandManager* commandManager); void NotDefined(const QString& commandId, const NotDefinedException* exception); void NotEnabled(const QString& commandId, const NotEnabledException* exception); void NotHandled(const QString& commandId, const NotHandledException* exception); void PostExecuteFailure(const QString& commandId, const ExecutionException* exception); void PostExecuteSuccess(const QString& commandId, - const Object::Pointer returnValue); + const Object::Pointer& returnValue); void PreExecute(const QString& commandId, const SmartPointer< - const ExecutionEvent> event); + const ExecutionEvent>& event); private: CommandManager* commandManager; }; struct CommandCategoryListener: public ICommandCategoryListener { CommandCategoryListener(CommandManager* commandManager); void CategoryChanged( - const SmartPointer categoryEvent); + const SmartPointer& categoryEvent); private: CommandManager* commandManager; }; - ICommandCategoryListener::Pointer categoryListener; + QScopedPointer categoryListener; struct CommandListener: public ICommandListener { CommandListener(CommandManager* commandManager); - void CommandChanged(const SmartPointer commandEvent); + void CommandChanged(const SmartPointer& commandEvent); private: CommandManager* commandManager; }; - ICommandListener::Pointer commandListener; + QScopedPointer commandListener; struct ParameterTypeListener: public IParameterTypeListener { ParameterTypeListener(CommandManager* commandManager); void ParameterTypeChanged( - const SmartPointer parameterTypeEvent); + const SmartPointer& parameterTypeEvent); private: CommandManager* commandManager; }; - IParameterTypeListener::Pointer parameterTypeListener; + QScopedPointer parameterTypeListener; public: /** * The identifier of the category in which all auto-generated commands will * appear. This value must never be null. */ static const QString AUTOGENERATED_CATEGORY_ID; // = "org.blueberry.core.commands.categories.autogenerated"; /** * The default constructor */ CommandManager(); /** * Adds a listener to this command manager. The listener will be notified * when the set of defined commands changes. This can be used to track the * global appearance and disappearance of commands. * * @param listener * The listener to attach; must not be null. */ void AddCommandManagerListener(ICommandManagerListener* listener); /** * Adds an execution listener to this manager. This listener will be * notified if any of the commands controlled by this manager execute. This * can be used to support macros and instrumentation of commands. * * @param listener * The listener to attach; must not be null. */ void AddExecutionListener(IExecutionListener* listener); /** * Sets the name and description of the category for uncategorized commands. * This is the category that will be returned if * {@link #getCategory(String)} is called with null. * * @param name * The name of the category for uncategorized commands; must not * be null. * @param description * The description of the category for uncategorized commands; * may be null. */ void DefineUncategorizedCategory(const QString& name, const QString& description); /** *

* Returns a {@link ParameterizedCommand} with a command and * parameterizations as specified in the provided * serializedParameterizedCommand string. The * serializedParameterizedCommand must use the format * returned by {@link ParameterizedCommand#serialize()} and described in the * Javadoc for that method. *

*

* If a parameter id encoded in the * serializedParameterizedCommand does not exist in the * encoded command, that parameter id and value are ignored. A given * parameter id should not be used more than once in * serializedParameterizedCommand. This will not result in * an exception, but in this case the value of the parameter when the * command is executed is unspecified. *

*

* This method will never return null, however it may throw * an exception if there is a problem processing the serialization string or * the encoded command is undefined. *

* * @param serializedParameterizedCommand * a string representing a command id and parameter ids and * values; must not be null * @return a {@link ParameterizedCommand} with the command and * parameterizations encoded in the * serializedParameterizedCommand; never * null. * @throws NotDefinedException * if the command indicated in * serializedParameterizedCommand is not defined * @throws SerializationException * if there is an error deserializing * serializedParameterizedCommand * @see ParameterizedCommand#serialize() */ SmartPointer Deserialize(const QString& serializedParameterizedCommand); /** * Returns all of the commands known by this manager -- defined and * undefined. * * @return All of the commands; may be empty, but never null. */ QList > GetAllCommands() const; /** * Gets the category with the given identifier. If no such category * currently exists, then the category will be created (but be undefined). * * @param categoryId * The identifier to find; must not be null. If * the category is null, then a category suitable * for uncategorized items is defined and returned. * @return The category with the given identifier; this value will never be * null, but it might be undefined. * @see Category */ SmartPointer GetCategory(const QString& categoryId); /** * Gets the command with the given identifier. If no such command currently * exists, then the command will be created (but will be undefined). * * @param commandId * The identifier to find; must not be null and * must not be zero-length. * @return The command with the given identifier; this value will never be * null, but it might be undefined. * @see Command */ SmartPointer GetCommand(const QString& commandId); /** * Returns the categories that are defined. * * @return The defined categories; this value may be empty, but it is never * null. */ QList > GetDefinedCategories(); /** * Returns the set of identifiers for those category that are defined. * * @return The set of defined category identifiers; this value may be empty, * but it is never null. */ QSet GetDefinedCategoryIds() const; /** * Returns the set of identifiers for those commands that are defined. * * @return The set of defined command identifiers; this value may be empty, * but it is never null. */ QSet GetDefinedCommandIds() const; /** * Returns the commands that are defined. * * @return The defined commands; this value may be empty, but it is never * null. */ QList > GetDefinedCommands() const; /** * Returns the set of identifiers for those parameter types that are * defined. * * @return The set of defined command parameter type identifiers; this value * may be empty, but it is never null. */ QSet GetDefinedParameterTypeIds() const; /** * Returns the command parameter types that are defined. * * @return The defined command parameter types; this value may be empty, but * it is never null. */ QList > GetDefinedParameterTypes(); /** * Gets the help context identifier for a particular command. The command's * handler is first checked for a help context identifier. If the handler * does not have a help context identifier, then the help context identifier * for the command is returned. If neither has a help context identifier, * then null is returned. * * @param command * The command for which the help context should be retrieved; * must not be null. * @return The help context identifier to use for the given command; may be * null. * @throws NotDefinedException * If the given command is not defined. */ QString GetHelpContextId(const SmartPointer command) const; /** * Gets the command {@link ParameterType} with the given identifier. If no * such command parameter type currently exists, then the command parameter * type will be created (but will be undefined). * * @param parameterTypeId * The identifier to find; must not be null and * must not be zero-length. * @return The {@link ParameterType} with the given identifier; this value * will never be null, but it might be undefined. */ SmartPointer GetParameterType(const QString& parameterTypeId); /** * Removes a listener from this command manager. * * @param listener * The listener to be removed; must not be null. */ void RemoveCommandManagerListener(ICommandManagerListener* listener); /** * Removes an execution listener from this command manager. * * @param listener * The listener to be removed; must not be null. */ void RemoveExecutionListener(IExecutionListener* listener); /** * Block updates all of the handlers for all of the commands. If the handler * is null or the command id does not exist in the map, then * the command becomes unhandled. Otherwise, the handler is set to the * corresponding value in the map. * * @param handlersByCommandId * A map of command identifiers (String) to * handlers (IHandler). This map may be * null if all handlers should be cleared. * Similarly, if the map is empty, then all commands will become * unhandled. */ void SetHandlersByCommandId( const QHash >& handlersByCommandId); /** * Sets the help context identifier to associate with a particular handler. * * @param handler * The handler with which to register a help context identifier; * must not be null. * @param helpContextId * The help context identifier to register; may be * null if the help context identifier should be * removed. */ void SetHelpContextId(const SmartPointer handler, const QString& helpContextId); /** * Fires the notEnabled event for * executionListeners. *

* Note: This supports bridging actions to the command framework, * and should not be used outside the framework. *

* * @param commandId * The command id of the command about to execute, never * null. * @param exception * The exception, never null. */ void FireNotEnabled(const QString& commandId, const NotEnabledException* exception); /** * Fires the notDefined event for * executionListeners. *

* Note: This supports bridging actions to the command framework, * and should not be used outside the framework. *

* * @param commandId * The command id of the command about to execute, never * null. * @param exception * The exception, never null. */ void FireNotDefined(const QString& commandId, const NotDefinedException* exception); /** * Fires the preExecute event for * executionListeners. *

* Note: This supports bridging actions to the command framework, * and should not be used outside the framework. *

* * @param commandId * The command id of the command about to execute, never * null. * @param event * The event that triggered the command, may be null. */ void FirePreExecute(const QString& commandId, const SmartPointer< const ExecutionEvent> event); /** * Fires the postExecuteSuccess event for * executionListeners. *

* Note: This supports bridging actions to the command framework, * and should not be used outside the framework. *

* * @param commandId * The command id of the command executed, never * null. * @param returnValue * The value returned from the command, may be null. */ void FirePostExecuteSuccess(const QString& commandId, Object::Pointer returnValue); /** * Fires the postExecuteFailure event for * executionListeners. *

* Note: This supports bridging actions to the command framework, * and should not be used outside the framework. *

* * @param commandId * The command id of the command executed, never * null. * @param exception * The exception, never null. */ void FirePostExecuteFailure(const QString& commandId, const ExecutionException* exception); protected: /** * The escape character to use for serialization and deserialization of * parameterized commands. */ static const char ESCAPE_CHAR; // = '%'; /** * The character that separates a parameter id from its value. */ static const char ID_VALUE_CHAR; // = '='; /** * The character that indicates the end of a list of parameters. */ static const char PARAMETER_END_CHAR; // = ')'; /** * The character that separators parameters from each other. */ static const char PARAMETER_SEPARATOR_CHAR; // = ','; /** * The character that indicates the start of a list of parameters. */ static const char PARAMETER_START_CHAR; // = '('; friend class ParameterizedCommand; private: /** * Unescapes special characters in the command id, parameter ids and * parameter values for {@link #deserialize(String)}. The special characters * {@link #PARAMETER_START_CHAR}, {@link #PARAMETER_END_CHAR}, * {@link #ID_VALUE_CHAR}, {@link #PARAMETER_SEPARATOR_CHAR} and * {@link #ESCAPE_CHAR} are escaped by prepending an {@link #ESCAPE_CHAR} * character. *

* See also ParameterizedCommand.escape(String) *

* * @param escapedText * a String that may contain escaped special * characters for command serialization. * @return a String representing escapedText * with any escaped characters replaced by their literal values * @throws SerializationException * if escapedText contains an invalid escape * sequence */ static QString Unescape(const QString& escapedText); /** * The map of category identifiers (String) to categories ( * Category). This collection may be empty, but it is never * null. */ QHash > categoriesById; /** * The set of identifiers for those categories that are defined. This value * may be empty, but it is never null. */ QSet definedCategoryIds; /** * The set of identifiers for those command parameter types that are * defined. This value may be empty, but it is never null. * */ QSet definedParameterTypeIds; /** * The execution listener for this command manager. This just forwards * events from commands controlled by this manager to listeners on this * manager. */ - SmartPointer executionListener; + QScopedPointer executionListener; /** * The collection of execution listeners. This collection is * null if there are no listeners. */ IExecutionListenerWithChecks::Events executionEvents; /** * */ ICommandManagerListener::Events commandManagerEvents; /** * The help context identifiers ({@link String}) for a handler ({@link IHandler}). * This map may be empty, but it is never null. Entries are * removed if all strong references to the handler are removed. */ QHash, QString> helpContextIdsByHandler; /** * The map of parameter type identifiers (String) to * parameter types ( ParameterType). This collection may be * empty, but it is never null. */ QHash > parameterTypesById; /** * Notifies all of the listeners to this manager that the set of defined * command identifiers has changed. * * @param event * The event to send to all of the listeners; must not be * null. */ void FireCommandManagerChanged( const SmartPointer event); /** * Returns an array of parameterizations for the provided command by * deriving the parameter ids and values from the provided * serializedParameters string. * * @param serializedParameters * a String encoding parameter ids and values; must not be * null. * @param parameters * array of parameters of the command being deserialized; may be * null. * @return an array of parameterizations; may be null. * @throws SerializationException * if there is an error deserializing the parameters */ QList GetParameterizations( const QString& serializedParameters, const QList >& parameters) const; /** * Searches for the index of a char in a String * but disregards characters prefixed with the {@link #ESCAPE_CHAR} escape * character. This is used by {@link #deserialize(String)} and * {@link #getParameterizations(String, IParameter[])} to parse the * serialized parameterized command string. * * @param escapedText * the string to search for the index of ch in * @param ch * a character to search for in escapedText * @return the index of the first unescaped occurrence of the character in * escapedText, or -1 if the * character does not occur unescaped. * @see String#indexOf(int) */ int UnescapedIndexOf(const QString& escapedText, const char ch) const; }; } #endif /* BERRYCOMMANDMANAGER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryExecutionEvent.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryExecutionEvent.cpp index 616ec60e0a..9df2db493f 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryExecutionEvent.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryExecutionEvent.cpp @@ -1,124 +1,125 @@ /*=================================================================== 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 "berryExecutionEvent.h" #include "common/berryCommandExceptions.h" #include "berryIParameterValueConverter.h" #include "berryCommandCategory.h" +#include "berryState.h" #include "berryIHandler.h" #include #include namespace berry { ExecutionEvent::ExecutionEvent() { } -ExecutionEvent::ExecutionEvent(const Command::ConstPointer cmd, - const ParameterMap& params, const Object::ConstPointer trg, - const Object::ConstPointer appContext) +ExecutionEvent::ExecutionEvent(const Command::ConstPointer& cmd, + const ParameterMap& params, const Object::ConstPointer& trg, + const Object::Pointer& appContext) : applicationContext(appContext), command(cmd), parameters(params), trigger(trg) { } -const Object::ConstPointer ExecutionEvent::GetApplicationContext() const +const Object::Pointer ExecutionEvent::GetApplicationContext() const { return applicationContext; } const Command::ConstPointer ExecutionEvent::GetCommand() const { return command; } const Object::ConstPointer ExecutionEvent::GetObjectParameterForExecution( const QString& parameterId) const { if (command.IsNull()) { throw ExecutionException( "No command is associated with this execution event"); //$NON-NLS-1$ } try { // const ParameterType parameterType = command // .getParameterType(parameterId); // if (parameterType == null) // { // throw new ExecutionException( // "Command does not have a parameter type for the given parameter"); //$NON-NLS-1$ // } // const AbstractParameterValueConverter valueConverter = parameterType // .getValueConverter(); // if (valueConverter == null) // { // throw new ExecutionException( // "Command does not have a value converter"); //$NON-NLS-1$ // } const QString stringValue = this->GetParameter(parameterId); ObjectString::Pointer objectValue(new ObjectString(stringValue)); // const Object objectValue = valueConverter // .convertToObject(stringValue); return objectValue; } catch (NotDefinedException e) { throw ExecutionException("Command is not defined", e); //$NON-NLS-1$ } // catch (ParameterValueConversionException e) // { // throw new ExecutionException( // "The parameter string could not be converted to an object", e); //$NON-NLS-1$ // } } QString ExecutionEvent::GetParameter(const QString& parameterId) const { ParameterMap::const_iterator res = parameters.find(parameterId); if (res != parameters.end()) return res.value(); else return ""; } const ExecutionEvent::ParameterMap& ExecutionEvent::GetParameters() const { return parameters; } const Object::ConstPointer ExecutionEvent::GetTrigger() const { return trigger; } QString ExecutionEvent::ToString() const { QString str; QTextStream ss(&str); ss << "ExecutionEvent(" << command->ToString() << ',' << parameters.size() << ',' - << trigger->ToString() << ',' << applicationContext->ToString() << ')'; + << (trigger ? trigger->ToString() : QString()) << ',' << applicationContext->ToString() << ')'; return str; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryExecutionEvent.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryExecutionEvent.h index 87a3c197e8..cb982079aa 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryExecutionEvent.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryExecutionEvent.h @@ -1,180 +1,173 @@ /*=================================================================== 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 BERRYEXECUTIONEVENT_H_ #define BERRYEXECUTIONEVENT_H_ #include #include "berryCommand.h" #include namespace berry { /** *

* The data object to pass to the command (and its handler) as it executes. This * carries information about the current state of the application, and the * application context in which the command was executed. *

*

* An execution event carries three blocks of data: the parameters, the trigger, * and the application context. How these blocks are used is application * dependent. In the BlueBerry workbench, the trigger is an SWT event, and the * application context contains information about the selection and active part. *

- * - * @since 3.1 */ class BERRY_COMMANDS ExecutionEvent : public Object { public: berryObjectMacro(ExecutionEvent); typedef QHash ParameterMap; private: /** * The state of the application at the time the execution was triggered. In * the BlueBerry workbench, this might contain information about the active * part of the active selection (for example). This value may be * null. */ - const Object::ConstPointer applicationContext; + const Object::Pointer applicationContext; /** * The command being executed. This value may be null. */ const Command::ConstPointer command; /** * The parameters to qualify the execution. For handlers that normally * prompt for additional information, these can be used to avoid prompting. * This value may be empty, but it is never null. */ const ParameterMap parameters; /** * The object that triggered the execution. In an event-driven architecture, * this is typically just another event. In the BlueBerry workbench, this is * typically an SWT event. This value may be null. */ const Object::ConstPointer trigger; public: /** * Constructs a new instance of ExecutionEvent with no * parameters, no trigger and no application context. This is just a * convenience method. - * - * @since 3.2 */ ExecutionEvent(); /** * Constructs a new instance of ExecutionEvent. * * @param command * The command being executed; may be null. * @param parameters * The parameters to qualify the execution; must not be * null. This must be a map of parameter ids (String) * to parameter values (String). * @param trigger * The object that triggered the execution; may be * null. * @param applicationContext * The state of the application at the time the execution was * triggered; may be null. - * @since 3.2 */ - ExecutionEvent(const Command::ConstPointer command, const ParameterMap& parameters, - const Object::ConstPointer trigger, const Object::ConstPointer applicationContext); + ExecutionEvent(const Command::ConstPointer& command, const ParameterMap& parameters, + const Object::ConstPointer& trigger, const Object::Pointer& applicationContext); /** * Returns the state of the application at the time the execution was * triggered. * * @return The application context; may be null. */ - const Object::ConstPointer GetApplicationContext() const; + const Object::Pointer GetApplicationContext() const; /** * Returns the command being executed. * * @return The command being executed. - * @since 3.2 */ const Command::ConstPointer GetCommand() const; /** * Returns the object represented by the string value of the parameter with * the provided id. *

* This is intended to be used in the scope of an * {@link IHandler#execute(ExecutionEvent)} method, so any problem getting * the object value causes ExecutionException to be thrown. *

* * @param parameterId * The id of a parameter to retrieve the object value of. * @return The object value of the parameter with the provided id. * @throws ExecutionException * if the parameter object value could not be obtained for any * reason - * @since 3.2 */ const Object::ConstPointer GetObjectParameterForExecution(const QString& parameterId) const; /** * Returns the value of the parameter with the given id. * * @param parameterId * The id of the parameter to retrieve; may be null. * @return The parameter value; null if the parameter cannot * be found. */ QString GetParameter(const QString ¶meterId) const; /** * Returns all of the parameters. * * @return The parameters; never null, but may be empty. */ const ParameterMap& GetParameters() const; /** * Returns the object that triggered the execution * * @return The trigger; null if there was no trigger. */ const Object::ConstPointer GetTrigger() const; /** * The string representation of this execution event -- for debugging * purposes only. This string should not be shown to an end user. */ QString ToString() const; }; } #endif /*BERRYEXECUTIONEVENT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandCategoryListener.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandCategoryListener.cpp index 991b8f206a..0f65f59948 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandCategoryListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandCategoryListener.cpp @@ -1,44 +1,48 @@ /*=================================================================== 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 "berryICommandCategoryListener.h" #include "berryCommandCategory.h" #include "berryCommandCategoryEvent.h" namespace berry { void ICommandCategoryListener::Events ::AddListener(ICommandCategoryListener* l) { if (l == 0) return; categoryChanged += Delegate(l, &ICommandCategoryListener::CategoryChanged); } void ICommandCategoryListener::Events ::RemoveListener(ICommandCategoryListener* l) { if (l == 0) return; categoryChanged -= Delegate(l, &ICommandCategoryListener::CategoryChanged); } +ICommandCategoryListener::~ICommandCategoryListener() +{ +} + } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandCategoryListener.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandCategoryListener.h index 003137396e..c71d2153ab 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandCategoryListener.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandCategoryListener.h @@ -1,71 +1,71 @@ /*=================================================================== 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 BERRYICOMMANDCATEGORYLISTENER_H_ #define BERRYICOMMANDCATEGORYLISTENER_H_ -#include -#include #include namespace berry { +template class SmartPointer; + class CommandCategoryEvent; /** * An instance of this interface can be used by clients to receive notification * of changes to one or more instances of Category. *

* This interface may be implemented by clients. *

* - * @since 3.1 * @see CommandCategory#AddCategoryListener(ICommandCategoryListener) * @see CommandCategory#RemoveCategoryListener(ICommandCategoryListener) */ -struct ICommandCategoryListener : public virtual Object { - - berryInterfaceMacro(ICommandCategoryListener, berry); +struct ICommandCategoryListener +{ struct Events { - typedef Message1 > Event; + typedef Message1& > Event; Event categoryChanged; void AddListener(ICommandCategoryListener* listener); void RemoveListener(ICommandCategoryListener* listener); - typedef MessageDelegate1 > Delegate; + typedef MessageDelegate1& > Delegate; }; + virtual ~ICommandCategoryListener(); + /** * Notifies that one or more properties of an instance of * CommandCategory have changed. Specific details are described in * the CommandCategoryEvent. * * @param categoryEvent * the category event. Guaranteed not to be null. */ - virtual void CategoryChanged(const SmartPointer categoryEvent) = 0; + virtual void CategoryChanged(const SmartPointer& categoryEvent) = 0; }; } #endif /* BERRYICOMMANDCATEGORYLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandListener.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandListener.cpp index 492cea52b0..2b1c78af83 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandListener.cpp @@ -1,47 +1,52 @@ /*=================================================================== 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 "berryICommandListener.h" #include "berryCommand.h" #include "berryCommandEvent.h" #include "berryCommandCategory.h" +#include "berryState.h" #include "berryIHandler.h" namespace berry { void ICommandListener::Events ::AddListener(ICommandListener* l) { if (l == 0) return; commandChanged += Delegate(l, &ICommandListener::CommandChanged); } void ICommandListener::Events ::RemoveListener(ICommandListener* l) { if (l == 0) return; commandChanged -= Delegate(l, &ICommandListener::CommandChanged); } +ICommandListener::~ICommandListener() +{ +} + } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandListener.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandListener.h index 46cccb7b2e..c9c56e46c2 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandListener.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandListener.h @@ -1,70 +1,72 @@ /*=================================================================== 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 BERRYICOMMANDLISTENER_H_ #define BERRYICOMMANDLISTENER_H_ -#include -#include #include +#include + namespace berry { +template class SmartPointer; + class CommandEvent; /** * An instance of this interface can be used by clients to receive notification * of changes to one or more instances of Command. *

* This interface may be implemented by clients. *

* - * @since 3.1 * @see Command#addCommandListener(ICommandListener) * @see Command#removeCommandListener(ICommandListener) */ -struct ICommandListener : public virtual Object { - - berryInterfaceMacro(ICommandListener, berry); +struct BERRY_COMMANDS ICommandListener +{ struct Events { - typedef Message1 > Event; + typedef Message1&> Event; Event commandChanged; void AddListener(ICommandListener* listener); void RemoveListener(ICommandListener* listener); private: - typedef MessageDelegate1 > Delegate; + typedef MessageDelegate1&> Delegate; }; + virtual ~ICommandListener(); + /** * Notifies that one or more properties of an instance of * Command have changed. Specific details are described in * the CommandEvent. * * @param commandEvent * the command event. Guaranteed not to be null. */ - virtual void CommandChanged(const SmartPointer commandEvent) = 0; + virtual void CommandChanged(const SmartPointer& commandEvent) = 0; }; } #endif /* BERRYICOMMANDLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandManagerListener.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandManagerListener.cpp index 2613409cdc..a539b7c182 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandManagerListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandManagerListener.cpp @@ -1,39 +1,43 @@ /*=================================================================== 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 "berryICommandManagerListener.h" #include "berryCommandManagerEvent.h" namespace berry { void ICommandManagerListener::Events::AddListener(ICommandManagerListener* l) { if (l == 0) return; commandManagerChanged += Delegate(l, &ICommandManagerListener::CommandManagerChanged); } void ICommandManagerListener::Events::RemoveListener(ICommandManagerListener* l) { if (l == 0) return; commandManagerChanged -= Delegate(l, &ICommandManagerListener::CommandManagerChanged); } +ICommandManagerListener::~ICommandManagerListener() +{ +} + } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandManagerListener.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandManagerListener.h index ab9b741995..f83131b557 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandManagerListener.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryICommandManagerListener.h @@ -1,73 +1,73 @@ /*=================================================================== 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 BERRYICOMMANDMANAGERLISTENER_H_ #define BERRYICOMMANDMANAGERLISTENER_H_ #include -#include -#include +#include namespace berry { +template class SmartPointer; + class CommandManagerEvent; /** * An instance of this interface can be used by clients to receive notification * of changes to one or more instances of ICommandManager. *

* This interface may be implemented by clients. *

* - * @since 3.1 * @see CommandManager#addCommandManagerListener(ICommandManagerListener) * @see CommandManager#removeCommandManagerListener(ICommandManagerListener) */ -struct BERRY_COMMANDS ICommandManagerListener: public virtual Object +struct BERRY_COMMANDS ICommandManagerListener { -berryInterfaceMacro(ICommandManagerListener, berry); - -struct Events { + struct Events { - typedef Message1 > Event; + typedef Message1& > Event; Event commandManagerChanged; void AddListener(ICommandManagerListener* listener); void RemoveListener(ICommandManagerListener* listener); private: - typedef MessageDelegate1 > Delegate; - } ; + typedef MessageDelegate1& > Delegate; + }; + + virtual ~ICommandManagerListener(); /** * Notifies that one or more properties of an instance of * ICommandManager have changed. Specific details are * described in the CommandManagerEvent. * * @param commandManagerEvent * the commandManager event. Guaranteed not to be * null. */ -virtual void CommandManagerChanged(const SmartPointer commandManagerEvent) = 0; + virtual void CommandManagerChanged(const SmartPointer& commandManagerEvent) = 0; }; } #endif /* BERRYICOMMANDMANAGERLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListener.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListener.cpp index 2b99c9e29e..a6ce322ddd 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListener.cpp @@ -1,77 +1,78 @@ /*=================================================================== 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 "berryIExecutionListener.h" #include "berryIParameterValueConverter.h" #include "berryExecutionEvent.h" #include "berryCommandCategory.h" +#include "berryState.h" #include "berryIHandler.h" namespace berry { IExecutionListener::Events::~Events() { } void IExecutionListener::Events ::AddListener(IExecutionListener* l) { if (l == 0) return; notHandled += NotHandledDelegate(l, &IExecutionListener::NotHandled); postExecuteFailure += PostExecuteFailureDelegate(l, &IExecutionListener::PostExecuteFailure); postExecuteSuccess += PostExecuteSuccessDelegate(l, &IExecutionListener::PostExecuteSuccess); preExecute += PreExecuteDelegate(l, &IExecutionListener::PreExecute); } void IExecutionListener::Events ::RemoveListener(IExecutionListener* l) { if (l == 0) return; notHandled -= NotHandledDelegate(l, &IExecutionListener::NotHandled); postExecuteFailure -= PostExecuteFailureDelegate(l, &IExecutionListener::PostExecuteFailure); postExecuteSuccess -= PostExecuteSuccessDelegate(l, &IExecutionListener::PostExecuteSuccess); preExecute -= PreExecuteDelegate(l, &IExecutionListener::PreExecute); } bool IExecutionListener::Events ::HasListeners() const { return notHandled.HasListeners() || postExecuteFailure.HasListeners() || postExecuteSuccess.HasListeners() || preExecute.HasListeners(); } bool IExecutionListener::Events ::IsEmpty() const { return !this->HasListeners(); } IExecutionListener::~IExecutionListener() { } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListener.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListener.h index fe3660665d..86be22628c 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListener.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListener.h @@ -1,121 +1,117 @@ /*=================================================================== 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 BERRYIEXECUTIONLISTENER_H_ #define BERRYIEXECUTIONLISTENER_H_ #include -#include #include #include #include "common/berryCommandExceptions.h" namespace berry { class ExecutionEvent; /** *

* A listener to the execution of commands. This listener will be notified if a * command is about to execute, and when that execution completes. It is not * possible for the listener to prevent the execution, only to respond to it in * some way. *

- * - * @since 3.1 */ -struct BERRY_COMMANDS IExecutionListener : public virtual Object { - - berryInterfaceMacro(IExecutionListener, berry); +struct BERRY_COMMANDS IExecutionListener +{ struct Events { Message2 notHandled; Message2 postExecuteFailure; - Message2 postExecuteSuccess; - Message2 > preExecute; + Message2 postExecuteSuccess; + Message2& > preExecute; virtual ~Events(); virtual void AddListener(IExecutionListener* listener); virtual void RemoveListener(IExecutionListener* listener); virtual bool HasListeners() const; virtual bool IsEmpty() const; private: typedef MessageDelegate2 NotHandledDelegate; typedef MessageDelegate2 PostExecuteFailureDelegate; - typedef MessageDelegate2 PostExecuteSuccessDelegate; - typedef MessageDelegate2 > PreExecuteDelegate; + typedef MessageDelegate2 PostExecuteSuccessDelegate; + typedef MessageDelegate2& > PreExecuteDelegate; }; virtual ~IExecutionListener(); /** * Notifies the listener that an attempt was made to execute a command with * no handler. * * @param commandId * The identifier of command that is not handled; never * null * @param exception * The exception that occurred; never null. */ virtual void NotHandled(const QString& commandId, const NotHandledException* exception) = 0; /** * Notifies the listener that a command has failed to complete execution. * * @param commandId * The identifier of the command that has executed; never * null. * @param exception * The exception that occurred; never null. */ virtual void PostExecuteFailure(const QString& commandId, const ExecutionException* exception) = 0; /** * Notifies the listener that a command has completed execution * successfully. * * @param commandId * The identifier of the command that has executed; never * null. * @param returnValue * The return value from the command; may be null. */ - virtual void PostExecuteSuccess(const QString& commandId, const Object::Pointer returnValue) = 0; + virtual void PostExecuteSuccess(const QString& commandId, const Object::Pointer& returnValue) = 0; /** * Notifies the listener that a command is about to execute. * * @param commandId * The identifier of the command that is about to execute, never * null. * @param event * The event that will be passed to the execute * method; never null. */ - virtual void PreExecute(const QString& commandId, const SmartPointer event) = 0; + virtual void PreExecute(const QString& commandId, const SmartPointer& event) = 0; }; } #endif /* BERRYIEXECUTIONLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListenerWithChecks.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListenerWithChecks.cpp index be246979e3..c51ee3279c 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListenerWithChecks.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListenerWithChecks.cpp @@ -1,71 +1,72 @@ /*=================================================================== 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 "berryIExecutionListenerWithChecks.h" #include "berryExecutionEvent.h" #include "berryIParameterValueConverter.h" #include "berryCommandCategory.h" +#include "berryState.h" #include "berryIHandler.h" namespace berry { void IExecutionListenerWithChecks::Events ::AddListener(IExecutionListener* l) { if (l == 0) return; IExecutionListener::Events::AddListener(l); if (IExecutionListenerWithChecks* cl = dynamic_cast(l)) { notDefined += NotDefinedDelegate(cl, &IExecutionListenerWithChecks::NotDefined); notEnabled += NotEnabledDelegate(cl, &IExecutionListenerWithChecks::NotEnabled); } } void IExecutionListenerWithChecks::Events ::RemoveListener(IExecutionListener* l) { if (l == 0) return; IExecutionListener::Events::RemoveListener(l); if (IExecutionListenerWithChecks* cl = dynamic_cast(l)) { notDefined -= NotDefinedDelegate(cl, &IExecutionListenerWithChecks::NotDefined); notEnabled -= NotEnabledDelegate(cl, &IExecutionListenerWithChecks::NotEnabled); } } bool IExecutionListenerWithChecks::Events ::HasListeners() const { return IExecutionListener::Events::HasListeners() || notDefined.HasListeners() || notEnabled.HasListeners(); } bool IExecutionListenerWithChecks::Events ::IsEmpty() const { return !this->HasListeners(); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListenerWithChecks.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListenerWithChecks.h index 2ac3962af4..d4570dc62b 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListenerWithChecks.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIExecutionListenerWithChecks.h @@ -1,87 +1,83 @@ /*=================================================================== 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 BERRYIEXECUTIONLISTENERWITHCHECKS_H_ #define BERRYIEXECUTIONLISTENERWITHCHECKS_H_ #include "berryIExecutionListener.h" #include "common/berryCommandExceptions.h" namespace berry { /** *

* A listener to the execution of commands. This listener will be notified if * someone tries to execute a command and it is not enabled or not defined. The * listener also be notified if a command is about to execute, and when that * execution completes. It is not possible for the listener to prevent the * execution, only to respond to it in some way. *

*

* Clients may implement. *

- * - * @since 3.2 */ struct BERRY_COMMANDS IExecutionListenerWithChecks : public IExecutionListener { - berryInterfaceMacro(IExecutionListenerWithChecks, berry); - struct Events : public IExecutionListener::Events { Message2 notDefined; Message2 notEnabled; void AddListener(IExecutionListener* listener); void RemoveListener(IExecutionListener* listener); bool HasListeners() const; bool IsEmpty() const; private: typedef MessageDelegate2 NotDefinedDelegate; typedef MessageDelegate2 NotEnabledDelegate; }; /** * Notifies the listener that an attempt was made to execute a command that * is not defined. * * @param commandId * The identifier of command that is not defined; never * null * @param exception * The exception that occurred; never null. */ virtual void NotDefined(const QString& commandId, const NotDefinedException* exception) = 0; /** * Notifies the listener that an attempt was made to execute a command that * is disabled. * * @param commandId * The identifier of command that is not enabled; never * null * @param exception * The exception that occurred; never null. */ virtual void NotEnabled(const QString& commandId, const NotEnabledException* exception) = 0; }; } #endif /* BERRYIEXECUTIONLISTENERWITHCHECKS_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIHandler.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIHandler.h index b3e043c04c..e3ee947558 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIHandler.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIHandler.h @@ -1,123 +1,126 @@ /*=================================================================== 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 BERRYIHANDLER_H_ #define BERRYIHANDLER_H_ #include #include #include namespace berry { struct IHandlerListener; class ExecutionEvent; /** * A handler is the pluggable piece of a command that handles execution. Each * command can have zero or more handlers associated with it (in general), of * which only one will be active at any given moment in time. When the command * is asked to execute, it will simply pass that request on to its active * handler, if any. * * @see AbstractHandler - * @since 3.1 */ -struct BERRY_COMMANDS IHandler : public Object { +struct BERRY_COMMANDS IHandler : public virtual Object +{ - berryInterfaceMacro(IHandler, berry); + berryObjectMacro(berry::IHandler) /** * Registers an instance of IHandlerListener to listen for * changes to properties of this instance. * * @param handlerListener * the instance to register. Must not be null. If * an attempt is made to register an instance which is already * registered with this instance, no operation is performed. */ - virtual void AddHandlerListener(SmartPointer handlerListener) = 0; + virtual void AddHandlerListener(IHandlerListener* handlerListener) = 0; /** - * Disposes of this handler. This can be used as an opportunity to unhook listeners + * Disposes of this handler. This method is run once when the object is no + * longer referenced. This can be used as an opportunity to unhook listeners * from other objects. */ - virtual ~IHandler() {} + virtual void Dispose() = 0; /** * Executes with the map of parameter values by name. * * @param event * An event containing all the information about the current * state of the application; must not be null. * @return the result of the execution. Reserved for future use, must be * null. * @throws ExecutionException * if an exception occurred during execution. */ - virtual Object::Pointer Execute(const SmartPointer event) = 0; + virtual Object::Pointer Execute(const SmartPointer& event) = 0; /** * Called by the framework to allow the handler to update its enabled state. * * @param evaluationContext * the state to evaluate against. May be null * which indicates that the handler can query whatever model that * is necessary. This context must not be cached. */ - virtual void SetEnabled(Object::ConstPointer evaluationContext) = 0; + virtual void SetEnabled(const Object::Pointer& evaluationContext) = 0; /** * Returns whether this handler is capable of executing at this moment in * time. If the enabled state is other than true clients should also * consider implementing IHandler2 so they can be notified about framework * execution contexts. * * @return true if the command is enabled; false * otherwise. * @see IHandler2#setEnabled(Object) */ virtual bool IsEnabled() const = 0; /** * Returns whether this handler is really capable of handling delegation. In * the case of a handler that is a composition of other handlers, this reply * is intended to indicate whether the handler is truly capable of receiving * delegated responsibilities at this time. * * @return true if the handler is handled; false * otherwise. */ virtual bool IsHandled() const = 0; /** * Unregisters an instance of IHandlerListener listening for * changes to properties of this instance. * * @param handlerListener * the instance to unregister. Must not be null. * If an attempt is made to unregister an instance which is not * already registered with this instance, no operation is * performed. */ - virtual void RemoveHandlerListener(SmartPointer handlerListener) = 0; + virtual void RemoveHandlerListener(IHandlerListener* handlerListener) = 0; }; } +Q_DECLARE_INTERFACE(berry::IHandler, "org.blueberry.core.commands.IHandler") + #endif /*BERRYIHANDLER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIHandlerListener.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIHandlerListener.cpp index 96985406ab..844978ae5c 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIHandlerListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIHandlerListener.cpp @@ -1,43 +1,47 @@ /*=================================================================== 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 "berryIHandlerListener.h" #include "berryIHandler.h" #include "berryHandlerEvent.h" namespace berry { void IHandlerListener::Events -::AddListener(IHandlerListener::Pointer l) +::AddListener(IHandlerListener* l) { - if (l.IsNull()) return; + if (l == NULL) return; - handlerChanged += Delegate(l.GetPointer(), &IHandlerListener::HandlerChanged); + handlerChanged += Delegate(l, &IHandlerListener::HandlerChanged); } void IHandlerListener::Events -::RemoveListener(IHandlerListener::Pointer l) +::RemoveListener(IHandlerListener* l) { - if (l.IsNull()) return; + if (l == NULL) return; - handlerChanged -= Delegate(l.GetPointer(), &IHandlerListener::HandlerChanged); + handlerChanged -= Delegate(l, &IHandlerListener::HandlerChanged); +} + +IHandlerListener::~IHandlerListener() +{ } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIHandlerListener.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIHandlerListener.h index 96673f4154..cde1f9fc6f 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIHandlerListener.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIHandlerListener.h @@ -1,72 +1,72 @@ /*=================================================================== 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 BERRYIHANDLERLISTENER_H_ #define BERRYIHANDLERLISTENER_H_ -#include -#include #include #include namespace berry { +template class SmartPointer; + class HandlerEvent; /** * An instance of this interface can be used by clients to receive notification * of changes to one or more instances of IHandler. *

* This interface may be implemented by clients. *

* - * @since 3.1 * @see IHandler#addHandlerListener(IHandlerListener) * @see IHandler#removeHandlerListener(IHandlerListener) */ -struct BERRY_COMMANDS IHandlerListener : public virtual Object { - - berryInterfaceMacro(IHandlerListener, berry); +struct BERRY_COMMANDS IHandlerListener +{ struct Events { - typedef Message1 > Event; + typedef Message1&> Event; Event handlerChanged; - void AddListener(IHandlerListener::Pointer listener); - void RemoveListener(IHandlerListener::Pointer listener); + void AddListener(IHandlerListener* listener); + void RemoveListener(IHandlerListener* listener); private: - typedef MessageDelegate1 > Delegate; + typedef MessageDelegate1&> Delegate; }; + virtual ~IHandlerListener(); + /** * Notifies that one or more properties of an instance of * IHandler have changed. Specific details are described in * the HandlerEvent. * * @param handlerEvent * the handler event. Guaranteed not to be null. */ - virtual void HandlerChanged(SmartPointer handlerEvent) = 0; + virtual void HandlerChanged(const SmartPointer& handlerEvent) = 0; }; } #endif /* BERRYIHANDLERLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIObjectWithState.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIObjectWithState.h index 24d1ad12bf..fc15b5b424 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIObjectWithState.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIObjectWithState.h @@ -1,86 +1,87 @@ /*=================================================================== 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 BERRYIOBJECTWITHSTATE_H_ #define BERRYIOBJECTWITHSTATE_H_ -#include -#include "berryState.h" +#include "berryObject.h" -#include +#include namespace berry { +class State; + /** *

* An object that holds zero or more state objects. This state information can * be shared between different instances of IObjectWithState. *

*

* Clients may implement, but must not extend this interface. *

* * @see AbstractHandlerWithState - * @since 3.2 */ -struct BERRY_COMMANDS IObjectWithState : public virtual Object { +struct BERRY_COMMANDS IObjectWithState : public virtual Object +{ - berryInterfaceMacro(IObjectWithState, berry); + berryObjectMacro(berry::IObjectWithState) /** * Adds state to this object. * * @param id * The identifier indicating the type of state being added; must * not be null. * @param state * The new state to add to this object; must not be * null. */ - virtual void AddState(const QString& id, const State::Pointer state) = 0; + virtual void AddState(const QString& id, const SmartPointer& state) = 0; /** * Gets the state with the given id. * * @param stateId * The identifier of the state to retrieve; must not be * null. * @return The state; may be null if there is no state with * the given id. */ - virtual State::Pointer GetState(const QString& stateId) const = 0; + virtual SmartPointer GetState(const QString& stateId) const = 0; /** * Gets the identifiers for all of the state associated with this object. * * @return All of the state identifiers; may be empty, but never * null. */ - virtual QStringList GetStateIds() const = 0; + virtual QList GetStateIds() const = 0; /** * Removes state from this object. * * @param stateId * The id of the state to remove from this object; must not be * null. */ virtual void RemoveState(const QString& stateId) = 0; }; } #endif /*BERRYIOBJECTWITHSTATE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameter.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameter.h index 5c50bd849c..44be5babf9 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameter.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameter.h @@ -1,78 +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 BERRYIPARAMETER_H_ #define BERRYIPARAMETER_H_ #include #include #include -#include namespace berry { +struct IParameterValues; + /** *

* A parameter for a command. A parameter identifies a type of information that * the command might accept. For example, a "Show View" command might accept the * id of a view for display. This parameter also identifies possible values, for * display in the user interface. *

*/ struct BERRY_COMMANDS IParameter : public virtual Object { - berryInterfaceMacro(IParameter, berry) + berryObjectMacro(berry::IParameter) typedef QHash ParameterValues; /** * Returns the identifier for this parameter. * * @return The identifier; never null. */ virtual QString GetId() const = 0; /** * Returns the human-readable name for this parameter. * * @return The parameter name; never null. */ virtual QString GetName() const = 0; /** * Returns the values associated with this parameter. * * @return The values associated with this parameter. This must not be * null. * @throws ParameterValuesException * If the values can't be retrieved for some reason. */ - virtual ParameterValues GetValues() const = 0; + virtual IParameterValues* GetValues() const = 0; /** * Returns whether parameter is optional. Otherwise, it is required. * * @return true if the parameter is optional; * false if it is required. */ virtual bool IsOptional() const = 0; }; } #endif /*BERRYIPARAMETER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterTypeListener.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterTypeListener.cpp index 68b1a84a14..5df43bc944 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterTypeListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterTypeListener.cpp @@ -1,43 +1,47 @@ /*=================================================================== 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 "berryIParameterTypeListener.h" #include "berryParameterTypeEvent.h" #include "berryParameterType.h" namespace berry { void IParameterTypeListener::Events ::AddListener(IParameterTypeListener* l) { if (l == 0) return; parameterTypeChanged += Delegate(l, &IParameterTypeListener::ParameterTypeChanged); } void IParameterTypeListener::Events ::RemoveListener(IParameterTypeListener* l) { if (l == 0) return; parameterTypeChanged -= Delegate(l, &IParameterTypeListener::ParameterTypeChanged); } +IParameterTypeListener::~IParameterTypeListener() +{ +} + } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterTypeListener.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterTypeListener.h index 7e2f86ac96..dd51f3bc42 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterTypeListener.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterTypeListener.h @@ -1,72 +1,73 @@ /*=================================================================== 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 BERRYIPARAMETERTYPELISTENER_H_ #define BERRYIPARAMETERTYPELISTENER_H_ -#include -#include #include #include namespace berry { +template class SmartPointer; + class ParameterTypeEvent; /** * An instance of this interface can be used by clients to receive notification * of changes to one or more instances of {@link ParameterType}. *

* This interface may be implemented by clients. *

* * @see ParameterType#AddListener(IParameterTypeListener::Pointer) * @see ParameterType#RemoveListener(IParameterTypeListener::Pointer) */ -struct BERRY_COMMANDS IParameterTypeListener : public virtual Object { - - berryInterfaceMacro(IParameterTypeListener, berry); +struct BERRY_COMMANDS IParameterTypeListener +{ struct Events { - typedef Message1 > Event; + typedef Message1& > Event; Event parameterTypeChanged; void AddListener(IParameterTypeListener* listener); void RemoveListener(IParameterTypeListener* listener); - typedef MessageDelegate1 > Delegate; + typedef MessageDelegate1& > Delegate; }; + virtual ~IParameterTypeListener(); + /** * Notifies that one or more properties of an instance of * {@link ParameterType} have changed. Specific details are described in the * {@link ParameterTypeEvent}. * * @param parameterTypeEvent * the event. Guaranteed not to be null. */ - virtual void ParameterTypeChanged(const SmartPointer parameterTypeEvent) = 0; + virtual void ParameterTypeChanged(const SmartPointer& parameterTypeEvent) = 0; }; } #endif /* BERRYIPARAMETERTYPELISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryRuntime.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValueConverter.cpp similarity index 82% copy from BlueBerry/Bundles/org.blueberry.core.runtime/src/berryRuntime.cpp copy to BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValueConverter.cpp index 7be762e2ce..503ce215b1 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryRuntime.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValueConverter.cpp @@ -1,23 +1,23 @@ /*=================================================================== 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 "berryRuntime.h" +#include "berryIParameterValueConverter.h" namespace berry { -const std::string Runtime::ADAPTER_SERVICE_ID = "org.blueberry.service.adapter"; +IParameterValueConverter::~IParameterValueConverter() {} } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValueConverter.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValueConverter.h index 1b1f04a13e..9c0d2e40b3 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValueConverter.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValueConverter.h @@ -1,106 +1,108 @@ /*=================================================================== 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 BERRYABSTRACTPARAMETERVALUECONVERTER_H_ #define BERRYABSTRACTPARAMETERVALUECONVERTER_H_ #include #include #include namespace berry { /** *

* Supports conversion between objects and strings for command parameter values. * Extenders must produce strings that identify objects (of a specific command * parameter type) as well as consume the strings to locate and return the * objects they identify. *

*

* This class offers multiple handlers of a command a consistent way of * converting string parameter values into the objects that the handlers would * prefer to deal with. This class also gives clients a way to serialize * object parameters as strings so that entire parameterized commands can be * serialized, stored and later deserialized and executed. *

*

* This class will typically be extended so the subclass can be referenced from * the converter attribute of the * commandParameterType elemement of the - * org.eclipse.ui.commands extension-point. Objects implementing + * org.blueberry.ui.commands extension-point. Objects implementing * this interface may also be passed directly to * {@link ParameterType#Define(IParameterValueConverter::Pointer)} by * clients. *

* * @see ParameterType#Define(IParameterValueConverter::Pointer) * @see ParameterizedCommand#Serialize() */ -struct BERRY_COMMANDS IParameterValueConverter : public virtual Object { +struct BERRY_COMMANDS IParameterValueConverter { - berryInterfaceMacro(IParameterValueConverter, berry); + virtual ~IParameterValueConverter(); /** * Returns whether the provided value is compatible with this parameter * value converter. An object is compatible with a converter if the object is an * instance of the class defined in the type attribute of * the commandParameterType element. * * @param value * an object to check for compatibility with this parameter type; * may be null. * @return true if the value is compatible with this converter, * false otherwise */ - virtual bool IsCompatible(const Object::ConstPointer value) const = 0; + //virtual bool IsCompatible(const Object::ConstPointer value) const = 0; /** * Converts a string encoded command parameter value into the parameter * value object. * * @param parameterValue * a command parameter value string describing an object; may be * null * @return the object described by the command parameter value string; may * be null * @throws ParameterValueConversionException * if an object cannot be produced from the * parameterValue string */ virtual Object::Pointer ConvertToObject(const QString& parameterValue) = 0; /** * Converts a command parameter value object into a string that encodes a * reference to the object or serialization of the object. * * @param parameterValue * an object to convert into an identifying string; may be * null * @return a string describing the provided object; may be null * @throws ParameterValueConversionException * if a string reference or serialization cannot be provided for * the parameterValue */ - virtual QString ConvertToString(const Object::Pointer parameterValue) = 0; + virtual QString ConvertToString(const Object::Pointer& parameterValue) = 0; }; } +Q_DECLARE_INTERFACE(berry::IParameterValueConverter, "org.blueberry.core.commands.IParameterValueConverter") + #endif /* BERRYABSTRACTPARAMETERVALUECONVERTER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryRuntime.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValues.cpp similarity index 82% copy from BlueBerry/Bundles/org.blueberry.core.runtime/src/berryRuntime.cpp copy to BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValues.cpp index 7be762e2ce..c0230ebfaa 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryRuntime.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValues.cpp @@ -1,23 +1,23 @@ /*=================================================================== 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 "berryRuntime.h" +#include "berryIParameterValues.h" namespace berry { -const std::string Runtime::ADAPTER_SERVICE_ID = "org.blueberry.service.adapter"; +IParameterValues::~IParameterValues() {} } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValues.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValues.h new file mode 100644 index 0000000000..56c70b1f0a --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValues.h @@ -0,0 +1,53 @@ +/*=================================================================== + +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 BERRYIPARAMETERVALUES_H +#define BERRYIPARAMETERVALUES_H + +#include "berryObject.h" + +#include +#include + +namespace berry { + +/** + *

+ * The parameters for a command. This interface will only be consulted if the + * parameters need to be displayed to the user. Otherwise, they will be ignored. + *

+*/ +struct IParameterValues +{ + virtual ~IParameterValues(); + + /** + * Returns a map keyed by externalized names for parameter values. These + * names should be human-readable, and are generally for display to the user + * in a user interface of some sort. The values should be actual values that + * will be interpreted by the handler for the command. + * + * @return A map of the externalizable name of the parameter value (String) + * to the actual value of the parameter (String). + */ + virtual QHash GetParameterValues() const = 0; +}; + +} + +Q_DECLARE_INTERFACE(berry::IParameterValues, "org.blueberry.core.commands.IParameterValues") + +#endif // BERRYIPARAMETERVALUES_H diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIStateListener.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIStateListener.h index 736b33ea5e..f99c226454 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIStateListener.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIStateListener.h @@ -1,73 +1,74 @@ /*=================================================================== 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 BERRYISTATELISTENER_H_ #define BERRYISTATELISTENER_H_ -#include "berryObject.h" -#include "berryMacros.h" - #include +#include "berryMessage.h" + namespace berry { +template class SmartPointer; + +class Object; class State; /** *

* A listener to changes in some state. *

*

* Clients may implement, but must not extend this interface. *

*/ -struct BERRY_COMMANDS IStateListener { - - berryInterfaceMacro(IStateListener, berry); +struct BERRY_COMMANDS IStateListener +{ struct Events { - typedef Message2&, const Object::Pointer&> StateEvent; + typedef Message2&, const SmartPointer&> StateEvent; StateEvent stateChanged; void AddListener(IStateListener* listener); void RemoveListener(IStateListener* listener); private: - typedef MessageDelegate2&, const Object::Pointer&> Delegate; + typedef MessageDelegate2&, const SmartPointer&> Delegate; }; virtual ~IStateListener(); /** * Handles a change to the value in some state. * * @param state * The state that has changed; never null. The * value for this state has been updated to the new value. * @param oldValue * The old value; may be anything. */ virtual void HandleStateChange(const SmartPointer& state, - const Object::Pointer& oldValue) = 0; + const SmartPointer& oldValue) = 0; }; } #endif /* BERRYISTATELISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryITypedParameter.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryITypedParameter.h index 013838bbf9..2430c74129 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryITypedParameter.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryITypedParameter.h @@ -1,55 +1,55 @@ /*=================================================================== 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 BERRYITYPEDPARAMETER_H_ #define BERRYITYPEDPARAMETER_H_ #include #include #include namespace berry { class ParameterType; /** * A command parameter that has a declared type. This interface is intended to * be implemented by implementors of {@link IParameter} that will support * parameter types. * */ struct BERRY_COMMANDS ITypedParameter : public virtual Object { - berryInterfaceMacro(ITypedParameter, berry); + berryObjectMacro(berry::ITypedParameter) /** * Returns the {@link ParameterType} associated with a command parameter or * null if the parameter does not declare a type. *

* Note that the parameter type returned may be undefined. *

* * @return the parameter type associated with a command parameter or * null if the parameter does not declare a type */ - virtual SmartPointer GetParameterType() = 0; + virtual SmartPointer GetParameterType() const = 0; }; } #endif /* BERRYITYPEDPARAMETER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryNamedHandleObjectWithState.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryNamedHandleObjectWithState.cpp index 2b0ce0c804..fb90b216af 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryNamedHandleObjectWithState.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryNamedHandleObjectWithState.cpp @@ -1,115 +1,115 @@ /*=================================================================== 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 "berryNamedHandleObjectWithState.h" #include "berryINamedHandleStateIds.h" -#include +#include "berryState.h" namespace berry { void NamedHandleObjectWithState::AddState(const QString& stateId, - const State::Pointer state) + const State::Pointer& state) { if (!state) { - throw Poco::NullPointerException("Cannot add a null state"); //$NON-NLS-1$ + throw Poco::NullPointerException("Cannot add a null state"); } states[stateId] = state; } QString NamedHandleObjectWithState::GetDescription() const { const QString description(NamedHandleObject::GetDescription()); // Trigger a NDE. const State::ConstPointer descriptionState(this->GetState(INamedHandleStateIds::DESCRIPTION)); if (descriptionState.IsNotNull()) { const Object::ConstPointer value(descriptionState->GetValue()); if (value.IsNotNull()) { return value->ToString(); } } return description; } QString NamedHandleObjectWithState::GetName() const { const QString name(NamedHandleObject::GetName()); // Trigger a NDE, if necessary. const State::ConstPointer nameState(this->GetState(INamedHandleStateIds::NAME)); if (nameState.IsNotNull()) { const Object::ConstPointer value(nameState->GetValue()); if (value.IsNotNull()) { return value->ToString(); } } return name; } State::Pointer NamedHandleObjectWithState::GetState( const QString& stateId) const { if (states.empty()) { return State::Pointer(0); } QHash::const_iterator iter = states.find(stateId); return iter.value(); } -QStringList NamedHandleObjectWithState::GetStateIds() const +QList NamedHandleObjectWithState::GetStateIds() const { if (states.empty()) { - return QStringList(); + return QList(); } - QStringList stateIds; + QList stateIds; for (QHash::const_iterator iter = states.begin(); iter != states.end(); ++iter) { stateIds.push_back(iter.key()); } return stateIds; } void NamedHandleObjectWithState::RemoveState(const QString& id) { if (id.isEmpty()) { throw ctkInvalidArgumentException("Cannot remove an empty id"); } states.remove(id); } NamedHandleObjectWithState::NamedHandleObjectWithState(const QString& id) : NamedHandleObject(id) { } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryNamedHandleObjectWithState.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryNamedHandleObjectWithState.h index ae0b688733..476cfc8529 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryNamedHandleObjectWithState.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryNamedHandleObjectWithState.h @@ -1,76 +1,76 @@ /*=================================================================== 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 BERRYNAMEDHANDLEOBJECTWITHSTATE_H_ #define BERRYNAMEDHANDLEOBJECTWITHSTATE_H_ #include "common/berryNamedHandleObject.h" #include "berryIObjectWithState.h" #include namespace berry { /** *

* A named handle object that can carry state with it. This state can be used to * override the name or description. *

*

* Clients may neither instantiate nor extend this class. *

*/ class BERRY_COMMANDS NamedHandleObjectWithState : public NamedHandleObject, public IObjectWithState { public: berryObjectMacro(berry::NamedHandleObjectWithState) - void AddState(const QString& stateId, const State::Pointer state); + void AddState(const QString& stateId, const SmartPointer& state); QString GetDescription() const; QString GetName() const; - State::Pointer GetState(const QString& stateId) const; + SmartPointer GetState(const QString& stateId) const; - QStringList GetStateIds() const; + QList GetStateIds() const; void RemoveState(const QString& id); - private: +private: - /** - * The map of states currently held by this command. If this command has no - * state, then this will be empty. - */ - QHash states; + /** + * The map of states currently held by this command. If this command has no + * state, then this will be empty. + */ + QHash > states; - protected: +protected: - /** - * Constructs a new instance of NamedHandleObject. - * - * @param id - * The identifier for this handle; must not be empty. - */ - NamedHandleObjectWithState(const QString& id); + /** + * Constructs a new instance of NamedHandleObject. + * + * @param id + * The identifier for this handle; must not be empty. + */ + NamedHandleObjectWithState(const QString& id); }; } #endif /*BERRYNAMEDHANDLEOBJECTWITHSTATE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterType.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterType.cpp index ba64324439..8624badffe 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterType.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterType.cpp @@ -1,126 +1,126 @@ /*=================================================================== 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 "berryParameterType.h" #include "internal/berryCommandUtils.h" #include "common/berryCommandExceptions.h" #include "berryParameterTypeEvent.h" #include "berryIParameterValueConverter.h" #include namespace berry { void ParameterType::AddListener(IParameterTypeListener* listener) { parameterTypeEvents.AddListener(listener); } bool ParameterType::operator<(const Object* object) const { const ParameterType* castedObject = dynamic_cast(object); int compareTo = CommandUtils::Compare(defined, castedObject->defined); if (compareTo == 0) { compareTo = CommandUtils::Compare(id, castedObject->id); } return compareTo < 0; } -void ParameterType::Define( - const SmartPointer parameterTypeConverter) +void ParameterType::Define(const QString& type, + const QSharedPointer& parameterTypeConverter) { - const bool definedChanged = !this->defined; this->defined = true; + this->type = type.isNull() ? QObject::staticMetaObject.className() : type; this->parameterTypeConverter = parameterTypeConverter; ParameterTypeEvent::Pointer event( new ParameterTypeEvent(ParameterType::Pointer(this), definedChanged)); this->FireParameterTypeChanged(event); } - -SmartPointer ParameterType::GetValueConverter() const +#include +IParameterValueConverter* ParameterType::GetValueConverter() const { if (!this->IsDefined()) { throw NotDefinedException( "Cannot use GetValueConverter() with an undefined ParameterType"); //$NON-NLS-1$ } - return parameterTypeConverter; + return parameterTypeConverter.data(); } -bool ParameterType::IsCompatible(const Object::ConstPointer value) const +bool ParameterType::IsCompatible(const QObject* const value) const { if (!this->IsDefined()) { throw NotDefinedException( "Cannot use IsCompatible() with an undefined ParameterType"); } - return parameterTypeConverter->IsCompatible(value); + return value->inherits(qPrintable(type)); } void ParameterType::RemoveListener(IParameterTypeListener* listener) { parameterTypeEvents.RemoveListener(listener); } QString ParameterType::ToString() const { if (str.isEmpty()) { QTextStream stringBuffer(&str); stringBuffer << "ParameterType(" << id << "," << defined << ")"; } return str; } void ParameterType::Undefine() { str = ""; const bool definedChanged = defined; defined = false; - parameterTypeConverter = 0; + parameterTypeConverter.clear(); ParameterTypeEvent::Pointer event( new ParameterTypeEvent(ParameterType::Pointer(this), definedChanged)); this->FireParameterTypeChanged(event); } ParameterType::ParameterType(const QString& id) : HandleObject(id) { } void ParameterType::FireParameterTypeChanged(const SmartPointer< ParameterTypeEvent> event) { if (!event) { throw ctkInvalidArgumentException("Cannot send a null event to listeners."); } parameterTypeEvents.parameterTypeChanged(event); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterType.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterType.h index 49e0f1b89e..c2855cbd8d 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterType.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterType.h @@ -1,193 +1,207 @@ /*=================================================================== 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 BERRYPARAMETERTYPE_H_ #define BERRYPARAMETERTYPE_H_ #include "common/berryHandleObject.h" #include "berryIParameterTypeListener.h" #include "berryIParameterValueConverter.h" +#include + namespace berry { struct IParameterValueConverter; /** *

* Provides information about the type of a command parameter. Clients can use a * parameter type to check if an object matches the type of the parameter with * {@link #IsCompatible(Object::Pointer)} and can get an * {@link IParameterValueConverter} to convert between objects matching * the parameter type and strings that encode the object's identity. *

*

* A command parameter is not required to declare a type. To determine if a * given parameter has a type, check if an {@link IParameter} implements * {@link ITypedParameter} and if so, use * {@link ITypedParameter#GetParameterType()} like this: *

* *
  *                   IParameter::Pointer parameter = // ... get IParameter from Command
  *                   if (ITypedParameter::Pointer typedParameter = parameter.Cast())
  *                   {
  *                     ParameterType::Pointer type = typedParameter->GetParameterType();
  *                     if (type) {
  *                       // this parameter has a ParameterType
  *                     }
  *                   }
  * 
* * @see IParameter * @see ITypedParameter#GetParameterType() */ class BERRY_COMMANDS ParameterType: public HandleObject { //implements Comparable { public: berryObjectMacro(ParameterType); /** * Adds a listener to this parameter type that will be notified when its * state changes. * * @param listener * The listener to be added; must not be null. */ void AddListener(IParameterTypeListener* listener); /** * Compares this parameter type with another object by comparing each of the * non-transient attributes. * * @param object * The object with which to compare; must be an instance of * {@link ParameterType}. * @return A negative integer, zero or a positive integer, if the object is * greater than, equal to or less than this parameter type. */ bool operator<(const Object* object) const; /** *

* Defines this parameter type, setting the defined property to * true. *

*

* Notification is sent to all listeners that something has changed. *

* + * @param type + * a string identifying the object type for this parameter + * type; null is interpreted as + * "QObject" * @param parameterTypeConverter * an {@link AbstractParameterValueConverter} to perform * string/object conversions for parameter values; may be * null */ - void Define(const SmartPointer parameterTypeConverter); + void Define(const QString& type, + const QSharedPointer& parameterTypeConverter); /** * Returns the value converter associated with this parameter, if any. * * @return The parameter value converter, or null if there is * no value converter for this parameter. * @throws NotDefinedException * if the parameter type is not currently defined */ - SmartPointer GetValueConverter() const; + IParameterValueConverter* GetValueConverter() const; /** * Returns whether the provided value is compatible with this parameter * type. An object is compatible with a parameter type if the object is an * instance of the class defined as the parameter's type class. * * @param value * an object to check for compatibility with this parameter type; * may be null. * @return true if the value is compatible with this type, * false otherwise * @throws NotDefinedException * if the parameter type is not currently defined */ - bool IsCompatible(const Object::ConstPointer value) const; + bool IsCompatible(const QObject* const value) const; /** * Unregisters listener for changes to properties of this parameter type. * * @param listener * the instance to unregister. Must not be null. * If an attempt is made to unregister an instance which is not * already registered with this instance, no operation is * performed. */ void RemoveListener(IParameterTypeListener* listener); /** * The string representation of this parameter type. For debugging purposes * only. This string should not be shown to an end user. * * @return The string representation; never null. */ QString ToString() const; /** * Makes this parameter type become undefined. Notification is sent to all * listeners. */ void Undefine(); protected: friend class CommandManager; /** * Constructs a new instance based on the given identifier. When a parameter * type is first constructed, it is undefined. Parameter types should only * be constructed by the {@link CommandManager} to ensure that the * identifier remains unique. * * @param id * The identifier for this type. This value must not be * null, and must be unique amongst all parameter * types. */ ParameterType(const QString& id); private: /** * Notifies all listeners that this parameter type has changed. This sends * the given event to all of the listeners, if any. * * @param event * The event to send to the listeners; must not be * null. */ void FireParameterTypeChanged(const SmartPointer event); /** * An {@link AbstractParameterValueConverter} for converting parameter * values between objects and strings. This may be null. */ - SmartPointer parameterTypeConverter; + QSharedPointer parameterTypeConverter; + + /** + * A string specifying the object type of this parameter type. This will be + * null when the parameter type is undefined but never null + * when it is defined. + */ + QString type; IParameterTypeListener::Events parameterTypeEvents; }; } #endif /* BERRYPARAMETERTYPE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterization.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterization.cpp index bb440b9754..7a01fcc78d 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterization.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterization.cpp @@ -1,119 +1,120 @@ /*=================================================================== 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 "berryParameterization.h" #include "berryIParameter.h" +#include "berryIParameterValues.h" namespace berry { const uint Parameterization::HASH_CODE_NOT_COMPUTED = 0; const uint Parameterization::HASH_FACTOR = 89; const uint Parameterization::HASH_INITIAL = qHash("berry::Parameterization"); Parameterization::Parameterization(const SmartPointer parameter, const QString& value) : hashCode(HASH_CODE_NOT_COMPUTED), parameter(parameter), value(value) { if (!parameter) { throw ctkInvalidArgumentException( "You cannot parameterize a null parameter"); } } Parameterization::Parameterization(const Parameterization& p) : hashCode(p.hashCode), parameter(p.parameter), value(p.value) { } Parameterization& Parameterization::operator=(const Parameterization& p) { this->hashCode = p.hashCode; this->parameter = p.parameter; this->value = p.value; return *this; } bool Parameterization::operator==(const Parameterization& parameterization) const { if (this == ¶meterization) { return true; } // if (!(object instanceof Parameterization)) { // return false; // } if (this->parameter->GetId() != parameterization.parameter->GetId()) { return false; } return (this->value == parameterization.value); } Parameterization::operator bool() const { return true; } SmartPointer Parameterization::GetParameter() const { return parameter; } QString Parameterization::GetValue() const { return value; } QString Parameterization::GetValueName() const { - const IParameter::ParameterValues parameterValues = parameter->GetValues(); + const QHash parameterValues = parameter->GetValues()->GetParameterValues(); QString returnValue; for (IParameter::ParameterValues::const_iterator parameterValueItr = parameterValues.begin(); parameterValueItr != parameterValues.end(); ++ parameterValueItr) { const QString currentValue(parameterValueItr.value()); if (value == currentValue) { returnValue = parameterValueItr.key(); break; } } return returnValue; } uint Parameterization::HashCode() const { if (hashCode == HASH_CODE_NOT_COMPUTED) { hashCode = HASH_INITIAL * HASH_FACTOR + parameter->HashCode(); hashCode = hashCode * HASH_FACTOR + qHash(value); if (hashCode == HASH_CODE_NOT_COMPUTED) { hashCode++; } } return hashCode; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterizedCommand.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterizedCommand.cpp index b4af02bae7..c18f6df375 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterizedCommand.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterizedCommand.cpp @@ -1,432 +1,449 @@ /*=================================================================== 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 "berryParameterizedCommand.h" #include "berryIParameter.h" +#include "berryIParameterValues.h" #include "berryCommand.h" #include "berryParameterization.h" #include "berryExecutionEvent.h" #include "berryCommandManager.h" #include "berryCommandCategory.h" +#include "berryState.h" #include "berryIHandler.h" #include "internal/berryCommandUtils.h" #include namespace berry { const int INDEX_PARAMETER_ID = 0; const int INDEX_PARAMETER_NAME = 1; const int INDEX_PARAMETER_VALUE_NAME = 2; const int INDEX_PARAMETER_VALUE_VALUE = 3; const uint ParameterizedCommand::HASH_CODE_NOT_COMPUTED = 0; const uint ParameterizedCommand::HASH_FACTOR = 89; const uint ParameterizedCommand::HASH_INITIAL = qHash("berry::ParameterizedCommand"); ParameterizedCommand::ParameterizedCommand(const SmartPointer& command, const QList& params) : command(command), hashCode(HASH_CODE_NOT_COMPUTED) { if (!command) { throw Poco::NullPointerException( "A parameterized command cannot have a null command"); } QList parameters; try { parameters = command->GetParameters(); } catch (const NotDefinedException* /*e*/) { // This should not happen. } if (!params.empty() && !parameters.empty()) { - for (unsigned int j = 0; j < parameters.size(); j++) + for (int j = 0; j < parameters.size(); j++) { - for (unsigned int i = 0; i < params.size(); i++) + for (int i = 0; i < params.size(); i++) { if (parameters[j] == params[i].GetParameter()) { this->parameterizations.push_back(params[i]); } } } } } bool ParameterizedCommand::operator<(const Object* object) const { const ParameterizedCommand* command = dynamic_cast(object); const bool thisDefined = this->command->IsDefined(); const bool otherDefined = command->command->IsDefined(); if (!thisDefined || !otherDefined) { return CommandUtils::Compare(thisDefined, otherDefined) < 0; } try { const int compareTo = this->GetName().compare(command->GetName()); if (compareTo == 0) { return (this->GetId() < command->GetId()); } return compareTo < 0; } catch (const NotDefinedException* /*e*/) { throw CommandException( "Concurrent modification of a command's defined state"); } } bool ParameterizedCommand::operator==(const Object* object) const { if (this == object) { return true; } if (const ParameterizedCommand* command = dynamic_cast(object)) { if (!(this->command == command->command)) { return false; } return CommandUtils::Equals(this->parameterizations, command->parameterizations); } return false; } -Object::Pointer ParameterizedCommand::ExecuteWithChecks(const Object::ConstPointer trigger, - const Object::ConstPointer applicationContext) +Object::Pointer ParameterizedCommand::ExecuteWithChecks(const Object::ConstPointer& trigger, + const Object::Pointer& applicationContext) { ExecutionEvent::Pointer excEvent(new ExecutionEvent(command, this->GetParameterMap(), trigger, applicationContext)); return command->ExecuteWithChecks(excEvent); } SmartPointer ParameterizedCommand::GetCommand() const { return command; } QString ParameterizedCommand::GetId() const { return command->GetId(); } QString ParameterizedCommand::GetName() const { if (name.isEmpty()) { QTextStream nameBuffer(&name); nameBuffer << command->GetName() << " ("; const unsigned int parameterizationCount = (unsigned int) parameterizations.size(); for (unsigned int i = 0; i < parameterizationCount; i++) { const Parameterization& parameterization = parameterizations[i]; nameBuffer << parameterization.GetParameter()->GetName() << ": "; try { nameBuffer << parameterization.GetValueName(); } - catch (const ParameterValuesException* /*e*/) + catch (const ParameterValuesException& /*e*/) { /* * Just let it go for now. If someone complains we can * add more info later. */ } // If there is another item, append a separator. if (i + 1 < parameterizationCount) { nameBuffer << ", "; } nameBuffer << ")"; } } return name; } QHash ParameterizedCommand::GetParameterMap() const { QHash parameterMap; - for (unsigned int i = 0; i < parameterizations.size(); i++) + for (int i = 0; i < parameterizations.size(); i++) { const Parameterization& parameterization = parameterizations[i]; parameterMap.insert(parameterization.GetParameter()->GetId(), parameterization.GetValue()); } return parameterMap; } uint ParameterizedCommand::HashCode() const { if (hashCode == HASH_CODE_NOT_COMPUTED) { hashCode = HASH_INITIAL * HASH_FACTOR + (command ? command->HashCode() : 0); hashCode = hashCode * HASH_FACTOR; - for (unsigned int i = 0; i < parameterizations.size(); i++) + for (int i = 0; i < parameterizations.size(); i++) { hashCode += parameterizations[i].HashCode(); } if (hashCode == HASH_CODE_NOT_COMPUTED) { hashCode++; } } return hashCode; } QString ParameterizedCommand::Serialize() { const QString escapedId(this->Escape(this->GetId())); if (parameterizations.empty()) { return escapedId; } QString str; QTextStream buffer(&str); buffer << CommandManager::PARAMETER_START_CHAR; - for (unsigned int i = 0; i < parameterizations.size(); i++) + for (int i = 0; i < parameterizations.size(); i++) { if (i> 0) { // insert separator between parameters buffer << CommandManager::PARAMETER_SEPARATOR_CHAR; } const Parameterization& parameterization = parameterizations[i]; const QString parameterId(parameterization.GetParameter()->GetId()); const QString escapedParameterId(this->Escape(parameterId)); buffer << escapedParameterId; const QString parameterValue(parameterization.GetValue()); if (!parameterValue.isEmpty()) { const QString escapedParameterValue(this->Escape(parameterValue)); buffer << CommandManager::ID_VALUE_CHAR << escapedParameterValue; } } buffer << CommandManager::PARAMETER_END_CHAR; return str; } QString ParameterizedCommand::ToString() const { QString str; QTextStream buffer(&str); buffer << "ParameterizedCommand(" << command->ToString() << "," << CommandUtils::ToString(parameterizations) << ")"; return str; } QList ParameterizedCommand::GenerateCombinations(const SmartPointer command) { QList parameters(command->GetParameters()); typedef QList > ExpandedParamsType; const ExpandedParamsType expansion(ExpandParameters(0, parameters)); QList combinations; for (ExpandedParamsType::const_iterator expansionItr = expansion.begin(); expansionItr != expansion.end(); ++expansionItr) { QList combination(*expansionItr); QList parameterizations(combination); ParameterizedCommand::Pointer pCmd(new ParameterizedCommand(command, parameterizations)); combinations.push_back(pCmd); } return combinations; } ParameterizedCommand::Pointer ParameterizedCommand::GenerateCommand(const SmartPointer command, const QHash& parameters) { // no parameters if (parameters.empty()) { ParameterizedCommand::Pointer pCmd(new ParameterizedCommand(command, QList())); return pCmd; } try { QList parms; // iterate over given parameters for (QHash::const_iterator i = parameters.begin(); i != parameters.end(); ++i) { QString key(i.key()); // get the parameter from the command IParameter::Pointer parameter(command->GetParameter(key)); // if the parameter is defined add it to the parameter list if (!parameter) { return ParameterizedCommand::Pointer(0); } ParameterType::Pointer parameterType(command->GetParameterType(key)); if (!parameterType) { QString val(*(i.value().Cast())); parms.push_back(Parameterization(parameter, val)); } else { - IParameterValueConverter::Pointer valueConverter(parameterType - ->GetValueConverter()); + IParameterValueConverter* valueConverter(parameterType->GetValueConverter()); if (valueConverter) { QString val(valueConverter->ConvertToString(i.value())); parms.push_back(Parameterization(parameter, val)); } else { QString val(*(i.value().Cast())); parms.push_back(Parameterization(parameter, val)); } } } // convert the parameters to an Parameterization array and create // the command ParameterizedCommand::Pointer pCmd(new ParameterizedCommand(command, parms)); return pCmd; } catch (const NotDefinedException* /*e*/) { } catch (const ParameterValueConversionException* /*e*/) { } return ParameterizedCommand::Pointer(0); } QString ParameterizedCommand::Escape(const QString& rawText) { QString buffer; for (QString::const_iterator i = rawText.begin(); i != rawText.end(); ++i) { QString::value_type c = *i; if (c == CommandManager::PARAMETER_START_CHAR || c == CommandManager::PARAMETER_END_CHAR || c == CommandManager::ID_VALUE_CHAR || c == CommandManager::PARAMETER_SEPARATOR_CHAR || c == CommandManager::ESCAPE_CHAR) { buffer += CommandManager::ESCAPE_CHAR; } buffer += c; } if (buffer.isEmpty()) { return rawText; } return buffer; } QList > ParameterizedCommand::ExpandParameters( unsigned int startIndex, const QList& parameters) { typedef QList > ReturnType; - const unsigned int nextIndex = startIndex + 1; + const int nextIndex = startIndex + 1; const bool noMoreParameters = (nextIndex >= parameters.size()); const IParameter::Pointer parameter(parameters[startIndex]); ReturnType parameterizations; if (parameter->IsOptional()) { parameterizations.push_back(QList()); } - IParameter::ParameterValues parameterValues(parameter->GetValues()); - for (IParameter::ParameterValues::iterator parameterValueItr = + IParameterValues* values = NULL; + try + { + values = parameter->GetValues(); + } + catch (const ParameterValuesException& /*e*/) + { + if (noMoreParameters) + { + return parameterizations; + } + + // Make recursive call + return ExpandParameters(nextIndex, parameters); + } + + const QHash parameterValues = values->GetParameterValues(); + for (IParameter::ParameterValues::const_iterator parameterValueItr = parameterValues.begin(); parameterValueItr != parameterValues.end(); ++parameterValueItr) { QList combination; combination.push_back( Parameterization(parameter, parameterValueItr.value())); parameterizations.push_back(combination); } // Check if another iteration will produce any more names. if (noMoreParameters) { // This is it, so just return the current parameterizations. return parameterizations; } // Make recursive call ReturnType suffixes(ExpandParameters(nextIndex, parameters)); if (suffixes.empty()) { // This is it, so just return the current parameterizations. return parameterizations; } ReturnType returnValue; for (ReturnType::iterator suffixItr = suffixes.begin(); suffixItr != suffixes.end(); ++suffixItr) { for (ReturnType::iterator combinationItr = parameterizations.begin(); combinationItr != parameterizations.end(); ++combinationItr) { QList newCombination(*combinationItr); newCombination.append(*suffixItr); returnValue.push_back(newCombination); } } return returnValue; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterizedCommand.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterizedCommand.h index 40f60b8e95..7ba97d93c2 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterizedCommand.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterizedCommand.h @@ -1,338 +1,338 @@ /*=================================================================== 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 BERRYPARAMETERIZEDCOMMAND_H_ #define BERRYPARAMETERIZEDCOMMAND_H_ #include #include #include "common/berryCommandExceptions.h" #include #include #include namespace berry { struct IParameter; class Command; class Parameterization; /** *

* A command that has had one or more of its parameters specified. This class * serves as a utility class for developers that need to manipulate commands * with parameters. It handles the behaviour of generating a parameter map and a * human-readable name. *

*/ class BERRY_COMMANDS ParameterizedCommand: public Object { //implements Comparable { public: berryObjectMacro(ParameterizedCommand); /** * The index of the parameter id in the parameter values. * * @deprecated no longer used */ static const int INDEX_PARAMETER_ID; // = 0; /** * The index of the human-readable name of the parameter itself, in the * parameter values. * * @deprecated no longer used */ static const int INDEX_PARAMETER_NAME; // = 1; /** * The index of the human-readable name of the value of the parameter for * this command. * * @deprecated no longer used */ static const int INDEX_PARAMETER_VALUE_NAME; // = 2; /** * The index of the value of the parameter that the command can understand. * * @deprecated no longer used */ static const int INDEX_PARAMETER_VALUE_VALUE; // = 3; /** * Constructs a new instance of ParameterizedCommand with * specific values for zero or more of its parameters. * * @param command * The command that is parameterized; must not be * null. * @param parameterizations * An array of parameterizations binding parameters to values for * the command. This value may be null. */ ParameterizedCommand(const SmartPointer& command, const QList& parameterizations); bool operator<(const Object* object) const; bool operator==(const Object* object) const; /** * Executes this command with its parameters. This does extra checking to * see if the command is enabled and defined. If it is not both enabled and * defined, then the execution listeners will be notified and an exception * thrown. * * @param trigger * The object that triggered the execution; may be * null. * @param applicationContext * The state of the application at the time the execution was * triggered; may be null. * @return The result of the execution; may be null. * @throws ExecutionException * If the handler has problems executing this command. * @throws NotDefinedException * If the command you are trying to execute is not defined. * @throws NotEnabledException * If the command you are trying to execute is not enabled. * @throws NotHandledException * If there is no handler. */ - Object::Pointer ExecuteWithChecks(const Object::ConstPointer trigger, - const Object::ConstPointer applicationContext); + Object::Pointer ExecuteWithChecks(const Object::ConstPointer& trigger, + const Object::Pointer& applicationContext); /** * Returns the base command. It is possible for more than one parameterized * command to have the same identifier. * * @return The command; never null, but may be undefined. */ SmartPointer GetCommand() const; /** * Returns the command's base identifier. It is possible for more than one * parameterized command to have the same identifier. * * @return The command id; never null. */ QString GetId() const; /** * Returns a human-readable representation of this command with all of its * parameterizations. * * @return The human-readable representation of this parameterized command; * never null. * @throws NotDefinedException * If the underlying command is not defined. */ QString GetName() const; /** * Returns the parameter map, as can be used to construct an * ExecutionEvent. * * @return The map of parameter ids (String) to parameter * values (String). This map is never * null, but may be empty. */ QHash GetParameterMap() const; uint HashCode() const; /** * Returns a {@link String} containing the command id, parameter ids and * parameter values for this {@link ParameterizedCommand}. The returned * {@link String} can be stored by a client and later used to reconstruct an * equivalent {@link ParameterizedCommand} using the * {@link CommandManager#deserialize(String)} method. *

* The syntax of the returned {@link String} is as follows: *

* *
* serialization = commandId [ '(' parameters ')' ]
* parameters = parameter [ ',' parameters ]
* parameter = parameterId [ '=' parameterValue ] *
* *

* In the syntax above, sections inside square-brackets are optional. The * characters in single quotes ((, ), * , and =) indicate literal characters. *

*

* commandId represents the command id encoded with * separator characters escaped. parameterId and * parameterValue represent the parameter ids and * values encoded with separator characters escaped. The separator * characters (, ), , and * = are escaped by prepending a %. This * requires % to be escaped, which is also done by prepending * a %. *

*

* The order of the parameters is not defined (and not important). A missing * parameterValue indicates that the value of the * parameter is null. *

*

* For example, the string shown below represents a serialized parameterized * command that can be used to show the Resource perspective: *

*

* org.eclipse.ui.perspectives.showPerspective(org.eclipse.ui.perspectives.showPerspective.perspectiveId=org.eclipse.ui.resourcePerspective) *

*

* This example shows the more general form with multiple parameters, * null value parameters, and escaped = in the * third parameter value. *

*

* command.id(param1.id=value1,param2.id,param3.id=esc%=val3) *

* * @return A string containing the escaped command id, parameter ids and * parameter values; never null. * @see CommandManager#deserialize(String) */ QString Serialize(); QString ToString() const; /** *

* Generates all the possible combinations of command parameterizations for * the given command. If the command has no parameters, then this is simply * a parameterized version of that command. If a parameter is optional, both * the included and not included cases are considered. *

*

* If one of the parameters cannot be loaded due to a * ParameterValuesException, then it is simply ignored. *

* * @param command * The command for which the parameter combinations should be * generated; must not be null. * @return A collection of ParameterizedCommand instances * representing all of the possible combinations. This value is * never empty and it is never null. * @throws NotDefinedException * If the command is not defined. */ static QList GenerateCombinations(const SmartPointer command); /** * Take a command and a map of parameter IDs to values, and generate the * appropriate parameterized command. * * @param command * The command object. Must not be null. * @param parameters * A map of String parameter ids to objects. May be * null. * @return the parameterized command, or null if it could not * be generated */ static ParameterizedCommand::Pointer GenerateCommand(const SmartPointer command, const QHash& parameters); private: /** * The constant integer hash code value meaning the hash code has not yet * been computed. */ static const uint HASH_CODE_NOT_COMPUTED; // = 0; /** * A factor for computing the hash code for all parameterized commands. */ static const uint HASH_FACTOR; // = 89; /** * The seed for the hash code for all parameterized commands. */ static const uint HASH_INITIAL; /** * Escapes special characters in the command id, parameter ids and parameter * values for {@link #serialize()}. The special characters * {@link CommandManager#PARAMETER_START_CHAR}, * {@link CommandManager#PARAMETER_END_CHAR}, * {@link CommandManager#ID_VALUE_CHAR}, * {@link CommandManager#PARAMETER_SEPARATOR_CHAR} and * {@link CommandManager#ESCAPE_CHAR} are escaped by prepending a * {@link CommandManager#ESCAPE_CHAR} character. * * @param rawText * a String to escape special characters in for * serialization. * @return a String representing rawText with * special serialization characters escaped */ static QString Escape(const QString& rawText); /** * Generates every possible combination of parameter values for the given * parameters. Parameters values that cannot be initialized are just * ignored. Optional parameters are considered. * * @param startIndex * The index in the parameters that we should * process. This must be a valid index. * @param parameters * The parameters in to process; must not be null. * @return A collection (Collection) of combinations (List * of Parameterization). */ static QList > ExpandParameters(unsigned int startIndex, const QList >& parameters); /** * The base command which is being parameterized. This value is never * null. */ const SmartPointer command; /** * The hash code for this object. This value is computed lazily, and marked * as invalid when one of the values on which it is based changes. */ mutable uint hashCode; /** * This is an array of parameterization defined for this command. This value * may be null if the command has no parameters. */ QList parameterizations; mutable QString name; }; } #endif /* BERRYPARAMETERIZEDCOMMAND_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryHandleObject.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryHandleObject.cpp index 8139043b37..bd5db0aad9 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryHandleObject.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryHandleObject.cpp @@ -1,60 +1,60 @@ /*=================================================================== 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 "berryHandleObject.h" #include namespace berry { const uint HandleObject::HASH_CODE_NOT_COMPUTED = 0; const uint HandleObject::HASH_FACTOR = 89; -const uint HandleObject::HASH_INITIAL = qHash("berry::HandleObject"); +const uint HandleObject::HASH_INITIAL = qHash(HandleObject::GetStaticClassName()); HandleObject::HandleObject(const QString& ID) : hashCode(HASH_CODE_NOT_COMPUTED), defined(false), id(ID) { } bool HandleObject::operator==(const Object* object) const { // Check if they're the same. if (object == this) { return true; } // Check if they're the same type. if (const Self* o = dynamic_cast(object)) { // Check each property in turn. return (id == o->id); } return false; } QString HandleObject::GetId() const { return id; } bool HandleObject::IsDefined() const { return defined; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryHandleObject.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryHandleObject.h index c50ece2d86..d680036029 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryHandleObject.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryHandleObject.h @@ -1,168 +1,168 @@ /*=================================================================== 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 BERRYHANDLEOBJECT_H_ #define BERRYHANDLEOBJECT_H_ #include #include #include #include namespace berry { /** *

* An object that can exist in one of two states: defined and undefined. This is * used by APIs that want to give a handle to an object, even though the object * does not fully exist yet. This way, users can attach listeners to objects * before they come into existence. It also protects the API from users that do * not release references when they should. *

*

* To enforce good coding practice, all handle objects must implement * equals and toString. Please use * string to cache the result for toString once * calculated. *

*

* All handle objects are referred to using a single identifier. This identifier * is a instance of String. It is important that this identifier * remain unique within whatever context that handle object is being used. For * example, there should only ever be one instance of Command * with a given identifier. *

* * @since 3.1 */ class BERRY_COMMANDS HandleObject : public virtual Object { // extends EventManager implements IIdentifiable { public: berryObjectMacro(HandleObject); private: /** * The constant integer hash code value meaning the hash code has not yet * been computed. */ static const uint HASH_CODE_NOT_COMPUTED; // = 0; /** * A factor for computing the hash code for all schemes. */ static const uint HASH_FACTOR; // = 89; /** * The seed for the hash code for all schemes. */ static const uint HASH_INITIAL; /** * The hash code for this object. This value is computed lazily, and marked * as invalid when one of the values on which it is based changes. */ mutable uint hashCode; // = HASH_CODE_NOT_COMPUTED; protected: /** * Whether this object is defined. A defined object is one that has been * fully initialized. By default, all objects start as undefined. */ bool defined; /** * The identifier for this object. This identifier should be unique across * all objects of the same type and should never change. This value will * never be null. */ const QString id; /** * The string representation of this object. This string is for debugging * purposes only, and is not meant to be displayed to the user. This value * is computed lazily, and is cleared if one of its dependent values * changes. */ mutable QString str; /** * Constructs a new instance of HandleObject. * * @param id * The id of this handle; must not be null. */ HandleObject(const QString& id); public: /** * Tests whether this object is equal to another object. A handle object is * only equal to another handle object with the same id and the same class. * * @param object * The object with which to compare; may be null. * @return true if the objects are equal; false * otherwise. */ bool operator==(const Object* object) const; - virtual QString GetId() const; + QString GetId() const; /** * Computes the hash code for this object based on the id. * * @return The hash code for this object. */ virtual uint HashCode() const { if (hashCode == HASH_CODE_NOT_COMPUTED) { hashCode = HASH_INITIAL * HASH_FACTOR + qHash(id); if (hashCode == HASH_CODE_NOT_COMPUTED) { hashCode++; } } return hashCode; } /** * Whether this instance is defined. A defined instance is one that has been * fully initialized. This allows objects to effectively disappear even * though other objects may still have references to them. * * @return true if this object is defined; false * otherwise. */ - virtual bool IsDefined() const; + bool IsDefined() const; /** * Makes this object becomes undefined. This method should make any defined * properties null. It should also send notification to any * listeners that these properties have changed. */ virtual void Undefine() = 0; }; } #endif /*BERRYHANDLEOBJECT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/internal/berryCommandUtils.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/internal/berryCommandUtils.h index e45659096a..2063a44b80 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/internal/berryCommandUtils.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/internal/berryCommandUtils.h @@ -1,148 +1,148 @@ /*=================================================================== 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 __BERRY_COMMAND_UTILS_H__ #define __BERRY_COMMAND_UTILS_H__ #include #include #include namespace berry { /** * A class providing utility functions for the commands plug-in. */ class CommandUtils { public: /** * Compares two boolean values. false is considered to be * less than true. * * @param left * The left value to compare. * @param right * The right value to compare. * @return -1 if left is false * and right is true;0 * if they are equal; 1 if left is * true and right is * false */ static int Compare(const bool left, const bool right); static int Compare(const QString& left, const QString& right); /** * Compares two objects that are not otherwise comparable. If neither object * is null, then the string representation of each object is * used. * * @param left * The left value to compare. The string representation of this * value must not be null. * @param right * The right value to compare. The string representation of this * value must not be null. * @return -1 if left is null * and right is not null; * 0 if they are both null; * 1 if left is not null * and right is null. Otherwise, the * result of * left.toString().compareTo(right.toString()). */ static int CompareObj(const Object::ConstPointer left, const Object::ConstPointer right); /** * Tests whether two arrays of objects are equal to each other. The arrays * must not be null, but their elements may be * null. * * @param leftArray * The left array to compare; may be null, and * may be empty and may contain null elements. * @param rightArray * The right array to compare; may be null, and * may be empty and may contain null elements. * @return true if the arrays are equal length and the * elements at the same position are equal; false * otherwise. */ template static int Compare(const QList& leftArray, const QList& rightArray) { int result = (int) (leftArray.size() - rightArray.size()); if (result == 0) { - for (unsigned int i = 0; i < leftArray.size(); ++i) + for (int i = 0; i < leftArray.size(); ++i) { if (!(leftArray[i] == rightArray[i])) { return leftArray[i]->ToString().compare(rightArray[i]->ToString()); } } } return result < 0 ? -1 : (result > 0 ? 1 : 0); } /** * Tests whether two arrays of objects are equal to each other. The arrays * must not be null, but their elements may be * null. * * @param leftArray * The left array to compare; may be null, and * may be empty and may contain null elements. * @param rightArray * The right array to compare; may be null, and * may be empty and may contain null elements. * @return true if the arrays are equal length and the * elements at the same position are equal; false * otherwise. */ template static bool Equals(const QList& leftArray, const QList& rightArray) { return leftArray == rightArray; } template static QString ToString(const QList& vec) { QString str; QTextStream ss(&str); ss << "["; - for (unsigned int i = 0; i < vec.size(); ++i) + for (int i = 0; i < vec.size(); ++i) { if (i > 0) ss << ","; ss << vec[i]; } return str; } }; } #endif // __BERRY_COMMAND_UTILS_H__ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/util/berryCommandTracing.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/util/berryCommandTracing.h index a7dd0b4864..0e4cb7827f 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/util/berryCommandTracing.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/util/berryCommandTracing.h @@ -1,73 +1,74 @@ /*=================================================================== 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 BERRYCOMMANDTRACING_H_ #define BERRYCOMMANDTRACING_H_ #include +#include + namespace berry { /** *

* A utility class for printing tracing output to the console. *

*

* Clients must not extend or instantiate this class. *

- * - * @since 3.2 */ -class CommandTracing { +class BERRY_COMMANDS CommandTracing +{ public: /** * The separator to place between the component and the message. */ static const QString SEPARATOR; // = " >>> "; /** *

* Prints a tracing message to standard out. The message is prefixed by a * component identifier and some separator. See the example below. *

* *
    *        BINDINGS >> There are 4 deletion markers
    * 
* * @param component * The component for which this tracing applies; may be * empty * @param message * The message to print to standard out; may be empty */ static void PrintTrace(const QString& component, const QString& message); private: /** * This class is not intended to be instantiated. */ CommandTracing(); }; } #endif /* BERRYCOMMANDTRACING_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/files.cmake b/BlueBerry/Bundles/org.blueberry.core.expressions/files.cmake index 9967694ac9..dc7bc9f4da 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/files.cmake +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/files.cmake @@ -1,57 +1,58 @@ set(MOC_H_FILES ) set(CACHED_RESOURCE_FILES plugin.xml ) set(SRC_CPP_FILES berryElementHandler.cpp berryEvaluationContext.cpp berryEvaluationResult.cpp berryExpression.cpp berryExpressionConverter.cpp berryExpressionInfo.cpp berryExpressionTagNames.cpp + berryICountable.h berryIEvaluationContext.cpp berryIIterable.cpp berryIPropertyTester.cpp berryIVariableResolver.cpp berryPropertyTester.cpp ) set(INTERNAL_CPP_FILES berryAdaptExpression.cpp berryAndExpression.cpp berryCompositeExpression.cpp berryCountExpression.cpp berryDefaultVariable.cpp berryDefinitionRegistry.cpp berryEnablementExpression.cpp berryEqualsExpression.cpp berryExpressionPlugin.cpp berryExpressions.cpp berryExpressionStatus.cpp berryInstanceofExpression.cpp berryIterateExpression.cpp berryNotExpression.cpp berryOrExpression.cpp berryProperty.cpp berryPropertyTesterDescriptor.cpp berryReferenceExpression.cpp berryResolveExpression.cpp berryStandardElementHandler.cpp berrySystemTestExpression.cpp berryTestExpression.cpp berryTypeExtension.cpp berryTypeExtensionManager.cpp berryWithExpression.cpp ) foreach(file ${SRC_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/${file}) endforeach(file ${SRC_CPP_FILES}) foreach(file ${INTERNAL_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/internal/${file}) endforeach(file ${INTERNAL_CPP_FILES}) diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryEvaluationContext.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryEvaluationContext.cpp index 10daf39653..d5639fb95e 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryEvaluationContext.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryEvaluationContext.cpp @@ -1,137 +1,132 @@ /*=================================================================== 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 "berryEvaluationContext.h" namespace berry { EvaluationContext::EvaluationContext(IEvaluationContext* parent, - const Object::Pointer& defaultVariable) + const Object::ConstPointer& defaultVariable) : fParent(parent), fDefaultVariable(defaultVariable), fAllowPluginActivation(-1) { poco_assert(defaultVariable != 0); } EvaluationContext::EvaluationContext(IEvaluationContext* parent, - const Object::Pointer& defaultVariable, + const Object::ConstPointer& defaultVariable, const std::vector& resolvers) : fParent(parent), fDefaultVariable(defaultVariable), fVariableResolvers(resolvers), fAllowPluginActivation(-1) { poco_assert(defaultVariable != 0); poco_assert(resolvers.size() != 0); } -IEvaluationContext* -EvaluationContext::GetParent() const +IEvaluationContext* EvaluationContext::GetParent() const { return fParent; } -IEvaluationContext* -EvaluationContext::GetRoot() +IEvaluationContext* EvaluationContext::GetRoot() const { if (fParent == 0) - return this; + return const_cast(this); return fParent->GetRoot(); } -Object::Pointer -EvaluationContext::GetDefaultVariable() const +Object::ConstPointer EvaluationContext::GetDefaultVariable() const { return fDefaultVariable; } -void -EvaluationContext::SetAllowPluginActivation(bool value) +void EvaluationContext::SetAllowPluginActivation(bool value) { fAllowPluginActivation= value ? 1 : 0; } -bool -EvaluationContext::GetAllowPluginActivation() const +bool EvaluationContext::GetAllowPluginActivation() const { if (fAllowPluginActivation < 0) { if (fParent) { return fParent->GetAllowPluginActivation(); } return false; } return fAllowPluginActivation; } void -EvaluationContext::AddVariable(const QString &name, const Object::Pointer& value) +EvaluationContext::AddVariable(const QString &name, const Object::ConstPointer& value) { poco_assert(name.size() != 0); poco_assert(value.IsNotNull()); fVariables[name] = value; } -Object::Pointer +Object::ConstPointer EvaluationContext::RemoveVariable(const QString &name) { poco_assert(name.size() != 0); - Object::Pointer elem(fVariables[name]); + Object::ConstPointer elem(fVariables[name]); fVariables.remove(name); return elem; } -Object::Pointer +Object::ConstPointer EvaluationContext::GetVariable(const QString& name) const { poco_assert(name.size() != 0); - Object::Pointer result; + Object::ConstPointer result; - QHash::const_iterator iter(fVariables.find(name)); + QHash::const_iterator iter(fVariables.find(name)); if (iter != fVariables.end()) { result = iter.value(); } if (!result.IsNull()) return result; if (fParent != 0) return fParent->GetVariable(name); return result; } -Object::Pointer -EvaluationContext::ResolveVariable(const QString &name, const QList& args) +Object::ConstPointer +EvaluationContext::ResolveVariable(const QString &name, const QList& args) const { if (fVariableResolvers.size() > 0) { for (unsigned int i= 0; i < fVariableResolvers.size(); ++i) { IVariableResolver* resolver = fVariableResolvers[i]; Object::Pointer variable(resolver->Resolve(name, args)); if (!variable.IsNull()) return variable; } } if (fParent != 0) return fParent->ResolveVariable(name, args); return Object::Pointer(); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryEvaluationContext.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryEvaluationContext.h index b5b12a303e..39a8da7094 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryEvaluationContext.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryEvaluationContext.h @@ -1,125 +1,125 @@ /*=================================================================== 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 BERRYEVALUATIONCONTEXT_H_ #define BERRYEVALUATIONCONTEXT_H_ #include "berryIEvaluationContext.h" #include "berryIVariableResolver.h" #include #include "Poco/Any.h" #include #include namespace berry { /** * A default implementation of an evaluation context. *

* Clients may instantiate this default context. The class is * not intended to be subclassed by clients. *

* * @since 3.0 */ class BERRY_EXPRESSIONS EvaluationContext : public IEvaluationContext { private: - IEvaluationContext* fParent; - Object::Pointer fDefaultVariable; - QHash fVariables; + IEvaluationContext* const fParent; + Object::ConstPointer fDefaultVariable; + QHash fVariables; std::vector fVariableResolvers; int fAllowPluginActivation; public: /** * Create a new evaluation context with the given parent and default * variable. * * @param parent the parent context. Can be null. * @param defaultVariable the default variable */ - EvaluationContext(IEvaluationContext* parent, const Object::Pointer& defaultVariable); + EvaluationContext(IEvaluationContext* parent, const Object::ConstPointer& defaultVariable); /** * Create a new evaluation context with the given parent and default * variable. * * @param parent the parent context. Can be null. * @param defaultVariable the default variable * @param resolvers an array of IVariableResolvers to * resolve additional variables. * * @see #resolveVariable(String, Object[]) */ - EvaluationContext(IEvaluationContext* parent, const Object::Pointer& defaultVariable, + EvaluationContext(IEvaluationContext* parent, const Object::ConstPointer& defaultVariable, const std::vector& resolvers); /** * {@inheritDoc} */ IEvaluationContext* GetParent() const; /** * {@inheritDoc} */ - IEvaluationContext* GetRoot(); + IEvaluationContext* GetRoot() const; /** * {@inheritDoc} */ - Object::Pointer GetDefaultVariable() const; + Object::ConstPointer GetDefaultVariable() const; /** * {@inheritDoc} */ void SetAllowPluginActivation(bool value); /** * {@inheritDoc} */ bool GetAllowPluginActivation() const; /** * {@inheritDoc} */ - void AddVariable(const QString& name, const Object::Pointer& value); + void AddVariable(const QString& name, const Object::ConstPointer& value); /** * {@inheritDoc} */ - Object::Pointer RemoveVariable(const QString& name); + Object::ConstPointer RemoveVariable(const QString& name); /** * {@inheritDoc} */ - Object::Pointer GetVariable(const QString &name) const; + Object::ConstPointer GetVariable(const QString &name) const; /** * {@inheritDoc} */ - Object::Pointer ResolveVariable(const QString& name, const QList& args); + Object::ConstPointer ResolveVariable(const QString& name, const QList& args) const; }; } // namespace berry #endif /*BERRYEVALUATIONCONTEXT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryEvaluationResult.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryEvaluationResult.cpp index 8b9a6db801..42d70c214b 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryEvaluationResult.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryEvaluationResult.cpp @@ -1,114 +1,115 @@ /*=================================================================== 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 "berryEvaluationResult.h" namespace berry { const int EvaluationResult::FALSE_VALUE = 0; const int EvaluationResult::TRUE_VALUE = 1; const int EvaluationResult::NOT_LOADED_VALUE = 2; const SmartPointer EvaluationResult::FALSE_EVAL(new EvaluationResult(EvaluationResult::FALSE_VALUE)); const SmartPointer EvaluationResult::TRUE_EVAL(new EvaluationResult(EvaluationResult::TRUE_VALUE)); const SmartPointer EvaluationResult::NOT_LOADED(new EvaluationResult(NOT_LOADED_VALUE)); bool EvaluationResult::operator==(const Object* result) const { if(const EvaluationResult* o = dynamic_cast(result)) { return this->fValue == o->fValue; } return false; } bool EvaluationResult::operator!=(const Object* result) const { return !(this == result); } const SmartPointer EvaluationResult::AND[3][3] = { // FALSE TRUE NOT_LOADED /* FALSE */ { EvaluationResult::FALSE_EVAL, EvaluationResult::FALSE_EVAL, EvaluationResult::FALSE_EVAL }, /* TRUE */ { EvaluationResult::FALSE_EVAL, EvaluationResult::TRUE_EVAL, EvaluationResult::NOT_LOADED }, /* PNL */ { EvaluationResult::FALSE_EVAL, EvaluationResult::NOT_LOADED, EvaluationResult::NOT_LOADED } }; const SmartPointer EvaluationResult::OR[3][3] = { // FALSE TRUE NOT_LOADED /* FALSE */ { EvaluationResult::FALSE_EVAL, EvaluationResult::TRUE_EVAL, EvaluationResult::NOT_LOADED }, /* TRUE */ { EvaluationResult::TRUE_EVAL, EvaluationResult::TRUE_EVAL, EvaluationResult::TRUE_EVAL }, /* PNL */ { EvaluationResult::NOT_LOADED, EvaluationResult::TRUE_EVAL, EvaluationResult::NOT_LOADED } }; const SmartPointer EvaluationResult::NOT[3] = { // FALSE TRUE NOT_LOADED EvaluationResult::TRUE_EVAL, EvaluationResult::FALSE_EVAL, EvaluationResult::NOT_LOADED }; EvaluationResult::EvaluationResult(int value) { fValue= value; } EvaluationResult::EvaluationResult(const EvaluationResult &o) - : fValue(o.fValue) + : Object() + , fValue(o.fValue) { } EvaluationResult::ConstPointer EvaluationResult::And(const EvaluationResult::ConstPointer& other) const { return AND[fValue][other->fValue]; } EvaluationResult::ConstPointer EvaluationResult::Or(const EvaluationResult::ConstPointer& other) const { return OR[fValue][other->fValue]; } EvaluationResult::ConstPointer EvaluationResult::Not() const { return NOT[fValue]; } EvaluationResult::ConstPointer EvaluationResult::ValueOf(bool b) { return (b ? TRUE_EVAL : FALSE_EVAL); } QString EvaluationResult::ToString() const { switch (fValue) { case 0: return "false"; case 1: return "true"; case 2: return "not_loaded"; default: Q_ASSERT(false); return ""; } } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpression.cpp index 30046c2f0a..c32c30dd1e 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpression.cpp @@ -1,132 +1,132 @@ /*=================================================================== 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 "berryExpression.h" #include namespace berry { const uint Expression::HASH_CODE_NOT_COMPUTED = 0; const uint Expression::HASH_FACTOR = 89; const QString Expression::ATT_VALUE= "value"; const Expression::Pointer Expression::TRUE_EVAL(new TRUE_EVALExpression()); const Expression::Pointer Expression::FALSE_EVAL(new FALSE_EVALExpression()); Expression::Expression() { fHashCode = HASH_CODE_NOT_COMPUTED; } Expression::~Expression() { } bool Expression::Equals(const QList& leftArray, const QList& rightArray) { return (leftArray == rightArray); } bool Expression::Equals(const QList& leftArray, const QList& rightArray) { return (leftArray == rightArray); } uint Expression::HashCode(Expression::Pointer object) { return object != 0 ? object->HashCode() : 0; } uint Expression::HashCode(const QList& array) { if (array.size() == 0) { return 0; } uint hashCode = qHash("QList"); - for (unsigned int i= 0; i < array.size(); i++) + for (int i= 0; i < array.size(); i++) { hashCode = hashCode * HASH_FACTOR + HashCode(array[i]); } return hashCode; } uint Expression::HashCode(const QList& array) { if (array.isEmpty()) { return 0; } int hashCode = (int) Poco::hash("std::vector"); - for (unsigned int i= 0; i < array.size(); i++) + for (int i= 0; i < array.size(); i++) { hashCode = hashCode + (int) array[i]->HashCode(); } return hashCode; } const ExpressionInfo* Expression::ComputeExpressionInfo() const { ExpressionInfo* result= new ExpressionInfo(); this->CollectExpressionInfo(result); return result; } void Expression::CollectExpressionInfo(ExpressionInfo* info) const { info->AddMisBehavingExpressionType(typeid(this)); } uint Expression::ComputeHashCode() const { return qHash(this); } uint Expression::HashCode() const { if (fHashCode != HASH_CODE_NOT_COMPUTED) return fHashCode; fHashCode= this->ComputeHashCode(); if (fHashCode == HASH_CODE_NOT_COMPUTED) fHashCode++; return fHashCode; } bool Expression::operator==(const Object* object) const { if (const Expression* other = dynamic_cast(object)) return this->HashCode() == other->HashCode(); return false; } QString Expression::ToString() const { return typeid(this).name(); } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpression.h index 516fd12190..b0c351fc43 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpression.h @@ -1,224 +1,224 @@ /*=================================================================== 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 BERRYEXPRESSION_H_ #define BERRYEXPRESSION_H_ #include "berryExpressionInfo.h" #include "berryIEvaluationContext.h" #include "berryEvaluationResult.h" #include #include #include namespace berry { /** * Abstract base class for all expressions provided by the common * expression language. *

* An expression is evaluated by calling {@link #evaluate(IEvaluationContext)}. *

*

* This class may be subclassed to provide specific expressions. *

*/ class BERRY_EXPRESSIONS Expression : public Object { public: berryObjectMacro(Expression); /** * The constant integer hash code value meaning the hash code has not yet * been computed. */ static const uint HASH_CODE_NOT_COMPUTED; /** * A factor for computing the hash code for all expressions. */ static const uint HASH_FACTOR; /** * Name of the value attribute of an expression (value is value). */ static const QString ATT_VALUE; private: /** * The hash code for this object. This value is computed lazily. If it is * not yet computed, it is equal to {@link #HASH_CODE_NOT_COMPUTED}. */ mutable uint fHashCode; protected: /** * Checks whether two objects are equal using the * equals(Object) method of the left object. * This method handles null for either the left * or right object. * * @param left the first object to compare; may be null. * @param right the second object to compare; may be null. * @return TRUE_EVAL if the two objects are equivalent; * FALSE_EVAL otherwise. */ // static bool Equals(final Object left, final Object right); /** * Tests whether two arrays of objects are equal to each other. The arrays * must not be null, but their elements may be * null. * * @param leftArray the left array to compare; may be null, and * may be empty and may contain null elements. * @param rightArray the right array to compare; may be null, * and may be empty and may contain null elements. * * @return TRUE_EVAL if the arrays are equal length and the elements * at the same position are equal; FALSE_EVAL otherwise. */ static bool Equals(const QList& leftArray, const QList& rightArray); static bool Equals(const QList& leftArray, const QList& rightArray); /** * Returns the hash code for the given object. This method * handles null. * * @param object the object for which the hash code is desired; may be * null. * * @return The hash code of the object; zero if the object is * null. */ static uint HashCode(Expression::Pointer object); /** * Returns the hash code for the given array. This method handles * null. * * @param array the array for which the hash code is desired; may be * null. * @return the hash code of the array; zero if the object is * null. */ static uint HashCode(const QList& array); static uint HashCode(const QList& array); /** * Method to compute the hash code for this object. The result * returned from this method is cached in the fHashCode * field. If the value returned from the method equals {@link #HASH_CODE_NOT_COMPUTED} * (e.g. -1) then the value is incremented by one. *

* This default implementation calls super.hashCode() *

* @return a hash code for this object. */ virtual uint ComputeHashCode() const; public: /** * The expression corresponding to {@link EvaluationResult#TRUE_EVAL}. */ static const Expression::Pointer TRUE_EVAL; /** * The expression corresponding to {@link EvaluationResult#FALSE_EVAL}. */ static const Expression::Pointer FALSE_EVAL; Expression(); virtual ~Expression(); virtual uint HashCode() const; /** * Evaluates this expression. * * @param context an evaluation context providing information like variable, * name spaces, etc. necessary to evaluate this expression * * @return the result of the expression evaluation * * @throws CoreException if the evaluation failed. The concrete reason is * defined by the subclass implementing this method */ virtual SmartPointer Evaluate(IEvaluationContext* context) const = 0; /** * Computes the expression information for the given expression tree. *

* This is a convenience method for collecting the expression information * using {@link Expression#collectExpressionInfo(ExpressionInfo)}. *

* * @return the expression information */ virtual const ExpressionInfo* ComputeExpressionInfo() const; /** * Collects information about this expression tree. This default * implementation add the expression's type to the set of misbehaving * expression types. * * @param info the expression information object used * to collect the information */ virtual void CollectExpressionInfo(ExpressionInfo* info) const; virtual QString ToString() const; virtual bool operator==(const Object* object) const; }; class TRUE_EVALExpression : public Expression { public: SmartPointer Evaluate(IEvaluationContext* /*context*/) const { return EvaluationResult::TRUE_EVAL; } - void CollectExpressionInfo(ExpressionInfo* /*info*/) {} + void CollectExpressionInfo(ExpressionInfo* /*info*/) const {} }; class FALSE_EVALExpression : public Expression { public: SmartPointer Evaluate(IEvaluationContext* /*context*/) const { return EvaluationResult::FALSE_EVAL; } - void CollectExpressionInfo(ExpressionInfo* /*info*/) {} + void CollectExpressionInfo(ExpressionInfo* /*info*/) const {} }; } // namespace berry #endif /*BERRYEXPRESSION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionConverter.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionConverter.cpp index e430f7cbb7..198b395c6a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionConverter.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionConverter.cpp @@ -1,161 +1,161 @@ /*=================================================================== 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 "berryExpressionConverter.h" #include "berryPlatformException.h" #include "berryIConfigurationElement.h" #include "berryIExtension.h" #include "berryIContributor.h" #include "berryCoreException.h" #include "berryElementHandler.h" #include "berryExpression.h" #include "berryStatus.h" #include "internal/berryExpressionPlugin.h" #include "internal/berryCompositeExpression.h" #include "Poco/DOM/Node.h" #include "Poco/DOM/Element.h" namespace berry { ExpressionConverter* ExpressionConverter::INSTANCE = 0; ExpressionConverter* ExpressionConverter::GetDefault() { if (INSTANCE) return INSTANCE; QList handlers; handlers.push_back(ElementHandler::GetDefault()); INSTANCE = new ExpressionConverter(handlers); return INSTANCE; } ExpressionConverter::ExpressionConverter(const QList& handlers) { fHandlers = handlers; } Expression::Pointer ExpressionConverter::Perform(const IConfigurationElement::Pointer& root) { - for (unsigned int i = 0; i < fHandlers.size(); i++) { + for (int i = 0; i < fHandlers.size(); i++) { ElementHandler::Pointer handler = fHandlers[i]; Expression::Pointer result = handler->Create(this, root); if (!result.IsNull()) return result; } return Expression::Pointer(); } Expression::Pointer ExpressionConverter::Perform(Poco::XML::Element* root) { - for (unsigned int i = 0; i < fHandlers.size(); i++) { + for (int i = 0; i < fHandlers.size(); i++) { ElementHandler::Pointer handler = fHandlers[i]; Expression::Pointer result = handler->Create(this, root); if (!result.IsNull()) return result; } return Expression::Pointer(); } void ExpressionConverter::ProcessChildren(const IConfigurationElement::Pointer& element, const CompositeExpression::Pointer& result) { QList children(element->GetChildren()); QList::iterator iter; for (iter = children.begin(); iter != children.end(); ++iter) { Expression::Pointer child = this->Perform(*iter); if (child.IsNull()) { IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, ExpressionPlugin::GetPluginId(), IStatus::ERROR_TYPE, QString("Unknown expression element ") + GetDebugPath(*iter), BERRY_STATUS_LOC)); throw CoreException(status); } result->Add(child); } } QString ExpressionConverter::GetDebugPath(const IConfigurationElement::Pointer& configurationElement) { QString buf; buf.append(configurationElement->GetName()); Object::Pointer parent= configurationElement->GetParent(); while (parent) { if (IConfigurationElement::Pointer parent2 = parent.Cast()) { buf.append(" > "); buf.append(parent2->GetName()); QString id= parent2->GetAttribute("id"); if (!id.isEmpty()) { buf.append(" (id=").append(id).append(')'); } parent= parent2->GetParent(); } else if (IExtension::Pointer parent2 = parent.Cast()) { buf.append(" : "); buf.append(parent2->GetExtensionPointUniqueIdentifier()); buf.append(" @ "); buf.append(parent2->GetContributor()->GetName()); parent = 0; } else { parent = 0; } } return buf; } void ExpressionConverter::ProcessChildren(Poco::XML::Element* element, const CompositeExpression::Pointer& result) { Poco::XML::Node* child = element->firstChild(); while (child != 0) { if (child->nodeType() == Poco::XML::Node::ELEMENT_NODE) { Poco::XML::Element* elem = static_cast(child); Expression::Pointer exp = this->Perform(elem); if (exp.IsNull()) { IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, ExpressionPlugin::GetPluginId(), IStatus::ERROR_TYPE, QString("Unknown expression element ") + QString::fromStdString(elem->nodeName()), BERRY_STATUS_LOC)); throw CoreException(status); } result->Add(exp); } child = child->nextSibling(); } } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryICountable.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryICountable.h index 141216be22..79fbd0b5b9 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryICountable.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryICountable.h @@ -1,53 +1,52 @@ /*=================================================================== 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 BERRYICOUNTABLE_H_ #define BERRYICOUNTABLE_H_ #include #include #include namespace berry { /** * Objects that are adaptable to ICountable can be used * as the default variable in a count expression. * * @see IAdaptable * @see IAdapterManager - * - * @since 3.3 */ -struct BERRY_EXPRESSIONS ICountable : public Object { +struct BERRY_EXPRESSIONS ICountable : public Object +{ berryObjectMacro(ICountable); /** * Returns the number of elements. * * @return the number of elements */ - virtual int Count() = 0; - - virtual ~ICountable() {} + virtual int Count() const = 0; }; } +Q_DECLARE_INTERFACE(berry::ICountable, "org.blueberry.core.ICountable") + #endif /*BERRYICOUNTABLE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIEvaluationContext.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIEvaluationContext.cpp index 7ef6ad5d51..80ad062c8a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIEvaluationContext.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIEvaluationContext.cpp @@ -1,30 +1,30 @@ /*=================================================================== 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 "berryIEvaluationContext.h" namespace berry { struct UndefinedVariable : public Object { }; -Object::Pointer IEvaluationContext::UNDEFINED_VARIABLE(new UndefinedVariable()); +Object::ConstPointer IEvaluationContext::UNDEFINED_VARIABLE(new UndefinedVariable()); IEvaluationContext::~IEvaluationContext() {} } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIEvaluationContext.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIEvaluationContext.h index 30cf414033..8267078b1a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIEvaluationContext.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIEvaluationContext.h @@ -1,149 +1,149 @@ /*=================================================================== 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 BERRYIEVALUATIONCONTEXT_H_ #define BERRYIEVALUATIONCONTEXT_H_ #include #include #include namespace berry { /** * An evaluation context is used to manage a set of objects needed during * XML expression evaluation. A context has a parent context, can manage * a set of named variables and has a default variable. The default variable * is used during XML expression evaluation if no explicit variable is * referenced. *

* This interface is not intended to be implemented by clients. Clients * are allowed to instantiate EvaluationContext. *

* * @since 3.0 */ struct BERRY_EXPRESSIONS IEvaluationContext : public Object { - berryInterfaceMacro(IEvaluationContext, berry) + berryObjectMacro(berry::IEvaluationContext) /** * Represents the value used by variables that exist but are not defined * in a evaluation context. When tested by the 'with' expression, false * will be returned. */ - static Object::Pointer UNDEFINED_VARIABLE; + static Object::ConstPointer UNDEFINED_VARIABLE; virtual ~IEvaluationContext(); /** * Returns the parent context or null if * this is the root of the evaluation context hierarchy. * * @return the parent evaluation context or null */ virtual IEvaluationContext* GetParent() const = 0; /** * Returns the root evaluation context. * * @return the root evaluation context */ - virtual IEvaluationContext* GetRoot() = 0; + virtual IEvaluationContext* GetRoot() const = 0; /** * Specifies whether this evaluation context allows activation * of plug-ins for testers used in the expression tree. To actual * trigger the plug-in loading this flag has to be set to * true and the actual test expression must have the * attribute forcePluginActivation set to * true as well. * * @param value whether this evaluation context allows plug-in activation * @since 3.2 */ virtual void SetAllowPluginActivation(bool value) = 0; /** * Returns whether this evaluation context supports plug-in * activation. If not set via {@link #setAllowPluginActivation(boolean)} * the parent value is returned. If no parent is set false * is returned. * * @return whether plug-in activation is supported or not * @since 3.2 */ virtual bool GetAllowPluginActivation() const = 0; /** * Returns the default variable. * * @return the default variable or null if * no default variable is managed. */ - virtual Object::Pointer GetDefaultVariable() const = 0; + virtual Object::ConstPointer GetDefaultVariable() const = 0; /** * Adds a new named variable to this context. If a variable * with the name already exists the new one overrides the * existing one. * * @param name the variable's name * @param value the variable's value */ - virtual void AddVariable(const QString& name, const Object::Pointer& value) = 0; + virtual void AddVariable(const QString& name, const Object::ConstPointer& value) = 0; /** * Removes the variable managed under the given name * from this evaluation context. * * @param name the variable's name * @return the currently stored value or null if * the variable doesn't exist */ - virtual Object::Pointer RemoveVariable(const QString& name) = 0; + virtual Object::ConstPointer RemoveVariable(const QString& name) = 0; /** * Returns the variable managed under the given name. * * @param name the variable's name * @return the variable's value or null if the content * doesn't manage a variable with the given name */ - virtual Object::Pointer GetVariable(const QString& name) const = 0; + virtual Object::ConstPointer GetVariable(const QString& name) const = 0; /** * Resolves a variable for the given name and arguments. This * method can be used to dynamically resolve variable such as * plug-in descriptors, resources, etc. The method is used * by the resolve expression. * * @param name the variable to resolve * @param args an object array of arguments used to resolve the * variable * @return the variable's value or null if no variable * can be resolved for the given name and arguments * @exception CoreException if an errors occurs while resolving * the variable */ - virtual Object::Pointer ResolveVariable(const QString& name, const QList& args) = 0; + virtual Object::ConstPointer ResolveVariable(const QString& name, const QList& args) const = 0; }; } // namespace berry #endif /*BERRYIEVALUATIONCONTEXT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIIterable.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIIterable.h index 485d1a640b..fc8cb4927b 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIIterable.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIIterable.h @@ -1,55 +1,61 @@ /*=================================================================== 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 BERRYIITERABLE_H_ #define BERRYIITERABLE_H_ #include #include #include namespace berry { /** * Objects that are adaptable to IIterable can be used * as the default variable in an iterate expression. * * @see IAdaptable * @see IAdapterManager */ struct BERRY_EXPRESSIONS IIterable : public Object { - berryInterfaceMacro(IIterable, berry) + berryObjectMacro(berry::IIterable) typedef QList::iterator iterator; + typedef QList::const_iterator const_iterator; virtual ~IIterable(); /** * Returns an iterator to iterate over the elements. * * @return an iterator */ virtual iterator begin() = 0; virtual iterator end() = 0; + virtual const_iterator begin() const = 0; + virtual const_iterator end() const = 0; + }; } // namespace berry +Q_DECLARE_INTERFACE(berry::IIterable, "org.blueberry.core.IIterable") + #endif /*BERRYIITERABLE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIPropertyTester.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIPropertyTester.h index 3efa96ed46..2ecdc2f2ec 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIPropertyTester.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryIPropertyTester.h @@ -1,113 +1,112 @@ /*=================================================================== 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 BERRYIPROPERTYTESTER_H_ #define BERRYIPROPERTYTESTER_H_ #include #include #include #include #include #include #include namespace berry { /** * A property tester can be used to add additional properties to test to an * existing type. *

* This interface is not intended to be implemented by clients. Clients * should subclass type PropertyTester. *

- * - * @since 3.0 */ -struct BERRY_EXPRESSIONS IPropertyTester : public Object { +struct BERRY_EXPRESSIONS IPropertyTester : public Object +{ - berryInterfaceMacro(IPropertyTester, berry); + berryObjectMacro(berry::IPropertyTester) virtual ~IPropertyTester(); /** * Returns whether the property tester can handle the given * property or not. * * @param namespace the name space to be considered * @param property the property to test * @return true if the tester provides an implementation * for the given property; otherwise false is returned */ virtual bool Handles(const QString& namespaze, const QString& property) = 0; /** * Returns whether the implementation class for this property tester is * loaded or not. * * @return trueif the implementation class is loaded; * false otherwise */ virtual bool IsInstantiated() = 0; /** * Returns true if the implementation class of this property * tester can be loaded. This is the case if the plug-in providing * the implementation class is active. Returns false otherwise. * * @return whether the implementation class can be loaded or not */ virtual bool IsDeclaringPluginActive() = 0; /** * Loads the implementation class for this property tester and returns an * instance of this class. * * @return an instance of the implementation class for this property tester * * @throws CoreException if the implementation class cannot be loaded */ virtual IPropertyTester* Instantiate() = 0; /** * Executes the property test determined by the parameter property. * * @param receiver the receiver of the property test * @param property the property to test * @param args additional arguments to evaluate the property. If no arguments * are specified in the test expression an array of length 0 * is passed * @param expectedValue the expected value of the property. The value is either * of type java.lang.String or a boxed base type. If no value was * specified in the test expressions then null is passed * * @return returns true if the property is equal to the expected value; * otherwise false is returned */ - virtual bool Test(Object::Pointer receiver, const QString& property, + virtual bool Test(Object::ConstPointer receiver, const QString& property, const QList& args, Object::Pointer expectedValue) = 0; }; } // namespace berry Q_DECLARE_INTERFACE(berry::IPropertyTester, "org.blueberry.IPropertyTester") #endif /*BERRYIPROPERTYTESTER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryPropertyTester.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryPropertyTester.cpp index 86b505952f..4814ca3fa2 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryPropertyTester.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryPropertyTester.cpp @@ -1,61 +1,63 @@ /*=================================================================== 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 "berryPropertyTester.h" #include "berryPlatform.h" #include "berryIContributor.h" +#include + namespace berry { void PropertyTester::InternalInitialize(PropertyTesterDescriptor::Pointer descriptor) { fProperties = descriptor->GetProperties(); fNamespace= descriptor->GetNamespace(); fConfigElement= descriptor->GetExtensionElement(); } PropertyTesterDescriptor::Pointer PropertyTester::InternalCreateDescriptor() { PropertyTesterDescriptor::Pointer tester(new PropertyTesterDescriptor(fConfigElement, fNamespace, fProperties)); return tester; } bool PropertyTester::Handles(const QString &namespaze, const QString &property) { return fNamespace == namespaze && fProperties.contains("," + property + ","); } bool PropertyTester::IsInstantiated() { return true; } bool PropertyTester::IsDeclaringPluginActive() { QSharedPointer plugin = Platform::GetCTKPlugin(fConfigElement->GetContributor()->GetName()); return plugin->getState() == ctkPlugin::ACTIVE; } IPropertyTester* PropertyTester::Instantiate() { return this; } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryAdaptExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryAdaptExpression.cpp index 0a76e1cac8..63d4646f24 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryAdaptExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryAdaptExpression.cpp @@ -1,129 +1,124 @@ /*=================================================================== 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 "berryAdaptExpression.h" #include -#include #include #include #include "berryExpressions.h" #include "berryDefaultVariable.h" #include namespace berry { const QString AdaptExpression::ATT_TYPE= "type"; /** * The seed for the hash code for all adapt expressions. */ const uint AdaptExpression::HASH_INITIAL = qHash("berry::AdaptExpression"); AdaptExpression::AdaptExpression(IConfigurationElement::Pointer configElement) { fTypeName = configElement->GetAttribute(ATT_TYPE); Expressions::CheckAttribute(ATT_TYPE, fTypeName); } AdaptExpression::AdaptExpression(Poco::XML::Node* /*element*/) { throw Poco::NotImplementedException(); //fTypeName = element->GetAttribute(ATT_TYPE); //Expressions::CheckAttribute(ATT_TYPE, fTypeName.length() > 0 ? fTypeName : null); } AdaptExpression::AdaptExpression(const QString& typeName) { poco_assert(typeName.size() != 0); fTypeName= typeName; } //bool //AdaptExpression::equals(final Object object) //{ // if (!(object instanceof AdaptExpression)) // return FALSE_EVAL; // // final AdaptExpression that= (AdaptExpression)object; // return this.fTypeName.equals(that.fTypeName) // && equals(this.fExpressions, that.fExpressions); //} uint -AdaptExpression::ComputeHashCode() +AdaptExpression::ComputeHashCode() const { throw Poco::NotImplementedException("ComputeHashCode not implemented"); //return HASH_INITIAL * HASH_FACTOR + HashCode(fExpressions) // * HASH_FACTOR + fTypeName.hashCode(); } /* (non-Javadoc) * @see Expression#evaluate(IVariablePool) */ EvaluationResult::ConstPointer AdaptExpression::Evaluate(IEvaluationContext* context) const { if (fTypeName.size() == 0) return EvaluationResult::FALSE_EVAL; - Object::Pointer var = context->GetDefaultVariable(); - Object::Pointer adapted; + Object::ConstPointer var = context->GetDefaultVariable(); + Object::ConstPointer adapted; IAdapterManager* manager = Platform::GetAdapterManager(); if (Expressions::IsInstanceOf(var.GetPointer(), fTypeName)) { adapted = var; } else { - if (!manager->HasAdapter(var->GetClassName(), fTypeName.toStdString())) + if (!manager->HasAdapter(var.GetPointer(), fTypeName)) return EvaluationResult::FALSE_EVAL; - Poco::Any anyAdapted(manager->GetAdapter(var.GetPointer(), fTypeName.toStdString())); - if (!anyAdapted.empty() && anyAdapted.type() == typeid(Object::Pointer)) - { - adapted = Poco::AnyCast(anyAdapted); - } + adapted = manager->GetAdapter(var.GetPointer(), fTypeName); } // the adapted result is null but hasAdapter returned TRUE_EVAL check // if the adapter is loaded. if (adapted.IsNull()) { - if (manager->QueryAdapter(var->GetClassName(), fTypeName.toStdString()) == IAdapterManager::NOT_LOADED) + if (manager->QueryAdapter(var.GetPointer(), fTypeName) == IAdapterManager::NOT_LOADED) { return EvaluationResult::NOT_LOADED; } else { return EvaluationResult::FALSE_EVAL; } } DefaultVariable scope(context, adapted); return this->EvaluateAnd(&scope); } void -AdaptExpression::CollectExpressionInfo(ExpressionInfo* info) +AdaptExpression::CollectExpressionInfo(ExpressionInfo* info) const { // Although the default variable is passed to the children of this // expression as an instance of the adapted type it is OK to only // mark a default variable access. info->MarkDefaultVariableAccessed(); CompositeExpression::CollectExpressionInfo(info); } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryAdaptExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryAdaptExpression.h index cf847a7166..c1011d4690 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryAdaptExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryAdaptExpression.h @@ -1,80 +1,80 @@ /*=================================================================== 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 BERRYADAPTEXPRESSION_H_ #define BERRYADAPTEXPRESSION_H_ #include "berryCompositeExpression.h" namespace Poco { namespace XML { class Node; } } namespace berry { struct IConfigurationElement; class AdaptExpression : public CompositeExpression { private: static const QString ATT_TYPE; /** * The seed for the hash code for all adapt expressions. */ static const uint HASH_INITIAL; QString fTypeName; public: AdaptExpression(SmartPointer configElement); AdaptExpression(Poco::XML::Node* element); AdaptExpression(const QString& typeName); // bool equals(final Object object) { // if (!(object instanceof AdaptExpression)) // return false; // // final AdaptExpression that= (AdaptExpression)object; // return this.fTypeName.equals(that.fTypeName) // && equals(this.fExpressions, that.fExpressions); // } /* (non-Javadoc) * @see Expression#evaluate(IVariablePool) */ EvaluationResult::ConstPointer Evaluate(IEvaluationContext* context) const; - void CollectExpressionInfo(ExpressionInfo* info); + void CollectExpressionInfo(ExpressionInfo* info) const; protected: - uint ComputeHashCode(); + uint ComputeHashCode() const; }; } // namespace berry #endif /*BERRYADAPTEXPRESSION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.cpp index 9f6e8f93b7..b8a0266b37 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.cpp @@ -1,82 +1,82 @@ /*=================================================================== 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 "berryCompositeExpression.h" #include "Poco/Hash.h" namespace berry { const uint CompositeExpression::HASH_INITIAL = Poco::Hash()("berry::CompositeExpression"); void CompositeExpression::Add(Expression::Pointer expression) { fExpressions.push_back(expression); } QList CompositeExpression::GetChildren() { return fExpressions; } EvaluationResult::ConstPointer CompositeExpression::EvaluateAnd(IEvaluationContext* scope) const { if (fExpressions.size() == 0) return EvaluationResult::TRUE_EVAL; EvaluationResult::ConstPointer result = EvaluationResult::TRUE_EVAL; foreach (Expression::Pointer iter, fExpressions) { result = result->And(iter->Evaluate(scope)); // keep iterating even if we have a not loaded found. It can be // that we find a FALSE_EVAL which will result in a better result. if (result == EvaluationResult::FALSE_EVAL) return result; } return result; } EvaluationResult::ConstPointer CompositeExpression::EvaluateOr(IEvaluationContext* scope) const { if (fExpressions.size() == 0) return EvaluationResult::TRUE_EVAL; EvaluationResult::ConstPointer result = EvaluationResult::FALSE_EVAL; foreach (Expression::Pointer iter, fExpressions) { result = result->Or(iter->Evaluate(scope)); if (result == EvaluationResult::TRUE_EVAL) return result; } return result; } -void CompositeExpression::CollectExpressionInfo(ExpressionInfo* info) +void CompositeExpression::CollectExpressionInfo(ExpressionInfo* info) const { if (fExpressions.size() == 0) return; foreach (Expression::Pointer iter, fExpressions) { iter->CollectExpressionInfo(info); } } -uint CompositeExpression::ComputeHashCode() +uint CompositeExpression::ComputeHashCode() const { return HASH_INITIAL * HASH_FACTOR + this->HashCode(fExpressions); } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.h index b1e89cdb2e..65a72b636c 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.h @@ -1,62 +1,62 @@ /*=================================================================== 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 BERRYCOMPOSITEEXPRESSION_H_ #define BERRYCOMPOSITEEXPRESSION_H_ #include "berryExpression.h" #include "berryExpressionInfo.h" #include "berryEvaluationResult.h" #include "berryIEvaluationContext.h" namespace berry { class CompositeExpression : public Expression { public: berryObjectMacro(CompositeExpression); private: /** * The seed for the hash code for all composite expressions. */ static const uint HASH_INITIAL; protected: QList fExpressions; virtual EvaluationResult::ConstPointer EvaluateAnd(IEvaluationContext* scope) const; virtual EvaluationResult::ConstPointer EvaluateOr(IEvaluationContext* scope) const; - virtual uint ComputeHashCode(); + virtual uint ComputeHashCode() const; public: virtual void Add(Expression::Pointer expression); virtual QList GetChildren(); - virtual void CollectExpressionInfo(ExpressionInfo* info); + virtual void CollectExpressionInfo(ExpressionInfo* info) const; }; } // namespace berry #endif /*BERRYCOMPOSITEEXPRESSION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCountExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCountExpression.cpp index 3b6c73cd31..98f824f39a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCountExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCountExpression.cpp @@ -1,139 +1,139 @@ /*=================================================================== 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 "berryCountExpression.h" #include "berryExpressions.h" #include #include namespace berry { const int CountExpression::ANY_NUMBER= 5; const int CountExpression::EXACT= 4; const int CountExpression::ONE_OR_MORE= 3; const int CountExpression::NONE_OR_ONE= 2; const int CountExpression::NONE= 1; const int CountExpression::UNKNOWN= 0; const uint CountExpression::HASH_INITIAL = qHash("berry::CountExpression"); void CountExpression::InitializeSize(QString size) { if (size.isNull()) size = "*"; if (size == "*") fMode = ANY_NUMBER; else if (size == "?") fMode = NONE_OR_ONE; else if (size == "!") fMode = NONE; else if (size == "+") fMode = ONE_OR_MORE; else { bool ok = false; fSize = size.toInt(&ok); if (ok) { fMode = EXACT; } else { fMode = UNKNOWN; } } } CountExpression::CountExpression(const IConfigurationElement::Pointer& configElement) { QString size = configElement->GetAttribute(ATT_VALUE); this->InitializeSize(size); } CountExpression::CountExpression(Poco::XML::Element* element) { std::string size = element->getAttribute(ATT_VALUE.toStdString()); this->InitializeSize(size.size() > 0 ? QString::fromStdString(size) : QString()); } CountExpression::CountExpression(const QString& size) { this->InitializeSize(size); } EvaluationResult::ConstPointer CountExpression::Evaluate(IEvaluationContext* context) const { - Object::Pointer var(context->GetDefaultVariable()); + Object::ConstPointer var(context->GetDefaultVariable()); ObjectList::size_type size; - if(ObjectList::Pointer coll = var.Cast >()) + if(ObjectList::ConstPointer coll = var.Cast >()) { size = coll->size(); } else { - ICountable::Pointer countable = Expressions::GetAsICountable(var, Expression::ConstPointer(this)); + ICountable::ConstPointer countable = Expressions::GetAsICountable(var, Expression::ConstPointer(this)); if (!countable) return EvaluationResult::NOT_LOADED; size = countable->Count(); } switch (fMode) { case UNKNOWN: return EvaluationResult::FALSE_EVAL; case NONE: return EvaluationResult::ValueOf(size == 0); case NONE_OR_ONE: return EvaluationResult::ValueOf(size == 0 || size == 1); case ONE_OR_MORE: return EvaluationResult::ValueOf(size >= 1); case EXACT: return EvaluationResult::ValueOf( (ObjectList::size_type) fSize == size); case ANY_NUMBER: return EvaluationResult::TRUE_EVAL; } return EvaluationResult::FALSE_EVAL; } void - CountExpression::CollectExpressionInfo(ExpressionInfo* info) + CountExpression::CollectExpressionInfo(ExpressionInfo* info) const { info->MarkDefaultVariableAccessed(); } bool CountExpression::operator==(const Object* object) const { if (const CountExpression* that = dynamic_cast(object)) { return (this->fMode == that->fMode) && (this->fSize == that->fSize); } return false; } uint - CountExpression::ComputeHashCode() + CountExpression::ComputeHashCode() const { return HASH_INITIAL * HASH_FACTOR + fMode * HASH_FACTOR + fSize; } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCountExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCountExpression.h index 3199c44301..56bd12494d 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCountExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCountExpression.h @@ -1,74 +1,74 @@ /*=================================================================== 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 __BERRY_COUNT_EXPRESSION_H__ #define __BERRY_COUNT_EXPRESSION_H__ #include "berryExpression.h" #include "berryIEvaluationContext.h" #include "berryExpressionInfo.h" #include "Poco/DOM/Element.h" #include namespace berry { struct IConfigurationElement; class CountExpression : public Expression { private: static const int ANY_NUMBER; static const int EXACT; static const int ONE_OR_MORE; static const int NONE_OR_ONE; static const int NONE; static const int UNKNOWN; /** * The seed for the hash code for all count expressions. */ static const uint HASH_INITIAL; int fMode; int fSize; void InitializeSize(QString size); public: CountExpression(const SmartPointer& configElement); CountExpression(Poco::XML::Element* element); CountExpression(const QString& size); EvaluationResult::ConstPointer Evaluate(IEvaluationContext* context) const; - void CollectExpressionInfo(ExpressionInfo* info); + void CollectExpressionInfo(ExpressionInfo* info) const; bool operator==(const Object* object) const; protected: - uint ComputeHashCode(); + uint ComputeHashCode() const; }; } // namespace berry #endif // __BERRY_COUNT_EXPRESSION_H__ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefaultVariable.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefaultVariable.cpp index 9d759c5023..1c7f8a62f4 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefaultVariable.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefaultVariable.cpp @@ -1,85 +1,85 @@ /*=================================================================== 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 "berryDefaultVariable.h" #include namespace berry { DefaultVariable::DefaultVariable(IEvaluationContext* parent, - const Object::Pointer& defaultVariable) + const Object::ConstPointer& defaultVariable) + : fDefaultVariable(defaultVariable) + , fParent(parent) { - poco_check_ptr(parent); + Q_ASSERT(parent); - fParent= parent; - - while (dynamic_cast(parent)) + while (dynamic_cast(parent)) { parent = parent->GetParent(); } - fManagedPool= parent; - fDefaultVariable= defaultVariable; + fManagedPool = parent; + fDefaultVariable = defaultVariable; } IEvaluationContext* DefaultVariable::GetParent() const { return fParent; } -IEvaluationContext* DefaultVariable::GetRoot() +IEvaluationContext* DefaultVariable::GetRoot() const { return fParent->GetRoot(); } -Object::Pointer DefaultVariable::GetDefaultVariable() const +Object::ConstPointer DefaultVariable::GetDefaultVariable() const { return fDefaultVariable; } void DefaultVariable::SetAllowPluginActivation(bool value) { fParent->SetAllowPluginActivation(value); } bool DefaultVariable::GetAllowPluginActivation() const { return fParent->GetAllowPluginActivation(); } -void DefaultVariable::AddVariable(const QString& name, const Object::Pointer& value) +void DefaultVariable::AddVariable(const QString& name, const Object::ConstPointer& value) { fManagedPool->AddVariable(name, value); } -Object::Pointer DefaultVariable::RemoveVariable(const QString &name) +Object::ConstPointer DefaultVariable::RemoveVariable(const QString &name) { return fManagedPool->RemoveVariable(name); } -Object::Pointer DefaultVariable::GetVariable(const QString &name) const +Object::ConstPointer DefaultVariable::GetVariable(const QString &name) const { return fManagedPool->GetVariable(name); } -Object::Pointer DefaultVariable::ResolveVariable(const QString &name, - const QList& args) +Object::ConstPointer DefaultVariable::ResolveVariable(const QString &name, + const QList& args) const { return fManagedPool->ResolveVariable(name, args); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefaultVariable.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefaultVariable.h index a47301c461..a686acd783 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefaultVariable.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefaultVariable.h @@ -1,91 +1,92 @@ /*=================================================================== 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 BERRYDEFAULTVARIABLE_H_ #define BERRYDEFAULTVARIABLE_H_ #include "berryIEvaluationContext.h" namespace berry { -class DefaultVariable : public IEvaluationContext { +class DefaultVariable : public IEvaluationContext +{ private: - Object::Pointer fDefaultVariable; + Object::ConstPointer fDefaultVariable; IEvaluationContext* fParent; IEvaluationContext* fManagedPool; public: /** * Constructs a new variable pool for a single default variable. * * @param parent the parent context for the default variable. Must not * be null. * @param defaultVariable the default variable */ - DefaultVariable(IEvaluationContext* parent, const Object::Pointer& defaultVariable); + DefaultVariable(IEvaluationContext* parent, const Object::ConstPointer& defaultVariable); /** * {@inheritDoc} */ IEvaluationContext* GetParent() const; /** * {@inheritDoc} */ - IEvaluationContext* GetRoot(); + IEvaluationContext* GetRoot() const; /** * {@inheritDoc} */ - Object::Pointer GetDefaultVariable() const; + Object::ConstPointer GetDefaultVariable() const; /** * {@inheritDoc} */ void SetAllowPluginActivation(bool value); /** * {@inheritDoc} */ bool GetAllowPluginActivation() const; /** * {@inheritDoc} */ - void AddVariable(const QString& name, const Object::Pointer& value); + void AddVariable(const QString& name, const Object::ConstPointer& value); /** * {@inheritDoc} */ - Object::Pointer RemoveVariable(const QString& name); + Object::ConstPointer RemoveVariable(const QString& name); /** * {@inheritDoc} */ - Object::Pointer GetVariable(const QString& name) const; + Object::ConstPointer GetVariable(const QString& name) const; /** * {@inheritDoc} */ - Object::Pointer ResolveVariable(const QString& name, const QList& args); + Object::ConstPointer ResolveVariable(const QString& name, const QList& args) const; }; } // namespace berry #endif /*BERRYDEFAULTVARIABLE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefinitionRegistry.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefinitionRegistry.cpp index 2cfe5acfac..396970d4b9 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefinitionRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefinitionRegistry.cpp @@ -1,101 +1,102 @@ /*=================================================================== 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 "berryDefinitionRegistry.h" #include "berryExpressionConverter.h" #include "berryExpressionStatus.h" #include "berryCoreException.h" +#include "berryElementHandler.h" #include "berryPlatform.h" #include "berryPlatformException.h" #include "berryStatus.h" #include "berryIExtensionRegistry.h" #include "berryIConfigurationElement.h" #include "berryInvalidRegistryObjectException.h" namespace berry { QHash& DefinitionRegistry::GetCache() { return cache; } DefinitionRegistry::DefinitionRegistry() { //Platform.getExtensionRegistry().addRegistryChangeListener(this, "org.blueberry.core.expressions"); //$NON-NLS-1$ } Expression::Pointer DefinitionRegistry::GetExpression(const QString& id) { Expression::Pointer cachedExpression= this->GetCache()[id]; if (!cachedExpression.IsNull()) { return cachedExpression; } IExtensionRegistry* registry = Platform::GetExtensionRegistry(); QList ces = registry->GetConfigurationElementsFor("org.blueberry.core.expressions.definitions"); Expression::Pointer foundExpression; for (QList::iterator i= ces.begin(); i != ces.end(); ++i) { QString cid = (*i)->GetAttribute("id"); if (!cid.isNull()) { if (cid == id) { try { foundExpression= this->GetExpression(id, *i); break; } - catch (const InvalidRegistryObjectException& e) + catch (const InvalidRegistryObjectException& /*e*/) { IStatus::Pointer status(new ExpressionStatus(ExpressionStatus::MISSING_EXPRESSION, QString("Unable to locate expression definition ") + id, BERRY_STATUS_LOC)); throw CoreException(status); } } } } if (foundExpression.IsNull()) { IStatus::Pointer status(new ExpressionStatus(ExpressionStatus::MISSING_EXPRESSION, QString("Unable to locate expression definition ") + id, BERRY_STATUS_LOC)); throw CoreException(status); } return foundExpression; } Expression::Pointer DefinitionRegistry::GetExpression(const QString& id, const IConfigurationElement::Pointer& element) { QList children(element->GetChildren()); Expression::Pointer expr= ExpressionConverter::GetDefault()->Perform(children[0]); if (!expr.IsNull()) { this->GetCache()[id] = expr; } return expr; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryEqualsExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryEqualsExpression.cpp index 6719e938a1..64ddef9856 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryEqualsExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryEqualsExpression.cpp @@ -1,77 +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. ===================================================================*/ #include "berryEqualsExpression.h" #include "berryExpressions.h" #include #include #include #include namespace berry { const std::size_t EqualsExpression::HASH_INITIAL= Poco::Hash()("berry::EqualsExpression"); EqualsExpression::EqualsExpression(Object::Pointer expectedValue) { poco_assert(expectedValue.IsNotNull()); fExpectedValue = expectedValue; } EqualsExpression::EqualsExpression(const IConfigurationElement::Pointer& element) { QString value = element->GetAttribute(ATT_VALUE); Expressions::CheckAttribute(ATT_VALUE, value); fExpectedValue = Expressions::ConvertArgument(value); } EqualsExpression::EqualsExpression(Poco::XML::Element* element) { std::string strValue = element->getAttribute(ATT_VALUE.toStdString()); QString value(strValue.size() > 0 ? QString::fromStdString(strValue) : QString()); Expressions::CheckAttribute(ATT_VALUE, value); fExpectedValue = Expressions::ConvertArgument(value); } EvaluationResult::ConstPointer EqualsExpression::Evaluate(IEvaluationContext* context) const { - Object::Pointer element= context->GetDefaultVariable(); + Object::ConstPointer element= context->GetDefaultVariable(); return EvaluationResult::ValueOf(element == fExpectedValue); } void -EqualsExpression::CollectExpressionInfo(ExpressionInfo* info) { +EqualsExpression::CollectExpressionInfo(ExpressionInfo* info) const +{ info->MarkDefaultVariableAccessed(); } bool EqualsExpression::operator==(const Object* object) const { if(const EqualsExpression* that = dynamic_cast(object)) { return this->fExpectedValue == that->fExpectedValue; } return false; } -std::size_t -EqualsExpression::ComputeHashCode() { +uint +EqualsExpression::ComputeHashCode() const +{ return HASH_INITIAL * HASH_FACTOR + fExpectedValue->HashCode(); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryEqualsExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryEqualsExpression.h index 57fc45eacd..62384f53dc 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryEqualsExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryEqualsExpression.h @@ -1,61 +1,61 @@ /*=================================================================== 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 __BERRY_EQUALS_EXPRESSION_H__ #define __BERRY_EQUALS_EXPRESSION_H__ #include "berryExpression.h" #include "berryExpressionInfo.h" #include "berryIEvaluationContext.h" #include "Poco/DOM/Element.h" namespace berry { struct IConfigurationElement; class EqualsExpression : public Expression { /** * The seed for the hash code for all equals expressions. */ private: static const std::size_t HASH_INITIAL; Object::Pointer fExpectedValue; public: EqualsExpression(const Object::Pointer expectedValue); EqualsExpression(const SmartPointer& element); EqualsExpression(Poco::XML::Element* element); EvaluationResult::ConstPointer Evaluate(IEvaluationContext* context) const; - void CollectExpressionInfo(ExpressionInfo* info); + void CollectExpressionInfo(ExpressionInfo* info) const; bool operator==(const Object* object) const; protected: - std::size_t ComputeHashCode(); + uint ComputeHashCode() const; }; } // namespace berry #endif // __BERRY_EQUALS_EXPRESSION_H__ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressions.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressions.cpp index 428b6d18da..b177dcdfa7 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressions.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressions.cpp @@ -1,346 +1,334 @@ /*=================================================================== 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 "berryExpressions.h" #include "berryExpressionStatus.h" #include #include #include #include #include #include #include namespace berry { const bool Expressions::TRACING = true; Expressions::Expressions() { // no instance } bool Expressions::IsInstanceOf(const Object* element, const QString& type) { // null isn't an instanceof of anything. if (element == 0) return false; // TODO Reflection // return IsSubtype(element, type) return element->GetClassName() == type; } void Expressions::CheckAttribute(const QString& name, const QString& value) { if (value.isNull()) { IStatus::Pointer status(new ExpressionStatus( ExpressionStatus::MISSING_ATTRIBUTE, QString("Mandatory attribute %1 is missing").arg(name), BERRY_STATUS_LOC)); throw CoreException(status); } } void Expressions::CheckAttribute(const QString& name, const QString& value, QStringList &validValues) { CheckAttribute(name, value); if (validValues.contains(value)) return; IStatus::Pointer status(new ExpressionStatus(ExpressionStatus::WRONG_ATTRIBUTE_VALUE, QString("Attribute value %1 is not valid").arg(value), BERRY_STATUS_LOC)); throw CoreException(status); } void Expressions::CheckCollection(Object::ConstPointer var, Expression::Pointer expression) { if (var.Cast >()) return; IStatus::Pointer status(new ExpressionStatus(ExpressionStatus::VARIABLE_IS_NOT_A_COLLECTION, QString("The default variable is not of type ObjectList. " "Failed expression: %1").arg(expression->ToString()), BERRY_STATUS_LOC)); throw CoreException(status); } - IIterable::Pointer - Expressions::GetAsIIterable(Object::Pointer var, Expression::ConstPointer expression) + IIterable::ConstPointer + Expressions::GetAsIIterable(Object::ConstPointer var, Expression::ConstPointer expression) { - IIterable::Pointer iterable(var.Cast()); + IIterable::ConstPointer iterable(var.Cast()); if (!iterable.IsNull()) { return iterable; } else { IAdapterManager* manager= Platform::GetAdapterManager(); - Object::Pointer result; - Poco::Any any(manager->GetAdapter(var, IIterable::GetStaticClassName())); - if (!any.empty() && any.type() == typeid(Object::Pointer)) - { - result = Poco::AnyCast(any); - } + iterable = manager->GetAdapter(var.GetPointer()); - if (result) + if (iterable) { - iterable = result.Cast(); return iterable; } - if (manager->QueryAdapter(var->GetClassName(), IIterable::GetStaticClassName()) == IAdapterManager::NOT_LOADED) + if (manager->QueryAdapter(var.GetPointer()) == IAdapterManager::NOT_LOADED) return IIterable::Pointer(); IStatus::Pointer status(new ExpressionStatus(ExpressionStatus::VARIABLE_IS_NOT_A_COLLECTION, QString("The default variable is not iterable. Failed expression: %1").arg(expression->ToString()), BERRY_STATUS_LOC)); throw CoreException(status); } } - ICountable::Pointer - Expressions::GetAsICountable(Object::Pointer var, Expression::ConstPointer expression) + ICountable::ConstPointer + Expressions::GetAsICountable(Object::ConstPointer var, Expression::ConstPointer expression) { - ICountable::Pointer countable(var.Cast()); + ICountable::ConstPointer countable(var.Cast()); if (!countable.IsNull()) { return countable; } else { IAdapterManager* manager = Platform::GetAdapterManager(); - Object::Pointer result; - Poco::Any any(manager->GetAdapter(var, ICountable::GetStaticClassName())); - if (!any.empty() && any.type() == typeid(Object::Pointer)) - { - result = Poco::AnyCast(any); - } - + ICountable::ConstPointer result(manager->GetAdapter(var.GetPointer())); if (result) { - countable = result.Cast(); + return result; } - if (manager->QueryAdapter(var->GetClassName(), ICountable::GetStaticClassName()) == IAdapterManager::NOT_LOADED) - return ICountable::Pointer(); + if (manager->QueryAdapter(var.GetPointer()) == IAdapterManager::NOT_LOADED) + return ICountable::ConstPointer(); IStatus::Pointer status(new ExpressionStatus(ExpressionStatus::VARIABLE_IS_NOT_A_COLLECTION, QString("The default variable is not countable. Failed expression: %1").arg(expression->ToString()), BERRY_STATUS_LOC)); throw CoreException(status); } } bool Expressions::GetOptionalBooleanAttribute(IConfigurationElement::Pointer element, const QString& attributeName) { QString value = element->GetAttribute(attributeName); if (value.isNull()) return false; return value.compare("true", Qt::CaseInsensitive) == 0; } bool Expressions::GetOptionalBooleanAttribute(Poco::XML::Element* element, const QString& attributeName) { QString value = QString::fromStdString(element->getAttribute(attributeName.toStdString())); if (value.size() == 0) return false; return value.compare("true", Qt::CaseInsensitive) == 0; } QList Expressions::GetArguments(const IConfigurationElement::Pointer& element, const QString& attributeName) { QString value = element->GetAttribute(attributeName); if (!value.isNull()) { return ParseArguments(value); } return QList(); } QList Expressions::GetArguments(Poco::XML::Element* element, const QString& attributeName) { std::string value = element->getAttribute(attributeName.toStdString()); if (value.size() > 0) { return ParseArguments(QString::fromStdString(value)); } return QList(); } QList Expressions::ParseArguments(const QString& args) { QList result; int start= 0; int comma; while ((comma = FindNextComma(args, start)) != -1) { result.push_back(ConvertArgument(args.mid(start, comma-start).trimmed())); start= comma + 1; } result.push_back(ConvertArgument(args.mid(start).trimmed())); return result; } int Expressions::FindNextComma(const QString& str, int start) { bool inString = false; - for (unsigned int i = start; i < str.size(); i++) + for (int i = start; i < str.size(); i++) { const QChar ch = str.at(i); if (ch == ',' && ! inString) return i; if (ch == '\'') { if (!inString) { inString= true; } else { if (i + 1 < str.size() && str.at(i + 1) == '\'') { i++; } else { inString= false; } } } else if (ch == ',' && !inString) { return i; } } if (inString) { IStatus::Pointer status(new ExpressionStatus(ExpressionStatus::STRING_NOT_TERMINATED, QString("The String \"%1\" is not correctly terminated with an apostrophe character.").arg(str), BERRY_STATUS_LOC)); throw CoreException(status); } return -1; } Object::Pointer Expressions::ConvertArgument(const QString& arg) { if (arg.isNull()) { return Object::Pointer(); } else if (arg.length() == 0) { ObjectString::Pointer var(new ObjectString(arg)); return var; } else if (arg.at(0) == '\'' && arg.at(arg.size() - 1) == '\'') { ObjectString::Pointer var(new ObjectString(UnEscapeString(arg.mid(1, arg.size() - 2)))); return var; } else if ("true" == arg) { ObjectBool::Pointer var(new ObjectBool(true)); return var; } else if ("false" == arg) { ObjectBool::Pointer var(new ObjectBool(false)); return var; } else if (arg.indexOf('.') != -1) { bool ok = false; float num = arg.toFloat(&ok); if (ok) { ObjectFloat::Pointer var(new ObjectFloat(num)); return var; } else { ObjectString::Pointer var(new ObjectString(arg)); return var; } } else { bool ok = false; int num = arg.toInt(&ok); if (ok) { ObjectInt::Pointer var(new ObjectInt(num)); return var; } else { ObjectString::Pointer var(new ObjectString(arg)); return var; } } } QString Expressions::UnEscapeString(const QString& str) { QString result = ""; - for (unsigned int i= 0; i < str.size(); i++) + for (int i= 0; i < str.size(); i++) { const QChar ch= str.at(i); if (ch == '\'') { if (i == str.size() - 1 || str.at(i + 1) != '\'') { IStatus::Pointer status(new ExpressionStatus(ExpressionStatus::STRING_NOT_CORRECT_ESCAPED, QString("The String \"%1\" is not correctly escaped. " "Wrong number of apostrophe characters.").arg(str), BERRY_STATUS_LOC)); throw CoreException(status); } result.append('\''); i++; } else { result.append(ch); } } return result; } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressions.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressions.h index ad99d89d98..e9475b0c1a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressions.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressions.h @@ -1,104 +1,104 @@ /*=================================================================== 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 BERRYEXPRESSIONS_H_ #define BERRYEXPRESSIONS_H_ #include "Poco/Any.h" #include "Poco/DOM/Element.h" #include "berryExpression.h" #include "berryIIterable.h" #include "berryICountable.h" #include #include namespace berry { struct IConfigurationElement; class Expressions { private: Expressions(); static int FindNextComma(const QString& str, int start); public: /* debugging flag to enable tracing */ static const bool TRACING; static bool IsInstanceOf(const Object *element, const QString& type); static void CheckAttribute(const QString& name, const QString& value); static void CheckAttribute(const QString& name, const QString& value, QStringList& validValues); static void CheckCollection(Object::ConstPointer var, Expression::Pointer expression); /** * Converts the given variable into an IIterable. If a corresponding adapter can't be found an * exception is thrown. If the corresponding adapter isn't loaded yet, null is returned. * * @param var the variable to turn into an IIterable * @param expression the expression referring to the variable * * @return the IIterable or null if a corresponding adapter isn't loaded yet * * @throws CoreException if the var can't be adapted to an IIterable */ - static IIterable::Pointer GetAsIIterable(Object::Pointer var, Expression::ConstPointer expression); + static IIterable::ConstPointer GetAsIIterable(Object::ConstPointer var, Expression::ConstPointer expression); /** * Converts the given variable into an ICountable. If a corresponding adapter can't be found an * exception is thrown. If the corresponding adapter isn't loaded yet, null is returned. * * @param var the variable to turn into an ICountable * @param expression the expression referring to the variable * * @return the ICountable or null if a corresponding adapter isn't loaded yet * * @throws CoreException if the var can't be adapted to an ICountable */ - static ICountable::Pointer GetAsICountable(Object::Pointer var, Expression::ConstPointer expression); + static ICountable::ConstPointer GetAsICountable(Object::ConstPointer var, Expression::ConstPointer expression); static bool GetOptionalBooleanAttribute(SmartPointer element, const QString& attributeName); static bool GetOptionalBooleanAttribute(Poco::XML::Element* element, const QString& attributeName); //---- Argument parsing -------------------------------------------- static QList GetArguments(const SmartPointer& element, const QString& attributeName); static QList GetArguments(Poco::XML::Element* element, const QString& attributeName); static QList ParseArguments(const QString& args); static Object::Pointer ConvertArgument(const QString& arg); static QString UnEscapeString(const QString& str); }; } #endif /*BERRYEXPRESSIONS_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryInstanceofExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryInstanceofExpression.cpp index eb403d4653..621fd05908 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryInstanceofExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryInstanceofExpression.cpp @@ -1,80 +1,80 @@ /*=================================================================== 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 "berryInstanceofExpression.h" #include "berryExpressions.h" #include namespace berry { const uint InstanceofExpression::HASH_INITIAL= qHash("berry::InstanceofExpression"); InstanceofExpression::InstanceofExpression(const IConfigurationElement::Pointer& element) { fTypeName = element->GetAttribute(ATT_VALUE); Expressions::CheckAttribute(ATT_VALUE, fTypeName); } InstanceofExpression::InstanceofExpression(Poco::XML::Element* element) { std::string value = element->getAttribute(ATT_VALUE.toStdString()); fTypeName = value.size() > 0 ? QString::fromStdString(value) : QString(); Expressions::CheckAttribute(ATT_VALUE, fTypeName); } InstanceofExpression::InstanceofExpression(const QString& typeName) : fTypeName(typeName) { } EvaluationResult::ConstPointer InstanceofExpression::Evaluate(IEvaluationContext* context) const { - Object::Pointer element= context->GetDefaultVariable(); + Object::ConstPointer element= context->GetDefaultVariable(); return EvaluationResult::ValueOf(Expressions::IsInstanceOf(element.GetPointer(), fTypeName)); } void -InstanceofExpression::CollectExpressionInfo(ExpressionInfo* info) +InstanceofExpression::CollectExpressionInfo(ExpressionInfo* info) const { info->MarkDefaultVariableAccessed(); } bool InstanceofExpression::operator==(const Object* object) const { if (const InstanceofExpression* that = dynamic_cast(object)) { return this->fTypeName == that->fTypeName; } return false; } QString InstanceofExpression::ToString() const { return QString(""; } uint -InstanceofExpression::ComputeHashCode() +InstanceofExpression::ComputeHashCode() const { return HASH_INITIAL * HASH_FACTOR + qHash(fTypeName); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryInstanceofExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryInstanceofExpression.h index f5b03bb017..cf1164740b 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryInstanceofExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryInstanceofExpression.h @@ -1,73 +1,73 @@ /*=================================================================== 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 __BERRY_INSTANCEOF_EXPRESSION_H__ #define __BERRY_INSTANCEOF_EXPRESSION_H__ #include "berryExpression.h" #include "Poco/DOM/Element.h" namespace berry { struct IConfigurationElement; struct InstanceofExpression : public Expression { private: /** * The seed for the hash code for all instance of expressions. */ static const uint HASH_INITIAL; QString fTypeName; public: InstanceofExpression(const SmartPointer& element); InstanceofExpression(Poco::XML::Element* element); InstanceofExpression(const QString &typeName); /* * @see org.blueberry.jdt.internal.corext.refactoring.participants.Expression#evaluate(java.lang.Object) */ EvaluationResult::ConstPointer Evaluate(IEvaluationContext* context) const; - void CollectExpressionInfo(ExpressionInfo* info); + void CollectExpressionInfo(ExpressionInfo* info) const; bool operator==(const Object* object) const; //---- Debugging --------------------------------------------------- /* * @see java.lang.Object#toString() */ QString ToString() const; protected: - uint ComputeHashCode(); + uint ComputeHashCode() const; }; } // namespace berry #endif // __BERRY_INSTANCEOF_EXPRESSION_H__ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryIterateExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryIterateExpression.cpp index 96076452ff..15e9d5157a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryIterateExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryIterateExpression.cpp @@ -1,292 +1,293 @@ /*=================================================================== 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 "berryIterateExpression.h" #include "berryExpressions.h" #include "berryDefaultVariable.h" #include #include #include namespace berry { const QString IterateExpression::ATT_OPERATOR = "operator"; const QString IterateExpression::ATT_IF_EMPTY = "ifEmpty"; const int IterateExpression::OR = 1; const int IterateExpression::AND = 2; const uint IterateExpression::HASH_INITIAL = qHash("berry::IterateExpression"); struct IteratePool : public IEvaluationContext { private: - QList::iterator fIterator; - QList::iterator fIterEnd; - Object::Pointer fDefaultVariable; + QList::const_iterator fIterator; + QList::const_iterator fIterEnd; + Object::ConstPointer fDefaultVariable; IEvaluationContext* fParent; public: - IteratePool(IEvaluationContext* parent, QList::iterator begin, QList::iterator end) + IteratePool(IEvaluationContext* parent, QList::const_iterator begin, + QList::const_iterator end) { poco_check_ptr(parent); fParent= parent; fIterator = begin; fIterEnd = end; } IEvaluationContext* GetParent() const { return fParent; } - IEvaluationContext* GetRoot() { + IEvaluationContext* GetRoot() const { return fParent->GetRoot(); } - Object::Pointer GetDefaultVariable() const { + Object::ConstPointer GetDefaultVariable() const { return fDefaultVariable; } bool GetAllowPluginActivation() const { return fParent->GetAllowPluginActivation(); } void SetAllowPluginActivation(bool value) { fParent->SetAllowPluginActivation(value); } - void AddVariable(const QString& name, const Object::Pointer& value) { + void AddVariable(const QString& name, const Object::ConstPointer& value) { fParent->AddVariable(name, value); } - Object::Pointer RemoveVariable(const QString& name) { + Object::ConstPointer RemoveVariable(const QString& name) { return fParent->RemoveVariable(name); } - Object::Pointer GetVariable(const QString& name) const { + Object::ConstPointer GetVariable(const QString& name) const { return fParent->GetVariable(name); } - Object::Pointer ResolveVariable(const QString& name, const QList& args) { + Object::ConstPointer ResolveVariable(const QString& name, const QList& args) const { return fParent->ResolveVariable(name, args); } Poco::Any Next() { fDefaultVariable = (++fIterator)->GetPointer(); return fDefaultVariable; } bool HasNext() { return (fIterator != fIterEnd); } }; IterateExpression::IterateExpression( const IConfigurationElement::Pointer& configElement) { QString opValue = configElement->GetAttribute(ATT_OPERATOR); this->InitializeOperatorValue(opValue); this->InitializeEmptyResultValue(configElement->GetAttribute(ATT_IF_EMPTY)); } IterateExpression::IterateExpression(Poco::XML::Element* element) { std::string opValue = element->getAttribute(ATT_OPERATOR.toStdString()); this->InitializeOperatorValue(opValue.size() > 0 ? QString::fromStdString(opValue) : QString()); std::string ifEmpty = element->getAttribute(ATT_IF_EMPTY.toStdString()); this->InitializeEmptyResultValue(ifEmpty.size() > 0 ? QString::fromStdString(ifEmpty) : QString()); } IterateExpression::IterateExpression(const QString& opValue) { this->InitializeOperatorValue(opValue); } IterateExpression::IterateExpression(const QString& opValue, const QString& ifEmpty) { this->InitializeOperatorValue(opValue); this->InitializeEmptyResultValue(ifEmpty); } void IterateExpression::InitializeOperatorValue(const QString& opValue) { if (opValue.isNull()) { fOperator = AND; } else { QStringList fValidOperators; fValidOperators.push_back("and"); fValidOperators.push_back("or"); Expressions::CheckAttribute(ATT_OPERATOR, opValue, fValidOperators); if ("and" == opValue) { fOperator = AND; } else { fOperator = OR; } } } void IterateExpression::InitializeEmptyResultValue(const QString& value) { if (value.isNull()) { fEmptyResult = -1; } else { fEmptyResult = value.compare("true", Qt::CaseInsensitive) == 0 ? 1 : 0; } } EvaluationResult::ConstPointer IterateExpression::Evaluate(IEvaluationContext* context) const { - Object::Pointer var = context->GetDefaultVariable(); - ObjectList* col = dynamic_cast*>(var.GetPointer()); + Object::ConstPointer var = context->GetDefaultVariable(); + const ObjectList* col = dynamic_cast*>(var.GetPointer()); if (col) { switch (col->size()) { case 0: { if (fEmptyResult == -1) { return fOperator == AND ? EvaluationResult::TRUE_EVAL : EvaluationResult::FALSE_EVAL; } else { return fEmptyResult == 1 ? EvaluationResult::TRUE_EVAL : EvaluationResult::FALSE_EVAL; } } case 1: { IEvaluationContext::Pointer scope(new DefaultVariable(context, col->front())); return this->EvaluateAnd(scope.GetPointer()); } default: IteratePool iter(context, col->begin(), col->end()); EvaluationResult::ConstPointer result = fOperator == AND ? EvaluationResult::TRUE_EVAL : EvaluationResult::FALSE_EVAL; while (iter.HasNext()) { switch (fOperator) { case OR: result = result->Or(this->EvaluateAnd(&iter)); if (result == EvaluationResult::TRUE_EVAL) return result; break; case AND: result = result->And(this->EvaluateAnd(&iter)); if (result != EvaluationResult::TRUE_EVAL) return result; break; } iter.Next(); } return result; } } else { - IIterable::Pointer iterable = Expressions::GetAsIIterable(Object::Pointer(var), + IIterable::ConstPointer iterable = Expressions::GetAsIIterable(var, Expression::ConstPointer(this)); if (iterable.IsNull()) return EvaluationResult::NOT_LOADED; int count = 0; IteratePool iter(context, iterable->begin(), iterable->end()); EvaluationResult::ConstPointer result = fOperator == AND ? EvaluationResult::TRUE_EVAL : EvaluationResult::FALSE_EVAL; while (iter.HasNext()) { count++; switch (fOperator) { case OR: result = result->Or(this->EvaluateAnd(&iter)); if (result == EvaluationResult::TRUE_EVAL) return result; break; case AND: result = result->And(this->EvaluateAnd(&iter)); if (result != EvaluationResult::TRUE_EVAL) return result; break; } iter.Next(); } if (count > 0) { return result; } else { if (fEmptyResult == -1) { return fOperator == AND ? EvaluationResult::TRUE_EVAL : EvaluationResult::FALSE_EVAL; } else { return fEmptyResult == 1 ? EvaluationResult::TRUE_EVAL : EvaluationResult::FALSE_EVAL; } } } } -void IterateExpression::CollectExpressionInfo(ExpressionInfo* info) +void IterateExpression::CollectExpressionInfo(ExpressionInfo* info) const { // Although we access every single variable we only mark the default // variable as accessed since we don't have single variables for the // elements. info->MarkDefaultVariableAccessed(); CompositeExpression::CollectExpressionInfo(info); } bool IterateExpression::operator==(const Object* object) const { if (const IterateExpression* that = dynamic_cast(object)) { return (this->fOperator == that->fOperator) && this->Equals(this->fExpressions, that->fExpressions); } return false; } -uint IterateExpression::ComputeHashCode() +uint IterateExpression::ComputeHashCode() const { return HASH_INITIAL * HASH_FACTOR + this->HashCode(fExpressions) * HASH_FACTOR + fOperator; } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryIterateExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryIterateExpression.h index d039067f78..d6782ff57a 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryIterateExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryIterateExpression.h @@ -1,83 +1,83 @@ /*=================================================================== 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 __BERRY_ITERATE_EXPRESSION_H__ #define __BERRY_ITERATE_EXPRESSION_H__ #include "berryCompositeExpression.h" #include "Poco/DOM/Element.h" #include "Poco/Any.h" namespace berry { struct IConfigurationElement; struct IterateExpression : public CompositeExpression { private: static const QString ATT_OPERATOR; static const QString ATT_IF_EMPTY; static const int OR; static const int AND; /** * The seed for the hash code for all iterate expressions. */ static const uint HASH_INITIAL; int fOperator; int fEmptyResult; public: IterateExpression(const SmartPointer& configElement); IterateExpression(Poco::XML::Element* element); IterateExpression(const QString& opValue); IterateExpression(const QString& opValue, const QString& ifEmpty); private: void InitializeOperatorValue(const QString& opValue); void InitializeEmptyResultValue(const QString& value); public: /* (non-Javadoc) * @see Expression#evaluate(IVariablePool) */ EvaluationResult::ConstPointer Evaluate(IEvaluationContext* context) const; - void CollectExpressionInfo(ExpressionInfo* info); + void CollectExpressionInfo(ExpressionInfo* info) const; bool operator==(const Object* object) const; protected: - uint ComputeHashCode(); + uint ComputeHashCode() const; }; } // namespace berry #endif // __BERRY_ITERATE_EXPRESSION_H__ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryNotExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryNotExpression.cpp index 6f37a3579e..b23c0be84c 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryNotExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryNotExpression.cpp @@ -1,61 +1,61 @@ /*=================================================================== 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 "berryNotExpression.h" #include #include namespace berry { const std::size_t NotExpression::HASH_INITIAL = Poco::hash("berry::NotExpression"); NotExpression::NotExpression(Expression::Pointer expression) { poco_assert(expression.IsNotNull()); fExpression= expression; } EvaluationResult::ConstPointer NotExpression::Evaluate(IEvaluationContext* context) const { return fExpression->Evaluate(context)->Not(); } void -NotExpression::CollectExpressionInfo(ExpressionInfo* info) +NotExpression::CollectExpressionInfo(ExpressionInfo* info) const { fExpression->CollectExpressionInfo(info); } bool NotExpression::operator==(const Object* object) const { if (const NotExpression* that = dynamic_cast(object)) { return this->fExpression == that->fExpression; } return false; } -std::size_t -NotExpression::ComputeHashCode() +uint +NotExpression::ComputeHashCode() const { return HASH_INITIAL * HASH_FACTOR + fExpression->HashCode(); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryNotExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryNotExpression.h index e3c2312021..8f5e920418 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryNotExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryNotExpression.h @@ -1,53 +1,53 @@ /*=================================================================== 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 __BERRY_NOT_EXPRESSION_H__ #define __BERRY_NOT_EXPRESSION_H__ #include "berryExpression.h" namespace berry { class NotExpression : public Expression { private: /** * The seed for the hash code for all not expressions. */ static const std::size_t HASH_INITIAL; Expression::Pointer fExpression; public: NotExpression(Expression::Pointer expression); EvaluationResult::ConstPointer Evaluate(IEvaluationContext* context) const; - void CollectExpressionInfo(ExpressionInfo* info); + void CollectExpressionInfo(ExpressionInfo* info) const; bool operator==(const Object* object) const; protected: - std::size_t ComputeHashCode(); + uint ComputeHashCode() const; }; } // namespace berry #endif // __BERRY_NOT_EXPRESSION_H__ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryProperty.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryProperty.cpp index ebda0bfaef..267a218754 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryProperty.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryProperty.cpp @@ -1,84 +1,84 @@ /*=================================================================== 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 "berryProperty.h" #include #include namespace berry { -Property::Property(Object::Pointer type, +Property::Property(Object::ConstPointer type, const QString &namespaze, const QString &name) : fType(type), fNamespace(namespaze), fName(name) { } void Property::SetPropertyTester(IPropertyTester::Pointer tester) { poco_check_ptr(tester); fTester= tester; } bool Property::IsInstantiated() { return fTester->IsInstantiated(); } bool Property::IsDeclaringPluginActive() { return fTester->IsDeclaringPluginActive(); } bool Property::IsValidCacheEntry(bool forcePluginActivation) { if (forcePluginActivation) { return this->IsInstantiated() && this->IsDeclaringPluginActive(); } else { return (this->IsInstantiated() && this->IsDeclaringPluginActive()) || (!this->IsInstantiated() && !this->IsDeclaringPluginActive()); } } -bool Property::Test(Object::Pointer receiver, const QList& args, +bool Property::Test(Object::ConstPointer receiver, const QList& args, Object::Pointer expectedValue) { return fTester->Test(receiver, fName, args, expectedValue); } bool Property::operator==(Property& obj) { return fType == obj.fType && fNamespace == obj.fNamespace && fName == obj.fName; } bool Property::operator==(Property* obj) { return this->operator==(*obj); } int Property::HashCode() { return (int) ((Poco::Hash()(typeid(fType).name()) << 16) | (Poco::Hash()(fNamespace.toStdString()) << 8) | Poco::Hash()(fName.toStdString())); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryProperty.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryProperty.h index 782e46ca88..9ca3b844d1 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryProperty.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryProperty.h @@ -1,71 +1,71 @@ /*=================================================================== 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 BERRYPROPERTY_H_ #define BERRYPROPERTY_H_ #include "berryIPropertyTester.h" #include "berryObject.h" #include "Poco/SharedPtr.h" #include "Poco/Any.h" #include #include namespace berry { class Property { public: typedef Property Self; typedef Poco::SharedPtr Pointer; typedef Poco::SharedPtr ConstPointer; private: - Object::Pointer fType; + Object::ConstPointer fType; QString fNamespace; QString fName; IPropertyTester::Pointer fTester; friend class TypeExtensionManager; - /* package */ Property(Object::Pointer type, + /* package */ Property(Object::ConstPointer type, const QString& namespaze, const QString& name); /* package */ void SetPropertyTester(IPropertyTester::Pointer tester); public: bool IsInstantiated(); bool IsDeclaringPluginActive(); bool IsValidCacheEntry(bool forcePluginActivation); - bool Test(Object::Pointer receiver, const QList& args, + bool Test(Object::ConstPointer receiver, const QList& args, Object::Pointer expectedValue); bool operator==(Property& obj); bool operator==(Property* obj); int HashCode(); }; } // namespace berry #endif /*BERRYPROPERTY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyTesterDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyTesterDescriptor.cpp index 66d2c7c0dd..13a01cd9c4 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyTesterDescriptor.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyTesterDescriptor.cpp @@ -1,126 +1,126 @@ /*=================================================================== 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 "berryPropertyTesterDescriptor.h" #include "berryPlatform.h" #include "berryCoreException.h" #include "berryStatus.h" #include "berryExpressionPlugin.h" #include #include #include "Poco/String.h" namespace berry { const QString PropertyTesterDescriptor::PROPERTIES= "properties"; const QString PropertyTesterDescriptor::NAMESPACE= "namespace"; const QString PropertyTesterDescriptor::CLASS= "class"; PropertyTesterDescriptor::PropertyTesterDescriptor(const IConfigurationElement::Pointer& element) : fConfigElement(element) { fNamespace = fConfigElement->GetAttribute(NAMESPACE); if (fNamespace.isNull()) { IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, ExpressionPlugin::GetPluginId(), IStatus::ERROR_TYPE, "The mandatory attribute namespace is missing. Tester has been disabled.", BERRY_STATUS_LOC)); throw CoreException(status); } QString buffer(","); QString properties = fConfigElement->GetAttribute(PROPERTIES); if (properties.isNull()) { IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, ExpressionPlugin::GetPluginId(), IStatus::ERROR_TYPE, "The mandatory attribute properties is missing. Tester has been disabled.", BERRY_STATUS_LOC)); throw CoreException(status); } foreach(QChar ch, properties) { if (!ch.isSpace()) { buffer.append(ch); } } buffer.append(','); fProperties = buffer; } PropertyTesterDescriptor::PropertyTesterDescriptor(const IConfigurationElement::Pointer& element, const QString& namespaze, const QString& properties) : fConfigElement(element), fNamespace(namespaze), fProperties(properties) { } QString PropertyTesterDescriptor::GetProperties() { return fProperties; } QString PropertyTesterDescriptor::GetNamespace() { return fNamespace; } IConfigurationElement::Pointer PropertyTesterDescriptor::GetExtensionElement() { return fConfigElement; } bool PropertyTesterDescriptor::Handles(const QString &namespaze, const QString &property) { return fNamespace == namespaze && fProperties.contains("," + property + ","); } bool PropertyTesterDescriptor::IsInstantiated() { return false; } bool PropertyTesterDescriptor::IsDeclaringPluginActive() { QSharedPointer plugin = Platform::GetPlugin(fConfigElement->GetContributor()->GetName()); return plugin->getState() == ctkPlugin::ACTIVE; } IPropertyTester* PropertyTesterDescriptor::Instantiate() { return fConfigElement->CreateExecutableExtension(CLASS); } bool -PropertyTesterDescriptor::Test(Object::Pointer /*receiver*/, const QString & /*method*/, +PropertyTesterDescriptor::Test(Object::ConstPointer /*receiver*/, const QString & /*method*/, const QList & /*args*/, Object::Pointer /*expectedValue*/) { poco_bugcheck_msg("Method should never be called"); return false; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyTesterDescriptor.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyTesterDescriptor.h index c2a267d3d7..7ae877be22 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyTesterDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyTesterDescriptor.h @@ -1,71 +1,71 @@ /*=================================================================== 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 BERRYPROPERTYTESTERDESCRIPTOR_H_ #define BERRYPROPERTYTESTERDESCRIPTOR_H_ #include "berryIPropertyTester.h" #include "Poco/Any.h" namespace berry { struct IConfigurationElement; class PropertyTesterDescriptor : public IPropertyTester { public: berryObjectMacro(PropertyTesterDescriptor); private: const SmartPointer fConfigElement; QString fNamespace; QString fProperties; static const QString PROPERTIES; static const QString NAMESPACE; static const QString CLASS; public: PropertyTesterDescriptor(const SmartPointer& element); PropertyTesterDescriptor(const SmartPointer& element, const QString& namespaze, const QString& properties); QString GetProperties(); QString GetNamespace(); SmartPointer GetExtensionElement(); bool Handles(const QString& namespaze, const QString& property); bool IsInstantiated(); bool IsDeclaringPluginActive(); IPropertyTester* Instantiate(); - bool Test(Object::Pointer receiver, const QString& method, + bool Test(Object::ConstPointer receiver, const QString& method, const QList& args, Object::Pointer expectedValue); }; } // namespace berry #endif /*BERRYPROPERTYTESTERDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryReferenceExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryReferenceExpression.cpp index ef2dde9809..cc87312074 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryReferenceExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryReferenceExpression.cpp @@ -1,96 +1,96 @@ /*=================================================================== 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 "berryReferenceExpression.h" #include "berryExpressions.h" #include #include #include "Poco/Hash.h" namespace berry { const QString ReferenceExpression::ATT_DEFINITION_ID= "definitionId"; const std::size_t ReferenceExpression::HASH_INITIAL= Poco::Hash()("berry::ReferenceExpression"); DefinitionRegistry ReferenceExpression::fgDefinitionRegistry = DefinitionRegistry(); DefinitionRegistry& ReferenceExpression::GetDefinitionRegistry() { return fgDefinitionRegistry; } ReferenceExpression::ReferenceExpression(const QString &definitionId) { fDefinitionId= definitionId; } ReferenceExpression::ReferenceExpression(IConfigurationElement::Pointer element) { fDefinitionId = element->GetAttribute(ATT_DEFINITION_ID); Expressions::CheckAttribute(ATT_DEFINITION_ID, fDefinitionId); } ReferenceExpression::ReferenceExpression(Poco::XML::Element* element) { fDefinitionId = QString::fromStdString(element->getAttribute(ATT_DEFINITION_ID.toStdString())); Expressions::CheckAttribute(ATT_DEFINITION_ID, fDefinitionId.size() > 0 ? fDefinitionId : QString()); } EvaluationResult::ConstPointer ReferenceExpression::Evaluate(IEvaluationContext* context) const { Expression::Pointer expr= GetDefinitionRegistry().GetExpression(fDefinitionId); return expr->Evaluate(context); } void -ReferenceExpression::CollectExpressionInfo(ExpressionInfo* info) +ReferenceExpression::CollectExpressionInfo(ExpressionInfo* info) const { Expression::Pointer expr; try { expr= GetDefinitionRegistry().GetExpression(fDefinitionId); } - catch (const CoreException& e) + catch (const CoreException& /*e*/) { // We didn't find the expression definition. So no // expression info can be collected. return; } expr->CollectExpressionInfo(info); } bool ReferenceExpression::operator==(const Object* object) const { if (const ReferenceExpression* that = dynamic_cast(object)) { return this->fDefinitionId == that->fDefinitionId; } return false; } -std::size_t -ReferenceExpression::ComputeHashCode() +uint +ReferenceExpression::ComputeHashCode() const { return HASH_INITIAL * HASH_FACTOR + Poco::Hash()(fDefinitionId.toStdString()); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryReferenceExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryReferenceExpression.h index fa1aa4f528..2bf6021639 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryReferenceExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryReferenceExpression.h @@ -1,72 +1,72 @@ /*=================================================================== 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 __BERRY_REFERENCE_EXPRESSION_H__ #define __BERRY_REFERENCE_EXPRESSION_H__ #include "berryDefinitionRegistry.h" #include "Poco/DOM/Element.h" namespace berry { /** * This class makes use of the org.blueberry.core.expressions.definitions * extension point to evaluate the current context against pre-defined * expressions. It provides core expression re-use. */ class ReferenceExpression : public Expression { private: // consider making this a more general extension manager // for now it's just part of the reference expression static DefinitionRegistry fgDefinitionRegistry; static DefinitionRegistry& GetDefinitionRegistry(); static const QString ATT_DEFINITION_ID; /** * The seed for the hash code for all equals expressions. */ static const std::size_t HASH_INITIAL; QString fDefinitionId; public: ReferenceExpression(const QString& definitionId); ReferenceExpression(SmartPointer element); ReferenceExpression(Poco::XML::Element* element); EvaluationResult::ConstPointer Evaluate(IEvaluationContext* context) const; - void CollectExpressionInfo(ExpressionInfo* info); + void CollectExpressionInfo(ExpressionInfo* info) const; bool operator==(const Object* object) const; protected: - std::size_t ComputeHashCode(); + uint ComputeHashCode() const; }; } // namespace berry #endif // __BERRY_REFERENCE_EXPRESSION_H__ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryResolveExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryResolveExpression.cpp index 8dd9e9687a..a9f2105a16 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryResolveExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryResolveExpression.cpp @@ -1,99 +1,99 @@ /*=================================================================== 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 "berryResolveExpression.h" #include "berryExpressions.h" #include "berryEvaluationContext.h" #include "berryExpressionStatus.h" #include #include namespace berry { const QString ResolveExpression::ATT_VARIABLE= "variable"; const QString ResolveExpression::ATT_ARGS= "args"; const uint ResolveExpression::HASH_INITIAL = qHash("berry::ResolveExpression"); ResolveExpression::ResolveExpression(const IConfigurationElement::Pointer& configElement) { fVariable = configElement->GetAttribute(ATT_VARIABLE); Expressions::CheckAttribute(ATT_VARIABLE, fVariable); fArgs = Expressions::GetArguments(configElement, ATT_ARGS); } ResolveExpression::ResolveExpression(Poco::XML::Element* element) { fVariable = QString::fromStdString(element->getAttribute(ATT_VARIABLE.toStdString())); Expressions::CheckAttribute(ATT_VARIABLE, fVariable.size() > 0 ? fVariable : QString()); fArgs = Expressions::GetArguments(element, ATT_ARGS); } ResolveExpression::ResolveExpression(const QString& variable, const QList& args) : fVariable(variable), fArgs(args) { } EvaluationResult::ConstPointer ResolveExpression::Evaluate(IEvaluationContext* context) const { - Object::Pointer variable= context->ResolveVariable(fVariable, fArgs); + Object::ConstPointer variable= context->ResolveVariable(fVariable, fArgs); if (variable.IsNull()) { IStatus::Pointer status(new ExpressionStatus(ExpressionStatus::VARIABLE_NOT_DEFINED, QString("The variable %1 is not defined.").arg(fVariable), BERRY_STATUS_LOC)); throw CoreException(status); } EvaluationContext evalContext(context, variable); return this->EvaluateAnd(&evalContext); } void -ResolveExpression::CollectExpressionInfo(ExpressionInfo* info) +ResolveExpression::CollectExpressionInfo(ExpressionInfo* info) const { ExpressionInfo other; this->CompositeExpression::CollectExpressionInfo(&other); if (other.HasDefaultVariableAccess()) { info->AddVariableNameAccess(fVariable); } info->MergeExceptDefaultVariable(&other); } bool ResolveExpression::operator==(const Object* object) const { if (const ResolveExpression* that = dynamic_cast(object)) { return this->fVariable == that->fVariable && this->Equals(this->fArgs, that->fArgs) && this->Equals(this->fExpressions, that->fExpressions); } return false; } uint -ResolveExpression::ComputeHashCode() +ResolveExpression::ComputeHashCode() const { return HASH_INITIAL * HASH_FACTOR + this->HashCode(fExpressions) * HASH_FACTOR + this->HashCode(fArgs) * HASH_FACTOR + qHash(fVariable); } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryResolveExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryResolveExpression.h index cbdbc9ad16..cbe8f9cdd5 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryResolveExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryResolveExpression.h @@ -1,66 +1,66 @@ /*=================================================================== 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 __BERRY_RESOLVE_EXPRESSION_H__ #define __BERRY_RESOLVE_EXPRESSION_H__ #include "berryCompositeExpression.h" #include "Poco/DOM/Element.h" #include namespace berry { struct IConfigurationElement; class ResolveExpression : public CompositeExpression { private: QString fVariable; QList fArgs; static const QString ATT_VARIABLE; static const QString ATT_ARGS; /** * The seed for the hash code for all resolve expressions. */ static const uint HASH_INITIAL; public: ResolveExpression(const SmartPointer& configElement); ResolveExpression(Poco::XML::Element* element); ResolveExpression(const QString& variable, const QList& args); EvaluationResult::ConstPointer Evaluate(IEvaluationContext* context) const; - void CollectExpressionInfo(ExpressionInfo* info); + void CollectExpressionInfo(ExpressionInfo* info) const; bool operator==(const Object* object) const; protected: - uint ComputeHashCode(); + uint ComputeHashCode() const; }; } // namespace berry #endif // __BERRY_RESOLVE_EXPRESSION_H__ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berrySystemTestExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berrySystemTestExpression.cpp index 38cb7e7e9b..74a939f46f 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berrySystemTestExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berrySystemTestExpression.cpp @@ -1,93 +1,93 @@ /*=================================================================== 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 "berrySystemTestExpression.h" #include "berryExpressions.h" #include #include namespace berry { const QString SystemTestExpression::ATT_PROPERTY= "property"; const uint SystemTestExpression::HASH_INITIAL = qHash("berry::SystemTestExpression"); SystemTestExpression::SystemTestExpression(const IConfigurationElement::Pointer& element) { fProperty = element->GetAttribute(ATT_PROPERTY); Expressions::CheckAttribute(ATT_PROPERTY, fProperty); fExpectedValue = element->GetAttribute(ATT_VALUE); Expressions::CheckAttribute(ATT_VALUE, fExpectedValue); } SystemTestExpression::SystemTestExpression(Poco::XML::Element* element) { fProperty= QString::fromStdString(element->getAttribute(ATT_PROPERTY.toStdString())); Expressions::CheckAttribute(ATT_PROPERTY, fProperty.size() > 0 ? fProperty : QString()); fExpectedValue = QString::fromStdString(element->getAttribute(ATT_VALUE.toStdString())); Expressions::CheckAttribute(ATT_VALUE, fExpectedValue.size() > 0 ? fExpectedValue : QString()); } SystemTestExpression::SystemTestExpression(const QString &property, const QString &expectedValue) : fProperty(property), fExpectedValue(expectedValue) { } EvaluationResult::ConstPointer SystemTestExpression::Evaluate(IEvaluationContext* /*context*/) const { QString str = Platform::GetProperty(fProperty); if (str.isEmpty()) return EvaluationResult::FALSE_EVAL; return EvaluationResult::ValueOf(str == fExpectedValue); } void -SystemTestExpression::CollectExpressionInfo(ExpressionInfo* info) +SystemTestExpression::CollectExpressionInfo(ExpressionInfo* info) const { info->MarkSystemPropertyAccessed(); } bool SystemTestExpression::operator==(const Object* object) const { if (const SystemTestExpression* that = dynamic_cast(object)) { return this->fProperty == that->fProperty && this->fExpectedValue == that->fExpectedValue; } return false; } uint -SystemTestExpression::ComputeHashCode() +SystemTestExpression::ComputeHashCode() const { return HASH_INITIAL * HASH_FACTOR + qHash(fExpectedValue) * HASH_FACTOR + qHash(fProperty); } QString SystemTestExpression::ToString() const { return QString("& element); SystemTestExpression(Poco::XML::Element* element); SystemTestExpression(const QString& property, const QString& expectedValue); EvaluationResult::ConstPointer Evaluate(IEvaluationContext* context) const; - void CollectExpressionInfo(ExpressionInfo* info); + void CollectExpressionInfo(ExpressionInfo* info) const; bool operator==(const Object* object) const; QString ToString() const; protected: - uint ComputeHashCode(); + uint ComputeHashCode() const ; }; } // namespace berry #endif // __BERRY_SYSTEM_TEXT_EXPRESSION_H__ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.cpp index d3e9229e31..97a48c8965 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.cpp @@ -1,190 +1,190 @@ /*=================================================================== 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 "berryTestExpression.h" #include "berryExpressions.h" #include "berryExpressionStatus.h" #include "berryPlatform.h" #include "berryCoreException.h" #include #include namespace berry { const QChar TestExpression::PROP_SEP = '.'; const QString TestExpression::ATT_PROPERTY = "property"; const QString TestExpression::ATT_ARGS = "args"; const QString TestExpression::ATT_FORCE_PLUGIN_ACTIVATION = "forcePluginActivation"; TypeExtensionManager TestExpression::fgTypeExtensionManager("propertyTesters"); const uint TestExpression::HASH_INITIAL= qHash("berry::TextExpression"); TestExpression::TestExpression(const IConfigurationElement::Pointer& element) { QString property = element->GetAttribute(ATT_PROPERTY); int pos = property.lastIndexOf(PROP_SEP); if (pos == -1) { IStatus::Pointer status(new ExpressionStatus( ExpressionStatus::NO_NAMESPACE_PROVIDED, "The property attribute of the test expression must be qualified by a name space.", BERRY_STATUS_LOC)); throw CoreException(status); } fNamespace = property.left(pos); fProperty = property.mid(pos + 1); fArgs = Expressions::GetArguments(element, ATT_ARGS); fExpectedValue = Expressions::ConvertArgument(element->GetAttribute(ATT_VALUE)); fForcePluginActivation = Expressions::GetOptionalBooleanAttribute(element, ATT_FORCE_PLUGIN_ACTIVATION); } TestExpression::TestExpression(Poco::XML::Element* element) { QString property= QString::fromStdString(element->getAttribute(ATT_PROPERTY.toStdString())); int pos = property.lastIndexOf(PROP_SEP); if (pos == -1) { IStatus::Pointer status(new ExpressionStatus( ExpressionStatus::NO_NAMESPACE_PROVIDED, "The property attribute of the test expression must be qualified by a name space.", BERRY_STATUS_LOC)); throw CoreException(status); } fNamespace = property.left(pos); fProperty = property.mid(pos + 1); fArgs = Expressions::GetArguments(element, ATT_ARGS); std::string value = element->getAttribute(ATT_VALUE.toStdString()); fExpectedValue = Expressions::ConvertArgument(value.size() > 0 ? QString::fromStdString(value) : QString()); fForcePluginActivation = Expressions::GetOptionalBooleanAttribute(element, ATT_FORCE_PLUGIN_ACTIVATION); } TestExpression::TestExpression(const QString& namespaze, const QString& property, const QList& args, Object::Pointer expectedValue) : fNamespace(namespaze), fProperty(property), fArgs(args), fExpectedValue(expectedValue), fForcePluginActivation(false) { } TestExpression::TestExpression(const QString &namespaze, const QString &property, const QList& args, Object::Pointer expectedValue, bool forcePluginActivation) : fNamespace(namespaze), fProperty(property), fArgs(args), fExpectedValue(expectedValue), fForcePluginActivation(forcePluginActivation) { } EvaluationResult::ConstPointer TestExpression::Evaluate(IEvaluationContext* context) const { - Object::Pointer element(context->GetDefaultVariable()); + Object::ConstPointer element(context->GetDefaultVariable()); if (typeid(Platform) == typeid(element.GetPointer())) { QString str = Platform::GetProperty(fProperty); if (str.isEmpty()) { return EvaluationResult::FALSE_EVAL; } ObjectString::Pointer var = fArgs[0].Cast(); if (var) return EvaluationResult::ValueOf(static_cast(*var) == str); return EvaluationResult::FALSE_EVAL; } Property::Pointer property= fgTypeExtensionManager.GetProperty(element, fNamespace, fProperty, context->GetAllowPluginActivation() && fForcePluginActivation); if (!property->IsInstantiated()) return EvaluationResult::NOT_LOADED; return EvaluationResult::ValueOf(property->Test(element, fArgs, fExpectedValue)); } void -TestExpression::CollectExpressionInfo(ExpressionInfo* info) +TestExpression::CollectExpressionInfo(ExpressionInfo* info) const { info->MarkDefaultVariableAccessed(); info->AddAccessedPropertyName(fNamespace + PROP_SEP + fProperty); } bool TestExpression::operator==(const Object* object) const { if (const TestExpression* that = dynamic_cast(object)) { return this->fNamespace == that->fNamespace && this->fProperty == that->fProperty && this->fForcePluginActivation == that->fForcePluginActivation && this->Equals(this->fArgs, that->fArgs) && this->fExpectedValue == that->fExpectedValue; } return false; } -uint TestExpression::ComputeHashCode() +uint TestExpression::ComputeHashCode() const { return HASH_INITIAL * HASH_FACTOR + this->HashCode(fArgs) * HASH_FACTOR + fExpectedValue->HashCode() * HASH_FACTOR + qHash(fNamespace) * HASH_FACTOR + qHash(fProperty) * HASH_FACTOR + (fForcePluginActivation ? 1 : 0); } QString TestExpression::ToString() const { QString args(""); - for (unsigned int i= 0; i < fArgs.size(); i++) + for (int i= 0; i < fArgs.size(); i++) { Object::Pointer arg= fArgs[i]; ObjectString::Pointer strarg = arg.Cast(); if (strarg) { args.append('\''); args.append(static_cast(*strarg)); args.append('\''); } else { args.append(arg->ToString()); } if (i < fArgs.size() - 1) args.append(", "); } return "ToString() + "\"" : "\"") + " plug-in activation: " + (fForcePluginActivation ? "eager" : "lazy") + "/>"; } //---- testing --------------------------------------------------- bool TestExpression::TestGetForcePluginActivation() { return fForcePluginActivation; } TypeExtensionManager& TestExpression::TestGetTypeExtensionManager() { return fgTypeExtensionManager; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.h index 5d57871f11..f8807fc433 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.h @@ -1,93 +1,93 @@ /*=================================================================== 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 __BERRY_TEST_EXPRESSION_H__ #define __BERRY_TEST_EXPRESSION_H__ #include "berryExpression.h" #include "berryTypeExtensionManager.h" #include "berryObject.h" #include "Poco/DOM/Element.h" namespace berry { struct IConfigurationElement; class TestExpression : public Expression { private: QString fNamespace; QString fProperty; QList fArgs; Object::Pointer fExpectedValue; bool fForcePluginActivation; static const QChar PROP_SEP; static const QString ATT_PROPERTY; static const QString ATT_ARGS; static const QString ATT_FORCE_PLUGIN_ACTIVATION; /** * The seed for the hash code for all test expressions. */ static const uint HASH_INITIAL; static TypeExtensionManager fgTypeExtensionManager; public: TestExpression(const SmartPointer& element); TestExpression(Poco::XML::Element* element); TestExpression(const QString& namespaze, const QString& property, const QList& args, Object::Pointer expectedValue); TestExpression(const QString& namespaze, const QString& property, const QList& args, Object::Pointer expectedValue, bool forcePluginActivation); EvaluationResult::ConstPointer Evaluate(IEvaluationContext* context) const; - void CollectExpressionInfo(ExpressionInfo* info); + void CollectExpressionInfo(ExpressionInfo* info) const; bool operator==(const Object* object) const; protected: - uint ComputeHashCode(); + uint ComputeHashCode() const; //---- Debugging --------------------------------------------------- /* (non-Javadoc) * @see java.lang.Object#toString() */ public: QString ToString() const; //---- testing --------------------------------------------------- bool TestGetForcePluginActivation(); static TypeExtensionManager& TestGetTypeExtensionManager(); }; } // namespace berry #endif // __BERRY_TEST_EXPRESSION_H__ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtension.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtension.cpp index 96fad6796a..79459c51fd 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtension.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtension.cpp @@ -1,123 +1,123 @@ /*=================================================================== 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 "berryTypeExtension.h" #include "berryTypeExtensionManager.h" #include "berryPropertyTesterDescriptor.h" #include "berryPropertyTester.h" #include "berryExpressionStatus.h" #include namespace berry { TypeExtension::TypeExtension(const QString& typeInfo) : fTypeInfo(typeInfo), fExtendersLoaded(false), fExtendsLoaded(false) { } IPropertyTester::Pointer TypeExtension::FindTypeExtender( TypeExtensionManager& manager, const QString& namespaze, const QString& method, bool staticMethod, bool forcePluginActivation) { if (!fExtendersLoaded) { fExtenders = manager.LoadTesters(fTypeInfo); fExtendersLoaded = true; } IPropertyTester::Pointer result; // handle extenders associated with this type extender - for (unsigned int i= 0; i < fExtenders.size(); i++) + for (int i= 0; i < fExtenders.size(); i++) { IPropertyTester::Pointer extender = fExtenders[i]; if (extender.IsNull() || !extender->Handles(namespaze, method)) continue; if (extender->IsInstantiated()) { // There is no need to check for an active plug-in here. If a plug-in // gets uninstalled we receive an registry event which will flush the whole // type extender cache and will reinstantiate the testers. However Bundle#stop // isn't handled by this. According to bug https://bugs.blueberry.org/bugs/show_bug.cgi?id=130338 // we don't have to support stop in 3.2. If we have to in the future we have to // reactivate the stopped plug-in if we are in forcePluginActivation mode. return extender; } else { if (extender->IsDeclaringPluginActive() || forcePluginActivation) { PropertyTesterDescriptor::Pointer descriptor = extender.Cast(); if (!descriptor.IsNull()) { try { IPropertyTester::Pointer inst(descriptor->Instantiate()); inst.Cast()->InternalInitialize(descriptor); fExtenders[i]= extender = inst; return extender; } catch (const CoreException& e) { fExtenders[i] = IPropertyTester::Pointer(); throw e; } } else { fExtenders[i]= IPropertyTester::Pointer(); IStatus::Pointer status(new ExpressionStatus(ExpressionStatus::TYPE_EXTENDER_INCORRECT_TYPE, "The implementation class is not a sub type of berry::PropertyTester", BERRY_STATUS_LOC)); throw CoreException(status); } } else { return extender; } } } // there is no inheritance for static methods if (staticMethod) return CONTINUE_::Pointer(new CONTINUE_()); // handle inheritance chain // TODO Reflection // if (!fExtendsLoaded) { // fExtends.clear(); // Object::ExtTypeInfo types(fTypeInfo); // while (!types.m_TypeNames.empty()) { // types.m_TypeNames.pop_back(); // types.m_TypeInfos.pop_back(); // fExtends.push_back(manager.Get(types)); // } // fExtendsLoaded = true; // } // for (unsigned int i= 0; i < fExtends.size(); i++) { // result = fExtends[i]->FindTypeExtender(manager, namespaze, method, staticMethod, forcePluginActivation); // if (result.Cast().IsNull()) // return result; // } return CONTINUE_::Pointer(new CONTINUE_()); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtension.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtension.h index 516fb62e14..47e044eec7 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtension.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtension.h @@ -1,109 +1,109 @@ /*=================================================================== 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 BERRYTYPEEXTENSION_H_ #define BERRYTYPEEXTENSION_H_ #include #include #include "berryIPropertyTester.h" namespace berry { class TypeExtensionManager; class END_POINT_; class TypeExtension : public Object { public: berryObjectMacro(TypeExtension); private: /* the type this extension is extending */ QString fTypeInfo; /* the list of associated extenders */ QList fExtenders; bool fExtendersLoaded; /* the extensions associated with fType's super classes */ QList fExtends; bool fExtendsLoaded; TypeExtension() : fExtendersLoaded(false), fExtendsLoaded(false) { // special constructor to create the CONTINUE instance } protected: friend class TypeExtensionManager; /* a special property tester instance that is used to signal that method searching has to continue */ /* package */ class CONTINUE_ : public IPropertyTester { public: berryObjectMacro(CONTINUE_); bool Handles(const QString& /*namespaze*/, const QString& /*method*/) { return false; } bool IsInstantiated() { return true; } bool IsDeclaringPluginActive() { return true; } IPropertyTester* Instantiate() { return this; } - bool Test(Object::Pointer /*receiver*/, const QString& /*method*/, + bool Test(Object::ConstPointer /*receiver*/, const QString& /*method*/, const QList& /*args*/, Object::Pointer /*expectedValue*/) { return false; } }; static const CONTINUE_ CONTINUE; static const END_POINT_ END_POINT; /* package */ TypeExtension(const QString &typeInfo); /* package */ IPropertyTester::Pointer FindTypeExtender(TypeExtensionManager& manager, const QString &namespaze, const QString &method, bool staticMethod, bool forcePluginActivation); }; /* a special type extension instance that marks the end of an evaluation chain */ class END_POINT_ : public TypeExtension { protected: IPropertyTester::Pointer FindTypeExtender(TypeExtensionManager& /*manager*/, const QString& /*namespaze*/, const QString& /*name*/, bool /*staticMethod*/, bool /*forcePluginActivation*/) { return CONTINUE_::Pointer(new CONTINUE_()); } }; } // namespace berry #endif /*BERRYTYPEEXTENSION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtensionManager.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtensionManager.cpp index 465e2295d4..139559f5a9 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtensionManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtensionManager.cpp @@ -1,167 +1,167 @@ /*=================================================================== 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 "berryLog.h" #include "berryTypeExtensionManager.h" #include "berryExpressions.h" #include "berryExpressionStatus.h" #include "berryPropertyTesterDescriptor.h" #include "berryPlatform.h" #include "berryCoreException.h" #include #include namespace berry { const QString TypeExtensionManager::TYPE= "type"; TypeExtensionManager::TypeExtensionManager(const QString& extensionPoint) : fExtensionPoint(extensionPoint) { //Platform.getExtensionRegistry().addRegistryChangeListener(this); this->InitializeCaches(); } - Property::Pointer TypeExtensionManager::GetProperty(Object::Pointer receiver, + Property::Pointer TypeExtensionManager::GetProperty(Object::ConstPointer receiver, const QString& namespaze, const QString& method) { return GetProperty(receiver, namespaze, method, false); } /*synchronized*/Property::Pointer TypeExtensionManager::GetProperty( - Object::Pointer receiver, const QString& namespaze, + Object::ConstPointer receiver, const QString& namespaze, const QString& method, bool forcePluginActivation) { std::clock_t start= 0; if (Expressions::TRACING) start = std::clock(); // if we call a static method than the receiver is the class object //Class clazz= receiver instanceof Class ? (Class)receiver : receiver.getClass(); Property::Pointer result(new Property(receiver, namespaze, method)); Property::Pointer cached(fPropertyCache->Get(result)); if (!cached.isNull()) { if (cached->IsValidCacheEntry(forcePluginActivation)) { if (Expressions::TRACING) { BERRY_INFO << "[Type Extension] - method " << receiver->ToString() << "#" << method.toStdString() << " found in cache: " << (double(std::clock() - start))/(CLOCKS_PER_SEC/1000) << " ms."; } return cached; } // The type extender isn't loaded in the cached method but can be loaded // now. So remove method from cache and do the normal look up so that the // implementation class gets loaded. fPropertyCache->Remove(cached); } TypeExtension::Pointer extension(this->Get(receiver->GetClassName())); IPropertyTester::Pointer extender(extension->FindTypeExtender(*this, namespaze, method, false /*receiver instanceof Class*/, forcePluginActivation)); if (!extender.Cast().IsNull() || extender.IsNull()) { QString msg("Unknown method for "); msg.append(receiver->GetClassName()); IStatus::Pointer status(new ExpressionStatus(ExpressionStatus::TYPE_EXTENDER_UNKOWN_METHOD, QString("No property tester contributes a property %1 to type %2") .arg(namespaze + "::" + method).arg(receiver->GetClassName()), BERRY_STATUS_LOC)); throw CoreException(status); } result->SetPropertyTester(extender); fPropertyCache->Put(result); if (Expressions::TRACING) { BERRY_INFO << "[Type Extension] - method " << typeid(receiver).name() << "#" << method << " not found in cache: " << (double(std::clock() - start))/(CLOCKS_PER_SEC/1000) << " ms."; } return result; } /* package */TypeExtension::Pointer TypeExtensionManager::Get(const QString& type) { TypeExtension::Pointer result(fTypeExtensionMap[type]); if (result.IsNull()) { result = new TypeExtension(type); fTypeExtensionMap[type] = result; } return result; } QList TypeExtensionManager::LoadTesters(const QString& typeName) { if (fConfigurationElementMap.isEmpty()) { IExtensionRegistry* registry = Platform::GetExtensionRegistry(); QList ces( registry->GetConfigurationElementsFor(QString("org.blueberry.core.expressions.") + fExtensionPoint)); - for (unsigned int i= 0; i < ces.size(); i++) + for (int i= 0; i < ces.size(); i++) { IConfigurationElement::Pointer config(ces[i]); QString typeAttr = config->GetAttribute(TYPE); fConfigurationElementMap[typeAttr].push_back(config); } } //std::string typeName= type.getName(); QList typeConfigs = fConfigurationElementMap.take(typeName); QList result; - for (unsigned int i= 0; i < typeConfigs.size(); i++) + for (int i= 0; i < typeConfigs.size(); i++) { IConfigurationElement::Pointer config(typeConfigs[i]); try { IPropertyTester::Pointer descr(new PropertyTesterDescriptor(config)); result.push_back(descr); } - catch (const CoreException& e) + catch (const CoreException& /*e*/) { //TODO //ExpressionPlugin.getDefault().getLog().log(e.getStatus()); IPropertyTester::Pointer nullTester(new NULL_PROPERTY_TESTER_()); result.push_back(nullTester); } } return result; } /*synchronized*/void TypeExtensionManager::InitializeCaches() { fPropertyCache = new PropertyCache(1000); fConfigurationElementMap.clear(); fTypeExtensionMap.clear(); } TypeExtensionManager::~TypeExtensionManager() { if (fPropertyCache) delete fPropertyCache; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtensionManager.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtensionManager.h index 98719edd2d..144bd59507 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtensionManager.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtensionManager.h @@ -1,125 +1,125 @@ /*=================================================================== 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 BERRYTYPEEXTENSIONMANAGER_H_ #define BERRYTYPEEXTENSIONMANAGER_H_ #include "berryIPropertyTester.h" #include "berryTypeExtension.h" #include "berryPropertyCache.h" #include "berryProperty.h" #include #include #include namespace berry { class TypeExtensionManager { // implements IRegistryChangeListener { private: QString fExtensionPoint; static const QString TYPE; class NULL_PROPERTY_TESTER_ : public IPropertyTester { public: bool Handles(const QString& /*namespaze*/, const QString& /*property*/) { return false; } bool IsInstantiated() { return true; } bool IsDeclaringPluginActive() { return true; } IPropertyTester* Instantiate() { return this; } - bool Test(Object::Pointer, const QString& /*property*/, + bool Test(Object::ConstPointer, const QString& /*property*/, const QList& /*args*/, Object::Pointer /*expectedValue*/) { return false; } }; static const NULL_PROPERTY_TESTER_ NULL_PROPERTY_TESTER; /* * Map containing all already created type extension object. */ QHash fTypeExtensionMap; /* * Table containing mapping of class name to configuration element */ QHash > fConfigurationElementMap; /* * A cache to give fast access to the last 1000 method invocations. */ PropertyCache* fPropertyCache; public: TypeExtensionManager(const QString& extensionPoint); ~TypeExtensionManager(); - Property::Pointer GetProperty(Object::Pointer receiver, + Property::Pointer GetProperty(Object::ConstPointer receiver, const QString& namespaze, const QString& method); - /*synchronized*/Property::Pointer GetProperty(Object::Pointer receiver, + /*synchronized*/Property::Pointer GetProperty(Object::ConstPointer receiver, const QString& namespaze, const QString& method, bool forcePluginActivation); protected: friend class TypeExtension; /* * This method doesn't need to be synchronized since it is called * from withing the getProperty method which is synchronized */ /* package */TypeExtension::Pointer Get(const QString& type); /* * This method doesn't need to be synchronized since it is called * from withing the getProperty method which is synchronized */ /* package */QList LoadTesters(const QString& typeName); // public void registryChanged(IRegistryChangeEvent event) { // IExtensionDelta[] deltas= event.getExtensionDeltas(ExpressionPlugin.getPluginId(), fExtensionPoint); // if (deltas.length > 0) { // initializeCaches(); // } // } private: /*synchronized*/void InitializeCaches(); }; } #endif /*BERRYTYPEEXTENSIONMANAGER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryWithExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryWithExpression.cpp index 6421880031..d863c714f3 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryWithExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryWithExpression.cpp @@ -1,99 +1,99 @@ /*=================================================================== 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 "berryWithExpression.h" #include "berryExpressions.h" #include "berryEvaluationContext.h" #include "berryExpressionStatus.h" #include #include namespace berry { const QString WithExpression::ATT_VARIABLE= "variable"; const uint WithExpression::HASH_INITIAL= qHash("berry::WithExpression"); WithExpression::WithExpression(const IConfigurationElement::Pointer& configElement) { fVariable = configElement->GetAttribute(ATT_VARIABLE); Expressions::CheckAttribute(ATT_VARIABLE, fVariable); } WithExpression::WithExpression(Poco::XML::Element* element) { fVariable = QString::fromStdString(element->getAttribute(ATT_VARIABLE.toStdString())); Expressions::CheckAttribute(ATT_VARIABLE, fVariable.length() > 0 ? fVariable : QString()); } WithExpression::WithExpression(const QString& variable) : fVariable(variable) { } bool WithExpression::operator==(const Object* object) const { if (const WithExpression* that = dynamic_cast(object)) { return this->fVariable == that->fVariable && this->Equals(this->fExpressions, that->fExpressions); } return false; } EvaluationResult::ConstPointer WithExpression::Evaluate(IEvaluationContext* context) const { - Object::Pointer variable(context->GetVariable(fVariable)); + Object::ConstPointer variable(context->GetVariable(fVariable)); if (variable.IsNull()) { IStatus::Pointer status(new ExpressionStatus(ExpressionStatus::VARIABLE_NOT_DEFINED, QString("The variable %1 is not defined").arg(fVariable), BERRY_STATUS_LOC)); throw CoreException(status); } if (variable == IEvaluationContext::UNDEFINED_VARIABLE) { return EvaluationResult::FALSE_EVAL; } EvaluationContext::Pointer scope(new EvaluationContext(context, variable)); return this->EvaluateAnd(scope.GetPointer()); } void -WithExpression::CollectExpressionInfo(ExpressionInfo* info) +WithExpression::CollectExpressionInfo(ExpressionInfo* info) const { ExpressionInfo* other = new ExpressionInfo(); CompositeExpression::CollectExpressionInfo(other); if (other->HasDefaultVariableAccess()) { info->AddVariableNameAccess(fVariable); } info->MergeExceptDefaultVariable(other); } uint -WithExpression::ComputeHashCode() +WithExpression::ComputeHashCode() const { return HASH_INITIAL * HASH_FACTOR + this->HashCode(fExpressions) * HASH_FACTOR + qHash(fVariable); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryWithExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryWithExpression.h index 58947101f6..6050328ff9 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryWithExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryWithExpression.h @@ -1,62 +1,62 @@ /*=================================================================== 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 __BERRY_WITH_EXPRESSION_H__ #define __BERRY_WITH_EXPRESSION_H__ #include "berryCompositeExpression.h" #include "Poco/DOM/Element.h" namespace berry { struct IConfigurationElement; class WithExpression : public CompositeExpression { private: QString fVariable; static const QString ATT_VARIABLE; /** * The seed for the hash code for all with expressions. */ static const uint HASH_INITIAL; public: WithExpression(const SmartPointer& configElement); WithExpression(Poco::XML::Element* element); WithExpression(const QString &variable); bool operator==(const Object* object) const; EvaluationResult::ConstPointer Evaluate(IEvaluationContext* context) const; - void CollectExpressionInfo(ExpressionInfo* info); + void CollectExpressionInfo(ExpressionInfo* info) const; protected: - uint ComputeHashCode(); + uint ComputeHashCode() const; }; } // namespace berry #endif // __BERRY_WITH_EXPRESSION_H__ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeEvent.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeEvent.h index 54e9ef7874..cd14956f9b 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeEvent.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeEvent.h @@ -1,74 +1,74 @@ /*=================================================================== 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 BERRYIJOBCHANGEEVENT_H_ #define BERRYIJOBCHANGEEVENT_H_ #include #include #include #include #include namespace berry { class Job; /** * An event describing a change to the state of a job. * * @see IJobChangeListener * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_JOBS IJobChangeEvent : public Object { - berryInterfaceMacro(IJobChangeEvent, berry); + berryObjectMacro(berry::IJobChangeEvent) /** * The amount of time in milliseconds to wait after scheduling the job before it * should be run, or -1 if not applicable for this type of event. * This value is only applicable for the scheduled event. * * @return the delay time for this event */ virtual Poco::Timestamp::TimeDiff GetDelay() const = 0; /** * The job on which this event occurred. * * @return the job for this event */ virtual SmartPointer GetJob() const = 0; /** * The result returned by the job's run method, or null if * not applicable. This value is only applicable for the done event. * * @return the status for this event */ virtual IStatus::Pointer GetResult() const = 0; }; } #endif /* BERRYIJOBCHANGEEVENT_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeListener.cpp b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeListener.cpp index 5999b261fb..fec2a93a3d 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeListener.cpp @@ -1,73 +1,66 @@ /*=================================================================== 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 "berryIJobChangeListener.h" namespace berry { -void IJobChangeListener::Events::AddListener( - IJobChangeListener::Pointer listener) +void IJobChangeListener::Events::AddListener(IJobChangeListener* listener) { if (!listener) return; Types types = listener->GetEventTypes(); if (types & ABOUT_TO_RUN) - jobAboutToRun += Delegate(listener.GetPointer(), - &IJobChangeListener::AboutToRun); + jobAboutToRun += Delegate(listener, &IJobChangeListener::AboutToRun); if (types & AWAKE) - jobAwake += Delegate(listener.GetPointer(), &IJobChangeListener::Awake); + jobAwake += Delegate(listener, &IJobChangeListener::Awake); if (types & DONE) - jobDone += Delegate(listener.GetPointer(), &IJobChangeListener::Done); + jobDone += Delegate(listener, &IJobChangeListener::Done); if (types & RUNNING) - jobRunning += Delegate(listener.GetPointer(), &IJobChangeListener::Running); + jobRunning += Delegate(listener, &IJobChangeListener::Running); if (types & SCHEDULED) - jobScheduled += Delegate(listener.GetPointer(), - &IJobChangeListener::Scheduled); + jobScheduled += Delegate(listener, &IJobChangeListener::Scheduled); if (types & SLEEPING) - jobSleeping += Delegate(listener.GetPointer(), - &IJobChangeListener::Sleeping); + jobSleeping += Delegate(listener, &IJobChangeListener::Sleeping); } -void IJobChangeListener::Events::RemoveListener( - IJobChangeListener::Pointer listener) +void IJobChangeListener::Events::RemoveListener(IJobChangeListener* listener) { if (!listener) return; - jobAboutToRun -= Delegate(listener.GetPointer(), - &IJobChangeListener::AboutToRun); - jobAwake -= Delegate(listener.GetPointer(), &IJobChangeListener::Awake); - jobDone -= Delegate(listener.GetPointer(), &IJobChangeListener::Done); - jobRunning -= Delegate(listener.GetPointer(), &IJobChangeListener::Running); - jobScheduled -= Delegate(listener.GetPointer(), - &IJobChangeListener::Scheduled); - jobSleeping -= Delegate(listener.GetPointer(), &IJobChangeListener::Sleeping); + jobAboutToRun -= Delegate(listener, &IJobChangeListener::AboutToRun); + jobAwake -= Delegate(listener, &IJobChangeListener::Awake); + jobDone -= Delegate(listener, &IJobChangeListener::Done); + jobRunning -= Delegate(listener, &IJobChangeListener::Running); + jobScheduled -= Delegate(listener, &IJobChangeListener::Scheduled); + jobSleeping -= Delegate(listener, &IJobChangeListener::Sleeping); } void IJobChangeListener::Events::SetExceptionHandler(const AbstractExceptionHandler& handler) { jobAboutToRun.SetExceptionHandler(handler); jobAwake.SetExceptionHandler(handler); jobDone.SetExceptionHandler(handler); jobRunning.SetExceptionHandler(handler); jobScheduled.SetExceptionHandler(handler); jobSleeping.SetExceptionHandler(handler); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeListener.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeListener.h index f26ab13606..24ab1c42b7 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeListener.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeListener.h @@ -1,165 +1,159 @@ /*=================================================================== 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 BERRYIJOBCHANGELISTENER_H_ #define BERRYIJOBCHANGELISTENER_H_ #include "berryIJobChangeEvent.h" namespace berry { /** * Callback interface for clients interested in being notified when jobs change state. *

* A single job listener instance can be added either to the job manager, for notification * of all scheduled jobs, or to any set of individual jobs. A single listener instance should * not be added to both the job manager, and to individual jobs (such a listener may * receive duplicate notifications). *

* Clients should not rely on the result of the Job#GetState() * method on jobs for which notification is occurring. Listeners are notified of * all job state changes, but whether the state change occurs before, during, or * after listeners are notified is unspecified. *

* Clients may implement this interface. *

* @see IJobManager#AddJobChangeListener(IJobChangeListener::Pointer) * @see IJobManager#RemoveJobChangeListener(IJobChangeListener::Pointer) * @see Job#AddJobChangeListener(IJobChangeListener::Pointer) * @see Job#GetState() * @see Job#RemoveJobChangeListener(IJobChangeListener::Pointer) */ -struct BERRY_JOBS IJobChangeListener: public Object +struct BERRY_JOBS IJobChangeListener { -berryInterfaceMacro(IJobChangeListener, berry); + berryObjectMacro(berry::IJobChangeListener) struct BERRY_JOBS Events { - typedef Message1 JobChangeEventType; + typedef Message1 JobChangeEventType; enum Type { NONE = 0x00000000, ABOUT_TO_RUN = 0x00000001, AWAKE = 0x00000002, DONE = 0x00000004, RUNNING = 0x00000008, SCHEDULED = 0x00000010, SLEEPING = 0x00000020, ALL = 0xffffffff }; - BERRY_DECLARE_FLAGS(Types, Type) + Q_DECLARE_FLAGS(Types, Type) JobChangeEventType jobAboutToRun; JobChangeEventType jobAwake; JobChangeEventType jobDone; JobChangeEventType jobRunning; JobChangeEventType jobScheduled; JobChangeEventType jobSleeping; - void AddListener(IJobChangeListener::Pointer listener); - void RemoveListener(IJobChangeListener::Pointer listener); + void AddListener(IJobChangeListener* listener); + void RemoveListener(IJobChangeListener* listener); void SetExceptionHandler(const AbstractExceptionHandler& handler); - typedef MessageDelegate1 + typedef MessageDelegate1 Delegate; }; virtual Events::Types GetEventTypes() = 0; /** * Notification that a job is about to be run. Listeners are allowed to sleep, cancel, * or change the priority of the job before it is started (and as a result may prevent * the run from actually occurring). * * @param event the event details */ - virtual void AboutToRun(const IJobChangeEvent::ConstPointer /*event*/) + virtual void AboutToRun(const IJobChangeEvent::ConstPointer& /*event*/) { } - ; /** * Notification that a job was previously sleeping and has now been rescheduled * to run. * * @param event the event details */ - virtual void Awake(const IJobChangeEvent::ConstPointer /*event*/) + virtual void Awake(const IJobChangeEvent::ConstPointer& /*event*/) { } - ; /** * Notification that a job has completed execution, either due to cancelation, successful * completion, or failure. The event status object indicates how the job finished, * and the reason for failure, if applicable. * * @param event the event details */ - virtual void Done(const IJobChangeEvent::ConstPointer /*event*/) + virtual void Done(const IJobChangeEvent::ConstPointer& /*event*/) { } - ; /** * Notification that a job has started running. * * @param event the event details */ - virtual void Running(const IJobChangeEvent::ConstPointer /*event*/) + virtual void Running(const IJobChangeEvent::ConstPointer& /*event*/) { } - ; /** * Notification that a job is being added to the queue of scheduled jobs. * The event details includes the scheduling delay before the job should start * running. * * @param event the event details, including the job instance and the scheduling * delay */ - virtual void Scheduled(const IJobChangeEvent::ConstPointer /*event*/) + virtual void Scheduled(const IJobChangeEvent::ConstPointer& /*event*/) { } - ; /** * Notification that a job was waiting to run and has now been put in the * sleeping state. * * @param event the event details */ - virtual void Sleeping(const IJobChangeEvent::ConstPointer /*event*/) + virtual void Sleeping(const IJobChangeEvent::ConstPointer& /*event*/) { } - ; }; } -BERRY_DECLARE_OPERATORS_FOR_FLAGS(berry::IJobChangeListener::Events::Types) +Q_DECLARE_OPERATORS_FOR_FLAGS(berry::IJobChangeListener::Events::Types) #endif /* BERRYIJOBCHANGELISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobManager.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobManager.h index 1eb6c6f5d0..92e13b6778 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobManager.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobManager.h @@ -1,440 +1,440 @@ /*=================================================================== 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 _BERRY_IJOBMANAGER_H #define _BERRY_IJOBMANAGER_H #include #include #include "berryJob.h" #include "berryProgressProvider.h" #include "berryIProgressMonitor.h" #include "berryIJobChangeListener.h" #include namespace berry { /** * The job manager provides facilities for scheduling, querying, and maintaining jobs * and locks. In particular, the job manager provides the following services: *
    *
  • Maintains a queue of jobs that are waiting to be run. Items can be added to * the queue using the schedule method.
  • *
  • @todo Allows manipulation of groups of jobs called job families. } Job families can * be canceled, put to sleep, or woken up atomically. There is also a mechanism * for querying the set of known jobs in a given family.>
  • * *
  • Allows listeners to find out about progress on running jobs, and to find out * when jobs have changed states.
  • *
  • @todo Provides a factory for creating lock objects. Lock objects are smart monitors * that have strategies for avoiding deadlock. >
  • * *
  • Provide feedback to a client that is waiting for a given job or family of jobs * to complete.
  • *
* * @see Job * @see ILock * * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_JOBS IJobManager: public Object { - berryInterfaceMacro(IJobManager, berry); + berryObjectMacro(berry::IJobManager) /** * A system property key indicating whether the job manager should create * job threads as daemon threads. Set to true to force all worker * threads to be created as daemon threads. Set to false to force * all worker threads to be created as non-daemon threads. * * not used yet */ static const std::string PROP_USE_DAEMON_THREADS ; /** * Registers a job listener with the job manager. * Has no effect if an identical listener is already registered. * * @param listener the listener to be added * @see #removeJobChangeListener(IJobChangeListener) * @see IJobChangeListener */ - virtual void AddJobChangeListener(IJobChangeListener::Pointer listener) = 0; + virtual void AddJobChangeListener(IJobChangeListener* listener) = 0; ///** // * Begins applying this rule in the calling thread. If the rule conflicts with another // * rule currently running in another thread, this method blocks until there are // * no conflicting rules. Calls to beginRule must eventually be followed // * by a matching call to endRule in the same thread and with the identical // * rule instance. // *

// * Rules can be nested only if the rule for the inner beginRule // * is contained within the rule for the outer beginRule. Rule containment // * is tested with the API method ISchedulingRule.contains. Also, begin/end // * pairs must be strictly nested. Only the rule that has most recently begun // * can be ended at any given time. // *

// * A rule of null can be used, but will be ignored for scheduling // * purposes. The outermost non-null rule in the thread will be used for scheduling. A // * null rule that is begun must still be ended. // *

// * If this method is called from within a job that has a scheduling rule, the // * given rule must also be contained within the rule for the running job. // *

// * Note that endRule must be called even if beginRule fails. // * The recommended usage is: // *

   // * final ISchedulingRule rule = ...;
   // * try {
   // *   manager.beginRule(rule, monitor);
   // * } finally {
   // *   manager.endRule(rule);
   // * }
   // * 
// * // * @param rule the rule to begin applying in this thread, or null // * @param monitor a progress monitor, or null if progress // * reporting and cancellation are not desired // * @throws IllegalArgumentException if the rule is not strictly nested within // * all other rules currently active for this thread // * @throws OperationCanceledException if the supplied monitor reports cancelation // * before the rule becomes available // * @see ISchedulingRule#contains(ISchedulingRule) // */ /// virtual void BeginRule(const ISchedulingRule& rule, const IProgressMonitor& monitor) = 0; ///** // * Cancels all jobs in the given job family. Jobs in the family that are currently waiting // * will be removed from the queue. Sleeping jobs will be discarded without having // * a chance to wake up. Currently executing jobs will be asked to cancel but there // * is no guarantee that they will do so. // * // * @param family the job family to cancel, or null to cancel all jobs // * @see Job#belongsTo(Object) // */ /// virtual void Cancel(const Object& family); /** * Returns a progress monitor that can be used to provide * aggregated progress feedback on a set of running jobs. A user * interface will typically group all jobs in a progress group together, * providing progress feedback for individual jobs as well as aggregated * progress for the entire group. Jobs in the group may be run sequentially, * in parallel, or some combination of the two. *

* Recommended usage (this snippet runs two jobs in sequence in a * single progress group): *

    *    Job parseJob, compileJob;
    *    IProgressMonitor pm = Platform.getJobManager().createProgressGroup();
    *    try {
    *       pm.beginTask("Building", 10);
    *       parseJob.setProgressGroup(pm, 5);
    *       parseJob.schedule();
    *       compileJob.setProgressGroup(pm, 5);
    *       compileJob.schedule();
    *       parseJob.join();
    *       compileJob.join();
    *    } finally {
    *       pm.done();
    *    }
    * 
* * @see Job#setProgressGroup(IProgressMonitor, int) * @see IProgressMonitor * @return a progress monitor */ virtual IProgressMonitor::Pointer CreateProgressGroup() = 0; ///** // * Returns the job that is currently running in this thread, or null if there // * is no currently running job. // * // * @return the job or null // */ //// virtual Job CurrentJob() = 0; ///** // * Ends the application of a rule to the calling thread. Calls to endRule // * must be preceded by a matching call to beginRule in the same thread // * with an identical rule instance. // *

// * Rules can be nested only if the rule for the inner beginRule // * is contained within the rule for the outer beginRule. Also, begin/end // * pairs must be strictly nested. Only the rule that has most recently begun // * can be ended at any given time. // * // * @param rule the rule to end applying in this thread // * @throws IllegalArgumentException if this method is called on a rule for which // * there is no matching begin, or that does not match the most recent begin. // * @see ISchedulingRule#contains(ISchedulingRule) // */ /// virtual void EndRule(const ISchedulingRule& rule) = 0; ///** // * Returns all waiting, executing and sleeping jobs belonging // * to the given family. If no jobs are found, an empty array is returned. // * // * @param family the job family to find, or null to find all jobs // * @return the job array // * @see Job#belongsTo(Object) // */ /// virtual Job[] Find(const Object& family) = 0; /** * Returns whether the job manager is currently idle. The job manager is * idle if no jobs are currently running or waiting to run. * * @return true if the job manager is idle, and * false otherwise * @since 3.1 */ virtual bool IsIdle()= 0; /** * Returns whether the job manager is currently suspended. * * @return true if the job manager is suspended, and * false otherwise * @since 3.4 * @see #suspend() * @see #resume() */ virtual bool IsSuspended() = 0; ///** // * Waits until all jobs of the given family are finished. This method will block the // * calling thread until all such jobs have finished executing, or until this thread is // * interrupted. If there are no jobs in // * the family that are currently waiting, running, or sleeping, this method returns // * immediately. Feedback on how the join is progressing is provided to a progress // * monitor. // *

// * If this method is called while the job manager is suspended, only jobs // * that are currently running will be joined; Once there are no jobs // * in the family in the {@link Job#RUNNING} state, this method returns. // *

// *

// * Note that there is a deadlock risk when using join. If the calling thread owns // * a lock or object monitor that the joined thread is waiting for, deadlock // * will occur. This method can also result in starvation of the current thread if // * another thread continues to add jobs of the given family, or if a // * job in the given family reschedules itself in an infinite loop. // *

// * // * @param family the job family to join, or null to join all jobs. // * @param monitor Progress monitor for reporting progress on how the // * wait is progressing, or null if no progress monitoring is required. // * @exception InterruptedException if this thread is interrupted while waiting // * @exception OperationCanceledException if the progress monitor is canceled while waiting // * @see Job#belongsTo(Object) // * @see #suspend() // */ /// virtual void Join(const Object& family, const IProgressMonitor& monitor) /// throw(InterruptedException, OperationCanceledException) = 0; ///** // * Creates a new lock object. All lock objects supplied by the job manager // * know about each other and will always avoid circular deadlock amongst // * themselves. // * // * @return the new lock object // */ /// virtual ILock newLock() = 0; /** * Removes a job listener from the job manager. * Has no effect if an identical listener is not already registered. * * @param listener the listener to be removed * @see #addJobChangeListener(IJobChangeListener) * @see IJobChangeListener */ - virtual void RemoveJobChangeListener(IJobChangeListener::Pointer listener) = 0; + virtual void RemoveJobChangeListener(IJobChangeListener* listener) = 0; ///** // * Resumes execution of jobs after a previous suspend. All // * jobs that were sleeping or waiting prior to the suspension, or that were // * scheduled while the job manager was suspended, will now be eligible // * for execution. // *

// * Calling this method on a rule that is not suspended has no effect. If another // * thread also owns the rule at the time this method is called, then the rule will // * not be resumed until all threads have released the rule. // * // * @deprecated This method is not safe and should not be used. // * Suspending a scheduling rule violates the thread safety // * of clients that use scheduling rules as a mutual exclusion mechanism, // * and can result in concurrency problems in all clients that use the suspended rule. // * @see #suspend(ISchedulingRule, IProgressMonitor) // */ /// virtual void Resume(const ISchedulingRule& rule) = 0; ///** // * Resumes execution of jobs after a previous suspend. All // * jobs that were sleeping or waiting prior to the suspension, or that were // * scheduled while the job manager was suspended, will now be eligible // * for execution. // *

// * Calling resume when the job manager is not suspended // * has no effect. // * // * @see #suspend() // * @see #isSuspended() // */ ////virtual void Resume() = 0; ///** // * Provides a hook that is notified whenever a thread is about to wait on a lock, // * or when a thread is about to release a lock. This hook must only be set once. // *

// * This method is for internal use by the platform-related plug-ins. // * Clients should not call this method. // *

// * @see LockListener // */ // TODO LockListener .. SetLockListener /// virtual void SetLockListener(const LockListener& listener) = 0; /** * Registers a progress provider with the job manager. If there was a * provider already registered, it is replaced. *

* This method is intended for use by the currently executing Eclipse application. * Plug-ins outside the currently running application should not call this method. *

* * @param provider the new provider, or null if no progress * is needed */ virtual void SetProgressProvider(ProgressProvider::Pointer) = 0; /** * Suspends execution of all jobs. Jobs that are already running * when this method is invoked will complete as usual, but all sleeping and * waiting jobs will not be executed until the job manager is resumed. *

* The job manager will remain suspended until a subsequent call to * resume. Further calls to suspend * when the job manager is already suspended are ignored. *

* All attempts to join sleeping and waiting jobs while the job manager is * suspended will return immediately. *

* Note that this very powerful function should be used with extreme caution. * Suspending the job manager will prevent all jobs in the system from executing, * which may have adverse affects on components that are relying on * execution of jobs. The job manager should never be suspended without intent * to resume execution soon afterwards. * * @see #resume() * @see #join(Object, IProgressMonitor) * @see #isSuspended() */ // virtual void Suspend() = 0; ///** // * Defers execution of all jobs with scheduling rules that conflict with the // * given rule. The caller will be blocked until all currently executing jobs with // * conflicting rules are completed. Conflicting jobs that are sleeping or waiting at // * the time this method is called will not be executed until the rule is resumed. // *

// * While a rule is suspended, all calls to beginRule and // * endRule on a suspended rule will not block the caller. // * The rule remains suspended until a subsequent call to // * resume(ISchedulingRule) with the identical rule instance. // * Further calls to suspend with an identical rule prior to calling // * resume are ignored. // *

// *

// * This method is long-running; progress and cancelation are provided by // * the given progress monitor. In the case of cancelation, the rule will // * not be suspended. // *

// * Note: this very powerful function should be used with extreme caution. // * Suspending rules will prevent jobs in the system from executing, which may // * have adverse effects on components that are relying on execution of jobs. // * The job manager should never be suspended without intent to resume // * execution soon afterwards. Deadlock will result if the thread responsible // * for resuming the rule attempts to join a suspended job. // * // * @deprecated This method is not safe and should not be used. // * Suspending a scheduling rule violates the thread safety // * of clients that use scheduling rules as a mutual exclusion mechanism, // * and can result in concurrency problems in all clients that use the suspended rule. // * @param rule The scheduling rule to suspend. Must not be null. // * @param monitor a progress monitor, or null if progress // * reporting is not desired // * @exception OperationCanceledException if the operation is canceled. // * Cancelation can occur even if no progress monitor is provided. // * @see #resume(ISchedulingRule) // */ /// virtual void Suspend(const ISchedulingRule& rule, const IProgressMonitor& monitor) = 0; ///** // * Requests that all jobs in the given job family be suspended. Jobs currently // * waiting to be run will be removed from the queue and moved into the // * SLEEPING state. Jobs that have been put to sleep // * will remain in that state until either resumed or canceled. This method has // * no effect on jobs that are not currently waiting to be run. // *

// * Sleeping jobs can be resumed using wakeUp. // * // * @param family the job family to sleep, or null to sleep all jobs. // * @see Job#belongsTo(Object) // */ /// virtual void Sleep(const Object& family) = 0; ///** // * Transfers ownership of a scheduling rule to another thread. The identical // * scheduling rule must currently be owned by the calling thread as a result of // * a previous call to beginRule. The destination thread must // * not already own a scheduling rule. // *

// * Calling this method is equivalent to atomically calling endRule // * in the calling thread followed by an immediate beginRule in // * the destination thread. The destination thread is responsible for subsequently // * calling endRule when it is finished using the rule. // *

// * This method has no effect when the destination thread is the same as the // * calling thread. // * // * @param rule The scheduling rule to transfer // * @param destinationThread The new owner for the transferred rule. // * @since 3.1 // */ /// virtual void TransferRule(const ISchedulingRule& rule, Poco::Thread* destinationThread) = 0; ///** // * Resumes scheduling of all sleeping jobs in the given family. This method // * has no effect on jobs in the family that are not currently sleeping. // * // * @param family the job family to wake up, or null to wake up all jobs // * @see Job#belongsTo(Object) // */ /// virtual void WakeUp(const Object& family) = 0; }; } #endif /* IJOBMANAGER */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobStatus.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobStatus.h index 8e3640a319..cc07592d94 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobStatus.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobStatus.h @@ -1,45 +1,46 @@ /*=================================================================== 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 _BERRYIJOBSTATUS_H #define _BERRYIJOBSTATUS_H #include "berryIStatus.h" #include "berryObject.h" #include "berryJob.h" namespace berry { /** * Represents status relating to the execution of jobs. * @see IStatus * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ - struct IJobStatus : public IStatus { +struct IJobStatus : public virtual IStatus +{ - berryObjectMacro(IJobStatus); + berryObjectMacro(IJobStatus) /** * Returns the job associated with this status. * @return the job associated with this status */ virtual Job::Pointer GetJob() = 0; }; } #endif /*_BERRYIJOBSTATUS_H */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryILock.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryILock.h index 842f11e7d5..f1400c28dc 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryILock.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryILock.h @@ -1,125 +1,125 @@ /*=================================================================== 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 _BERRY_ILOCK_H_ #define _BERRY_ILOCK_H_ #include #include #include "berryJobExceptions.h" namespace berry { /** * A lock is used to control access to an exclusive resource. *

* Locks are reentrant. That is, they can be acquired multiple times by the same thread * without releasing. Locks are only released when the number of successful acquires * equals the number of successful releases. *

* Locks are capable of detecting and recovering from programming errors that cause * circular waiting deadlocks. When a deadlock between two or more ILock * instances is detected, detailed debugging information is printed to the log file. The * locks will then automatically recover from the deadlock by employing a release * and wait strategy. One thread will lose control of the locks it owns, thus breaking * the deadlock and allowing other threads to proceed. Once that thread's locks are * all available, it will be given exclusive access to all its locks and allowed to proceed. * A thread can only lose locks while it is waiting on an acquire() call. * *

* Successive acquire attempts by different threads are queued and serviced on * a first come, first served basis. *

* It is very important that acquired locks eventually get released. Calls to release * should be done in a finally block to ensure they execute. For example: *

  * try {
  *   lock.acquire();
  *   // ... do work here ...
  * } finally {
  *   lock.release();
  * }
  * 
* Note: although lock.acquire should never fail, it is good practice to place * it inside the try block anyway. Releasing without acquiring is far less catastrophic * than acquiring without releasing. *

* * @see IJobManager#NewLock() * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_JOBS ILock: public Object { - berryInterfaceMacro(ILock, berry); + berryObjectMacro(berry::ILock) /** * Attempts to acquire this lock. If the lock is in use and the specified delay is * greater than zero, the calling thread will block until one of the following happens: *
    *
  • This lock is available
  • *
  • The thread is interrupted
  • *
  • The specified delay has elapsed
  • *
*

* While a thread is waiting, locks it already owns may be granted to other threads * if necessary to break a deadlock. In this situation, the calling thread may be blocked * for longer than the specified delay. On returning from this call, the calling thread * will once again have exclusive access to any other locks it owned upon entering * the acquire method. * * @param delay the number of milliseconds to delay * @return true if the lock was successfully acquired, and * false otherwise. * @exception InterruptedException if the thread was interrupted */ virtual bool Acquire(long delay) throw (InterruptedException) = 0; /** * Acquires this lock. If the lock is in use, the calling thread will block until the lock * becomes available. If the calling thread owns several locks, it will be blocked * until all threads it requires become available, or until the thread is interrupted. * While a thread is waiting, its locks may be granted to other threads if necessary * to break a deadlock. On returning from this call, the calling thread will * have exclusive access to this lock, and any other locks it owned upon * entering the acquire method. *

* This implementation ignores attempts to interrupt the thread. If response to * interruption is needed, use the method acquire(long) */ virtual void Acquire(); /** * Returns the number of nested acquires on this lock that have not been released. * This is the number of times that release() must be called before the lock is * freed. * * @return the number of nested acquires that have not been released */ virtual int GetDepth() = 0; /** * Releases this lock. Locks must only be released by the thread that currently * owns the lock. */ virtual void Release() = 0; }; } #endif // BERRY_ILOCK_H diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIProgressMonitor.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIProgressMonitor.h index b0cdbb0187..3d30144562 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIProgressMonitor.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIProgressMonitor.h @@ -1,117 +1,117 @@ /*=================================================================== 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 BERRY_IPROGRESS_MONITOR_H #define BERRY_IPROGRESS_MONITOR_H #include #include "berryObject.h" #include namespace berry { struct IProgressMonitor: public Object { -berryInterfaceMacro(IProgressMonitor, berry); + berryObjectMacro(berry::IProgressMonitor) /** Constant indicating an unknown amount of work. */ static const int UNKNOWN = -1; /** * Notifies that the main task is beginning. This must only be called once * on a given progress monitor instance. * * @param name the name (or description) of the main task * @param totalWork the total number of work units into which * the main task is been subdivided. If the value is UNKNOWN * the implementation is free to indicate progress in a way which * doesn't require the total number of work units in advance. */ virtual void BeginTask(const std::string& name, int totalWork) = 0; /** * Notifies that the work is done; that is, either the main task is completed * or the user canceled it. This method may be called more than once * (implementations should be prepared to handle this case). */ virtual void Done() = 0; /** * Internal method to handle scaling correctly. This method * must not be called by a client. Clients should * always use the method worked(int). * * @param work the amount of work done */ virtual void InternalWorked(double work) = 0; /** * Returns whether cancellation of current operation has been requested. * Long-running operations should poll to see if cancellation * has been requested. * * @return true if cancellation has been requested, * and false otherwise * @see #setCanceled(bool) */ virtual bool IsCanceled() = 0; /** * Sets the cancel state to the given value. * * @param value true indicates that cancellation has * been requested (but not necessarily acknowledged); * false clears this flag * @see #isCanceled() */ virtual void SetCanceled(bool value) = 0; /** * Sets the task name to the given value. This method is used to * restore the task label after a nested operation was executed. * Normally there is no need for clients to call this method. * * @param name the name (or description) of the main task * @see #beginTask */ virtual void SetTaskName(const std::string& name) = 0; /** * Notifies that a subtask of the main task is beginning. * Subtasks are optional; the main task might not have subtasks. * * @param name the name (or description) of the subtask */ virtual void SubTask(const std::string& name) = 0; /** * Notifies that a given number of work unit of the main task * has been completed. Note that this amount represents an * installment, as opposed to a cumulative amount of work done * to date. * * @param work a non-negative number of work units just completed */ virtual void Worked(int work) = 0; }; } #endif /* _BERRY_IPROGRESS_MONITOR_H */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIProgressMonitorWithBlocking.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIProgressMonitorWithBlocking.h index 5af58bb1f8..8a169d6e88 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIProgressMonitorWithBlocking.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIProgressMonitorWithBlocking.h @@ -1,84 +1,84 @@ /*=================================================================== 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 _BERRY_IPROGRESSMONITORWITHBLOCKING_H #define _BERRY_IPROGRESSMONITORWITHBLOCKING_H #include "berryObject.h" #include #include "berryIStatus.h" #include "berryIProgressMonitor.h" namespace berry { /** * An extension to the IProgressMonitor interface for monitors that want to * support feedback when an activity is blocked due to concurrent activity in * another thread. *

* When a monitor that supports this extension is passed to an operation, the * operation should call setBlocked whenever it knows that it * must wait for a lock that is currently held by another thread. The operation * should continue to check for and respond to cancellation requests while * blocked. When the operation is no longer blocked, it must call clearBlocked * to clear the blocked state. *

* This interface can be used without OSGi running. *

* Clients may implement this interface. *

* @see IProgressMonitor */ struct BERRY_JOBS IProgressMonitorWithBlocking: public IProgressMonitor { - berryInterfaceMacro(IProgressMonitorWithBlocking, berry); + berryObjectMacro(berry::IProgressMonitorWithBlocking) /** * Indicates that this operation is blocked by some background activity. If * a running operation ever calls setBlocked, it must * eventually call clearBlocked before the operation * completes. *

* If the caller is blocked by a currently executing job, this method will return * an IJobStatus indicating the job that is currently blocking * the caller. If this blocking job is not known, this method will return a plain * informational IStatus object. *

* * @param reason an optional status object whose message describes the * reason why this operation is blocked, or null if this * information is not available. * @see #clearBlocked() */ virtual void SetBlocked(IStatus::Pointer reason)= 0; /** * Clears the blocked state of the running operation. If a running * operation ever calls setBlocked, it must eventually call * clearBlocked before the operation completes. * * @see #setBlocked(IStatus) */ virtual void ClearBlocked() = 0; }; } #endif /* _BERRY_IPROGRESSMONITORWITHBLOCKING_H */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryISchedulingRule.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryISchedulingRule.h index 32a9e049ec..2088e32f9a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryISchedulingRule.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryISchedulingRule.h @@ -1,93 +1,93 @@ /*=================================================================== 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 _BERRY_ISCHEDULING_RULE_H_ #define _BERRY_ISCHEDULING_RULE_H_ #include #include namespace berry { /** * Scheduling rules are used by jobs to indicate when they need exclusive access * to a resource. * @todo * Scheduling rules can also be applied synchronously to a thread * using IJobManager.beginRule(ISchedulingRule) and * IJobManager.endRule(ISchedulingRule). * * The job manager guarantees that * no two jobs with conflicting scheduling rules will run concurrently. * @todo * Multiple rules can be applied to a given thread only if the outer rule explicitly * allows the nesting as specified by the contains method. * *

* Clients may implement this interface. * * @see Job#GetRule() * @see Job#SetRule(ISchedulingRule) * @see Job#Schedule(long) * @see IJobManager#BeginRule(ISchedulingRule, org.eclipse.core.runtime.IProgressMonitor) * @see IJobManager#EndRule(ISchedulingRule) */ struct BERRY_JOBS ISchedulingRule: public Object { - berryInterfaceMacro(ISchedulingRule, berry); + berryObjectMacro(berry::ISchedulingRule) /** * Returns whether this scheduling rule completely contains another scheduling * rule. Rules can only be nested within a thread if the inner rule is completely * contained within the outer rule. *

* Implementations of this method must obey the rules of a partial order relation * on the set of all scheduling rules. In particular, implementations must be reflexive * (a.contains(a) is always true), antisymmetric (a.contains(b) and b.contains(a) iff * equals(b), * and transitive (if a.contains(b) and b.contains(c), then a.contains(c)). Implementations * of this method must return false when compared to a rule they * know nothing about. * * @param rule the rule to check for containment * @return true if this rule contains the given rule, and * false otherwise. */ virtual bool Contains(ISchedulingRule::Pointer rule) const = 0; /** * Returns whether this scheduling rule is compatible with another scheduling rule. * If true is returned, then no job with this rule will be run at the * same time as a job with the conflicting rule. If false is returned, * then the job manager is free to run jobs with these rules at the same time. *

* Implementations of this method must be reflexive, symmetric, and consistent, * and must return false when compared to a rule they know * nothing about. * * @param rule the rule to check for conflicts * @return true if the rule is conflicting, and false * otherwise. */ virtual bool IsConflicting(ISchedulingRule::Pointer myRule) const = 0; }; } #endif // _BERRY_ISCHEDULING_RULE_H_ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJob.cpp b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJob.cpp index 861d1d4aaa..9f65a0c133 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJob.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJob.cpp @@ -1,205 +1,205 @@ /*=================================================================== 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 "berryJob.h" #include "berryIJobManager.h" #include "internal/berryJobManager.h" #include "berryIStatus.h" #include "berryStatus.h" #include namespace berry { -const IStatus::Pointer Job::ASYNC_FINISH(new Status ( IStatus::OK_TYPE, JobManager::PI_JOBS(), 1, "") ) ; +const IStatus::Pointer Job::ASYNC_FINISH(new Status ( IStatus::OK_TYPE, JobManager::PI_JOBS(), 1, "", BERRY_STATUS_LOC) ) ; -Job::Job(std::string name) : - InternalJob(name) +Job::Job(const QString& name) + : InternalJob(name) { } const IJobManager* Job::GetJobManager() { return ptr_manager; } bool Job::BelongsTo(Object::Pointer /*family*/) { return false; } bool Job::Cancel() { return InternalJob::Cancel(); } void Job::Done(IStatus::Pointer result) { InternalJob::Done(result); } -std::string Job::GetName() const +QString Job::GetName() const { return InternalJob::GetName(); } int Job::GetPriority() const { return InternalJob::GetPriority(); } // TODO QualifiedName muss noch implementiert werden // Object Job::GetProperty(QualifiedName key) // { // return InternalJob::GetProperty(key); // } IStatus::Pointer Job::GetResult() const { return InternalJob::GetResult(); } ISchedulingRule::Pointer Job::GetRule() const { return InternalJob::GetRule(); } int Job::GetState() const { return InternalJob::GetState(); } Poco::Thread* Job::GetThread() const { return InternalJob::GetThread(); } bool Job::IsBlocking() { return InternalJob::IsBlocking(); } bool Job::IsSystem() const { return InternalJob::IsSystem(); } bool Job::IsUser() const { return InternalJob::IsUser(); } // TODO Join //void Job::Join() // throw (InterruptedException) // { // InternalJob::Join(); // } -void Job::RemoveJobChangeListener(IJobChangeListener::Pointer listener) +void Job::RemoveJobChangeListener(IJobChangeListener* listener) { InternalJob::RemoveJobChangeListener(listener); } void Job::Schedule() { Poco::Timestamp::TimeDiff tmpNoDelay = 0; InternalJob::Schedule(tmpNoDelay); } void Job::Schedule(Poco::Timestamp::TimeDiff delay) { InternalJob::Schedule(delay); } -void Job::SetName(std::string name) +void Job::SetName(const QString& name) { InternalJob::SetName(name); } void Job::SetPriority(int priority) { InternalJob::SetPriority(priority); } void Job::SetProgressGroup(IProgressMonitor::Pointer group, int ticks) { InternalJob::SetProgressGroup(group, ticks); } // TODO SetProperty // void Job::SetProperty(QualifiedName key, Object value) // { // InternalJob::SetProperty(key, value); // } void Job::SetRule(ISchedulingRule::Pointer rule) { InternalJob::SetRule(rule); } void Job::SetSystem(bool value) { InternalJob::SetSystem(value); } void Job::SetUser(bool value) { InternalJob::SetUser(value); } void Job::SetThread(Poco::Thread* thread) { InternalJob::SetThread(thread); } bool Job::ShouldRun() { return true; } bool Job::ShouldSchedule() { return true; } bool Job::Sleep() { return InternalJob::Sleep(); } void Job::WakeUp() { InternalJob::WakeUp(0); } void Job::WakeUp(long delay) { InternalJob::WakeUp(delay); } void Job::Canceling() { //default implementation does nothing } } diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJob.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJob.h index 8de5ca16ce..a3b9e4d373 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJob.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJob.h @@ -1,639 +1,639 @@ /*=================================================================== 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 _BERRY_JOB_H #define _BERRY_JOB_H #include #include // #include "berryISchedulingRule.h" #include "berryJobExceptions.h" #include "internal/berryInternalJob.h" #include #include namespace berry { struct IJobManager; /** * Jobs are units of runnable work that can be scheduled to be run with the job * manager. Once a job has completed, it can be scheduled to run again (jobs are * reusable). *

* Jobs have a state that indicates what they are currently doing. When constructed, * jobs start with a state value of NONE. When a job is scheduled * to be run, it moves into the WAITING state. When a job starts * running, it moves into the RUNNING state. When execution finishes * (either normally or through cancellation), the state changes back to * NONE. *

* A job can also be in the SLEEPING state. This happens if a user * calls Job.sleep() on a waiting job, or if a job is scheduled to run after a specified * delay. Only jobs in the WAITING state can be put to sleep. * Sleeping jobs can be woken at any time using Job.wakeUp(), which will put the * job back into the WAITING state. *

* Jobs can be assigned a priority that is used as a hint about how the job should * be scheduled. There is no guarantee that jobs of one priority will be run before * all jobs of lower priority. The documentation of the various priority constants provide * more detail about what each priority means. By default, jobs start in the * LONG priority class. * * @see IJobManager * */ //TODO struct Job: public InternalJob, public IAdaptable class BERRY_JOBS Job: public InternalJob { public: berryObjectMacro(Job); /** * Job status return value that is used to indicate asynchronous job completion. * @see Job#Run(IProgressMonitor::Pointer) * @see Job#Done(IStatus::Pointer) */ static const IStatus::Pointer ASYNC_FINISH ; /* Job priorities */ /** * Job priority constant (value 10) for interactive jobs. * Interactive jobs generally have priority over all other jobs. * Interactive jobs should be either fast running or very low on CPU * usage to avoid blocking other interactive jobs from running. * * @see #GetPriority() * @see #SetPriority(int) * @see #Run(IProgressMonitor::Pointer) */ static const int INTERACTIVE = 10; /** * Job priority constant (value 20) for short background jobs. * Short background jobs are jobs that typically complete within a second, * but may take longer in some cases. Short jobs are given priority * over all other jobs except interactive jobs. * * @see #GetPriority() * @see #SetPriority(int) * @see #Run(IProgressMonitor::Pointer) */ static const int SHORT = 20; /** * Job priority constant (value 30) for long-running background jobs. * * @see #GetPriority() * @see #SetPriority(int) * @see #Run(IProgressMonitor::Pointer) */ static const int LONG = 30; /** * Job priority constant (value 40) for build jobs. Build jobs are * generally run after all other background jobs complete. * * @see #GetPriority() * @see #SetPriority(int) * @see #Run(IProgressMonitor) */ static const int BUILD = 40; /** * Job priority constant (value 50) for decoration jobs. * Decoration jobs have lowest priority. Decoration jobs generally * compute extra information that the user may be interested in seeing * but is generally not waiting for. * * @see #GetPriority() * @see #SetPriority(int) * @see #Run(IProgressMonitor) */ static const int DECORATE = 50; /** * Job state code (value 0) indicating that a job is not * currently sleeping, waiting, or running (i.e., the job manager doesn't know * anything about the job). * * @see #GetState() */ static const int NONE = 0; /** * Job state code (value 1) indicating that a job is sleeping. * * @see #Run(IProgressMonitor) * @see #GetState() */ static const int SLEEPING = 0x01; /** * Job state code (value 2) indicating that a job is waiting to be run. * * @see #GetState() */ static const int WAITING = 0x02; /** * Job state code (value 4) indicating that a job is currently running * * @see #GetState() */ static const int RUNNING = 0x04; /** * Returns the job manager. * * @return the job manager */ static const IJobManager* GetJobManager(); /** * Creates a new job with the specified name. The job name is a human-readable * value that is displayed to users. The name does not need to be unique, but it * must not be null. * * @param name the name of the job. */ - Job(std::string name); + Job(const QString& name); /** * Registers a job listener with this job * Has no effect if an identical listener is already registered. * * @param listener the listener to be added. */ - void AddJobChangeListener(IJobChangeListener::Pointer listener); + void AddJobChangeListener(IJobChangeListener* listener); /** * Returns whether this job belongs to the given family. Job families are * represented as objects that are not interpreted or specified in any way * by the job manager. Thus, a job can choose to belong to any number of * families. *

* Clients may override this method. This default implementation always returns * false. Overriding implementations must return false * for families they do not recognize. *

* * @param family the job family identifier * @return true if this job belongs to the given family, and * false otherwise. */ bool BelongsTo(Object::Pointer family); /** * Stops the job. If the job is currently waiting, * it will be removed from the queue. If the job is sleeping, * it will be discarded without having a chance to resume and its sleeping state * will be cleared. If the job is currently executing, it will be asked to * stop but there is no guarantee that it will do so. * * @return false if the job is currently running (and thus may not * respond to cancellation), and true in all other cases. */ bool Cancel(); /** * Jobs that complete their execution asynchronously must indicate when they * are finished by calling this method. This method must not be called by * a job that has not indicated that it is executing asynchronously. *

* This method must not be called from within the scope of a job's run * method. Jobs should normally indicate completion by returning an appropriate * status from the run method. Jobs that return a status of * ASYNC_FINISH from their run method must later call * done to indicate completion. * * @param result a status object indicating the result of the job's execution. * @see #ASYNC_FINISH * @see #Run(IProgressMonitor::Pointer) */ void Done(IStatus::Pointer result); /** * Returns the human readable name of this job. The name is never * null. * * @return the name of this job */ - std::string GetName() const; + QString GetName() const; /** * Returns the priority of this job. The priority is used as a hint when the job * is scheduled to be run. * * @return the priority of the job. One of INTERACTIVE, SHORT, LONG, BUILD, * or DECORATE. */ int GetPriority() const; /** * Returns the value of the property of this job identified by the given key, * or null if this job has no such property. * * @param key the name of the property * @return the value of the property, * or null if this job has no such property * @see #SetProperty(QualifiedName, Object) */ //TODO QualifiedName GetPropertys ///Object GetProperty(QualifiedName key) const ; /** * Returns the result of this job's last run. * * @return the result of this job's last run, or null if this * job has never finished running. */ IStatus::Pointer GetResult() const ; /** * Returns the scheduling rule for this job. Returns null if this job has no * scheduling rule. * * @return the scheduling rule for this job, or null. * @see ISchedulingRule * @see #SetRule(ISchedulingRule::Pointer) */ ISchedulingRule::Pointer GetRule() const; /** * Returns the state of the job. Result will be one of: *

    *
  • Job.RUNNING - if the job is currently running.
  • *
  • Job.WAITING - if the job is waiting to be run.
  • *
  • Job.SLEEPING - if the job is sleeping.
  • *
  • Job.NONE - in all other cases.
  • *
*

* Note that job state is inherently volatile, and in most cases clients * cannot rely on the result of this method being valid by the time the * result is obtained. For example, if getState returns * RUNNING, the job may have actually completed by the * time the getState method returns. All clients can infer from * invoking this method is that the job was recently in the returned state. * * @return the job state */ int GetState() const; /** * Returns the thread that this job is currently running in. * * @return the thread this job is running in, or null * if this job is not running or the thread is unknown. */ Poco::Thread* GetThread() const; /** * Returns whether this job is blocking a higher priority non-system job from * starting due to a conflicting scheduling rule. Returns false * if this job is not running, or is not blocking a higher priority non-system job. * * @return true if this job is blocking a higher priority non-system * job, and false otherwise. * @see #GetRule() * @see #IsSystem() */ bool IsBlocking(); /** * Returns whether this job is a system job. System jobs are typically not * revealed to users in any UI presentation of jobs. Other than their UI presentation, * system jobs act exactly like other jobs. If this value is not explicitly set, jobs * are treated as non-system jobs. The default value is false. * * @return true if this job is a system job, and * false otherwise. * @see #SetSystem(bool) */ bool IsSystem() const; /** * Returns whether this job has been directly initiated by a UI end user. * These jobs may be presented differently in the UI. The default value * is false. * * @return true if this job is a user-initiated job, and * false otherwise. * @see #SetUser(bool) */ bool IsUser() const; /** * Waits until this job is finished. This method will block the calling thread until the * job has finished executing, or until this thread has been interrupted. If the job * has not been scheduled, this method returns immediately. A job must not * be joined from within the scope of its run method. *

* If this method is called on a job that reschedules itself from within the * run method, the join will return at the end of the first execution. * In other words, join will return the first time this job exits the * {@link #RUNNING} state, or as soon as this job enters the {@link #NONE} state. *

*

* If this method is called while the job manager is suspended, this job * will only be joined if it is already running; if this job is waiting or sleeping, * this method returns immediately. *

*

* Note that there is a deadlock risk when using join. If the calling thread owns * a lock or object monitor that the joined thread is waiting for, deadlock * will occur. *

* * @exception InterruptedException if this thread is interrupted while waiting * @see ILock * @see IJobManager#Suspend() */ //TODO Error Join Problem InterruptedException /// void Join() ; /** * Removes a job listener from this job. * Has no effect if an identical listener is not already registered. * * @param listener the listener to be removed */ - void RemoveJobChangeListener(IJobChangeListener::Pointer listener); + void RemoveJobChangeListener(IJobChangeListener* listener); /** * Schedules this job to be run. The job is added to a queue of waiting * jobs, and will be run when it arrives at the beginning of the queue. *

* This is a convenience method, fully equivalent to * Schedule(0L). *

* @see #Schedule(long) */ void Schedule(); /** * Schedules this job to be run after a specified delay. The job is put in the * {@link #SLEEPING} state until the specified delay has elapsed, after which * the job is added to a queue of {@link #WAITING} jobs. Once the job arrives * at the beginning of the queue, it will be run at the first available opportunity. *

* Jobs of equal priority and delay with conflicting scheduling * rules are guaranteed to run in the order they are scheduled. No guarantees * are made about the relative execution order of jobs with unrelated or * null scheduling rules, or different priorities. *

* If this job is currently running, it will be rescheduled with the specified * delay as soon as it finishes. If this method is called multiple times * while the job is running, the job will still only be rescheduled once, * with the most recent delay value that was provided. *

* Scheduling a job that is waiting or sleeping has no effect. *

* * @param delay a time delay in milliseconds before the job should run * @see ISchedulingRule */ void Schedule(Poco::Timestamp::TimeDiff delay); /** * Changes the name of this job. If the job is currently running, waiting, * or sleeping, the new job name may not take effect until the next time the * job is scheduled. *

* The job name is a human-readable value that is displayed to users. The name * does not need to be unique, but it must not be null. * * @param name the name of the job. */ - void SetName(std::string name); + void SetName(const QString& name); /** * Sets the priority of the job. This will not affect the execution of * a running job, but it will affect how the job is scheduled while * it is waiting to be run. * * @param priority the new job priority. One of * INTERACTIVE, SHORT, LONG, BUILD, or DECORATE. */ void SetPriority(int priority); /** * Associates this job with a progress group. Progress feedback * on this job's next execution will be displayed together with other * jobs in that group. The provided monitor must be a monitor * created by the method IJobManager.createProgressGroup * and must have at least ticks units of available work. *

* The progress group must be set before the job is scheduled. * The group will be used only for a single invocation of the job's * run method, after which any association of this job to the * group will be lost. * * @see IJobManager#createProgressGroup() * @param group The progress group to use for this job * @param ticks the number of work ticks allocated from the * parent monitor, or {@link IProgressMonitor#UNKNOWN} */ void SetProgressGroup(IProgressMonitor::Pointer group, int ticks); /** * Sets the value of the property of this job identified * by the given key. If the supplied value is null, * the property is removed from this resource. *

* Properties are intended to be used as a caching mechanism * by ISV plug-ins. They allow key-object associations to be stored with * a job instance. These key-value associations are maintained in * memory (at all times), and the information is never discarded automatically. *

* The qualifier part of the property name must be the unique identifier * of the declaring plug-in (e.g. "com.example.plugin"). *

* * @param key the qualified name of the property * @param value the value of the property, * or null if the property is to be removed * @see #GetProperty(QualifiedName) */ //TODO QualifiedName SetProperty /// void SetProperty(QualifiedName key, Object value); /** * Sets the scheduling rule to be used when scheduling this job. This method * must be called before the job is scheduled. * * @param rule the new scheduling rule, or null if the job * should have no scheduling rule * @see #GetRule() */ void SetRule(ISchedulingRule::Pointer rule); /** * Sets whether or not this job is a system job. System jobs are typically not * revealed to users in any UI presentation of jobs. Other than their UI presentation, * system jobs act exactly like other jobs. If this value is not explicitly set, jobs * are treated as non-system jobs. This method must be called before the job * is scheduled. * * @param value true if this job should be a system job, and * false otherwise. * @see #IsSystem() */ void SetSystem(bool value); /** * Sets whether or not this job has been directly initiated by a UI end user. * These jobs may be presented differently in the UI. This method must be * called before the job is scheduled. * * @param value true if this job is a user-initiated job, and * false otherwise. * @see #IsUser() */ void SetUser(bool value); /** * Sets the thread that this job is currently running in, or null * if this job is not running or the thread is unknown. *

* Jobs that use the {@link #ASYNC_FINISH} return code should tell * the job what thread it is running in. This is used to prevent deadlocks. * * @param thread the thread that this job is running in. * * @see #ASYNC_FINISH * @see #Run(IProgressMonitor::Pointer) */ void SetThread(Poco::Thread* thread); /** * Returns whether this job should be run. * If false is returned, this job will be discarded by the job manager * without running. *

* This method is called immediately prior to calling the job's * run method, so it can be used for last minute pre-condition checking before * a job is run. This method must not attempt to schedule or change the * state of any other job. *

* Clients may override this method. This default implementation always returns * true. *

* * @return true if this job should be run * and false otherwise */ virtual bool ShouldRun(); /** * Returns whether this job should be scheduled. * If false is returned, this job will be discarded by the job manager * without being added to the queue. *

* This method is called immediately prior to adding the job to the waiting job * queue.,so it can be used for last minute pre-condition checking before * a job is scheduled. *

* Clients may override this method. This default implementation always returns * true. *

* * @return true if the job manager should schedule this job * and false otherwise */ virtual bool ShouldSchedule(); /** * Requests that this job be suspended. If the job is currently waiting to be run, it * will be removed from the queue move into the {@link #SLEEPING} state. * The job will remain asleep until either resumed or canceled. If this job is not * currently waiting to be run, this method has no effect. *

* Sleeping jobs can be resumed using wakeUp. * * @return false if the job is currently running (and thus cannot * be put to sleep), and true in all other cases * @see #WakeUp() */ bool Sleep(); /** * Puts this job immediately into the {@link #WAITING} state so that it is * eligible for immediate execution. If this job is not currently sleeping, * the request is ignored. *

* This is a convenience method, fully equivalent to * wakeUp(0L). *

* @see #Sleep() */ void WakeUp(); /** * Puts this job back into the {@link #WAITING} state after * the specified delay. This is equivalent to canceling the sleeping job and * rescheduling with the given delay. If this job is not currently sleeping, * the request is ignored. * * @param delay the number of milliseconds to delay * @see #Sleep() */ void WakeUp(long delay); protected: /** * A hook method indicating that this job is running and {@link #cancel()} * is being called for the first time. *

* Subclasses may override this method to perform additional work when * a cancellation request is made. This default implementation does nothing. */ virtual void Canceling(); /** * Executes this job. Returns the result of the execution. *

* The provided monitor can be used to report progress and respond to * cancellation. If the progress monitor has been canceled, the job * should finish its execution at the earliest convenience and return a result * status of severity {@link IStatus#CANCEL}. The singleton * cancel status {@link Status#CANCEL_STATUS} can be used for * this purpose. The monitor is only valid for the duration of the invocation * of this method. *

* This method must not be called directly by clients. Clients should call * schedule, which will in turn cause this method to be called. *

* Jobs can optionally finish their execution asynchronously (in another thread) by * returning a result status of {@link #ASYNC_FINISH}. Jobs that finish * asynchronously must specify the execution thread by calling * setThread, and must indicate when they are finished by calling * the method done. * * @param monitor the monitor to be used for reporting progress and * responding to cancellation. The monitor is never null * @return resulting status of the run. The result must not be null * @see #ASYNC_FINISH * @see #Done(IStatus) */ virtual IStatus::Pointer Run(IProgressMonitor::Pointer myProgressMonitor) = 0; }; } #endif /* BERRY_JOB_H */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJobStatus.cpp b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJobStatus.cpp index 667310a9d7..ef94835299 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJobStatus.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJobStatus.cpp @@ -1,82 +1,37 @@ /*=================================================================== 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 "berryJobStatus.h" #include "internal/berryJobManager.h" #include namespace berry { -JobStatus::JobStatus(const Status::Severity& serverity, Job::Pointer sptr_job, - const std::string& message) : - m_myJob(sptr_job), m_internalStatus(new Status(serverity, - JobManager::PI_JOBS(), 1, message)) +JobStatus::JobStatus(const Severity& severity, Job::Pointer sptr_job, + const QString& message, const Status::SourceLocation& sl) + : Status(severity, JobManager::PI_JOBS(), 1, message, sl) + , m_myJob(sptr_job) { } Job::Pointer JobStatus::GetJob() { return m_myJob; } -std::vector JobStatus::GetChildren() const -{ - return m_internalStatus->GetChildren(); -} - -int JobStatus::GetCode() const -{ - return m_internalStatus->GetCode(); -} - -std::exception JobStatus::GetException() const -{ - return m_internalStatus->GetException(); -} - -std::string JobStatus::GetMessage() const -{ - return m_internalStatus->GetMessage(); -} - -std::string JobStatus::GetPlugin() const -{ - return m_internalStatus->GetPlugin(); -} - -IStatus::Severity JobStatus::GetSeverity() const -{ - return m_internalStatus->GetSeverity(); -} - -bool JobStatus::IsMultiStatus() const -{ - return m_internalStatus->IsMultiStatus(); -} - -bool JobStatus::IsOK() const -{ - return m_internalStatus->IsOK(); -} - -bool JobStatus::Matches(const Severities& severityMask) const -{ - return m_internalStatus->Matches(severityMask); -} - } diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJobStatus.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJobStatus.h index d02e8baee5..8c2035e02c 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJobStatus.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryJobStatus.h @@ -1,105 +1,56 @@ /*=================================================================== 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 _BERRYJOBSTATUS_H #define _BERRYJOBSTATUS_H #include "berryIJobStatus.h" #include "berryStatus.h" #include "berryJob.h" -#include namespace berry { - class BERRY_JOBS JobStatus : public IJobStatus { +class BERRY_JOBS JobStatus : public Status, public IJobStatus +{ - - public: +public: berryObjectMacro(JobStatus); /** * Creates a new job status with no interesting error code or exception. * @param severity * @param job * @param message */ - JobStatus( const Status::Severity& severity, Job::Pointer sptr_job, const std::string& message) ; + JobStatus(const Severity& severity, Job::Pointer sptr_job, const QString& message, + const Status::SourceLocation& sl); /** * @see IJobStatus#GetJob() */ - Job::Pointer GetJob() ; - - /** - * @see org.blueberry.solstice.common IStatus GetChildren() - */ - std::vector GetChildren() const ; - - /** - * @see org.blueberry.solstice.common IStatus GetCode() - */ - int GetCode() const ; - - /** - *@see org.blueberry.solstice.common IStatus GetException () - */ - std::exception GetException() const ; - - /** - * @see org.blueberry.solstice.common GetMessage () - */ - std::string GetMessage() const ; - - /** - * @see org.blueberry.solstice.common IStatus GetPlugin() - */ - std::string GetPlugin() const ; - - /** - * @see org.blueberry.solstice.common IStatus GetSeverity () - */ - Severity GetSeverity() const ; - - /** - * @see org.blueberry.solstice.common IsMultiStatus () - */ - bool IsMultiStatus() const ; - - /** - * @see org.blueberry.solstice.common IStatus IsOk () - */ - bool IsOK() const ; - - /** - * @see org.blueberry.solstice.common IStatus Matches () - */ - bool Matches(const Severities& severityMask) const ; - - - private: - - Job::Pointer m_myJob ; + Job::Pointer GetJob(); - Status::Pointer m_internalStatus ; +private: + Job::Pointer m_myJob; - }; +}; - } +} #endif /* _BERRYJOBSTATUS_H */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryInternalJob.cpp b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryInternalJob.cpp index 4ff0a13771..647c99c9ab 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryInternalJob.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryInternalJob.cpp @@ -1,445 +1,449 @@ /*=================================================================== 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. ===================================================================*/ #define NOMINMAX #include "berryInternalJob.h" #include #include "berryJob.h" #include "berryJobManager.h" #include "berryJobExceptions.h" -#include -#include #include #include namespace berry { -InternalJob::InternalJob(std::string name) : - jobNumber(nextJobNumber++), flags(Job::NONE), name(name), next(0), - previous(0), priority(Job::LONG), sptr_schedulingRule(0), - sptr_monitor(0), m_startTime(), waitQueueStamp(T_NONE), ptr_thread(0) +InternalJob::InternalJob(const QString& name) + : jobNumber(nextJobNumber++) + , flags(Job::NONE) + , name(name) + , next(0) + , previous(0) + , priority(Job::LONG) + , sptr_schedulingRule(0) + , sptr_monitor(0) + , m_startTime() + , waitQueueStamp(T_NONE) + , ptr_thread(0) { jobEvents.SetExceptionHandler(MessageExceptionHandler(&ptr_manager->m_JobListeners, &JobListeners::HandleException)); } JobManager* const InternalJob::ptr_manager = JobManager::GetInstance(); // time_variables definitions // implemented as TimeDiff, if needed can be used to create a Poco::Timestamp with the given value const Poco::Timestamp::TimeDiff InternalJob::T_INFINITE = std::numeric_limits::max(); // indicates if a job has a scheduling time // implemented as TimeDiff, if needed can be used to create a Poco::Timestamp with the given value const Poco::Timestamp::TimeDiff InternalJob::T_NONE = -1; void InternalJob::AddLast(InternalJob::Pointer entry) { InternalJob::Pointer last; last = this; //find the end of the queue while (last->previous) last = last->previous; //add the new entry to the end of the queue last->previous = entry.GetPointer(); entry->next = last; entry->previous = 0; } bool InternalJob::operator==(const Object* otherJob) const { if (const InternalJob* temp = dynamic_cast(otherJob)) { return temp->m_startTime >= m_startTime; } else return false; } const IJobChangeListener::Events& InternalJob::GetListeners() const { return jobEvents; } IProgressMonitor::Pointer InternalJob::GetProgressMonitor() const { return sptr_monitor; } Poco::Timestamp InternalJob::GetStartTime() const { return m_startTime; } int InternalJob::InternalGetState() const { return flags & M_STATE; } void InternalJob::InternalSetPriority(int newPriority) { this->priority = newPriority; } void InternalJob::InternalSetRule(ISchedulingRule::Pointer rule) { sptr_schedulingRule = rule; } //TODO InternalSetState void InternalJob::InternalSetState(int i) { flags = (flags & ~M_STATE) | i; } bool InternalJob::IsAboutToRunCanceled() const { return (flags & M_ABOUT_TO_RUN_CANCELED) != 0; } bool InternalJob::IsRunCanceled() const { return (flags & M_RUN_CANCELED) != 0; } bool InternalJob::IsConflicting(InternalJob::Pointer otherJob) const { ISchedulingRule::Pointer otherRule = otherJob->GetRule(); if (sptr_schedulingRule.GetPointer() == 0 || otherRule.GetPointer() == 0) return false; // TODO MultiRule: extend the IsConflicting (...) method with MultiRule // if one of the rules is a compound rule, it must be asked the question. //if (schedulingRule.GetClass() == MultiRule.class) // return schedulingRule.IsConflicting(otherRule); return otherRule->IsConflicting(sptr_schedulingRule); } InternalJob::Pointer InternalJob::Next() const { return next; } InternalJob::Pointer InternalJob::Previous() const { return InternalJob::Pointer(previous); } InternalJob::Pointer InternalJob::Remove() { if (next != 0) next->SetPrevious(InternalJob::Pointer(previous)); if (previous != 0) previous->SetNext(next); next = previous = 0; return InternalJob::Pointer(this); } void InternalJob::SetAboutToRunCanceled(bool value) throw (JobRuntimeException) { flags = value ? flags | M_ABOUT_TO_RUN_CANCELED : flags & ~M_ABOUT_TO_RUN_CANCELED; } void InternalJob::SetRunCanceled(bool value) { flags = value ? flags | M_RUN_CANCELED : flags & ~M_RUN_CANCELED; } void InternalJob::SetNext(InternalJob::Pointer entry) { this->next = entry; } void InternalJob::SetPrevious(InternalJob::Pointer entry) { this->previous = entry.GetPointer(); } void InternalJob::SetProgressMonitor(IProgressMonitor::Pointer monitor) { sptr_monitor = monitor; } void InternalJob::SetResult(IStatus::Pointer result) { m_result = result; } void InternalJob::SetStartTime(Poco::Timestamp::TimeDiff time) { m_startTime = m_startTime + time; } void InternalJob::SetStartTime(const Poco::Timestamp& newtime) { m_startTime = newtime; } -std::string InternalJob::ToString() +QString InternalJob::ToString() const { - std::stringstream ss; - ss << GetName() << "(" << jobNumber << ")"; - return ss.str(); + return GetName() + "(" + QString::number(jobNumber) + ")"; } void InternalJob::SetWaitQueueStamp(Poco::Timestamp waitQueueStamp) { this->waitQueueStamp = waitQueueStamp; } Poco::Timestamp InternalJob::GetWaitQueueStamp() { return waitQueueStamp; } int InternalJob::nextJobNumber = 0; -void InternalJob::AddJobChangeListener(IJobChangeListener::Pointer listener) +void InternalJob::AddJobChangeListener(IJobChangeListener* listener) { jobEvents.AddListener(listener); } bool InternalJob::BelongsTo(Object::Pointer /*family*/) { return false; } bool InternalJob::Cancel() { return ptr_manager->Cancel(InternalJob::Pointer(this)); } void InternalJob::Canceling() { //default implementation does nothing } void InternalJob::Done(IStatus::Pointer endResult) { ptr_manager->EndJob(InternalJob::Pointer(this),endResult, true); } -std::string InternalJob::GetName() const +QString InternalJob::GetName() const { return name; } int InternalJob::GetPriority() const { return priority; } //TODO QualifiedName GetProperty //Object::Pointer //InternalJob //::GetProperty(QualifiedName key) { // // thread safety: (Concurrency001 - copy on write) // std::map temp (properties); // if (temp.empty()) return Object::Pointer(0); // else return temp[key]; // } IStatus::Pointer InternalJob::GetResult() const { return m_result; } ISchedulingRule::Pointer InternalJob::GetRule() const { return sptr_schedulingRule; } int InternalJob::GetState() const { int state = flags & M_STATE; switch (state) { //blocked state is equivalent to waiting state for clients case BLOCKED: return Job::WAITING; case ABOUT_TO_RUN: return Job::RUNNING; case ABOUT_TO_SCHEDULE: return Job::WAITING; default: return state; } } Poco::Thread* InternalJob::GetThread() const { return ptr_thread; } bool InternalJob::IsSystem() const { return (flags & M_SYSTEM) != 0; } bool InternalJob::IsBlocking() { return ptr_manager->IsBlocking(InternalJob::Pointer(this)); } bool InternalJob::IsUser() const { return (flags & M_USER) != 0; } //void //InternalJob //::Join() throws InterruptedException { // manager.join(this); // } -void InternalJob::RemoveJobChangeListener(IJobChangeListener::Pointer listener) +void InternalJob::RemoveJobChangeListener(IJobChangeListener* listener) { jobEvents.RemoveListener(listener); } void InternalJob::Schedule(Poco::Timestamp::TimeDiff delay) { if (ShouldSchedule()) ptr_manager->Schedule(InternalJob::Pointer(this), delay, false); } -void InternalJob::SetName(const std::string& name) +void InternalJob::SetName(const QString& name) { - assert(!name.empty()); + Q_ASSERT(!name.isEmpty()); this->name = name; } void InternalJob::SetPriority(int newPriority) { switch (newPriority) { case Job::INTERACTIVE: case Job::SHORT: case Job::LONG: case Job::BUILD: case Job::DECORATE: ptr_manager->SetPriority(InternalJob::Pointer(this), newPriority); break; default: throw IllegalArgumentException(newPriority); } } void InternalJob::SetProgressGroup(IProgressMonitor::Pointer group, int ticks) { assert(group.GetPointer() != 0); InternalJob::Pointer sptr_temp(this); IProgressMonitor::Pointer sptr_pm = ptr_manager->CreateMonitor(sptr_temp, group, ticks); if (sptr_pm != 0) SetProgressMonitor(sptr_pm); } //TODO QualifiedName SetProperty //void //InternalJob //::SetProperty(QualifiedName key, Object value) { // // thread safety: (Concurrency001 - copy on write) // if (value == NULL) { // if (properties == NULL) // return; // ObjectMap temp = (ObjectMap) properties.Clone(); // temp.Remove(key); // if (temp.isEmpty()) // properties = NULL; // else // properties = temp; // } else { // ObjectMap temp = properties; // if (temp == NULL) // temp = new ObjectMap(5); // else // temp = (ObjectMap) properties.Clone(); // temp.Put(key, value); // properties = temp; // } // } void InternalJob::SetRule(ISchedulingRule::Pointer rule) { ptr_manager->SetRule(InternalJob::Pointer(this), rule); } void InternalJob::SetSystem(bool value) { //TODO Error Exception Problem IllegalStateException //if (GetState() != Job.NONE) //throw IllegalStateException(); flags = value ? flags | M_SYSTEM : flags & ~M_SYSTEM; } void InternalJob::SetThread(Poco::Thread* thread) { ptr_thread = thread; } void InternalJob::SetUser(bool value) { //TODO Error Exception Problem IllegalStateException if (GetState() != Job::NONE) throw IllegalStateException(); flags = value ? flags | M_USER : flags & ~M_USER; } bool InternalJob::ShouldSchedule() { return true; } bool InternalJob::Sleep() { return ptr_manager->Sleep(InternalJob::Pointer(this)); } void InternalJob::WakeUp(long delay) { ptr_manager->WakeUp(InternalJob::Pointer(this), delay); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryInternalJob.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryInternalJob.h index cf3a250fc0..d86893ad91 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryInternalJob.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryInternalJob.h @@ -1,467 +1,467 @@ /*=================================================================== 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 BERRY_INTERNALJOB_H #define BERRY_INTERNALJOB_H #include #include #include #include #include "berryJobExceptions.h" #include "berryISchedulingRule.h" #include "berryIProgressMonitor.h" #include "berryIJobChangeListener.h" #include #include #include #include #include #include namespace berry { struct JobManager; /** * Internal implementation class for jobs. Clients must not implement this class * directly. All jobs must be subclasses of the API org.blueberry_core_jobs.Job class. */ // struct BERRY_JOBS InternalJob: public Object, public Comparable struct BERRY_JOBS InternalJob : public Object { friend struct JobQueue; friend struct JobManager; berryObjectMacro(InternalJob); bool operator==(const Object* otherJob) const; /** * Adds an entry at the end of the list of which this item is the head. */ void AddLast(InternalJob::Pointer entry); /* * Returns the job listeners that are only listening to this job. */ const IJobChangeListener::Events& GetListeners() const; /** * Returns the job's progress monitor, or null if it is not running. */ IProgressMonitor::Pointer GetProgressMonitor() const; /** * Returns the time that this job should be started, awakened, or * rescheduled, depending on the current state. * @return time in milliseconds */ Poco::Timestamp GetStartTime() const; /** * Returns the raw job state, including internal states no exposed as API. */ int InternalGetState() const; /* * @see Job#GetState() */ int GetState() const; /** * @see Job#GetName() */ - std::string GetName() const; + QString GetName() const; /* * @see Job#setRule(ISchedulingRule::Pointer) */ void InternalSetRule(ISchedulingRule::Pointer rule); /** * Must be called from JobManager#setPriority */ void InternalSetPriority(int newPriority); /** * Must be called from JobManager#ChangeState */ void InternalSetState(int i); /** * Returns whether this job was canceled when it was about to run */ bool IsAboutToRunCanceled() const; /** * Returns whether this job was canceled when it was running. */ bool IsRunCanceled() const ; /** * Returns true if this job conflicts with the given job, and false otherwise. */ bool IsConflicting(InternalJob::Pointer otherJob) const; /** * Returns the next entry (ahead of this one) in the list, or null if there is no next entry */ InternalJob::Pointer Next() const; /** * Returns the previous entry (behind this one) in the list, or null if there is no previous entry */ InternalJob::Pointer Previous() const; /** * Removes this entry from any list it belongs to. Returns the receiver. */ InternalJob::Pointer Remove(); /* * @see Job#run(IProgressMonitor) */ virtual IStatus::Pointer Run(IProgressMonitor::Pointer myProgressMonitor) = 0 ; /** * Sets whether this job was canceled when it was about to run */ void SetAboutToRunCanceled(bool value) throw (JobRuntimeException); /** * Sets the next entry in this linked list of jobs. * @param entry */ /** * Sets whether this job was canceled when it was running */ void SetRunCanceled(bool value) ; void SetNext(InternalJob::Pointer entry); /** * Sets the previous entry in this linked list of jobs. * @param entry */ void SetPrevious(InternalJob::Pointer entry); /** * Sets the progress monitor to use for the next execution of this job, * or for clearing the monitor when a job completes. * @param monitor a progress monitor */ void SetProgressMonitor(IProgressMonitor::Pointer monitor); /** * Sets or clears the result of an execution of this job. * @param result a result status, or null */ void SetResult(IStatus::Pointer result) ; /** * Sets a time to start, wake up, or schedule this job, * depending on the current state * @param time a time in milliseconds */ void SetStartTime(Poco::Timestamp::TimeDiff time); void SetStartTime(const Poco::Timestamp& newtime); /* * @see Job.SetThread */ void SetThread(Poco::Thread* thread); /* * @see Job.GetThread */ Poco::Thread* GetThread() const; /* * Prints a string-based representation of this job instance. * For debugging purposes only. */ - std::string ToString(); + QString ToString() const; /** * @param waitQueueStamp The waitQueueStamp to set. */ void SetWaitQueueStamp(Poco::Timestamp waitQueueStamp); /** * @return Returns the waitQueueStamp. */ Poco::Timestamp GetWaitQueueStamp(); protected: - InternalJob(std::string name); + InternalJob(const QString& name); /* - * @see Job#AddJobListener(IJobChangeListener::Pointer) + * @see Job#AddJobListener(IJobChangeListener*) */ - void AddJobChangeListener(IJobChangeListener::Pointer listener); + void AddJobChangeListener(IJobChangeListener* listener); /* * @see Job#BelongsTo(Object) */ virtual bool BelongsTo(Object::Pointer family); /* * @see Job#Cancel() */ bool Cancel(); /* * @see Job#Canceling() */ virtual void Canceling(); /* * * @see Job#Done(IStatus:.Pointer) */ void Done(IStatus::Pointer endResult); /* * @see Job#GetPriority() */ int GetPriority() const; /* * @see Job#GetProperty */ /// Object GetProperty(QualifiedName key) ; /* * @see Job#GetResult */ IStatus::Pointer GetResult() const ; /* * @see Job#GetRule */ ISchedulingRule::Pointer GetRule() const; /* * @see Job.IsSystem() */ bool IsSystem() const; /* * @see Job.IsUser() */ bool IsUser() const; /* * @see Job#Join() */ /// void Join() throws InterruptedException ; /* * @see Job#RemoveJobListener(IJobChangeListener) */ - void RemoveJobChangeListener(IJobChangeListener::Pointer listener); + void RemoveJobChangeListener(IJobChangeListener* listener); /* * @see Job#Schedule(long) */ void Schedule(Poco::Timestamp::TimeDiff delay); /* * @see Job#SetName(std::string) */ - void SetName(const std::string& name); + void SetName(const QString& name); /* * @see Job#SetPriority(int) */ void SetPriority(int newPriority); /* * @see Job#SetProgressGroup(IProgressMonitor::Pointer, int ticks) */ void SetProgressGroup(IProgressMonitor::Pointer group, int ticks); /* * @see Job#SetProperty(QualifiedName,Object) */ /// void SetProperty(QualifiedName key, Object value) ; /* internalSetRule * @see Job#SetRule(ISchedulingRule::Pointer) */ void SetRule(ISchedulingRule::Pointer rule); /* * @see Job.SetSystem */ void SetSystem(bool value); /* * @see Job.SetUser */ void SetUser(bool value); /* * @see Job#ShouldSchedule */ virtual bool ShouldSchedule(); /* * @see Job#Sleep() */ bool Sleep(); /* * @see Job#WakeUp(long) */ void WakeUp(long delay); public: /** * Flag on a job indicating that it was canceled when running. This flag * is used to ensure that #canceling is only ever called once on a job in * case of recursive cancellation attempts. */ static const int M_RUN_CANCELED = 0x0800; /** * Job state code (value 16) indicating that a job has been removed from * the wait queue and is about to start running. From an API point of view, * this is the same as RUNNING. */ static const int ABOUT_TO_RUN = 0x10; /** * Job state code (value 32) indicating that a job has passed scheduling * precondition checks and is about to be added to the wait queue. From an API point of view, * this is the same as WAITING. */ static const int ABOUT_TO_SCHEDULE = 0x20; /** * Job state code (value 8) indicating that a job is blocked by another currently * running job. From an API point of view, this is the same as WAITING. */ static const int BLOCKED = 0x08; /** * Start time constant indicating a job should be started at * a time in the infinite future, causing it to sleep forever. */ static const Poco::Timestamp::TimeDiff T_INFINITE; /** * Start time constant indicating that the job has no start time. */ static const Poco::Timestamp::TimeDiff T_NONE; private: //flag mask bits static const int M_STATE = 0xFF; static const int M_SYSTEM = 0x0100; static const int M_USER = 0x0200; /** * flag on a job indicating that it was about to run, but has been canceled */ static const int M_ABOUT_TO_RUN_CANCELED = 0x0400; static int nextJobNumber; int jobNumber; volatile int flags; /// ListenerList listeners ; - std::string name; + QString name; /** * The job ahead of me in a queue or list. */ InternalJob::Pointer next; /** * The job behind me in a queue or list. */ InternalJob* previous; int priority; /** * Arbitrary properties (key,value) pairs, attached * to a job instance by a third party. */ //std::map properties ; IStatus::Pointer m_result; // Pointer to the ISchedulingRule belonging to the particular job ISchedulingRule::Pointer sptr_schedulingRule; IProgressMonitor::Pointer sptr_monitor; /** * If the job is waiting, this represents the time the job should start by. * If this job is sleeping, this represents the time the job should wake up. * If this job is running, this represents the delay automatic rescheduling, * or -1 if the job should not be rescheduled. */ Poco::Timestamp m_startTime; /** * Stamp added when a job is added to the wait queue. Used to ensure * jobs in the wait queue maintain their insertion order even if they are * removed from the wait queue temporarily while blocked */ Poco::Timestamp waitQueueStamp; /* * The that is currently running this job */ Poco::Thread* ptr_thread; InternalJob(const Self&); protected: static JobManager* const ptr_manager; IJobChangeListener::Events jobEvents; /* * @see Job#isBlocking() */ bool IsBlocking(); }; } #endif /* BERRY_INTERNALJOB_H */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.cpp b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.cpp index 1370da582c..a80f9e9311 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.cpp @@ -1,159 +1,164 @@ /*=================================================================== 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 "berryJobListeners.h" #include "berryJobManager.h" #include "berryJob.h" +#include "berryOperationCanceledException.h" +#include "berryLog.h" -#include #include namespace berry { struct AboutToRunDoit: public JobListeners::IListenerDoit { void Notify(const IJobChangeListener::Events& events, - const IJobChangeEvent::ConstPointer event) const + const IJobChangeEvent::ConstPointer& event) const { events.jobAboutToRun(event); } }; struct AwakeDoit: public JobListeners::IListenerDoit { void Notify(const IJobChangeListener::Events& events, - const IJobChangeEvent::ConstPointer event) const + const IJobChangeEvent::ConstPointer& event) const { events.jobAwake(event); } }; struct DoneDoit: public JobListeners::IListenerDoit { void Notify(const IJobChangeListener::Events& events, - const IJobChangeEvent::ConstPointer event) const + const IJobChangeEvent::ConstPointer& event) const { events.jobDone(event); } }; struct RunningDoit: public JobListeners::IListenerDoit { void Notify(const IJobChangeListener::Events& events, - const IJobChangeEvent::ConstPointer event) const + const IJobChangeEvent::ConstPointer& event) const { events.jobRunning(event); } }; struct ScheduledDoit: public JobListeners::IListenerDoit { void Notify(const IJobChangeListener::Events& events, - const IJobChangeEvent::ConstPointer event) const + const IJobChangeEvent::ConstPointer& event) const { events.jobScheduled(event); } }; struct SleepingDoit: public JobListeners::IListenerDoit { void Notify(const IJobChangeListener::Events& events, - const IJobChangeEvent::ConstPointer event) const + const IJobChangeEvent::ConstPointer& event) const { events.jobSleeping(event); } }; -JobListeners::JobListeners() : - aboutToRun(new AboutToRunDoit()), awake(new AwakeDoit()), - done(new DoneDoit()), running(new RunningDoit()), scheduled( - new ScheduledDoit()), sleeping(new SleepingDoit()) +JobListeners::JobListeners() + : aboutToRun(new AboutToRunDoit()) + , awake(new AwakeDoit()) + , done(new DoneDoit()) + , running(new RunningDoit()) + , scheduled(new ScheduledDoit()) + , sleeping(new SleepingDoit()) { } JobListeners::~JobListeners() { delete aboutToRun; delete awake; delete done; delete running; delete scheduled; delete sleeping; } JobChangeEvent::Pointer JobListeners::NewEvent(Job::Pointer job) { JobChangeEvent::Pointer instance(new JobChangeEvent()); instance->job = job; return instance; } JobChangeEvent::Pointer JobListeners::NewEvent(Job::Pointer job, IStatus::Pointer result) { JobChangeEvent::Pointer instance(new JobChangeEvent()); instance->job = job; instance->result = result; return instance; } JobChangeEvent::Pointer JobListeners::NewEvent(Job::Pointer job, Poco::Timestamp::TimeDiff delay) { JobChangeEvent::Pointer instance(new JobChangeEvent()); instance->job = job; instance->delay = delay; return instance; } void JobListeners::DoNotify(const IListenerDoit* doit, - const IJobChangeEvent::ConstPointer event) + const IJobChangeEvent::ConstPointer& event) { //notify all global listeners doit->Notify(global, event); //notify all local listeners const IJobChangeListener::Events& events = event->GetJob().Cast ()->GetListeners(); doit->Notify(events, event); } void JobListeners::HandleException(const std::exception& e) { //this code is roughly copied from InternalPlatform.run(ISafeRunnable), //but in-lined here for performance reasons try { dynamic_cast (e); return; - } catch (const std::bad_cast&) + } + catch (const std::bad_cast&) { // TODO get bundle id (find a C++ way) //std::string pluginId = JobOSGiUtils.getDefault().getBundleId(listener); - std::string pluginId; - if (pluginId.empty()) + QString pluginId; + if (pluginId.isEmpty()) pluginId = JobManager::PI_JOBS(); - std::string message = "Problems occurred when invoking code from plug-in: " + QString message = "Problems occurred when invoking code from plug-in: " + pluginId; - std::cerr << message << std::endl; + BERRY_ERROR << message; // TODO Logging // RuntimeLog.log(new Status(IStatus.ERROR, pluginId, JobManager.PLUGIN_ERROR, // message, e)); } } } diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.h index f37832e7f5..948a725f8b 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.h @@ -1,133 +1,133 @@ /*=================================================================== 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 BERRYJOBLISTENERS_H_ #define BERRYJOBLISTENERS_H_ #include "berryJobChangeEvent.h" #include "berryIJobChangeListener.h" namespace berry { /** * Responsible for notifying all job listeners about job lifecycle events. Uses a * specialized iterator to ensure the complex iteration logic is contained in one place. */ class JobListeners { public: struct IListenerDoit { virtual void Notify(const IJobChangeListener::Events& listener, - const IJobChangeEvent::ConstPointer event) const = 0; + const IJobChangeEvent::ConstPointer& event) const = 0; virtual ~IListenerDoit() {} }; private: friend struct JobManager; const IListenerDoit* aboutToRun; const IListenerDoit* awake; const IListenerDoit* done; const IListenerDoit* running; const IListenerDoit* scheduled; const IListenerDoit* sleeping; /** * The global job listeners. */ IJobChangeListener::Events global; /** * TODO Could use an instance pool to re-use old event objects */ static JobChangeEvent::Pointer NewEvent(SmartPointer job); static JobChangeEvent::Pointer NewEvent(SmartPointer job, IStatus::Pointer result); static JobChangeEvent::Pointer NewEvent(SmartPointer job, Poco::Timestamp::TimeDiff delay); /** * Process the given doit for all global listeners and all local listeners * on the given job. */ void DoNotify(const IListenerDoit* doit, - const IJobChangeEvent::ConstPointer event); + const IJobChangeEvent::ConstPointer& event); public: JobListeners(); ~JobListeners(); void HandleException(const std::exception& e); - void Add(IJobChangeListener::Pointer listener) + void Add(IJobChangeListener* listener) { global.AddListener(listener); } - void Remove(IJobChangeListener::Pointer listener) + void Remove(IJobChangeListener* listener) { global.RemoveListener(listener); } void AboutToRun(SmartPointer job) { DoNotify(aboutToRun, NewEvent(job)); } void Awake(SmartPointer job) { DoNotify(awake, NewEvent(job)); } void Done(SmartPointer job, IStatus::Pointer result, bool reschedule) { JobChangeEvent::Pointer event = NewEvent(job, result); event->reschedule = reschedule; DoNotify(done, event); } void Running(SmartPointer job) { DoNotify(running, NewEvent(job)); } void Scheduled(SmartPointer job, Poco::Timestamp::TimeDiff delay, bool reschedule) { JobChangeEvent::Pointer event = NewEvent(job, delay); event->reschedule = reschedule; DoNotify(scheduled, event); } void Sleeping(SmartPointer job) { DoNotify(sleeping, NewEvent(job)); } }; } #endif /* BERRYJOBLISTENERS_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobManager.cpp b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobManager.cpp index cec6c6ce97..cdac6f9d98 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobManager.cpp @@ -1,1200 +1,1205 @@ /*=================================================================== 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. ===================================================================*/ #define NOMINMAX #include "berryJobManager.h" #include "berryIProgressMonitor.h" #include "berryNullProgressMonitor.h" #include "berryIStatus.h" #include "berryJobStatus.h" #include #include namespace berry { /** * test class implementing ISchedulingRule to validate client defined rules */ struct NullRule: public ISchedulingRule { bool Contains(ISchedulingRule::Pointer myRule) const; bool IsConflicting(ISchedulingRule::Pointer myRule) const; }; bool NullRule::IsConflicting(ISchedulingRule::Pointer dummyRule) const { return dummyRule == this; } bool NullRule::Contains(ISchedulingRule::Pointer dummyRule) const { return dummyRule == this; } JobManager::JobManager() : sptr_testRule(new NullRule()),m_active(true), m_Pool(new WorkerPool(this)), m_sptr_progressProvider(0), m_JobQueueSleeping(true), m_JobQueueWaiting(false),m_suspended(false), m_waitQueueCounter(0) { m_JobListeners.global.SetExceptionHandler(MessageExceptionHandler< JobListeners> (&m_JobListeners, &JobListeners::HandleException)); } // DEBUG VARIABLES -const std::string& JobManager::PI_JOBS() +const QString& JobManager::PI_JOBS() { - static std::string id("org.blueberry.core.jobs"); + static const QString id("org.blueberry.core.jobs"); return id; } bool JobManager::DEBUG = false; bool JobManager::DEBUG_BEGIN_END = false; bool JobManager::DEBUG_DEADLOCK = false; bool JobManager::DEBUG_LOCKS = false; bool JobManager::DEBUG_TIMING = false; bool JobManager::DEBUG_SHUTDOWN = false; const int JobManager::PLUGIN_ERROR = 2; JobManager* JobManager::GetInstance() { // we don't need to lock the creation of "instance" because GetInstance() is // called when statically initializing InternalJob::ptr_manager (which happens // in single-threaded mode) static JobManager instance; return &instance; } std::string JobManager::PrintState(int state) { switch (state) { case Job::NONE: return "NONE"; case Job::WAITING: return "WAITING"; case Job::SLEEPING: return "SLEEPING"; case Job::RUNNING: return "RUNNING"; case InternalJob::BLOCKED: return "BLOCKED"; case InternalJob::ABOUT_TO_RUN: return "ABOUT_TO_RUN"; case InternalJob::ABOUT_TO_SCHEDULE: return "ABOUT_TO_SCHEDULE"; } return "UNKNOWN"; } void JobManager::Shutdown() { JobManager* ptr_instance(GetInstance()); if (ptr_instance != 0) { ptr_instance->DoShutdown(); // ptr_instance = 0; // need to call the destructor of the static object .. } } //void //JobManager //::Cancel(Object family) { // //don't synchronize because cancel calls listeners // for (Iterator it = select(family).iterator(); it.hasNext();) // cancel((Job) it.next()); // } IProgressMonitor::Pointer JobManager::CreateProgressGroup() { if (m_sptr_progressProvider != 0) return (m_sptr_progressProvider->CreateProgressGroup()); NullProgressMonitor::Pointer sptr_defaultProgressMonitor( new NullProgressMonitor); return sptr_defaultProgressMonitor; } Job* JobManager::CurrentJob() { //Poco::Thread* ptr_current = Poco::Thread::current(); //if (Worker* worker = dynamic_cast(ptr_current) ) // return ((Worker) ptr_current).currentJob(); // { // Poco::ScopedLock lockMe (m_mutex); // Poco::HashSet::Iterator it ; // for (it = m_running.begin(); it != m_running.end(); it ++) { // Job job* = dynamic_cast (it); // if (job->GetThread() == ptr_current) // return job; // } //} return 0; } //void //JobManager //::EndRule(ISchedulingRule rule) { //implicitJobs.end(rule, false); // } //Job[] //JobManager //::Find(Object family) { // List members = select(family); // return (Job[]) members.toArray(new Job[members.size()]); // } // // LockManager GetLockManager() { // return lockManager; // } // bool JobManager::IsIdle() { { Poco::ScopedLock m_managerLock(m_mutex); return m_running.empty() && m_JobQueueWaiting.IsEmpty(); } } bool JobManager::IsSuspended() { { Poco::ScopedLock m_managerLock(m_mutex); m_suspended = true; } return m_suspended; } // // /* // * @see IJobManager#join(String, IProgressMonitor) // */ //void //JobManager //::Join(final Object family, IProgressMonitor monitor) throws InterruptedException, OperationCanceledException { // monitor = monitorFor(monitor); // IJobChangeListener listener = null; // final Set jobs; // int jobCount; // Job blocking = null; // synchronized (lock) { // //don't join a waiting or sleeping job when suspended (deadlock risk) // int states = suspended ? Job.RUNNING : Job.RUNNING | Job.WAITING | Job.SLEEPING; // jobs = Collections.synchronizedSet(new HashSet(select(family, states))); // jobCount = jobs.size(); // if (jobCount > 0) { // //if there is only one blocking job, use it in the blockage callback below // if (jobCount == 1) // blocking = (Job) jobs.iterator().next(); // listener = new JobChangeAdapter() { // public void done(IJobChangeEvent event) { // //don't remove from list if job is being rescheduled // if (!((JobChangeEvent) event).reschedule) // jobs.remove(event.getJob()); // } // // //update the list of jobs if new ones are added during the join // public void scheduled(IJobChangeEvent event) { // //don't add to list if job is being rescheduled // if (((JobChangeEvent) event).reschedule) // return; // Job job = event.getJob(); // if (job.belongsTo(family)) // jobs.add(job); // } // }; // addJobChangeListener(listener); // } // } // if (jobCount == 0) { // //use up the monitor outside synchronized block because monitors call untrusted code // monitor.beginTask(JobMessages.jobs_blocked0, 1); // monitor.done(); // return; // } // //spin until all jobs are completed // try { // monitor.beginTask(JobMessages.jobs_blocked0, jobCount); // monitor.subTask(NLS.bind(JobMessages.jobs_waitFamSub, Integer.toString(jobCount))); // reportBlocked(monitor, blocking); // int jobsLeft; // int reportedWorkDone = 0; // while ((jobsLeft = jobs.size()) > 0) { // //don't let there be negative work done if new jobs have // //been added since the join began // int actualWorkDone = Math.max(0, jobCount - jobsLeft); // if (reportedWorkDone < actualWorkDone) { // monitor.worked(actualWorkDone - reportedWorkDone); // reportedWorkDone = actualWorkDone; // monitor.subTask(NLS.bind(JobMessages.jobs_waitFamSub, Integer.toString(jobsLeft))); // } // if (Thread.interrupted()) // throw new InterruptedException(); // if (monitor.isCanceled()) // throw new OperationCanceledException(); // //notify hook to service pending syncExecs before falling asleep // lockManager.aboutToWait(null); // Thread.sleep(100); // } // } finally { // lockManager.aboutToRelease(); // removeJobChangeListener(listener); // reportUnblocked(monitor); // monitor.done(); // } // } //JobManager //::NewLock() { // return lockManager.newLock(); // } -void JobManager::RemoveJobChangeListener(IJobChangeListener::Pointer listener) +void JobManager::RemoveJobChangeListener(IJobChangeListener* listener) { m_JobListeners.Remove(listener); } -void JobManager::ReportBlocked(IProgressMonitor::Pointer sptr_monitor, InternalJob::Pointer sptr_blockingJob) const { - +void JobManager::ReportBlocked(IProgressMonitor::Pointer sptr_monitor, InternalJob::Pointer sptr_blockingJob) const +{ if ( sptr_monitor.Cast() == 0 ) return ; if (sptr_blockingJob == 0 || sptr_blockingJob->IsSystem()) - { - Status::Pointer sptr_reason( new Status(IStatus::INFO_TYPE, JobManager::PI_JOBS(), 1, "the user operation is waiting for background work to complete" ) ); - - } + { + Status::Pointer sptr_reason( + new Status(IStatus::INFO_TYPE, JobManager::PI_JOBS(), 1, + "the user operation is waiting for background work to complete", + BERRY_STATUS_LOC)); + } else - { - std::stringstream msg ; - msg << "the user operation is waiting for : " << sptr_blockingJob->GetName() << " to complete. " ; - JobStatus::Pointer sptr_reason(new JobStatus(IStatus::INFO_TYPE, sptr_blockingJob.Cast(), msg.str() )); - } - // ((IProgressmonitorWithBlocking) sptr_monitor)->SetBlocked(sptr_reason); + { + QString msg = "the user operation is waiting for : " + sptr_blockingJob->GetName() + + " to complete. "; + JobStatus::Pointer sptr_reason( + new JobStatus(IStatus::INFO_TYPE, sptr_blockingJob.Cast(), msg, + BERRY_STATUS_LOC)); } + // ((IProgressmonitorWithBlocking) sptr_monitor)->SetBlocked(sptr_reason); +} -void JobManager::ReportUnblocked(IProgressMonitor::Pointer sptr_monitor) const { +void JobManager::ReportUnblocked(IProgressMonitor::Pointer sptr_monitor) const +{ if ( IProgressMonitorWithBlocking::Pointer sptr_monitorWithBlocking = sptr_monitor.Cast() ) - sptr_monitorWithBlocking->ClearBlocked(); - } + sptr_monitorWithBlocking->ClearBlocked(); +} void JobManager::Resume() { { Poco::ScopedLock lockMe(m_mutex); m_suspended = false; //poke the job pool m_Pool->JobQueued(); } } //TODO implicit Jobs //void //JobManager //::Resume(ISchedulingRule rule)const { // implicitJobs.resume(rule); // } void JobManager::SetProgressProvider(ProgressProvider::Pointer provider) { m_sptr_progressProvider = provider; } void JobManager::SetRule(InternalJob::Pointer job, ISchedulingRule::Pointer sptr_rule) { Poco::ScopedLock m_managerLock(m_mutex); //cannot change the rule of a job that is already running ( GetRule is set to protected which should be // changed if this assert is needed // assert(job->GetState() == Job.NONE); ValidateRule(sptr_rule); job->InternalSetRule(sptr_rule); } //void //JobManager //::Sleep(Object family) { // //don't synchronize because sleep calls listeners // for (Iterator it = select(family).iterator(); it.hasNext();) { // sleep((InternalJob) it.next()); // } // } void JobManager::Suspend() { { Poco::ScopedLock lockMe(m_mutex); m_suspended = true; } } //void //JobManager //::Suspend(ISchedulingRule rule, IProgressMonitor monitor)const { // Assert.isNotNull(rule); // implicitJobs.suspend(rule, monitorFor(monitor)); // } //void //JobManager //::TransferRule(ISchedulingRule rule, Thread destinationThread) { // implicitJobs.transfer(rule, destinationThread); // } //void //JobManager //::SetLockListener(LockListener listener) { // lockManager.setLockListener(listener); // } //void //JobManager //::WakeUp(Object family) { // //don't synchronize because wakeUp calls listeners // for (Iterator it = select(family).iterator(); it.hasNext();) { // wakeUp((InternalJob) it.next(), 0L); // } // } -void JobManager::AddJobChangeListener(IJobChangeListener::Pointer listener) +void JobManager::AddJobChangeListener(IJobChangeListener* listener) { m_JobListeners.Add(listener); } //void //JobManager //::BeginRule(ISchedulingRule rule, IProgressMonitor monitor) { // validateRule(rule); // implicitJobs.begin(rule, monitorFor(monitor), false); // } // // /** // * For debugging purposes only // */ //std::String //JobManager //::PrintJobName(Job job) { // if (job instanceof ThreadJob) { // Job realJob = ((ThreadJob) job).realJob; // if (realJob != null) // return realJob.getClass().getName(); // return "ThreadJob on rule: " + job.getRule(); //$NON-NLS-1$ // } // return job.getClass().getName(); // } // // instance = this; // initDebugOptions(); // synchronized (lock) { // running = new HashSet(10); // } // pool.setDaemon(JobOSGiUtils.getDefault().useDaemonThreads()); //} void JobManager::ChangeState(InternalJob::Pointer sptr_job, int newState) { bool blockedJobs = false; { Poco::ScopedLock m_managerLock(m_mutex); int tmp_oldState = sptr_job->InternalGetState(); switch (tmp_oldState) { case Job::NONE: case InternalJob::ABOUT_TO_SCHEDULE: break; case InternalJob::BLOCKED: //remove this job from the linked list of blocked jobs sptr_job->Remove(); break; case Job::WAITING: m_JobQueueWaiting.Remove(sptr_job); // assert(false, "Tried to remove a job that wasn't in the queue"); break; case Job::SLEEPING: m_JobQueueSleeping.Remove(sptr_job); // assert(false, "Tried to remove a job that wasn't in the queue"); case Job::RUNNING: case InternalJob::ABOUT_TO_RUN: - m_running.erase(sptr_job); + m_running.remove(sptr_job); //add any blocked jobs back to the wait queue InternalJob::Pointer sptr_blocked(sptr_job->Previous()); sptr_job->Remove(); blockedJobs = sptr_blocked != 0; while (sptr_blocked != 0) { InternalJob::Pointer previous = sptr_blocked->Previous(); ChangeState(sptr_blocked, Job::WAITING); sptr_blocked = previous; } break; // default : // Assert.isLegal(false, "Invalid job state: " + job + ", state: " + oldState); } sptr_job->InternalSetState(newState); switch (newState) { case Job::NONE: sptr_job->SetStartTime(InternalJob::T_NONE); sptr_job->SetWaitQueueStamp(InternalJob::T_NONE); case InternalJob::BLOCKED: break; case Job::WAITING: m_JobQueueWaiting.Enqueue(sptr_job); break; case Job::SLEEPING: //try { m_JobQueueSleeping.Enqueue(sptr_job); //} catch (RuntimeException e) { // throw new RuntimeException("Error changing from state: " + oldState); //} break; case Job::RUNNING: case InternalJob::ABOUT_TO_RUN: sptr_job->SetStartTime(InternalJob::T_NONE); sptr_job->SetWaitQueueStamp(InternalJob::T_NONE); m_running.insert(sptr_job); break; case InternalJob::ABOUT_TO_SCHEDULE: break; // default : // Assert.isLegal(false, "Invalid job state: " + job + ", state: " + newState); } } //notify queue outside sync block if (blockedJobs) m_Pool->JobQueued(); } Poco::Timestamp::TimeDiff JobManager::DelayFor(int priority) { //these values may need to be tweaked based on machine speed switch (priority) { case Job::INTERACTIVE: return 0; case Job::SHORT: return 50; case Job::LONG: return 100; case Job::BUILD: return 500; case Job::DECORATE: return 1000; default: // Assert.isTrue(false, "Job has invalid priority: " + priority); //$NON-NLS-1$ return 0; } } void JobManager::DoSchedule(InternalJob::Pointer job, Poco::Timestamp::TimeDiff delay) { Poco::ScopedLock managerLock(m_mutex); //job may have been canceled already int state = job->InternalGetState(); if (state != InternalJob::ABOUT_TO_SCHEDULE && state != Job::SLEEPING) return; //if it's a decoration job with no rule, don't run it right now if the system is busy if (job->GetPriority() == Job::DECORATE && job->GetRule() == 0) { Poco::Timestamp::TimeDiff tmp_minDelay = m_running.size() * 100; delay = std::max(delay, tmp_minDelay); } if (delay > 0) { job->SetStartTime(Poco::Timestamp() + delay * 100); InternalJob::Pointer sptr_job(job); ChangeState(sptr_job, Job::SLEEPING); } else { job->SetStartTime(Poco::Timestamp() + DelayFor(job->GetPriority()) * 100); job->SetWaitQueueStamp(m_waitQueueCounter++); InternalJob::Pointer sptr_job(job); ChangeState(sptr_job, Job::WAITING); } } void JobManager::DoShutdown() { std::vector vec_ToCancel; { Poco::ScopedLock LockMe(m_mutex); if (m_active) { m_active = false; //cancel all running jobs vec_ToCancel.assign(m_running.begin(), m_running.end()); //clean up m_JobQueueSleeping.Clear(); m_JobQueueWaiting.Clear(); m_running.clear(); } } // Give running jobs a chance to finish. Wait 0.1 seconds for up to 3 times. if (!vec_ToCancel.empty()) { for (std::size_t i = 0; i < vec_ToCancel.size(); i++) { // cancel jobs outside sync block to avoid deadlock Cancel(vec_ToCancel[i]); } for (int waitAttempts = 0; waitAttempts < 3; waitAttempts++) { Poco::Thread::yield(); { Poco::ScopedLock LockMe(m_mutex); if (m_running.empty()) break; } if (DEBUG_SHUTDOWN) { // JobManager.debug("Shutdown - job wait cycle #" + (waitAttempts + 1)); std::vector vec_StillRunning; { Poco::ScopedLock LockMe(m_mutex); vec_StillRunning.assign(m_running.begin(), m_running.end()); // if (!vec_StillRunning.empty()) { //for (int j = 0; j < stillRunning.length; j++) { // JobManager.debug("\tJob: " + printJobName(stillRunning[j])); //$NON-NLS-1$ //} } } Poco::Thread::sleep(100); Poco::Thread::yield(); } // retrieve list of the jobs that are still running { Poco::ScopedLock LockMe(m_mutex); vec_ToCancel.assign(m_running.begin(), m_running.end()); } } if (!vec_ToCancel.empty()) { /*for (int i = 0; i < vec_ToCancel.size(); i++) {*/ // std::string tmp_jobName = PrintJobName(toCancel[i]); // //this doesn't need to be translated because it's just being logged // String msg = "Job found still running after platform shutdown. Jobs should be canceled by the plugin that // scheduled them during shutdown: " + jobName; // RuntimeLog.log(new Status(IStatus.WARNING, JobManager.PI_JOBS, JobManager.PLUGIN_ERROR, msg, null)); // // // TODO the RuntimeLog.log in its current implementation won't produce a log // // during this stage of shutdown. For now add a standard error output. // // One the logging story is improved, the System.err output below can be removed: // System.err.println(msg); // } } m_Pool->Shutdown(); } Job::Pointer JobManager::NextJob() { { Poco::ScopedLock managerLock(m_mutex); //do nothing if the job manager is suspended if (m_suspended) return Job::Pointer(0); // tickle the sleep queue to see if anyone wakes up Poco::Timestamp now; InternalJob::Pointer ptr_job = m_JobQueueSleeping.Peek(); while (ptr_job != 0 && ptr_job->GetStartTime() < now) { // a job that slept to long is set a new start time and is put into the waiting queue ptr_job->SetStartTime(now + DelayFor(ptr_job->GetPriority())); ptr_job->SetWaitQueueStamp(m_waitQueueCounter++); InternalJob::Pointer sptr_job(ptr_job); ChangeState(sptr_job, Job::WAITING); ptr_job = m_JobQueueSleeping.Peek(); } //process the wait queue until we find a job whose rules are satisfied. while ((ptr_job = m_JobQueueWaiting.Peek()) != 0) { InternalJob::Pointer sptr_job(ptr_job); InternalJob::Pointer sptr_blocker = FindBlockingJob(sptr_job); if (sptr_blocker == 0) break; //queue this job after the job that's blocking it ChangeState(sptr_job, InternalJob::BLOCKED); //assert job does not already belong to some other data structure //Assert.isTrue(job.next() == null); //Assert.isTrue(job.previous() == null); sptr_blocker->AddLast(ptr_job); } // the job to run must be in the running list before we exit // the sync block, otherwise two jobs with conflicting rules could start at once if (ptr_job != 0) { InternalJob::Pointer sptr_job(ptr_job); ChangeState(sptr_job, InternalJob::ABOUT_TO_RUN); } return ptr_job.Cast (); } } //TODO Job families //void //JobManager //::Select(List members, Object family, InternalJob firstJob, int stateMask) { // if (firstJob == null) // return; // InternalJob job = firstJob; // do { // //note that job state cannot be NONE at this point // if ((family == null || job.belongsTo(family)) && ((job.getState() & stateMask) != 0)) // members.add(job); // job = job.previous(); // } while (job != null && job != firstJob); // } //List //JobManager //::Select(Object family) { // return select(family, Job.WAITING | Job.SLEEPING | Job.RUNNING); // } //List //JobManager //::Select(Object family, int stateMask) { // List members = new ArrayList(); // synchronized (lock) { // if ((stateMask & Job.RUNNING) != 0) { // for (Iterator it = running.iterator(); it.hasNext();) { // select(members, family, (InternalJob) it.next(), stateMask); // } // } // if ((stateMask & Job.WAITING) != 0) // select(members, family, waiting.peek(), stateMask); // if ((stateMask & Job.SLEEPING) != 0) // select(members, family, sleeping.peek(), stateMask); // } // return members; // } // dummy validateRule implemenation void JobManager::ValidateRule(ISchedulingRule::Pointer sptr_rule) { //null rule always valid if (sptr_rule == 0) return; //contains method must be reflexive poco_assert(sptr_rule->Contains(sptr_rule)) ; //contains method must return false when given an unknown rule poco_assert(!sptr_rule->Contains(sptr_testRule)); //isConflicting method must be reflexive poco_assert(sptr_rule->IsConflicting(sptr_rule)); //isConflicting method must return false when given an unknown rule poco_assert(!sptr_rule->IsConflicting(sptr_testRule)); } bool JobManager::Cancel(InternalJob::Pointer sptr_job) { IProgressMonitor::Pointer sptr_progressMonitor(0); bool runCanceling = false; { Poco::ScopedLock mangerMutex (m_mutex); switch (sptr_job->GetState()) { case Job::NONE : return true; case Job::RUNNING : //cannot cancel a job that has already started (as opposed to ABOUT_TO_RUN) if (sptr_job->InternalGetState() == Job::RUNNING) { sptr_progressMonitor = sptr_job->GetProgressMonitor(); runCanceling = sptr_job->IsRunCanceled(); if(runCanceling) sptr_job->SetRunCanceled(true); break ; } //signal that the job should be canceled before it gets a chance to run sptr_job->SetAboutToRunCanceled(true); return false; default : ChangeState(sptr_job, Job::NONE); } } //call monitor outside sync block if (sptr_progressMonitor != 0) { if(runCanceling) { if (!sptr_progressMonitor->IsCanceled()) sptr_progressMonitor->SetCanceled(true); sptr_job->Canceling(); } return false; } //only notify listeners if the job was waiting or sleeping - m_JobListeners.Done(sptr_job.Cast(), Status::CANCEL_STATUS, false); + m_JobListeners.Done(sptr_job.Cast(), Status::CANCEL_STATUS(BERRY_STATUS_LOC), false); return true; } IProgressMonitor::Pointer JobManager::CreateMonitor( Job::Pointer sptr_jobToMonitor) { IProgressMonitor::Pointer sptr_monitor(0); if (m_sptr_progressProvider != 0) sptr_monitor = m_sptr_progressProvider->CreateMonitor(sptr_jobToMonitor); if (sptr_monitor == 0) { NullProgressMonitor::Pointer sptr_defaultMonitor(new NullProgressMonitor()); return sptr_defaultMonitor; } - return sptr_monitor ; + return sptr_monitor; } IProgressMonitor::Pointer JobManager::CreateMonitor(InternalJob::Pointer sptr_job, IProgressMonitor::Pointer group, int ticks) { { Poco::ScopedLock managerLock(m_mutex); //group must be set before the job is scheduled //this includes the ABOUT_TO_SCHEDULE state, during which it is still //valid to set the progress monitor if (sptr_job->GetState() != Job::NONE) { IProgressMonitor::Pointer dummy(0); return dummy; } IProgressMonitor::Pointer sptr_monitor(0); if (m_sptr_progressProvider != 0) sptr_monitor = m_sptr_progressProvider->CreateMonitor(sptr_job.Cast() , group, ticks); if (sptr_monitor == 0) { // return a default NullprogressMonitor NullProgressMonitor::Pointer sptr_defaultMonitor(new NullProgressMonitor() ); return sptr_defaultMonitor; } return sptr_monitor; } } void JobManager::EndJob(InternalJob::Pointer ptr_job, IStatus::Pointer result, bool notify) { Poco::Timestamp::TimeDiff rescheduleDelay(InternalJob::T_NONE); { Poco::ScopedLock lock ( m_mutex); // if the job is finishing asynchronously, there is nothing more to do for now if (result == Job::ASYNC_FINISH) return; //if job is not known then it cannot be done if (ptr_job->GetState() == Job::NONE) return; ptr_job->SetResult(result); ptr_job->SetProgressMonitor(IProgressMonitor::Pointer(0)); ptr_job->SetThread(0); rescheduleDelay = ptr_job->GetStartTime().epochMicroseconds(); InternalJob::Pointer sptr_job(ptr_job); ChangeState(sptr_job, Job::NONE); } //notify listeners outside sync block bool reschedule = m_active && rescheduleDelay > InternalJob::T_NONE && ptr_job->ShouldSchedule(); if (notify) m_JobListeners.Done(ptr_job.Cast(), result, reschedule); //reschedule the job if requested and we are still active if (reschedule) Schedule(ptr_job, rescheduleDelay, reschedule); } InternalJob::Pointer JobManager::FindBlockingJob(InternalJob::Pointer waitingJob) { if (waitingJob->GetRule() == 0) return InternalJob::Pointer(0); { Poco::ScopedLock managerLock (m_mutex); if (m_running.empty() ) { InternalJob::Pointer dummy; return (dummy); } //check the running jobs bool hasBlockedJobs = false; - Poco::HashSet::Iterator it; + QSet::Iterator it; for ( it = m_running.begin(); it != m_running.end(); it ++ ) { InternalJob::Pointer sptr_job = *it ++; if (waitingJob->IsConflicting(sptr_job)) return sptr_job; if (!hasBlockedJobs) hasBlockedJobs = sptr_job->Previous() != 0; } // there are no blocked jobs, so we are done if (!hasBlockedJobs) { InternalJob::Pointer dummy; return (dummy); } //check all jobs blocked by running jobs - Poco::HashSet::Iterator it_blocked; + QSet::Iterator it_blocked; for( it_blocked = m_running.begin(); it_blocked != m_running.end(); it_blocked ++ ) { InternalJob::Pointer sptr_job = *it_blocked ++; while (true) { sptr_job = sptr_job->Previous(); if (sptr_job == 0) break; if (waitingJob->IsConflicting(sptr_job)) return sptr_job; } } } InternalJob::Pointer sptr_null; return (sptr_null); } bool JobManager::IsActive() { return m_active; } bool JobManager::IsBlocking(InternalJob::Pointer sptr_runningJob) { { Poco::ScopedLock lockMe (m_mutex); // if this job isn't running, it can't be blocking anyone if (sptr_runningJob->GetState() != Job::RUNNING) return false; // if any job is queued behind this one, it is blocked by it InternalJob::Pointer ptr_previous = sptr_runningJob->Previous(); while (ptr_previous != 0) { // ignore jobs of lower priority (higher priority value means lower priority) if (ptr_previous->GetPriority() < sptr_runningJob->GetPriority()) { if (!ptr_previous->IsSystem()) return true; // TODO Implicit Jobs // implicit jobs should interrupt unless they act on behalf of system jobs // if (previous instanceof ThreadJob && ((ThreadJob) previous).shouldInterrupt()) // return true; } ptr_previous = ptr_previous->previous; } // none found return false; } } //void //JobManager //::Join(InternalJob job) { // final IJobChangeListener listener; // final Semaphore barrier; // synchronized (lock) { // int state = job.getState(); // if (state == Job.NONE) // return; // //don't join a waiting or sleeping job when suspended (deadlock risk) // if (suspended && state != Job.RUNNING) // return; // //it's an error for a job to join itself // if (state == Job.RUNNING && job.getThread() == Thread.currentThread()) // throw new IllegalStateException("Job attempted to join itself"); //$NON-NLS-1$ // //the semaphore will be released when the job is done // barrier = new Semaphore(null); // listener = new JobChangeAdapter() { // public void done(IJobChangeEvent event) { // barrier.release(); // } // }; // job.addJobChangeListener(listener); // //compute set of all jobs that must run before this one // //add a listener that removes jobs from the blocking set when they finish // } // //wait until listener notifies this thread. // try { // while (true) { // //notify hook to service pending syncExecs before falling asleep // lockManager.aboutToWait(job.getThread()); // try { // if (barrier.acquire(Long.MAX_VALUE)) // break; // } catch (InterruptedException e) { // //loop and keep trying // } // } // } finally { // lockManager.aboutToRelease(); // job.removeJobChangeListener(listener); // } // } bool JobManager::RunNow(InternalJob::Pointer sptr_job) { { Poco::ScopedLock lockMe (m_mutex); //cannot start if there is a conflicting job if (FindBlockingJob(sptr_job) != 0) return false; ChangeState(sptr_job, Job::RUNNING); sptr_job->SetProgressMonitor(IProgressMonitor::Pointer(new NullProgressMonitor())); sptr_job->Run(IProgressMonitor::Pointer(0)); } return true; } void JobManager::Schedule(InternalJob::Pointer job, Poco::Timestamp::TimeDiff delay, bool reschedule) { if (!m_active) throw Poco::IllegalStateException("Job manager has been shut down."); poco_assert(job); // "Job is null" poco_assert(delay >= 0); // "Scheduling delay is negative" { Poco::ScopedLock managerLock (m_mutex); //if the job is already running, set it to be rescheduled when done if (job->GetState() == Job::RUNNING) { job->SetStartTime(delay); return; } //can't schedule a job that is waiting or sleeping if (job->InternalGetState() != Job::NONE) return; //remember that we are about to schedule the job //to prevent multiple schedule attempts from succeeding (bug 68452) InternalJob::Pointer sptr_job(job); ChangeState(sptr_job, InternalJob::ABOUT_TO_SCHEDULE); } //notify listeners outside sync block m_JobListeners.Scheduled(job.Cast(), delay, reschedule); //schedule the job DoSchedule(job, delay); //call the pool outside sync block to avoid deadlock m_Pool->JobQueued(); } bool JobManager::Sleep(InternalJob::Pointer job) { { Poco::ScopedLock lockMe (m_mutex); InternalJob::Pointer sptr_job(job); switch (job->GetState()) { case Job::RUNNING : //cannot be paused if it is already running (as opposed to ABOUT_TO_RUN) if (job->InternalGetState() == Job::RUNNING) return false; //job hasn't started running yet (aboutToRun listener) break; case Job::SLEEPING : //update the job wake time job->SetStartTime(InternalJob::T_INFINITE); //change state again to re-shuffle the sleep queue ChangeState(sptr_job, Job::SLEEPING); return true; case Job::NONE : return true; case Job::WAITING : //put the job to sleep break; } job->SetStartTime(InternalJob::T_INFINITE); ChangeState(sptr_job, Job::SLEEPING); } m_JobListeners.Sleeping(job.Cast()); return true; } void JobManager::SetPriority(InternalJob::Pointer job, int newPriority) { { Poco::ScopedLock lockMe (m_mutex); InternalJob::Pointer sptr_job(job); int oldPriority = job->GetPriority(); if (oldPriority == newPriority) return; job->InternalSetPriority(newPriority); //if the job is waiting to run, re-shuffle the queue if (sptr_job->GetState() == Job::WAITING) { Poco::Timestamp oldStart = job->GetStartTime(); job->SetStartTime(oldStart += (DelayFor(newPriority) - DelayFor(oldPriority))); m_JobQueueWaiting.Resort(job); } } } Poco::Timespan::TimeDiff JobManager::SleepHint() { Poco::ScopedLock managerLock (m_mutex); // wait forever if job manager is suspended if (m_suspended) return InternalJob::T_INFINITE; if (!m_JobQueueWaiting.IsEmpty()) return 0; // return the anticipated time that the next sleeping job will wake InternalJob::Pointer ptr_next(0); ptr_next = m_JobQueueSleeping.Peek(); if (ptr_next == 0) return InternalJob::T_INFINITE; Poco::Timestamp tmp_startTime = ptr_next->GetStartTime(); Poco::Timestamp tmp_currentTime; Poco::Timestamp::TimeDiff timeToStart = tmp_startTime - tmp_currentTime; return timeToStart; } Job::Pointer JobManager::StartJob() { Job::Pointer job(0); while (true) { job = NextJob(); if (!job) return Job::Pointer(0); //must perform this outside sync block because it is third party code bool shouldRun = job->ShouldRun(); //check for listener veto if (shouldRun) m_JobListeners.AboutToRun(job); //listeners may have canceled or put the job to sleep bool endJob = false; { Poco::ScopedLock lock(m_mutex); InternalJob::Pointer internal = job; if (internal->InternalGetState() == InternalJob::ABOUT_TO_RUN) { if (shouldRun && !internal->IsAboutToRunCanceled()) { internal->SetProgressMonitor(CreateMonitor(job)); //change from ABOUT_TO_RUN to RUNNING internal->InternalSetState(Job::RUNNING); break; } internal->SetAboutToRunCanceled(false); endJob = true; //fall through and end the job below } } if (endJob) { //job has been vetoed or canceled, so mark it as done - EndJob(job,Status::CANCEL_STATUS, true); + EndJob(job,Status::CANCEL_STATUS(BERRY_STATUS_LOC), true); continue; } } m_JobListeners.Running(job); return job; } void JobManager::WakeUp(InternalJob::Pointer job, Poco::Timestamp::TimeDiff delay) { poco_assert(delay >= 0); // "Scheduling delay is negative" { Poco::ScopedLock m_managerLock (m_mutex); //cannot wake up if it is not sleeping if (job->GetState() != Job::SLEEPING) return; DoSchedule(job, delay); } //call the pool outside sync block to avoid deadlock m_Pool->JobQueued(); /// IListenerExtension only notify of wake up if immediate if (delay == 0) m_JobListeners.Awake(job.Cast()); } IProgressMonitor::Pointer JobManager::MonitorFor(IProgressMonitor::Pointer sptr_monitor) { if(sptr_monitor == 0 || sptr_monitor.Cast() ) { if(m_sptr_progressProvider != 0 ) sptr_monitor = m_sptr_progressProvider->GetDefaultMonitor(); } if(sptr_monitor == 0) { IProgressMonitor::Pointer sptr_nullProgressMonitor(new NullProgressMonitor()); return sptr_nullProgressMonitor; } return sptr_monitor; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobManager.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobManager.h index 0c77a1ffa2..94dd4590a0 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobManager.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobManager.h @@ -1,434 +1,435 @@ /*=================================================================== 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 _BERRY_JOBMANAGER_H #define _BERRY_JOBMANAGER_H #include "berryInternalJob.h" #include "berryJobQueue.h" #include "berryWorkerPool.h" #include "berryJobListeners.h" #include "berryJob.h" #include "berryIProgressMonitorWithBlocking.h" #include "berryIJobManager.h" #include "berryISchedulingRule.h" #include #include #include #include #include #include #include #include #include namespace berry { /** * Implementation of API type IJobManager * * Implementation note: all the data structures of this class are protected * by a single lock object held as a private field in this class. The JobManager * instance itself is not used because this class is publicly reachable, and third * party clients may try to synchronize on it. * * The WorkerPool class uses its own monitor for synchronizing its data * structures. To avoid deadlock between the two classes, the JobManager * must NEVER call the worker pool while its own monitor is held. */ struct BERRY_JOBS JobManager: public IJobManager { public: friend class WorkerPool; friend struct InternalJob; friend struct NullRule; berryObjectMacro(JobManager); /** * The unique identifier constant of this plug-in. */ - static const std::string& PI_JOBS(); + static const QString& PI_JOBS(); static bool DEBUG; static bool DEBUG_BEGIN_END; static bool DEBUG_DEADLOCK; static bool DEBUG_LOCKS; static bool DEBUG_TIMING; static bool DEBUG_SHUTDOWN; /** * Status code constant indicating an error occurred while running a plug-in. * For backward compatibility with Platform.PLUGIN_ERROR left at (value = 2). */ static const int PLUGIN_ERROR; /// const ImplicitJobs iImplicitJobs = new ImplicitJobs(this); /** * The singleton job manager instance. It must be a singleton because * all job instances maintain a reference (as an optimization) and have no way * of updating it. */ static JobManager* GetInstance(); /** * For debugging purposes only */ static std::string PrintState(int state); /** * Note that although this method is not API, clients have historically used * it to force jobs shutdown in cases where OSGi shutdown does not occur. * For this reason, this method should be considered near-API and should not * be changed if at all possible. */ static void Shutdown(); // void Cancel(Object family) ; IProgressMonitor::Pointer CreateProgressGroup(); Job* CurrentJob(); // void EndRule(ISchedulingRule rule) ; // Job[] Find(Object family) ; // LockManager GetLockManager() { // return lockManager; // } bool IsIdle(); bool IsSuspended(); // void Join(final Object family, IProgressMonitor monitor) throws InterruptedException, OperationCanceledException ); // ILock NewLock() ; /** - * @see IJobManager#RemoveChangeListener(IJobChangeListener::Pointer) + * @see IJobManager#RemoveChangeListener(IJobChangeListener*) */ - void RemoveJobChangeListener(IJobChangeListener::Pointer listener); + void RemoveJobChangeListener(IJobChangeListener* listener); // /** //* report to the progress monitor that this thread is blocked, supplying //* an information message, and if possible the job that is causing the blockage. //* important: an invocation of this method must be followed eventually be //* an invocation of ReportUnblocked. //* @param monitor the monitor to report blocking to //* @param BlockingJob the job that is blocking this thread, or null //* @see #Reportunblocked //*/ void ReportBlocked( IProgressMonitor::Pointer monitor, InternalJob::Pointer blockingjob) const ; /** * Reports that this thread was blocked, but is no longer blocked and is able * to proceed. * @param monitor The monitor to report unblocking to. * @see #ReportBlocked */ void ReportUnblocked(IProgressMonitor::Pointer monitor) const ; /** * @have a look at IJobManager Resume */ void Resume(); // /** // * @have a look at IJobManager Resume // */ // void Resume(ISchedulingRule::Pointer rule)const ; /** * @have a look at IJobManager SetProgressProvider */ void SetProgressProvider(ProgressProvider::Pointer provider); void SetRule(InternalJob::Pointer job, ISchedulingRule::Pointer rule); // /* // * @see IJobManager#sleep(std::string) // */ // void Sleep(Object family) ; void Suspend(); /* * @see schedule(long) */ void Schedule(InternalJob::Pointer job, Poco::Timestamp::TimeDiff delay, bool reschedule); // void Suspend(ISchedulingRule::Pointer rule, IProgressMonitor::Pointer monitor)const ; // void TransferRule(ISchedulingRule rule, Thread destinationThread) ; // void SetLockListener(LockListener listener) ; // /** // * Puts a job to sleep. Returns true if the job was successfully put to sleep. // */ // void WakeUp(Object family) ; - void AddJobChangeListener(IJobChangeListener::Pointer listener); + void AddJobChangeListener(IJobChangeListener* listener); // void beginRule(ISchedulingRule rule, IProgressMonitor monitor) ; protected: /** * Cancels a job */ bool Cancel(InternalJob::Pointer job); /** * Returns a new progress monitor for this job, belonging to the given * progress group. Returns null if it is not a valid time to set the job's group. */ IProgressMonitor::Pointer CreateMonitor(InternalJob::Pointer job, IProgressMonitor::Pointer group, int ticks); /** * Indicates that a job was running, and has now finished. Note that this method * can be called under OutOfMemoryError conditions and thus must be paranoid * about allocating objects. */ /// optional Extension IStatus for implementation help have a look at the Java JobAPI void EndJob(InternalJob::Pointer job,IStatus::Pointer result, bool notify); /** * Returns a running or blocked job whose scheduling rule conflicts with the * scheduling rule of the given waiting job. Returns null if there are no * conflicting jobs. A job can only run if there are no running jobs and no blocked * jobs whose scheduling rule conflicts with its rule. */ InternalJob::Pointer FindBlockingJob(InternalJob::Pointer waitingJob); /** * Returns whether the job manager is active (has not been shutdown). */ bool IsActive(); /** * Returns true if the given job is blocking the execution of a non-system * job. */ bool IsBlocking(InternalJob::Pointer runningJob); // void Join(InternalJob job) ; /** * Attempts to immediately start a given job. Returns true if the job was * successfully started, and false if it could not be started immediately * due to a currently running job with a conflicting rule. Listeners will never * be notified of jobs that are run in this way. */ bool RunNow(InternalJob::Pointer sptr_job); /** * Puts a job to sleep. Returns true if the job was successfully put to sleep. */ bool Sleep(InternalJob::Pointer job); /** * Changes a job priority. */ void SetPriority(InternalJob::Pointer job, int newPriority); /** * Returns the estimated time in milliseconds before the next job is scheduled * to wake up. The result may be negative. Returns InternalJob.T_INFINITE if * there are no sleeping or waiting jobs. */ Poco::Timespan::TimeDiff SleepHint(); /** * Returns the next job to be run, or null if no jobs are waiting to run. * The worker must call endJob when the job is finished running. */ Job::Pointer StartJob(); /* * @see Job#WakeUp(long) */ void WakeUp(InternalJob::Pointer job, Poco::Timestamp::TimeDiff delay); private: JobManager(); /* Poco Mutex for synchronizing purposes */ Poco::Mutex m_mutex; // Dummy Null rule to validate SchedulingRules implemented by clients SmartPointer sptr_testRule; // //ToDO static const ISchedulingRule nullRule = new ISchedulingRule() { // public bool Contains(ISchedulingRule rule) ; // public boolean IsConflicting(ISchedulingRule rule) ; /** * True if this manager is active, and false otherwise. A job manager * starts out active, and becomes inactive if it has been shutdown * and not restarted. */ volatile bool m_active; JobListeners m_JobListeners; // // /** // * The lock for synchronizing all activity in the job manager. To avoid deadlock, // * this lock must never be held for extended periods, and must never be // * held while third party code is being called. // */ // // private final Object lock = new Object(); // static const Object lock ; // // //private LockManager lockManager = new LockManager(); // static const LockManger lockManager; /** * The pool of worker threads. */ WorkerPool::Pointer m_Pool; ProgressProvider::Pointer m_sptr_progressProvider; + /** * Jobs that are currently running. Should only be modified from changeState */ - Poco::HashSet m_running; + QSet m_running; /** * Jobs that are sleeping. Some sleeping jobs are scheduled to wake * up at a given start time, while others will sleep indefinitely until woken. * Should only be modified from changeState */ JobQueue m_JobQueueSleeping; /** * jobs that are waiting to be run. Should only be modified from changeState */ JobQueue m_JobQueueWaiting; /** * True if this manager has been suspended, and false otherwise. A job manager * starts out not suspended, and becomes suspended when suspend * is invoked. Once suspended, no jobs will start running until resume * is cancelled. */ bool m_suspended; /** * Counter to record wait queue insertion order. */ long long m_waitQueueCounter; // /** // * For debugging purposes only // */ // const std::string PrintJobName(Job job); /** * Atomically updates the state of a job, adding or removing from the * necessary queues or sets. */ void ChangeState(InternalJob::Pointer job, int newState); /** * Returns a new progress monitor for this job. Never returns null. */ IProgressMonitor::Pointer CreateMonitor(Job::Pointer sptr_jobToMonitor); /** * Returns the delay in milliseconds that a job with a given priority can * tolerate waiting. */ Poco::Timestamp::TimeDiff DelayFor(int priority); /** * Performs the scheduling of a job. Does not perform any notifications. */ void DoSchedule(InternalJob::Pointer job, Poco::Timestamp::TimeDiff delay); /** * Shuts down the job manager. Currently running jobs will be told * to stop, but worker threads may still continue processing. * (note: This implemented IJobManager.Shutdown which was removed * due to problems caused by premature shutdown) */ void DoShutdown(); // void InitDebugOptions() ; /** * Removes and returns the first waiting job in the queue. Returns null if there * are no items waiting in the queue. If an item is removed from the queue, * it is moved to the running jobs list. */ Job::Pointer NextJob(); /** * Returns a non-null progress monitor instance. If the monitor is null, * returns the default monitor supplied by the progress provider, or a * NullProgressMonitor if no default monitor is available. */ IProgressMonitor::Pointer MonitorFor(IProgressMonitor::Pointer monitor); // /** // * Adds all family members in the list of jobs to the collection // */ // void Select(List members, Object family, InternalJob firstJob, int stateMask) ; // // /** // * Returns a list of all jobs known to the job manager that belong to the given family. // */ // List Select(Object family) ; // // /** // * Returns a list of all jobs known to the job manager that belong to the given // * family and are in one of the provided states. // */ // List Select(Object family, int stateMask) ; /** * Validates that the given scheduling rule obeys the constraints of * scheduling rules as described in the ISchedulingRule */ void ValidateRule(ISchedulingRule::Pointer rule); }; } #endif /* _BERRY_TEMPLATE_H */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobQueue.cpp b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobQueue.cpp index 1f4c11f816..4bad704441 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobQueue.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobQueue.cpp @@ -1,146 +1,146 @@ /*=================================================================== 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 "berryJobQueue.h" // changed Java JobQueue implementation .. // if only one element is in the queue than InternalJob->next and InternalJob->previous pointer are pointing to 0 and not to the Element itself // I think its better .. will see namespace berry { class DummyJob: public InternalJob { public: IStatus::Pointer Run(IProgressMonitor::Pointer) { - return Status::OK_STATUS; + return Status::OK_STATUS(BERRY_STATUS_LOC); } DummyJob() : InternalJob("Queue-Head") { } }; JobQueue::JobQueue(bool allowConflictOvertaking) : dummy(new DummyJob()), m_allowConflictOvertaking(allowConflictOvertaking) { dummy->SetNext(dummy); dummy->SetPrevious(dummy); } //TODO JobQueue Constructor IStatus Implementierung //TODO Constructor JobQueue IStatus .. implementation // public JobQueue(boolean allowConflictOvertaking) { // //compareTo on dummy is never called // dummy = new InternalJob("Queue-Head") {//$NON-NLS-1$ // public IStatus run(IProgressMonitor m) { // return Status.OK_STATUS; // } // }; // dummy.setNext(dummy); // dummy.setPrevious(dummy); // this.allowConflictOvertaking = allowConflictOvertaking; //} bool JobQueue::CanOvertake(InternalJob::Pointer newEntry, InternalJob::Pointer queueEntry) { //can never go past the end of the queue if (queueEntry == dummy.GetPointer()) return false; //if the new entry was already in the wait queue, ensure it is re-inserted in correct position (bug 211799) if (newEntry->GetWaitQueueStamp() > 0 && newEntry->GetWaitQueueStamp() < queueEntry->GetWaitQueueStamp()) return true; //if the new entry has lower priority, there is no need to overtake the existing entry if ((queueEntry == newEntry)) return false; // the new entry has higher priority, but only overtake the existing entry if the queue allows it InternalJob::Pointer sptr_queueEntry(queueEntry); return m_allowConflictOvertaking || !newEntry->IsConflicting(sptr_queueEntry); } void JobQueue::Clear() { dummy->SetNext(dummy); dummy->SetPrevious(dummy); } // notice: important that the first element in the queue is internally set as a dummy element InternalJob::Pointer JobQueue::Dequeue() { InternalJob::Pointer ptr_dummyPrevious = dummy->Previous(); // sets previous pointer to 0 if there is only 1 Element in the queue if (ptr_dummyPrevious == dummy) { dummy->previous = 0; return dummy; } return ptr_dummyPrevious->Remove(); } void JobQueue::Enqueue(InternalJob::Pointer newEntry) { InternalJob::Pointer tail = dummy->Next(); //overtake lower priority jobs. Only overtake conflicting jobs if allowed to while (CanOvertake(newEntry, tail)) tail = tail->Next(); InternalJob::Pointer tailPrevious = tail->Previous(); newEntry->SetNext(tail); newEntry->SetPrevious(tailPrevious); tailPrevious->SetNext(newEntry); tail->SetPrevious(newEntry); } void JobQueue::Remove(InternalJob::Pointer jobToRemove) { jobToRemove->Remove(); } void JobQueue::Resort(InternalJob::Pointer entry) { this->Remove(entry); this->Enqueue(entry); } bool JobQueue::IsEmpty() { return this->dummy->next == dummy; } InternalJob::Pointer JobQueue::Peek() { return dummy->Previous() == dummy ? InternalJob::Pointer(0) : dummy->Previous(); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorker.cpp b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorker.cpp index 3ecdee4a77..ceb943a222 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorker.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorker.cpp @@ -1,138 +1,134 @@ /*=================================================================== 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 "berryWorker.h" #include "berryWorkerPool.h" -#include -#include #include "berryJobManager.h" +#include "berryLog.h" namespace berry { /************************* begin of nested JobRunnable class definition ****************************/ int Worker::m_nextWorkerNumber = 0; Worker::JobRunnable::JobRunnable(Worker* currentWorker) : ptr_currentWorker(currentWorker) { } // not a good implementation yet .. without the IStatus it can not be checked if a job has been // executed correctly void Worker::JobRunnable::run() { ptr_currentWorker->setPriority(PRIO_NORMAL); try { while ((ptr_currentWorker->ptr_currentJob = ptr_currentWorker->m_wpPool.Lock()->StartJob(ptr_currentWorker)) != 0) { - IStatus::Pointer result = Status::OK_STATUS ; + IStatus::Pointer result = Status::OK_STATUS(BERRY_STATUS_LOC); try { ptr_currentWorker->ptr_currentJob->SetThread(ptr_currentWorker); ptr_currentWorker->ptr_currentJob->Run(ptr_currentWorker->ptr_currentJob->GetProgressMonitor()); // java thread.interrupted throw FinallyThrowException(); } catch(FinallyThrowException) { RunMethodFinallyExecution(result); } // provided an unspecific exception handling, if specific exceptions are added within core job executing methods // the specific thrown exceptions should be handled below catch(...) { RunMethodFinallyExecution(result); } } throw FinallyThrowException(); } catch (FinallyThrowException&) { ptr_currentWorker->ptr_currentJob = 0; Worker::Pointer sptr_currentWorker(ptr_currentWorker); ptr_currentWorker->m_wpPool.Lock()->EndWorker(sptr_currentWorker); } catch (...) { ptr_currentWorker->ptr_currentJob = 0; Worker::Pointer sptr_currentWorker(ptr_currentWorker); ptr_currentWorker->m_wpPool.Lock()->EndWorker(sptr_currentWorker); } } void Worker::JobRunnable::RunMethodFinallyExecution(IStatus::Pointer sptr_result) { - //clear interrupted state for this thread - //Thread.interrupted(); + //clear interrupted state for this thread + //Thread.interrupted(); - //result must not be null -if (sptr_result.IsNull()) + //result must not be null + if (sptr_result.IsNull()) { - std::runtime_error tempError("NullPointerException") ; + std::runtime_error tempError("NullPointerException"); sptr_result = HandleException( ptr_currentWorker->ptr_currentJob, tempError ); } - ptr_currentWorker->m_wpPool.Lock()->EndJob( ptr_currentWorker->ptr_currentJob, sptr_result ); + ptr_currentWorker->m_wpPool.Lock()->EndJob( ptr_currentWorker->ptr_currentJob, sptr_result ); - if ((sptr_result->GetSeverity() & (IStatus::ERROR_TYPE | IStatus::WARNING_TYPE)) != 0) - // TODO Logging RuntimeLog.log(result); - std::cout << " Status after executing the job : " << sptr_result->ToString() ; - ptr_currentWorker->ptr_currentJob = 0; - //reset thread priority in case job changed it - ptr_currentWorker->setPriority(PRIO_NORMAL); - - } + if ((sptr_result->GetSeverity() & (IStatus::ERROR_TYPE | IStatus::WARNING_TYPE)) != 0) + // TODO Logging RuntimeLog.log(result); + BERRY_ERROR << " Status after executing the job : " << sptr_result->ToString(); + ptr_currentWorker->ptr_currentJob = 0; + //reset thread priority in case job changed it + ptr_currentWorker->setPriority(PRIO_NORMAL); +} IStatus::Pointer Worker::JobRunnable::HandleException(InternalJob::Pointer sptr_job, const std::exception& exception) - { - std::stringstream ss; - ss << "An internal error occurred while executing the job: " << sptr_job->GetName() ; - IStatus::Pointer sptr_errorStatus(new Status(IStatus::ERROR_TYPE, JobManager::PI_JOBS(), JobManager::PLUGIN_ERROR, ss.str(), exception) ) ; - return sptr_errorStatus ; - } - - +{ + QString msg = "An internal error occurred while executing the job: " + sptr_job->GetName(); + IStatus::Pointer sptr_errorStatus(new Status(IStatus::ERROR_TYPE, JobManager::PI_JOBS(), + JobManager::PLUGIN_ERROR, msg, ctkException(exception.what()), BERRY_STATUS_LOC)); + return sptr_errorStatus ; +} /************************* end of nested JobRunnable class definition ****************************/ Worker::Worker(WeakPointer myPool) : Poco::Thread("Worker-" + m_nextWorkerNumber++), m_Runnable(this), m_wpPool( myPool), ptr_currentJob(0) { } void Worker::Start() { Poco::Thread::start(m_Runnable); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/files.cmake b/BlueBerry/Bundles/org.blueberry.core.runtime/files.cmake index 0245042994..4b1d810f09 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/files.cmake +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/files.cmake @@ -1,123 +1,119 @@ set(MOC_H_FILES src/berryPlugin.h src/internal/berryCTKPluginListener.h src/internal/berryCTKPluginActivator.h src/internal/berryExtensionRegistry.h src/internal/berryPreferencesService.h ) set(CACHED_RESOURCE_FILES plugin.xml ) set(SRC_CPP_FILES berryBackingStoreException.cpp berryContributorFactory.cpp berryCoreException.cpp berryDebugBreakpointManager.cpp berryDebugUtil.cpp berryException.cpp berryExtensionType.cpp berryIAdaptable.cpp berryIAdapterManager.cpp berryIDebugObjectListener.cpp berryILog.cpp berryIPreferences.cpp berryIBerryPreferences.cpp berryIPreferencesService.cpp berryListenerList.h berryLog.cpp berryMultiStatus.cpp berryObject.cpp berryObjectGeneric.h berryObjectList.h berryObjects.cpp - berryObjectString.h + berryObjectString.cpp berryObjectStringMap.cpp berryOperationCanceledException.cpp berryPlatform.cpp berryPlatformException.cpp berryPlatformObject.cpp berryPlugin.cpp - berryRuntime.cpp berrySafeRunner.cpp berrySmartPointer.h - berryStackTrace.cpp berryStatus.cpp berryWeakPointer.h # application application/berryIApplication.cpp application/berryStarter.cpp # registry registry/berryIConfigurationElement.cpp registry/berryIContributor.cpp registry/berryIExecutableExtension.cpp registry/berryIExecutableExtensionFactory.cpp registry/berryIExtension.cpp registry/berryIExtensionPoint.cpp registry/berryIExtensionRegistry.cpp registry/berryInvalidRegistryObjectException.cpp registry/berryIRegistryEventListener.cpp registry/berryRegistryConstants.cpp ) set(INTERNAL_CPP_FILES berryAbstractPreferencesStorage.cpp berryCombinedEventDelta.cpp berryConfigurationElement.h berryConfigurationElement.cpp berryConfigurationElementAttribute.cpp berryConfigurationElementDescription.cpp berryConfigurationElementHandle.cpp berryCTKPluginActivator.cpp berryCTKPluginListener.cpp berryCTKPluginUtils.cpp berryExtension.cpp - #berryExtensionDelta.cpp berryExtensionHandle.cpp berryExtensionPoint.cpp berryExtensionPointHandle.cpp berryExtensionRegistry.cpp berryExtensionsParser.cpp berryHandle.cpp berryInternalPlatform.cpp berryIObjectManager.cpp berryIRuntimeConstants.cpp berryLogImpl.cpp berryKeyedElement.cpp berryKeyedHashSet.cpp berryPreferences.cpp berryPreferencesService.cpp berryProvisioningInfo.cpp berryRegistryContribution.cpp berryRegistryContributor.cpp - #berryRegistryDelta.cpp berryRegistryObjectFactory.cpp berryRegistryIndexChildren.cpp berryRegistryIndexElement.cpp berryRegistryMessages.cpp berryRegistryObject.cpp berryRegistryObjectManager.cpp berryRegistryObjectReferenceMap.cpp berryRegistryProperties.cpp berryRegistryStrategy.cpp berryRegistryTimestamp.cpp berryRegistrySupport.cpp berryTemporaryObjectManager.cpp berryThirdLevelConfigurationElementHandle.cpp berryXMLPreferencesStorage.cpp ) set(CPP_FILES ) foreach(file ${SRC_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/${file}) endforeach(file ${SRC_CPP_FILES}) foreach(file ${INTERNAL_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/internal/${file}) endforeach(file ${INTERNAL_CPP_FILES}) diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/application/berryIApplication.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/application/berryIApplication.h index 16161f8d4e..2f48e4b33b 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/application/berryIApplication.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/application/berryIApplication.h @@ -1,102 +1,98 @@ /*=================================================================== 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 BERRYIAPPLICATION_H_ #define BERRYIAPPLICATION_H_ #include -#include "berryMacros.h" #include namespace berry { /** * Bootstrap type for an application. An IApplication represent executable * entry points into an application. An IApplication can be configured into * the Platform's org.blueberry.osgi.applications extension-point. * *

* Clients may implement this interface. *

- * - * @since 1.0 */ -struct org_blueberry_core_runtime_EXPORT IApplication { - - berryManifestMacro(IApplication, berry); +struct org_blueberry_core_runtime_EXPORT IApplication +{ /** * Exit object indicating normal termination */ static const int EXIT_OK; /** * Exit object requesting platform restart */ static const int EXIT_RESTART; /** * Exit object requesting that the command passed back be executed. Typically * this is used to relaunch BlueBerry with different command line arguments. When the executable is * relaunched the command line will be retrieved from the BlueBerry.exitdata system property. */ static const int EXIT_RELAUNCH; virtual ~IApplication(); /** * Starts this application with the given context and returns a result. This * method must not exit until the application is finished and is ready to exit. * The content of the context is unchecked and should conform to the expectations of * the application being invoked.

* * Applications can return any object they like. If an Integer is returned * it is treated as the program exit code if BlueBerry is exiting. *

* Note: This method is called by the platform; it is not intended * to be called directly by clients. *

* @return the return value of the application * @see #EXIT_OK * @see #EXIT_RESTART * @see #EXIT_RELAUNCH * @param context the application context to pass to the application * @exception Exception if there is a problem running this application. */ virtual int Start() = 0; /** * Forces this running application to exit. This method should wait until the * running application is ready to exit. The {@link #start()} * should already have exited or should exit very soon after this method exits

* * This method is only called to force an application to exit. * This method will not be called if an application exits normally from * the {@link #start()} method. *

* Note: This method is called by the platform; it is not intended * to be called directly by clients. *

*/ virtual void Stop() = 0; }; } Q_DECLARE_INTERFACE(berry::IApplication, "org.blueberry.IApplication") #endif /*BERRYIAPPLICATION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryDebugBreakpointManager.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryDebugBreakpointManager.cpp index ee6e6a2b50..065fe9910a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryDebugBreakpointManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryDebugBreakpointManager.cpp @@ -1,237 +1,237 @@ /*=================================================================== 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 "berryDebugBreakpointManager.h" #include "berryDebugUtil.h" #include "berryObject.h" #include "berryLog.h" #include #include #include #include #include #include #include #include #include #include namespace berry { const std::string DebugBreakpointManager::BREAKPOINTS_XML = "breakpoints.xml"; const std::string DebugBreakpointManager::BREAKPOINTS_TAG = "breakpoints"; const std::string DebugBreakpointManager::OBJECT_TAG = "object"; const std::string DebugBreakpointManager::SMARTPOINTER_TAG = "smartpointer"; const std::string DebugBreakpointManager::ID_ATTR = "id"; const std::string DebugBreakpointManager::CLASSNAME_ATTR = "className"; const std::string DebugBreakpointManager::OBJECTID_ATTR = "objectId"; const std::string DebugBreakpointManager::ENABLED_ATTR = "enabled"; void DebugBreakpointManager::AddSmartpointerBreakpoint(int smartPointerId, const Object* obj) { - BERRY_INFO << "Smartpointer breakpoint added: " << smartPointerId; + //BERRY_INFO << "Smartpointer breakpoint added: " << smartPointerId; m_SmartPointerBreakpoints[smartPointerId] = obj; } void DebugBreakpointManager::AddObjectBreakpoint(unsigned long objectTraceId) { - BERRY_INFO << "Object breakpoint added: " << objectTraceId; + //BERRY_INFO << "Object breakpoint added: " << objectTraceId; m_ObjectBreakpoints.insert(objectTraceId); } void DebugBreakpointManager::RemoveSmartpointerBreakpoint(int smartPointerId) { m_SmartPointerBreakpoints.erase(smartPointerId); } void DebugBreakpointManager::RemoveObjectBreakpoint(unsigned long objectTraceId) { m_ObjectBreakpoints.erase(objectTraceId); } const std::set& DebugBreakpointManager::GetObjectBreakpoints() const { return m_ObjectBreakpoints; } const Poco::HashMap& DebugBreakpointManager::GetSmartPointerBreakpoints() const { return m_SmartPointerBreakpoints; } bool DebugBreakpointManager::BreakAtObject(unsigned long traceId) const { return m_ObjectBreakpoints.find(traceId) != m_ObjectBreakpoints.end(); } bool DebugBreakpointManager::BreakAtSmartpointer(int spId) const { return m_SmartPointerBreakpoints.find(spId) != m_SmartPointerBreakpoints.end(); } #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugBreakpointManager::SaveState(const QString& path) const { Poco::XML::Document* doc = new Poco::XML::Document(); Poco::XML::Element* breakpoints = doc->createElement(BREAKPOINTS_TAG); doc->appendChild(breakpoints)->release(); for (std::set::const_iterator i = m_ObjectBreakpoints.begin(); i != m_ObjectBreakpoints.end(); ++i) { Poco::XML::Element* objectBreakpoint = doc->createElement(OBJECT_TAG); breakpoints->appendChild(objectBreakpoint)->release(); std::stringstream ss; ss << *i; objectBreakpoint->setAttribute(ID_ATTR, ss.str()); const Object* obj = DebugUtil::GetObject(*i); if (obj) { - objectBreakpoint->setAttribute(CLASSNAME_ATTR, obj->GetClassName()); + objectBreakpoint->setAttribute(CLASSNAME_ATTR, obj->GetClassName().toStdString()); } } for (Poco::HashMap::ConstIterator i = m_SmartPointerBreakpoints.begin(); i != m_SmartPointerBreakpoints.end(); ++i) { Poco::XML::Element* spBreakpoint = doc->createElement(SMARTPOINTER_TAG); breakpoints->appendChild(spBreakpoint)->release(); std::stringstream ss; ss << i->first; spBreakpoint->setAttribute(ID_ATTR, ss.str()); const Object* obj = i->second; if (i->second) { - spBreakpoint->setAttribute(CLASSNAME_ATTR, obj->GetClassName()); + spBreakpoint->setAttribute(CLASSNAME_ATTR, obj->GetClassName().toStdString()); ss.clear(); ss << obj->GetTraceId(); spBreakpoint->setAttribute(OBJECTID_ATTR, ss.str()); } } Poco::FileOutputStream writer(path.toStdString()); Poco::XML::DOMWriter out; out.setOptions(3); //write declaration and pretty print out.writeNode(writer, doc); doc->release(); } #else void DebugBreakpointManager::SaveState(const QString& /*path*/) const {} #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugBreakpointManager::RestoreState(const QString& path) { try { Poco::XML::DOMParser parser; Poco::FileInputStream reader(path.toStdString()); Poco::XML::InputSource source(reader); //source.setSystemId(baseDir); Poco::XML::Document* doc = parser.parse(&source); Poco::XML::Element* breakpoints = doc->documentElement(); if (breakpoints) { // restore object breakpoints Poco::XML::NodeList* elementList = breakpoints->getElementsByTagName( OBJECT_TAG); for (std::size_t i = 0; i < elementList->length(); i++) { Poco::XML::Element* elem = dynamic_cast (elementList->item(i)); if (!elem->hasAttribute(ID_ATTR)) continue; const std::string& attr = elem->getAttribute(ID_ATTR); int traceId = 0; try { traceId = Poco::NumberParser::parse(attr); } catch (const Poco::SyntaxException& e) { BERRY_WARN << e.displayText(); } DebugUtil::GetBreakpointManager()->AddObjectBreakpoint(traceId); } elementList->release(); // restore smartpointer breakpoints elementList = breakpoints->getElementsByTagName(SMARTPOINTER_TAG); for (std::size_t i = 0; i < elementList->length(); i++) { Poco::XML::Element* elem = dynamic_cast (elementList->item(i)); if (!elem->hasAttribute(ID_ATTR)) continue; const std::string& attr = elem->getAttribute(ID_ATTR); int spId = 0; try { spId = Poco::NumberParser::parse(attr); } catch (const Poco::SyntaxException& e) { BERRY_WARN << e.displayText(); } DebugUtil::GetBreakpointManager()->AddSmartpointerBreakpoint(spId); } elementList->release(); } doc->release(); } catch (Poco::XML::SAXParseException& e) { BERRY_WARN << e.displayText(); } catch (Poco::FileNotFoundException& /*e*/) { } catch (Poco::FileException& e) { BERRY_WARN << e.displayText(); } } #else void DebugBreakpointManager::RestoreState(const QString& /*path*/) { } #endif } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryDebugUtil.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryDebugUtil.cpp index ac00ceb843..65620aeac1 100755 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryDebugUtil.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryDebugUtil.cpp @@ -1,549 +1,549 @@ /*=================================================================== 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 "berryIDebugObjectListener.h" #include "berryDebugUtil.h" #include "berryObject.h" #include "berryLog.h" #include "berryPlatform.h" #include "berryDebugBreakpointManager.h" #include "internal/berryCTKPluginActivator.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace berry { static IDebugObjectListener::Events _G_ObjectEvents; const QString DebugUtil::DEBUG_UTIL_XML = "debugutil.xml"; const QString DebugUtil::DEBUGUTIL_TAG = "debugutil"; const QString DebugUtil::TRACEOBJECT_TAG = "traceObject"; const QString DebugUtil::TRACECLASS_TAG = "traceClass"; const QString DebugUtil::ID_ATTR = "id"; const QString DebugUtil::NAME_ATTR = "name"; QHash > DebugUtil::m_TraceIdToSmartPointerMap; QHash DebugUtil::m_TraceIdToObjectMap; QSet DebugUtil::m_TracedObjects; QSet DebugUtil::m_TracedClasses; class NotClassName: public std::unary_function { QString name; public: NotClassName(const QString& s) : name(s) { } bool operator()(const Object* entry) const { return name != entry->GetClassName(); } }; class AccumulateClassNames: public std::binary_function*, const Object*, QSet*> { public: QSet* operator()(QSet* names, const Object* entry) { names->insert(entry->GetClassName()); return names; } }; DebugBreakpointManager* DebugUtil::GetBreakpointManager() { static DebugBreakpointManager breakpointManager; return &breakpointManager; } #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::TraceObject(const Object* object) { BERRY_INFO << "Tracing enabled for: " << object->GetTraceId() << std::endl; m_TracedObjects.insert(object->GetTraceId()); _G_ObjectEvents.objTracingEvent(object->GetTraceId(), true, object); } #else void DebugUtil::TraceObject(const Object* /*object*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::TraceObject(unsigned int traceId) { BERRY_INFO << "Tracing enabled for: " << traceId << std::endl; m_TracedObjects.insert(traceId); TraceIdToObjectType::ConstIterator i = m_TraceIdToObjectMap.find(traceId); if (i != m_TraceIdToObjectMap.end()) _G_ObjectEvents.objTracingEvent(traceId, true, i.value()); else _G_ObjectEvents.objTracingEvent(traceId, true, 0); } #else void DebugUtil::TraceObject(unsigned int /*traceId*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::TraceClass(const QString& className) { BERRY_INFO << "Tracing enabled for: " << className << std::endl; m_TracedClasses.insert(className); //_G_ObjectEvents.objTracingEvent(object->GetTraceId(), true, object); } #else void DebugUtil::TraceClass(const QString& /*className*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::StopTracing(unsigned int traceId) { BERRY_INFO << "Tracing stopped for: " << traceId << std::endl; m_TracedObjects.remove(traceId); TraceIdToObjectType::ConstIterator i = m_TraceIdToObjectMap.find(traceId); if (i != m_TraceIdToObjectMap.end()) _G_ObjectEvents.objTracingEvent(traceId, false, i.value()); else _G_ObjectEvents.objTracingEvent(traceId, false, 0); } #else void DebugUtil::StopTracing(unsigned int /*traceId*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::StopTracing(const Object* obj) { BERRY_INFO << "Tracing stopped for: " << obj->GetTraceId() << std::endl; m_TracedObjects.remove(obj->GetTraceId()); _G_ObjectEvents.objTracingEvent(obj->GetTraceId(), false, obj); } #else void DebugUtil::StopTracing(const Object* /*obj*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::StopTracing(const QString& className) { BERRY_INFO << "Tracing stopped for: " << className << std::endl; m_TracedClasses.remove(className); //_G_ObjectEvents.objTracingEvent(obj->GetTraceId(), false, obj); } #else void DebugUtil::StopTracing(const QString& /*className*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER bool DebugUtil::IsTraced(const Object* object) { if (m_TracedObjects.find(object->GetTraceId()) != m_TracedObjects.end()) return true; if (m_TracedClasses.find(object->GetClassName()) != m_TracedClasses.end()) return true; return false; } #else bool DebugUtil::IsTraced(const Object* /*object*/) { return false; } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER bool DebugUtil::IsTraced(unsigned int traceId) { if (m_TracedObjects.find(traceId) != m_TracedObjects.end()) return true; TraceIdToObjectType::Iterator it = m_TraceIdToObjectMap.find(traceId); if (it != m_TraceIdToObjectMap.end()) { if (m_TracedClasses.find(it.value()->GetClassName()) != m_TracedClasses.end()) return true; } return false; } #else bool DebugUtil::IsTraced(unsigned int /*traceId*/) { return false; } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER bool DebugUtil::IsTraced(const QString& className) { return m_TracedClasses.find(className) != m_TracedClasses.end(); } #else bool DebugUtil::IsTraced(const QString& /*className*/) { return false; } #endif QSet DebugUtil::GetTracedObjects() { return m_TracedObjects; } const Object* DebugUtil::GetObject(unsigned int traceId) { return m_TraceIdToObjectMap[traceId]; } #ifdef BLUEBERRY_DEBUG_SMARTPOINTER QList DebugUtil::GetSmartPointerIDs( const Object* objectPointer, const QList& excludeList) { Q_ASSERT(objectPointer != 0); QList ids = m_TraceIdToSmartPointerMap[objectPointer->GetTraceId()]; for (QList::const_iterator iter = excludeList.begin(); iter != excludeList.end(); ++iter) ids.removeAll(*iter); return ids; } #else QList DebugUtil::GetSmartPointerIDs( const Object* /*objectPointer*/, const QList& /*excludeList*/) { return QList(); } #endif QList DebugUtil::GetRegisteredObjects() { return m_TraceIdToObjectMap.values(); } void DebugUtil::PrintSmartPointerIDs(const Object* objectPointer, const QList& excludeList) { qDebug() << "SmartPointer IDs [ "; if (IsTraced(objectPointer)) { QList ids = GetSmartPointerIDs(objectPointer, excludeList); for (QList::const_iterator iter = ids.begin(); iter != ids.end(); ++iter) { qDebug() << *iter << " "; } } else { qDebug() << "n/a "; } qDebug() << "]\n"; } void DebugUtil::AddObjectListener(IDebugObjectListener* listener) { _G_ObjectEvents.AddListener(listener); } void DebugUtil::RemoveObjectListener(IDebugObjectListener* listener) { _G_ObjectEvents.RemoveListener(listener); } void DebugUtil::ResetObjectSummary() { m_TraceIdToObjectMap.clear(); m_TraceIdToSmartPointerMap.clear(); m_TracedObjects.clear(); } bool DebugUtil::PrintObjectSummary(bool details) { QSet names; std::accumulate(m_TraceIdToObjectMap.begin(), m_TraceIdToObjectMap.end(), &names, AccumulateClassNames()); if (!names.isEmpty()) { std::cout << std::endl << std::endl << "#########################################################" << std::endl; std::cout << "######## berry::Object leakage summary: ########" << std::endl << std::endl; for (QSet::const_iterator i = names.begin(); i != names.end(); ++i) { PrintObjectSummary(*i, details); if (details) std::cout << std::endl; } std::cout << std::endl << "#########################################################" << std::endl << std::endl; } return !names.isEmpty(); } bool DebugUtil::PrintObjectSummary(const QString& className, bool details) { TraceIdToObjectType::ConstIterator endIter = std::remove_if(m_TraceIdToObjectMap.begin(), m_TraceIdToObjectMap.end(), NotClassName(className)); qDebug() << "Class:" << className; if (details) std::cout << std::endl; std::size_t count = 0; for (TraceIdToObjectType::ConstIterator iter = m_TraceIdToObjectMap.begin(); iter != endIter; ++iter, ++count) { if (details) { qDebug() << (*(iter.value())); PrintSmartPointerIDs(iter.value()); } } qDebug() << "(" << count << " instances)\n"; return (count!=0); } unsigned int& DebugUtil::GetSmartPointerCounter() { static unsigned int counter = 0; return counter; } #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::UnregisterSmartPointer(unsigned int smartPointerId, const Object* objectPointer) { poco_assert(objectPointer != 0); m_TraceIdToSmartPointerMap[objectPointer->GetTraceId()].removeAll(smartPointerId); _G_ObjectEvents.spDestroyedEvent(smartPointerId, objectPointer); } #else void DebugUtil::UnregisterSmartPointer(unsigned int /*smartPointerId*/, const Object* /*objectPointer*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::RegisterSmartPointer(unsigned int smartPointerId, const Object* objectPointer, bool /*recordStack*/) { poco_assert(objectPointer != 0); if (m_TracedClasses.find(objectPointer->GetClassName()) != m_TracedClasses.end() || m_TracedObjects.find(objectPointer->GetTraceId()) != m_TracedObjects.end()) { m_TraceIdToSmartPointerMap[objectPointer->GetTraceId()].push_back(smartPointerId); _G_ObjectEvents.spCreatedEvent(smartPointerId, objectPointer); } if (GetBreakpointManager()->BreakAtSmartpointer(smartPointerId)) poco_debugger_msg("SmartPointer Breakpoint reached"); } #else void DebugUtil::RegisterSmartPointer(unsigned int /*smartPointerId*/, const Object* /*objectPointer*/, bool /*recordStack*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::RegisterObject(const Object* objectPointer) { m_TraceIdToObjectMap.insert(objectPointer->GetTraceId(), objectPointer); _G_ObjectEvents.objCreatedEvent(objectPointer); if (GetBreakpointManager()->BreakAtObject(objectPointer->GetTraceId())) { std::string msg = "SmartPointer Breakpoint reached for "; - msg += objectPointer->GetClassName(); + msg += objectPointer->GetClassName().toStdString(); poco_debugger_msg(msg.c_str()); } } #else void DebugUtil::RegisterObject(const Object* /*objectPointer*/) { } #endif #ifdef BLUEBERRY_DEBUG_SMARTPOINTER void DebugUtil::UnregisterObject(const Object* objectPointer) { m_TraceIdToObjectMap.remove(objectPointer->GetTraceId()); _G_ObjectEvents.objDestroyedEvent(objectPointer); } #else void DebugUtil::UnregisterObject(const Object* /*objectPointer*/) { } #endif bool DebugUtil::GetPersistencePath(QDir& path) { QFileInfo statePath = CTKPluginActivator::getPluginContext()->getDataFile(QString()); path = statePath.absoluteFilePath(); return true; } void DebugUtil::SaveState(const QDir& path) { QString saveFile = path.absoluteFilePath(DEBUG_UTIL_XML); Poco::XML::Document* doc = new Poco::XML::Document(); Poco::XML::Element* debugutil = doc->createElement(DEBUGUTIL_TAG.toStdString()); doc->appendChild(debugutil)->release(); for (QSet::const_iterator i = m_TracedObjects.begin(); i != m_TracedObjects.end(); ++i) { Poco::XML::Element* traceObject = doc->createElement(TRACEOBJECT_TAG.toStdString()); debugutil->appendChild(traceObject)->release(); traceObject->setAttribute(ID_ATTR.toStdString(), QString::number(*i).toStdString()); } for (QSet::const_iterator i = m_TracedClasses.begin(); i != m_TracedClasses.end(); ++i) { Poco::XML::Element* traceClass = doc->createElement(TRACECLASS_TAG.toStdString()); debugutil->appendChild(traceClass)->release(); traceClass->setAttribute(NAME_ATTR.toStdString(), i->toStdString()); } try { Poco::FileOutputStream writer(saveFile.toStdString()); Poco::XML::DOMWriter out; out.setOptions(3); //write declaration and pretty print out.writeNode(writer, doc); doc->release(); // save BreakpointManager QString saveBM = path.absoluteFilePath(QString::fromStdString(DebugBreakpointManager::BREAKPOINTS_XML)); GetBreakpointManager()->SaveState(saveBM); } catch (Poco::FileException& e) { BERRY_WARN << e.displayText(); } } void DebugUtil::RestoreState(const QDir& path) { QString restoreFile = path.absoluteFilePath(DEBUG_UTIL_XML); try { Poco::XML::DOMParser parser; Poco::FileInputStream reader(restoreFile.toStdString()); Poco::XML::InputSource source(reader); //source.setSystemId(baseDir); Poco::XML::Document* doc = parser.parse(&source); Poco::XML::Element* debugutil = doc->documentElement(); if (debugutil) { // restore traced objects Poco::XML::NodeList* elementList = debugutil->getElementsByTagName(TRACEOBJECT_TAG.toStdString()); for (std::size_t i = 0; i < elementList->length(); i++) { Poco::XML::Element* elem = dynamic_cast (elementList->item(static_cast(i))); if (!elem->hasAttribute(ID_ATTR.toStdString())) continue; const std::string& attr = elem->getAttribute(ID_ATTR.toStdString()); int traceId = 0; try { traceId = Poco::NumberParser::parse(attr); } catch (const Poco::SyntaxException& e) { BERRY_WARN << e.displayText(); } DebugUtil::TraceObject(traceId); } elementList->release(); // restore traced classes elementList = debugutil->getElementsByTagName(TRACECLASS_TAG.toStdString()); for (std::size_t i = 0; i < elementList->length(); i++) { Poco::XML::Element* elem = dynamic_cast (elementList->item(static_cast(i))); if (!elem->hasAttribute(NAME_ATTR.toStdString())) continue; const std::string& traceClass = elem->getAttribute(NAME_ATTR.toStdString()); if (!traceClass.empty()) DebugUtil::TraceClass(QString::fromStdString(traceClass)); } elementList->release(); } doc->release(); } catch (Poco::XML::SAXParseException& e) { BERRY_WARN << e.displayText(); } catch (Poco::FileNotFoundException&) { } catch (Poco::FileException& e) { BERRY_WARN << e.displayText(); } // restore BreakpointManager GetBreakpointManager()->RestoreState(path.absoluteFilePath(QString::fromStdString(DebugBreakpointManager::BREAKPOINTS_XML))); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryFlags.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryFlags.h deleted file mode 100755 index f5c96f3564..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryFlags.h +++ /dev/null @@ -1,85 +0,0 @@ -/*=================================================================== - -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 BERRYFLAGS_H_ -#define BERRYFLAGS_H_ - -#include - -namespace berry { - -class org_blueberry_core_runtime_EXPORT Flag -{ - int i; -public: - inline Flag(int i); - inline operator int() const { return i; } -}; - -inline Flag::Flag(int ai) : i(ai) {} - -class org_blueberry_core_runtime_EXPORT IncompatibleFlag -{ - int i; -public: - inline explicit IncompatibleFlag(int i); - inline operator int() const { return i; } -}; - -inline IncompatibleFlag::IncompatibleFlag(int ai) : i(ai) {} - - -template -class Flags -{ - typedef void **Zero; - int i; -public: - typedef Enum enum_type; - inline Flags(const Flags &f) : i(f.i) {} - inline Flags(Enum f) : i(f) {} - inline Flags(Zero = 0) : i(0) {} - inline Flags(Flag f) : i(f) {} - - inline Flags &operator=(const Flags &f) { i = f.i; return *this; } - inline Flags &operator&=(int mask) { i &= mask; return *this; } - inline Flags &operator&=(unsigned int mask) { i &= mask; return *this; } - inline Flags &operator|=(Flags f) { i |= f.i; return *this; } - inline Flags &operator|=(Enum f) { i |= f; return *this; } - inline Flags &operator^=(Flags f) { i ^= f.i; return *this; } - inline Flags &operator^=(Enum f) { i ^= f; return *this; } - - inline operator int() const { return i; } - - inline Flags operator|(Flags f) const { Flags g; g.i = i | f.i; return g; } - inline Flags operator|(Enum f) const { Flags g; g.i = i | f; return g; } - inline Flags operator^(Flags f) const { Flags g; g.i = i ^ f.i; return g; } - inline Flags operator^(Enum f) const { Flags g; g.i = i ^ f; return g; } - inline Flags operator&(int mask) const { Flags g; g.i = i & mask; return g; } - inline Flags operator&(unsigned int mask) const { Flags g; g.i = i & mask; return g; } - inline Flags operator&(Enum f) const { Flags g; g.i = i & f; return g; } - inline Flags operator~() const { Flags g; g.i = ~i; return g; } - - inline bool operator!() const { return !i; } - - inline bool TestFlag(Enum f) const { return (i & f) == f; } - -}; - -} // namespace berry - -#endif /* BERRYFLAGS_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIAdaptable.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIAdaptable.h index cf9cf68b28..04cde820b9 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIAdaptable.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIAdaptable.h @@ -1,77 +1,91 @@ /*=================================================================== 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 _BERRY_IADAPTABLE_H_ #define _BERRY_IADAPTABLE_H_ #include -#include #include -#include +#include + +#include namespace berry { /** * An interface for an adaptable object. *

* Adaptable objects can be dynamically extended to provide different * interfaces (or "adapters"). Adapters are created by adapter * factories, which are in turn managed by type by adapter managers. *

* For example, *
  *     IAdaptable a = [some adaptable];
  *     IFoo x = (IFoo)a.getAdapter(IFoo.class);
  *     if (x != null)
  *         [do IFoo things with x]
  * 
*

* This interface can be used without OSGi running. *

* Clients may implement this interface, or obtain a default implementation * of this interface by subclassing PlatformObject. *

* @see IAdapterFactory * @see IAdapterManager * @see PlatformObject */ -struct org_blueberry_core_runtime_EXPORT IAdaptable { +struct org_blueberry_core_runtime_EXPORT IAdaptable +{ public: - berryNameMacro(berry::IAdaptable); - /** * Returns an object which is an instance of the given class * associated with this object. Returns null if * no such object can be found. * * @param adapterType the adapter class to look up * @return a object castable to the given class, * or null if this object does not * have an adapter for the given class */ - virtual Poco::Any GetAdapter(const QString& adapterType) = 0; + virtual Object* GetAdapter(const QString& adapterType) = 0; + + template + A* GetAdapter() + { + const char* typeName = qobject_interface_iid(); + if (typeName == NULL) + { + BERRY_WARN << "Error getting adapter for '" << Object::DemangleName(typeid(*this).name()) << "': " + << "Cannot get the interface id for type '" << Object::DemangleName(typeid(A).name()) + << "'. It is probably missing a Q_DECLARE_INTERFACE macro in its header."; + return NULL; + } + return dynamic_cast(this->GetAdapter(typeName)); + } virtual ~IAdaptable(); }; } // namespace berry #endif /*_BERRY_IADAPTABLE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIAdapterManager.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIAdapterManager.h index 4df2b65417..6c3384cb1d 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIAdapterManager.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIAdapterManager.h @@ -1,278 +1,287 @@ /*=================================================================== 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 BERRYIADAPTERMANAGER_H_ #define BERRYIADAPTERMANAGER_H_ #include #include #include "berryPlatformObject.h" #include "berryIAdapterFactory.h" -#include #include #include namespace berry { /** * An adapter manager maintains a registry of adapter factories. Clients * directly invoke methods on an adapter manager to register and unregister * adapters. All adaptable objects (that is, objects that implement the IAdaptable * interface) tunnel IAdaptable.getAdapter invocations to their * adapter manager's IAdapterManger.getAdapter method. The * adapter manager then forwards this request unmodified to the IAdapterFactory.getAdapter * method on one of the registered adapter factories. *

* Adapter factories can be registered programmatically using the registerAdapters * method. Alternatively, they can be registered declaratively using the * org.blueberry.core.runtime.adapters extension point. Factories registered * with this extension point will not be able to provide adapters until their * corresponding plugin has been activated. *

* The following code snippet shows how one might register an adapter of type * com.example.acme.Sticky on resources in the workspace. *

* *

  *  IAdapterFactory pr = new IAdapterFactory() {
  *    public Class[] getAdapterList() {
  *      return new Class[] { com.example.acme.Sticky.class };
  *    }
  *    public Object getAdapter(Object adaptableObject, Class adapterType) {
  *      IResource res = (IResource) adaptableObject;
  *      QualifiedName key = new QualifiedName("com.example.acme", "sticky-note");
  *      try {
  *        com.example.acme.Sticky v = (com.example.acme.Sticky) res.getSessionProperty(key);
  *        if (v == null) {
  *          v = new com.example.acme.Sticky();
  *          res.setSessionProperty(key, v);
  *        }
  *      } catch (CoreException e) {
  *        // unable to access session property - ignore
  *      }
  *      return v;
  *    }
  *  }
  *  Platform.getAdapterManager().registerAdapters(pr, IResource.class);
  *   
* *

* This interface can be used without OSGi running. *

* This interface is not intended to be implemented by clients. *

* @see IAdaptable * @see IAdapterFactory */ struct org_blueberry_core_runtime_EXPORT IAdapterManager: public Object { - berryInterfaceMacro(IAdapterManager, berry); + berryObjectMacro(berry::IAdapterManager) /** * This value can be returned to indicate that no applicable adapter factory * was found. * @since org.blueberry.equinox.common 3.3 */ static const int NONE; /** * This value can be returned to indicate that an adapter factory was found, * but has not been loaded. * @since org.blueberry.equinox.common 3.3 */ static const int NOT_LOADED; /** * This value can be returned to indicate that an adapter factory is loaded. * @since org.blueberry.equinox.common 3.3 */ static const int LOADED; - /** - * Returns the types that can be obtained by converting adaptableClass - * via this manager. Converting means that subsequent calls to getAdapter() - * or loadAdapter() could result in an adapted object. - *

- * Note that the returned types do not guarantee that - * a subsequent call to getAdapter with the same type as an argument - * will return a non-null result. If the factory's plug-in has not yet been - * loaded, or if the factory itself returns null, then - * getAdapter will still return null. - *

- * @param adaptableClass the adaptable class being queried - * @return an array of type names that can be obtained by converting - * adaptableClass via this manager. An empty array - * is returned if there are none. - * @since 3.1 - */ - virtual std::vector ComputeAdapterTypes( - const std::type_info& adaptableClass) = 0; - - /** - * Returns the class search order for a given class. The search order from a - * class with the definition
- * class X extends Y implements A, B
- * is as follows: - *
    - *
  • the target's class: X - *
  • X's superclasses in order to Object - *
  • a breadth-first traversal of the target class's interfaces in the - * order returned by getInterfaces (in the example, A and its - * superinterfaces then B and its superinterfaces)
  • - *
- * - * @param clazz the class for which to return the class order. - * @return the class search order for the given class. The returned - * search order will minimally contain the target class. - * @since 3.1 - */ - //public Class[] computeClassOrder(Class clazz); - /** * Returns a Poco::Any object which contains an instance of the given name associated * with the given adaptable. Returns an empty Poco::Any if no such object can * be found. *

* Note that this method will never cause plug-ins to be loaded. If the * only suitable factory is not yet loaded, this method will return an empty Poco::Any. * If activation of the plug-in providing the factory is required, use the * LoadAdapter method instead. * * @param adaptable the adaptable object being queried (usually an instance * of IAdaptable) * @param adapterTypeName the fully qualified name of the type of adapter to look up * @return a Poco::Any castable to the given adapter type, or empty * if the given adaptable object does not have an available adapter of the * given type */ template - Poco::Any GetAdapter(A adaptable, const std::string& adapterTypeName) { - return this->GetAdapter(Poco::Any(adaptable), adapterTypeName, false); + A* GetAdapter(const Object* adaptable) + { + const char* typeName = qobject_interface_iid(); + if (typeName == NULL) + { + BERRY_WARN << "Error getting adapter for '" << Object::DemangleName(typeid(*adaptable).name()) << "': " + << "Cannot get the interface id for type '" << Object::DemangleName(typeid(A).name()) + << "'. It is probably missing a Q_DECLARE_INTERFACE macro in its header."; + return NULL; + } + return dynamic_cast(this->GetAdapter(adaptable, typeName, false)); } + /** + * Returns an object which is an instance of the given class name associated + * with the given object. Returns null if no such object can + * be found. + *

+ * Note that this method will never cause plug-ins to be loaded. If the + * only suitable factory is not yet loaded, this method will return null. + * If activation of the plug-in providing the factory is required, use the + * loadAdapter method instead. + * + * @param adaptable the adaptable object being queried (usually an instance + * of IAdaptable) + * @param adapterTypeName the fully qualified name of the type of adapter to look up + * @return an object castable to the given adapter type, or null + * if the given adaptable object does not have an available adapter of the + * given type + */ + virtual Object* GetAdapter(const Object* adaptable, const QString& adapterTypeName) = 0; + /** * Returns whether there is an adapter factory registered that may be able * to convert adaptable to an object of type adapterTypeName. *

* Note that a return value of true does not guarantee that * a subsequent call to GetAdapter with the same arguments * will return a non-empty result. If the factory's plug-in has not yet been * loaded, or if the factory itself returns nothing, then * GetAdapter will still return an empty Poco::Any. * * @param adaptable the adaptable object being queried (usually an instance * of IAdaptable) * @param adapterTypeName the fully qualified class name of an adapter to * look up * @return true if there is an adapter factory that claims * it can convert adaptable to an object of type adapterType, * and false otherwise. */ - virtual bool HasAdapter(const std::string& adaptableType, const std::string& adapterType) = 0; + virtual bool HasAdapter(const Object* adaptableType, const QString& adapterType) = 0; + + template + int QueryAdapter(const Object* adaptable) + { + const char* typeName = qobject_interface_iid(); + if (typeName == NULL) + { + BERRY_WARN << "Error querying adapter manager for '" << Object::DemangleName(typeid(*adaptable).name()) << "': " + << "Cannot get the interface id for type '" << Object::DemangleName(typeid(A).name()) + << "'. It is probably missing a Q_DECLARE_INTERFACE macro in its header."; + return NONE; + } + return this->QueryAdapter(adaptable, typeName); + } /** * Returns a status of an adapter factory registered that may be able * to convert adaptable to an object of type adapterTypeName. *

* One of the following values can be returned:

    *
  • {@link berry::IAdapterManager::NONE} if no applicable adapter factory was found;
  • *
  • {@link berry::IAdapterManager::NOT_LOADED} if an adapter factory was found, but has not been loaded;
  • *
  • {@link berry::IAdapterManager::LOADED} if an adapter factory was found, and it is loaded.
  • *

* @param adaptable the adaptable object being queried (usually an instance * of IAdaptable) * @param adapterTypeName the fully qualified class name of an adapter to * look up * @return a status of the adapter */ - virtual int - QueryAdapter(const std::string& adaptableType, const std::string& adapterType) = 0; + virtual int QueryAdapter(const Object* adaptableType, const QString& adapterType) = 0; /** * Returns an object that is an instance of the given class name associated * with the given object. Returns an empty Poco::Any if no such object can * be found. *

* Note that unlike the GetAdapter methods, this method * will cause the plug-in that contributes the adapter factory to be loaded * if necessary. As such, this method should be used judiciously, in order * to avoid unnecessary plug-in activations. Most clients should avoid * activation by using GetAdapter instead. * * @param adaptable the adaptable object being queried (usually an instance * of IAdaptable) * @param adapterTypeName the fully qualified name of the type of adapter to look up * @return a Poco::Any castable to the given adapter type, or empty * if the given adaptable object does not have an available adapter of the * given type */ template - Poco::Any LoadAdapter(A adaptable, const std::string& adapterTypeName) { - return this->GetAdapter(Poco::Any(adaptable), adapterTypeName, true); + A* LoadAdapter(const Object* adaptable) + { + const char* typeName = qobject_interface_iid(); + if (typeName == NULL) + { + BERRY_WARN << "Error getting adapter for '" << Object::DemangleName(typeid(*adaptable).name()) << "': " + << "Cannot get the interface id for type '" << Object::DemangleName(typeid(A).name()) + << "'. It is probably missing a Q_DECLARE_INTERFACE macro in its header."; + return NULL; + } + return dynamic_cast(this->GetAdapter(adaptable, typeName, true)); } /** * Registers the given adapter factory as extending objects of the given * type. * * @param factory the adapter factory * @param adaptableTypeName the fully qualified typename being extended * @see #UnregisterAdapters(IAdapterFactory*) * @see #UnregisterAdapters(IAdapterFactory*, const std::adaptableTypeName&) */ virtual void RegisterAdapters(IAdapterFactory* factory, - const std::string& adaptableTypeName) = 0; + const QString& adaptableTypeName) = 0; /** * Removes the given adapter factory completely from the list of registered * factories. Equivalent to calling UnregisterAdapters(IAdapterFactory*, const std::string&) * on all classes against which it had been explicitly registered. Does * nothing if the given factory is not currently registered. * * @param factory the adapter factory to remove * @see #RegisterAdapters(IAdapterFactory*, const std::string&) */ virtual void UnregisterAdapters(IAdapterFactory* factory) = 0; /** * Removes the given adapter factory from the list of factories registered * as extending the given class. Does nothing if the given factory and type * combination is not registered. * * @param factory the adapter factory to remove * @param adaptableTypeName one of the type names against which the given factory is * registered * @see #RegisterAdapters(IAdapterFactory*, const std::string&) */ virtual void UnregisterAdapters(IAdapterFactory* factory, - const std::string& adaptableTypeName) = 0; + const QString& adaptableTypeName) = 0; -protected: +private: - virtual Poco::Any GetAdapter(Poco::Any adaptable, const std::string& adapterType, bool force) = 0; + virtual Object* GetAdapter(const Object* adaptable, const QString& adapterType, bool force) = 0; }; } // namespace berry Q_DECLARE_INTERFACE(berry::IAdapterManager, "org.blueberry.service.IAdapterManager") #endif /*BERRYIADAPTERMANAGER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.h index 676fd741a1..7e6586a608 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.h @@ -1,48 +1,48 @@ /*=================================================================== 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 BERRYIBERRYPREFERENCES_H_ #define BERRYIBERRYPREFERENCES_H_ #include #include "berryIPreferences.h" #include "berryMessage.h" namespace berry { /// /// Like IEclipsePreferences an extension to the osgi-IPreferences /// to send out events when nodes or values changed in a node. /// struct org_blueberry_core_runtime_EXPORT IBerryPreferences : virtual public IPreferences { - berryInterfaceMacro(IBerryPreferences, berry); + berryObjectMacro(berry::IBerryPreferences) virtual ~IBerryPreferences(); /// /// Invoked when this node was changed, that is when a property /// was changed or when a new child node was inserted. /// berry::Message1 OnChanged; }; } // namespace berry #endif /*BERRYIBERRYPREFERENCES_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIDebugObjectListener.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIDebugObjectListener.cpp index 55ee32485d..988c4e21cf 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIDebugObjectListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIDebugObjectListener.cpp @@ -1,45 +1,49 @@ /*=================================================================== 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 "berryIDebugObjectListener.h" namespace berry { void IDebugObjectListener::Events::AddListener(IDebugObjectListener* l) { if (l == 0) return; Types t = l->GetEventTypes(); if (t & OBJECT_CREATED) objCreatedEvent += ObjDelegate(l, &IDebugObjectListener::ObjectCreated); if (t & OBJECT_DESTROYED) objDestroyedEvent += ObjDelegate(l, &IDebugObjectListener::ObjectDestroyed); if (t & OBJECT_TRACING) objTracingEvent += TraceDelegate(l, &IDebugObjectListener::ObjectTracingChanged); if (t & SMARTPOINTER_CREATED) spCreatedEvent += SPDelegate(l, &IDebugObjectListener::SmartPointerCreated); if (t & SMARTPOINTER_CREATED) spDestroyedEvent += SPDelegate(l, &IDebugObjectListener::SmartPointerDestroyed); } void IDebugObjectListener::Events::RemoveListener(IDebugObjectListener* l) { if (l == 0) return; objCreatedEvent -= ObjDelegate(l, &IDebugObjectListener::ObjectCreated); objDestroyedEvent -= ObjDelegate(l, &IDebugObjectListener::ObjectDestroyed); objTracingEvent -= TraceDelegate(l, &IDebugObjectListener::ObjectTracingChanged); spCreatedEvent -= SPDelegate(l, &IDebugObjectListener::SmartPointerCreated); spDestroyedEvent -= SPDelegate(l, &IDebugObjectListener::SmartPointerDestroyed); } +IDebugObjectListener::~IDebugObjectListener() +{ +} + } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIDebugObjectListener.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIDebugObjectListener.h index 8501349ea4..0c0af1e8c3 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIDebugObjectListener.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIDebugObjectListener.h @@ -1,99 +1,96 @@ /*=================================================================== 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 BERRYIDEBUGOBJECTLISTENER_H_ #define BERRYIDEBUGOBJECTLISTENER_H_ -#include -#include +#include "berryMessage.h" #include namespace berry { -struct org_blueberry_core_runtime_EXPORT IDebugObjectListener: public Object -{ +class Object; - berryInterfaceMacro(IDebugObjectListener, berry) +struct org_blueberry_core_runtime_EXPORT IDebugObjectListener +{ struct org_blueberry_core_runtime_EXPORT Events { enum Type { NONE = 0x00000000, OBJECT_CREATED = 0x00000001, OBJECT_DESTROYED = 0x00000002, OBJECT_TRACING = 0x00000004, SMARTPOINTER_CREATED = 0x00000008, SMARTPOINTER_DESTROYED = 0x00000010, ALL = 0xffffffff }; - BERRY_DECLARE_FLAGS(Types, Type) + Q_DECLARE_FLAGS(Types, Type) typedef Message1 ObjectEventType; typedef Message3 TracingEventType; typedef Message2 SmartPointerEventType; ObjectEventType objCreatedEvent; ObjectEventType objDestroyedEvent; TracingEventType objTracingEvent; SmartPointerEventType spCreatedEvent; SmartPointerEventType spDestroyedEvent; void AddListener(IDebugObjectListener* listener); void RemoveListener(IDebugObjectListener* listener); typedef MessageDelegate1 ObjDelegate; typedef MessageDelegate3 TraceDelegate; typedef MessageDelegate2 SPDelegate; }; - virtual ~IDebugObjectListener() - { - } + virtual ~IDebugObjectListener(); virtual Events::Types GetEventTypes() const = 0; virtual void ObjectCreated(const Object* /*obj*/) { } virtual void ObjectDestroyed(const Object* /*obj*/) { } virtual void ObjectTracingChanged(unsigned int /*traceId*/, bool /*enabled*/ = true, const Object* /*obj*/ = 0) { } virtual void SmartPointerCreated(unsigned int /*id*/, const Object* /*obj*/) { } virtual void SmartPointerDestroyed(unsigned int /*id*/, const Object* /*obj*/) { } }; } -BERRY_DECLARE_OPERATORS_FOR_FLAGS(berry::IDebugObjectListener::Events::Types) +Q_DECLARE_OPERATORS_FOR_FLAGS(berry::IDebugObjectListener::Events::Types) #endif /* BERRYIDEBUGOBJECTLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIPreferences.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIPreferences.h index a779fb52b5..dc14cf7ea9 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIPreferences.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIPreferences.h @@ -1,705 +1,705 @@ /*=================================================================== 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 BERRYIPREFERENCES_H_ #define BERRYIPREFERENCES_H_ #include #include "berryObject.h" #include "berryBackingStoreException.h" namespace berry { /** * A node in a hierarchical collection of preference data. * *

* This interface allows applications to store and retrieve user and system * preference data. This data is stored persistently in an * implementation-dependent backing store. Typical implementations include flat * files, OS-specific registries, directory servers and SQL databases. * *

* For each bundle, there is a separate tree of nodes for each user, and one for * system preferences. The precise description of "user" and "system" will vary * from one bundle to another. Typical information stored in the user preference * tree might include font choice, and color choice for a bundle which interacts * with the user via a servlet. Typical information stored in the system * preference tree might include installation data, or things like high score * information for a game program. * *

* Nodes in a preference tree are named in a similar fashion to directories in a * hierarchical file system. Every node in a preference tree has a node name * (which is not necessarily unique), a unique absolute path name , * and a path name relative to each ancestor including itself. * *

* The root node has a node name of the empty QString object (""). * Every other node has an arbitrary node name, specified at the time it is * created. The only restrictions on this name are that it cannot be the empty * string, and it cannot contain the slash character ('/'). * *

* The root node has an absolute path name of "/". Children of the * root node have absolute path names of "/" + <node name> * . All other nodes have absolute path names of <parent's absolute * path name> + "/" + <node name> . Note that * all absolute path names begin with the slash character. * *

* A node n 's path name relative to its ancestor a is simply the * string that must be appended to a 's absolute path name in order to * form n 's absolute path name, with the initial slash character (if * present) removed. Note that: *

    *
  • No relative path names begin with the slash character. *
  • Every node's path name relative to itself is the empty string. *
  • Every node's path name relative to its parent is its node name (except * for the root node, which does not have a parent). *
  • Every node's path name relative to the root is its absolute path name * with the initial slash character removed. *
* *

* Note finally that: *

    *
  • No path name contains multiple consecutive slash characters. *
  • No path name with the exception of the root's absolute path name end in * the slash character. *
  • Any string that conforms to these two rules is a valid path name. *
* *

* Each Preference node has zero or more properties associated with * it, where a property consists of a name and a value. The bundle writer is * free to choose any appropriate names for properties. Their values can be of * type QString,long,int,bool, * std::vector,float, or double but they can * always be accessed as if they were QString objects. * *

* All node name and property name comparisons are case-sensitive. * *

* All of the methods that modify preference data are permitted to operate * asynchronously; they may return immediately, and changes will eventually * propagate to the persistent backing store, with an implementation-dependent * delay. The flush method may be used to synchronously force updates * to the backing store. * *

* Implementations must automatically attempt to flush to the backing store any * pending updates for a bundle's preferences when the bundle is stopped or * otherwise ungets the IPreferences Service. * *

* The methods in this class may be invoked concurrently by multiple threads in * a single Java Virtual Machine (JVM) without the need for external * synchronization, and the results will be equivalent to some serial execution. * If this class is used concurrently by multiple JVMs that store their * preference data in the same backing store, the data store will not be * corrupted, but no other guarantees are made concerning the consistency of the * preference data. * * * @version $Revision$ */ struct org_blueberry_core_runtime_EXPORT IPreferences : virtual public Object { - berryInterfaceMacro(IPreferences, berry); + berryObjectMacro(berry::IPreferences) virtual ~IPreferences(); /** * Associates the specified value with the specified key in this node. * * @param key key with which the specified value is to be associated. * @param value value to be associated with the specified key. * @throws NullPointerException if key or value is * null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. */ virtual void Put(const QString& key, const QString& value) = 0; /** * Returns the value associated with the specified key in this * node. Returns the specified default if there is no value associated with * the key, or the backing store is inaccessible. * * @param key key whose associated value is to be returned. * @param def the value to be returned in the event that this node has no * value associated with key or the backing store is * inaccessible. * @return the value associated with key, or def if * no value is associated with key. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @throws NullPointerException if key is null. (A * null default is permitted.) */ virtual QString Get(const QString& key, const QString& def) const = 0; /** * Removes the value associated with the specified key in this * node, if any. * * @param key key whose mapping is to be removed from this node. * @see #get(const QString&,const QString&) * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. */ virtual void Remove(const QString& key) = 0; /** * Removes all of the properties (key-value associations) in this node. This * call has no effect on any descendants of this node. * * @throws BackingStoreException if this operation cannot be completed due * to a failure in the backing store, or inability to communicate * with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #remove(const QString&) */ virtual void Clear() = 0; /** * Associates a QString object representing the specified * int value with the specified key in this node. The * associated string is the one that would be returned if the int * value were passed to Integer.toString(int). This method is * intended for use in conjunction with {@link #getInt}method. * *

* Implementor's note: it is not necessary that the property value * be represented by a QString object in the backing store. If the * backing store supports integer values, it is not unreasonable to use * them. This implementation detail is not visible through the * IPreferences API, which allows the value to be read as an * int (with getInt or a QString (with * get) type. * * @param key key with which the string form of value is to be associated. * @param value value whose string form is to be associated with * key. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #getInt(const QString&,int) */ virtual void PutInt(const QString& key, int value) = 0; /** * Returns the int value represented by the QString * object associated with the specified key in this node. The * QString object is converted to an int as by * Integer.parseInt(QString). Returns the specified default if * there is no value associated with the key, the backing store * is inaccessible, or if Integer.parseInt(QString) would throw a * NumberFormatException if the associated value were * passed. This method is intended for use in conjunction with the * {@link #putInt}method. * * @param key key whose associated value is to be returned as an * int. * @param def the value to be returned in the event that this node has no * value associated with key or the associated value * cannot be interpreted as an int or the backing store is * inaccessible. * @return the int value represented by the QString * object associated with key in this node, or * def if the associated value does not exist or cannot * be interpreted as an int type. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #putInt(const QString&,int) * @see #get(const QString&,const QString&) */ virtual int GetInt(const QString& key, int def) const = 0; /** * Associates a QString object representing the specified * long value with the specified key in this node. The * associated QString object is the one that would be returned if * the long value were passed to Long.toString(long). * This method is intended for use in conjunction with the {@link #getLong} * method. * *

* Implementor's note: it is not necessary that the value * be represented by a QString type in the backing store. If the * backing store supports long values, it is not unreasonable to * use them. This implementation detail is not visible through the * IPreferences API, which allows the value to be read as a * long (with getLong or a QString (with * get) type. * * @param key key with which the string form of value * is to be associated. * @param value value whose string form is to be associated with * key. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #getLong(const QString&,long) */ virtual void PutLong(const QString& key, long value) = 0; /** * Returns the long value represented by the QString * object associated with the specified key in this node. The * QString object is converted to a long as by * Long.parseLong(QString). Returns the specified default if * there is no value associated with the key, the backing store * is inaccessible, or if Long.parseLong(QString) would throw a * NumberFormatException if the associated value were * passed. This method is intended for use in conjunction with the * {@link #putLong}method. * * @param key key whose associated value is to be returned as a * long value. * @param def the value to be returned in the event that this node has no * value associated with key or the associated value * cannot be interpreted as a long type or the backing * store is inaccessible. * @return the long value represented by the QString * object associated with key in this node, or * def if the associated value does not exist or cannot * be interpreted as a long type. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #putLong(const QString&,long) * @see #get(const QString&,const QString&) */ virtual long GetLong(const QString& key, long def) const = 0; /** * Associates a QString object representing the specified * bool value with the specified key in this node. The * associated string is "true" if the value is true, and "false" * if it is false. This method is intended for use in * conjunction with the {@link #getBool}method. * *

* Implementor's note: it is not necessary that the value be * represented by a string in the backing store. If the backing store * supports bool values, it is not unreasonable to use them. * This implementation detail is not visible through the IPreferences * API, which allows the value to be read as a bool * (with getBool) or a QString (with get) * type. * * @param key key with which the string form of value is to be * associated. * @param value value whose string form is to be associated with * key. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #getBool(const QString&,bool) * @see #get(const QString&,const QString&) */ virtual void PutBool(const QString& key, bool value) = 0; /** * Returns the bool value represented by the QString * object associated with the specified key in this node. Valid * strings are "true", which represents true, and "false", which * represents false. Case is ignored, so, for example, "TRUE" * and "False" are also valid. This method is intended for use in * conjunction with the {@link #putBool}method. * *

* Returns the specified default if there is no value associated with the * key, the backing store is inaccessible, or if the associated * value is something other than "true" or "false", ignoring case. * * @param key key whose associated value is to be returned as a * bool. * @param def the value to be returned in the event that this node has no * value associated with key or the associated value * cannot be interpreted as a bool or the backing store * is inaccessible. * @return the bool value represented by the std::string * object associated with key in this node, or * null if the associated value does not exist or cannot * be interpreted as a bool. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #get(const QString&,const QString&) * @see #putBool(const QString&,bool) */ virtual bool GetBool(const QString& key, bool def) const = 0; /** * Associates a QString object representing the specified * float value with the specified key in this node. * The associated QString object is the one that would be returned * if the float value were passed to * Float.toString(float). This method is intended for use in * conjunction with the {@link #getFloat}method. * *

* Implementor's note: it is not necessary that the value be * represented by a string in the backing store. If the backing store * supports float values, it is not unreasonable to use them. * This implementation detail is not visible through the IPreferences * API, which allows the value to be read as a float (with * getFloat) or a QString (with get) type. * * @param key key with which the string form of value is to be * associated. * @param value value whose string form is to be associated with * key. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #getFloat(const QString&,float) */ virtual void PutFloat(const QString& key, float value) = 0; /** * Returns the float value represented by the QString * object associated with the specified key in this node. The * QString object is converted to a float value as by * Float.parseFloat(QString). Returns the specified default if * there is no value associated with the key, the backing store * is inaccessible, or if Float.parseFloat(QString) would throw a * NumberFormatException if the associated value were passed. * This method is intended for use in conjunction with the {@link #putFloat} * method. * * @param key key whose associated value is to be returned as a * float value. * @param def the value to be returned in the event that this node has no * value associated with key or the associated value * cannot be interpreted as a float type or the backing * store is inaccessible. * @return the float value represented by the string associated * with key in this node, or def if the * associated value does not exist or cannot be interpreted as a * float type. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @throws NullPointerException if key is null. * @see #putFloat(const QString&,float) * @see #get(const QString&,const QString&) */ virtual float GetFloat(const QString& key, float def) const = 0; /** * Associates a QString object representing the specified * double value with the specified key in this node. * The associated QString object is the one that would be returned * if the double value were passed to * Double.toString(double). This method is intended for use in * conjunction with the {@link #getDouble}method * *

* Implementor's note: it is not necessary that the value be * represented by a string in the backing store. If the backing store * supports double values, it is not unreasonable to use them. * This implementation detail is not visible through the IPreferences * API, which allows the value to be read as a double (with * getDouble) or a QString (with get) * type. * * @param key key with which the string form of value is to be * associated. * @param value value whose string form is to be associated with * key. * @throws NullPointerException if key is null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #getDouble(const QString&,double) */ virtual void PutDouble(const QString& key, double value) = 0; /** * Returns the double value represented by the QString * object associated with the specified key in this node. The * QString object is converted to a double value as by * Double.parseDouble(QString). Returns the specified default if * there is no value associated with the key, the backing store * is inaccessible, or if Double.parseDouble(QString) would throw * a NumberFormatException if the associated value were passed. * This method is intended for use in conjunction with the * {@link #putDouble}method. * * @param key key whose associated value is to be returned as a * double value. * @param def the value to be returned in the event that this node has no * value associated with key or the associated value * cannot be interpreted as a double type or the backing * store is inaccessible. * @return the double value represented by the QString * object associated with key in this node, or * def if the associated value does not exist or cannot * be interpreted as a double type. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the the {@link #removeNode()}method. * @throws NullPointerException if key is null. * @see #putDouble(const QString&,double) * @see #get(const QString&,const QString&) */ virtual double GetDouble(const QString& key, double def) const = 0; /** * Associates a QByteArray object representing the specified * QByteArray with the specified key in this node. The * associated QByteArray object is stored in Base64 encoding. * This method is intended for use in conjunction with the * {@link #getByteArray}method. * * @param key key with which the string form of value * is to be associated. * @param value value whose string form is to be associated with * key. * @throws NullPointerException if key or value is * null. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #GetByteArray(const QString&,const QByteArray&) * @see #Get(const QString&,const QString&) */ virtual void PutByteArray(const QString& key, const QByteArray& value) = 0; /** * Returns the std::vector value represented by the QString * object associated with the specified key in this node. Valid * QString objects are Base64 encoded binary data, as * defined in RFC 2045 , * Section 6.8, with one minor change: the string must consist solely of * characters from the Base64 Alphabet ; no newline characters or * extraneous characters are permitted. This method is intended for use in * conjunction with the {@link #putByteArray}method. * *

* Returns the specified default if there is no value associated with the * key, the backing store is inaccessible, or if the associated * value is not a valid Base64 encoded byte array (as defined above). * * @param key key whose associated value is to be returned as a * std::vector object. * @param def the value to be returned in the event that this node has no * value associated with key or the associated value * cannot be interpreted as a std::vector type, or the backing * store is inaccessible. * @return the std::vector value represented by the QString * object associated with key in this node, or * def if the associated value does not exist or cannot * be interpreted as a std::vector. * @throws NullPointerException if key is null. (A * null value for def is permitted.) * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #get(const QString&,const QString&) * @see #putByteArray(const QString&,std::vector) */ virtual QByteArray GetByteArray(const QString& key, const QByteArray& def) const = 0; /** * Returns all of the keys that have an associated value in this node. (The * returned array will be of size zero if this node has no preferences and * not null!) * * @return an array of the keys that have an associated value in this node. * @throws BackingStoreException if this operation cannot be completed due * to a failure in the backing store, or inability to communicate * with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. */ virtual QStringList Keys() const = 0; /** * Returns the names of the children of this node. (The returned array will * be of size zero if this node has no children and not null!) * * @return the names of the children of this node. * @throws BackingStoreException if this operation cannot be completed due * to a failure in the backing store, or inability to communicate * with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. */ virtual QStringList ChildrenNames() const = 0; /** * Returns the parent of this node, or null if this is the root. * * @return the parent of this node. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. */ virtual IPreferences::Pointer Parent() const = 0; /** * Returns a named IPreferences object (node), creating it and any * of its ancestors if they do not already exist. Accepts a relative or * absolute pathname. Absolute pathnames (which begin with '/') * are interpreted relative to the root of this node. Relative pathnames * (which begin with any character other than '/') are * interpreted relative to this node itself. The empty string ("") * is a valid relative pathname, referring to this node itself. * *

* If the returned node did not exist prior to this call, this node and any * ancestors that were created by this call are not guaranteed to become * persistent until the flush method is called on the returned * node (or one of its descendants). * * @param pathName the path name of the IPreferences object to * return. * @return the specified IPreferences object. * @throws IllegalArgumentException if the path name is invalid. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @throws NullPointerException if path name is null. * @see #flush() */ virtual IPreferences::Pointer Node(const QString& pathName) = 0; /** * Returns true if the named node exists. Accepts a relative or absolute * pathname. Absolute pathnames (which begin with '/') are * interpreted relative to the root of this node. Relative pathnames (which * begin with any character other than '/') are interpreted * relative to this node itself. The pathname "" is valid, and * refers to this node itself. * *

* If this node (or an ancestor) has already been removed with the * {@link #removeNode()}method, it is legal to invoke this method, * but only with the pathname ""; the invocation will return * false. Thus, the idiom p.nodeExists("") may be * used to test whether p has been removed. * * @param pathName the path name of the node whose existence is to be * checked. * @return true if the specified node exists. * @throws BackingStoreException if this operation cannot be completed due * to a failure in the backing store, or inability to communicate * with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method and * pathname is not the empty string (""). * @throws IllegalArgumentException if the path name is invalid (i.e., it * contains multiple consecutive slash characters, or ends with a * slash character and is more than one character long). */ virtual bool NodeExists(const QString& pathName) const = 0; /** * Removes this node and all of its descendants, invalidating any properties * contained in the removed nodes. Once a node has been removed, attempting * any method other than name(),absolutePath() or * nodeExists("") on the corresponding IPreferences * instance will fail with an IllegalStateException. (The * methods defined on Object can still be invoked on a node after * it has been removed; they will not throw IllegalStateException.) * *

* The removal is not guaranteed to be persistent until the flush * method is called on the parent of this node. * * @throws IllegalStateException if this node (or an ancestor) has already * been removed with the {@link #removeNode()}method. * @throws BackingStoreException if this operation cannot be completed due * to a failure in the backing store, or inability to communicate * with it. * @see #flush() */ virtual void RemoveNode() throw(Poco::Exception, BackingStoreException) = 0; /** * Returns this node's name, relative to its parent. * * @return this node's name, relative to its parent. */ virtual QString Name() const = 0; /** * Returns this node's absolute path name. Note that: *

    *
  • Root node - The path name of the root node is "/". *
  • Slash at end - Path names other than that of the root node may not * end in slash ('/'). *
  • Unusual names -"." and ".." have no * special significance in path names. *
  • Illegal names - The only illegal path names are those that contain * multiple consecutive slashes, or that end in slash and are not the root. *
* * @return this node's absolute path name. */ virtual QString AbsolutePath() const = 0; /** * Forces any changes in the contents of this node and its descendants to * the persistent store. * *

* Once this method returns successfully, it is safe to assume that all * changes made in the subtree rooted at this node prior to the method * invocation have become permanent. * *

* Implementations are free to flush changes into the persistent store at * any time. They do not need to wait for this method to be called. * *

* When a flush occurs on a newly created node, it is made persistent, as * are any ancestors (and descendants) that have yet to be made persistent. * Note however that any properties value changes in ancestors are not * guaranteed to be made persistent. * * @throws BackingStoreException if this operation cannot be completed due * to a failure in the backing store, or inability to communicate * with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #sync() */ virtual void Flush() = 0; /** * Ensures that future reads from this node and its descendants reflect any * changes that were committed to the persistent store (from any VM) prior * to the sync invocation. As a side-effect, forces any changes * in the contents of this node and its descendants to the persistent store, * as if the flush method had been invoked on this node. * * @throws BackingStoreException if this operation cannot be completed due * to a failure in the backing store, or inability to communicate * with it. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()}method. * @see #flush() */ virtual void Sync() = 0; }; } // namespace berry #endif /*BERRYIPREFERENCES_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryISafeRunnable.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryISafeRunnable.h index 6b771864ab..d5d434628b 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryISafeRunnable.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryISafeRunnable.h @@ -1,102 +1,102 @@ /*=================================================================== 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 BERRYISAFERUNNABLE_H_ #define BERRYISAFERUNNABLE_H_ #include #include #include namespace berry { /** * Safe runnables represent blocks of code and associated exception * handlers. They are typically used when a plug-in needs to call some * untrusted code (e.g., code contributed by another plug-in via an * extension). *

* This interface can be used without OSGi running. *

* Clients may implement this interface. *

* @see SafeRunner#run(ISafeRunnable) */ struct org_blueberry_core_runtime_EXPORT ISafeRunnable: public Object { -berryInterfaceMacro(ISafeRunnable, berry); + berryObjectMacro(berry::ISafeRunnable) /** * Handles an exception thrown by this runnable's run * method. The processing done here should be specific to the * particular usecase for this runnable. Generalized exception * processing (e.g., logging in the platform's log) is done by the * Platform's run mechanism. * * @param exception an exception which occurred during processing * the body of this runnable (i.e., in run()) * @see SafeRunner#run(ISafeRunnable) */ virtual void HandleException(const std::exception& exception) = 0; /** * Runs this runnable. Any exceptions thrown from this method will * be passed to this runnable's handleException * method. * * @exception Exception if a problem occurred while running this method. * The exception will be processed by handleException * @see SafeRunner#run(ISafeRunnable) */ virtual void Run() = 0; }; template struct SafeRunnableDelegate: public ISafeRunnable { typedef void(R::*RunCallback)(); typedef void(R::*HandleExcCallback)(const std::exception&); SafeRunnableDelegate(R* runnable, RunCallback func, HandleExcCallback handleFunc = 0) : m_Runnable(runnable), m_RunFunc(func), m_HandleExcFunc(handleFunc) { } void Run() { m_Runnable->*m_RunFunc(); } void HandleException(const std::exception& exception) { if (m_HandleExcFunc) m_Runnable->*m_HandleExcFunc(exception); } private: R* m_Runnable; RunCallback m_RunFunc; HandleExcCallback m_HandleExcFunc; }; } #endif /* BERRYISAFERUNNABLE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIStatus.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIStatus.h index 04e051e327..5407145dbb 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIStatus.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIStatus.h @@ -1,206 +1,204 @@ /*=================================================================== 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 BERRYISTATUS_H_ #define BERRYISTATUS_H_ #include #include -#include #include namespace berry { /** * A status object represents the outcome of an operation. * All CoreExceptions carry a status object to indicate * what went wrong. Status objects are also returned by methods needing * to provide details of failures (e.g., validation methods). *

* A status carries the following information: *

    *
  • plug-in identifier (required)
  • *
  • severity (required)
  • *
  • status code (required)
  • *
  • message (required) - localized to current locale
  • *
  • exception (optional) - for problems stemming from a failure at * a lower level
  • *
* Some status objects, known as multi-statuses, have other status objects * as children. *

*

* The class Status is the standard public implementation * of status objects; the subclass MultiStatus is the * implements multi-status objects. *

* This interface can be used without OSGi running. *

* @see MultiStatus * @see Status */ struct org_blueberry_core_runtime_EXPORT IStatus: public Object { - - berryInterfaceMacro(IStatus, berry); + berryObjectMacro(berry::IStatus) enum Severity { /** Status severity constant (value 0) indicating this status represents the nominal case. * This constant is also used as the status code representing the nominal case. */ OK_TYPE = 0x00, /** Status type severity (bit mask, value 1) indicating this status is informational only. */ INFO_TYPE = 0x01, /** Status type severity (bit mask, value 2) indicating this status represents a warning. */ WARNING_TYPE = 0x02, /** Status type severity (bit mask, value 4) indicating this status represents an error. */ ERROR_TYPE = 0x04, /** Status type severity (bit mask, value 8) indicating this status represents a cancelation. */ CANCEL_TYPE = 0x08 }; Q_DECLARE_FLAGS(Severities, Severity) /** * Returns a list of status object immediately contained in this * multi-status, or an empty list if this is not a multi-status. * * @return an array of status objects * @see #isMultiStatus() */ virtual QList GetChildren() const = 0; /** * Returns the plug-in-specific status code describing the outcome. * * @return plug-in-specific status code */ virtual int GetCode() const = 0; /** * Returns the relevant low-level exception, or null if none. * For example, when an operation fails because of a network communications * failure, this might return the java.io.IOException * describing the exact nature of that failure. * * @return the relevant low-level exception, or null if none */ virtual const ctkException* GetException() const = 0; /** * Returns the message describing the outcome. * The message is localized to the current locale. * * @return a localized message */ virtual QString GetMessage() const = 0; /** * Returns the unique identifier of the plug-in associated with this status * (this is the plug-in that defines the meaning of the status code). * * @return the unique identifier of the relevant plug-in */ virtual QString GetPlugin() const = 0; /** * Returns the severity. The severities are as follows (in * descending order): *
    *
  • CANCEL_TYPE - cancelation occurred
  • *
  • ERROR_TYPE - a serious error (most severe)
  • *
  • WARNING_TYPE - a warning (less severe)
  • *
  • INFO_TYPE - an informational ("fyi") message (least severe)
  • *
  • OK_TYPE - everything is just fine
  • *
*

* The severity of a multi-status is defined to be the maximum * severity of any of its children, or OK if it has * no children. *

* * @return the severity: one of OK_TYPE, ERROR_TYPE, * INFO_TYPE, WARNING_TYPE, or CANCEL_TYPE * @see #matches(int) */ virtual Severity GetSeverity() const = 0; /** * Returns whether this status is a multi-status. * A multi-status describes the outcome of an operation * involving multiple operands. *

* The severity of a multi-status is derived from the severities * of its children; a multi-status with no children is * OK_TYPE by definition. * A multi-status carries a plug-in identifier, a status code, * a message, and an optional exception. Clients may treat * multi-status objects in a multi-status unaware way. *

* * @return true for a multi-status, * false otherwise * @see #getChildren() */ virtual bool IsMultiStatus() const = 0; /** * Returns whether this status indicates everything is okay * (neither info, warning, nor error). * * @return true if this status has severity * OK, and false otherwise */ virtual bool IsOK() const = 0; /** * Returns whether the severity of this status matches the given * severity mask. Note that a status with severity OK_TYPE * will never match; use isOK instead to detect * a status with a severity of OK. * * @param severityMask a mask formed by bitwise or'ing severity mask * constants (ERROR_TYPE, WARNING_TYPE, * INFO_TYPE, CANCEL_TYPE) * @return true if there is at least one match, * false if there are no matches * @see #getSeverity() * @see #CANCEL_TYPE * @see #ERROR_TYPE * @see #WARNING_TYPE * @see #INFO_TYPE */ virtual bool Matches(const Severities& severityMask) const = 0; virtual QString GetFileName() const = 0; virtual QString GetMethodName() const = 0; virtual int GetLineNumber() const = 0; }; } Q_DECLARE_OPERATORS_FOR_FLAGS(berry::IStatus::Severities) #endif /* BERRYISTATUS_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryLog.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryLog.cpp index 7af536c911..15cab5a448 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryLog.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryLog.cpp @@ -1,26 +1,26 @@ /*=================================================================== 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 "berryLog.h" #include -std::stringstream& operator<<(std::stringstream& os, const QString& str) +std::ostream& operator<<(std::ostream& os, const QString& str) { os << str.toStdString(); return os; } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryLog.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryLog.h index 0a40149d60..4a7543004a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryLog.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryLog.h @@ -1,33 +1,33 @@ /*=================================================================== 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 __BERRY_LOG_H__ #define __BERRY_LOG_H__ #include #include #define BERRY_INFO MBI_INFO("BlueBerry") #define BERRY_WARN MBI_WARN("BlueBerry") #define BERRY_ERROR MBI_ERROR("BlueBerry") #define BERRY_FATAL MBI_FATAL("BlueBerry") #define BERRY_DEBUG MBI_DEBUG("BlueBerry") -org_blueberry_core_runtime_EXPORT std::stringstream& operator<<(std::stringstream& os, const QString& str); +org_blueberry_core_runtime_EXPORT std::ostream& operator<<(std::ostream& os, const QString& str); #endif /*__BERRY_LOG_H__*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMacros.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMacros.h index 1c95e2cff2..d1b6d06d7c 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMacros.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMacros.h @@ -1,119 +1,73 @@ /*=================================================================== 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 __BERRY_MACROS_H__ #define __BERRY_MACROS_H__ #include "berryWeakPointer.h" #include "berryExtensionType.h" -#define berryNameMacro(className) \ - virtual const char* GetClassName() const \ - { return #className; }\ - static const char* GetStaticClassName() \ - { return #className; }\ - -#define berryManifestMacro(className, namespaze) \ - static const char* GetManifestName() \ - { return #namespaze #className; } \ - -#define berryObjectMacro(className) \ - typedef className Self; \ - typedef berry::SmartPointer Pointer; \ - typedef berry::SmartPointer ConstPointer; \ - typedef berry::WeakPointer WeakPtr; \ - typedef berry::WeakPointer ConstWeakPtr; \ - berryNameMacro(className); \ - -#define berryInterfaceMacro(className, namespaze) \ - public: \ - berryObjectMacro(className); \ - berryManifestMacro(className, namespaze); \ +#define berryObjectMacro(className) \ + typedef className Self; \ + typedef berry::SmartPointer Pointer; \ + typedef berry::SmartPointer ConstPointer; \ + typedef berry::WeakPointer WeakPtr; \ + typedef berry::WeakPointer ConstWeakPtr; \ + static const char* GetStaticClassName() \ + { return #className; } -#define berrySimpleInterfaceMacro(className, namespaze) \ - protected: className() {} \ - public: \ - berryNameMacro(className); \ - berryManifestMacro(className, namespaze); \ +/* #define berryNewMacro(x) \ static Pointer New(void) \ { \ Pointer smartPtr(new x); \ return smartPtr; \ } \ #define berryNewMacro1Param(x, type1) \ static Pointer New(type1 param1) \ { \ Pointer smartPtr(new x(param1)); \ return smartPtr; \ } \ #define berryNewMacro2Param(x, type1, type2) \ static Pointer New(type1 param1, type2 param2) \ { \ Pointer smartPtr(new x(param1, param2)); \ return smartPtr; \ } \ #define berryNewMacro3Param(x, type1, type2, type3) \ static Pointer New(type1 param1, type2 param2, type3 param3) \ { \ Pointer smartPtr (new x(param1, param2, param3)); \ return smartPtr; \ -} \ - -#ifndef BERRY_NO_TYPESAFE_FLAGS - -#include "berryFlags.h" - -#define BERRY_DECLARE_FLAGS(_Flags, _Enum)\ -typedef berry::Flags<_Enum> _Flags; - -#if defined _MSC_VER && _MSC_VER < 1300 -# define BERRY_DECLARE_INCOMPATIBLE_FLAGS(_Flags) -#else -# define BERRY_DECLARE_INCOMPATIBLE_FLAGS(_Flags) \ -inline berry::IncompatibleFlag operator|(_Flags::enum_type f1, int f2) \ -{ return berry::IncompatibleFlag(int(f1) | f2); } -#endif - -#define BERRY_DECLARE_OPERATORS_FOR_FLAGS(_Flags) \ -inline berry::Flags<_Flags::enum_type> operator|(_Flags::enum_type f1, _Flags::enum_type f2) \ -{ return berry::Flags<_Flags::enum_type>(f1) | f2; } \ -inline berry::Flags<_Flags::enum_type> operator|(_Flags::enum_type f1, berry::Flags<_Flags::enum_type> f2) \ -{ return f2 | f1; } BERRY_DECLARE_INCOMPATIBLE_FLAGS(_Flags) - -#else /* BERRY_NO_TYPESAFE_FLAGS */ - -#define BERRY_DECLARE_FLAGS(_Flags, _Enum)\ -typedef uint _Flags; -#define BERRY_DECLARE_OPERATORS_FOR_FLAGS(_Flags) - -#endif /* BERRY_NO_TYPESAFE_FLAGS */ +} +*/ #define BERRY_REGISTER_EXTENSION_CLASS(_ClassType, _PluginContext)\ {\ QString typeName = _PluginContext->getPlugin()->getSymbolicName();\ typeName = (typeName + "_") + _ClassType::staticMetaObject.className();\ ::berry::registerExtensionType<_ClassType>(typeName.toLatin1().data());\ } #endif /*__BERRY_MACROS_H__*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMessage.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMessage.h index 2f8a5d7210..ecfa0e2c67 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMessage.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMessage.h @@ -1,1075 +1,1075 @@ /*=================================================================== 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 BERRYMESSAGE_H_ #define BERRYMESSAGE_H_ #include #include /** * Adds a Message<> variable and methods to add/remove message delegates to/from * this variable. */ -#define berryNewMessageMacro(msgHandleObject) \ +#define berryNewMessageMacro(msgHandleObject) \ private: Message<> m_ ## msgHandleObject ## Message; \ public: \ inline void Add ## msgHandleObject ## Listener(const MessageAbstractDelegate<>& delegate) \ { m_ ## msgHandleObject ## Message += delegate; } \ inline void Remove ## msgHandleObject ## Listener(const MessageAbstractDelegate<>& delegate) \ { m_ ## msgHandleObject ## Message -= delegate; } \ -#define berryNewMessageWithReturnMacro(msgHandleObject, returnType) \ +#define berryNewMessageWithReturnMacro(msgHandleObject, returnType) \ private: Message m_ ## msgHandleObject ## Message; \ public: \ inline void Add ## msgHandleObject ## Listener(const MessageAbstractDelegate& delegate) \ { m_ ## msgHandleObject ## Message += delegate; } \ inline void Remove ## msgHandleObject ## Listener(const MessageAbstractDelegate& delegate) \ { m_ ## msgHandleObject ## Message -= delegate; } \ -#define berryNewMessage1Macro(msgHandleObject, type1) \ +#define berryNewMessage1Macro(msgHandleObject, type1) \ private: Message1< type1 > m_msgHandleObject ## Message; \ public: \ void Add ## msgHandleObject ## Listener(const MessageAbstractDelegate1< type1 >& delegate) \ { m_ ## msgHandleObject ## Message += delegate; } \ void Remove ## msgHandleObject ## Listener(const MessageAbstractDelegate1< type1 >& delegate) \ { m_ ## msgHandleObject ## Message -= delegate; } \ namespace berry { template class MessageAbstractDelegate { public: virtual ~MessageAbstractDelegate() { } virtual A Execute() = 0; virtual bool operator==(const MessageAbstractDelegate* cmd) = 0; virtual MessageAbstractDelegate* Clone() const = 0; }; template class MessageAbstractDelegate1 { public: virtual ~MessageAbstractDelegate1() { } virtual A Execute(T t) = 0; virtual bool operator==(const MessageAbstractDelegate1* cmd) = 0; virtual MessageAbstractDelegate1* Clone() const = 0; }; template class MessageAbstractDelegate2 { public: virtual ~MessageAbstractDelegate2() { } virtual A Execute(T t, U u) const = 0; virtual bool operator==(const MessageAbstractDelegate2* cmd) = 0; virtual MessageAbstractDelegate2* Clone() const = 0; }; template class MessageAbstractDelegate3 { public: virtual ~MessageAbstractDelegate3() { } virtual A Execute(T t, U u, V v) const = 0; virtual bool operator==(const MessageAbstractDelegate3* cmd) = 0; virtual MessageAbstractDelegate3* Clone() const = 0; }; template class MessageAbstractDelegate4 { public: virtual ~MessageAbstractDelegate4() { } virtual A Execute(T t, U u, V v, W w) const = 0; virtual bool operator==(const MessageAbstractDelegate4* cmd) = 0; virtual MessageAbstractDelegate4* Clone() const = 0; }; template class MessageDelegate: public MessageAbstractDelegate { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate(R* object, A(R::*memberFunctionPointer)()) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } virtual ~MessageDelegate() { } // override function "Call" virtual A Execute() { return (m_Object->*m_MemberFunctionPointer)(); // execute member function } bool operator==(const MessageAbstractDelegate* c) { const MessageDelegate* cmd = dynamic_cast*> (c); if (!cmd) return false; if ((void*) this->m_Object != (void*) cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate* Clone() const { return new MessageDelegate(m_Object, m_MemberFunctionPointer); } private: R* m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(); // pointer to member function }; template class MessageDelegate1: public MessageAbstractDelegate1 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate1(R* object, A(R::*memberFunctionPointer)(T)) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } virtual ~MessageDelegate1() { } // override function "Call" virtual A Execute(T t) { return (m_Object->*m_MemberFunctionPointer)(t); // execute member function } bool operator==(const MessageAbstractDelegate1* c) { const MessageDelegate1* cmd = dynamic_cast*> (c); if (!cmd) return false; if ((void*) this->m_Object != (void*) cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate1* Clone() const { return new MessageDelegate1(m_Object, m_MemberFunctionPointer); } private: R* m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T); // pointer to member function }; template class MessageDelegate2: public MessageAbstractDelegate2 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate2(R* object, A(R::*memberFunctionPointer)(T, U)) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } virtual ~MessageDelegate2() { } // override function "Call" virtual A Execute(T t, U u) const { return (m_Object->*m_MemberFunctionPointer)(t, u); // execute member function } bool operator==(const MessageAbstractDelegate2* c) { const MessageDelegate2* cmd = dynamic_cast*> (c); if (!cmd) return false; if ((void*) this->m_Object != (void*) cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate2* Clone() const { return new MessageDelegate2(m_Object, m_MemberFunctionPointer); } private: R* m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T, U); // pointer to member function }; template class MessageDelegate3: public MessageAbstractDelegate3 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate3(R* object, A(R::*memberFunctionPointer)(T, U, V)) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } virtual ~MessageDelegate3() { } // override function "Call" virtual A Execute(T t, U u, V v) const { return (m_Object->*m_MemberFunctionPointer)(t, u, v); // execute member function } bool operator==(const MessageAbstractDelegate3* c) { const MessageDelegate3* cmd = dynamic_cast*> (c); if (!cmd) return false; if ((void*) this->m_Object != (void*) cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate3* Clone() const { return new MessageDelegate3(m_Object, m_MemberFunctionPointer); } private: R* m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T, U, V); // pointer to member function }; template class MessageDelegate4: public MessageAbstractDelegate4 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate4(R* object, A(R::*memberFunctionPointer)(T, U, V, W)) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } virtual ~MessageDelegate4() { } // override function "Call" virtual A Execute(T t, U u, V v, W w) const { return (m_Object->*m_MemberFunctionPointer)(t, u, v, w); // execute member function } bool operator==(const MessageAbstractDelegate4* c) { const MessageDelegate4* cmd = dynamic_cast*> (c); if (!cmd) return false; if ((void*) this->m_Object != (void*) cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate4* Clone() const { return new MessageDelegate4(m_Object, m_MemberFunctionPointer); } private: R* m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T, U, V, W); // pointer to member function }; struct AbstractExceptionHandler { virtual void HandleException(const std::exception& exc) = 0; virtual AbstractExceptionHandler* Clone() const = 0; virtual ~AbstractExceptionHandler() { } }; template struct MessageExceptionHandler: public AbstractExceptionHandler { typedef void (R::*HandleExceptionCallback)(const std::exception&); MessageExceptionHandler(R* r, HandleExceptionCallback c) : m_Object(r), m_ExceptionCallback(c) { } void HandleException(const std::exception& exc) { (m_Object->*m_ExceptionCallback)(exc); } AbstractExceptionHandler* Clone() const { if (!m_Object) return 0; return new MessageExceptionHandler(m_Object, m_ExceptionCallback); } private: R* m_Object; HandleExceptionCallback m_ExceptionCallback; }; template class DelegateList { public: typedef D Delegate; typedef std::vector ListType; DelegateList() : m_ExcHandler(0) { } ~DelegateList() { for (typename ListType::iterator iter = m_Delegates.begin(); iter != m_Delegates.end(); ++iter) { delete *iter; } delete m_ExcHandler; } void Add(const Delegate& d) const { Delegate* copy = d.Clone(); Poco::FastMutex::ScopedLock lock(m_Mutex); for (typename ListType::iterator iter = m_Delegates.begin(); iter != m_Delegates.end(); ++iter) { if ((*iter)->operator==(copy)) { delete copy; return; } } m_Delegates.push_back(copy); } void Remove(const Delegate& d) const { Poco::FastMutex::ScopedLock lock(m_Mutex); for (typename ListType::iterator iter = m_Delegates.begin(); iter != m_Delegates.end(); ++iter) { if ((*iter)->operator==(&d)) { delete *iter; m_Delegates.erase(iter); return; } } } bool IsEmpty() const { return m_Delegates.empty(); } template void Send0(Dummy) const { ListType delegates; { Poco::FastMutex::ScopedLock lock(m_Mutex); delegates.assign(m_Delegates.begin(), m_Delegates.end()); } for (typename ListType::iterator iter = delegates.begin(); iter != delegates.end(); ++iter) { try { // notify each listener (*iter)->Execute(); } catch (const std::exception& e) { if (m_ExcHandler) { m_ExcHandler->HandleException(e); } else { throw e; } } catch (...) { if (m_ExcHandler) { m_ExcHandler->HandleException(std::exception()); } else throw ; } } } template void Send1(T t) const { ListType delegates; { Poco::FastMutex::ScopedLock lock(m_Mutex); delegates.assign(m_Delegates.begin(), m_Delegates.end()); } for (typename ListType::iterator iter = delegates.begin(); iter != delegates.end(); ++iter) { try { // notify each listener (*iter)->Execute(t); } catch (const std::exception& e) { if (m_ExcHandler) { m_ExcHandler->HandleException(e); } else { throw e; } } catch (...) { if (m_ExcHandler) { m_ExcHandler->HandleException(std::exception()); } else throw; } } } template void Send2(T t, U u) const { ListType delegates; { Poco::FastMutex::ScopedLock lock(m_Mutex); delegates.assign(m_Delegates.begin(), m_Delegates.end()); } for (typename ListType::iterator iter = delegates.begin(); iter != delegates.end(); ++iter) { try { // notify each listener (*iter)->Execute(t, u); } catch (const std::exception& e) { if (m_ExcHandler) { m_ExcHandler->HandleException(e); } else { throw e; } } catch (...) { if (m_ExcHandler) { m_ExcHandler->HandleException(std::exception()); } else throw; } } } template void Send3(T t, U u, V v) const { ListType delegates; { Poco::FastMutex::ScopedLock lock(m_Mutex); delegates.assign(m_Delegates.begin(), m_Delegates.end()); } for (typename ListType::iterator iter = delegates.begin(); iter != delegates.end(); ++iter) { try { // notify each listener (*iter)->Execute(t, u, v); } catch (const std::exception& e) { if (m_ExcHandler) { m_ExcHandler->HandleException(e); } else { throw e; } } catch (...) { if (m_ExcHandler) { m_ExcHandler->HandleException(std::exception()); } else throw; } } } template void Send4(T t, U u, V v, W w) const { ListType delegates; { Poco::FastMutex::ScopedLock lock(m_Mutex); delegates.assign(m_Delegates.begin(), m_Delegates.end()); } for (typename ListType::iterator iter = delegates.begin(); iter != delegates.end(); ++iter) { try { // notify each listener (*iter)->Execute(t, u, v, w); } catch (const std::exception& e) { if (m_ExcHandler) { m_ExcHandler->HandleException(e); } else { throw e; } } catch (...) { if (m_ExcHandler) { m_ExcHandler->HandleException(std::exception()); } else throw; } } } void SetExceptionHandler(const AbstractExceptionHandler& handler) { Poco::FastMutex::ScopedLock lock(m_Mutex); delete m_ExcHandler; m_ExcHandler = handler.Clone(); } AbstractExceptionHandler* GetExceptionHandler() const { Poco::FastMutex::ScopedLock lock(m_Mutex); if (m_ExcHandler) return m_ExcHandler->Clone(); return 0; } ListType GetDelegates() const { Poco::FastMutex::ScopedLock lock(m_Mutex); return m_Delegates; } private: /** * \brief List of listeners. * * This is declared mutable for a reason: Imagine an object that sends out notifications, e.g. * * \code class Database { public: Message Modified; }; * \endcode * * Now imaginge someone gets a const Database object, because he/she should not write to the * database. He/she should anyway be able to register for notifications about changes in the database * -- this is why AddListener and RemoveListener are declared const. m_Listeners must be * mutable so that AddListener and RemoveListener can modify it regardless of the object's constness. */ mutable std::vector m_Delegates; mutable AbstractExceptionHandler* m_ExcHandler; mutable Poco::FastMutex m_Mutex; }; /** * \brief Event/message/notification class. * * This class * allows one class to send out messages and another class to * receive these message. There are subclasses for sending * parameters along with the messages. * * This is an implementation of the Observer pattern. * * \li There is no guarantee about the order of which observer is notified first. At the moment the observers which register first will be notified first. * \li Notifications are synchronous, by direct method calls. There is no support for asynchronous messages. * */ // message without parameters (pure signals) template class Message { public: typedef Message Self; typedef MessageAbstractDelegate AbstractDelegate; typedef typename DelegateList::ListType ListenerList; void AddListener(const AbstractDelegate& delegate) const { delegates.Add(delegate); } void operator +=(const AbstractDelegate& delegate) const { this->AddListener(delegate); } void RemoveListener(const AbstractDelegate& delegate) const { delegates.Remove(delegate); } void operator -=(const AbstractDelegate& delegate) const { this->RemoveListener(delegate); } void Send() const { delegates.Send0(0); } void operator()() const { this->Send(); } void SetExceptionHandler(const AbstractExceptionHandler& handler) { delegates.SetExceptionHandler(handler); } AbstractExceptionHandler* GetExceptionHandler() const { return delegates.GetExceptionHandler(); } ListenerList GetListeners() const { return delegates.GetDelegates(); } bool HasListeners() const { return !delegates.IsEmpty(); } bool IsEmpty() const { return delegates.IsEmpty(); } protected: DelegateList delegates; }; // message with 1 parameter and return type template class Message1 { public: typedef Message1 Self; typedef MessageAbstractDelegate1 AbstractDelegate; typedef typename DelegateList::ListType ListenerList; void AddListener(const AbstractDelegate& delegate) const { delegates.Add(delegate); } void operator +=(const AbstractDelegate& delegate) const { this->AddListener(delegate); } void RemoveListener(const AbstractDelegate& delegate) const { delegates.Remove(delegate); } void operator -=(const AbstractDelegate& delegate) const { this->RemoveListener(delegate); } void Send(T t) const { delegates.Send1(t); } void operator()(T t) const { this->Send(t); } void SetExceptionHandler(const AbstractExceptionHandler& handler) { delegates.SetExceptionHandler(handler); } AbstractExceptionHandler* GetExceptionHandler() const { return delegates.GetExceptionHandler(); } ListenerList GetListeners() const { return delegates.GetDelegates(); } bool HasListeners() const { return !delegates.IsEmpty(); } bool IsEmpty() const { return delegates.IsEmpty(); } protected: DelegateList delegates; }; // message with 2 parameters and return type template class Message2 { public: typedef Message2 Self; typedef MessageAbstractDelegate2 AbstractDelegate; typedef typename DelegateList::ListType ListenerList; void AddListener(const AbstractDelegate& delegate) const { delegates.Add(delegate); } void operator +=(const AbstractDelegate& delegate) const { this->AddListener(delegate); } void RemoveListener(const AbstractDelegate& delegate) const { delegates.Remove(delegate); } void operator -=(const AbstractDelegate& delegate) const { this->RemoveListener(delegate); } void Send(T t, U u) const { delegates.Send2(t, u); } void operator()(T t, U u) const { this->Send(t, u); } void SetExceptionHandler(const AbstractExceptionHandler& handler) { delegates.SetExceptionHandler(handler); } AbstractExceptionHandler* GetExceptionHandler() const { return delegates.GetExceptionHandler(); } ListenerList GetListeners() const { return delegates.GetDelegates(); } bool HasListeners() const { return !delegates.IsEmpty(); } bool IsEmpty() const { return delegates.IsEmpty(); } protected: DelegateList delegates; }; // message with 3 parameters and return type template class Message3 { public: typedef Message3 Self; typedef MessageAbstractDelegate3 AbstractDelegate; typedef typename DelegateList::ListType ListenerList; void AddListener(const AbstractDelegate& delegate) const { delegates.Add(delegate); } void operator +=(const AbstractDelegate& delegate) const { this->AddListener(delegate); } void RemoveListener(const AbstractDelegate& delegate) const { delegates.Remove(delegate); } void operator -=(const AbstractDelegate& delegate) const { this->RemoveListener(delegate); } void Send(T t, U u, V v) const { delegates.Send3(t, u, v); } void operator()(T t, U u, V v) const { this->Send(t, u, v); } void SetExceptionHandler(const AbstractExceptionHandler& handler) { delegates.SetExceptionHandler(handler); } AbstractExceptionHandler* GetExceptionHandler() const { return delegates.GetExceptionHandler(); } ListenerList GetListeners() const { return delegates.GetDelegates(); } bool HasListeners() const { return !delegates.IsEmpty(); } bool IsEmpty() const { return delegates.IsEmpty(); } protected: DelegateList delegates; }; // message with 4 parameters and return type template class Message4 { public: typedef Message4 Self; typedef MessageAbstractDelegate4 AbstractDelegate; typedef typename DelegateList::ListType ListenerList; void AddListener(const AbstractDelegate& delegate) const { delegates.Add(delegate); } void operator +=(const AbstractDelegate& delegate) const { this->AddListener(delegate); } void RemoveListener(const AbstractDelegate& delegate) const { delegates.Remove(delegate); } void operator -=(const AbstractDelegate& delegate) const { this->RemoveListener(delegate); } void Send(T t, U u, V v, W w) const { delegates.Send4(t, u, v, w); } void operator()(T t, U u, V v, W w) const { this->Send(t, u , v, w); } void SetExceptionHandler(const AbstractExceptionHandler& handler) { delegates.SetExceptionHandler(handler); } AbstractExceptionHandler* GetExceptionHandler() const { return delegates.GetExceptionHandler(); } ListenerList GetListeners() const { return delegates.GetDelegates(); } bool HasListeners() const { return !delegates.IsEmpty(); } bool IsEmpty() const { return delegates.IsEmpty(); } protected: DelegateList delegates; }; } // namespace berry #endif /*BERRYMESSAGE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMultiStatus.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMultiStatus.cpp index d4ce6517f8..206e28880d 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMultiStatus.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMultiStatus.cpp @@ -1,128 +1,128 @@ /*=================================================================== 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 "berryMultiStatus.h" #include namespace berry { IStatus::Severity MultiStatus::GetMaxSeverity(const QList& children) const { Severity maxSeverity = this->GetSeverity(); - for (unsigned int i = 0; i < children.size(); i++) + for (int i = 0; i < children.size(); i++) { Q_ASSERT(children[i]); Severity severity = children[i]->GetSeverity(); if (severity > maxSeverity) maxSeverity = severity; } return maxSeverity; } MultiStatus::MultiStatus(const QString& pluginId, int code, const QList& newChildren, const QString& message, const SourceLocation& sl) : Status(OK_TYPE, pluginId, code, message, sl), children(newChildren) { this->SetSeverity(GetMaxSeverity(children)); } MultiStatus::MultiStatus(const QString& pluginId, int code, const QList& newChildren, const QString& message, const ctkException& exception, const SourceLocation& sl) : Status(OK_TYPE, pluginId, code, message, exception, sl), children(newChildren) { this->SetSeverity(GetMaxSeverity(children)); } MultiStatus::MultiStatus(const QString& pluginId, int code, const QString& message, const SourceLocation& sl) : Status(OK_TYPE, pluginId, code, message, sl) { } MultiStatus::MultiStatus(const QString& pluginId, int code, const QString& message, const ctkException& exception, const SourceLocation& sl) : Status(OK_TYPE, pluginId, code, message, exception, sl) { } void MultiStatus::Add(IStatus::Pointer status) { poco_assert(status); children.push_back(status); Severity newSev = status->GetSeverity(); if (newSev > this->GetSeverity()) { this->SetSeverity(newSev); } } void MultiStatus::AddAll(IStatus::Pointer status) { Q_ASSERT(status); QList statuses(status->GetChildren()); - for (unsigned int i = 0; i < statuses.size(); i++) + for (int i = 0; i < statuses.size(); i++) { this->Add(statuses[i]); } } QList MultiStatus::GetChildren() const { return children; } bool MultiStatus::IsMultiStatus() const { return true; } void MultiStatus::Merge(const IStatus::Pointer& status) { poco_assert(status); if (!status->IsMultiStatus()) { this->Add(status); } else { this->AddAll(status); } } QString MultiStatus::ToString() const { QString str; QTextStream buf(&str); buf << Status::ToString() << " children=["; - for (unsigned int i = 0; i < children.size(); i++) + for (int i = 0; i < children.size(); i++) { if (i != 0) { buf << " "; } buf << children[i]->ToString(); } buf << "]"; return str; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryRuntime.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryNonDerivable.h similarity index 67% rename from BlueBerry/Bundles/org.blueberry.core.runtime/src/berryRuntime.h rename to BlueBerry/Bundles/org.blueberry.core.runtime/src/berryNonDerivable.h index 5d90201857..1824561762 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryRuntime.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryNonDerivable.h @@ -1,33 +1,30 @@ /*=================================================================== 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 BERRYRUNTIME_H_ -#define BERRYRUNTIME_H_ - -#include - -#include +#ifndef BERRYNONDERIVABLE_H +#define BERRYNONDERIVABLE_H namespace berry { -struct org_blueberry_core_runtime_EXPORT Runtime +class NonDerivable { - static const std::string ADAPTER_SERVICE_ID; +protected: + NonDerivable() {} }; } -#endif /*BERRYRUNTIME_H_*/ +#endif // BERRYNONDERIVABLE_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.cpp index 2cd40e59d0..b4289c15dd 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.cpp @@ -1,291 +1,308 @@ /*=================================================================== 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 "berryObject.h" #ifdef BLUEBERRY_DEBUG_SMARTPOINTER #include "berryDebugUtil.h" #endif #include "berryLog.h" #include #include #include #include // Better name demangling for gcc #if __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ > 0 ) #define GCC_USEDEMANGLE #endif #ifdef GCC_USEDEMANGLE #include #include #endif +#if defined(_WIN32) && defined(NDEBUG) +// exported from VC CRT +extern "C" +char * _unDName(char * outputString, const char * name, int maxStringLength, + void * (* pAlloc )(size_t), void (* pFree )(void *), + unsigned short disableFlags); +#endif + namespace berry { void Object::Delete() { this->UnRegister(); } +QString Object::DemangleName(const char* mangledName) +{ + QString name(mangledName); +#ifdef GCC_USEDEMANGLE + int status; + char* unmangled = abi::__cxa_demangle(mangledName, 0, 0, &status); + + if(status == 0) + { + name = QString(unmangled); + free(unmangled); + } +#elif defined(_WIN32) && defined(NDEBUG) + char * const unmangled = _unDName(0, mangledName, 0, malloc, free, 0x2800); + if (unmangled) + { + name = QString(unmangled); + free(unmangled); + } +#endif + return name; +} + #ifdef _WIN32 void* Object ::operator new(size_t n) { return new char[n]; } void* Object ::operator new[](size_t n) { return new char[n]; } void Object ::operator delete(void* m) { delete [] (char*)m; } void Object ::operator delete[](void* m, size_t) { delete [] (char*)m; } #endif +const char* Object::GetStaticClassName() +{ + return "berry::Object"; +} + +QString Object::GetClassName() const +{ + return DemangleName(typeid(*this).name()); +} + QDebug Object::Print(QDebug os, Indent indent) const { os = this->PrintHeader(os, indent); os = this->PrintSelf(os, indent.GetNextIndent()); return this->PrintTrailer(os, indent); } QString Object::ToString() const { QString str; QDebug ss(&str); this->Print(ss); return str; } uint Object::HashCode() const { return qHash(this); } bool Object::operator<(const Object* o) const { return this < o; } void Object::Register() const { m_ReferenceCount.ref(); } void Object::UnRegister(bool del) const { if (!m_ReferenceCount.deref() && del) { delete this; } } void Object::SetReferenceCount(int ref) { QMutexLocker lock(&m_ReferenceCountLock); m_ReferenceCount = ref; if (ref == 0) { delete this; } } bool Object::operator==(const Object* o) const { return this == o; } #ifdef BLUEBERRY_DEBUG_SMARTPOINTER unsigned int Object::GetTraceId() const { return m_TraceId; } unsigned int& Object::GetTraceIdCounter() const { static unsigned int traceId = 0; return traceId; } #endif Object::Object() : m_ReferenceCount(0) { #ifdef BLUEBERRY_DEBUG_SMARTPOINTER unsigned int& id = GetTraceIdCounter(); m_TraceId = ++id; DebugUtil::RegisterObject(this); #endif } Object::~Object() { /** * warn user if reference counting is on and the object is being referenced * by another object. */ if (m_ReferenceCount > 0) { // A general exception safety rule is that destructors should // never throw. Something is wrong with a program that reaches // this point anyway. Also this is the least-derived class so the // whole object has been destroyed by this point anyway. Just // issue a warning. BERRY_WARN << "WARNING: In " __FILE__ ", line " << __LINE__ << "\n" << this->GetClassName() << " (" << this << "): Trying to delete object with non-zero reference count."; } /** * notifies the registered functions that the object is being destroyed */ m_DestroyMessage.Send(); #ifdef BLUEBERRY_DEBUG_SMARTPOINTER DebugUtil::UnregisterObject(this); #endif } QDebug Object::PrintSelf(QDebug os, Indent Indent) const { -#ifdef GCC_USEDEMANGLE - char const * mangledName = typeid(*this).name(); - int status; - char* unmangled = abi::__cxa_demangle(mangledName, 0, 0, &status); - - os << Indent << "RTTI typeinfo: "; - - if(status == 0) - { - os << unmangled; - free(unmangled); - } - else - { - os << mangledName; - } - - os << '\n'; -#else - os << Indent << "RTTI typeinfo: " << typeid( *this ).name() << '\n'; -#endif + QString demangledName = DemangleName(typeid(*this).name()); + os << Indent << "RTTI typeinfo: " << demangledName << '\n'; os << Indent << "Reference Count: " << m_ReferenceCount << '\n'; + return os; } /** * Define a default print header for all objects. */ QDebug Object::PrintHeader(QDebug os, Indent Indent) const { os << Indent << this->GetClassName() << " (" << this << ")\n"; return os; } /** * Define a default print trailer for all objects. */ QDebug Object::PrintTrailer(QDebug os, Indent /*Indent*/) const { return os; } // ============== Indent related implementations ============== static const char blanks[41] = " "; -//Indent* -//Indent::New() -//{ -// return new Self; -//} - Indent Indent::GetNextIndent() { int Indent = m_Indent + 2; if (Indent > 40) { Indent = 40; } return Indent; } QDebug operator<<(QDebug os, const berry::Indent& ind) { os.nospace() << blanks + (40 - ind.m_Indent); return os; } } // namespace berry QDebug operator<<(QDebug os, const berry::Object& o) { return o.Print(os); } QDebug operator<<(QDebug os, const berry::SmartPointer& o) { return o->Print(os); } QDebug operator<<(QDebug os, const berry::SmartPointer& o) { return o->Print(os); } QTextStream& operator<<(QTextStream& os, const berry::Object& o) { os << o.ToString(); return os; } QTextStream& operator<<(QTextStream& os, const berry::SmartPointer& o) { os << o->ToString(); return os; } //QTextStream& operator<<(QTextStream& os, const berry::SmartPointer& o) //{ // os << o->ToString(); // return os; //} uint qHash(const berry::Object& o) { return o.HashCode(); } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.h index d75ff909a2..a1ae30cbea 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.h @@ -1,264 +1,241 @@ /*=================================================================== 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 BERRYOSGILIGHTOBJECT_H_ #define BERRYOSGILIGHTOBJECT_H_ #include #include "berryMacros.h" #include "berryMessage.h" #include #include #include #include #include #ifdef _MSC_VER // disable inheritance by dominance warnings #pragma warning( disable : 4250 4275 4251 ) // disable warning: C++ exception specification ignored except to indicate a function is not __declspec(nothrow) #pragma warning( disable : 4290 ) #endif class QDebug; class QTextStream; namespace berry { class org_blueberry_core_runtime_EXPORT Indent { public: /** Standard class typedefs. */ typedef Indent Self; - /** Method for creation through the object factory. */ - //static Self* New(); - - /** Destroy this instance. */ - //void Delete() {delete this;} - /** Construct the object with an initial Indentation level. */ Indent(int ind = 0) { m_Indent=ind; } - /** Return the name of the class. */ - //static const char *GetClassName() {return "Indent";} - /** * Determine the next Indentation level. Keep Indenting by two until the * a maximum of forty spaces is reached. */ Indent GetNextIndent(); /** Print out the Indentation. Basically output a bunch of spaces. */ - friend QDebug operator<<(QDebug os, const Indent& o); + friend org_blueberry_core_runtime_EXPORT QDebug operator<<(QDebug os, const Indent& o); private: int m_Indent; }; /** \class Object * \brief Light weight base class for most BlueBerry classes. * * Object is copied from itk::LightObject and is the highest * level base class for most BlueBerry objects. It * implements reference counting and the API for object printing. * */ class org_blueberry_core_runtime_EXPORT Object { - /** - * The message macro is used to create a message object as well as add / remove functions - * (AddDestroyListener, RemoveDestroyListener) - * in order to register functions which will be called when the object is destroyed. - * More information about the NewMessageMacro can be found in @see berryMessage.h - * - */ - berryNewMessageMacro(Destroy) +private: + + mutable Message<> m_DestroyMessage; public: - berryObjectMacro(Object); - -// struct Hash { -// inline std::size_t operator()(const Self* value) const -// { -// return value->HashCode(); -// } - -// inline std::size_t operator()(Self::ConstPointer value) const -// { -// return value->HashCode(); -// } - -// inline std::size_t operator()(Self::WeakPtr value) const -// { -// try { -// const Self::ConstPointer sv(value.Lock()); -// return sv->HashCode(); -// } -// catch (BadWeakPointerException& /*e*/) -// { -// return 0; -// } -// } -// }; + typedef Object Self; + typedef berry::SmartPointer Pointer; + typedef berry::SmartPointer ConstPointer; + typedef berry::WeakPointer WeakPtr; + typedef berry::WeakPointer ConstWeakPtr; + + static const char* GetStaticClassName(); + virtual QString GetClassName() const; /** Delete an BlueBerry object. This method should always be used to delete an * object when the new operator was used to create it. Using the C * delete method will not work with reference counting. */ virtual void Delete(); #ifdef _WIN32 /** Used to avoid dll boundary problems. */ void* operator new(size_t); void* operator new[](size_t); void operator delete(void*); void operator delete[](void*, size_t); #endif + static QString DemangleName(const char* typeName); + /** * Cause the object to print itself out. This is usually used to provide * detailed information about the object's state. It just calls the * header/self/trailer virtual print methods, which can be overriden by * subclasses. */ QDebug Print(QDebug os, Indent Indent=0) const; /** * Returns a string representation of this object. The default * implementation returns an empty string. */ virtual QString ToString() const; /** * Returns a hash code value for the object. */ virtual uint HashCode() const; /** * Override this method to implement a specific "less than" operator * for associative STL containers. */ virtual bool operator<(const Object*) const; /** Increase the reference count (mark as used by another object). */ void Register() const; /** Decrease the reference count (release by another object). * Set del to false if you do not want the object to be deleted if * the reference count is zero (use with care!) */ void UnRegister(bool del = true) const; /** Gets the reference count on this object. */ int GetReferenceCount() const { return m_ReferenceCount; } /** Sets the reference count on this object. This is a dangerous * method, use it with care. */ void SetReferenceCount(int); + inline void AddDestroyListener(const MessageAbstractDelegate<>& delegate) const + { m_DestroyMessage += delegate; } + inline void RemoveDestroyListener(const MessageAbstractDelegate<>& delegate) const + { m_DestroyMessage -= delegate; } + + /** * A generic comparison method. Override this method in subclasses and * cast to your derived class to provide a more detailed comparison. */ virtual bool operator==(const Object*) const; #ifdef BLUEBERRY_DEBUG_SMARTPOINTER unsigned int GetTraceId() const; private: unsigned int m_TraceId; unsigned int& GetTraceIdCounter() const; public: #endif protected: - friend class QScopedPointerObjectDeleter; + friend struct QScopedPointerObjectDeleter; Object(); virtual ~Object(); /** * Methods invoked by Print() to print information about the object * including superclasses. Typically not called by the user (use Print() * instead) but used in the hierarchical print process to combine the * output of several classes. */ virtual QDebug PrintSelf(QDebug os, Indent indent) const; virtual QDebug PrintHeader(QDebug os, Indent indent) const; virtual QDebug PrintTrailer(QDebug os, Indent indent) const; /** Number of uses of this object by other objects. */ mutable QAtomicInt m_ReferenceCount; /** Mutex lock to protect modification to the reference count */ mutable QMutex m_ReferenceCountLock; private: Object(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented }; // A custom deleter for QScopedPointer // berry::Object instances in a QScopedPointer should have reference count one, // such that they are not accidentally deleted when a temporary smart pointer // pointing to it goes out of scope. This deleter fixes the reference count and // always deletes the instance. Use a berry::SmartPointer if the lifetime should // exceed the one of the pointer. struct QScopedPointerObjectDeleter { static inline void cleanup(Object* obj) { if (obj == NULL) return; obj->UnRegister(false); delete obj; } }; org_blueberry_core_runtime_EXPORT QDebug operator<<(QDebug os, const berry::Indent& o); } /** * This operator allows all subclasses of Object to be printed via QDebug <<. * It in turn invokes the Print method, which in turn will invoke the * PrintSelf method that all objects should define, if they have anything * interesting to print out. */ org_blueberry_core_runtime_EXPORT QDebug operator<<(QDebug os, const berry::Object& o); org_blueberry_core_runtime_EXPORT QDebug operator<<(QDebug os, const berry::SmartPointer& o); org_blueberry_core_runtime_EXPORT QDebug operator<<(QDebug os, const berry::SmartPointer& o); org_blueberry_core_runtime_EXPORT QTextStream& operator<<(QTextStream& os, const berry::Object& o); org_blueberry_core_runtime_EXPORT QTextStream& operator<<(QTextStream& os, const berry::SmartPointer& o); //org_blueberry_core_runtime_EXPORT QTextStream& operator<<(QTextStream& os, const berry::SmartPointer& o); Q_DECLARE_METATYPE(berry::Object::Pointer) org_blueberry_core_runtime_EXPORT uint qHash(const berry::Object& o); #endif /*BERRYOSGILIGHTOBJECT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectGeneric.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectGeneric.h index 1a44329390..9bf2b664cd 100755 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectGeneric.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectGeneric.h @@ -1,113 +1,113 @@ /*=================================================================== 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 BERRYOBJECTGENERIC_H_ #define BERRYOBJECTGENERIC_H_ #include #include #include "berryMacros.h" #include "berryObject.h" namespace berry { template class org_blueberry_core_runtime_EXPORT ObjectGeneric : public Object { public: berryObjectMacro(ObjectGeneric); typedef T ValueType; ObjectGeneric() : m_Value(0) {} ObjectGeneric(T x) : m_Value(x) {} //ObjectGeneric(const Self& o) { m_Value = o.m_Value; } virtual ~ObjectGeneric() { } void SetValue(T val) { m_Value = val; } T GetValue() const { return m_Value; } bool operator==(const Object* o) const { if(const Self* other = dynamic_cast(o)) return (this->m_Value == other->m_Value); return false; } virtual std::string GetValueAsString() const { std::stringstream myStr; std::locale originalLocale = myStr.getloc(); std::locale C("C"); myStr.imbue(C); myStr << GetValue() ; myStr.imbue(originalLocale); return myStr.str(); } virtual bool Assignable(Object::ConstPointer other) const { return other.Cast() != 0; } virtual void Assign(Object::ConstPointer other) { ConstPointer specOther = other.Cast(); if (specOther && this->m_Value != specOther->m_Value) { this->m_Value = specOther->m_Value; } } protected: T m_Value; }; } // namespace berry /** * Generates a specialized subclass of berry::ObjectGeneric. * This way, GetClassName() returns the value provided by ObjectName. * Please see berryObjects.h for examples * @param ObjectName the name of the instantiation of ObjectGeneric * @param Type the value type */ -#define berrySpecializeGenericObject(ObjectName,Type,DefaultValue) \ -class org_blueberry_core_runtime_EXPORT ObjectName: public ::berry::ObjectGeneric< Type > \ +#define berrySpecializeGenericObject(ObjectName,Type,DefaultValue) \ +class org_blueberry_core_runtime_EXPORT ObjectName: public ::berry::ObjectGeneric< Type > \ { \ public: \ berryObjectMacro(ObjectName); \ - ObjectName() : ::berry::ObjectGeneric< Type >(DefaultValue) { } \ - ObjectName(Type x) : ::berry::ObjectGeneric(x) {} \ - /*ObjectName(const ObjectName& o) : ObjectGeneric< Type >(o) {} */ \ + ObjectName() : ::berry::ObjectGeneric< Type >(DefaultValue) { } \ + ObjectName(Type x) : ::berry::ObjectGeneric(x) {} \ + QString ToString() const { QString txt; QTextStream ts(&txt); ts << m_Value; return txt; } \ }; #endif /* BERRYOBJECTGENERIC_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.cpp new file mode 100644 index 0000000000..235ccb5ea6 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.cpp @@ -0,0 +1,57 @@ +/*=================================================================== + +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 "berryObjectString.h" + +namespace berry { + +ObjectString::ObjectString() +{} + +ObjectString::ObjectString(const QString& s) + : QString(s) +{} + +bool ObjectString::operator==(const Object* other) const +{ + if (const ObjectString* otherStr = dynamic_cast(other)) + { + return QString::operator ==(*otherStr); + } + return false; +} + +bool ObjectString::operator==(const QString& other) const +{ + return QString::operator==(other); +} + +QString ObjectString::ToString() const +{ + return *this; +} + +ObjectString::~ObjectString() +{ +} + +berry::ObjectString &berry::ObjectString::operator =(const QString &other) +{ + QString::operator =(other); + return *this; +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.h index 25a2d7c6a0..e289bb4e86 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.h @@ -1,41 +1,53 @@ /*=================================================================== 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 BERRYOSGISTRING_H_ -#define BERRYOSGISTRING_H_ +#ifndef BERRYOBJECTSTRING_H_ +#define BERRYOBJECTSTRING_H_ #include "berryMacros.h" +#include "berryObject.h" #include +#include + namespace berry { -class ObjectString : public QString, public Object +class org_blueberry_core_runtime_EXPORT ObjectString : public QString, public Object { public: berryObjectMacro(berry::ObjectString) - ObjectString() {} - ObjectString(const QString& s) : QString(s) {} + ObjectString(); + ObjectString(const QString& s); + + ~ObjectString(); + + bool operator==(const Object* other) const; + + bool operator==(const QString& other) const; + + ObjectString& operator=(const QString& other); + + QString ToString() const; - ~ObjectString() {} }; } -#endif /*BERRYOSGISTRING_H_*/ +#endif /*BERRYOBJECTSTRING_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.cpp index 56782d9449..459d37d793 100755 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.cpp @@ -1,43 +1,41 @@ /*=================================================================== 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 "berryPlatformObject.h" #include "berryPlatform.h" #include "berryIAdapterManager.h" namespace berry { PlatformObject::PlatformObject() - : Object() { - } -Poco::Any PlatformObject::GetAdapter(const std::string& adapter) +Object* PlatformObject::GetAdapter(const QString& adapter) { IAdapterManager* adapterManager = Platform::GetAdapterManager(); if (adapterManager) { - return adapterManager->GetAdapter(Object::Pointer(this), adapter); + return adapterManager->GetAdapter(this, adapter); } else { - return Poco::Any(); + return NULL; } } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.h index 88534d9f11..ceaeb41b66 100755 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.h @@ -1,84 +1,84 @@ /*=================================================================== 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 BERRYPLATFORMOBJECT_H_ #define BERRYPLATFORMOBJECT_H_ #include #include #include "berryIAdaptable.h" namespace berry { /** * An abstract superclass implementing the IAdaptable * interface. getAdapter invocations are directed * to the platform's adapter manager. *

* Note: In situations where it would be awkward to subclass this * class, the same affect can be achieved simply by implementing * the IAdaptable interface and explicitly forwarding * the getAdapter request to the platform's * adapater manager. The method would look like: *

  *     public Object getAdapter(Class adapter) {
  *         return Platform.getAdapterManager().getAdapter(this, adapter);
  *     }
  * 
*

*

* Clients may subclass. *

* * @see Platform#getAdapterManager */ -class org_blueberry_core_runtime_EXPORT PlatformObject : public Object, public IAdaptable { +class org_blueberry_core_runtime_EXPORT PlatformObject : public virtual Object, public IAdaptable { public: berryObjectMacro(berry::PlatformObject); /** * Constructs a new platform object. */ PlatformObject(); /** * Returns an object which is an instance of the given class * associated with this object. Returns null if * no such object can be found. *

* This implementation of the method declared by IAdaptable * passes the request along to the platform's adapter manager; roughly * Platform.getAdapterManager().getAdapter(this, adapter). * Subclasses may override this method (however, if they do so, they * should invoke the method on their superclass to ensure that the * Platform's adapter manager is consulted). *

* * @see IAdaptable#getAdapter * @see Platform#getAdapterManager */ - Poco::Any GetAdapter(const std::string& adapter); + Object* GetAdapter(const QString& adapter); }; } #endif /* BERRYPLATFORMOBJECT_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryStackTrace.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryStackTrace.cpp deleted file mode 100755 index 19c1a0eece..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryStackTrace.cpp +++ /dev/null @@ -1,804 +0,0 @@ -/*=================================================================== - -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. - -===================================================================*/ -/************************************************************************* - * - * $Id$ - * - * Copyright (c) 1998 by Bjorn Reese - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND - * CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER. - * - ************************************************************************ - * - * 1999/08/19 - breese - * - Cleaned up the interface - * - * 1999/08/06 - breese - * - Added U_STACK_TRACE for HP/UX - * - * 1999/01/24 - breese - * - Added GCC_DumpStack - * - * 1998/12/21 - breese - * - Fixed include files and arguments for waitpid() - * - Made an AIX workaround for waitpid() exiting with EINTR - * - Added a missing 'quit' command for OSF dbx - * - ************************************************************************/ - -#if defined(unix) || defined(__unix) || defined(__xlC__) -# define PLATFORM_UNIX -#elif defined(WIN32) || defined(_WIN32) -# define PLATFORM_WIN32 -#endif - -#if defined(_AIX) || defined(__xlC__) -# define PLATFORM_AIX -#elif defined(__FreeBSD__) -# define PLATFORM_FREEBSD -#elif defined(hpux) || defined(__hpux) || defined(_HPUX_SOURCE) -# define PLATFORM_HPUX -#elif defined(sgi) || defined(mips) || defined(_SGI_SOURCE) -# define PLATFORM_IRIX -#elif defined(__osf__) -# define PLATFORM_OSF -#elif defined(M_I386) || defined(_SCO_DS) || defined(_SCO_C_DIALECT) -# define PLATFORM_SCO -#elif defined(sun) || defined(__sun__) || defined(__SUNPRO_C) -# if defined(__SVR4) || defined(__svr4__) -# define PLATFORM_SOLARIS -# endif -#endif - -/* ANSI C includes */ -#include -#include -#include -#include -#include -#include -#include -#if defined(PLATFORM_UNIX) -# include -# include -# include -# if defined(PLATFORM_IRIX) && defined(USE_BUILTIN) -/* Compile with -DUSE_BUILTIN and -lexc */ -# include -# elif defined(PLATFORM_HPUX) && defined(USE_BUILTIN) -/* Compile with -DUSE_BUILTIN and -lcl */ -extern void U_STACK_TRACE(void); -# endif -#endif - -#ifndef STDIN_FILENO -# define STDIN_FILENO 0 -# define STDOUT_FILENO 1 -# define STDERR_FILENO 2 -#endif // STDIN_FILENO - -#include "berryStackTrace.h" - -#ifndef FALSE -# define FALSE (0 == 1) -# define TRUE (! FALSE) -#endif - -#define SYS_ERROR -1 - -#ifndef EXIT_SUCCESS -# define EXIT_SUCCESS 0 -#endif -#ifndef EXIT_FAILURE -# define EXIT_FAILURE 1 -#endif - -#define MAX_BUFFER_SIZE 512 -#if defined(__GNUC__) -/* Change the code if ADDRESSLIST_SIZE is increased */ -# define ADDRESSLIST_SIZE 20 -#endif - -/************************************************************************* - * Globals - * - * We cannot pass custom arguments to signal handlers so we store - * them as global variables (but limit their scope to this file.) - */ -static const char *global_progname; -static int global_output = STDOUT_FILENO; - - -#if defined(PLATFORM_UNIX) -/************************************************************************* - * my_pclose [private] - */ -static void my_pclose(int fd, int pid) -{ - close(fd); - /* Make sure the the child process has terminated */ - (void)kill(pid, SIGTERM); -} - -/************************************************************************* - * my_popen [private] - */ -static int my_popen(const char *command, pid_t *pid) -{ - int rc; - int pipefd[2]; - - rc = pipe(pipefd); - if (SYS_ERROR != rc) - { - *pid = fork(); - switch (*pid) - { - case SYS_ERROR: - rc = SYS_ERROR; - close(pipefd[0]); - close(pipefd[1]); - break; - - case 0: /* Child */ - close(pipefd[0]); - close(STDOUT_FILENO); - close(STDERR_FILENO); - dup2(pipefd[1], STDOUT_FILENO); - dup2(pipefd[1], STDERR_FILENO); - /* - * The System() call assumes that /bin/sh is - * always available, and so will we. - */ - execl("/bin/sh", "/bin/sh", "-c", command, NULL); - _exit(EXIT_FAILURE); - break; - - default: /* Parent */ - close(pipefd[1]); - rc = pipefd[0]; - break; - } /* switch */ - } - return rc; -} - -/************************************************************************* - * my_getline [private] - */ -static int my_getline(int fd, char *buffer, int max) -{ - char c; - int i = 0; - - do { - if (read(fd, &c, 1) < 1) - return 0; - if (i < max) - buffer[i++] = c; - } while (c != '\n'); - buffer[i] = (char)0; - return i; -} - -/************************************************************************* - * GCC_DumpStack [private] - * - * - * This code is still experimental. - * - * Stackbased arrays are used to prevent allocating from the heap. - * Warning: sprintf/sscanf are not ASync safe. They were used for - * convenience. - * - * 'nm' is used because it is most widespread - * GNU: nm [-B] - * Solaris: nm -x -p - * IRIX: nm -x -B (but __builtin_return_address() always returns NULL) - * AIX: nm -x -B - * OSF/1: nm -B - * SCO/OpenServer: nm -x -p - * HP/UX nm -x -p - */ - -#if defined(__GNUC__) && defined(USE_BUILTIN) - -typedef struct { - unsigned long realAddress; - unsigned long closestAddress; - char name[MAX_BUFFER_SIZE + 1]; - char type; -} address_T; - - -static void GCC_DumpStack(void) -{ - int i; - void *p = &p; /* dummy start value */ - address_T syms[ADDRESSLIST_SIZE + 1]; - char buffer[MAX_BUFFER_SIZE]; - int fd; - pid_t pid; - unsigned long addr; - unsigned long highestAddress; - unsigned long lowestAddress; - char type; - char *pname; - char name[MAX_BUFFER_SIZE]; - int number; - - for (i = 0; p; i++) - { - /* - * This is based on code by Steve Coleman - * - * __builtin_return_address() only accepts a constant as argument. - */ - switch (i) - { - case 0: - if (__builtin_frame_address(0)) - p = __builtin_return_address(0); - else p = NULL; - break; - case 1: - if (__builtin_frame_address(1)) - p = __builtin_return_address(1); - else p = NULL; - break; - case 2: - if (__builtin_frame_address(2)) - p = __builtin_return_address(2); - else p = NULL; - break; - case 3: - if (__builtin_frame_address(3)) - p = __builtin_return_address(3); - else p = NULL; - break; - case 4: - if (__builtin_frame_address(4)) - p = __builtin_return_address(4); - else p = NULL; - break; - case 5: - if (__builtin_frame_address(5)) - p = __builtin_return_address(5); - else p = NULL; - break; - case 6: - if (__builtin_frame_address(6)) - p = __builtin_return_address(6); - else p = NULL; - break; - case 7: - if (__builtin_frame_address(7)) - p = __builtin_return_address(7); - else p = NULL; - break; - case 8: - if (__builtin_frame_address(8)) - p = __builtin_return_address(8); - else p = NULL; - break; - case 9: - if (__builtin_frame_address(9)) - p = __builtin_return_address(9); - else p = NULL; - break; - case 10: - if (__builtin_frame_address(10)) - p = __builtin_return_address(10); - else p = NULL; - break; - case 11: - if (__builtin_frame_address(11)) - p = __builtin_return_address(11); - else p = NULL; - break; - case 12: - if (__builtin_frame_address(12)) - p = __builtin_return_address(12); - else p = NULL; - break; - case 13: - if (__builtin_frame_address(13)) - p = __builtin_return_address(13); - else p = NULL; - break; - case 14: - if (__builtin_frame_address(14)) - p = __builtin_return_address(14); - else p = NULL; - break; - case 15: - if (__builtin_frame_address(15)) - p = __builtin_return_address(15); - else p = NULL; - break; - case 16: - if (__builtin_frame_address(16)) - p = __builtin_return_address(16); - else p = NULL; - break; - case 17: - if (__builtin_frame_address(17)) - p = __builtin_return_address(17); - else p = NULL; - break; - case 18: - if (__builtin_frame_address(18)) - p = __builtin_return_address(18); - else p = NULL; - break; - case 19: - if (__builtin_frame_address(19)) - p = __builtin_return_address(19); - else p = NULL; - break; - default: - /* Change ADDRESSLIST_SIZE if more are added */ - p = NULL; - break; - } - if ((p) && (i < ADDRESSLIST_SIZE)) - { - syms[i].realAddress = (unsigned long)p; - syms[i].closestAddress = 0; - syms[i].name[0] = (char)0; - syms[i].type = ' '; - } - else - { - syms[i].realAddress = 0; - break; /* for */ - } - } /* for */ - - - /* First find out if we are using GNU or vendor nm */ - number = 0; - strcpy(buffer, "nm -V 2>/dev/null | grep GNU | wc -l"); - fd = my_popen(buffer, &pid); - if (SYS_ERROR != fd) - { - if (my_getline(fd, buffer, sizeof(buffer))) - { - sscanf(buffer, "%d", &number); - } - my_pclose(fd, pid); - } - if (number == 0) /* vendor nm */ - { -# if defined(PLATFORM_SOLARIS) || defined(PLATFORM_SCO) || defined(PLATFORM_HPUX) - strcpy(buffer, "nm -x -p "); -# elif defined(PLATFORM_AIX) || defined(PLATFORM_IRIX) || defined(PLATFORM_OSF) - strcpy(buffer, "nm -x -B "); -# else - strcpy(buffer, "nm -B "); -# endif - } - else /* GNU nm */ - strcpy(buffer, "nm -B "); - strcat(buffer, global_progname); - - lowestAddress = ULONG_MAX; - highestAddress = 0; - fd = my_popen(buffer, &pid); - if (SYS_ERROR != fd) - { - while (my_getline(fd, buffer, sizeof(buffer))) - { - if (buffer[0] == '\n') - continue; - if (3 == sscanf(buffer, "%lx %c %s", &addr, &type, name)) - { - if ((type == 't') || type == 'T') - { - if (addr == 0) - continue; /* while */ - if (addr < lowestAddress) - lowestAddress = addr; - if (addr > highestAddress) - highestAddress = addr; - for (i = 0; syms[i].realAddress != 0; i++) - { - if ((addr <= syms[i].realAddress) && - (addr > syms[i].closestAddress)) - { - syms[i].closestAddress = addr; - strncpy(syms[i].name, name, MAX_BUFFER_SIZE); - syms[i].name[MAX_BUFFER_SIZE] = (char)0; - syms[i].type = type; - } - } - } - } - } - my_pclose(fd, pid); - - for (i = 0; syms[i].realAddress != 0; i++) - { - if ((syms[i].name[0] == (char)0) || - (syms[i].realAddress <= lowestAddress) || - (syms[i].realAddress >= highestAddress)) - { - sprintf(buffer, "[%d] 0x%08lx ???\n", i, syms[i].realAddress); - } - else - { - sprintf(buffer, "[%d] 0x%08lx <%s + 0x%lx> %c\n", - i, - syms[i].realAddress, - syms[i].name, - syms[i].realAddress - syms[i].closestAddress, - syms[i].type); - } - write(global_output, buffer, strlen(buffer)); - } - } -} -#endif - -/************************************************************************* - * DumpStack [private] - */ -static int DumpStack(char *format, ...) -{ - int gotSomething = FALSE; - int fd; - pid_t pid; - int status = EXIT_FAILURE; - int rc; - va_list args; - char *buffer; - char cmd[MAX_BUFFER_SIZE]; - char buf[MAX_BUFFER_SIZE]; - - /* - * Please note that vsprintf() is not ASync safe (ie. cannot safely - * be used from a signal handler.) If this proves to be a problem - * then the cmd string can be built by more basic functions such as - * strcpy, strcat, and a homemade integer-to-ascii function. - */ - va_start(args, format); - vsprintf(cmd, format, args); - va_end(args); - - fd = my_popen(cmd, &pid); - if (SYS_ERROR != fd) - { - /* - * Wait for the child to exit. This must be done - * to make the debugger attach successfully. - * The output from the debugger is buffered on - * the pipe. - * - * AIX needs the looping hack - */ - do - { - rc = waitpid(pid, &status, 0); - } - while ((SYS_ERROR == rc) && (EINTR == errno)); - - if ((WIFEXITED(status)) && (WEXITSTATUS(status) == EXIT_SUCCESS)) - { - while (my_getline(fd, buf, sizeof(buf))) - { - buffer = buf; - if (! gotSomething) - { - size_t written = 0; - written += write(global_output, "Output from ", - strlen("Output from ")); - strtok(cmd, " "); - written += write(global_output, cmd, strlen(cmd)); - written += write(global_output, "\n", strlen("\n")); - if (written) gotSomething = TRUE; - } - if ('\n' == buf[strlen(buf)-1]) - { - buf[strlen(buf)-1] = (char)0; - } - size_t written = 0; - written += write(global_output, buffer, strlen(buffer)); - written += write(global_output, "\n", strlen("\n")); - if (written != strlen(buffer) + strlen("\n")) - { - gotSomething = FALSE; - } - } - } - my_pclose(fd, pid); - } - return gotSomething; -} -#endif /* PLATFORM_UNIX */ - -/************************************************************************* - * StackTrace - */ -void StackTrace(void) -{ -#if defined(PLATFORM_UNIX) - /* - * In general dbx seems to do a better job than gdb. - * - * Different dbx implementations require different flags/commands. - */ - -# if defined(PLATFORM_AIX) - - if (DumpStack("dbx -a %d 2>/dev/null </dev/null </dev/null <&1 </dev/null </dev/null </dev/null </dev/null </dev/null </dev/null </dev/null </dev/null </dev/null <&1 < < - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF - * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND - * CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER. - * - ************************************************************************ - * - * Purpose: - * To generate a stacktrace of a program. - * - * Description: - * If a debugger is located on the machine we will try this first, - * as it usually give better information than built-in methods. - * The debugger needs the name of the program to be able to attach - * to it, so this must be passed to StackTraceInit(). The second - * argument is a filedescriptor that StackTrace() writes to. If this - * argument is -1 then standard output will be used. - * - * Compilation: - * Some platforms have a built-in method to generate stacktraces, but - * they are usually located in some non-standard library. The following - * are supported: - * - * IRIX Compile with -DUSE_BUILTIN and -lexc - * HP/UX Compile with -DUSE_BUILTIN and -lcl - * GCC Compile with -DUSE_BUILTIN - * - ************************************************************************/ - -#ifndef H_DEBUG_STACKTRACE -#define H_DEBUG_STACKTRACE - -void StackTrace(void); -void StackTraceInit(const char *progname, int handle); - -#endif /* H_DEBUG_STACKTRACE */ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryStatus.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryStatus.h index 6f7972aff9..93cd3b2dee 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryStatus.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryStatus.h @@ -1,259 +1,259 @@ /*=================================================================== 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 BERRYSTATUS_H_ #define BERRYSTATUS_H_ #include "berryIStatus.h" #include namespace berry { /** * A concrete status implementation, suitable either for * instantiating or subclassing. *

* This class can be used without OSGi running. *

*/ -class org_blueberry_core_runtime_EXPORT Status : public IStatus +class org_blueberry_core_runtime_EXPORT Status : public virtual IStatus { public: struct SourceLocation { SourceLocation(const QString& fileName = QString(), const QString& methodName = QString(), int lineNumber = 0) : fileName(fileName), methodName(methodName), lineNumber(lineNumber) {} const QString fileName; const QString methodName; const int lineNumber; }; private: /** * The severity. One of *
    *
  • CANCEL
  • *
  • ERROR
  • *
  • WARNING
  • *
  • INFO
  • *
  • or OK (0)
  • *
*/ Severity severity; /** Unique identifier of plug-in. */ QString pluginId; /** Plug-in-specific status code. */ int code; /** Message, localized to the current locale. */ QString message; /** Wrapped exception, or null if none. */ ctkException* exception; /** Constant to avoid generating garbage. */ static const QList theEmptyStatusArray; SourceLocation sourceLocation; public: /** * A standard OK status with an "ok" message. */ static const IStatus::Pointer OK_STATUS(const SourceLocation& sl); /** * A standard CANCEL status with no message. */ static const IStatus::Pointer CANCEL_STATUS(const SourceLocation& sl); /** * Creates a new status object. The created status has no children. * * @param severity the severity; one of OK, ERROR, * INFO, WARNING, or CANCEL * @param pluginId the unique identifier of the relevant plug-in * @param code the plug-in-specific status code, or OK * @param message a human-readable message, localized to the * current locale */ Status(const Severity& severity, const QString& pluginId, int code, const QString& message, const SourceLocation& sl); /** * Creates a new status object. The created status has no children. * * @param severity the severity; one of OK, ERROR, * INFO, WARNING, or CANCEL * @param pluginId the unique identifier of the relevant plug-in * @param code the plug-in-specific status code, or OK * @param message a human-readable message, localized to the * current locale * @param exception a low-level exception. */ Status(const Severity& severity, const QString& pluginId, int code, const QString& message, const ctkException& exc, const SourceLocation& sl); /** * Simplified constructor of a new status object; assumes that code is OK. * The created status has no children. * * @param severity the severity; one of OK, ERROR, * INFO, WARNING, or CANCEL * @param pluginId the unique identifier of the relevant plug-in * @param message a human-readable message, localized to the * current locale */ Status(const Severity& severity, const QString& pluginId, const QString& message, const SourceLocation& sl); /** * Simplified constructor of a new status object; assumes that code is OK. * The created status has no children. * * @param severity the severity; one of OK, ERROR, * INFO, WARNING, or CANCEL * @param pluginId the unique identifier of the relevant plug-in * @param message a human-readable message, localized to the * current locale * @param exception a low-level exception. */ Status(const Severity& severity, const QString& pluginId, const QString& message, const ctkException& exc, const SourceLocation& sl); /* * Implements the corresponding method on IStatus. */ QList GetChildren() const; /* * Implements the corresponding method on IStatus. */ int GetCode() const; /* * Implements the corresponding method on IStatus. */ const ctkException* GetException() const; /* * Implements the corresponding method on IStatus. */ QString GetMessage() const; /* * Implements the corresponding method on IStatus. */ QString GetPlugin() const; /* * Implements the corresponding method on IStatus. */ Severity GetSeverity() const; /* * Implements the corresponding method on IStatus. */ bool IsMultiStatus() const; /* * Implements the corresponding method on IStatus. */ bool IsOK() const; /* * Implements the corresponding method on IStatus. */ bool Matches(const Severities& severityMask) const; QString GetFileName() const; QString GetMethodName() const; int GetLineNumber() const; protected: /** * Sets the status code. * * @param code the plug-in-specific status code, or OK */ virtual void SetCode(int code); /** * Sets the exception. * * @param exception a low-level exception, or null if not * applicable */ virtual void SetException(const ctkException& exception); /** * Sets the message. If null is passed, message is set to an empty * string. * * @param message a human-readable message, localized to the * current locale */ virtual void SetMessage(const QString& message); /** * Sets the plug-in id. * * @param pluginId the unique identifier of the relevant plug-in */ virtual void SetPlugin(const QString& pluginId); /** * Sets the severity. * * @param severity the severity; one of OK, ERROR, * INFO, WARNING, or CANCEL */ virtual void SetSeverity(const Severity& severity); public: /** * Returns a string representation of the status, suitable * for debugging purposes only. */ QString ToString() const; }; } #define BERRY_STATUS_LOC berry::Status::SourceLocation(__FILE__, __FUNCTION__, __LINE__) #endif /* BERRYSTATUS_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundle.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundle.cpp deleted file mode 100644 index 409b20c608..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundle.cpp +++ /dev/null @@ -1,318 +0,0 @@ -/*=================================================================== - -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 "berryLog.h" - -#include "Poco/Exception.h" - -#include "berryBundle.h" -#include "berryInternalPlatform.h" -#include "berryBundleLoader.h" -#include "berryBundleManifest.h" -#include "berryIBundleActivator.h" -#include "berryIBundleContext.h" -#include "berryPlatformException.h" - -#include - -#include - -namespace berry { - -Bundle::Bundle(BundleLoader& loader, IBundleStorage::Pointer storage, bool initialize) : - m_BundleLoader(loader) -{ - { - Poco::Mutex::ScopedLock lock(m_Mutex); - m_Storage = storage; - } - - if (initialize) - { - init(); - } -} - -void Bundle::init() -{ - Poco::Mutex::ScopedLock lock(m_Mutex); - try - { - this->LoadManifest(); - m_State = BUNDLE_INSTALLED; - } - catch (Poco::FileException& exc) - { - BERRY_ERROR << "Exception: " << exc.displayText() << std::endl; - m_State = BUNDLE_UNINSTALLED; - } -} - -Bundle::~Bundle() -{ - -} - -bool Bundle::operator==(const Object* o) const -{ - if (const IBundle* bundle = dynamic_cast(o)) - return this->GetSymbolicName() == bundle->GetSymbolicName(); - - return false; -} - -IBundleActivator* -Bundle::GetActivator() const -{ - Poco::Mutex::ScopedLock lock(m_Mutex); - if (m_State == BUNDLE_ACTIVE) - return m_Activator; - - return 0; -} - -const std::string& -Bundle::GetActivatorClass() const -{ - return m_Manifest->GetActivatorClass(); -} - -const std::string& -Bundle::GetActivatorLibrary() const -{ - return m_Manifest->GetActivatorLibrary(); -} - -const std::string& -Bundle::GetCopyright() const -{ - return m_Manifest->GetCopyright(); -} - -const std::string& -Bundle::GetVendor() const -{ - return m_Manifest->GetVendor(); -} - -IBundleManifest::ActivationPolicy -Bundle::GetActivationPolicy() const -{ - return m_Manifest->GetActivationPolicy(); -} - -std::istream* -Bundle::GetLocalizedResource(const std::string& name) const -{ - return m_Storage->GetResource(name); -} - -std::istream* -Bundle::GetResource(const std::string& name) const -{ - return m_Storage->GetResource(name); -} - -bool -Bundle::IsActive() const -{ - return m_State == BUNDLE_ACTIVE; -} - -bool -Bundle::IsResolved() const -{ - return m_State == BUNDLE_RESOLVED || m_State == BUNDLE_STARTING || - m_State == BUNDLE_ACTIVE || m_State == BUNDLE_STOPPING; -} - -bool -Bundle::IsStarted() const -{ - return m_State == BUNDLE_STARTING || m_State == BUNDLE_ACTIVE || - m_State == BUNDLE_STOPPING; -} - -bool Bundle::IsSystemBundle() const -{ - return m_Manifest->IsSystemBundle(); -} - -const IBundleManifest& -Bundle::GetManifest() const -{ - return *m_Manifest; -} - -const std::string& -Bundle::GetName() const -{ - return m_Manifest->GetName(); -} - -const Poco::Path -Bundle::GetPath() const -{ - return m_Storage->GetPath(); -} - -IBundleStorage& -Bundle::GetStorage() -{ - return *m_Storage; -} - -// const Version& GetVersion() const; - -const IBundleManifest::Dependencies& -Bundle::GetRequiredBundles() const -{ - return m_Manifest->GetRequiredBundles(); -} - -void -Bundle::Resolve() -{ - if (m_State == BUNDLE_INSTALLED) - { - ctkPluginContext* context = InternalPlatform::GetInstance()->GetCTKPluginFrameworkContext(); - - //const BundleManifest::Dependencies& dependencies =; - IBundleManifest::Dependencies::const_iterator iter; - for (iter = this->GetRequiredBundles().begin(); iter != this->GetRequiredBundles().end(); ++iter) - { - //BERRY_INFO << "Checking dependency:" << iter->symbolicName << ";\n"; - IBundle::Pointer bundle = m_BundleLoader.FindBundle(iter->symbolicName); - if (bundle.IsNull()) - { - // Check if we have a CTK Plugin dependency - bool resolved = false; - if (context) - { - QString symbolicName = QString::fromStdString(iter->symbolicName); - foreach (QSharedPointer plugin, context->getPlugins()) - { - if (plugin->getSymbolicName() == symbolicName) - { - resolved = true; - break; - } - } - } - - if (!resolved) - { - throw BundleResolveException(QString("The bundle ") + QString::fromStdString(this->GetSymbolicName()) + " depends on missing bundle: " + QString::fromStdString(iter->symbolicName)); - } - } - else if (!bundle->IsResolved()) - { - bundle->Resolve(); - } - } - m_State = BUNDLE_RESOLVED; - } -} - -void -Bundle::Start() -{ - if (m_State == BUNDLE_RESOLVED) - { - Poco::Mutex::ScopedLock lock(m_Mutex); - - m_State = BUNDLE_STARTING; -// BundleEvent starting(this, BundleEvent::EV_BUNDLE_STARTING); -// this->GetEvents().bundleStarting(this, starting); - BERRY_INFO(InternalPlatform::GetInstance()->ConsoleLog()) << "Bundle " << this->GetSymbolicName() << " is starting"; - m_Activator->Start(m_BundleLoader.GetContextForBundle(IBundle::Pointer(this))); - - m_State = BUNDLE_ACTIVE; -// BundleEvent started(this, BundleEvent::EV_BUNDLE_STARTED); -// this->GetEvents().bundleStarted(this, started); -// BERRY_INFO << "Bundle " << this->GetSymbolicName() << " is active"; - } - else - { - throw BundleStateException(QString("Bundle ") + QString::fromStdString(this->GetSymbolicName()) + - " could not be started, because it is not in state RESOLVED."); - } -} - -void -Bundle::Stop() -{ - throw Poco::NotImplementedException("Bundle::Stop() not implemented yet"); -} - -Bundle::State -Bundle::GetState() const -{ - return m_State; -} - -std::string -Bundle::GetStateString() const -{ - switch (this->GetState()) - { - case BUNDLE_INSTALLED: - return "Installed"; - case BUNDLE_UNINSTALLED: - return "Uninstalled"; - case BUNDLE_RESOLVED: - return "Resolved"; - case BUNDLE_STARTING: - return "Starting"; - case BUNDLE_ACTIVE: - return "Active"; - case BUNDLE_STOPPING: - return "Stopping"; - default: throw BundleStateException("The bundle is not in a valid state"); - } -} - -//BundleEvents& -//Bundle::GetEvents() -//{ -// return m_BundleLoader.GetEvents(); -//} - -const std::string& -Bundle::GetSymbolicName() const -{ - return m_Manifest->GetSymbolicName(); -} - -void -Bundle::LoadManifest() -{ - std::istream* istr = m_Storage->GetResource("META-INF/MANIFEST.MF"); - if (!istr) - throw Poco::FileNotFoundException("Could not load META-INF/MANIFEST.MF from " + m_Storage->GetPath().toString()); - - m_Manifest = new BundleManifest(istr); - delete istr; -} - -void -Bundle::SetActivator(IBundleActivator* activator) -{ - Poco::Mutex::ScopedLock lock(m_Mutex); - m_Activator = activator; -} - -} diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundle.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundle.h deleted file mode 100644 index 56be4b28d5..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundle.h +++ /dev/null @@ -1,98 +0,0 @@ -/*=================================================================== - -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 BERRYBUNDLE_H_ -#define BERRYBUNDLE_H_ - -#include "Poco/Path.h" -#include "Poco/Mutex.h" - -#include "berryIBundle.h" -#include "berryIBundleStorage.h" - -namespace berry { - -class BundleLoader; - -class Bundle : public IBundle -{ - -public: - - berryObjectMacro(Bundle); - - Bundle(BundleLoader& loader, IBundleStorage::Pointer storage, bool init = true); - ~Bundle(); - - void init(); - - IBundleActivator* GetActivator() const; - const std::string& GetActivatorClass() const; - const std::string& GetActivatorLibrary() const; - - const std::string& GetCopyright() const; - const std::string& GetVendor() const; - - IBundleManifest::ActivationPolicy GetActivationPolicy() const; - - std::istream* GetLocalizedResource(const std::string& name) const; - std::istream* GetResource(const std::string& name) const; - - bool IsActive() const; - bool IsResolved() const; - bool IsStarted() const; - bool IsSystemBundle() const; - - const IBundleManifest& GetManifest() const; - const std::string& GetName() const; - const Poco::Path GetPath() const; - IBundleStorage& GetStorage(); - // const Version& GetVersion() const; - - const IBundleManifest::Dependencies& GetRequiredBundles() const; - - void Resolve(); - - void Start(); - void Stop(); - - State GetState() const; - std::string GetStateString() const; - - //BundleEvents& GetEvents(); - - const std::string& GetSymbolicName() const; - - virtual void LoadManifest(); - void SetActivator(IBundleActivator* activator); - - bool operator==(const Object* o) const; - -protected: - - IBundleManifest::Pointer m_Manifest; - IBundleStorage::Pointer m_Storage; - BundleLoader& m_BundleLoader; - - IBundleActivator* m_Activator; - State m_State; - - mutable Poco::Mutex m_Mutex; -}; - -} // namespace berry - -#endif /*BERRYBUNDLE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleContext.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleContext.cpp deleted file mode 100644 index 644d41a85e..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleContext.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/*=================================================================== - -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 "berryBundleContext.h" - -#include "berryBundle.h" -#include "berryBundleLoader.h" - -namespace berry { - -BundleContext::BundleContext(BundleLoader& loader, IBundle::Pointer bundle, - const Poco::Path& persistencyDir) : - m_BundleLoader(loader),m_Bundle(bundle), m_PersistencyDir(persistencyDir) -{ - -} - -BundleContext::~BundleContext() -{ - -} - -bool BundleContext::operator==(const Object* o) const -{ - if (const IBundleContext* context = dynamic_cast(o)) - return this->GetThisBundle() == context->GetThisBundle(); - - return false; -} - -void BundleContext::RegisterService(const std::string& id, Service::Pointer service) const -{ - Platform::GetServiceRegistry().RegisterService(id, service); -} - -IBundleContext::Pointer -BundleContext::GetContextForBundle(IBundle::ConstPointer bundle) const -{ - return m_BundleLoader.GetContextForBundle(bundle); -} - -//BundleEvents& -//BundleContext::GetEvents() const -//{ -// return m_BundleLoader.GetEvents(); -//} - -IBundle::ConstPointer -BundleContext::FindBundle(const std::string& name) const -{ - return m_BundleLoader.FindBundle(name); -} - -void -BundleContext::ListBundles(std::vector& bundles) const -{ - for (BundleLoader::BundleMap::const_iterator i = m_BundleLoader.m_BundleMap.begin(); - i != m_BundleLoader.m_BundleMap.end(); ++i) - { - if (i.value().m_Bundle) - { - bundles.push_back(i.value().m_Bundle); - } - } -} - -Poco::Logger& -BundleContext::GetLogger() const -{ - return m_BundleLoader.GetLogger(); -} - -Poco::Path -BundleContext::GetPathForLibrary(const std::string& libraryName) const -{ - return m_BundleLoader.GetPathForLibrary(libraryName); -} - -Poco::Path -BundleContext::GetPersistentDirectory() const -{ - return m_PersistencyDir; -} - -IBundle::Pointer -BundleContext::GetThisBundle() const -{ - return m_Bundle; -} - -void -BundleContext::InitPersistency(const std::string& /*persistencyPath*/) -{ - -} - -} diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleContext.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleContext.h deleted file mode 100644 index e4a3f9a600..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleContext.h +++ /dev/null @@ -1,71 +0,0 @@ -/*=================================================================== - -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 BERRYBUNDLECONTEXT_H_ -#define BERRYBUNDLECONTEXT_H_ - -#include "berryIBundleContext.h" -#include "berryBundleLoader.h" - -namespace berry { - -class BundleContext : public IBundleContext -{ - -public: - - berryObjectMacro(BundleContext); - - BundleContext(BundleLoader& loader, SmartPointer bundle, - const Poco::Path& persistencyDir); - - ~BundleContext(); - - IBundleContext::Pointer GetContextForBundle(SmartPointer bundle) const; - - //BundleEvents& GetEvents() const; - - SmartPointer FindBundle(const std::string& name) const; - - void ListBundles(std::vector >& bundles) const; - - Poco::Logger& GetLogger() const; - - // Logger& GetLogger() const; - - Poco::Path GetPathForLibrary(const std::string& libraryName) const; - - Poco::Path GetPersistentDirectory() const; - - void RegisterService(const std::string& id, Service::Pointer service) const; - - SmartPointer GetThisBundle() const; - - void InitPersistency(const std::string& persistencyPath); - - //static std::string GetLoggerName(const Bundle* bundle); - - bool operator==(const Object* o) const; - -private: - BundleLoader& m_BundleLoader; - SmartPointer m_Bundle; - const Poco::Path m_PersistencyDir; -}; - -} // namespace berry - -#endif /*BERRYBUNDLECONTEXT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleDirectory.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleDirectory.cpp deleted file mode 100644 index a68bd156c6..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleDirectory.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/*=================================================================== - -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 "berryLog.h" - -#include "berryBundleDirectory.h" -#include "berryInternalPlatform.h" - -#include - -#include "Poco/Exception.h" -#include "Poco/FileStream.h" -#include "Poco/Path.h" -#include "Poco/File.h" - -namespace berry { - -BundleDirectory::BundleDirectory(const Path& path) : - m_RootPath(path) -{ - //Path manifestPath(m_RootPath); - //manifestPath.append(Path("META-INF/manifest.mf")); -} - -BundleDirectory::~BundleDirectory() -{ - -} - -bool BundleDirectory::operator==(const Object* o) const -{ - if (const IBundleStorage* dir = dynamic_cast(o)) - return this->GetPath().toString() == dir->GetPath().toString(); - - return false; -} - -std::istream* -BundleDirectory::GetResource(const std::string& path) const -{ - Poco::Path resPath(m_RootPath); - std::string resStr = resPath.append(Path(path)).toString(); - //BERRY_INFO << "Getting resource: " << resStr << std::endl; - try { - return new Poco::FileInputStream(resStr); - } - catch (...) - {} - return 0; -} - -void -BundleDirectory::List(const std::string& path, std::vector& files, - bool quiet) const -{ - try - { - Poco::Path fullPath(m_RootPath); - fullPath.append(path); - Poco::File file(fullPath); - file.list(files); - } - catch (Poco::FileNotFoundException& exc) - { - if (!quiet) - { - BERRY_WARN << "Warning: " << exc.displayText() << std::endl; - throw exc; - } - } - catch (const Poco::PathNotFoundException& exc) - { - if (!quiet) - { - BERRY_WARN << "Warning: " << exc.displayText() << std::endl; - throw exc; - } - } -} - -bool BundleDirectory::IsDirectory(const std::string& path) const -{ - Poco::Path fullPath(m_RootPath); - fullPath.append(path); - Poco::File file(fullPath.makeDirectory()); - //BERRY_INFO(InternalPlatform::GetInstance()->ConsoleLog()) << - // "Testing " << file.path() << " for directory: " << - // (file.exists() && file.isDirectory() ? "true" : "false") << std::endl; - return file.exists() && file.isDirectory(); -} - -Path -BundleDirectory::GetPath() const -{ - return m_RootPath; -} - -Path BundleDirectory::BuildPath(const std::string& path) const -{ - Poco::Path tmp(m_RootPath); - return tmp.append(Path(path)); -} - -} diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleDirectory.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleDirectory.h deleted file mode 100644 index 611fdf604c..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleDirectory.h +++ /dev/null @@ -1,54 +0,0 @@ -/*=================================================================== - -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 BERRYBUNDLEDIRECTORY_H_ -#define BERRYBUNDLEDIRECTORY_H_ - -#include - -#include "berryIBundleStorage.h" - - -namespace berry { - -using namespace Poco; - -class BundleDirectory : public IBundleStorage -{ - -private: - Path m_RootPath; - -public: - - berryObjectMacro(BundleDirectory); - - BundleDirectory(const Path& path); - virtual ~BundleDirectory(); - - std::istream* GetResource(const std::string& path) const; - void List(const std::string& path, std::vector& files, bool quiet = true) const; - bool IsDirectory(const std::string& path) const; - Path GetPath() const; - - Path BuildPath(const std::string& path) const; - - bool operator==(const Object* o) const; -}; - -} // namespace berry - -#endif /*BERRYBUNDLEDIRECTORY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleManifest.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleManifest.cpp deleted file mode 100644 index 17de758e19..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleManifest.cpp +++ /dev/null @@ -1,177 +0,0 @@ -/*=================================================================== - -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 "berryBundleManifest.h" - -#include "Poco/AutoPtr.h" -#include "Poco/StringTokenizer.h" -#include "Poco/Util/PropertyFileConfiguration.h" - -#include - -namespace berry { - -BundleManifest::BundleManifest(std::istream* istr) -: POLICY_EAGER("eager"), POLICY_LAZY("lazy") -{ - this->ParseManifest(istr); -} - -BundleManifest::~BundleManifest() -{ - -} - -bool BundleManifest::operator==(const Object* o) const -{ - if (const IBundleManifest* manifest = dynamic_cast(o)) - return this->GetSymbolicName() == manifest->GetSymbolicName(); - - return false; -} - -const std::string& -BundleManifest::GetActivatorClass() const -{ - return m_Activator; -} - -const std::string& -BundleManifest::GetActivatorLibrary() const -{ - return m_ActivatorLibrary; -} - -const std::string& -BundleManifest::GetCopyright() const -{ - return m_Copyright; -} - -IBundleManifest::ActivationPolicy -BundleManifest::GetActivationPolicy() const -{ - return m_ActivationPolicy; -} - -bool -BundleManifest::IsSystemBundle() const -{ - return m_SystemBundle; -} - -const std::string& -BundleManifest::GetName() const -{ - return m_Name; -} - -const BundleManifest::Dependencies& -BundleManifest::GetRequiredBundles() const -{ - return m_Dependencies; -} - -const std::string& -BundleManifest::GetSymbolicName() const -{ - return m_SymbolicName; -} - -const std::string& -BundleManifest::GetVendor() const -{ - return m_Vendor; -} - -//const Version& GetVersion() const; - -void -BundleManifest::ParseActivator(const std::string& activator) -{ - Poco::StringTokenizer tokenizer(activator, ";", - Poco::StringTokenizer::TOK_IGNORE_EMPTY | Poco::StringTokenizer::TOK_TRIM); - - if (tokenizer.count() == 0) - { - m_Activator = ""; - m_ActivatorLibrary = ""; - return; - } - - m_Activator = tokenizer[0]; - m_Activator = activator; - - m_ActivatorLibrary = ""; - if (tokenizer.count() > 1) - { - Poco::StringTokenizer tokenizer2(tokenizer[1], "=", - Poco::StringTokenizer::TOK_IGNORE_EMPTY | Poco::StringTokenizer::TOK_TRIM); - - if (tokenizer2.count() == 2 && tokenizer2[0] == "library") - { - m_ActivatorLibrary = tokenizer[1]; - } - } - -} - -void -BundleManifest::ParseManifest(std::istream* istr) -{ - //BERRY_INFO << "Start parsing manifest\n"; - Poco::AutoPtr config(new Poco::Util::PropertyFileConfiguration(*istr)); - - if (config->hasProperty(BUNDLE_ACTIVATOR)) - this->ParseActivator(config->getString(BUNDLE_ACTIVATOR)); - else - { - m_Activator = ""; - m_ActivatorLibrary = ""; - } - - - m_Copyright = config->getString(BUNDLE_COPYRIGHT, ""); - m_ActivationPolicy = (config->getString(BUNDLE_ACTIVATION_POLICY, POLICY_LAZY) == POLICY_EAGER) ? EAGER : LAZY ; - m_Name = config->getString(BUNDLE_NAME, ""); - m_SymbolicName = config->getString(BUNDLE_SYMBOLICNAME, ""); - m_Vendor = config->getString(BUNDLE_VENDOR, ""); - m_ManifestVersion = config->getString(MANIFEST_VERSION, "1.0"); - m_SystemBundle = config->getBool(SYSTEM_BUNDLE, false); - - if (config->hasProperty(REQUIRE_BUNDLE)) - this->ParseRequiredBundles(config->getString(REQUIRE_BUNDLE)); - -} - -void -BundleManifest::ParseRequiredBundles(const std::string& requiredBundles) -{ - Poco::StringTokenizer tokenizer(requiredBundles, ",", - Poco::StringTokenizer::TOK_IGNORE_EMPTY | Poco::StringTokenizer::TOK_TRIM); - - Poco::StringTokenizer::Iterator iter; - for (iter = tokenizer.begin(); iter != tokenizer.end(); iter++) - { - Poco::StringTokenizer tokenizer2(*iter, ";", - Poco::StringTokenizer::TOK_IGNORE_EMPTY | Poco::StringTokenizer::TOK_TRIM); - Dependency dep; - dep.symbolicName = tokenizer2[0]; - m_Dependencies.push_back(dep); - } -} - -} // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleManifest.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleManifest.h deleted file mode 100644 index 5e727b5f59..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryBundleManifest.h +++ /dev/null @@ -1,74 +0,0 @@ -/*=================================================================== - -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 BERRYBUNDLEMANIFEST_H_ -#define BERRYBUNDLEMANIFEST_H_ - -#include "berryIBundleManifest.h" - - -namespace berry { - -class BundleManifest : public IBundleManifest -{ - -public: - - berryObjectMacro(BundleManifest); - - BundleManifest(std::istream* istr); - ~BundleManifest(); - - const std::string& GetActivatorClass() const; - const std::string& GetActivatorLibrary() const; - const std::string& GetCopyright() const; - ActivationPolicy GetActivationPolicy() const; - bool IsSystemBundle() const; - const std::string& GetName() const; - const IBundleManifest::Dependencies& GetRequiredBundles() const; - const std::string& GetSymbolicName() const; - const std::string& GetVendor() const; - //const Version& GetVersion() const; - - bool operator==(const Object* o) const; - -private: - - const std::string POLICY_EAGER; - const std::string POLICY_LAZY; - - void ParseActivator(const std::string& activator); - void ParseManifest(std::istream* istr); - void ParseRequiredBundles(const std::string& requiredBundles); - - IBundleManifest::Dependencies m_Dependencies; - std::string m_ActivatorLibrary; - - std::string m_Activator; - std::string m_Copyright; - ActivationPolicy m_ActivationPolicy; - std::string m_Name; - std::string m_SymbolicName; - std::string m_Vendor; - std::string m_Version; - std::string m_ManifestVersion; - bool m_SystemBundle; - std::string m_RequireBundle; -}; - -} // namespace berry - -#endif /*BERRYBUNDLEMANIFEST_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp index 0101264a6c..991041e7a6 100755 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp @@ -1,217 +1,221 @@ /*=================================================================== 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 NOMINMAX +#define NOMINMAX +#endif + #include "berryCTKPluginActivator.h" #include "berryPlatform.h" #include "berryInternalPlatform.h" //#include "berryCTKPluginListener_p.h" #include "berryPreferencesService.h" #include "berryExtensionRegistry.h" #include "berryRegistryConstants.h" #include "berryRegistryProperties.h" #include "berryRegistryStrategy.h" #include #include #include namespace berry { ctkPluginContext* org_blueberry_core_runtime_Activator::context = 0; void org_blueberry_core_runtime_Activator::start(ctkPluginContext* context) { this->context = context; RegistryProperties::SetContext(context); //ProcessCommandLine(); this->startRegistry(); preferencesService.reset(new PreferencesService(context->getDataFile("").absolutePath())); prefServiceReg = context->registerService(preferencesService.data()); // // register a listener to catch new plugin installations/resolutions. // pluginListener.reset(new CTKPluginListener(m_ExtensionPointService)); // context->connectPluginListener(pluginListener.data(), SLOT(pluginChanged(ctkPluginEvent)), Qt::DirectConnection); // // populate the registry with all the currently installed plugins. // // There is a small window here while processPlugins is being // // called where the pluginListener may receive a ctkPluginEvent // // to add/remove a plugin from the registry. This is ok since // // the registry is a synchronized object and will not add the // // same bundle twice. // pluginListener->processPlugins(context->getPlugins()); } void org_blueberry_core_runtime_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) //pluginListener.reset(); //Platform::GetServiceRegistry().UnRegisterService(IExtensionPointService::SERVICE_ID); prefServiceReg.unregister(); preferencesService->ShutDown(); preferencesService.reset(); prefServiceReg = 0; this->stopRegistry(); RegistryProperties::SetContext(NULL); this->context = 0; } ctkPluginContext* org_blueberry_core_runtime_Activator::getPluginContext() { return context; } #if defined(Q_OS_LINUX) || defined(Q_OS_DARWIN) || defined(Q_CC_MINGW) #include QString org_blueberry_core_runtime_Activator::getPluginId(void *symbol) { if (symbol == NULL) return QString(); Dl_info info = {0,0,0,0}; if(dladdr(symbol, &info) == 0) { return QString(); } else if(info.dli_fname) { QFile soPath(info.dli_fname); int index = soPath.fileName().lastIndexOf('.'); QString pluginId = soPath.fileName().left(index); if (pluginId.startsWith("lib")) pluginId = pluginId.mid(3); return pluginId.replace('_', '.'); } return QString(); } +#elif defined(Q_CC_MSVC) + +#include +#include +#include +QString org_blueberry_core_runtime_Activator::getPluginId(void *symbol) +{ + if (symbol == NULL) return QString(); + + if (ctk::DebugSymInitialize()) + { + std::vector moduleBuffer(sizeof(IMAGEHLP_MODULE64)); + PIMAGEHLP_MODULE64 pModuleInfo = (PIMAGEHLP_MODULE64)&moduleBuffer.front(); + pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64); + if (SymGetModuleInfo64(GetCurrentProcess(), (DWORD64)symbol, pModuleInfo)) + { + QString pluginId = pModuleInfo->ModuleName; + return pluginId.replace('_', '.'); + } + } + return QString(); +} + +#endif + +org_blueberry_core_runtime_Activator::org_blueberry_core_runtime_Activator() + : userRegistryKey(new QObject()) + , masterRegistryKey(new QObject()) +{ +} + +org_blueberry_core_runtime_Activator::~org_blueberry_core_runtime_Activator() +{ +} + void org_blueberry_core_runtime_Activator::startRegistry() { // see if the customer suppressed the creation of default registry QString property = context->getProperty(RegistryConstants::PROP_DEFAULT_REGISTRY).toString(); if (property.compare("false", Qt::CaseInsensitive) == 0) return; // check to see if we need to use null as a userToken if (context->getProperty(RegistryConstants::PROP_REGISTRY_NULL_USER_TOKEN).toString().compare("true", Qt::CaseInsensitive) == 0) { userRegistryKey.reset(0); } // Determine primary and alternative registry locations. BlueBerry extension registry cache // can be found in one of the two locations: // a) in the local configuration area (standard location passed in by the platform) -> priority // b) in the shared configuration area (typically, shared install is used) QList registryLocations; QList readOnlyLocations; RegistryStrategy* strategy = NULL; //Location configuration = OSGIUtils.getDefault().getConfigurationLocation(); QString configuration = context->getDataFile("").absoluteFilePath(); if (configuration.isEmpty()) { RegistryProperties::SetProperty(RegistryConstants::PROP_NO_REGISTRY_CACHE, "true"); RegistryProperties::SetProperty(RegistryConstants::PROP_NO_LAZY_CACHE_LOADING, "true"); strategy = new RegistryStrategy(QList(), QList(), masterRegistryKey.data()); } else { //File primaryDir = new File(configuration.getURL().getPath() + '/' + STORAGE_DIR); //bool primaryReadOnly = configuration.isReadOnly(); QString primaryDir = configuration; bool primaryReadOnly = false; //Location parentLocation = configuration.getParentLocation(); QString parentLocation; if (!parentLocation.isEmpty()) { // File secondaryDir = new File(parentLocation.getURL().getFile() + '/' + IRegistryConstants.RUNTIME_NAME); // registryLocations << primaryDir << secondaryDir; // readOnlyLocations << primaryReadOnly << true; // secondary BlueBerry location is always read only } else { registryLocations << primaryDir; readOnlyLocations << primaryReadOnly; } strategy = new RegistryStrategy(registryLocations, readOnlyLocations, masterRegistryKey.data()); } ExtensionRegistry* registry = new ExtensionRegistry(strategy, masterRegistryKey.data(), userRegistryKey.data()); defaultRegistry.reset(registry); registryServiceReg = context->registerService(registry); //commandRegistration = EquinoxUtils.registerCommandProvider(Activator.getContext()); } void org_blueberry_core_runtime_Activator::stopRegistry() { if (!defaultRegistry.isNull()) { registryServiceReg.unregister(); defaultRegistry->Stop(masterRegistryKey.data()); } // if (!commandRegistration.isNull()) // { // commandRegistration.unregister(); // } } -#elif defined(Q_CC_MSVC) - -#include -#include -#include -QString org_blueberry_core_runtime_Activator::getPluginId(void *symbol) -{ - if (symbol == NULL) return QString(); - - if (ctk::DebugSymInitialize()) - { - std::vector moduleBuffer(sizeof(IMAGEHLP_MODULE64)); - PIMAGEHLP_MODULE64 pModuleInfo = (PIMAGEHLP_MODULE64)&moduleBuffer.front(); - pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64); - if (SymGetModuleInfo64(GetCurrentProcess(), (DWORD64)symbol, pModuleInfo)) - { - QString pluginId = pModuleInfo->ModuleName; - return pluginId.replace('_', '.'); - } - } - return QString(); -} - -#endif - -org_blueberry_core_runtime_Activator::org_blueberry_core_runtime_Activator() - : userRegistryKey(new QObject()) - , masterRegistryKey(new QObject()) -{ -} - -org_blueberry_core_runtime_Activator::~org_blueberry_core_runtime_Activator() -{ -} - } Q_EXPORT_PLUGIN2(org_blueberry_core_runtime, berry::org_blueberry_core_runtime_Activator) diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.h index b60a8d1de3..cedb78f70d 100755 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.h @@ -1,81 +1,81 @@ /*=================================================================== 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 BERRYCTKPLUGINACTIVATOR_H #define BERRYCTKPLUGINACTIVATOR_H #include #include #include namespace berry { //class CTKPluginListener; class PreferencesService; -class IExtensionRegistry; +struct IExtensionRegistry; class org_blueberry_core_runtime_Activator : public QObject, public ctkPluginActivator { Q_OBJECT #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) Q_PLUGIN_METADATA(IID "org_blueberry_osgi") #endif Q_INTERFACES(ctkPluginActivator) public: org_blueberry_core_runtime_Activator(); ~org_blueberry_core_runtime_Activator(); void start(ctkPluginContext* context); void stop(ctkPluginContext* context); static ctkPluginContext* getPluginContext(); /** * Returns the plug-in id of the plug-in that contains the provided symbol, or * a null QString if the plug-in could not be determined. */ static QString getPluginId(void* symbol); private: void startRegistry(); void stopRegistry(); static ctkPluginContext* context; //QScopedPointer pluginListener; QScopedPointer preferencesService; ctkServiceRegistration prefServiceReg; QScopedPointer defaultRegistry; ctkServiceRegistration registryServiceReg; QScopedPointer userRegistryKey; QScopedPointer masterRegistryKey; }; typedef org_blueberry_core_runtime_Activator CTKPluginActivator; } #endif // BERRYCTKPLUGINACTIVATOR_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginListener.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginListener.cpp index f2a17f5dee..3d5ac88a07 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginListener.cpp @@ -1,150 +1,150 @@ /*=================================================================== 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 "berryCTKPluginListener.h" #include "berryExtensionRegistry.h" #include "berryRegistryStrategy.h" #include "berryIContributor.h" #include "berryContributorFactory.h" #include #include #include #include const QString berry::CTKPluginListener::PLUGIN_MANIFEST = "plugin.xml"; namespace berry { CTKPluginListener::CTKPluginListener(ExtensionRegistry* registry, QObject* key, RegistryStrategy* strategy) : registry(registry), strategy(strategy), token(key) { currentStateStamp << 0; } void CTKPluginListener::ProcessPlugins(const QList >& plugins) { // sort the plugins according to their dependencies //const QList > sortedPlugins = sortPlugins(plugins); foreach (QSharedPointer plugin, plugins) { if (IsPluginResolved(plugin)) AddPlugin(plugin); else RemovePlugin(plugin); } } void CTKPluginListener::PluginChanged(const ctkPluginEvent& event) { /* Only should listen for RESOLVED and UNRESOLVED events. * * When a plugin is updated the Framework will publish an UNRESOLVED and * then a RESOLVED event which should cause the plugin to be removed * and then added back into the registry. * * When a plugin is uninstalled the Framework should publish an UNRESOLVED * event and then an UNINSTALLED event so the plugin will have been removed * by the UNRESOLVED event before the UNINSTALLED event is published. */ QSharedPointer plugin = event.getPlugin(); switch (event.getType()) { case ctkPluginEvent::RESOLVED : { { QMutexLocker l(&mutex); long newStateStamp = registry->ComputeState(); if (currentStateStamp[0] != newStateStamp) { // new state stamp currentStateStamp[0] = newStateStamp; } } AddPlugin(plugin); break; } case ctkPluginEvent::UNRESOLVED : RemovePlugin(plugin); break; + default: break; } } bool CTKPluginListener::IsPluginResolved(QSharedPointer plugin) { return (plugin->getState() & (ctkPlugin::RESOLVED | ctkPlugin::ACTIVE | ctkPlugin::STARTING | ctkPlugin::STOPPING)) != 0; } void CTKPluginListener::RemovePlugin(QSharedPointer plugin) { long timestamp = 0; if (strategy->CheckContributionsTimestamp()) { QString pluginManifest = GetExtensionPath(plugin); if (!pluginManifest.isEmpty()) { timestamp = strategy->GetExtendedTimestamp(plugin, pluginManifest); } } registry->Remove(QString::number(plugin->getPluginId()), timestamp); } QString CTKPluginListener::GetExtensionPath(QSharedPointer plugin) { // bail out if system plugin if (plugin->getPluginId() == 0) return QString(); // bail out if the plugin does not have a symbolic name if (plugin->getSymbolicName().isEmpty()) return QString(); return PLUGIN_MANIFEST; } void CTKPluginListener::AddPlugin(QSharedPointer plugin) { // if the given plugin already exists in the registry then return. // note that this does not work for update cases. IContributor::Pointer contributor = ContributorFactory::CreateContributor(plugin); if (registry->HasContributor(contributor)) { return; } QString pluginManifest = GetExtensionPath(plugin); if (pluginManifest.isEmpty()) return; QByteArray ba = plugin->getResource(pluginManifest); if (ba.isEmpty()) return; long timestamp = 0; if (strategy->CheckContributionsTimestamp()) { timestamp = strategy->GetExtendedTimestamp(plugin, pluginManifest); } QBuffer buffer(&ba); - //buffer.open(QIODevice::ReadOnly); registry->AddContribution(&buffer, contributor, true, pluginManifest, NULL, token, timestamp); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginUtils.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginUtils.cpp index 1fd7880031..0559118d62 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginUtils.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginUtils.cpp @@ -1,120 +1,120 @@ /*=================================================================== 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 "berryCTKPluginUtils.h" #include "berryCTKPluginActivator.h" #include "berryIRuntimeConstants.h" #include "berryLog.h" #include namespace berry { const QString CTKPluginUtils::PROP_CONFIG_AREA = "blueberry.configuration.area"; const QString CTKPluginUtils::PROP_INSTANCE_AREA = "blueberry.instance.area"; CTKPluginUtils::CTKPluginUtils() { InitServices(); } void CTKPluginUtils::InitServices() { ctkPluginContext* context = org_blueberry_core_runtime_Activator::getPluginContext(); if (context == NULL) { //RuntimeLog.log(new Status(IStatus.ERROR, RegistryMessages.OWNER_NAME, 0, RegistryMessages.bundle_not_activated, null)); BERRY_ERROR << "The plugin " << IRuntimeConstants::PI_RUNTIME() << " was not activated."; return; } //debugTracker = new ServiceTracker(context, DebugOptions.class.getName(), null); //debugTracker.open(); // locations //const QString FILTER_PREFIX = "(&(objectClass=org.blueberry.service.datalocation.Location)(type="; // Filter filter = null; // try { // filter = context.createFilter(FILTER_PREFIX + PROP_CONFIG_AREA + "))"); //$NON-NLS-1$ // } catch (InvalidSyntaxException e) { // // ignore this. It should never happen as we have tested the above format. // } // configurationLocationTracker = new ServiceTracker(context, filter, null); // configurationLocationTracker.open(); } CTKPluginUtils* CTKPluginUtils::GetDefault() { static CTKPluginUtils singleton; return &singleton; } void CTKPluginUtils::CloseServices() { // if (!debugTracker.isNull()) // { // debugTracker->close(); // debugTracker.reset(); // } // if (!configurationLocationTracker.isNull()) // { // configurationLocationTracker->close(); // configurationLocationTracker.reset(); // } } -bool CTKPluginUtils::GetBoolDebugOption(const QString& option, bool defaultValue) const +bool CTKPluginUtils::GetBoolDebugOption(const QString& /*option*/, bool defaultValue) const { // if (debugTracker == null) { // RuntimeLog.log(new Status(IStatus.ERROR, RegistryMessages.OWNER_NAME, 0, RegistryMessages.bundle_not_activated, null)); // return defaultValue; // } // DebugOptions options = (DebugOptions) debugTracker.getService(); // if (options != null) { // String value = options.getOption(option); // if (value != null) // return value.equalsIgnoreCase("true"); //$NON-NLS-1$ // } return defaultValue; } QSharedPointer CTKPluginUtils::GetPlugin(const QString& pluginName) { QList > plugins = org_blueberry_core_runtime_Activator::getPluginContext()->getPlugins(); //Return the first plugin matching the plugin name and which is not installed or uninstalled foreach (QSharedPointer plugin, plugins) { if (plugin->getSymbolicName() == pluginName && (plugin->getState() & (ctkPlugin::INSTALLED | ctkPlugin::UNINSTALLED)) == 0) { return plugin; } } return QSharedPointer(); } //Location CTKPluginUtils::GetConfigurationLocation() const //{ // if (configurationLocationTracker == null) // return null; // return (Location) configurationLocationTracker.getService(); //} } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCodeCache.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCodeCache.cpp deleted file mode 100644 index 0555e60866..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCodeCache.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/*=================================================================== - -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 "berryLog.h" - -#include "berryCodeCache.h" -#include "berryInternalPlatform.h" - -#include "Poco/Path.h" -#include "Poco/SharedLibrary.h" - -#include -#include -#include - -namespace berry { - -CodeCache::CodeCache(const std::string& path) : m_CachePath(path) -{ - BERRY_INFO(InternalPlatform::GetInstance()->ConsoleLog()) << "Creating CodeCache with path: " << path << std::endl; - if (!m_CachePath.exists()) - { - m_CachePath.createDirectories(); - } - -} - -CodeCache::~CodeCache() -{ - -} - -void -CodeCache::Clear() -{ - if (m_CachePath.exists()) - { - BERRY_INFO(InternalPlatform::GetInstance()->ConsoleLog()) << "Clearing code cache\n"; - std::vector files; - m_CachePath.list(files); - for (std::vector::iterator iter = files.begin(); iter != files.end(); ++iter) - { - iter->remove(true); - } - } -} - -bool -CodeCache::HasLibrary(const std::string& name) -{ - //BERRY_INFO << "HasLibrary checks for: " << name; - - std::vector files; - m_CachePath.list(files); - - std::string libName(name); - //libName.append(Poco::SharedLibrary::suffix()); - - std::vector::iterator iter; - for (iter = files.begin(); iter != files.end(); iter++) - { - if ((*iter) == libName) { - //BERRY_INFO << " FOUND\n"; - return true; - } - } - - //BERRY_INFO << " NOT FOUND\n"; - return false; -} - -void -CodeCache::InstallLibrary(const std::string& name, std::istream& istr) -{ - //BERRY_INFO << "Installing library " << name << " to " << this->GetPathForLibrary(name).toString() << std::endl; - std::ofstream ostr(this->GetPathForLibrary(name).toString().c_str(), std::ios::binary | std::ios::trunc); - - ostr << istr.rdbuf(); -} - -void -CodeCache::InstallLibrary(const std::string& name, const Poco::File& path) -{ - //BERRY_INFO << "Registering library " << name << " in " << path.path() << std::endl; - m_LibPaths.insert(std::make_pair(name, path)); -} - -void -CodeCache::UnInstallLibrary(const std::string& name) -{ - std::map::iterator iter = m_LibPaths.find(name); - - if (iter == m_LibPaths.end()) - { - Poco::File(this->GetPathForLibrary(name)).remove(); - } - else - { - m_LibPaths.erase(name); - } -} - -Poco::Path -CodeCache::GetPathForLibrary(const std::string& name) -{ - // We instructed cmake to replace "." with "_" in library names - // since they are also used for defines (for Windows dll import/export - // stuff) and . is bad in identifiers. - // Hence we must replace all "." with "_" here too - std::string libName(name); - std::replace(libName.begin(), libName.end(), '.', '_'); - - //BERRY_INFO << "Getting path for library: " << libName << std::endl; - if (m_LibPaths.find(libName) != m_LibPaths.end()) - { - return Poco::Path(m_LibPaths[libName].path(), libName + Poco::SharedLibrary::suffix()); - } - else - { - return Poco::Path(m_CachePath.path(), libName + Poco::SharedLibrary::suffix()); - } -} - -} diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCodeCache.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCodeCache.h deleted file mode 100644 index b4060bd499..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCodeCache.h +++ /dev/null @@ -1,83 +0,0 @@ -/*=================================================================== - -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 BERRYCODECACHE_H_ -#define BERRYCODECACHE_H_ - -#include -#include -#include - -#include "Poco/File.h" -#include "Poco/Path.h" - -namespace berry { - -class CodeCache -{ -public: - CodeCache(const std::string& path); - virtual ~CodeCache(); - - void Clear(); - - /** - * Checks if the library with name name is installed - * - * @param name The name of the library without the library suffix - * @return true if the library is installed, false otherwise - */ - bool HasLibrary(const std::string& name); - - /** - * Installs a library in the plugin cache directory under the name name. - * This is used to copy libraries from Zip files, network locations etc. - * into the local cache directory. - * - * @param name The name of the library without the library suffix - * @param istr The binary input stream representing the library to be installed - */ - void InstallLibrary(const std::string& name, std::istream& istr); - - /** - * Installs the library name. The method only registers a library under the - * name name in the path path (no files or copied). - * - * @param name The name of the library without the library suffix - * @param path The path to the library - */ - void InstallLibrary(const std::string& name, const Poco::File& path); - - /** - * If the library with name name has been copied into the local - * cache directory, it will be deleted. Otherwise, the library will become - * unknown to the CodeCache. - * - * @param name The name of the library without the library suffix - */ - void UnInstallLibrary(const std::string& name); - - Poco::Path GetPathForLibrary(const std::string& name); - -private: - Poco::File m_CachePath; - - std::map m_LibPaths; -}; - -} - -#endif /*BERRYCODECACHE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCombinedEventDelta.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCombinedEventDelta.cpp index 7d0bc8040a..0e43f0c16d 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCombinedEventDelta.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCombinedEventDelta.cpp @@ -1,205 +1,206 @@ /*=================================================================== 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 "berryCombinedEventDelta.h" #include "berryExtensionPoint.h" #include "berryExtensionPointHandle.h" #include "berryIExtensionPoint.h" #include "berryExtensionHandle.h" #include "berryIExtension.h" #include "berryIObjectManager.h" #include namespace berry { struct CombinedEventDeltaData : public QSharedData { const bool addition; // true: objects were added; false: objects were removed // the object manager from which all the objects contained in this delta will be found SmartPointer objectManager; QHash > extensionsByID; // extension point ID -> List of Integer extensions IDs QHash > extPointsByID; // extension point ID -> List of Integer extension point IDs QList allExtensions; // List of Integer IDs QList allExtensionPoints; // List if Integer IDs CombinedEventDeltaData(bool addition) : addition(addition), objectManager(0) { } QList& GetExtensionsBucket(const QString& id) { return extensionsByID[id]; } QList& GetExtPointsBucket(const QString& id) { return extPointsByID[id]; } QList& GetExtPointsGlobal() { return allExtensionPoints; } QList& GetExtensionsGlobal() { return allExtensions; } }; CombinedEventDelta::CombinedEventDelta(bool addition) : d(new CombinedEventDeltaData(addition)) { } CombinedEventDelta::CombinedEventDelta() { } CombinedEventDelta::CombinedEventDelta(const CombinedEventDelta &other) : d(other.d) { } CombinedEventDelta::~CombinedEventDelta() { } CombinedEventDelta &CombinedEventDelta::operator =(const CombinedEventDelta &other) { d = other.d; + return *this; } void CombinedEventDelta::Reset() { d.reset(); } bool CombinedEventDelta::IsNull() const { return !d; } CombinedEventDelta CombinedEventDelta::RecordAddition() { return CombinedEventDelta(true); } CombinedEventDelta CombinedEventDelta::RecordRemoval() { return CombinedEventDelta(false); } bool CombinedEventDelta::IsAddition() const { return d->addition; } bool CombinedEventDelta::IsRemoval() const { return !d->addition; } void CombinedEventDelta::SetObjectManager(const SmartPointer& manager) { d->objectManager = manager; } SmartPointer CombinedEventDelta::GetObjectManager() const { return d->objectManager; } void CombinedEventDelta::RememberExtensionPoint(const SmartPointer& extensionPoint) { QString bucketId = extensionPoint->GetUniqueIdentifier(); int extPt = extensionPoint->GetObjectId(); d->GetExtPointsBucket(bucketId).push_back(extPt); d->GetExtPointsGlobal().push_back(extPt); } void CombinedEventDelta::RememberExtension(const SmartPointer& extensionPoint, int ext) { QString bucketId = extensionPoint->GetUniqueIdentifier(); d->GetExtensionsBucket(bucketId).push_back(ext); d->GetExtensionsGlobal().push_back(ext); } void CombinedEventDelta::RememberExtensions(const SmartPointer& extensionPoint, const QList& exts) { for (int i = 0; i < exts.size(); ++i) RememberExtension(extensionPoint, exts[i]); } QList > CombinedEventDelta::GetExtensionPoints(const QString& id) const { QList extensionPoints; if (!id.isEmpty() && !d->extPointsByID.isEmpty()) { extensionPoints = d->extPointsByID[id]; } else if (id.isEmpty()) { extensionPoints = d->allExtensionPoints; } if (extensionPoints.isEmpty()) // no changes that fit the filter return QList(); QList result; for (int i = 0; i < extensionPoints.size(); ++i) { int extPt = extensionPoints[i]; IExtensionPoint::Pointer extensionPoint(new ExtensionPointHandle(d->objectManager, extPt)); result.push_back(extensionPoint); } return result; } QList > CombinedEventDelta::GetExtensions(const QString& id) const { QList extensions; if (!id.isEmpty() && !d->extensionsByID.isEmpty()) { extensions = d->extensionsByID[id]; } else if (id.isEmpty()) { extensions = d->allExtensions; } if (extensions.isEmpty()) // no changes that fit the filter return QList(); QList result; for (int i = 0; i < extensions.size(); ++i) { int ext = extensions[i]; IExtension::Pointer extension(new ExtensionHandle(d->objectManager, ext)); result.push_back(extension); } return result; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryConfigurationElement.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryConfigurationElement.cpp index 1cd6f369fd..23faeb6f50 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryConfigurationElement.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryConfigurationElement.cpp @@ -1,315 +1,315 @@ /*=================================================================== 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 "berryConfigurationElement.h" #include "berryIExecutableExtension.h" #include "berryIExecutableExtensionFactory.h" #include "berryConfigurationElementHandle.h" #include "berryStatus.h" #include "berryRegistryMessages.h" #include "berryRegistryConstants.h" #include "berryCoreException.h" #include "berryExtensionRegistry.h" #include "berryRegistryObjectManager.h" #include "berryRegistryContributor.h" #include "berryObjectString.h" #include "berryObjectStringMap.h" #include namespace berry { ConfigurationElement::ConfigurationElement(ExtensionRegistry* registry, bool persist) : RegistryObject(registry, persist) { } ConfigurationElement::ConfigurationElement(int self, const QString& contributorId, const QString& name, const QList& propertiesAndValue, const QList& children, int extraDataOffset, int parent, short parentType, ExtensionRegistry* registry, bool persist) : RegistryObject(registry, persist), parentId(parent), parentType(parentType), propertiesAndValue(propertiesAndValue), name(name), contributorId(contributorId) { SetObjectId(self); SetRawChildren(children); SetExtraDataOffset(extraDataOffset); } void ConfigurationElement::ThrowException(const QString& message, const ctkException& exc) { IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, RegistryConstants::PLUGIN_ERROR, message, exc, BERRY_STATUS_LOC)); throw CoreException(status); } void ConfigurationElement::ThrowException(const QString &message) { IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, RegistryConstants::PLUGIN_ERROR, message, BERRY_STATUS_LOC)); throw CoreException(status); } QString ConfigurationElement::GetValue() const { return GetValueAsIs(); } QString ConfigurationElement::GetValueAsIs() const { if (!propertiesAndValue.empty() && propertiesAndValue.size() % 2 == 1) return propertiesAndValue.back(); return QString(); } QString ConfigurationElement::GetAttributeAsIs(const QString& attrName) const { if (propertiesAndValue.size() <= 1) return QString(); int size = propertiesAndValue.size() - (propertiesAndValue.size() % 2); for (int i = 0; i < size; i += 2) { if (propertiesAndValue[i] == attrName) return propertiesAndValue[i + 1]; } return QString(); } QList ConfigurationElement::GetAttributeNames() const { if (propertiesAndValue.size() <= 1) return QList(); QList result; int size = propertiesAndValue.size() / 2; for (int i = 0; i < size; i++) { result.push_back(propertiesAndValue[i * 2]); } return result; } void ConfigurationElement::SetProperties(const QList& value) { propertiesAndValue = value; } QList ConfigurationElement::GetPropertiesAndValue() const { return propertiesAndValue; } void ConfigurationElement::SetValue(const QString& value) { if (propertiesAndValue.empty()) { propertiesAndValue.push_back(value); return; } if (propertiesAndValue.size() % 2 == 1) { propertiesAndValue[propertiesAndValue.size() - 1] = value; return; } propertiesAndValue.push_back(value); } void ConfigurationElement::SetContributorId(const QString& id) { contributorId = id; } QString ConfigurationElement::GetContributorId() const { return contributorId; } void ConfigurationElement::SetParentId(int objectId) { parentId = objectId; } QString ConfigurationElement::GetName() const { return name; } void ConfigurationElement::SetName(const QString& name) { this->name = name; } void ConfigurationElement::SetParentType(short type) { parentType = type; } QObject* ConfigurationElement::CreateExecutableExtension(const QString& attributeName) { QString prop; QString executable; QString contributorName; QString className; Object::Pointer initData; int i = 0; if (!attributeName.isEmpty()) { prop = GetAttribute(attributeName); } else { // property not specified, try as element value prop = GetValue().trimmed(); } if (prop.isEmpty()) { // property not defined, try as a child element QList exec = GetChildren(attributeName); if (!exec.empty()) { ConfigurationElement::Pointer element = exec[0]; // assumes single definition contributorName = element->GetAttribute("plugin"); className = element->GetAttribute("class"); QList parms = element->GetChildren("parameter"); if (!parms.empty()) { QHash initParms; for (i = 0; i < parms.size(); i++) { QString pname = parms[i]->GetAttribute("name"); if (!pname.isEmpty()) initParms.insert(pname, parms[i]->GetAttribute("value")); } if (!initParms.isEmpty()) initData = new ObjectStringMap(initParms); } } else { // specified name is not a simple attribute nor child element ThrowException(QString("Executable extension definition for \"%1\" not found.").arg(attributeName)); } } else { // simple property or element value, parse it into its components i = prop.indexOf(QRegExp("[^:]:[^:]")); if (i != -1) { executable = prop.left(i+1).trimmed(); initData = new ObjectString(prop.mid(i + 2).trimmed()); } else { executable = prop; } i = executable.indexOf('/'); if (i != -1) { contributorName = executable.left(i).trimmed(); className = executable.mid(i + 1).trimmed(); } else { className = executable; } } // create a new instance RegistryContributor::Pointer defaultContributor = registry->GetObjectManager()->GetContributor(contributorId); QObject* result = registry->CreateExecutableExtension(defaultContributor, className, contributorName); // Check if we have extension adapter and initialize; // Make the call even if the initialization string is null try { // We need to take into account both "old" and "new" style executable extensions if (IExecutableExtension* execExt = qobject_cast(result)) { ConfigurationElementHandle::Pointer confElementHandle(new ConfigurationElementHandle( registry->GetObjectManager(), GetObjectId())); execExt->SetInitializationData(confElementHandle, attributeName, initData); } } catch (const CoreException& ce) { // user code threw exception throw ce; } catch (const ctkException& te) { // user code caused exception ThrowException(QString("Plug-in \"%1\" was unable to execute setInitializationData on an instance of \"%2\".") .arg(GetContributor()->GetName()).arg(className), te); } // Deal with executable extension factories. if (IExecutableExtensionFactory* execExtFactory = qobject_cast(result)) { result = execExtFactory->Create(); } return result; } -QString ConfigurationElement::GetAttribute(const QString& attrName, const QLocale& locale) const +QString ConfigurationElement::GetAttribute(const QString& attrName, const QLocale& /*locale*/) const { registry->LogMultiLangError(); return GetAttribute(attrName); } -QString ConfigurationElement::GetValue(const QLocale& locale) const +QString ConfigurationElement::GetValue(const QLocale& /*locale*/) const { registry->LogMultiLangError(); return GetValue(); } QString ConfigurationElement::GetAttribute(const QString& attrName) const { return GetAttributeAsIs(attrName); } QList ConfigurationElement::GetChildren(const QString& childrenName) const { QList result; if (GetRawChildren().empty()) return result; RegistryObjectManager::Pointer objectManager = registry->GetObjectManager(); for (int i = 0; i < children.size(); i++) { ConfigurationElement::Pointer toTest = objectManager->GetObject( children[i], NoExtraData() ? RegistryObjectManager::CONFIGURATION_ELEMENT : RegistryObjectManager::THIRDLEVEL_CONFIGURATION_ELEMENT).Cast(); if (toTest->name == childrenName) { result.push_back(toTest); } } return result; } SmartPointer ConfigurationElement::GetContributor() const { return registry->GetObjectManager()->GetContributor(contributorId); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryConfigurationElementHandle.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryConfigurationElementHandle.cpp index 94d1c00fe3..6d01c7b088 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryConfigurationElementHandle.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryConfigurationElementHandle.cpp @@ -1,202 +1,202 @@ /*=================================================================== 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 "berryConfigurationElementHandle.h" #include "berryConfigurationElement.h" #include "berryCoreException.h" #include "berryExtensionRegistry.h" #include "berryExtensionHandle.h" #include "berryIContributor.h" #include "berryIExtension.h" #include "berryInvalidRegistryObjectException.h" #include "berryRegistryObjectManager.h" #include "berryRegistryMessages.h" #include "berryRegistryConstants.h" #include "berryStatus.h" namespace berry { ConfigurationElementHandle::ConfigurationElementHandle(const SmartPointer& objectManager, int id) : Handle(objectManager, id) { } ConfigurationElementHandle::ConfigurationElementHandle(const IObjectManager *objectManager, int id) : Handle(objectManager, id) { } QString ConfigurationElementHandle::GetAttribute(const QString& propertyName) const { return GetConfigurationElement()->GetAttribute(propertyName); } QString ConfigurationElementHandle::GetAttribute(const QString& attrName, const QLocale& locale) const { return GetConfigurationElement()->GetAttribute(attrName, locale); } QList ConfigurationElementHandle::GetAttributeNames() const { return GetConfigurationElement()->GetAttributeNames(); } QList ConfigurationElementHandle::GetChildren() const { ConfigurationElement::Pointer actualCe = GetConfigurationElement(); QList result; if (actualCe->NoExtraData()) { foreach(Handle::Pointer handle, objectManager->GetHandles(actualCe->GetRawChildren(), RegistryObjectManager::CONFIGURATION_ELEMENT)) { result.push_back(handle.Cast()); } return result; } foreach(Handle::Pointer handle, objectManager->GetHandles(actualCe->GetRawChildren(), RegistryObjectManager::THIRDLEVEL_CONFIGURATION_ELEMENT)) { result.push_back(handle.Cast()); } return result; } QObject* ConfigurationElementHandle::CreateExecutableExtension(const QString& propertyName) const { try { return GetConfigurationElement()->CreateExecutableExtension(propertyName); } catch (const InvalidRegistryObjectException& e) { Status::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, RegistryConstants::PLUGIN_ERROR, "Invalid registry object", e, BERRY_STATUS_LOC)); if (const RegistryObjectManager* regObjMgr = dynamic_cast(objectManager)) { regObjMgr->GetRegistry()->Log(status); } throw CoreException(status); } } QString ConfigurationElementHandle::GetAttributeAsIs(const QString& name) const { return GetConfigurationElement()->GetAttributeAsIs(name); } QList ConfigurationElementHandle::GetChildren(const QString& name) const { QList result; ConfigurationElement::Pointer actualCE = GetConfigurationElement(); QList children = objectManager->GetObjects(actualCE->GetRawChildren(), actualCE->NoExtraData() ? RegistryObjectManager::CONFIGURATION_ELEMENT : RegistryObjectManager::THIRDLEVEL_CONFIGURATION_ELEMENT); if (children.empty()) { return result; } for (int i = 0; i < children.size(); i++) { ConfigurationElement::Pointer ce = children[i].Cast(); if (ce->GetName() == name) { result.push_back(objectManager->GetHandle(ce->GetObjectId(), actualCE->NoExtraData() ? RegistryObjectManager::CONFIGURATION_ELEMENT : RegistryObjectManager::THIRDLEVEL_CONFIGURATION_ELEMENT).Cast()); } } return result; } SmartPointer ConfigurationElementHandle::GetDeclaringExtension() const { Object::ConstPointer result(this); while (!((result = result.Cast()->GetParent()).Cast())) { /*do nothing*/ } IExtension::Pointer extension(const_cast(result.Cast().GetPointer())); return extension; } QString ConfigurationElementHandle::GetName() const { return GetConfigurationElement()->GetName(); } SmartPointer ConfigurationElementHandle::GetParent() const { ConfigurationElement::Pointer actualCe = GetConfigurationElement(); return objectManager->GetHandle(actualCe->parentId, actualCe->parentType); } QString ConfigurationElementHandle::GetValue() const { return GetConfigurationElement()->GetValue(); } QString ConfigurationElementHandle::GetValue(const QLocale& locale) const { return GetConfigurationElement()->GetValue(locale); } QString ConfigurationElementHandle::GetValueAsIs() const { return GetConfigurationElement()->GetValueAsIs(); } SmartPointer ConfigurationElementHandle::GetObject() const { return GetConfigurationElement(); } QString ConfigurationElementHandle::GetNamespaceIdentifier() const { // namespace name is determined by the contributing extension return GetDeclaringExtension()->GetNamespaceIdentifier(); } SmartPointer ConfigurationElementHandle::GetContributor() const { return GetConfigurationElement()->GetContributor(); } bool ConfigurationElementHandle::IsValid() const { try { GetConfigurationElement(); } - catch (const InvalidRegistryObjectException& e) + catch (const InvalidRegistryObjectException& /*e*/) { return false; } return true; } SmartPointer ConfigurationElementHandle::GetConfigurationElement() const { return objectManager->GetObject(GetId(), RegistryObjectManager::CONFIGURATION_ELEMENT).Cast(); } bool ConfigurationElementHandle::ShouldPersist() const { return GetConfigurationElement()->ShouldPersist(); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtension.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtension.cpp index d7a5635817..265978b2bb 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtension.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtension.cpp @@ -1,143 +1,143 @@ /*=================================================================== 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 "berryExtension.h" #include "berryExtensionRegistry.h" #include "berryRegistryContributor.h" #include "berryRegistryObjectManager.h" namespace berry { const int Extension::LABEL = 0; //The human readable name of the extension const int Extension::XPT_NAME = 1; // The fully qualified name of the extension point to which this extension is attached to const int Extension::CONTRIBUTOR_ID = 2; // ID of the actual contributor of this extension const int Extension::EXTRA_SIZE = 3; QList Extension::GetExtraData() const { //The extension has been created by parsing, or does not have any extra data if (NoExtraData()) { return extraInformation; } // //The extension has been loaded from the cache. // if (extraInformation.empty()) // { // extraInformation = registry->GetTableReader()->LoadExtensionExtraData(GetExtraDataOffset()); // } return extraInformation; } Extension::Extension(ExtensionRegistry* registry, bool persist) : RegistryObject(registry, persist) { for (int i = 0; i < EXTRA_SIZE; ++i) extraInformation << QString(); } Extension::Extension(int self, const QString& simpleId, const QString& namespaze, const QList& children, int extraData, ExtensionRegistry* registry, bool persist) : RegistryObject(registry, persist), simpleId(simpleId), namespaceIdentifier(namespaze) { for (int i = 0; i < EXTRA_SIZE; ++i) extraInformation << QString(); SetObjectId(self); SetRawChildren(children); SetExtraDataOffset(extraData); } QString Extension::GetExtensionPointIdentifier() const { return GetExtraData()[XPT_NAME]; } QString Extension::GetSimpleIdentifier() const { return simpleId; } QString Extension::GetUniqueIdentifier() const { return simpleId.isEmpty() ? QString() : this->GetNamespaceIdentifier() + '.' + simpleId; } void Extension::SetExtensionPointIdentifier(const QString& value) { extraInformation[XPT_NAME] = value; } void Extension::SetSimpleIdentifier(const QString& value) { simpleId = value; } QString Extension::GetLabel() const { return GetExtraData()[LABEL]; } void Extension::SetLabel(const QString& value) { extraInformation[LABEL] = value; } QString Extension::GetContributorId() const { return GetExtraData()[CONTRIBUTOR_ID]; } void Extension::SetContributorId(const QString& value) { extraInformation[CONTRIBUTOR_ID] = value; } void Extension::SetNamespaceIdentifier(const QString& value) { namespaceIdentifier = value; } QString Extension::GetLabelAsIs() const { return GetExtraData()[LABEL]; } -QString Extension::GetLabel(const QLocale& locale) const +QString Extension::GetLabel(const QLocale& /*locale*/) const { registry->LogMultiLangError(); return GetLabel(); } SmartPointer Extension::GetContributor() const { return registry->GetObjectManager()->GetContributor(GetContributorId()); } QString Extension::GetNamespaceIdentifier() const { return namespaceIdentifier; } QString Extension::ToString() const { return GetUniqueIdentifier() + " -> " + GetExtensionPointIdentifier(); } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionDelta.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionDelta.cpp deleted file mode 100644 index 1eacdada75..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionDelta.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/*=================================================================== - -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 "berryExtensionDelta.h" - -#include "berryExtensionHandle.h" -#include "berryExtensionPointHandle.h" -#include "berryIObjectManager.h" -#include "berryRegistryDelta.h" - -namespace berry { - -class ExtensionDeltaData : public QSharedData -{ -public: - - ExtensionDeltaData() - : kind(ExtensionDelta::ADDED), extension(0), extensionPoint(0), containingDelta(NULL) - { - } - - QString GetKindString() const - { - switch (kind) - { - case ExtensionDelta::ADDED : - return "ADDED"; - case ExtensionDelta::REMOVED : - return "REMOVED"; - } - return "UNKNOWN"; - } - - ExtensionDelta::Kind kind; - int extension; - int extensionPoint; - RegistryDelta* containingDelta; -}; - -ExtensionDelta::ExtensionDelta() - : d(new ExtensionDeltaData) -{ -} - -ExtensionDelta::ExtensionDelta(const ExtensionDelta &other) - : d(other.d) -{ -} - -ExtensionDelta::~ExtensionDelta() -{ -} - -ExtensionDelta &ExtensionDelta::operator =(const ExtensionDelta &other) -{ - d = other.d; - return *this; -} - -bool ExtensionDelta::operator ==(const ExtensionDelta &other) const -{ - return d == other.d; -} - -uint ExtensionDelta::GetHashCode() const -{ - return qHash(d.constData()); -} - -void ExtensionDelta::SetContainingDelta(RegistryDelta* containingDelta) -{ - d->containingDelta = containingDelta; -} - -int ExtensionDelta::GetExtensionId() const -{ - return d->extension; -} - -int ExtensionDelta::GetExtensionPointId() const -{ - return d->extensionPoint; -} - -SmartPointer ExtensionDelta::GetExtensionPoint() const -{ - IExtensionPoint::Pointer xp(new ExtensionPointHandle(d->containingDelta->GetObjectManager(), - d->extensionPoint)); - return xp; -} - -void ExtensionDelta::SetExtensionPoint(int extensionPoint) -{ - d->extensionPoint = extensionPoint; -} - -ExtensionDelta::Kind ExtensionDelta::GetKind() const -{ - return d->kind; -} - -SmartPointer ExtensionDelta::GetExtension() const -{ - IExtension::Pointer ext(new ExtensionHandle(d->containingDelta->GetObjectManager(), - d->extension)); - return ext; -} - -void ExtensionDelta::SetExtension(int extension) -{ - d->extension = extension; -} - -void ExtensionDelta::SetKind(Kind kind) const -{ - d->kind = kind; -} - -QString ExtensionDelta::ToString() const -{ - return "\n\t\t" + GetExtensionPoint()->GetUniqueIdentifier() + " - " + - GetExtension()->GetNamespaceIdentifier() + '.' + GetExtension()->GetSimpleIdentifier() + - " (" + d->GetKindString() + ")"; -} - -} - -uint qHash(const berry::ExtensionDelta& delta) -{ - return delta.GetHashCode(); -} diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionDelta.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionDelta.h deleted file mode 100644 index 639761d59f..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionDelta.h +++ /dev/null @@ -1,111 +0,0 @@ -/*=================================================================== - -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 BERRYEXTENSIONDELTA_H -#define BERRYEXTENSIONDELTA_H - -#include - -namespace berry { - -template class SmartPointer; - -struct IExtension; -struct IExtensionPoint; - -class ExtensionDeltaData; -class RegistryDelta; - -class ExtensionDelta -{ - -public: - - enum Kind { - /** - * Delta kind constant indicating that an extension has been added to an - * extension point. - * @see ExtensionDelta#getKind() - */ - ADDED = 1, - - /** - * Delta kind constant indicating that an extension has been removed from an - * extension point. - * @see ExtensionDelta#getKind() - */ - REMOVED = 2 - }; - - ExtensionDelta(); - ExtensionDelta(const ExtensionDelta& other); - - ~ExtensionDelta(); - - ExtensionDelta& operator=(const ExtensionDelta& other); - - bool operator==(const ExtensionDelta& other) const; - - uint GetHashCode() const; - - void SetContainingDelta(RegistryDelta* containingDelta); - - int GetExtensionId() const; - - int GetExtensionPointId() const; - - /** - * Returns the affected extension point. - * - * @return the affected extension point - */ - SmartPointer GetExtensionPoint() const; - - void SetExtensionPoint(int extensionPoint); - - /** - * The kind of this extension delta. - * - * @return the kind of change this delta represents - * @see #ADDED - * @see #REMOVED - */ - Kind GetKind() const; - - /** - * Returns the affected extension. - * - * @return the affected extension - */ - SmartPointer GetExtension() const; - - void SetExtension(int extension); - - void SetKind(Kind kind) const; - - QString ToString() const; - -private: - - QExplicitlySharedDataPointer d; - -}; - -} - -uint qHash(const berry::ExtensionDelta& delta); - -#endif // BERRYEXTENSIONDELTA_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionHandle.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionHandle.cpp index 9106cb2299..193838a93a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionHandle.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionHandle.cpp @@ -1,121 +1,121 @@ /*=================================================================== 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 "berryExtensionHandle.h" #include "berryExtension.h" #include "berryIConfigurationElement.h" #include "berryIContributor.h" #include "berryRegistryObjectManager.h" #include "berryInvalidRegistryObjectException.h" namespace berry { ExtensionHandle::ExtensionHandle(const SmartPointer &objectManager, int id) : Handle(objectManager, id) { } ExtensionHandle::ExtensionHandle(const IObjectManager *objectManager, int id) : Handle(objectManager, id) { } QString ExtensionHandle::GetNamespaceIdentifier() const { return GetExtension()->GetNamespaceIdentifier(); } SmartPointer ExtensionHandle::GetContributor() const { return GetExtension()->GetContributor(); } QString ExtensionHandle::GetExtensionPointUniqueIdentifier() const { return GetExtension()->GetExtensionPointIdentifier(); } QString ExtensionHandle::GetLabel() const { return GetExtension()->GetLabel(); } QString ExtensionHandle::GetLabelAsIs() const { return GetExtension()->GetLabelAsIs(); } QString ExtensionHandle::GetLabel(const QLocale& locale) const { return GetExtension()->GetLabel(locale); } QString ExtensionHandle::GetSimpleIdentifier() const { return GetExtension()->GetSimpleIdentifier(); } QString ExtensionHandle::GetUniqueIdentifier() const { return GetExtension()->GetUniqueIdentifier(); } QList > ExtensionHandle::GetConfigurationElements() const { QList handles = objectManager->GetHandles(GetExtension()->GetRawChildren(), RegistryObjectManager::CONFIGURATION_ELEMENT); QList result; foreach (Handle::Pointer handle, handles) { result.push_back(handle.Cast()); } return result; } bool ExtensionHandle::IsValid() const { try { GetExtension(); } - catch (const InvalidRegistryObjectException& e) + catch (const InvalidRegistryObjectException& /*e*/) { return false; } return true; } SmartPointer ExtensionHandle::GetExtension() const { return objectManager->GetObject(GetId(), RegistryObjectManager::EXTENSION).Cast(); } bool ExtensionHandle::ShouldPersist() const { return GetExtension()->ShouldPersist(); } QString ExtensionHandle::GetContributorId() const { return GetExtension()->GetContributorId(); } SmartPointer ExtensionHandle::GetObject() const { return GetExtension(); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionPoint.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionPoint.cpp index f9b784dfdd..b11cda4ddc 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionPoint.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionPoint.cpp @@ -1,145 +1,145 @@ /*=================================================================== 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 "berryExtensionPoint.h" #include "berryExtensionRegistry.h" #include "berryRegistryContributor.h" #include "berryRegistryObjectManager.h" #include namespace berry { const int ExtensionPoint::LABEL = 0; //The human readable name for the extension point const int ExtensionPoint::SCHEMA = 1; //The schema of the extension point const int ExtensionPoint::QUALIFIED_NAME = 2; //The fully qualified name of the extension point const int ExtensionPoint::NAMESPACE = 3; //The name of the namespace of the extension point const int ExtensionPoint::CONTRIBUTOR_ID = 4; //The ID of the actual contributor of the extension point const int ExtensionPoint::EXTRA_SIZE = 5; QList ExtensionPoint::GetExtraData() const { //The extension point has been created by parsing, or does not have any extra data if (NoExtraData()) { //When this is true, the extraInformation is always a String[]. This happens when the object is created by the parser. return extraInformation; } // //The extension point has been loaded from the cache. // if (extraInformation.empty()) // { // extraInformation = registry->GetTableReader()->LoadExtensionPointExtraData(GetExtraDataOffset()); // } return extraInformation; } ExtensionPoint::ExtensionPoint(ExtensionRegistry* registry, bool persist) : RegistryObject(registry, persist) { for (int i = 0; i < EXTRA_SIZE; ++i) extraInformation << QString(); } ExtensionPoint::ExtensionPoint(int self, const QList& children, int dataOffset, ExtensionRegistry* registry, bool persist) : RegistryObject(registry, persist) { for (int i = 0; i < EXTRA_SIZE; ++i) extraInformation << QString(); SetObjectId(self); SetRawChildren(children); SetExtraDataOffset(dataOffset); } QString ExtensionPoint::GetSimpleIdentifier() const { return GetUniqueIdentifier().mid(GetUniqueIdentifier().lastIndexOf('.') + 1); } QString ExtensionPoint::GetSchemaReference() const { return QDir::fromNativeSeparators(GetExtraData()[SCHEMA]); } QString ExtensionPoint::GetLabel() const { return GetExtraData()[LABEL]; } QString ExtensionPoint::GetUniqueIdentifier() const { return GetExtraData()[QUALIFIED_NAME]; } QString ExtensionPoint::GetNamespace() const { return GetExtraData()[NAMESPACE]; } QString ExtensionPoint::GetContributorId() const { return GetExtraData()[CONTRIBUTOR_ID]; } void ExtensionPoint::SetSchema(const QString& value) { extraInformation[SCHEMA] = value; } void ExtensionPoint::SetLabel(const QString& value) { extraInformation[LABEL] = value; } void ExtensionPoint::SetUniqueIdentifier(const QString& value) { extraInformation[QUALIFIED_NAME] = value; } void ExtensionPoint::SetNamespace(const QString& value) { extraInformation[NAMESPACE] = value; } void ExtensionPoint::SetContributorId(const QString id) { extraInformation[CONTRIBUTOR_ID] = id; } QString ExtensionPoint::GetLabelAsIs() const { return GetExtraData()[LABEL]; } -QString ExtensionPoint::GetLabel(const QLocale& locale) +QString ExtensionPoint::GetLabel(const QLocale& /*locale*/) { registry->LogMultiLangError(); return GetLabel(); } SmartPointer ExtensionPoint::GetContributor() const { return registry->GetObjectManager()->GetContributor(GetContributorId()); } QString ExtensionPoint::ToString() const { return GetUniqueIdentifier(); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionPointHandle.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionPointHandle.cpp index bebf692a8f..0b8892987a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionPointHandle.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionPointHandle.cpp @@ -1,159 +1,159 @@ /*=================================================================== 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 "berryExtensionPointHandle.h" #include "berryIExtension.h" #include "berryExtension.h" #include "berryIObjectManager.h" #include "berryIConfigurationElement.h" #include "berryIContributor.h" #include "berryInvalidRegistryObjectException.h" #include "berryExtensionPoint.h" #include "berryRegistryObjectManager.h" namespace berry { ExtensionPointHandle::ExtensionPointHandle(const SmartPointer& objectManager, int id) : Handle(objectManager, id) { } ExtensionPointHandle::ExtensionPointHandle(const IObjectManager *objectManager, int id) : Handle(objectManager, id) { } QList > ExtensionPointHandle::GetExtensions() const { QList handles = objectManager->GetHandles(GetExtensionPoint()->GetRawChildren(), RegistryObjectManager::EXTENSION); QList result; foreach(Handle::Pointer handle, handles) { result.push_back(handle.Cast()); } return result; } QString ExtensionPointHandle::GetNamespaceIdentifier() const { return GetExtensionPoint()->GetNamespace(); } SmartPointer ExtensionPointHandle::GetContributor() const { return GetExtensionPoint()->GetContributor(); } SmartPointer ExtensionPointHandle::GetExtension(const QString& extensionId) const { if (extensionId.isEmpty()) return IExtension::Pointer(); QList children = GetExtensionPoint()->GetRawChildren(); for (int i = 0; i < children.size(); i++) { // Here we directly get the object because it avoids the creation of // garbage and because we'll need the object anyway to compare the value if (extensionId == objectManager->GetObject(children[i], RegistryObjectManager::EXTENSION).Cast()->GetUniqueIdentifier()) return objectManager->GetHandle(children[i], RegistryObjectManager::EXTENSION).Cast(); } return IExtension::Pointer(); } QList > ExtensionPointHandle::GetConfigurationElements() const { //get the actual extension objects since we'll need to get the configuration elements information. QList > tmpExtensions = objectManager->GetObjects(GetExtensionPoint()->GetRawChildren(), RegistryObjectManager::EXTENSION); if (tmpExtensions.empty()) return QList(); QList result; for (int i = 0; i < tmpExtensions.size(); ++i) { QList handles = objectManager->GetHandles(tmpExtensions[i]->GetRawChildren(), RegistryObjectManager::CONFIGURATION_ELEMENT); for (int j = 0; j < handles.size(); ++j) { result.push_back(handles[j].Cast()); } } return result; } QString ExtensionPointHandle::GetLabelAsIs() const { return GetExtensionPoint()->GetLabelAsIs(); } QString ExtensionPointHandle::GetLabel() const { return GetExtensionPoint()->GetLabel(); } QString ExtensionPointHandle::GetLabel(const QLocale& locale) const { return GetExtensionPoint()->GetLabel(locale); } QString ExtensionPointHandle::GetSchemaReference() const { return GetExtensionPoint()->GetSchemaReference(); } QString ExtensionPointHandle::GetSimpleIdentifier() const { return GetExtensionPoint()->GetSimpleIdentifier(); } QString ExtensionPointHandle::GetUniqueIdentifier() const { return GetExtensionPoint()->GetUniqueIdentifier(); } bool ExtensionPointHandle::IsValid() const { try { GetExtensionPoint(); } - catch (const InvalidRegistryObjectException& e) + catch (const InvalidRegistryObjectException& /*e*/) { return false; } return true; } bool ExtensionPointHandle::ShouldPersist() const { return GetExtensionPoint()->ShouldPersist(); } SmartPointer ExtensionPointHandle::GetObject() const { return GetExtensionPoint(); } SmartPointer ExtensionPointHandle::GetExtensionPoint() const { return objectManager->GetObject(GetId(), RegistryObjectManager::EXTENSION_POINT).Cast(); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.cpp index 5182bcd951..03ba36eaf7 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.cpp @@ -1,1338 +1,1338 @@ /*=================================================================== 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 "berryExtensionRegistry.h" #include "berryCombinedEventDelta.h" #include "berryConfigurationElement.h" #include "berryConfigurationElementAttribute.h" #include "berryConfigurationElementDescription.h" #include "berryExtension.h" #include "berryExtensionHandle.h" #include "berryExtensionPoint.h" #include "berryExtensionPointHandle.h" #include "berryExtensionsParser.h" #include "berryIConfigurationElement.h" #include "berryIExtension.h" #include "berryIExtensionPoint.h" #include "berryMultiStatus.h" #include "berryPlatform.h" #include "berryRegistryConstants.h" #include "berryRegistryContribution.h" #include "berryRegistryContributor.h" #include "berryRegistryMessages.h" #include "berryRegistryObjectFactory.h" #include "berryRegistryObjectManager.h" #include "berryRegistryProperties.h" #include "berryRegistryStrategy.h" #include "berryStatus.h" #include #include namespace berry { struct ExtensionRegistry::ListenerInfo { QString filter; IRegistryEventListener* listener; ListenerInfo(IRegistryEventListener* listener, const QString& filter) : filter(filter), listener(listener) { } /** * Used by ListenerList to ensure uniqueness. */ bool operator==(const ListenerInfo& another) const { return another.listener == this->listener; } }; void ExtensionRegistry::Add(const SmartPointer &element) { QWriteLocker l(&access); eventDelta = CombinedEventDelta::RecordAddition(); BasicAdd(element, true); FireRegistryChangeEvent(); eventDelta.Reset(); } QString ExtensionRegistry::AddExtension(int extension) { Extension::Pointer addedExtension = registryObjects->GetObject(extension, RegistryObjectManager::EXTENSION).Cast(); QString extensionPointToAddTo = addedExtension->GetExtensionPointIdentifier(); ExtensionPoint::Pointer extPoint = registryObjects->GetExtensionPointObject(extensionPointToAddTo); //orphan extension if (extPoint.IsNull()) { registryObjects->AddOrphan(extensionPointToAddTo, extension); return QString(); } // otherwise, link them QList newExtensions = extPoint->GetRawChildren(); newExtensions.push_back(extension); Link(extPoint, newExtensions); if (!eventDelta.IsNull()) eventDelta.RememberExtension(extPoint, extension); return extPoint->GetNamespace(); //return RecordChange(extPoint, extension, ExtensionDelta::ADDED); } QString ExtensionRegistry::AddExtensionPoint(int extPoint) { ExtensionPoint::Pointer extensionPoint = registryObjects->GetObject(extPoint, RegistryObjectManager::EXTENSION_POINT).Cast(); if (!eventDelta.IsNull()) eventDelta.RememberExtensionPoint(extensionPoint); QList orphans = registryObjects->RemoveOrphans(extensionPoint->GetUniqueIdentifier()); if (orphans.empty()) return QString(); Link(extensionPoint, orphans); if (!eventDelta.IsNull()) eventDelta.RememberExtensions(extensionPoint, orphans); return extensionPoint->GetNamespace(); //return RecordChange(extensionPoint, orphans, ExtensionDelta::ADDED); } QSet ExtensionRegistry::AddExtensionsAndExtensionPoints(const SmartPointer& element) { // now add and resolve extensions and extension points QSet affectedNamespaces; QList extPoints = element->GetExtensionPoints(); for (int i = 0; i < extPoints.size(); i++) { QString namespaze = this->AddExtensionPoint(extPoints[i]); if (!namespaze.isEmpty()) affectedNamespaces.insert(namespaze); } QList extensions = element->GetExtensions(); for (int i = 0; i < extensions.size(); i++) { QString namespaze = this->AddExtension(extensions[i]); if (!namespaze.isEmpty()) affectedNamespaces.insert(namespaze); } return affectedNamespaces; } void ExtensionRegistry::AddListenerInternal(IRegistryEventListener* listener, const QString& filter) { listeners.Add(ListenerInfo(listener, filter)); } void ExtensionRegistry::BasicAdd(const SmartPointer& element, bool link) { registryObjects->AddContribution(element); if (!link) return; AddExtensionsAndExtensionPoints(element); SetObjectManagers(registryObjects->CreateDelegatingObjectManager( registryObjects->GetAssociatedObjects(element->GetContributorId()))); } void ExtensionRegistry::SetObjectManagers(const SmartPointer& manager) { if (!eventDelta.IsNull()) eventDelta.SetObjectManager(manager); } void ExtensionRegistry::BasicRemove(const QString& contributorId) { // ignore anonymous namespaces RemoveExtensionsAndExtensionPoints(contributorId); QHash associatedObjects = registryObjects->GetAssociatedObjects(contributorId); registryObjects->RemoveObjects(associatedObjects); registryObjects->AddNavigableObjects(associatedObjects); // put the complete set of navigable objects SetObjectManagers(registryObjects->CreateDelegatingObjectManager(associatedObjects)); registryObjects->RemoveContribution(contributorId); registryObjects->RemoveContributor(contributorId); } void ExtensionRegistry::FireRegistryChangeEvent() { // if there is nothing to say, just bail out if (listeners.IsEmpty()) { return; } // for thread safety, create tmp collections QList tmpListeners = listeners.GetListeners(); // do the notification asynchronously //strategy->ScheduleChangeEvent(tmpListeners, tmpDeltas, this); this->ScheduleChangeEvent(tmpListeners, eventDelta); } //RegistryDelta ExtensionRegistry::GetDelta(const QString& namespaze) const //{ // // is there a delta for the plug-in? // RegistryDelta existingDelta = deltas.value(namespaze); // if (existingDelta != null) // return existingDelta; // //if not, create one // RegistryDelta delta = new RegistryDelta(); // deltas.put(namespace, delta); // return delta; //} void ExtensionRegistry::Link(const SmartPointer& extPoint, const QList& extensions) { extPoint->SetRawChildren(extensions); registryObjects->Add(extPoint, true); } //QString ExtensionRegistry::RecordChange(const SmartPointer& extPoint, int extension, int kind) //{ // // avoid computing deltas when there are no listeners // if (listeners.isEmpty()) // return QString(); // ExtensionDelta extensionDelta = new ExtensionDelta(); // extensionDelta.setExtension(extension); // extensionDelta.setExtensionPoint(extPoint.getObjectId()); // extensionDelta.setKind(kind); // getDelta(extPoint.getNamespace()).addExtensionDelta(extensionDelta); // return extPoint.getNamespace(); //} //QString ExtensionRegistry::RecordChange(const SmartPointer& extPoint, const QList& extensions, int kind) //{ // if (listeners.isEmpty()) // return null; // QString namespace = extPoint.getNamespace(); // if (extensions == null || extensions.length == 0) // return namespace; // RegistryDelta pluginDelta = getDelta(extPoint.getNamespace()); // for (int i = 0; i < extensions.length; i++) { // ExtensionDelta extensionDelta = new ExtensionDelta(); // extensionDelta.setExtension(extensions[i]); // extensionDelta.setExtensionPoint(extPoint.getObjectId()); // extensionDelta.setKind(kind); // pluginDelta.addExtensionDelta(extensionDelta); // } // return namespace; //} QString ExtensionRegistry::RemoveExtension(int extensionId) { Extension::Pointer extension = registryObjects->GetObject(extensionId, RegistryObjectManager::EXTENSION).Cast(); registryObjects->RemoveExtensionFromNamespaceIndex(extensionId, extension->GetNamespaceIdentifier()); QString xptName = extension->GetExtensionPointIdentifier(); ExtensionPoint::Pointer extPoint = registryObjects->GetExtensionPointObject(xptName); if (extPoint.IsNull()) { registryObjects->RemoveOrphan(xptName, extensionId); return QString(); } // otherwise, unlink the extension from the extension point QList existingExtensions = extPoint->GetRawChildren(); QList newExtensions; if (existingExtensions.size() > 1) { for (int i = 0; i < existingExtensions.size(); ++i) if (existingExtensions[i] != extension->GetObjectId()) newExtensions.push_back(existingExtensions[i]); } Link(extPoint, newExtensions); if (!eventDelta.IsNull()) eventDelta.RememberExtension(extPoint, extensionId); return extPoint->GetNamespace(); //return recordChange(extPoint, extension.getObjectId(), IExtensionDelta.REMOVED); } QString ExtensionRegistry::RemoveExtensionPoint(int extPoint) { ExtensionPoint::Pointer extensionPoint = registryObjects->GetObject( extPoint, RegistryObjectManager::EXTENSION_POINT).Cast(); registryObjects->RemoveExtensionPointFromNamespaceIndex(extPoint, extensionPoint->GetNamespace()); QList existingExtensions = extensionPoint->GetRawChildren(); if (!existingExtensions.empty()) { registryObjects->AddOrphans(extensionPoint->GetUniqueIdentifier(), existingExtensions); Link(extensionPoint, QList()); } if (!eventDelta.IsNull()) { eventDelta.RememberExtensionPoint(extensionPoint); eventDelta.RememberExtensions(extensionPoint, existingExtensions); } return extensionPoint->GetNamespace(); //return recordChange(extensionPoint, existingExtensions, IExtensionDelta.REMOVED); } QSet ExtensionRegistry::RemoveExtensionsAndExtensionPoints(const QString& contributorId) { QSet affectedNamespaces; QList extensions = registryObjects->GetExtensionsFrom(contributorId); for (int i = 0; i < extensions.size(); i++) { QString namespaze = this->RemoveExtension(extensions[i]); if (!namespaze.isEmpty()) affectedNamespaces.insert(namespaze); } // remove extension points QList extPoints = registryObjects->GetExtensionPointsFrom(contributorId); for (int i = 0; i < extPoints.size(); i++) { QString namespaze = this->RemoveExtensionPoint(extPoints[i]); if (!namespaze.isEmpty()) affectedNamespaces.insert(namespaze); } return affectedNamespaces; } struct ExtensionRegistry::QueueElement { QList listenerInfos; CombinedEventDelta scheduledDelta; QueueElement() { } QueueElement(const QList& infos, const CombinedEventDelta& delta) : listenerInfos(infos), scheduledDelta(delta) { } }; class ExtensionRegistry::RegistryEventThread : public QThread { private: QAtomicInt stop; ExtensionRegistry* registry; Queue& queue; public: RegistryEventThread(ExtensionRegistry* registry, Queue& queue) : stop(0), registry(registry), queue(queue) { this->setObjectName("Extension Registry Event Dispatcher"); } void interrupt() { stop.fetchAndStoreOrdered(1); } void run() { while (!stop.fetchAndAddOrdered(0)) { QueueElement element; { Queue::Locker l(&queue); while (queue.empty()) queue.wait(); element = queue.takeFirst(); } registry->ProcessChangeEvent(element.listenerInfos, element.scheduledDelta); } } }; bool ExtensionRegistry::CheckReadWriteAccess(QObject* key, bool persist) const { if (masterToken == key) return true; if (userToken == key && !persist) return true; return false; } void ExtensionRegistry::LogError(const QString& owner, const QString& contributionName, const ctkException& e) { QString message = QString("Could not parse XML contribution for \"%1\". Any contributed extensions " "and extension points will be ignored.").arg(QString(owner) + "/" + contributionName); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, 0, message, e, BERRY_STATUS_LOC)); Log(status); } void ExtensionRegistry::CreateExtensionData(const QString& contributorId, const ConfigurationElementDescription& description, const SmartPointer& parent, bool persist) { ConfigurationElement::Pointer currentConfigurationElement = GetElementFactory()->CreateConfigurationElement(persist); currentConfigurationElement->SetContributorId(contributorId); currentConfigurationElement->SetName(description.GetName()); QList descriptionProperties = description.GetAttributes(); QList properties; if (!descriptionProperties.empty()) { for (int i = 0; i < descriptionProperties.size(); i++) { properties.push_back(descriptionProperties[i].GetName()); properties.push_back(Translate(descriptionProperties[i].GetValue(), NULL)); } } currentConfigurationElement->SetProperties(properties); QString value = description.GetValue(); if (!value.isEmpty()) currentConfigurationElement->SetValue(value); GetObjectManager()->Add(currentConfigurationElement, true); // process children QList children = description.GetChildren(); if (!children.empty()) { for (int i = 0; i < children.size(); i++) { CreateExtensionData(contributorId, children[i], currentConfigurationElement, persist); } } QList newValues = parent->GetRawChildren(); newValues.push_back(currentConfigurationElement->GetObjectId()); parent->SetRawChildren(newValues); currentConfigurationElement->SetParentId(parent->GetObjectId()); currentConfigurationElement->SetParentType(parent.Cast() ? RegistryObjectManager::CONFIGURATION_ELEMENT : RegistryObjectManager::EXTENSION); } bool ExtensionRegistry::RemoveObject(const SmartPointer& registryObject, bool isExtensionPoint, QObject* token) { if (!CheckReadWriteAccess(token, registryObject->ShouldPersist())) throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry.removeExtension() method. Check if proper access token is supplied."); int id = registryObject->GetObjectId(); QWriteLocker l(&access); eventDelta = CombinedEventDelta::RecordRemoval(); if (isExtensionPoint) { RemoveExtensionPoint(id); } else { RemoveExtension(id); } QHash removed; removed.insert(id, registryObject); // There is some asymmetry between extension and extension point removal. Removing extension point makes // extensions "orphans" but does not remove them. As a result, only extensions needs to be processed. if (!isExtensionPoint) { registryObjects->AddAssociatedObjects(removed, registryObject); } registryObjects->RemoveObjects(removed); registryObjects->AddNavigableObjects(removed); IObjectManager::Pointer manager = registryObjects->CreateDelegatingObjectManager(removed); //GetDelta(namespaze)->SetObjectManager(manager); //eventDelta->SetObjectManager(manager); registryObjects->UnlinkChildFromContributions(id); FireRegistryChangeEvent(); eventDelta.Reset(); return true; } -void ExtensionRegistry::SetFileManager(const QString& cacheBase, bool isCacheReadOnly) +void ExtensionRegistry::SetFileManager(const QString& /*cacheBase*/, bool /*isCacheReadOnly*/) { // if (cacheStorageManager != NULL) // cacheStorageManager->Close(); // close existing file manager first // if (cacheBase != null) { // cacheStorageManager = new StorageManager(cacheBase, isCacheReadOnly ? "none" : null, isCacheReadOnly); //$NON-NLS-1$ // try { // cacheStorageManager.open(!isCacheReadOnly); // } catch (IOException e) { // // Ignore the exception. The registry will be rebuilt from source. // } // } } void ExtensionRegistry::EnterRead() { access.lockForRead(); } void ExtensionRegistry::ExitRead() { access.unlock(); } void ExtensionRegistry::SetElementFactory() { if (isMultiLanguage) { throw ctkRuntimeException("Multi-language registry not supported yet."); //theRegistryObjectFactory = new RegistryObjectFactoryMulti(this); } else { theRegistryObjectFactory.reset(new RegistryObjectFactory(this)); } } //TableReader ExtensionRegistry::getTableReader() const //{ // return theTableReader; //} bool ExtensionRegistry::CheckCache() { // for (int index = 0; index < strategy.getLocationsLength(); index++) { // File possibleCacheLocation = strategy.getStorage(index); // if (possibleCacheLocation == null) // break; // bail out on the first null // setFileManager(possibleCacheLocation, strategy.isCacheReadOnly(index)); // if (cacheStorageManager != null) { // // check this new location: // File cacheFile = null; // try { // cacheFile = cacheStorageManager.lookup(TableReader.getTestFileName(), false); // } catch (IOException e) { // //Ignore the exception. The registry will be rebuilt from the xml files. // } // if (cacheFile != null && cacheFile.isFile()) // return true; // found the appropriate location // } // } return false; } void ExtensionRegistry::StopChangeEventScheduler() { if (!eventThread.isNull()) { Queue::Locker l(&queue); eventThread->interrupt(); eventThread->wait(); eventThread.reset(); } } SmartPointer ExtensionRegistry::GetObjectManager() const { return registryObjects; } void ExtensionRegistry::AddListener(IRegistryEventListener* listener, const QString& extensionPointId) { AddListenerInternal(listener, extensionPointId); } QList > ExtensionRegistry::GetConfigurationElementsFor(const QString& extensionPointId) const { // this is just a convenience API - no need to do any sync'ing here int lastdot = extensionPointId.lastIndexOf('.'); if (lastdot == -1) { QList(); } return GetConfigurationElementsFor(extensionPointId.left(lastdot), extensionPointId.mid(lastdot + 1)); } QList > ExtensionRegistry::GetConfigurationElementsFor(const QString& pluginId, const QString& extensionPointSimpleId) const { // this is just a convenience API - no need to do any sync'ing here IExtensionPoint::Pointer extPoint = this->GetExtensionPoint(pluginId, extensionPointSimpleId); if (extPoint.IsNull()) return QList(); return extPoint->GetConfigurationElements(); } QList > ExtensionRegistry::GetConfigurationElementsFor(const QString& pluginId, const QString& extensionPointName, const QString& extensionId) const { // this is just a convenience API - no need to do any sync'ing here IExtension::Pointer extension = this->GetExtension(pluginId, extensionPointName, extensionId); if (extension.IsNull()) return QList(); return extension->GetConfigurationElements(); } SmartPointer ExtensionRegistry::GetExtension(const QString& extensionId) const { if (extensionId.isEmpty()) return IExtension::Pointer(); int lastdot = extensionId.lastIndexOf('.'); if (lastdot == -1) return IExtension::Pointer(); QString namespaze = extensionId.left(lastdot); QList extensions; { QReadLocker l(&access); extensions = registryObjects->GetExtensionsFromNamespace(namespaze); } for (int i = 0; i < extensions.size(); i++) { ExtensionHandle::Pointer suspect = extensions[i]; if (extensionId == suspect->GetUniqueIdentifier()) return suspect; } return IExtension::Pointer(); } SmartPointer ExtensionRegistry::GetExtension(const QString& extensionPointId, const QString& extensionId) const { // this is just a convenience API - no need to do any sync'ing here int lastdot = extensionPointId.lastIndexOf('.'); if (lastdot == -1) return IExtension::Pointer(); return GetExtension(extensionPointId.left(lastdot), extensionPointId.mid(lastdot + 1), extensionId); } SmartPointer ExtensionRegistry::GetExtension(const QString& pluginId, const QString& extensionPointName, const QString& extensionId) const { // this is just a convenience API - no need to do any sync'ing here IExtensionPoint::Pointer extPoint = GetExtensionPoint(pluginId, extensionPointName); if (extPoint.IsNotNull()) return extPoint->GetExtension(extensionId); return IExtension::Pointer(); } SmartPointer ExtensionRegistry::GetExtensionPoint(const QString& xptUniqueId) const { QReadLocker l(&access); return registryObjects->GetExtensionPointHandle(xptUniqueId); } SmartPointer ExtensionRegistry::GetExtensionPoint(const QString& elementName, const QString& xpt) const { QReadLocker l(&access); return registryObjects->GetExtensionPointHandle(elementName + '.' + xpt); } QList > ExtensionRegistry::GetExtensionPoints() const { QList handles; { QReadLocker l(&access); handles = registryObjects->GetExtensionPointsHandles(); } QList result; foreach(ExtensionPointHandle::Pointer handle, handles) { result.push_back(handle); } return result; } QList > ExtensionRegistry::GetExtensionPoints(const QString& namespaceName) const { QList handles; { QReadLocker l(&access); handles = registryObjects->GetExtensionPointsFromNamespace(namespaceName); } QList result; foreach(ExtensionPointHandle::Pointer handle, handles) { result.push_back(handle); } return result; } QList > ExtensionRegistry::GetExtensions(const QString& namespaceName) const { QList handles; { QReadLocker l(&access); handles = registryObjects->GetExtensionsFromNamespace(namespaceName); } QList result; foreach (ExtensionHandle::Pointer handle, handles) { result.push_back(handle); } return result; } QList > ExtensionRegistry::GetExtensions(const SmartPointer& contributor) const { RegistryContributor::Pointer regContributor = contributor.Cast(); if (regContributor.IsNull()) throw ctkInvalidArgumentException("Contributor must be a RegistryContributor."); // should never happen QString contributorId = regContributor->GetActualId(); QList handles; { QReadLocker l(&access); handles = registryObjects->GetExtensionsFromContributor(contributorId); } QList result; foreach (ExtensionHandle::Pointer handle, handles) { result.push_back(handle); } return result; } QList > ExtensionRegistry::GetExtensionPoints(const SmartPointer& contributor) const { RegistryContributor::Pointer regContributor = contributor.Cast(); if (regContributor.IsNull()) throw ctkInvalidArgumentException("Contributor must be a RegistryContributor."); // should never happen QString contributorId = regContributor->GetActualId(); QList handles; { QReadLocker l(&access); handles = registryObjects->GetExtensionPointsFromContributor(contributorId); } QList result; foreach (ExtensionPointHandle::Pointer handle, handles) { result.push_back(handle); } return result; } QList ExtensionRegistry::GetNamespaces() const { QReadLocker l(&access); QList namespaceElements = registryObjects->GetNamespacesIndex().Elements(); QList namespaceNames; for (int i = 0; i < namespaceElements.size(); i++) { namespaceNames.push_back(namespaceElements[i]->GetKey()); } return namespaceNames; } bool ExtensionRegistry::HasContributor(const SmartPointer& contributor) const { RegistryContributor::Pointer regContributor = contributor.Cast(); if (regContributor.IsNull()) throw ctkInvalidArgumentException("Contributor must be a RegistryContributor."); // should never happen QString contributorId = regContributor->GetActualId(); return HasContributor(contributorId); } bool ExtensionRegistry::HasContributor(const QString& contributorId) const { QReadLocker l(&access); return registryObjects->HasContribution(contributorId); } void ExtensionRegistry::Remove(const QString& removedContributorId, long timestamp) { Remove(removedContributorId); if (timestamp != 0) aggregatedTimestamp.Remove(timestamp); } void ExtensionRegistry::RemoveContributor(const SmartPointer& contributor, QObject* key) { RegistryContributor::Pointer regContributor = contributor.Cast(); if (regContributor.IsNull()) throw ctkInvalidArgumentException("Contributor must be a RegistryContributor."); // should never happen if (!CheckReadWriteAccess(key, true)) throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry.removeContributor() method. Check if proper access token is supplied."); QString contributorId = regContributor->GetActualId(); Remove(contributorId); } void ExtensionRegistry::Remove(const QString& removedContributorId) { QWriteLocker l(&access); eventDelta = CombinedEventDelta::RecordRemoval(); BasicRemove(removedContributorId); FireRegistryChangeEvent(); eventDelta.Reset(); } void ExtensionRegistry::RemoveListener(IRegistryEventListener* listener) { listeners.Remove(ListenerInfo(listener, QString())); } ExtensionRegistry::ExtensionRegistry(RegistryStrategy* registryStrategy, QObject* masterToken, QObject* userToken) : registryObjects(NULL), isMultiLanguage(false), mlErrorLogged(false), eventThread(NULL) { isMultiLanguage = RegistryProperties::GetProperty(RegistryConstants::PROP_MULTI_LANGUAGE) == "true"; if (registryStrategy != NULL) strategy.reset(registryStrategy); else strategy.reset(new RegistryStrategy(QList(), QList(), NULL)); this->masterToken = masterToken; this->userToken = userToken; registryObjects = new RegistryObjectManager(this); bool isRegistryFilledFromCache = false; // indicates if registry was able to use cache to populate it's content if (strategy->CacheUse()) { // Try to read the registry from the cache first. If that fails, create a new registry QTime timer; if (Debug()) timer.start(); //The cache is made of several files, find the real names of these other files. If all files are found, try to initialize the objectManager if (CheckCache()) { // TODO Registry Cache // try { // theTableReader.setTableFile(cacheStorageManager.lookup(TableReader.TABLE, false)); // theTableReader.setExtraDataFile(cacheStorageManager.lookup(TableReader.EXTRA, false)); // theTableReader.setMainDataFile(cacheStorageManager.lookup(TableReader.MAIN, false)); // theTableReader.setContributionsFile(cacheStorageManager.lookup(TableReader.CONTRIBUTIONS, false)); // theTableReader.setContributorsFile(cacheStorageManager.lookup(TableReader.CONTRIBUTORS, false)); // theTableReader.setNamespacesFile(cacheStorageManager.lookup(TableReader.NAMESPACES, false)); // theTableReader.setOrphansFile(cacheStorageManager.lookup(TableReader.ORPHANS, false)); // long timestamp = strategy.getContributionsTimestamp(); // isRegistryFilledFromCache = registryObjects.init(timestamp); // if (isRegistryFilledFromCache) // aggregatedTimestamp.set(timestamp); // } catch (IOException e) { // // The registry will be rebuilt from the xml files. Make sure to clear anything filled // // from cache so that we won't have partially filled items. // isRegistryFilledFromCache = false; // clearRegistryCache(); // log(new Status(IStatus.ERROR, RegistryMessages.OWNER_NAME, 0, RegistryMessages.registry_bad_cache, e)); // } } // if (!isRegistryFilledFromCache) // { // // set cache storage manager to a first writable location // for (int index = 0; index < strategy.getLocationsLength(); index++) { // if (!strategy.isCacheReadOnly(index)) { // setFileManager(strategy.getStorage(index), false); // break; // } // } // } if (Debug() && isRegistryFilledFromCache) BERRY_INFO << "Reading registry cache: " << timer.elapsed() << "ms"; if (Debug()) { if (!isRegistryFilledFromCache) BERRY_INFO << "Reloading registry from manifest files..."; else BERRY_INFO << "Using registry cache..."; } } if (DebugEvents()) { struct DebugRegistryListener : public IRegistryEventListener { void Added(const QList& extensions) { BERRY_INFO << "Registry extensions ADDED:"; foreach(IExtension::Pointer extension, extensions) { BERRY_INFO << "\t" << extension->GetExtensionPointUniqueIdentifier() << " - " << extension->GetNamespaceIdentifier() << "." << extension->GetSimpleIdentifier(); } } void Removed(const QList& extensions) { BERRY_INFO << "Registry extensions REMOVED:"; foreach(IExtension::Pointer extension, extensions) { BERRY_INFO << "\t" << extension->GetExtensionPointUniqueIdentifier() << " - " << extension->GetNamespaceIdentifier() << "." << extension->GetSimpleIdentifier(); } } void Added(const QList& extensionPoints) { BERRY_INFO << "Registry extension-points ADDED:"; foreach(IExtensionPoint::Pointer extensionPoint, extensionPoints) { BERRY_INFO << "\t" << extensionPoint->GetUniqueIdentifier(); } } void Removed(const QList& extensionPoints) { BERRY_INFO << "Registry extension-points REMOVED:"; foreach(IExtensionPoint::Pointer extensionPoint, extensionPoints) { BERRY_INFO << "\t" << extensionPoint->GetUniqueIdentifier(); } } }; debugRegistryListener.reset(new DebugRegistryListener()); AddListener(debugRegistryListener.data()); } // Do extra start processing if specified in the registry strategy strategy->OnStart(this, isRegistryFilledFromCache); } ExtensionRegistry::~ExtensionRegistry() { } -void ExtensionRegistry::Stop(QObject* key) +void ExtensionRegistry::Stop(QObject* /*key*/) { // If the registry creator specified a key token, check that the key mathches it // (it is assumed that registry owner keeps the key to prevent unautorized accesss). if (masterToken != NULL && masterToken != NULL) { throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry.stop() method. Check if proper access token is supplied."); //$NON-NLS-1$ } // Do extra stop processing if specified in the registry strategy strategy->OnStop(this); StopChangeEventScheduler(); // if (cacheStorageManager == NULL) // return; // if (!registryObjects.isDirty() || cacheStorageManager.isReadOnly()) { // cacheStorageManager.close(); // theTableReader.close(); // return; // } // File tableFile = null; // File mainFile = null; // File extraFile = null; // File contributionsFile = null; // File contributorsFile = null; // File namespacesFile = null; // File orphansFile = null; // TableWriter theTableWriter = new TableWriter(this); // try { // cacheStorageManager.lookup(TableReader.TABLE, true); // cacheStorageManager.lookup(TableReader.MAIN, true); // cacheStorageManager.lookup(TableReader.EXTRA, true); // cacheStorageManager.lookup(TableReader.CONTRIBUTIONS, true); // cacheStorageManager.lookup(TableReader.CONTRIBUTORS, true); // cacheStorageManager.lookup(TableReader.NAMESPACES, true); // cacheStorageManager.lookup(TableReader.ORPHANS, true); // tableFile = File.createTempFile(TableReader.TABLE, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$ // mainFile = File.createTempFile(TableReader.MAIN, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$ // extraFile = File.createTempFile(TableReader.EXTRA, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$ // contributionsFile = File.createTempFile(TableReader.CONTRIBUTIONS, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$ // contributorsFile = File.createTempFile(TableReader.CONTRIBUTORS, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$ // namespacesFile = File.createTempFile(TableReader.NAMESPACES, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$ // orphansFile = File.createTempFile(TableReader.ORPHANS, ".new", cacheStorageManager.getBase()); //$NON-NLS-1$ // theTableWriter.setTableFile(tableFile); // theTableWriter.setExtraDataFile(extraFile); // theTableWriter.setMainDataFile(mainFile); // theTableWriter.setContributionsFile(contributionsFile); // theTableWriter.setContributorsFile(contributorsFile); // theTableWriter.setNamespacesFile(namespacesFile); // theTableWriter.setOrphansFile(orphansFile); // } catch (IOException e) { // cacheStorageManager.close(); // return; //Ignore the exception since we can recompute the cache // } // try { // long timestamp; // // A bit of backward compatibility: if registry was modified, but timestamp was not, // // it means that the new timestamp tracking mechanism was not used. In this case // // explicitly obtain timestamps for all contributions. Note that this logic // // maintains a problem described in the bug 104267 for contributions that // // don't use the timestamp tracking mechanism. // if (aggregatedTimestamp.isModifed()) // timestamp = aggregatedTimestamp.getContentsTimestamp(); // use timestamp tracking // else // timestamp = strategy.getContributionsTimestamp(); // use legacy approach // if (theTableWriter.saveCache(registryObjects, timestamp)) // cacheStorageManager.update(new QString[] {TableReader.TABLE, TableReader.MAIN, TableReader.EXTRA, TableReader.CONTRIBUTIONS, TableReader.CONTRIBUTORS, TableReader.NAMESPACES, TableReader.ORPHANS}, new QString[] {tableFile.getName(), mainFile.getName(), extraFile.getName(), contributionsFile.getName(), contributorsFile.getName(), namespacesFile.getName(), orphansFile.getName()}); // } catch (IOException e) { // //Ignore the exception since we can recompute the cache // } // theTableReader.close(); // cacheStorageManager.close(); } void ExtensionRegistry::ClearRegistryCache() { // QString[] keys = new QString[] {TableReader.TABLE, TableReader.MAIN, TableReader.EXTRA, TableReader.CONTRIBUTIONS, TableReader.ORPHANS}; // for (int i = 0; i < keys.length; i++) // try { // cacheStorageManager.remove(keys[i]); // } catch (IOException e) { // log(new Status(IStatus.ERROR, RegistryMessages.OWNER_NAME, IStatus.ERROR, RegistryMessages.meta_registryCacheReadProblems, e)); // } aggregatedTimestamp.Reset(); } RegistryObjectFactory* ExtensionRegistry::GetElementFactory() { if (theRegistryObjectFactory.isNull()) SetElementFactory(); return theRegistryObjectFactory.data(); } void ExtensionRegistry::Log(const SmartPointer& status) const { strategy->Log(status); } QString ExtensionRegistry::Translate(const QString& key, QTranslator* resources) const { if (isMultiLanguage) return key; return strategy->Translate(key, resources); } bool ExtensionRegistry::Debug() const { return strategy->Debug(); } bool ExtensionRegistry::DebugEvents() const { return strategy->DebugRegistryEvents(); } bool ExtensionRegistry::UseLazyCacheLoading() const { return strategy->CacheLazyLoading(); } long ExtensionRegistry::ComputeState() const { return strategy->GetContainerTimestamp(); } QObject* ExtensionRegistry::CreateExecutableExtension(const SmartPointer& defaultContributor, const QString& className, const QString& requestedContributorName) { return strategy->CreateExecutableExtension(defaultContributor, className, requestedContributorName); } void ExtensionRegistry::ProcessChangeEvent( const QList& listenerInfos, const CombinedEventDelta& scheduledDelta) { for (int i = 0; i < listenerInfos.size(); i++) { const ListenerInfo& listenerInfo = listenerInfos[i]; IRegistryEventListener* extensionListener = listenerInfo.listener; QList extensions = scheduledDelta.GetExtensions(listenerInfo.filter); QList extensionPoints = scheduledDelta.GetExtensionPoints(listenerInfo.filter); // notification order - on addition: extension points; then extensions if (scheduledDelta.IsAddition()) { if (!extensionPoints.empty()) extensionListener->Added(extensionPoints); if (!extensions.empty()) extensionListener->Added(extensions); } else { // on removal: extensions; then extension points if (!extensions.empty()) extensionListener->Removed(extensions); if (!extensionPoints.empty()) extensionListener->Removed(extensionPoints); } } IObjectManager::Pointer manager = scheduledDelta.GetObjectManager(); if (manager.IsNotNull()) manager->Close(); } void ExtensionRegistry::ScheduleChangeEvent(const QList& listenerInfos, const CombinedEventDelta& scheduledDelta) { QueueElement newElement(listenerInfos, scheduledDelta); if (eventThread.isNull()) { eventThread.reset(new RegistryEventThread(this, queue)); eventThread->start(); } { Queue::Locker l(&queue); queue.push_back(newElement); queue.notify(); } } bool ExtensionRegistry::AddContribution(QIODevice* is, const SmartPointer& contributor, bool persist, const QString& contributionName, QTranslator* translationBundle, QObject* key, long timestamp) { bool result = AddContribution(is, contributor, persist, contributionName, translationBundle, key); if (timestamp != 0) aggregatedTimestamp.Add(timestamp); return result; } bool ExtensionRegistry::AddContribution(QIODevice* is, const SmartPointer& contributor, bool persist, const QString& contributionName, QTranslator* translationBundle, QObject* key) { if (!CheckReadWriteAccess(key, persist)) throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry::AddContribution() method. Check if proper access token is supplied."); RegistryContributor::Pointer internalContributor = contributor.Cast(); registryObjects->AddContributor(internalContributor); // only adds a contributor if it is not already present QString ownerName = internalContributor->GetActualName(); QString message = QString("Problems parsing plug-in manifest for: \"%1\".").arg(ownerName); MultiStatus::Pointer problems(new MultiStatus(RegistryMessages::OWNER_NAME, ExtensionsParser::PARSE_PROBLEM, message, BERRY_STATUS_LOC)); ExtensionsParser parser(problems, this); RegistryContribution::Pointer contribution = GetElementFactory()->CreateContribution(internalContributor->GetActualId(), persist); try { QXmlInputSource xmlInput(is); bool success = parser.parseManifest(strategy->GetXMLParser(), &xmlInput, contributionName, GetObjectManager().GetPointer(), contribution, translationBundle); int status = problems->GetSeverity(); if (status != IStatus::OK_TYPE || !success) { Log(problems); if (status == IStatus::ERROR_TYPE || status == IStatus::CANCEL_TYPE || !success) return false; } } catch (const ctkException& e) { LogError(ownerName, contributionName, e); return false; } Add(contribution); // the add() method does synchronization return true; } bool ExtensionRegistry::AddExtensionPoint(const QString& identifier, const SmartPointer& contributor, bool persist, const QString& label, const QString& schemaReference, QObject* token) { if (!CheckReadWriteAccess(token, persist)) throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry::AddExtensionPoint() method. Check if proper access token is supplied."); RegistryContributor::Pointer internalContributor = contributor.Cast(); registryObjects->AddContributor(internalContributor); // only adds a contributor if it is not already present QString contributorId = internalContributor->GetActualId(); // Extension point Id might not be null if (identifier.isEmpty()) { QString message = QString("Missing ID for the extension point \"%1\". Element ignored.").arg(label); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, 0, message, BERRY_STATUS_LOC)); Log(status); } // addition wraps in a contribution RegistryContribution::Pointer contribution = GetElementFactory()->CreateContribution(contributorId, persist); ExtensionPoint::Pointer currentExtPoint = GetElementFactory()->CreateExtensionPoint(persist); QString uniqueId; QString namespaceName; int simpleIdStart = identifier.lastIndexOf('.'); if (simpleIdStart == -1) { namespaceName = contribution->GetDefaultNamespace(); uniqueId = namespaceName + '.' + identifier; } else { namespaceName = identifier.left(simpleIdStart); uniqueId = identifier; } currentExtPoint->SetUniqueIdentifier(uniqueId); currentExtPoint->SetNamespace(namespaceName); QString labelNLS = Translate(label, NULL); currentExtPoint->SetLabel(labelNLS); currentExtPoint->SetSchema(schemaReference); if (!GetObjectManager()->AddExtensionPoint(currentExtPoint, true)) { if (Debug()) { QString msg = QString("Ignored duplicate extension point \"%1\" supplied by \"%2\".").arg(uniqueId).arg(contribution->GetDefaultNamespace()); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, 0, msg, BERRY_STATUS_LOC)); Log(status); } return false; } currentExtPoint->SetContributorId(contributorId); // array format: {Number of extension points, Number of extensions, Extension Id} QList contributionChildren; // Put the extension points into this namespace contributionChildren.push_back(1); contributionChildren.push_back(0); contributionChildren.push_back(currentExtPoint->GetObjectId()); contribution->SetRawChildren(contributionChildren); Add(contribution); return true; } bool ExtensionRegistry::AddExtension(const QString& identifier, const SmartPointer& contributor, bool persist, const QString& label, const QString& extensionPointId, const ConfigurationElementDescription& configurationElements, QObject* token) { if (!CheckReadWriteAccess(token, persist)) throw ctkInvalidArgumentException("Unauthorized access to the ExtensionRegistry::AddExtensionPoint() method. Check if proper access token is supplied."); // prepare namespace information RegistryContributor::Pointer internalContributor = contributor.Cast(); registryObjects->AddContributor(internalContributor); // only adds a contributor if it is not already present QString contributorId = internalContributor->GetActualId(); // addition wraps in a contribution RegistryContribution::Pointer contribution = GetElementFactory()->CreateContribution(contributorId, persist); Extension::Pointer currentExtension = GetElementFactory()->CreateExtension(persist); QString simpleId; QString namespaceName; int simpleIdStart = identifier.lastIndexOf('.'); if (simpleIdStart != -1) { simpleId = identifier.mid(simpleIdStart + 1); namespaceName = identifier.left(simpleIdStart); } else { simpleId = identifier; namespaceName = contribution->GetDefaultNamespace(); } currentExtension->SetSimpleIdentifier(simpleId); currentExtension->SetNamespaceIdentifier(namespaceName); QString extensionLabelNLS = Translate(label, NULL); currentExtension->SetLabel(extensionLabelNLS); QString targetExtensionPointId; if (extensionPointId.indexOf('.') == -1) // No dots -> namespace name added at the start targetExtensionPointId = contribution->GetDefaultNamespace() + '.' + extensionPointId; else targetExtensionPointId = extensionPointId; currentExtension->SetExtensionPointIdentifier(targetExtensionPointId); // if we have an Id specified, check for duplicates. Only issue warning if duplicate found // as it might still work fine - depending on the access pattern. if (!simpleId.isNull() && Debug()) { QString uniqueId = namespaceName + '.' + simpleId; IExtension::Pointer existingExtension = GetExtension(uniqueId); if (existingExtension.IsNotNull()) { QString currentSupplier = contribution->GetDefaultNamespace(); QString existingSupplier = existingExtension->GetContributor()->GetName(); QString msg = QString("Extensions supplied by \"%1\" and \"%2\" have the same Id: \"%3\".") .arg(currentSupplier).arg(existingSupplier).arg(uniqueId); IStatus::Pointer status(new Status(IStatus::WARNING_TYPE, RegistryMessages::OWNER_NAME, 0, msg, BERRY_STATUS_LOC)); Log(status); return false; } } GetObjectManager()->Add(currentExtension, true); CreateExtensionData(contributorId, configurationElements, currentExtension, persist); currentExtension->SetContributorId(contributorId); QList contributionChildren; contributionChildren.push_back(0); contributionChildren.push_back(1); contributionChildren.push_back(currentExtension->GetObjectId()); contribution->SetRawChildren(contributionChildren); Add(contribution); return true; } bool ExtensionRegistry::RemoveExtension(const SmartPointer& extension, QObject* token) { ExtensionHandle::Pointer handle = extension.Cast(); if (handle.IsNull()) return false; return RemoveObject(handle->GetObject(), false, token); } bool ExtensionRegistry::RemoveExtensionPoint(const SmartPointer& extensionPoint, QObject* token) { ExtensionPointHandle::Pointer handle = extensionPoint.Cast(); if (handle.IsNull()) return false; return RemoveObject(handle->GetObject(), true, token); } QList > ExtensionRegistry::GetAllContributors() const { QList result; QReadLocker l(&access); foreach(RegistryContributor::Pointer contributor, registryObjects->GetContributors().values()) { result.push_back(contributor); } return result; } bool ExtensionRegistry::IsMultiLanguage() const { return isMultiLanguage; } QList ExtensionRegistry::Translate(const QList& nonTranslated, const SmartPointer& contributor, const QLocale& locale) const { return strategy->Translate(nonTranslated, contributor, locale); } QLocale ExtensionRegistry::GetLocale() const { return strategy->GetLocale(); } void ExtensionRegistry::LogMultiLangError() const { if (mlErrorLogged) // only log this error ones return; IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, 0, QString("The requested multi-language operation is not enabled. See runtime option \"") + Platform::ARG_REGISTRY_MULTI_LANGUAGE + "\".", ctkInvalidArgumentException(""), BERRY_STATUS_LOC)); Log(status); mlErrorLogged = true; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionsParser.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionsParser.cpp index f6224724d6..a68da1ce53 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionsParser.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionsParser.cpp @@ -1,643 +1,643 @@ /*=================================================================== 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 "berryExtensionsParser.h" #include "berryConfigurationElement.h" #include "berryExtension.h" #include "berryExtensionPoint.h" #include "berryExtensionRegistry.h" #include "berryIContributor.h" #include "berryIExtension.h" #include "berryLog.h" #include "berryMultiStatus.h" #include "berryRegistryContribution.h" #include "berryRegistryMessages.h" #include "berryRegistryObject.h" #include "berryRegistryObjectFactory.h" #include "berryRegistryObjectManager.h" #include namespace berry { long ExtensionsParser::cumulativeTime = 0; // Valid States const int ExtensionsParser::IGNORED_ELEMENT_STATE = 0; const int ExtensionsParser::INITIAL_STATE = 1; const int ExtensionsParser::PLUGIN_STATE = 2; const int ExtensionsParser::PLUGIN_EXTENSION_POINT_STATE = 5; const int ExtensionsParser::PLUGIN_EXTENSION_STATE = 6; const int ExtensionsParser::CONFIGURATION_ELEMENT_STATE = 10; const int ExtensionsParser::EXTENSION_POINT_INDEX = 0; const int ExtensionsParser::EXTENSION_INDEX = 1; const int ExtensionsParser::LAST_INDEX = 1; const int ExtensionsParser::PARSE_PROBLEM = 1; const QString ExtensionsParser::PLUGIN = "plugin"; const QString ExtensionsParser::PLUGIN_ID = "id"; const QString ExtensionsParser::PLUGIN_NAME = "name"; const QString ExtensionsParser::BUNDLE_UID = "id"; const QString ExtensionsParser::EXTENSION_POINT = "extension-point"; const QString ExtensionsParser::EXTENSION_POINT_NAME = "name"; const QString ExtensionsParser::EXTENSION_POINT_ID = "id"; const QString ExtensionsParser::EXTENSION_POINT_SCHEMA = "schema"; const QString ExtensionsParser::EXTENSION = "extension"; const QString ExtensionsParser::EXTENSION_NAME = "name"; const QString ExtensionsParser::EXTENSION_ID = "id"; const QString ExtensionsParser::EXTENSION_TARGET = "point"; const QString ExtensionsParser::ELEMENT = "element"; const QString ExtensionsParser::ELEMENT_NAME = "name"; const QString ExtensionsParser::ELEMENT_VALUE = "value"; const QString ExtensionsParser::PROPERTY = "property"; const QString ExtensionsParser::PROPERTY_NAME = "name"; const QString ExtensionsParser::PROPERTY_VALUE = "value"; ExtensionsParser::ExtensionsParser(const SmartPointer& status, ExtensionRegistry* registry) : locator(NULL), extractNamespaces(true), status(status), registry(registry), resources(NULL), objectManager(NULL) { } void ExtensionsParser::setDocumentLocator(QXmlLocator* locator) { this->locator = locator; } bool ExtensionsParser::characters(const QString& ch) { int state = stateStack.back(); if (state != CONFIGURATION_ELEMENT_STATE) return true; if (state == CONFIGURATION_ELEMENT_STATE) { // Accept character data within an element, is when it is // part of a configuration element (i.e. an element within an EXTENSION element ConfigurationElement::Pointer currentConfigElement = objectStack.back().Cast(); if (configurationElementValue.isNull()) { if (!ch.trimmed().isEmpty()) { configurationElementValue = ch; } } else { configurationElementValue.append(ch); } if (!configurationElementValue.isEmpty()) currentConfigElement->SetValue(configurationElementValue); } return true; } -bool ExtensionsParser::endElement(const QString& uri, const QString& elementName, const QString& /*qName*/) +bool ExtensionsParser::endElement(const QString& /*uri*/, const QString& elementName, const QString& /*qName*/) { switch (stateStack.back()) { case IGNORED_ELEMENT_STATE : { stateStack.pop(); return true; } case INITIAL_STATE : { // shouldn't get here internalError(QString("Element/end element mismatch for element \"%1\".").arg(elementName)); return false; } case PLUGIN_STATE : { stateStack.pop(); QList& extensionPoints = scratchVectors[EXTENSION_POINT_INDEX]; QList& extensions = scratchVectors[EXTENSION_INDEX]; QList namespaceChildren; namespaceChildren.push_back(0); namespaceChildren.push_back(0); // Put the extension points into this namespace if (extensionPoints.size() > 0) { namespaceChildren[RegistryContribution::EXTENSION_POINT] = extensionPoints.size(); for (int i = 0; i < extensionPoints.size(); ++i) { namespaceChildren.push_back(extensionPoints[i]->GetObjectId()); } extensionPoints.clear(); } // Put the extensions into this namespace too if (extensions.size() > 0) { namespaceChildren[RegistryContribution::EXTENSION] = extensions.size(); for (int i = 0; i < extensions.size(); ++i) { namespaceChildren.push_back(extensions[i]->GetObjectId()); } extensions.clear(); } contribution->SetRawChildren(namespaceChildren); return true; } case PLUGIN_EXTENSION_POINT_STATE : { if (elementName == EXTENSION_POINT) { stateStack.pop(); } return true; } case PLUGIN_EXTENSION_STATE : { if (elementName == EXTENSION) { stateStack.pop(); // Finish up extension object Extension::Pointer currentExtension = objectStack.pop().Cast(); if (currentExtension->GetNamespaceIdentifier().isEmpty()) currentExtension->SetNamespaceIdentifier(contribution->GetDefaultNamespace()); currentExtension->SetContributorId(contribution->GetContributorId()); scratchVectors[EXTENSION_INDEX].push_back(currentExtension); } return true; } case CONFIGURATION_ELEMENT_STATE : { // We don't care what the element name was stateStack.pop(); // Now finish up the configuration element object configurationElementValue.clear(); ConfigurationElement::Pointer currentConfigElement = objectStack.pop().Cast(); QString value = currentConfigElement->GetValueAsIs(); if (!value.isEmpty()) { currentConfigElement->SetValue(translate(value).trimmed()); } RegistryObject::Pointer parent = objectStack.back().Cast(); // Want to add this configuration element to the subelements of an extension QList newValues = parent->GetRawChildren(); newValues.push_back(currentConfigElement->GetObjectId()); parent->SetRawChildren(newValues); currentConfigElement->SetParentId(parent->GetObjectId()); currentConfigElement->SetParentType(parent.Cast() ? RegistryObjectManager::CONFIGURATION_ELEMENT : RegistryObjectManager::EXTENSION); return true; } default: // should never get here return false; } } bool ExtensionsParser::error(const QXmlParseException& ex) { logStatus(ex); return true; } bool ExtensionsParser::fatalError(const QXmlParseException& ex) { cleanup(); logStatus(ex); return false; } bool ExtensionsParser::parseManifest(QXmlReader* reader, QXmlInputSource* in, const QString& manifestName, RegistryObjectManager* registryObjects, const SmartPointer& currentNamespace, QTranslator* translator) { QTime start; this->resources = translator; this->objectManager = registryObjects; //initialize the parser with this object this->contribution = currentNamespace; if (registry->Debug()) start.start(); if (reader == NULL) { cumulativeTime += start.elapsed(); throw ctkInvalidArgumentException("XML Reader not available"); } locationName = manifestName; reader->setContentHandler(this); reader->setDeclHandler(this); reader->setDTDHandler(this); reader->setEntityResolver(this); reader->setErrorHandler(this); reader->setLexicalHandler(this); bool success = reader->parse(in); if (registry->Debug()) { cumulativeTime += start.elapsed(); BERRY_INFO << "Cumulative parse time so far : " << cumulativeTime; } return success; } bool ExtensionsParser::startDocument() { stateStack.push(INITIAL_STATE); for (int i = 0; i <= LAST_INDEX; i++) { scratchVectors[i].clear(); } return true; } -bool ExtensionsParser::startElement(const QString& uri, const QString& elementName, - const QString& qName, const QXmlAttributes& attributes) +bool ExtensionsParser::startElement(const QString& /*uri*/, const QString& elementName, + const QString& /*qName*/, const QXmlAttributes& attributes) { switch (stateStack.back()) { case INITIAL_STATE : handleInitialState(elementName, attributes); break; case PLUGIN_STATE : handlePluginState(elementName, attributes); break; case PLUGIN_EXTENSION_POINT_STATE : handleExtensionPointState(elementName); break; case PLUGIN_EXTENSION_STATE : case CONFIGURATION_ELEMENT_STATE : handleExtensionState(elementName, attributes); break; default : stateStack.push(IGNORED_ELEMENT_STATE); internalError(QString("Unknown element \"%1\", found at the top level, ignored.").arg(elementName)); } return true; } bool ExtensionsParser::warning(const QXmlParseException& ex) { logStatus(ex); return true; } void ExtensionsParser::error(const SmartPointer& error) { status->Add(error); } void ExtensionsParser::cleanup() { foreach (RegistryObject::Pointer object, addedRegistryObjects) { if (ExtensionPoint::Pointer extPoint = object.Cast()) { QString id = extPoint->GetUniqueIdentifier(); objectManager->RemoveExtensionPoint(id); } else { objectManager->Remove(object->GetObjectId(), true); } } } void ExtensionsParser::handleExtensionPointState(const QString& elementName) { // We ignore all elements under extension points (if there are any) stateStack.push(IGNORED_ELEMENT_STATE); unknownElement(EXTENSION_POINT, elementName); } void ExtensionsParser::handleExtensionState(const QString& elementName, const QXmlAttributes& attributes) { // You need to change the state here even though we will be executing the same // code for ExtensionState and ConfigurationElementState. We ignore the name // of the element for ConfigurationElements. When we are wrapping up, we will // want to add each configuration element object to the subElements vector of // its parent configuration element object. However, the first configuration // element object we created (the last one we pop off the stack) will need to // be added to a vector in the extension object called _configuration. stateStack.push(CONFIGURATION_ELEMENT_STATE); configurationElementValue.clear(); // create a new Configuration Element and push it onto the object stack ConfigurationElement::Pointer currentConfigurationElement = registry->GetElementFactory()->CreateConfigurationElement(contribution->ShouldPersist()); currentConfigurationElement->SetContributorId(contribution->GetContributorId()); objectStack.push(currentConfigurationElement); currentConfigurationElement->SetName(elementName); // Processing the attributes of a configuration element involves creating // a new configuration property for each attribute and populating the configuration // property with the name/value pair of the attribute. Note there will be one // configuration property for each attribute parseConfigurationElementAttributes(attributes); objectManager->Add(currentConfigurationElement, true); addedRegistryObjects.push_back(currentConfigurationElement); } -void ExtensionsParser::handleInitialState(const QString& elementName, const QXmlAttributes& attributes) +void ExtensionsParser::handleInitialState(const QString& /*elementName*/, const QXmlAttributes& /*attributes*/) { // new manifests should have the plugin (or fragment) element empty stateStack.push(PLUGIN_STATE); objectStack.push(contribution); } void ExtensionsParser::handlePluginState(const QString& elementName, const QXmlAttributes& attributes) { if (elementName == EXTENSION_POINT) { stateStack.push(PLUGIN_EXTENSION_POINT_STATE); parseExtensionPointAttributes(attributes); return; } if (elementName == EXTENSION) { stateStack.push(PLUGIN_EXTENSION_STATE); parseExtensionAttributes(attributes); return; } // If we get to this point, the element name is one we don't currently accept. // Set the state to indicate that this element will be ignored stateStack.push(IGNORED_ELEMENT_STATE); unknownElement(PLUGIN, elementName); } void ExtensionsParser::logStatus(const QXmlParseException& ex) { QString name = ex.systemId(); if (name.isEmpty()) name = locationName; if (!name.isEmpty()) name = name.mid(1 + name.lastIndexOf("/")); QString msg; if (name.isEmpty()) msg = QString("Parsing error: \"%1\"").arg(ex.message()); else msg = QString("Parsing error in \"%1\" [line %2, column %3]: \"%4\".").arg(name) .arg(ex.lineNumber()).arg(ex.columnNumber()).arg(ex.message()); IStatus::Pointer status(new Status(IStatus::WARNING_TYPE, RegistryMessages::OWNER_NAME, PARSE_PROBLEM, msg, BERRY_STATUS_LOC)); error(status); } void ExtensionsParser::parseConfigurationElementAttributes(const QXmlAttributes& attributes) { ConfigurationElement::Pointer parentConfigurationElement = objectStack.back().Cast(); // process attributes int len = attributes.length(); if (len == 0) { parentConfigurationElement->SetProperties(QList()); return; } QList properties; for (int i = 0; i < len; i++) { properties.push_back(attributes.localName(i)); properties.push_back(translate(attributes.value(i))); } parentConfigurationElement->SetProperties(properties); } void ExtensionsParser::parseExtensionAttributes(const QXmlAttributes& attributes) { Extension::Pointer currentExtension = registry->GetElementFactory()->CreateExtension(contribution->ShouldPersist()); objectStack.push(currentExtension); QString simpleId; QString namespaceName; // Process Attributes int len = attributes.length(); for (int i = 0; i < len; i++) { QString attrName = attributes.localName(i); QString attrValue = attributes.value(i).trimmed(); if (attrName == EXTENSION_NAME) currentExtension->SetLabel(translate(attrValue)); else if (attrName == EXTENSION_ID) { int simpleIdStart = attrValue.lastIndexOf('.'); if ((simpleIdStart != -1) && extractNamespaces) { simpleId = attrValue.mid(simpleIdStart + 1); namespaceName = attrValue.left(simpleIdStart); } else { simpleId = attrValue; namespaceName = contribution->GetDefaultNamespace(); } currentExtension->SetSimpleIdentifier(simpleId); currentExtension->SetNamespaceIdentifier(namespaceName); } else if (attrName == EXTENSION_TARGET) { // check if point is specified as a simple or qualified name QString targetName; if (attrValue.lastIndexOf('.') == -1) { QString baseId = contribution->GetDefaultNamespace(); targetName = baseId + '.' + attrValue; } else { targetName = attrValue; } currentExtension->SetExtensionPointIdentifier(targetName); } else { unknownAttribute(attrName, EXTENSION); } } if (currentExtension->GetExtensionPointIdentifier().isEmpty()) { missingAttribute(EXTENSION_TARGET, EXTENSION); stateStack.pop(); stateStack.push(IGNORED_ELEMENT_STATE); objectStack.pop(); return; } // if we have an Id specified, check for duplicates. Only issue warning (not error) if duplicate found // as it might still work fine - depending on the access pattern. if (!simpleId.isEmpty() && registry->Debug()) { QString uniqueId = namespaceName + '.' + simpleId; IExtension::Pointer existingExtension = registry->GetExtension(uniqueId); if (existingExtension.IsNotNull()) { QString currentSupplier = contribution->GetDefaultNamespace(); QString existingSupplier = existingExtension->GetContributor()->GetName(); QString msg = QString("Extensions supplied by \"%1\" and \"%2\" have the same Id: \"%3\".") .arg(currentSupplier).arg(existingSupplier).arg(uniqueId); IStatus::Pointer status(new Status(IStatus::WARNING_TYPE, RegistryMessages::OWNER_NAME, 0, msg, BERRY_STATUS_LOC)); registry->Log(status); } else if (!processedExtensionIds.isEmpty()) { // check elements in this contribution foreach (QString processedId, processedExtensionIds) { if (uniqueId == processedId) { QString currentSupplier = contribution->GetDefaultNamespace(); QString existingSupplier = currentSupplier; QString msg = QString("Extensions supplied by \"%1\" and \"%2\" have the same Id: \"%3\".") .arg(currentSupplier).arg(existingSupplier).arg(uniqueId); IStatus::Pointer status(new Status(IStatus::WARNING_TYPE, RegistryMessages::OWNER_NAME, 0, msg, BERRY_STATUS_LOC)); registry->Log(status); break; } } } processedExtensionIds.push_back(uniqueId); } objectManager->Add(currentExtension, true); addedRegistryObjects.push_back(currentExtension); } void ExtensionsParser::missingAttribute(const QString& attribute, const QString& element) { if (locator == NULL) internalError(QString("Missing \"%1\" attribute in \"%2\" element. Element ignored.").arg(attribute).arg(element)); else internalError(QString("Missing \"%1\" attribute in \"%2\" element (line: %3). Element ignored.") .arg(attribute).arg(element).arg(locator->lineNumber())); } void ExtensionsParser::unknownAttribute(const QString& attribute, const QString& element) { if (locator == NULL) internalError(QString("Unknown attribute \"%1\" for element \"%2\" ignored.").arg(attribute).arg(element)); else internalError(QString("Unknown attribute \"%1\" for element \"%2\" ignored (line: %3).") .arg(attribute).arg(element).arg(locator->lineNumber())); } void ExtensionsParser::unknownElement(const QString& parent, const QString& element) { if (locator == NULL) internalError(QString("Unknown element \"%1\", found within a \"%2\", ignored.").arg(element).arg(parent)); else internalError(QString("Unknown element \"%1\", found within a \"%2\", ignored (line: %3).") .arg(element).arg(parent).arg(locator->lineNumber())); } void ExtensionsParser::parseExtensionPointAttributes(const QXmlAttributes& attributes) { ExtensionPoint::Pointer currentExtPoint = registry->GetElementFactory()->CreateExtensionPoint(contribution->ShouldPersist()); // Process Attributes int len = attributes.length(); for (int i = 0; i < len; i++) { QString attrName = attributes.localName(i); QString attrValue = attributes.value(i).trimmed(); if (attrName == EXTENSION_POINT_NAME) currentExtPoint->SetLabel(translate(attrValue)); else if (attrName == EXTENSION_POINT_ID) { QString uniqueId; QString namespaceName; int simpleIdStart = attrValue.lastIndexOf('.'); if (simpleIdStart != -1 && extractNamespaces) { namespaceName = attrValue.left(simpleIdStart); uniqueId = attrValue; } else { namespaceName = contribution->GetDefaultNamespace(); uniqueId = namespaceName + '.' + attrValue; } currentExtPoint->SetUniqueIdentifier(uniqueId); currentExtPoint->SetNamespace(namespaceName); } else if (attrName == EXTENSION_POINT_SCHEMA) currentExtPoint->SetSchema(attrValue); else unknownAttribute(attrName, EXTENSION_POINT); } if (currentExtPoint->GetSimpleIdentifier().isEmpty() || currentExtPoint->GetLabel().isEmpty()) { QString attribute = currentExtPoint->GetSimpleIdentifier().isEmpty() ? EXTENSION_POINT_ID : EXTENSION_POINT_NAME; missingAttribute(attribute, EXTENSION_POINT); stateStack.pop(); stateStack.push(IGNORED_ELEMENT_STATE); return; } if (!objectManager->AddExtensionPoint(currentExtPoint, true)) { // avoid adding extension point second time as it might cause // extensions associated with the existing extension point to // become inaccessible. if (registry->Debug()) { QString msg = QString("Ignored duplicate extension point \"%1\" supplied by \"%2\".") .arg(currentExtPoint->GetUniqueIdentifier()).arg(contribution->GetDefaultNamespace()); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, 0, msg, BERRY_STATUS_LOC)); registry->Log(status); } stateStack.pop(); stateStack.push(IGNORED_ELEMENT_STATE); return; } if (currentExtPoint->GetNamespace().isEmpty()) currentExtPoint->SetNamespace(contribution->GetDefaultNamespace()); currentExtPoint->SetContributorId(contribution->GetContributorId()); addedRegistryObjects.push_back(currentExtPoint); // Now populate the the vector just below us on the objectStack with this extension point scratchVectors[EXTENSION_POINT_INDEX].push_back(currentExtPoint); } void ExtensionsParser::internalError(const QString& message) { IStatus::Pointer status(new Status(IStatus::WARNING_TYPE, RegistryMessages::OWNER_NAME, PARSE_PROBLEM, message, BERRY_STATUS_LOC)); error(status); } QString ExtensionsParser::translate(const QString& key) const { return registry->Translate(key, resources); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryIObjectManager.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryIObjectManager.h index c33cef2fc1..2d9f29fd49 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryIObjectManager.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryIObjectManager.h @@ -1,45 +1,45 @@ /*=================================================================== 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 BERRYIOBJECTMANAGER_H #define BERRYIOBJECTMANAGER_H #include namespace berry { class Handle; class RegistryObject; struct IObjectManager : public Object { - berryInterfaceMacro(IObjectManager, berry) + berryObjectMacro(berry::IObjectManager) virtual ~IObjectManager(); virtual SmartPointer GetHandle(int id, short type) const = 0; virtual QList > GetHandles(const QList& ids, short type) const = 0; virtual SmartPointer GetObject(int id, short type) const = 0; virtual QList > GetObjects(const QList& values, short type) const = 0; virtual void Close() = 0; }; } #endif // BERRYIOBJECTMANAGER_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp index 3e0635e3e8..1e4f10f13a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp @@ -1,593 +1,597 @@ /*=================================================================== 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 NOMINMAX +#define NOMINMAX +#endif + #include "berryInternalPlatform.h" #include "berryLog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "berryPlatform.h" #include "berryPlatformException.h" #include "berryDebugUtil.h" //#include "event/berryPlatformEvents.h" //#include "berryPlatformLogChannel.h" #include "berryProvisioningInfo.h" #include "berryCTKPluginActivator.h" #include "berryLogImpl.h" #include #include #include #include #include namespace berry { Poco::Mutex InternalPlatform::m_Mutex; InternalPlatform::InternalPlatform() : m_Initialized(false) , m_Running(false) , m_ConsoleLog(false) , m_PlatformLogger(0) , m_ctkPluginFrameworkFactory(0) { } InternalPlatform::~InternalPlatform() { } InternalPlatform* InternalPlatform::GetInstance() { Poco::Mutex::ScopedLock lock(m_Mutex); static InternalPlatform instance; return &instance; } bool InternalPlatform::ConsoleLog() const { return m_ConsoleLog; } ctkPluginContext* InternalPlatform::GetCTKPluginFrameworkContext() const { if (m_ctkPluginFrameworkFactory) { return m_ctkPluginFrameworkFactory->getFramework()->getPluginContext(); } return 0; } IAdapterManager* InternalPlatform::GetAdapterManager() const { AssertInitialized(); return NULL; } void InternalPlatform::Initialize(int& argc, char** argv, Poco::Util::AbstractConfiguration* config) { // initialization Poco::Mutex::ScopedLock lock(m_Mutex); m_Argc = &argc; m_Argv = argv; try { this->init(argc, argv); } catch (const Poco::Util::UnknownOptionException& e) { BERRY_WARN << e.displayText(); } this->loadConfiguration(); if (config) { this->config().add(config, 50, false); } m_ConsoleLog = this->GetConfiguration().hasProperty(Platform::ARG_CONSOLELOG.toStdString()); m_ConfigPath.setPath(QString::fromStdString(this->GetConfiguration().getString("application.configDir"))); m_InstancePath.setPath(QString::fromStdString(this->GetConfiguration().getString("application.dir"))); try { m_InstallPath.setPath(QString::fromStdString(this->GetConfiguration().getString(Platform::ARG_HOME.toStdString()))); } catch (Poco::NotFoundException& ) { m_InstallPath = m_InstancePath; } if (this->GetConfiguration().hasProperty(Platform::ARG_STORAGE_DIR.toStdString())) { QString dataLocation = QString::fromStdString(this->GetConfiguration().getString(Platform::ARG_STORAGE_DIR.toStdString(), "")); if (dataLocation.at(dataLocation.size()-1) != '/') { dataLocation += '/'; } m_UserPath.setPath(dataLocation); } else { // Append a hash value of the absolute path of the executable to the data location. // This allows to start the same application from different build or install trees. #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) QString dataLocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + '_'; #else QString dataLocation = QDesktopServices::storageLocation(QDesktopServices::DataLocation) + '_'; #endif dataLocation += QString::number(qHash(QCoreApplication::applicationDirPath())) + "/"; m_UserPath.setPath(dataLocation); } BERRY_INFO(m_ConsoleLog) << "Framework storage dir: " << m_UserPath.absolutePath(); QFileInfo userFile(m_UserPath.absolutePath()); if (!QDir().mkpath(userFile.absoluteFilePath()) || !userFile.isWritable()) { QString tmpPath = QDir::temp().absoluteFilePath(QString::fromStdString(this->commandName())); BERRY_WARN << "Storage dir " << userFile.absoluteFilePath() << " is not writable. Falling back to temporary path " << tmpPath; QDir().mkpath(tmpPath); userFile.setFile(tmpPath); } // Initialize the CTK Plugin Framework ctkProperties fwProps; fwProps.insert(ctkPluginConstants::FRAMEWORK_STORAGE, userFile.absoluteFilePath()); if (this->GetConfiguration().hasProperty(Platform::ARG_CLEAN.toStdString())) { fwProps.insert(ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN, ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); } if (this->GetConfiguration().hasProperty(Platform::ARG_CONSOLELOG.toStdString())) { fwProps.insert("org.commontk.pluginfw.debug.framework", true); fwProps.insert("org.commontk.pluginfw.debug.errors", true); fwProps.insert("org.commontk.pluginfw.debug.pluginfw", true); fwProps.insert("org.commontk.pluginfw.debug.lazy_activation", true); fwProps.insert("org.commontk.pluginfw.debug.resolve", true); } if (this->GetConfiguration().hasProperty(Platform::ARG_PRELOAD_LIBRARY.toStdString())) { QString preloadLibs = QString::fromStdString(this->GetConfiguration().getString(Platform::ARG_PRELOAD_LIBRARY.toStdString())); fwProps.insert(ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES, preloadLibs.split(',', QString::SkipEmptyParts)); } m_ctkPluginFrameworkFactory = new ctkPluginFrameworkFactory(fwProps); QSharedPointer pfw = m_ctkPluginFrameworkFactory->getFramework(); pfw->init(); ctkPluginContext* pfwContext = pfw->getPluginContext(); // FIXME: This is a quick-fix for Bug 16224 - Umlaut and other special characters in install/binary path // Assumption : linux provides utf8, windows provides ascii encoded argv lists #ifdef Q_OS_WIN QString provisioningFile = QString::fromStdString(this->GetConfiguration().getString(Platform::ARG_PROVISIONING.toStdString())); #else QString provisioningFile = QString::fromUtf8(this->GetConfiguration().getString(Platform::ARG_PROVISIONING.toStdString())); #endif if (!provisioningFile.isEmpty()) { BERRY_INFO(m_ConsoleLog) << "Using provisioning file: " << provisioningFile; ProvisioningInfo provInfo(provisioningFile); // it can still happen, that the encoding is not compatible with the fromUtf8 function ( i.e. when manipulating the LANG variable // in such case, the QStringList in provInfo is empty which we can easily check for if( provInfo.getPluginDirs().empty() ) { BERRY_ERROR << "Cannot search for provisioning file, the retrieved directory list is empty.\n" << "This can occur if there are some special (non-ascii) characters in the install path."; throw berry::PlatformException("No provisioning file specified. Terminating..."); } foreach(QString pluginPath, provInfo.getPluginDirs()) { ctkPluginFrameworkLauncher::addSearchPath(pluginPath); } bool forcePluginOverwrite = this->GetConfiguration().hasOption(Platform::ARG_FORCE_PLUGIN_INSTALL.toStdString()); QList pluginsToStart = provInfo.getPluginsToStart(); foreach(QUrl pluginUrl, provInfo.getPluginsToInstall()) { if (forcePluginOverwrite) { uninstallPugin(pluginUrl, pfwContext); } try { BERRY_INFO(m_ConsoleLog) << "Installing CTK plug-in from: " << pluginUrl.toString().toStdString(); QSharedPointer plugin = pfwContext->installPlugin(pluginUrl); if (pluginsToStart.contains(pluginUrl)) { m_CTKPluginsToStart << plugin->getPluginId(); } } catch (const ctkPluginException& e) { QString errorMsg; QDebug dbg(&errorMsg); dbg << e.printStackTrace(); BERRY_ERROR << qPrintable(errorMsg); } } } else { BERRY_INFO << "No provisioning file set."; } m_BaseStatePath.setPath(m_UserPath.absolutePath() + "/bb-metadata/bb-plugins"); QString logPath(m_UserPath.absoluteFilePath(QString::fromStdString(this->commandName()) + ".log")); m_PlatformLogChannel = new Poco::SimpleFileChannel(logPath.toStdString()); m_PlatformLogger = &Poco::Logger::create("PlatformLogger", m_PlatformLogChannel, Poco::Message::PRIO_TRACE); m_Initialized = true; #ifdef BLUEBERRY_DEBUG_SMARTPOINTER DebugUtil::RestoreState(m_UserPath); #endif } void InternalPlatform::uninstallPugin(const QUrl& pluginUrl, ctkPluginContext* pfwContext) { QFileInfo libInfo(pluginUrl.toLocalFile()); QString libName = libInfo.baseName(); if (libName.startsWith("lib")) { libName = libName.mid(3); } QString symbolicName = libName.replace('_', '.'); foreach(QSharedPointer plugin, pfwContext->getPlugins()) { if (plugin->getSymbolicName() == symbolicName && plugin->getLocation() != pluginUrl.toString()) { BERRY_WARN << "A plug-in with the symbolic name " << symbolicName.toStdString() << " but different location is already installed. Trying to uninstall " << plugin->getLocation().toStdString(); plugin->uninstall(); return; } } } void InternalPlatform::Launch() { AssertInitialized(); if (m_Running) return; m_Running = true; this->run(); } void InternalPlatform::Shutdown() { QSharedPointer ctkPluginFW; { Poco::Mutex::ScopedLock lock(m_Mutex); AssertInitialized(); DebugUtil::SaveState(m_UserPath); ctkPluginFW = m_ctkPluginFrameworkFactory->getFramework(); m_Initialized = false; } ctkPluginFW->stop(); this->uninitialize(); // wait 10 seconds for the CTK plugin framework to stop ctkPluginFW->waitForStop(10000); } void InternalPlatform::AssertInitialized() const { if (!m_Initialized) throw Poco::SystemException("The Platform has not been initialized yet!"); } IExtensionRegistry* InternalPlatform::GetExtensionRegistry() { if (m_RegistryTracker.isNull()) { m_RegistryTracker.reset(new ctkServiceTracker(berry::CTKPluginActivator::getPluginContext())); m_RegistryTracker->open(); } return m_RegistryTracker->getService(); } IPreferencesService *InternalPlatform::GetPreferencesService() { if (m_PreferencesTracker.isNull()) { m_PreferencesTracker.reset(new ctkServiceTracker(berry::CTKPluginActivator::getPluginContext())); m_PreferencesTracker->open(); } return m_PreferencesTracker->getService(); } QDir InternalPlatform::GetConfigurationPath() { return m_ConfigPath; } QDir InternalPlatform::GetInstallPath() { return m_InstallPath; } QDir InternalPlatform::GetInstancePath() { return m_InstancePath; } bool InternalPlatform::GetStatePath(QDir& statePath, const QSharedPointer& plugin, bool create) { QFileInfo tmpStatePath(m_BaseStatePath.absoluteFilePath(plugin->getSymbolicName())); if (tmpStatePath.exists()) { if (tmpStatePath.isDir() && tmpStatePath.isWritable() && tmpStatePath.isReadable()) { statePath.setPath(tmpStatePath.absoluteFilePath()); return true; } else { return false; } } else if (create) { bool created = statePath.mkpath(tmpStatePath.absoluteFilePath()); if (created) { statePath.setPath(tmpStatePath.absoluteFilePath()); return true; } return false; } return false; } //PlatformEvents& InternalPlatform::GetEvents() //{ // return m_Events; //} QDir InternalPlatform::GetUserPath() { return m_UserPath; } ILog *InternalPlatform::GetLog(const QSharedPointer &plugin) const { LogImpl* result = m_Logs.value(plugin->getPluginId()); if (result != NULL) return result; // ExtendedLogService logService = (ExtendedLogService) extendedLogTracker.getService(); // Logger logger = logService == null ? null : logService.getLogger(bundle, PlatformLogWriter.EQUINOX_LOGGER_NAME); // result = new Log(bundle, logger); // ExtendedLogReaderService logReader = (ExtendedLogReaderService) logReaderTracker.getService(); // logReader.addLogListener(result, result); // logs.put(bundle, result); // return result; result = new LogImpl(plugin); m_Logs.insert(plugin->getPluginId(), result); return result; } bool InternalPlatform::IsRunning() const { Poco::Mutex::ScopedLock lock(m_Mutex); return (m_Initialized && m_Running); } QSharedPointer InternalPlatform::GetPlugin(const QString &symbolicName) { QList > plugins = InternalPlatform::GetInstance()->GetCTKPluginFrameworkContext()->getPlugins(); QSharedPointer res(0); foreach(QSharedPointer plugin, plugins) { if ((plugin->getState() & (ctkPlugin::INSTALLED | ctkPlugin::UNINSTALLED)) == 0 && plugin->getSymbolicName() == symbolicName) { if (res.isNull()) { res = plugin; } else if (res->getVersion().compare(plugin->getVersion()) < 0) { res = plugin; } } } return res; } QList > InternalPlatform::GetPlugins(const QString &symbolicName, const QString &version) { QList > plugins = InternalPlatform::GetInstance()->GetCTKPluginFrameworkContext()->getPlugins(); QMap > selected; ctkVersion versionObj(version); foreach(QSharedPointer plugin, plugins) { if ((plugin->getState() & (ctkPlugin::INSTALLED | ctkPlugin::UNINSTALLED)) == 0 && plugin->getSymbolicName() == symbolicName) { if (plugin->getVersion().compare(versionObj) > -1) { selected.insert(plugin->getVersion(), plugin); } } } QList > sortedPlugins = selected.values(); QList > reversePlugins; qCopyBackward(sortedPlugins.begin(), sortedPlugins.end(), reversePlugins.end()); return reversePlugins; } Poco::Logger* InternalPlatform::GetLogger() { return m_PlatformLogger; } Poco::Util::LayeredConfiguration& InternalPlatform::GetConfiguration() const { return this->config(); } QStringList InternalPlatform::GetApplicationArgs() const { return m_FilteredArgs; } int& InternalPlatform::GetRawApplicationArgs(char**& argv) { argv = m_Argv; return *m_Argc; } void InternalPlatform::defineOptions(Poco::Util::OptionSet& options) { Poco::Util::Option helpOption("help", "h", "print this help text"); helpOption.callback(Poco::Util::OptionCallback(this, &InternalPlatform::PrintHelp)); options.addOption(helpOption); Poco::Util::Option newInstanceOption(Platform::ARG_NEWINSTANCE.toStdString(), "", "forces a new instance of this application"); newInstanceOption.binding(Platform::ARG_NEWINSTANCE.toStdString()); options.addOption(newInstanceOption); Poco::Util::Option cleanOption(Platform::ARG_CLEAN.toStdString(), "", "cleans the plugin cache"); cleanOption.binding(Platform::ARG_CLEAN.toStdString()); options.addOption(cleanOption); Poco::Util::Option appOption(Platform::ARG_APPLICATION.toStdString(), "", "the id of the application extension to be executed"); appOption.argument("").binding(Platform::ARG_APPLICATION.toStdString()); options.addOption(appOption); Poco::Util::Option storageDirOption(Platform::ARG_STORAGE_DIR.toStdString(), "", "the location for storing persistent application data"); storageDirOption.argument("").binding(Platform::ARG_STORAGE_DIR.toStdString()); options.addOption(storageDirOption); Poco::Util::Option consoleLogOption(Platform::ARG_CONSOLELOG.toStdString(), "", "log messages to the console"); consoleLogOption.binding(Platform::ARG_CONSOLELOG.toStdString()); options.addOption(consoleLogOption); Poco::Util::Option forcePluginOption(Platform::ARG_FORCE_PLUGIN_INSTALL.toStdString(), "", "force installing plug-ins with same symbolic name"); forcePluginOption.binding(Platform::ARG_FORCE_PLUGIN_INSTALL.toStdString()); options.addOption(forcePluginOption); Poco::Util::Option preloadLibsOption(Platform::ARG_PRELOAD_LIBRARY.toStdString(), "", "preload a library"); preloadLibsOption.argument("").repeatable(true).callback(Poco::Util::OptionCallback(this, &InternalPlatform::handlePreloadLibraryOption)); options.addOption(preloadLibsOption); Poco::Util::Option testPluginOption(Platform::ARG_TESTPLUGIN.toStdString(), "", "the plug-in to be tested"); testPluginOption.argument("").binding(Platform::ARG_TESTPLUGIN.toStdString()); options.addOption(testPluginOption); Poco::Util::Option testAppOption(Platform::ARG_TESTAPPLICATION.toStdString(), "", "the application to be tested"); testAppOption.argument("").binding(Platform::ARG_TESTAPPLICATION.toStdString()); options.addOption(testAppOption); Poco::Util::Option noRegistryCacheOption(Platform::ARG_NO_REGISTRY_CACHE.toStdString(), "", "do not use a cache for the registry"); noRegistryCacheOption.binding(Platform::ARG_NO_REGISTRY_CACHE.toStdString()); options.addOption(noRegistryCacheOption); Poco::Util::Option noLazyRegistryCacheLoadingOption(Platform::ARG_NO_LAZY_REGISTRY_CACHE_LOADING.toStdString(), "", "do not use lazy cache loading for the registry"); noLazyRegistryCacheLoadingOption.binding(Platform::ARG_NO_LAZY_REGISTRY_CACHE_LOADING.toStdString()); options.addOption(noLazyRegistryCacheLoadingOption); Poco::Util::Option registryMultiLanguageOption(Platform::ARG_REGISTRY_MULTI_LANGUAGE.toStdString(), "", "enable multi-language support for the registry"); registryMultiLanguageOption.binding(Platform::ARG_REGISTRY_MULTI_LANGUAGE.toStdString()); options.addOption(registryMultiLanguageOption); Poco::Util::Option xargsOption(Platform::ARG_XARGS.toStdString(), "", "Extended argument list"); xargsOption.argument("").binding(Platform::ARG_XARGS.toStdString()); options.addOption(xargsOption); Poco::Util::Application::defineOptions(options); } -void InternalPlatform::handlePreloadLibraryOption(const std::string& name, const std::string& value) +void InternalPlatform::handlePreloadLibraryOption(const std::string& /*name*/, const std::string& value) { std::string oldVal; if (this->config().hasProperty(Platform::ARG_PRELOAD_LIBRARY.toStdString())) { oldVal = this->config().getString(Platform::ARG_PRELOAD_LIBRARY.toStdString()); } this->config().setString(Platform::ARG_PRELOAD_LIBRARY.toStdString(), oldVal + "," + value); } int InternalPlatform::main(const std::vector& args) { for(std::vector::const_iterator i = args.begin(); i != args.end(); ++i) { m_FilteredArgs << QString::fromStdString(*i); } //m_FilteredArgs.insert(m_FilteredArgs.begin(), this->config().getString("application.argv[0]")); ctkPluginContext* context = GetCTKPluginFrameworkContext(); QFileInfo storageDir = context->getDataFile(""); m_ctkPluginFrameworkFactory->getFramework()->start(); foreach(long pluginId, m_CTKPluginsToStart) { BERRY_INFO(m_ConsoleLog) << "Starting CTK plug-in: " << context->getPlugin(pluginId)->getSymbolicName().toStdString() << " [" << pluginId << "]"; // do not change the autostart setting of this plugin context->getPlugin(pluginId)->start(ctkPlugin::START_TRANSIENT | ctkPlugin::START_ACTIVATION_POLICY); } return EXIT_OK; } void InternalPlatform::PrintHelp(const std::string&, const std::string&) { Poco::Util::HelpFormatter help(this->options()); help.setAutoIndent(); help.setCommand(this->commandName()); help.format(std::cout); exit(EXIT_OK); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryKeyedElement.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryKeyedElement.cpp index 933d6a1ad8..7882c2cdca 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryKeyedElement.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryKeyedElement.cpp @@ -1,43 +1,43 @@ /*=================================================================== 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 "berryKeyedElement.h" #include namespace berry { KeyedElement::~KeyedElement() { } bool KeyedElement::operator ==(const KeyedElement& other) const { return (typeid(*this) == typeid(other) && IsEqual(other)); } -bool KeyedElement::operator ==(const KeyedElement* other) const +bool KeyedElement::operator ==(const Object* other) const { if (other == NULL) return false; - return (typeid(this) == typeid(other) && IsEqual(*other)); + return (typeid(this) == typeid(other) && IsEqual(*static_cast(other))); } uint KeyedElement::HashCode() const { return qHash(this->GetKey()); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryKeyedElement.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryKeyedElement.h index 10a8da3e18..645c542509 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryKeyedElement.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryKeyedElement.h @@ -1,47 +1,47 @@ /*=================================================================== 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 BERRYKEYEDELEMENT_H #define BERRYKEYEDELEMENT_H #include namespace berry { class KeyedElement : public Object { public: berryObjectMacro(berry::KeyedElement) ~KeyedElement(); bool operator==(const KeyedElement& other) const; - bool operator==(const KeyedElement* other) const; + bool operator==(const Object* other) const; virtual QString GetKey() const = 0; uint HashCode() const; private: virtual bool IsEqual(const KeyedElement& other) const = 0; }; } #endif // BERRYKEYEDELEMENT_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryLogImpl.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryLogImpl.cpp index afe170d812..ab9910856d 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryLogImpl.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryLogImpl.cpp @@ -1,76 +1,76 @@ /*=================================================================== 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 "berryLogImpl.h" #include "berryIStatus.h" #include #include namespace berry { LogImpl::LogImpl(const QSharedPointer& plugin) : plugin(plugin) { } LogImpl::~LogImpl() { } -void LogImpl::AddLogListener(ILogListener* listener) +void LogImpl::AddLogListener(ILogListener* /*listener*/) { } QSharedPointer LogImpl::GetBundle() const { return plugin; } void LogImpl::Log(const SmartPointer& status) { switch (status->GetSeverity()) { case IStatus::WARNING_TYPE: mbilog::PseudoStream(mbilog::Warn, qPrintable(status->GetFileName()), status->GetLineNumber(), qPrintable(status->GetMethodName()))(qPrintable(plugin->getSymbolicName())) << status->ToString().toStdString(); break; case IStatus::ERROR_TYPE: mbilog::PseudoStream(mbilog::Error, qPrintable(status->GetFileName()), status->GetLineNumber(), qPrintable(status->GetMethodName()))(qPrintable(plugin->getSymbolicName())) << status->ToString().toStdString(); break; default: mbilog::PseudoStream(mbilog::Info, qPrintable(status->GetFileName()), status->GetLineNumber(), qPrintable(status->GetMethodName()))(qPrintable(plugin->getSymbolicName())) << status->ToString().toStdString(); break; } } -void LogImpl::RemoveLogListener(ILogListener* listener) +void LogImpl::RemoveLogListener(ILogListener* /*listener*/) { } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryProvisioningInfo.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryProvisioningInfo.cpp index 8a10e944b6..3e3bbacc01 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryProvisioningInfo.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryProvisioningInfo.cpp @@ -1,228 +1,232 @@ /*=================================================================== 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 "berryProvisioningInfo.h" #include #include #include #include #include namespace berry { #ifdef CMAKE_INTDIR const QString ProvisioningInfo::intermediateOutDir = QString(CMAKE_INTDIR); #else const QString ProvisioningInfo::intermediateOutDir = QString(); #endif ProvisioningInfo::ProvisioningInfo(const QString& file) { this->readProvisioningFile(file); } QStringList ProvisioningInfo::getPluginDirs() const { return pluginDirs.toList(); } QList ProvisioningInfo::getPluginsToInstall() const { return pluginsToInstall; } QList ProvisioningInfo::getPluginsToStart() const { return pluginsToStart; } void ProvisioningInfo::readProvisioningFile(const QString& filePath) { QFile file(filePath); file.open(QFile::ReadOnly); QTextStream fileStream(&file); QRegExp sep("\\s+"); QString line; int count = 1; do { line = fileStream.readLine().trimmed(); if (!line.isEmpty() && !line.startsWith('#')) { QString keyword = line.section(sep, 0, 0); QString value = line.mid(keyword.size()).trimmed(); value = substituteKeywords(value); if (keyword.isEmpty()) { BERRY_WARN << "Keyword missing in line " << count << " of provisioning file " << filePath.toStdString(); continue; } Keyword key = UNKNOWN; if (keyword.compare("READ", Qt::CaseInsensitive) == 0) { key = READ; } else if (keyword.compare("INSTALL", Qt::CaseInsensitive) == 0) { key = INSTALL; } else if (keyword.compare("START", Qt::CaseInsensitive) == 0) { key = START; } else if (keyword.compare("STOP", Qt::CaseInsensitive) == 0) { key = STOP; } if (key == UNKNOWN) { BERRY_WARN << "Keyword " << keyword.toStdString() << " in line " << count << " of provisioning file " << filePath.toStdString() << " unknown"; continue; } if (value.isEmpty()) { BERRY_WARN << "Value after keyword " << keyword.toStdString() << " missing in line " << count << " of provisioning file " << filePath.toStdString(); continue; } switch (key) { case READ: { QUrl readFileUrl(value); if (!readFileUrl.isValid()) { BERRY_WARN << "The READ URL " << value.toStdString() << "is invalid: " << readFileUrl.errorString().toStdString(); break; } this->readProvisioningFile(readFileUrl.toLocalFile()); break; } case INSTALL: { this->addPluginToInstall(value); break; } case START: { this->addPluginToStart(value); break; } case STOP: { break; } + case UNKNOWN: + { + break; // error handled above + } } } ++count; } while (!line.isNull()); } QUrl ProvisioningInfo::addPluginToInstall(const QString& file) { QUrl pluginUrl(file); if (!pluginUrl.isValid()) { BERRY_WARN << "The plugin URL " << file.toStdString() << " is invalid:" << pluginUrl.errorString().toStdString(); return QUrl(); } QFileInfo fileInfo(pluginUrl.toLocalFile()); if (!fileInfo.exists()) { QString fileName = fileInfo.fileName(); QString filePath = fileInfo.absolutePath(); if (!intermediateOutDir.isEmpty()) { // search in the intermediate output dir QString filePath2 = filePath + "/" + intermediateOutDir; fileInfo = QFileInfo(filePath2 + "/" + fileName); if (!fileInfo.exists()) { BERRY_WARN << "The plugin " << fileName.toStdString() << " was not found in " << filePath.toStdString() << " or " << filePath2.toStdString(); return QUrl(); } pluginUrl = QUrl::fromLocalFile(fileInfo.canonicalFilePath()); pluginDirs.insert(fileInfo.canonicalPath()); } else { BERRY_WARN << "The plugin " << fileName.toStdString() << " was not found in " << filePath.toStdString(); return QUrl(); } } else { pluginDirs.insert(fileInfo.canonicalPath()); } pluginsToInstall.append(pluginUrl); return pluginUrl; } void ProvisioningInfo::addPluginToStart(const QString& file) { QUrl pluginUrl = this->addPluginToInstall(file); if (!pluginUrl.isEmpty()) { pluginsToStart.append(pluginUrl); } } QString ProvisioningInfo::substituteKeywords(const QString& value) const { QString appPath = QCoreApplication::applicationDirPath(); if (appPath.endsWith('/')) { appPath.chop(1); } #ifdef CMAKE_INTDIR // Strip the intermediate dir from the application path QString intDir(CMAKE_INTDIR); if (appPath.endsWith(intDir)) { appPath.chop(intDir.size()+1); } #endif #ifdef _WIN32 if (value.contains("@EXECUTABLE_DIR") && value.contains("blueberry_osgi")) { // special case for org_blueberry_osgi in install trees for Windows return QString(value).replace("@EXECUTABLE_DIR", appPath, Qt::CaseInsensitive).replace("plugins/", ""); } #endif return QString(value).replace("@EXECUTABLE_DIR", appPath, Qt::CaseInsensitive); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryDelta.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryDelta.cpp deleted file mode 100644 index 66bf8a2e87..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryDelta.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/*=================================================================== - -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 "berryExtensionDelta.h" -#include "berryRegistryDelta.h" -#include "berryIExtension.h" - -#include - -namespace berry { - -class RegistryDeltaData : public QSharedData -{ -public: - - RegistryDeltaData() - : objectManager(NULL) - { - } - - QSet extensionDeltas; //the extension deltas (each element indicate the type of the delta) - SmartPointer objectManager; //The object manager from which all the objects contained in the deltas will be found. - -}; - -RegistryDelta::RegistryDelta() - : d(new RegistryDeltaData) -{ - //Nothing to do -} - -RegistryDelta::~RegistryDelta() -{ -} - -int RegistryDelta::GetExtensionDeltasCount() const -{ - return d->extensionDeltas.size(); -} - -QList RegistryDelta::GetExtensionDeltas() const -{ - return d->extensionDeltas.toList(); -} - -QList RegistryDelta::GetExtensionDeltas(const QString& extensionPoint) const -{ - QList selectedExtDeltas; - foreach (ExtensionDelta extensionDelta, d->extensionDeltas) - { - if (extensionDelta.GetExtension()->GetExtensionPointUniqueIdentifier() == extensionPoint) - { - selectedExtDeltas.push_back(extensionDelta); - } - } - return selectedExtDeltas; -} - -ExtensionDelta RegistryDelta::GetExtensionDelta(const QString& extensionPointId, const QString& extensionId) const -{ - foreach (ExtensionDelta extensionDelta, d->extensionDeltas) - { - IExtension::Pointer extension = extensionDelta.GetExtension(); - if (extension->GetExtensionPointUniqueIdentifier() == extensionPointId && - extension->GetUniqueIdentifier() == extensionId) - { - return extensionDelta; - } - } - return ExtensionDelta(); -} - -void RegistryDelta::AddExtensionDelta(ExtensionDelta& extensionDelta) -{ - d->extensionDeltas.insert(extensionDelta); - extensionDelta.SetContainingDelta(this); -} - -QString RegistryDelta::ToString() const -{ - QString str("\n\tHost "); - str += ": ("; - int i = 0; - foreach (ExtensionDelta extensionDelta, d->extensionDeltas) - { - str += extensionDelta.ToString(); - if (i < d->extensionDeltas.size() -1) str += ", "; - } - str += ")"; - return str; -} - -void RegistryDelta::SetObjectManager(const SmartPointer& objectManager) -{ - d->objectManager = objectManager; - //TODO May want to add into the existing one here... if it is possible to have batching -} - -SmartPointer RegistryDelta::GetObjectManager() const -{ - return d->objectManager; -} - -} diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryDelta.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryDelta.h deleted file mode 100644 index e76d3e611c..0000000000 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryDelta.h +++ /dev/null @@ -1,68 +0,0 @@ -/*=================================================================== - -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 BERRYREGISTRYDELTA_H -#define BERRYREGISTRYDELTA_H - -#include -#include - -namespace berry { - -struct IObjectManager; - -class ExtensionDelta; -class RegistryDeltaData; - -/** - * The extension deltas are grouped by namespace. There is one registry delta by namespace. - */ -class RegistryDelta -{ - -public: - - RegistryDelta(); - ~RegistryDelta(); - - int GetExtensionDeltasCount() const; - - QList GetExtensionDeltas() const; - - QList GetExtensionDeltas(const QString& extensionPoint) const; - - /** - * @param extensionPointId - * @param extensionId must not be null - */ - ExtensionDelta GetExtensionDelta(const QString& extensionPointId, const QString& extensionId) const; - - void AddExtensionDelta(ExtensionDelta &extensionDelta); - - QString ToString() const; - - void SetObjectManager(const SmartPointer& objectManager); - - SmartPointer GetObjectManager() const; - -private: - - QExplicitlySharedDataPointer d; -}; - -} - -#endif // BERRYREGISTRYDELTA_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryObjectManager.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryObjectManager.cpp index 91f779dfe4..27a82600ef 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryObjectManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryObjectManager.cpp @@ -1,880 +1,888 @@ /*=================================================================== 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 NOMINMAX +#define NOMINMAX +#endif + #include "berryRegistryObjectManager.h" #include "berryConfigurationElementHandle.h" #include "berryExtension.h" #include "berryExtensionHandle.h" #include "berryExtensionPoint.h" #include "berryExtensionPointHandle.h" #include "berryInvalidRegistryObjectException.h" #include "berryRegistryObjectReferenceMap.h" #include "berryRegistryConstants.h" #include "berryRegistryContribution.h" #include "berryRegistryContributor.h" #include "berryRegistryIndexElement.h" #include "berryRegistryObject.h" #include "berryRegistryProperties.h" #include "berryTemporaryObjectManager.h" #include "berryThirdLevelConfigurationElementHandle.h" #include namespace berry { const int RegistryObjectManager::CACHE_INITIAL_SIZE = 512; -uint RegistryObjectManager::UNKNOWN = std::numeric_limits::max(); +int RegistryObjectManager::UNKNOWN = std::numeric_limits::max(); RegistryObjectManager::RegistryObjectManager(ExtensionRegistry* registry) : cache(NULL), nextId(1), orphanExtensionsLoaded(false), formerContributionsLoaded(false), contributorsLoaded(false), namespacesIndexLoaded(false), isDirty(false), fromCache(false), registry(registry) { if (RegistryProperties::GetProperty(RegistryConstants::PROP_NO_REGISTRY_FLUSHING) .compare("true", Qt::CaseInsensitive) == 0) { cache = new RegistryObjectReferenceMap(RegistryObjectReferenceMap::HARD, CACHE_INITIAL_SIZE); } else { cache = new RegistryObjectReferenceMap(RegistryObjectReferenceMap::SOFT, CACHE_INITIAL_SIZE); } } RegistryObjectManager::~RegistryObjectManager() { delete cache; } void RegistryObjectManager::Add(const SmartPointer& registryObject, bool hold) { if (registryObject->GetObjectId() == UNKNOWN) { int id = nextId++; registryObject->SetObjectId(id); } cache->Put(registryObject->GetObjectId(), registryObject); if (hold) Hold(registryObject); } SmartPointer RegistryObjectManager::GetObject(int id, short type) const { return BasicGetObject(id, type); } bool RegistryObjectManager::ShouldPersist(int id) const { RegistryObject::Pointer result = cache->Get(id); if (result.IsNotNull()) return result->ShouldPersist(); return true; } QList > RegistryObjectManager::GetObjects(const QList& values, short type) const { QMutexLocker l(&mutex); return this->GetObjects_unlocked(values, type); } QList > RegistryObjectManager::GetObjects_unlocked(const QList& values, short type) const { if (values.empty()) { return QList(); } QList results; for (int i = 0; i < values.size(); ++i) { results.push_back(BasicGetObject(values[i], type)); } return results; } SmartPointer RegistryObjectManager::GetHandle(int id, short type) const { Handle::Pointer result; switch (type) { case EXTENSION_POINT : result = new ExtensionPointHandle(IObjectManager::ConstPointer(this), id); break; case EXTENSION : result = new ExtensionHandle(IObjectManager::ConstPointer(this), id); break; case CONFIGURATION_ELEMENT : result = new ConfigurationElementHandle(IObjectManager::ConstPointer(this), id); break; case THIRDLEVEL_CONFIGURATION_ELEMENT : default : //avoid compiler error, type should always be known result = new ThirdLevelConfigurationElementHandle(IObjectManager::ConstPointer(this), id); } return result; } QList > RegistryObjectManager::GetHandles(const QList& ids, short type) const { QList results; if (ids.empty()) return results; switch (type) { case EXTENSION_POINT : for (int i = 0; i < ids.size(); i++) { Handle::Pointer handle(new ExtensionPointHandle(this, ids[i])); results.push_back(handle); } break; case EXTENSION : for (int i = 0; i < ids.size(); i++) { Handle::Pointer handle(new ExtensionHandle(this, ids[i])); results.push_back(handle); } break; case CONFIGURATION_ELEMENT : for (int i = 0; i < ids.size(); i++) { Handle::Pointer handle(new ConfigurationElementHandle(this, ids[i])); results.push_back(handle); } break; case THIRDLEVEL_CONFIGURATION_ELEMENT : for (int i = 0; i < ids.size(); i++) { Handle::Pointer handle(new ThirdLevelConfigurationElementHandle(this, ids[i])); results.push_back(handle); } break; } return results; } bool RegistryObjectManager::IsDirty() const { return isDirty; } void RegistryObjectManager::MarkDirty() { isDirty = true; } void RegistryObjectManager::Close() { //do nothing. } ExtensionRegistry* RegistryObjectManager::GetRegistry() const { return registry; } QList > RegistryObjectManager::GetExtensionsFromContributor(const QString& contributorId) const { QList ids = GetExtensionsFrom(contributorId); QList result; foreach(Handle::Pointer handle, GetHandles(ids, EXTENSION)) { result.push_back(handle.Cast()); } return result; } QList > RegistryObjectManager::GetExtensionPointsFromContributor(const QString& contributorId) const { QList ids = GetExtensionPointsFrom(contributorId); QList result; foreach(Handle::Pointer handle, GetHandles(ids, EXTENSION_POINT)) { result.push_back(handle.Cast()); } return result; } QList > RegistryObjectManager::GetExtensionPointsFromNamespace(const QString& namespaceName) const { QMutexLocker l(&mutex); RegistryIndexElement::Pointer indexElement = GetNamespaceIndex(namespaceName); QList namespaceExtensionPoints = indexElement->GetExtensionPoints(); QList result; foreach(Handle::Pointer handle, GetHandles(namespaceExtensionPoints, EXTENSION_POINT)) { result.push_back(handle.Cast()); } return result; } QList > RegistryObjectManager::GetExtensionsFromNamespace(const QString& namespaceName) const { QMutexLocker l(&mutex); RegistryIndexElement::Pointer indexElement = GetNamespaceIndex(namespaceName); QList namespaceExtensions = indexElement->GetExtensions(); // filter extensions with no extension point (orphan extensions) QList result; - QList exts = GetObjects(namespaceExtensions, EXTENSION); + QList exts = GetObjects_unlocked(namespaceExtensions, EXTENSION); for (int i = 0; i < exts.size(); i++) { Extension::Pointer ext = exts[i].Cast(); - if (GetExtensionPointObject(ext->GetExtensionPointIdentifier()).IsNotNull()) + if (GetExtensionPointObject_unlocked(ext->GetExtensionPointIdentifier()).IsNotNull()) { result.push_back(GetHandle(ext->GetObjectId(), EXTENSION).Cast()); } } return result; } -bool RegistryObjectManager::Init(long timeStamp) +bool RegistryObjectManager::Init(long /*timeStamp*/) { return false; // QMutexLocker l(&mutex); // TableReader reader = registry.getTableReader(); // Object[] results = reader.loadTables(timeStamp); // if (results == null) { // return false; // } // fileOffsets = (OffsetTable) results[0]; // extensionPoints = (HashtableOfStringAndInt) results[1]; // nextId = ((Integer) results[2]).intValue(); // fromCache = true; // if (!registry.useLazyCacheLoading()) { // //TODO Here we could grow all the tables to the right size (ReferenceMap) // reader.setHoldObjects(true); // markOrphansHasDirty(getOrphans()); // fromCache = reader.readAllCache(this); // formerContributions = getFormerContributions(); // } // return fromCache; } void RegistryObjectManager::AddContribution(const SmartPointer& contribution) { QMutexLocker l(&mutex); isDirty = true; QString Id = contribution->GetKey(); KeyedElement::Pointer existingContribution = GetFormerContributions().GetByKey(Id); if (existingContribution.IsNotNull()) { // move it from former to new contributions RemoveContribution(Id); newContributions.Add(existingContribution); } else { existingContribution = newContributions.GetByKey(Id); } if (existingContribution.IsNotNull()) // merge existingContribution.Cast()->MergeContribution(contribution); else newContributions.Add(contribution); UpdateNamespaceIndex(contribution, true); } QList RegistryObjectManager::GetExtensionPointsFrom(const QString& id) const { QMutexLocker l(&mutex); return this->GetExtensionPointsFrom_unlocked(id); } QList RegistryObjectManager::GetExtensionPointsFrom_unlocked(const QString& id) const { KeyedElement::Pointer tmp = newContributions.GetByKey(id); if (tmp.IsNull()) tmp = GetFormerContributions().GetByKey(id); if (tmp.IsNull()) return QList(); return tmp.Cast()->GetExtensionPoints(); } bool RegistryObjectManager::HasContribution(const QString& id) const { KeyedElement::Pointer result = newContributions.GetByKey(id); if (result.IsNull()) result = GetFormerContributions().GetByKey(id); return result.IsNotNull(); } void RegistryObjectManager::Remove(int id, bool release) { QMutexLocker l(&mutex); this->Remove_unlocked(id, release); } void RegistryObjectManager::Remove_unlocked(int id, bool release) { RegistryObject::Pointer toRemove = cache->Get(id); // if (fileOffsets != null) // fileOffsets.removeKey(id); if (toRemove.IsNotNull()) Remove(toRemove, release); } SmartPointer RegistryObjectManager::GetExtensionPointObject(const QString& xptUniqueId) const { QMutexLocker l(&mutex); - int id; + return this->GetExtensionPointObject_unlocked(xptUniqueId); +} + +SmartPointer RegistryObjectManager::GetExtensionPointObject_unlocked(const QString& xptUniqueId) const +{ HashtableOfStringAndInt::const_iterator idIter = extensionPoints.find(xptUniqueId); if (idIter == extensionPoints.end()) return ExtensionPoint::Pointer(); return GetObject(idIter.value(), EXTENSION_POINT).Cast(); } QList > RegistryObjectManager::GetExtensionPointsHandles() const { QMutexLocker l(&mutex); QList result; foreach(Handle::Pointer handle, GetHandles(extensionPoints.values(), EXTENSION_POINT)) { result.push_back(handle.Cast()); } return result; } SmartPointer RegistryObjectManager::GetExtensionPointHandle(const QString& xptUniqueId) { QMutexLocker l(&mutex); HashtableOfStringAndInt::const_iterator idIter = extensionPoints.find(xptUniqueId); if (idIter == extensionPoints.end()) return ExtensionPointHandle::Pointer(); return GetHandle(idIter.value(), EXTENSION_POINT).Cast(); } QList RegistryObjectManager::GetExtensionsFrom(const QString& contributorId) const { QMutexLocker l(&mutex); return this->GetExtensionsFrom_unlocked(contributorId); } QList RegistryObjectManager::GetExtensionsFrom_unlocked(const QString& contributorId) const { KeyedElement::Pointer tmp = newContributions.GetByKey(contributorId); if (tmp.IsNull()) tmp = GetFormerContributions().GetByKey(contributorId); if (tmp.IsNull()) return QList(); return tmp.Cast()->GetExtensions(); } bool RegistryObjectManager::AddExtensionPoint(const SmartPointer& currentExtPoint, bool hold) { QMutexLocker l(&mutex); QString uniqueId = currentExtPoint->GetUniqueIdentifier(); if (extensionPoints.contains(uniqueId)) return false; Add(currentExtPoint, hold); extensionPoints.insert(uniqueId, currentExtPoint->GetObjectId()); return true; } void RegistryObjectManager::RemoveExtensionPoint(const QString& extensionPointId) { QMutexLocker l(&mutex); HashtableOfStringAndInt::iterator pointIdIter = extensionPoints.find(extensionPointId); if (pointIdIter == extensionPoints.end()) return; int pointId = pointIdIter.value(); extensionPoints.erase(pointIdIter); Remove_unlocked(pointId, true); } void RegistryObjectManager::RemoveContribution(const QString& contributorId) { QMutexLocker l(&mutex); bool removed = newContributions.RemoveByKey(contributorId); if (removed == false) { removed = GetFormerContributions().RemoveByKey(contributorId); if (removed) formerContributions = GetFormerContributions(); //This forces the removed namespace to stay around, so we do not forget about removed namespaces } if (removed) { isDirty = true; return; } } void RegistryObjectManager::AddOrphans(const QString& extensionPoint, const QList& extensions) { OrphansMapType& orphans = GetOrphans(); orphans[extensionPoint].append(extensions); } void RegistryObjectManager::AddOrphan(const QString& extensionPoint, int extension) { OrphansMapType& orphans = GetOrphans(); orphans[extensionPoint].push_back(extension); } QList RegistryObjectManager::RemoveOrphans(const QString& extensionPoint) { OrphansMapType& orphans = GetOrphans(); return orphans.take(extensionPoint); } void RegistryObjectManager::RemoveOrphan(const QString& extensionPoint, int extension) { OrphansMapType& orphans = GetOrphans(); OrphansMapType::iterator existingOrphanExtensionsIter = orphans.find(extensionPoint); if (existingOrphanExtensionsIter == orphans.end()) return; existingOrphanExtensionsIter.value().removeAll(extension); if (existingOrphanExtensionsIter.value().empty()) { orphans.erase(existingOrphanExtensionsIter); } } QHash > RegistryObjectManager::GetOrphanExtensions() const { return GetOrphans(); } int RegistryObjectManager::GetNextId() const { return nextId; } HashtableOfStringAndInt RegistryObjectManager::GetExtensionPoints() const { return extensionPoints; } QList RegistryObjectManager::GetContributions() const { QList result; result.push_back(newContributions); result.push_back(GetFormerContributions()); return result; } RegistryObjectManager::ContributorsMapType& RegistryObjectManager::GetContributors() const { if (!contributorsLoaded) { if (fromCache) { //contributors = registry->GetTableReader()->LoadContributors(); } contributorsLoaded = true; } return contributors; } SmartPointer RegistryObjectManager::GetContributor(const QString& id) const { QMutexLocker l(&mutex); RegistryContributor::Pointer contributor = GetContributors().value(id); if (contributor.IsNotNull()) return contributor; // check if we have it among removed contributors - potentially // notification of removals might be processed after the contributor // marked as removed: if (!removedContributors.empty()) { return removedContributors.value(id); } return RegistryContributor::Pointer(); } void RegistryObjectManager::AddContributor(const SmartPointer& newContributor) { QMutexLocker l(&mutex); QString key = newContributor->GetActualId(); if (!GetContributors().contains(key)) { isDirty = true; if (!removedContributors.empty()) { removedContributors.remove(key); } GetContributors().insert(key, newContributor); } } void RegistryObjectManager::RemoveContributor(const QString& id) { QMutexLocker l(&mutex); isDirty = true; RegistryContributor::Pointer removed = GetContributors().take(id); if (removed.IsNotNull()) { removedContributors.insert(id, removed); } } KeyedHashSet& RegistryObjectManager::GetNamespacesIndex() const { if (!namespacesIndexLoaded) { if (fromCache) { //namespacesIndex = registry->GetTableReader()->LoadNamespaces(); } namespacesIndexLoaded = true; } return namespacesIndex; } QHash > RegistryObjectManager::GetAssociatedObjects(const QString& contributionId) const { QMutexLocker l(&mutex); //Collect all the objects associated with this contribution QList xpts = GetExtensionPointsFrom_unlocked(contributionId); QList exts = GetExtensionsFrom_unlocked(contributionId); QHash actualObjects; for (int i = 0; i < exts.size(); i++) { RegistryObject::Pointer tmp = BasicGetObject(exts[i], RegistryObjectManager::EXTENSION); actualObjects.insert(exts[i], tmp); CollectChildren(tmp, 0, actualObjects); } for (int i = 0; i < xpts.size(); i++) { RegistryObject::Pointer xpt = BasicGetObject(xpts[i], RegistryObjectManager::EXTENSION_POINT); actualObjects.insert(xpts[i], xpt); } return actualObjects; } void RegistryObjectManager::AddAssociatedObjects(QHash >& map, const SmartPointer& registryObject) { QMutexLocker l(&mutex); CollectChildren(registryObject, 0, map); } void RegistryObjectManager::AddNavigableObjects(QHash >& associatedObjects) { QMutexLocker l(&mutex); typedef QHash ObjectsMapType; ObjectsMapType result; for (ObjectsMapType::ConstIterator iter = associatedObjects.begin(); iter != associatedObjects.end(); ++iter) { const RegistryObject::Pointer& object = iter.value(); if (Extension::Pointer extension = object.Cast()) { // add extension point ExtensionPoint::Pointer extPoint = GetExtensionPointObject(extension->GetExtensionPointIdentifier()); if (extPoint.IsNull()) // already removed? continue; if (!associatedObjects.contains(extPoint->GetObjectId())) result.insert(extPoint->GetObjectId(), extPoint); // add all extensions for the extension point QList extensions = extPoint->GetRawChildren(); for (int j = 0; j < extensions.size(); j++) { RegistryObject::Pointer tmp = BasicGetObject(extensions[j], RegistryObjectManager::EXTENSION); if (tmp.IsNull()) // already removed continue; if (!associatedObjects.contains(extensions[j])) { result.insert(extensions[j], tmp); CollectChildren(tmp, 0, result); } } } else if (ExtensionPoint::Pointer extPoint = object.Cast()) { // by now extensions of this extension point have been marked as orphans OrphansMapType& orphans = GetOrphans(); QString name = extPoint->GetUniqueIdentifier(); QList extensions = orphans.value(name); for (int j = 0; j < extensions.size(); j++) { RegistryObject::Pointer tmp = BasicGetObject(extensions[j], RegistryObjectManager::EXTENSION); if (tmp.IsNull()) // already removed continue; if (!associatedObjects.contains(extensions[j])) { result.insert(extensions[j], tmp); CollectChildren(tmp, 0, result); } } } } for (ObjectsMapType::ConstIterator iter = result.begin(); iter != result.end(); ++iter) { associatedObjects.insert(iter.key(), iter.value()); } } void RegistryObjectManager::RemoveObjects(const QHash >& associatedObjects) { QMutexLocker l(&mutex); //Remove the objects from the main object manager so they can no longer be accessed. foreach (RegistryObject::Pointer toRemove, associatedObjects) { Remove(toRemove->GetObjectId(), true); if (ExtensionPoint::Pointer extPoint = toRemove.Cast()) { RemoveExtensionPoint(extPoint->GetUniqueIdentifier()); } } } SmartPointer RegistryObjectManager::CreateDelegatingObjectManager(const QHash > &object) { IObjectManager::Pointer objMgr(new TemporaryObjectManager(object, this)); return objMgr; } bool RegistryObjectManager::UnlinkChildFromContributions(int id) { QMutexLocker l(&mutex); if (UnlinkChildFromContributions(newContributions.Elements(), id)) return true; return UnlinkChildFromContributions(GetFormerContributions().Elements(), id); } QString RegistryObjectManager::FindCommonNamespaceIdentifier(const QList >& registryObjects) const { QString namespaceName; for (int i = 0; i < registryObjects.size(); i++) { RegistryObject::Pointer currentObject = registryObjects[i]; QString tmp; if (ExtensionPoint::Pointer extPoint = currentObject.Cast()) { tmp = extPoint->GetNamespace(); } else if (Extension::Pointer extension = currentObject.Cast()) { tmp = extension->GetNamespaceIdentifier(); } if (namespaceName.isNull()) { namespaceName = tmp; continue; } if (namespaceName != tmp) { return QString(); } } return namespaceName; } void RegistryObjectManager::RemoveExtensionPointFromNamespaceIndex(int extensionPoint, const QString& namespaceName) { QMutexLocker l(&mutex); RegistryIndexElement::Pointer indexElement = GetNamespaceIndex(namespaceName); indexElement->UpdateExtensionPoint(extensionPoint, false); } void RegistryObjectManager::RemoveExtensionFromNamespaceIndex(int extensions, const QString& namespaceName) { QMutexLocker l(&mutex); RegistryIndexElement::Pointer indexElement = GetNamespaceIndex(namespaceName); indexElement->UpdateExtension(extensions, false); } void RegistryObjectManager::UpdateNamespaceIndex(const SmartPointer& contribution, bool added) { // if all extension points are from the same namespace combine them in one block and add them all together QList contribExtensionPoints = contribution->GetExtensionPoints(); QList extensionPointObjects = GetObjects_unlocked(contribExtensionPoints, EXTENSION_POINT); QString commonExptsNamespace; if (contribExtensionPoints.size() > 1) { commonExptsNamespace = FindCommonNamespaceIdentifier(extensionPointObjects); } if (!commonExptsNamespace.isEmpty()) { RegistryIndexElement::Pointer indexElement = GetNamespaceIndex(commonExptsNamespace); indexElement->UpdateExtensionPoints(contribExtensionPoints, added); } else { for (int i = 0; i < contribExtensionPoints.size(); i++) { QString namespaceName = extensionPointObjects[i].Cast()->GetNamespace(); RegistryIndexElement::Pointer indexElement = GetNamespaceIndex(namespaceName); indexElement->UpdateExtensionPoint(contribExtensionPoints[i], added); } } // if all extensions are from the same namespace combine them in one block and add them all together QList contrExtensions = contribution->GetExtensions(); QList extensionObjects = GetObjects_unlocked(contrExtensions, EXTENSION); QString commonExtNamespace; if (contrExtensions.size() > 1) { commonExtNamespace = FindCommonNamespaceIdentifier(extensionObjects); } if (!commonExtNamespace.isEmpty()) { RegistryIndexElement::Pointer indexElement = GetNamespaceIndex(commonExtNamespace); indexElement->UpdateExtensions(contrExtensions, added); } else { for (int i = 0; i < contrExtensions.size(); i++) { QString namespaceName = extensionObjects[i].Cast()->GetNamespaceIdentifier(); RegistryIndexElement::Pointer indexElement = GetNamespaceIndex(namespaceName); indexElement->UpdateExtension(contrExtensions[i], added); } } } KeyedHashSet& RegistryObjectManager::GetFormerContributions() const { if (!formerContributionsLoaded) { if (fromCache) { //formerContributions = registry->GetTableReader()->LoadContributions(); } formerContributionsLoaded = true; } return formerContributions; } void RegistryObjectManager::Remove(const SmartPointer& registryObject, bool release) { cache->Remove(registryObject->GetObjectId()); if (release) Release(registryObject); } void RegistryObjectManager::Hold(const SmartPointer& toHold) { heldObjects.Add(toHold); } void RegistryObjectManager::Release(const SmartPointer& toRelease) { heldObjects.Remove(toRelease); } SmartPointer RegistryObjectManager::BasicGetObject(int id, short type) const { RegistryObject::Pointer result = cache->Get(id); if (result.IsNotNull()) return result; if (fromCache) result = Load(id, type); if (result.IsNull()) throw InvalidRegistryObjectException(); cache->Put(id, result); return result; } -SmartPointer RegistryObjectManager::Load(int id, short type) const +SmartPointer RegistryObjectManager::Load(int /*id*/, short /*type*/) const { // TableReader reader = registry.getTableReader(); // if (fileOffsets == null) // return null; // int offset = fileOffsets.get(id); // if (offset == Integer.MIN_VALUE) // return null; // switch (type) { // case CONFIGURATION_ELEMENT : // return reader.loadConfigurationElement(offset); // case THIRDLEVEL_CONFIGURATION_ELEMENT : // return reader.loadThirdLevelConfigurationElements(offset, this); // case EXTENSION : // return reader.loadExtension(offset); // case EXTENSION_POINT : // default : //avoid compile errors. type must always be known // return reader.loadExtensionPointTree(offset, this); // } return RegistryObject::Pointer(); } RegistryObjectManager::OrphansMapType& RegistryObjectManager::GetOrphans() const { if (!orphanExtensionsLoaded) { if(fromCache) { //orphanExtensions = registry->GetTableReader()->LoadOrphans(); } orphanExtensionsLoaded = true; } return orphanExtensions; } SmartPointer RegistryObjectManager::GetNamespaceIndex(const QString& namespaceName) const { RegistryIndexElement::Pointer indexElement = GetNamespacesIndex().GetByKey(namespaceName).Cast(); if (indexElement.IsNull()) { indexElement = new RegistryIndexElement(namespaceName); namespacesIndex.Add(indexElement); } return indexElement; } void RegistryObjectManager::CollectChildren(const SmartPointer& ce, int level, QHash >& collector) const { QList children = GetObjects(ce->GetRawChildren(), level == 0 || ce->NoExtraData() ? RegistryObjectManager::CONFIGURATION_ELEMENT : RegistryObjectManager::THIRDLEVEL_CONFIGURATION_ELEMENT); for (int j = 0; j < children.size(); j++) { collector.insert(children[j]->GetObjectId(), children[j]); CollectChildren(children[j], level + 1, collector); } } bool RegistryObjectManager::UnlinkChildFromContributions(const QList >& contributions, int id) { for (int i = 0; i < contributions.size(); i++) { RegistryContribution::Pointer candidate = contributions[i].Cast(); if (candidate.IsNull()) continue; if (candidate->HasChild(id)) { candidate->UnlinkChild(id); if (candidate->IsEmpty()) RemoveContribution(candidate->GetContributorId()); return true; } } return false; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryObjectManager.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryObjectManager.h index a1cae59657..91c9048660 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryObjectManager.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryObjectManager.h @@ -1,284 +1,285 @@ /*=================================================================== 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 BERRYREGISTRYOBJECTMANAGER_H #define BERRYREGISTRYOBJECTMANAGER_H #include "berryIObjectManager.h" #include "berryHashtableOfStringAndInt.h" #include "berryKeyedHashSet.h" #include namespace berry { class ExtensionHandle; class ExtensionPoint; class ExtensionPointHandle; class ExtensionRegistry; class RegistryContribution; class RegistryContributor; class RegistryIndexElement; class RegistryObject; class RegistryObjectReferenceMap; /** * This class manage all the object from the registry but does not deal with their dependencies. * It serves the objects which are either directly obtained from memory or read from a cache. * It also returns handles for objects. */ class RegistryObjectManager : public IObjectManager { public: berryObjectMacro(berry::RegistryObjectManager) //Constants used to get the objects and their handles enum Type { CONFIGURATION_ELEMENT = 1, EXTENSION, EXTENSION_POINT, THIRDLEVEL_CONFIGURATION_ELEMENT }; RegistryObjectManager(ExtensionRegistry* registry); ~RegistryObjectManager(); void Add(const SmartPointer& registryObject, bool hold); SmartPointer GetObject(int id, short type) const; // The current impementation of this method assumes that we don't cache dynamic // extension. In this case all extensions not yet loaded (i.e. not in the memory cache) // are "not dynamic" and we actually check memory objects to see if they are dynamic. // // If we decide to allow caching of dynamic objects, the implementation // of this method would have to retrieved the object from disk and check // its "dynamic" status. The problem is that id alone is not enough to get the object // from the disk; object type is needed as well. bool ShouldPersist(int id) const; QList > GetObjects(const QList& values, short type) const; SmartPointer GetHandle(int id, short type) const; QList > GetHandles(const QList& ids, short type) const; bool IsDirty() const; void MarkDirty(); void Close(); ExtensionRegistry* GetRegistry() const; QList > GetExtensionsFromContributor(const QString& contributorId) const; QList > GetExtensionPointsFromContributor(const QString& contributorId) const; QList > GetExtensionPointsFromNamespace(const QString& namespaceName) const; // This method filters out extensions with no extension point QList > GetExtensionsFromNamespace(const QString& namespaceName) const; SmartPointer GetContributor(const QString& id) const; protected: friend class Extension; friend class ExtensionPoint; friend class ExtensionRegistry; friend class ExtensionsParser; friend class RegistryContribution; friend class RegistryObject; mutable QMutex mutex; static const int CACHE_INITIAL_SIZE; // = 512; - static uint UNKNOWN; + static int UNKNOWN; typedef QHash > OrphansMapType; typedef QHash > ContributorsMapType; /** * Initialize the object manager. Return true if the initialization succeeded, false otherwise */ bool Init(long timeStamp); void AddContribution(const SmartPointer& contribution); QList GetExtensionPointsFrom(const QString& id) const; QList GetExtensionPointsFrom_unlocked(const QString& id) const; bool HasContribution(const QString& id) const; void Remove(int id, bool release); void Remove_unlocked(int id, bool release); QList > GetObjects_unlocked(const QList& values, short type) const; SmartPointer GetExtensionPointObject(const QString& xptUniqueId) const; + SmartPointer GetExtensionPointObject_unlocked(const QString& xptUniqueId) const; QList > GetExtensionPointsHandles() const; SmartPointer GetExtensionPointHandle(const QString& xptUniqueId); QList GetExtensionsFrom(const QString& contributorId) const; QList GetExtensionsFrom_unlocked(const QString& contributorId) const; bool AddExtensionPoint(const SmartPointer& currentExtPoint, bool hold); void RemoveExtensionPoint(const QString& extensionPointId); void RemoveContribution(const QString &contributorId); void AddOrphans(const QString& extensionPoint, const QList& extensions); void AddOrphan(const QString& extensionPoint, int extension); QList RemoveOrphans(const QString& extensionPoint); void RemoveOrphan(const QString& extensionPoint, int extension); //This method is only used by the writer to reach in QHash > GetOrphanExtensions() const; // This method is only used by the writer to reach in int GetNextId() const; // This method is only used by the writer to reach in HashtableOfStringAndInt GetExtensionPoints() const; // This method is only used by the writer to reach in QList GetContributions() const; // This method is used internally and by the writer to reach in. Notice that it doesn't // return contributors marked as removed. ContributorsMapType& GetContributors() const; // only adds a contributor if it is not already present in the table void AddContributor(const SmartPointer& newContributor); void RemoveContributor(const QString& id); KeyedHashSet& GetNamespacesIndex() const; /** * Collect all the objects that are removed by this operation and store * them in a IObjectManager so that they can be accessed from the appropriate * deltas but not from the registry. */ QHash > GetAssociatedObjects(const QString& contributionId) const; /** * Adds elements to be removed along with the registry object. */ void AddAssociatedObjects(QHash >& map, const SmartPointer& registryObject); /** * Add to the set of the objects all extensions and extension points that * could be navigated to from the objects in the set. */ void AddNavigableObjects(QHash >& associatedObjects); void RemoveObjects(const QHash >& associatedObjects); SmartPointer CreateDelegatingObjectManager(const QHash >& object); bool UnlinkChildFromContributions(int id); private: // key: extensionPointName, value: object id HashtableOfStringAndInt extensionPoints; //This is loaded on startup. Then entries can be added when loading a new plugin from the xml. // key: object id, value: an object RegistryObjectReferenceMap* cache; //Entries are added by getter. The structure is not thread safe. //key: int, value: int //OffsetTable fileOffsets = null; //This is read once on startup when loading from the cache. Entries are never added here. They are only removed to prevent "removed" objects to be reloaded. int nextId; //This is only used to get the next number available. mutable bool orphanExtensionsLoaded; //Those two data structures are only used when the addition or the removal of a plugin occurs. //They are used to keep track on a contributor basis of the extension being added or removed KeyedHashSet newContributions; //represents the contributers added during this session. mutable KeyedHashSet formerContributions; //represents the contributers encountered in previous sessions. This is loaded lazily. mutable bool formerContributionsLoaded; mutable QHash > contributors; // key: contributor ID; value: contributor name mutable bool contributorsLoaded; QHash > removedContributors; // key: contributor ID; value: contributor name mutable KeyedHashSet namespacesIndex; // registry elements (extension & extensionpoints) indexed by namespaces mutable bool namespacesIndexLoaded; // Map key: extensionPointFullyQualifiedName, value int[] of orphan extensions. // The orphan access does not need to be synchronized because the it is protected by the lock in extension registry. mutable QHash > orphanExtensions; KeyedHashSet heldObjects; //strong reference to the objects that must be hold on to //Indicate if objects have been removed or added from the table. This only needs to be set in a couple of places (addNamespace and removeNamespace) bool isDirty; bool fromCache; ExtensionRegistry* registry; // TODO make ExtensionPoint, Extension provide namespace in a same way (move it to the RegistryObject?) // See if all the registryObjects have the same namespace. If not, return null. // Also can return null if empty array is passed in or objects are of an unexpected type QString FindCommonNamespaceIdentifier(const QList >& registryObjects) const; void RemoveExtensionPointFromNamespaceIndex(int extensionPoint, const QString& namespaceName); void RemoveExtensionFromNamespaceIndex(int extensions, const QString& namespaceName); // Called from a synchronized method void UpdateNamespaceIndex(const SmartPointer& contribution, bool added); KeyedHashSet& GetFormerContributions() const; void Remove(const SmartPointer& registryObject, bool release); void Hold(const SmartPointer& toHold); void Release(const SmartPointer& toRelease); SmartPointer BasicGetObject(int id, short type) const; SmartPointer Load(int id, short type) const; OrphansMapType& GetOrphans() const; // Find or create required index element SmartPointer GetNamespaceIndex(const QString& namespaceName) const; void CollectChildren(const SmartPointer& ce, int level, QHash >& collector) const; // Called from a synchronized method only bool UnlinkChildFromContributions(const QList >& contributions, int id); }; } #endif // BERRYREGISTRYOBJECTMANAGER_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryObjectReferenceMap.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryObjectReferenceMap.cpp index 813e5bee2d..147e7254e9 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryObjectReferenceMap.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryObjectReferenceMap.cpp @@ -1,157 +1,158 @@ /*=================================================================== 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 "berryRegistryObjectReferenceMap.h" #include "berryRegistryObject.h" namespace berry { struct RegistryObjectReferenceMap::IEntry { virtual ~IEntry() {} /** * Returns the value of this entry. * @return The entry value. */ virtual SmartPointer GetValue() const = 0; }; class RegistryObjectReferenceMap::SmartRef : public RegistryObjectReferenceMap::IEntry { private: /** * Reference value. Note this can never be null. */ RegistryObject::Pointer value; public: SmartRef(const RegistryObject::Pointer value) : value(value) { } RegistryObject::Pointer GetValue() const { return value; } }; class RegistryObjectReferenceMap::WeakRef : public RegistryObjectReferenceMap::IEntry { private: /** * Reference value. Note this can never be null. */ RegistryObject::WeakPtr value; public: WeakRef(const RegistryObject::Pointer value) : value(value) { } RegistryObject::Pointer GetValue() const { return value.Lock(); } }; RegistryObjectReferenceMap::RegistryObjectReferenceMap(ReferenceType referenceType, int capacity) : valueType(referenceType) { references.reserve(capacity); } RegistryObjectReferenceMap::~RegistryObjectReferenceMap() { for(ReferenceMapType::Iterator i = references.begin(); i != references.end(); ++i) { delete i.value(); } } SmartPointer RegistryObjectReferenceMap::Get(int key) const { Purge(); ReferenceMapType::const_iterator entry = references.find(key); if (entry != references.end()) return entry.value()->GetValue(); return RegistryObject::Pointer(); } void RegistryObjectReferenceMap::Put(int key, const SmartPointer& value) { if (value.IsNull()) throw ctkInvalidArgumentException("null values not allowed"); Purge(); ReferenceMapType::Iterator i = references.find(key); if (i != references.end()) { delete *i; } references.insert(key, NewEntry(value)); } SmartPointer RegistryObjectReferenceMap::Remove(int key) { Purge(); IEntry* entry = references.take(key); RegistryObject::Pointer obj = entry->GetValue(); delete entry; return obj; } RegistryObjectReferenceMap::IEntry* RegistryObjectReferenceMap::NewEntry(const SmartPointer& value) const { switch (valueType) { case HARD : return new SmartRef(value); case SOFT : return new WeakRef(value); + default: return NULL; } } void RegistryObjectReferenceMap::Purge() const { for (ReferenceMapType::Iterator i = references.begin(); i != references.end();) { if (i.value()->GetValue().IsNull()) { i = references.erase(i); } else { ++i; } } } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryStrategy.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryStrategy.cpp index 166b6ec938..b98281bf9a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryStrategy.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryRegistryStrategy.cpp @@ -1,272 +1,272 @@ /*=================================================================== 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 "berryRegistryStrategy.h" #include "berryCoreException.h" #include "berryCTKPluginListener.h" #include "berryExtensionRegistry.h" #include "berryExtensionType.h" #include "berryRegistryConstants.h" #include "berryRegistryContributor.h" #include "berryRegistryMessages.h" #include "berryRegistrySupport.h" #include "berryStatus.h" #include "berryLog.h" #include "berryCTKPluginActivator.h" #include "berryCTKPluginUtils.h" #include #include #include #include #include #include namespace berry { RegistryStrategy::RegistryStrategy(const QList& storageDirs, const QList& cacheReadOnly, QObject* key) : storageDirs(storageDirs), cacheReadOnly(cacheReadOnly), token(key), trackTimestamp(false) { // Only do timestamp calculations if osgi.checkConfiguration is set to "true" (typically, // this implies -dev mode) ctkPluginContext* context = org_blueberry_core_runtime_Activator::getPluginContext(); if (context) { trackTimestamp = context->getProperty(RegistryConstants::PROP_CHECK_CONFIG).toString().compare("true", Qt::CaseInsensitive) == 0; } } RegistryStrategy::~RegistryStrategy() { } int RegistryStrategy::GetLocationsLength() const { return storageDirs.size(); } QString RegistryStrategy::GetStorage(int index) const { return storageDirs[index]; } bool RegistryStrategy::IsCacheReadOnly(int index) const { if (!cacheReadOnly.empty()) return cacheReadOnly[index]; return true; } void RegistryStrategy::Log(const SmartPointer& status) { RegistrySupport::Log(status, QString()); } QString RegistryStrategy::Translate(const QString& key, QTranslator* resources) { return RegistrySupport::Translate(key, resources); } void RegistryStrategy::OnStart(IExtensionRegistry* reg, bool loadedFromCache) { ExtensionRegistry* registry = dynamic_cast(reg); if (registry == NULL) return; // register a listener to catch new plugin installations/resolutions. pluginListener.reset(new CTKPluginListener(registry, token, this)); org_blueberry_core_runtime_Activator::getPluginContext()->connectPluginListener( pluginListener.data(), SLOT(PluginChanged(ctkPluginEvent)), Qt::DirectConnection); // populate the registry with all the currently installed plugins. // There is a small window here while ProcessPlugins is being // called where the pluginListener may receive a ctkPluginEvent // to add/remove a plugin from the registry. This is ok since // the registry is a synchronized object and will not add the // same bundle twice. if (!loadedFromCache) pluginListener->ProcessPlugins(org_blueberry_core_runtime_Activator::getPluginContext()->getPlugins()); } -void RegistryStrategy::OnStop(IExtensionRegistry* registry) +void RegistryStrategy::OnStop(IExtensionRegistry* /*registry*/) { if (!pluginListener.isNull()) { org_blueberry_core_runtime_Activator::getPluginContext()->disconnectPluginListener(pluginListener.data()); } } QObject* RegistryStrategy::CreateExecutableExtension(const SmartPointer& contributor, const QString& className, const QString& /*overridenContributorName*/) { QObject* result = NULL; QSharedPointer plugin = CTKPluginUtils::GetDefault()->GetPlugin(contributor->GetName()); if (!plugin.isNull()) { // immediately start the plugin but do not change the plugins autostart setting plugin->start(ctkPlugin::START_TRANSIENT); } else { QString message = QString("Unable to find plugin \"%1\" for contributor \"%2\".") .arg(contributor->GetName()).arg(contributor->GetActualName()); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, RegistryConstants::PLUGIN_ERROR, message, BERRY_STATUS_LOC)); throw CoreException(status); } QString typeName = contributor->GetActualName() + "_" + className; int extensionTypeId = ExtensionType::type(typeName.toAscii().data()); if (extensionTypeId == 0) { QString message = QString("Unable to find class \"%1\" from contributor \"%2\"." " The class was either not registered via " "BERRY_REGISTER_EXTENSION_CLASS(type, pluginContext) " "or you forgot to run Qt's moc on the header file.") .arg(className).arg(contributor->GetActualName()); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, RegistryConstants::PLUGIN_ERROR, message, BERRY_STATUS_LOC)); throw CoreException(status); } else { try { result = ExtensionType::construct(extensionTypeId); } catch (const ctkException& e) { QString message = QString("Contributor \"%1\" was unable to instantiate class \"%2\".") .arg(contributor->GetActualName()).arg(className); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, RegistryConstants::PLUGIN_ERROR, message, e, BERRY_STATUS_LOC)); throw CoreException(status); } catch (const std::exception& e) { QString message = QString("Contributor \"%1\" was unable to instantiate class \"%2\". Error: \"%3\"") .arg(contributor->GetActualName()).arg(className).arg(QString(e.what())); IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, RegistryMessages::OWNER_NAME, RegistryConstants::PLUGIN_ERROR, message, BERRY_STATUS_LOC)); throw CoreException(status); } } return result; } //void RegistryStrategy::ScheduleChangeEvent(const QList& listeners, // const QHash& deltas, // IExtensionRegistry* registry) //{ // if (ExtensionRegistry* extRegistry = dynamic_cast(registry)) // extRegistry->ScheduleChangeEvent(listeners, deltas); //} //SmartPointer RegistryStrategy::ProcessChangeEvent(const QList& listeners, // const QHash& deltas, // IExtensionRegistry* registry) //{ // if (ExtensionRegistry* extRegistry = dynamic_cast(registry)) // return extRegistry->ProcessChangeEvent(listeners, deltas); // return IStatus::Pointer(); //} bool RegistryStrategy::Debug() const { return false; } bool RegistryStrategy::DebugRegistryEvents() const { return false; } bool RegistryStrategy::CacheUse() const { return true; } bool RegistryStrategy::CacheLazyLoading() const { return true; } long RegistryStrategy::GetContainerTimestamp() const { return 0; } long RegistryStrategy::GetContributionsTimestamp() const { return 0; } bool RegistryStrategy::CheckContributionsTimestamp() const { return trackTimestamp; } long RegistryStrategy::GetExtendedTimestamp(const QSharedPointer& plugin, const QString& pluginManifest) const { if (pluginManifest.isEmpty()) return 0; // The plugin manifest does not have a timestamp as it is embedded into // the plugin itself. Try to get the timestamp of the plugin instead. QFileInfo pluginInfo(QUrl(plugin->getLocation()).toLocalFile()); if (pluginInfo.exists()) { return ctk::msecsTo(QDateTime::fromTime_t(0), pluginInfo.lastModified()) + plugin->getPluginId(); //return pluginManifest.openConnection().getLastModified() + bundle.getBundleId(); } else { if (Debug()) { BERRY_DEBUG << "Unable to obtain timestamp for the plugin " << plugin->getSymbolicName(); } return 0; } } QXmlReader* RegistryStrategy::GetXMLParser() const { if (theXMLParser.isNull()) { theXMLParser.reset(new QXmlSimpleReader()); } return theXMLParser.data(); } QList RegistryStrategy::Translate(const QList& nonTranslated, - const SmartPointer& contributor, - const QLocale& locale) + const SmartPointer& /*contributor*/, + const QLocale& /*locale*/) { return nonTranslated; } QLocale RegistryStrategy::GetLocale() const { return QLocale(); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryTemporaryObjectManager.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryTemporaryObjectManager.cpp index 3c40d250a1..07d9a91723 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryTemporaryObjectManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryTemporaryObjectManager.cpp @@ -1,133 +1,133 @@ /*=================================================================== 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 "berryTemporaryObjectManager.h" #include "berryRegistryObjectManager.h" #include "berryExtensionHandle.h" #include "berryExtensionPointHandle.h" #include "berryInvalidRegistryObjectException.h" #include "berryRegistryObject.h" #include "berryThirdLevelConfigurationElementHandle.h" namespace berry { TemporaryObjectManager::TemporaryObjectManager(const QHash >& actualObjects, RegistryObjectManager* parent) : actualObjects(actualObjects), parent(parent) { } SmartPointer TemporaryObjectManager::GetHandle(int id, short type) const { Handle::Pointer handle; switch (type) { case RegistryObjectManager::EXTENSION_POINT : handle = new ExtensionPointHandle(IObjectManager::ConstPointer(this), id); return handle; case RegistryObjectManager::EXTENSION : handle = new ExtensionHandle(IObjectManager::ConstPointer(this), id); return handle; case RegistryObjectManager::CONFIGURATION_ELEMENT : handle = new ConfigurationElementHandle(IObjectManager::ConstPointer(this), id); return handle; case RegistryObjectManager::THIRDLEVEL_CONFIGURATION_ELEMENT : default : //avoid compiler error, type should always be known handle = new ThirdLevelConfigurationElementHandle(IObjectManager::ConstPointer(this), id); return handle; } } QList > TemporaryObjectManager::GetHandles(const QList& ids, short type) const { QList results; switch (type) { case RegistryObjectManager::EXTENSION_POINT : for (int i = 0; i < ids.size(); i++) { Handle::Pointer handle(new ExtensionPointHandle(IObjectManager::ConstPointer(this), ids[i])); results.push_back(handle); } break; case RegistryObjectManager::EXTENSION : for (int i = 0; i < ids.size(); i++) { Handle::Pointer handle(new ExtensionHandle(IObjectManager::ConstPointer(this), ids[i])); results.push_back(handle); } break; case RegistryObjectManager::CONFIGURATION_ELEMENT : for (int i = 0; i < ids.size(); i++) { Handle::Pointer handle(new ConfigurationElementHandle(IObjectManager::ConstPointer(this), ids[i])); results.push_back(handle); } break; case RegistryObjectManager::THIRDLEVEL_CONFIGURATION_ELEMENT : for (int i = 0; i < ids.size(); i++) { Handle::Pointer handle(new ThirdLevelConfigurationElementHandle(IObjectManager::ConstPointer(this), ids[i])); results.push_back(handle); } break; } return results; } SmartPointer TemporaryObjectManager::GetObject(int id, short type) const { QMutexLocker l(&mutex); RegistryObject::Pointer result; try { result = parent->GetObject(id, type); } - catch (const InvalidRegistryObjectException& e) + catch (const InvalidRegistryObjectException& /*e*/) { result = actualObjects.value(id); } if (result.IsNull()) throw InvalidRegistryObjectException(); return result; } QList > TemporaryObjectManager::GetObjects(const QList& values, short type) const { QMutexLocker l(&mutex); QList results; for (int i = 0; i < values.size(); i++) { results.push_back(GetObject(values[i], type)); } return results; } void TemporaryObjectManager::Close() { QMutexLocker l(&mutex); actualObjects.clear(); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryThirdLevelConfigurationElementHandle.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryThirdLevelConfigurationElementHandle.h index b6ada9469f..287fd47af0 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryThirdLevelConfigurationElementHandle.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryThirdLevelConfigurationElementHandle.h @@ -1,44 +1,45 @@ /*=================================================================== 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 BERRYTHIRDLEVELCONFIGURATIONELEMENTHANDLE_H #define BERRYTHIRDLEVELCONFIGURATIONELEMENTHANDLE_H #include "berryConfigurationElementHandle.h" namespace berry { class ThirdLevelConfigurationElementHandle : public ConfigurationElementHandle { public: berryObjectMacro(berry::ThirdLevelConfigurationElementHandle) ThirdLevelConfigurationElementHandle(const SmartPointer& objectManager, int id); ThirdLevelConfigurationElementHandle(const IObjectManager* objectManager, int id); + using ConfigurationElementHandle::GetChildren; QList > GetChildren() const; protected: SmartPointer GetConfigurationElement() const; }; } #endif // BERRYTHIRDLEVELCONFIGURATIONELEMENTHANDLE_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIConfigurationElement.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIConfigurationElement.h index 83d4706ea8..5562e42e85 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIConfigurationElement.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIConfigurationElement.h @@ -1,302 +1,304 @@ /*=================================================================== 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 BERRYIEXTENSIONELEMENT_H_ #define BERRYIEXTENSIONELEMENT_H_ #include #include namespace berry { struct IContributor; struct IExtension; class Handle; /** * A configuration element, with its attributes and children, * directly reflects the content and structure of the extension section * within the declaring plug-in's manifest (plugin.xml) file. *

* This interface also provides a way to create executable extension * objects. *

*

* These registry objects are intended for relatively short-term use. Clients that * deal with these objects must be aware that they may become invalid if the * declaring plug-in is updated or uninstalled. If this happens, all methods except * {@link #IsValid()} will throw {@link InvalidRegistryObjectException}. * For configuration element objects, the most common case is code in a plug-in dealing * with extensions contributed to one of the extension points it declares. * Code in a plug-in that has declared that it is not dynamic aware (or not * declared anything) can safely ignore this issue, since the registry * would not be modified while it is active. However, code in a plug-in that * declares that it is dynamic aware must be careful when accessing the extension * and configuration element objects because they become invalid if the contributing * plug-in is removed. Similarly, tools that analyze or display the extension registry * are vulnerable. Client code can pre-test for invalid objects by calling {@link #IsValid()}, * which never throws this exception. However, pre-tests are usually not sufficient * because of the possibility of the extension or configuration element object becoming * invalid as a result of a concurrent activity. At-risk clients must treat * InvalidRegistryObjectException as if it were a checked exception. * Also, such clients should probably register a listener with the extension registry * so that they receive notification of any changes to the registry. *

* This interface is not intended to be implemented by clients. *

* @noimplement This interface is not intended to be implemented by clients. */ struct org_blueberry_core_runtime_EXPORT IConfigurationElement : public virtual Object { - berryInterfaceMacro(IConfigurationElement, berry) + berryObjectMacro(berry::IConfigurationElement) virtual ~IConfigurationElement(); /** * Creates and returns a new instance of the executable extension * identified by the named attribute of this configuration element. * The named attribute value must contain a fully qualified name * of a class. The class can either refer to a class implementing * the executable extension or to a factory capable of returning the * executable extension. *

* The specified class is instantiated using its 0-argument public constructor. *

* Then the following checks are done:
* If the specified class implements the {@link IExecutableExtension} * interface, the method {@link IExecutableExtension#SetInitializationData(IConfigurationElement, QString, Object*)} * is called, passing to the object the configuration information that was used to create it. *

* If the specified class implements {@link IExecutableExtensionFactory} * interface, the method {@link IExecutableExtensionFactory#Create()} * is invoked. *

*

* Unlike other methods on this object, invoking this method may activate * the plug-in. *

* * @param propertyName the name of the property * @return the executable instance * @exception CoreException if an instance of the executable extension * could not be created for any reason * @see IExecutableExtension#SetInitializationData(IConfigurationElement, QString, Object*) * @see IExecutableExtensionFactory * @throws InvalidRegistryObjectException if this configuration element is no longer valid */ virtual QObject* CreateExecutableExtension(const QString& propertyName) const = 0; template C* CreateExecutableExtension(const QString &propertyName) const { C* interface = qobject_cast(this->CreateExecutableExtension(propertyName)); if (interface == 0) { BERRY_WARN << "The QObject subclass " << this->GetAttribute(propertyName).toStdString() << " does not seem to implement the required interface \"" - << qobject_interface_iid() << "\", or you forgot the Q_INTERFACES macro."; + << qobject_interface_iid() << "\", or you forgot the Q_INTERFACES macro."; } return interface; } /** * Returns the named attribute of this configuration element, or * null if none. *

* The names of configuration element attributes * are the same as the attribute names of the corresponding XML element. * For example, the configuration markup *

    * <bg pattern="stripes"/>
    * 
* corresponds to a configuration element named "bg" * with an attribute named "pattern" * with attribute value "stripes". *

*

Note that any translation specified in the plug-in manifest * file is automatically applied. *

* * @param name the name of the attribute * @return attribute value, or null if none * @throws InvalidRegistryObjectException if this configuration element is no longer valid */ virtual QString GetAttribute(const QString& name) const = 0; /** * Returns the names of the attributes of this configuration element. * Returns an empty list if this configuration element has no attributes. *

* The names of configuration element attributes * are the same as the attribute names of the corresponding XML element. * For example, the configuration markup *

    * <bg color="blue" pattern="stripes"/>
    * 
* corresponds to a configuration element named "bg" * with attributes named "color" * and "pattern". *

* * @return the names of the attributes * @throws InvalidRegistryObjectException if this configuration element is no longer valid */ virtual QList GetAttributeNames() const = 0; /** * Returns all configuration elements that are children of this * configuration element. * Returns an empty list if this configuration element has no children. *

* Each child corresponds to a nested * XML element in the configuration markup. * For example, the configuration markup *

    * <view>
    *     <verticalHint>top</verticalHint>
    *     <horizontalHint>left</horizontalHint>
    * </view>
    * 
* corresponds to a configuration element, named "view", * with two children. *

* * @return the child configuration elements * @throws InvalidRegistryObjectException if this configuration element is no longer valid * @see #getChildren(String) */ virtual QList GetChildren() const = 0; /** * Returns all child configuration elements with the given name. * Returns an empty list if this configuration element has no children * with the given name. * * @param name the name of the child configuration element * @return the child configuration elements with that name * @throws InvalidRegistryObjectException if this configuration element is no longer valid * @see #getChildren() */ virtual QList GetChildren(const QString& name) const = 0; /** * Returns the extension that declares this configuration element. * * @return the extension * @throws InvalidRegistryObjectException if this configuration element is no longer valid */ virtual SmartPointer GetDeclaringExtension() const = 0; /** * Returns the name of this configuration element. * The name of a configuration element is the same as * the XML tag of the corresponding XML element. * For example, the configuration markup *
    * <wizard name="Create Project"/>
    * 
* corresponds to a configuration element named "wizard". * * @return the name of this configuration element * @throws InvalidRegistryObjectException if this configuration element is no longer valid */ virtual QString GetName() const = 0; /** * Returns the element which contains this element. If this element * is an immediate child of an extension, the * returned value can be downcast to IExtension. * Otherwise the returned value can be downcast to * IConfigurationElement. * * @return the parent of this configuration element * or null * @throws InvalidRegistryObjectException if this configuration element is no longer valid */ virtual SmartPointer GetParent() const = 0; /** * Returns the text value of this configuration element. * For example, the configuration markup *
    * <script lang="javascript">.\scripts\cp.js</script>
    * 
* corresponds to a configuration element "script" * with value ".\scripts\cp.js". *

Values may span multiple lines (i.e., contain carriage returns * and/or line feeds). *

Note that any translation specified in the plug-in manifest * file is automatically applied. *

* * @return the text value of this configuration element or null * @throws InvalidRegistryObjectException if this configuration element is no longer valid */ virtual QString GetValue() const = 0; /** * When multi-language support is enabled, this method returns the text value of this * configuration element in the specified locale, or null if none. *

* The locale matching tries to find the best match between available translations and * the requested locale, falling back to a more generic locale ("en") when the specific * locale ("en_US") is not available. *

* If multi-language support is not enabled, this method is equivalent to the method * {@link #getValue()}. *

* @param locale the requested locale * @return the text value of this configuration element in the specified locale, * or null * @throws InvalidRegistryObjectException if this configuration element is no longer valid * @see #GetValue(String) * @see IExtensionRegistry#IsMultiLanguage() */ virtual QString GetValue(const QLocale& locale) const = 0; /** * Returns the namespace name for this configuration element. * * @return the namespace name for this configuration element * @throws InvalidRegistryObjectException if this configuration element is no longer valid */ virtual QString GetNamespaceIdentifier() const = 0; /** * Returns the contributor of this configuration element. * * @return the contributor for this configuration element * @throws InvalidRegistryObjectException if this configuration element is no longer valid */ virtual SmartPointer GetContributor() const = 0; /** * Returns whether this configuration element object is valid. * * @return true if the object is valid, and false * if it is no longer valid */ virtual bool IsValid() const = 0; }; } // namespace berry +Q_DECLARE_INTERFACE(berry::IConfigurationElement, "org.blueberry.core.IConfigurationElement") + #endif /*BERRYIEXTENSIONELEMENT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIContributor.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIContributor.h index b0d29d48e7..13af6e12b6 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIContributor.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIContributor.h @@ -1,60 +1,59 @@ /*=================================================================== 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 BERRYICONTRIBUTOR_H #define BERRYICONTRIBUTOR_H #include "berryObject.h" -#include "berryMacros.h" #include namespace berry { /** * This interface describes a registry contributor - an entity that supplies information * to the extension registry. *

* Registry contributor objects can be obtained by calling {@link IExtensionPoint#GetContributor()}, * {@link IExtension#GetContributor()}, and {@link IConfigurationElement#GetContributor()}. * Alternatively, a contributor factory appropriate for the registry in use can be called to directly * obtain an IContributor object. *

* This interface is not intended to be implemented or extended by clients. *

* @see ContributorFactoryOSGi * @see ContributorFactorySimple * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ struct org_blueberry_core_runtime_EXPORT IContributor : public Object { - berryInterfaceMacro(IContributor, berry) + berryObjectMacro(berry::IContributor) virtual ~IContributor(); /** * Provides name of the contributor (e.g., "org.eclipse.core.runtime"). * * @return name of the registry contributor */ virtual QString GetName() const = 0; }; } #endif // BERRYICONTRIBUTOR_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExecutableExtension.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExecutableExtension.h index 9b487e8bcd..7f9a886031 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExecutableExtension.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExecutableExtension.h @@ -1,144 +1,144 @@ /*=================================================================== 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 BERRYIEXECUTABLEEXTENSION_H_ #define BERRYIEXECUTABLEEXTENSION_H_ #include "berryObject.h" #include "berrySmartPointer.h" #include namespace berry { struct IConfigurationElement; /** * Interface for executable extension classes that require access to * their configuration element, or implement an extension adapter. *

* Extension adapters are typically required in cases where the extension * implementation does not follow the interface rules specified * by the provider of the extension point. In these * cases, the role of the adapter is to map between the extension point * interface, and the actual extension implementation. In general, adapters * are used when attempting to plug-in existing Java implementations, or * non-Java implementations (e.g., external executables). *

*

* Clients may implement this interface. *

* * @see IConfigurationElement#createExecutableExtension */ struct org_blueberry_core_runtime_EXPORT IExecutableExtension { virtual ~IExecutableExtension(); /** * This method is called by the implementation of the method * IConfigurationElement.createExecutableExtension * on a newly constructed extension, passing it its relevant configuration * information. Most executable extensions only make use of the first * two call arguments. *

* Regular executable extensions specify their Java implementation * class name as an attribute of the configuration element for the * extension. For example *

    *     <action run="com.example.BaseAction"/>
    * 
* In the above example, this method would be called with a reference * to the <action> element (first argument), and * "run" as the name of the attribute that defined * this executable extension (second argument). *

*

* The last parameter is for the specific use of extension adapters * and is typically not used by regular executable extensions. *

*

* There are two supported ways of associating additional * adapter-specific data with the configuration in a way that * is transparent to the extension point implementor: *

*

* (1) by specifying adapter data as part of the implementation * class attribute value. The Java class name can be followed * by a ":" separator, followed by any adapter data in string * form. For example, if the extension point specifies an attribute * "run" to contain the name of the extension implementation, * an adapter can be configured as *

    *     <action run="com.example.ExternalAdapter:./cmds/util.exe -opt 3"/>
    * 
*

*

* (2) by converting the attribute used to specify the executable * extension to a child element of the original configuration element, * and specifying the adapter data in the form of xml markup. * Using this form, the example above would become *

    *     <action>
    *         <run class="com.xyz.ExternalAdapter">
    *             <parameter name="exec" value="./cmds/util.exe"/>
    *             <parameter name="opt"  value="3"/>
    *         </run>
    *     </action>
    * 
*

*

* Form (2) will typically only be * used for extension points that anticipate the majority of * extensions configured into it will in fact be in the form * of adapters. *

*

* In either case, the specified adapter class is instantiated using its * 0-argument public constructor. The adapter data is passed as the * last argument of this method. The data argument is defined as Object. * It can have the following values: *

    *
  • null, if no adapter data was supplied
  • *
  • in case (1), the initialization data * string is passed as a String
  • *
  • in case (2), the initialization data is passed * as a Hashtable containing the actual * parameter names and values (both Strings)
  • *
*

* * @param config the configuration element used to trigger this execution. * It can be queried by the executable extension for specific * configuration properties * @param propertyName the name of an attribute of the configuration element * used on the createExecutableExtension(String) call. This * argument can be used in the cases where a single configuration element * is used to define multiple executable extensions. * @param data adapter data in the form of a String, * a Hashtable, or null. * @exception CoreException if error(s) detected during initialization processing * @see IConfigurationElement#createExecutableExtension */ virtual void SetInitializationData(const SmartPointer& config, const QString& propertyName, const Object::Pointer& data) = 0; }; } -Q_DECLARE_INTERFACE(berry::IExecutableExtension, "org.blueberry.IExecutableExtension") +Q_DECLARE_INTERFACE(berry::IExecutableExtension, "org.blueberry.ui.IExecutableExtension") #endif /*BERRYIEXECUTABLEEXTENSION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtension.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtension.h index a446952ce1..8880d59465 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtension.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtension.h @@ -1,155 +1,155 @@ /*=================================================================== 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 BERRYIEXTENSION_H_ #define BERRYIEXTENSION_H_ #include #include namespace berry { struct IConfigurationElement; struct IContributor; /** * An extension declared in a plug-in. * All information is obtained from the declaring plug-in's * manifest (plugin.xml) file. *

* These registry objects are intended for relatively short-term use. Clients that * deal with these objects must be aware that they may become invalid if the * declaring plug-in is updated or uninstalled. If this happens, all methods except * {@link #IsValid()} will throw {@link InvalidRegistryObjectException}. * For extension objects, the most common case is code in a plug-in dealing * with extensions contributed to one of the extension points it declares. * Code in a plug-in that has declared that it is not dynamic aware (or not * declared anything) can safely ignore this issue, since the registry * would not be modified while it is active. However, code in a plug-in that * declares that it is dynamic aware must be careful when accessing the extension * objects because they become invalid if the contributing plug-in is removed. * Similarly, tools that analyze or display the extension registry are vulnerable. * Client code can pre-test for invalid objects by calling {@link #IsValid()}, * which never throws this exception. However, pre-tests are usually not sufficient * because of the possibility of the extension object becoming invalid as a * result of a concurrent activity. At-risk clients must treat * InvalidRegistryObjectException as if it were a checked exception. * Also, such clients should probably register a listener with the extension registry * so that they receive notification of any changes to the registry. *

* This interface is not intended to be implemented by clients. *

* @noimplement This interface is not intended to be implemented by clients. */ struct org_blueberry_core_runtime_EXPORT IExtension : public virtual Object { - berryInterfaceMacro(IExtension, berry) + berryObjectMacro(berry::IExtension) virtual ~IExtension(); /** * Returns all configuration elements declared by this extension. * These elements are a direct reflection of the configuration * markup supplied in the manifest (plugin.xml) * file for the plug-in that declares this extension. * Returns an empty array if this extension does not declare any * configuration elements. * * @return the configuration elements declared by this extension * @throws InvalidRegistryObjectException if this extension is no longer valid */ virtual QList > GetConfigurationElements() const = 0; /** * Returns the namespace name for this extension. * * @return the namespace name for this extension * @throws InvalidRegistryObjectException if this extension is no longer valid */ virtual QString GetNamespaceIdentifier() const = 0; /** * Returns the contributor of this extension. * * @return the contributor for this extension * @throws InvalidRegistryObjectException if this extension is no longer valid */ virtual SmartPointer GetContributor() const = 0; /** * Returns the unique identifier of the extension point * to which this extension should be contributed. * * @return the unique identifier of the relevant extension point * @throws InvalidRegistryObjectException if this extension is no longer valid */ virtual QString GetExtensionPointUniqueIdentifier() const = 0; /** * Returns a displayable label for this extension. * Returns the empty string if no label for this extension * is specified in the extension manifest file. *

Note that any translation specified in the extension manifest * file is automatically applied. *

* * @return a displayable string label for this extension, * possibly the empty string * @throws InvalidRegistryObjectException if this extension is no longer valid */ virtual QString GetLabel() const = 0; /** * Returns the simple identifier of this extension, or null * if this extension does not have an identifier. * This identifier is specified in the extensions manifest * file as a non-empty string containing no period characters * ('.') and must be unique within the defining host. * * @return the simple identifier of the extension (e.g. "main") * or null * @throws InvalidRegistryObjectException if this extension is no longer valid */ virtual QString GetSimpleIdentifier() const = 0; /** * Returns the unique identifier of this extension, or null * if this extension does not have an identifier. * If available, this identifier is unique within the extension registry, and * is composed of the identifier of the host that declared * this extension and this extension's simple identifier. * * @return the unique identifier of the extension * (e.g. "com.example.acme.main"), or null * @throws InvalidRegistryObjectException if this extension is no longer valid */ virtual QString GetUniqueIdentifier() const = 0; /** * Returns whether this extension object is valid. * * @return true if the object is valid, and false * if it is no longer valid */ virtual bool IsValid() const = 0; }; } #endif /*BERRYIEXTENSION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtensionPoint.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtensionPoint.h index d17dac6b04..348f527b36 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtensionPoint.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtensionPoint.h @@ -1,167 +1,167 @@ /*=================================================================== 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 BERRYIEXTENSIONPOINT_H_ #define BERRYIEXTENSIONPOINT_H_ #include namespace berry { struct IConfigurationElement; struct IContributor; struct IExtension; /** * An extension point declared in a plug-in. * Except for the list of extensions plugged in to it, the information * available for an extension point is obtained from the declaring plug-in's * manifest (plugin.xml) file. *

* These registry objects are intended for relatively short-term use. Clients that * deal with these objects must be aware that they may become invalid if the * declaring plug-in is updated or uninstalled. If this happens, all methods except * {@link #isValid()} will throw {@link InvalidRegistryObjectException}. * For extension point objects, the most common case is code in a plug-in dealing * with one of the extension points it declares. These extension point objects are * guaranteed to be valid while the plug-in is active. Code in a plug-in that has * declared that it is not dynamic aware (or not declared anything) can also safely * ignore this issue, since the registry would not be modified while it is * active. However, code in a plug-in that declares that it is dynamic aware * must be careful if it access the extension point object of a different plug-in, * because it's at risk if that other plug-in is removed. Similarly, * tools that analyze or display the extension registry are vulnerable. * Client code can pre-test for invalid objects by calling {@link #isValid()}, * which never throws this exception. However, pre-tests are usually not sufficient * because of the possibility of the extension point object becoming invalid as a * result of a concurrent activity. At-risk clients must treat * InvalidRegistryObjectException as if it were a checked exception. * Also, such clients should probably register a listener with the extension registry * so that they receive notification of any changes to the registry. *

*

* This interface is not intended to be implemented by clients. *

* @noimplement This interface is not intended to be implemented by clients. */ struct IExtensionPoint : public virtual Object { - berryInterfaceMacro(IExtensionPoint, berry) + berryObjectMacro(berry::IExtensionPoint) virtual ~IExtensionPoint(); /** * Returns all configuration elements from all extensions configured * into this extension point. Returns an empty array if this extension * point has no extensions configured, or none of the extensions * contain configuration elements. * * @return the configuration elements for all extension configured * into this extension point * @throws InvalidRegistryObjectException if this extension point is no longer valid */ virtual QList > GetConfigurationElements() const = 0; /** * Returns the namespace name for this extension point. * * @return the namespace name for this extension point * @throws InvalidRegistryObjectException if this extension point is no longer valid */ virtual QString GetNamespaceIdentifier() const = 0; /** * Returns the contributor of this extension point. * * @return the contributor for this extension point * @throws InvalidRegistryObjectException if this extension point is no longer valid */ virtual SmartPointer GetContributor() const = 0; /** * Returns the extension with the given unique identifier configured into * this extension point, or null if there is no such extension. * Since an extension might not have an identifier, some extensions * can only be found via the getExtensions method. * * @param extensionId the unique identifier of an extension * (e.g. "com.example.acme.main"). * @return an extension, or null * @throws InvalidRegistryObjectException if this extension point is no longer valid */ virtual SmartPointer GetExtension(const QString& extensionId) const = 0; /** * Returns all extensions configured into this extension point. * Returns an empty array if this extension point has no extensions. * * @return the extensions configured into this extension point * @throws InvalidRegistryObjectException if this extension point is no longer valid */ virtual QList > GetExtensions() const = 0; /** * Returns a displayable label for this extension point. * Returns the empty string if no label for this extension point * is specified in the plug-in manifest file. *

Note that any translation specified in the plug-in manifest * file is automatically applied. *

* * @return a displayable string label for this extension point, * possibly the empty string * @throws InvalidRegistryObjectException if this extension point is no longer valid */ virtual QString GetLabel() const = 0; /** * Returns the simple identifier of this extension point. * This identifier is a non-empty string containing no * period characters ('.') and is guaranteed * to be unique within the defining plug-in. * * @return the simple identifier of the extension point (e.g. "builders") * @throws InvalidRegistryObjectException if this extension point is no longer valid */ virtual QString GetSimpleIdentifier() const = 0; /** * Returns the unique identifier of this extension point. * This identifier is unique within the plug-in registry, and * is composed of the namespace for this extension point * and this extension point's simple identifier. * * * @return the unique identifier of the extension point * (e.g. "org.blueberry.core.resources.builders") * @throws InvalidRegistryObjectException if this extension point is no longer valid */ virtual QString GetUniqueIdentifier() const = 0; /** * Returns whether this extension point object is valid. * * @return true if the object is valid, and false * if it is no longer valid */ virtual bool IsValid() const = 0; }; } #endif /*BERRYIEXTENSIONPOINT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.test/src/berryITestDescriptor.h b/BlueBerry/Bundles/org.blueberry.test/src/berryITestDescriptor.h index ed2d5348a1..67540cc46e 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/berryITestDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.test/src/berryITestDescriptor.h @@ -1,42 +1,42 @@ /*=================================================================== 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 BERRYITESTDESCRIPTOR_H_ #define BERRYITESTDESCRIPTOR_H_ #include #include #include namespace berry { struct ITestDescriptor : public Object { - berryInterfaceMacro(ITestDescriptor, berry); + berryObjectMacro(berry::ITestDescriptor) virtual CppUnit::Test* CreateTest() = 0; virtual std::string GetId() const = 0; virtual std::string GetContributor() const = 0; virtual std::string GetDescription() const = 0; virtual bool IsUITest() const = 0; }; } #endif /* BERRYITESTDESCRIPTOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditor.cpp index b29b5a0a74..e591a489bf 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditor.cpp @@ -1,342 +1,339 @@ /*=================================================================== 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 "berryHelpEditor.h" #include "berryHelpEditorInput.h" #include "berryHelpPluginActivator.h" #include "berryHelpPerspective.h" #include "berryHelpWebView.h" #include "berryQHelpEngineWrapper.h" #include "berryHelpEditorFindWidget.h" #include "berryHelpPluginActivator.h" #include "berryQHelpEngineWrapper.h" #include #include #include #include #include #include #include namespace berry { const QString HelpEditor::EDITOR_ID = "org.blueberry.editors.help"; HelpEditor::HelpEditor() : m_ToolBar(0) , m_WebView(0) { } HelpEditor::~HelpEditor() { - // we need to wrap the RemovePartListener call inside a - // register/unregister block to prevent infinite recursion - // due to the destruction of temporary smartpointer to this - this->Register(); - this->GetSite()->GetPage()->RemovePartListener(IPartListener::Pointer(this)); - this->GetSite()->GetPage()->GetWorkbenchWindow()->RemovePerspectiveListener(IPerspectiveListener::Pointer(this)); - this->UnRegister(false); + this->GetSite()->GetPage()->RemovePartListener(this); + this->GetSite()->GetPage()->GetWorkbenchWindow()->RemovePerspectiveListener(this); } void HelpEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input) { if (input.Cast().IsNull()) throw PartInitException("Invalid Input: Must be berry::HelpEditorInput"); this->SetSite(site); - site->GetPage()->AddPartListener(IPartListener::Pointer(this)); - site->GetPage()->GetWorkbenchWindow()->AddPerspectiveListener(IPerspectiveListener::Pointer(this)); + site->GetPage()->AddPartListener(this); + site->GetPage()->GetWorkbenchWindow()->AddPerspectiveListener(this); m_WebView = new HelpWebView(site, 0); connect(m_WebView, SIGNAL(loadFinished(bool)), this, SLOT(InitializeTitle())); this->DoSetInput(input); } void HelpEditor::CreateQtPartControl(QWidget* parent) { QVBoxLayout* verticalLayout = new QVBoxLayout(parent); verticalLayout->setSpacing(0); verticalLayout->setContentsMargins(0, 0, 0, 0); m_ToolBar = new QToolBar(parent); m_ToolBar->setMaximumHeight(32); verticalLayout->addWidget(m_ToolBar); m_WebView->setParent(parent); m_WebView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); verticalLayout->addWidget(m_WebView); m_FindWidget = new HelpEditorFindWidget(parent); m_FindWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Maximum); verticalLayout->addWidget(m_FindWidget); m_FindWidget->hide(); connect(m_FindWidget, SIGNAL(findNext()), this, SLOT(findNext())); connect(m_FindWidget, SIGNAL(findPrevious()), this, SLOT(findPrevious())); connect(m_FindWidget, SIGNAL(find(QString, bool)), this, SLOT(find(QString, bool))); connect(m_FindWidget, SIGNAL(escapePressed()), m_WebView, SLOT(setFocus())); // Fill the editor toolbar m_BackAction = m_ToolBar->addAction(QIcon(":/org.blueberry.ui.qt.help/go-previous.png"), "Go back", m_WebView, SLOT(backward())); m_ForwardAction = m_ToolBar->addAction(QIcon(":/org.blueberry.ui.qt.help/go-next.png"), "Go forward", m_WebView, SLOT(forward())); m_HomeAction = m_ToolBar->addAction(QIcon(":/org.blueberry.ui.qt.help/go-home.png"), "Go home", m_WebView, SLOT(home())); m_PrintAction = m_ToolBar->addAction(QIcon(":/org.blueberry.ui.qt.help/print.png"), "Print", m_WebView, SLOT(print())); m_ToolBar->addSeparator(); m_FindAction = m_ToolBar->addAction(QIcon(":/org.blueberry.ui.qt.help/find.png"), "Find in text", this, SLOT(ShowTextSearch())); m_ToolBar->addSeparator(); m_ZoomIn = m_ToolBar->addAction(QIcon(":/org.blueberry.ui.qt.help/zoom-in.png"), "Zoom in", m_WebView, SLOT(scaleUp())); m_ZoomOut = m_ToolBar->addAction(QIcon(":/org.blueberry.ui.qt.help/zoom-out.png"), "Zoom out", m_WebView, SLOT(scaleDown())); m_ToolBar->addSeparator(); m_OpenHelpMode = m_ToolBar->addAction("Open Help Perspective", this, SLOT(OpenHelpPerspective())); m_CloseHelpMode = m_ToolBar->addAction("Close Help Perspective", this, SLOT(CloseHelpPerspective())); IPerspectiveDescriptor::Pointer currPersp = this->GetSite()->GetPage()->GetPerspective(); m_OpenHelpMode->setVisible(!(currPersp.IsNotNull() && currPersp->GetId() == HelpPerspective::ID)); m_CloseHelpMode->setVisible((currPersp.IsNotNull() && currPersp->GetId() == HelpPerspective::ID)); connect(m_WebView, SIGNAL(backwardAvailable(bool)), m_BackAction, SLOT(setEnabled(bool))); connect(m_WebView, SIGNAL(forwardAvailable(bool)), m_ForwardAction, SLOT(setEnabled(bool))); m_BackAction->setEnabled(false); m_ForwardAction->setEnabled(false); m_HomeAction->setEnabled(!HelpPluginActivator::getInstance()->getQHelpEngine().homePage().isEmpty()); connect(&HelpPluginActivator::getInstance()->getQHelpEngine(), SIGNAL(homePageChanged(QString)), this, SLOT(HomePageChanged(QString))); } void HelpEditor::DoSetInput(IEditorInput::Pointer input) { if (input.IsNull()) { // close editor class CloseEditorRunnable : public Poco::Runnable { private: IEditorPart::Pointer editor; public: CloseEditorRunnable(IEditorPart::Pointer editor) : editor(editor) {} void run() { editor->GetSite()->GetPage()->CloseEditor(editor, false); delete this; } }; Display::GetDefault()->AsyncExec(new CloseEditorRunnable(IEditorPart::Pointer(this))); } else { // an empty url represents the home page HelpEditorInput::Pointer helpInput = input.Cast(); QString currHomePage = HelpPluginActivator::getInstance()->getQHelpEngine().homePage(); if (helpInput->GetUrl().isEmpty() && !currHomePage.isEmpty()) { helpInput = HelpEditorInput::Pointer(new HelpEditorInput(currHomePage)); } QtEditorPart::SetInput(helpInput); m_WebView->setSource(helpInput->GetUrl()); } } void HelpEditor::SetInputWithNotify(IEditorInput::Pointer input) { DoSetInput(input); FirePropertyChange(IWorkbenchPartConstants::PROP_INPUT); } void HelpEditor::SetInput(IEditorInput::Pointer input) { SetInputWithNotify(input); } void HelpEditor::HomePageChanged(const QString &page) { if (page.isEmpty()) { m_HomeAction->setEnabled(false); } m_HomeAction->setEnabled(true); if (this->GetEditorInput().Cast()->GetUrl().isEmpty()) { IEditorInput::Pointer newInput(new HelpEditorInput(page)); DoSetInput(newInput); } } void HelpEditor::OpenHelpPerspective() { PlatformUI::GetWorkbench()->ShowPerspective(HelpPerspective::ID, this->GetSite()->GetPage()->GetWorkbenchWindow()); } void HelpEditor::CloseHelpPerspective() { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); page->ClosePerspective(page->GetPerspective(), true, true); } void HelpEditor::InitializeTitle() { QString title = m_WebView->title(); this->SetPartName(title); } void HelpEditor::ShowTextSearch() { m_FindWidget->show(); } void HelpEditor::SetFocus() { m_WebView->setFocus(); enableShortcuts(); } QWebPage *HelpEditor::GetQWebPage() const { return m_WebView->page(); } IPartListener::Events::Types HelpEditor::GetPartEventTypes() const { return IPartListener::Events::DEACTIVATED; } -void HelpEditor::PartDeactivated(IWorkbenchPartReference::Pointer partRef) +void HelpEditor::PartDeactivated(const IWorkbenchPartReference::Pointer& partRef) { if (partRef == GetSite()->GetPage()->GetReference(IWorkbenchPart::Pointer(this))) disableShortcuts(); } IPerspectiveListener::Events::Types HelpEditor::GetPerspectiveEventTypes() const { return IPerspectiveListener::Events::ACTIVATED | IPerspectiveListener::Events::DEACTIVATED; } -void HelpEditor::PerspectiveActivated(SmartPointer page, IPerspectiveDescriptor::Pointer perspective) +void HelpEditor::PerspectiveActivated(const SmartPointer& /*page*/, + const IPerspectiveDescriptor::Pointer& perspective) { if (perspective->GetId() == HelpPerspective::ID) { m_OpenHelpMode->setVisible(false); m_CloseHelpMode->setVisible(true); } } -void HelpEditor::PerspectiveDeactivated(SmartPointer page, IPerspectiveDescriptor::Pointer perspective) +void HelpEditor::PerspectiveDeactivated(const SmartPointer& /*page*/, + const IPerspectiveDescriptor::Pointer& perspective) { if (perspective->GetId() == HelpPerspective::ID) { m_OpenHelpMode->setVisible(true); m_CloseHelpMode->setVisible(false); } } void HelpEditor::findNext() { find(m_FindWidget->text(), true); } void HelpEditor::findPrevious() { find(m_FindWidget->text(), false); } void HelpEditor::find(const QString &ttf, bool forward) { bool found = findInWebPage(ttf, forward); if (!found && ttf.isEmpty()) found = true; // the line edit is empty, no need to mark it red... if (!m_FindWidget->isVisible()) m_FindWidget->show(); m_FindWidget->setPalette(found); } bool HelpEditor::findInWebPage(const QString &ttf, bool forward) { bool found = false; QWebPage::FindFlags options; if (!ttf.isEmpty()) { if (!forward) options |= QWebPage::FindBackward; if (m_FindWidget->caseSensitive()) options |= QWebPage::FindCaseSensitively; found = m_WebView->findText(ttf, options); if (!found) { options |= QWebPage::FindWrapsAroundDocument; found = m_WebView->findText(ttf, options); } } // force highlighting of all other matches, also when empty (clear) options = QWebPage::HighlightAllOccurrences; if (m_FindWidget->caseSensitive()) options |= QWebPage::FindCaseSensitively; m_WebView->findText(QLatin1String(""), options); m_WebView->findText(ttf, options); return found; } void HelpEditor::enableShortcuts() { m_BackAction->setShortcut(QKeySequence::Back); m_ForwardAction->setShortcut(QKeySequence::Forward); m_FindAction->setShortcut(QKeySequence::Find); m_ZoomIn->setShortcut(QKeySequence::ZoomIn); m_ZoomOut->setShortcut(QKeySequence::ZoomOut); } void HelpEditor::disableShortcuts() { m_BackAction->setShortcut(QKeySequence()); m_ForwardAction->setShortcut(QKeySequence()); m_FindAction->setShortcut(QKeySequence()); m_ZoomIn->setShortcut(QKeySequence()); m_ZoomOut->setShortcut(QKeySequence()); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditor.h b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditor.h index ba9bea81a0..946401b733 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditor.h @@ -1,112 +1,114 @@ /*=================================================================== 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 BERRYHELPEDITOR_H_ #define BERRYHELPEDITOR_H_ #include #include #include #include class QToolBar; class QWebPage; namespace berry { class HelpWebView; class HelpEditorFindWidget; class HelpEditor : public QtEditorPart, public IReusableEditor, public IPartListener, public IPerspectiveListener { Q_OBJECT public: berryObjectMacro(HelpEditor); static const QString EDITOR_ID; HelpEditor(); ~HelpEditor(); void Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input); void SetFocus(); void DoSave() {} void DoSaveAs() {} bool IsDirty() const { return false; } bool IsSaveAsAllowed() const { return false; } QWebPage* GetQWebPage() const; IPartListener::Events::Types GetPartEventTypes() const; - void PartDeactivated(IWorkbenchPartReference::Pointer /*partRef*/); + void PartDeactivated(const IWorkbenchPartReference::Pointer& /*partRef*/); IPerspectiveListener::Events::Types GetPerspectiveEventTypes() const; - void PerspectiveActivated(SmartPointer page, IPerspectiveDescriptor::Pointer perspective); - void PerspectiveDeactivated(SmartPointer page, IPerspectiveDescriptor::Pointer perspective); + void PerspectiveActivated(const SmartPointer& page, + const IPerspectiveDescriptor::Pointer& perspective); + void PerspectiveDeactivated(const SmartPointer& page, + const IPerspectiveDescriptor::Pointer& perspective); protected: void CreateQtPartControl(QWidget* parent); void DoSetInput(IEditorInput::Pointer input); void SetInputWithNotify(IEditorInput::Pointer input); void SetInput(IEditorInput::Pointer input); private Q_SLOTS: void HomePageChanged(const QString& page); void OpenHelpPerspective(); void CloseHelpPerspective(); void InitializeTitle(); void ShowTextSearch(); void findNext(); void findPrevious(); void find(const QString& ttf, bool forward); private: bool findInWebPage(const QString& ttf, bool forward); void enableShortcuts(); void disableShortcuts(); private: Q_DISABLE_COPY(HelpEditor) QToolBar* m_ToolBar; HelpWebView* m_WebView; HelpEditorFindWidget* m_FindWidget; QAction* m_BackAction; QAction* m_ForwardAction; QAction* m_FindAction; QAction* m_ZoomIn; QAction* m_ZoomOut; QAction* m_OpenHelpMode; QAction* m_CloseHelpMode; QAction* m_HomeAction; QAction* m_PrintAction; }; } // end namespace berry #endif /*BERRYHELPEDITOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpPluginActivator.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpPluginActivator.cpp index e5671e6c1c..f616f1797d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpPluginActivator.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpPluginActivator.cpp @@ -1,472 +1,476 @@ /*=================================================================== 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 "berryHelpPluginActivator.h" #include "berryHelpContentView.h" #include "berryHelpIndexView.h" #include "berryHelpSearchView.h" #include "berryHelpEditor.h" #include "berryHelpEditorInput.h" #include "berryHelpPerspective.h" #include "berryQHelpEngineConfiguration.h" #include "berryQHelpEngineWrapper.h" #include #include #include #include #include namespace berry { class HelpPerspectiveListener : public IPerspectiveListener { public: Events::Types GetPerspectiveEventTypes() const; - void PerspectiveOpened(SmartPointer page, IPerspectiveDescriptor::Pointer perspective); - void PerspectiveChanged(SmartPointer page, IPerspectiveDescriptor::Pointer perspective, const QString &changeId); + using IPerspectiveListener::PerspectiveChanged; + + void PerspectiveOpened(const SmartPointer& page, const IPerspectiveDescriptor::Pointer& perspective); + void PerspectiveChanged(const SmartPointer& page, const IPerspectiveDescriptor::Pointer& perspective, const QString &changeId); }; class HelpWindowListener : public IWindowListener { public: HelpWindowListener(); ~HelpWindowListener(); - void WindowClosed(IWorkbenchWindow::Pointer window); - void WindowOpened(IWorkbenchWindow::Pointer window); + void WindowClosed(const IWorkbenchWindow::Pointer& window); + void WindowOpened(const IWorkbenchWindow::Pointer& window); private: // We use the same perspective listener for every window - IPerspectiveListener::Pointer perspListener; + QScopedPointer perspListener; }; HelpPluginActivator* HelpPluginActivator::instance = 0; HelpPluginActivator::HelpPluginActivator() : pluginListener(0) { this->instance = this; } HelpPluginActivator::~HelpPluginActivator() { instance = 0; } void HelpPluginActivator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(berry::HelpContentView, context) BERRY_REGISTER_EXTENSION_CLASS(berry::HelpIndexView, context) BERRY_REGISTER_EXTENSION_CLASS(berry::HelpSearchView, context) BERRY_REGISTER_EXTENSION_CLASS(berry::HelpEditor, context) BERRY_REGISTER_EXTENSION_CLASS(berry::HelpPerspective, context) QFileInfo qhcInfo = context->getDataFile("qthelpcollection.qhc"); helpEngine.reset(new QHelpEngineWrapper(qhcInfo.absoluteFilePath())); if (!helpEngine->setupData()) { BERRY_ERROR << "QHelpEngine set-up failed: " << helpEngine->error().toStdString(); return; } helpEngineConfiguration.reset(new QHelpEngineConfiguration(context, *helpEngine.data())); delete pluginListener; pluginListener = new QCHPluginListener(context, helpEngine.data()); context->connectPluginListener(pluginListener, SLOT(pluginChanged(ctkPluginEvent))); // register all QCH files from all the currently installed plugins pluginListener->processPlugins(); helpEngine->initialDocSetupDone(); // Register a wnd listener which registers a perspective listener for each // new window. The perspective listener opens the help home page in the window // if no other help page is opened yet. - wndListener = IWindowListener::Pointer(new HelpWindowListener()); - PlatformUI::GetWorkbench()->AddWindowListener(wndListener); + wndListener.reset(new HelpWindowListener()); + PlatformUI::GetWorkbench()->AddWindowListener(wndListener.data()); // Register an event handler for CONTEXTHELP_REQUESTED events helpContextHandler.reset(new HelpContextHandler); ctkDictionary helpHandlerProps; helpHandlerProps.insert(ctkEventConstants::EVENT_TOPIC, "org/blueberry/ui/help/CONTEXTHELP_REQUESTED"); context->registerService(helpContextHandler.data(), helpHandlerProps); } void HelpPluginActivator::stop(ctkPluginContext* /*context*/) { delete pluginListener; pluginListener = 0; if (PlatformUI::IsWorkbenchRunning()) { - PlatformUI::GetWorkbench()->RemoveWindowListener(wndListener); + PlatformUI::GetWorkbench()->RemoveWindowListener(wndListener.data()); } - wndListener = 0; + wndListener.reset(); } HelpPluginActivator *HelpPluginActivator::getInstance() { return instance; } QHelpEngineWrapper& HelpPluginActivator::getQHelpEngine() { return *helpEngine; } void HelpPluginActivator::linkActivated(IWorkbenchPage::Pointer page, const QUrl &link) { IEditorInput::Pointer input(new HelpEditorInput(link)); // see if an editor with the same input is already open IEditorPart::Pointer reuseEditor = page->FindEditor(input); if (reuseEditor) { // just activate it page->Activate(reuseEditor); } else { // reuse the currently active editor, if it is a HelpEditor reuseEditor = page->GetActiveEditor(); if (reuseEditor.IsNotNull() && page->GetReference(reuseEditor)->GetId() == HelpEditor::EDITOR_ID) { page->ReuseEditor(reuseEditor.Cast(), input); page->Activate(reuseEditor); } else { // get the last used HelpEditor instance QList editors = page->FindEditors(IEditorInput::Pointer(0), HelpEditor::EDITOR_ID, IWorkbenchPage::MATCH_ID); if (editors.empty()) { // no HelpEditor is currently open, create a new one page->OpenEditor(input, HelpEditor::EDITOR_ID); } else { // reuse an existing editor reuseEditor = editors.front()->GetEditor(false); page->ReuseEditor(reuseEditor.Cast(), input); page->Activate(reuseEditor); } } } } QCHPluginListener::QCHPluginListener(ctkPluginContext* context, QHelpEngine* helpEngine) : delayRegistration(true), context(context), helpEngine(helpEngine) {} void QCHPluginListener::processPlugins() { QMutexLocker lock(&mutex); processPlugins_unlocked(); } void QCHPluginListener::pluginChanged(const ctkPluginEvent& event) { QMutexLocker lock(&mutex); if (delayRegistration) { this->processPlugins_unlocked(); return; } /* Only should listen for RESOLVED and UNRESOLVED events. * * When a plugin is updated the Framework will publish an UNRESOLVED and * then a RESOLVED event which should cause the plugin to be removed * and then added back into the registry. * * When a plugin is uninstalled the Framework should publish an UNRESOLVED * event and then an UNINSTALLED event so the plugin will have been removed * by the UNRESOLVED event before the UNINSTALLED event is published. */ QSharedPointer plugin = event.getPlugin(); switch (event.getType()) { - case ctkPluginEvent::RESOLVED : - addPlugin(plugin); - break; - case ctkPluginEvent::UNRESOLVED : - removePlugin(plugin); - break; + case ctkPluginEvent::RESOLVED : + addPlugin(plugin); + break; + case ctkPluginEvent::UNRESOLVED : + removePlugin(plugin); + break; + default: + break; } } void QCHPluginListener::processPlugins_unlocked() { if (!delayRegistration) return; foreach (QSharedPointer plugin, context->getPlugins()) { if (isPluginResolved(plugin)) addPlugin(plugin); else removePlugin(plugin); } delayRegistration = false; } bool QCHPluginListener::isPluginResolved(QSharedPointer plugin) { return (plugin->getState() & (ctkPlugin::RESOLVED | ctkPlugin::ACTIVE | ctkPlugin::STARTING | ctkPlugin::STOPPING)) != 0; } void QCHPluginListener::removePlugin(QSharedPointer plugin) { // bail out if system plugin if (plugin->getPluginId() == 0) return; QFileInfo qchDirInfo = context->getDataFile("qch_files/" + QString::number(plugin->getPluginId())); if (qchDirInfo.exists()) { QDir qchDir(qchDirInfo.absoluteFilePath()); QStringList qchEntries = qchDir.entryList(QStringList("*.qch")); QStringList qchFiles; foreach(QString qchEntry, qchEntries) { qchFiles << qchDir.absoluteFilePath(qchEntry); } // unregister the cached qch files foreach(QString qchFile, qchFiles) { QString namespaceName = QHelpEngineCore::namespaceName(qchFile); if (namespaceName.isEmpty()) { BERRY_ERROR << "Could not get the namespace for qch file " << qchFile.toStdString(); continue; } else { if (!helpEngine->unregisterDocumentation(namespaceName)) { BERRY_ERROR << "Unregistering qch namespace " << namespaceName.toStdString() << " failed: " << helpEngine->error().toStdString(); } } } // clean the directory foreach(QString qchEntry, qchEntries) { qchDir.remove(qchEntry); } } } void QCHPluginListener::addPlugin(QSharedPointer plugin) { // bail out if system plugin if (plugin->getPluginId() == 0) return; QFileInfo qchDirInfo = context->getDataFile("qch_files/" + QString::number(plugin->getPluginId())); QUrl location(plugin->getLocation()); QFileInfo pluginFileInfo(location.toLocalFile()); if (!qchDirInfo.exists() || qchDirInfo.lastModified() < pluginFileInfo.lastModified()) { removePlugin(plugin); if (!qchDirInfo.exists()) { QDir().mkpath(qchDirInfo.absoluteFilePath()); } QStringList localQCHFiles; QStringList resourceList = plugin->findResources("/", "*.qch", true); foreach(QString resource, resourceList) { QByteArray content = plugin->getResource(resource); QFile localFile(qchDirInfo.absoluteFilePath() + "/" + resource.section('/', -1)); localFile.open(QIODevice::WriteOnly); localFile.write(content); localFile.close(); if (localFile.error() != QFile::NoError) { BERRY_WARN << "Error writing " << localFile.fileName().toStdString() << ": " << localFile.errorString().toStdString(); } else { localQCHFiles << localFile.fileName(); } } foreach(QString qchFile, localQCHFiles) { if (!helpEngine->registerDocumentation(qchFile)) { BERRY_ERROR << "Registering qch file " << qchFile.toStdString() << " failed: " << helpEngine->error().toStdString(); } } } } IPerspectiveListener::Events::Types HelpPerspectiveListener::GetPerspectiveEventTypes() const { return Events::OPENED | Events::CHANGED; } -void HelpPerspectiveListener::PerspectiveOpened(SmartPointer page, IPerspectiveDescriptor::Pointer perspective) +void HelpPerspectiveListener::PerspectiveOpened(const SmartPointer& page, const IPerspectiveDescriptor::Pointer& perspective) { // if no help editor is opened, open one showing the home page if (perspective->GetId() == HelpPerspective::ID && page->FindEditors(IEditorInput::Pointer(0), HelpEditor::EDITOR_ID, IWorkbenchPage::MATCH_ID).empty()) { IEditorInput::Pointer input(new HelpEditorInput()); page->OpenEditor(input, HelpEditor::EDITOR_ID); } } -void HelpPerspectiveListener::PerspectiveChanged(SmartPointer page, IPerspectiveDescriptor::Pointer perspective, const QString &changeId) +void HelpPerspectiveListener::PerspectiveChanged(const SmartPointer& page, const IPerspectiveDescriptor::Pointer& perspective, const QString &changeId) { if (perspective->GetId() == HelpPerspective::ID && changeId == IWorkbenchPage::CHANGE_RESET) { PerspectiveOpened(page, perspective); } } HelpWindowListener::HelpWindowListener() : perspListener(new HelpPerspectiveListener()) { // Register perspective listener for already opened windows typedef QList WndVec; WndVec windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows(); for (WndVec::iterator i = windows.begin(); i != windows.end(); ++i) { - (*i)->AddPerspectiveListener(perspListener); + (*i)->AddPerspectiveListener(perspListener.data()); } } HelpWindowListener::~HelpWindowListener() { typedef QList WndVec; WndVec windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows(); for (WndVec::iterator i = windows.begin(); i != windows.end(); ++i) { - (*i)->RemovePerspectiveListener(perspListener); + (*i)->RemovePerspectiveListener(perspListener.data()); } } -void HelpWindowListener::WindowClosed(IWorkbenchWindow::Pointer window) +void HelpWindowListener::WindowClosed(const IWorkbenchWindow::Pointer& window) { - window->RemovePerspectiveListener(perspListener); + window->RemovePerspectiveListener(perspListener.data()); } -void HelpWindowListener::WindowOpened(IWorkbenchWindow::Pointer window) +void HelpWindowListener::WindowOpened(const IWorkbenchWindow::Pointer& window) { - window->AddPerspectiveListener(perspListener); + window->AddPerspectiveListener(perspListener.data()); } void HelpContextHandler::handleEvent(const ctkEvent &event) { struct _runner : public Poco::Runnable { _runner(const ctkEvent& ev) : ev(ev) {} void run() { QUrl helpUrl; if (ev.containsProperty("url")) { helpUrl = QUrl(ev.getProperty("url").toString()); } else { helpUrl = contextUrl(); } HelpPluginActivator::linkActivated(PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(), helpUrl); delete this; } QUrl contextUrl() const { berry::IWorkbench* currentWorkbench = berry::PlatformUI::GetWorkbench(); if (currentWorkbench) { berry::IWorkbenchWindow::Pointer currentWorkbenchWindow = currentWorkbench->GetActiveWorkbenchWindow(); if (currentWorkbenchWindow) { berry::IWorkbenchPage::Pointer currentPage = currentWorkbenchWindow->GetActivePage(); if (currentPage) { berry::IWorkbenchPart::Pointer currentPart = currentPage->GetActivePart(); if (currentPart) { QString pluginID = currentPart->GetSite()->GetPluginId(); QString viewID = currentPart->GetSite()->GetId(); QString loc = "qthelp://" + pluginID + "/bundle/%1.html"; QHelpEngineWrapper& helpEngine = HelpPluginActivator::getInstance()->getQHelpEngine(); // Get view help page if available QUrl contextUrl(loc.arg(viewID.replace(".", "_"))); QUrl url = helpEngine.findFile(contextUrl); if (url.isValid()) return url; else { BERRY_INFO << "Context help url invalid: " << contextUrl.toString().toStdString(); } // If no view help exists get plugin help if available QUrl pluginContextUrl(loc.arg(pluginID.replace(".", "_"))); url = helpEngine.findFile(pluginContextUrl); if (url.isValid()) return url; // Try to get the index.html file of the plug-in contributing the // currently active part. QUrl pluginIndexUrl(loc.arg("index")); url = helpEngine.findFile(pluginIndexUrl); if (url != pluginIndexUrl) { // Use the default page instead of another index.html // (merged via the virtual folder property). url = QUrl(); } return url; } } } } return QUrl(); } ctkEvent ev; }; // sync with GUI thread Display::GetDefault()->AsyncExec(new _runner(event)); } } #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(org_blueberry_ui_qt_help, berry::HelpPluginActivator) #endif diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpPluginActivator.h b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpPluginActivator.h index 157018f622..0ba31602fe 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpPluginActivator.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpPluginActivator.h @@ -1,120 +1,120 @@ /*=================================================================== 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 BERRYLOGPLUGIN_H_ #define BERRYLOGPLUGIN_H_ #include #include #include #include #include #include #include class QHelpEngine; namespace berry { class QHelpEngineConfiguration; class QHelpEngineWrapper; class QCHPluginListener; class HelpContextHandler : public QObject, public ctkEventHandler { Q_OBJECT #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) Q_PLUGIN_METADATA(IID "org_blueberry_ui_qt_help") #endif Q_INTERFACES(ctkEventHandler) public: void handleEvent(const ctkEvent& event); }; class HelpPluginActivator : public QObject, public ctkPluginActivator { Q_OBJECT Q_INTERFACES(ctkPluginActivator) public: HelpPluginActivator(); ~HelpPluginActivator(); void start(ctkPluginContext* context); void stop(ctkPluginContext* context); static HelpPluginActivator* getInstance(); static void linkActivated(IWorkbenchPage::Pointer page, const QUrl &link); QHelpEngineWrapper& getQHelpEngine(); private: Q_DISABLE_COPY(HelpPluginActivator) static HelpPluginActivator* instance; QScopedPointer helpEngine; QScopedPointer helpEngineConfiguration; QScopedPointer helpContextHandler; QCHPluginListener* pluginListener; - IWindowListener::Pointer wndListener; + QScopedPointer wndListener; }; /** * A listener for CTK plugin events. When plugins come and go we look to see * if there are any qch files and update the QHelpEngine accordingly. */ class QCHPluginListener : public QObject { Q_OBJECT public: QCHPluginListener(ctkPluginContext* context, QHelpEngine* helpEngine); void processPlugins(); public Q_SLOTS: void pluginChanged(const ctkPluginEvent& event); private: void processPlugins_unlocked(); bool isPluginResolved(QSharedPointer plugin); void removePlugin(QSharedPointer plugin); void addPlugin(QSharedPointer plugin); QMutex mutex; bool delayRegistration; ctkPluginContext* context; QHelpEngine* helpEngine; }; } #endif /*BERRYLOGPLUGIN_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpWebView.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpWebView.cpp index 7fd80252bf..b98ee9873c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpWebView.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpWebView.cpp @@ -1,546 +1,546 @@ /*=================================================================== 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 "berryHelpWebView.h" #include "berryHelpPluginActivator.h" #include "berryHelpEditor.h" #include "berryHelpEditorInput.h" #include "berryQHelpEngineWrapper.h" #include #include #include #include #include #include #include #include #include #include #include #include #include namespace berry { struct ExtensionMap { const char *extension; const char *mimeType; } extensionMap[] = { { ".bmp", "image/bmp" }, { ".css", "text/css" }, { ".gif", "image/gif" }, { ".html", "text/html" }, { ".htm", "text/html" }, { ".ico", "image/x-icon" }, { ".jpeg", "image/jpeg" }, { ".jpg", "image/jpeg" }, { ".js", "application/x-javascript" }, { ".mng", "video/x-mng" }, { ".pbm", "image/x-portable-bitmap" }, { ".pgm", "image/x-portable-graymap" }, { ".pdf", "application/pdf" }, { ".png", "image/png" }, { ".ppm", "image/x-portable-pixmap" }, { ".rss", "application/rss+xml" }, { ".svg", "image/svg+xml" }, { ".svgz", "image/svg+xml" }, { ".text", "text/plain" }, { ".tif", "image/tiff" }, { ".tiff", "image/tiff" }, { ".txt", "text/plain" }, { ".xbm", "image/x-xbitmap" }, { ".xml", "text/xml" }, { ".xpm", "image/x-xpm" }, { ".xsl", "text/xsl" }, { ".xhtml", "application/xhtml+xml" }, { ".wml", "text/vnd.wap.wml" }, { ".wmlc", "application/vnd.wap.wmlc" }, { "about:blank", 0 }, { 0, 0 } }; const QString HelpWebView::m_PageNotFoundMessage = QCoreApplication::translate("org.blueberry.ui.qt.help", "Error 404...


The page could not be found


'%1'" "

"); class HelpNetworkReply : public QNetworkReply { public: HelpNetworkReply(const QNetworkRequest &request, const QByteArray &fileData, const QString &mimeType); virtual void abort(); virtual qint64 bytesAvailable() const { return data.length() + QNetworkReply::bytesAvailable(); } protected: virtual qint64 readData(char *data, qint64 maxlen); private: QByteArray data; qint64 origLen; }; HelpNetworkReply::HelpNetworkReply(const QNetworkRequest &request, const QByteArray &fileData, const QString& mimeType) : data(fileData), origLen(fileData.length()) { setRequest(request); setOpenMode(QIODevice::ReadOnly); setHeader(QNetworkRequest::ContentTypeHeader, mimeType); setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(origLen)); QTimer::singleShot(0, this, SIGNAL(metaDataChanged())); QTimer::singleShot(0, this, SIGNAL(readyRead())); } void HelpNetworkReply::abort() { } qint64 HelpNetworkReply::readData(char *buffer, qint64 maxlen) { qint64 len = qMin(qint64(data.length()), maxlen); if (len) { memcpy(buffer, data.constData(), len); data.remove(0, len); } if (!data.length()) QTimer::singleShot(0, this, SIGNAL(finished())); return len; } class HelpNetworkAccessManager : public QNetworkAccessManager { public: HelpNetworkAccessManager(QObject *parent); protected: virtual QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData = 0); }; HelpNetworkAccessManager::HelpNetworkAccessManager(QObject *parent) : QNetworkAccessManager(parent) { } QNetworkReply *HelpNetworkAccessManager::createRequest(Operation /*op*/, const QNetworkRequest &request, QIODevice* /*outgoingData*/) { QString url = request.url().toString(); QHelpEngine& helpEngine = HelpPluginActivator::getInstance()->getQHelpEngine(); // TODO: For some reason the url to load is already wrong (passed from webkit) // though the css file and the references inside should work that way. One // possible problem might be that the css is loaded at the same level as the // html, thus a path inside the css like (../images/foo.png) might cd out of // the virtual folder // if (!helpEngine.findFile(url).isValid()) { // if (url.startsWith(AbstractHelpWebView::DocPath)) { // QUrl newUrl = request.url(); // if (!newUrl.path().startsWith(QLatin1String("/qdoc/"))) { // newUrl.setPath(QLatin1String("qdoc") + newUrl.path()); // url = newUrl.toString(); // } // } // } const QString &mimeType = HelpWebView::mimeFromUrl(url); const QByteArray &data = helpEngine.findFile(url).isValid() ? helpEngine.fileData(url) : HelpWebView::m_PageNotFoundMessage.arg(url).toUtf8(); return new HelpNetworkReply(request, data, mimeType.isEmpty() ? QLatin1String("application/octet-stream") : mimeType); } class HelpPage : public QWebPage { public: HelpPage(IEditorSite::Pointer editorSite, QObject *parent); protected: virtual QWebPage *createWindow(QWebPage::WebWindowType); virtual void triggerAction(WebAction action, bool checked = false); virtual bool acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, NavigationType type); private: IEditorSite::Pointer m_EditorSite; bool m_CloseNewTabIfNeeded; friend class HelpWebView; QUrl m_loadingUrl; Qt::MouseButtons m_pressedButtons; Qt::KeyboardModifiers m_keyboardModifiers; }; HelpPage::HelpPage(IEditorSite::Pointer editorSite, QObject *parent) : QWebPage(parent) , m_EditorSite(editorSite) , m_CloseNewTabIfNeeded(false) , m_pressedButtons(Qt::NoButton) , m_keyboardModifiers(Qt::NoModifier) { } -QWebPage *HelpPage::createWindow(QWebPage::WebWindowType type) +QWebPage *HelpPage::createWindow(QWebPage::WebWindowType /*type*/) { IEditorInput::Pointer input(new HelpEditorInput(QUrl())); IEditorPart::Pointer editorPart = m_EditorSite->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID); HelpEditor::Pointer helpEditor = editorPart.Cast(); HelpPage* newPage = static_cast(helpEditor->GetQWebPage()); if (newPage) newPage->m_CloseNewTabIfNeeded = m_CloseNewTabIfNeeded; m_CloseNewTabIfNeeded = false; return newPage; } void HelpPage::triggerAction(WebAction action, bool checked) { switch (action) { case OpenLinkInNewWindow: m_CloseNewTabIfNeeded = true; default: // fall through QWebPage::triggerAction(action, checked); break; } } bool HelpPage::acceptNavigationRequest(QWebFrame *, const QNetworkRequest &request, - QWebPage::NavigationType type) + QWebPage::NavigationType /*type*/) { - const bool closeNewTab = m_CloseNewTabIfNeeded; + //const bool closeNewTab = m_CloseNewTabIfNeeded; m_CloseNewTabIfNeeded = false; // open in an external browser if a http link const QUrl &url = request.url(); if (url.scheme() == QLatin1String("http")) { QDesktopServices::openUrl(url); return false; } // const QUrl &url = request.url(); // if (AbstractHelpWebView::launchWithExternalApp(url)) // { // if (closeNewTab) // QMetaObject::invokeMethod(centralWidget, "closeTab"); // return false; // } // if (type == QWebPage::NavigationTypeLinkClicked // && (m_keyboardModifiers & Qt::ControlModifier // || m_pressedButtons == Qt::MidButton)) // { // if (centralWidget->newEmptyTab()) // centralWidget->setSource(url); // m_pressedButtons = Qt::NoButton; // m_keyboardModifiers = Qt::NoModifier; // return false; // } // m_loadingUrl = url; // because of async page loading, we will hit some kind // of race condition while using a remote command, like a combination of // SetSource; SyncContent. SetSource would be called and SyncContents shortly // afterwards, but the page might not have finished loading and the old url // would be returned. return true; } // -- HelpWebView HelpWebView::HelpWebView(IEditorSite::Pointer editorSite, QWidget *parent, qreal zoom) : QWebView(parent) //, parentWidget(parent) , m_LoadFinished(false) , m_HelpEngine(HelpPluginActivator::getInstance()->getQHelpEngine()) { setAcceptDrops(false); setPage(new HelpPage(editorSite, parent)); page()->setNetworkAccessManager(new HelpNetworkAccessManager(this)); QAction* action = pageAction(QWebPage::OpenLinkInNewWindow); action->setText(tr("Open Link in New Tab")); if (!parent) action->setVisible(false); pageAction(QWebPage::DownloadLinkToDisk)->setVisible(false); pageAction(QWebPage::DownloadImageToDisk)->setVisible(false); pageAction(QWebPage::OpenImageInNewWindow)->setVisible(false); connect(pageAction(QWebPage::Copy), SIGNAL(changed()), this, SLOT(actionChanged())); connect(pageAction(QWebPage::Back), SIGNAL(changed()), this, SLOT(actionChanged())); connect(pageAction(QWebPage::Forward), SIGNAL(changed()), this, SLOT(actionChanged())); connect(page(), SIGNAL(linkHovered(QString,QString,QString)), this, SIGNAL(highlighted(QString))); connect(this, SIGNAL(urlChanged(QUrl)), this, SIGNAL(sourceChanged(QUrl))); connect(this, SIGNAL(loadStarted()), this, SLOT(setLoadStarted())); connect(this, SIGNAL(loadFinished(bool)), this, SLOT(setLoadFinished(bool))); connect(page(), SIGNAL(printRequested(QWebFrame*)), this, SIGNAL(printRequested())); setFont(viewerFont()); setTextSizeMultiplier(zoom == 0.0 ? 1.0 : zoom); } HelpWebView::~HelpWebView() { } QFont HelpWebView::viewerFont() const { //if (m_HelpEngine.usesBrowserFont()) // return m_HelpEngine.browserFont(); QWebSettings *webSettings = QWebSettings::globalSettings(); return QFont(webSettings->fontFamily(QWebSettings::StandardFont), webSettings->fontSize(QWebSettings::DefaultFontSize)); } void HelpWebView::setViewerFont(const QFont &font) { QWebSettings *webSettings = settings(); webSettings->setFontFamily(QWebSettings::StandardFont, font.family()); webSettings->setFontSize(QWebSettings::DefaultFontSize, font.pointSize()); } void HelpWebView::scaleUp() { setTextSizeMultiplier(textSizeMultiplier() + 0.1); } void HelpWebView::scaleDown() { setTextSizeMultiplier(qMax(0.0, textSizeMultiplier() - 0.1)); } void HelpWebView::resetScale() { setTextSizeMultiplier(1.0); } bool HelpWebView::handleForwardBackwardMouseButtons(QMouseEvent *e) { if (e->button() == Qt::XButton1) { triggerPageAction(QWebPage::Back); return true; } if (e->button() == Qt::XButton2) { triggerPageAction(QWebPage::Forward); return true; } return false; } QUrl HelpWebView::source() const { HelpPage *currentPage = static_cast (page()); if (currentPage && !hasLoadFinished()) { // see HelpPage::acceptNavigationRequest(...) return currentPage->m_loadingUrl; } return url(); } void HelpWebView::setSource(const QUrl &url) { if (m_HelpEngine.findFile(url).isValid()) load(url); else setHtml(m_PageNotFoundMessage.arg(url.toString())); } void HelpWebView::wheelEvent(QWheelEvent *e) { if (e->modifiers()& Qt::ControlModifier) { e->accept(); e->delta() > 0 ? scaleUp() : scaleDown(); } else { QWebView::wheelEvent(e); } } void HelpWebView::mouseReleaseEvent(QMouseEvent *e) { #ifndef Q_OS_LINUX if (handleForwardBackwardMouseButtons(e)) return; #endif QWebView::mouseReleaseEvent(e); } void HelpWebView::actionChanged() { QAction *a = qobject_cast(sender()); if (a == pageAction(QWebPage::Copy)) emit copyAvailable(a->isEnabled()); else if (a == pageAction(QWebPage::Back)) emit backwardAvailable(a->isEnabled()); else if (a == pageAction(QWebPage::Forward)) emit forwardAvailable(a->isEnabled()); } void HelpWebView::mousePressEvent(QMouseEvent *event) { #ifdef Q_OS_LINUX if (handleForwardBackwardMouseButtons(event)) return; #endif HelpPage *currentPage = static_cast(page()); if (currentPage) { currentPage->m_pressedButtons = event->buttons(); currentPage->m_keyboardModifiers = event->modifiers(); } QWebView::mousePressEvent(event); } void HelpWebView::setLoadStarted() { m_LoadFinished = false; } void HelpWebView::setLoadFinished(bool ok) { m_LoadFinished = ok; emit sourceChanged(url()); } QString HelpWebView::mimeFromUrl(const QUrl &url) { const QString &path = url.path(); const int index = path.lastIndexOf(QLatin1Char('.')); const QByteArray &ext = path.mid(index).toUtf8().toLower(); const ExtensionMap *e = extensionMap; while (e->extension) { if (ext == e->extension) return QLatin1String(e->mimeType); ++e; } return QLatin1String(""); } bool HelpWebView::canOpenPage(const QString &url) { return !mimeFromUrl(url).isEmpty(); } bool HelpWebView::isLocalUrl(const QUrl &url) { const QString &scheme = url.scheme(); return scheme.isEmpty() || scheme == QLatin1String("file") || scheme == QLatin1String("qrc") || scheme == QLatin1String("data") || scheme == QLatin1String("qthelp") || scheme == QLatin1String("about"); } bool HelpWebView::launchWithExternalApp(const QUrl &url) { if (isLocalUrl(url)) { const QHelpEngine& helpEngine = HelpPluginActivator::getInstance()->getQHelpEngine(); const QUrl &resolvedUrl = helpEngine.findFile(url); if (!resolvedUrl.isValid()) return false; const QString& path = resolvedUrl.path(); if (!canOpenPage(path)) { QTemporaryFile tmpTmpFile; if (!tmpTmpFile.open()) return false; const QString &extension = QFileInfo(path).completeSuffix(); QFile actualTmpFile(tmpTmpFile.fileName() % QLatin1String(".") % extension); if (!actualTmpFile.open(QIODevice::ReadWrite | QIODevice::Truncate)) return false; actualTmpFile.write(helpEngine.fileData(resolvedUrl)); actualTmpFile.close(); return QDesktopServices::openUrl(QUrl(actualTmpFile.fileName())); } } else if (url.scheme() == QLatin1String("http")) { return QDesktopServices::openUrl(url); } return false; } void HelpWebView::home() { setSource(m_HelpEngine.homePage()); } void HelpWebView::print() { QPrinter printer; QPrintDialog *dialog = new QPrintDialog(&printer, this); dialog->setWindowTitle(tr("Print Document")); if(hasSelection()) { dialog->addEnabledOption(QAbstractPrintDialog::PrintSelection); } if(dialog->exec() == QDialog::Accepted) { QWebView::print(&printer); } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryLogView.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryLogView.cpp index dee4c45928..ce32004946 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryLogView.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryLogView.cpp @@ -1,56 +1,50 @@ /*=================================================================== 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. ===================================================================*/ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif #include "berryLogView.h" #include "berryQtLogView.h" #include namespace berry { LogView::LogView() { } -LogView::LogView(const LogView& other) -{ - Q_UNUSED(other) - throw std::runtime_error("Copy constructor not implemented"); -} - void LogView::CreateQtPartControl(QWidget* parent) { QHBoxLayout* layout = new QHBoxLayout(parent); layout->setContentsMargins(0,0,0,0); QtLogView* logView = new QtLogView(parent); layout->addWidget(logView); } void LogView::SetFocus() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryLogView.h b/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryLogView.h index 4d08e09390..3cb8ad7486 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryLogView.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryLogView.h @@ -1,45 +1,44 @@ /*=================================================================== 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 BERRYLOGVIEW_H_ #define BERRYLOGVIEW_H_ #include #include "berryQtViewPart.h" namespace berry { class LogView : public QtViewPart { Q_OBJECT public: LogView(); - LogView(const LogView& other); void SetFocus(); protected: void CreateQtPartControl(QWidget* parent); }; } // namespace berry #endif /*BERRYLOGVIEW_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryQtLogView.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryQtLogView.cpp index adcfddcd85..d5bad2f170 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryQtLogView.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryQtLogView.cpp @@ -1,168 +1,168 @@ /*=================================================================== 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. ===================================================================*/ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif #include "berryQtLogView.h" #include "berryQtLogPlugin.h" #include #include #include #include #include #include #include namespace berry { QtLogView::QtLogView(QWidget *parent) : QWidget(parent) { berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); berry::IBerryPreferences::Pointer prefs = (prefService->GetSystemPreferences()->Node("org_blueberry_ui_qt_log")) .Cast(); prefs->PutBool("ShowAdvancedFields", false); prefs->PutBool("ShowCategory", true); bool showAdvancedFields = false; ui.setupUi(this); model = QtLogPlugin::GetInstance()->GetLogModel(); model->SetShowAdvancedFiels( showAdvancedFields ); filterModel = new QSortFilterProxyModel(this); filterModel->setSourceModel(model); filterModel->setFilterKeyColumn(-1); #ifdef __APPLE__ QFont fnt = ui.tableView->font(); fnt.setPointSize(11); ui.tableView->setFont(fnt); #endif ui.tableView->setModel(filterModel); ui.tableView->verticalHeader()->setVisible(false); ui.tableView->horizontalHeader()->setStretchLastSection(true); connect( ui.filterContent, SIGNAL( textChanged( const QString& ) ), this, SLOT( slotFilterChange( const QString& ) ) ); connect( filterModel, SIGNAL( rowsInserted ( const QModelIndex &, int, int ) ), this, SLOT( slotRowAdded( const QModelIndex &, int , int ) ) ); connect( ui.SaveToClipboard, SIGNAL( clicked()),this, SLOT(on_SaveToClipboard_clicked())); ui.ShowAdvancedFields->setChecked( showAdvancedFields ); } QtLogView::~QtLogView() { } void QtLogView::slotScrollDown( ) { ui.tableView->scrollToBottom(); } void QtLogView::slotFilterChange( const QString& q ) { filterModel->setFilterRegExp(QRegExp(q, Qt::CaseInsensitive, QRegExp::FixedString)); } -void QtLogView::slotRowAdded ( const QModelIndex & /*parent*/, int start, int end ) +void QtLogView::slotRowAdded ( const QModelIndex & /*parent*/, int /*start*/, int /*end*/ ) { ui.tableView->setVisible(false); ui.tableView->resizeRowsToContents(); //only resize columns when first entry is added static bool first = true; if(first) { ui.tableView->resizeColumnsToContents(); first = false; } ui.tableView->setVisible(true); QTimer::singleShot(0,this,SLOT( slotScrollDown() ) ); } -void QtLogView::showEvent( QShowEvent * event ) +void QtLogView::showEvent( QShowEvent * /*event*/ ) { ui.tableView->setVisible(false); ui.tableView->resizeColumnsToContents(); ui.tableView->resizeRowsToContents(); ui.tableView->setVisible(true); } void QtLogView::on_ShowAdvancedFields_clicked( bool checked ) { ui.tableView->setVisible(false); QtLogPlugin::GetInstance()->GetLogModel()->SetShowAdvancedFiels( checked ); ui.tableView->resizeColumnsToContents(); ui.tableView->setVisible(true); berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); berry::IBerryPreferences::Pointer prefs = (prefService->GetSystemPreferences()->Node("org_blueberry_ui_qt_log")) .Cast(); prefs->PutBool("ShowAdvancedFields", checked); prefs->Flush(); } void QtLogView::on_ShowCategory_clicked( bool checked ) { ui.tableView->setVisible(false); QtLogPlugin::GetInstance()->GetLogModel()->SetShowCategory( checked ); ui.tableView->resizeColumnsToContents(); ui.tableView->setVisible(true); berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); berry::IBerryPreferences::Pointer prefs = (prefService->GetSystemPreferences()->Node("org_blueberry_ui_qt_log")) .Cast(); prefs->PutBool("ShowCategory", checked); prefs->Flush(); } void QtLogView::on_SaveToClipboard_clicked() { QClipboard *clipboard = QApplication::clipboard(); QString loggingMessagesAsText = QString(""); for (int i=0; imodel()->rowCount(); i++) { for (int j=0; jmodel()->columnCount(); j++) { QModelIndex index = ui.tableView->model()->index(i, j); loggingMessagesAsText += ui.tableView->model()->data(index, Qt::DisplayRole).toString() + " "; } loggingMessagesAsText += "\n"; } clipboard->setText(loggingMessagesAsText); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryQtPlatformLogModel.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryQtPlatformLogModel.cpp index 4d6427635f..5e2f93f7e8 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryQtPlatformLogModel.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryQtPlatformLogModel.cpp @@ -1,345 +1,346 @@ /*=================================================================== 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. ===================================================================*/ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif #include "berryQtPlatformLogModel.h" #include "berryQtLogPlugin.h" #include "berryPlatform.h" #include "mbilogLoggingTypes.h" #include #include #include #include #include #include #include +#include namespace berry { const QString QtPlatformLogModel::Error = QString("Error"); const QString QtPlatformLogModel::Warn = QString("Warning"); const QString QtPlatformLogModel::Fatal = QString("Fatal"); const QString QtPlatformLogModel::Info = QString("Info"); const QString QtPlatformLogModel::Debug = QString("Debug"); void QtPlatformLogModel::slotFlushLogEntries() { m_Mutex.lock(); QList *tmp=m_Active; m_Active=m_Pending; m_Pending=tmp; m_Mutex.unlock(); int num = static_cast(m_Pending->size()); if (num > 0) { int row = static_cast(m_Entries.size()); this->beginInsertRows(QModelIndex(), row, row+num-1); do { m_Entries.push_back(m_Pending->front()); m_Pending->pop_front(); } while(--num); this->endInsertRows(); } } void QtPlatformLogModel::addLogEntry(const mbilog::LogMessage &msg) { m_Mutex.lock(); //mbilog::BackendCout::FormatSmart(msg); FormatSmart is not static any more. So commented out this statement. Todo: fix m_Active->push_back(ExtendedLogMessage(msg)); m_Mutex.unlock(); emit signalFlushLogEntries(); } void QtPlatformLogModel::SetShowAdvancedFiels( bool showAdvancedFiels ) { if( m_ShowAdvancedFiels != showAdvancedFiels ) { m_ShowAdvancedFiels = showAdvancedFiels; this->beginResetModel(); this->endResetModel(); } } void QtPlatformLogModel::SetShowCategory( bool showCategory ) { if( m_ShowCategory != showCategory ) { m_ShowCategory = showCategory; this->beginResetModel(); this->endResetModel(); } } void QtPlatformLogModel::addLogEntry(const ctkPluginFrameworkEvent& event) { int level = mbilog::Info; if (event.getType() == ctkPluginFrameworkEvent::PLUGIN_ERROR) { level = mbilog::Error; } else if (event.getType() == ctkPluginFrameworkEvent::FRAMEWORK_WAIT_TIMEDOUT || event.getType() == ctkPluginFrameworkEvent::PLUGIN_WARNING) { level = mbilog::Warn; } mbilog::LogMessage msg(level,"n/a",-1,"n/a"); QString str; QDebug dbg(&str); dbg << event; msg.message = str.toStdString(); //msg.moduleName = event.getPlugin()->getSymbolicName().toStdString(); addLogEntry(msg); } QtPlatformLogModel::QtPlatformLogModel(QObject* parent) : QAbstractTableModel(parent), m_ShowAdvancedFiels(false), m_ShowCategory(true) { m_Active=new QList; m_Pending=new QList; connect(this, SIGNAL(signalFlushLogEntries()), this, SLOT( slotFlushLogEntries() ), Qt::QueuedConnection ); QtLogPlugin::GetInstance()->GetContext()->connectFrameworkListener(this, SLOT(addLogEntry(ctkPluginFrameworkEvent))); myBackend = new QtLogBackend(this); } QtPlatformLogModel::~QtPlatformLogModel() { disconnect(this, SIGNAL(signalFlushLogEntries()), this, SLOT( slotFlushLogEntries() )); QtLogPlugin::GetInstance()->GetContext()->disconnectFrameworkListener(this); // dont delete and unregister backend, only deactivate it to avoid thread syncronization issues cause mbilog::UnregisterBackend is not threadsafe // will be fixed. // delete myBackend; // delete m_Active; // delete m_Pending; m_Mutex.lock(); myBackend->Deactivate(); m_Mutex.unlock(); } // QT Binding int QtPlatformLogModel::rowCount(const QModelIndex&) const { return static_cast(m_Entries.size()); } int QtPlatformLogModel::columnCount(const QModelIndex&) const { int returnValue = 2; if( m_ShowAdvancedFiels ) returnValue += 7; if( m_ShowCategory ) returnValue += 1; return returnValue; } /* struct LogEntry { LogEntry(const std::string& msg, const std::string& src, std::time_t t) : message(msg.c_str()), moduleName(src.c_str()),time(std::clock()) { } QString message; clock_t time; QString level; QString filePath; QString lineNumber; QString moduleName; QString category; QString function; LogEntry(const mbilog::LogMessage &msg) { message = msg.message.c_str(); filePath = msg.filePath; std::stringstream out; out << msg.lineNumber; lineNumber = out.str().c_str(); moduleName = msg.moduleName; category = msg.category.c_str(); function = msg.functionName; time=std::clock(); } }; */ QVariant QtPlatformLogModel::data(const QModelIndex& index, int role) const { const ExtendedLogMessage *msg = &m_Entries[index.row()]; if (role == Qt::DisplayRole) { switch (index.column()) { case 0: if (m_ShowAdvancedFiels) return msg->getTime(); else return msg->getLevel(); case 1: if (m_ShowAdvancedFiels) return msg->getLevel(); else return msg->getMessage(); case 2: if (m_ShowAdvancedFiels) return msg->getMessage(); else return msg->getCategory(); case 3: if (m_ShowAdvancedFiels && m_ShowCategory) return msg->getCategory(); else if (m_ShowAdvancedFiels && !m_ShowCategory) return msg->getModuleName(); else break; case 4: if (m_ShowAdvancedFiels && m_ShowCategory) return msg->getModuleName(); else if (m_ShowAdvancedFiels && !m_ShowCategory) return msg->getFunctionName(); else break; case 5: if (m_ShowAdvancedFiels && m_ShowCategory) return msg->getFunctionName(); else if (m_ShowAdvancedFiels && !m_ShowCategory) return msg->getPath(); else break; case 6: if (m_ShowAdvancedFiels && m_ShowCategory) return msg->getPath(); else if (m_ShowAdvancedFiels && !m_ShowCategory) return msg->getLine(); else break; case 7: if (m_ShowAdvancedFiels && m_ShowCategory) return msg->getLine(); else break; } } else if( role == Qt::DecorationRole ) { if ( (m_ShowAdvancedFiels && index.column()==1) || (!m_ShowAdvancedFiels && index.column()==0) ) { QString file ( ":/org_blueberry_ui_qt_log/information.png" ); if( msg->message.level == mbilog::Error ) file = ":/org_blueberry_ui_qt_log/error.png"; else if( msg->message.level == mbilog::Warn ) file = ":/org_blueberry_ui_qt_log/warning.png"; else if( msg->message.level == mbilog::Debug ) file = ":/org_blueberry_ui_qt_log/debug.png"; else if( msg->message.level == mbilog::Fatal ) file = ":/org_blueberry_ui_qt_log/fatal.png"; QIcon icon(file); return QVariant(icon); } } return QVariant(); } QVariant QtPlatformLogModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { if( m_ShowAdvancedFiels && m_ShowCategory ) { switch (section) { case 0: return QVariant(" Time "); case 1: return QVariant(" Level "); case 2: return QVariant(" Message "); case 3: return QVariant(" Category "); case 4: return QVariant(" Module "); case 5: return QVariant(" Function "); case 6: return QVariant(" File "); case 7: return QVariant(" Line "); } } else if (m_ShowAdvancedFiels && !m_ShowCategory) { switch (section) { case 0: return QVariant(" Time "); case 1: return QVariant(" Level "); case 2: return QVariant(" Message "); case 3: return QVariant(" Module "); case 4: return QVariant(" Function "); case 5: return QVariant(" File "); case 6: return QVariant(" Line "); } } else //!m_ShowAdvancedFiels, m_ShowCategory is not handled seperately because it only activates case 2 { switch (section) { case 0: return QVariant(" Level "); case 1: return QVariant(" Message "); case 2: return QVariant(" Category "); } } } return QVariant(); } QVariant QtPlatformLogModel::ExtendedLogMessage::getTime() const { std::stringstream ss; std::locale C("C"); ss.imbue(C); ss << std::setw(7) << std::setprecision(3) << std::fixed << ((double)this->time)/CLOCKS_PER_SEC; return QVariant(QString(ss.str().c_str())); } QString QtPlatformLogModel::GetDataAsString() { QString returnValue(""); for (int message=0; messagerowCount(QModelIndex()); message++) { for (int column=0; columncolumnCount(QModelIndex()); column++) { returnValue += " " + this->data(this->index(message,column),Qt::DisplayRole).toString(); } returnValue += "\n"; } return returnValue; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectBrowserView.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectBrowserView.cpp index 9bf1671b71..dd0720ce9a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectBrowserView.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectBrowserView.cpp @@ -1,279 +1,271 @@ /*=================================================================== 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. ===================================================================*/ #ifdef __MINGW32__ // We need to inlclude winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif #include #include #include #include #include "berryObjectBrowserView.h" #include "berryDebugUtil.h" #include "berryDebugBreakpointManager.h" namespace berry { const std::string ObjectBrowserView::VIEW_ID = "objectbrowser"; ObjectBrowserView::ObjectBrowserView() : m_ActionToggleBreakpoint(this), m_ActionEnableBreakpoint(this), m_ActionDisableBreakpoint(this) { #ifdef BLUEBERRY_DEBUG_SMARTPOINTER m_Useful = true; #else m_Useful = false; #endif } -ObjectBrowserView::ObjectBrowserView(const ObjectBrowserView& other) - : m_ActionToggleBreakpoint(this), m_ActionEnableBreakpoint(this), - m_ActionDisableBreakpoint(this) -{ - Q_UNUSED(other) - throw std::runtime_error("Copy constructor not implemented"); -} - void ObjectBrowserView::Init(IViewSite::Pointer site, IMemento::Pointer memento) { QtViewPart::Init(site, memento); m_StateMemento = memento; } void ObjectBrowserView::CreateQtPartControl(QWidget* parent) { if (m_Useful) { m_Controls.setupUi(parent); m_ProxyModel = new QSortFilterProxyModel(m_Controls.m_TreeView); m_ObjectModel = new QtObjectTableModel(m_ProxyModel); m_ProxyModel->setSourceModel(m_ObjectModel); m_Controls.m_TreeView->setModel(m_ProxyModel); m_Controls.m_TreeView->setSortingEnabled(true); m_Controls.m_TreeView->setContextMenuPolicy(Qt::CustomContextMenu); m_ActionToggleBreakpoint.setText(QString("Toggle Breakpoint")); m_ActionToggleBreakpoint.setCheckable(true); m_ContextMenu.addAction(&m_ActionToggleBreakpoint); QToolBar* toolbar = new QToolBar(parent); QAction* resetAction = toolbar->addAction("Reset"); toolbar->addAction("Show Breakpoints Only"); connect(resetAction, SIGNAL(triggered(bool)), this, SLOT(ResetAction(bool))); connect(m_Controls.m_TreeView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(SelectionChanged(const QItemSelection&, const QItemSelection&))); connect(m_Controls.m_TreeView, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(ContextMenuRequested(const QPoint&))); // context menu actions connect(&m_ActionToggleBreakpoint, SIGNAL(triggered(bool)), this, SLOT(ToggleBreakpoint(bool))); parent->layout()->setMenuBar(toolbar); RestoreGuiState(m_StateMemento); m_StateMemento = 0; } else { QVBoxLayout* layout = new QVBoxLayout(parent); QLabel* label = new QLabel(parent); label->setText( "Set the CMake variable BLUEBERRY_DEBUG_SMARTPOINTER to ON for a useful object browser."); label->setWordWrap(true); label->setAlignment(Qt::AlignTop); layout->addWidget(label); } } void ObjectBrowserView::RestoreGuiState(IMemento::Pointer memento) { if (memento) { IMemento::Pointer columnWidths = memento->GetChild("columnWidths"); if (columnWidths) { int colWidth = 0; if (columnWidths->GetInteger("column0", colWidth)) { m_Controls.m_TreeView->setColumnWidth(0, colWidth); } if (columnWidths->GetInteger("column1", colWidth)) { m_Controls.m_TreeView->setColumnWidth(1, colWidth); } } IMemento::Pointer splitter = memento->GetChild("splitter"); if (splitter) { QList sizes; int size = 200; splitter->GetInteger("first", size); sizes.push_back(size); splitter->GetInteger("second", size); sizes.push_back(size); m_Controls.m_Splitter->setSizes(sizes); } } } void ObjectBrowserView::ResetAction(bool /*checked*/) { m_ObjectModel->ResetData(); } void ObjectBrowserView::SelectionChanged(const QItemSelection& selected, const QItemSelection& /*deselected*/) { QList indexes = selected.indexes(); if (indexes.empty()) { m_Controls.m_DetailsView->clear(); return; } QModelIndex index = indexes.front(); if (!index.parent().isValid()) { m_Controls.m_DetailsView->clear(); } QVariant data = m_ProxyModel->data(index, Qt::UserRole); if (data.isValid()) { const ObjectItem* item = static_cast (data.value ()); if (item) { const Object* obj = 0; if (item->type == ObjectItem::INSTANCE) obj = item->obj; else if (item->type == ObjectItem::SMARTPOINTER) { const ObjectItem* item = static_cast (m_ProxyModel->data(index.parent(), Qt::UserRole).value ()); if (item) obj = item->obj; } if (obj) { QString str; QDebug ss(&str); obj->Print(ss); m_Controls.m_DetailsView->setPlainText(str); } else { m_Controls.m_DetailsView->setPlainText(QString("0")); } } else { m_Controls.m_DetailsView->setPlainText(QString("0")); } } } void ObjectBrowserView::ContextMenuRequested(const QPoint& p) { QModelIndex index = m_Controls.m_TreeView->selectionModel()->currentIndex(); if (index.isValid()) { QVariant data = m_ProxyModel->data(index, Qt::UserRole); if (!data.isValid()) return; const ObjectItem* item = static_cast (data.value ()); if (item->type == ObjectItem::CLASS) return; m_ContextMenu.exec(m_Controls.m_TreeView->mapToGlobal(p)); } } void ObjectBrowserView::ToggleBreakpoint(bool checked) { QModelIndex index = m_Controls.m_TreeView->selectionModel()->currentIndex(); if (index.isValid()) { QVariant data = m_ProxyModel->data(index, Qt::UserRole); if (!data.isValid()) return; const ObjectItem* item = static_cast (data.value ()); if (item->type == ObjectItem::INSTANCE) { #ifdef BLUEBERRY_DEBUG_SMARTPOINTER if (checked) DebugUtil::GetBreakpointManager()->AddObjectBreakpoint(item->obj->GetTraceId()); else DebugUtil::GetBreakpointManager()->RemoveObjectBreakpoint(item->obj->GetTraceId()); #endif } else if (item->type == ObjectItem::SMARTPOINTER) { if (checked) DebugUtil::GetBreakpointManager()->AddSmartpointerBreakpoint(item->spId); else DebugUtil::GetBreakpointManager()->RemoveSmartpointerBreakpoint( item->spId); } } } void ObjectBrowserView::SetFocus() { if (m_Useful) { m_Controls.m_TreeView->setFocus(); } } void ObjectBrowserView::SaveState(IMemento::Pointer memento) { if (!m_Useful) return; IMemento::Pointer cols = memento->CreateChild("columnWidths"); cols->PutInteger("column0", m_Controls.m_TreeView->columnWidth(0)); cols->PutInteger("column1", m_Controls.m_TreeView->columnWidth(1)); QList sizes(m_Controls.m_Splitter->sizes()); IMemento::Pointer splitter = memento->CreateChild("splitter"); splitter->PutInteger("first", sizes[0]); splitter->PutInteger("second", sizes[1]); // delete the tree view here in order to delete the underlying model // which in turn unregisters the object listener. Otherwise, we get // notifications of deleted objects during workbench shutdown which // leads to segmentation faults m_Controls.m_TreeView->deleteLater(); } } //namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectBrowserView.h b/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectBrowserView.h index 98330a34fc..6cfc57d68b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectBrowserView.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectBrowserView.h @@ -1,101 +1,100 @@ /*=================================================================== 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 BERRY_OBJECTINSPECTORVIEW_H_INCLUDED #define BERRY_OBJECTINSPECTORVIEW_H_INCLUDED #include #include #include #include "berryQtObjectTableModel.h" #include #include class QAbstractProxyModel; namespace berry { /*! * \ingroup org_blueberry_ui_qt_objectinspector_internal * * \brief Object Inspector * * You need to reimplement the methods SetFocus() and CreateQtPartControl(QWidget*) * from berry::QtViewPart * * \sa berry::QtViewPart */ class ObjectBrowserView : public berry::QtViewPart { Q_OBJECT public: static const std::string VIEW_ID; ObjectBrowserView(); - ObjectBrowserView(const ObjectBrowserView& other); void Init(IViewSite::Pointer site, IMemento::Pointer memento); /*! * \brief Gives focus to a specific control in the view * This method is called from the framework when the view is activated. */ void SetFocus(); void SaveState(IMemento::Pointer memento); protected slots: void ResetAction(bool checked); void SelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); void ContextMenuRequested(const QPoint&); void ToggleBreakpoint(bool checked); protected: /*! * \brief Builds the user interface of the view * This method is called from the framework. The parent widget has no layout, so * you should set one adapted to your needs. */ void CreateQtPartControl(QWidget* parent); void RestoreGuiState(IMemento::Pointer memento); private: Ui::QtObjectBrowserView m_Controls; QtObjectTableModel* m_ObjectModel; QAbstractProxyModel* m_ProxyModel; QAction m_ActionToggleBreakpoint; QAction m_ActionEnableBreakpoint; QAction m_ActionDisableBreakpoint; QMenu m_ContextMenu; IMemento::Pointer m_StateMemento; bool m_Useful; }; } //namespace berry #endif /*BERRY_OBJECTINSPECTORVIEW_H_INCLUDED*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectItem.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectItem.cpp index f7e9fe39e0..07c450e7b0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectItem.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectItem.cpp @@ -1,107 +1,105 @@ /*=================================================================== 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 "berryObjectItem.h" namespace berry { ObjectItem::ObjectItem() { type = CLASS; - className = 0; parent = 0; } -ObjectItem::ObjectItem(const char* className) : +ObjectItem::ObjectItem(const QString& className) : className(className), type(CLASS), parent(0) { } ObjectItem::ObjectItem(const Object* obj, ObjectItem* parent) : obj(obj), type(INSTANCE), parent(parent) { } ObjectItem::ObjectItem(unsigned int spId, ObjectItem* parent) : spId(spId), type(SMARTPOINTER), parent(parent) { } ObjectItem::ObjectItem(const ObjectItem& item) : type(item.type), children(item.children), parent(item.parent) { switch (type) { case CLASS: className = item.className; break; case INSTANCE: obj = item.obj; break; case SMARTPOINTER: spId = item.spId; break; } } ObjectItem::~ObjectItem() { qDeleteAll(children); } ObjectItem& ObjectItem::operator=(const ObjectItem& item) { type = item.type; children = item.children; parent = item.parent; switch (type) { case CLASS: className = item.className; break; case INSTANCE: obj = item.obj; break; case SMARTPOINTER: spId = item.spId; break; } return *this; } bool ObjectItem::operator==(const ObjectItem& item) const { if (type != item.type) return false; switch (type) { case CLASS: { - std::string str(className); - return str == item.className; + return className == item.className; } case INSTANCE: return obj == item.obj; case SMARTPOINTER: return spId == item.spId; }; return false; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectItem.h b/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectItem.h index d18823291c..a07f2ef5e7 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectItem.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryObjectItem.h @@ -1,67 +1,68 @@ /*=================================================================== 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 BERRYOBJECTITEM_H_ #define BERRYOBJECTITEM_H_ #include #include namespace berry { struct ObjectItem { enum Type { CLASS = 0, INSTANCE = 1, SMARTPOINTER = 2 }; union { const Object* obj; - const char* className; unsigned int spId; }; + QString className; + Type type; QList children; ObjectItem* parent; ObjectItem(); - ObjectItem(const char* className); + ObjectItem(const QString& className); ObjectItem(const Object* obj, ObjectItem* parent); ObjectItem(unsigned int spId, ObjectItem* parent); ObjectItem(const ObjectItem& item); ~ObjectItem(); ObjectItem& operator=(const ObjectItem& item); bool operator==(const ObjectItem& item) const; }; } #endif /* BERRYOBJECTITEM_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryQtObjectTableModel.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryQtObjectTableModel.cpp index c6a7cee470..8f7e384296 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryQtObjectTableModel.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryQtObjectTableModel.cpp @@ -1,590 +1,590 @@ /*=================================================================== 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 "berryQtObjectTableModel.h" #include #include #include #include #include #include namespace berry { class DebugObjectListener: public IDebugObjectListener { public: DebugObjectListener(QtObjectTableModel* model) : model(model) { } Events::Types GetEventTypes() const { return Events::ALL; } void ObjectCreated(const Object* obj) { model->ObjectCreated(obj); } void ObjectDestroyed(const Object* obj) { model->ObjectDestroyed(obj); } void ObjectTracingChanged(unsigned int /*traceId*/, bool /*enabled = true*/, const Object* /*obj*/ = 0) { } void SmartPointerCreated(unsigned int id, const Object* obj) { model->SmartPointerCreated(id, obj); } void SmartPointerDestroyed(unsigned int id, const Object* obj) { model->SmartPointerDestroyed(id, obj); } private: QtObjectTableModel* model; }; QtObjectTableModel::QtObjectTableModel(QObject* parent) : QAbstractItemModel(parent), objectListener(new DebugObjectListener(this)) { QList objects = DebugUtil::GetRegisteredObjects(); for (QList::const_iterator i = objects.begin(); i != objects.end(); ++i) { - const char* name = (*i)->GetClassName(); + QString name = (*i)->GetClassName(); ObjectItem* classItem = 0; QListIterator iter(indexData); bool classFound = false; while (iter.hasNext()) { classItem = iter.next(); - if (std::strcmp(classItem->className, name) == 0) + if (name == classItem->className) { classFound = true; break; } } ObjectItem* instanceItem = new ObjectItem(*i, 0); // get smartpointer ids QList spIds(DebugUtil::GetSmartPointerIDs(*i)); for (QList::const_iterator spIdIter = spIds.begin(); spIdIter != spIds.end(); ++spIdIter) { ObjectItem* spItem = new ObjectItem((unsigned int) (*spIdIter), instanceItem); instanceItem->children.push_back(spItem); } if (classFound) { instanceItem->parent = classItem; classItem->children.push_back(instanceItem); } else { classItem = new ObjectItem(name); indexData.push_back(classItem); instanceItem->parent = classItem; classItem->children.push_back(instanceItem); } } QTimer* timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(UpdatePendingData())); timer->start(500); - DebugUtil::AddObjectListener(objectListener.GetPointer()); + DebugUtil::AddObjectListener(objectListener.data()); } QtObjectTableModel::~QtObjectTableModel() { - DebugUtil::RemoveObjectListener(objectListener.GetPointer()); + DebugUtil::RemoveObjectListener(objectListener.data()); qDeleteAll(pendingData); qDeleteAll(indexData); } QModelIndex QtObjectTableModel::index(int row, int column, const QModelIndex& parent) const { if (parent.isValid()) { if (parent.parent().isValid()) { ObjectItem* data = static_cast (parent.internalPointer()); poco_assert(data->type == ObjectItem::INSTANCE) ; return createIndex(row, column, data->children[row]); } else { ObjectItem* data = static_cast(parent.internalPointer()); poco_assert(data->type == ObjectItem::CLASS); return createIndex(row, column, data->children[row]); } } else return createIndex(row, column, indexData[row]); } QModelIndex QtObjectTableModel::parent(const QModelIndex& index) const { ObjectItem* data = static_cast(index.internalPointer()); if (data->parent) { return createIndex(data->parent->children.indexOf(data), 0, data->parent); } else { return QModelIndex(); } } int QtObjectTableModel::rowCount(const QModelIndex& parent) const { if (parent.isValid()) { if (parent.parent().isValid()) { if (parent.parent().parent().isValid()) // smart pointer parent return 0; // instance parent ObjectItem* data = static_cast(parent.internalPointer()); poco_assert(data->type == ObjectItem::INSTANCE); return data->children.size(); } else { // class parent ObjectItem* data = static_cast(parent.internalPointer()); poco_assert(data->type == ObjectItem::CLASS); return data->children.size(); } } else { // root return indexData.size(); } } int QtObjectTableModel::columnCount(const QModelIndex&) const { return 2; } QVariant QtObjectTableModel::data(const QModelIndex& index, int role) const { if (role == Qt::DisplayRole) { if (index.column() == 0) { if (index.parent().isValid()) { QModelIndex parentIndex = index.parent(); if (parentIndex.parent().isValid()) { ObjectItem* data = static_cast(index.internalPointer()); poco_assert(data->type == ObjectItem::SMARTPOINTER); return QVariant(QString("SmartPointer (id: ") + QString::number(data->spId) + QString(")")); } else { ObjectItem* data = static_cast(index.internalPointer()); poco_assert(data->type == ObjectItem::INSTANCE); #ifdef BLUEBERRY_DEBUG_SMARTPOINTER QString text = QString::number(data->obj->GetTraceId()); #else QString text; #endif text += QString(" (References: ") + QString::number(data->obj->GetReferenceCount()) + QString(")"); return QVariant(text); } } else { ObjectItem* data = static_cast(index.internalPointer()); poco_assert(data->type == ObjectItem::CLASS); return QVariant(QString(data->className) + " (" + QString::number(data->children.size()) + ")"); } } } else if (role == Qt::CheckStateRole && index.column() == 1) { ObjectItem* data = static_cast(index.internalPointer()); if (data->type == ObjectItem::INSTANCE) { QVariant var = (DebugUtil::IsTraced(data->obj) ? Qt::Checked : Qt::Unchecked); return var; } else if (data->type == ObjectItem::CLASS) { QVariant var = (DebugUtil::IsTraced(data->className) ? Qt::Checked : Qt::Unchecked); return var; } } else if (role == Qt::DecorationRole && index.column() == 0) { ObjectItem* data = static_cast(index.internalPointer()); if (data->type == ObjectItem::INSTANCE) { QVariant var; #ifdef BLUEBERRY_DEBUG_SMARTPOINTER if (DebugUtil::GetBreakpointManager()->BreakAtObject(data->obj->GetTraceId())) #else if(false) #endif { var = QIcon(":/objectinspector/break-enabled.png"); } return var; } else if (data->type == ObjectItem::SMARTPOINTER) { QVariant var; if (DebugUtil::GetBreakpointManager()->BreakAtSmartpointer(data->spId)) { var = QIcon(":/objectinspector/break-enabled.png"); } return var; } } else if (role == Qt::UserRole) { return QVariant::fromValue(index.internalPointer()); } return QVariant(); } QVariant QtObjectTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { case 0: { int count = 0; QListIterator iter(indexData); while (iter.hasNext()) { count += iter.next()->children.size(); } return QVariant(QString("Instances (") + QString::number(count) + ")"); } case 1: { return QVariant(QString("Trace")); } } } return QVariant(); } Qt::ItemFlags QtObjectTableModel::flags(const QModelIndex& index) const { Qt::ItemFlags flags = QAbstractItemModel::flags(index); ObjectItem* item = static_cast (index.internalPointer()); if ((item->type == ObjectItem::INSTANCE || item->type == ObjectItem::CLASS) && index.column() == 1) flags |= Qt::ItemIsUserCheckable; return flags; } bool QtObjectTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid() && index.column() == 1 && role == Qt::CheckStateRole) { ObjectItem* item = static_cast (index.internalPointer()); if (value.toInt() == Qt::Checked) { if (item->type == ObjectItem::INSTANCE) DebugUtil::TraceObject(item->obj); else if (item->type == ObjectItem::CLASS) DebugUtil::TraceClass(item->className); } else { if (item->type == ObjectItem::INSTANCE) DebugUtil::StopTracing(item->obj); else if (item->type == ObjectItem::CLASS) DebugUtil::StopTracing(item->className); } emit dataChanged(index, index); return true; } return false; } void QtObjectTableModel::ResetData() { indexData.clear(); DebugUtil::ResetObjectSummary(); QAbstractItemModel::beginResetModel(); QAbstractItemModel::endResetModel(); } void QtObjectTableModel::ObjectCreated(const Object* obj) { // This method is called inside the berry::Object // constructor, hence we cannot reliably call the virtual // method berry::Object::GetClassName() to put the new // object under the right "class" parent. So add it to // a list of pending objects. ObjectItem* item = new ObjectItem(obj, 0); pendingData.push_back(item); } void QtObjectTableModel::UpdatePendingData() { if (pendingData.empty()) return; QListIterator instanceIter(pendingData); while (instanceIter.hasNext()) { ObjectItem* instanceItem = instanceIter.next(); ObjectItem* classItem = 0; ObjectItem classSearchItem(instanceItem->obj->GetClassName()); int classIndex = 0; classItem = FindObjectItem(classSearchItem, classIndex); if (!classItem) { classItem = new ObjectItem(instanceItem->obj->GetClassName()); classItem->children.push_back(instanceItem); instanceItem->parent = classItem; classIndex = rowCount(QModelIndex()); beginInsertRows(QModelIndex(), classIndex, classIndex); indexData.push_back(classItem); endInsertRows(); } else { instanceItem->parent = classItem; QModelIndex classModelIndex = createIndex(classIndex, 0, classItem); int rowIndex = rowCount(classModelIndex); beginInsertRows(classModelIndex, rowIndex, rowIndex); classItem->children.push_back(instanceItem); endInsertRows(); } } pendingData.clear(); } void QtObjectTableModel::ObjectDestroyed(const Object* obj) { ObjectItem searchItem(obj, 0); int index = 0; ObjectItem* item = FindObjectItem(searchItem, index); if (!item) { QMutableListIterator pendingIter(pendingData); while (pendingIter.hasNext()) { ObjectItem* pendingItem = pendingIter.next(); if (pendingItem->obj == obj) { pendingIter.remove(); delete pendingItem; break; } } return; } int parentIndex = indexData.indexOf(item->parent); beginRemoveRows(createIndex(parentIndex, 0, item->parent), index, index); item->parent->children.removeAt(index); endRemoveRows(); if (item->parent->children.empty()) { beginRemoveRows(QModelIndex(), parentIndex, parentIndex); indexData.removeAt(parentIndex); endRemoveRows(); delete item->parent; } else { delete item; } } void QtObjectTableModel::SmartPointerCreated(unsigned int id, const Object* obj) { ObjectItem searchInstance(obj, 0); int instanceIndex = 0; ObjectItem* instanceItem = FindObjectItem(searchInstance, instanceIndex); if (!instanceItem) { QListIterator pendingIter(pendingData); while (pendingIter.hasNext()) { ObjectItem* pendingItem = pendingIter.next(); if (pendingItem->obj == obj) { pendingItem->children.push_back(new ObjectItem(id, pendingItem)); break; } } return; } int itemIndex = instanceItem->children.size(); beginInsertRows(createIndex(instanceIndex, 0, instanceItem), itemIndex, itemIndex); instanceItem->children.push_back(new ObjectItem(id, instanceItem)); endInsertRows(); } void QtObjectTableModel::SmartPointerDestroyed(unsigned int id, const Object* obj) { ObjectItem searchSP(id, 0); int spIndex = 0; ObjectItem* spItem = FindObjectItem(searchSP, spIndex); if (!spItem) { QListIterator pendingIter(pendingData); while (pendingIter.hasNext()) { ObjectItem* pendingItem = pendingIter.next(); if (pendingItem->obj == obj) { QMutableListIterator spIter(pendingItem->children); while (spIter.hasNext()) { spItem = spIter.next(); if (spItem->spId == id) { spIter.remove(); delete spItem; return; } } break; } } return; } int parentIndex = 0; ObjectItem searchInstance(obj, 0); ObjectItem* instanceItem = FindObjectItem(searchInstance, parentIndex); beginRemoveRows(createIndex(parentIndex, 0, instanceItem), spIndex, spIndex); instanceItem->children.removeAt(spIndex); delete spItem; endRemoveRows(); } ObjectItem* QtObjectTableModel::FindObjectItem( const ObjectItem& item, int& index) { switch (item.type) { case ObjectItem::CLASS: { QListIterator i(indexData); index = 0; while (i.hasNext()) { ObjectItem* next = i.next(); - if (std::strcmp(next->className, item.className) == 0) - return next; + if (next->className == item.className) + return next; ++index; } return 0; } case ObjectItem::INSTANCE: { QListIterator i(indexData); while (i.hasNext()) { ObjectItem* next = i.next(); index = 0; QListIterator childIter(next->children); while (childIter.hasNext()) { ObjectItem* child = childIter.next(); if (child->obj == item.obj) return child; ++index; } } return 0; } case ObjectItem::SMARTPOINTER: { QListIterator classIter(indexData); while (classIter.hasNext()) { ObjectItem* nextClass = classIter.next(); QListIterator instanceIter(nextClass->children); while (instanceIter.hasNext()) { ObjectItem* nextInstance = instanceIter.next(); index = 0; QListIterator spIter(nextInstance->children); while (spIter.hasNext()) { ObjectItem* nextSp = spIter.next(); if (nextSp->spId == item.spId) return nextSp; ++index; } } } return 0; } } return 0; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryQtObjectTableModel.h b/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryQtObjectTableModel.h index 8a4d9ee6d6..b299dfc07b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryQtObjectTableModel.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.objectinspector/src/internal/berryQtObjectTableModel.h @@ -1,81 +1,81 @@ /*=================================================================== 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 BERRYQTOBJECTTABLEMODEL_H_ #define BERRYQTOBJECTTABLEMODEL_H_ #include #include #include #include #include "berryObjectItem.h" namespace berry { class QtObjectTableModel: public QAbstractItemModel { Q_OBJECT public: QtObjectTableModel(QObject* parent = 0); ~QtObjectTableModel(); QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const; QModelIndex parent(const QModelIndex& index) const; int rowCount(const QModelIndex&) const; int columnCount(const QModelIndex&) const; QVariant data(const QModelIndex& index, int) const; QVariant headerData(int section, Qt::Orientation orientation, int) const; Qt::ItemFlags flags(const QModelIndex& index) const; bool setData(const QModelIndex &index, const QVariant &value, int role); void ResetData(); protected: void ObjectCreated(const Object* obj); void ObjectDestroyed(const Object* obj); void SmartPointerCreated(unsigned int id, const Object* obj); void SmartPointerDestroyed(unsigned int id, const Object* obj); private slots: void UpdatePendingData(); private: ObjectItem* FindObjectItem(const ObjectItem& item, int& index); QList indexData; QList pendingData; - IDebugObjectListener::Pointer objectListener; + QScopedPointer objectListener; friend class DebugObjectListener; }; } #endif /* BERRYQTOBJECTTABLEMODEL_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake b/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake index ac5d297365..fde8abe0d2 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake @@ -1,425 +1,468 @@ set(SRC_CPP_FILES berryAbstractSourceProvider.cpp berryAbstractUICTKPlugin.cpp berryConstants.cpp berryDisplay.cpp berryEditorPart.cpp berryFileEditorInput.cpp berryGeometry.cpp berryIActionBars.h + berryIContextService.cpp berryIContributionRoot.h berryIDropTargetListener.cpp berryIEditorDescriptor.cpp berryIEditorInput.cpp berryIEditorMatchingStrategy.cpp berryIEditorPart.cpp berryIEditorReference.cpp berryIEditorRegistry.cpp berryIEditorSite.cpp berryIFileEditorMapping.cpp berryIFolderLayout.cpp berryImageDescriptor.cpp berryIMemento.cpp berryINullSelectionListener.cpp berryIPageLayout.cpp berryIPartListener.cpp berryIPageService.cpp berryIPartService.cpp berryIPathEditorInput.cpp berryIPerspectiveDescriptor.cpp berryIPerspectiveFactory.cpp berryIPerspectiveListener.cpp berryIPerspectiveRegistry.cpp berryIPlaceholderFolderLayout.cpp berryIPluginContribution.h berryIPostSelectionProvider.cpp berryIPreferencePage.cpp berryIPropertyChangeListener.cpp berryIQtPreferencePage.cpp berryIQtStyleManager.cpp berryIReusableEditor.cpp berryISaveablePart.cpp berryISaveablesLifecycleListener.cpp berryISaveablesSource.cpp berryISelection.cpp berryISelectionChangedListener.cpp berryISelectionListener.cpp berryISelectionProvider.cpp berryISelectionService.cpp berryIShellListener.cpp berryIShellProvider.cpp + berryIShowInSource.h + berryIShowInTarget.h berryISizeProvider.cpp berryISourceProvider.cpp berryISourceProviderListener.cpp berryISources.cpp berryIStickyViewDescriptor.cpp berryIStructuredSelection.cpp berryIViewCategory.cpp berryIViewDescriptor.cpp berryIViewLayout.cpp berryIViewPart.cpp berryIViewReference.cpp berryIViewRegistry.cpp berryIViewSite.cpp berryIWorkbenchCommandConstants.cpp berryIWindowListener.cpp berryIWorkbench.cpp berryIWorkbenchListener.cpp berryIWorkbenchPage.cpp berryIWorkbenchPart.cpp berryIWorkbenchPartConstants.cpp berryIWorkbenchPartDescriptor.cpp berryIWorkbenchPartReference.cpp berryIWorkbenchPartSite.cpp berryIWorkbenchSite.cpp berryIWorkbenchWindow.cpp berryMenuUtil.cpp berryPlatformUI.cpp berryPoint.cpp berryPropertyChangeEvent.cpp berryQModelIndexObject.cpp berryQtEditorPart.cpp berryQtItemSelection.cpp berryQtIntroPart.cpp berryQtPreferences.cpp berryQtSelectionProvider.cpp berryQtViewPart.cpp berryRectangle.cpp berrySameShellProvider.cpp berrySaveable.cpp berrySaveablesLifecycleEvent.cpp berrySelectionChangedEvent.cpp berryShell.cpp berryShellEvent.cpp + berryShowInContext.cpp berryUIException.cpp berryViewPart.cpp berryWindow.cpp berryWorkbenchActionConstants.cpp berryWorkbenchPart.cpp berryWorkbenchPreferenceConstants.cpp berryXMLMemento.cpp #actions actions/berryAbstractContributionFactory.cpp actions/berryAbstractGroupMarker.cpp #actions/berryAction.cpp #actions/berryActionContributionItem.cpp actions/berryCommandContributionItem.h actions/berryCommandContributionItem.cpp actions/berryContributionItem.cpp actions/berryContributionItemFactory.cpp actions/berryContributionManager.cpp actions/berryIContributionItem.h actions/berryIContributionManager.h actions/berryIContributionManagerOverrides.cpp actions/berryIMenuManager.h #actions/berryManuBarManager.cpp actions/berryMenuManager.cpp actions/berrySeparator.cpp actions/berrySubContributionItem.cpp #application application/berryActionBarAdvisor.cpp application/berryIActionBarConfigurer.cpp application/berryIWorkbenchConfigurer.cpp application/berryIWorkbenchWindowConfigurer.cpp application/berryWorkbenchAdvisor.cpp application/berryWorkbenchWindowAdvisor.cpp #commands commands/berryICommandImageService.cpp commands/berryICommandService.cpp commands/berryIElementReference.h commands/berryIElementUpdater.h commands/berryIMenuService.h commands/berryUIElement.cpp #dialogs dialogs/berryIDialog.cpp dialogs/berryIShowViewDialog.cpp dialogs/berryMessageDialog.cpp #guitk guitk/berryGuiTkControlEvent.cpp guitk/berryGuiTkEvent.cpp guitk/berryGuiTkIControlListener.cpp guitk/berryGuiTkIMenuListener.cpp guitk/berryGuiTkISelectionListener.cpp guitk/berryGuiTkSelectionEvent.cpp #handlers handlers/berryHandlerUtil.cpp handlers/berryIHandlerActivation.cpp handlers/berryIHandlerService.cpp + handlers/berryRadioState.cpp + handlers/berryRegistryToggleState.cpp handlers/berryShowViewHandler.cpp + handlers/berryToggleState.cpp #intro intro/berryIIntroManager.cpp intro/berryIIntroPart.cpp intro/berryIIntroSite.cpp intro/berryIntroPart.cpp #tweaklets tweaklets/berryDnDTweaklet.cpp tweaklets/berryGuiWidgetsTweaklet.cpp tweaklets/berryImageTweaklet.cpp tweaklets/berryMessageDialogTweaklet.cpp tweaklets/berryITracker.cpp tweaklets/berryWorkbenchPageTweaklet.cpp tweaklets/berryWorkbenchTweaklet.cpp #presentations presentations/berryIPresentablePart.cpp presentations/berryIPresentationFactory.cpp presentations/berryIPresentationSerializer.cpp presentations/berryIStackPresentationSite.cpp presentations/berryStackDropResult.cpp presentations/berryStackPresentation.cpp #services services/berryIDisposable.cpp services/berryIEvaluationReference.h services/berryIEvaluationService.cpp services/berryINestable.cpp services/berryIServiceFactory.cpp services/berryIServiceLocator.cpp + services/berryIServiceScopes.cpp services/berryIServiceWithSources.cpp + services/berryISourceProviderService.cpp #testing testing/berryTestableObject.cpp #util util/berryISafeRunnableRunner.cpp util/berrySafeRunnable.cpp # application application/berryQtWorkbenchAdvisor.cpp ) set(INTERNAL_CPP_FILES defaultpresentation/berryEmptyTabFolder.cpp defaultpresentation/berryEmptyTabItem.cpp defaultpresentation/berryNativeTabFolder.cpp defaultpresentation/berryNativeTabItem.cpp defaultpresentation/berryQCTabBar.cpp defaultpresentation/berryQtWorkbenchPresentationFactory.cpp util/berryAbstractTabFolder.cpp util/berryAbstractTabItem.cpp util/berryIPresentablePartList.cpp util/berryLeftToRightTabOrder.cpp util/berryPartInfo.cpp util/berryPresentablePartFolder.cpp util/berryReplaceDragHandler.cpp util/berryTabbedStackPresentation.cpp util/berryTabDragHandler.cpp util/berryTabFolderEvent.cpp util/berryTabOrder.cpp #intro intro/berryEditorIntroAdapterPart.cpp intro/berryIIntroDescriptor.cpp intro/berryIIntroRegistry.cpp intro/berryIntroConstants.cpp intro/berryIntroDescriptor.cpp intro/berryIntroPartAdapterSite.cpp intro/berryIntroRegistry.cpp intro/berryViewIntroAdapterPart.cpp intro/berryWorkbenchIntroManager.cpp berryAbstractMenuAdditionCacheEntry.cpp berryAbstractPartSelectionTracker.cpp berryAbstractSelectionService.cpp + berryActivePartExpression.cpp berryAlwaysEnabledExpression.cpp + berryAndExpression.cpp berryBundleUtility.cpp berryCommandContributionItemParameter.cpp + berryCommandParameter.cpp + berryCommandPersistence.cpp berryCommandService.cpp + berryCommandServiceFactory.cpp + berryCommandStateProxy.cpp + berryCompositeExpression.cpp berryContainerPlaceholder.cpp berryContributionRoot.cpp berryDetachedPlaceHolder.cpp berryDefaultSaveable.cpp berryDefaultStackPresentationSite.cpp berryDetachedWindow.cpp berryDragUtil.cpp berryEditorAreaHelper.cpp berryEditorDescriptor.cpp berryEditorManager.cpp berryEditorReference.cpp berryEditorRegistry.cpp berryEditorRegistryReader.cpp berryEditorSashContainer.cpp berryEditorSite.cpp berryElementReference.cpp berryErrorViewPart.cpp berryEvaluationAuthority.cpp berryEvaluationReference.cpp berryEvaluationResultCache.cpp berryEvaluationService.cpp berryExpressionAuthority.cpp berryFileEditorMapping.cpp berryFolderLayout.cpp + berryHandlerActivation.cpp + berryHandlerAuthority.cpp + berryHandlerPersistence.cpp + berryHandlerProxy.cpp + berryHandlerService.cpp + berryHandlerServiceFactory.cpp berryIDragOverListener.cpp berryIDropTarget.cpp berryIEvaluationResultCache.cpp berryILayoutContainer.cpp + berryInternalMenuService.h berryIServiceLocatorCreator.cpp berryIStickyViewManager.cpp berryIWorkbenchLocationService.cpp berryLayoutHelper.cpp berryLayoutPart.cpp berryLayoutPartSash.cpp berryLayoutTree.cpp berryLayoutTreeNode.cpp + berryMenuServiceFactory.cpp berryMMMenuListener.cpp + berryNestableHandlerService.cpp berryNullEditorInput.cpp berryPageLayout.cpp berryPagePartSelectionTracker.cpp berryPageSelectionService.cpp + berryParameterValueConverterProxy.cpp berryPartList.cpp berryPartPane.cpp berryPartPlaceholder.cpp berryPartSashContainer.cpp berryPartService.cpp berryPartSite.cpp berryPartStack.cpp berryPartTester.cpp + berryPersistentState.cpp berryPerspective.cpp berryPerspectiveDescriptor.cpp berryPerspectiveExtensionReader.cpp berryPerspectiveHelper.cpp berryPerspectiveRegistry.cpp berryPerspectiveRegistryReader.cpp berryPlaceholderFolderLayout.cpp berryPreferenceConstants.cpp berryPresentablePart.cpp berryPresentationFactoryUtil.cpp berryPresentationSerializer.cpp berryQtControlWidget.cpp berryQtDnDControlWidget.cpp berryQtDisplay.cpp berryQtDnDTweaklet.cpp berryQtFileImageDescriptor.cpp berryQtGlobalEventFilter.cpp berryQtIconImageDescriptor.cpp berryQtImageTweaklet.cpp berryQtMainWindowControl.cpp berryQtMessageDialogTweaklet.cpp berryQtMissingImageDescriptor.cpp berryQtOpenPerspectiveAction.cpp berryQtPerspectiveSwitcher.cpp berryQtSafeApplication.cpp berryQtSash.cpp berryQtShell.cpp berryQtShowViewAction.cpp berryQtShowViewDialog.cpp berryQtStyleManager.cpp berryQtStylePreferencePage.cpp berryQtTracker.cpp berryQtWidgetController.cpp berryQtWidgetsTweaklet.cpp berryQtWidgetsTweakletImpl.cpp berryQtWorkbenchPageTweaklet.cpp berryQtWorkbenchTweaklet.cpp + berryRegistryPersistence.cpp berryRegistryReader.cpp berrySaveablesList.cpp berryShowViewMenu.cpp berryServiceLocator.cpp berryServiceLocatorCreator.cpp berryShellPool.cpp + berrySlaveCommandService.cpp + berrySlaveHandlerService.cpp + berrySlaveMenuService.cpp + berrySourceProviderService.cpp berrySourcePriorityNameMapping.cpp berryStatusUtil.cpp berryStickyViewDescriptor.cpp berryStickyViewManager.cpp berryTweaklets.cpp + berryUtil.cpp berryViewDescriptor.cpp berryViewFactory.cpp berryViewLayout.cpp berryViewReference.cpp berryViewRegistry.cpp berryViewRegistryReader.cpp berryViewSashContainer.cpp berryViewSite.cpp berryWorkbenchPage.cpp berryWindowManager.cpp berryWindowPartSelectionTracker.cpp berryWindowSelectionService.cpp berryWorkbench.cpp berryWorkbenchConfigurer.cpp berryWorkbenchConstants.cpp + berryWorkbenchLocationService.cpp berryWorkbenchMenuService.cpp berryWorkbenchPagePartList.cpp berryWorkbenchPartReference.cpp berryWorkbenchPlugin.cpp berryWorkbenchRegistryConstants.cpp berryWorkbenchServiceRegistry.cpp + berryWorkbenchSourceProvider.cpp berryWorkbenchTestable.cpp berryWorkbenchWindow.cpp berryWorkbenchWindowConfigurer.cpp + berryWorkbenchWindowExpression.cpp berryWWinActionBars.cpp berryWWinPartService.cpp ) set(MOC_H_FILES src/berryEditorPart.h + src/berryQtSelectionProvider.h src/berryViewPart.h src/berryWorkbenchPart.h - src/intro/berryIntroPart.h - src/berryQtSelectionProvider.h + src/actions/berryCommandContributionItem.h - src/internal/berryMMMenuListener.h + src/intro/berryIntroPart.h - src/internal/defaultpresentation/berryNativeTabFolder.h - src/internal/defaultpresentation/berryNativeTabItem.h - src/internal/defaultpresentation/berryQCTabBar.h - src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.h - - src/internal/intro/berryEditorIntroAdapterPart.h + src/handlers/berryShowViewHandler.h + src/internal/berryCommandServiceFactory.h + src/internal/berryHandlerServiceFactory.h + src/internal/berryMenuServiceFactory.h + src/internal/berryMMMenuListener.h + src/internal/berryWorkbenchSourceProvider.h src/internal/berryQtDisplay.h src/internal/berryQtDnDTweaklet.h src/internal/berryQtGlobalEventFilter.h src/internal/berryQtImageTweaklet.h src/internal/berryQtMainWindowControl.h src/internal/berryQtMessageDialogTweaklet.h src/internal/berryQtOpenPerspectiveAction.h src/internal/berryQtPerspectiveSwitcher.h src/internal/berryQtSash.h src/internal/berryQtShowViewAction.h src/internal/berryQtStyleManager.h src/internal/berryQtStylePreferencePage.h src/internal/berryQtTracker.h src/internal/berryQtWidgetsTweaklet.h src/internal/berryQtWidgetsTweakletImpl.h src/internal/berryQtWorkbenchTweaklet.h src/internal/berryQtWorkbenchPageTweaklet.h + + src/internal/defaultpresentation/berryNativeTabFolder.h + src/internal/defaultpresentation/berryNativeTabItem.h + src/internal/defaultpresentation/berryQCTabBar.h + src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.h + + src/internal/intro/berryEditorIntroAdapterPart.h ) set(UI_FILES src/internal/berryQtShowViewDialog.ui src/internal/berryQtStylePreferencePage.ui src/internal/berryQtStatusPart.ui ) set(QRC_FILES resources/org_blueberry_ui_qt.qrc ) set(CACHED_RESOURCE_FILES plugin.xml ) set(CPP_FILES ) foreach(file ${SRC_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/${file}) endforeach(file ${SRC_CPP_FILES}) foreach(file ${INTERNAL_CPP_FILES}) set(CPP_FILES ${CPP_FILES} src/internal/${file}) endforeach(file ${INTERNAL_CPP_FILES}) diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/plugin.xml b/BlueBerry/Bundles/org.blueberry.ui.qt/plugin.xml index 8754aa85be..82a058d000 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/plugin.xml +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/plugin.xml @@ -1,144 +1,167 @@ - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - + - + - + 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 19bbbbe79a..8b956a2a1e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp @@ -1,714 +1,733 @@ /*=================================================================== 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) + 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) + 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); // } - //item->AddListener(this->GetItemListener()); + + 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(const QString& id) +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.GetPointer()); + 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); } } ICommandListener* CommandContributionItem::GetCommandListener() { if (!commandListener) { class MyCommandListener : public ICommandListener { private: CommandContributionItem* item; public: MyCommandListener(CommandContributionItem* item) : item(item) {} - void CommandChanged(SmartPointer commandEvent) + void CommandChanged(const SmartPointer& commandEvent) { if (commandEvent->IsHandledChanged() || commandEvent->IsEnabledChanged() || commandEvent->IsDefinedChanged()) { item->UpdateCommandProperties(commandEvent); } } }; - commandListener = ICommandListener::Pointer(new MyCommandListener(this)); + commandListener.reset(new MyCommandListener(this)); } - return commandListener.GetPointer(); + 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(const UIElement::Pointer& element) +void CommandContributionItem::HandleWidgetSelection() { // // Special check for ToolBar dropdowns... // if (this->OpenDropDownMenu(event)) // //return; -// if ((style & (UIElement::STYLE_TOGGLE | UIElement::STYLE_CHECK)) != 0) -// { -// checkedState = element->GetChecked(); -// } + if ((style & STYLE_CHECK) != 0) + { + checkedState = action->isChecked(); + } -// try -// { -// handlerService->ExecuteCommand(command, element); -// } catch (const ExecutionException& e) -// { -// WorkbenchPlugin::Log("Failed to execute item " //$NON-NLS-1$ -// + GetId(), e); -// } catch (const NotDefinedException& e) -// { -// WorkbenchPlugin::Log("Failed to execute item " //$NON-NLS-1$ -// + GetId(), e); -// } catch (const NotEnabledException& e) -// { -// WorkbenchPlugin::Log("Failed to execute item " //$NON-NLS-1$ -// + GetId(), e); -// } catch (const NotHandledException& e) -// { -// WorkbenchPlugin::Log("Failed to execute item " //$NON-NLS-1$ -// + GetId(), e); -// } + 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/berryCommandContributionItem.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.h index e91c1645e5..4b8d52ee38 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.h @@ -1,205 +1,215 @@ /*=================================================================== 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 BERRYCOMMANDCONTRIBUTIONITEM_H_ #define BERRYCOMMANDCONTRIBUTIONITEM_H_ #include "berryContributionItem.h" #include namespace berry { struct IMenuService; struct ICommandService; struct ICommandListener; struct IHandlerService; struct IHandler; struct IElementReference; struct IServiceLocator; class CommandEvent; class ParameterizedCommand; class CommandContributionItemParameter; class UIElement; /** * A contribution item which delegates to a command. It can be used in {@link * AbstractContributionFactory#CreateContributionItems(IServiceLocator, * IContributionRoot)}. *

* It currently supports placement in menus and toolbars. *

*

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

*/ -class BERRY_UI_QT CommandContributionItem : public ContributionItem +class BERRY_UI_QT CommandContributionItem : public QObject, public ContributionItem { + Q_OBJECT public: /** * Mode bit: Show text on tool items or buttons, even if an image is * present. If this mode bit is not set, text is only shown on tool items if * there is no image present. */ static Modes modes; private: //LocalResourceManager localResourceManager; //Listener menuItemListener; QAction* action; IMenuService* menuService; ICommandService* commandService; IHandlerService* handlerService; //IBindingService bindingService; SmartPointer command; QIcon icon; QString label; QString tooltip; QChar mnemonic; SmartPointer elementRef; bool checkedState; Style style; - SmartPointer commandListener; + QScopedPointer commandListener; QString dropDownMenuOverride; //IWorkbenchHelpSystem workbenchHelpSystem; QString helpContextId; Modes mode; /** * This is true when the menu contribution's visibleWhen * checkEnabled attribute is true. */ bool visibleEnabled; // items contributed QString contributedLabel; QIcon contributedIcon; SmartPointer serviceLocator; public: /** * Create a CommandContributionItem to place in a ContributionManager. * * @param contributionParameters * parameters necessary to render this contribution item. */ CommandContributionItem( const SmartPointer& contributionParameters); ~CommandContributionItem(); + using ContributionItem::Fill; + QAction* Fill(QMenu* parent, QAction* before); QAction* Fill(QToolBar* parent, QAction* before); - void Update(const QString& id = QString()); + void Update(); + + void Update(const QString& id); bool IsEnabled() const; bool IsVisible() const; void UpdateCommandPropertiesInUI(const SmartPointer< const CommandEvent>& commandEvent); private: void SetImages(IServiceLocator* locator, const QString &iconStyle); ICommandListener *GetCommandListener(); void UpdateMenuItem(); void UpdateToolItem(); void UpdateCommandProperties(const SmartPointer commandEvent); bool ShouldRestoreAppearance(const SmartPointer& handler); SmartPointer GetCommand() const; void CreateCommand(const QString& commandId, const QHash& parameters); QString GetToolTipText(const QString& text) const; QString UpdateMnemonic(const QString& s); // void disposeOldImages() { // if (localResourceManager != null) { // localResourceManager.dispose(); // localResourceManager = null; // } // } //SmartPointer GetItemListener(); - void HandleWidgetSelection(const SmartPointer& element); + void connectNotify(const char *signal); + void disconnectNotify(const char *signal); /** * Determines if the selection was on the dropdown affordance and, if so, * opens the drop down menu (populated using the same id as this item... * * @param event * The SWT.Selection event to be tested * * @return true iff a drop down menu was opened */ //TODO Tool item drop down menu contributions //bool OpenDropDownMenu(SmartPointer event); void SetIcon(const QIcon& icon); void UpdateIcons(); void SetText(const QString& text); void SetChecked(bool checked); void SetToolTip(const QString& text); +private slots: + + void HandleWidgetSelection(); + }; } #endif /* BERRYCOMMANDCONTRIBUTIONITEM_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIContributionItem.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIContributionItem.h index baa329b4a1..64b29f748a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIContributionItem.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIContributionItem.h @@ -1,202 +1,202 @@ /*=================================================================== 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 BERRYICONTRIBUTIONITEM_H #define BERRYICONTRIBUTIONITEM_H #include #include class QStatusBar; class QMenu; class QMenuBar; class QToolBar; class QAction; namespace berry { struct IContributionManager; /** * A contribution item represents a contribution to a shared UI resource such as a * menu or tool bar. More generally, contribution items are managed by a contribution * manager. * For instance, in a tool bar a contribution item is a tool bar button or a separator. * In a menu bar a contribution item is a menu, and in a menu a contribution item * is a menu item or separator. *

* A contribution item can realize itself in different Qt widgets, using the different * fill methods. The same type of contribution item can be used with a * MenuBarManager, ToolBarManager, * or a StatusLineManager. *

*

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

* * @see IContributionManager * @noimplement This interface is not intended to be implemented by clients. */ struct IContributionItem : public virtual Object { - berryInterfaceMacro(IContributionItem, berry) + berryObjectMacro(berry::IContributionItem) /** * Fills the given status bar control with controls representing this * contribution item. Used by StatusLineManager. * * @param parent the parent control */ virtual void Fill(QStatusBar* parent) = 0; /** * Fills the given menu bar with controls representing this contribution item. * Used by MenuBarManager. * * @param parent the parent menu * @param index the index where the controls are inserted, * or -1 to insert at the end */ virtual QAction* Fill(QMenuBar* parent, QAction* before) = 0; /** * Fills the given menu with controls representing this contribution item. * Used by MenuManager. * * @param parent the parent menu * @param index the index where the controls are inserted, * or -1 to insert at the end */ virtual QAction* Fill(QMenu* parent, QAction* before) = 0; /** * Fills the given tool bar with controls representing this contribution item. * Used by ToolBarManager. * * @param parent the parent tool bar * @param index the index where the controls are inserted, * or -1 to insert at the end */ virtual QAction* Fill(QToolBar* parent, QAction* before) = 0; /** * Returns the identifier of this contribution item. * The id is used for retrieving an item from its manager. * * @return the contribution item identifier, or null * if none */ virtual QString GetId() const = 0; /** * Returns whether this contribution item is enabled. * * @return true if this item is enabled */ virtual bool IsEnabled() const = 0; /** * Returns whether this contribution item is dirty. A dirty item will be * recreated when the action bar is updated. * * @return true if this item is dirty */ virtual bool IsDirty() const = 0; /** * Returns whether this contribution item is dynamic. A dynamic contribution * item contributes items conditionally, dependent on some internal state. * * @return true if this item is dynamic, and * false for normal items */ virtual bool IsDynamic() const = 0; /** * Returns whether this contribution item is a group marker. * This information is used when adding items to a group. * * @return true if this item is a group marker, and * false for normal items * * @see GroupMarker * @see IContributionManager#appendToGroup(String, IContributionItem) * @see IContributionManager#prependToGroup(String, IContributionItem) */ virtual bool IsGroupMarker() const = 0; /** * Returns whether this contribution item is a separator. * This information is used to enable hiding of unnecessary separators. * * @return true if this item is a separator, and * false for normal items * @see Separator */ virtual bool IsSeparator() const = 0; /** * Returns whether this contribution item is visibile within its manager. * * @return true if this item is visible, and * false otherwise */ virtual bool IsVisible() const = 0; /** * Saves any state information of the control(s) owned by this contribution item. * The contribution manager calls this method before disposing of the controls. */ virtual void SaveWidgetState() = 0; /** * Sets the parent manager of this item * * @param parent the parent contribution manager */ virtual void SetParent(IContributionManager* parent) = 0; /** * Sets whether this contribution item is visibile within its manager. * * @param visible true if this item should be visible, and * false otherwise */ virtual void SetVisible(bool visible) = 0; /** * Updates any controls cached by this contribution item with any * changes which have been made to this contribution item since the last update. * Called by contribution manager update methods. */ virtual void Update() = 0; /** * Updates any controls cached by this contribution item with changes * for the the given property. * * @param id the id of the changed property */ virtual void Update(const QString& id) = 0; }; } #endif // BERRYICONTRIBUTIONITEM_H 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 6eaf10e31b..8e8ff07e47 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,252 @@ /*=================================================================== 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 { - berryInterfaceMacro(IContributionManager, berry) + 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 b35afdf9c8..22d20c8354 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 { - berryInterfaceMacro(IContributionManagerOverrides, berry) + 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; /** * 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; }; } #endif // BERRYICONTRIBUTIONMANAGEROVERRIDES_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIMenuManager.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIMenuManager.h index 2a63afc077..2223488de7 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIMenuManager.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIMenuManager.h @@ -1,130 +1,130 @@ /*=================================================================== 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 BERRYIMENUMANAGER_H #define BERRYIMENUMANAGER_H #include #include namespace berry { /** * The IMenuManager interface provides protocol for managing * contributions to a menu bar and its sub menus. * An IMenuManager is also an IContributionItem, * allowing sub-menus to be nested in parent menus. *

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

*

* This package provides a concrete menu manager implementation, * {@link MenuManager MenuManager}. *

* @noimplement This interface is not intended to be implemented by clients. */ struct IMenuManager : public virtual IContributionManager, public IContributionItem { - berryInterfaceMacro(IMenuManager, berry) + berryObjectMacro(berry::IMenuManager) /** * Adds a menu listener to this menu. * Has no effect if an identical listener is already registered. * * @param listener a menu listener */ //virtual void AddMenuListener(QObject* listener, const char* slot) = 0; /** * Finds the manager for the menu at the given path. A path * consists of contribution item ids separated by the separator * character. The path separator character is '/'. *

* Convenience for findUsingPath(path) which * extracts an IMenuManager if possible. *

* * @param path the path string * @return the menu contribution item, or null * if there is no such contribution item or if the item does * not have an associated menu manager */ virtual IMenuManager::Pointer FindMenuUsingPath(const QString& path) const = 0; /** * Finds the contribution item at the given path. A path * consists of contribution item ids separated by the separator * character. The path separator character is '/'. * * @param path the path string * @return the contribution item, or null if there is no * such contribution item */ virtual IContributionItem::Pointer FindUsingPath(const QString& path) const = 0; /** * Returns whether all items should be removed when the menu is about to * show, but before notifying menu listeners. The default is * false. * * @return true if all items should be removed when shown, * false if not */ virtual bool GetRemoveAllWhenShown() const = 0; /** * Returns whether this menu should be enabled or not. * * @return true if enabled, and * false if disabled */ virtual bool IsEnabled() const = 0; /** * Removes the given menu listener from this menu. * Has no effect if an identical listener is not registered. * * @param listener the menu listener */ //virtual void RemoveMenuListener(QObject* listener) = 0; /** * Sets whether all items should be removed when the menu is about to show, * but before notifying menu listeners. * * @param removeAll * true if all items should be removed when shown, * false if not */ virtual void SetRemoveAllWhenShown(bool removeAll) = 0; /** * Incrementally builds the menu from the contribution items, and * does so recursively for all submenus. * * @param force true means update even if not dirty, * and false for normal incremental updating */ virtual void UpdateAll(bool force) = 0; }; } #endif // BERRYIMENUMANAGER_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 2bfd845380..4ea4d19af3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryMenuManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryMenuManager.cpp @@ -1,699 +1,726 @@ /*=================================================================== 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 { return -1; } int GetVisible(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(); } - menu->menu; + 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 (unsigned int i = 0; i < mi.size(); i++) + 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()) + 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)); int newItems = menu->actions().size() - start; 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); + } + } +} + } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryMenuManager.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryMenuManager.h index 049eb866e6..2a8f0e5e59 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryMenuManager.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryMenuManager.h @@ -1,466 +1,469 @@ /*=================================================================== 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 BERRYMENUMANAGER_H_ #define BERRYMENUMANAGER_H_ #include "berryIMenuManager.h" #include "berryContributionManager.h" #include #include class QMenu; class QMenuProxy; class QAction; namespace berry { class MMMenuListener; /** * A menu manager is a contribution manager which realizes itself and its items * in a menu control; either as a menu bar, a sub-menu, or a context menu. *

* This class may be instantiated; it may also be subclassed. *

*/ class BERRY_UI_QT MenuManager: public ContributionManager, public IMenuManager { public: berryObjectMacro(MenuManager) private: friend class MMMenuListener; /** * The menu id. */ QString id; /** * List of registered menu listeners (element type: IMenuListener). */ //IMenuListener::Events menuEvents; //GuiTk::IMenuListener::Pointer menuListener; /** * The menu control; null before * creation and after disposal. */ QMenuProxy* menu; QAction* menuItem; QScopedPointer menuListener; /** * The menu item widget; null before * creation and after disposal. This field is used * when this menu manager is a sub-menu. */ //SmartPointer menuItem; /** * The text for a sub-menu. */ QString menuText; /** * The image for a sub-menu. */ QIcon image; /** * A resource manager to remember all of the images that have been used by this menu. */ //LocalResourceManager imageManager; /** * The overrides for items of this manager */ SmartPointer overrides; /** * The parent contribution manager. */ IContributionManager* parent; /** * Indicates whether removeAll should be * called just before the menu is displayed. */ bool removeAllWhenShown; /** * allows a submenu to display a shortcut key. This is often used with the * QuickMenu command or action which can pop up a menu using the shortcut. */ QString definitionId; protected: /** * Indicates this item is visible in its manager; true * by default. */ bool visible; public: /** * Creates a menu manager with the given text and id. * Typically no text is given when creating a context menu. * Supply a text and id for creating a sub-menu, where it needs to be referred to by the id. * * @param text the text for the menu, or "" if none * @param id the menu id, or "" if it is to have no id */ MenuManager(const QString& text = QString(), const QString& id = QString()); ~MenuManager(); /** * Creates a menu manager with the given text, image, and id. * Typically used for creating a sub-menu, where it needs to be referred to by id. * * @param text the text for the menu, or "" if none * @param image the image for the menu, or ImageDescriptor::Pointer(0) if none * @param id the menu id, or "" if it is to have no id */ MenuManager(const QString& text, const QIcon& image, const QString& id); /* * @see IMenuManager#AddMenuListener(SmartPointer) */ //void AddMenuListener(SmartPointer listener); bool IsDirty() const; /** * Creates and returns a Qt menu control for this menu, * and installs all registered contributions. * Does not create a new control if one already exists. *

* Note that the menu is not expected to be dynamic. *

* * @param parent the parent control * @return the menu control */ QMenu* CreateContextMenu(QWidget* parent); /** * Creates and returns a Qt menu bar control for this menu, * for use in the given QWidget, and installs all registered * contributions. Does not create a new control if one already exists. * * @param parent the parent decorations * @return the menu control * @since 2.1 */ QMenuBar* CreateMenuBar(QWidget* parent); /* * @see IContributionItem#Fill(QStatusBar*) */ void Fill(QStatusBar* parent); /* * @see IContributionItem#Fill(QToolBar*, int) */ QAction* Fill(QToolBar* parent, QAction *index); /* * @see IContributionItem#Fill(QMenu*, int) */ QAction* Fill(QMenu* parent, QAction *before); /* * @see IContributionItem#Fill(QMenuBar*, int) */ QAction* Fill(QMenuBar* parent, QAction *before); /* * @see IMenuManager#FindMenuUsingPath(const QString&) */ IMenuManager::Pointer FindMenuUsingPath(const QString& path) const; /* * @see IMenuManager#FindUsingPath(const QString&) */ IContributionItem::Pointer FindUsingPath(const QString& path) const; /** * Returns the menu id. The menu id is used when creating a contribution * item for adding this menu as a sub menu of another. * * @return the menu id */ QString GetId() const; /** * Returns the SWT menu control for this menu manager. * * @return the menu control */ QMenu* GetMenu() const; /** * Returns the text shown in the menu, potentially with a shortcut * appended. * * @return the menu text */ QString GetMenuText() const; /** * Returns the image for this menu as an image descriptor. * * @return the image, or null if this menu has no image */ QIcon GetImage() const; /* * @see IContributionManager#GetOverrides() */ SmartPointer GetOverrides(); /** * Returns the parent contribution manager of this manger. * * @return the parent contribution manager */ IContributionManager* GetParent() const; /* * @see IMenuManager#GetRemoveAllWhenShown() */ bool GetRemoveAllWhenShown() const; /* * @see IContributionItem#IsDynamic() */ bool IsDynamic() const; /** * Returns whether this menu should be enabled or not. * Used to enable the menu item containing this menu when it is realized as a sub-menu. *

* The default implementation of this framework method * returns true. Subclasses may reimplement. *

* * @return true if enabled, and * false if disabled */ bool IsEnabled() const; /* * @see IContributionItem#IsGroupMarker() */ bool IsGroupMarker() const; /* * @see IContributionItem#IsSeparator() */ bool IsSeparator() const; /* * @see IContributionItem#IsVisible() */ bool IsVisible() const; /** * The MenuManager implementation of this ContributionManager method * also propagates the dirty flag up the parent chain. */ void MarkDirty(); /* * @see IMenuManager#removeMenuListener(IMenuListener) */ //void RemoveMenuListener(SmartPointer listener); /* * @IContributionItem#SaveWidgetState() */ void SaveWidgetState(); /** * Sets the overrides for this contribution manager * * @param newOverrides the overrides for the items of this manager */ void SetOverrides(SmartPointer newOverrides); /* * @see IContributionItem#SetParent(IContributionManager) */ void SetParent(IContributionManager* manager); /* * @see IMenuManager#SetRemoveAllWhenShown(boolean) */ void SetRemoveAllWhenShown(bool removeAll); /* * @see IContributionItem#SetVisible(bool) */ void SetVisible(bool visible); /** * Sets the action definition id of this action. This simply allows the menu * item text to include a short cut if available. It can be used to * notify a user of a key combination that will open a quick menu. * * @param definitionId * the command definition id */ void SetActionDefinitionId(const QString& definitionId); /* * @see IContributionItem#Update() */ void Update(); void Update(const QString& property); /** * The MenuManager implementation of this IContributionManager * updates this menu, but not any of its submenus. * * @see #updateAll */ void Update(bool force); /* * @see IMenuManager#UpdateAll(bool) */ void UpdateAll(bool force); private: /** * Notifies any menu listeners that a menu is about to show. * Only listeners registered at the time this method is called are notified. * * @param manager the menu manager * * @see IMenuListener#menuAboutToShow */ //void FireAboutToShow(IMenuManager::Pointer manager); /** * Notifies any menu listeners that a menu is about to hide. * Only listeners registered at the time this method is called are notified. * * @param manager the menu manager * */ //void FireAboutToHide(IMenuManager::Pointer manager); /** * Notifies all listeners that this menu is about to appear. */ //void HandleAboutToShow(); /** * Notifies all listeners that this menu is about to disappear. */ //void HandleAboutToHide(); /** * Initializes the menu control. */ void InitializeMenu(); /** * Dispose any images allocated for this menu */ // void DisposeOldImages(); /** * Updates the menu item for this sub menu. * The menu item is disabled if this sub menu is empty. * Does nothing if this menu is not a submenu. */ void UpdateMenuItem(); QAction* FillMenu(QWidget* parent, QAction* before); + void DumpActionInfo(QMenuProxy* menu); + void DumpActionInfo(QWidget* widget, int level); + protected: /** * Get all the items from the implementation's widget. * * @return the menu items */ //QList > GetMenuItems(); /** * Get an item from the implementation's widget. * * @param index * of the item * @return the menu item */ //SmartPointer GetMenuItem(unsigned int index); /** * Get the menu item count for the implementation's widget. * * @return the number of items */ //unsigned int GetMenuItemCount(); /** * Call an IContributionItem's fill method with the * implementation's widget. The default is to use the Menu * widget.
* fill(Menu menu, int index) * * @param ci * An IContributionItem whose fill() * method should be called. * @param index * The position the fill() method should start * inserting at. */ void DoItemFill(IContributionItem::Pointer ci, QAction *before); /** * Incrementally builds the menu from the contribution items. * This method leaves out double separators and separators in the first * or last position. * * @param force true means update even if not dirty, * and false for normal incremental updating * @param recursive true means recursively update * all submenus, and false means just this menu */ void Update(bool force, bool recursive); }; } #endif /* BERRYMENUMANAGER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySeparator.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySeparator.h index f58ba5ac10..0f21bcbef0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySeparator.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySeparator.h @@ -1,68 +1,70 @@ /*=================================================================== 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 BERRYSEPARATOR_H #define BERRYSEPARATOR_H #include "berryAbstractGroupMarker.h" namespace berry { /** * A separator is a special kind of contribution item which acts * as a visual separator and, optionally, acts as a group marker. * Unlike group markers, separators do have a visual representation for * menus and toolbars. *

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

* @noextend This class is not intended to be subclassed by clients. */ class Separator : public AbstractGroupMarker { public: /** * Creates a separator which does not start a new group. */ Separator(); /** * Creates a new separator which also defines a new group having the given group name. * The group name must not be null or the empty string. * The group name is also used as the item id. * * @param groupName the group name of the separator */ Separator(const QString& groupName); + using AbstractGroupMarker::Fill; + QAction* Fill(QMenu* menu, QAction* before); QAction* Fill(QToolBar* toolbar, QAction* before); /** * The Separator implementation of this IContributionItem * method returns true */ bool IsSeparator() const; }; } #endif // BERRYSEPARATOR_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySubContributionItem.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySubContributionItem.cpp index 3cea2554a8..4ef6d00ed0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySubContributionItem.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySubContributionItem.cpp @@ -1,119 +1,119 @@ /*=================================================================== 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 "berrySubContributionItem.h" namespace berry { SubContributionItem::SubContributionItem(IContributionItem::Pointer item) : visible(true), innerItem(item) { } void SubContributionItem::Fill(QStatusBar* parent) { if (visible) { innerItem->Fill(parent); } } QAction *SubContributionItem::Fill(QMenu *parent, QAction *before) { if (visible) { return innerItem->Fill(parent, before); } return 0; } QAction *SubContributionItem::Fill(QToolBar *parent, QAction *before) { if (visible) { return innerItem->Fill(parent, before); } return 0; } QString SubContributionItem::GetId() const { return innerItem->GetId(); } IContributionItem::Pointer SubContributionItem::GetInnerItem() const { return innerItem; } bool SubContributionItem::IsEnabled() const { return innerItem->IsEnabled(); } bool SubContributionItem::IsDirty() const { return innerItem->IsDirty(); } bool SubContributionItem::IsDynamic() const { return innerItem->IsDynamic(); } bool SubContributionItem::IsGroupMarker() const { return innerItem->IsGroupMarker(); } bool SubContributionItem::IsSeparator() const { return innerItem->IsSeparator(); } bool SubContributionItem::IsVisible() const { return visible && innerItem->IsVisible(); } -void SubContributionItem::SetParent(IContributionManager */*parent*/) +void SubContributionItem::SetParent(IContributionManager* /*parent*/) { // do nothing, the parent of our inner item // is its SubContributionManager } void SubContributionItem::SetVisible(bool visible) { this->visible = visible; } void SubContributionItem::Update() { innerItem->Update(); } void SubContributionItem::Update(const QString& id) { innerItem->Update(id); } void SubContributionItem::SaveWidgetState() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySubContributionItem.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySubContributionItem.h index 2f426b4be9..31ed6f1ac2 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySubContributionItem.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySubContributionItem.h @@ -1,149 +1,151 @@ /*=================================================================== 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 BERRYSUBCONTRIBUTIONITEM_H_ #define BERRYSUBCONTRIBUTIONITEM_H_ #include "berryIContributionItem.h" #include namespace berry { /** * A SubContributionItem is a wrapper for an IContributionItem. * It is used within a SubContributionManager to control the visibility * of items. *

* This class is not intended to be subclassed. *

* @noextend This class is not intended to be subclassed by clients. */ class BERRY_UI_QT SubContributionItem : public IContributionItem { public: berryObjectMacro(SubContributionItem) private: /** * The visibility of the item. */ bool visible; /** * The inner item for this contribution. */ IContributionItem::Pointer innerItem; public: /** * Creates a new SubContributionItem. * @param item the contribution item to be wrapped */ SubContributionItem(IContributionItem::Pointer item); + using IContributionItem::Fill; + /* * Method declared on IContributionItem. */ void Fill(QStatusBar* parent); /* * Method declared on IContributionItem. */ QAction* Fill(QMenu* parent, QAction* before); /* * Method declared on IContributionItem. */ QAction* Fill(QToolBar* parent, QAction* before); /* * Method declared on IContributionItem. */ QString GetId() const; /** * Returns the inner contribution item. * * @return the inner contribution item */ IContributionItem::Pointer GetInnerItem() const; /* * Method declared on IContributionItem. */ bool IsEnabled() const; /* * Method declared on IContributionItem. */ bool IsDirty() const; /* * Method declared on IContributionItem. */ bool IsDynamic() const; /* * Method declared on IContributionItem. */ bool IsGroupMarker() const; /* * Method declared on IContributionItem. */ bool IsSeparator() const; /* * Method declared on IContributionItem. */ bool IsVisible() const; /* * Method declared on IContributionItem. */ void SetParent(IContributionManager* parent); /* * Method declared on IContributionItem. */ void SetVisible(bool visible); /* * Method declared on IContributionItem. */ void Update(); /* * Method declared on IContributionItem. */ void Update(const QString& id); /* * @see IContributionItem#SaveWidgetState() */ void SaveWidgetState(); }; } #endif /* BERRYSUBCONTRIBUTIONITEM_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryActionBarAdvisor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryActionBarAdvisor.cpp index ee3307686e..5d57857588 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryActionBarAdvisor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryActionBarAdvisor.cpp @@ -1,87 +1,88 @@ /*=================================================================== 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 "berryActionBarAdvisor.h" #include #include #include +#include namespace berry { ActionBarAdvisor::ActionBarAdvisor(const SmartPointer& configurer) : actionBarConfigurer(configurer) { Q_ASSERT(configurer.IsNotNull()); } IActionBarConfigurer::Pointer ActionBarAdvisor::GetActionBarConfigurer() const { return actionBarConfigurer; } void ActionBarAdvisor::FillActionBars(FillFlags flags) { if (flags.testFlag(FILL_PROXY)) { this->MakeActions(actionBarConfigurer->GetWindowConfigurer()->GetWindow().GetPointer()); } if (flags.testFlag(FILL_MENU_BAR)) { this->FillMenuBar(actionBarConfigurer->GetMenuManager()); } if (flags.testFlag(FILL_TOOL_BAR)) { this->FillToolBar(actionBarConfigurer->GetToolBarManager()); } if (flags.testFlag(FILL_STATUS_LINE)) { //this->FillStatusLine(actionBarConfigurer->GetStatusLineManager()); } } void ActionBarAdvisor::MakeActions(IWorkbenchWindow* /*window*/) { // do nothing } void ActionBarAdvisor::FillMenuBar(IMenuManager* /*menuBar*/) { // do nothing } void ActionBarAdvisor::FillToolBar(IToolBarManager* /*toolBar*/) { // do nothing } void ActionBarAdvisor::FillStatusLine(IStatusLineManager* /*statusLine*/) { // do nothing } bool ActionBarAdvisor::SaveState(SmartPointer /*memento*/) { return true; } bool ActionBarAdvisor::RestoreState(SmartPointer /*memento*/) { return true; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIActionBarConfigurer.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIActionBarConfigurer.h index b8c6da8d21..f274b09649 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIActionBarConfigurer.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIActionBarConfigurer.h @@ -1,106 +1,106 @@ /*=================================================================== 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 BERRYIACTIONBARCONFIGURER_H_ #define BERRYIACTIONBARCONFIGURER_H_ #include #include namespace berry { struct IWorkbenchWindowConfigurer; struct IMenuManager; struct IToolBarManager; /** * Interface providing special access for configuring the action bars * of a workbench window. *

* Note that these objects are only available to the main application * (the plug-in that creates and owns the workbench). *

*

* This interface is not intended to be implemented by clients. *

* * @see org.blueberry.ui.application.WorkbenchAdvisor#fillActionBars * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IActionBarConfigurer : public Object { - berryInterfaceMacro(IActionBarConfigurer, berry) + berryObjectMacro(berry::IActionBarConfigurer) ~IActionBarConfigurer(); /** * Returns the workbench window configurer for the window * containing this configurer's action bars. * * @return the workbench window configurer */ virtual SmartPointer GetWindowConfigurer() = 0; /** * Creates a menu manager for the main menu bar of a workbench window. The * action bar advisor should use this factory method rather than creating a * MenuManager directly. * * @return the menu manager */ virtual IMenuManager* GetMenuManager() = 0; /** * Creates a tool bar manager for the workbench window's tool bar. The * action bar advisor should use this factory method rather than creating a * ToolBarManager directly. * * @return the tool bar manager */ virtual IToolBarManager* GetToolBarManager() = 0; /* * Returns the status line manager of a workbench window. * * @return the status line manager */ //virtual IStatusLineManager GetStatusLineManager() = 0; /* * Register the action as a global action with a workbench * window. *

* For a workbench retarget action * ({@link org.blueberry.ui.actions.RetargetAction RetargetAction}) * to work, it must be registered. * You should also register actions that will participate * in custom key bindings. *

* * @param action the global action * @see org.blueberry.ui.actions.RetargetAction */ //virtual void RegisterGlobalAction(IAction action) = 0; }; } #endif /*BERRYIACTIONBARCONFIGURER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIWorkbenchConfigurer.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIWorkbenchConfigurer.h index 2899478766..cbbbdacd22 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIWorkbenchConfigurer.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIWorkbenchConfigurer.h @@ -1,260 +1,261 @@ /*=================================================================== 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 BERRYIWORKBENCHCONFIGURER_H_ #define BERRYIWORKBENCHCONFIGURER_H_ #include #include #include "berryIWorkbench.h" #include "berryIWorkbenchWindowConfigurer.h" namespace berry { /** * Interface providing special access for configuring the workbench. *

* Note that these objects are only available to the main application * (the plug-in that creates and owns the workbench). *

*

* This interface is not intended to be implemented by clients. *

* * @see WorkbenchAdvisor#Initialize() * @note This interface is not intended to be implemented by clients. */ -struct BERRY_UI_QT IWorkbenchConfigurer : public Object { +struct BERRY_UI_QT IWorkbenchConfigurer : public Object +{ - berryInterfaceMacro(IWorkbenchConfigurer, berry); + berryObjectMacro(berry::IWorkbenchConfigurer) ~IWorkbenchConfigurer(); /** * Restore status code indicating that the saved state * could not be restored, but that startup should continue * with a reset state. * * @see #RestoreState() */ static const int RESTORE_CODE_RESET = 1; /** * Restore status code indicating that the saved state * could not be restored, and that the application * must exit immediately without modifying any previously * saved workbench state. */ static const int RESTORE_CODE_EXIT = 2; /** * Returns the underlying workbench. * * @return the workbench */ virtual IWorkbench* GetWorkbench() = 0; /** * Returns whether the workbench state should be saved on close and * restored on subsequent open. *

* The initial value is false. *

* * @return true to save and restore workbench state, or * false to forget current workbench state on close. */ virtual bool GetSaveAndRestore() = 0; /** * Sets whether the workbench state should be saved on close and * restored on subsequent open. * * @param enabled true to save and restore workbench state, or * false to forget current workbench state on close. */ virtual void SetSaveAndRestore(bool enabled) = 0; /** * Restores a workbench window from the given memento. * * @param memento the memento from which to restore the window's state * @return the configurer for the restored window * @throws WorkbenchException if an error occurred during the restore * @see IWorkbenchWindowConfigurer#SaveState(IMemento::Pointer) */ virtual IWorkbenchWindowConfigurer::Pointer RestoreWorkbenchWindow(IMemento::Pointer memento) = 0; /* * Declares a workbench image. *

* The workbench remembers the given image descriptor under the given name, * and makes the image available to plug-ins via * {@link IWorkbench#GetSharedImages() IWorkbench.getSharedImages()}. * For "shared" images, the workbench remembers the image descriptor and * will manages the image object create from it; clients retrieve "shared" * images via * {@link org.blueberry.ui.ISharedImages#getImage ISharedImages.getImage()}. * For the other, "non-shared" images, the workbench remembers only the * image descriptor; clients retrieve the image descriptor via * {@link org.blueberry.ui.ISharedImages#getImageDescriptor * ISharedImages.getImageDescriptor()} and are entirely * responsible for managing the image objects they create from it. * (This is made confusing by the historical fact that the API interface * is called "ISharedImages".) *

* * @param symbolicName the symbolic name of the image * @param descriptor the image descriptor * @param shared true if this is a shared image, and * false if this is not a shared image * @see org.blueberry.ui.ISharedImages#getImage * @see org.blueberry.ui.ISharedImages#getImageDescriptor */ // virtual void declareImage(String symbolicName, ImageDescriptor descriptor, // boolean shared); /** * Forces the workbench to close due to an emergency. This method should * only be called when the workbench is in dire straights and cannot * continue, and cannot even risk a normal workbench close (think "out of * memory" or "unable to create shell"). When this method is called, an * abbreviated workbench shutdown sequence is performed (less critical * steps may be skipped). The workbench advisor is still called; however, * it must not attempt to communicate with the user. While an emergency * close is in progress, EmergencyClosing() returns * true. %Workbench advisor methods should always check this * flag before communicating with the user. * * @see #EmergencyClosing() */ virtual void EmergencyClose() = 0; /** * Returns whether the workbench is being closed due to an emergency. * When this method returns true, the workbench is in dire * straights and cannot continue. Indeed, things are so bad that we cannot * even risk a normal workbench close. %Workbench advisor methods should * always check this flag before attempting to communicate with the user. * * @return true if the workbench is in the process of being * closed under emergency conditions, and false otherwise */ virtual bool EmergencyClosing() = 0; /** * Returns an object that can be used to configure the given window. * * @param window a workbench window * @return a workbench window configurer */ virtual IWorkbenchWindowConfigurer::Pointer GetWindowConfigurer( IWorkbenchWindow::Pointer window) = 0; /** * Returns the data associated with the workbench at the given key. * * @param key the key * @return the data, or null if there is no data at the given * key */ virtual Object::Pointer GetData(const QString& key) const = 0; /** * Sets the data associated with the workbench at the given key. * * @param key the key * @param data the data, or null to delete existing data */ virtual void SetData(const QString& key, Object::Pointer data) = 0; /** * Restores the workbench state saved from the previous session, if any. * This includes any open windows and their open perspectives, open views * and editors, layout information, and any customizations to the open * perspectives. *

* This is typically called from the advisor's WorkbenchAdvisor#OpenWindows() * method. *

* * @return a status object indicating whether the restore was successful * @see #RESTORE_CODE_RESET * @see #RESTORE_CODE_EXIT * @see WorkbenchAdvisor#OpenWindows() */ virtual bool RestoreState() = 0; /** * Opens the first time window, using the default perspective and * default page input. *

* This is typically called from the advisor's WorkbenchAdvisor#OpenWindows() * method. *

* * @see WorkbenchAdvisor#OpenWindows() */ virtual void OpenFirstTimeWindow() = 0; /** * Returns true if the workbench should exit when the last * window is closed, false if the window should just be * closed, leaving the workbench (and its event loop) running. *

* If true, the last window's state is saved before closing, * so that it will be restored in the next session. This applies only if * #GetSaveAndRestore() returns true). *

*

* If false, the window is simply closed, losing its state. *

*

* If the workbench is left running, it can be closed using * IWorkbench#Close(), or a new window can be opened using * IWorkbench#OpenWorkbenchWindow(const QString&, IAdaptable*). *

*

* The initial value is true. *

* * @return true if the workbench will exit when the last * window is closed, false if the window should just * be closed */ virtual bool GetExitOnLastWindowClose() = 0; /** * Sets whether the workbench should exit when the last window is closed, or * whether the window should just be closed, leaving the workbench (and its * event loop) running. *

* For more details, see #GetExitOnLastWindowClose(). *

* * @param enabled * true if the workbench should exit when the last * window is closed, false if the window should * just be closed */ virtual void SetExitOnLastWindowClose(bool enabled) = 0; }; } #endif /*BERRYIWORKBENCHCONFIGURER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIWorkbenchWindowConfigurer.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIWorkbenchWindowConfigurer.h index 81ddafc2d1..933e1c1753 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIWorkbenchWindowConfigurer.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryIWorkbenchWindowConfigurer.h @@ -1,378 +1,378 @@ /*=================================================================== 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 BERRYIWORKBENCHWINDOWCONFIGURER_H_ #define BERRYIWORKBENCHWINDOWCONFIGURER_H_ #include #include #include "berryPoint.h" class QMenuBar; namespace berry { struct IActionBarConfigurer; struct IDropTargetListener; struct IMemento; struct IWorkbenchConfigurer; struct IWorkbenchWindow; /** * Interface providing special access for configuring workbench windows. *

* %Window configurer objects are in 1-1 correspondence with the workbench * windows they configure. Clients may use Get/SetData to * associate arbitrary state with the window configurer object. *

*

* Note that these objects are only available to the main application * (the plug-in that creates and owns the workbench). *

*

* This interface is not intended to be implemented by clients. *

* * @see IWorkbenchConfigurer#GetWindowConfigurer() * @see WorkbenchAdvisor#PreWindowOpen() * @note This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IWorkbenchWindowConfigurer : public Object { - berryInterfaceMacro(IWorkbenchWindowConfigurer, berry) + berryObjectMacro(berry::IWorkbenchWindowConfigurer) ~IWorkbenchWindowConfigurer(); /** * Returns the underlying workbench window. * * @return the workbench window */ virtual SmartPointer GetWindow() = 0; /** * Returns the workbench configurer. * * @return the workbench configurer */ virtual SmartPointer GetWorkbenchConfigurer() = 0; /** * Returns the action bar configurer for this workbench * window. * * @return the action bar configurer */ virtual SmartPointer GetActionBarConfigurer() = 0; /** * Returns the title of the underlying workbench window. * * @return the window title */ virtual QString GetTitle() = 0; /** * Sets the title of the underlying workbench window. * * @param title the window title */ virtual void SetTitle(const QString& title) = 0; /** * Returns whether the underlying workbench window has a menu bar. *

* The initial value is true. *

* * @return true for a menu bar, and false * for no menu bar */ virtual bool GetShowMenuBar() const = 0; /** * Sets whether the underlying workbench window has a menu bar. * * @param show true for a menu bar, and false * for no menu bar */ virtual void SetShowMenuBar(bool show) = 0; /** * Returns whether the underlying workbench window has a tool bar. *

* The initial value is true. *

* * @return true for a tool bar, and false * for no tool bar */ virtual bool GetShowToolBar() const = 0; /** * Sets whether the underlying workbench window has a tool bar. * * @param show true for a tool bar, and false * for no tool bar */ virtual void SetShowToolBar(bool show) = 0; /** * Returns whether the underlying workbench window has a status line. *

* The initial value is true. *

* * @return true for a status line, and false * for no status line */ virtual bool GetShowStatusLine() const = 0; /** * Sets whether the underlying workbench window has a status line. * * @param show true for a status line, and false * for no status line */ virtual void SetShowStatusLine(bool show) = 0; /** * Returns whether the underlying workbench window has a perspective bar (the * perspective bar provides buttons to quickly switch between perspectives). *

* The initial value is false. *

* * @return true for a perspective bar, and false * for no perspective bar */ virtual bool GetShowPerspectiveBar() const = 0; /** * Sets whether the underlying workbench window has a perspective bar (the * perspective bar provides buttons to quickly switch between perspectives). * * @param show true for a perspective bar, and * false for no perspective bar */ virtual void SetShowPerspectiveBar(bool show) = 0; /** * Returns whether the underlying workbench window has a progress indicator. *

* The initial value is false. *

* * @return true for a progress indicator, and false * for no progress indicator */ virtual bool GetShowProgressIndicator() const = 0; /** * Sets whether the underlying workbench window has a progress indicator. * * @param show true for a progress indicator, and false * for no progress indicator */ virtual void SetShowProgressIndicator(bool show) = 0; /** * Returns the style bits to use for the window's main widget when it is created. * The default is 0. * * @return the style bits */ virtual Qt::WindowFlags GetWindowFlags() const = 0; /** * Sets the style bits to use for the window's main widget when it is created. * This method has no effect after the widget is created. * That is, it must be called within the WorkbenchAdvisor#PreWindowOpen() * callback. *

* For more details on the applicable style bits, see the * documentation for Qt::WindowFlags. *

* * @param windowFlags the style bits */ virtual void SetWindowFlags(Qt::WindowFlags windowFlags) = 0; /** * Returns the size to use for the window's shell when it is created. * * @return the initial size to use for the shell */ virtual Point GetInitialSize() const = 0; /** * Sets the size to use for the window's shell when it is created. * This method has no effect after the shell is created. * That is, it must be called within the WorkbenchAdvisor#PreWindowOpen() * callback. * * @param initialSize the initial size to use for the shell */ virtual void SetInitialSize(Point initialSize) = 0; /* * Returns the data associated with this workbench window at the given key. * * @param key the key * @return the data, or null if there is no data at the given * key */ //virtual Object getData(String key); /* * Sets the data associated with this workbench window at the given key. * * @param key the key * @param data the data, or null to delete existing data */ //virtual void setData(String key, Object data); /** * Adds the given drag and drop Mime types to the ones * supported for drag and drop on the editor area of this workbench window. *

* The workbench advisor would ordinarily call this method from the * PreWindowOpen callback. * A newly-created workbench window supports no drag and drop transfer * types. *

*

* Note that drag and drop to the editor area requires adding one or more * transfer types (using AddEditorAreaTransfer) and * configuring a drop target listener * (with ConfigureEditorAreaDropListener) * capable of handling any of those transfer types. *

* * @param transfer a drag and drop transfer object * @see #configureEditorAreaDropListener * @see org.blueberry.ui.part.EditorInputTransfer */ virtual void AddEditorAreaTransfer(const QStringList& transferTypes) = 0; /** * Configures the drop target listener for the editor area of this workbench window. *

* The workbench advisor ordinarily calls this method from the * PreWindowOpen callback. * A newly-created workbench window has no configured drop target listener for its * editor area. *

*

* Note that drag and drop to the editor area requires adding one or more * transfer types (using AddEditorAreaTransfer) and * configuring a drop target listener * (with ConfigureEditorAreaDropListener) * capable of handling any of those transfer types. *

* * @param dropTargetListener the drop target listener that will handle * requests to drop an object on to the editor area of this window * * @see #AddEditorAreaTransfer */ - virtual void ConfigureEditorAreaDropListener(const SmartPointer& dropTargetListener) = 0; + virtual void ConfigureEditorAreaDropListener(IDropTargetListener* dropTargetListener) = 0; /** * Creates the menu bar for the window's shell. *

* This should only be called if the advisor is defining custom window contents * in CreateWindowContents, and may only be called once. * The caller must set it in the shell using Shell.setMenuBar(Menu) * but must not make add, remove or change items in the result. * The menu bar is populated by the window's menu manager. * The application can add to the menu manager in the advisor's * FillActionBars method instead. *

* * @return the menu bar, suitable for setting in the shell */ virtual QMenuBar* CreateMenuBar() = 0; /** * Creates the tool bar control. *

* This should only be called if the advisor is defining custom window contents * in CreateWindowContents, and may only be called once. * The caller must lay out the tool bar appropriately within the parent, * but must not add, remove or change items in the result (hence the * return type of QWidget). * The tool bar is populated by the window's tool bar manager. * The application can add to the tool bar manager in the advisor's * FillActionBars method instead. *

* * @param parent the parent widget * @return the tool bar control, suitable for laying out in the parent */ virtual QWidget* CreateToolBar(QWidget* parent) = 0; /* * Creates the status line control. *

* This should only be called if the advisor is defining custom window contents * in createWindowContents, and may only be called once. * The caller must lay out the status line appropriately within the parent, * but must not add, remove or change items in the result (hence the * return type of Control). * The status line is populated by the window's status line manager. * The application can add to the status line manager in the advisor's * fillActionBars method instead. *

* * @param parent the parent composite * @return the status line control, suitable for laying out in the parent */ //virtual Control createStatusLineControl(Composite parent); /** * Creates the page composite, in which the window's pages, and their * views and editors, appear. *

* This should only be called if the advisor is defining custom window contents * in WorkbenchWindowAdvisor#CreateWindowContents(), and may only be called once. * The caller must lay out the page composite appropriately within the parent, * but must not add, remove or change items in the result. * The page composite is populated by the workbench. *

* * @param parent the parent composite * @return the page composite, suitable for laying out in the parent */ virtual QWidget* CreatePageComposite(QWidget* parent) = 0; /** * Saves the current state of the window using the specified memento. * * @param memento the memento in which to save the window's state * @return a status object indicating whether the save was successful * @see IWorkbenchConfigurer#RestoreWorkbenchWindow(IMemento::Pointer) */ virtual bool SaveState(SmartPointer memento) = 0; }; } #endif /*BERRYIWORKBENCHWINDOWCONFIGURER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp index 780f3568e8..a64c6484a7 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchWindowAdvisor.cpp @@ -1,143 +1,144 @@ /*=================================================================== 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 "berryWorkbenchWindowAdvisor.h" #include +#include #include #include #include #include #include #include "internal/berryWorkbenchWindowConfigurer.h" #include "internal/berryWorkbenchPlugin.h" namespace berry { IWorkbenchWindowConfigurer::Pointer WorkbenchWindowAdvisor::GetWindowConfigurer() { return windowConfigurer; } WorkbenchWindowAdvisor::WorkbenchWindowAdvisor( const IWorkbenchWindowConfigurer::Pointer& configurer) { poco_assert(configurer.IsNotNull()); this->windowConfigurer = configurer; } WorkbenchWindowAdvisor::~WorkbenchWindowAdvisor() { } void WorkbenchWindowAdvisor::PreWindowOpen() { // do nothing } ActionBarAdvisor::Pointer WorkbenchWindowAdvisor::CreateActionBarAdvisor( IActionBarConfigurer::Pointer configurer) { ActionBarAdvisor::Pointer actionBarAdvisor(new ActionBarAdvisor(configurer)); return actionBarAdvisor; } void WorkbenchWindowAdvisor::PostWindowRestore() { // do nothing } void WorkbenchWindowAdvisor::OpenIntro() { // TODO: Refactor this into an IIntroManager.openIntro(IWorkbenchWindow) call // introOpened flag needs to be global IWorkbenchConfigurer::Pointer wbConfig = GetWindowConfigurer()->GetWorkbenchConfigurer(); QString key = "introOpened"; //$NON-NLS-1$ ObjectBool::Pointer introOpened = wbConfig->GetData(key).Cast(); if (introOpened && introOpened->GetValue()) { return; } wbConfig->SetData(key, ObjectBool::Pointer(new ObjectBool(true))); IPreferences::Pointer workbenchPrefs = WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); bool showIntro = workbenchPrefs->GetBool(WorkbenchPreferenceConstants::SHOW_INTRO, true); IIntroManager* introManager = wbConfig->GetWorkbench()->GetIntroManager(); bool hasIntro = introManager->HasIntro(); bool isNewIntroContentAvailable = introManager->IsNewContentAvailable(); if (hasIntro && (showIntro || isNewIntroContentAvailable)) { introManager ->ShowIntro(GetWindowConfigurer()->GetWindow(), false); workbenchPrefs->PutBool(WorkbenchPreferenceConstants::SHOW_INTRO, false); workbenchPrefs->Flush(); } } void WorkbenchWindowAdvisor::PostWindowCreate() { // do nothing } void WorkbenchWindowAdvisor::PostWindowOpen() { // do nothing } bool WorkbenchWindowAdvisor::PreWindowShellClose() { // do nothing, but allow the close() to proceed return true; } void WorkbenchWindowAdvisor::PostWindowClose() { // do nothing } void WorkbenchWindowAdvisor::CreateWindowContents(Shell::Pointer shell) { this->GetWindowConfigurer().Cast()->CreateDefaultContents(shell); } void* WorkbenchWindowAdvisor::CreateEmptyWindowContents(void* /*parent*/) { return 0; } bool WorkbenchWindowAdvisor::SaveState(IMemento::Pointer /*memento*/) { // do nothing return true; } bool WorkbenchWindowAdvisor::RestoreState(IMemento::Pointer /*memento*/) { // do nothing return true; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractSourceProvider.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractSourceProvider.cpp index a9a81b089c..be749e9771 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractSourceProvider.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractSourceProvider.cpp @@ -1,75 +1,75 @@ /*=================================================================== 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 "berryAbstractSourceProvider.h" #include "services/berryIServiceLocator.h" #include namespace berry { -bool AbstractSourceProvider::DEBUG = true; //Policy.DEBUG_SOURCES; +bool AbstractSourceProvider::DEBUG = false; //Policy.DEBUG_SOURCES; void AbstractSourceProvider::FireSourceChanged(int sourcePriority, - const QString &sourceName, Object::Pointer sourceValue) + const QString &sourceName, Object::ConstPointer sourceValue) { sourceEvents.singleSourceChanged(sourcePriority, sourceName, sourceValue); } void AbstractSourceProvider::FireSourceChanged(int sourcePriority, - const QHash &sourceValuesByName) + const QHash &sourceValuesByName) { sourceEvents.multipleSourcesChanged(sourcePriority, sourceValuesByName); } void AbstractSourceProvider::LogDebuggingInfo(const QString& message) { if (DEBUG && (message != "")) { BERRY_INFO << "SOURCES" << " >>> " << message; } } void AbstractSourceProvider::AddSourceProviderListener( ISourceProviderListener* listener) { if (listener == 0) { - throw Poco::NullPointerException("The listener cannot be null"); //$NON-NLS-1$ + throw Poco::NullPointerException("The listener cannot be null"); } sourceEvents.AddListener(listener); } void AbstractSourceProvider::RemoveSourceProviderListener( ISourceProviderListener* listener) { if (listener == 0) { - throw Poco::NullPointerException("The listener cannot be null"); //$NON-NLS-1$ + throw Poco::NullPointerException("The listener cannot be null"); } sourceEvents.RemoveListener(listener); } -void AbstractSourceProvider::Initialize(IServiceLocator::ConstPointer /*locator*/) +void AbstractSourceProvider::Initialize(IServiceLocator* /*locator*/) { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractSourceProvider.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractSourceProvider.h index 174af1cf92..a9830f28e2 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractSourceProvider.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractSourceProvider.h @@ -1,118 +1,114 @@ /*=================================================================== 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 BERRYABSTRACTSOURCEPROVIDER_H_ #define BERRYABSTRACTSOURCEPROVIDER_H_ #include "berryISourceProvider.h" #include namespace berry { struct IServiceLocator; /** *

* An implementation of ISourceProvider that provides listener * support. Subclasses need only call fireSourceChanged whenever * appropriate. *

- * - * @since 3.1 */ class AbstractSourceProvider : public ISourceProvider { protected: /** * Whether source providers should print out debugging information to the * console when events arrive. - * - * @since 3.2 */ static bool DEBUG; // = Policy.DEBUG_SOURCES; /** * Notifies all listeners that a single source has changed. * * @param sourcePriority * The source priority that has changed. * @param sourceName * The name of the source that has changed; must not be * null. * @param sourceValue * The new value for the source; may be null. */ void FireSourceChanged(int sourcePriority, - const QString& sourceName, Object::Pointer sourceValue); + const QString& sourceName, Object::ConstPointer sourceValue); /** * Notifies all listeners that multiple sources have changed. * * @param sourcePriority * The source priority that has changed. * @param sourceValuesByName * The map of source names (String) to source * values (Object) that have changed; must not * be null. The names must not be * null, but the values may be null. */ void FireSourceChanged(int sourcePriority, - const QHash& sourceValuesByName); + const QHash& sourceValuesByName); /** * Logs a debugging message in an appropriate manner. If the message is * null or the DEBUG is false, * then this method does nothing. * * @param message * The debugging message to log; if null, then * nothing is logged. - * @since 3.2 */ void LogDebuggingInfo(const QString& message); private: ISourceProviderListener::Events sourceEvents; public: + berryObjectMacro(berry::AbstractSourceProvider) + void AddSourceProviderListener(ISourceProviderListener* listener); void RemoveSourceProviderListener(ISourceProviderListener *listener); /** * This method is called when the source provider is instantiated by * org.blueberry.ui.services. Clients may override this method * to perform initialization. * * @param locator * The global service locator. It can be used to retrieve * services like the IContextService - * @since 3.4 */ - void Initialize(SmartPointer locator); + virtual void Initialize(IServiceLocator* locator); }; } #endif /* BERRYABSTRACTSOURCEPROVIDER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.cpp index 518a8c4e40..f856d850e6 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.cpp @@ -1,282 +1,281 @@ /*=================================================================== 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 "berryAbstractUICTKPlugin.h" #include "internal/berryBundleUtility.h" #include "internal/berryWorkbenchPlugin.h" #include "berryImageDescriptor.h" #include "berryPlatformUI.h" #include "berryIPreferencesService.h" #include "berryIPreferences.h" #include #include namespace berry { const QString AbstractUICTKPlugin::FN_DIALOG_SETTINGS = "dialog_settings.xml"; AbstractUICTKPlugin::AbstractUICTKPlugin() : preferencesService(0) - , context(0) { - } // IDialogSettings getDialogSettings() { // if (dialogSettings == null) { // loadDialogSettings(); // } // return dialogSettings; // } // ImageRegistry getImageRegistry() { // if (imageRegistry == null) { // imageRegistry = createImageRegistry(); // initializeImageRegistry(imageRegistry); // } // return imageRegistry; // } IPreferencesService* AbstractUICTKPlugin::GetPreferencesService() const { // Create the preference store lazily. if (preferencesService == 0) { - ctkServiceReference serviceRef = context->getServiceReference(); + ctkServiceReference serviceRef = m_Context->getServiceReference(); if (!serviceRef) { BERRY_ERROR << "Preferences service not available"; } - preferencesService = context->getService(serviceRef); + preferencesService = m_Context->getService(serviceRef); } return preferencesService; } SmartPointer AbstractUICTKPlugin::GetPreferences() const { IPreferencesService* prefService = this->GetPreferencesService(); if (prefService == NULL) return IPreferences::Pointer(0); return prefService->GetSystemPreferences(); } IWorkbench* AbstractUICTKPlugin::GetWorkbench() { return PlatformUI::GetWorkbench(); } // ImageRegistry createImageRegistry() // { // // //If we are in the UI Thread use that // if (Display.getCurrent() != null) // { // return new ImageRegistry(Display.getCurrent()); // } // // if (PlatformUI.isWorkbenchRunning()) // { // return new ImageRegistry(PlatformUI.getWorkbench().getDisplay()); // } // // //Invalid thread access if it is not the UI Thread // //and the workbench is not created. // throw new SWTError(SWT.ERROR_THREAD_INVALID_ACCESS); // } // void initializeImageRegistry(ImageRegistry reg) { // // spec'ed to do nothing // } // void loadDialogSettings() { // dialogSettings = new DialogSettings("Workbench"); //$NON-NLS-1$ // // // bug 69387: The instance area should not be created (in the call to // // #getStateLocation) if -data @none or -data @noDefault was used // IPath dataLocation = getStateLocationOrNull(); // if (dataLocation != null) { // // try r/w state area in the local file system // String readWritePath = dataLocation.append(FN_DIALOG_SETTINGS) // .toOSString(); // File settingsFile = new File(readWritePath); // if (settingsFile.exists()) { // try { // dialogSettings.load(readWritePath); // } catch (IOException e) { // // load failed so ensure we have an empty settings // dialogSettings = new DialogSettings("Workbench"); //$NON-NLS-1$ // } // // return; // } // } // // // otherwise look for bundle specific dialog settings // URL dsURL = BundleUtility.find(getBundle(), FN_DIALOG_SETTINGS); // if (dsURL == null) { // return; // } // // InputStream is = null; // try { // is = dsURL.openStream(); // BufferedReader reader = new BufferedReader( // new InputStreamReader(is, "utf-8")); //$NON-NLS-1$ // dialogSettings.load(reader); // } catch (IOException e) { // // load failed so ensure we have an empty settings // dialogSettings = new DialogSettings("Workbench"); //$NON-NLS-1$ // } finally { // try { // if (is != null) { // is.close(); // } // } catch (IOException e) { // // do nothing // } // } // } // void refreshPluginActions() { // // If the workbench is not started yet, or is no longer running, do nothing. // if (!PlatformUI.isWorkbenchRunning()) { // return; // } // // // startup() is not guaranteed to be called in the UI thread, // // but refreshPluginActions must run in the UI thread, // // so use asyncExec. See bug 6623 for more details. // Display.getDefault().asyncExec(new Runnable() { // public void run() { // WWinPluginAction.refreshActionList(); // } // }); // } // void saveDialogSettings() { // if (dialogSettings == null) { // return; // } // // try { // IPath path = getStateLocationOrNull(); // if(path == null) { // return; // } // String readWritePath = path // .append(FN_DIALOG_SETTINGS).toOSString(); // dialogSettings.save(readWritePath); // } catch (IOException e) { // // spec'ed to ignore problems // } catch (IllegalStateException e) { // // spec'ed to ignore problems // } // } void AbstractUICTKPlugin::start(ctkPluginContext* context) { - this->context = context; + Plugin::start(context); // Should only attempt refreshPluginActions() once the bundle // has been fully started. Otherwise, action delegates // can be created while in the process of creating // a triggering action delegate (if UI events are processed during startup). // Also, if the start throws an exception, the bundle will be shut down. // We don't want to have created any delegates if this happens. // See bug 63324 for more details. // bundleListener = new BundleListener() // { // public void bundleChanged(BundleEvent event) // { // if (event.getBundle() == getBundle()) // { // if (event.getType() == BundleEvent.STARTED) // { // // We're getting notified that the bundle has been started. // // Make sure it's still active. It may have been shut down between // // the time this event was queued and now. // if (getBundle().getState() == Bundle.ACTIVE) // { // refreshPluginActions(); // } // fc.removeBundleListener(this); // } // } // } // }; // context.addBundleListener(bundleListener); // bundleListener is removed in stop(BundleContext) } void AbstractUICTKPlugin::stop(ctkPluginContext* context) { Q_UNUSED(context) - this->context = 0; // try // { // if (bundleListener != null) // { // context.removeBundleListener(bundleListener); // } // saveDialogSettings(); // savePreferenceStore(); // preferenceStore = null; // if (imageRegistry != null) // imageRegistry.dispose(); // imageRegistry = null; //} + + Plugin::stop(context); } SmartPointer AbstractUICTKPlugin::ImageDescriptorFromPlugin( const QString& pluginId, const QString& imageFilePath) { if (pluginId.isEmpty() || imageFilePath.isEmpty()) { throw ctkInvalidArgumentException("argument cannot be empty"); } // if the plug-in is not ready then there is no image QSharedPointer plugin = BundleUtility::FindPlugin(pluginId); if (!BundleUtility::IsReady(plugin.data())) { return ImageDescriptor::Pointer(0); } QByteArray imgContent = plugin->getResource(imageFilePath); QImage image = QImage::fromData(imgContent); QPixmap pixmap = QPixmap::fromImage(image); QIcon* icon = new QIcon(pixmap); if (icon->isNull()) return ImageDescriptor::Pointer(0); return ImageDescriptor::CreateFromImage(icon); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h index ac05691486..ab4218e075 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractUICTKPlugin.h @@ -1,334 +1,331 @@ /*=================================================================== 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 BERRYABSTRACTUICTKPLUGIN_H_ #define BERRYABSTRACTUICTKPLUGIN_H_ #include #include namespace berry { template class SmartPointer; struct IPreferences; struct IPreferencesService; struct IWorkbench; -class ImageDescriptor; +struct ImageDescriptor; /** * \ingroup org_blueberry_ui_qt * * Abstract base class for plug-ins that integrate with the BlueBerry platform UI. *

* Subclasses obtain the following capabilities: *

*

* Preferences *

    *
  • The platform core runtime contains general support for plug-in * preferences (org.blueberry.core.runtime.Preferences). * This class provides appropriate conversion to the older JFace preference * API (org.blueberry.jface.preference.IPreferenceStore).
  • *
  • The method getPreferenceStore returns the JFace preference * store (cf. Plugin.getPluginPreferences which returns * a core runtime preferences object.
  • *
  • Subclasses may reimplement initializeDefaultPreferences * to set up any default values for preferences using JFace API. In this * case, initializeDefaultPluginPreferences should not be * overridden.
  • *
  • Subclasses may reimplement * initializeDefaultPluginPreferences to set up any default * values for preferences using core runtime API. In this * case, initializeDefaultPreferences should not be * overridden.
  • *
  • Preferences are also saved automatically on plug-in shutdown. * However, saving preferences immediately after changing them is * strongly recommended, since that ensures that preference settings * are not lost even in the event of a platform crash.
  • *
* Dialogs *
    *
  • The dialog store is read the first time getDialogSettings * is called.
  • *
  • The dialog store allows the plug-in to "record" important choices made * by the user in a wizard or dialog, so that the next time the * wizard/dialog is used the widgets can be defaulted to better values. A * wizard could also use it to record the last 5 values a user entered into * an editable combo - to show "recent values".
  • *
  • The dialog store is found in the file whose name is given by the * constant FN_DIALOG_STORE. A dialog store file is first * looked for in the plug-in's read/write state area; if not found there, * the plug-in's install directory is checked. * This allows a plug-in to ship with a read-only copy of a dialog store * file containing initial values for certain settings.
  • *
  • Plug-in code can call saveDialogSettings to cause settings to * be saved in the plug-in's read/write state area. A plug-in may opt to do * this each time a wizard or dialog is closed to ensure the latest * information is always safe on disk.
  • *
  • Dialog settings are also saved automatically on plug-in shutdown.
  • *
* Images *
    *
  • A typical UI plug-in will have some images that are used very frequently * and so need to be cached and shared. The plug-in's image registry * provides a central place for a plug-in to store its common images. * Images managed by the registry are created lazily as needed, and will be * automatically disposed of when the plug-in shuts down. Note that the * number of registry images should be kept to a minimum since many OSs * have severe limits on the number of images that can be in memory at once. *
*

* For easy access to your plug-in object, use the singleton pattern. Declare a * static variable in your plug-in class for the singleton. Store the first * (and only) instance of the plug-in class in the singleton when it is created. * Then access the singleton when needed through a static getDefault * method. *

*

* See the description on {@link Plugin}. *

*/ class BERRY_UI_QT AbstractUICTKPlugin : public Plugin { private: /** * The name of the dialog settings file (value * "dialog_settings.xml"). */ static const QString FN_DIALOG_SETTINGS; /** * Storage for dialog and wizard data; null if not yet * initialized. */ //DialogSettings dialogSettings = null; /** * Storage for preferences. */ mutable IPreferencesService* preferencesService; /** * The registry for all graphic images; null if not yet * initialized. */ //ImageRegistry imageRegistry = null; /** * The bundle listener used for kicking off refreshPluginActions(). */ //BundleListener bundleListener; - ctkPluginContext* context; - - public: /** * Creates an abstract UI plug-in runtime object. *

* Plug-in runtime classes are ctkPluginActivators and so must * have an default constructor. This method is called by the runtime when * the associated bundle is being activated. */ AbstractUICTKPlugin(); /** * Returns the dialog settings for this UI plug-in. * The dialog settings is used to hold persistent state data for the various * wizards and dialogs of this plug-in in the context of a workbench. *

* If an error occurs reading the dialog store, an empty one is quietly created * and returned. *

*

* Subclasses may override this method but are not expected to. *

* * @return the dialog settings */ // IDialogSettings getDialogSettings(); /** * Returns the image registry for this UI plug-in. *

* The image registry contains the images used by this plug-in that are very * frequently used and so need to be globally shared within the plug-in. Since * many OSs have a severe limit on the number of images that can be in memory at * any given time, a plug-in should only keep a small number of images in their * registry. *

* Subclasses should reimplement initializeImageRegistry if they have * custom graphic images to load. *

*

* Subclasses may override this method but are not expected to. *

* * @return the image registry */ // ImageRegistry getImageRegistry(); /** * Returns the preferences service for this UI plug-in. * This preferences service is used to hold persistent settings for this plug-in in * the context of a workbench. Some of these settings will be user controlled, * whereas others may be internal setting that are never exposed to the user. *

* If an error occurs reading the preferences service, an empty preference service is * quietly created, initialized with defaults, and returned. *

* * @return the preferences service */ IPreferencesService* GetPreferencesService() const; SmartPointer GetPreferences() const; /** * Returns the Platform UI workbench. *

* This method exists as a convenience for plugin implementors. The * workbench can also be accessed by invoking PlatformUI.getWorkbench(). *

* @return IWorkbench the workbench for this plug-in */ IWorkbench* GetWorkbench(); protected: /** * Returns a new image registry for this plugin-in. The registry will be * used to manage images which are frequently used by the plugin-in. *

* The default implementation of this method creates an empty registry. * Subclasses may override this method if needed. *

* * @return ImageRegistry the resulting registry. * @see #getImageRegistry */ // ImageRegistry createImageRegistry(); /** * Initializes an image registry with images which are frequently used by the * plugin. *

* The image registry contains the images used by this plug-in that are very * frequently used and so need to be globally shared within the plug-in. Since * many OSs have a severe limit on the number of images that can be in memory * at any given time, each plug-in should only keep a small number of images in * its registry. *

* Implementors should create a JFace image descriptor for each frequently used * image. The descriptors describe how to create/find the image should it be needed. * The image described by the descriptor is not actually allocated until someone * retrieves it. *

* Subclasses may override this method to fill the image registry. *

* @param reg the registry to initalize * * @see #getImageRegistry */ // void initializeImageRegistry(ImageRegistry reg); /** * Loads the dialog settings for this plug-in. * The default implementation first looks for a standard named file in the * plug-in's read/write state area; if no such file exists, the plug-in's * install directory is checked to see if one was installed with some default * settings; if no file is found in either place, a new empty dialog settings * is created. If a problem occurs, an empty settings is silently used. *

* This framework method may be overridden, although this is typically * unnecessary. *

*/ // void loadDialogSettings(); /** * Refreshes the actions for the plugin. * This method is called from startup. *

* This framework method may be overridden, although this is typically * unnecessary. *

*/ // void refreshPluginActions(); /** * Saves this plug-in's dialog settings. * Any problems which arise are silently ignored. */ // void saveDialogSettings(); public: /** * The AbstractUIPlugin implementation of this Plugin * method refreshes the plug-in actions. Subclasses may extend this method, * but must send super first. */ void start(ctkPluginContext* context); /** * The AbstractUIPlugin implementation of this Plugin * method saves this plug-in's preference and dialog stores and shuts down * its image registry (if they are in use). Subclasses may extend this * method, but must send super last. A try-finally statement should * be used where necessary to ensure that super.shutdown() is * always done. */ void stop(ctkPluginContext* context); /** * Creates and returns a new image descriptor for an image file located * within the specified plug-in. *

* This is a convenience method that simply locates the image file in * within the plug-in (no image registries are involved). The path is * relative to the root of the plug-in, and takes into account files * coming from plug-in fragments. The path may include $arg$ elements. * However, the path must not have a leading "." or path separator. * Clients should use a path like "icons/mysample.gif" rather than * "./icons/mysample.gif" or "/icons/mysample.gif". *

* * @param pluginId the id of the plug-in containing the image file; * null is returned if the plug-in does not exist * @param imageFilePath the relative path of the image file, relative to the * root of the plug-in; the path must be legal * @return an image descriptor, or null if no image * could be found * @since 3.0 */ static SmartPointer ImageDescriptorFromPlugin( const QString& pluginId, const QString& imageFilePath); }; } // namespace berry #endif /*BERRYABSTRACTUICTKPLUGIN_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIActionBars.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIActionBars.h index ad9b2fc3b3..2236893cea 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIActionBars.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIActionBars.h @@ -1,171 +1,171 @@ /*=================================================================== 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 BERRYIACTIONBARS_H #define BERRYIACTIONBARS_H #include namespace berry { struct IServiceLocator; struct IMenuManager; struct IStatusLineManager; struct IToolBarManager; class Action; /** * Used by a part to access its menu, toolbar, and status line managers. *

* Within the workbench each part, editor or view, has a private set of action * bars. This set, which contains a menu, toolbar, and status line, appears * in the local toolbar for a view and in the window for an editor. The view * may provide an implementation for pre-existing actions or add new actions to * the action bars. *

* In a workbench window there are a number of actions which are applicable to * all parts. Some common examples are CUT, COPY and * PASTE. These actions, known as "global actions", are contributed to * the workbench window by the window itself and shared by all parts. The * presentation is owned by the window. The implementation is delegated to the * active part. *

* To participate in the global action design an IWorkbenchPart should * register a handler for each global action which is implemented by the part. This * can be done by calling setGlobalActionHandler. For convenience, the * standard global actions are defined in * IWorkbenchActionConstants. *

* Additional work is required for the Delete global action. In * this case the accelerator is defined in the menu item text but is not hooked * on the window. This is to support text editors where the Delete * key is functional even when the Delete action is disabled (no text * is selected). An implementation for this accelerator must be defined locally, * in each part, by listening for Delete key events. *

* A part may also contribute new actions to the action bars as required. To do * this, call getMenuManager, getToolBarManager, or * getStatusLineManager as appropriate to get the action target. * Add the action(s) to the target and call update to commit * any changes to the underlying widgets. *

* This interface is not intended to be implemented by clients. *

* @noimplement This interface is not intended to be implemented by clients. */ struct IActionBars : public Object { - berryInterfaceMacro(IActionBars, berry) + berryObjectMacro(berry::IActionBars) /** * Clears the global action handler list. *

* Note: Clients who manipulate the global action list are * responsible for calling updateActionBars so that the changes * can be propagated throughout the workbench. *

*/ virtual void ClearGlobalActionHandlers() = 0; /** * Returns the global action handler for the action with the given id. * * @param actionId an action id declared in the registry * @return an action handler which implements the action id, or * null if none is registered * @see IWorkbenchActionConstants * @see #setGlobalActionHandler(String, IAction) */ virtual Action* GetGlobalActionHandler(const QString& actionId) const = 0; /** * Returns the menu manager. *

* Note: Clients who add or remove items from the returned menu manager are * responsible for calling updateActionBars so that the changes * can be propagated throughout the workbench. *

* * @return the menu manager */ virtual IMenuManager* GetMenuManager() = 0; /** * Returns the service locator for these action bars. The locator is found * by looking locally, and then ascending the action bar hierarchy. * * @return The service locator; never null. */ virtual IServiceLocator* GetServiceLocator() = 0; /** * Returns the status line manager. *

* Note: Clients who add or remove items from the returned status line * manager are responsible for calling updateActionBars so * that the changes can be propagated throughout the workbench. *

* * @return the status line manager */ virtual IStatusLineManager* GetStatusLineManager() = 0; /** * Returns the tool bar manager. *

* Note: Clients who add or remove items from the returned tool bar manager are * responsible for calling updateActionBars so that the changes * can be propagated throughout the workbench. *

* * @return the tool bar manager */ virtual IToolBarManager* GetToolBarManager() = 0; /** * Sets the global action handler for the action with the given id. *

* Note: Clients who manipulate the global action list are * responsible for calling updateActionBars so that the changes * can be propagated throughout the workbench. *

* * @param actionId an action id declared in the registry * @param handler an action which implements the action id, or * null to clear any existing handler * @see IWorkbenchActionConstants */ virtual void SetGlobalActionHandler(const QString& actionId, Action* handler) = 0; /** * Updates the action bars. *

* Clients who add or remove items from the menu, tool bar, or status line * managers, or that update global action handlers, should call this method * to propagated the changes throughout the workbench. *

* * @see #setGlobalActionHandler(String, IAction) * @see #clearGlobalActionHandlers() */ virtual void UpdateActionBars() = 0; }; } #endif // BERRYIACTIONBARS_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIContextService.cpp similarity index 54% copy from BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIContextService.cpp index 25a2d7c6a0..25fc8369ca 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIContextService.cpp @@ -1,41 +1,26 @@ /*=================================================================== 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 BERRYOSGISTRING_H_ -#define BERRYOSGISTRING_H_ - -#include "berryMacros.h" - -#include +#include "berryIContextService.h" namespace berry { -class ObjectString : public QString, public Object -{ - -public: - - berryObjectMacro(berry::ObjectString) - - ObjectString() {} - ObjectString(const QString& s) : QString(s) {} - - ~ObjectString() {} -}; +const QString IContextService::CONTEXT_ID_WORKBENCH_MENU = "org.blueberry.ui.contexts.workbenchMenu"; +const QString IContextService::CONTEXT_ID_DIALOG = "org.blueberry.ui.contexts.dialog"; +const QString IContextService::CONTEXT_ID_DIALOG_AND_WINDOW = "org.blueberry.ui.contexts.dialogAndWindow"; +const QString IContextService::CONTEXT_ID_WINDOW = "org.blueberry.ui.contexts.window"; } - -#endif /*BERRYOSGISTRING_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIContextService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIContextService.h new file mode 100644 index 0000000000..82462713ce --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIContextService.h @@ -0,0 +1,382 @@ +/*=================================================================== + +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 BERRYICONTEXTSERVICE_H +#define BERRYICONTEXTSERVICE_H + +#include "berryIServiceWithSources.h" + +namespace berry { + +struct IContextActivation; +struct IContextManagerListener; + +class Context; +class Expression; +class Shell; + +/** + *

+ * Provides services related to contexts in the blueberry workbench. This provides + * access to contexts. + *

+ *

+ * This service can be acquired from your service locator: + *

+ *   IContextService service = (IContextService) getSite().getService(IContextService.class);
+ * 
+ *
    + *
  • This service is available globally.
  • + *
+ *

+ * + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + */ +struct IContextService : public IServiceWithSources +{ + + /** + * The identifier for the context that is active when a workbench is active. + */ + static const QString CONTEXT_ID_WORKBENCH_MENU; // = "org.blueberry.ui.contexts.workbenchMenu"; + + /** + * The identifier for the context that is active when a shell registered as + * a dialog. + */ + static const QString CONTEXT_ID_DIALOG; // = "org.blueberry.ui.contexts.dialog"; + + /** + * The identifier for the context that is active when a shell is registered + * as either a window or a dialog. + */ + static const QString CONTEXT_ID_DIALOG_AND_WINDOW; // = "org.blueberry.ui.contexts.dialogAndWindow"; + + /** + * The identifier for the context that is active when a shell is registered + * as a window. + */ + static const QString CONTEXT_ID_WINDOW; // = "org.blueberry.ui.contexts.window"; + + enum ShellType { + /** + * The type used for registration indicating that the shell should be + * treated as a dialog. When the given shell is active, the "In Dialogs" + * context should also be active. + */ + TYPE_DIALOG = 0, + + /** + * The type used for registration indicating that the shell should not + * receive any key bindings be default. When the given shell is active, we + * should not provide any EnabledSubmission instances for the + * "In Dialogs" or "In Windows" contexts. + * + */ + TYPE_NONE = 1, + + /** + * The type used for registration indicating that the shell should be + * treated as a window. When the given shell is active, the "In Windows" + * context should also be active. + */ + TYPE_WINDOW = 2 + }; + + /** + *

+ * Activates the given context within the context of this service. If this + * service was retrieved from the workbench, then this context will be + * active globally. If the service was retrieved from a nested component, + * then the context will only be active within that component. + *

+ *

+ * Also, it is guaranteed that the contexts submitted through a particular + * service will be cleaned up when that services is destroyed. So, for + * example, a service retrieved from a IWorkbenchPartSite + * would deactivate all of its contexts when the site is destroyed. + *

+ * + * @param contextId + * The identifier for the context which should be activated; must + * not be null. + * @return A token which can be used to later cancel the activation. Only + * someone with access to this token can cancel the activation. The + * activation will automatically be cancelled if the context from + * which this service was retrieved is destroyed. + */ + virtual SmartPointer ActivateContext(const QString& contextId) = 0; + + /** + *

+ * Activates the given context within the context of this service. The + * context becomes active when expression evaluates to + * true. This is the same as calling + * {@link #activateContext(String, Expression, boolean)} with global==false. + *

+ *

+ * Also, it is guaranteed that the context submitted through a particular + * service will be cleaned up when that services is destroyed. So, for + * example, a service retrieved from a IWorkbenchPartSite + * would deactivate all of its handlers when the site is destroyed. + *

+ * + * @param contextId + * The identifier for the context which should be activated; must + * not be null. + * @param expression + * This expression must evaluate to true before + * this context will really become active. The expression may be + * null if the context should always be active. + * @return A token which can be used to later cancel the activation. Only + * someone with access to this token can cancel the activation. The + * activation will automatically be cancelled if the context from + * which this service was retrieved is destroyed. + * + * @see ISources + */ + virtual SmartPointer ActivateContext(const QString& contextId, + const SmartPointer& expression) = 0; + + /** + *

+ * Activates the given context within the context of this service. The + * context becomes active when expression evaluates to + * true. If global==false then this service + * must also be the active service to activate the context. + *

+ *

+ * Also, it is guaranteed that the context submitted through a particular + * service will be cleaned up when that services is destroyed. So, for + * example, a service retrieved from a IWorkbenchPartSite + * would deactivate all of its handlers when the site is destroyed. + *

+ * + * @param contextId + * The identifier for the context which should be activated; must + * not be null. + * @param expression + * This expression must evaluate to true before + * this context will really become active. The expression may be + * null if the context should always be active. + * @param global + * Indicates that the handler should be activated irrespectively + * of whether the corresponding workbench component (e.g., + * window, part, etc.) is active. + * @return A token which can be used to later cancel the activation. Only + * someone with access to this token can cancel the activation. The + * activation will automatically be cancelled if the context from + * which this service was retrieved is destroyed. + * + * @see ISources + */ + virtual SmartPointer ActivateContext(const QString& contextId, + const SmartPointer& expression, + bool global) = 0; + + /** + * Adds a listener to this context service. The listener will be notified + * when the set of defined contexts changes. This can be used to track the + * global appearance and disappearance of contexts. + *

+ * Note: listeners should be removed when no longer necessary. If + * not, they will be removed when the IServiceLocator used to acquire this + * service is disposed. + *

+ * + * @param listener + * The listener to attach; must not be null. + * @see RemoveContextManagerListener(IContextManagerListener*) + */ + virtual void AddContextManagerListener(IContextManagerListener* listener) = 0; + + /** + * Deactivates the given context within the context of this service. If the + * handler was context with a different service, then it must be deactivated + * from that service instead. It is only possible to retract a context + * activation with this method. That is, you must have the same + * IContextActivation used to activate the context. + * + * @param activation + * The token that was returned from a call to + * activateContext; must not be null. + */ + virtual void DeactivateContext(const SmartPointer& activation) = 0; + + /** + * Deactivates the given contexts within the context of this service. If the + * contexts were activated with a different service, then they must be + * deactivated from that service instead. It is only possible to retract + * context activations with this method. That is, you must have the same + * IContextActivation instances used to activate the + * contexts. + * + * @param activations + * The tokens that were returned from a call to + * activateContext. This collection must only + * contain instances of IContextActivation. The + * collection must not be null. + */ + virtual void DeactivateContexts(const QList >& activations) = 0; + + /** + * Returns the set of active context identifiers. + * + * @return The set of active context identifiers; this value may be + * null if no active contexts have been set yet. If + * the set is not null, then it contains only + * instances of String. + */ + virtual QList GetActiveContextIds() const = 0; + + /** + * Retrieves the context with the given identifier. If no such context + * exists, then an undefined context with the given id is created. + * + * @param contextId + * The identifier to find; must not be null. + * @return A context with the given identifier, either defined or undefined. + */ + virtual SmartPointer GetContext(const QString& contextId) const = 0; + + /** + * Returns the collection of all of the defined contexts in the workbench. + * + * @return The collection of contexts (Context) that are + * defined; never null, but may be empty. + */ + virtual QList > GetDefinedContexts() const = 0; + + /** + * Returns the collection of the identifiers for all of the defined contexts + * in the workbench. + * + * @return The collection of context identifiers (String) + * that are defined; never null, but may be empty. + */ + virtual QList GetDefinedContextIds() const = 0; + + /** + * Returns the shell type for the given shell. + * + * @param shell + * The shell for which the type should be determined. If this + * value is null, then + * IContextService.TYPE_NONE is returned. + * @return IContextService.TYPE_WINDOW, + * IContextService.TYPE_DIALOG, or + * IContextService.TYPE_NONE. + */ + virtual ShellType GetShellType(const SmartPointer& shell) const = 0; + + virtual ShellType GetShellType(QWidget* widget) const = 0; + + /** + *

+ * Reads the context information from the registry and the preferences. This + * will overwrite any of the existing information in the context service. + * This method is intended to be called during start-up. When this method + * completes, this context service will reflect the current state of the + * registry and preference store. + *

+ */ + virtual void ReadRegistry() = 0; + + /** + *

+ * Registers a shell to automatically promote or demote some basic types of + * contexts. The "In Dialogs" and "In Windows" contexts are provided by the + * system. This a convenience method to ensure that these contexts are + * promoted when the given is shell is active. + *

+ *

+ * If a shell is registered as a window, then the "In Windows" context is + * enabled when that shell is active. If a shell is registered as a dialog -- + * or is not registered, but has a parent shell -- then the "In Dialogs" + * context is enabled when that shell is active. If the shell is registered + * as none -- or is not registered, but has no parent shell -- then the + * neither of the contexts will be enabled (by us -- someone else can always + * enabled them). + *

+ *

+ * If the provided shell has already been registered, then this method will + * change the registration. + *

+ * + * @param shell + * The shell to register for key bindings; must not be + * null. + * @param type + * The type of shell being registered. This value must be one of + * the constants given in this interface. + * + * @return true if the shell had already been registered + * (i.e., the registration has changed); false + * otherwise. + */ + virtual bool RegisterShell(const SmartPointer& shell, ShellType type) = 0; + + /** + * Removes a listener from this context service. + * + * @param listener + * The listener to be removed; must not be null. + */ + virtual void RemoveContextManagerListener(IContextManagerListener* listener) = 0; + + /** + *

+ * Unregisters a shell that was previously registered. After this method + * completes, the shell will be treated as if it had never been registered + * at all. If you have registered a shell, you should ensure that this + * method is called when the shell is disposed. Otherwise, a potential + * memory leak will exist. + *

+ *

+ * If the shell was never registered, or if the shell is null, + * then this method returns false and does nothing. + * + * @param shell + * The shell to be unregistered; does nothing if this value is + * null. + * + * @return true if the shell had been registered; + * false otherwise. + */ + virtual bool UnregisterShell(const SmartPointer& shell) = 0; + + /** + * Informs the service that a batch operation has started. + *

+ * Note: You must insure that if you call + * deferUpdates(true) that nothing in your batched operation + * will prevent the matching call to deferUpdates(false). + *

+ * + * @param defer + * true when starting a batch operation false when ending the + * operation + */ + virtual void DeferUpdates(bool defer) = 0; + +}; + +} + +Q_DECLARE_INTERFACE(berry::IContextService, "org.blueberry.ui.IContextService") + +#endif // BERRYICONTEXTSERVICE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIContributionRoot.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIContributionRoot.h index 7cd3bff72f..ff15896822 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIContributionRoot.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIContributionRoot.h @@ -1,71 +1,71 @@ /*=================================================================== 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 BERRYICONTRIBUTIONROOT_H #define BERRYICONTRIBUTIONROOT_H #include namespace berry { struct IContributionItem; class Expression; /** * Instances of this interface represent a position in the contribution * hierarchy into which {@link AbstractContributionFactory} instances may insert * elements. Instances of this interface are provided by the platform and this * interface should NOT be implemented by clients. */ struct IContributionRoot : public Object { - berryInterfaceMacro(IContributionRoot, berry) + berryObjectMacro(berry::IContributionRoot) /** * Adds a given contribution item with provided visibility expression and * kill-switch filtering as a direct child of this container. This should be * called for all top-level elements created in * {@link AbstractContributionFactory#createContributionItems(org.eclipse.ui.services.IServiceLocator, IContributionRoot)} * * @param item * the item to add * @param visibleWhen * the visibility expression. May be null. */ virtual void AddContributionItem(const SmartPointer& item, const SmartPointer& visibleWhen) = 0; /** * Registers visibilty for arbitrary {@link IContributionItem} instances * that are NOT direct children of this container. Ie: children of a * {@link IContributionManager} that has been previously registered with a * call to {{@link #AddContributionItem(IContributionItem, Expression)}. * * @param item * the item for which to register a visibility clause * @param visibleWhen * the visibility expression. May be null in which * case this method is a no-op. */ virtual void RegisterVisibilityForChild(const SmartPointer& item, const SmartPointer& visibleWhen) = 0; }; } #endif // BERRYICONTRIBUTIONROOT_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIDropTargetListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIDropTargetListener.h index 8cdcc05a0b..73bb89e410 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIDropTargetListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIDropTargetListener.h @@ -1,85 +1,82 @@ /*=================================================================== 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 BERRYIDROPTARGETLISTENER_H #define BERRYIDROPTARGETLISTENER_H -#include -#include - #include +#include "berryMessage.h" class QDragEnterEvent; class QDragLeaveEvent; class QDragMoveEvent; class QDropEvent; namespace berry { -struct BERRY_UI_QT IDropTargetListener : public Object { - - berryInterfaceMacro(IDropTargetListener, berry); +struct BERRY_UI_QT IDropTargetListener +{ struct Events { enum Type { NONE = 0x00000000, ENTER = 0x00000001, LEAVE = 0x00000002, MOVE = 0x00000004, DROP = 0x00000008, ALL = 0xffffffff }; Q_DECLARE_FLAGS(Types, Type) typedef Message1 DragEnterEventType; typedef Message1 DragLeaveEventType; typedef Message1 DragMoveEventType; typedef Message1 DropEventType; DragEnterEventType dragEnter; DragLeaveEventType dragLeave; DragMoveEventType dragMove; DropEventType drop; void AddListener(IDropTargetListener* listener); void RemoveListener(IDropTargetListener* listener); private: typedef MessageDelegate1 DragEnterDelegate; typedef MessageDelegate1 DragLeaveDelegate; typedef MessageDelegate1 DragMoveDelegate; typedef MessageDelegate1 DropDelegate; }; virtual Events::Types GetDropTargetEventTypes() const = 0; virtual void DragEnterEvent(QDragEnterEvent* /*event*/) {} virtual void DragLeaveEvent(QDragLeaveEvent* /*event*/) {} virtual void DragMoveEvent(QDragMoveEvent* /*event*/) {} virtual void DropEvent(QDropEvent* /*event*/) {} }; } Q_DECLARE_OPERATORS_FOR_FLAGS(berry::IDropTargetListener::Events::Types) #endif // BERRYIDROPTARGETLISTENER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorDescriptor.h index dc48ff4586..144a73b17f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorDescriptor.h @@ -1,123 +1,123 @@ /*=================================================================== 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 BERRYIEDITORDESCRIPTOR_H_ #define BERRYIEDITORDESCRIPTOR_H_ #include #include "berryIWorkbenchPartDescriptor.h" #include "berryIEditorMatchingStrategy.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * Description of an editor in the workbench editor registry. The * editor descriptor contains the information needed to create editor instances. *

* An editor descriptor typically represents one of three types of editors: *

    *
  • a file editor extension for a specific file extension.
  • *
  • a file editor added by the user (via the workbench preference page)
  • *
  • a general editor extension which works on objects other than files.
  • *
*

*

* This interface is not intended to be implemented or extended by clients. *

* * @see IEditorRegistry * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IEditorDescriptor : public IWorkbenchPartDescriptor { - berryInterfaceMacro(IEditorDescriptor, berry); + berryObjectMacro(berry::IEditorDescriptor) virtual ~IEditorDescriptor(); /** * Returns the editor id. *

* For internal editors, this is the extension id as defined in the workbench * registry; for external editors, it is path and file name of the external * program. *

* * @return the id of the editor */ virtual QString GetId() const = 0; /** * Returns the descriptor of the image for this editor. * * @return the descriptor of the image to display next to this editor */ //ImageDescriptor getImageDescriptor() = 0; /** * Returns the label to show for this editor. * * @return the editor label */ virtual QString GetLabel() const = 0; /** * Returns whether this editor descriptor will open a regular editor * part inside the editor area. * * @return true if editor is inside editor area, and * false otherwise * @since 3.0 */ virtual bool IsInternal() const = 0; /** * Returns whether this editor descriptor will open an external * editor in-place inside the editor area. * * @return true if editor is in-place, and false * otherwise * @since 3.0 */ virtual bool IsOpenInPlace() const = 0; /** * Returns whether this editor descriptor will open an external editor * in a new window outside the workbench. * * @return true if editor is external, and false * otherwise * @since 3.0 */ virtual bool IsOpenExternal() const = 0; /** * Returns the editor matching strategy object for editors * represented by this editor descriptor, or null * if there is no explicit matching strategy specified. * * @return the editor matching strategy, or null if none * @since 3.1 */ virtual IEditorMatchingStrategy::Pointer GetEditorMatchingStrategy() = 0; }; } #endif /*BERRYIEDITORDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorInput.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorInput.h index de21afd1d9..cc4a571f7f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorInput.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorInput.h @@ -1,143 +1,143 @@ /*=================================================================== 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 BERRYIEDITORINPUT_H_ #define BERRYIEDITORINPUT_H_ #include #include #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * IEditorInput is a light weight descriptor of editor input, * like a file name but more abstract. It is not a model. It is a description of * the model source for an IEditorPart. *

* Clients implementing this editor input interface must override * Object#operator==(const Object*) to answer true * for two inputs that are * the same. The IWorbenchPage.openEditor APIs are dependent on * this to find an editor with the same input. *

*

* Clients should extend this interface to declare new types of editor inputs. *

*

* An editor input is passed to an editor via the IEditorPart.init * method. Due to the wide range of valid editor inputs, it is not possible to * define generic methods for getting and setting bytes. *

*

* Editor input must implement the IAdaptable interface; * extensions are managed by the platform's adapter manager. *

*

* Please note that it is important that the editor input be light weight. * Within the workbench, the navigation history tends to hold on to editor * inputs as a means of reconstructing the editor at a later time. The * navigation history can hold on to quite a few inputs (i.e., the default is * fifty). The actual data model should probably not be held in the input. *

* * * @see org.blueberry.ui.IEditorPart * @see org.blueberry.ui.IWorkbenchPage#openEditor(IEditorInput, String) * @see org.blueberry.ui.IWorkbenchPage#openEditor(IEditorInput, String, boolean) */ struct BERRY_UI_QT IEditorInput : public Object // public IAdaptable { - berryInterfaceMacro(IEditorInput, berry) + berryObjectMacro(berry::IEditorInput) ~IEditorInput(); /** * Returns whether the editor input exists. *

* This method is primarily used to determine if an editor input should * appear in the "File Most Recently Used" menu. An editor input will appear * in the list until the return value of exists becomes * false or it drops off the bottom of the list. * * @return true if the editor input exists; * false otherwise */ virtual bool Exists() const = 0; /** * Returns the image descriptor for this input. * *

* Note: although a null return value has never been permitted from this * method, there are many known buggy implementations that return null. * Clients that need the image for an editor are advised to use * IWorkbenchPart.getImage() instead of IEditorInput.getImageDescriptor(), * or to recover from a null return value in a manner that records the ID of * the problematic editor input. Implementors that have been returning null * from this method should pick some other default return value (such as * ImageDescriptor.getMissingImageDescriptor()). *

* * @return the image descriptor for this input; may be null if * there is no image. */ //virtual ImageDescriptor GetImageDescriptor() = 0; /** * Returns the name of this editor input for display purposes. *

* For instance, when the input is from a file, the return value would * ordinarily be just the file name. * * @return the name string; never null; */ virtual QString GetName() const = 0; /** * Returns an object that can be used to save the state of this editor * input. * * @return the persistable element, or null if this editor * input cannot be persisted */ //virtual IPersistableElement GetPersistable() = 0; /** * Returns the tool tip text for this editor input. This text is used to * differentiate between two input with the same name. For instance, * MyClass.java in folder X and MyClass.java in folder Y. The format of the * text varies between input types. *

* * @return the tool tip text; never null. */ virtual QString GetToolTipText() const = 0; /** * Returns true if two editor inputs are the same * */ virtual bool operator==(const Object* o) const = 0; }; } #endif /*BERRYIEDITORINPUT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorMatchingStrategy.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorMatchingStrategy.h index 732913f901..09e90a4e17 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorMatchingStrategy.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorMatchingStrategy.h @@ -1,66 +1,65 @@ /*=================================================================== 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 BERRYIEDITORMATCHINGSTRATEGY_H_ #define BERRYIEDITORMATCHINGSTRATEGY_H_ #include #include "berryIEditorReference.h" #include "berryIEditorInput.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * An editor matching strategy allows editor extensions to provide their own * algorithm for matching the input of an open editor of that type to a * given editor input. This is used to find a matching editor during * {@link org.blueberry.ui.IWorkbenchPage#openEditor(IEditorInput, String, boolean)} and * {@link org.blueberry.ui.IWorkbenchPage#findEditor(IEditorInput)}. - * - * @since 3.1 */ -struct BERRY_UI_QT IEditorMatchingStrategy : public Object { +struct BERRY_UI_QT IEditorMatchingStrategy : public Object +{ - berryInterfaceMacro(IEditorMatchingStrategy, berry); + berryObjectMacro(berry::IEditorMatchingStrategy) ~IEditorMatchingStrategy(); /** * Returns whether the editor represented by the given editor reference * matches the given editor input. *

* Implementations should inspect the given editor input first, * and try to reject it early before calling IEditorReference.getEditorInput(), * since that method may be expensive. *

* * @param editorRef the editor reference to match against * @param input the editor input to match * @return true if the editor matches the given editor input, * false if it does not match */ virtual bool Matches(IEditorReference::Pointer editorRef, IEditorInput::Pointer input) = 0; }; } -Q_DECLARE_INTERFACE(berry::IEditorMatchingStrategy, "org.blueberry.IEditorMatchingStrategy") +Q_DECLARE_INTERFACE(berry::IEditorMatchingStrategy, "org.blueberry.ui.IEditorMatchingStrategy") #endif /*BERRYIEDITORMATCHINGSTRATEGY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorPart.h index c342f107ba..dab8c1b2f2 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorPart.h @@ -1,130 +1,131 @@ /*=================================================================== 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 BERRYIEDITORPART_H_ #define BERRYIEDITORPART_H_ #include "berryIWorkbenchPart.h" #include "berryISaveablePart.h" #include namespace berry { struct IEditorInput; struct IEditorSite; /** * \ingroup org_blueberry_ui_qt * * An editor is a visual component within a workbench page. It is * typically used to edit or browse a document or input object. The input * is identified using an IEditorInput. Modifications made * in an editor part follow an open-save-close lifecycle model (in contrast * to a view part, where modifications are saved to the workbench * immediately). *

* An editor is document or input-centric. Each editor has an input, and only * one editor can exist for each editor input within a page. This policy has * been designed to simplify part management. *

* An editor should be used in place of a view whenever more than one instance * of a document type can exist. *

* This interface may be implemented directly. For convenience, a base * implementation is defined in EditorPart. *

*

* An editor part is added to the workbench in two stages: *

    *
  1. An editor extension is contributed to the workbench registry. This * extension defines the extension id, extension class, and the file * extensions which are supported by the editor.
  2. *
  3. An editor part based upon the extension is created and added to the * workbench when the user opens a file with one of the supported file * extensions (or some other suitable form of editor input).
  4. *
*

*

* All editor parts implement the IAdaptable interface; extensions * are managed by the platform's adapter manager. *

* * @see org.blueberry.ui.IWorkbenchPage#openEditor(IEditorInput, String) * @see org.blueberry.ui.part.EditorPart */ struct BERRY_UI_QT IEditorPart : public virtual IWorkbenchPart, - public ISaveablePart { + public ISaveablePart +{ - berryInterfaceMacro(IEditorPart, berry); + berryObjectMacro(berry::IEditorPart) virtual ~IEditorPart(); /** * The property id for getEditorInput. */ //static const int PROP_INPUT = IWorkbenchPartConstants.PROP_INPUT; /** * Returns the input for this editor. If this value changes the part must * fire a property listener event with PROP_INPUT. * * @return the editor input */ virtual SmartPointer GetEditorInput() const = 0; /** * Returns the site for this editor. * This method is equivalent to (IEditorSite) getSite(). *

* The site can be null while the editor is being initialized. * After the initialization is complete, this value must be non-null * for the remainder of the editor's life cycle. *

* * @return the editor site; this value may be null if the editor * has not yet been initialized */ virtual SmartPointer GetEditorSite() const = 0; /** * Initializes this editor with the given editor site and input. *

* This method is automatically called shortly after the part is instantiated. * It marks the start of the part's lifecycle. The * {@link IWorkbenchPart#dispose IWorkbenchPart.dispose} method will be called * automically at the end of the lifecycle. Clients must not call this method. *

* Implementors of this method must examine the editor input object type to * determine if it is understood. If not, the implementor must throw * a PartInitException *

* @param site the editor site * @param input the editor input * @exception PartInitException if this editor was not initialized successfully */ virtual void Init(SmartPointer site, SmartPointer input) = 0; }; } -Q_DECLARE_INTERFACE(berry::IEditorPart, "org.blueberry.IEditorPart") +Q_DECLARE_INTERFACE(berry::IEditorPart, "org.blueberry.ui.IEditorPart") #endif /*BERRYIEDITORPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorReference.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorReference.h index 187fd007a3..c97014a035 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorReference.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorReference.h @@ -1,83 +1,83 @@ /*=================================================================== 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 BERRYIEDITORREFERENCE_H_ #define BERRYIEDITORREFERENCE_H_ #include "berryIWorkbenchPartReference.h" #include "berryIEditorPart.h" #include "berryIEditorInput.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * Implements a reference to a editor. * The IEditorPart will not be instanciated until * the editor becomes visible or the API getEditor * is sent with true; *

* This interface is not intended to be implemented by clients. *

*/ struct BERRY_UI_QT IEditorReference : public virtual IWorkbenchPartReference { - berryInterfaceMacro(IEditorReference, berry); + berryObjectMacro(berry::IEditorReference) ~IEditorReference(); /** * Returns the factory id of the factory used to * restore this editor. Returns null if the editor * is not persistable. */ virtual QString GetFactoryId() = 0; /** * Returns the editor input name. May return null is the * name is not available or if the editor failed to be * restored. */ virtual QString GetName() = 0; /** * Returns the editor referenced by this object. * Returns null if the editor was not instantiated or * it failed to be restored. Tries to restore the editor * if restore is true. */ virtual IEditorPart::Pointer GetEditor(bool restore) = 0; /** * Returns the editor input for the editor referenced by this object. *

* Unlike most of the other methods on this type, this method * can trigger plug-in activation. *

* * @return the editor input for the editor referenced by this object * @throws PartInitException if there was an error restoring the editor input * @since 3.1 */ virtual IEditorInput::Pointer GetEditorInput() = 0; }; } // namespace berry #endif /*BERRYIEDITORREFERENCE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorSite.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorSite.h index 190d17d805..a0ceea03f5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorSite.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorSite.h @@ -1,133 +1,133 @@ /*=================================================================== 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 BERRYIEDITORSITE_H_ #define BERRYIEDITORSITE_H_ #include "berryIWorkbenchPartSite.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * The primary interface between an editor part and the workbench. *

* The workbench exposes its implemention of editor part sites via this * interface, which is not intended to be implemented or extended by clients. *

* @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IEditorSite : public virtual IWorkbenchPartSite { - berryInterfaceMacro(IEditorSite, berry); + berryObjectMacro(berry::IEditorSite) virtual ~IEditorSite(); /** * Returns the action bar contributor for this editor. *

* An action contributor is responsable for the creation of actions. * By design, this contributor is used for one or more editors of the same type. * Thus, the contributor returned by this method is not owned completely * by the editor - it is shared. *

* * @return the editor action bar contributor, or null if none exists */ //virtual IEditorActionBarContributor getActionBarContributor(); /** * Returns the action bars for this part site. Editors of the same type (and * in the same window) share the same action bars. Contributions to the * action bars are done by the IEditorActionBarContributor. * * @return the action bars * @since 2.1 */ //virtual IActionBars getActionBars(); /** *

* Registers a pop-up menu with the default id for extension. The default id * is defined as the part id. *

*

* By default, context menus include object contributions based on the * editor input for the current editor. It is possible to override this * behaviour by calling this method with includeEditorInput * as false. This might be desirable for editors that * present a localized view of an editor input (e.g., a node in a model * editor). *

*

* For a detailed description of context menu registration see * {@link IWorkbenchPartSite#registerContextMenu(MenuManager, ISelectionProvider)} *

* * @param menuManager * the menu manager; must not be null. * @param selectionProvider * the selection provider; must not be null. * @param includeEditorInput * Whether the editor input should be included when adding object * contributions to this context menu. * @see IWorkbenchPartSite#registerContextMenu(MenuManager, * ISelectionProvider) * @since 3.1 */ // virtual void registerContextMenu(MenuManager menuManager, // ISelectionProvider selectionProvider, boolean includeEditorInput); /** *

* Registers a pop-up menu with a particular id for extension. This method * should only be called if the target part has more than one context menu * to register. *

*

* By default, context menus include object contributions based on the * editor input for the current editor. It is possible to override this * behaviour by calling this method with includeEditorInput * as false. This might be desirable for editors that * present a localized view of an editor input (e.g., a node in a model * editor). *

*

* For a detailed description of context menu registration see * {@link IWorkbenchPartSite#registerContextMenu(MenuManager, ISelectionProvider)} *

* * @param menuId * the menu id; must not be null. * @param menuManager * the menu manager; must not be null. * @param selectionProvider * the selection provider; must not be null. * @param includeEditorInput * Whether the editor input should be included when adding object * contributions to this context menu. * @see IWorkbenchPartSite#registerContextMenu(MenuManager, * ISelectionProvider) * @since 3.1 */ // virtual void registerContextMenu(String menuId, MenuManager menuManager, // ISelectionProvider selectionProvider, boolean includeEditorInput); }; } #endif /*BERRYIEDITORSITE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIFileEditorMapping.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIFileEditorMapping.h index e7676e2c48..450d12df2d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIFileEditorMapping.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIFileEditorMapping.h @@ -1,110 +1,111 @@ /*=================================================================== 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 BERRYIFILEEDITORMAPPING_H_ #define BERRYIFILEEDITORMAPPING_H_ #include #include "berryIEditorDescriptor.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * An association between a file name/extension and a list of known editors for * files of that type. *

* The name and extension can never empty or null. The name may contain * the single wild card character (*) to indicate the editor applies to * all files with the same extension (e.g. *.doc). The name can never * embed the wild card character within itself (i.e. rep*) *

*

* This interface is not intended to be implemented by clients. *

* * @see IEditorRegistry#getFileEditorMappings * @noimplement This interface is not intended to be implemented by clients. */ -struct BERRY_UI_QT IFileEditorMapping : public Object { +struct BERRY_UI_QT IFileEditorMapping : public Object +{ - berryInterfaceMacro(IFileEditorMapping, berry); + berryObjectMacro(berry::IFileEditorMapping) virtual ~IFileEditorMapping(); /** * Returns the default editor registered for this type mapping. * * @return the descriptor of the default editor, or null if there * is no default editor registered. Will also return null if * the default editor exists but fails the Expressions check. */ virtual IEditorDescriptor::Pointer GetDefaultEditor() = 0; /** * Returns the list of editors registered for this type mapping. * * @return a possibly empty list of editors. */ virtual QList GetEditors() const = 0; /** * Returns the list of editors formerly registered for this type mapping * which have since been deleted. * * @return a possibly empty list of editors */ virtual QList GetDeletedEditors() const = 0; /** * Returns the file's extension for this type mapping. * * @return the extension for this mapping */ virtual QString GetExtension() const = 0; /** * Returns the descriptor of the image to use for a file of this type. *

* The image is obtained from the default editor. A default file image is * returned if no default editor is available. *

* * @return the descriptor of the image to use for a resource of this type */ //virtual ImageDescriptor GetImageDescriptor() = 0; /** * Returns the label to use for this mapping. * Labels have the form "name.extension". * * @return the label to use for this mapping */ virtual QString GetLabel() const = 0; /** * Returns the file's name for this type mapping. * * @return the name for this mapping */ virtual QString GetName() const = 0; }; } #endif /*BERRYIFILEEDITORMAPPING_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIFolderLayout.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIFolderLayout.h index 565ae8e4bd..4aac14907f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIFolderLayout.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIFolderLayout.h @@ -1,56 +1,57 @@ /*=================================================================== 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 BERRYIFOLDERLAYOUT_H_ #define BERRYIFOLDERLAYOUT_H_ #include "berryIPlaceholderFolderLayout.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * An IFolderLayout is used to define the initial views within a folder. * The folder itself is contained within an IPageLayout. *

* This interface is not intended to be implemented by clients. *

* * @see IPageLayout#createFolder * @noimplement This interface is not intended to be implemented by clients. */ -struct BERRY_UI_QT IFolderLayout : public IPlaceholderFolderLayout { +struct BERRY_UI_QT IFolderLayout : public IPlaceholderFolderLayout +{ - berryInterfaceMacro(IFolderLayout, berry); + berryObjectMacro(berry::IFolderLayout) ~IFolderLayout(); /** * Adds a view with the given compound id to this folder. * See the {@link IPageLayout} type documentation for more details about compound ids. * The primary id must name a view contributed to the workbench's view extension point * (named "org.blueberry.ui.views"). * * @param viewId the view id */ virtual void AddView(const QString& viewId) = 0; }; } #endif /*BERRYIFOLDERLAYOUT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIMemento.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIMemento.h index f1caa839f5..fad592d2eb 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIMemento.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIMemento.h @@ -1,250 +1,250 @@ /*=================================================================== 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 BERRYIMEMENTO_H_ #define BERRYIMEMENTO_H_ #include #include #include #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * Interface to a memento used for saving the important state of an object * in a form that can be persisted in the file system. *

* Mementos were designed with the following requirements in mind: *

    *
  1. Certain objects need to be saved and restored across platform sessions. *
  2. *
  3. When an object is restored, an appropriate class for an object might not * be available. It must be possible to skip an object in this case.
  4. *
  5. When an object is restored, the appropriate class for the object may be * different from the one when the object was originally saved. If so, the * new class should still be able to read the old form of the data.
  6. *
*

*

* Mementos meet these requirements by providing support for storing a * mapping of arbitrary string keys to primitive values, and by allowing * mementos to have other mementos as children (arranged into a tree). * A robust external storage format based on XML is used. *

* The key for an attribute may be any alpha numeric value. However, the * value of TAG_ID is reserved for internal use. *

* This interface is not intended to be implemented or extended by clients. *

* * @see IPersistableElement * @see IElementFactory * @noimplement This interface is not intended to be implemented by clients. * **/ struct BERRY_UI_QT IMemento: public Object { -berryInterfaceMacro(IMemento, berry); + berryObjectMacro(berry::IMemento) /** * Special reserved key used to store the memento id * (value "IMemento.internal.id"). * * @see #getID() */ static const QString TAG_ID; // = "IMemento.internal.id"; /** * Creates a new child of this memento with the given type. *

* The GetChild and GetChildren methods * are used to retrieve children of a given type. *

* * @param type the type * @return a new child memento * @see #GetChild * @see #GetChildren */ virtual IMemento::Pointer CreateChild(const QString& type) = 0; /** * Creates a new child of this memento with the given type and id. * The id is stored in the child memento (using a special reserved * key, TAG_ID) and can be retrieved using GetID. *

* The GetChild and GetChildren methods * are used to retrieve children of a given type. *

* * @param type the type * @param id the child id * @return a new child memento with the given type and id * @see #GetID */ virtual IMemento::Pointer CreateChild(const QString& type, const QString& id) = 0; /** * Returns the first child with the given type id. * * @param type the type id * @return the first child with the given type */ virtual IMemento::Pointer GetChild(const QString& type) const = 0; /** * Returns all children with the given type id. * * @param type the type id * @return an array of children with the given type */ virtual QList GetChildren(const QString& type) const = 0; /** * Gets the floating point value of the given key. * * @param key the key * @param value the value of the given key * @return false if the key was not found or was found * but was not a floating point number, else true */ virtual bool GetFloat(const QString& key, double& value) const = 0; /** * Gets the integer value of the given key. * * @param key the key * @param value the value of the given key * @return false if the key was not found or was found * but was not an integer, else true */ virtual bool GetInteger(const QString& key, int& value) const = 0; /** * Gets the string value of the given key. * * @param key the key * @param value the value of the given key * @return false if the key was not found, else true */ virtual bool GetString(const QString& key, QString& value) const = 0; /** * Gets the boolean value of the given key. * * @param key the key * @param value the value of the given key * @return false if the key was not found, else true */ virtual bool GetBoolean(const QString& key, bool& value) const = 0; /** * Returns the data of the Text node of the memento. Each memento is allowed * only one Text node. * * @return the data of the Text node of the memento, or null * if the memento has no Text node. */ virtual QString GetTextData() const = 0; /** * Returns an array of all the attribute keys of the memento. This will not * be null. If there are no keys, an array of length zero will * be returned. * @return an array with all the attribute keys of the memento */ virtual QList GetAttributeKeys() const = 0; /** * Returns the type for this memento. * * @return the memento type * @see #CreateChild(const QString&) * @see #CreateChild(const QString&, const QString&) */ virtual QString GetType() const = 0; /** * Returns the id for this memento. * * @return the memento id, or "" if none * @see #CreateChild(const QString&, const QString&) */ virtual QString GetID() const = 0; /** * Sets the value of the given key to the given floating point number. * * @param key the key * @param value the value */ virtual void PutFloat(const QString& key, double value) = 0; /** * Sets the value of the given key to the given integer. * * @param key the key * @param value the value */ virtual void PutInteger(const QString& key, int value) = 0; /** * Copy the attributes and children from memento * to the receiver. * * @param memento the IMemento to be copied. */ virtual void PutMemento(IMemento::Pointer memento) = 0; /** * Sets the value of the given key to the given const QString&. * * @param key the key * @param value the value */ virtual void PutString(const QString& key, const QString& value) = 0; /** * Sets the value of the given key to the given boolean value. * * @param key the key * @param value the value */ virtual void PutBoolean(const QString& key, bool value) = 0; /** * Sets the memento's Text node to contain the given data. Creates the Text node if * none exists. If a Text node does exist, it's current contents are replaced. * Each memento is allowed only one text node. * * @param data the data to be placed on the Text node */ virtual void PutTextData(const QString& data) = 0; virtual ~IMemento(); }; } // namespace berry #endif /*BERRYIMEMENTO_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryINullSelectionListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryINullSelectionListener.h index c967d18a22..3eb43cc838 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryINullSelectionListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryINullSelectionListener.h @@ -1,101 +1,103 @@ /*=================================================================== 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 BERRYINULLSELECTIONLISTENER_H_ #define BERRYINULLSELECTIONLISTENER_H_ #include "berryISelectionListener.h" namespace berry { /** * Interface for listening to null selection changes. *

* This interface should be implemented by selection listeners * that want to be notified when the selection becomes null. * It has no methods. It simply indicates the desire to receive * null selection events through the existing * SelectionChanged() method. Either the part or the * selection may be null. *

* * @see ISelectionListener#SelectionChanged() * @see IActionDelegate#SelectionChanged() * @see ISelectionListener * */ -struct BERRY_UI_QT INullSelectionListener : public ISelectionListener { - berryInterfaceMacro(INullSelectionListener, berry) +struct BERRY_UI_QT INullSelectionListener : public ISelectionListener +{ + berryObjectMacro(berry::INullSelectionListener) ~INullSelectionListener(); }; /** * \ingroup org_blueberry_ui_qt * * This template can be used like this: * * * class MyClass { * * private: * void HandleSelectionChanged(berry::IWorkbenchPart::Pointer part, berry::ISelection::ConstPointer selection) * { // do something } * * berry::INullSelectionListener::Pointer m_SelectionListener; * * public: * MyClass() * : m_SelectionListener(new berry::NullSelectionChangedAdapter(this, &MyClass::HandleSelectionChanged)) * { * // get the selection service * // ... * service->AddPostSelectionListener(m_SelectionListener); * } * }; * */ template struct NullSelectionChangedAdapter: public INullSelectionListener { typedef R Listener; typedef void - (R::*Callback)(IWorkbenchPart::Pointer, ISelection::ConstPointer); + (R::*Callback)(const IWorkbenchPart::Pointer&, const ISelection::ConstPointer&); NullSelectionChangedAdapter(R* l, Callback c) : listener(l), callback(c) { poco_assert(listener); poco_assert(callback); } - void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) + void SelectionChanged(const IWorkbenchPart::Pointer& part, + const ISelection::ConstPointer& selection) { (listener->*callback)(part, selection); } private: Listener* listener; Callback callback; }; } #endif /* BERRYINULLSELECTIONLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPageLayout.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPageLayout.h index bec1dfe34b..2b41762ff0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPageLayout.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPageLayout.h @@ -1,502 +1,502 @@ /*=================================================================== 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 BERRYIPAGELAYOUT_H_ #define BERRYIPAGELAYOUT_H_ #include "berryIFolderLayout.h" #include "berryIPlaceholderFolderLayout.h" #include "berryIViewLayout.h" #include "berryIPerspectiveDescriptor.h" #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * A page layout defines the initial layout for a perspective within a page * in a workbench window. *

* This interface is not intended to be implemented by clients. *

*

* When a perspective is opened, it creates a new page layout with a single editor area. * This layout is then passed to the perspective factory (implementation of * {@link org.blueberry.ui.IPerspectiveFactory#createInitialLayout(IPageLayout)}) where * additional views and other content can be added, using the existing editor area as * the initial point of reference. *

*

* In some cases, multiple instances of a particular view may need to be added * to the same layout. These are disambiguated using a secondary id. * In layout methods taking a view id, the id can have the compound form: * primaryId [':' secondaryId]. * If a secondary id is given, the view must allow multiple instances by * having specified allowMultiple="true" in its extension. * View placeholders may also have a secondary id. *

*

* Wildcards are permitted in placeholder ids (but not regular view ids). * '*' matches any substring, '?' matches any single character. * Wildcards can be specified for the primary id, the secondary id, or both. * For example, the placeholder "someView:*" will match any occurrence of the view * that has primary id "someView" and that also has some non-null secondary id. * Note that this placeholder will not match the view if it has no secondary id, * since the compound id in this case is simply "someView". *

*

* Example of populating a layout with standard workbench views: *

  * IPageLayout layout = ...
  * // Get the editor area.
  * String editorArea = layout.getEditorArea();
  *
  * // Top left: Resource Navigator view and Bookmarks view placeholder
  * IFolderLayout topLeft = layout.createFolder("topLeft", IPageLayout.LEFT, 0.25f,
  *    editorArea);
  * topLeft.addView(IPageLayout.ID_RES_NAV);
  * topLeft.addPlaceholder(IPageLayout.ID_BOOKMARKS);
  *
  * // Bottom left: Outline view and Property Sheet view
  * IFolderLayout bottomLeft = layout.createFolder("bottomLeft", IPageLayout.BOTTOM, 0.50f,
  *     "topLeft");
  * bottomLeft.addView(IPageLayout.ID_OUTLINE);
  * bottomLeft.addView(IPageLayout.ID_PROP_SHEET);
  *
  * // Bottom right: Task List view
  * layout.addView(IPageLayout.ID_TASK_LIST, IPageLayout.BOTTOM, 0.66f, editorArea);
  * 
*

* @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IPageLayout : public Object { - berryInterfaceMacro(IPageLayout, berry) + berryObjectMacro(berry::IPageLayout) /** * The part id for the workbench's editor area. This may only be used * as a reference part for view addition. */ static const QString ID_EDITOR_AREA; // = "org.blueberry.ui.editors"; /** * The view id for the workbench's Resource Navigator standard component. */ static const QString ID_RES_NAV; // = "org.blueberry.ui.views.ResourceNavigator"; /** * The view id for the workbench's Property Sheet standard component. */ static const QString ID_PROP_SHEET; // = "org.blueberry.ui.views.PropertySheet"; /** * The view id for the workbench's Content Outline standard component. */ static const QString ID_OUTLINE; // = "org.blueberry.ui.views.ContentOutline"; /** * The view id for the workbench's Bookmark Navigator standard component. */ static const QString ID_BOOKMARKS; // = "org.blueberry.ui.views.BookmarkView"; /** * The view id for the workbench's Problems View standard component. * @since 3.0 */ static const QString ID_PROBLEM_VIEW; // = "org.blueberry.ui.views.ProblemView"; /** * The view id for the workbench's Progress View standard component. * @since 3.2 */ static const QString ID_PROGRESS_VIEW; // = "org.blueberry.ui.views.ProgressView"; /** * The view id for the workbench's Task List standard component. */ static const QString ID_TASK_LIST; // = "org.blueberry.ui.views.TaskList"; /** * Id of the navigate action set. * (value "org.blueberry.ui.NavigateActionSet") * @since 2.1 */ static const QString ID_NAVIGATE_ACTION_SET; // = "org.blueberry.ui.NavigateActionSet"; /** * Relationship constant indicating a part should be placed to the left of * its relative. */ static const int LEFT; // = 1; /** * Relationship constant indicating a part should be placed to the right of * its relative. */ static const int RIGHT; // = 2; /** * Relationship constant indicating a part should be placed above its * relative. */ static const int TOP; // = 3; /** * Relationship constant indicating a part should be placed below its * relative. */ static const int BOTTOM; // = 4; /** * Minimum acceptable ratio value when adding a view * @since 2.0 */ static const float RATIO_MIN; // = 0.05f; /** * Maximum acceptable ratio value when adding a view * @since 2.0 */ static const float RATIO_MAX; // = 0.95f; /** * The default view ratio width for regular (non-fast) views. * @since 2.0 */ static const float DEFAULT_VIEW_RATIO; // = 0.5f; /** * A variable used to represent invalid ratios. * @since 2.0 */ static const float INVALID_RATIO; // = -1f; /** * A variable used to represent a ratio which has not been specified. * @since 2.0 */ static const float NULL_RATIO; // = -2f; /** * Adds an action set with the given id to this page layout. * The id must name an action set contributed to the workbench's extension * point (named "org.blueberry.ui.actionSet"). * * @param actionSetId the action set id */ //virtual void AddActionSet(const QString& actionSetId) = 0; /** * Adds a perspective shortcut to the page layout. * These are typically shown in the UI to allow rapid navigation to appropriate new wizards. * For example, in the Eclipse IDE, these appear as items under the Window > Open Perspective menu. * The id must name a perspective extension contributed to the * workbench's perspectives extension point (named "org.blueberry.ui.perspectives"). * * @param id the perspective id */ virtual void AddPerspectiveShortcut(const QString& id) = 0; /** * Adds a view placeholder to this page layout. * A view placeholder is used to define the position of a view before the view * appears. Initially, it is invisible; however, if the user ever opens a view * whose compound id matches the placeholder, the view will appear at the same * location as the placeholder. * See the {@link IPageLayout} type documentation for more details about compound ids. * If the placeholder contains wildcards, it remains in the layout, otherwise * it is replaced by the view. * If the primary id of the placeholder has no wildcards, it must refer to a view * contributed to the workbench's view extension point * (named "org.blueberry.ui.views"). * * @param viewId the compound view id (wildcards allowed) * @param relationship the position relative to the reference part; * one of TOP, BOTTOM, LEFT, * or RIGHT * @param ratio a ratio specifying how to divide the space currently occupied by the reference part, * in the range 0.05f to 0.95f. * Values outside this range will be clipped to facilitate direct manipulation. * For a vertical split, the part on top gets the specified ratio of the current space * and the part on bottom gets the rest. * Likewise, for a horizontal split, the part at left gets the specified ratio of the current space * and the part at right gets the rest. * @param refId the id of the reference part; either a view id, a folder id, * or the special editor area id returned by getEditorArea */ virtual void AddPlaceholder(const QString& viewId, int relationship, float ratio, const QString& refId) = 0; /** * Adds an item to the Show In prompter. * The id must name a view contributed to the workbench's view extension point * (named "org.blueberry.ui.views"). * * @param id the view id * * @since 2.1 */ virtual void AddShowInPart(const QString& id) = 0; /** * Adds a show view shortcut to the page layout. * These are typically shown in the UI to allow rapid navigation to appropriate views. * For example, in the Eclipse IDE, these appear as items under the Window > Show View menu. * The id must name a view contributed to the workbench's views extension point * (named "org.blueberry.ui.views"). * * @param id the view id */ virtual void AddShowViewShortcut(const QString& id) = 0; /** * Adds a view with the given compound id to this page layout. * See the {@link IPageLayout} type documentation for more details about compound ids. * The primary id must name a view contributed to the workbench's view extension point * (named "org.blueberry.ui.views"). * * @param viewId the compound view id * @param relationship the position relative to the reference part; * one of TOP, BOTTOM, LEFT, * or RIGHT * @param ratio a ratio specifying how to divide the space currently occupied by the reference part, * in the range 0.05f to 0.95f. * Values outside this range will be clipped to facilitate direct manipulation. * For a vertical split, the part on top gets the specified ratio of the current space * and the part on bottom gets the rest. * Likewise, for a horizontal split, the part at left gets the specified ratio of the current space * and the part at right gets the rest. * @param refId the id of the reference part; either a view id, a folder id, * or the special editor area id returned by getEditorArea */ virtual void AddView(const QString& viewId, int relationship, float ratio, const QString& refId) = 0; /** * Creates and adds a new folder with the given id to this page layout. * The position and relative size of the folder is expressed relative to * a reference part. * * @param folderId the id for the new folder. This must be unique within * the layout to avoid collision with other parts. * @param relationship the position relative to the reference part; * one of TOP, BOTTOM, LEFT, * or RIGHT * @param ratio a ratio specifying how to divide the space currently occupied by the reference part, * in the range 0.05f to 0.95f. * Values outside this range will be clipped to facilitate direct manipulation. * For a vertical split, the part on top gets the specified ratio of the current space * and the part on bottom gets the rest. * Likewise, for a horizontal split, the part at left gets the specified ratio of the current space * and the part at right gets the rest. * @param refId the id of the reference part; either a view id, a folder id, * or the special editor area id returned by getEditorArea * @return the new folder */ virtual IFolderLayout::Pointer CreateFolder(const QString& folderId, int relationship, float ratio, const QString& refId) = 0; /** * Creates and adds a placeholder for a new folder with the given id to this page layout. * The position and relative size of the folder is expressed relative to * a reference part. * * @param folderId the id for the new folder. This must be unique within * the layout to avoid collision with other parts. * @param relationship the position relative to the reference part; * one of TOP, BOTTOM, LEFT, * or RIGHT * @param ratio a ratio specifying how to divide the space currently occupied by the reference part, * in the range 0.05f to 0.95f. * Values outside this range will be clipped to facilitate direct manipulation. * For a vertical split, the part on top gets the specified ratio of the current space * and the part on bottom gets the rest. * Likewise, for a horizontal split, the part at left gets the specified ratio of the current space * and the part at right gets the rest. * @param refId the id of the reference part; either a view id, a folder id, * or the special editor area id returned by getEditorArea * @return a placeholder for the new folder * @since 2.0 */ virtual IPlaceholderFolderLayout::Pointer CreatePlaceholderFolder(const QString& folderId, int relationship, float ratio, const QString& refId) = 0; /** * Returns the special identifier for the editor area in this page * layout. The identifier for the editor area is also stored in * ID_EDITOR_AREA. *

* The editor area is automatically added to each layout before anything else. * It should be used as the point of reference when adding views to a layout. *

* * @return the special id of the editor area */ virtual QString GetEditorArea() = 0; /** * Returns whether the page's layout will show * the editor area. * * @return true when editor area visible, false otherwise */ virtual bool IsEditorAreaVisible() = 0; /** * Show or hide the editor area for the page's layout. * * @param showEditorArea true to show the editor area, false to hide the editor area */ virtual void SetEditorAreaVisible(bool showEditorArea) = 0; /** * Sets whether this layout is fixed. * In a fixed layout, layout parts cannot be moved or zoomed, and the initial * set of views cannot be closed. * * @param isFixed true if this layout is fixed, false if not * @since 3.0 */ virtual void SetFixed(bool isFixed) = 0; /** * Returns true if this layout is fixed, false if not. * In a fixed layout, layout parts cannot be moved or zoomed, and the initial * set of views cannot be closed. * The default is false. * * @return true if this layout is fixed, false if not. * @since 3.0 */ virtual bool IsFixed() = 0; /** * Returns the layout for the view or placeholder with the given compound id in * this page layout. * See the {@link IPageLayout} type documentation for more details about compound ids. * Returns null if the specified view or placeholder is unknown to the layout. * * @param id the compound view id or placeholder * @return the view layout, or null * @since 3.0 */ virtual IViewLayout::Pointer GetViewLayout(const QString& id) = 0; /** * Adds a standalone view with the given compound id to this page layout. * See the {@link IPageLayout} type documentation for more details about compound ids. * A standalone view cannot be docked together with other views. * A standalone view's title can optionally be hidden. If hidden, * then any controls typically shown with the title (such as the close button) * are also hidden. Any contributions or other content from the view itself * are always shown (e.g. toolbar or view menu contributions, content description). *

* The id must name a view contributed to the workbench's view extension point * (named "org.blueberry.ui.views"). *

* * @param viewId the compound view id * @param showTitle true to show the title and related controls, * false to hide them * @param relationship the position relative to the reference part; * one of TOP, BOTTOM, LEFT, * or RIGHT * @param ratio a ratio specifying how to divide the space currently occupied by the reference part, * in the range 0.05f to 0.95f. * Values outside this range will be clipped to facilitate direct manipulation. * For a vertical split, the part on top gets the specified ratio of the current space * and the part on bottom gets the rest. * Likewise, for a horizontal split, the part at left gets the specified ratio of the current space * and the part at right gets the rest. * @param refId the id of the reference part; either a view id, a folder id, * or the special editor area id returned by getEditorArea * * @since 3.0 */ virtual void AddStandaloneView(const QString& viewId, bool showTitle, int relationship, float ratio, const QString& refId) = 0; /** * Adds a standalone view placeholder to this page layout. A view * placeholder is used to define the position of a view before the view * appears. Initially, it is invisible; however, if the user ever opens a * view whose compound id matches the placeholder, the view will appear at * the same location as the placeholder. See the {@link IPageLayout} type * documentation for more details about compound ids. If the placeholder * contains wildcards, it remains in the layout, otherwise it is replaced by * the view. If the primary id of the placeholder has no wildcards, it must * refer to a view contributed to the workbench's view extension point * (named "org.blueberry.ui.views"). * * @param viewId * the compound view id (wildcards allowed) * @param relationship * the position relative to the reference part; one of * TOP, BOTTOM, LEFT, * or RIGHT * @param ratio * a ratio specifying how to divide the space currently occupied * by the reference part, in the range 0.05f to * 0.95f. Values outside this range will be * clipped to facilitate direct manipulation. For a vertical * split, the part on top gets the specified ratio of the current * space and the part on bottom gets the rest. Likewise, for a * horizontal split, the part at left gets the specified ratio of * the current space and the part at right gets the rest. * @param refId * the id of the reference part; either a view id, a folder id, * or the special editor area id returned by * getEditorArea * @param showTitle * true to show the view's title, false if not * * @since 3.2 */ virtual void AddStandaloneViewPlaceholder(const QString& viewId, int relationship, float ratio, const QString& refId, bool showTitle) = 0; /** * Returns the perspective descriptor for the perspective being layed out. * * @return the perspective descriptor for the perspective being layed out * @since 3.2 */ virtual IPerspectiveDescriptor::Pointer GetDescriptor() = 0; /** * Returns the folder layout for the view or placeholder with the given * compound id in this page layout. See the {@link IPageLayout} type * documentation for more details about compound ids. Returns * null if the specified view or placeholder is unknown to * the layout, or the placeholder was not in a folder. * * @param id * the compound view id or placeholder. Must not be * null. * @return the folder layout, or null * @since 3.3 */ virtual IPlaceholderFolderLayout::Pointer GetFolderForView(const QString& id) = 0; }; } #endif /*BERRYIPAGELAYOUT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPageService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPageService.h index 2673554a3b..e0dc1c7fca 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPageService.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPageService.h @@ -1,108 +1,110 @@ /*=================================================================== 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 BERRYIPAGESERVICE_H_ #define BERRYIPAGESERVICE_H_ #include #include "berryIPerspectiveListener.h" namespace berry { struct IWorkbenchPage; /** * A page service tracks the page and perspective lifecycle events * within a workbench window. *

* This service can be acquired from your service locator: *

  *  IPageService service = (IPageService) getSite().getService(IPageService.class);
  * 
*
    *
  • This service is not available globally, only from the workbench window level down.
  • *
*

* * @see IWorkbenchWindow * @see IPageListener * @see IPerspectiveListener * @see org.blueberry.ui.services.IServiceLocator#getService(Class) * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IPageService { virtual ~IPageService(); /** * Adds the given listener for page lifecycle events. * Has no effect if an identical listener is already registered. *

* Note: listeners should be removed when no longer necessary. If * not, they will be removed when the IServiceLocator used to acquire this * service is disposed. *

* * @param listener a page listener * @see #removePageListener(IPageListener) */ //virtual void AddPageListener(IPageListener listener); /** * Adds the given listener for a page's perspective lifecycle events. * Has no effect if an identical listener is already registered. *

* Note: listeners should be removed when no longer necessary. If * not, they will be removed when the IServiceLocator used to acquire this * service is disposed. *

* * @param listener a perspective listener * @see #removePerspectiveListener(IPerspectiveListener) */ - virtual void AddPerspectiveListener(IPerspectiveListener::Pointer listener) = 0; + virtual void AddPerspectiveListener(IPerspectiveListener* listener) = 0; /** * Returns the active page. * * @return the active page, or null if no page is currently active */ - virtual SmartPointer GetActivePage() = 0; + virtual SmartPointer GetActivePage() const = 0; /** * Removes the given page listener. * Has no affect if an identical listener is not registered. * * @param listener a page listener */ //virtual void RemovePageListener(IPageListener listener); /** * Removes the given page's perspective listener. * Has no affect if an identical listener is not registered. * * @param listener a perspective listener */ - virtual void RemovePerspectiveListener(IPerspectiveListener::Pointer listener) = 0; + virtual void RemovePerspectiveListener(IPerspectiveListener* listener) = 0; virtual IPerspectiveListener::Events& GetPerspectiveEvents() = 0; }; } +Q_DECLARE_INTERFACE(berry::IPageService, "org.blueberry.ui.IPageService") + #endif /* BERRYIPAGESERVICE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPartListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPartListener.cpp index 1cf1d7a88b..f14b561856 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPartListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPartListener.cpp @@ -1,63 +1,67 @@ /*=================================================================== 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 "berryIPartListener.h" namespace berry { void IPartListener::Events -::AddListener(IPartListener::Pointer l) +::AddListener(IPartListener* l) { - if (l.IsNull()) return; + if (l == NULL) return; Types t = l->GetPartEventTypes(); if (t & ACTIVATED) - partActivated += Delegate(l.GetPointer(), &IPartListener::PartActivated); + partActivated += Delegate(l, &IPartListener::PartActivated); if (t & BROUGHT_TO_TOP) - partBroughtToTop += Delegate(l.GetPointer(), &IPartListener::PartBroughtToTop); + partBroughtToTop += Delegate(l, &IPartListener::PartBroughtToTop); if (t & CLOSED) - partClosed += Delegate(l.GetPointer(), &IPartListener::PartClosed); + partClosed += Delegate(l, &IPartListener::PartClosed); if (t & DEACTIVATED) - partDeactivated += Delegate(l.GetPointer(), &IPartListener::PartDeactivated); + partDeactivated += Delegate(l, &IPartListener::PartDeactivated); if (t & OPENED) - partOpened += Delegate(l.GetPointer(), &IPartListener::PartOpened); + partOpened += Delegate(l, &IPartListener::PartOpened); if (t & HIDDEN) - partHidden += Delegate(l.GetPointer(), &IPartListener::PartHidden); + partHidden += Delegate(l, &IPartListener::PartHidden); if (t & VISIBLE) - partVisible += Delegate(l.GetPointer(), &IPartListener::PartVisible); + partVisible += Delegate(l, &IPartListener::PartVisible); if (t & INPUT_CHANGED) - partInputChanged += Delegate(l.GetPointer(), &IPartListener::PartInputChanged); + partInputChanged += Delegate(l, &IPartListener::PartInputChanged); } void IPartListener::Events -::RemoveListener(IPartListener::Pointer l) +::RemoveListener(IPartListener* l) +{ + if (l == NULL) return; + + partActivated -= Delegate(l, &IPartListener::PartActivated); + partBroughtToTop -= Delegate(l, &IPartListener::PartBroughtToTop); + partClosed -= Delegate(l, &IPartListener::PartClosed); + partDeactivated -= Delegate(l, &IPartListener::PartDeactivated); + partOpened -= Delegate(l, &IPartListener::PartOpened); + partHidden -= Delegate(l, &IPartListener::PartHidden); + partVisible -= Delegate(l, &IPartListener::PartVisible); + partInputChanged -= Delegate(l, &IPartListener::PartInputChanged); +} + +IPartListener::~IPartListener() { - if (l.IsNull()) return; - - partActivated -= Delegate(l.GetPointer(), &IPartListener::PartActivated); - partBroughtToTop -= Delegate(l.GetPointer(), &IPartListener::PartBroughtToTop); - partClosed -= Delegate(l.GetPointer(), &IPartListener::PartClosed); - partDeactivated -= Delegate(l.GetPointer(), &IPartListener::PartDeactivated); - partOpened -= Delegate(l.GetPointer(), &IPartListener::PartOpened); - partHidden -= Delegate(l.GetPointer(), &IPartListener::PartHidden); - partVisible -= Delegate(l.GetPointer(), &IPartListener::PartVisible); - partInputChanged -= Delegate(l.GetPointer(), &IPartListener::PartInputChanged); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPartListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPartListener.h index a6277af4e1..0cce3bc3e1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPartListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPartListener.h @@ -1,163 +1,164 @@ /*=================================================================== 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 BERRYIPARTLISTENER_H_ #define BERRYIPARTLISTENER_H_ #include #include #include #include "berryIWorkbenchPartReference.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * Interface for listening to part lifecycle events. *

* This interface may be implemented by clients. *

* * @see IPartService#AddPartListener(IPartListener) */ -struct BERRY_UI_QT IPartListener : public virtual Object { - - berryInterfaceMacro(IPartListener, berry); +struct BERRY_UI_QT IPartListener +{ struct Events { enum Type { NONE = 0x00000000, ACTIVATED = 0x00000001, BROUGHT_TO_TOP = 0x00000002, CLOSED = 0x00000004, DEACTIVATED = 0x00000008, OPENED = 0x00000010, HIDDEN = 0x00000020, VISIBLE = 0x00000040, INPUT_CHANGED = 0x00000080, ALL = 0xffffffff }; - BERRY_DECLARE_FLAGS(Types, Type) + Q_DECLARE_FLAGS(Types, Type) - typedef Message1 PartEvent; + typedef Message1 PartEvent; PartEvent partActivated; PartEvent partBroughtToTop; PartEvent partClosed; PartEvent partDeactivated; PartEvent partOpened; PartEvent partHidden; PartEvent partVisible; PartEvent partInputChanged; - void AddListener(IPartListener::Pointer listener); - void RemoveListener(IPartListener::Pointer listener); + void AddListener(IPartListener* listener); + void RemoveListener(IPartListener* listener); private: - typedef MessageDelegate1 Delegate; + typedef MessageDelegate1 Delegate; }; + virtual ~IPartListener(); + virtual Events::Types GetPartEventTypes() const = 0; - /** - * Notifies this listener that the given part has been activated. - * - * @param partRef the part that was activated - * @see IWorkbenchPage#activate - */ - virtual void PartActivated(IWorkbenchPartReference::Pointer /*partRef*/) {}; - - /** - * Notifies this listener that the given part has been brought to the top. - *

- * These events occur when an editor is brought to the top in the editor area, - * or when a view is brought to the top in a page book with multiple views. - * They are normally only sent when a part is brought to the top - * programmatically (via IPerspective.bringToTop). When a part is - * activated by the user clicking on it, only partActivated is sent. - *

- * - * @param partRef the part that was surfaced - * @see IWorkbenchPage#bringToTop - */ - virtual void PartBroughtToTop(IWorkbenchPartReference::Pointer /*partRef*/) {}; - - /** - * Notifies this listener that the given part has been closed. - *

- * Note that if other perspectives in the same page share the view, - * this notification is not sent. It is only sent when the view - * is being removed from the page entirely (it is being disposed). - *

- * - * @param partRef the part that was closed - * @see IWorkbenchPage#hideView - */ - virtual void PartClosed(IWorkbenchPartReference::Pointer /*partRef*/) {}; - - /** - * Notifies this listener that the given part has been deactivated. - * - * @param partRef the part that was deactivated - * @see IWorkbenchPage#activate - */ - virtual void PartDeactivated(IWorkbenchPartReference::Pointer /*partRef*/) {}; - - /** - * Notifies this listener that the given part has been opened. - *

- * Note that if other perspectives in the same page share the view, - * this notification is not sent. It is only sent when the view - * is being newly opened in the page (it is being created). - *

- * - * @param partRef the part that was opened - * @see IWorkbenchPage#showView - */ - virtual void PartOpened(IWorkbenchPartReference::Pointer /*partRef*/) {}; - - /** - * Notifies this listener that the given part is hidden or obscured by another part. - * - * @param partRef the part that is hidden or obscured by another part - */ - virtual void PartHidden(IWorkbenchPartReference::Pointer /*partRef*/) {}; - - /** - * Notifies this listener that the given part is visible. - * - * @param partRef the part that is visible - */ - virtual void PartVisible(IWorkbenchPartReference::Pointer /*partRef*/) {}; - - /** - * Notifies this listener that the given part's input was changed. - * - * @param partRef the part whose input was changed - */ - virtual void PartInputChanged(IWorkbenchPartReference::Pointer /*partRef*/) {}; + /** + * Notifies this listener that the given part has been activated. + * + * @param partRef the part that was activated + * @see IWorkbenchPage#activate + */ + virtual void PartActivated(const IWorkbenchPartReference::Pointer& /*partRef*/) {} + + /** + * Notifies this listener that the given part has been brought to the top. + *

+ * These events occur when an editor is brought to the top in the editor area, + * or when a view is brought to the top in a page book with multiple views. + * They are normally only sent when a part is brought to the top + * programmatically (via IPerspective.bringToTop). When a part is + * activated by the user clicking on it, only partActivated is sent. + *

+ * + * @param partRef the part that was surfaced + * @see IWorkbenchPage#bringToTop + */ + virtual void PartBroughtToTop(const IWorkbenchPartReference::Pointer& /*partRef*/) {} + + /** + * Notifies this listener that the given part has been closed. + *

+ * Note that if other perspectives in the same page share the view, + * this notification is not sent. It is only sent when the view + * is being removed from the page entirely (it is being disposed). + *

+ * + * @param partRef the part that was closed + * @see IWorkbenchPage#hideView + */ + virtual void PartClosed(const IWorkbenchPartReference::Pointer& /*partRef*/) {} + + /** + * Notifies this listener that the given part has been deactivated. + * + * @param partRef the part that was deactivated + * @see IWorkbenchPage#activate + */ + virtual void PartDeactivated(const IWorkbenchPartReference::Pointer& /*partRef*/) {} + + /** + * Notifies this listener that the given part has been opened. + *

+ * Note that if other perspectives in the same page share the view, + * this notification is not sent. It is only sent when the view + * is being newly opened in the page (it is being created). + *

+ * + * @param partRef the part that was opened + * @see IWorkbenchPage#showView + */ + virtual void PartOpened(const IWorkbenchPartReference::Pointer& /*partRef*/) {} + + /** + * Notifies this listener that the given part is hidden or obscured by another part. + * + * @param partRef the part that is hidden or obscured by another part + */ + virtual void PartHidden(const IWorkbenchPartReference::Pointer& /*partRef*/) {} + + /** + * Notifies this listener that the given part is visible. + * + * @param partRef the part that is visible + */ + virtual void PartVisible(const IWorkbenchPartReference::Pointer& /*partRef*/) {} + + /** + * Notifies this listener that the given part's input was changed. + * + * @param partRef the part whose input was changed + */ + virtual void PartInputChanged(const IWorkbenchPartReference::Pointer& /*partRef*/) {} }; } // namespace berry -BERRY_DECLARE_OPERATORS_FOR_FLAGS(berry::IPartListener::Events::Types) +Q_DECLARE_OPERATORS_FOR_FLAGS(berry::IPartListener::Events::Types) #endif /*BERRYIPARTLISTENER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPartService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPartService.h index 91387b4c3c..22477ac5df 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPartService.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPartService.h @@ -1,84 +1,86 @@ /*=================================================================== 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 BERRYIPARTSERVICE_H_ #define BERRYIPARTSERVICE_H_ #include #include "berryIWorkbenchPart.h" #include "berryIWorkbenchPartReference.h" #include "berryIPartListener.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * A part service tracks the creation and activation of parts within a * workbench page. *

* This interface is not intended to be implemented by clients. *

* * @see IWorkbenchPage */ struct BERRY_UI_QT IPartService { virtual ~IPartService(); /** * Adds the given observer for part lifecycle events. * Has no effect if an identical listener is already registered. *

* Note: listeners should be removed when no longer necessary. If * not, they will be removed when the IServiceLocator used to acquire this * service is disposed. *

* * @param listener a part listener * @see #removePartListener(IPartListener) */ - virtual void AddPartListener(IPartListener::Pointer listener) = 0; + virtual void AddPartListener(IPartListener* listener) = 0; /** * Returns the active part. * * @return the active part, or null if no part is currently active */ virtual IWorkbenchPart::Pointer GetActivePart() = 0; /** * Returns the active part reference. * * @return the active part reference, or null if no part * is currently active */ virtual IWorkbenchPartReference::Pointer GetActivePartReference() = 0; /** * Removes the given part listener. * Has no affect if an identical listener is not registered. * * @param listener a part listener */ - virtual void RemovePartListener(IPartListener::Pointer listener) = 0; + virtual void RemovePartListener(IPartListener* listener) = 0; }; } // namespace berry +Q_DECLARE_INTERFACE(berry::IPartService, "org.blueberry.ui.IPartService") + #endif /*BERRYIPARTSERVICE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPathEditorInput.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPathEditorInput.h index 3ecea1d5ac..a806ef4170 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPathEditorInput.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPathEditorInput.h @@ -1,63 +1,63 @@ /*=================================================================== 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 BERRYIPATHEDITORINPUT_H_ #define BERRYIPATHEDITORINPUT_H_ #include "berryIEditorInput.h" #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * This interface defines an editor input based on the local file system path * of a file. *

* Clients implementing this editor input interface should override * Object.equals(Object) to answer true for two inputs * that are the same. The IWorkbenchPage.openEditor APIs * are dependent on this to find an editor with the same input. *

* Path-oriented editors should support this as a valid input type, and * can allow full read-write editing of its content. *

* All editor inputs must implement the IAdaptable interface; * extensions are managed by the platform's adapter manager. *

* * @see org.blueberry.core.runtime.IPath * @since 3.0 */ struct BERRY_UI_QT IPathEditorInput : public IEditorInput { - berryInterfaceMacro(IPathEditorInput, berry); + berryObjectMacro(berry::IPathEditorInput) virtual ~IPathEditorInput(); /** * Returns the local file system path of the file underlying this editor input. * * @return a local file system path */ virtual QString GetPath() const = 0; }; } #endif /*BERRYIPATHEDITORINPUT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h index a081aa0caf..ff6426a977 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h @@ -1,123 +1,124 @@ /*=================================================================== 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 BERRYIPERSPECTIVEDESCRIPTOR_H_ #define BERRYIPERSPECTIVEDESCRIPTOR_H_ #include #include #include #include "berryImageDescriptor.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * A perspective descriptor describes a perspective in an * IPerspectiveRegistry. *

* A perspective is a template for view visibility, layout, and action visibility * within a workbench page. There are two types of perspective: a predefined * perspective and a custom perspective. *

    *
  • A predefined perspective is defined by an extension to the workbench's * perspective extension point ("org.blueberry.ui.perspectives"). * The extension defines a id, label, and IPerspectiveFactory. * A perspective factory is used to define the initial layout for a page. *
  • *
  • A custom perspective is defined by the user. In this case a predefined * perspective is modified to suit a particular task and saved as a new * perspective. The attributes for the perspective are stored in a separate file * in the workbench's metadata directory. *
  • *
*

*

* Within a page the user can open any of the perspectives known * to the workbench's perspective registry, typically by selecting one from the * workbench's Open Perspective menu. When selected, the views * and actions within the active page rearrange to reflect the perspective. *

*

* This interface is not intended to be implemented by clients. *

* @see IPerspectiveRegistry * @noimplement This interface is not intended to be implemented by clients. */ -struct BERRY_UI_QT IPerspectiveDescriptor : public Object { +struct BERRY_UI_QT IPerspectiveDescriptor : public Object +{ - berryInterfaceMacro(IPerspectiveDescriptor, berry); + berryObjectMacro(berry::IPerspectiveDescriptor) virtual ~IPerspectiveDescriptor(); /** * Returns the description of this perspective. * This is the value of its "description" attribute. * * @return the description * @since 3.0 */ virtual QString GetDescription() const = 0; /** * Returns this perspective's id. For perspectives declared via an extension, * this is the value of its "id" attribute. * * @return the perspective id */ virtual QString GetId() const = 0; /** * Returns the descriptor of the image to show for this perspective. * If the extension for this perspective specifies an image, the descriptor * for it is returned. Otherwise a default image is returned. * * @return the descriptor of the image to show for this perspective */ virtual ImageDescriptor::Pointer GetImageDescriptor() const = 0; /** * Returns this perspective's label. For perspectives declared via an extension, * this is the value of its "label" attribute. * * @return the label */ virtual QString GetLabel() const = 0; /** * Returns true if this perspective is predefined by an * extension. * * @return boolean whether this perspective is predefined by an extension */ virtual bool IsPredefined() const = 0; /** * Return the category path of this descriptor * * @return the category path of this descriptor */ virtual std::vector GetCategoryPath() = 0; virtual std::vector< std::string> GetKeywordReferences() const = 0; }; } #endif /*BERRYIPERSPECTIVEDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveFactory.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveFactory.h index 0fee51d67a..2787f2a849 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveFactory.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveFactory.h @@ -1,111 +1,112 @@ /*=================================================================== 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 BERRYIPERSPECTIVEFACTORY_H_ #define BERRYIPERSPECTIVEFACTORY_H_ #include #include #include "berryIPageLayout.h" #include namespace berry { /** * A perspective factory generates the initial page layout and visible * action set for a page. *

* When a new page is created in the workbench a perspective is used to define * the initial page layout. If this is a predefined perspective (based on an extension to * the workbench's perspective extension point) an IPerspectiveFactory * is used to define the initial page layout. *

* The factory for the perspective is created and passed an IPageLayout * where views can be added. The default layout consists of the editor area with no * additional views. Additional views are added to the layout using * the editor area as the initial point of reference. The factory is used only briefly * while a new page is created; then discarded. *

* To define a perspective clients should implement this interface and * include the name of their class in an extension to the workbench's perspective * extension point (named "org.blueberry.ui.perspectives"). For example, * the plug-in's XML markup might contain: *

  * <extension point="org.blueberry.ui.perspectives">
  *   <perspective
  *       id="com.example.plugin.perspective"
  *       name="My Perspective"
  *       class="namespaze::MyPerspective">
  *   </perspective>
  * </extension>
  * 
*

* Example of populating a page with standard workbench views: *

  * public: void CreateInitialLayout(IPageLayout layout) {
  *    // Get the editor area.
  *    QString editorArea = layout->GetEditorArea();
  *
  *    // Top left: Resource Navigator view and Bookmarks view placeholder
  *    IFolderLayout::Pointer topLeft = layout->CreateFolder("topLeft", IPageLayout::LEFT, 0.25f,
  *      editorArea);
  *    topLeft->AddView(IPageLayout::ID_RES_NAV);
  *    topLeft->AddPlaceholder(IPageLayout::ID_BOOKMARKS);
  *
  *    // Bottom left: Outline view and Property Sheet view
  *    IFolderLayout::Pointer bottomLeft = layout->CreateFolder("bottomLeft", IPageLayout::BOTTOM, 0.50f,
  *      "topLeft");
  *    bottomLeft->AddView(IPageLayout::ID_OUTLINE);
  *    bottomLeft->AddView(IPageLayout::ID_PROP_SHEET);
  *
  *    // Bottom right: Task List view
  *    layout->AddView(IPageLayout::ID_TASK_LIST, IPageLayout::BOTTOM, 0.66f, editorArea);
  *  }
  * 
*

* Within the workbench a user may override the visible views, layout and * action sets of a predefined perspective to create a custom perspective. In such cases * the layout is persisted by the workbench and the factory is not used. *

*/ -struct BERRY_UI_QT IPerspectiveFactory : public Object { +struct BERRY_UI_QT IPerspectiveFactory : public Object +{ - berryInterfaceMacro(IPerspectiveFactory, berry); + berryObjectMacro(berry::IPerspectiveFactory) ~IPerspectiveFactory(); /** * Creates the initial layout for a page. *

* Implementors of this method may add additional views to a * perspective. The perspective already contains an editor folder * identified by the result of IPageLayout.getEditorArea(). * Additional views should be added to the layout using this value as * the initial point of reference. *

* * @param layout the page layout */ virtual void CreateInitialLayout(IPageLayout::Pointer layout) = 0; }; } -Q_DECLARE_INTERFACE(berry::IPerspectiveFactory, "org.blueberry.IPerspectiveFactory") +Q_DECLARE_INTERFACE(berry::IPerspectiveFactory, "org.blueberry.ui.IPerspectiveFactory") #endif /* BERRYIPERSPECTIVEFACTORY_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveListener.cpp index a9bc44362b..0e05fa426c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveListener.cpp @@ -1,99 +1,103 @@ /*=================================================================== 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 "berryIPerspectiveListener.h" #include "berryIWorkbenchPage.h" namespace berry { void IPerspectiveListener::Events -::AddListener(IPerspectiveListener::Pointer listener) +::AddListener(IPerspectiveListener* listener) { - if (listener.IsNull()) return; + if (listener == NULL) return; Types types = listener->GetPerspectiveEventTypes(); if (types & ACTIVATED) - this->perspectiveActivated += Delegate2(listener.GetPointer(), &IPerspectiveListener::PerspectiveActivated); + this->perspectiveActivated += Delegate2(listener, &IPerspectiveListener::PerspectiveActivated); if (types & CHANGED) - this->perspectiveChanged += PerspChangedDelegate(listener.GetPointer(), &IPerspectiveListener::PerspectiveChanged); + this->perspectiveChanged += PerspChangedDelegate(listener, &IPerspectiveListener::PerspectiveChanged); if (types & PART_CHANGED) - this->perspectivePartChanged += PerspPartChangedDelegate(listener.GetPointer(), &IPerspectiveListener::PerspectiveChanged); + this->perspectivePartChanged += PerspPartChangedDelegate(listener, &IPerspectiveListener::PerspectiveChanged); if (types & OPENED) - this->perspectiveOpened += Delegate2(listener.GetPointer(), &IPerspectiveListener::PerspectiveOpened); + this->perspectiveOpened += Delegate2(listener, &IPerspectiveListener::PerspectiveOpened); if (types & CLOSED) - this->perspectiveClosed += Delegate2(listener.GetPointer(), &IPerspectiveListener::PerspectiveClosed); + this->perspectiveClosed += Delegate2(listener, &IPerspectiveListener::PerspectiveClosed); if (types & DEACTIVATED) - this->perspectiveDeactivated += Delegate2(listener.GetPointer(), &IPerspectiveListener::PerspectiveDeactivated); + this->perspectiveDeactivated += Delegate2(listener, &IPerspectiveListener::PerspectiveDeactivated); if (types & SAVED_AS) - this->perspectiveSavedAs += PerspSavedAsDelegate(listener.GetPointer(), &IPerspectiveListener::PerspectiveSavedAs); + this->perspectiveSavedAs += PerspSavedAsDelegate(listener, &IPerspectiveListener::PerspectiveSavedAs); if (types & PRE_DEACTIVATE) - this->perspectivePreDeactivate += Delegate2(listener.GetPointer(), &IPerspectiveListener::PerspectivePreDeactivate); + this->perspectivePreDeactivate += Delegate2(listener, &IPerspectiveListener::PerspectivePreDeactivate); } void IPerspectiveListener::Events -::RemoveListener(IPerspectiveListener::Pointer listener) +::RemoveListener(IPerspectiveListener* listener) { - if (listener.IsNull()) return; - - this->perspectiveActivated -= Delegate2(listener.GetPointer(), &IPerspectiveListener::PerspectiveActivated); - this->perspectiveChanged -= PerspChangedDelegate(listener.GetPointer(), &IPerspectiveListener::PerspectiveChanged); - this->perspectivePartChanged -= PerspPartChangedDelegate(listener.GetPointer(), &IPerspectiveListener::PerspectiveChanged); - this->perspectiveOpened -= Delegate2(listener.GetPointer(), &IPerspectiveListener::PerspectiveOpened); - this->perspectiveClosed -= Delegate2(listener.GetPointer(), &IPerspectiveListener::PerspectiveClosed); - this->perspectiveDeactivated -= Delegate2(listener.GetPointer(), &IPerspectiveListener::PerspectiveDeactivated); - this->perspectiveSavedAs -= PerspSavedAsDelegate(listener.GetPointer(), &IPerspectiveListener::PerspectiveSavedAs); - this->perspectivePreDeactivate -= Delegate2(listener.GetPointer(), &IPerspectiveListener::PerspectivePreDeactivate); + if (listener == NULL) return; + + this->perspectiveActivated -= Delegate2(listener, &IPerspectiveListener::PerspectiveActivated); + this->perspectiveChanged -= PerspChangedDelegate(listener, &IPerspectiveListener::PerspectiveChanged); + this->perspectivePartChanged -= PerspPartChangedDelegate(listener, &IPerspectiveListener::PerspectiveChanged); + this->perspectiveOpened -= Delegate2(listener, &IPerspectiveListener::PerspectiveOpened); + this->perspectiveClosed -= Delegate2(listener, &IPerspectiveListener::PerspectiveClosed); + this->perspectiveDeactivated -= Delegate2(listener, &IPerspectiveListener::PerspectiveDeactivated); + this->perspectiveSavedAs -= PerspSavedAsDelegate(listener, &IPerspectiveListener::PerspectiveSavedAs); + this->perspectivePreDeactivate -= Delegate2(listener, &IPerspectiveListener::PerspectivePreDeactivate); } -void IPerspectiveListener::PerspectiveActivated(SmartPointer /*page*/, - IPerspectiveDescriptor::Pointer /*perspective*/) +IPerspectiveListener::~IPerspectiveListener() +{ +} + +void IPerspectiveListener::PerspectiveActivated(const SmartPointer& /*page*/, + const IPerspectiveDescriptor::Pointer& /*perspective*/) {} -void IPerspectiveListener::PerspectiveChanged(SmartPointer /*page*/, - IPerspectiveDescriptor::Pointer /*perspective*/, const QString& /*changeId*/) +void IPerspectiveListener::PerspectiveChanged(const SmartPointer& /*page*/, + const IPerspectiveDescriptor::Pointer& /*perspective*/, const QString& /*changeId*/) {} -void IPerspectiveListener::PerspectiveChanged(SmartPointer /*page*/, - IPerspectiveDescriptor::Pointer /*perspective*/, - IWorkbenchPartReference::Pointer /*partRef*/, const QString& /*changeId*/) +void IPerspectiveListener::PerspectiveChanged(const SmartPointer& /*page*/, + const IPerspectiveDescriptor::Pointer& /*perspective*/, + const IWorkbenchPartReference::Pointer& /*partRef*/, const QString& /*changeId*/) {} -void IPerspectiveListener::PerspectiveOpened(SmartPointer /*page*/, - IPerspectiveDescriptor::Pointer /*perspective*/) +void IPerspectiveListener::PerspectiveOpened(const SmartPointer& /*page*/, + const IPerspectiveDescriptor::Pointer& /*perspective*/) {} -void IPerspectiveListener::PerspectiveClosed(SmartPointer /*page*/, - IPerspectiveDescriptor::Pointer /*perspective*/) +void IPerspectiveListener::PerspectiveClosed(const SmartPointer& /*page*/, + const IPerspectiveDescriptor::Pointer& /*perspective*/) {} -void IPerspectiveListener::PerspectiveDeactivated(SmartPointer /*page*/, - IPerspectiveDescriptor::Pointer /*perspective*/) +void IPerspectiveListener::PerspectiveDeactivated(const SmartPointer& /*page*/, + const IPerspectiveDescriptor::Pointer& /*perspective*/) {} -void IPerspectiveListener::PerspectiveSavedAs(SmartPointer /*page*/, - IPerspectiveDescriptor::Pointer /*oldPerspective*/, - IPerspectiveDescriptor::Pointer /*newPerspective*/) +void IPerspectiveListener::PerspectiveSavedAs(const SmartPointer& /*page*/, + const IPerspectiveDescriptor::Pointer& /*oldPerspective*/, + const IPerspectiveDescriptor::Pointer& /*newPerspective*/) {}; -void IPerspectiveListener::PerspectivePreDeactivate(SmartPointer /*page*/, - IPerspectiveDescriptor::Pointer /*perspective*/) +void IPerspectiveListener::PerspectivePreDeactivate(const SmartPointer& /*page*/, + const IPerspectiveDescriptor::Pointer& /*perspective*/) {} } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveListener.h index 4ff3943131..cd4e79f300 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveListener.h @@ -1,200 +1,201 @@ /*=================================================================== 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 BERRYIPERSPECTIVELISTENER_H_ #define BERRYIPERSPECTIVELISTENER_H_ #include #include "berryIPerspectiveDescriptor.h" #include "berryIWorkbenchPartReference.h" #include namespace berry { struct IWorkbenchPage; /** * Interface for listening to perspective lifecycle events. *

* This interface may be implemented by clients. *

* * @see IPageService#addPerspectiveListener(IPerspectiveListener) * @see PerspectiveAdapter */ -struct BERRY_UI_QT IPerspectiveListener : public virtual Object { - - berryInterfaceMacro(IPerspectiveListener, berry); +struct BERRY_UI_QT IPerspectiveListener +{ struct Events { enum Type { NONE = 0x00000000, ACTIVATED = 0x00000001, CHANGED = 0x00000002, PART_CHANGED = 0x00000004, OPENED = 0x00000008, CLOSED = 0x00000010, DEACTIVATED = 0x00000020, SAVED_AS = 0x00000040, PRE_DEACTIVATE = 0x00000080, ALL = 0xffffffff }; - BERRY_DECLARE_FLAGS(Types, Type) + Q_DECLARE_FLAGS(Types, Type) - Message2, IPerspectiveDescriptor::Pointer> perspectiveActivated; - Message3, IPerspectiveDescriptor::Pointer, const QString&> perspectiveChanged; - Message4, IPerspectiveDescriptor::Pointer, IWorkbenchPartReference::Pointer, const QString&> perspectivePartChanged; - Message2, IPerspectiveDescriptor::Pointer> perspectiveOpened; - Message2, IPerspectiveDescriptor::Pointer> perspectiveClosed; - Message2, IPerspectiveDescriptor::Pointer> perspectiveDeactivated; - Message3, IPerspectiveDescriptor::Pointer, IPerspectiveDescriptor::Pointer> perspectiveSavedAs; - Message2, IPerspectiveDescriptor::Pointer> perspectivePreDeactivate; + Message2&, const IPerspectiveDescriptor::Pointer&> perspectiveActivated; + Message3&, const IPerspectiveDescriptor::Pointer&, const QString&> perspectiveChanged; + Message4&, const IPerspectiveDescriptor::Pointer&, const SmartPointer&, const QString&> perspectivePartChanged; + Message2&, const IPerspectiveDescriptor::Pointer&> perspectiveOpened; + Message2&, const IPerspectiveDescriptor::Pointer&> perspectiveClosed; + Message2&, const IPerspectiveDescriptor::Pointer&> perspectiveDeactivated; + Message3&, const IPerspectiveDescriptor::Pointer&, const IPerspectiveDescriptor::Pointer&> perspectiveSavedAs; + Message2&, const IPerspectiveDescriptor::Pointer&> perspectivePreDeactivate; - void AddListener(IPerspectiveListener::Pointer l); - void RemoveListener(IPerspectiveListener::Pointer l); + void AddListener(IPerspectiveListener* l); + void RemoveListener(IPerspectiveListener* l); private: - typedef MessageDelegate2, IPerspectiveDescriptor::Pointer > Delegate2; - typedef MessageDelegate3, IPerspectiveDescriptor::Pointer, const QString&> PerspChangedDelegate; - typedef MessageDelegate3, IPerspectiveDescriptor::Pointer, IPerspectiveDescriptor::Pointer> PerspSavedAsDelegate; - typedef MessageDelegate4, IPerspectiveDescriptor::Pointer, IWorkbenchPartReference::Pointer, const QString&> PerspPartChangedDelegate; + typedef MessageDelegate2&, const IPerspectiveDescriptor::Pointer& > Delegate2; + typedef MessageDelegate3&, const IPerspectiveDescriptor::Pointer&, const QString&> PerspChangedDelegate; + typedef MessageDelegate3&, const IPerspectiveDescriptor::Pointer&, const IPerspectiveDescriptor::Pointer&> PerspSavedAsDelegate; + typedef MessageDelegate4&, const IPerspectiveDescriptor::Pointer&, const SmartPointer&, const QString&> PerspPartChangedDelegate; }; + virtual ~IPerspectiveListener(); + virtual Events::Types GetPerspectiveEventTypes() const = 0; /** * Notifies this listener that a perspective in the given page * has been activated. * * @param page the page containing the activated perspective * @param perspective the perspective descriptor that was activated * @see IWorkbenchPage#setPerspective */ - virtual void PerspectiveActivated(SmartPointer page, - IPerspectiveDescriptor::Pointer perspective); + virtual void PerspectiveActivated(const SmartPointer& page, + const IPerspectiveDescriptor::Pointer& perspective); /** * Notifies this listener that a perspective has changed in some way * (for example, editor area hidden, perspective reset, * view show/hide, editor open/close, etc). * * @param page the page containing the affected perspective * @param perspective the perspective descriptor * @param changeId one of the CHANGE_* constants on IWorkbenchPage */ - virtual void PerspectiveChanged(SmartPointer page, - IPerspectiveDescriptor::Pointer perspective, const QString& changeId); + virtual void PerspectiveChanged(const SmartPointer& page, + const IPerspectiveDescriptor::Pointer& perspective, const QString& changeId); /** * Notifies this listener that a part in the given page's perspective * has changed in some way (for example, view show/hide, editor open/close, etc). * * @param page the workbench page containing the perspective * @param perspective the descriptor for the changed perspective * @param partRef the reference to the affected part * @param changeId one of the CHANGE_* constants on IWorkbenchPage */ - virtual void PerspectiveChanged(SmartPointer page, - IPerspectiveDescriptor::Pointer perspective, - IWorkbenchPartReference::Pointer partRef, const QString& changeId); + virtual void PerspectiveChanged(const SmartPointer& page, + const IPerspectiveDescriptor::Pointer& perspective, + const SmartPointer& partRef, const QString& changeId); /** * Notifies this listener that a perspective in the given page has been * opened. * * @param page * the page containing the opened perspective * @param perspective * the perspective descriptor that was opened * @see IWorkbenchPage#setPerspective(IPerspectiveDescriptor) */ - virtual void PerspectiveOpened(SmartPointer page, - IPerspectiveDescriptor::Pointer perspective); + virtual void PerspectiveOpened(const SmartPointer& page, + const IPerspectiveDescriptor::Pointer& perspective); /** * Notifies this listener that a perspective in the given page has been * closed. * * @param page * the page containing the closed perspective * @param perspective * the perspective descriptor that was closed * @see IWorkbenchPage#closePerspective(IPerspectiveDescriptor, boolean, boolean) * @see IWorkbenchPage#closeAllPerspectives(boolean, boolean) */ - virtual void PerspectiveClosed(SmartPointer page, - IPerspectiveDescriptor::Pointer perspective); + virtual void PerspectiveClosed(const SmartPointer& page, + const IPerspectiveDescriptor::Pointer& perspective); /** * Notifies this listener that a perspective in the given page has been * deactivated. * * @param page * the page containing the deactivated perspective * @param perspective * the perspective descriptor that was deactivated * @see IWorkbenchPage#setPerspective(IPerspectiveDescriptor) */ - virtual void PerspectiveDeactivated(SmartPointer page, - IPerspectiveDescriptor::Pointer perspective); + virtual void PerspectiveDeactivated(const SmartPointer& page, + const IPerspectiveDescriptor::Pointer& perspective); /** * Notifies this listener that a perspective in the given page has been * saved as a new perspective with a different perspective descriptor. * * @param page * the page containing the saved perspective * @param oldPerspective * the old perspective descriptor * @param newPerspective * the new perspective descriptor * @see IWorkbenchPage#savePerspectiveAs(IPerspectiveDescriptor) */ - virtual void PerspectiveSavedAs(SmartPointer page, - IPerspectiveDescriptor::Pointer oldPerspective, - IPerspectiveDescriptor::Pointer newPerspective); + virtual void PerspectiveSavedAs(const SmartPointer& page, + const IPerspectiveDescriptor::Pointer& oldPerspective, + const IPerspectiveDescriptor::Pointer& newPerspective); /** *

* Notifies this listener that a perspective in the given page is about to * be deactivated. *

*

* Note: This does not have the ability to veto a perspective deactivation. *

* * @param page * the page containing the deactivated perspective * @param perspective * the perspective descriptor that was deactivated * @see IWorkbenchPage#setPerspective(IPerspectiveDescriptor) */ - virtual void PerspectivePreDeactivate(SmartPointer page, - IPerspectiveDescriptor::Pointer perspective); + virtual void PerspectivePreDeactivate(const SmartPointer& page, + const IPerspectiveDescriptor::Pointer& perspective); }; } -BERRY_DECLARE_OPERATORS_FOR_FLAGS(berry::IPerspectiveListener::Events::Types) +Q_DECLARE_OPERATORS_FOR_FLAGS(berry::IPerspectiveListener::Events::Types) #endif /* BERRYIPERSPECTIVELISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPlaceholderFolderLayout.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPlaceholderFolderLayout.h index 074e361bc9..5f50b47576 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPlaceholderFolderLayout.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPlaceholderFolderLayout.h @@ -1,101 +1,101 @@ /*=================================================================== 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 BERRYIPLACEHOLDERFOLDERLAYOUT_H_ #define BERRYIPLACEHOLDERFOLDERLAYOUT_H_ #include #include #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * An IPlaceholderFolderLayout is used to define the initial * view placeholders within a folder. * The folder itself is contained within an IPageLayout. *

* This interface is not intended to be implemented by clients. *

* * @see IPageLayout#createPlaceholderFolder - * @since 2.0 * @noimplement This interface is not intended to be implemented by clients. */ -struct BERRY_UI_QT IPlaceholderFolderLayout : public Object { +struct BERRY_UI_QT IPlaceholderFolderLayout : public Object +{ - berryInterfaceMacro(IPlaceholderFolderLayout, berry); + berryObjectMacro(berry::IPlaceholderFolderLayout) virtual ~IPlaceholderFolderLayout(); /** * Adds a view placeholder to this folder. * A view placeholder is used to define the position of a view before the view * appears. Initially, it is invisible; however, if the user ever opens a view * whose compound id matches the placeholder, the view will appear at the same * location as the placeholder. * See the {@link IPageLayout} type documentation for more details about compound ids. * If the placeholder contains wildcards, it remains in the layout, otherwise * it is replaced by the view. * If the primary id of the placeholder has no wildcards, it must refer to a view * contributed to the workbench's view extension point * (named "org.blueberry.ui.views"). * * @param viewId the compound view id (wildcards allowed) */ virtual void AddPlaceholder(const QString& viewId) = 0; /** * Returns the property with the given id or null. Folder * properties are an extensible mechanism for perspective authors to * customize the appearance of view stacks. The list of customizable * properties is determined by the presentation factory. * * @param id * Must not be null. * @return property value, or null if the property is not * set. * @since 3.3 */ virtual QString GetProperty(const QString& id) = 0; /** * Sets the given property to the given value. Folder properties are an * extensible mechanism for perspective authors to customize the appearance * of view stacks. The list of customizable properties is determined by the * presentation factory. *

* These folder properties are intended to be set during * IPerspectiveFactory#createInitialLayout. Any subsequent * changes to property values after this method completes will not fire * change notifications and will not be reflected in the presentation. *

* * @param id * property id. Must not be null. * @param value * property value. null will clear the property. * @since 3.3 */ virtual void SetProperty(const QString& id, const QString& value) = 0; }; } #endif /*BERRYIPLACEHOLDERFOLDERLAYOUT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPluginContribution.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPluginContribution.h index 853e0a01c9..b5469a8f65 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPluginContribution.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPluginContribution.h @@ -1,52 +1,52 @@ /*=================================================================== 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 BERRYIPLUGINCONTRIBUTION_H #define BERRYIPLUGINCONTRIBUTION_H #include #include namespace berry { /** * An interface that descriptor classes may implement in addition to their * descriptor interface. This indicates that they may or may not originate from * a plugin contribution. This is useful in various activity filtering * scenarios. */ struct IPluginContribution : public virtual Object { - berryInterfaceMacro(IPluginContribution, berry) + berryObjectMacro(berry::IPluginContribution) /** * @return the local id of the contribution. Must not be null. * This should correspond to the extension-specific identifier for * a given contribution. */ virtual QString GetLocalId() const = 0; /** * @return the id of the originating plugin. Can be null if * this contribution did not originate from a plugin. */ virtual QString GetPluginId() const = 0; }; } #endif // BERRYIPLUGINCONTRIBUTION_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPostSelectionProvider.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPostSelectionProvider.h index 5236b9e84a..9d4ee4c826 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPostSelectionProvider.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPostSelectionProvider.h @@ -1,67 +1,66 @@ /*=================================================================== 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 BERRYIPOSTSELECTIONPROVIDER_H_ #define BERRYIPOSTSELECTIONPROVIDER_H_ #include "berryISelectionProvider.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * Selection provider extension interface to allow providers * to notify about post selection changed events. * A post selection changed event is equivalent to selection changed event * if the selection change was triggered by the mouse, but it has a delay * if the selection change is triggered by keyboard navigation. * * @see ISelectionProvider - * - * @since 3.0 */ -struct BERRY_UI_QT IPostSelectionProvider : public ISelectionProvider { +struct BERRY_UI_QT IPostSelectionProvider : public ISelectionProvider +{ - berryInterfaceMacro(IPostSelectionProvider, berry); + berryObjectMacro(berry::IPostSelectionProvider) ~IPostSelectionProvider(); /** * Adds a listener for post selection changes in this selection provider. * Has no effect if an identical listener is already registered. * * @param listener a selection changed listener */ virtual void AddPostSelectionChangedListener( - ISelectionChangedListener::Pointer listener) = 0; + ISelectionChangedListener* listener) = 0; /** * Removes the given listener for post selection changes from this selection * provider. * Has no affect if an identical listener is not registered. * * @param listener a selection changed listener */ virtual void RemovePostSelectionChangedListener( - ISelectionChangedListener::Pointer listener) = 0; + ISelectionChangedListener* listener) = 0; }; } #endif /*BERRYIPOSTSELECTIONPROVIDER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPreferencePage.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPreferencePage.h index 24fad6c834..f0e406aa23 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPreferencePage.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPreferencePage.h @@ -1,109 +1,109 @@ /*=================================================================== 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 BERRYIPREFERENCEPAGE_H_ #define BERRYIPREFERENCEPAGE_H_ #include "berryObject.h" #include "berryIPreferences.h" #include "berryIWorkbench.h" #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * Interface for workbench preference pages. *

* Clients should implement this interface and include the name of their class * in an extension contributed to the workbench's preference extension point * (named "org.blueberry.ui.preferencePages"). * For example, the plug-in's XML markup might contain: *

  * <extension point="org.blueberry.ui.preferencePages">
  *      <page id="com.example.myplugin.prefs"
  *         name="Knobs"
  *         class="ns::MyPreferencePage" />
  * </extension>
  * 
*

*/ struct BERRY_UI_QT IPreferencePage: virtual public Object { - berryInterfaceMacro(IPreferencePage, berry); + berryObjectMacro(berry::IPreferencePage) ~IPreferencePage(); /** * Initializes this preference page for the given workbench. *

* This method is called automatically as the preference page is being created * and initialized. Clients must not call this method. *

* * @param workbench the workbench */ virtual void Init(IWorkbench::Pointer workbench) = 0; /** * Creates the top level control for this preference * page under the given parent widget. *

* Implementors are responsible for ensuring that * the created control can be accessed via GetControl *

* * @param parent the parent widget */ virtual void CreateControl(void* parent) = 0; /** * Returns the top level control for this dialog page. *

* May return null if the control * has not been created yet. *

* * @return the top level control or null */ virtual void* GetControl() const = 0; /// /// Invoked when the OK button was clicked in the preferences dialog /// virtual bool PerformOk() = 0; /// /// Invoked when the Cancel button was clicked in the preferences dialog /// virtual void PerformCancel() = 0; /// /// Invoked when the user performed an import. As the values of the preferences may have changed /// you should read all values again from the preferences service. /// virtual void Update() = 0; }; } -Q_DECLARE_INTERFACE(berry::IPreferencePage, "org.blueberry.IPreferencePage") +Q_DECLARE_INTERFACE(berry::IPreferencePage, "org.blueberry.ui.IPreferencePage") #endif /*BERRYIPREFERENCEPAGE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIQtPreferencePage.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIQtPreferencePage.h index 838ac05e2d..9dfb9daa2f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIQtPreferencePage.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIQtPreferencePage.h @@ -1,57 +1,57 @@ /*=================================================================== 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 BERRYIQTPREFERENCEPAGE_H_ #define BERRYIQTPREFERENCEPAGE_H_ #ifdef __MINGW32__ // We need to include winbase.h here in order to declare // atomic intrinsics like InterlockedIncrement correctly. // Otherwhise, they would be declared wrong within qatomic_windows.h . #include #endif #include #include "berryIPreferencePage.h" #include namespace berry { /** * \ingroup org_blueberry_ui_qt * */ struct BERRY_UI_QT IQtPreferencePage : public IPreferencePage { - berryInterfaceMacro(IQtPreferencePage, berry); + berryObjectMacro(berry::IQtPreferencePage); virtual void CreateQtControl(QWidget* parent) = 0; virtual QWidget* GetQtControl() const = 0; protected: void CreateControl(void* parent); void* GetControl() const; }; } #endif /*BERRYIQTPREFERENCEPAGE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIReusableEditor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIReusableEditor.h index a3d8657f7b..ff4b4fa5e9 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIReusableEditor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIReusableEditor.h @@ -1,54 +1,55 @@ /*=================================================================== 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 BERRYIREUSABLEEDITOR_H_ #define BERRYIREUSABLEEDITOR_H_ #include "berryIEditorPart.h" #include "berryIEditorInput.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * Interface for reusable editors. * * An editors may support changing its input so that * the workbench may change its contents instead of * opening a new editor. */ -struct BERRY_UI_QT IReusableEditor : public virtual IEditorPart { +struct BERRY_UI_QT IReusableEditor : public virtual IEditorPart +{ - berryInterfaceMacro(IReusableEditor, berry); + berryObjectMacro(berry::IReusableEditor) virtual ~IReusableEditor(); /** * Sets the input to this editor. * *

Note: Clients must fire the {@link IEditorPart#PROP_INPUT } * property change within their implementation of * setInput().

* * @param input the editor input */ virtual void SetInput(IEditorInput::Pointer input) = 0; }; } #endif /*BERRYIREUSABLEEDITOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablePart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablePart.h index 094e52b3dc..b0304f879e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablePart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablePart.h @@ -1,121 +1,121 @@ /*=================================================================== 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 BERRYISAVEABLEPART_H_ #define BERRYISAVEABLEPART_H_ #include #include #include #include namespace berry { /** * Workbench parts implement or adapt to this interface to participate * in the enablement and execution of the Save and * Save As actions. * - * @since 2.1 - * @see org.blueberry.ui.IEditorPart + * @see IEditorPart */ -struct BERRY_UI_QT ISaveablePart : public virtual Object { +struct BERRY_UI_QT ISaveablePart : public virtual Object +{ - berryInterfaceMacro(ISaveablePart, berry); + berryObjectMacro(berry::ISaveablePart) /** * The property id for isDirty. */ static const int PROP_DIRTY; // = IWorkbenchPartConstants.PROP_DIRTY; /** * Saves the contents of this part. *

* If the save is successful, the part should fire a property changed event * reflecting the new dirty state (PROP_DIRTY property). *

*

* If the save is cancelled through user action, or for any other reason, the * part should invoke setCancelled on the IProgressMonitor * to inform the caller. *

*

* This method is long-running; progress and cancellation are provided * by the given progress monitor. *

* * @param monitor the progress monitor */ virtual void DoSave(/*IProgressMonitor monitor*/) = 0; /** * Saves the contents of this part to another object. *

* Implementors are expected to open a "Save As" dialog where the user will * be able to select a new name for the contents. After the selection is made, * the contents should be saved to that new name. During this operation a * IProgressMonitor should be used to indicate progress. *

*

* If the save is successful, the part fires a property changed event * reflecting the new dirty state (PROP_DIRTY property). *

*/ virtual void DoSaveAs() = 0; /** * Returns whether the contents of this part have changed since the last save * operation. If this value changes the part must fire a property listener * event with PROP_DIRTY. *

* Note: this method is called often on a part open or part * activation switch, for example by actions to determine their * enabled status. *

* * @return true if the contents have been modified and need * saving, and false if they have not changed since the last * save */ virtual bool IsDirty() const = 0; /** * Returns whether the "Save As" operation is supported by this part. * * @return true if "Save As" is supported, and false * if not supported */ virtual bool IsSaveAsAllowed() const = 0; /** * Returns whether the contents of this part should be saved when the part * is closed. * * @return true if the contents of the part should be saved on * close, and false if the contents are expendable */ virtual bool IsSaveOnCloseNeeded() const = 0; }; } -Q_DECLARE_INTERFACE(berry::ISaveablePart, "org.blueberry.ISaveablePart") +Q_DECLARE_INTERFACE(berry::ISaveablePart, "org.blueberry.ui.ISaveablePart") #endif /* BERRYISAVEABLEPART_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablesLifecycleListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablesLifecycleListener.cpp index 188c8508ea..68e9a1f674 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablesLifecycleListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablesLifecycleListener.cpp @@ -1,39 +1,43 @@ /*=================================================================== 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 "berryISaveablesLifecycleListener.h" namespace berry { void ISaveablesLifecycleListener::Events -::AddListener(ISaveablesLifecycleListener::Pointer listener) +::AddListener(ISaveablesLifecycleListener* listener) { - if (listener.IsNull()) return; + if (listener == NULL) return; - this->lifecycleChange += Delegate(listener.GetPointer(), &ISaveablesLifecycleListener::HandleLifecycleEvent); + this->lifecycleChange += Delegate(listener, &ISaveablesLifecycleListener::HandleLifecycleEvent); } void ISaveablesLifecycleListener::Events -::RemoveListener(ISaveablesLifecycleListener::Pointer listener) +::RemoveListener(ISaveablesLifecycleListener* listener) { - if (listener.IsNull()) return; + if (listener == NULL) return; - this->lifecycleChange -= Delegate(listener.GetPointer(), &ISaveablesLifecycleListener::HandleLifecycleEvent); + this->lifecycleChange -= Delegate(listener, &ISaveablesLifecycleListener::HandleLifecycleEvent); +} + +ISaveablesLifecycleListener::~ISaveablesLifecycleListener() +{ } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablesLifecycleListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablesLifecycleListener.h index d8ffe1b297..a75d9371fb 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablesLifecycleListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablesLifecycleListener.h @@ -1,82 +1,81 @@ /*=================================================================== 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 BERRYISAVEABLESLIFECYCLELISTENER_H_ #define BERRYISAVEABLESLIFECYCLELISTENER_H_ #include "berrySaveablesLifecycleEvent.h" #include -#include namespace berry { /** * Listener for events fired by implementers of {@link ISaveablesSource}. * *

* This service can be acquired from a part's service locator: * *

  * ISaveablesLifecycleListener listener = (ISaveablesLifecycleListener) getSite()
  *    .getService(ISaveablesLifecycleListener.class);
  * 
* * or, in the case of implementers of {@link ISaveablesSource} that are not a * part, from the workbench: * *
  * ISaveablesLifecycleListener listener = (ISaveablesLifecycleListener) workbench
  *    .getService(ISaveablesLifecycleListener.class);
  * 
* *
    *
  • This service is available globally.
  • *
*

- * - * @since 3.2 */ -struct ISaveablesLifecycleListener : public virtual Object { - - berryInterfaceMacro(ISaveablesLifecycleListener, berry); +struct ISaveablesLifecycleListener : public virtual Object +{ + berryObjectMacro(berry::ISaveablesLifecycleListener) struct Events { - Message1 lifecycleChange; + Message1 lifecycleChange; - void AddListener(ISaveablesLifecycleListener::Pointer listener); - void RemoveListener(ISaveablesLifecycleListener::Pointer listener); + void AddListener(ISaveablesLifecycleListener* listener); + void RemoveListener(ISaveablesLifecycleListener* listener); private: - typedef MessageDelegate1 Delegate; + typedef MessageDelegate1 Delegate; }; + virtual ~ISaveablesLifecycleListener(); + /** * Handle the given event. This method must be called on the UI thread. * * @param event */ - virtual void HandleLifecycleEvent(SaveablesLifecycleEvent::Pointer event) = 0; + virtual void HandleLifecycleEvent(const SaveablesLifecycleEvent::Pointer& event) = 0; }; } -Q_DECLARE_INTERFACE(berry::ISaveablesLifecycleListener, "org.blueberry.ui.qt.ISaveablesLifecycleListener") +Q_DECLARE_INTERFACE(berry::ISaveablesLifecycleListener, "org.blueberry.ui.ISaveablesLifecycleListener") #endif /* BERRYISAVEABLESLIFECYCLELISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablesSource.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablesSource.h index b782234d5c..a3ea39f178 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablesSource.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISaveablesSource.h @@ -1,124 +1,125 @@ /*=================================================================== 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 BERRYISAVEABLESSOURCE_H_ #define BERRYISAVEABLESSOURCE_H_ #include #include #include "berrySaveable.h" namespace berry { /** * Represents a source of Saveable objects (units of saveability). Workbench * parts that show more than one unit of saveability, or whose units of * saveability change over time, should implement this interface in order to * provide better integration with workbench facilities like the Save command, * prompts to save on part close or shutdown, etc. *

* IMPORTANT: As of 3.2, implementers of ISaveablesSource must * satisfy the following conditions: *

    *
  • If ISaveablesSource is implemented by an IWorkbenchPart: *
      *
    • the part must implement ISaveablePart
    • *
    • if any of its Saveable objects are dirty, the part must return * true from {@link ISaveablePart#isDirty()}
    • *
    • the part must return true from * {@link ISaveablePart#isSaveOnCloseNeeded()} if it is dirty (the default * behaviour implemented by {@link EditorPart})
    • *
    • the part must not implement {@link ISaveablePart2}
    • *
    *
  • *
  • If ISaveablesSource is implemented by a non-part (possible as of 3.2.1 and 3.3): *
      *
    • the Workbench's {@link ISaveablesLifecycleListener} (obtained from the * Workbench by calling * workbench.getService(ISaveablesLifecycleListener.class)) must * be notified of any change to the result of {@link #getSaveables()}
    • *
    • getActiveSaveables() should be implemented to return an empty array *
    • *
    *
* If any of these conditions are not met, it is undefined whether the Workbench * will prompt to save dirty Saveables when closing parts or the Workbench. *

*

* These conditions may be relaxed in future releases. *

* * @since 3.2 */ -struct BERRY_UI_QT ISaveablesSource : public virtual Object { +struct BERRY_UI_QT ISaveablesSource : public virtual Object +{ - berryInterfaceMacro(ISaveablesSource, berry); + berryObjectMacro(berry::ISaveablesSource) ~ISaveablesSource(); /** * Returns the saveables presented by the workbench part. If the return * value of this method changes during the lifetime of * this part (i.e. after initialization and control creation but before disposal) * the part must notify an implicit listener using * {@link ISaveablesLifecycleListener#handleLifecycleEvent(SaveablesLifecycleEvent)}. *

* Additions of saveables to the list of saveables of this part are * announced using an event of type * {@link SaveablesLifecycleEvent#POST_OPEN}. Removals are announced in a * two-stage process, first using an event of type * {@link SaveablesLifecycleEvent#PRE_CLOSE} followed by an event of type * {@link SaveablesLifecycleEvent#POST_CLOSE}. Since firing the * PRE_CLOSE event may trigger prompts to save dirty * saveables, the cancellation status of the event must be checked by the * part after the notification. When removing only non-dirty saveables, * POST_CLOSE notification is sufficient. *

*

* The listener is obtained from the part site by calling * partSite.getService(ISaveablesLifecycleListener.class). *

*

* The part must not notify from its initialization methods (e.g. init * or createPartControl), or from its dispose method. Parts that * implement {@link IReusableEditor} must notify when their input is changed * through {@link IReusableEditor#setInput(IEditorInput)}. *

* * @return the saveables presented by the workbench part * * @see ISaveablesLifecycleListener */ virtual QList GetSaveables() = 0; /** * Returns the saveables currently active in the workbench part. *

* Certain workbench actions, such as Save, target only the active saveables * in the active part. For example, the active saveables could be determined * based on the current selection in the part. *

* * @return the saveables currently active in the workbench part */ virtual QList GetActiveSaveables() = 0; }; } #endif /* BERRYISAVEABLESSOURCE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelection.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelection.h index e28f2881ee..46fabc93d0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelection.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelection.h @@ -1,55 +1,55 @@ /*=================================================================== 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 BERRYISELECTION_H_ #define BERRYISELECTION_H_ #include #include #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * Interface for a selection. * * @see ISelectionProvider * @see ISelectionChangedListener * @see SelectionChangedEvent * **/ struct BERRY_UI_QT ISelection : public Object { - berryInterfaceMacro(ISelection, berry); + berryObjectMacro(berry::ISelection) ~ISelection(); /** * Returns whether this selection is empty. * * @return true if this selection is empty, * and false otherwise */ virtual bool IsEmpty() const = 0; }; } #endif /*BERRYISELECTION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionChangedListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionChangedListener.cpp index 613ff7fdc2..c3f64cbe0c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionChangedListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionChangedListener.cpp @@ -1,40 +1,44 @@ /*=================================================================== 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 "berryISelectionChangedListener.h" #include "berryISelectionProvider.h" namespace berry { void ISelectionChangedListener::Events -::AddListener(ISelectionChangedListener::Pointer listener) +::AddListener(ISelectionChangedListener* listener) { - if (listener.IsNull()) return; + if (listener == NULL) return; - this->selectionChanged += Delegate(listener.GetPointer(), &ISelectionChangedListener::SelectionChanged); + this->selectionChanged += Delegate(listener, &ISelectionChangedListener::SelectionChanged); } void ISelectionChangedListener::Events -::RemoveListener(ISelectionChangedListener::Pointer listener) +::RemoveListener(ISelectionChangedListener* listener) { - if (listener.IsNull()) return; + if (listener == NULL) return; - this->selectionChanged -= Delegate(listener.GetPointer(), &ISelectionChangedListener::SelectionChanged); + this->selectionChanged -= Delegate(listener, &ISelectionChangedListener::SelectionChanged); +} + +ISelectionChangedListener::~ISelectionChangedListener() +{ } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionChangedListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionChangedListener.h index 7194248ba8..a0c6f3b01b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionChangedListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionChangedListener.h @@ -1,67 +1,68 @@ /*=================================================================== 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 BERRYISELECTIONCHANGEDLISTENER_H_ #define BERRYISELECTIONCHANGEDLISTENER_H_ #include #include #include #include "berrySelectionChangedEvent.h" namespace berry { class SelectionChangedEvent; /** * \ingroup org_blueberry_ui_qt * * A listener which is notified when a viewer's selection changes. * * @see ISelection * @see ISelectionProvider * @see SelectionChangedEvent */ -struct BERRY_UI_QT ISelectionChangedListener : public virtual Object { - - berryInterfaceMacro(ISelectionChangedListener, berry); +struct BERRY_UI_QT ISelectionChangedListener +{ struct BERRY_UI_QT Events { - Message1 selectionChanged; + Message1 selectionChanged; - void AddListener(ISelectionChangedListener::Pointer listener); - void RemoveListener(ISelectionChangedListener::Pointer listener); + void AddListener(ISelectionChangedListener* listener); + void RemoveListener(ISelectionChangedListener* listener); private: - typedef MessageDelegate1 Delegate; + typedef MessageDelegate1 Delegate; }; + virtual ~ISelectionChangedListener(); + /** * Notifies that the selection has changed. * * @param event event object describing the change */ - virtual void SelectionChanged(SelectionChangedEvent::Pointer event) = 0; + virtual void SelectionChanged(const SelectionChangedEvent::Pointer& event) = 0; }; } #endif /*BERRYISELECTIONCHANGEDLISTENER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionListener.cpp index b11441e17c..a4dda88fe5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionListener.cpp @@ -1,39 +1,43 @@ /*=================================================================== 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 "berryISelectionListener.h" namespace berry { void ISelectionListener::Events -::AddListener(ISelectionListener::Pointer listener) +::AddListener(ISelectionListener* listener) { - if (listener.IsNull()) return; + if (listener == NULL) return; - this->selectionChanged += Delegate(listener.GetPointer(), &ISelectionListener::SelectionChanged); + this->selectionChanged += Delegate(listener, &ISelectionListener::SelectionChanged); } void ISelectionListener::Events -::RemoveListener(ISelectionListener::Pointer listener) +::RemoveListener(ISelectionListener* listener) { - if (listener.IsNull()) return; + if (listener == NULL) return; - this->selectionChanged -= Delegate(listener.GetPointer(), &ISelectionListener::SelectionChanged); + this->selectionChanged -= Delegate(listener, &ISelectionListener::SelectionChanged); +} + +ISelectionListener::~ISelectionListener() +{ } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionListener.h index 573e955dba..dec5ea1905 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionListener.h @@ -1,131 +1,131 @@ /*=================================================================== 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 BERRYISELECTIONLISTENER_H_ #define BERRYISELECTIONLISTENER_H_ #include #include #include "berryIWorkbenchPart.h" #include "berryISelection.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * Interface for listening to selection changes. *

* This interface may be implemented by clients. *

* * @see ISelectionService#AddSelectionListener(ISelectionListener::Pointer) * @see ISelectionService#AddSelectionListener(const QString&, ISelectionListener::Pointer) * @see INullSelectionListener */ -struct BERRY_UI_QT ISelectionListener: public virtual Object +struct BERRY_UI_QT ISelectionListener { - berryInterfaceMacro(ISelectionListener, berry); - struct Events { - Message2 + Message2 selectionChanged; - void AddListener(ISelectionListener::Pointer listener); - void RemoveListener(ISelectionListener::Pointer listener); + void AddListener(ISelectionListener* listener); + void RemoveListener(ISelectionListener* listener); - typedef MessageDelegate2 Delegate; + typedef MessageDelegate2 Delegate; }; + virtual ~ISelectionListener(); + /** * Notifies this listener that the selection has changed. *

* This method is called when the selection changes from one to a * non-null value, but not when the selection changes to * null. If there is a requirement to be notified in the latter * scenario, implement INullSelectionListener. The event will * be posted through this method. *

* * @param part the workbench part containing the selection * @param selection the current selection. This may be null * if INullSelectionListener is implemented. */ - virtual void SelectionChanged(IWorkbenchPart::Pointer part, - ISelection::ConstPointer selection) = 0; + virtual void SelectionChanged(const IWorkbenchPart::Pointer& part, + const ISelection::ConstPointer& selection) = 0; }; /** * \ingroup org_blueberry_ui_qt * * This template can be used like this: * * * class MyClass { * * private: * void HandleSelectionChanged(berry::IWorkbenchPart::Pointer part, berry::ISelection::ConstPointer selection) * { // do something } * * berry::ISelectionListener::Pointer m_SelectionListener; * * public: * MyClass() * : m_SelectionListener(new berry::SelectionChangedAdapter(this, &MyClass::HandleSelectionChanged)) * { * // get the selection service * // ... * service->AddPostSelectionListener(m_SelectionListener); * } * }; * */ template struct SelectionChangedAdapter: public ISelectionListener { typedef R Listener; typedef void - (R::*Callback)(IWorkbenchPart::Pointer, ISelection::ConstPointer); + (R::*Callback)(const IWorkbenchPart::Pointer&, const ISelection::ConstPointer&); SelectionChangedAdapter(R* l, Callback c) : listener(l), callback(c) { poco_assert(listener); poco_assert(callback); } - void SelectionChanged(IWorkbenchPart::Pointer part, ISelection::ConstPointer selection) + void SelectionChanged(const IWorkbenchPart::Pointer& part, const ISelection::ConstPointer& selection) { (listener->*callback)(part, selection); } private: Listener* listener; Callback callback; }; } #endif /*BERRYISELECTIONLISTENER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionProvider.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionProvider.h index 3f264b7f92..3ba2cb85ac 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionProvider.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionProvider.h @@ -1,77 +1,78 @@ /*=================================================================== 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 BERRYISELECTIONPROVIDER_H_ #define BERRYISELECTIONPROVIDER_H_ #include #include "berryISelectionChangedListener.h" #include "berryISelection.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * Interface common to all objects that provide a selection. * * @see ISelection * @see ISelectionChangedListener * @see SelectionChangedEvent */ -struct BERRY_UI_QT ISelectionProvider : public virtual Object { +struct BERRY_UI_QT ISelectionProvider : public virtual Object +{ - berryInterfaceMacro(ISelectionProvider, berry); + berryObjectMacro(berry::ISelectionProvider) ~ISelectionProvider(); /** * Adds a listener for selection changes in this selection provider. * Has no effect if an identical listener is already registered. * * @param listener a selection changed listener */ - virtual void AddSelectionChangedListener(ISelectionChangedListener::Pointer listener) = 0; + virtual void AddSelectionChangedListener(ISelectionChangedListener* listener) = 0; /** * Returns the current selection for this provider. * * @return the current selection */ virtual ISelection::ConstPointer GetSelection() const = 0; /** * Removes the given selection change listener from this selection provider. * Has no affect if an identical listener is not registered. * * @param listener a selection changed listener */ virtual void RemoveSelectionChangedListener( - ISelectionChangedListener::Pointer listener) = 0; + ISelectionChangedListener* listener) = 0; /** * Sets the current selection for this selection provider. * * @param selection the new selection */ - virtual void SetSelection(ISelection::ConstPointer selection) = 0; + virtual void SetSelection(const ISelection::ConstPointer& selection) = 0; }; } #endif /*BERRYISELECTIONPROVIDER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionService.h index 088295170e..60579b7b46 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionService.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISelectionService.h @@ -1,183 +1,185 @@ /*=================================================================== 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 BERRYISELECTIONSERVICE_H_ #define BERRYISELECTIONSERVICE_H_ #include #include "berryISelection.h" #include "berryISelectionListener.h" #include "berryIWorkbenchPart.h" #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * A selection service tracks the selection within an object. *

* A listener that wants to be notified when the selection becomes * null must implement the INullSelectionListener * interface. *

*

* This interface is not intended to be implemented by clients. *

* @see org.blueberry.ui.ISelectionListener * @see org.blueberry.ui.INullSelectionListener */ struct BERRY_UI_QT ISelectionService { struct SelectionEvents { typedef Message2 SelectionEvent; typedef MessageDelegate2 Delegate; SelectionEvent selectionChanged; SelectionEvent postSelectionChanged; }; virtual ~ISelectionService(); //virtual SelectionEvents& GetSelectionEvents(const QString& partId = "") = 0; /** * Adds the given selection listener. * Has no effect if an identical listener is already registered. * * @param listener a selection listener */ - virtual void AddSelectionListener(ISelectionListener::Pointer listener) = 0; + virtual void AddSelectionListener(ISelectionListener* listener) = 0; /** * Adds a part-specific selection listener which is notified when selection changes * in the part with the given id. This is independent of part activation - the part * need not be active for notification to be sent. *

* When the part is created, the listener is passed the part's initial selection. * When the part is disposed, the listener is passed a null selection, * but only if the listener implements INullSelectionListener. *

*

* Note: This will not correctly track editor parts as each editor does * not have a unique partId. *

* * @param partId the id of the part to track * @param listener a selection listener * @since 2.0 */ - virtual void AddSelectionListener(const QString& partId, ISelectionListener::Pointer listener) = 0; + virtual void AddSelectionListener(const QString& partId, ISelectionListener* listener) = 0; /** * Adds the given post selection listener.It is equivalent to selection * changed if the selection was triggered by the mouse but it has a * delay if the selection is triggered by the keyboard arrows. * Has no effect if an identical listener is already registered. * * Note: Works only for StructuredViewer(s). * * @param listener a selection listener */ - virtual void AddPostSelectionListener(ISelectionListener::Pointer listener) = 0; + virtual void AddPostSelectionListener(ISelectionListener* listener) = 0; /** * Adds a part-specific selection listener which is notified when selection changes * in the part with the given id. This is independent of part activation - the part * need not be active for notification to be sent. *

* When the part is created, the listener is passed the part's initial selection. * When the part is disposed, the listener is passed a null selection, * but only if the listener implements INullSelectionListener. *

*

* Note: This will not correctly track editor parts as each editor does * not have a unique partId. *

* * @param partId the id of the part to track * @param listener a selection listener * @since 2.0 */ virtual void AddPostSelectionListener(const QString& partId, - ISelectionListener::Pointer listener) = 0; + ISelectionListener* listener) = 0; /** * Returns the current selection in the active part. If the selection in the * active part is undefined (the active part has no selection provider) * the result will be null. * * @return the current selection, or null if undefined */ virtual ISelection::ConstPointer GetSelection() const = 0; /** * Returns the current selection in the part with the given id. If the part is not open, * or if the selection in the active part is undefined (the active part has no selection provider) * the result will be null. * * @param partId the id of the part * @return the current selection, or null if undefined * @since 2.0 */ virtual ISelection::ConstPointer GetSelection(const QString& partId) = 0; /** * Removes the given selection listener. * Has no effect if an identical listener is not registered. * * @param listener a selection listener */ - virtual void RemoveSelectionListener(ISelectionListener::Pointer listener) = 0; + virtual void RemoveSelectionListener(ISelectionListener* listener) = 0; /** * Removes the given part-specific selection listener. * Has no effect if an identical listener is not registered for the given part id. * * @param partId the id of the part to track * @param listener a selection listener * @since 2.0 */ virtual void RemoveSelectionListener(const QString& partId, - ISelectionListener::Pointer listener) = 0; + ISelectionListener* listener) = 0; /** * Removes the given post selection listener. * Has no effect if an identical listener is not registered. * * @param listener a selection listener */ - virtual void RemovePostSelectionListener(ISelectionListener::Pointer listener) = 0; + virtual void RemovePostSelectionListener(ISelectionListener* listener) = 0; /** * Removes the given part-specific post selection listener. * Has no effect if an identical listener is not registered for the given part id. * * @param partId the id of the part to track * @param listener a selection listener * @since 2.0 */ virtual void RemovePostSelectionListener(const QString& partId, - ISelectionListener::Pointer listener) = 0; + ISelectionListener* listener) = 0; }; } // namespace berry +Q_DECLARE_INTERFACE(berry::ISelectionService, "org.blueberry.ui.ISelectionService") + #endif /*BERRYISELECTIONSERVICE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellListener.cpp index 884e8cacf5..ef442ffb36 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellListener.cpp @@ -1,59 +1,63 @@ /*=================================================================== 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 "berryIShellListener.h" #include "berryShell.h" namespace berry { void IShellListener::Events -::AddListener(IShellListener::Pointer listener) +::AddListener(IShellListener* listener) { - if (listener.IsNull()) return; + if (listener == NULL) return; - shellActivated += Delegate(listener.GetPointer(), &IShellListener::ShellActivated); - shellClosed += Delegate(listener.GetPointer(), &IShellListener::ShellClosed); - shellDeactivated += Delegate(listener.GetPointer(), &IShellListener::ShellDeactivated); - shellDeiconified += Delegate(listener.GetPointer(), &IShellListener::ShellDeiconified); - shellIconified += Delegate(listener.GetPointer(), &IShellListener::ShellIconified); + shellActivated += Delegate(listener, &IShellListener::ShellActivated); + shellClosed += Delegate(listener, &IShellListener::ShellClosed); + shellDeactivated += Delegate(listener, &IShellListener::ShellDeactivated); + shellDeiconified += Delegate(listener, &IShellListener::ShellDeiconified); + shellIconified += Delegate(listener, &IShellListener::ShellIconified); } void IShellListener::Events -::RemoveListener(IShellListener::Pointer listener) +::RemoveListener(IShellListener* listener) { - if (listener.IsNull()) return; + if (listener == NULL) return; - shellActivated -= Delegate(listener.GetPointer(), &IShellListener::ShellActivated); - shellClosed -= Delegate(listener.GetPointer(), &IShellListener::ShellClosed); - shellDeactivated -= Delegate(listener.GetPointer(), &IShellListener::ShellDeactivated); - shellDeiconified -= Delegate(listener.GetPointer(), &IShellListener::ShellDeiconified); - shellIconified -= Delegate(listener.GetPointer(), &IShellListener::ShellIconified); + shellActivated -= Delegate(listener, &IShellListener::ShellActivated); + shellClosed -= Delegate(listener, &IShellListener::ShellClosed); + shellDeactivated -= Delegate(listener, &IShellListener::ShellDeactivated); + shellDeiconified -= Delegate(listener, &IShellListener::ShellDeiconified); + shellIconified -= Delegate(listener, &IShellListener::ShellIconified); } -void IShellListener::ShellActivated(ShellEvent::Pointer /*e*/) +IShellListener::~IShellListener() +{ +} + +void IShellListener::ShellActivated(const ShellEvent::Pointer& /*e*/) {} -void IShellListener::ShellClosed(ShellEvent::Pointer /*e*/) +void IShellListener::ShellClosed(const ShellEvent::Pointer& /*e*/) {} -void IShellListener::ShellDeactivated(ShellEvent::Pointer /*e*/) +void IShellListener::ShellDeactivated(const ShellEvent::Pointer& /*e*/) {} -void IShellListener::ShellDeiconified(ShellEvent::Pointer /*e*/) +void IShellListener::ShellDeiconified(const ShellEvent::Pointer& /*e*/) {} -void IShellListener::ShellIconified(ShellEvent::Pointer /*e*/) +void IShellListener::ShellIconified(const ShellEvent::Pointer& /*e*/) {} } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellListener.h index 3caf4620ab..ad0014748a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellListener.h @@ -1,118 +1,119 @@ /*=================================================================== 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 BERRYISHELLLISTENER_H_ #define BERRYISHELLLISTENER_H_ #include #include "berryShellEvent.h" #include #include namespace berry { /** * Classes which implement this interface provide methods * that deal with changes in state of Shells. *

* After creating an instance of a class that implements * this interface it can be added to a shell using the * AddShellListener method and removed using * the RemoveShellListener method. When the * state of the shell changes, the appropriate method will * be invoked. *

* * @see ShellEvent */ -struct BERRY_UI_QT IShellListener : public virtual Object { +struct BERRY_UI_QT IShellListener +{ - berryInterfaceMacro(IShellListener, berry); - - struct BERRY_UI_QT Events { - typedef Message1 ShellEventType; + struct Events { + typedef Message1 ShellEventType; enum Type { NONE = 0x00000000, ACTIVATED = 0x00000001, CLOSED = 0x00000002, DEACTIVATED = 0x00000004, DEICONIFIED = 0x00000008, ICONIFIED = 0x00000010, ALL = 0xffffffff }; - BERRY_DECLARE_FLAGS(Types, Type) + Q_DECLARE_FLAGS(Types, Type) ShellEventType shellActivated; ShellEventType shellClosed; ShellEventType shellDeactivated; ShellEventType shellDeiconified; ShellEventType shellIconified; - void AddListener(IShellListener::Pointer listener); - void RemoveListener(IShellListener::Pointer listener); + void AddListener(IShellListener* listener); + void RemoveListener(IShellListener* listener); private: - typedef MessageDelegate1 Delegate; + typedef MessageDelegate1 Delegate; }; -/** - * Sent when a shell becomes the active window. - * - * @param e an event containing information about the activation - */ -virtual void ShellActivated(ShellEvent::Pointer e); - -/** - * Sent when a shell is closed. - * - * @param e an event containing information about the close - */ -virtual void ShellClosed(ShellEvent::Pointer e); - -/** - * Sent when a shell stops being the active window. - * - * @param e an event containing information about the deactivation - */ -virtual void ShellDeactivated(ShellEvent::Pointer e); - -/** - * Sent when a shell is un-minimized. - * - * @param e an event containing information about the un-minimization - */ -virtual void ShellDeiconified(ShellEvent::Pointer e); - -/** - * Sent when a shell is minimized. - * - * @param e an event containing information about the minimization - */ -virtual void ShellIconified(ShellEvent::Pointer e); + virtual ~IShellListener(); + + /** + * Sent when a shell becomes the active window. + * + * @param e an event containing information about the activation + */ + virtual void ShellActivated(const ShellEvent::Pointer& e); + + /** + * Sent when a shell is closed. + * + * @param e an event containing information about the close + */ + virtual void ShellClosed(const ShellEvent::Pointer& e); + + /** + * Sent when a shell stops being the active window. + * + * @param e an event containing information about the deactivation + */ + virtual void ShellDeactivated(const ShellEvent::Pointer& e); + + /** + * Sent when a shell is un-minimized. + * + * @param e an event containing information about the un-minimization + */ + virtual void ShellDeiconified(const ShellEvent::Pointer& e); + + /** + * Sent when a shell is minimized. + * + * @param e an event containing information about the minimization + */ + virtual void ShellIconified(const ShellEvent::Pointer& e); }; } -BERRY_DECLARE_OPERATORS_FOR_FLAGS(berry::IShellListener::Events::Types) +Q_DECLARE_OPERATORS_FOR_FLAGS(berry::IShellListener::Events::Types) #endif /* BERRYISHELLLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellProvider.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellProvider.h index a63ae5b679..a5d90564d5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellProvider.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellProvider.h @@ -1,53 +1,54 @@ /*=================================================================== 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 BERRYISHELLPROVIDER_H_ #define BERRYISHELLPROVIDER_H_ #include #include "berryShell.h" #include namespace berry { /** * Interface for objects that can return a shell. This is normally used for * opening child windows. An object that wants to open child shells can take * an IShellProvider in its constructor, and the object that implements IShellProvider * can dynamically choose where child shells should be opened. * * @since 3.1 */ -struct BERRY_UI_QT IShellProvider : public virtual Object { +struct BERRY_UI_QT IShellProvider : public virtual Object +{ - berryInterfaceMacro(IShellProvider, berry); + berryObjectMacro(berry::IShellProvider) ~IShellProvider(); /** * Returns the current shell (or null if none). This return value may * change over time, and should not be cached. * * @return the current shell or null if none */ - virtual Shell::Pointer GetShell() = 0; + virtual Shell::Pointer GetShell() const = 0; }; } #endif /* BERRYISHELLPROVIDER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShowInSource.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShowInSource.h new file mode 100644 index 0000000000..ef72858133 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShowInSource.h @@ -0,0 +1,53 @@ +/*=================================================================== + +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 BERRYISHOWINSOURCE_H +#define BERRYISHOWINSOURCE_H + +#include + +namespace berry { + +class ShowInContext; + +/** + * Parts which need to provide a particular context to a 'Show In' target can + * provide this interface. + *

+ * The part can either directly implement this interface, or provide it via + * IAdaptable#GetAdapter(). + *

null if there is + * currently no valid context to show. + * + * @return the context to show, or null + */ + virtual SmartPointer GetShowInContext() const = 0; +}; + +} + +Q_DECLARE_INTERFACE(berry::IShowInSource, "org.blueberry.ui.IShowInSource") + +#endif // BERRYISHOWINSOURCE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShowInTarget.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShowInTarget.h new file mode 100644 index 0000000000..c791a5f03e --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShowInTarget.h @@ -0,0 +1,56 @@ +/*=================================================================== + +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 BERRYISHOWINTARGET_H +#define BERRYISHOWINTARGET_H + +#include + +namespace berry { + +class ShowInContext; + +/** + * This interface must be provided by Show In targets (views listed in the 'Show In' + * menu). + *

+ * The view can either directly implement this interface, or provide it via + * IAdaptable.getAdapter(IShowInTarget.class). + *

+ * + * @see IPageLayout#AddShowInPart + */ +struct IShowInTarget : public virtual Object +{ + + berryObjectMacro(berry::IShowInTarget) + + /** + * Shows the given context in this target. + * The target should check the context's selection for elements + * to show. If there are no relevant elements in the selection, + * then it should check the context's input. + * + * @param context the context to show + * @return true if the context could be shown, + * false otherwise + */ + virtual bool Show(const SmartPointer& context) = 0; +}; + +} + +#endif // BERRYISHOWINTARGET_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISourceProvider.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISourceProvider.h index 8565b5e1b1..93f565dc71 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISourceProvider.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISourceProvider.h @@ -1,106 +1,106 @@ /*=================================================================== 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 BERRYISOURCEPROVIDER_H_ #define BERRYISOURCEPROVIDER_H_ #include #include #include #include namespace berry { struct ISourceProviderListener; /** *

* A provider of notifications for when a change has occurred to a particular * type of source. These providers can be given to the appropriate service, and * this service will then re-evaluate the appropriate pieces of its internal * state in response to these changes. *

*

* It is recommended that clients subclass AbstractSourceProvider * instead, as this provides some common support for listeners. *

* - * @since 3.1 - * @see org.blueberry.ui.handlers.IHandlerService - * @see org.blueberry.ui.ISources + * @see IHandlerService + * @see ISources */ -struct ISourceProvider : public virtual Object { +struct ISourceProvider : public virtual Object +{ - berryInterfaceMacro(ISourceProvider, berry) + berryObjectMacro(berry::ISourceProvider) - typedef QHash StateMapType; + typedef QHash StateMapType; ~ISourceProvider(); /** * Adds a listener to this source provider. This listener will be notified * whenever the corresponding source changes. * * @param listener * The listener to add; must not be null. */ virtual void AddSourceProviderListener(ISourceProviderListener* listener) = 0; /** * Returns the current state of the sources tracked by this provider. This * is used to provide a view of the world if the event loop is busy and * things are some state has already changed. *

* For use with core expressions, this map should contain * IEvaluationContext#UNDEFINED_VARIABLE for properties which * are only sometimes available. *

* * @return A map of variable names (String) to variable * values (Object). This may be empty, and may be * null. */ - virtual StateMapType GetCurrentState() = 0; + virtual StateMapType GetCurrentState() const = 0; /** * Returns the names of those sources provided by this class. This is used * by clients of source providers to determine which source providers they * actually need. * * @return An array of source names. This value should never be * null or empty. */ - virtual QStringList GetProvidedSourceNames() = 0; + virtual QList GetProvidedSourceNames() const = 0; /** * Removes a listener from this source provider. This listener will be * notified whenever the corresponding source changes. * * @param listener * The listener to remove; must not be null. */ virtual void RemoveSourceProviderListener(ISourceProviderListener* listener) = 0; }; } -Q_DECLARE_INTERFACE(berry::ISourceProvider, "org.blueberry.ISourceProvider") +Q_DECLARE_INTERFACE(berry::ISourceProvider, "org.blueberry.ui.ISourceProvider") #endif /* BERRYISOURCEPROVIDER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISourceProviderListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISourceProviderListener.cpp index 8e3dce5d3b..a42b9b61e4 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISourceProviderListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISourceProviderListener.cpp @@ -1,37 +1,41 @@ /*=================================================================== 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 "berryISourceProviderListener.h" namespace berry { void ISourceProviderListener::Events::AddListener(ISourceProviderListener* l) { if (l == 0) return; multipleSourcesChanged += Delegate2(l, &ISourceProviderListener::SourceChanged); singleSourceChanged += Delegate3(l, &ISourceProviderListener::SourceChanged); } void ISourceProviderListener::Events::RemoveListener(ISourceProviderListener* l) { if (l == 0) return; multipleSourcesChanged -= Delegate2(l, &ISourceProviderListener::SourceChanged); singleSourceChanged -= Delegate3(l, &ISourceProviderListener::SourceChanged); } +ISourceProviderListener::~ISourceProviderListener() +{ +} + } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISourceProviderListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISourceProviderListener.h index 9b8108ff58..ca6fffbc3a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISourceProviderListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISourceProviderListener.h @@ -1,100 +1,100 @@ /*=================================================================== 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 BERRYISOURCEPROVIDERLISTENER_H_ #define BERRYISOURCEPROVIDERLISTENER_H_ #include #include #include #include #include namespace berry { /** *

* A listener to changes in a particular source of information. This listener is * notified as the source changes. Typically, workbench services will implement * this interface, and register themselves as listeners to the * ISourceProvider instances that are registered with them. *

* - * @since 3.1 - * @see org.blueberry.ui.ISources - * @see org.blueberry.ui.ISourceProvider + * @see ISources + * @see ISourceProvider */ -struct BERRY_UI_QT ISourceProviderListener : public virtual Object { - - berryInterfaceMacro(ISourceProviderListener, berry) +struct BERRY_UI_QT ISourceProviderListener +{ struct Events { - Message2& > multipleSourcesChanged; - Message3 singleSourceChanged; + Message2& > multipleSourcesChanged; + Message3 singleSourceChanged; void AddListener(ISourceProviderListener* l); void RemoveListener(ISourceProviderListener* l); private: - typedef MessageDelegate2& > Delegate2; - typedef MessageDelegate3 Delegate3; + typedef MessageDelegate2& > Delegate2; + typedef MessageDelegate3 Delegate3; }; + virtual ~ISourceProviderListener(); + /** * Handles a change to multiple sources. The source priority should be a bit * mask indicating the sources. The map will be used to construct the * variables on an IEvaluationContext * * @param sourcePriority * A bit mask of all the source priorities that have changed. * @param sourceValuesByName * A mapping of the source names (String) to the * source values (Object). The names should * never be null, but the values may be. The map * must not be null, and should contain at least * two elements (one for each source). * @see org.blueberry.core.expressions.IEvaluationContext * @see ISources */ virtual void SourceChanged(int sourcePriority, - const QHash& sourceValuesByName) = 0; + const QHash& sourceValuesByName) = 0; /** * Handles a change to one source. The source priority should indicate the * source, and the name-value pair will be used to create an * IEvaluationContext with a single variable. * * @param sourcePriority * A bit mask of all the source priorities that have changed. * @param sourceName * The name of the source that changed; must not be * null. * @param sourceValue * The new value for that source; may be null. * @see org.blueberry.core.expressions.IEvaluationContext * @see ISources */ virtual void SourceChanged(int sourcePriority, - const QString& sourceName, Object::Pointer sourceValue) = 0; + const QString& sourceName, Object::ConstPointer sourceValue) = 0; }; } #endif /* BERRYISOURCEPROVIDERLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISources.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISources.cpp index e46b1704ce..762a7d5380 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISources.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISources.cpp @@ -1,255 +1,250 @@ /*=================================================================== 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 "berryISources.h" #include namespace berry { int ISources::WORKBENCH() { static int val = 0; return val; } -int ISources::LEGACY_LEGACY() -{ - static int val = 1; - return val; -} - -int ISources::LEGACY_LOW() -{ - static int val = 1 << 1; - return val; -} - -int ISources::LEGACY_MEDIUM() -{ - static int val = 1 << 2; - return val; -} - int ISources::ACTIVE_CONTEXT() { - static int val = 1 << 6; + static int val = 1 << 3; return val; } const QString ISources::ACTIVE_CONTEXT_NAME() { static const QString val = "activeContexts"; return val; } int ISources::ACTIVE_ACTION_SETS() { - static int val = 1 << 8; + static int val = 1 << 5; return val; } const QString ISources::ACTIVE_ACTION_SETS_NAME() { static const QString val = "activeActionSets"; return val; } int ISources::ACTIVE_SHELL() { - static int val = 1 << 10; + static int val = 1 << 7; return val; } const QString ISources::ACTIVE_SHELL_NAME() { static const QString val = "activeShell"; return val; } int ISources::ACTIVE_WORKBENCH_WINDOW_SHELL() { - static int val = 1 << 12; + static int val = 1 << 9; return val; } const QString ISources::ACTIVE_WORKBENCH_WINDOW_SHELL_NAME() { static const QString val = "activeWorkbenchWindowShell"; return val; } int ISources::ACTIVE_WORKBENCH_WINDOW() { - static int val = 1 << 14; + static int val = 1 << 11; return val; } const QString ISources::ACTIVE_WORKBENCH_WINDOW_NAME() { static const QString val = "activeWorkbenchWindow"; return val; } int ISources::ACTIVE_WORKBENCH_WINDOW_SUBORDINATE() { - static int val = 1 << 15; + static int val = 1 << 12; return val; } -const QString ISources::ACTIVE_WORKBENCH_WINDOW_IS_COOLBAR_VISIBLE_NAME() +const QString ISources::ACTIVE_WORKBENCH_WINDOW_IS_TOOLBAR_VISIBLE_NAME() { static const QString val = ISources::ACTIVE_WORKBENCH_WINDOW_NAME() - + ".isCoolbarVisible"; + + ".isToolbarVisible"; return val; } const QString ISources::ACTIVE_WORKBENCH_WINDOW_IS_PERSPECTIVEBAR_VISIBLE_NAME() { static const QString val = ISources::ACTIVE_WORKBENCH_WINDOW_NAME() + ".isPerspectiveBarVisible"; return val; } +const QString ISources::ACTIVE_WORKBENCH_WINDOW_IS_STATUS_LINE_VISIBLE_NAME() +{ + static const QString val = ISources::ACTIVE_WORKBENCH_WINDOW_NAME() + + ".isStatusLineVisible"; + return val; +} + const QString ISources::ACTIVE_WORKBENCH_WINDOW_ACTIVE_PERSPECTIVE_NAME() { static const QString val = ISources::ACTIVE_WORKBENCH_WINDOW_NAME() + ".activePerspective"; return val; } int ISources::ACTIVE_EDITOR() { - static int val = 1 << 16; + static int val = 1 << 13; return val; } const QString ISources::ACTIVE_EDITOR_NAME() { static const QString val = "activeEditor"; return val; } +const QString ISources::ACTIVE_EDITOR_INPUT_NAME() +{ + static const QString val = "activeEditorInput"; + return val; +} + int ISources::ACTIVE_EDITOR_ID() { - static int val = 1 << 18; + static int val = 1 << 15; return val; } const QString ISources::ACTIVE_EDITOR_ID_NAME() { static const QString val = "activeEditorId"; return val; } int ISources::ACTIVE_PART() { - static int val = 1 << 20; + static int val = 1 << 17; return val; } const QString ISources::ACTIVE_PART_NAME() { static const QString val = "activePart"; return val; } int ISources::ACTIVE_PART_ID() { - static int val = 1 << 22; + static int val = 1 << 19; return val; } const QString ISources::ACTIVE_PART_ID_NAME() { static const QString val = "activePartId"; return val; } int ISources::ACTIVE_SITE() { - static int val = 1 << 26; + static int val = 1 << 23; return val; } const QString ISources::ACTIVE_SITE_NAME() { static const QString val = "activeSite"; return val; } const QString ISources::SHOW_IN_SELECTION() { static const QString val = "showInSelection"; return val; } const QString ISources::SHOW_IN_INPUT() { static const QString val = "showInInput"; return val; } int ISources::ACTIVE_CURRENT_SELECTION() { - static int val = 1 << 30; + static int val = 1 << 27; return val; } const QString ISources::ACTIVE_CURRENT_SELECTION_NAME() { static const QString val = "selection"; return val; } int ISources::ACTIVE_MENU() { - static int val = 1 << 31; + static int val = 1 << 30; return val; } const QString ISources::ACTIVE_MENU_NAME() { static const QString val = "activeMenu"; return val; } const QString ISources::ACTIVE_MENU_SELECTION_NAME() { static const QString val = "activeMenuSelection"; return val; } const QString ISources::ACTIVE_MENU_EDITOR_INPUT_NAME() { static const QString val = "activeMenuEditorInput"; return val; } const QString ISources::ACTIVE_FOCUS_CONTROL_NAME() { static const QString val = "activeFocusControl"; return val; } const QString ISources::ACTIVE_FOCUS_CONTROL_ID_NAME() { static const QString val = "activeFocusControlId"; return val; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISources.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISources.h index 40c2234855..dbfc13f96e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISources.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryISources.h @@ -1,340 +1,296 @@ /*=================================================================== 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 BERRYISOURCES_H_ #define BERRYISOURCES_H_ #include #include namespace berry { /** * \ingroup org_blueberry_ui_qt * *

* A source is type of event change that can occur within the workbench. For * example, the active workbench window can change, so it is considered a * source. Workbench services can track changes to these sources, and thereby * try to resolve conflicts between a variety of possible options. This is most * commonly used for things like handlers and contexts. *

*

* This interface defines the source that are known to the workbench at * compile-time. These sources can be combined in a bit-wise fashion. So, for * example, a ACTIVE_PART | ACTIVE_CONTEXT source includes change * to both the active context and the active part. *

*

* The values assigned to each source indicates its relative priority. The * higher the value, the more priority the source is given in resolving * conflicts. Another way to look at this is that the higher the value, the more * "local" the source is to what the user is currently doing. This is similar * to, but distinct from the concept of components. The nesting support provided * by components represent only one source (ACTIVE_SITE) that * the workbench understands. *

*

* Note that for backward compatibility, we must reserve the lowest three bits * for Priority instances using the old * HandlerSubmission mechanism. This mechanism was used in * Eclipse 3.0. *

*

* Note in 3.3: *

*

* Currently, source variables are not extensible by user plugins, and * the number of bits available for resolving conflicts is limited. When * the variable sources become user extensible a new conflict resolution * mechanism will be implemented. *

* @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * * @see org.blueberry.ui.ISourceProvider - * @since 3.1 */ -struct BERRY_UI_QT ISources { +struct BERRY_UI_QT ISources +{ /** * The priority given to default handlers and handlers that are active * across the entire workbench. */ static int WORKBENCH(); // = 0; - /** - * The priority given when the activation is defined by a handler submission - * with a legacy priority. - */ - static int LEGACY_LEGACY(); // = 1; - - /** - * The priority given when the activation is defined by a handler submission - * with a low priority. - */ - static int LEGACY_LOW(); // = 1 << 1; - - /** - * The priority given when the activation is defined by a handler submission - * with a medium priority. - */ - static int LEGACY_MEDIUM(); // = 1 << 2; - /** * The priority given when the source includes a particular context. */ - static int ACTIVE_CONTEXT(); // = 1 << 6; + static int ACTIVE_CONTEXT(); // = 1 << 3; /** * The variable name for the active contexts. This is for use with the * ISourceProvider and IEvaluationContext. - * @since 3.2 */ - static const QString ACTIVE_CONTEXT_NAME(); // = "activeContexts"; + static const QString ACTIVE_CONTEXT_NAME(); /** * The priority given when the source includes a particular action set. - * @since 3.2 */ - static int ACTIVE_ACTION_SETS(); // = 1 << 8; + static int ACTIVE_ACTION_SETS(); // = 1 << 5; /** * The variable name for the active action sets. This is for use with the * {@link ISourceProvider} and {@link IEvaluationContext}. - * @since 3.2 */ - static const QString ACTIVE_ACTION_SETS_NAME(); // = "activeActionSets"(); + static const QString ACTIVE_ACTION_SETS_NAME(); /** * The priority given when the source includes the currently active shell. */ - static int ACTIVE_SHELL(); // = 1 << 10(); + static int ACTIVE_SHELL(); // = 1 << 7(); /** * The variable name for the active shell. This is for use with the * ISourceProvider and IEvaluationContext. */ - static const QString ACTIVE_SHELL_NAME(); // = "activeShell"(); + static const QString ACTIVE_SHELL_NAME(); /** * The priority given when the source includes the currently active * workbench window shell. - * @since 3.2 */ - static int ACTIVE_WORKBENCH_WINDOW_SHELL(); // = 1 << 12(); + static int ACTIVE_WORKBENCH_WINDOW_SHELL(); // = 1 << 9(); /** * The variable name for the active workbench window shell. This is for use * with the ISourceProvider and * IEvaluationContext. - * @since 3.2 */ - static const QString ACTIVE_WORKBENCH_WINDOW_SHELL_NAME(); // = "activeWorkbenchWindowShell"(); + static const QString ACTIVE_WORKBENCH_WINDOW_SHELL_NAME(); /** * The priority given when the source includes the currently active * workbench window. */ - static int ACTIVE_WORKBENCH_WINDOW(); // = 1 << 14(); + static int ACTIVE_WORKBENCH_WINDOW(); // = 1 << 11(); /** * The variable name for the active workbench window. This is for use with * the ISourceProvider and IEvaluationContext. */ - static const QString ACTIVE_WORKBENCH_WINDOW_NAME(); // = "activeWorkbenchWindow"(); + static const QString ACTIVE_WORKBENCH_WINDOW_NAME(); /** * The priority given when the source includes subordinate properties of the currently active * workbench window. - * - * @since 3.3 */ - static int ACTIVE_WORKBENCH_WINDOW_SUBORDINATE(); // = 1 << 15(); + static int ACTIVE_WORKBENCH_WINDOW_SUBORDINATE(); // = 1 << 12(); /** * The variable name for the coolbar visibility state of the active * workbench window. This is for use with the ISourceProvider * and IEvaluationContext. - * - * @since 3.3 */ - static const QString ACTIVE_WORKBENCH_WINDOW_IS_COOLBAR_VISIBLE_NAME(); // = ACTIVE_WORKBENCH_WINDOW_NAME - // + ".isCoolbarVisible"(); + static const QString ACTIVE_WORKBENCH_WINDOW_IS_TOOLBAR_VISIBLE_NAME(); /** * The variable name for the perspective bar visibility state of the active * workbench window. This is for use with the ISourceProvider * and IEvaluationContext. - * - * @since 3.3 */ - static const QString ACTIVE_WORKBENCH_WINDOW_IS_PERSPECTIVEBAR_VISIBLE_NAME(); // = ACTIVE_WORKBENCH_WINDOW_NAME - // + ".isPerspectiveBarVisible"(); + static const QString ACTIVE_WORKBENCH_WINDOW_IS_PERSPECTIVEBAR_VISIBLE_NAME(); + + /** + * The variable name for the status line visibility state of the active + * workbench window. This is for use with the ISourceProvider + * and IEvaluationContext. + */ + static const QString ACTIVE_WORKBENCH_WINDOW_IS_STATUS_LINE_VISIBLE_NAME(); /** * The variable name for the current perspective of the active workbench * window. This is for use with the ISourceProvider and * IEvaluationContext. - * - * @since 3.4 */ - static const QString ACTIVE_WORKBENCH_WINDOW_ACTIVE_PERSPECTIVE_NAME(); // = ACTIVE_WORKBENCH_WINDOW_NAME - //+ ".activePerspective"(); + static const QString ACTIVE_WORKBENCH_WINDOW_ACTIVE_PERSPECTIVE_NAME(); /** * The priority given when the source includes the active editor part. */ - static int ACTIVE_EDITOR(); // = 1 << 16(); + static int ACTIVE_EDITOR(); // = 1 << 13(); /** * The variable name for the active editor part. This is for use with the * ISourceProvider and IEvaluationContext. - * @since 3.2 */ - static const QString ACTIVE_EDITOR_NAME(); // = "activeEditor"(); + static const QString ACTIVE_EDITOR_NAME(); + + /** + * The editor input of the currently active editor. + */ + static const QString ACTIVE_EDITOR_INPUT_NAME(); /** * The priority given when the source includes the active editor identifier. - * - * @since 3.2 */ - static int ACTIVE_EDITOR_ID(); // = 1 << 18(); + static int ACTIVE_EDITOR_ID(); // = 1 << 15(); /** * The variable name for the active editor identifier. This is for use with * the ISourceProvider and IEvaluationContext. - * - * @since 3.2 */ - static const QString ACTIVE_EDITOR_ID_NAME(); // = "activeEditorId"(); + static const QString ACTIVE_EDITOR_ID_NAME(); /** * The priority given when the source includes the active part. */ - static int ACTIVE_PART(); // = 1 << 20(); + static int ACTIVE_PART(); // = 1 << 17(); /** * The variable name for the active part. This is for use with the * ISourceProvider and IEvaluationContext. */ - static const QString ACTIVE_PART_NAME(); // = "activePart"(); + static const QString ACTIVE_PART_NAME(); /** * The priority given when the source includes the active part id. - * - * @since 3.2 */ - static int ACTIVE_PART_ID(); // = 1 << 22(); + static int ACTIVE_PART_ID(); // = 1 << 19(); /** * The variable name for the active part id. This is for use with the * ISourceProvider and IEvaluationContext. - * - * @since 3.2 */ - static const QString ACTIVE_PART_ID_NAME(); // = "activePartId"(); + static const QString ACTIVE_PART_ID_NAME(); /** * The priority given when the source includes the active workbench site. In * the case of nesting components, one should be careful to only activate * the most nested component. */ - static int ACTIVE_SITE(); // = 1 << 26(); + static int ACTIVE_SITE(); // = 1 << 23(); /** * The variable name for the active workbench site. This is for use with the * ISourceProvider and IEvaluationContext. */ - static const QString ACTIVE_SITE_NAME(); // = "activeSite"(); + static const QString ACTIVE_SITE_NAME(); /** * The variable for the showIn selection. This is for use with the * ISourceProvider and IEvaluationContext. - * @since 3.4 * @see IShowInSource */ - static const QString SHOW_IN_SELECTION(); // = "showInSelection"(); + static const QString SHOW_IN_SELECTION(); /** * The variable for the showIn input. This is for use with the * ISourceProvider and IEvaluationContext. - * @since 3.4 * @see IShowInSource */ - static const QString SHOW_IN_INPUT(); // = "showInInput"(); + static const QString SHOW_IN_INPUT(); /** * The priority given when the source includes the current selection. */ - static int ACTIVE_CURRENT_SELECTION(); // = 1 << 30(); + static int ACTIVE_CURRENT_SELECTION(); // = 1 << 27(); /** * The variable name for the active selection. This is for use with the * ISourceProvider and IEvaluationContext. - * @since 3.2 */ - static const QString ACTIVE_CURRENT_SELECTION_NAME(); // = "selection"(); + static const QString ACTIVE_CURRENT_SELECTION_NAME(); /** * The priority given when the source includes the current menu. - * @since 3.2 */ - static int ACTIVE_MENU(); // = 1 << 31(); + static int ACTIVE_MENU(); // = 1 << 30(); /** * The variable name for the active menu. This is for use with the * {@link ISourceProvider} and {@link IEvaluationContext}. - * @since 3.2 */ - static const QString ACTIVE_MENU_NAME(); // = "activeMenu"(); + static const QString ACTIVE_MENU_NAME(); /** * The variable name for the local selection, available while a * context menu is visible. - * - * @since 3.3 */ - static const QString ACTIVE_MENU_SELECTION_NAME(); // = "activeMenuSelection"(); + static const QString ACTIVE_MENU_SELECTION_NAME(); /** * The variable name for the local editor input which is sometimes * available while a context menu is visible. - * - * @since 3.3 */ - static const QString ACTIVE_MENU_EDITOR_INPUT_NAME(); // = "activeMenuEditorInput"(); + static const QString ACTIVE_MENU_EDITOR_INPUT_NAME(); /** * The variable name for the active focus Control, when provided by the * IFocusService. - * - * @since 3.3 */ - static const QString ACTIVE_FOCUS_CONTROL_NAME(); // = "activeFocusControl"(); + static const QString ACTIVE_FOCUS_CONTROL_NAME(); /** * The variable name for the active focus Control id, when provided by the * IFocusService. - * - * @since 3.3 */ - static const QString ACTIVE_FOCUS_CONTROL_ID_NAME(); // = "activeFocusControlId"(); + static const QString ACTIVE_FOCUS_CONTROL_ID_NAME(); }; } #endif /*BERRYISOURCES_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIStructuredSelection.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIStructuredSelection.h index 3c625210f2..71d287b808 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIStructuredSelection.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIStructuredSelection.h @@ -1,88 +1,88 @@ /*=================================================================== 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 BERRYISTRUCTUREDSELECTION_H_ #define BERRYISTRUCTUREDSELECTION_H_ #include "berryISelection.h" #include #include namespace berry { /** * A selection containing elements. */ struct BERRY_UI_QT IStructuredSelection : public ISelection { typedef ObjectList ContainerType; typedef ContainerType::const_iterator iterator; - berryInterfaceMacro(IStructuredSelection, berry) + berryObjectMacro(berry::IStructuredSelection) /** * Returns the first element in this selection, or null * if the selection is empty. * * @return an element, or null if none */ virtual Object::Pointer GetFirstElement() const = 0; /** * Returns an iterator to the beginning of the elements of this selection. * * @return an iterator over the selected elements */ virtual iterator Begin() const = 0; /** * Returns an iterator to the end of the elements of this selection. * * @return an iterator over the selected elements */ virtual iterator End() const = 0; /** * Returns the number of elements selected in this selection. * * @return the number of elements selected */ virtual int Size() const = 0; /** * Returns the elements in this selection as a vector. * * @return the selected elements as a vector */ virtual ContainerType::Pointer ToVector() const = 0; /* * We need to define at least the destructor in this compilation unit * because of the export macro above. Otherwise Windows throws * a linker error in dependent librraies. The export macro is needed * for gcc < 4.5 to correctly mark the type_info object of this class * as visible (we have default visibility 'hidden') so that dynamic_cast calls work. */ virtual ~IStructuredSelection(); }; } #endif /* BERRYISTRUCTUREDSELECTION_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewCategory.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewCategory.h index a231857fc0..6a3d267a31 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewCategory.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewCategory.h @@ -1,45 +1,45 @@ /*=================================================================== 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 BERRYIVIEWCATEGORY_H_ #define BERRYIVIEWCATEGORY_H_ #include "berryIViewDescriptor.h" #include namespace berry { /** * \ingroup org_blueberry_ui_qt * */ struct BERRY_UI_QT IViewCategory : public Object { - berryInterfaceMacro(IViewCategory, berry); + berryObjectMacro(berry::IViewCategory) virtual QString GetId() const = 0; virtual QString GetLabel() const = 0; virtual QStringList GetPath() const = 0; virtual QList GetViews() const = 0; virtual ~IViewCategory(); }; } #endif /*BERRYIVIEWCATEGORY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewDescriptor.h index c95eb1abb3..8d34d15f69 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewDescriptor.h @@ -1,107 +1,109 @@ /*=================================================================== 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 BERRYIVIEWDESCRIPTOR_H_ #define BERRYIVIEWDESCRIPTOR_H_ #include #include "berryIWorkbenchPartDescriptor.h" #include "berryIViewPart.h" #include #include #include "berryImageDescriptor.h" #include #include namespace berry { + /** * \ingroup org_blueberry_ui_qt * * This is a view descriptor. It provides a "description" of a given * given view so that the view can later be constructed. *

* The view registry provides facilities to map from an extension * to a IViewDescriptor. *

*

* This interface is not intended to be implemented by clients. *

* * @see org.blueberry.ui.IViewRegistry */ struct BERRY_UI_QT IViewDescriptor : public IWorkbenchPartDescriptor, public IAdaptable { - berryInterfaceMacro(IViewDescriptor, berry); + + berryObjectMacro(berry::IViewDescriptor) ~IViewDescriptor(); /** * Creates an instance of the view defined in the descriptor. * * @return the view part * @throws CoreException thrown if there is a problem creating the part */ virtual IViewPart::Pointer CreateView() = 0; - virtual std::vector< std::string> GetKeywordReferences() const = 0; /** * Returns an array of strings that represent * view's category path. This array will be used * for hierarchical presentation of the * view in places like submenus. * @return array of category tokens or null if not specified. */ virtual const QList& GetCategoryPath() const = 0; /** * Returns the description of this view. * * @return the description */ virtual QString GetDescription() const = 0; /** * Returns the descriptor for the icon to show for this view. */ virtual SmartPointer GetImageDescriptor() const = 0; /** * Returns whether this view allows multiple instances. * * @return whether this view allows multiple instances */ virtual bool GetAllowMultiple() const = 0; /** * Returns whether this view can be restored upon workbench restart. * * @return whether whether this view can be restored upon workbench restart */ virtual bool IsRestorable() const = 0; virtual bool operator==(const Object*) const = 0; }; + } #endif /*BERRYIVIEWDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewLayout.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewLayout.h index d66bd24d2d..6dffc9ad18 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewLayout.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewLayout.h @@ -1,92 +1,92 @@ /*=================================================================== 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 BERRYIVIEWLAYOUT_H_ #define BERRYIVIEWLAYOUT_H_ #include #include #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * Represents the layout info for a view or placeholder in an {@link IPageLayout}. *

* This interface is not intended to be implemented by clients. *

* - * @since 3.0 * @noimplement This interface is not intended to be implemented by clients. */ -struct BERRY_UI_QT IViewLayout : public Object { +struct BERRY_UI_QT IViewLayout : public Object +{ - berryInterfaceMacro(IViewLayout, berry); + berryObjectMacro(berry::IViewLayout) virtual ~IViewLayout(); /** * Returns whether the view is closeable. * The default is true. * * @return true if the view is closeable, false if not */ virtual bool IsCloseable() = 0; /** * Sets whether the view is closeable. * * @param closeable true if the view is closeable, false if not */ virtual void SetCloseable(bool closeable) = 0; /** * Returns whether the view is moveable. * The default is true. * * @return true if the view is moveable, false if not */ virtual bool IsMoveable() = 0; /** * Sets whether the view is moveable. * * @param moveable true if the view is moveable, false if not */ virtual void SetMoveable(bool moveable) = 0; /** * Returns whether the view is a standalone view. * * @see IPageLayout#addStandaloneView */ virtual bool IsStandalone() = 0; /** * Returns whether the view shows its title. * This is only applicable to standalone views. * * @see IPageLayout#addStandaloneView */ virtual bool GetShowTitle() = 0; }; } #endif /*BERRYIVIEWLAYOUT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewPart.h index 08281534ed..c1d428b5f8 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewPart.h @@ -1,124 +1,125 @@ /*=================================================================== 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 BERRYIVIEWPART_H_ #define BERRYIVIEWPART_H_ #include #include "berryMacros.h" #include "berryIMemento.h" #include "berryIWorkbenchPart.h" #include "berryIViewSite.h" #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * A view is a visual component within a workbench page. It is typically used to * navigate a hierarchy of information (like the workspace), open an editor, or * display properties for the active editor. Modifications made in a view are * saved immediately (in contrast to an editor part, which conforms to a more * elaborate open-save-close lifecycle). *

* Only one instance of a particular view type may exist within a workbench * page. This policy is designed to simplify part management for a user. *

*

* This interface may be implemented directly. For convenience, a base * implementation is defined in ViewPart. *

*

* A view is added to the workbench in two steps: *

    *
  1. A view extension is contributed to the workbench registry. This * extension defines the extension id and extension class.
  2. *
  3. The view is included in the default layout for a perspective. * Alternatively, the user may open the view from the Perspective menu.
  4. *
*

*

* Views implement the IAdaptable interface; extensions are * managed by the platform's adapter manager. *

*

* As of 3.4, views may optionally adapt to {@link ISizeProvider} if they have * a preferred size. The default presentation will make a best effort to * allocate the preferred size to a view if it is the only part in a stack. If * there is more than one part in the stack, the constraints will be disabled * for that stack. The size constraints are adjusted for the size of the tab and * border trim. Note that this is considered to be a hint to the presentation, * and not all presentations may honor size constraints. *

* * @see IWorkbenchPage#showView * @see org.blueberry.ui.part.ViewPart * @see ISizeProvider */ -struct BERRY_UI_QT IViewPart : public virtual IWorkbenchPart { +struct BERRY_UI_QT IViewPart : public virtual IWorkbenchPart +{ - berryInterfaceMacro(IViewPart, berry); + berryObjectMacro(berry::IViewPart) virtual ~IViewPart(); /** * Returns the site for this view. * This method is equivalent to (IViewSite) getSite(). *

* The site can be null while the view is being initialized. * After the initialization is complete, this value must be non-null * for the remainder of the view's life cycle. *

* * @return the view site; this value may be null if the view * has not yet been initialized */ virtual IViewSite::Pointer GetViewSite() = 0; /** * Initializes this view with the given view site. A memento is passed to * the view which contains a snapshot of the views state from a previous * session. Where possible, the view should try to recreate that state * within the part controls. *

* This method is automatically called by the workbench shortly after the part * is instantiated. It marks the start of the views's lifecycle. Clients must * not call this method. *

* * @param site the view site * @param memento the IViewPart state or null if there is no previous saved state * @exception PartInitException if this view was not initialized successfully */ virtual void Init(IViewSite::Pointer site, IMemento::Pointer memento = IMemento::Pointer(0)) = 0; /** * Saves the object state within a memento. * * @param memento a memento to receive the object state */ virtual void SaveState(IMemento::Pointer memento) = 0; }; } -Q_DECLARE_INTERFACE(berry::IViewPart, "org.blueberry.IViewPart") +Q_DECLARE_INTERFACE(berry::IViewPart, "org.blueberry.ui.IViewPart") #endif /*BERRYIVIEWPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewReference.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewReference.h index b067d9b551..a6334e853f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewReference.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewReference.h @@ -1,60 +1,60 @@ /*=================================================================== 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 BERRYIVIEWREFERENCE_H_ #define BERRYIVIEWREFERENCE_H_ #include "berryIWorkbenchPartReference.h" #include "berryIViewPart.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * Defines a reference to an IViewPart. *

* This interface is not intended to be implemented by clients. *

*/ struct BERRY_UI_QT IViewReference : virtual public IWorkbenchPartReference { - berryInterfaceMacro(IViewReference, berry) + berryObjectMacro(berry::IViewReference) ~IViewReference(); /** * Returns the secondary ID for the view. * * @return the secondary ID, or null if there is no secondary id * @see IWorkbenchPage#showView(String, String, int) * @since 3.0 */ virtual QString GetSecondaryId() = 0; /** * Returns the IViewPart referenced by this object. * Returns null if the view was not instantiated or * it failed to be restored. Tries to restore the view * if restore is true. */ virtual IViewPart::Pointer GetView(bool restore) = 0; }; } // namespace berry #endif /*BERRYIVIEWREFERENCE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewSite.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewSite.h index e498799f8a..e53e8e29f5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewSite.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewSite.h @@ -1,62 +1,62 @@ /*=================================================================== 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 BERRYIVIEWSITE_H_ #define BERRYIVIEWSITE_H_ #include "berryIWorkbenchPartSite.h" #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * The primary interface between a view part and the workbench. *

* The workbench exposes its implemention of view part sites via this interface, * which is not intended to be implemented or extended by clients. *

* @noimplement This interface is not intended to be implemented by clients. */ -struct BERRY_UI_QT IViewSite : public virtual IWorkbenchPartSite { +struct BERRY_UI_QT IViewSite : public virtual IWorkbenchPartSite +{ - berryInterfaceMacro(IViewSite, berry); + berryObjectMacro(berry::IViewSite) virtual ~IViewSite(); /** * Returns the action bars for this part site. * Views have exclusive use of their site's action bars. * * @return the action bars */ //IActionBars getActionBars(); /** * Returns the secondary id for this part site's part, * or null if it has none. * * @see IWorkbenchPage#showView(String, String, int) - * @since 3.0 */ virtual QString GetSecondaryId() = 0; }; } #endif /*BERRYIVIEWSITE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWindowListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWindowListener.cpp index 4a66d63adf..41774cfdf6 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWindowListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWindowListener.cpp @@ -1,45 +1,49 @@ /*=================================================================== 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 "berryIWindowListener.h" namespace berry { void IWindowListener::Events -::AddListener(IWindowListener::Pointer listener) +::AddListener(IWindowListener* listener) { - if (listener.IsNull()) return; + if (listener == NULL) return; - windowActivated += Delegate(listener.GetPointer(), &IWindowListener::WindowActivated); - windowDeactivated += Delegate(listener.GetPointer(), &IWindowListener::WindowDeactivated); - windowClosed += Delegate(listener.GetPointer(), &IWindowListener::WindowClosed); - windowOpened += Delegate(listener.GetPointer(), &IWindowListener::WindowOpened); + windowActivated += Delegate(listener, &IWindowListener::WindowActivated); + windowDeactivated += Delegate(listener, &IWindowListener::WindowDeactivated); + windowClosed += Delegate(listener, &IWindowListener::WindowClosed); + windowOpened += Delegate(listener, &IWindowListener::WindowOpened); } void IWindowListener::Events -::RemoveListener(IWindowListener::Pointer listener) +::RemoveListener(IWindowListener* listener) { - if (listener.IsNull()) return; + if (listener == NULL) return; - windowActivated -= Delegate(listener.GetPointer(), &IWindowListener::WindowActivated); - windowDeactivated -= Delegate(listener.GetPointer(), &IWindowListener::WindowDeactivated); - windowClosed -= Delegate(listener.GetPointer(), &IWindowListener::WindowClosed); - windowOpened -= Delegate(listener.GetPointer(), &IWindowListener::WindowOpened); + windowActivated -= Delegate(listener, &IWindowListener::WindowActivated); + windowDeactivated -= Delegate(listener, &IWindowListener::WindowDeactivated); + windowClosed -= Delegate(listener, &IWindowListener::WindowClosed); + windowOpened -= Delegate(listener, &IWindowListener::WindowOpened); +} + +IWindowListener::~IWindowListener() +{ } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWindowListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWindowListener.h index 753928e7d4..cc94cb605b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWindowListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWindowListener.h @@ -1,99 +1,99 @@ /*=================================================================== 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 BERRYIWINDOWLISTENER_H_ #define BERRYIWINDOWLISTENER_H_ #include -#include #include #include "berryIWorkbenchWindow.h" namespace berry { /** * Interface for listening to window lifecycle events. *

* This interface may be implemented by clients. *

*/ -struct BERRY_UI_QT IWindowListener : public virtual Object { - - berryInterfaceMacro(IWindowListener, berry); +struct BERRY_UI_QT IWindowListener +{ struct Events { - typedef Message1 WindowEvent; + typedef Message1 WindowEvent; WindowEvent windowActivated; WindowEvent windowDeactivated; WindowEvent windowClosed; WindowEvent windowOpened; - void AddListener(IWindowListener::Pointer listener); - void RemoveListener(IWindowListener::Pointer listener); + void AddListener(IWindowListener* listener); + void RemoveListener(IWindowListener* listener); private: - typedef MessageDelegate1 Delegate; + typedef MessageDelegate1 Delegate; }; + virtual ~IWindowListener(); + /** * Notifies this listener that the given window has been activated. *

* Note: This event is not fired if no perspective is * open (the window is empty). *

* * @param window the window that was activated */ - virtual void WindowActivated(IWorkbenchWindow::Pointer /*window*/) {}; + virtual void WindowActivated(const IWorkbenchWindow::Pointer& /*window*/) {} /** * Notifies this listener that the given window has been deactivated. *

* Note: This event is not fired if no perspective is * open (the window is empty). *

* * @param window the window that was activated */ - virtual void WindowDeactivated(IWorkbenchWindow::Pointer /*window*/) {}; + virtual void WindowDeactivated(const IWorkbenchWindow::Pointer& /*window*/) {} /** * Notifies this listener that the given window has been closed. * * @param window the window that was closed * @see IWorkbenchWindow#close */ - virtual void WindowClosed(IWorkbenchWindow::Pointer /*window*/) {}; + virtual void WindowClosed(const IWorkbenchWindow::Pointer& /*window*/) {} /** * Notifies this listener that the given window has been opened. * * @param window the window that was opened * @see IWorkbench#openWorkbenchWindow */ - virtual void WindowOpened(IWorkbenchWindow::Pointer /*window*/) {}; + virtual void WindowOpened(const IWorkbenchWindow::Pointer& /*window*/) {} }; } #endif /* BERRYIWINDOWLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbench.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbench.h index cd3ad8fe5e..08257c56ef 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbench.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbench.h @@ -1,400 +1,400 @@ /*=================================================================== 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 BERRYIWORKBENCH_H_ #define BERRYIWORKBENCH_H_ #include #include "services/berryIServiceLocator.h" #include "dialogs/berryIDialog.h" #include "berryIViewRegistry.h" #include "berryIEditorRegistry.h" #include "intro/berryIIntroManager.h" #include "berryIPerspectiveRegistry.h" #include "berryIWorkbenchWindow.h" #include "berryIWorkbenchListener.h" #include "berryIWindowListener.h" #include "berryDisplay.h" namespace berry { struct IWorkbenchPage; /** * \ingroup org_blueberry_ui_qt * * A workbench is the root object for the BlueBerry Platform user interface. *

* A workbench has one or more main windows which present to the end * user information based on some underlying model, typically on resources in an * underlying workspace. A workbench usually starts with a single open window, * and automatically closes when its last window closes. *

*

* Each workbench window has a collection of pages; the active * page is the one that is being presented to the end user; at most one page is * active in a window at a time. *

*

* Each workbench page has a collection of workbench parts, of which * there are two kinds: views and editors. A page's parts are arranged (tiled or * stacked) for presentation on the screen. The arrangement is not fixed; the * user can arrange the parts as they see fit. A perspective is a * template for a page, capturing a collection of parts and their arrangement. *

*

* The platform creates a workbench when the workbench plug-in is activated; * since this happens at most once during the life of the running platform, * there is only one workbench instance. Due to its singular nature, it is * commonly referred to as the workbench. *

*

* The workbench supports a few {@link IServiceLocator services} by default. If * these services are used to allocate resources, it is important to remember to * clean up those resources after you are done with them. Otherwise, the * resources will exist until the workbench shuts down. The supported services * are: *

*
    *
  • {@link IBindingService}
  • *
  • {@link ICommandService}
  • *
  • {@link IContextService}
  • *
  • {@link IHandlerService}
  • *
*

* This interface is not intended to be implemented by clients. *

* * @see PlatformUI#getWorkbench * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IWorkbench : public IServiceLocator { - berryInterfaceMacro(IWorkbench, berry); + berryObjectMacro(berry::IWorkbench) virtual ~IWorkbench(); /** * Returns the display for this workbench. *

* Code should always ask the workbench for the display rather than rely on * {@link Display#getDefault Display.getDefault()}. *

* * @return the display to be used for all UI interactions with this * workbench */ virtual Display* GetDisplay() = 0; /** * Adds a workbench listener. * * @param listener * the workbench listener to add * @since 3.2 */ - virtual void AddWorkbenchListener(IWorkbenchListener::Pointer listener) = 0; + virtual void AddWorkbenchListener(IWorkbenchListener* listener) = 0; /** * Removes a workbench listener. * * @param listener * the workbench listener to remove * @since 3.2 */ - virtual void RemoveWorkbenchListener(IWorkbenchListener::Pointer listener) = 0; + virtual void RemoveWorkbenchListener(IWorkbenchListener* listener) = 0; /** * Returns the workbench events object */ virtual IWorkbenchListener::Events& GetWorkbenchEvents() = 0; /** * Adds a window listener. * * @param listener * the window listener to add * @since 2.0 */ - virtual void AddWindowListener(IWindowListener::Pointer listener) = 0; + virtual void AddWindowListener(IWindowListener* listener) = 0; /** * Removes a window listener. * * @param listener * the window listener to remove * @since 2.0 */ - virtual void RemoveWindowListener(IWindowListener::Pointer listener) = 0; + virtual void RemoveWindowListener(IWindowListener* listener) = 0; /** * Returns the window events object * */ virtual IWindowListener::Events& GetWindowEvents() = 0; /** * Closes this workbench and all its open windows. *

* If the workbench has an open editor with unsaved content, the user will * be given the opportunity to save it. *

* * @return true if the workbench was successfully closed, and * false if it is still open */ virtual bool Close() = 0; /** * Returns the currently active window for this workbench (if any). Returns * null if there is no active workbench window. Returns * null if called from a non-UI thread. * * @return the active workbench window, or null if there is * no active workbench window or if called from a non-UI thread */ - virtual IWorkbenchWindow::Pointer GetActiveWorkbenchWindow() = 0; + virtual IWorkbenchWindow::Pointer GetActiveWorkbenchWindow() const = 0; /** * Returns the perspective registry for the workbench. * * @return the workbench perspective registry */ virtual IPerspectiveRegistry* GetPerspectiveRegistry() = 0; /** * Returns the view registry for the workbench. * * @return the workbench view registry * @since 3.1 */ virtual IViewRegistry* GetViewRegistry() = 0; /** * Returns the editor registry for the workbench. * * @return the workbench editor registry */ virtual IEditorRegistry* GetEditorRegistry() = 0; /** * Returns the number of open main windows associated with this workbench. * Note that wizards and dialogs are not included in this list since they * are not considered main windows. * * @return the number of open windows * @since 3.0 */ virtual std::size_t GetWorkbenchWindowCount() = 0; /** * Returns a list of the open main windows associated with this workbench. * Note that wizards and dialogs are not included in this list since they * are not considered main windows. * * @return a list of open windows */ virtual QList GetWorkbenchWindows() = 0; /** * Creates and opens a new workbench window with one page. The perspective * of the new page is defined by the specified perspective ID. The new * window and new page become active. *

* Note: The caller is responsible to ensure the action using this * method will explicitly inform the user a new window will be opened. * Otherwise, callers are strongly recommended to use the * openPerspective APIs to programmatically show a * perspective to avoid confusing the user. *

*

* In most cases where this method is used the caller is tightly coupled to * a particular perspective. They define it in the registry and contribute * some user interface action to open or activate it. In situations like * this a static variable is often used to identify the perspective ID. *

* * @param perspectiveId * the perspective id for the window's initial page, or * null for no initial page * @param input * the page input, or null if there is no current * input. This is used to seed the input for the new page's * views. * @return the new workbench window * @exception WorkbenchException * if a new window and page could not be opened * * @see IWorkbench#showPerspective(String, IWorkbenchWindow, IAdaptable) */ virtual IWorkbenchWindow::Pointer OpenWorkbenchWindow(const QString& perspectiveId, IAdaptable* input) = 0; /** * Creates and opens a new workbench window with one page. The perspective * of the new page is defined by the default perspective ID. The new window * and new page become active. *

* Note: The caller is responsible to ensure the action using this * method will explicitly inform the user a new window will be opened. * Otherwise, callers are strongly recommended to use the * openPerspective APIs to programmatically show a * perspective to avoid confusing the user. *

* * @param input * the page input, or null if there is no current * input. This is used to seed the input for the new page's * views. * @return the new workbench window * @exception WorkbenchException * if a new window and page could not be opened * * @see IWorkbench#showPerspective(String, IWorkbenchWindow, IAdaptable) */ virtual IWorkbenchWindow::Pointer OpenWorkbenchWindow(IAdaptable* input) = 0; /** * Shows the specified perspective to the user. The caller should use this * method when the perspective to be shown is not dependent on the page's * input. That is, the perspective can open in any page depending on user * preferences. *

* The perspective may be shown in the specified window, in another existing * window, or in a new window depending on user preferences. The exact * policy is controlled by the workbench to ensure consistency to the user. * The policy is subject to change. The current policy is as follows: *

    *
  • If the specified window has the requested perspective open, then the * window is given focus and the perspective is shown. The page's input is * ignored.
  • *
  • If another window that has the workspace root as input and the * requested perspective open and active, then the window is given focus. *
  • *
  • Otherwise the requested perspective is opened and shown in the * specified window or in a new window depending on the current user * preference for opening perspectives, and that window is given focus. *
  • *
*

*

* The workbench also defines a number of menu items to activate or open * each registered perspective. A complete list of these perspectives is * available from the perspective registry found on IWorkbench. *

* * @param perspectiveId * the perspective ID to show * @param window * the workbench window of the action calling this method. * @return the workbench page that the perspective was shown * @exception WorkbenchException * if the perspective could not be shown * * @since 2.0 */ virtual SmartPointer ShowPerspective(const QString& perspectiveId, IWorkbenchWindow::Pointer window) = 0; /** * Shows the specified perspective to the user. The caller should use this * method when the perspective to be shown is dependent on the page's input. * That is, the perspective can only open in any page with the specified * input. *

* The perspective may be shown in the specified window, in another existing * window, or in a new window depending on user preferences. The exact * policy is controlled by the workbench to ensure consistency to the user. * The policy is subject to change. The current policy is as follows: *

    *
  • If the specified window has the requested perspective open and the * same requested input, then the window is given focus and the perspective * is shown.
  • *
  • If another window has the requested input and the requested * perspective open and active, then that window is given focus.
  • *
  • If the specified window has the same requested input but not the * requested perspective, then the window is given focus and the perspective * is opened and shown on condition that the user preference is not to open * perspectives in a new window.
  • *
  • Otherwise the requested perspective is opened and shown in a new * window, and the window is given focus.
  • *
*

*

* The workbench also defines a number of menu items to activate or open * each registered perspective. A complete list of these perspectives is * available from the perspective registry found on IWorkbench. *

* * @param perspectiveId * the perspective ID to show * @param window * the workbench window of the action calling this method. * @param input * the page input, or null if there is no current * input. This is used to seed the input for the page's views * @return the workbench page that the perspective was shown * @exception WorkbenchException * if the perspective could not be shown * * @since 2.0 */ virtual SmartPointer ShowPerspective(const QString& perspectiveId, IWorkbenchWindow::Pointer window, IAdaptable* input) = 0; /** * Save all dirty editors in the workbench. Opens a dialog to prompt the * user if confirm is true. Return true if successful. Return * false if the user has canceled the command. * * @param confirm true to ask the user before saving unsaved * changes (recommended), and false to save * unsaved changes without asking * @return true if the command succeeded, and * false if the operation was canceled by the user or * an error occurred while saving */ virtual bool SaveAllEditors(bool confirm) = 0; /** * Return the intro manager for this workbench. * * @return the intro manager for this workbench. Guaranteed not to be * null. */ virtual IIntroManager* GetIntroManager() = 0; /** * Returns a boolean indicating whether the workbench is in the process of * closing. * * @return true if the workbench is in the process of * closing, false otherwise * @since 3.1 */ virtual bool IsClosing() = 0; /** * Applies changes of the current theme to the user interface. */ virtual void UpdateTheme() = 0; }; } #endif /*BERRYIWORKBENCH_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchListener.cpp index abf5dec244..edcf744649 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchListener.cpp @@ -1,41 +1,45 @@ /*=================================================================== 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 "berryIWorkbenchListener.h" namespace berry { void IWorkbenchListener::Events -::AddListener(IWorkbenchListener::Pointer listener) +::AddListener(IWorkbenchListener* listener) { - if (listener.IsNull()) return; + if (listener == NULL) return; - preShutdown += Delegate2(listener.GetPointer(), &IWorkbenchListener::PreShutdown); - postShutdown += Delegate1(listener.GetPointer(), &IWorkbenchListener::PostShutdown); + preShutdown += Delegate2(listener, &IWorkbenchListener::PreShutdown); + postShutdown += Delegate1(listener, &IWorkbenchListener::PostShutdown); } void IWorkbenchListener::Events -::RemoveListener(IWorkbenchListener::Pointer listener) +::RemoveListener(IWorkbenchListener* listener) { - if (listener.IsNull()) return; + if (listener == NULL) return; - preShutdown -= Delegate2(listener.GetPointer(), &IWorkbenchListener::PreShutdown); - postShutdown -= Delegate1(listener.GetPointer(), &IWorkbenchListener::PostShutdown); + preShutdown -= Delegate2(listener, &IWorkbenchListener::PreShutdown); + postShutdown -= Delegate1(listener, &IWorkbenchListener::PostShutdown); +} + +IWorkbenchListener::~IWorkbenchListener() +{ } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchListener.h index 85249e0acd..3a5951b9e5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchListener.h @@ -1,101 +1,99 @@ /*=================================================================== 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 BERRYIWORKBENCHLISTENER_H_ #define BERRYIWORKBENCHLISTENER_H_ #include -#include -#include -#include +#include "berryMessage.h" namespace berry { struct IWorkbench; /** * Interface for listening to workbench lifecycle events. *

* This interface may be implemented by clients. *

* * @see IWorkbench#addWorkbenchListener * @see IWorkbench#removeWorkbenchListener - * @since 3.2 */ -struct BERRY_UI_QT IWorkbenchListener : public virtual Object { - - berryInterfaceMacro(IWorkbenchListener, berry); +struct BERRY_UI_QT IWorkbenchListener +{ struct Events { typedef Message2 PreShutdownEvent; typedef Message1 PostShutdownEvent; PreShutdownEvent preShutdown; PostShutdownEvent postShutdown; - void AddListener(IWorkbenchListener::Pointer listener); - void RemoveListener(IWorkbenchListener::Pointer listener); + void AddListener(IWorkbenchListener* listener); + void RemoveListener(IWorkbenchListener* listener); private: typedef MessageDelegate2 Delegate2; typedef MessageDelegate1 Delegate1; }; + virtual ~IWorkbenchListener(); + /** * Notifies that the workbench is about to shut down. *

* This method is called immediately prior to workbench shutdown before any * windows have been closed. *

*

* The listener may veto a regular shutdown by returning false, * although this will be ignored if the workbench is being forced to shut down. *

*

* Since other workbench listeners may veto the shutdown, the listener should * not dispose resources or do any other work during this notification that would * leave the workbench in an inconsistent state. *

* * @param workbench the workbench * @param forced true if the workbench is being forced to shutdown, * false for a regular close * @return true to allow the workbench to proceed with shutdown, * false to veto a non-forced shutdown */ - virtual bool PreShutdown(IWorkbench* /*workbench*/, bool /*forced*/) { return true; }; + virtual bool PreShutdown(IWorkbench* /*workbench*/, bool /*forced*/) { return true; } /** * Performs arbitrary finalization after the workbench stops running. *

* This method is called during workbench shutdown after all windows * have been closed. *

* * @param workbench the workbench */ - virtual void PostShutdown(IWorkbench* /*workbench*/) {}; + virtual void PostShutdown(IWorkbench* /*workbench*/) {} }; } #endif /* BERRYIWORKBENCHLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPage.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPage.h index a72805e870..5a13e28c6e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPage.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPage.h @@ -1,853 +1,854 @@ /*=================================================================== 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 BERRYIWORKBENCHPAGE_H_ #define BERRYIWORKBENCHPAGE_H_ #include #include "berryIEditorReference.h" #include "berryIViewReference.h" #include "berryIPerspectiveDescriptor.h" #include "berryIEditorPart.h" #include "berryIViewPart.h" #include "berryIEditorInput.h" #include "berryIPartService.h" #include "berryISelectionService.h" #include "berryIReusableEditor.h" #include "berryIWorkbenchWindow.h" /** * \ingroup org_blueberry_ui_qt * */ namespace berry { /** * A workbench page consists of an arrangement of views and editors intended to * be presented together to the user in a single workbench window. *

* A page can contain 0 or more views and 0 or more editors. These views and * editors are contained wholly within the page and are not shared with other * pages. The layout and visible action set for the page is defined by a * perspective. *

* The number of views and editors within a page is restricted to simplify part * management for the user. In particular: *

    *
  • Unless a view explicitly allows for multiple instances in its plugin * declaration there will be only one instance in a given workbench page.
  • *
  • Only one editor can exist for each editor input within a page. *
  • *
*

*

* This interface is not intended to be implemented by clients. *

* * @see IPerspectiveDescriptor * @see IEditorPart * @see IViewPart */ -struct BERRY_UI_QT IWorkbenchPage : public IPartService, public ISelectionService, public Object { +struct BERRY_UI_QT IWorkbenchPage : public IPartService, public ISelectionService, public Object +{ - berryInterfaceMacro(IWorkbenchPage, berry) + berryObjectMacro(berry::IWorkbenchPage) ~IWorkbenchPage(); /** * An optional attribute within a workspace marker (IMarker) * which identifies the preferred editor type to be opened when * openEditor is called. * * @see #openEditor(IEditorInput, String) * @see #openEditor(IEditorInput, String, boolean) * @deprecated in 3.0 since the notion of markers this is not generally * applicable. Use the IDE-specific constant * IDE.EDITOR_ID_ATTR. */ static const QString EDITOR_ID_ATTR; // = "org.blueberry.ui.editorID"; /** * Change event id when the perspective is reset to its original state. * * @see IPerspectiveListener */ static const QString CHANGE_RESET; // = "reset"; /** * Change event id when the perspective has completed a reset to its * original state. * * @since 3.0 * @see IPerspectiveListener */ static const QString CHANGE_RESET_COMPLETE; // = "resetComplete"; /** * Change event id when one or more views are shown in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_VIEW_SHOW; // = "viewShow"; /** * Change event id when one or more views are hidden in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_VIEW_HIDE; // = "viewHide"; /** * Change event id when one or more editors are opened in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_EDITOR_OPEN; // = "editorOpen"; /** * Change event id when one or more editors are closed in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_EDITOR_CLOSE; // = "editorClose"; /** * Change event id when the editor area is shown in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_EDITOR_AREA_SHOW; // = "editorAreaShow"; /** * Change event id when the editor area is hidden in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_EDITOR_AREA_HIDE; // = "editorAreaHide"; /** * Change event id when an action set is shown in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_ACTION_SET_SHOW; // = "actionSetShow"; /** * Change event id when an action set is hidden in a perspective. * * @see IPerspectiveListener */ static const QString CHANGE_ACTION_SET_HIDE; // = "actionSetHide"; /** * Show view mode that indicates the view should be made visible and * activated. Use of this mode has the same effect as calling * {@link #showView(String)}. */ static const int VIEW_ACTIVATE; // = 1; /** * Show view mode that indicates the view should be made visible. If the * view is opened in the container that contains the active view then this * has the same effect as VIEW_CREATE. */ static const int VIEW_VISIBLE; // = 2; /** * Show view mode that indicates the view should be made created but not * necessarily be made visible. It will only be made visible in the event * that it is opened in its own container. In other words, only if it is not * stacked with another view. */ static const int VIEW_CREATE; // = 3; /** * Editor opening match mode specifying that no matching against existing * editors should be done. */ static const int MATCH_NONE; // = 0; /** * Editor opening match mode specifying that the editor input should be * considered when matching against existing editors. */ static const int MATCH_INPUT; // = 1; /** * Editor opening match mode specifying that the editor id should be * considered when matching against existing editors. */ static const int MATCH_ID; // = 2; /** * Activates the given part. The part will be brought to the front and given * focus. The part must belong to this page. * * @param part * the part to activate */ virtual void Activate(IWorkbenchPart::Pointer part) = 0; /** * Adds a property change listener. * * @param listener * the property change listener to add */ //virtual void addPropertyChangeListener(IPropertyChangeListener listener); /** * Moves the given part forward in the Z order of this page so as to make it * visible, without changing which part has focus. The part must belong to * this page. * * @param part * the part to bring forward */ virtual void BringToTop(IWorkbenchPart::Pointer part) = 0; /** * Closes this workbench page. If this page is the active one, this honor is * passed along to one of the window's other pages if possible. *

* If the page has an open editor with unsaved content, the user will be * given the opportunity to save it. *

* * @return true if the page was successfully closed, and * false if it is still open */ virtual bool Close() = 0; /** * Closes all of the editors belonging to this workbench page. *

* If the page has open editors with unsaved content and save * is true, the user will be given the opportunity to save * them. *

* * @param save * * @return true if all editors were successfully closed, and * false if at least one is still open */ virtual bool CloseAllEditors(bool save) = 0; /** * Closes the given Array of editor references. The editors * must belong to this workbench page. *

* If any of the editors have unsaved content and save is * true, the user will be given the opportunity to save * them. *

* * @param editorRefs * the editors to close * @param save * true to save the editor contents if required * (recommended), and false to discard any unsaved * changes * @return true if the editors were successfully closed, and * false if the editors are still open */ virtual bool CloseEditors(const QList& editorRefs, bool save) = 0; /** * Closes the given editor. The editor must belong to this workbench page. *

* If the editor has unsaved content and save is * true, the user will be given the opportunity to save it. *

* * @param editor * the editor to close * @param save * true to save the editor contents if required * (recommended), and false to discard any unsaved * changes * @return true if the editor was successfully closed, and * false if the editor is still open */ virtual bool CloseEditor(IEditorPart::Pointer editor, bool save) = 0; /** * Returns the view in this page with the specified id. There is at most one * view in the page with the specified id. * * @param viewId * the id of the view extension to use * @return the view, or null if none is found */ virtual IViewPart::Pointer FindView(const QString& viewId) = 0; /** * Returns the view reference with the specified id. * * @param viewId * the id of the view extension to use * @return the view reference, or null if none is found */ virtual IViewReference::Pointer FindViewReference(const QString& viewId) = 0; /** * Returns the view reference with the specified id and secondary id. * * @param viewId * the id of the view extension to use * @param secondaryId * the secondary id to use, or null for no * secondary id * @return the view reference, or null if none is found */ virtual IViewReference::Pointer FindViewReference(const QString& viewId, const QString& secondaryId) = 0; /** * Returns the active editor open in this page. *

* This is the visible editor on the page, or, if there is more than one * visible editor, this is the one most recently brought to top. *

* * @return the active editor, or null if no editor is active */ virtual IEditorPart::Pointer GetActiveEditor() = 0; /** * Returns the editor with the specified input. Returns null if there is no * opened editor with that input. * * @param input * the editor input * @return an editor with input equals to input */ virtual IEditorPart::Pointer FindEditor(IEditorInput::Pointer input) = 0; /** * Returns an array of editor references that match the given input and/or * editor id, as specified by the given match flags. Returns an empty array * if there are no matching editors, or if matchFlags is MATCH_NONE. * * @param input * the editor input, or null if MATCH_INPUT is not * specified in matchFlags * @param editorId * the editor id, or null if MATCH_ID is not * specified in matchFlags * @param matchFlags * a bit mask consisting of zero or more of the MATCH_* constants * OR-ed together * @return the references for the matching editors * * @see #MATCH_NONE * @see #MATCH_INPUT * @see #MATCH_ID */ virtual QList FindEditors(IEditorInput::Pointer input, const QString& editorId, int matchFlags) = 0; /** * Returns a list of the editors open in this page. *

* Note that each page has its own editors; editors are never shared between * pages. *

* * @return a list of open editors * * @deprecated use #getEditorReferences() instead */ virtual QList GetEditors() = 0; /** * Returns an array of references to open editors in this page. *

* Note that each page has its own editors; editors are never shared between * pages. *

* * @return a list of open editors */ virtual QList GetEditorReferences() = 0; /** * Returns a list of dirty editors in this page. * * @return a list of dirty editors */ virtual QList GetDirtyEditors() = 0; /** * Returns the input for this page. * * @return the input for this page, or null if none */ virtual IAdaptable* GetInput() = 0; /** * Returns the page label. This will be a unique identifier within the * containing workbench window. * * @return the page label */ virtual QString GetLabel() = 0; /** * Returns the current perspective descriptor for this page, or * null if there is no current perspective. * * @return the current perspective descriptor or null * @see #setPerspective * @see #savePerspective */ virtual IPerspectiveDescriptor::Pointer GetPerspective() = 0; /** * Returns a list of the reference to views visible on this page. *

* Note that each page has its own views; views are never shared between * pages. *

* * @return a list of references to visible views */ virtual QList GetViewReferences() = 0; /** * Returns a list of the views visible on this page. *

* Note that each page has its own views; views are never shared between * pages. *

* * @return a list of visible views * * @deprecated use #getViewReferences() instead. */ virtual QList GetViews() = 0; /** * Returns the workbench window of this page. * * @return the workbench window */ virtual IWorkbenchWindow::Pointer GetWorkbenchWindow() = 0; /** * Hides the given view. The view must belong to this page. * * @param view * the view to hide */ virtual void HideView(IViewPart::Pointer view) = 0; /** * Hides the given view that belongs to the reference, if any. * * @param view * the references whos view is to be hidden */ virtual void HideView(IViewReference::Pointer view) = 0; /** * Returns true if perspective with given id contains view with given id */ virtual bool HasView(const std::string& perspectiveId, const std::string& viewId) = 0; /** * Returns whether the specified part is visible. * * @param part * the part to test * @return boolean true if part is visible */ virtual bool IsPartVisible(IWorkbenchPart::Pointer part) = 0; /** * Removes the perspective specified by desc. * * @param desc * the perspective that will be removed */ virtual void RemovePerspective(IPerspectiveDescriptor::Pointer desc) = 0; /** * Reuses the specified editor by setting its new input. * * @param editor * the editor to be reused * @param input * the new input for the reusable editor */ virtual void ReuseEditor(IReusableEditor::Pointer editor, IEditorInput::Pointer input) = 0; /** * Opens an editor on the given input. *

* If this page already has an editor open on the target input that editor * is activated; otherwise, a new editor is opened. Two editor inputs, * input1 and input2, are considered the same if * *

    * input1.equals(input2) == true
    * 
. *

*

* The editor type is determined by mapping editorId to an * editor extension registered with the workbench. An editor id is passed * rather than an editor object to prevent the accidental creation of more * than one editor for the same input. It also guarantees a consistent * lifecycle for editors, regardless of whether they are created by the user * or restored from saved data. *

* * @param input * the editor input * @param editorId * the id of the editor extension to use * @return an open and active editor, or null if an external * editor was opened * @exception PartInitException * if the editor could not be created or initialized */ virtual IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorId) = 0; /** * Opens an editor on the given input. *

* If this page already has an editor open on the target input that editor * is brought to the front; otherwise, a new editor is opened. Two editor * inputs are considered the same if they equal. See * Object.equals(Object) * and IEditorInput. If activate == true the editor * will be activated. *

* The editor type is determined by mapping editorId to an editor * extension registered with the workbench. An editor id is passed rather than * an editor object to prevent the accidental creation of more than one editor * for the same input. It also guarantees a consistent lifecycle for editors, * regardless of whether they are created by the user or restored from saved * data. *

* * @param input the editor input * @param editorId the id of the editor extension to use * @param activate if true the editor will be activated * @return an open editor, or null if an external editor was opened * @exception PartInitException if the editor could not be created or initialized */ virtual IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorId, bool activate) = 0; /** * Opens an editor on the given input. *

* If this page already has an editor open that matches the given input * and/or editor id (as specified by the matchFlags argument), that editor * is brought to the front; otherwise, a new editor is opened. Two editor * inputs are considered the same if they equal. See * Object.equals(Object) * and IEditorInput. If activate == true the editor * will be activated. *

* The editor type is determined by mapping editorId to an editor * extension registered with the workbench. An editor id is passed rather than * an editor object to prevent the accidental creation of more than one editor * for the same input. It also guarantees a consistent lifecycle for editors, * regardless of whether they are created by the user or restored from saved * data. *

* * @param input the editor input * @param editorId the id of the editor extension to use * @param activate if true the editor will be activated * @param matchFlags a bit mask consisting of zero or more of the MATCH_* constants OR-ed together * @return an open editor, or null if an external editor was opened * @exception PartInitException if the editor could not be created or initialized * * @see #MATCH_NONE * @see #MATCH_INPUT * @see #MATCH_ID */ virtual IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorId, bool activate, int matchFlags) = 0; /** * Removes the property change listener. * * @param listener * the property change listener to remove */ //virtual void removePropertyChangeListener(IPropertyChangeListener listener); /** * Changes the visible views, their layout, and the visible action sets * within the page to match the current perspective descriptor. This is a * rearrangement of components and not a replacement. The contents of the * current perspective descriptor are unaffected. *

* For more information on perspective change see * setPerspective(). *

*/ virtual void ResetPerspective() = 0; /** * Saves the contents of all dirty editors belonging to this workbench page. * If there are no dirty editors this method returns without effect. *

* If confirm is true the user is prompted to * confirm the command. *

*

* Note that as of 3.2, this method also saves views that implement * ISaveablePart and are dirty. *

* * @param confirm true to ask the user before saving unsaved * changes (recommended), and false to save * unsaved changes without asking * @return true if the command succeeded, and * false if the operation was canceled by the user or * an error occurred while saving */ virtual bool SaveAllEditors(bool confirm) = 0; /** * Saves the contents of the given editor if dirty. If not, this method * returns without effect. *

* If confirm is true the user is prompted to * confirm the command. Otherwise, the save happens without prompt. *

*

* The editor must belong to this workbench page. *

* * @param editor * the editor to close * @param confirm * true to ask the user before saving unsaved * changes (recommended), and false to save * unsaved changes without asking * @return true if the command succeeded, and * false if the editor was not saved */ virtual bool SaveEditor(IEditorPart::Pointer editor, bool confirm) = 0; /** * Saves the visible views, their layout, and the visible action sets for * this page to the current perspective descriptor. The contents of the * current perspective descriptor are overwritten. */ virtual void SavePerspective() = 0; /** * Saves the visible views, their layout, and the visible action sets for * this page to the given perspective descriptor. The contents of the given * perspective descriptor are overwritten and it is made the current one for * this page. * * @param perspective * the perspective descriptor to save to */ virtual void SavePerspectiveAs(IPerspectiveDescriptor::Pointer perspective) = 0; /** * Changes the visible views, their layout, and the visible action sets * within the page to match the given perspective descriptor. This is a * rearrangement of components and not a replacement. The contents of the * old perspective descriptor are unaffected. *

* When a perspective change occurs the old perspective is deactivated * (hidden) and cached for future reference. Then the new perspective is * activated (shown). The views within the page are shared by all existing * perspectives to make it easy for the user to switch between one * perspective and another quickly without loss of context. *

*

* During activation the action sets are modified. If an action set is * specified in the new perspective which is not visible in the old one it * will be created. If an old action set is not specified in the new * perspective it will be disposed. *

*

* The visible views and their layout within the page also change. If a view * is specified in the new perspective which is not visible in the old one a * new instance of the view will be created. If an old view is not specified * in the new perspective it will be hidden. This view may reappear if the * user selects it from the View menu or if they switch to a perspective * (which may be the old one) where the view is visible. *

*

* The open editors are not modified by this method. *

* * @param perspective * the perspective descriptor */ virtual void SetPerspective(IPerspectiveDescriptor::Pointer perspective) = 0; /** * Shows the view identified by the given view id in this page and gives it * focus. If there is a view identified by the given view id (and with no * secondary id) already open in this page, it is given focus. * * @param viewId * the id of the view extension to use * @return the shown view * @exception PartInitException * if the view could not be initialized */ virtual IViewPart::Pointer ShowView(const QString& viewId) = 0; /** * Shows a view in this page with the given id and secondary id. The * behaviour of this method varies based on the supplied mode. If * VIEW_ACTIVATE is supplied, the view is focus. If * VIEW_VISIBLE is supplied, then it is made visible but not * given focus. Finally, if VIEW_CREATE is supplied the view * is created and will only be made visible if it is not created in a folder * that already contains visible views. *

* This allows multiple instances of a particular view to be created. They * are disambiguated using the secondary id. If a secondary id is given, the * view must allow multiple instances by having specified * allowMultiple="true" in its extension. *

* * @param viewId * the id of the view extension to use * @param secondaryId * the secondary id to use, or null for no * secondary id * @param mode * the activation mode. Must be {@link #VIEW_ACTIVATE}, * {@link #VIEW_VISIBLE} or {@link #VIEW_CREATE} * @return a view * @exception PartInitException * if the view could not be initialized * @exception IllegalArgumentException * if the supplied mode is not valid */ virtual IViewPart::Pointer ShowView(const QString& viewId, const QString& secondaryId, int mode) = 0; /** * Returns true if the editor is pinned and should not be * reused. * * @param editor * the editor to test * @return boolean whether the editor is pinned */ virtual bool IsEditorPinned(IEditorPart::Pointer editor) = 0; /** * Returns the perspective shortcuts associated with the current * perspective. Returns an empty array if there is no current perspective. * * @see IPageLayout#addPerspectiveShortcut(String) * @return an array of perspective identifiers */ virtual QList GetPerspectiveShortcuts() = 0; /** * Returns the show view shortcuts associated with the current perspective. * Returns an empty array if there is no current perspective. * * @see IPageLayout#addShowViewShortcut(String) * @return an array of view identifiers */ virtual QList GetShowViewShortcuts() = 0; /** * Returns the descriptors for the perspectives that are open in this page, * in the order in which they were opened. * * @return the open perspective descriptors, in order of opening */ virtual QList GetOpenPerspectives() = 0; /** * Returns the descriptors for the perspectives that are open in this page, * in the order in which they were activated (oldest first). * * @return the open perspective descriptors, in order of activation */ virtual QList GetSortedPerspectives() = 0; /** * Closes current perspective. If last perspective, then entire page * is closed. * * @param saveParts * whether the page's parts should be saved if closed * @param closePage * whether the page itself should be closed if last perspective */ virtual void CloseCurrentPerspective(bool saveParts, bool closePage) = 0; /** * Closes the specified perspective in this page. If the last perspective in * this page is closed, then all editors are closed. Views that are not * shown in other perspectives are closed as well. If saveParts * is true, the user will be prompted to save any unsaved * changes for parts that are being closed. The page itself is closed if * closePage is true. * * @param desc * the descriptor of the perspective to be closed * @param saveParts * whether the page's parts should be saved if closed * @param closePage * whether the page itself should be closed if last perspective */ virtual void ClosePerspective(IPerspectiveDescriptor::Pointer desc, bool saveParts, bool closePage) = 0; /** * Closes all perspectives in this page. All editors are closed, prompting * to save any unsaved changes if saveEditors is * true. The page itself is closed if closePage * is true. * * @param saveEditors * whether the page's editors should be saved * @param closePage * whether the page itself should be closed */ virtual void CloseAllPerspectives(bool saveEditors, bool closePage) = 0; /** * Find the part reference for the given part. A convenience method to * quickly go from part to part reference. * * @param part * The part to search for. It can be null. * @return The reference for the given part, or null if no * reference can be found. */ virtual IWorkbenchPartReference::Pointer GetReference(IWorkbenchPart::Pointer part) = 0; }; } // namespace berry #endif /*BERRYIWORKBENCHPAGE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPart.h index b2dc0d6c15..fb9327fe28 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPart.h @@ -1,270 +1,270 @@ /*=================================================================== 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 IWORKBENCHPART_H_ #define IWORKBENCHPART_H_ #include #include "berryIPropertyChangeListener.h" #include namespace berry { struct IWorkbenchPartSite; /** * \ingroup org_blueberry_ui_qt * * A workbench part is a visual component within a workbench page. There * are two subtypes: view and editor, as defined by IViewPart and * IEditorPart. *

* A view is typically used to navigate a hierarchy of information (like the * workspace), open an editor, or display properties for the active editor. * Modifications made in a view are saved immediately. *

* An editor is typically used to edit or browse a document or input object. * The input is identified using an IEditorInput. Modifications made * in an editor part follow an open-save-close lifecycle model. *

* This interface may be implemented directly. For convenience, a base * implementation is defined in WorkbenchPart. *

* The lifecycle of a workbench part is as follows: *

    *
  • When a part extension is created: *
      *
    • instantiate the part
    • *
    • create a part site
    • *
    • call part.init(site)
    • *
    *
  • When a part becomes visible in the workbench: *
      *
    • add part to presentation by calling * part.createControl(parent) to create actual widgets
    • *
    • fire partOpened event to all listeners
    • *
    *
  • *
  • When a part is activated or gets focus: *
      *
    • call part.setFocus()
    • *
    • fire partActivated event to all listeners
    • *
    *
  • *
  • When a part is closed: *
      *
    • if save is needed, do save; if it fails or is canceled return
    • *
    • if part is active, deactivate part
    • *
    • fire partClosed event to all listeners
    • *
    • remove part from presentation; part controls are disposed as part * of the SWT widget tree *
    • call part.dispose()
    • *
    *
  • *
*

*

* After createPartControl has been called, the implementor may * safely reference the controls created. When the part is closed * these controls will be disposed as part of an SWT composite. This * occurs before the IWorkbenchPart.dispose method is called. * If there is a need to free SWT resources the part should define a dispose * listener for its own control and free those resources from the dispose * listener. If the part invokes any method on the disposed SWT controls * after this point an SWTError will be thrown. *

*

* The last method called on IWorkbenchPart is dispose. * This signals the end of the part lifecycle. *

*

* An important point to note about this lifecycle is that following * a call to init, createControl may never be called. Thus in the dispose * method, implementors must not assume controls were created. *

*

* Workbench parts implement the IAdaptable interface; extensions * are managed by the platform's adapter manager. *

* * @see IViewPart * @see IEditorPart */ struct BERRY_UI_QT IWorkbenchPart : public virtual Object { // public IAdaptable { - berryInterfaceMacro(IWorkbenchPart, berry); + berryObjectMacro(berry::IWorkbenchPart) virtual ~IWorkbenchPart(); /** * The property id for getTitle, getTitleImage * and getTitleToolTip. */ //static const int PROP_TITLE = IWorkbenchPartConstants.PROP_TITLE; /** * Adds a listener for changes to properties of this workbench part. * Has no effect if an identical listener is already registered. *

* The property ids are defined in {@link IWorkbenchPartConstants}. *

* * @param listener a property listener */ virtual void AddPropertyListener(IPropertyChangeListener* listener) = 0; /** * Creates the controls for this workbench part. *

* Clients should not call this method (the workbench calls this method when * it needs to, which may be never). *

*

* For implementors this is a multi-step process: *

    *
  1. Create one or more controls within the parent.
  2. *
  3. Set the parent layout as needed.
  4. *
  5. Register any global actions with the site's IActionBars.
  6. *
  7. Register any context menus with the site.
  8. *
  9. Register a selection provider with the site, to make it available to * the workbench's ISelectionService (optional).
  10. *
*

* * @param parent the parent control */ virtual void CreatePartControl(void* parent) = 0; /** * Returns the site for this workbench part. The site can be * null while the workbench part is being initialized. After * the initialization is complete, this value must be non-null * for the remainder of the part's life cycle. * * @return The part site; this value may be null if the part * has not yet been initialized */ virtual SmartPointer GetSite() const = 0; /** * Returns the name of this part. If this value changes the part must fire a * property listener event with {@link IWorkbenchPartConstants#PROP_PART_NAME}. * * @return the name of this view, or the empty string if the name is being managed * by the workbench (not null) */ virtual QString GetPartName() const = 0; /** * Returns the content description of this part. The content description is an optional * user-readable string that describes what is currently being displayed in the part. * By default, the workbench will display the content description in a line * near the top of the view or editor. * An empty string indicates no content description * text. If this value changes the part must fire a property listener event * with {@link IWorkbenchPartConstants#PROP_CONTENT_DESCRIPTION}. * * @return the content description of this part (not null) */ virtual QString GetContentDescription() const = 0; /** * Returns the title image of this workbench part. If this value changes * the part must fire a property listener event with * PROP_TITLE. *

* The title image is usually used to populate the title bar of this part's * visual container. Since this image is managed by the part itself, callers * must not dispose the returned image. *

* * @return the title image */ virtual void* GetTitleImage() const = 0; /** * Returns the title tool tip text of this workbench part. * An empty string result indicates no tool tip. * If this value changes the part must fire a property listener event with * PROP_TITLE. *

* The tool tip text is used to populate the title bar of this part's * visual container. *

* * @return the workbench part title tool tip (not null) */ virtual QString GetTitleToolTip() const = 0; /** * Removes the given property listener from this workbench part. * Has no affect if an identical listener is not registered. * * @param listener a property listener */ virtual void RemovePropertyListener(IPropertyChangeListener* listener) = 0; /** * Return the value for the arbitrary property key, or null. * * @param key * the arbitrary property. Must not be null. * @return the property value, or null. */ virtual QString GetPartProperty(const QString& key) const = 0; /** * Set an arbitrary property on the part. It is the implementor's * responsibility to fire the corresponding PropertyChangeEvent. *

* A default implementation has been added to WorkbenchPart. *

* * @param key * the arbitrary property. Must not be null. * @param value * the property value. A null value will remove * that property. */ virtual void SetPartProperty(const QString& key, const QString& value) = 0; /** * Return an unmodifiable map of the arbitrary properties. This method can * be used to save the properties during workbench save/restore. * * @return A Map of the properties. Must not be null. */ virtual const QHash& GetPartProperties() const = 0; /** * Asks this part to take focus within the workbench. *

* Clients should not call this method (the workbench calls this method at * appropriate times). To have the workbench activate a part, use * IWorkbenchPage.activate(IWorkbenchPart) instead. *

*/ virtual void SetFocus() = 0; }; } // namespace berry #endif /*IWORKBENCHPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartDescriptor.h index b608694aab..cb1abba10d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartDescriptor.h @@ -1,71 +1,71 @@ /*=================================================================== 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 BERRYIWORKBENCHPARTDESCRIPTOR_H_ #define BERRYIWORKBENCHPARTDESCRIPTOR_H_ #include #include #include #include "berryImageDescriptor.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * Description of a workbench part. The part descriptor contains * the information needed to create part instances. *

* This interface is not intended to be implemented by clients. *

*/ struct BERRY_UI_QT IWorkbenchPartDescriptor : public virtual Object { - berryInterfaceMacro(IWorkbenchPartDescriptor, berry); + berryObjectMacro(berry::IWorkbenchPartDescriptor) /** * Returns the part id. * * @return the id of the part */ virtual QString GetId() const = 0; /** * Returns the descriptor of the image for this part. * * @return the descriptor of the image to display next to this part */ virtual SmartPointer GetImageDescriptor() const = 0; /** * Returns the label to show for this part. * * @return the part label */ virtual QString GetLabel() const = 0; virtual ~IWorkbenchPartDescriptor(); }; } // namespace berry #endif /*BERRYIWORKBENCHPARTDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartReference.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartReference.h index 2a3935ec42..5ac92dc8ed 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartReference.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartReference.h @@ -1,152 +1,152 @@ /*=================================================================== 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 BERRYIWORKBENCHPARTREFERENCE_H_ #define BERRYIWORKBENCHPARTREFERENCE_H_ #include #include #include "berryIPropertyChangeListener.h" namespace berry { struct IWorkbenchPart; struct IWorkbenchPage; /** * \ingroup org_blueberry_ui_qt * * Implements a reference to a IWorkbenchPart. * The IWorkbenchPart will not be instanciated until the part * becomes visible or the API getPart is sent with true; *

* This interface is not intended to be implemented by clients. *

*/ struct BERRY_UI_QT IWorkbenchPartReference : public Object { - berryInterfaceMacro(IWorkbenchPartReference, berry) + berryObjectMacro(berry::IWorkbenchPartReference) ~IWorkbenchPartReference(); /** * Returns the IWorkbenchPart referenced by this object. * Returns null if the editors was not instantiated or * it failed to be restored. Tries to restore the editor * if restore is true. */ virtual SmartPointer GetPart(bool restore) = 0; /** * @see IWorkbenchPart#getTitleImage */ virtual void* GetTitleImage() = 0; /** * @see IWorkbenchPart#getTitleToolTip */ virtual QString GetTitleToolTip() const = 0; /** * @see IWorkbenchPartSite#getId */ virtual QString GetId() const = 0; /** * @see IWorkbenchPart#addPropertyListener */ virtual void AddPropertyListener(IPropertyChangeListener* listener) = 0; /** * @see IWorkbenchPart#removePropertyListener */ virtual void RemovePropertyListener(IPropertyChangeListener* listener) = 0; /** * Returns the workbench page that contains this part */ virtual SmartPointer GetPage() const = 0; /** * Returns the name of the part, as it should be shown in tabs. * * @return the part name * * @since 3.0 */ virtual QString GetPartName() const = 0; /** * Returns the content description for the part (or the empty string if none) * * @return the content description for the part * * @since 3.0 */ virtual QString GetContentDescription() const = 0; /** * Returns true if the part is pinned otherwise returns false. */ virtual bool IsPinned() const = 0; /** * Returns whether the part is dirty (i.e. has unsaved changes). * * @return true if the part is dirty, false otherwise * * @since 3.2 (previously existed on IEditorReference) */ virtual bool IsDirty() const = 0; /** * Return an arbitrary property from the reference. If the part has been * instantiated, it just delegates to the part. If not, then it looks in its * own cache of properties. If the property is not available or the part has * never been instantiated, it can return null. * * @param key * The property to return. Must not be null. * @return The String property, or null. * @since 3.3 */ virtual QString GetPartProperty(const QString& key) const = 0; /** * Add a listener for changes in the arbitrary properties set. * * @param listener * Must not be null. * @since 3.3 */ //virtual void addPartPropertyListener(IPropertyChangeListener listener) = 0; /** * Remove a listener for changes in the arbitrary properties set. * * @param listener * Must not be null. * @since 3.3 */ //virtual void removePartPropertyListener(IPropertyChangeListener listener) = 0; }; } // namespace berry #endif /*BERRYIWORKBENCHPARTREFERENCE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartSite.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartSite.h index ae670cd522..59b44ad6a4 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartSite.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartSite.h @@ -1,85 +1,85 @@ /*=================================================================== 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 IWORKBENCHPARTSITE_H_ #define IWORKBENCHPARTSITE_H_ #include "berryIWorkbenchSite.h" namespace berry { struct IWorkbenchPart; /** * \ingroup org_blueberry_ui_qt * * The primary interface between a workbench part and the workbench. *

* This interface is not intended to be implemented or extended by clients. *

* @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IWorkbenchPartSite : public IWorkbenchSite { - berryInterfaceMacro(IWorkbenchPartSite, berry) + berryObjectMacro(berry::IWorkbenchPartSite) ~IWorkbenchPartSite(); /** * Returns the part registry extension id for this workbench site's part. *

* The name comes from the id attribute in the configuration * element. *

* * @return the registry extension id */ - virtual QString GetId() = 0; + virtual QString GetId() const = 0; /** * Returns the part associated with this site * * @return the part associated with this site */ virtual SmartPointer GetPart() = 0; /** * Returns the unique identifier of the plug-in that defines this workbench * site's part. * * @return the unique identifier of the declaring plug-in */ - virtual QString GetPluginId() = 0; + virtual QString GetPluginId() const = 0; /** * Returns the registered name for this workbench site's part. *

* The name comes from the name attribute in the configuration * element. *

* * @return the part name */ - virtual QString GetRegisteredName() = 0; + virtual QString GetRegisteredName() const = 0; }; } // namespace berry #endif /*IWORKBENCHPARTSITE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchSite.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchSite.h index 1c35c919b1..82eb8e7d80 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchSite.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchSite.h @@ -1,109 +1,109 @@ /*=================================================================== 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 BERRYIWORKBENCHSITE_H_ #define BERRYIWORKBENCHSITE_H_ #include #include #include "services/berryIServiceLocator.h" namespace berry { struct IWorkbenchPage; struct ISelectionProvider; struct IWorkbenchWindow; class Shell; /** * \ingroup org_blueberry_ui_qt * * The common interface between the workbench and its parts, including pages * within parts. *

* The workbench site supports a few {@link IServiceLocator services} by * default. If these services are used to allocate resources, it is important to * remember to clean up those resources after you are done with them. Otherwise, * the resources will exist until the workbench site is disposed. The supported * services are: *

*
    *
  • {@link ICommandService}
  • *
  • {@link IContextService}
  • *
  • {@link IHandlerService}
  • *
  • {@link IBindingService}. Resources allocated through this service will * not be cleaned up until the workbench shuts down.
  • *
*

* This interface is not intended to be implemented or extended by clients. *

* * @see org.blueberry.ui.IWorkbenchPartSite * @see org.blueberry.ui.part.IPageSite * @since 2.0 * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IWorkbenchSite : public IServiceLocator { // IAdaptable, IShellProvider { - berryInterfaceMacro(IWorkbenchSite, berry); + berryObjectMacro(berry::IWorkbenchSite) virtual ~IWorkbenchSite(); /** * Returns the page containing this workbench site. * * @return the page containing this workbench site */ virtual SmartPointer GetPage() = 0; /** * Returns the selection provider for this workbench site. * * @return the selection provider, or null if none */ virtual SmartPointer GetSelectionProvider() = 0; /** * Returns the shell for this workbench site. Not intended to be called from * outside the UI thread. Clients should call IWorkbench.getDisplay() to * gain access to the display rather than calling getShell().getDisplay(). * * @return the shell for this workbench site */ virtual SmartPointer GetShell() = 0; /** * Returns the workbench window containing this workbench site. * * @return the workbench window containing this workbench site */ virtual SmartPointer GetWorkbenchWindow() = 0; /** * Sets the selection provider for this workbench site. * * @param provider * the selection provider, or null to clear it */ virtual void SetSelectionProvider(SmartPointer provider) = 0; }; } #endif /*BERRYIWORKBENCHSITE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchWindow.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchWindow.h index ee7751bfe9..16e689863e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchWindow.h @@ -1,213 +1,213 @@ /*=================================================================== 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 BERRYIWORKBENCHWINDOW_H_ #define BERRYIWORKBENCHWINDOW_H_ #include #include #include #include "berryIPageService.h" #include "berryShell.h" #include "services/berryIServiceLocator.h" namespace berry { struct IPartService; struct ISelectionService; struct IWorkbenchPage; struct IWorkbench; /** * \ingroup org_blueberry_ui_qt * * A workbench window is a top level window in a workbench. Visually, a * workbench window has a menubar, a toolbar, a status bar, and a main area for * displaying a single page consisting of a collection of views and editors. *

* Each workbench window has a collection of 0 or more pages; the active page is * the one that is being presented to the end user; at most one page is active * in a window at a time. *

*

* The workbench window supports a few {@link IServiceLocator services} by * default. If these services are used to allocate resources, it is important to * remember to clean up those resources after you are done with them. Otherwise, * the resources will exist until the workbench window is closed. The supported * services are: *

*
    *
  • {@link ICommandService}
  • *
  • {@link IContextService}
  • *
  • {@link IHandlerService}
  • *
  • {@link IBindingService}. Resources allocated through this service will * not be cleaned up until the workbench shuts down.
  • *
*

* This interface is not intended to be implemented by clients. *

* * @see IWorkbenchPage * @noimplement This interface is not intended to be implemented by clients. * */ struct BERRY_UI_QT IWorkbenchWindow : public IPageService, public IServiceLocator, public virtual Object { - berryInterfaceMacro(IWorkbenchWindow, berry); + berryObjectMacro(berry::IWorkbenchWindow) /** * Closes this workbench window. *

* If the window has an open editor with unsaved content, the user will be * given the opportunity to save it. *

* * @return true if the window was successfully closed, and * false if it is still open */ virtual bool Close() = 0; virtual SmartPointer GetPage(int i) = 0; /** * Returns the currently active page for this workbench window. * * @return the active page, or null if none */ - virtual SmartPointer GetActivePage() = 0; + virtual SmartPointer GetActivePage() const = 0; /** * Sets or clears the currently active page for this workbench window. * * @param page * the new active page */ virtual void SetActivePage(SmartPointer page) = 0; /** * Returns the part service which tracks part activation within this * workbench window. * * @return the part service */ virtual IPartService* GetPartService() = 0; /** * Returns the selection service which tracks selection within this * workbench window. * * @return the selection service */ virtual ISelectionService* GetSelectionService() = 0; /** * Returns this workbench window's shell. * * @return the shell containing this window's controls or null * if the shell has not been created yet or if the window has been closed */ - virtual Shell::Pointer GetShell() = 0; + virtual Shell::Pointer GetShell() const = 0; /** * Returns the workbench for this window. * * @return the workbench */ virtual IWorkbench* GetWorkbench() = 0; /** * Returns whether the specified menu is an application menu as opposed to * a part menu. Application menus contain items which affect the workbench * or window. Part menus contain items which affect the active part (view * or editor). *

* This is typically used during "in place" editing. Application menus * should be preserved during menu merging. All other menus may be removed * from the window. *

* * @param menuId * the menu id * @return true if the specified menu is an application * menu, and false if it is not */ //virtual bool IsApplicationMenu(const QString& menuId) = 0; /** * Creates and opens a new workbench page. The perspective of the new page * is defined by the specified perspective ID. The new page become active. *

* Note: Since release 2.0, a window is limited to contain at most * one page. If a page exist in the window when this method is used, then * another window is created for the new page. Callers are strongly * recommended to use the IWorkbench.showPerspective APIs to * programmatically show a perspective. *

* * @param perspectiveId * the perspective id for the window's initial page * @param input * the page input, or null if there is no current * input. This is used to seed the input for the new page's * views. * @return the new workbench page * @exception WorkbenchException * if a page could not be opened * * @see IWorkbench#showPerspective(String, IWorkbenchWindow, IAdaptable) */ virtual SmartPointer OpenPage(const QString& perspectiveId, IAdaptable* input) = 0; /** * Creates and opens a new workbench page. The default perspective is used * as a template for creating the page. The page becomes active. *

* Note: Since release 2.0, a window is limited to contain at most * one page. If a page exist in the window when this method is used, then * another window is created for the new page. Callers are strongly * recommended to use the IWorkbench.showPerspective APIs to * programmatically show a perspective. *

* * @param input * the page input, or null if there is no current * input. This is used to seed the input for the new page's * views. * @return the new workbench window * @exception WorkbenchException * if a page could not be opened * * @see IWorkbench#showPerspective(String, IWorkbenchWindow, IAdaptable) */ virtual SmartPointer OpenPage(IAdaptable* input) = 0; virtual void SetPerspectiveExcludeList(std::vector v) = 0; virtual std::vector GetPerspectiveExcludeList() = 0; virtual void SetViewExcludeList(std::vector v) = 0; virtual std::vector GetViewExcludeList() = 0; virtual ~IWorkbenchWindow(); }; } #endif /*BERRYIWORKBENCHWINDOW_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPropertyChangeEvent.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPropertyChangeEvent.h index 386da90b35..c6e562c612 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPropertyChangeEvent.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPropertyChangeEvent.h @@ -1,128 +1,129 @@ /*=================================================================== 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 BERRYPROPERTYCHANGEEVENT_H_ #define BERRYPROPERTYCHANGEEVENT_H_ #include #include #include namespace berry { /** * An event object describing a change to a named property. *

* This concrete class was designed to be instantiated, but may * also be subclassed if required. *

*

* The JFace frameworks contain classes that report property * change events for internal state changes that may be of interest * to external parties. A special listener interface * (IPropertyChangeListener) is defined for this purpose, * and a typical class allow listeners to be registered via * an addPropertyChangeListener method. *

* * @see IPropertyChangeListener */ -class BERRY_UI_QT PropertyChangeEvent : public Object { +class BERRY_UI_QT PropertyChangeEvent : public Object +{ public: - berryObjectMacro(PropertyChangeEvent); + berryObjectMacro(PropertyChangeEvent) private: /** * The name of the changed property. */ QString propertyName; /** * The old value of the changed property, or null if * not known or not relevant. */ Object::Pointer oldValue; /** * The new value of the changed property, or null if * not known or not relevant. */ Object::Pointer newValue; /** * The object on which the property change occured */ Object::Pointer source; public: /** * Creates a new property change event. * * @param source the object whose property has changed * @param property the property that has changed (must not be null) * @param oldValue the old value of the property, or null if none * @param newValue the new value of the property, or null if none */ PropertyChangeEvent(Object::Pointer source, const QString& property, Object::Pointer oldValue, Object::Pointer newValue); /** * Returns the new value of the property. * * @return the new value, or null if not known * or not relevant (for instance if the property was removed). */ Object::Pointer GetNewValue(); /** * Returns the old value of the property. * * @return the old value, or null if not known * or not relevant (for instance if the property was just * added and there was no old value). */ Object::Pointer GetOldValue(); /** * Returns the name of the property that changed. *

* Warning: there is no guarantee that the property name returned * is a constant string. Callers must compare property names using * equals, not ==. *

* * @return the name of the property that changed */ QString GetProperty(); /** * Returns the object whose property has changed * * @return the object whose property has changed */ Object::Pointer GetSource(); }; } #endif /* BERRYPROPERTYCHANGEEVENT_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtSelectionProvider.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtSelectionProvider.cpp index 95426e4e38..b1b9c8dfdd 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtSelectionProvider.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtSelectionProvider.cpp @@ -1,108 +1,109 @@ /*=================================================================== 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 "berryLog.h" #include "berryQtSelectionProvider.h" #include "berryQtItemSelection.h" #include "berryQModelIndexObject.h" namespace berry { QtSelectionProvider::QtSelectionProvider() : qSelectionModel(0) { } -void QtSelectionProvider::AddSelectionChangedListener(ISelectionChangedListener::Pointer l) +void QtSelectionProvider::AddSelectionChangedListener(ISelectionChangedListener* l) { selectionEvents.AddListener(l); } -void QtSelectionProvider::RemoveSelectionChangedListener(ISelectionChangedListener::Pointer l) +void QtSelectionProvider::RemoveSelectionChangedListener(ISelectionChangedListener* l) { selectionEvents.RemoveListener(l); } ISelection::ConstPointer QtSelectionProvider::GetSelection() const { if (qSelectionModel) { ISelection::Pointer qsel(new QtItemSelection(qSelectionModel->selection())); return qsel; } return ISelection::ConstPointer(0); } -void QtSelectionProvider::SetSelection(ISelection::ConstPointer selection) +void QtSelectionProvider::SetSelection(const ISelection::ConstPointer& selection) { this->SetSelection(selection, QItemSelectionModel::ClearAndSelect); } -void QtSelectionProvider::SetSelection(ISelection::ConstPointer selection, QItemSelectionModel::SelectionFlags flags) +void QtSelectionProvider::SetSelection(const ISelection::ConstPointer& selection, + QItemSelectionModel::SelectionFlags flags) { if (!qSelectionModel) return; if (QtItemSelection::ConstPointer qsel = selection.Cast()) { qSelectionModel->select(qsel->GetQItemSelection(), flags); } } QItemSelection QtSelectionProvider::GetQItemSelection() const { if (qSelectionModel) return qSelectionModel->selection(); return QItemSelection(); } void QtSelectionProvider::SetQItemSelection(const QItemSelection& selection) { if (qSelectionModel) qSelectionModel->select(selection, QItemSelectionModel::Select); } QItemSelectionModel* QtSelectionProvider::GetItemSelectionModel() const { return qSelectionModel; } void QtSelectionProvider::SetItemSelectionModel(QItemSelectionModel* selModel) { if (qSelectionModel) { qSelectionModel->disconnect(this); } qSelectionModel = selModel; if (qSelectionModel) { this->connect(qSelectionModel, SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(FireSelectionChanged(const QItemSelection&, const QItemSelection&))); } } void QtSelectionProvider::FireSelectionChanged(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/) { QtItemSelection::Pointer sel(new QtItemSelection(this->GetQItemSelection())); SelectionChangedEvent::Pointer event(new SelectionChangedEvent(ISelectionProvider::Pointer(this), sel)); selectionEvents.selectionChanged(event); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtSelectionProvider.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtSelectionProvider.h index dabe661d1d..f62e7e7a02 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtSelectionProvider.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtSelectionProvider.h @@ -1,70 +1,70 @@ /*=================================================================== 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 BERRYQTSELECTIONPROVIDER_H_ #define BERRYQTSELECTIONPROVIDER_H_ #include #include #include #include #include namespace berry { class BERRY_UI_QT QtSelectionProvider: public QObject, public ISelectionProvider { Q_OBJECT public: berryObjectMacro(QtSelectionProvider); QtSelectionProvider(); - void AddSelectionChangedListener(ISelectionChangedListener::Pointer listener); + void AddSelectionChangedListener(ISelectionChangedListener* listener); - void RemoveSelectionChangedListener( - ISelectionChangedListener::Pointer listener); + void RemoveSelectionChangedListener(ISelectionChangedListener* listener); ISelection::ConstPointer GetSelection() const; - void SetSelection(ISelection::ConstPointer selection); + void SetSelection(const ISelection::ConstPointer& selection); - virtual void SetSelection(ISelection::ConstPointer selection, QItemSelectionModel::SelectionFlags); + virtual void SetSelection(const ISelection::ConstPointer& selection, + QItemSelectionModel::SelectionFlags); QItemSelection GetQItemSelection() const; void SetQItemSelection(const QItemSelection& selection); QItemSelectionModel* GetItemSelectionModel() const; void SetItemSelectionModel(QItemSelectionModel* combo); protected: ISelectionChangedListener::Events selectionEvents; QItemSelectionModel* qSelectionModel; protected slots: virtual void FireSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); }; } #endif /* BERRYQTSELECTIONPROVIDER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.cpp index c417a513e2..0ab95da142 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.cpp @@ -1,47 +1,47 @@ /*=================================================================== 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 "tweaklets/berryGuiWidgetsTweaklet.h" #include "berrySameShellProvider.h" namespace berry { SameShellProvider::SameShellProvider(void* target) : targetControl(target) { } SameShellProvider::SameShellProvider(Shell::Pointer sh) : targetControl(0), shell(sh) { } -Shell::Pointer SameShellProvider::GetShell() +Shell::Pointer SameShellProvider::GetShell() const { if (shell != 0) { return shell; } return targetControl == 0 ? Shell::Pointer(0) : Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(targetControl); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.h index ebff332656..39740b2b84 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySameShellProvider.h @@ -1,74 +1,74 @@ /*=================================================================== 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 BERRYSAMESHELLPROVIDER_H_ #define BERRYSAMESHELLPROVIDER_H_ #include #include "berryShell.h" #include #include "berryIShellProvider.h" namespace berry { /** * Standard shell provider that always returns the shell containing the given * control. This will always return the correct shell for the control, even if * the control is reparented. * * @since 3.1 */ class BERRY_UI_QT SameShellProvider : public IShellProvider { private: void* targetControl; Shell::Pointer shell; public: berryObjectMacro(SameShellProvider); /** * Returns a shell provider that always returns the current * shell for the given control. * * @param targetControl control whose shell will be tracked, or null if getShell() should always * return null */ SameShellProvider(void* targetControl); /** * Returns a shell provider that always returns the given shell. * * @param shell the shell which should always be returned, * or null if GetShell() should alway return null */ SameShellProvider(Shell::Pointer shell); /* (non-javadoc) * @see IShellProvider#getShell() */ - Shell::Pointer GetShell(); + Shell::Pointer GetShell() const; }; } #endif /* BERRYSAMESHELLPROVIDER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.cpp index bf5a120889..ac907723d3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.cpp @@ -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. ===================================================================*/ #include "berrySaveable.h" #include "berryIWorkbenchPage.h" #include "berryIWorkbenchPart.h" namespace berry { bool Saveable::Show(IWorkbenchPage::Pointer /*page*/) { return false; } /*IJobRunnable*/void Saveable::DoSave(/*IProgressMonitor monitor, IShellProvider shellProvider*/) { this->DoSave(/*monitor*/); //return 0; } void Saveable::DisableUI(const QList& /*parts*/, bool /*closing*/) { //TODO Saveable DisableUI // for (int i = 0; i < parts.length; i++) { // IWorkbenchPart workbenchPart = parts[i]; // Composite paneComposite = (Composite) ((PartSite) workbenchPart // .getSite()).getPane().getControl(); // Control[] paneChildren = paneComposite.getChildren(); // Composite toDisable = ((Composite) paneChildren[0]); // toDisable.setEnabled(false); // if (waitCursor == null) { // waitCursor = new Cursor(workbenchPart.getSite().getWorkbenchWindow().getShell().getDisplay(), SWT.CURSOR_WAIT); // } // originalCursor = paneComposite.getCursor(); // paneComposite.setCursor(waitCursor); // } } void Saveable::EnableUI(QList& /*parts*/) { //TODO Saveable EnableUI // for (unsigned int i = 0; i < parts.size(); i++) { // IWorkbenchPart::Pointer workbenchPart = parts[i]; // Composite paneComposite = (Composite) ((PartSite) workbenchPart // .getSite()).getPane().getControl(); // Control[] paneChildren = paneComposite.getChildren(); // Composite toEnable = ((Composite) paneChildren[0]); // paneComposite.setCursor(originalCursor); // if (waitCursor!=null && !waitCursor.isDisposed()) { // waitCursor.dispose(); // waitCursor = null; // } // toEnable.setEnabled(true); // } } -Poco::Any Saveable::GetAdapter(const QString& /*adapter*/) +Object* Saveable::GetAdapter(const QString& /*adapter*/) { - return Poco::Any(); + return NULL; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.h index 702ed007ae..f2474129fa 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.h @@ -1,287 +1,287 @@ /*=================================================================== 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 BERRYSAVEABLE_H_ #define BERRYSAVEABLE_H_ #include #include #include #include #include "berryImageDescriptor.h" namespace berry { struct IWorkbenchPage; struct IWorkbenchPart; /** * A Saveable represents a unit of saveability, e.g. an editable * subset of the underlying domain model that may contain unsaved changes. * Different workbench parts (editors and views) may present the same saveables * in different ways. This interface allows the workbench to provide more * appropriate handling of operations such as saving and closing workbench * parts. For example, if two editors sharing the same saveable with unsaved * changes are closed simultaneously, the user is only prompted to save the * changes once for the shared saveable, rather than once for each editor. *

* Workbench parts that work in terms of saveables should implement * {@link ISaveablesSource}. *

* * @see ISaveablesSource */ class BERRY_UI_QT Saveable : /*public InternalSaveable*/ public virtual Object, public IAdaptable { public: berryObjectMacro(Saveable) private: //Cursor waitCursor; //Cursor originalCursor; public: typedef QSet Set; /** * Attempts to show this saveable in the given page and returns * true on success. The default implementation does nothing * and returns false. * * @param page * the workbench page in which to show this saveable * @return true if this saveable is now visible to the user * @since 3.3 */ virtual bool Show(SmartPointer page); /** * Returns the name of this saveable for display purposes. * * @return the model's name; never null. */ virtual QString GetName() const = 0; /** * Returns the tool tip text for this saveable. This text is used to * differentiate between two inputs with the same name. For instance, * MyClass.java in folder X and MyClass.java in folder Y. The format of the * text varies between input types. * * @return the tool tip text; never null */ virtual QString GetToolTipText() const = 0; /** * Returns the image descriptor for this saveable. * * @return the image descriptor for this model; may be null * if there is no image */ virtual SmartPointer GetImageDescriptor() const = 0; /** * Saves the contents of this saveable. *

* If the save is cancelled through user action, or for any other reason, * the part should invoke setCancelled on the * IProgressMonitor to inform the caller. *

*

* This method is long-running; progress and cancellation are provided by * the given progress monitor. *

* * @param monitor * the progress monitor * @throws CoreException * if the save fails; it is the caller's responsibility to * report the failure to the user */ virtual void DoSave(/*IProgressMonitor monitor*/) = 0; /** * Returns whether the contents of this saveable have changed since the last * save operation. *

* Note: this method is called frequently, for example by actions to * determine their enabled status. *

* * @return true if the contents have been modified and need * saving, and false if they have not changed since * the last save */ virtual bool IsDirty() const = 0; /** * Clients must implement equals and hashCode as defined in * {@link Object#equals(Object)} and {@link Object#hashCode()}. Two * saveables should be equal if their dirty state is shared, and saving one * will save the other. If two saveables are equal, their names, tooltips, * and images should be the same because only one of them will be shown when * prompting the user to save. * * @param object * @return true if this Saveable is equal to the given object */ - virtual bool operator<(const Saveable* object) const = 0; + virtual bool operator<(const Object* object) const = 0; /** * Clients must implement equals and hashCode as defined in * {@link Object#equals(Object)} and {@link Object#hashCode()}. Two * saveables should be equal if their dirty state is shared, and saving one * will save the other. If two saveables are equal, their hash codes MUST be * the same, and their names, tooltips, and images should be the same * because only one of them will be shown when prompting the user to save. *

* IMPORTANT: Implementers should ensure that the hashCode returned is * sufficiently unique so as not to collide with hashCodes returned by other * implementations. It is suggested that the defining plug-in's ID be used * as part of the returned hashCode, as in the following example: *

* *
    *     int PRIME = 31;
    *     int hash = ...; // compute the "normal" hash code, e.g. based on some identifier unique within the defining plug-in
    *     return hash * PRIME + MY_PLUGIN_ID.hashCode();
    * 
* * @return a hash code */ - //virtual int hashCode(); + virtual uint HashCode() const = 0; /** * Saves this saveable, or prepares this saveable for a background save * operation. Returns null if this saveable has been successfully saved, or * a job runnable that needs to be run to complete the save in the * background. This method is called in the UI thread. If this saveable * supports saving in the background, it should do only minimal work. * However, since the job runnable returned by this method (if any) will not * run on the UI thread, this method should copy any state that can only be * accessed from the UI thread so that the job runnable will be able to * access it. *

* The supplied shell provider can be used from within this method and from * within the job runnable for the purpose of parenting dialogs. Care should * be taken not to open dialogs gratuitously and only if user input is * required for cases where the save cannot otherwise proceed - note that in * any given save operation, many saveable objects may be saved at the same * time. In particular, errors should be signaled by throwing an exception, * or if an error occurs while running the job runnable, an error status * should be returned. *

*

* If the foreground part of the save is cancelled through user action, or * for any other reason, the part should invoke setCancelled * on the IProgressMonitor to inform the caller. If the * background part of the save is cancelled, the job should return a * {@link IStatus#CANCEL} status. *

*

* This method is long-running; progress and cancellation are provided by * the given progress monitor. *

*

* The default implementation of this method calls * {@link #doSave(IProgressMonitor)} and returns null. *

* * @param monitor * a progress monitor used for reporting progress and * cancellation * @param shellProvider * an object that can provide a shell for parenting dialogs * @return null if this saveable has been saved successfully, * or a job runnable that needs to be run to complete the save in * the background. * * @since 3.3 */ //TODO Saveable IJobRunnable, IProgressMonitor, and IShellProvider // virtual /*IJobRunnable*/void DoSave(/*IProgressMonitor monitor, // IShellProvider shellProvider*/); /** * Disables the UI of the given parts containing this saveable if necessary. * This method is not intended to be called by clients. A corresponding call * to *

* Saveables that can be saved in the background should ensure that the user * cannot make changes to their data from the UI, for example by disabling * controls, unless they are prepared to handle this case. This method is * called on the UI thread after a job runnable has been returned from * {@link #doSave(IProgressMonitor, IShellProvider)} and before * spinning the event loop. The closing flag indicates that * this saveable is currently being saved in response to closing a workbench * part, in which case further changes to this saveable through the UI must * be prevented. *

*

* The default implementation calls setEnabled(false) on the given parts' * composites. *

* * @param parts * the workbench parts containing this saveable * @param closing * a boolean flag indicating whether the save was triggered by a * request to close a workbench part, and all of the given parts * will be closed after the save operation finishes successfully. * * @since 3.3 */ virtual void DisableUI(const QList >& parts, bool closing); /** * Enables the UI of the given parts containing this saveable after a * background save operation has finished. This method is not intended to be * called by clients. *

* The default implementation calls setEnabled(true) on the given parts' * composites. *

* * @param parts * the workbench parts containing this saveable * * @since 3.3 */ virtual void EnableUI(QList >& parts); protected: /** * This implementation of {@link IAdaptable#GetAdapterImpl(const std::type_info&)} returns * null. Subclasses may override. This allows two unrelated * subclasses of Saveable to implement {@link #equals(Object)} and * {@link #hashCode()} based on an underlying implementation class that is * shared by both Saveable subclasses. * * @since 3.3 */ - virtual Poco::Any GetAdapter(const QString& adapter); + virtual Object* GetAdapter(const QString& adapter); }; } #endif /* BERRYSAVEABLE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveablesLifecycleEvent.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveablesLifecycleEvent.h index b9f447ee78..bc6cd32a45 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveablesLifecycleEvent.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveablesLifecycleEvent.h @@ -1,143 +1,142 @@ /*=================================================================== 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 BERRYSAVEABLESLIFECYCLEEVENT_H_ #define BERRYSAVEABLESLIFECYCLEEVENT_H_ #include #include #include "berrySaveable.h" #include namespace berry { /** * Event object describing a change to a set of Saveable objects. - * - * @since 3.2 */ -class BERRY_UI_QT SaveablesLifecycleEvent : public Object { +class BERRY_UI_QT SaveablesLifecycleEvent : public Object +{ public: - berryObjectMacro(SaveablesLifecycleEvent); + berryObjectMacro(SaveablesLifecycleEvent) /** * Event type constant specifying that the given saveables have been opened. */ static const int POST_OPEN; // = 1; /** * Event type constant specifying that the given saveables are about to be * closed. Listeners may veto the closing if isForce() is false. */ static const int PRE_CLOSE; // = 2; /** * Event type constant specifying that the given saveables have been closed. */ static const int POST_CLOSE; // = 3; /** * Event type constant specifying that the dirty state of the given saveables * has changed. */ static const int DIRTY_CHANGED; // = 4; private: int eventType; QList saveables; bool force; bool veto; Object::Pointer source; public: /** * Creates a new SaveablesLifecycleEvent. * * @param source * The source of the event. If an ISaveablesSource notifies * about changes to the saveables returned by * {@link ISaveablesSource#getSaveables()}, the source must be * the ISaveablesSource object. * @param eventType * the event type, currently one of POST_OPEN, PRE_CLOSE, * POST_CLOSE, DIRTY_CHANGED * @param saveables * The affected saveables * @param force * true if the event type is PRE_CLOSE and this is a closed force * that cannot be canceled. */ SaveablesLifecycleEvent(Object::Pointer source_, int eventType_, const QList& saveables_, bool force_); /** * Returns the eventType, currently one of POST_OPEN, PRE_CLOSE, POST_CLOSE, * DIRTY_CHANGED. Listeners should silently ignore unknown event types since * new event types might be added in the future. * * @return the eventType */ int GetEventType(); Object::Pointer GetSource(); /** * Returns the affected saveables. * * @return the saveables */ QList GetSaveables(); /** * Returns the veto. This value is ignored for POST_OPEN,POST_CLOSE, and * DIRTY_CHANGED. * * @return Returns the veto. */ bool IsVeto(); /** * @param veto * The veto to set. */ void SetVeto(bool veto); /** * Sets the force flag. This value is ignored for POST_OPEN, POST_CLOSE, and * DIRTY_CHANGED. * * @return Returns the force. */ bool IsForce(); }; } #endif /* BERRYSAVEABLESLIFECYCLEEVENT_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.cpp index 372a5ce39d..7eab010ffe 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.cpp @@ -1,39 +1,54 @@ /*=================================================================== 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 "berryShell.h" namespace berry { +Shell::Shell() + : extraShellListener(NULL) +{ +} + Object::Pointer Shell::GetData(const QString& id) const { QHash::const_iterator iter = data.find(id); if (iter == data.end()) return Object::Pointer(0); return iter.value(); } -void Shell::SetData(Object::Pointer data, const QString& id) +void Shell::SetData(const Object::Pointer& data, const QString& id) { this->data[id] = data; } +IShellListener* Shell::GetExtraShellListener() const +{ + return extraShellListener; +} + +void Shell::SetExtraShellListener(IShellListener* l) +{ + extraShellListener = l; +} + void Shell::SetBounds(int x, int y, int width, int height) { Rectangle rect(x, y, width, height); this->SetBounds(rect); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h index 3ed7d6cbee..b179bcd881 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h @@ -1,329 +1,338 @@ /*=================================================================== 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 BERRYSHELL_H_ #define BERRYSHELL_H_ #include #include #include "berryIShellListener.h" #include "guitk/berryGuiTkIControlListener.h" #include "berryRectangle.h" #include "berryPoint.h" #include namespace berry { /** * Instances of this class represent the "windows" * which the desktop or "window manager" is managing. * Instances that do not have a parent (that is, they * are built using the constructor, which takes a * Display as the argument) are described * as top level shells. Instances that do have * a parent are described as secondary or * dialog shells. *

* Instances are always displayed in one of the maximized, * minimized or normal states: *

    *
  • * When an instance is marked as maximized, the * window manager will typically resize it to fill the * entire visible area of the display, and the instance * is usually put in a state where it can not be resized * (even if it has style RESIZE) until it is * no longer maximized. *
  • * When an instance is in the normal state (neither * maximized or minimized), its appearance is controlled by * the style constants which were specified when it was created * and the restrictions of the window manager (see below). *
  • * When an instance has been marked as minimized, * its contents (client area) will usually not be visible, * and depending on the window manager, it may be * "iconified" (that is, replaced on the desktop by a small * simplified representation of itself), relocated to a * distinguished area of the screen, or hidden. Combinations * of these changes are also possible. *
  • *
*

* The modality of an instance may be specified using * style bits. The modality style bits are used to determine * whether input is blocked for other shells on the display. * The PRIMARY_MODAL style allows an instance to block * input to its parent. The APPLICATION_MODAL style * allows an instance to block input to every other shell in the * display. The SYSTEM_MODAL style allows an instance * to block input to all shells, including shells belonging to * different applications. *

* Note: The styles supported by this class are treated * as HINTs, since the window manager for the * desktop on which the instance is visible has ultimate * control over the appearance and behavior of decorations * and modality. For example, some window managers only * support resizable windows and will always assume the * RESIZE style, even if it is not set. In addition, if a * modality style is not supported, it is "upgraded" to a * more restrictive modality style that is supported. For * example, if PRIMARY_MODAL is not supported, * it would be upgraded to APPLICATION_MODAL. * A modality style may also be "downgraded" to a less * restrictive style. For example, most operating systems * no longer support SYSTEM_MODAL because * it can freeze up the desktop, so this is typically * downgraded to APPLICATION_MODAL. *

*
Styles:
*
BORDER, CLOSE, MIN, MAX, NO_TRIM, RESIZE, TITLE, ON_TOP, TOOL
*
APPLICATION_MODAL, MODELESS, PRIMARY_MODAL, SYSTEM_MODAL
*
Events:
*
Activate, Close, Deactivate, Deiconify, Iconify
*
* Class SWT provides two "convenience constants" * for the most commonly required style combinations: *
*
SHELL_TRIM
*
* the result of combining the constants which are required * to produce a typical application top level shell: (that * is, CLOSE | TITLE | MIN | MAX | RESIZE) *
*
DIALOG_TRIM
*
* the result of combining the constants which are required * to produce a typical application dialog shell: (that * is, TITLE | CLOSE | BORDER) *
*
*

*

* Note: Only one of the styles APPLICATION_MODAL, MODELESS, * PRIMARY_MODAL and SYSTEM_MODAL may be specified. *

* IMPORTANT: This class is not intended to be subclassed. *

* * @see Decorations * @see SWT * @see Shell snippets * @see SWT Example: ControlExample * @see Sample code and further information */ class BERRY_UI_QT Shell : public virtual Object { public: - berryObjectMacro(Shell); + berryObjectMacro(Shell) + + Shell(); Object::Pointer GetData(const QString& id = "") const; - void SetData(Object::Pointer data, const QString& id = ""); + void SetData(const Object::Pointer& data, const QString& id = ""); + + IShellListener* GetExtraShellListener() const; + + void SetExtraShellListener(IShellListener* l); void SetBounds(int x, int y, int width, int height); virtual void SetBounds(const Rectangle& bounds) = 0; virtual Rectangle GetBounds() const = 0; virtual void SetLocation(int x, int y) = 0; virtual Point ComputeSize(int wHint, int hHint, bool changed) = 0; /** * Returns the receiver's text, which is the string that the * window manager will typically display as the receiver's title. * If the text has not previously been set, returns an empty string. * * @return the text */ virtual QString GetText() const = 0; /** * Sets the receiver's text, which is the string that the window manager * will typically display as the receiver's title, to the argument. */ virtual void SetText(const QString& text) = 0; virtual bool IsVisible() = 0; virtual void SetVisible(bool visible) = 0; virtual QWidget* GetControl() = 0; virtual void SetImages(const QList& images) = 0; /** * Returns true if the receiver is currently * maximized, and false otherwise. *

* * @return the maximized state * * @see #SetMaximized */ virtual bool GetMaximized() = 0; /** * Returns true if the receiver is currently * minimized, and false otherwise. *

* * @return the minimized state * * @see #SetMinimized */ virtual bool GetMinimized() = 0; /** * Sets the minimized stated of the receiver. * If the argument is true causes the receiver * to switch to the minimized state, and if the argument is * false and the receiver was previously minimized, * causes the receiver to switch back to either the maximized * or normal states. *

* Note: The result of intermixing calls to setMaximized(true) * and setMinimized(true) will vary by platform. Typically, * the behavior will match the platform user's expectations, but not * always. This should be avoided if possible. *

* * @param minimized the new maximized state * * @see #SetMaximized */ virtual void SetMinimized(bool minimized) = 0; /** * Sets the maximized state of the receiver. * If the argument is true causes the receiver * to switch to the maximized state, and if the argument is * false and the receiver was previously maximized, * causes the receiver to switch back to either the minimized * or normal states. *

* Note: The result of intermixing calls to setMaximized(true) * and setMinimized(true) will vary by platform. Typically, * the behavior will match the platform user's expectations, but not * always. This should be avoided if possible. *

* * @param maximized the new maximized state * * @see #SetMinimized */ virtual void SetMaximized(bool maximized) = 0; /** * Adds the listener to the collection of listeners who will * be notified when operations are performed on the receiver, * by sending the listener one of the messages defined in the * IShellListener interface. * * @param listener the listener which should be notified * * @see IShellListener * @see #RemoveShellListener */ - virtual void AddShellListener(IShellListener::Pointer listener) = 0; + virtual void AddShellListener(IShellListener* listener) = 0; /** * Removes the listener from the collection of listeners who will * be notified when operations are performed on the receiver. * * @param listener the listener which should no longer be notified * * @see IShellListener * @see #AddShellListener */ - virtual void RemoveShellListener(IShellListener::Pointer listener) = 0; + virtual void RemoveShellListener(IShellListener* listener) = 0; /** * Moves the receiver to the top of the drawing order for * the display on which it was created (so that all other * shells on that display, which are not the receiver's * children will be drawn behind it), marks it visible, * sets the focus and asks the window manager to make the * shell active. */ virtual void Open(bool block = false) = 0; /** * Requests that the window manager close the receiver in * the same way it would be closed when the user clicks on * the "close box" or performs some other platform specific * key or mouse combination that indicates the window * should be removed. */ virtual void Close() = 0; /** * If the receiver is visible, moves it to the top of the * drawing order for the display on which it was created * (so that all other shells on that display, which are not * the receiver's children will be drawn behind it) and * asks the window manager to make the shell active. */ virtual void SetActive() = 0; /** * Returns an array containing all shells which are * descendants of the receiver. *

* @return the dialog shells * * @exception SWTException

    *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • *
*/ virtual QList GetShells() = 0; /** * Returns the receiver's style information. *

* Note that the value which is returned by this method may * not match the value which was provided to the constructor * when the receiver was created. This can occur when the underlying * operating system does not support a particular combination of * requested styles. For example, if the platform widget used to * implement a particular SWT widget always has scroll bars, the * result of calling this method would always have the * SWT.H_SCROLL and SWT.V_SCROLL bits set. *

* * @return the style bits * * @exception SWTException
    *
  • ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  • *
  • ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  • *
*/ virtual Qt::WindowFlags GetStyle () const = 0; private: QHash data; + IShellListener* extraShellListener; }; } +Q_DECLARE_METATYPE(berry::Shell*) + #endif /* BERRYSHELL_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShowInContext.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShowInContext.cpp new file mode 100644 index 0000000000..1f633c4ef4 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShowInContext.cpp @@ -0,0 +1,49 @@ +/*=================================================================== + +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 "berryShowInContext.h" + +#include "berryISelection.h" + +namespace berry { + +ShowInContext::ShowInContext(const Object::Pointer& input, const SmartPointer& selection) + : input(input) + , selection(selection) +{ +} + +Object::Pointer ShowInContext::GetInput() const +{ + return input; +} + +SmartPointer ShowInContext::GetSelection() const +{ + return selection; +} + +void ShowInContext::SetInput(const Object::Pointer& input) +{ + this->input = input; +} + +void ShowInContext::SetSelection(const SmartPointer& selection) +{ + this->selection = selection; +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShowInContext.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShowInContext.h new file mode 100644 index 0000000000..eefe64da75 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShowInContext.h @@ -0,0 +1,89 @@ +/*=================================================================== + +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 BERRYSHOWINCONTEXT_H +#define BERRYSHOWINCONTEXT_H + +#include "berryObject.h" + +#include + +namespace berry { + +struct ISelection; + +/** + * Carries the context for the Show In action. + * The default implementation carries an input and a selection. + * Subclasses may extend. + * + * @see IShowInSource + * @see IShowInTarget + */ +class BERRY_UI_QT ShowInContext : public virtual Object +{ + +private: + + Object::Pointer input; + SmartPointer selection; + +public: + + berryObjectMacro(berry::ShowInContext) + + /** + * Constructs a new ShowInContext with the given input and + * selection. + * + * @param input the input or null + * @param selection the selection or null + */ + ShowInContext(const Object::Pointer& input, const SmartPointer& selection); + + /** + * Returns the input, or null to indicate no input + * + * @return the input or null. + */ + Object::Pointer GetInput() const; + + /** + * Returns the selection, or null to indicate no selection. + * + * @return the selection or null + */ + SmartPointer GetSelection() const; + + /** + * Sets the input, or null to indicate no input. + * + * @param input the input or null + */ + void SetInput(const Object::Pointer& input); + + /** + * Sets the selection, or null to indicate no selection. + * + * @param selection the selection or null + */ + void SetSelection(const SmartPointer& selection); + +}; + +} + +#endif // BERRYSHOWINCONTEXT_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.cpp index 5b6f214b69..531caa4669 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.cpp @@ -1,580 +1,580 @@ /*=================================================================== 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 "tweaklets/berryGuiWidgetsTweaklet.h" #include "berryWindow.h" #include "berryConstants.h" #include "berrySameShellProvider.h" #include "berryMenuManager.h" #include namespace berry { const int Window::OK = 0; const int Window::CANCEL = 1; QList Window::defaultImages = QList(); Window::IExceptionHandler::Pointer Window::exceptionHandler(new DefaultExceptionHandler()); IShellProvider::Pointer Window::defaultModalParent(new DefaultModalParent()); Window::WindowShellListener::WindowShellListener(Window* wnd) : window(wnd) { } -void Window::WindowShellListener::ShellClosed(ShellEvent::Pointer event) +void Window::WindowShellListener::ShellClosed(const ShellEvent::Pointer& event) { event->doit = false; // don't close now if (window->CanHandleShellCloseEvent()) { window->HandleShellCloseEvent(); } } void Window::DefaultExceptionHandler::HandleException(const std::exception& t) { // Try to keep running. std::cerr << t.what(); } -Shell::Pointer Window::DefaultModalParent::GetShell() +Shell::Pointer Window::DefaultModalParent::GetShell() const { Shell::Pointer parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetActiveShell(); // Make sure we don't pick a parent that has a modal child (this can lock the app) if (parent == 0) { // If this is a top-level window, then there must not be any open modal windows. parent = Window::GetModalChild(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShells()); } else { // If we picked a parent with a modal child, use the modal child instead Shell::Pointer modalChild = Window::GetModalChild(parent->GetShells()); if (modalChild != 0) { parent = modalChild; } } return parent; } Shell::Pointer Window::GetModalChild(const QList& toSearch) { int modal = Constants::APPLICATION_MODAL | Constants::SYSTEM_MODAL | Constants::PRIMARY_MODAL; size_t size = toSearch.size(); for (size_t i = size - 1; i < size; i--) { Shell::Pointer shell = toSearch[i]; // Check if this shell has a modal child QList children = shell->GetShells(); Shell::Pointer modalChild = GetModalChild(children); if (modalChild != 0) { return modalChild; } // If not, check if this shell is modal itself if (shell->IsVisible() && (shell->GetStyle() & modal) != 0) { return shell; } } return Shell::Pointer(0); } //void Window::RunEventLoop() //{ // // //Use the display provided by the shell if possible // Display display; // if (shell == null) // { // display = Display.getCurrent(); // } // else // { // display = loopShell.getDisplay(); // } // // while (loopShell != null && !loopShell.isDisposed()) // { // try // { // if (!display.readAndDispatch()) // { // display.sleep(); // } // } catch (Throwable e) // { // exceptionHandler.handleException(e); // } // } // display.update(); //} Window::Window(Shell::Pointer parentShell) { this->parentShell = new SameShellProvider(parentShell); this->Init(); } Window::Window(IShellProvider::Pointer shellProvider) { poco_assert(shellProvider != 0); this->parentShell = shellProvider; this->Init(); } Window::~Window() { } void Window::Init() { this->shellStyle = Constants::SHELL_TRIM; this->returnCode = OK; this->block = false; } bool Window::CanHandleShellCloseEvent() { return true; } void Window::ConfigureShell(Shell::Pointer newShell) { // The single image version of this code had a comment related to bug // 46624, // and some code that did nothing if the stored image was already // disposed. // The equivalent in the multi-image version seems to be to remove the // disposed images from the array passed to the shell. if (defaultImages.size() > 0) { // ArrayList nonDisposedImages = new ArrayList(defaultImages.length); // for (int i = 0; i < defaultImages.length; ++i) // { // if (defaultImages[i] != null && !defaultImages[i].isDisposed()) // { // nonDisposedImages.add(defaultImages[i]); // } // } // // if (nonDisposedImages.size() <= 0) // { // System.err.println("Window.configureShell: images disposed"); //$NON-NLS-1$ // } // else // { // //Image[] array = new Image[nonDisposedImages.size()]; // nonDisposedImages.toArray(array); newShell->SetImages(defaultImages); // } } // Layout layout = getLayout(); // if (layout != null) // { // newShell.setLayout(layout); // } CreateTrimWidgets(newShell); } //voidWindow::ConstrainShellSize() //{ // // limit the shell size to the display size // Rectangle bounds = shell.getBounds(); // Rectangle constrained = getConstrainedShellBounds(bounds); // if (!bounds.equals(constrained)) // { // shell.setBounds(constrained); // } //} void* Window::CreateContents(Shell::Pointer parent) { // by default, just create a composite //return new Composite(parent, SWT.NONE); return parent->GetControl(); } Shell::Pointer Window::CreateShell() { Shell::Pointer newParent = this->GetParentShell(); // if (newParent != 0 && newParent.isDisposed()) // { // parentShell = new SameShellProvider(null); // newParent = getParentShell();//Find a better parent // } //Create the shell Shell::Pointer newShell = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->CreateShell(newParent, this->GetShellStyle()); // resizeListener = new Listener() { // public void handleEvent(Event e) { // resizeHasOccurred = true; // } // }; //newShell.addListener(SWT.Resize, resizeListener); newShell->SetData(Object::Pointer(this)); //Add a listener newShell->AddShellListener(this->GetShellListener()); //Set the layout this->ConfigureShell(newShell); // //Register for font changes // if (fontChangeListener == null) // { // fontChangeListener = new FontChangeListener(); // } // JFaceResources.getFontRegistry().addListener(fontChangeListener); return newShell; } void* Window::GetContents() { return contents; } Point Window::GetInitialLocation(const Point& initialSize) { void* parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(shell->GetControl()); Point centerPoint(0,0); Rectangle parentBounds(0,0,0,0); if (parent != 0) { parentBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(parent); centerPoint.x = parentBounds.x + parentBounds.width/2; centerPoint.y = parentBounds.y - parentBounds.height/2; } else { parentBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY) ->GetScreenSize(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetPrimaryScreenNumber()); centerPoint.x = parentBounds.width/2; centerPoint.y = parentBounds.height/2; } return Point(centerPoint.x - (initialSize.x / 2), std::max(parentBounds.y, std::min(centerPoint.y - (initialSize.y * 2 / 3), parentBounds.y + parentBounds.height - initialSize.y))); } Point Window::GetInitialSize() { return shell->ComputeSize(Constants::DEFAULT, Constants::DEFAULT, true); } Shell::Pointer Window::GetParentShell() { Shell::Pointer parent = parentShell->GetShell(); int modal = Constants::APPLICATION_MODAL | Constants::SYSTEM_MODAL | Constants::PRIMARY_MODAL; if ((this->GetShellStyle() & modal) != 0) { // If this is a modal shell with no parent, pick a shell using defaultModalParent. if (parent == 0) { parent = defaultModalParent->GetShell(); } } return parent; } -IShellListener::Pointer Window::GetShellListener() +IShellListener* Window::GetShellListener() { - if (windowShellListener == 0) - windowShellListener = new WindowShellListener(this); + if (windowShellListener.isNull()) + windowShellListener.reset(new WindowShellListener(this)); - return windowShellListener; + return windowShellListener.data(); } int Window::GetShellStyle() { return shellStyle; } void Window::HandleShellCloseEvent() { this->SetReturnCode(CANCEL); this->Close(); } void Window::InitializeBounds() { // if (resizeListener != null) // { // shell.removeListener(SWT.Resize, resizeListener); // } // if (resizeHasOccurred) // { // Check if shell size has been set already. // return; // } Point size = this->GetInitialSize(); Point location = this->GetInitialLocation(size); shell->SetBounds(this->GetConstrainedShellBounds(Rectangle(location.x, location.y, size.x, size.y))); } Rectangle Window::GetConstrainedShellBounds(const Rectangle& preferredSize) { Rectangle result(preferredSize); GuiWidgetsTweaklet* guiTweaklet(Tweaklets::Get(GuiWidgetsTweaklet::KEY)); int screenNum = guiTweaklet->GetClosestScreenNumber(result); Rectangle bounds(guiTweaklet->GetAvailableScreenSize(screenNum)); if (result.height > bounds.height) { result.height = bounds.height; } if (result.width > bounds.width) { result.width = bounds.width; } result.x = std::max(bounds.x, std::min(result.x, bounds.x + bounds.width - result.width)); result.y = std::max(bounds.y, std::min(result.y, bounds.y + bounds.height - result.height)); return result; } void Window::SetParentShell(Shell::Pointer newParentShell) { poco_assert(shell == 0); // "There must not be an existing shell."; //$NON-NLS-1$ parentShell = new SameShellProvider(newParentShell); } void Window::SetReturnCode(int code) { returnCode = code; } void Window::SetShellStyle(int newShellStyle) { shellStyle = newShellStyle; } void Window::AddMenuBar() { if (GetShell().IsNull() && menuBarManager.IsNull()) { menuBarManager = CreateMenuManager(); } } SmartPointer Window::CreateMenuManager() { MenuManager::Pointer manager(new MenuManager()); return manager; } void Window::CreateTrimWidgets(SmartPointer shell) { if (menuBarManager.IsNotNull()) { QMainWindow* mw = qobject_cast(shell->GetControl()); if (mw) { mw->setMenuBar(menuBarManager->CreateMenuBar(shell->GetControl())); menuBarManager->UpdateAll(true); } } // if (showTopSeperator()) // { // seperator1 = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL); // } //CreateToolBarControl(shell); //CreateStatusLine(shell); } bool Window::Close() { // BERRY_INFO << "Window::Close()"; // // stop listening for font changes // if (fontChangeListener != null) // { // JFaceResources.getFontRegistry().removeListener(fontChangeListener); // fontChangeListener = null; // } // remove this window from a window manager if it has one if (windowManager != 0) { windowManager->Remove(Window::Pointer(this)); windowManager = 0; } if (shell == 0) { return true; } shell->RemoveShellListener(this->GetShellListener()); shell->SetData(Object::Pointer(0)); // If we "close" the shell recursion will occur. // Instead, we need to "dispose" the shell to remove it from the // display. Tweaklets::Get(GuiWidgetsTweaklet::KEY)->DisposeShell(shell); shell = 0; contents = 0; return true; } void Window::Create() { shell = this->CreateShell(); contents = this->CreateContents(shell); //initialize the bounds of the shell to that appropriate for the // contents this->InitializeBounds(); } void* Window::GetDefaultImage() { return (defaultImages.size() < 1) ? 0 : defaultImages[0]; } QList Window::GetDefaultImages() { return defaultImages; } int Window::GetReturnCode() { return returnCode; } -Shell::Pointer Window::GetShell() +Shell::Pointer Window::GetShell() const { return shell; } WindowManager* Window::GetWindowManager() { return windowManager; } MenuManager *Window::GetMenuBarManager() const { return menuBarManager.GetPointer(); } int Window::Open() { if (shell == 0) { // create the window this->Create(); } // limit the shell size to the display size //constrainShellSize(); // open the window shell->Open(block); // // run the event loop if specified // if (block) // { // this->RunEventLoop(); // } return returnCode; } void Window::SetBlockOnOpen(bool shouldBlock) { block = shouldBlock; } void Window::SetDefaultImage(void* image) { if (image != 0) defaultImages.push_back(image); } void Window::SetDefaultImages(const QList& images) { defaultImages = images; } void Window::SetWindowManager(WindowManager* manager) { windowManager = manager; // Code to detect invalid usage if (manager != 0) { QList windows = manager->GetWindows(); - for (unsigned int i = 0; i < windows.size(); i++) + for (int i = 0; i < windows.size(); i++) { if (windows[i] == this) { return; } } manager->Add(Window::Pointer(this)); } } void Window::SetExceptionHandler(IExceptionHandler::Pointer handler) { if (exceptionHandler == 0) { exceptionHandler = handler; } } void Window::SetDefaultModalParent(IShellProvider::Pointer provider) { defaultModalParent = provider; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.h index 0250e0332a..ea8a17c847 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.h @@ -1,731 +1,732 @@ /*=================================================================== 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 BERRYWINDOW_H_ #define BERRYWINDOW_H_ #include #include "berryIShellProvider.h" #include "berryIShellListener.h" #include "berryPoint.h" #include "internal/berryWindowManager.h" #include "tweaklets/berryGuiWidgetsTweaklet.h" #include #include namespace berry { //struct IToolBarManager; class MenuManager; //class StatusLineManager; /** * A JFace window is an object that has no visual representation (no widgets) * until it is told to open. *

* Creating a window involves the following steps: *

    *
  • creating an instance of a concrete subclass of Window *
  • *
  • creating the window's shell and widget tree by calling * create (optional)
  • *
  • assigning the window to a window manager using * WindowManager.add (optional)
  • *
  • opening the window by calling open
  • *
* Opening the window will create its shell and widget tree if they have not * already been created. When the window is closed, the shell and widget tree * are disposed of and are no longer referenced, and the window is automatically * removed from its window manager. A window may be reopened. *

*

* The JFace window framework (this package) consists of this class, * Window, the abstract base of all windows, and one concrete * window classes (ApplicationWindow) which may also be * subclassed. Clients may define additional window subclasses as required. *

*

* The Window class provides methods that subclasses may * override to configure the window, including: *

    *
  • close- extend to free other SWT resources
  • *
  • configureShell- extend or reimplement to set shell * properties before window opens
  • *
  • createContents- extend or reimplement to create controls * before window opens
  • *
  • getInitialSize- reimplement to give the initial size for * the shell
  • *
  • getInitialLocation- reimplement to give the initial * location for the shell
  • *
  • getShellListener- extend or reimplement to receive shell * events
  • *
  • handleFontChange- reimplement to respond to font changes *
  • *
  • handleShellCloseEvent- extend or reimplement to handle * shell closings
  • *
*

*/ class BERRY_UI_QT Window: public IShellProvider { public: berryObjectMacro(Window); /** * Standard return code constant (value 0) indicating that the window was * opened. * * @see #open */ static const int OK; // = 0; /** * Standard return code constant (value 1) indicating that the window was * canceled. * * @see #open */ static const int CANCEL; // = 1; /** * An array of images to be used for the window. It is expected that the * array will contain the same icon rendered at different resolutions. */ static QList defaultImages; /** * This interface defines a Exception Handler which can be set as a global * handler and will be called if an exception happens in the event loop. */ struct IExceptionHandler: public Object { berryObjectMacro(IExceptionHandler) /** * Handle the exception. * * @param t * The exception that occured. */ virtual void HandleException(const std::exception& t) = 0; }; private: struct WindowShellListener : public IShellListener { WindowShellListener(Window* wnd); - void ShellClosed(ShellEvent::Pointer event); + void ShellClosed(const ShellEvent::Pointer& event); private: Window* window; }; - IShellListener::Pointer windowShellListener; + QScopedPointer windowShellListener; /** * Defines a default exception handler. */ struct DefaultExceptionHandler: public IExceptionHandler { /* * (non-Javadoc) * * @see org.blueberry.jface.window.Window.IExceptionHandler#handleException(java.lang.Throwable) */ void HandleException(const std::exception& t); }; /** * Menu bar manager, or null if none (default). * * @see #addMenuBar */ SmartPointer menuBarManager; /** * Tool bar manager, or null if none (default). * * @see #addToolBar */ //SmartPointer toolBarManager; /** * Status line manager, or null if none (default). * * @see #addStatusLine */ //SmartPointer statusLineManager; /** * The exception handler for this application. */ static IExceptionHandler::Pointer exceptionHandler; /** * Object used to locate the default parent for modal shells */ struct DefaultModalParent: public IShellProvider { - Shell::Pointer GetShell(); + Shell::Pointer GetShell() const; }; friend struct DefaultModalParent; static IShellProvider::Pointer defaultModalParent; /** * Object that returns the parent shell. */ IShellProvider::Pointer parentShell; /** * Shell style bits. * * @see #setShellStyle */ int shellStyle; // = Constants::SHELL_TRIM; /** * Window manager, or null if none. * * @see #setWindowManager */ WindowManager* windowManager; /** * Window shell, or null if none. */ Shell::Pointer shell; /** * Top level SWT control, or null if none */ void* contents; /** * Window return code; initially OK. * * @see #setReturnCode */ int returnCode; // = OK; /** * true if the open method should not return * until the window closes, and false if the * open method should return immediately; initially * false (non-blocking). * * @see #setBlockOnOpen */ bool block; // = false; // /** // * Internal class for informing this window when fonts change. // */ // class FontChangeListener implements IPropertyChangeListener { // public void propertyChange(PropertyChangeEvent event) { // handleFontChange(event); // } // } // /** // * Internal font change listener. // */ // private FontChangeListener fontChangeListener; /** * Internal fields to detect if shell size has been set */ //bool resizeHasOccurred = false; //Listener resizeListener; /** * Returns the most specific modal child from the given list of Shells. * * @param toSearch shells to search for modal children * @return the most specific modal child, or null if none * * @since 3.1 */ static Shell::Pointer GetModalChild( const QList& toSearch); /** * Runs the event loop for the given shell. * * @param loopShell * the shell */ //void RunEventLoop(); protected: /** * Creates a window instance, whose shell will be created under the given * parent shell. Note that the window will have no visual representation * until it is told to open. By default, open does not block. * * @param parentShell * the parent shell, or null to create a top-level * shell. Try passing "(Shell)null" to this method instead of "null" * if your compiler complains about an ambiguity error. * @see #setBlockOnOpen * @see #getDefaultOrientation() */ Window(Shell::Pointer parentShell); /** * Creates a new window which will create its shell as a child of whatever * the given shellProvider returns. * * @param shellProvider object that will return the current parent shell. Not null. * */ Window(IShellProvider::Pointer shellProvider); ~Window(); /** * Given the desired position of the window, this method returns an adjusted * position such that the window is no larger than its monitor, and does not * extend beyond the edge of the monitor. This is used for computing the * initial window position, and subclasses can use this as a utility method * if they want to limit the region in which the window may be moved. * * @param preferredSize * the preferred position of the window * @return a rectangle as close as possible to preferredSize that does not * extend outside the monitor * */ Rectangle GetConstrainedShellBounds(const Rectangle& preferredSize); /** * Initializes this windows variables */ virtual void Init(); /** * Determines if the window should handle the close event or do nothing. *

* The default implementation of this framework method returns * true, which will allow the * handleShellCloseEvent method to be called. Subclasses may * extend or reimplement. *

* * @return whether the window should handle the close event. */ virtual bool CanHandleShellCloseEvent(); /** * Configures the given shell in preparation for opening this window in it. *

* The default implementation of this framework method sets the shell's * image and gives it a grid layout. Subclasses may extend or reimplement. *

* * @param newShell * the shell */ virtual void ConfigureShell(Shell::Pointer newShell); /** * Constrain the shell size to be no larger than the display bounds. * * @since 2.0 */ //void ConstrainShellSize(); /** * Creates and returns this window's contents. Subclasses may attach any * number of children to the parent. As a convenience, the return value of * this method will be remembered and returned by subsequent calls to * getContents(). Subclasses may modify the parent's layout if they overload * getLayout() to return null. * *

* It is common practise to create and return a single composite that * contains the entire window contents. *

* *

* The default implementation of this framework method creates an instance * of Composite. Subclasses may override. *

* * @param parent * the parent composite for the controls in this window. The type * of layout used is determined by getLayout() * * @return the control that will be returned by subsequent calls to * getContents() */ virtual void* CreateContents(Shell::Pointer parent); /** * Creates and returns this window's shell. *

* The default implementation of this framework method creates a new shell * and configures it using configureShell. Rather than * override this method, subclasses should instead override * configureShell. *

* * @return the shell */ virtual Shell::Pointer CreateShell(); /** * Returns the top level control for this window. The parent of this control * is the shell. * * @return the top level control, or null if this window's * control has not been created yet */ virtual void* GetContents(); /** * Returns the initial location to use for the shell. The default * implementation centers the shell horizontally (1/2 of the difference to * the left and 1/2 to the right) and vertically (1/3 above and 2/3 below) * relative to the parent shell, or display bounds if there is no parent * shell. * * @param initialSize * the initial size of the shell, as returned by * getInitialSize. * @return the initial location of the shell */ virtual Point GetInitialLocation(const Point& initialSize); /** * Returns the initial size to use for the shell. The default implementation * returns the preferred size of the shell, using * Shell.computeSize(SWT.DEFAULT, SWT.DEFAULT, true). * * @return the initial size of the shell */ virtual Point GetInitialSize(); /** * Returns parent shell, under which this window's shell is created. * * @return the parent shell, or null if there is no parent * shell */ Shell::Pointer GetParentShell(); /** * Returns a shell listener. This shell listener gets registered with this * window's shell. *

* The default implementation of this framework method returns a new * listener that makes this window the active window for its window manager * (if it has one) when the shell is activated, and calls the framework * method handleShellCloseEvent when the shell is closed. * Subclasses may extend or reimplement. *

* * @return a shell listener */ - virtual IShellListener::Pointer GetShellListener(); + virtual IShellListener* GetShellListener(); /** * Returns the shell style bits. *

* The default value is SWT.CLOSE|SWT.MIN|SWT.MAX|SWT.RESIZE. * Subclassers should call setShellStyle to change this * value, rather than overriding this method. *

* * @return the shell style bits */ int GetShellStyle(); /** * Notifies that the window's close button was pressed, the close menu was * selected, or the ESCAPE key pressed. *

* The default implementation of this framework method sets the window's * return code to CANCEL and closes the window using * close. Subclasses may extend or reimplement. *

*/ virtual void HandleShellCloseEvent(); /** * Initializes the location and size of this window's SWT shell after it has * been created. *

* This framework method is called by the create framework * method. The default implementation calls getInitialSize * and getInitialLocation and passes the results to * Shell.setBounds. This is only done if the bounds of the * shell have not already been modified. Subclasses may extend or * reimplement. *

*/ virtual void InitializeBounds(); /** * Changes the parent shell. This is only safe to use when the shell is not * yet realized (i.e., created). Once the shell is created, it must be * disposed (i.e., closed) before this method can be called. * * @param newParentShell * The new parent shell; this value may be null if * there is to be no parent. * @since 3.1 */ void SetParentShell(Shell::Pointer newParentShell); /** * Sets this window's return code. The return code is automatically returned * by open if block on open is enabled. For non-blocking * opens, the return code needs to be retrieved manually using * getReturnCode. * * @param code * the return code */ void SetReturnCode(int code); /** * Sets the shell style bits. This method has no effect after the shell is * created. *

* The shell style bits are used by the framework method * createShell when creating this window's shell. *

* * @param newShellStyle * the new shell style bits */ void SetShellStyle(int newShellStyle); /** * Configures this window to have a menu bar. * Does nothing if it already has one. * This method must be called before this window's shell is created. */ void AddMenuBar(); /** * Returns a new menu manager for the window. *

* Subclasses may override this method to customize the menu manager. *

* @return a menu manager */ virtual SmartPointer CreateMenuManager(); /** * Creates the trim widgets around the content area. * * @param shell the shell */ virtual void CreateTrimWidgets(SmartPointer shell); public: /** * Closes this window, disposes its shell, and removes this window from its * window manager (if it has one). *

* This framework method may be extended (super.close must * be called). *

*

* Note that in order to prevent recursive calls to this method * it does not call Shell#close(). As a result ShellListeners * will not receive a shellClosed event. *

* * @return true if the window is (or was already) closed, and * false if it is still open */ virtual bool Close(); /** * Creates this window's widgetry in a new top-level shell. *

* The default implementation of this framework method creates this window's * shell (by calling createShell), and its controls (by * calling createContents), then initializes this window's * shell bounds (by calling initializeBounds). *

*/ virtual void Create(); /** * Returns the default image. This is the image that will be used for * windows that have no shell image at the time they are opened. There is no * default image unless one is installed via setDefaultImage. * * @return the default image, or null if none * @see #setDefaultImage */ static void* GetDefaultImage(); /** * Returns the array of default images to use for newly opened windows. It * is expected that the array will contain the same icon rendered at * different resolutions. * * @see org.blueberry.swt.widgets.Decorations#setImages(org.blueberry.swt.graphics.Image[]) * * @return the array of images to be used when a new window is opened * @see #setDefaultImages * @since 3.0 */ static QList GetDefaultImages(); /** * Returns this window's return code. A window's return codes are * window-specific, although two standard return codes are predefined: * OK and CANCEL. * * @return the return code */ int GetReturnCode(); /** * Returns this window's shell. * * @return this window's shell, or null if this window's * shell has not been created yet */ - Shell::Pointer GetShell(); + Shell::Pointer GetShell() const; /** * Returns the window manager of this window. * * @return the WindowManager, or null if none */ WindowManager* GetWindowManager(); /** * Returns the menu bar manager for this window (if it has one). * * @return the menu bar manager, or null if * this window does not have a menu bar * @see #addMenuBar() */ MenuManager* GetMenuBarManager() const; /** * Opens this window, creating it first if it has not yet been created. *

* If this window has been configured to block on open ( * setBlockOnOpen), this method waits until the window is * closed by the end user, and then it returns the window's return code; * otherwise, this method returns immediately. A window's return codes are * window-specific, although two standard return codes are predefined: * OK and CANCEL. *

* * @return the return code * * @see #create() */ int Open(); /** * Sets whether the open method should block until the window * closes. * * @param shouldBlock * true if the open method should * not return until the window closes, and false * if the open method should return immediately */ void SetBlockOnOpen(bool shouldBlock); /** * Sets the default image. This is the image that will be used for windows * that have no shell image at the time they are opened. There is no default * image unless one is installed via this method. * * @param image * the default image, or null if none */ static void SetDefaultImage(void* image); /** * Sets the array of default images to use for newly opened windows. It is * expected that the array will contain the same icon rendered at different * resolutions. * * @see org.blueberry.swt.widgets.Decorations#setImages(org.blueberry.swt.graphics.Image[]) * * @param images * the array of images to be used when this window is opened * @since 3.0 */ static void SetDefaultImages(const QList& images); /** * Sets the window manager of this window. *

* Note that this method is used by WindowManager to maintain * a backpointer. Clients must not call the method directly. *

* * @param manager * the window manager, or null if none */ void SetWindowManager(WindowManager* manager); /** * Sets the exception handler for this application. *

* Note that the handler may only be set once. Subsequent calls to this method will be * ignored. *

* * @param handler * the exception handler for the application. */ static void SetExceptionHandler(IExceptionHandler::Pointer handler); /** * Sets the default parent for modal Windows. This will be used to locate * the parent for any modal Window constructed with a null parent. * * @param provider shell provider that will be used to locate the parent shell * whenever a Window is created with a null parent * @since 3.1 */ static void SetDefaultModalParent(IShellProvider::Pointer provider); }; } + #endif /* BERRYWINDOW_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryXMLMemento.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryXMLMemento.cpp index 7144804791..4900943ca9 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryXMLMemento.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryXMLMemento.cpp @@ -1,430 +1,434 @@ /*=================================================================== 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 "berryXMLMemento.h" #include "internal/berryWorkbenchPlugin.h" #include #include #include #include #include #include #include #include #include #include #include #include #include const QString EMPTY_STRING; berry::XMLMemento::XMLMemento(Poco::XML::Document* document, Poco::XML::Element* elem) : factory(document), element(elem) { factory->duplicate(); element->duplicate(); } berry::XMLMemento::~XMLMemento() { element->release(); factory->release(); } berry::XMLMemento::Pointer berry::XMLMemento::CreateReadRoot( berry::XMLMemento::XMLByteInputStream& reader) { return CreateReadRoot(reader, ""); } berry::XMLMemento::Pointer berry::XMLMemento::CreateReadRoot( berry::XMLMemento::XMLByteInputStream& reader, const QString& baseDir) { QString errorMessage; Poco::Exception exception(""); try { Poco::XML::DOMParser parser; Poco::XML::InputSource source(reader); source.setSystemId(baseDir.toStdString()); Poco::XML::Document* doc = parser.parse(&source); Poco::XML::Element* elem = doc->documentElement(); - XMLMemento::Pointer memento = XMLMemento::New(doc, elem); + XMLMemento::Pointer memento(new XMLMemento(doc, elem)); doc->release(); return memento; } catch (Poco::XML::SAXParseException& e) { errorMessage = QString("Could not parse content of XML file: ") + QString::fromStdString(e.displayText()); } QString problemText = QString::fromStdString(exception.message()); if (problemText.isEmpty()) { problemText = errorMessage.isEmpty() ? "Could not find root element node of XML file." : errorMessage; } throw WorkbenchException(problemText); } berry::XMLMemento::Pointer berry::XMLMemento::CreateWriteRoot( const QString& type) { // TODO // try{ Poco::XML::Document* doc = new Poco::XML::Document(); Poco::XML::Element* elem = doc->createElement(type.toStdString()); doc->appendChild(elem)->release(); - XMLMemento::Pointer memento = XMLMemento::New(doc, elem); + XMLMemento::Pointer memento(new XMLMemento(doc, elem)); doc->release(); return memento; //}catch() //TODO: look for poco exceptions //{ //} } berry::IMemento::Pointer berry::XMLMemento::CreateChild( const QString& type) { Poco::XML::Element* child = factory->createElement(type.toStdString()); element->appendChild(child)->release(); - return XMLMemento::New(factory, child); + IMemento::Pointer xmlChild(new XMLMemento(factory,child)); + return xmlChild; } berry::IMemento::Pointer berry::XMLMemento::CreateChild( const QString& type, const QString& id) { Poco::XML::Element* child = factory->createElement(type.toStdString()); child->setAttribute(TAG_ID.toStdString(), id.toStdString()); element->appendChild(child)->release(); - return XMLMemento::New(factory, child); + IMemento::Pointer xmlChild(new XMLMemento(factory,child)); + return xmlChild; } berry::IMemento::Pointer berry::XMLMemento::CopyChild(IMemento::Pointer child) { //TODO check any casting errors Poco::XML::Element* elem = child.Cast ()->GetElement(); Poco::XML::Element* newElement = dynamic_cast (factory->importNode(elem, true)); element->appendChild(newElement)->release(); - return XMLMemento::New(factory, newElement); + IMemento::Pointer xmlCopy(new XMLMemento(factory, newElement)); + return xmlCopy; } berry::IMemento::Pointer berry::XMLMemento::GetChild(const QString& type) const { // Get the nodes. berry::XMLMemento::Pointer memento; Poco::XML::Element* child = element->getChildElement(type.toStdString()); // Find the first node which is a child of this node if (child) { - memento = berry::XMLMemento::New(factory, child); + memento = new berry::XMLMemento(factory, child); return memento; } // A child was not found. return memento; } QList berry::XMLMemento::GetChildren( const QString& type) const { QList mementos; Poco::XML::NodeList* elementList = element->getElementsByTagName(type.toStdString()); for (unsigned long i = 0; i < elementList->length(); i++) { Poco::XML::Element* elem = dynamic_cast (elementList->item(i)); - mementos << berry::XMLMemento::New(factory, elem); + IMemento::Pointer child(new berry::XMLMemento(factory, elem)); + mementos << child; } elementList->release(); return mementos; } bool berry::XMLMemento::GetFloat(const QString& key, double& value) const { if (!element->hasAttribute(key.toStdString())) return false; const std::string& attr = element->getAttribute(key.toStdString()); try { value = Poco::NumberParser::parseFloat(attr); - } catch (const Poco::SyntaxException& e) + } catch (const Poco::SyntaxException& /*e*/) { std::string _qnan = Poco::NumberFormatter::format(std::numeric_limits::quiet_NaN()); if (_qnan == attr) { value = std::numeric_limits::quiet_NaN(); return true; } std::string _inf = Poco::NumberFormatter::format(std::numeric_limits::infinity()); if (_inf == attr) { value = std::numeric_limits::infinity(); return true; } WorkbenchPlugin::Log("Memento problem - invalid float for key: " + key + " value: " + QString::fromStdString(attr)); return false; } return true; } QString berry::XMLMemento::GetType() const { return QString::fromStdString(element->nodeName()); } QString berry::XMLMemento::GetID() const { //TODO: make error handling! return QString::fromStdString(element->getAttribute(TAG_ID.toStdString())); } bool berry::XMLMemento::GetInteger(const QString& key, int& value) const { if (!element->hasAttribute(key.toStdString())) return false; const std::string& attr = element->getAttribute(key.toStdString()); try { value = Poco::NumberParser::parse(attr); } - catch (const Poco::SyntaxException& e) + catch (const Poco::SyntaxException& /*e*/) { WorkbenchPlugin::Log("Memento problem - invalid integer for key: " + key + " value: " + QString::fromStdString(attr)); return false; } return true; } bool berry::XMLMemento::GetBoolean(const QString& key, bool& value) const { const std::string& attr = element->getAttribute(key.toStdString()); if (attr.empty()) return false; else if (attr == "true") { value = true; return true; } else { value = false; return true; } } bool berry::XMLMemento::GetString(const QString& key, QString& value) const { QString v = QString::fromStdString(element->getAttribute(key.toStdString())); if (v.isEmpty()) return false; value = v; return true; } QString berry::XMLMemento::GetTextData() const { Poco::XML::Text* textNode = GetTextNode(); if (textNode != NULL) { return QString::fromStdString(textNode->getData()); } return EMPTY_STRING; } QList berry::XMLMemento::GetAttributeKeys() const { QList values; Poco::XML::NamedNodeMap* nnMap = element->attributes(); values.reserve(nnMap->length()); for (unsigned long i = 0; i < nnMap->length(); i++) { values[i] = QString::fromStdString(nnMap->item(i)->nodeName()); //TODO check if right } return values; } Poco::XML::Text* berry::XMLMemento::GetTextNode() const { //Get the nodes Poco::XML::NodeList* nodes = element->childNodes(); unsigned long size = nodes->length(); if (size == 0) return NULL; //Search for the text node for (unsigned long index = 0; index < size; index++) { if (nodes->item(index)->nodeType() == Poco::XML::Node::TEXT_NODE) { return dynamic_cast (nodes->item(index)); } } // a Text node was not found return NULL; } void berry::XMLMemento::PutElement(Poco::XML::Element* element, bool copyText) { Poco::XML::NamedNodeMap* nodeMap = element->attributes(); unsigned long size = nodeMap->length(); for (unsigned long index = 0; index < size; index++) { Poco::XML::Node* node = nodeMap->item(index); Poco::XML::Attr* attr = dynamic_cast (node); PutString(QString::fromStdString(attr->nodeName()), QString::fromStdString(attr->nodeValue())); } nodeMap->release(); bool needToCopyText = copyText; Poco::XML::Node* child = element->firstChild(); while (child) { unsigned short nodeType = child->nodeType(); switch (nodeType) { case Poco::XML::Node::ELEMENT_NODE: { Poco::XML::Element* elem = dynamic_cast (child); XMLMemento::Pointer child = CreateChild(QString::fromStdString(elem->nodeName())).Cast< berry::XMLMemento> (); child->PutElement(elem, true); } break; case Poco::XML::Node::TEXT_NODE: if (needToCopyText) { Poco::XML::Text* text = dynamic_cast (child); PutTextData(QString::fromStdString(text->getData())); needToCopyText = false; } break; default: break; } child = child->nextSibling(); } } void berry::XMLMemento::PutFloat(const QString& key, double value) { std::string xmlValue = Poco::NumberFormatter::format(value); element->setAttribute(key.toStdString(), xmlValue); } void berry::XMLMemento::PutInteger(const QString& key, int value) { std::string xmlValue = Poco::NumberFormatter::format(value); element->setAttribute(key.toStdString(), xmlValue); } void berry::XMLMemento::PutMemento(IMemento::Pointer memento) { // Do not copy the element's top level text node (this would overwrite the existing text). // Text nodes of children are copied. PutElement(memento.Cast ()->GetElement(), false); } void berry::XMLMemento::PutString(const QString& key, const QString& value) { element->setAttribute(key.toStdString(), value.toStdString()); //if (value == null) { // return;} //element.setAttribute(key, value); } void berry::XMLMemento::PutBoolean(const QString& key, bool value) { if (value) { element->setAttribute(key.toStdString(), "true"); } else { element->setAttribute(key.toStdString(), "false"); } } void berry::XMLMemento::PutTextData(const QString& data) { Poco::XML::Text* textNode = GetTextNode(); if (textNode == NULL) { textNode = factory->createTextNode(data.toStdString()); element->insertBefore(textNode, element->firstChild())->release(); } else { textNode->setData(data.toStdString()); } } void berry::XMLMemento::Save(berry::XMLMemento::XMLByteOutputStream& writer) { if (writer.good()) { Poco::XML::DOMWriter out; out.setOptions(3); //write declaration and pretty print out.writeNode(writer, factory); } else { //TODO } } Poco::XML::Element* berry::XMLMemento::GetElement() const { return element; } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryXMLMemento.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryXMLMemento.h index 9dfba7d783..4b814c606a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryXMLMemento.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryXMLMemento.h @@ -1,287 +1,287 @@ /*=================================================================== 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 BERRYXMLMEMENTO_H_ #define BERRYXMLMEMENTO_H_ #include #include "berryIMemento.h" #include "berryUIException.h" #include "Poco/DOM/Document.h" #include "Poco/DOM/Element.h" #include "Poco/SAX/XMLReader.h" namespace berry { /** * This class represents the default implementation of the * IMemento interface. *

* This class is not intended to be extended by clients. *

* * @see IMemento */ -class BERRY_UI_QT XMLMemento : public IMemento { +class BERRY_UI_QT XMLMemento : public IMemento +{ public: berryObjectMacro(XMLMemento) - berryNewMacro2Param(XMLMemento, Poco::XML::Document*, Poco::XML::Element*) /** * Defines a std::ostream as XML output stream */ typedef std::ostream XMLByteOutputStream; /** * Defines a std::istream as XML input stream */ typedef std::istream XMLByteInputStream; /** * Creates a memento for the specified document and element. *

* Clients should use CreateReadRoot and * CreateWriteRoot to create the initial * memento on a document. *

* * @param document the document for the memento * @param element the element node for the memento */ XMLMemento(Poco::XML::Document* document, Poco::XML::Element* elem); ~XMLMemento(); /** * Creates a Document from the Reader * and returns a memento on the first Element for reading * the document. * * @param reader the Reader used to create the memento's document * @return a memento on the first Element for reading the document * @throws WorkbenchException if IO problems, invalid format, or no element. */ static XMLMemento::Pointer CreateReadRoot(berry::XMLMemento::XMLByteInputStream& reader); /** * Creates a Document from the Reader * and returns a memento on the first Element for reading * the document. * * @param reader the Reader used to create the memento's document * @param baseDir the directory used to resolve relative file names * in the XML document. This directory must exist and include the * trailing separator. The directory format, including the separators, * must be valid for the platform. Can be null if not * needed. * @return a memento on the first Element for reading the document * @throws WorkbenchException if IO problems, invalid format, or no element. */ static XMLMemento::Pointer CreateReadRoot(berry::XMLMemento::XMLByteInputStream& reader, const QString& baseDir); /** * Returns a root memento for writing a document. * * @param type the element node type to create on the document * @return the root memento for writing a document */ static XMLMemento::Pointer CreateWriteRoot(const QString& type); /** * Copies another Memento into this memento * * @param child the new child memento * @return the new child memento */ IMemento::Pointer CopyChild(IMemento::Pointer child); /** * Creates a new child of this memento with the given type * * @param type the type * @return a new child memento with the given type */ virtual IMemento::Pointer CreateChild(const QString& type); /** * Creates a new child of this memento with the given type and id. * The id is stored in the child memento (using a special reserved * key, TAG_ID) and can be retrieved using getId. *

* The getChild and getChildren methods * are used to retrieve children of a given type. *

* * @param type the type * @param id the child id * @return a new child memento with the given type and id * @see #getID */ virtual IMemento::Pointer CreateChild(const QString& type, const QString& id); /** * Returns the first child with the given type id. * * @param type the type id * @return the first child with the given type */ virtual IMemento::Pointer GetChild(const QString& type) const; /** * Returns all children with the given type id. * * @param type the type id * @return an array of children with the given type */ virtual QList< IMemento::Pointer > GetChildren(const QString& type) const; /** * Returns the Type of this memento */ virtual QString GetType() const; /** * Returns the ID of this memento */ virtual QString GetID() const; /** * @see IMemento#GetInteger */ virtual bool GetInteger(const QString& key, int& value) const; /** * @see IMemento#GetFloat */ virtual bool GetFloat(const QString& key, double& value) const; /** * @see IMemento#GetString */ virtual bool GetString(const QString& key, QString& value) const; /** * @see IMemento#GetString */ virtual bool GetBoolean(const QString& key, bool& value) const; /** * Returns the data of the Text node of the memento. Each memento is allowed * only one Text node. * * @return the data of the Text node of the memento, or null * if the memento has no Text node. */ virtual QString GetTextData() const; /** * Returns an array of all the attribute keys of the memento. This will not * be null. If there are no keys, an array of length zero will * be returned. * @return an vector with all the attribute keys of the memento */ virtual QList< QString > GetAttributeKeys() const; /** * Puts a float in this memento * * @param key the key * @param value the value */ virtual void PutFloat(const QString& key, double value); /** * Puts a integer in this memento * * @param key the key * @param value the value */ virtual void PutInteger(const QString& key, int value); /** * Puts another memento in this memento as a child * * @param key the key * @param value the value */ virtual void PutMemento(IMemento::Pointer memento); /** * Puts a string in this memento * * @param key the key * @param value the value */ virtual void PutString(const QString& key, const QString& value); /** * Puts a boolean in this memento * * @param key the key * @param value the value */ virtual void PutBoolean(const QString& key, bool value); /** * Puts a text in this memento * * @param data the text */ virtual void PutTextData(const QString& data); /** * Saves this memento's document current values to the * specified writer. * * @param writer the writer used to save the memento's document * @throws IOException if there is a problem serializing the document to the stream. */ void Save(XMLByteOutputStream& writer); //TODO: throw(IOException) /** * Returns the element of the memento * * @return the xml element */ virtual Poco::XML::Element* GetElement() const; private: /** * Returns the Text node of the memento. Each memento is allowed only * one Text node. * * @return the Text node of the memento, or null if * the memento has no Text node. */ Poco::XML::Text* GetTextNode() const; /** * Places the element's attributes into the document. * @param copyText true if the first text node should be copied */ void PutElement(Poco::XML::Element* element, bool copyText); Poco::XML::Document* factory; Poco::XML::Element* element; }; }//namespace berry #endif /* BERRYXMLMEMENTO_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryICommandImageService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryICommandImageService.h index 135b918431..6779dcc639 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryICommandImageService.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryICommandImageService.h @@ -1,103 +1,103 @@ /*=================================================================== 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 BERRYICOMMANDIMAGESERVICE_H_ #define BERRYICOMMANDIMAGESERVICE_H_ #include "../services/berryIDisposable.h" #include namespace berry { /** *

* Provides a look-up facility for images associated with commands. *

*

* The type of an image indicates the state of the associated command * within the user interface. The supported types are: TYPE_DEFAULT * (to be used for an enabled command), TYPE_DISABLED (to be used * for a disabled command) and TYPE_HOVER (to be used for an * enabled command over which the mouse is hovering). *

*

* The style of an image is an arbitrary string used to distinguish * between sets of images associated with a command. For example, a command may * appear in the menus as the default style. However, in the toolbar, the * command is simply the default action for a toolbar drop down item. As such, * perhaps a different image style is appropriate. The classic case is the "Run * Last Launched" command, which appears in the menu and the toolbar, but with * different icons in each location. *

*

* We currently support a default image style (none) and an image style of * IMAGE_STYLE_TOOLBAR. *

* * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * - * @since 3.4 */ -struct BERRY_UI_QT ICommandImageService : public IDisposable { +struct BERRY_UI_QT ICommandImageService : public IDisposable +{ - berryInterfaceMacro(ICommandImageService, berry) + berryObjectMacro(berry::ICommandImageService) /** * The default image style. This is provided when no style is requested or * when the requested style is unavailable. (Value is null) */ static const QString IMAGE_STYLE_DEFAULT; /** * The image style used for commands in a toolbar. This is useful if you * want the icon for the command in the toolbar to be different than the one * that is displayed with menu items. (Value is toolbar) */ static const QString IMAGE_STYLE_TOOLBAR; // = "toolbar"; /** * Retrieves the image associated with the given command in the * default style. * * @param commandId * The identifier to find; must not be null. * @return An image appropriate for the given command; may be * null. */ virtual QIcon GetImage(const QString& commandId) = 0; /** * Retrieves the image associated with the given command in the * given style. * * @param commandId * The identifier to find; must not be null. * @param style * The style of the image to retrieve; may be null. * @return An image appropriate for the given command; A null QIcon * if the given image style cannot be found. */ virtual QIcon GetImage(const QString& commandId, const QString& style) = 0; }; } -Q_DECLARE_INTERFACE(berry::ICommandImageService, "org.blueberry.ui.qt.ICommandImageService") +Q_DECLARE_INTERFACE(berry::ICommandImageService, "org.blueberry.ui.ICommandImageService") #endif /* BERRYICOMMANDIMAGESERVICE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryICommandService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryICommandService.h index 3647eefe67..0d33acfa3a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryICommandService.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryICommandService.h @@ -1,376 +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. ===================================================================*/ #ifndef BERRYICOMMANDSERVICE_H_ #define BERRYICOMMANDSERVICE_H_ #include "../services/berryIDisposable.h" #include namespace berry { struct IExecutionListener; struct IHandler; struct IElementReference; class UIElement; class Command; class CommandCategory; class ParameterizedCommand; class ParameterType; /** *

* Provides services related to the command architecture within the workbench. * This service can be used to access the set of commands and command * categories. *

*

* This service can be acquired from your service locator: *

  *  ICommandService service = (ICommandService) getSite().getService(ICommandService.class);
  * 
*
    *
  • This service is available globally.
  • *
*

* @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ struct BERRY_UI_QT ICommandService : public IDisposable { - berryInterfaceMacro(ICommandService, berry) + berryObjectMacro(berry::ICommandService) /** * The identifier of the category in which all auto-generated commands will * appear. This value must never be null. */ static const QString AUTOGENERATED_CATEGORY_ID(); /** * Adds an execution listener to the command service. This listener will be * notified as commands are executed. *

* Note: listeners should be removed when no longer necessary. If * not, they will be removed when the IServiceLocator used to acquire this * service is disposed. *

* * @param listener * The listener to add; must not be null. * @see #removeExecutionListener(IExecutionListener) */ virtual void AddExecutionListener(IExecutionListener* listener) = 0; /** * Sets the name and description of the category for uncategorized commands. * This is the category that will be returned if * {@link #getCategory(String)} is called with null. * * @param name * The name of the category for uncategorized commands; must not * be null. * @param description * The description of the category for uncategorized commands; * may be null. */ virtual void DefineUncategorizedCategory(const QString& name, const QString& description) = 0; /** *

* Returns a {@link ParameterizedCommand} with a command and * parameterizations as specified in the provided * serializedParameterizedCommand string. The * serializedParameterizedCommand must use the format * returned by {@link ParameterizedCommand#serialize()} and described in the * Javadoc for that method. *

*

* If a parameter id encoded in the * serializedParameterizedCommand does not exist in the * encoded command, that parameter id and value are ignored. A given * parameter id should not be used more than once in * serializedParameterizedCommand. This will not result in * an exception, but the value of the parameter when the command is executed * cannot be specified here. *

*

* This method will never return null, however it may throw * an exception if there is a problem processing the serialization string or * the encoded command is undefined. *

* * @param serializedParameterizedCommand * a String representing a command id and * parameter ids and values * @return a ParameterizedCommand with the command and * parameterizations encoded in the * serializedParameterizedCommand * @throws NotDefinedException * if the command indicated in * serializedParameterizedCommand is not defined * @throws SerializationException * if there is an error deserializing * serializedParameterizedCommand * @see ParameterizedCommand#serialize() * @see CommandManager#deserialize(String) */ virtual SmartPointer Deserialize(const QString& serializedParameterizedCommand) const = 0; /** * Retrieves the category with the given identifier. If no such category * exists, then an undefined category with the given id is created. * * @param categoryId * The identifier to find. If the category is null, * then a category suitable for uncategorized items is defined * and returned. * @return A category with the given identifier, either defined or * undefined. */ virtual SmartPointer GetCategory(const QString& categoryId) const = 0; /** * Retrieves the command with the given identifier. If no such command * exists, then an undefined command with the given id is created. * * @param commandId * The identifier to find; must not be null. * @return A command with the given identifier, either defined or undefined. */ virtual SmartPointer GetCommand(const QString& commandId) const = 0; /** * Returns the collection of all of the defined categories in the workbench. * * @return The collection of categories (Category) that are * defined; never null, but may be empty. */ virtual QList > GetDefinedCategories() const = 0; /** * Returns the collection of the identifiers for all of the defined * categories in the workbench. * * @return The collection of category identifiers (String) * that are defined; never null, but may be empty. */ virtual QStringList GetDefinedCategoryIds() const = 0; /** * Returns the collection of the identifiers for all of the defined commands * in the workbench. * * @return The collection of command identifiers (String) * that are defined; never null, but may be empty. */ virtual QStringList GetDefinedCommandIds() const = 0; /** * Returns the collection of all of the defined commands in the workbench. * * @return The collection of commands (Command) that are * defined; never null, but may be empty. */ virtual QList > GetDefinedCommands() const = 0; /** * Returns the collection of the identifiers for all of the defined command * parameter types in the workbench. * * @return The collection of command parameter type identifiers (String) * that are defined; never null, but may be empty. */ virtual QStringList GetDefinedParameterTypeIds() const = 0; /** * Returns the collection of all of the defined command parameter types in * the workbench. * * @return The collection of command parameter types (ParameterType) * that are defined; never null, but may be empty. */ virtual QList > GetDefinedParameterTypes() const = 0; /** * Gets the help context identifier for a particular command. The command's * handler is first checked for a help context identifier. If the handler * does not have a help context identifier, then the help context identifier * for the command is returned. If neither has a help context identifier, * then null is returned. * * @param command * The command for which the help context should be retrieved; * must not be null. * @return The help context identifier to use for the given command; may be * null. * @throws NotDefinedException * If the given command is not defined. */ virtual QString GetHelpContextId(const SmartPointer& command) const = 0; /** * Gets the help context identifier for a particular command. The command's * handler is first checked for a help context identifier. If the handler * does not have a help context identifier, then the help context identifier * for the command is returned. If neither has a help context identifier, * then null is returned. * * @param commandId * The identifier of the command for which the help context * should be retrieved; must not be null. * @return The help context identifier to use for the given command; may be * null. * @throws NotDefinedException * If the command with the given identifier is not defined. */ virtual QString GetHelpContextId(const QString& commandId) const = 0; /** * Retrieves the command parameter type with the given identifier. If no * such parameter type exists, then an undefined parameter type with the * given id is created. * * @param parameterTypeId * The identifier to find; must not be null. * @return A command parameter type with the given identifier, either * defined or undefined. */ virtual SmartPointer GetParameterType(const QString& parameterTypeId) const = 0; /** *

* Reads the command information from the registry and the preferences. This * will overwrite any of the existing information in the command service. * This method is intended to be called during start-up. When this method * completes, this command service will reflect the current state of the * registry and preference store. *

*/ virtual void ReadRegistry() = 0; /** * Removes an execution listener from the command service. * * @param listener * The listener to remove; must not be null. */ virtual void RemoveExecutionListener(IExecutionListener* listener) = 0; /** * Sets the help context identifier to associate with a particular handler. * * @param handler * The handler with which to register a help context identifier; * must not be null. * @param helpContextId * The help context identifier to register; may be * null if the help context identifier should be * removed. */ virtual void SetHelpContextId(const SmartPointer& handler, const QString& helpContextId) = 0; /** * Register that this element accepts callbacks for this parameterized * command. *

* Note: elements should be removed when no longer necessary. If * not, they will be removed when the IServiceLocator used to acquire this * service is disposed. *

* * @param command * The parameterized command that is already specialized. Must * not be null. * @param element * The callback to register for this specialized command * instance. Must not be null. * @return A reference for the registered element that can be used to * unregister it. * @throws NotDefinedException * If the command included in the ParameterizedCommand is not * defined, or the element is null. * @see #unregisterElement(IElementReference) */ virtual SmartPointer RegisterElementForCommand( const SmartPointer& command, const SmartPointer& element) = 0; /** * Re-register a callback element provided by the ICommandService. This * element reference must not currently be held by the ICommandService. i.e. * it must have been removed using * {@link #unregisterElement(IElementReference)}. *

* Note: elements should be removed when no longer necessary. If * not, they will be removed when the IServiceLocator used to acquire this * service is disposed. *

* * @param elementReference * The reference to re-register. Must not be null. * @see #unregisterElement(IElementReference) */ virtual void RegisterElement(const SmartPointer& elementReference) = 0; /** * Unregister an element callback. It will be removed from the * ICommandService. The same service that is used to register an element for * a command must be used to unregister the element. * * @param elementReference * The callback reference that was provided by the command * service on registration. Must not be null. */ virtual void UnregisterElement(const SmartPointer& elementReference) = 0; /** * Refresh any elements registered against the command with the given id. * It allows the active handler the opportunity to provide user feedback. If * the command is parameterized, some of the parameters can be specified to * help narrow down which elements to refresh. *

* The service locator used in registering the element can also be used to * scope the search. For example: if you wanted all elements for your * command but only within the part's workbench window, you could use: * *

    * Map filter = new HashMap();
    * filter.put(IServiceScopes.WINDOW_SCOPE, getSite().getPage()
    *    .getWorkbenchWindow());
    * commandService.refreshElements(commandId, filter);
    * 
* *

* * @param commandId * The command id to refresh if it has registered eleemnts. * @param filter * key-value pairs that can narrow down the callbacks to return. * The parameters are ANDed together. This may be * null. */ virtual void RefreshElements(const QString& commandId, const QHash& filter) = 0; }; } -Q_DECLARE_INTERFACE(berry::ICommandService, "org.blueberry.ui.qt.ICommandService") +Q_DECLARE_INTERFACE(berry::ICommandService, "org.blueberry.ui.ICommandService") #endif /* BERRYICOMMANDSERVICE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryIElementReference.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryIElementReference.h index 5c30824a52..38e89c08b3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryIElementReference.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryIElementReference.h @@ -1,68 +1,68 @@ /*=================================================================== 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 BERRYIELEMENTREFERENCE_H_ #define BERRYIELEMENTREFERENCE_H_ #include #include namespace berry { class UIElement; /** * the ICommandService will return a reference for all callbacks that are * registered. This reference can be used to unregister the specific callback. *

* Similar in functionality to an IHandlerActivation. This interface should * not be implemented or extended by clients. *

*/ struct IElementReference : public Object { - berryInterfaceMacro(IElementReference, berry) + berryObjectMacro(berry::IElementReference) /** * The command id that this callback was registered against. * * @return The command id. Will not be null. */ virtual QString GetCommandId() const = 0; /** * The callback that was registered. * * @return Adapts to provide appropriate user feedback. Will not be * null. */ virtual SmartPointer GetElement() const = 0; /** * Parameters that help scope this callback registration. For example, it * can include parameters from the ParameterizedCommand. * * @return scoping parameters. Will not be null. */ virtual QHash GetParameters() const = 0; }; } #endif /* BERRYIELEMENTREFERENCE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryIElementUpdater.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryIElementUpdater.h index c44bcaa429..5ad6de03d4 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryIElementUpdater.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryIElementUpdater.h @@ -1,56 +1,56 @@ /*=================================================================== 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 BERRYIELEMENTUPDATER_H #define BERRYIELEMENTUPDATER_H #include namespace berry { class UIElement; /** * An IHandler for a command that expects to provide feedback through the * registered element mechanism must implement this interface. */ struct IElementUpdater : public virtual Object { - berryInterfaceMacro(IElementUpdater, berry) + berryObjectMacro(berry::IElementUpdater) /** * Whenever the elements for a command are refreshed, this method is called * on the active handler for that command. *

* Note: Handlers must never cache the element, which can disappear * or be replaced at any time. Everybody should go through the * ICommandService refreshElements(*) method. *

* * @param element * An element for a specific UI element. Will not be * null. * @param parameters * Any parameters registered with the callback. It may be empty. */ virtual void UpdateElement(UIElement* element, const QHash& parameters) = 0; }; } #endif // BERRYIELEMENTUPDATER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryIMenuService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryIMenuService.h index 48c97fd35d..828574eee1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryIMenuService.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/commands/berryIMenuService.h @@ -1,122 +1,122 @@ /*=================================================================== 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 BERRYIMENUSERVICE_H_ #define BERRYIMENUSERVICE_H_ #include namespace berry { class AbstractContributionFactory; class ContributionManager; struct IEvaluationContext; /** *

* Provides services related to the menu architecture within the workbench. It * can be used to contribute additional items to the menu, tool bar and status * line. *

*

* This service can be acquired from your service locator: *

  *  IMenuService service = (IMenuService) getSite().getService(IMenuService.class);
  * 
*
    *
  • This service is available globally.
  • *
*

* * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ struct IMenuService : public IServiceWithSources { - berryInterfaceMacro(IMenuService, berry) + berryObjectMacro(berry::IMenuService) /** * Contribute and initialize the contribution factory. This should only be * called once per factory. After the call, the factory should be treated as * an unmodifiable object. *

* Note: factories should be removed when no longer necessary. If * not, they will be removed when the IServiceLocator used to acquire this * service is disposed. *

* * @param factory * the contribution factory. Must not be null * @see #removeContributionFactory(AbstractContributionFactory) */ virtual void AddContributionFactory(const SmartPointer& factory) = 0; /** * Remove the contributed factory from the menu service. If the factory is * not contained by this service, this call does nothing. * * @param factory * the contribution factory to remove. Must not be * null. */ virtual void RemoveContributionFactory(const SmartPointer& factory) = 0; /** * Populate a ContributionManager at the specified starting * location with a set of IContributionItemss. It applies * AbstractContributionFactorys that are stored against the * provided location. * * @param mgr * The ContributionManager to populate * @param location * The starting location to begin populating this contribution * manager. The format is the Menu API URI format. * @see #releaseContributions(ContributionManager) */ virtual void PopulateContributionManager(ContributionManager* mgr, const QString& location) = 0; /** * Before calling dispose() on a ContributionManager populated by the menu * service, you must inform the menu service to release its contributions. * This takes care of unregistering any IContributionItems that have their * visibleWhen clause managed by this menu service. * * @param mgr * The manager that was populated by a call to * {@link #populateContributionManager(ContributionManager, String)} */ virtual void ReleaseContributions(ContributionManager* mgr) = 0; /** * Get the current state of eclipse as seen by the menu service. * * @return an IEvaluationContext containing state variables. * * @see org.eclipse.ui.ISources * @see org.eclipse.ui.services.IEvaluationService */ virtual SmartPointer GetCurrentState() const = 0; }; } -Q_DECLARE_INTERFACE(berry::IMenuService, "org.blueberry.ui.qt.IMenuService") +Q_DECLARE_INTERFACE(berry::IMenuService, "org.blueberry.ui.IMenuService") #endif /* BERRYIMENUSERVICE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/dialogs/berryIDialog.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/dialogs/berryIDialog.h index f2cc3890db..19d9e856d2 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/dialogs/berryIDialog.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/dialogs/berryIDialog.h @@ -1,70 +1,70 @@ /*=================================================================== 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 BERRYIDIALOG_H_ #define BERRYIDIALOG_H_ #include #include #include namespace berry { /** * \ingroup org_blueberry_ui_qt * */ struct BERRY_UI_QT IDialog : public virtual Object { - berryInterfaceMacro(IDialog, berry); + berryObjectMacro(berry::IDialog) /** * Constant for a dialog with no image (value 0). */ const static int NONE; // = 0; /** * Constant for a dialog with an error image (value 1). */ const static int ERR; // = 1; /** * Constant for a dialog with an info image (value 2). */ const static int INFORMATION; // = 2; /** * Constant for a dialog with a question image (value 3). */ const static int QUESTION; // = 3; /** * Constant for a dialog with a warning image (value 4). */ const static int WARNING; // = 4; enum ReturnCode { OK, CANCEL }; ~IDialog(); virtual int Open() = 0; }; } #endif /*BERRYIDIALOG_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/dialogs/berryIShowViewDialog.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/dialogs/berryIShowViewDialog.h index be9928393a..5b09345395 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/dialogs/berryIShowViewDialog.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/dialogs/berryIShowViewDialog.h @@ -1,44 +1,44 @@ /*=================================================================== 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 BERRYISHOWVIEWDIALOG_H_ #define BERRYISHOWVIEWDIALOG_H_ #include "berryIDialog.h" #include #include "berryIViewDescriptor.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * */ struct BERRY_UI_QT IShowViewDialog : public IDialog { - berryInterfaceMacro(IShowViewDialog, berry); + berryObjectMacro(berry::IShowViewDialog); ~IShowViewDialog(); virtual QList GetSelection() = 0; }; } #endif /*BERRYISHOWVIEWDIALOG_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkIControlListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkIControlListener.h index b160b27c7b..7a019ecb60 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkIControlListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkIControlListener.h @@ -1,240 +1,240 @@ /*=================================================================== 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 BERRYGUITKICONTROLLISTENER_H_ #define BERRYGUITKICONTROLLISTENER_H_ #include #include #include #include "berryGuiTkControlEvent.h" namespace berry { namespace GuiTk { /** * Classes which implement this interface provide methods * that deal with the events that are generated by moving * and resizing controls. *

* After creating an instance of a class that implements * this interface it can be added to a control using the * addControlListener method and removed using * the removeControlListener method. When a * control is moved or resized, the appropriate method will * be invoked. *

* * @see ControlAdapter * @see ControlEvent */ struct BERRY_UI_QT IControlListener: public virtual Object { - berryInterfaceMacro(IControlListener, berry); + berryObjectMacro(berry::GuiTk::IControlListener) struct BERRY_UI_QT Events { enum Type { NONE = 0x00000000, MOVED = 0x00000001, RESIZED = 0x00000002, ACTIVATED = 0x00000004, DESTROYED = 0x00000008, ALL = 0xffffffff }; - BERRY_DECLARE_FLAGS(Types, Type) + Q_DECLARE_FLAGS(Types, Type) typedef Message1 EventType; EventType movedEvent; EventType resizedEvent; EventType activatedEvent; EventType destroyedEvent; void AddListener(IControlListener::Pointer listener); void RemoveListener(IControlListener::Pointer listener); private: typedef MessageDelegate1 Delegate; }; virtual ~IControlListener(); virtual Events::Types GetEventTypes() const = 0; /** * Sent when the location (x, y) of a control changes relative * to its parent (or relative to the display, for Shells). * * @param e an event containing information about the move */ virtual void ControlMoved(ControlEvent::Pointer /*e*/) { } /** * Sent when the size (width, height) of a control changes. * * @param e an event containing information about the resize */ virtual void ControlResized(ControlEvent::Pointer /*e*/) { } virtual void ControlActivated(ControlEvent::Pointer /*e*/) { } virtual void ControlDestroyed(ControlEvent::Pointer /*e*/) { } }; template struct ControlMovedAdapter: public IControlListener { typedef R Listener; typedef void (R::*Callback)(ControlEvent::Pointer); ControlMovedAdapter(R* l, Callback c) : listener(l), callback(c) { poco_assert(listener); poco_assert(callback); } Events::Types GetEventTypes() const { return Events::MOVED; } void ControlMoved(ControlEvent::Pointer e) { (listener->*callback)(e); } private: Listener* listener; Callback callback; }; template struct ControlResizedAdapter: public IControlListener { typedef R Listener; typedef void (R::*Callback)(ControlEvent::Pointer); ControlResizedAdapter(R* l, Callback c) : listener(l), callback(c) { poco_assert(listener); poco_assert(callback); } Events::Types GetEventTypes() const { return Events::RESIZED; } void ControlResized(ControlEvent::Pointer e) { (listener->*callback)(e); } private: Listener* listener; Callback callback; }; template struct ControlActivatedAdapter: public IControlListener { typedef R Listener; typedef void (R::*Callback)(ControlEvent::Pointer); ControlActivatedAdapter(R* l, Callback c) : listener(l), callback(c) { poco_assert(listener); poco_assert(callback); } Events::Types GetEventTypes() const { return Events::ACTIVATED; } void ControlActivated(ControlEvent::Pointer e) { (listener->*callback)(e); } private: Listener* listener; Callback callback; }; template struct ControlDestroyedAdapter: public IControlListener { typedef R Listener; typedef void (R::*Callback)(ControlEvent::Pointer); ControlDestroyedAdapter(R* l, Callback c) : listener(l), callback(c) { poco_assert(listener); poco_assert(callback); } Events::Types GetEventTypes() const { return Events::DESTROYED; } void ControlDestroyed(ControlEvent::Pointer e) { (listener->*callback)(e); } private: Listener* listener; Callback callback; }; } } -BERRY_DECLARE_OPERATORS_FOR_FLAGS(berry::GuiTk::IControlListener::Events::Types) +Q_DECLARE_OPERATORS_FOR_FLAGS(berry::GuiTk::IControlListener::Events::Types) #endif /* BERRYGUITKICONTROLLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkIMenuListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkIMenuListener.h index c87ecbf2e9..b16bd5a77f 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkIMenuListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkIMenuListener.h @@ -1,90 +1,78 @@ /*=================================================================== 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 BERRYGUITKIMENULISTENER_H_ #define BERRYGUITKIMENULISTENER_H_ #include #include #include #include namespace berry { namespace GuiTk { /** - * Classes which implement this interface provide methods - * that deal with the events that are generated by moving - * and resizing controls. - *

- * After creating an instance of a class that implements - * this interface it can be added to a control using the - * addControlListener method and removed using - * the removeControlListener method. When a - * control is moved or resized, the appropriate method will - * be invoked. - *

+ * A menu listener that gets informed when a menu is about to show. * - * @see ControlAdapter - * @see ControlEvent + * @see MenuManager#addMenuListener */ struct BERRY_UI_QT IMenuListener: public virtual Object { - - berryInterfaceMacro(IMenuListener, berry); + berryObjectMacro(berry::GuiTk::IMenuListener) struct Events { typedef Message<> MenuEvent; MenuEvent menuAboutToShow; MenuEvent menuAboutToHide; void AddListener(IMenuListener::Pointer listener); void RemoveListener(IMenuListener::Pointer listener); private: typedef MessageDelegate Delegate; }; - /** - * Notifies this listener that the menu is about to be shown by - * the given menu manager. - * - * @param manager the menu manager - */ - virtual void MenuAboutToShow() = 0; + /** + * Notifies this listener that the menu is about to be shown by + * the given menu manager. + * + * @param manager the menu manager + */ + virtual void MenuAboutToShow() = 0; /** * Notifies this listener that the menu is about to be hidden by * the given menu manager. * * @param manager the menu manager */ virtual void MenuAboutToHide() = 0; }; } } #endif /* BERRYGUITKIMENULISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkISelectionListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkISelectionListener.h index 44ed5da12f..0e335cdd95 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkISelectionListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkISelectionListener.h @@ -1,102 +1,102 @@ /*=================================================================== 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 BERRYGUITKISELECTIONLISTENER_H_ #define BERRYGUITKISELECTIONLISTENER_H_ #include #include #include "berryGuiTkSelectionEvent.h" namespace berry { namespace GuiTk { /** * Classes which implement this interface provide methods * that deal with the events that are generated when selection * occurs in a control. *

* After creating an instance of a class that implements * this interface it can be added to a control using the * addSelectionListener method and removed using * the removeSelectionListener method. When * selection occurs in a control the appropriate method * will be invoked. *

* * @see SelectionAdapter * @see SelectionEvent */ struct BERRY_UI_QT ISelectionListener: public virtual Object { - berryInterfaceMacro(ISelectionListener, berry); + berryObjectMacro(berry::GuiTk::ISelectionListener) struct BERRY_UI_QT Events { typedef Message1 EventType; EventType selected; EventType defaultSelected; void AddListener(ISelectionListener::Pointer listener); void RemoveListener(ISelectionListener::Pointer listener); private: typedef MessageDelegate1 Delegate; }; virtual ~ISelectionListener(); /** * Sent when selection occurs in the control. *

* For example, selection occurs in a List when the user selects * an item or items with the keyboard or mouse. On some platforms, * the event occurs when a mouse button or key is pressed. On others, * it happens when the mouse or key is released. The exact key or * mouse gesture that causes this event is platform specific. *

* * @param e an event containing information about the selection */ virtual void WidgetSelected(SelectionEvent::Pointer /*e*/) {} /** * Sent when default selection occurs in the control. *

* For example, on some platforms default selection occurs in a List * when the user double-clicks an item or types return in a Text. * On some platforms, the event occurs when a mouse button or key is * pressed. On others, it happens when the mouse or key is released. * The exact key or mouse gesture that causes this event is platform * specific. *

* * @param e an event containing information about the default selection */ virtual void WidgetDefaultSelected(SelectionEvent::Pointer /*e*/) {} }; } } #endif /* BERRYGUITKISELECTIONLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryHandlerUtil.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryHandlerUtil.cpp index 18e192433e..ef0e53de46 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryHandlerUtil.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryHandlerUtil.cpp @@ -1,354 +1,413 @@ /*=================================================================== 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 "berryHandlerUtil.h" #include #include #include "berryISources.h" +#include "berryRegistryToggleState.h" +#include "berryRadioState.h" +#include "berryObjects.h" +#include "berryObjectString.h" namespace berry { -void HandlerUtil::NoVariableFound(ExecutionEvent::Pointer event, +void HandlerUtil::NoVariableFound(const ExecutionEvent::ConstPointer& event, const QString& name) { throw ExecutionException("No " + name + " found while executing " + event->GetCommand()->GetId()); } -void HandlerUtil::IncorrectTypeFound(ExecutionEvent::Pointer event, +void HandlerUtil::IncorrectTypeFound(const ExecutionEvent::ConstPointer& event, const QString& name, const QString& expectedType, const QString& wrongType) { throw ExecutionException("Incorrect type for " + name + " found while executing " + event->GetCommand()->GetId() + ", expected " + expectedType + " found " + wrongType); } -Object::Pointer HandlerUtil::GetVariable( - ExecutionEvent::Pointer event, const QString& name) +Object::ConstPointer HandlerUtil::GetVariable( + const ExecutionEvent::ConstPointer& event, const QString& name) { if (IEvaluationContext::ConstPointer evalContext = event->GetApplicationContext().Cast()) { - Object::Pointer var = evalContext->GetVariable(name); - return var == IEvaluationContext::UNDEFINED_VARIABLE ? Object::Pointer() : var; + Object::ConstPointer var = evalContext->GetVariable(name); + return var == IEvaluationContext::UNDEFINED_VARIABLE ? Object::ConstPointer() : var; } - return Object::Pointer(); + return Object::ConstPointer(); } -Object::Pointer HandlerUtil::GetVariableChecked( - ExecutionEvent::Pointer event, const QString& name) +Object::ConstPointer HandlerUtil::GetVariableChecked( + const ExecutionEvent::ConstPointer& event, const QString& name) { - Object::Pointer o(HandlerUtil::GetVariable(event, name)); + Object::ConstPointer o(HandlerUtil::GetVariable(event, name)); if (o.IsNull()) { HandlerUtil::NoVariableFound(event, name); } return o; } -Object::Pointer HandlerUtil::GetVariable( +Object::ConstPointer HandlerUtil::GetVariable( Object::Pointer context, const QString& name) { IEvaluationContext::Pointer eval(context.Cast()); if (eval.IsNotNull()) { - Object::Pointer var = eval->GetVariable(name); - return var == IEvaluationContext::UNDEFINED_VARIABLE ? Object::Pointer() : var; + Object::ConstPointer var = eval->GetVariable(name); + return var == IEvaluationContext::UNDEFINED_VARIABLE ? Object::ConstPointer() : var; } - return Object::Pointer(0); + return Object::ConstPointer(0); } -HandlerUtil::StringVectorType::Pointer HandlerUtil::GetActiveContexts( - ExecutionEvent::Pointer event) +HandlerUtil::StringVectorType::ConstPointer HandlerUtil::GetActiveContexts( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o(HandlerUtil::GetVariable(event, - ISources::ACTIVE_CONTEXT_NAME())); - return o.Cast(); + Object::ConstPointer o(HandlerUtil::GetVariable(event, ISources::ACTIVE_CONTEXT_NAME())); + return o.Cast(); } -HandlerUtil::StringVectorType::Pointer HandlerUtil::GetActiveContextsChecked( - ExecutionEvent::Pointer event) +HandlerUtil::StringVectorType::ConstPointer HandlerUtil::GetActiveContextsChecked( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o(HandlerUtil::GetVariableChecked(event, + Object::ConstPointer o(HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_CONTEXT_NAME())); - if (o.Cast().IsNull()) + if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_CONTEXT_NAME(), "StringVectorType", o->GetClassName()); } - return o.Cast(); + return o.Cast(); } -//IEditorPart::Pointer HandlerUtil::GetActiveEditor(ExecutionEvent::Pointer event) +//IEditorPart::Pointer HandlerUtil::GetActiveEditor(const ExecutionEvent::ConstPointer& event) //{ // Object::Pointer o(HandlerUtil::GetVariable(event, // ISources::ACTIVE_EDITOR_NAME)); // return o.Cast(); //} //IEditorPart::Pointer HandlerUtil::GetActiveEditorChecked( -// ExecutionEvent::Pointer event) +// const ExecutionEvent::ConstPointer& event) //{ // Object::Pointer o = HandlerUtil::GetVariableChecked(event, // ISources::ACTIVE_EDITOR_NAME); // if (o.Cast().IsNull()) // { // HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_EDITOR_NAME, // "IEditorPart", o->GetClassName()); // } // return (IEditorPart) o; //} -ObjectString::Pointer HandlerUtil::GetActiveEditorId(ExecutionEvent::Pointer event) +ObjectString::ConstPointer HandlerUtil::GetActiveEditorId(const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariable(event, - ISources::ACTIVE_EDITOR_ID_NAME()); - return o.Cast(); + Object::ConstPointer o = HandlerUtil::GetVariable(event, + ISources::ACTIVE_EDITOR_ID_NAME()); + return o.Cast(); } -ObjectString::Pointer HandlerUtil::GetActiveEditorIdChecked( - ExecutionEvent::Pointer event) +ObjectString::ConstPointer HandlerUtil::GetActiveEditorIdChecked( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariableChecked(event, - ISources::ACTIVE_EDITOR_ID_NAME()); - if (o.Cast().IsNull()) + Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, + ISources::ACTIVE_EDITOR_ID_NAME()); + if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_EDITOR_ID_NAME(), - "QString", o->GetClassName()); + "QString", o->GetClassName()); } - return o.Cast(); + return o.Cast(); } -IWorkbenchPart::Pointer HandlerUtil::GetActivePart(ExecutionEvent::Pointer event) +IWorkbenchPart::ConstPointer HandlerUtil::GetActivePart(const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariable(event, - ISources::ACTIVE_PART_NAME()); - return o.Cast(); + Object::ConstPointer o = HandlerUtil::GetVariable(event, + ISources::ACTIVE_PART_NAME()); + return o.Cast(); } -IWorkbenchPart::Pointer HandlerUtil::GetActivePartChecked( - ExecutionEvent::Pointer event) +IWorkbenchPart::ConstPointer HandlerUtil::GetActivePartChecked( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariableChecked(event, + Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_PART_NAME()); - if (o.Cast().IsNull()) + if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_PART_NAME(), - "IWorkbenchPart", o->GetClassName()); + "IWorkbenchPart", o->GetClassName()); } - return o.Cast(); + return o.Cast(); } -ObjectString::Pointer HandlerUtil::GetActivePartId(ExecutionEvent::Pointer event) +ObjectString::ConstPointer HandlerUtil::GetActivePartId(const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariable(event, - ISources::ACTIVE_PART_ID_NAME()); - return o.Cast(); + Object::ConstPointer o = HandlerUtil::GetVariable(event, + ISources::ACTIVE_PART_ID_NAME()); + return o.Cast(); } -ObjectString::Pointer HandlerUtil::GetActivePartIdChecked( - ExecutionEvent::Pointer event) +ObjectString::ConstPointer HandlerUtil::GetActivePartIdChecked( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariableChecked(event, - ISources::ACTIVE_PART_ID_NAME()); - if (o.Cast().IsNull()) + Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, + ISources::ACTIVE_PART_ID_NAME()); + if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_PART_ID_NAME(), - "QString", o->GetClassName()); + "QString", o->GetClassName()); } - return o.Cast(); + return o.Cast(); } -IWorkbenchPartSite::Pointer HandlerUtil::GetActiveSite( - ExecutionEvent::Pointer event) +IWorkbenchPartSite::ConstPointer HandlerUtil::GetActiveSite( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariable(event, - ISources::ACTIVE_SITE_NAME()); - return o.Cast(); + Object::ConstPointer o = HandlerUtil::GetVariable(event, + ISources::ACTIVE_SITE_NAME()); + return o.Cast(); } -IWorkbenchPartSite::Pointer HandlerUtil::GetActiveSiteChecked( - ExecutionEvent::Pointer event) +IWorkbenchPartSite::ConstPointer HandlerUtil::GetActiveSiteChecked( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariableChecked(event, + Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_SITE_NAME()); - if (o.Cast().IsNull()) + if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_SITE_NAME(), - "IWorkbenchSitePart", o->GetClassName()); + "IWorkbenchSitePart", o->GetClassName()); } - return o.Cast(); + return o.Cast(); } -ISelection::Pointer HandlerUtil::GetCurrentSelection( - ExecutionEvent::Pointer event) +ISelection::ConstPointer HandlerUtil::GetCurrentSelection( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariable(event, - ISources::ACTIVE_CURRENT_SELECTION_NAME()); - return o.Cast(); + Object::ConstPointer o = HandlerUtil::GetVariable(event, + ISources::ACTIVE_CURRENT_SELECTION_NAME()); + return o.Cast(); } -ISelection::Pointer HandlerUtil::GetCurrentSelectionChecked( - ExecutionEvent::Pointer event) +ISelection::ConstPointer HandlerUtil::GetCurrentSelectionChecked( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariableChecked(event, + Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_CURRENT_SELECTION_NAME()); - if (o.Cast().IsNull()) + if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, - ISources::ACTIVE_CURRENT_SELECTION_NAME(), "ISelection", - o->GetClassName()); + ISources::ACTIVE_CURRENT_SELECTION_NAME(), "ISelection", + o->GetClassName()); } - return o.Cast(); + return o.Cast(); } -HandlerUtil::StringVectorType::Pointer HandlerUtil::GetActiveMenus( - ExecutionEvent::Pointer event) +HandlerUtil::StringVectorType::ConstPointer HandlerUtil::GetActiveMenus( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariable(event, - ISources::ACTIVE_MENU_NAME()); - return o.Cast(); + Object::ConstPointer o = HandlerUtil::GetVariable(event, + ISources::ACTIVE_MENU_NAME()); + return o.Cast(); } -HandlerUtil::StringVectorType::Pointer HandlerUtil::GetActiveMenusChecked( - ExecutionEvent::Pointer event) +HandlerUtil::StringVectorType::ConstPointer HandlerUtil::GetActiveMenusChecked( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariableChecked(event, - ISources::ACTIVE_MENU_NAME()); - if (o.Cast().IsNull()) + Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, + ISources::ACTIVE_MENU_NAME()); + if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_MENU_NAME(), - "StringVectorType", o->GetClassName()); + "StringVectorType", o->GetClassName()); } - return o.Cast(); + return o.Cast(); } -ISelection::Pointer HandlerUtil::GetActiveMenuSelection( - ExecutionEvent::Pointer event) +ISelection::ConstPointer HandlerUtil::GetActiveMenuSelection( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariable(event, - ISources::ACTIVE_MENU_SELECTION_NAME()); - return o.Cast(); + Object::ConstPointer o = HandlerUtil::GetVariable(event, + ISources::ACTIVE_MENU_SELECTION_NAME()); + return o.Cast(); } -ISelection::Pointer HandlerUtil::GetActiveMenuSelectionChecked( - ExecutionEvent::Pointer event) +ISelection::ConstPointer HandlerUtil::GetActiveMenuSelectionChecked( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariableChecked(event, + Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_MENU_SELECTION_NAME()); - if (o.Cast().IsNull()) + if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, - ISources::ACTIVE_MENU_SELECTION_NAME(), "ISelection", o->GetClassName()); + ISources::ACTIVE_MENU_SELECTION_NAME(), + "ISelection", o->GetClassName()); } - return o.Cast(); + return o.Cast(); } -IWorkbenchWindow::Pointer HandlerUtil::GetActiveWorkbenchWindow( - ExecutionEvent::Pointer event) +IWorkbenchWindow::ConstPointer HandlerUtil::GetActiveWorkbenchWindow( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariable(event, - ISources::ACTIVE_WORKBENCH_WINDOW_NAME()); - return o.Cast(); + Object::ConstPointer o = HandlerUtil::GetVariable(event, + ISources::ACTIVE_WORKBENCH_WINDOW_NAME()); + return o.Cast(); } -IWorkbenchWindow::Pointer HandlerUtil::GetActiveWorkbenchWindowChecked( - ExecutionEvent::Pointer event) +IWorkbenchWindow::ConstPointer HandlerUtil::GetActiveWorkbenchWindowChecked( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariableChecked(event, - ISources::ACTIVE_WORKBENCH_WINDOW_NAME()); - if (o.Cast().IsNull()) + Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, + ISources::ACTIVE_WORKBENCH_WINDOW_NAME()); + if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, - ISources::ACTIVE_WORKBENCH_WINDOW_NAME(), "IWorkbenchWindow", - o->GetClassName()); + ISources::ACTIVE_WORKBENCH_WINDOW_NAME(), "IWorkbenchWindow", + o->GetClassName()); } - return o.Cast(); + return o.Cast(); } -ISelection::Pointer HandlerUtil::GetActiveMenuEditorInput( - ExecutionEvent::Pointer event) +ISelection::ConstPointer HandlerUtil::GetActiveMenuEditorInput( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariable(event, - ISources::ACTIVE_MENU_EDITOR_INPUT_NAME()); - return o.Cast(); + Object::ConstPointer o = HandlerUtil::GetVariable(event, + ISources::ACTIVE_MENU_EDITOR_INPUT_NAME()); + return o.Cast(); } -ISelection::Pointer HandlerUtil::GetActiveMenuEditorInputChecked( - ExecutionEvent::Pointer event) +ISelection::ConstPointer HandlerUtil::GetActiveMenuEditorInputChecked( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariableChecked(event, + Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_MENU_EDITOR_INPUT_NAME()); - if (o.Cast().IsNull()) + if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_MENU_EDITOR_INPUT_NAME(), "ISelection", o->GetClassName()); } - return o.Cast(); + return o.Cast(); } -ISelection::Pointer HandlerUtil::GetShowInSelection( - ExecutionEvent::Pointer event) +ISelection::ConstPointer HandlerUtil::GetShowInSelection( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariable(event, + Object::ConstPointer o = HandlerUtil::GetVariable(event, ISources::SHOW_IN_SELECTION()); - return o.Cast(); + return o.Cast(); } -ISelection::Pointer HandlerUtil::GetShowInSelectionChecked( - ExecutionEvent::Pointer event) +ISelection::ConstPointer HandlerUtil::GetShowInSelectionChecked( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer o = HandlerUtil::GetVariableChecked(event, + Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, ISources::SHOW_IN_SELECTION()); - if (o.Cast().IsNull()) + if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::SHOW_IN_SELECTION(), "ISelection", o->GetClassName()); } - return o.Cast(); + return o.Cast(); } -Object::Pointer HandlerUtil::GetShowInInput( - ExecutionEvent::Pointer event) +Object::ConstPointer HandlerUtil::GetShowInInput( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer var = HandlerUtil::GetVariable(event, + Object::ConstPointer var = HandlerUtil::GetVariable(event, ISources::SHOW_IN_INPUT()); // if (var == IEvaluationContext.UNDEFINED_VARIABLE) { // return null; // } return var; } -Object::Pointer HandlerUtil::GetShowInInputChecked( - ExecutionEvent::Pointer event) +Object::ConstPointer HandlerUtil::GetShowInInputChecked( + const ExecutionEvent::ConstPointer& event) { - Object::Pointer var = HandlerUtil::GetVariableChecked(event, + Object::ConstPointer var = HandlerUtil::GetVariableChecked(event, ISources::SHOW_IN_INPUT()); // if (var == IEvaluationContext.UNDEFINED_VARIABLE) { // HandlerUtil::IncorrectTypeFound(event, ISources::SHOW_IN_INPUT, Object.class, var // .getClass()); // } return var; } +bool HandlerUtil::ToggleCommandState(const SmartPointer& command) +{ + State::Pointer state = command->GetState(RegistryToggleState::STATE_ID); + if(state.IsNull()) + { + throw ExecutionException("The command does not have a toggle state"); + } + if(ObjectBool::Pointer boolObj = state->GetValue().Cast()) + { + bool oldValue = boolObj->GetValue(); + Object::Pointer newValue(new ObjectBool(!oldValue)); + state->SetValue(newValue); + return oldValue; + } + else + { + throw ExecutionException("The command's toggle state doesn't contain a boolean value"); + } +} + +bool HandlerUtil::MatchesRadioState(const SmartPointer& event) +{ + QString parameter = event->GetParameter(RadioState::PARAMETER_ID); + if (parameter.isNull()) + { + throw ExecutionException("The event does not have the radio state parameter"); + } + + Command::ConstPointer command = event->GetCommand(); + State::Pointer state = command->GetState(RadioState::STATE_ID); + if (state.IsNull()) + { + throw ExecutionException("The command does not have a radio state"); + } + if (ObjectString::Pointer strObj = state->GetValue().Cast()) + { + return parameter == *strObj; + } + else + { + throw ExecutionException("The command's radio state doesn't contain a String value"); + } +} + +void HandlerUtil::UpdateRadioState(const SmartPointer& command, const QString& newState) +{ + State::Pointer state = command->GetState(RadioState::STATE_ID); + if (state.IsNull()) + { + throw ExecutionException("The command does not have a radio state"); + } + Object::Pointer newValue(new ObjectString(newState)); + state->SetValue(newValue); +} + } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryHandlerUtil.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryHandlerUtil.h index 1d1c91dc74..6e0c7fa199 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryHandlerUtil.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryHandlerUtil.h @@ -1,405 +1,444 @@ /*=================================================================== 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 BERRYHANDLERUTIL_H_ #define BERRYHANDLERUTIL_H_ #include #include #include #include #include "berryIWorkbenchPart.h" #include "berryIWorkbenchPartSite.h" #include "berryISelection.h" #include "berryIWorkbenchWindow.h" #include "berryISources.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * Some common utilities for working with handlers in Platform UI. *

* Note: this class should not be instantiated or extended by clients. *

* * @since 3.3 */ class BERRY_UI_QT HandlerUtil { private: - static void NoVariableFound(ExecutionEvent::Pointer event, const QString& name); + static void NoVariableFound(const ExecutionEvent::ConstPointer& event, const QString& name); - static void IncorrectTypeFound(ExecutionEvent::Pointer event, const QString& name, + static void IncorrectTypeFound(const ExecutionEvent::ConstPointer& event, const QString& name, const QString& expectedType, const QString& wrongType); public: typedef ObjectList StringVectorType; /** * Extract the variable. * * @param event * The execution event that contains the application context * @param name * The variable name to extract. * @return The object from the application context, or null * if it could not be found. */ - static Object::Pointer GetVariable(ExecutionEvent::Pointer event, const QString& name); + static Object::ConstPointer GetVariable(const ExecutionEvent::ConstPointer& event, const QString& name); /** * Extract the variable. * * @param event * The execution event that contains the application context * @param name * The variable name to extract. * @return The object from the application context. Will not return * null. * @throws ExecutionException * if the variable is not found. */ - static Object::Pointer GetVariableChecked(ExecutionEvent::Pointer event, const QString& name); + static Object::ConstPointer GetVariableChecked(const ExecutionEvent::ConstPointer& event, const QString& name); /** * Extract the variable. * * @param context * The IEvaluationContext or null * @param name * The variable name to extract. * @return The object from the application context, or null * if it could not be found. */ - static Object::Pointer GetVariable(Object::Pointer context, const QString& name); + static Object::ConstPointer GetVariable(Object::Pointer context, const QString& name); /** * Return the active contexts. * * @param event * The execution event that contains the application context * @return a collection of String contextIds, or null. */ - static StringVectorType::Pointer GetActiveContexts(ExecutionEvent::Pointer event); + static StringVectorType::ConstPointer GetActiveContexts(const ExecutionEvent::ConstPointer& event); /** * Return the active contexts. * * @param event * The execution event that contains the application context * @return a collection of String contextIds. Will not return * null. * @throws ExecutionException * If the context variable is not found. */ - static StringVectorType::Pointer GetActiveContextsChecked(ExecutionEvent::Pointer event); + static StringVectorType::ConstPointer GetActiveContextsChecked(const ExecutionEvent::ConstPointer& event); /** * Return the active shell. Is not necessarily the active workbench window * shell. * * @param event * The execution event that contains the application context * @return the active shell, or null. */ -// static Shell GetActiveShell(ExecutionEvent::Pointer event) { +// static Shell GetActiveShell(const ExecutionEvent::ConstPointer& event) { // Object::Pointer o = getVariable(event, ISources.ACTIVE_SHELL_NAME); // if (o instanceof Shell) { // return (Shell) o; // } // return null; // } /** * Return the active shell. Is not necessarily the active workbench window * shell. * * @param event * The execution event that contains the application context * @return the active shell. Will not return null. * @throws ExecutionException * If the active shell variable is not found. */ -// static Shell GetActiveShellChecked(ExecutionEvent::Pointer event) +// static Shell GetActiveShellChecked(const ExecutionEvent::ConstPointer& event) // { // Object::Pointer o = getVariableChecked(event, ISources.ACTIVE_SHELL_NAME); // if (!(o instanceof Shell)) { // incorrectTypeFound(event, ISources.ACTIVE_SHELL_NAME, Shell.class, // o.getClass()); // } // return (Shell) o; // } /** * Return the active workbench window. * * @param event * The execution event that contains the application context * @return the active workbench window, or null. */ - static IWorkbenchWindow::Pointer GetActiveWorkbenchWindow(ExecutionEvent::Pointer event); + static IWorkbenchWindow::ConstPointer GetActiveWorkbenchWindow(const ExecutionEvent::ConstPointer& event); /** * Return the active workbench window. * * @param event * The execution event that contains the application context * @return the active workbench window. Will not return null. * @throws ExecutionException * If the active workbench window variable is not found. */ - static IWorkbenchWindow::Pointer GetActiveWorkbenchWindowChecked( - ExecutionEvent::Pointer event); + static IWorkbenchWindow::ConstPointer GetActiveWorkbenchWindowChecked( + const ExecutionEvent::ConstPointer& event); /** * Return the active editor. * * @param event * The execution event that contains the application context * @return the active editor, or null. */ - //static IEditorPart::Pointer GetActiveEditor(ExecutionEvent::Pointer event); + //static IEditorPart::Pointer GetActiveEditor(const ExecutionEvent::ConstPointer& event); /** * Return the active editor. * * @param event * The execution event that contains the application context * @return the active editor. Will not return null. * @throws ExecutionException * If the active editor variable is not found. */ - //static IEditorPart::Pointer GetActiveEditorChecked(ExecutionEvent::Pointer event); + //static IEditorPart::Pointer GetActiveEditorChecked(const ExecutionEvent::ConstPointer& event); /** * Return the part id of the active editor. * * @param event * The execution event that contains the application context * @return the part id of the active editor, or null. */ - static ObjectString::Pointer GetActiveEditorId(ExecutionEvent::Pointer event); + static ObjectString::ConstPointer GetActiveEditorId(const ExecutionEvent::ConstPointer& event); /** * Return the part id of the active editor. * * @param event * The execution event that contains the application context * @return the part id of the active editor. Will not return * null. * @throws ExecutionException * If the active editor id variable is not found. */ - static ObjectString::Pointer GetActiveEditorIdChecked(ExecutionEvent::Pointer event); + static ObjectString::ConstPointer GetActiveEditorIdChecked(const ExecutionEvent::ConstPointer& event); /** * Return the active part. * * @param event * The execution event that contains the application context * @return the active part, or null. */ - static IWorkbenchPart::Pointer GetActivePart(ExecutionEvent::Pointer event); + static IWorkbenchPart::ConstPointer GetActivePart(const ExecutionEvent::ConstPointer& event); /** * Return the active part. * * @param event * The execution event that contains the application context * @return the active part. Will not return null. * @throws ExecutionException * If the active part variable is not found. */ - static IWorkbenchPart::Pointer GetActivePartChecked(ExecutionEvent::Pointer event); + static IWorkbenchPart::ConstPointer GetActivePartChecked(const ExecutionEvent::ConstPointer& event); /** * Return the part id of the active part. * * @param event * The execution event that contains the application context * @return the part id of the active part, or null. */ - static ObjectString::Pointer GetActivePartId(ExecutionEvent::Pointer event); + static ObjectString::ConstPointer GetActivePartId(const ExecutionEvent::ConstPointer& event); /** * Return the part id of the active part. * * @param event * The execution event that contains the application context * @return the part id of the active part. Will not return null. * @throws ExecutionException * If the active part id variable is not found. */ - static ObjectString::Pointer GetActivePartIdChecked(ExecutionEvent::Pointer event); + static ObjectString::ConstPointer GetActivePartIdChecked(const ExecutionEvent::ConstPointer& event); /** * Return the active part site. * * @param event * The execution event that contains the application context * @return the active part site, or null. */ - static IWorkbenchPartSite::Pointer GetActiveSite(ExecutionEvent::Pointer event); + static IWorkbenchPartSite::ConstPointer GetActiveSite(const ExecutionEvent::ConstPointer& event); /** * Return the active part site. * * @param event * The execution event that contains the application context * @return the active part site. Will not return null. * @throws ExecutionException * If the active part site variable is not found. */ - static IWorkbenchPartSite::Pointer GetActiveSiteChecked(ExecutionEvent::Pointer event); + static IWorkbenchPartSite::ConstPointer GetActiveSiteChecked(const ExecutionEvent::ConstPointer& event); /** * Return the current selection. * * @param event * The execution event that contains the application context * @return the current selection, or null. */ - static ISelection::Pointer GetCurrentSelection(ExecutionEvent::Pointer event); + static ISelection::ConstPointer GetCurrentSelection(const ExecutionEvent::ConstPointer& event); /** * Return the current selection. * * @param event * The execution event that contains the application context * @return the current selection. Will not return null. * @throws ExecutionException * If the current selection variable is not found. */ - static ISelection::Pointer GetCurrentSelectionChecked(ExecutionEvent::Pointer event); + static ISelection::ConstPointer GetCurrentSelectionChecked(const ExecutionEvent::ConstPointer& event); /** * Return the menu IDs that were applied to the registered context menu. For * example, #CompilationUnitEditorContext. * * @param event * The execution event that contains the application context * @return the menu IDs, or null. */ - static StringVectorType::Pointer GetActiveMenus(ExecutionEvent::Pointer event); + static StringVectorType::ConstPointer GetActiveMenus(const ExecutionEvent::ConstPointer& event); /** * Return the menu IDs that were applied to the registered context menu. For * example, #CompilationUnitEditorContext. * * @param event * The execution event that contains the application context * @return the menu IDs. Will not return null. * @throws ExecutionException * If the active menus variable is not found. */ - static StringVectorType::Pointer GetActiveMenusChecked(ExecutionEvent::Pointer event); + static StringVectorType::ConstPointer GetActiveMenusChecked(const ExecutionEvent::ConstPointer& event); /** * Return the active menu selection. The active menu is a registered context * menu. * * @param event * The execution event that contains the application context * @return the active menu selection, or null. */ - static ISelection::Pointer GetActiveMenuSelection(ExecutionEvent::Pointer event); + static ISelection::ConstPointer GetActiveMenuSelection(const ExecutionEvent::ConstPointer& event); /** * Return the active menu selection. The active menu is a registered context * menu. * * @param event * The execution event that contains the application context * @return the active menu selection. Will not return null. * @throws ExecutionException * If the active menu selection variable is not found. */ - static ISelection::Pointer GetActiveMenuSelectionChecked(ExecutionEvent::Pointer event); + static ISelection::ConstPointer GetActiveMenuSelectionChecked(const ExecutionEvent::ConstPointer& event); /** * Return the active menu editor input, if available. The active menu is a * registered context menu. * * @param event * The execution event that contains the application context * @return the active menu editor, or null. */ - static ISelection::Pointer GetActiveMenuEditorInput(ExecutionEvent::Pointer event); + static ISelection::ConstPointer GetActiveMenuEditorInput(const ExecutionEvent::ConstPointer& event); /** * Return the active menu editor input. The active menu is a registered * context menu. Some context menus do not include the editor input which * will throw an exception. * * @param event * The execution event that contains the application context * @return the active menu editor input. Will not return null. * @throws ExecutionException * If the active menu editor input variable is not found. */ - static ISelection::Pointer GetActiveMenuEditorInputChecked( - ExecutionEvent::Pointer event); + static ISelection::ConstPointer GetActiveMenuEditorInputChecked( + const ExecutionEvent::ConstPointer& event); /** * Return the ShowInContext selection. * * @param event * The execution event that contains the application context * @return the show in selection, or null. */ - static ISelection::Pointer GetShowInSelection(ExecutionEvent::Pointer event); + static ISelection::ConstPointer GetShowInSelection(const ExecutionEvent::ConstPointer& event); /** * Return the ShowInContext selection. Will not return null. * * @param event * The execution event that contains the application context * @return the show in selection, or null. * @throws ExecutionException * If the show in selection variable is not found. */ - static ISelection::Pointer GetShowInSelectionChecked(ExecutionEvent::Pointer event); + static ISelection::ConstPointer GetShowInSelectionChecked(const ExecutionEvent::ConstPointer& event); /** * Return the ShowInContext input. * * @param event * The execution event that contains the application context * @return the show in input, or null. */ - static Object::Pointer GetShowInInput(ExecutionEvent::Pointer event); + static Object::ConstPointer GetShowInInput(const ExecutionEvent::ConstPointer& event); /** * Return the ShowInContext input. Will not return null. * * @param event * The execution event that contains the application context * @return the show in input, or null. * @throws ExecutionException * If the show in input variable is not found. */ - static Object::Pointer GetShowInInputChecked(ExecutionEvent::Pointer event); + static Object::ConstPointer GetShowInInputChecked(const ExecutionEvent::ConstPointer& event); + + /** + * Toggles the command's state. + * + * @param command The command whose state needs to be toggled + * @return the original value before toggling + * + * @throws ExecutionException + * When the command doesn't contain the toggle state or when the state doesn't contain a boolean value + */ + static bool ToggleCommandState(const SmartPointer& command); + + /** + * Checks whether the radio state of the command is same as the radio state + * parameter's value + * + * @param event + * The execution event that contains the application context + * @return true whe the values are same, false + * otherwise + * + * @throws ExecutionException + * When the command doesn't have the radio state or the event + * doesn't have the radio state parameter + */ + static bool MatchesRadioState(const SmartPointer& event); + + /** + * Updates the radio state of the command to the given value + * + * @param command + * the command whose state should be updated + * @param newState + * the new state + * + * @throws ExecutionException + * When the command doesn't have a radio state + */ + static void UpdateRadioState(const SmartPointer& command, const QString& newState); }; } #endif /*BERRYHANDLERUTIL_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryIHandlerActivation.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryIHandlerActivation.h index 44cd3397bc..c37955fb69 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryIHandlerActivation.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryIHandlerActivation.h @@ -1,122 +1,104 @@ /*=================================================================== 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 BERRYIHANDLERACTIVATION_H_ #define BERRYIHANDLERACTIVATION_H_ #include "internal/berryIEvaluationResultCache.h" #include namespace berry { struct IHandler; struct IHandlerService; /** *

* A token representing the activation of a handler. This token can later be * used to cancel that activation. Without this token, then handler will only * become inactive if the component in which the handler was activated is * destroyed. *

*

* This interface is not intended to be implemented or extended by clients. *

* - * @since 3.1 * @see org.eclipse.ui.ISources * @see org.eclipse.ui.ISourceProvider */ -struct BERRY_UI_QT IHandlerActivation : public IEvaluationResultCache { +struct BERRY_UI_QT IHandlerActivation : public virtual IEvaluationResultCache +{ - berryInterfaceMacro(IHandlerActivation, berry); + berryObjectMacro(berry::IHandlerActivation) ~IHandlerActivation(); /** * The depth at which the root exists. - * - * @since 3.2 */ static const int ROOT_DEPTH; // = 1; /** * Clears the cached computation of the isActive method, if * any. This method is only intended for internal use. It provides a * mechanism by which ISourceProvider events can invalidate * state on a IHandlerActivation instance. * * @deprecated Use {@link IEvaluationResultCache#clearResult()} instead. */ virtual void ClearActive() = 0; /** * Returns the identifier of the command whose handler is being activated. * * @return The command identifier; never null. */ virtual QString GetCommandId() const = 0; /** * Returns the depth at which this activation was created within the * services hierarchy. The root of the hierarchy is at a depth of * 1. This is used as the final tie-breaker in the event * that no other method can be used to determine a winner. * * @return The depth at which the handler was inserted into the services * hierarchy; should be a positive integer. - * @since 3.2 */ virtual int GetDepth() const = 0; /** * Returns the handler that should be activated. * * @return The handler; may be null. */ virtual SmartPointer GetHandler() const = 0; /** * Returns the handler service from which this activation was requested. * This is used to ensure that an activation can only be retracted from the * same service which issued it. * * @return The handler service; never null. */ - virtual SmartPointer GetHandlerService() const = 0; + virtual IHandlerService* GetHandlerService() const = 0; - /** - * Returns whether this handler activation is currently active -- given the - * current state of the workbench. This method should cache its computation. - * The cache will be cleared by a call to clearActive. - * - * @param context - * The context in which this state should be evaluated; must not - * be null. - * @return true if the activation is currently active; - * false otherwise. - * @deprecated Use - * {@link IEvaluationResultCache#evaluate(IEvaluationContext)} - * instead. - */ - virtual bool IsActive(SmartPointer context) const = 0; }; } #endif /* BERRYIHANDLERACTIVATION_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryIHandlerService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryIHandlerService.h index b762c2d175..943c9261a2 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryIHandlerService.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryIHandlerService.h @@ -1,435 +1,395 @@ /*=================================================================== 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 BERRYIHANDLERSERVICE_H_ #define BERRYIHANDLERSERVICE_H_ #include "services/berryIServiceWithSources.h" #include "common/berryCommandExceptions.h" namespace berry { class Command; class ExecutionEvent; class ParameterizedCommand; class Expression; class UIElement; struct IEvaluationContext; struct IHandler; struct IHandlerActivation; /** *

* Provides services related to activating and deactivating handlers within the * workbench. *

*

* This service can be acquired from your service locator: *

  *  IHandlerService service = (IHandlerService) getSite().getService(IHandlerService.class);
  * 
*
    *
  • This service is available globally.
  • *
*

* @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * * @since 3.1 */ -struct BERRY_UI_QT IHandlerService : public IServiceWithSources { +struct BERRY_UI_QT IHandlerService : public IServiceWithSources +{ - berryInterfaceMacro(IHandlerService, berry); + berryObjectMacro(berry::IHandlerService) ~IHandlerService(); /** *

* Activates the given handler from a child service. This is used by slave * and nested services to promote handler activations up to the root. By * using this method, it is possible for handlers coming from a more nested * component to override the nested component. *

* * @param activation * The activation that is local to the child service; must not be * null. * @return A token which can be used to later cancel the activation. Only * someone with access to this token can cancel the activation. The * activation will automatically be cancelled if the service locator * context from which this service was retrieved is destroyed. This * activation is local to this service (i.e., it is not the * activation that is passed as a parameter). * @since 3.2 */ virtual SmartPointer ActivateHandler(const SmartPointer& activation) = 0; /** *

* Activates the given handler within the context of this service. If this * service was retrieved from the workbench, then this handler will be * active globally. If the service was retrieved from a nested component, * then the handler will only be active within that component. *

*

* Also, it is guaranteed that the handlers submitted through a particular * service will be cleaned up when that services is destroyed. So, for * example, a service retrieved from a IWorkbenchPartSite * would deactivate all of its handlers when the site is destroyed. *

* * @param commandId * The identifier for the command which this handler handles; * must not be null. * @param handler * The handler to activate; must not be null. * @return A token which can be used to later cancel the activation. Only * someone with access to this token can cancel the activation. The * activation will automatically be cancelled if the context from * which this service was retrieved is destroyed. */ virtual SmartPointer ActivateHandler( const QString& commandId, const SmartPointer& handler) = 0; /** *

* Activates the given handler within the context of this service. The * handler becomes active when expression evaluates to * true. This is the same as calling * {@link #activateHandler(String, IHandler, Expression, boolean)} with * global==false. *

*

* Also, it is guaranteed that the handlers submitted through a particular * service will be cleaned up when that service is destroyed. So, for * example, a service retrieved from a IWorkbenchPartSite * would deactivate all of its handlers when the site is destroyed. *

* * @param commandId * The identifier for the command which this handler handles; * must not be null. * @param handler * The handler to activate; must not be null. * @param expression * This expression must evaluate to true before * this handler will really become active. The expression may be * null if the handler should always be active. * @return A token which can be used to later cancel the activation. Only * someone with access to this token can cancel the activation. The * activation will automatically be cancelled if the context from * which this service was retrieved is destroyed. * * @see org.eclipse.ui.ISources * @since 3.2 */ virtual SmartPointer ActivateHandler( const QString& commandId, const SmartPointer& handler, const SmartPointer& expression) = 0; /** *

* Activates the given handler within the context of this service. The * handler becomes active when expression evaluates to * true. if global==false, then this * handler service must also be the active service to active the handler. * For example, the handler service on a part is active when that part is * active. *

*

* Also, it is guaranteed that the handlers submitted through a particular * service will be cleaned up when that services is destroyed. So, for * example, a service retrieved from a IWorkbenchPartSite * would deactivate all of its handlers when the site is destroyed. *

* * @param commandId * The identifier for the command which this handler handles; * must not be null. * @param handler * The handler to activate; must not be null. * @param expression * This expression must evaluate to true before * this handler will really become active. The expression may be * null if the handler should always be active. * @param global * Indicates that the handler should be activated irrespectively * of whether the corresponding workbench component (e.g., * window, part, etc.) is active. * @return A token which can be used to later cancel the activation. Only * someone with access to this token can cancel the activation. The * activation will automatically be cancelled if the context from * which this service was retrieved is destroyed. * * @see org.eclipse.ui.ISources * @since 3.2 */ virtual SmartPointer ActivateHandler( const QString& commandId, const SmartPointer& handler, const SmartPointer& expression, bool global) = 0; - /** - *

- * Activates the given handler within the context of this service. The - * handler becomes active when expression evaluates to - * true. - *

- *

- * Also, it is guaranteed that the handlers submitted through a particular - * service will be cleaned up when that services is destroyed. So, for - * example, a service retrieved from a IWorkbenchPartSite - * would deactivate all of its handlers when the site is destroyed. - *

- * - * @param commandId - * The identifier for the command which this handler handles; - * must not be null. - * @param handler - * The handler to activate; must not be null. - * @param expression - * This expression must evaluate to true before - * this handler will really become active. The expression may be - * null if the handler should always be active. - * @param sourcePriorities - * The source priorities for the expression. - * @return A token which can be used to later cancel the activation. Only - * someone with access to this token can cancel the activation. The - * activation will automatically be cancelled if the context from - * which this service was retrieved is destroyed. - * - * @see org.eclipse.ui.ISources - * @deprecated Use - * {@link IHandlerService#activateHandler(String, IHandler, Expression)} - * instead. - */ - virtual SmartPointer ActivateHandler( - const QString& commandId, - const SmartPointer& handler, - const SmartPointer& expression, - int sourcePriorities) = 0; - /** * Creates an execution event based on an SWT event. This execution event * can then be passed to a command for execution. * * @param command * The command for which an execution event should be created; * must not be null. * @param event * The SWT event triggering the command execution; may be * null. * @return An execution event suitable for calling * {@link Command#executeWithChecks(ExecutionEvent)}. * @since 3.2 * @see Command#executeWithChecks(ExecutionEvent) */ virtual SmartPointer CreateExecutionEvent( const SmartPointer& command, const SmartPointer& uielement) = 0; /** * Creates a parameterized execution event based on an SWT event and a * parameterized command. This execution event can then be passed to a * command for execution. * * @param command * The parameterized command for which an execution event should * be created; must not be null. * @param event * The SWT event triggering the command execution; may be * null. * @return An execution event suitable for calling * {@link Command#executeWithChecks(ExecutionEvent)}. * @since 3.2 * @see ParameterizedCommand#getCommand() * @see Command#executeWithChecks(ExecutionEvent) */ virtual SmartPointer CreateExecutionEvent( const SmartPointer& command, const SmartPointer& uielement) = 0; /** * Deactivates the given handler within the context of this service. If the * handler was activated with a different service, then it must be * deactivated from that service instead. It is only possible to retract a * handler activation with this method. That is, you must have the same * IHandlerActivation used to activate the handler. * * @param activation * The token that was returned from a call to * activateHandler; must not be null. */ virtual void DeactivateHandler(const SmartPointer& activation) = 0; /** * Deactivates the given handlers within the context of this service. If the * handler was activated with a different service, then it must be * deactivated from that service instead. It is only possible to retract a * handler activation with this method. That is, you must have the same * IHandlerActivation used to activate the handler. * * @param activations * The tokens that were returned from a call to * activateHandler. This collection must only * contain instances of IHandlerActivation. The * collection must not be null. */ virtual void DeactivateHandlers( const QList >& activations) = 0; /** * Executes the command with the given identifier and no parameters. * * @param commandId * The identifier of the command to execute; must not be * null. * @param event * The SWT event triggering the command execution; may be * null. * @return The return value from the execution; may be null. * @throws ExecutionException * If the handler has problems executing this command. * @throws NotDefinedException * If the command you are trying to execute is not defined. * @throws NotEnabledException * If the command you are trying to execute is not enabled. * @throws NotHandledException * If there is no handler. * @since 3.2 * @see Command#executeWithChecks(ExecutionEvent) */ virtual Object::Pointer ExecuteCommand(const QString& commandId, const SmartPointer& uielement) = 0; /** * Executes the given parameterized command. * * @param command * The parameterized command to be executed; must not be * null. * @param event * The SWT event triggering the command execution; may be * null. * @return The return value from the execution; may be null. * @throws ExecutionException * If the handler has problems executing this command. * @throws NotDefinedException * If the command you are trying to execute is not defined. * @throws NotEnabledException * If the command you are trying to execute is not enabled. * @throws NotHandledException * If there is no handler. * @since 3.2 * @see Command#executeWithChecks(ExecutionEvent) */ virtual Object::Pointer ExecuteCommand(const SmartPointer& command, const SmartPointer& uielement) = 0; /** * Executes the given parameterized command in the provided context. It * takes care of finding the correct active handler given the context, calls * {@link IHandler2#setEnabled(Object)} to update the enabled state if * supported, and executes with that handler. * * @param command * The parameterized command to be executed; must not be * null. * @param event * The SWT event triggering the command execution; may be * null. * @param context * the evaluation context to run against. Must not be * null * @return The return value from the execution; may be null. * @throws ExecutionException * If the handler has problems executing this command. * @throws NotDefinedException * If the command you are trying to execute is not defined. * @throws NotEnabledException * If the command you are trying to execute is not enabled. * @throws NotHandledException * If there is no handler. * @since 3.4 * @see Command#executeWithChecks(ExecutionEvent) * @see #createContextSnapshot(boolean) */ virtual Object::Pointer ExecuteCommandInContext( const SmartPointer& command, const SmartPointer& uielement, const SmartPointer& context) = 0; /** * This method creates a copy of the application context returned by * {@link #getCurrentState()}. * * @param includeSelection * if true, include the default variable and * selection variables * @return an context filled with the current set of variables. If selection * is not included, the default variable is an empty collection - * @since 3.4 */ virtual SmartPointer CreateContextSnapshot(bool includeSelection) = 0; /** * Returns an evaluation context representing the current state of the * world. This is equivalent to the application context required by * {@link ExecutionEvent}. * * @return the current state of the application; never null. * @see ParameterizedCommand#executeWithChecks(Object, Object) * @see ExecutionEvent#ExecutionEvent(Command, java.util.Map, Object, * Object) * @see org.eclipse.ui.services.IEvaluationService */ - virtual IEvaluationContext* GetCurrentState() const = 0; + virtual SmartPointer GetCurrentState() const = 0; /** *

* Reads the handler information from the registry. This will overwrite any * of the existing information in the handler service. This method is * intended to be called during start-up. When this method completes, this * handler service will reflect the current state of the registry. *

*/ virtual void ReadRegistry() = 0; /** * Sets the help context identifier to associate with a particular handler. * * @param handler * The handler with which to register a help context identifier; * must not be null. * @param helpContextId * The help context identifier to register; may be * null if the help context identifier should be * removed. * @since 3.2 */ virtual void SetHelpContextId(const SmartPointer& handler, const QString& helpContextId) = 0; }; } -Q_DECLARE_INTERFACE(berry::IHandlerService, "org.blueberry.ui.qt.IHandlerService") +Q_DECLARE_INTERFACE(berry::IHandlerService, "org.blueberry.ui.IHandlerService") #endif /* BERRYIHANDLERSERVICE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryRadioState.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryRadioState.cpp new file mode 100644 index 0000000000..c8b15da5c7 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryRadioState.cpp @@ -0,0 +1,91 @@ +/*=================================================================== + +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 "berryRadioState.h" + +#include "berryObjectString.h" +#include "berryObjectStringMap.h" + +#include "berryIPreferences.h" + +namespace berry { + +const QString RadioState::STATE_ID = "org.blueberry.ui.commands.radioState"; +const QString RadioState::PARAMETER_ID = "org.blueberry.ui.commands.radioStateParameter"; + +RadioState::RadioState() +{ + SetShouldPersist(true); +} + +void RadioState::SetInitializationData(const SmartPointer& /*config*/, + const QString& /*propertyName*/, const Object::Pointer& data) +{ + bool shouldPersist = true; // persist by default + if (data.Cast()) + { + SetValue(data); + } + else if (ObjectStringMap::Pointer parameters = data.Cast()) + { + const QString defaultString = parameters->value("default"); + if (!defaultString.isNull()) + { + Object::Pointer value(new ObjectString(defaultString)); + SetValue(value); + } + + const QString persistedString = parameters->value("persisted"); + if (!persistedString.isNull() + && persistedString.compare("false", Qt::CaseInsensitive) == 0) + shouldPersist = false; + } + SetShouldPersist(shouldPersist); +} + +void RadioState::Load(const SmartPointer& store, const QString& preferenceKey) +{ + if (!ShouldPersist()) + return; + + const QString prefValue = store->Get(preferenceKey, QString()); + if (!prefValue.isEmpty()) + { + Object::Pointer value(new ObjectString(prefValue)); + SetValue(value); + } +} + +void RadioState::Save(const SmartPointer& store, const QString& preferenceKey) +{ + if (!ShouldPersist()) + return; + + const Object::Pointer value = GetValue(); + if (ObjectString::Pointer objStr = value.Cast()) + { + store->Put(preferenceKey, *objStr); + } +} + +void RadioState::SetValue(const Object::Pointer& value) +{ + if (!(value.Cast())) + return; // we set only String values + PersistentState::SetValue(value); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryRadioState.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryRadioState.h new file mode 100644 index 0000000000..d01a580a01 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryRadioState.h @@ -0,0 +1,75 @@ +/*=================================================================== + +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 BERRYRADIOSTATE_H +#define BERRYRADIOSTATE_H + +#include "internal/berryPersistentState.h" +#include "berryIExecutableExtension.h" + +namespace berry { + +/** + * This state supports a radio-button like command, where the value of the + * parameterized command is stored as state. The command must define a state + * using the {@link #STATE_ID} id and a string commandParameter using the + * {@link #PARAMETER_ID} id. Menu contributions supplied by + * org.eclipse.ui.menus can then set the {@link #PARAMETER_ID}. + *

+ * When parsing from the registry, this state understands two parameters: + * default, which is the default value for this item; and + * persisted, which is whether the state should be persisted + * between sessions. The default parameter has no default value and + * must be specified in one of its forms, and the persisted + * parameter defaults to true. If only one parameter is passed + * (i.e., using the class name followed by a colon), then it is assumed to be + * the default parameter. + *

+ * + * @see HandlerUtil#updateRadioState(org.eclipse.core.commands.Command, String) + * @see HandlerUtil#matchesRadioState(org.eclipse.core.commands.ExecutionEvent) + */ +class RadioState : public PersistentState, public IExecutableExtension +{ + +public: + + /** + * The state ID for a radio state understood by the system. + */ + static const QString STATE_ID; // = "org.blueberry.ui.commands.radioState"; + + /** + * The parameter ID for a radio state understood by the system. + */ + static const QString PARAMETER_ID; // = "org.blueberry.ui.commands.radioStateParameter"; + + RadioState(); + + void SetInitializationData(const SmartPointer& config, + const QString& propertyName, const Object::Pointer& data); + + void Load(const SmartPointer& store, const QString& preferenceKey); + + void Save(const SmartPointer& store, const QString& preferenceKey); + + void SetValue(const Object::Pointer& value); + +}; + +} + +#endif // BERRYRADIOSTATE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryRegistryToggleState.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryRegistryToggleState.cpp new file mode 100644 index 0000000000..0b90fe69cc --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryRegistryToggleState.cpp @@ -0,0 +1,78 @@ +/*=================================================================== + +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 "berryRegistryToggleState.h" + +#include "berryObjects.h" +#include "berryObjectString.h" +#include "berryObjectStringMap.h" + +namespace berry { + +const QString RegistryToggleState::STATE_ID = "org.blueberry.ui.commands.toggleState"; + +void RegistryToggleState::SetInitializationData( + const SmartPointer& /*configurationElement*/, + const QString& /*propertyName*/, const Object::Pointer& data) +{ + if (ObjectString::Pointer objStr = data.Cast()) + { + // This is the default value. + ReadDefault(*objStr); + SetShouldPersist(true); + } + else if (ObjectStringMap::Pointer parameters = data.Cast()) + { + QString defaultObject = parameters->value("default"); + if (!defaultObject.isNull()) + { + ReadDefault(defaultObject); + } + + QString persistedObject = parameters->value("persisted"); + if (!persistedObject.isNull()) + { + ReadPersisted(persistedObject); + } + } + else + { + SetShouldPersist(true); + } +} + +void RegistryToggleState::ReadDefault(const QString& defaultString) +{ + if (defaultString.compare("true", Qt::CaseInsensitive) == 0) + { + Object::Pointer newValue(new ObjectBool(true)); + SetValue(newValue); + } +} + +void RegistryToggleState::ReadPersisted(const QString& persistedString) +{ + if (persistedString.compare("false", Qt::CaseInsensitive) == 0) + { + SetShouldPersist(false); + } + else + { + SetShouldPersist(true); + } +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryRegistryToggleState.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryRegistryToggleState.h new file mode 100644 index 0000000000..cfc8be55ab --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryRegistryToggleState.h @@ -0,0 +1,83 @@ +/*=================================================================== + +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 BERRYREGISTRYTOGGLESTATE_H +#define BERRYREGISTRYTOGGLESTATE_H + +#include "berryToggleState.h" +#include "berryIExecutableExtension.h" + +namespace berry { + +/** + *

+ * A toggle state that can be read from the registry. This stores a piece of + * boolean state information. + *

+ *

+ * When parsing from the registry, this state understands two parameters: + * default, which is the default value for this item; and + * persisted, which is whether the state should be persisted + * between sessions. The default parameter defaults to + * false, and the persisted parameter defaults to + * true. If only one parameter is passed (i.e., using the class + * name followed by a colon), then it is assumed to be the default + * parameter. + *

+ *

+ * Clients may instantiate this class, but must not extend. + *

+ */ +class RegistryToggleState : public ToggleState, public IExecutableExtension +{ + +public: + + /** + * The state ID for a toggle state understood by the system. + */ + static const QString STATE_ID; // = "org.blueberry.ui.commands.toggleState"; + + void SetInitializationData(const SmartPointer& configurationElement, + const QString& propertyName, const Object::Pointer& data); + +private: + + /** + * Reads the default parameter from the given string. This + * converts the string to a boolean, using true as the + * default. + * + * @param defaultString + * The string to parse; may be null. + */ + void ReadDefault(const QString& defaultString); + + /** + * Reads the persisted parameter from the given string. This + * converts the string to a boolean, using true as the + * default. + * + * @param persistedString + * The string to parse; may be null. + */ + void ReadPersisted(const QString& persistedString); + +}; + +} + +#endif // BERRYREGISTRYTOGGLESTATE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryShowViewHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryShowViewHandler.cpp index 45433620e0..53e133686f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryShowViewHandler.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryShowViewHandler.cpp @@ -1,118 +1,117 @@ /*=================================================================== 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 "tweaklets/berryWorkbenchTweaklet.h" #include "berryShowViewHandler.h" #include "berryHandlerUtil.h" #include "dialogs/berryIShowViewDialog.h" #include "berryUIException.h" #include "berryIWorkbenchPage.h" #include "berryIViewDescriptor.h" #include "berryPlatformUI.h" #include #include namespace berry { -const QString ShowViewHandler::PARAMETER_NAME_VIEW_ID = "org.blueberry.ui.showView.viewId"; //$NON-NLS-1$ +const QString ShowViewHandler::PARAMETER_NAME_VIEW_ID = "org.blueberry.ui.views.showView.viewId"; ShowViewHandler::ShowViewHandler() { } -Object::Pointer ShowViewHandler::Execute( - const ExecutionEvent::Pointer event) +Object::Pointer ShowViewHandler::Execute(const ExecutionEvent::ConstPointer& event) { - IWorkbenchWindow::Pointer window = HandlerUtil::GetActiveWorkbenchWindowChecked(event); + IWorkbenchWindow::ConstPointer window = HandlerUtil::GetActiveWorkbenchWindowChecked(event); // Get the view identifier, if any. const ExecutionEvent::ParameterMap& parameters = event->GetParameters(); ExecutionEvent::ParameterMap::const_iterator result = parameters.find(PARAMETER_NAME_VIEW_ID); QString value; if (result != parameters.end()) value = result.value(); if (value.isEmpty()) { this->OpenOther(window); } else { try { this->OpenView(value, window); } catch (const PartInitException& e) { throw ExecutionException("Part could not be initialized", e); } } return Object::Pointer(0); } -void ShowViewHandler::OpenOther(IWorkbenchWindow::Pointer window) +void ShowViewHandler::OpenOther(IWorkbenchWindow::ConstPointer window) { const IWorkbenchPage::Pointer page = window->GetActivePage(); if (page.IsNull()) { return; } IShowViewDialog::Pointer dialog = Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateStandardDialog(WorkbenchTweaklet::DIALOG_ID_SHOW_VIEW).Cast(); if (dialog.IsNull()) return; int returnCode = dialog->Open(); if (returnCode == IDialog::CANCEL) { return; } const QList descriptors = dialog->GetSelection(); - for (unsigned int i = 0; i < descriptors.size(); ++i) + for (int i = 0; i < descriptors.size(); ++i) { try { this->OpenView(descriptors[i]->GetId(), window); } catch (PartInitException e) { // StatusUtil.handleStatus(e.getStatus(), // WorkbenchMessages.ShowView_errorTitle // + ": " + e.getMessage(), //$NON-NLS-1$ // StatusManager.SHOW); } } } -void ShowViewHandler::OpenView(const QString& viewId, IWorkbenchWindow::Pointer activeWorkbenchWindow) +void ShowViewHandler::OpenView(const QString& viewId, IWorkbenchWindow::ConstPointer activeWorkbenchWindow) { const IWorkbenchPage::Pointer activePage = activeWorkbenchWindow->GetActivePage(); if (activePage.IsNull()) { return; } activePage->ShowView(viewId); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryShowViewHandler.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryShowViewHandler.h index 6c1670da62..0c002d75a4 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryShowViewHandler.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryShowViewHandler.h @@ -1,80 +1,80 @@ /*=================================================================== 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 BERRYSHOWVIEWHANDLER_H_ #define BERRYSHOWVIEWHANDLER_H_ #include #include #include "berryIWorkbenchWindow.h" #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * Shows the given view. If no view is specified in the parameters, then this * opens the view selection dialog. * * @since 3.1 */ class BERRY_UI_QT ShowViewHandler : public AbstractHandler { + Q_OBJECT public: berryObjectMacro(ShowViewHandler); private: /** * The name of the parameter providing the view identifier. */ static const QString PARAMETER_NAME_VIEW_ID; public: /** * Creates a new ShowViewHandler that will open the view in its default location. */ ShowViewHandler(); - Object::Pointer Execute( - const ExecutionEvent::Pointer event); + Object::Pointer Execute(const ExecutionEvent::ConstPointer& event); private: /** * Opens a view selection dialog, allowing the user to chose a view. */ - void OpenOther(IWorkbenchWindow::Pointer window); + void OpenOther(IWorkbenchWindow::ConstPointer window); /** * Opens the view with the given identifier. * * @param viewId * The view to open; must not be null * @throws PartInitException * If the part could not be initialized. */ - void OpenView(const QString& viewId, IWorkbenchWindow::Pointer activeWorkbenchWindow); + void OpenView(const QString& viewId, IWorkbenchWindow::ConstPointer activeWorkbenchWindow); }; } #endif /*BERRYSHOWVIEWHANDLER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryToggleState.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryToggleState.cpp new file mode 100644 index 0000000000..f9c6d8db3a --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryToggleState.cpp @@ -0,0 +1,72 @@ +/*=================================================================== + +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 "berryToggleState.h" + +#include "berryObjects.h" + +#include "berryIPreferences.h" + +#include + +namespace berry { + +ToggleState::ToggleState() +{ + Object::Pointer value(new ObjectBool(false)); + SetValue(value); +} + +void ToggleState::Load(const SmartPointer& store, + const QString& preferenceKey) +{ + bool currentValue = GetValue().Cast()->GetValue(); + //store.setDefault(preferenceKey, currentValue); + if (ShouldPersist() && (store->Keys().contains(preferenceKey))) + { + const bool value = store->GetBool(preferenceKey, currentValue); + if (value != currentValue) + { + Object::Pointer newValue(new ObjectBool(value)); + SetValue(newValue); + } + } +} + +void ToggleState::Save(const SmartPointer& store, + const QString& preferenceKey) +{ + if (ShouldPersist()) + { + const Object::Pointer value = GetValue(); + if (ObjectBool::Pointer boolValue = value.Cast()) + { + store->PutBool(preferenceKey, boolValue->GetValue()); + } + } +} + +void ToggleState::SetValue(const Object::Pointer& value) +{ + if (!(value.Cast())) + { + throw ctkInvalidArgumentException("ToggleState takes a Boolean as a value"); + } + + PersistentState::SetValue(value); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryToggleState.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryToggleState.h new file mode 100644 index 0000000000..05831954f9 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryToggleState.h @@ -0,0 +1,59 @@ +/*=================================================================== + +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 BERRYTOGGLESTATE_H +#define BERRYTOGGLESTATE_H + +#include "internal/berryPersistentState.h" + +namespace berry { + +/** + *

+ * A piece of state storing a \c bool. + *

+ *

+ * If this state is registered using {@link IMenuStateIds#STYLE}, then it will + * control the presentation of the command if displayed in the menus, tool bars + * or status line. + *

+ *

+ * Clients may instantiate this class, but must not extend. + *

+ */ +class ToggleState : public PersistentState +{ + +public: + + /** + * Constructs a new ToggleState. By default, the toggle is + * off (e.g., false). + */ + ToggleState(); + + void Load(const SmartPointer& store, + const QString& preferenceKey); + + void Save(const SmartPointer& store, + const QString& preferenceKey); + + void SetValue(const Object::Pointer& value); +}; + +} + +#endif // BERRYTOGGLESTATE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractPartSelectionTracker.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractPartSelectionTracker.cpp index d1e5f61f83..251eaf7fb9 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractPartSelectionTracker.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractPartSelectionTracker.cpp @@ -1,130 +1,131 @@ /*=================================================================== 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 "berryAbstractPartSelectionTracker.h" #include "berryIPostSelectionProvider.h" #include "berryINullSelectionListener.h" #include "util/berrySafeRunnable.h" #include namespace berry { class SafeSelectionRunnable : public SafeRunnable { public: berryObjectMacro(SafeSelectionRunnable) - ISelectionListener::Pointer l; + ISelectionListener* l; - SafeSelectionRunnable(IWorkbenchPart::Pointer part, ISelection::ConstPointer sel) + SafeSelectionRunnable(const IWorkbenchPart::Pointer& part, + const ISelection::ConstPointer& sel) : p(part), s(sel) {} void Run() { l->SelectionChanged(p, s); } private: - IWorkbenchPart::Pointer p; - ISelection::ConstPointer s; + const IWorkbenchPart::Pointer p; + const ISelection::ConstPointer s; }; AbstractPartSelectionTracker::AbstractPartSelectionTracker( const QString& partId) { this->SetPartId(partId); } void AbstractPartSelectionTracker::AddSelectionListener( - ISelectionListener::Pointer listener) + ISelectionListener* listener) { fListeners.push_back(listener); } void AbstractPartSelectionTracker::AddPostSelectionListener( - ISelectionListener::Pointer listener) + ISelectionListener* listener) { fPostListeners.push_back(listener); } void AbstractPartSelectionTracker::RemoveSelectionListener( - ISelectionListener::Pointer listener) + ISelectionListener* listener) { fListeners.removeAll(listener); } void AbstractPartSelectionTracker::RemovePostSelectionListener( - ISelectionListener::Pointer listener) + ISelectionListener* listener) { fPostListeners.removeAll(listener); } AbstractPartSelectionTracker::~AbstractPartSelectionTracker() { } -void AbstractPartSelectionTracker::FireSelection(IWorkbenchPart::Pointer part, - ISelection::ConstPointer sel) +void AbstractPartSelectionTracker::FireSelection(const IWorkbenchPart::Pointer& part, + const ISelection::ConstPointer& sel) { SafeSelectionRunnable::Pointer runnable(new SafeSelectionRunnable(part, sel)); - for (QList::iterator i = fListeners.begin(); + for (QList::iterator i = fListeners.begin(); i != fListeners.end(); ++i) { - ISelectionListener::Pointer l = *i; - if ((part && sel) || l.Cast()) + ISelectionListener* l = *i; + if ((part && sel) || dynamic_cast(l)) { runnable->l = l; SafeRunner::Run(runnable); } } } -void AbstractPartSelectionTracker::FirePostSelection(IWorkbenchPart::Pointer part, - ISelection::ConstPointer sel) +void AbstractPartSelectionTracker::FirePostSelection(const IWorkbenchPart::Pointer& part, + const ISelection::ConstPointer& sel) { SafeSelectionRunnable::Pointer runnable(new SafeSelectionRunnable(part, sel)); - for (QList::iterator i = fPostListeners.begin(); + for (QList::iterator i = fPostListeners.begin(); i != fPostListeners.end(); ++i) { - ISelectionListener::Pointer l = *i; - if ((part && sel) || l.Cast()) + ISelectionListener* l = *i; + if ((part && sel) || dynamic_cast(l)) { runnable->l = l; SafeRunner::Run(runnable); } } } QString AbstractPartSelectionTracker::GetPartId() { return fPartId; } void AbstractPartSelectionTracker::SetPartId(const QString& partId) { fPartId = partId; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractPartSelectionTracker.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractPartSelectionTracker.h index 953ee7bb7a..0e38fbca1a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractPartSelectionTracker.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractPartSelectionTracker.h @@ -1,143 +1,143 @@ /*=================================================================== 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 BERRYABSTRACTPARTSELECTIONTRACKER_H_ #define BERRYABSTRACTPARTSELECTIONTRACKER_H_ #include #include #include "berryISelectionService.h" #include "berryISelectionListener.h" #include "berryIWorkbenchPart.h" namespace berry { class AbstractPartSelectionTracker : public virtual Object { public: berryObjectMacro(AbstractPartSelectionTracker) private: /** * List of selection listeners for this tracker */ - QList fListeners; + QList fListeners; /** * List of post selection listeners for this tracker */ - QList fPostListeners; + QList fPostListeners; /** * The id of the part this tracker tracks */ QString fPartId; public: /** * Constructs a part selection tracker for the part with the given id. * * @param id part identifier */ AbstractPartSelectionTracker(const QString& partId); /** * Adds a selection listener to this tracker * * @param listener the listener to add */ - void AddSelectionListener(ISelectionListener::Pointer listener); + void AddSelectionListener(ISelectionListener* listener); /** * Adds a post selection listener to this tracker * * @param listener the listener to add */ - void AddPostSelectionListener(ISelectionListener::Pointer listener); + void AddPostSelectionListener(ISelectionListener* listener); /** * Returns the selection from the part being tracked, * or null if the part is closed or has no selection. */ virtual ISelection::ConstPointer GetSelection() = 0; /** * Removes a selection listener from this tracker. * * @param listener the listener to remove */ - void RemoveSelectionListener(ISelectionListener::Pointer listener); + void RemoveSelectionListener(ISelectionListener* listener); /** * Removes a post selection listener from this tracker. * * @param listener the listener to remove */ - void RemovePostSelectionListener(ISelectionListener::Pointer listener); + void RemovePostSelectionListener(ISelectionListener* listener); /** * Disposes this selection tracker. This removes all listeners currently registered. */ ~AbstractPartSelectionTracker(); protected: /** * Fires a selection event to the listeners. * * @param part the part or null if no active part * @param sel the selection or null if no active selection * @param listeners the list of listeners to notify */ - void FireSelection(IWorkbenchPart::Pointer part, ISelection::ConstPointer sel); + void FireSelection(const IWorkbenchPart::Pointer& part, const ISelection::ConstPointer& sel); /** * Fires a post selection event to the listeners. * * @param part the part or null if no active part * @param sel the selection or null if no active selection * @param listeners the list of listeners to notify */ - void FirePostSelection(IWorkbenchPart::Pointer part, ISelection::ConstPointer sel); + void FirePostSelection(const IWorkbenchPart::Pointer& part, const ISelection::ConstPointer& sel); /** * Returns the id of the part that this tracks. * * @return part identifier */ QString GetPartId(); private: /** * Sets the id of the part that this tracks. * * @param id view identifier */ void SetPartId(const QString& partId); }; } #endif /* BERRYABSTRACTPARTSELECTIONTRACKER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractSelectionService.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractSelectionService.cpp index 80f2848abd..9ddfe6528c 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractSelectionService.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractSelectionService.cpp @@ -1,264 +1,263 @@ /*=================================================================== 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 "berryAbstractSelectionService.h" #include "berryWorkbenchPlugin.h" #include "berryIPostSelectionProvider.h" #include "berryINullSelectionListener.h" namespace berry { //ISelectionService::SelectionEvents& AbstractSelectionService::GetSelectionEvents(const QString& partId) //{ // if (partId.empty()) // { // return selectionEvents; // } // // return this->GetPerPartTracker(partId)->GetSelectionEvents(); //} AbstractSelectionService::AbstractSelectionService() + : selListener(new SelectionListener(this)) + , postSelListener(new PostSelectionListener(this)) { - selListener = new SelectionListener(this); - postSelListener = new PostSelectionListener(this); } AbstractSelectionService::SelectionListener::SelectionListener(AbstractSelectionService* service) : m_SelectionService(service) { } -void AbstractSelectionService::SelectionListener::SelectionChanged(SelectionChangedEvent::Pointer event) +void AbstractSelectionService::SelectionListener::SelectionChanged(const SelectionChangedEvent::Pointer& event) { m_SelectionService->FireSelection(m_SelectionService->activePart, event->GetSelection()); } AbstractSelectionService::PostSelectionListener::PostSelectionListener(AbstractSelectionService* service) : m_SelectionService(service) { } void AbstractSelectionService::PostSelectionListener::SelectionChanged( - SelectionChangedEvent::Pointer event) + const SelectionChangedEvent::Pointer& event) { m_SelectionService->FirePostSelection(m_SelectionService->activePart, event->GetSelection()); } -void AbstractSelectionService::AddSelectionListener(ISelectionListener::Pointer l) +void AbstractSelectionService::AddSelectionListener(ISelectionListener* l) { fListeners.push_back(l); } void AbstractSelectionService::AddSelectionListener(const QString& partId, - ISelectionListener::Pointer listener) + ISelectionListener* listener) { this->GetPerPartTracker(partId)->AddSelectionListener(listener); } -void AbstractSelectionService::AddPostSelectionListener( - ISelectionListener::Pointer l) +void AbstractSelectionService::AddPostSelectionListener(ISelectionListener* l) { fPostListeners.push_back(l); } void AbstractSelectionService::AddPostSelectionListener(const QString& partId, - ISelectionListener::Pointer listener) + ISelectionListener* listener) { this->GetPerPartTracker(partId)->AddPostSelectionListener(listener); } -void AbstractSelectionService::RemoveSelectionListener(ISelectionListener::Pointer l) +void AbstractSelectionService::RemoveSelectionListener(ISelectionListener* l) { fListeners.removeAll(l); } void AbstractSelectionService::RemovePostSelectionListener( - const QString& partId, ISelectionListener::Pointer listener) + const QString& partId, ISelectionListener* listener) { this->GetPerPartTracker(partId)->RemovePostSelectionListener(listener); } void AbstractSelectionService::RemovePostSelectionListener( - ISelectionListener::Pointer l) + ISelectionListener* l) { fPostListeners.removeAll(l); } void AbstractSelectionService::RemoveSelectionListener(const QString& partId, - ISelectionListener::Pointer listener) + ISelectionListener* listener) { this->GetPerPartTracker(partId)->RemoveSelectionListener(listener); } -void AbstractSelectionService::FireSelection(IWorkbenchPart::Pointer part, - ISelection::ConstPointer sel) +void AbstractSelectionService::FireSelection(const IWorkbenchPart::Pointer& part, + const ISelection::ConstPointer& sel) { - for (QList::iterator i = fListeners.begin(); + for (QList::iterator i = fListeners.begin(); i != fListeners.end(); ++i) { - ISelectionListener::Pointer l = *i; - if ((part && sel) || l.Cast()) + ISelectionListener* l = *i; + if ((part && sel) || dynamic_cast(l)) { try { l->SelectionChanged(part, sel); } catch (const ctkRuntimeException& rte) { WorkbenchPlugin::Log(rte); } catch (const std::exception& e) { WorkbenchPlugin::Log(e.what()); } } } } -void AbstractSelectionService::FirePostSelection(IWorkbenchPart::Pointer part, - ISelection::ConstPointer sel) +void AbstractSelectionService::FirePostSelection(const IWorkbenchPart::Pointer& part, + const ISelection::ConstPointer& sel) { - for (QList::iterator i = fPostListeners.begin(); + for (QList::iterator i = fPostListeners.begin(); i != fPostListeners.end(); ++i) { - ISelectionListener::Pointer l = *i; - if ((part && sel) || l.Cast()) + ISelectionListener* l = *i; + if ((part && sel) || dynamic_cast(l)) { try { l->SelectionChanged(part, sel); } catch (const ctkRuntimeException& rte) { WorkbenchPlugin::Log(rte); } catch (const std::exception& e) { WorkbenchPlugin::Log(e.what()); } } } } AbstractPartSelectionTracker::Pointer AbstractSelectionService::GetPerPartTracker( const QString& partId) { AbstractPartSelectionTracker::Pointer tracker; QHash::const_iterator res = perPartTrackers.find(partId); if (res == perPartTrackers.end()) { tracker = this->CreatePartTracker(partId); perPartTrackers[partId] = tracker; } else { tracker = res.value(); } return tracker; } ISelection::ConstPointer AbstractSelectionService::GetSelection() const { if (activeProvider.IsNotNull()) { return activeProvider->GetSelection(); } else { return ISelection::ConstPointer(0); } } ISelection::ConstPointer AbstractSelectionService::GetSelection(const QString& partId) { return this->GetPerPartTracker(partId)->GetSelection(); } void AbstractSelectionService::SetActivePart(IWorkbenchPart::Pointer newPart) { // Optimize. if (newPart == activePart) { return; } ISelectionProvider::Pointer selectionProvider; if (newPart.IsNotNull()) { selectionProvider = newPart->GetSite()->GetSelectionProvider(); if (selectionProvider.IsNull()) { newPart = 0; } } if (newPart == activePart) { return; } if (activePart.IsNotNull()) { if (activeProvider.IsNotNull()) { - activeProvider->RemoveSelectionChangedListener(selListener); + activeProvider->RemoveSelectionChangedListener(selListener.data()); if (activeProvider.Cast().IsNotNull()) { activeProvider.Cast() - ->RemovePostSelectionChangedListener(postSelListener); + ->RemovePostSelectionChangedListener(postSelListener.data()); } else { activeProvider - ->RemoveSelectionChangedListener(postSelListener); + ->RemoveSelectionChangedListener(postSelListener.data()); } activeProvider = 0; } activePart = 0; } activePart = newPart; if (newPart.IsNotNull()) { activeProvider = selectionProvider; // Fire an event if there's an active provider - activeProvider->AddSelectionChangedListener(selListener); + activeProvider->AddSelectionChangedListener(selListener.data()); ISelection::ConstPointer sel = activeProvider->GetSelection(); this->FireSelection(newPart, sel); if (activeProvider.Cast().IsNotNull()) { activeProvider.Cast() - ->AddPostSelectionChangedListener(postSelListener); + ->AddPostSelectionChangedListener(postSelListener.data()); } else { - activeProvider->AddSelectionChangedListener(postSelListener); + activeProvider->AddSelectionChangedListener(postSelListener.data()); } this->FirePostSelection(newPart, sel); } else { this->FireSelection(IWorkbenchPart::Pointer(0), ISelection::ConstPointer(0)); this->FirePostSelection(IWorkbenchPart::Pointer(0), ISelection::ConstPointer(0)); } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractSelectionService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractSelectionService.h index 0037640d98..36012420b0 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractSelectionService.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractSelectionService.h @@ -1,320 +1,321 @@ /*=================================================================== 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 BERRYABSTRACTSELECTIONSERVICE_H_ #define BERRYABSTRACTSELECTIONSERVICE_H_ #include "berryISelectionService.h" #include "berryIWorkbenchPage.h" #include "berryISelectionChangedListener.h" #include "berryISelectionProvider.h" #include "berryAbstractPartSelectionTracker.h" #include namespace berry { /** * \ingroup org_blueberry_ui_internal * * The selection service for a page */ class AbstractSelectionService : public ISelectionService { private: IWorkbenchPage* page; /** * The list of selection listeners (not per-part). */ - QList fListeners; + QList fListeners; /** * The list of post selection listeners (not per-part). */ - QList fPostListeners; + QList fPostListeners; /** * The currently active part. */ IWorkbenchPart::Pointer activePart; /** * The active part's selection provider, remembered in case the part * replaces its selection provider after we hooked a listener. */ ISelectionProvider::Pointer activeProvider; /** * Map from part id (String) to per-part tracker (AbstractPartSelectionTracker). */ QHash perPartTrackers; struct SelectionListener : public ISelectionChangedListener { SelectionListener(AbstractSelectionService* tracker); - void SelectionChanged(SelectionChangedEvent::Pointer event); + void SelectionChanged(const SelectionChangedEvent::Pointer& event); AbstractSelectionService* m_SelectionService; }; friend class PostSelectionListener; struct PostSelectionListener : public ISelectionChangedListener { PostSelectionListener(AbstractSelectionService* tracker); - void SelectionChanged(SelectionChangedEvent::Pointer event); + void SelectionChanged(const SelectionChangedEvent::Pointer& event); AbstractSelectionService* m_SelectionService; }; friend struct PostSelectionListener; /** * The JFace selection listener to hook on the active part's selection provider. */ - ISelectionChangedListener::Pointer selListener; + QScopedPointer selListener; /** * The JFace post selection listener to hook on the active part's selection provider. */ - ISelectionChangedListener::Pointer postSelListener; + QScopedPointer postSelListener; public: //SelectionEvents& GetSelectionEvents(const QString& partId = ""); /* (non-Javadoc) * Method declared on ISelectionService. */ - void AddSelectionListener(ISelectionListener::Pointer l); + void AddSelectionListener(ISelectionListener* l); /* (non-Javadoc) * Method declared on ISelectionService. */ - void AddSelectionListener(const QString& partId, ISelectionListener::Pointer listener); + void AddSelectionListener(const QString& partId, ISelectionListener* listener); /* (non-Javadoc) * Method declared on ISelectionService. */ - void AddPostSelectionListener(ISelectionListener::Pointer l); + void AddPostSelectionListener(ISelectionListener* l); /* (non-Javadoc) * Method declared on ISelectionService. */ void AddPostSelectionListener(const QString& partId, - ISelectionListener::Pointer listener); + ISelectionListener* listener); /* (non-Javadoc) * Method declared on ISelectionService. */ - void RemoveSelectionListener(ISelectionListener::Pointer l); + void RemoveSelectionListener(ISelectionListener* l); /* * (non-Javadoc) * Method declared on ISelectionListener. */ void RemovePostSelectionListener(const QString& partId, - ISelectionListener::Pointer listener); + ISelectionListener* listener); /* (non-Javadoc) * Method declared on ISelectionService. */ - void RemovePostSelectionListener(ISelectionListener::Pointer l); + void RemovePostSelectionListener(ISelectionListener* l); /* * (non-Javadoc) * Method declared on ISelectionListener. */ void RemoveSelectionListener(const QString& partId, - ISelectionListener::Pointer listener); + ISelectionListener* listener); protected: AbstractSelectionService(); /** * Fires a selection event to the given listeners. * * @param part the part or null if no active part * @param sel the selection or null if no active selection */ - void FireSelection(IWorkbenchPart::Pointer part, ISelection::ConstPointer sel); + void FireSelection(const IWorkbenchPart::Pointer& part, + const ISelection::ConstPointer& sel); /** * Fires a selection event to the given listeners. * * @param part the part or null if no active part * @param sel the selection or null if no active selection */ - void FirePostSelection(IWorkbenchPart::Pointer part, - ISelection::ConstPointer sel); + void FirePostSelection(const IWorkbenchPart::Pointer& part, + const ISelection::ConstPointer& sel); /** * Returns the per-part selection tracker for the given part id. * * @param partId part identifier * @return per-part selection tracker */ AbstractPartSelectionTracker::Pointer GetPerPartTracker(const QString& partId); /** * Creates a new per-part selection tracker for the given part id. * * @param partId part identifier * @return per-part selection tracker */ virtual AbstractPartSelectionTracker::Pointer CreatePartTracker( const QString& partId) const = 0; public: /** * Returns the selection. */ ISelection::ConstPointer GetSelection() const; /* * @see ISelectionService#getSelection(String) */ ISelection::ConstPointer GetSelection(const QString& partId); /** * Sets the current-active part (or null if none) * * @since 3.1 * * @param newPart the new active part (or null if none) */ void SetActivePart(IWorkbenchPart::Pointer newPart); // /** // * Notifies the listener that a part has been activated. // */ // public void partActivated(IWorkbenchPart newPart) { // // Optimize. // if (newPart == activePart) // return; // // // Unhook selection from the old part. // reset(); // // // Update active part. // activePart = newPart; // // // Hook selection on the new part. // if (activePart != null) { // activeProvider = activePart.getSite().getSelectionProvider(); // if (activeProvider != null) { // // Fire an event if there's an active provider // activeProvider.addSelectionChangedListener(selListener); // ISelection sel = activeProvider.getSelection(); // fireSelection(newPart, sel); // if (activeProvider instanceof IPostSelectionProvider) // ((IPostSelectionProvider) activeProvider) // .addPostSelectionChangedListener(postSelListener); // else // activeProvider.addSelectionChangedListener(postSelListener); // firePostSelection(newPart, sel); // } else { // //Reset active part. activeProvider may not be null next time this method is called. // activePart = null; // } // } // // No need to fire an event if no active provider, since this was done in reset() // } // // /** // * Notifies the listener that a part has been brought to the front. // */ // public void partBroughtToTop(IWorkbenchPart newPart) { // // do nothing, the active part has not changed, // // so the selection is unaffected // } // // /** // * Notifies the listener that a part has been closed // */ // public void partClosed(IWorkbenchPart part) { // // Unhook selection from the part. // if (part == activePart) { // reset(); // } // } // // /** // * Notifies the listener that a part has been deactivated. // */ // public void partDeactivated(IWorkbenchPart part) { // // Unhook selection from the part. // if (part == activePart) { // reset(); // } // } // // /** // * Notifies the listener that a part has been opened. // */ // public void partOpened(IWorkbenchPart part) { // // Wait for activation. // } // // /** // * Notifies the listener that a part has been opened. // */ // public void partInputChanged(IWorkbenchPart part) { // // 36501 - only process if part is active // if (activePart == part) { // reset(); // partActivated(part); // } // } // // /** // * Resets the service. The active part and selection provider are // * dereferenced. // */ // public void reset() { // if (activePart != null) { // fireSelection(null, null); // firePostSelection(null, null); // if (activeProvider != null) { // activeProvider.removeSelectionChangedListener(selListener); // if (activeProvider instanceof IPostSelectionProvider) // ((IPostSelectionProvider) activeProvider) // .removePostSelectionChangedListener(postSelListener); // else // activeProvider // .removeSelectionChangedListener(postSelListener); // activeProvider = null; // } // activePart = null; // } // } }; } #endif /*BERRYABSTRACTSELECTIONSERVICE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryActivePartExpression.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryActivePartExpression.cpp new file mode 100644 index 0000000000..81177b5223 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryActivePartExpression.cpp @@ -0,0 +1,71 @@ +/*=================================================================== + +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 "berryActivePartExpression.h" + +#include "berryISources.h" +#include "berryIWorkbenchPart.h" + +namespace berry { + +const int ActivePartExpression::HASH_INITIAL = qHash(ActivePartExpression::GetStaticClassName()); + +ActivePartExpression::ActivePartExpression(IWorkbenchPart* activePart) + : activePart(activePart) +{ + if (activePart == NULL) + { + throw ctkInvalidArgumentException("The active part must not be null"); + } +} + +void ActivePartExpression::CollectExpressionInfo(ExpressionInfo* info) const +{ + info->AddVariableNameAccess(ISources::ACTIVE_PART_NAME()); +} + +bool ActivePartExpression::operator==(const Object* object) const +{ + if (const ActivePartExpression* that = dynamic_cast(object)) + { + return this->activePart->operator ==(that->activePart); + } + + return false; +} + +SmartPointer ActivePartExpression::Evaluate(IEvaluationContext* context) const +{ + const Object::ConstPointer variable = context->GetVariable(ISources::ACTIVE_PART_NAME()); + if (variable == activePart) + { + return EvaluationResult::TRUE_EVAL; + } + return EvaluationResult::FALSE_EVAL; +} + +QString ActivePartExpression::ToString() const +{ + QString str = "ActivePartExpression(" + activePart->ToString() + ')'; + return str; +} + +uint ActivePartExpression::ComputeHashCode() const +{ + return HASH_INITIAL * HASH_FACTOR + activePart->HashCode(); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryActivePartExpression.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryActivePartExpression.h new file mode 100644 index 0000000000..c71e0f2074 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryActivePartExpression.h @@ -0,0 +1,80 @@ +/*=================================================================== + +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 BERRYACTIVEPARTEXPRESSION_H +#define BERRYACTIVEPARTEXPRESSION_H + +#include "berryExpression.h" + +namespace berry { + +struct IWorkbenchPart; + +/** + *

+ * An expression that is bound to a particular part instance. + *

+ *

+ * This class is not intended for use outside of the + * org.blueberry.ui plug-in. + *

+ */ +class ActivePartExpression : public Expression +{ + +private: + + /** + * The seed for the hash code for all schemes. + */ + static const int HASH_INITIAL; + + /** + * The part that must be active for this expression to evaluate to + * true. This value is never null. + */ + IWorkbenchPart* const activePart; + +public: + + berryObjectMacro(berry::ActivePartExpression) + + /** + * Constructs a new instance of ActivePartExpression + * + * @param activePart + * The part to match with the active part; may be + * null + */ + ActivePartExpression(IWorkbenchPart* activePart); + + void CollectExpressionInfo(ExpressionInfo* info) const; + + bool operator==(const Object* object) const; + + SmartPointer Evaluate(IEvaluationContext* context) const; + + QString ToString() const; + +protected: + + uint ComputeHashCode() const; + +}; + +} + +#endif // BERRYACTIVEPARTEXPRESSION_H diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAndExpression.cpp similarity index 56% copy from BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandler.cpp copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAndExpression.cpp index 512a980a11..0f763ec04c 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryAbstractHandler.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAndExpression.cpp @@ -1,48 +1,37 @@ /*=================================================================== 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 "berryAbstractHandler.h" +#include "berryAndExpression.h" namespace berry { -AbstractHandler::AbstractHandler() : - baseEnabled(true) +bool AndExpression::operator==(const Object* object) const { - -} - -bool AbstractHandler::IsEnabled() -{ - return baseEnabled; -} - -bool AbstractHandler::IsHandled() -{ - return true; -} - -void AbstractHandler::SetBaseEnabled(bool state) -{ - if (baseEnabled == state) + if(const AndExpression* that = dynamic_cast(object)) { - return; + return this->Equals(this->fExpressions, that->fExpressions); } - baseEnabled = state; - //fireHandlerChanged(new HandlerEvent(this, true, false)); + return false; } +EvaluationResult::ConstPointer +AndExpression::Evaluate(IEvaluationContext* context) const +{ + return this->EvaluateAnd(context); } + +} // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAndExpression.h old mode 100644 new mode 100755 similarity index 56% copy from BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAndExpression.h index 25a2d7c6a0..9fe6dda807 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectString.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAndExpression.h @@ -1,41 +1,36 @@ /*=================================================================== 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 BERRYOSGISTRING_H_ -#define BERRYOSGISTRING_H_ +#ifndef __BERRY_AND_EXPRESSION_H__ +#define __BERRY_AND_EXPRESSION_H__ -#include "berryMacros.h" - -#include +#include "berryCompositeExpression.h" namespace berry { -class ObjectString : public QString, public Object -{ +// Copied from org.blueberry.core.commands +class AndExpression : public CompositeExpression { public: - berryObjectMacro(berry::ObjectString) - - ObjectString() {} - ObjectString(const QString& s) : QString(s) {} + bool operator==(const Object* object) const; - ~ObjectString() {} + EvaluationResult::ConstPointer Evaluate(IEvaluationContext* context) const; }; -} +} // namespace berry -#endif /*BERRYOSGISTRING_H_*/ +#endif // __BERRY_AND_EXPRESSION_H__ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCategory.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCategory.h index c200ec1e32..6e37e62f03 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCategory.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCategory.h @@ -1,185 +1,185 @@ /*=================================================================== 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 BERRYCATEGORY_H_ #define BERRYCATEGORY_H_ #include #include namespace berry { /** * \ingroup org_blueberry_ui_internal * * Category provides for hierarchical grouping of elements * registered in the registry. One extension normally defines * a category, and other reference it via its ID. *

* A category may specify its parent category in order to * achieve hierarchy. *

*/ template class Category : /*IWorkbenchAdapter*/public IAdaptable, public Object { public: berryObjectMacro(Category) typedef T ElementType; /** * Name of the miscellaneous category */ const static QString MISC_NAME; /** * Identifier of the miscellaneous category */ const static QString MISC_ID; private: QString id; QString name; QList parentPath; QList elements; IConfigurationElement::Pointer configurationElement; public: /** * Creates an instance of Category as a * miscellaneous category. */ Category(); /** * Creates an instance of Category with * an ID and label. * * @param id the unique identifier for the category * @param label the presentation label for this category */ Category(const QString& id, const QString& label); /** * Creates an instance of Category using the * information from the specified configuration element. * * @param configElement the IConfigurationElement containing * the ID, label, and optional parent category path. * @throws WorkbenchException if the ID or label is null GetImageDescriptor() const; /** * Return the id for this category. * @return the id */ const QString& GetId() const; /** * Return the label for this category. * * @return the label */ QString GetLabel() const; /** * Return the parent path for this category. * * @return the parent path */ QList GetParentPath(); /** * Return the unparsed parent path. May be null. * * @return the unparsed parent path or null */ QString GetRawParentPath() const; /** * Return the root path for this category. * * @return the root path */ QString GetRootPath(); /** * Return the elements contained in this category. * * @return the elements */ const QList& GetElements() const; /** * Return whether a given object exists in this category. * * @param o the object to search for * @return whether the object is in this category */ bool HasElement(const ElementType& o) const; /** * Return whether this category has child elements. * * @return whether this category has child elements */ bool HasElements() const; /* (non-Javadoc) * @see org.blueberry.ui.model.IWorkbenchAdapter#getParent(java.lang.Object) */ ElementType* GetParent(const ElementType& o); /** * Clear all elements from this category. * */ void Clear(); protected: /* (non-Javadoc) * Method declared on IAdaptable. */ - Poco::Any GetAdapter(const QString& adapter); + Object* GetAdapter(const QString& adapter); }; } // namespace berry #include "berryCategory.txx" #endif /*BERRYCATEGORY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCategory.txx b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCategory.txx index 11d2c120fa..ef019a0808 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCategory.txx +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCategory.txx @@ -1,178 +1,178 @@ /*=================================================================== 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 __BERRY_CATEGORY_TXX__ #define __BERRY_CATEGORY_TXX__ #include "berryWorkbenchRegistryConstants.h" #include "../berryUIException.h" #include namespace berry { template const QString Category::MISC_NAME = "Other"; template const QString Category::MISC_ID = "org.blueberry.ui.internal.otherCategory"; template Category::Category() { this->id = MISC_ID; this->name = MISC_NAME; } template Category::Category(const QString& ID, const QString& label) : id(ID), name(label) { } template Category::Category(IConfigurationElement::Pointer configElement) : configurationElement(configElement) { QString id = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ID); if (id == "" || GetLabel() == "") { throw WorkbenchException(QString("Invalid category: ") + id); } } template void Category::AddElement(ElementType element) { elements.push_back(element); } template -Poco::Any Category::GetAdapter(const QString& adapter) +Object* Category::GetAdapter(const QString& adapter) { - if (adapter == IConfigurationElement::GetStaticClassName()) + if (adapter == qobject_interface_iid()) { - return Poco::Any(configurationElement); + return configurationElement.GetPointer(); } else { - return Poco::Any(); + return NULL; } } //template //ImageDescriptor Category::GetImageDescriptor() //{ // return WorkbenchImages.getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER); //} template const QString& Category::GetId() const { return id; } template QString Category::GetLabel() const { if (configurationElement.IsNull()) return name; return configurationElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME); } template QList Category::GetParentPath() { if (parentPath.size() > 0) { return parentPath; } QString unparsedPath(this->GetRawParentPath()); foreach(QString token, unparsedPath.split('/', QString::SkipEmptyParts)) { parentPath.push_back(token.trimmed()); } return parentPath; } template QString Category::GetRawParentPath() const { if (configurationElement.IsNull()) return QString(); return configurationElement->GetAttribute(WorkbenchRegistryConstants::ATT_PARENT_CATEGORY); } template QString Category::GetRootPath() { if (this->GetParentPath().size() > 0) { return GetParentPath()[0]; } return id; } template const QList& Category::GetElements() const { return elements; } template bool Category::HasElement(const ElementType& o) const { if (elements.empty()) { return false; } for (typename QList::const_iterator iter = elements.begin(); iter != elements.end(); ++iter) { if (*iter == o) return true; } return false; } template bool Category::HasElements() const { return !elements.empty(); } template T* Category::GetParent(const ElementType& o) { return 0; } template void Category::Clear() { elements.clear(); } } // namespace berry #endif // __BERRY_CATEGORY_TXX__ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandContributionItemParameter.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandContributionItemParameter.h index b0c745d5d2..03dc837172 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandContributionItemParameter.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandContributionItemParameter.h @@ -1,194 +1,194 @@ /*=================================================================== 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 BERRYCOMMANDCONTRIBUTIONITEMPARAMETER_H #define BERRYCOMMANDCONTRIBUTIONITEMPARAMETER_H #include #include #include "berryCommandContributionItem.h" namespace berry { struct IServiceLocator; /** * A help class for the various parameters that can be used with command * contributions. Mandatory parameters are in the constructor, and public fields * can be set to fill in other parameters. */ -class CommandContributionItemParameter : public Object +class CommandContributionItemParameter : public virtual Object { public: berryObjectMacro(CommandContributionItemParameter) /** * a service locator that is most appropriate for this contribution. * Typically the local {@link IWorkbenchWindow} or * {@link IWorkbenchPartSite} will be sufficient. Must not be * null. */ IServiceLocator* serviceLocator; /** * The id for this item. May be null. Items without an id * cannot be referenced later. */ QString id; /** * A command id for a defined command. Must not be null. */ QString commandId; /** * A map of strings to strings which represent parameter names to values. * The parameter names must match those in the command definition. May be * null */ QHash parameters; /** * An icon for this item. May be null. */ QIcon icon; /** * A label for this item. May be null. */ QString label; /** * A mnemonic for this item to be applied to the label. May be * null. */ QChar mnemonic; /** * A tooltip for this item. May be null. Tooltips are * currently only valid for toolbar contributions. */ QString tooltip; /** * The style of this menu contribution. See the CommandContributionItem * STYLE_* contants. */ CommandContributionItem::Style style; /** * The help context id to be applied to this contribution. May be * null */ QString helpContextId; /** * The icon style to use. */ QString iconStyle; /** * The visibility tracking for a menu contribution. */ bool visibleEnabled; /** * Any number of mode bits, like * {@link CommandContributionItem#MODE_FORCE_TEXT}. */ CommandContributionItem::Modes mode; /** * Create the parameter object. Nullable attributes can be set directly. * * @param serviceLocator * a service locator that is most appropriate for this * contribution. Typically the local {@link IWorkbenchWindow} or * {@link IWorkbenchPartSite} will be sufficient. Must not be * null. * @param id * The id for this item. May be null. Items * without an id cannot be referenced later. * @param commandId * A command id for a defined command. Must not be * null. * @param style * The style of this menu contribution. See the STYLE_* contants. */ CommandContributionItemParameter(IServiceLocator* serviceLocator, const QString& id, const QString& commandId, CommandContributionItem::Style style); /** * Build the parameter object. *

* Note: This constructor should not be called outside the framework. *

* * @param serviceLocator * a service locator that is most appropriate for this * contribution. Typically the local {@link IWorkbenchWindow} or * {@link IWorkbenchPartSite} will be sufficient. Must not be * null. * @param id * The id for this item. May be null. Items * without an id cannot be referenced later. * @param commandId * A command id for a defined command. Must not be * null. * @param parameters * A map of strings to strings which represent parameter names to * values. The parameter names must match those in the command * definition. May be null * @param icon * An icon for this item. May be null. * @param disabledIcon * A disabled icon for this item. May be null. * @param hoverIcon * A hover icon for this item. May be null. * @param label * A label for this item. May be null. * @param mnemonic * A mnemonic for this item to be applied to the label. May be * null. * @param tooltip * A tooltip for this item. May be null. Tooltips * are currently only valid for toolbar contributions. * @param style * The style of this menu contribution. See the STYLE_* contants. * @param helpContextId * the help context id to be applied to this contribution. May be * null * @param visibleEnabled * Visibility tracking for the menu contribution. * @noreference This constructor is not intended to be referenced by clients. */ CommandContributionItemParameter(IServiceLocator* serviceLocator, const QString& id, const QString& commandId, const QHash ¶meters, const QIcon& icon, const QString label, const QChar &mnemonic, const QString& tooltip, CommandContributionItem::Style style, const QString& helpContextId, bool visibleEnabled); }; } #endif // BERRYCOMMANDCONTRIBUTIONITEM_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandParameter.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandParameter.cpp new file mode 100644 index 0000000000..3c191eed42 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandParameter.cpp @@ -0,0 +1,147 @@ +/*=================================================================== + +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 "berryCommandParameter.h" + +#include "berryIConfigurationElement.h" +#include "berryIParameterValues.h" +#include "berryCoreException.h" +#include "berryCommandExceptions.h" +#include "berryParameterType.h" + +namespace berry { + +const QString CommandParameter::ATTRIBUTE_VALUES = "values"; +const int CommandParameter::HASH_CODE_NOT_COMPUTED = 0; +const int CommandParameter::HASH_FACTOR = 89; +const int CommandParameter::HASH_INITIAL = qHash(CommandParameter::GetStaticClassName()); + +CommandParameter::CommandParameter(const QString& id, const QString& name, + const SmartPointer& values, + const SmartPointer& parameterType, + const bool optional) + : name(name) + , optional(optional) + , parameterType(parameterType) + , valuesConfigurationElement(values) + , id(id) +{ + if (id.isNull()) + { + throw ctkInvalidArgumentException("Cannot create a parameter with a null id"); + } + + if (name.isNull()) + { + throw ctkInvalidArgumentException("The name of a parameter cannot be null."); + } + + if (values.IsNull()) + { + throw ctkInvalidArgumentException("The values for a parameter cannot be null."); + } +} + +bool CommandParameter::operator==(const Object* object) const +{ + if (this == object) + { + return true; + } + + if (const CommandParameter* parameter = dynamic_cast(object)) + { + if (id != parameter->id) + { + return false; + } + if (name != parameter->name) + { + return false; + } + if (values != parameter->values) + { + return false; + } + + return optional == parameter->optional; + } + else + { + return false; + } +} + +QString CommandParameter::GetId() const +{ + return id; +} + +QString CommandParameter::GetName() const +{ + return name; +} + +SmartPointer CommandParameter::GetParameterType() const +{ + return parameterType; +} + +IParameterValues* CommandParameter::GetValues() const +{ + if (values.isNull()) + { + try + { + values.reset(valuesConfigurationElement->CreateExecutableExtension(ATTRIBUTE_VALUES)); + } + catch (const CoreException& e) + { + throw ParameterValuesException("Problem creating parameter values", e); + } + + if (values.isNull()) + { + throw ParameterValuesException( + "Parameter values were not an instance of IParameterValues"); + } + } + + return values.data(); +} + +bool CommandParameter::IsOptional() const +{ + return optional; +} + +QString CommandParameter::ToString() const +{ + if (str.isNull()) + { + QString paramValuesStr; + if (!values.isNull()) + { + QDebug dbg(¶mValuesStr); + dbg << values->GetParameterValues(); + } + str = "Parameter(" + id + ',' + name + ',' + paramValuesStr + ',' + optional +')'; + } + + return str; +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandParameter.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandParameter.h new file mode 100644 index 0000000000..6dedcc5dcb --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandParameter.h @@ -0,0 +1,191 @@ +/*=================================================================== + +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 BERRYCOMMANDPARAMETER_H +#define BERRYCOMMANDPARAMETER_H + +#include "berryIParameter.h" +#include "berryITypedParameter.h" + +namespace berry { + +struct IConfigurationElement; + +/** + *

+ * A parameter for a command. A parameter identifies a type of information that + * the command might accept. For example, a "Show View" command might accept the + * id of a view for display. This parameter also identifies possible values, for + * display in the user interface. + *

+ *

+ * Parameters are mutable, and can change as the command changes. Notifications + * will not be sent if the parameter itself changes. Listeners can be attached + * to the command. + *

+ */ +class CommandParameter : public IParameter, public ITypedParameter +{ + +public: + + berryObjectMacro(berry::CommandParameter) + +private: + + /** + * The name of the configuration element attribute contain the values. This + * is used to retrieve the executable extension + * IParameterValues. + */ + static const QString ATTRIBUTE_VALUES; // = "values"; + + /** + * The constant integer hash code value meaning the hash code has not yet + * been computed. + */ + static const int HASH_CODE_NOT_COMPUTED; // = 0; + + /** + * A factor for computing the hash code for all schemes. + */ + static const int HASH_FACTOR; // = 89; + + /** + * The seed for the hash code for all schemes. + */ + static const int HASH_INITIAL; + + /** + * The hash code for this object. This value is computed lazily, and marked + * as invalid when one of the values on which it is based changes. + */ + mutable int hashCode; // = HASH_CODE_NOT_COMPUTED; + + /** + * The non-externalized name of this parameter. The name is used as the in a + * name-value parameter map. This value will never be null. + */ + const QString name; + + /** + * Whether the parameter is optional (as opposed to required). + */ + const bool optional; + + /** + * The type for this parameter. This value may be null if the + * parameter is not typed. + */ + const SmartPointer parameterType; + + /** + * The actual IParameterValues implementation. This is lazily + * loaded from the valuesConfigurationElement, to avoid + * unnecessary class-loading. + */ + mutable QScopedPointer values; + + /** + * The configuration element providing the executable extension that will + * implement IParameterValues. This value will not be + * null. + */ + const SmartPointer valuesConfigurationElement; + +protected: + + /** + * The identifier for this object. This identifier should be unique across + * all objects of the same type and should never change. This value will + * never be null. + */ + const QString id; + + /** + * The string representation of this object. This string is for debugging + * purposes only, and is not meant to be displayed to the user. This value + * is computed lazily, and is cleared if one of its dependent values + * changes. + */ + mutable QString str; + +public: + + /** + * Constructs a new instance of Parameter with all of its + * values pre-defined. + * + * @param id + * The identifier for this parameter; must not be + * null. + * @param name + * The name for this parameter; must not be null. + * @param values + * The values for this parameter; must not be null. + * @param parameterType + * the type for this parameter; may be null if the + * parmeter doesn't declare type. + * @param optional + * Whether this parameter is optional (as opposed to required). + * @param commandService + * The command service from which parameter types can be + * retrieved; must not be null. + */ + CommandParameter(const QString& id, const QString& name, + const SmartPointer& values, + const SmartPointer& parameterType, + const bool optional); + + /** + * Tests whether this object is equal to another object. A parameter is only + * equal to another parameter with the same properties. + * + * @param object + * The object with which to compare; may be null. + * @return true if the objects are equal; false + * otherwise. + */ + bool operator==(const Object* object) const; + + QString GetId() const; + + QString GetName() const; + + SmartPointer GetParameterType() const; + + IParameterValues* GetValues() const; + + uint HashCode() const + { + if (hashCode == HASH_CODE_NOT_COMPUTED) + { + hashCode = HASH_INITIAL * HASH_FACTOR + qHash(id); + if (hashCode == HASH_CODE_NOT_COMPUTED) + { + hashCode++; + } + } + return hashCode; + } + + bool IsOptional() const; + + QString ToString() const; +}; + +} +#endif // BERRYCOMMANDPARAMETER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandPersistence.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandPersistence.cpp new file mode 100644 index 0000000000..3b4eb4e7f0 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandPersistence.cpp @@ -0,0 +1,401 @@ +/*=================================================================== + +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 "berryCommandPersistence.h" + +#include "berryHandleObject.h" +#include "berryStatus.h" +#include "berryICommandService.h" +#include "berryIConfigurationElement.h" +#include "berryCommandCategory.h" +#include "berryCommand.h" +#include "berryCommandParameter.h" +#include "berryParameterType.h" +#include "berryParameterValueConverterProxy.h" +#include "berryCommandStateProxy.h" +#include "berryIExtensionRegistry.h" +#include "berryIExtension.h" +#include "berryPlatform.h" +#include "berryPlatformUI.h" +#include "berryWorkbenchPlugin.h" +#include "berryIPreferencesService.h" +#include "berryIPreferences.h" +#include "berryCommandService.h" + +namespace berry { + +const int CommandPersistence::INDEX_CATEGORY_DEFINITIONS = 0; +const int CommandPersistence::INDEX_COMMAND_DEFINITIONS = 1; +const int CommandPersistence::INDEX_PARAMETER_TYPE_DEFINITIONS = 2; +const int CommandPersistence::INDEX_SIZE = 3; + +void CommandPersistence::ReadCategoriesFromRegistry( + const QList >& configurationElements, + ICommandService* const commandService) +{ + // Undefine all the previous handle objects. + const QList handleObjects = commandService->GetDefinedCategories(); + foreach (const CommandCategory::Pointer handleObject, handleObjects) + { + handleObject->Undefine(); + } + + // Define the uncategorized category. + commandService->DefineUncategorizedCategory( + QObject::tr("Uncategorized"), + QObject::tr("Commands that were either auto-generated or have no category")); + + QList warningsToLog; + + foreach (const IConfigurationElement::Pointer& configurationElement, configurationElements) + { + // Read out the category identifier. + const QString categoryId = ReadRequired(configurationElement, + ATT_ID, warningsToLog, "Categories need an id"); + if (categoryId.isNull()) + { + continue; + } + + // Read out the name. + const QString name = ReadRequired(configurationElement, ATT_NAME, + warningsToLog, "Categories need a name", + categoryId); + if (name.isNull()) + { + continue; + } + + // Read out the description. + const QString description = ReadOptional(configurationElement, ATT_DESCRIPTION); + + const CommandCategory::Pointer category = commandService->GetCategory(categoryId); + category->Define(name, description); + } + + // If there were any warnings, then log them now. + LogWarnings(warningsToLog, + "Warnings while parsing the commands from the 'org.blueberry.ui.commands' and 'org.blueberry.ui.actionDefinitions' extension points."); +} + +void CommandPersistence::ReadCommandsFromRegistry( + const QList >& configurationElements, + ICommandService* const commandService) +{ + // Undefine all the previous handle objects. + const QList handleObjects = commandService->GetDefinedCommands(); + foreach (const Command::Pointer& handleObject, handleObjects) + { + handleObject->Undefine(); + } + + QList warningsToLog; + + foreach (const IConfigurationElement::Pointer& configurationElement, configurationElements) + { + // Read out the command identifier. + const QString commandId = ReadRequired(configurationElement, ATT_ID, + warningsToLog, "Commands need an id"); + if (commandId.isNull()) + { + continue; + } + + // Read out the name. + const QString name = ReadRequired(configurationElement, ATT_NAME, + warningsToLog, "Commands need a name"); + if (name.isNull()) + { + continue; + } + + // Read out the description. + const QString description = ReadOptional(configurationElement, ATT_DESCRIPTION); + + // Read out the category id. + QString categoryId = configurationElement->GetAttribute(ATT_CATEGORY_ID); + if (categoryId.isEmpty()) + { + categoryId = configurationElement->GetAttribute(ATT_CATEGORY); + if (categoryId.isEmpty()) + { + categoryId = QString(); + } + } + + // Read out the parameters. + const QList parameters = ReadParameters(configurationElement, + warningsToLog, commandService); + + // Read out the returnTypeId. + const QString returnTypeId = ReadOptional(configurationElement, ATT_RETURN_TYPE_ID); + + // Read out the help context identifier. + const QString helpContextId = ReadOptional(configurationElement, ATT_HELP_CONTEXT_ID); + + const Command::Pointer command = commandService->GetCommand(commandId); + const CommandCategory::Pointer category = commandService->GetCategory(categoryId); + if (!category->IsDefined()) + { + AddWarning(warningsToLog, "Commands should really have a category", + configurationElement, commandId, "categoryId", categoryId); + } + + ParameterType::Pointer returnType; + if (!returnTypeId.isNull()) + { + returnType = commandService->GetParameterType(returnTypeId); + } + + command->Define(name, description, category, parameters, returnType, helpContextId); + ReadState(configurationElement, warningsToLog, command); + } + + // If there were any warnings, then log them now. + LogWarnings(warningsToLog, + "Warnings while parsing the commands from the 'org.blueberry.ui.commands' and 'org.blueberry.ui.actionDefinitions' extension points."); +} + +QList > CommandPersistence::ReadParameters( + const SmartPointer& configurationElement, + QList >& warningsToLog, + ICommandService* const commandService) +{ + const QList parameterElements = configurationElement + ->GetChildren(TAG_COMMAND_PARAMETER); + if (parameterElements.isEmpty()) + { + return QList(); + } + + QList parameters; + foreach (const IConfigurationElement::Pointer& parameterElement, parameterElements) + { + // Read out the id + const QString id = ReadRequired(parameterElement, ATT_ID, + warningsToLog, "Parameters need an id"); + if (id.isNull()) + { + continue; + } + + // Read out the name. + const QString name = ReadRequired(parameterElement, ATT_NAME, + warningsToLog, "Parameters need a name"); + if (name.isNull()) + { + continue; + } + + /* + * The IParameterValues will be initialized lazily as an + * IExecutableExtension. + */ + + // Read out the typeId attribute, if present. + const QString typeId = ReadOptional(parameterElement, ATT_TYPE_ID); + + // Read out the optional attribute, if present. + const bool optional = ReadBoolean(parameterElement, ATT_OPTIONAL, true); + + ParameterType::Pointer type; + if (!typeId.isNull()) + { + type = commandService->GetParameterType(typeId); + } + + const IParameter::Pointer parameter(new CommandParameter(id, name, + parameterElement, type, optional)); + parameters.push_back(parameter); + } + + return parameters; +} + +void CommandPersistence::ReadParameterTypesFromRegistry( + const QList >& configurationElements, + ICommandService* const commandService) +{ + + // Undefine all the previous handle objects. + const QList handleObjects = commandService->GetDefinedParameterTypes(); + foreach (const ParameterType::Pointer& handleObject, handleObjects) + { + handleObject->Undefine(); + } + + QList warningsToLog; + + foreach (const IConfigurationElement::Pointer configurationElement, configurationElements) + { + // Read out the commandParameterType identifier. + const QString parameterTypeId = ReadRequired(configurationElement, + ATT_ID, warningsToLog, "Command parameter types need an id"); + if (parameterTypeId.isNull()) + { + continue; + } + + // Read out the type. + const QString type = ReadOptional(configurationElement, ATT_TYPE); + + // Read out the converter. + const QString converter = ReadOptional(configurationElement, ATT_CONVERTER); + + /* + * if the converter attribute was given, create a proxy + * AbstractParameterValueConverter for the ParameterType, otherwise + * null indicates there is no converter + */ + const QSharedPointer parameterValueConverter( + (converter.isNull()) ? NULL : new ParameterValueConverterProxy(configurationElement)); + + const ParameterType::Pointer parameterType = commandService->GetParameterType(parameterTypeId); + parameterType->Define(type, parameterValueConverter); + } + + // If there were any warnings, then log them now. + LogWarnings(warningsToLog, + "Warnings while parsing the commandParameterTypes from the 'org.blueberry.ui.commands' extension point."); + +} + +void CommandPersistence::ReadState( + const SmartPointer& configurationElement, + QList >& warningsToLog, + const SmartPointer& command) +{ + const QList stateElements = configurationElement + ->GetChildren(TAG_STATE); + if (stateElements.isEmpty()) + { + return; + } + + foreach (const IConfigurationElement::Pointer stateElement, stateElements) + { + const QString id = ReadRequired(stateElement, ATT_ID, warningsToLog, "State needs an id"); + if (id.isNull()) + { + continue; + } + + if (CheckClass(stateElement, warningsToLog, + "State must have an associated class", id)) + { + const State::Pointer state( + new CommandStateProxy(stateElement, ATT_CLASS, + WorkbenchPlugin::GetDefault()->GetPreferences(), + CommandService::CreatePreferenceKey(command, id)) + ); + command->AddState(id, state); + } + } +} + +bool CommandPersistence::IsChangeImportant(const QList >& /*extensions*/, + RegistryChangeType /*changeType*/) +{ + return false; +} + +bool CommandPersistence::IsChangeImportant(const QList >& /*extensionPoints*/, + RegistryChangeType /*changeType*/) +{ + return false; +} + +void CommandPersistence::Read() +{ + RegistryPersistence::Read(); + ReRead(); +} + +CommandPersistence::CommandPersistence(ICommandService* const commandService) + : commandService(commandService) +{ + if (commandService == NULL) + { + throw ctkInvalidArgumentException("The command service cannot be null"); + } +} + +bool CommandPersistence::CommandsNeedUpdating(const QList >& extensions) +{ + foreach(const IExtension::Pointer& extension, extensions) + { + if (extension->GetExtensionPointUniqueIdentifier() == EXTENSION_COMMANDS || + extension->GetExtensionPointUniqueIdentifier() == EXTENSION_ACTION_DEFINITIONS) + { + return true; + } + } + return false; +} + +void CommandPersistence::ReRead() +{ + // Create the extension registry mementos. + IExtensionRegistry* const registry = Platform::GetExtensionRegistry(); + QList > indexedConfigurationElements; + for (int i = 0; i < INDEX_SIZE; ++i) + { + indexedConfigurationElements.push_back(QList()); + } + + // Sort the commands extension point based on element name. + QList commandsExtensionPoint = registry + ->GetConfigurationElementsFor(EXTENSION_COMMANDS); + foreach (const IConfigurationElement::Pointer& configurationElement, commandsExtensionPoint) + { + const QString name = configurationElement->GetName(); + + // Check if it is a binding definition. + if (TAG_COMMAND == name) + { + indexedConfigurationElements[INDEX_COMMAND_DEFINITIONS].push_back(configurationElement); + } + else if (TAG_CATEGORY == name) + { + indexedConfigurationElements[INDEX_CATEGORY_DEFINITIONS].push_back(configurationElement); + } + else if (TAG_COMMAND_PARAMETER_TYPE == name) + { + indexedConfigurationElements[INDEX_PARAMETER_TYPE_DEFINITIONS].push_back(configurationElement); + } + } + + const QList actionDefinitionsExtensionPoint = registry + ->GetConfigurationElementsFor(EXTENSION_ACTION_DEFINITIONS); + foreach (const IConfigurationElement::Pointer& configurationElement, actionDefinitionsExtensionPoint) + { + const QString name = configurationElement->GetName(); + + if (TAG_ACTION_DEFINITION == name) + { + indexedConfigurationElements[INDEX_COMMAND_DEFINITIONS].push_back(configurationElement); + } + } + + ReadCategoriesFromRegistry(indexedConfigurationElements[INDEX_CATEGORY_DEFINITIONS], + commandService); + ReadCommandsFromRegistry(indexedConfigurationElements[INDEX_COMMAND_DEFINITIONS], + commandService); + ReadParameterTypesFromRegistry(indexedConfigurationElements[INDEX_PARAMETER_TYPE_DEFINITIONS], + commandService); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandPersistence.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandPersistence.h new file mode 100644 index 0000000000..af9710bf19 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandPersistence.h @@ -0,0 +1,200 @@ +/*=================================================================== + +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 BERRYCOMMANDPERSISTENCE_H +#define BERRYCOMMANDPERSISTENCE_H + +#include "berryRegistryPersistence.h" + +namespace berry { + +struct IParameter; + +/** + *

+ * A static class for accessing the registry and the preference store. + *

+ */ +class CommandPersistence : public RegistryPersistence +{ + +private: + + friend class CommandService; + + /** + * The index of the category elements in the indexed array. + * + * @see CommandPersistence#read() + */ + static const int INDEX_CATEGORY_DEFINITIONS; // = 0; + + /** + * The index of the command elements in the indexed array. + * + * @see CommandPersistence#read() + */ + static const int INDEX_COMMAND_DEFINITIONS; // = 1; + + /** + * The index of the commandParameterType elements in the indexed array. + * + * @see CommandPersistence#read() + */ + static const int INDEX_PARAMETER_TYPE_DEFINITIONS; // = 2; + + static const int INDEX_SIZE; + + /** + * Reads all of the category definitions from the commands extension point. + * + * @param configurationElements + * The configuration elements in the commands extension point; + * must not be null, but may be empty. + * @param configurationElementCount + * The number of configuration elements that are really in the + * array. + * @param commandService + * The command service to which the categories should be added; + * must not be null. + */ + static void ReadCategoriesFromRegistry( + const QList >& configurationElements, + ICommandService* const commandService); + + /** + * Reads all of the command definitions from the commands extension point. + * + * @param configurationElements + * The configuration elements in the commands extension point; + * must not be null, but may be empty. + * @param configurationElementCount + * The number of configuration elements that are really in the + * array. + * @param commandService + * The command service to which the commands should be added; + * must not be null. + */ + static void ReadCommandsFromRegistry( + const QList >& configurationElements, + ICommandService* const commandService); + + /** + * Reads the parameters from a parent configuration element. This is used to + * read the parameter sub-elements from a command element. Each parameter is + * guaranteed to be valid. If invalid parameters are found, then a warning + * status will be appended to the warningsToLog list. + * + * @param configurationElement + * The configuration element from which the parameters should be + * read; must not be null. + * @param warningsToLog + * The list of warnings found during parsing. Warnings found + * while parsing the parameters will be appended to this list. + * This value must not be null. + * @param commandService + * The command service from which the parameter can get parameter + * types; must not be null. + * @return The array of parameters found for this configuration element; + * null if none can be found. + */ + static QList > ReadParameters( + const SmartPointer& configurationElement, + QList >& warningsToLog, + ICommandService* const commandService); + + /** + * Reads all of the commandParameterType definitions from the commands + * extension point. + * + * @param configurationElements + * The configuration elements in the commands extension point; + * must not be null, but may be empty. + * @param configurationElementCount + * The number of configuration elements that are really in the + * array. + * @param commandService + * The command service to which the commands should be added; + * must not be null. + */ + static void ReadParameterTypesFromRegistry( + const QList >& configurationElements, + ICommandService* const commandService); + + /** + * Reads the states from a parent configuration element. This is used to + * read the state sub-elements from a command element. Each state is + * guaranteed to be valid. If invalid states are found, then a warning + * status will be appended to the warningsToLog list. + * + * @param configurationElement + * The configuration element from which the states should be + * read; must not be null. + * @param warningsToLog + * The list of warnings found during parsing. Warnings found + * while parsing the parameters will be appended to this list. + * This value must not be null. + * @param command + * The command for which the state is being read; may be + * null. + */ + static void ReadState( + const SmartPointer& configurationElement, + QList >& warningsToLog, + const SmartPointer& command); + + /** + * The command service with which this persistence class is associated; + * never null. + */ + ICommandService* const commandService; + +protected: + + bool IsChangeImportant(const QList >& extensions, + RegistryChangeType changeType); + + bool IsChangeImportant(const QList >& extensionPoints, + RegistryChangeType changeType); + + /** + * Reads all of the commands and categories from the registry, + * + * @param commandService + * The command service which should be populated with the values + * from the registry; must not be null. + */ + void Read(); + +public: + + /** + * Constructs a new instance of CommandPersistence. + * + * @param commandService + * The command service which should be populated with the values + * from the registry; must not be null. + */ + CommandPersistence(ICommandService* const commandService); + + bool CommandsNeedUpdating(const QList >& extensions); + + void ReRead(); +}; + +} + +#endif // BERRYCOMMANDPERSISTENCE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandService.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandService.cpp index 13a78fb4a3..a85d8e8d60 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandService.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandService.cpp @@ -1,318 +1,318 @@ /*=================================================================== 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 "berryCommandService.h" #include #include #include #include #include +#include "berryPersistentState.h" #include "berryWorkbenchPlugin.h" #include "berryElementReference.h" +#include "berryIPreferences.h" #include #include #include #include #include #include #include namespace berry { const QString CommandService::PREFERENCE_KEY_PREFIX = "org.blueberry.ui.commands/state"; const QString CommandService::CreatePreferenceKey(const SmartPointer& command, const QString& stateId) { return PREFERENCE_KEY_PREFIX + '/' + command->GetId() + '/' + stateId; } CommandService::CommandService( CommandManager* commandManager) : commandManager(commandManager) + , commandPersistence(this) { if (commandManager == 0) { throw std::invalid_argument("Cannot create a command service with a null manager"); } - //this.commandPersistence = new CommandPersistence(this); } CommandService::~CommandService() { this->Dispose(); } void CommandService::AddExecutionListener(IExecutionListener* listener) { commandManager->AddExecutionListener(listener); } void CommandService::DefineUncategorizedCategory(const QString& name, const QString& description) { commandManager->DefineUncategorizedCategory(name, description); } SmartPointer CommandService::Deserialize(const QString& serializedParameterizedCommand) const { return commandManager->Deserialize(serializedParameterizedCommand); } void CommandService::Dispose() { - //commandPersistence.dispose(); - /* * All state on all commands neeeds to be disposed. This is so that the * state has a chance to persist any changes. */ -// final Command[] commands = commandManager.getAllCommands(); -// for (int i = 0; i < commands.length; i++) { -// final Command command = commands[i]; -// final String[] stateIds = command.getStateIds(); -// for (int j = 0; j < stateIds.length; j++) { -// final String stateId = stateIds[j]; -// final State state = command.getState(stateId); -// if (state instanceof PersistentState) { -// final PersistentState persistentState = (PersistentState) state; -// if (persistentState.shouldPersist()) { -// persistentState.save(PrefUtil -// .getInternalPreferenceStore(), -// createPreferenceKey(command, stateId)); -// } -// } -// } -// } + const QList commands = commandManager->GetAllCommands(); + foreach (const Command::Pointer& command, commands) + { + const QList stateIds = command->GetStateIds(); + foreach(const QString& stateId, stateIds) + { + const State::Pointer state = command->GetState(stateId); + if (PersistentState::Pointer persistentState = state.Cast()) + { + if (persistentState->ShouldPersist()) + { + persistentState->Save(WorkbenchPlugin::GetDefault()->GetPreferences(), + CreatePreferenceKey(command, stateId)); + } + } + } + } commandCallbacks.clear(); } SmartPointer CommandService::GetCategory(const QString& categoryId) const { return commandManager->GetCategory(categoryId); } SmartPointer CommandService::GetCommand(const QString& commandId) const { return commandManager->GetCommand(commandId); } QList > CommandService::GetDefinedCategories() const { return commandManager->GetDefinedCategories(); } QStringList CommandService::GetDefinedCategoryIds() const { return commandManager->GetDefinedCategoryIds().toList(); } QStringList CommandService::GetDefinedCommandIds() const { return commandManager->GetDefinedCommandIds().toList(); } QList > CommandService::GetDefinedCommands() const { return commandManager->GetDefinedCommands(); } QStringList CommandService::GetDefinedParameterTypeIds() const { return commandManager->GetDefinedParameterTypeIds().toList(); } QList > CommandService::GetDefinedParameterTypes() const { return commandManager->GetDefinedParameterTypes(); } QString CommandService::GetHelpContextId(const SmartPointer& command) const { return commandManager->GetHelpContextId(command); } QString CommandService::GetHelpContextId(const QString& commandId) const { Command::Pointer command = GetCommand(commandId); return commandManager->GetHelpContextId(command); } SmartPointer CommandService::GetParameterType(const QString& parameterTypeId) const { return commandManager->GetParameterType(parameterTypeId); } void CommandService::ReadRegistry() { - //commandPersistence.read(); + commandPersistence.Read(); } void CommandService::RemoveExecutionListener(IExecutionListener* listener) { commandManager->RemoveExecutionListener(listener); } void CommandService::SetHelpContextId(const SmartPointer& handler, const QString& helpContextId) { commandManager->SetHelpContextId(handler, helpContextId); } void CommandService::RefreshElements(const QString& commandId, const QHash& filter) { Command::Pointer cmd = GetCommand(commandId); if (!cmd->IsDefined() || !(cmd->GetHandler().Cast())) { return; } IElementUpdater::Pointer updater = cmd->GetHandler().Cast(); if (commandCallbacks.isEmpty()) { return; } if(!commandCallbacks.contains(commandId)) { return; } foreach (IElementReference::Pointer callbackRef, commandCallbacks[commandId]) { struct _SafeRunnable : public ISafeRunnable { IElementUpdater* updater; IElementReference* callbackRef; _SafeRunnable(IElementUpdater* updater, IElementReference* callbackRef) : updater(updater), callbackRef(callbackRef) {} void HandleException(const std::exception& exc) { WorkbenchPlugin::Log(QString("Failed to update callback: ") + callbackRef->GetCommandId() + exc.what()); } void Run() { updater->UpdateElement(callbackRef->GetElement().GetPointer(), callbackRef->GetParameters()); } }; QHash parms = callbackRef->GetParameters(); ISafeRunnable::Pointer run(new _SafeRunnable(updater.GetPointer(), callbackRef.GetPointer())); if (filter.isEmpty()) { SafeRunner::Run(run); } else { bool match = true; QHashIterator i(filter); while (i.hasNext()) { i.next(); Object::Pointer value = parms[i.key()]; if (i.value() != value) { match = false; break; } } if (match) { SafeRunner::Run(run); } } } } SmartPointer CommandService::RegisterElementForCommand( const SmartPointer& command, const SmartPointer& element) { if (!command->GetCommand()->IsDefined()) { throw NotDefinedException( "Cannot define a callback for undefined command " + command->GetCommand()->GetId()); } if (element.IsNull()) { throw NotDefinedException("No callback defined for command " + command->GetCommand()->GetId()); } QHash paramMap = command->GetParameterMap(); QHash parms; for (QHash::const_iterator i = paramMap.begin(); i != paramMap.end(); ++i) { Object::Pointer value(new ObjectString(i.value())); parms.insert(i.key(), value); } IElementReference::Pointer ref(new ElementReference(command->GetId(), element, parms)); RegisterElement(ref); return ref; } void CommandService::RegisterElement(const SmartPointer& elementReference) { QList& parameterizedCommands = commandCallbacks[elementReference->GetCommandId()]; parameterizedCommands.push_back(elementReference); // If the active handler wants to update the callback, it can do // so now Command::Pointer command = GetCommand(elementReference->GetCommandId()); if (command->IsDefined()) { if (IElementUpdater::Pointer updater = command->GetHandler().Cast()) { updater->UpdateElement(elementReference->GetElement().GetPointer(), elementReference->GetParameters()); } } } void CommandService::UnregisterElement(const SmartPointer& elementReference) { if (commandCallbacks.contains(elementReference->GetCommandId())) { QList& parameterizedCommands = commandCallbacks[elementReference->GetCommandId()]; parameterizedCommands.removeAll(elementReference); if (parameterizedCommands.isEmpty()) { commandCallbacks.remove(elementReference->GetCommandId()); } } } -//CommandPersistence* CommandService::GetCommandPersistence() const -//{ -// return commandPersistence; -//} +const CommandPersistence* CommandService::GetCommandPersistence() const +{ + return &commandPersistence; +} } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandService.h index e689684bc9..dec8f990be 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandService.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandService.h @@ -1,143 +1,147 @@ /*=================================================================== 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 BERRYCOMMANDSERVICE_H #define BERRYCOMMANDSERVICE_H #include +#include "berryCommandPersistence.h" + namespace berry { class CommandManager; /** *

* Provides services related to the command architecture within the workbench. * This service can be used to access the set of commands and handlers. *

*/ class CommandService : public ICommandService { private: + friend class CommandPersistence; + /** * The preference key prefix for all handler state. */ static const QString PREFERENCE_KEY_PREFIX; /** * Creates a preference key for the given piece of state on the given * command. * * @param command * The command for which the preference key should be created; * must not be null. * @param stateId * The identifier of the state for which the preference key * should be created; must not be null. * @return A suitable preference key; never null. */ static const QString CreatePreferenceKey(const SmartPointer& command, const QString& stateId); /** * The command manager that supports this service. This value is never * null. */ CommandManager* commandManager; /** * The persistence class for this command service. */ - //CommandPersistence commandPersistence; + CommandPersistence commandPersistence; /** * This is a map of commandIds to a list containing currently registered * callbacks, in the form of IElementReference. */ QHash > > commandCallbacks; public: /** * Constructs a new instance of CommandService using a * command manager. Takes ownership of the provided CommandManager. * * @param commandManager * The command manager to use; must not be null. */ CommandService( CommandManager* commandManager); ~CommandService(); void AddExecutionListener(IExecutionListener* listener); void DefineUncategorizedCategory(const QString& name, const QString& description); SmartPointer Deserialize(const QString& serializedParameterizedCommand) const; void Dispose(); SmartPointer GetCategory(const QString& categoryId) const; SmartPointer GetCommand(const QString& commandId) const; QList > GetDefinedCategories() const; QStringList GetDefinedCategoryIds() const; QStringList GetDefinedCommandIds() const; QList > GetDefinedCommands() const; QStringList GetDefinedParameterTypeIds() const; QList > GetDefinedParameterTypes() const; QString GetHelpContextId(const SmartPointer& command) const; QString GetHelpContextId(const QString& commandId) const; SmartPointer GetParameterType(const QString& parameterTypeId) const; void ReadRegistry(); void RemoveExecutionListener(IExecutionListener* listener); void SetHelpContextId(const SmartPointer& handler, const QString& helpContextId); void RefreshElements(const QString& commandId, const QHash& filter); SmartPointer RegisterElementForCommand( const SmartPointer& command, const SmartPointer& element); void RegisterElement(const SmartPointer& elementReference); void UnregisterElement(const SmartPointer& elementReference); - //CommandPersistence* GetCommandPersistence() const; + const CommandPersistence* GetCommandPersistence() const; }; } #endif // BERRYCOMMANDSERVICE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandServiceFactory.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandServiceFactory.cpp new file mode 100644 index 0000000000..f2768da3e8 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandServiceFactory.cpp @@ -0,0 +1,66 @@ +/*=================================================================== + +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 "berryCommandServiceFactory.h" + +#include "berryICommandService.h" +#include "berryIServiceLocator.h" +#include "berryIServiceScopes.h" +#include "berryIWorkbenchLocationService.h" +#include "berryIWorkbenchWindow.h" +#include "berryIWorkbenchPartSite.h" + +#include "berrySlaveCommandService.h" + +namespace berry { + +Object* CommandServiceFactory::Create(const QString& serviceInterface, IServiceLocator* parentLocator, + IServiceLocator* locator) const +{ + if (serviceInterface != qobject_interface_iid()) + { + return NULL; + } + + IWorkbenchLocationService* wls = locator->GetService(); + IWorkbench* const wb = wls->GetWorkbench(); + if (wb == NULL) + { + return NULL; + } + + Object* parent = parentLocator->GetService(serviceInterface); + if (parent == NULL) + { + // we are registering the global services in the Workbench + return NULL; + } + IWorkbenchWindow* const window = wls->GetWorkbenchWindow(); + IWorkbenchPartSite* const site = wls->GetPartSite(); + + ICommandService* parentService = dynamic_cast(parent); + + if (site == NULL) + { + return new SlaveCommandService(parentService, + IServiceScopes::WINDOW_SCOPE, Object::Pointer(window)); + } + + return new SlaveCommandService(parentService, + IServiceScopes::PARTSITE_SCOPE, Object::Pointer(site)); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtDnDTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandServiceFactory.h old mode 100755 new mode 100644 similarity index 57% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtDnDTweaklet.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandServiceFactory.h index 57589ad2f8..067e97ee08 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtDnDTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandServiceFactory.h @@ -1,40 +1,38 @@ /*=================================================================== 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 BERRYCOMMANDSERVICEFACTORY_H +#define BERRYCOMMANDSERVICEFACTORY_H -#ifndef BERRYQTDNDTWEAKLET_H_ -#define BERRYQTDNDTWEAKLET_H_ - -#include +#include "berryIServiceFactory.h" namespace berry { -class QtDnDTweaklet : public QObject, public DnDTweaklet +class CommandServiceFactory : public QObject, public IServiceFactory { Q_OBJECT - Q_INTERFACES(berry::DnDTweaklet) + Q_INTERFACES(berry::IServiceFactory) public: - QtDnDTweaklet(); - QtDnDTweaklet(const QtDnDTweaklet& other); + Object* Create(const QString& serviceInterface, IServiceLocator* parentLocator, + IServiceLocator* locator) const; - ITracker* CreateTracker(); }; } -#endif /* BERRYQTDNDTWEAKLET_H_ */ +#endif // BERRYCOMMANDSERVICEFACTORY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandStateProxy.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandStateProxy.cpp new file mode 100644 index 0000000000..6e624811b0 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandStateProxy.cpp @@ -0,0 +1,233 @@ +/*=================================================================== + +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 "berryCommandStateProxy.h" + +#include "berryIConfigurationElement.h" +#include "berryStatus.h" +#include "berryPlatformUI.h" +#include "berryWorkbenchPlugin.h" +#include "berryIPreferences.h" + +namespace berry { + +CommandStateProxy::CommandStateProxy(const SmartPointer& configurationElement, + const QString& stateAttributeName, + const SmartPointer& preferenceStore, + const QString& preferenceKey) + : configurationElement(configurationElement) + , preferenceKey(preferenceKey) + , preferenceStore(preferenceStore) + , stateAttributeName(stateAttributeName) +{ + if (configurationElement.IsNull()) + { + throw ctkInvalidArgumentException( + "The configuration element backing a state proxy cannot be null"); + } + + if (stateAttributeName.isNull()) + { + throw ctkInvalidArgumentException( + "The attribute containing the state class must be known"); + } +} + +void CommandStateProxy::AddListener(IStateListener* listener) +{ + if (state.IsNull()) + { + this->AddListener(listener); + } + else + { + state->AddListener(listener); + } +} + +CommandStateProxy::~CommandStateProxy() +{ + if (state.IsNotNull()) + { + if (PersistentState::Pointer persistableState = state.Cast()) + { + if (persistableState->ShouldPersist() && preferenceStore.IsNotNull() + && !preferenceKey.isNull()) + { + persistableState->Save(preferenceStore, preferenceKey); + } + } + } +} + +Object::Pointer CommandStateProxy::GetValue() const +{ + if (const_cast(this)->LoadState()) + { + return state->GetValue(); + } + + return Object::Pointer(0); +} + +void CommandStateProxy::Load(const SmartPointer& /*store*/, + const QString& preferenceKey) +{ + if (LoadState()) + { + if (PersistentState::Pointer persistableState = state.Cast()) + { + if (persistableState->ShouldPersist() && preferenceStore.IsNotNull() + && !preferenceKey.isNull()) + { + persistableState->Load(preferenceStore, preferenceKey); + } + } + } +} + +void CommandStateProxy::RemoveListener(IStateListener* listener) +{ + if (state.IsNull()) + { + this->RemoveListener(listener); + } + else + { + state->RemoveListener(listener); + } +} + +void CommandStateProxy::Save(const SmartPointer& store, + const QString& preferenceKey) +{ + if (LoadState()) + { + if (PersistentState::Pointer persistableState = state.Cast()) + { + persistableState->Save(store, preferenceKey); + } + } +} + +void CommandStateProxy::SetId(const QString& id) +{ + PersistentState::SetId(id); + if (state.IsNotNull()) + { + state->SetId(id); + } +} + +void CommandStateProxy::SetShouldPersist(bool persisted) +{ + if (LoadState(persisted)) + { + if (PersistentState::Pointer persistableState = state.Cast()) + { + persistableState->SetShouldPersist(persisted); + } + } +} + +void CommandStateProxy::SetValue(const Object::Pointer& value) +{ + if (LoadState()) + { + state->SetValue(value); + } +} + +bool CommandStateProxy::ShouldPersist() +{ + if (LoadState()) + { + if (PersistentState::Pointer persistableState = state.Cast()) + { + return persistableState->ShouldPersist(); + } + } + + return false; +} + +QString CommandStateProxy::ToString() const +{ + if (state.IsNull()) + { + return configurationElement->GetAttribute(stateAttributeName); + } + + return state->ToString(); +} + +bool CommandStateProxy::LoadState(bool readPersistence) +{ + if (state.IsNull()) + { + try + { + state = configurationElement->CreateExecutableExtension(stateAttributeName); + + if (state.IsNull()) + { + const QString message = "The proxied state was the wrong class"; + const IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, + PlatformUI::PLUGIN_ID(), 0, message, BERRY_STATUS_LOC)); + WorkbenchPlugin::Log(message, status); + return false; + } + + state->SetId(GetId()); + configurationElement = 0; + + // Try to load the persistent state, if possible. + if (readPersistence) + { + if (PersistentState::Pointer persistentState = state.Cast()) + { + persistentState->SetShouldPersist(true); + } + } + Load(preferenceStore, preferenceKey); + + // Transfer the local listeners to the real state. + typedef IStateListener::Events::StateEvent::ListenerList ListenerListType; + const ListenerListType listenerArray = this->stateEvents.stateChanged.GetListeners(); + for (ListenerListType::const_iterator i = listenerArray.begin(); + i != listenerArray.end(); ++i) + { + state->AddListener(*(*i)); + this->RemoveListener(*(*i)); + } + + return true; + } + catch (const CoreException& e) + { + const QString message = "The proxied state for '" + configurationElement->GetAttribute(stateAttributeName) + + "' could not be loaded"; + IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, PlatformUI::PLUGIN_ID(), 0, + message, e, BERRY_STATUS_LOC)); + WorkbenchPlugin::Log(message, status); + return false; + } + } + + return true; +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandStateProxy.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandStateProxy.h new file mode 100644 index 0000000000..588c94ab03 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandStateProxy.h @@ -0,0 +1,151 @@ +/*=================================================================== + +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 BERRYCOMMANDSTATEPROXY_H +#define BERRYCOMMANDSTATEPROXY_H + +#include "berryPersistentState.h" + +namespace berry { + +struct IConfigurationElement; +struct IPreferences; + +/** + *

+ * A proxy for handler state that has been defined in XML. This delays the class + * loading until the state is really asked for information. Asking a proxy for + * anything (except disposing, and adding and removing listeners) will cause the + * proxy to instantiate the proxied handler. + *

+ *

+ * Loading the proxied state will automatically cause it to load its value from + * the preference store. Disposing of the state will cause it to persist its + * value. + *

+ *

+ * This class is not intended for use outside of the + * org.eclipse.ui.workbench plug-in. + *

+ */ +class CommandStateProxy : public PersistentState +{ + +public: + + berryObjectMacro(berry::CommandStateProxy) + +private: + + /** + * The configuration element from which the state can be created. This value + * will exist until the element is converted into a real class -- at which + * point this value will be set to null. + */ + SmartPointer configurationElement; + + /** + * The key in the preference store to locate the persisted state. + */ + const QString preferenceKey; + + /** + * The preference store containing the persisted state, if any. + */ + const SmartPointer preferenceStore; + + /** + * The real state. This value is null until the proxy is + * forced to load the real state. At this point, the configuration element + * is converted, nulled out, and this state gains a reference. + */ + SmartPointer state; + + /** + * The name of the configuration element attribute which contains the + * information necessary to instantiate the real state. + */ + const QString stateAttributeName; + +public: + + /** + * Constructs a new instance of HandlerState with all the + * information it needs to create the real state later. + * + * @param configurationElement + * The configuration element from which the real class can be + * loaded at run-time; must not be null. + * @param stateAttributeName + * The name of the attribute or element containing the state + * executable extension; must not be null. + * @param preferenceStore + * The preference store to which any persistent data should be + * written, and from which it should be loaded; may be + * null. + * @param preferenceKey + * The key at which the persistent data is located within the + * preference store. + */ + CommandStateProxy(const SmartPointer& configurationElement, + const QString& stateAttributeName, + const SmartPointer& preferenceStore, + const QString& preferenceKey); + + void AddListener(IStateListener* listener); + + ~CommandStateProxy(); + + Object::Pointer GetValue() const; + + void Load(const SmartPointer& store, + const QString& preferenceKey); + + using State::RemoveListener; + void RemoveListener(IStateListener* listener); + + void Save(const SmartPointer& store, + const QString& preferenceKey); + + void SetId(const QString& id); + + void SetShouldPersist(bool persisted); + + void SetValue(const Object::Pointer& value); + + bool ShouldPersist(); + + QString ToString() const; + +private: + + /** + * Loads the state, if possible. If the state is loaded, then the member + * variables are updated accordingly and the state is told to load its value + * from the preference store. + * + * @param readPersistence + * Whether the persistent state for this object should be read. + * @return true if the state is now non-null; + * false otherwise. + */ + bool LoadState(bool readPersistence = false); + +}; + +} + +#endif // BERRYCOMMANDSTATEPROXY_H diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCompositeExpression.cpp similarity index 97% copy from BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.cpp copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCompositeExpression.cpp index 9f6e8f93b7..b8a0266b37 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCompositeExpression.cpp @@ -1,82 +1,82 @@ /*=================================================================== 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 "berryCompositeExpression.h" #include "Poco/Hash.h" namespace berry { const uint CompositeExpression::HASH_INITIAL = Poco::Hash()("berry::CompositeExpression"); void CompositeExpression::Add(Expression::Pointer expression) { fExpressions.push_back(expression); } QList CompositeExpression::GetChildren() { return fExpressions; } EvaluationResult::ConstPointer CompositeExpression::EvaluateAnd(IEvaluationContext* scope) const { if (fExpressions.size() == 0) return EvaluationResult::TRUE_EVAL; EvaluationResult::ConstPointer result = EvaluationResult::TRUE_EVAL; foreach (Expression::Pointer iter, fExpressions) { result = result->And(iter->Evaluate(scope)); // keep iterating even if we have a not loaded found. It can be // that we find a FALSE_EVAL which will result in a better result. if (result == EvaluationResult::FALSE_EVAL) return result; } return result; } EvaluationResult::ConstPointer CompositeExpression::EvaluateOr(IEvaluationContext* scope) const { if (fExpressions.size() == 0) return EvaluationResult::TRUE_EVAL; EvaluationResult::ConstPointer result = EvaluationResult::FALSE_EVAL; foreach (Expression::Pointer iter, fExpressions) { result = result->Or(iter->Evaluate(scope)); if (result == EvaluationResult::TRUE_EVAL) return result; } return result; } -void CompositeExpression::CollectExpressionInfo(ExpressionInfo* info) +void CompositeExpression::CollectExpressionInfo(ExpressionInfo* info) const { if (fExpressions.size() == 0) return; foreach (Expression::Pointer iter, fExpressions) { iter->CollectExpressionInfo(info); } } -uint CompositeExpression::ComputeHashCode() +uint CompositeExpression::ComputeHashCode() const { return HASH_INITIAL * HASH_FACTOR + this->HashCode(fExpressions); } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCompositeExpression.h similarity index 89% copy from BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCompositeExpression.h index b1e89cdb2e..da9c604a0f 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCompositeExpression.h @@ -1,62 +1,62 @@ /*=================================================================== 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 BERRYCOMPOSITEEXPRESSION_H_ #define BERRYCOMPOSITEEXPRESSION_H_ #include "berryExpression.h" #include "berryExpressionInfo.h" #include "berryEvaluationResult.h" #include "berryIEvaluationContext.h" namespace berry { class CompositeExpression : public Expression { public: - berryObjectMacro(CompositeExpression); + berryObjectMacro(CompositeExpression) private: /** * The seed for the hash code for all composite expressions. */ static const uint HASH_INITIAL; protected: QList fExpressions; virtual EvaluationResult::ConstPointer EvaluateAnd(IEvaluationContext* scope) const; virtual EvaluationResult::ConstPointer EvaluateOr(IEvaluationContext* scope) const; - virtual uint ComputeHashCode(); + virtual uint ComputeHashCode() const; public: virtual void Add(Expression::Pointer expression); virtual QList GetChildren(); - virtual void CollectExpressionInfo(ExpressionInfo* info); + virtual void CollectExpressionInfo(ExpressionInfo* info) const; }; } // namespace berry #endif /*BERRYCOMPOSITEEXPRESSION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryContributionRoot.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryContributionRoot.cpp index ca0af6e9f1..5b1745a59e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryContributionRoot.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryContributionRoot.cpp @@ -1,96 +1,98 @@ /*=================================================================== 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 "berryContributionRoot.h" #include #include #include #include "berryAlwaysEnabledExpression.h" #include "berryInternalMenuService.h" namespace berry { ContributionRoot::ContributionRoot(InternalMenuService* menuService, const QSet > &restriction, ContributionManager* mgr, AbstractContributionFactory* factory) - : menuService(menuService), restriction(restriction), mgr(mgr), - factory(factory) + : menuService(menuService) + , mgr(mgr) + , factory(factory) + , restriction(restriction) { } void ContributionRoot::AddContributionItem(const SmartPointer& item, const SmartPointer& visibleWhen) { if (item.IsNull()) throw std::invalid_argument("item must not be null"); topLevelItems.append(item); Expression::Pointer visibleWhenTmp = visibleWhen; if (visibleWhenTmp.IsNull()) visibleWhenTmp = AlwaysEnabledExpression::INSTANCE; menuService->RegisterVisibleWhen(item, visibleWhenTmp, restriction, CreateIdentifierId(item)); itemsToExpressions.append(item); } QList > ContributionRoot::GetItems() const { return topLevelItems; } void ContributionRoot::Release() { foreach (IContributionItem::Pointer item, itemsToExpressions) { menuService->UnregisterVisibleWhen(item, restriction); //item.dispose(); } } void ContributionRoot::RegisterVisibilityForChild(const SmartPointer& item, const SmartPointer& visibleWhen) { if (item.IsNull()) throw std::invalid_argument("item must not be null"); Expression::Pointer visibleWhenTmp = visibleWhen; if (visibleWhenTmp.IsNull()) visibleWhenTmp = AlwaysEnabledExpression::INSTANCE; menuService->RegisterVisibleWhen(item, visibleWhenTmp, restriction, CreateIdentifierId(item)); itemsToExpressions.append(item); } ContributionManager* ContributionRoot::GetManager() const { return mgr; } QString ContributionRoot::CreateIdentifierId(const SmartPointer& item) { QString namespaze = factory->GetNamespace(); // create the activity identifier ID. If this factory doesn't have a namespace // it will be null. QString identifierID = (!namespaze.isEmpty()) ? namespaze + '/' + item->GetId() : QString(); return identifierID; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryContributionRoot.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryContributionRoot.h index 2f710b7061..7e09de161a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryContributionRoot.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryContributionRoot.h @@ -1,94 +1,94 @@ /*=================================================================== 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 BERRYCONTRIBUTIONROOT_H #define BERRYCONTRIBUTIONROOT_H #include #include namespace berry { struct IEvaluationReference; +struct InternalMenuService; -class InternalMenuService; class ContributionManager; class AbstractContributionFactory; /** * Default implementation. */ class ContributionRoot : public IContributionRoot { private: QList > topLevelItems; QList > itemsToExpressions; InternalMenuService* menuService; ContributionManager* mgr; AbstractContributionFactory* factory; public: QSet > restriction; berryObjectMacro(berry::ContributionRoot) ContributionRoot(InternalMenuService* menuService, const QSet >& restriction, ContributionManager* mgr, AbstractContributionFactory* factory); /* * @see IContributionRoot#AddContributionItem(IContributionItem, Expression) */ void AddContributionItem(const SmartPointer& item, const SmartPointer& visibleWhen); QList > GetItems() const; /** * Unregister all visible when expressions from the menu service. */ void Release(); /* * @see IContributionRoot#RegisterVisibilityForChild(IContributionItem, Expression) */ void RegisterVisibilityForChild(const SmartPointer& item, const SmartPointer& visibleWhen); /** * @return Returns the mgr. */ ContributionManager* GetManager() const; private: /** * Create the activity identifier for this contribution item. * * @param item the item * @return the identifier */ QString CreateIdentifierId(const SmartPointer& item); }; } #endif // BERRYCONTRIBUTIONROOT_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.cpp index dea85307d6..f22f2e62d5 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.cpp @@ -1,116 +1,123 @@ /*=================================================================== 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 "berryDefaultSaveable.h" #include "berryIWorkbenchPart.h" #include "berryIWorkbenchPage.h" #include "berryUIException.h" #include "berryImageDescriptor.h" namespace berry { DefaultSaveable::DefaultSaveable(IWorkbenchPart::Pointer _part) : part(_part) { } void DefaultSaveable::DoSave(/*IProgressMonitor monitor*/) { IWorkbenchPart::Pointer _part(part); if (_part.Cast () != 0) { _part.Cast ()->DoSave(/*monitor*/); } } QString DefaultSaveable::GetName() const { return part.Lock()->GetPartName(); } ImageDescriptor::Pointer DefaultSaveable::GetImageDescriptor() const { //TODO DefaultSaveable GetImageDescriptor // Image image = part.getTitleImage(); // if (image == null) // { // return null; // } // return ImageDescriptor.createFromImage(image); return ImageDescriptor::Pointer(0); } QString DefaultSaveable::GetToolTipText() const { return part.Lock()->GetTitleToolTip(); } bool DefaultSaveable::IsDirty() const { IWorkbenchPart::Pointer _part(part); if (_part.Cast () != 0) { return _part.Cast ()->IsDirty(); } return false; } -bool DefaultSaveable::operator<(const Saveable* obj) const +uint DefaultSaveable::HashCode() const +{ + return part.Lock()->HashCode(); +} + +bool DefaultSaveable::operator<(const Object* obj) const { if (this == obj) return false; if (obj == 0) return true; const DefaultSaveable* other = dynamic_cast (obj); + if (other == NULL) return true; + if (part.Expired()) { return !other->part.Expired(); } else return part < other->part; } bool DefaultSaveable::Show(IWorkbenchPage::Pointer page) { IWorkbenchPart::Pointer _part(part); IWorkbenchPartReference::Pointer reference = page->GetReference(_part); if (reference != 0) { page->Activate(_part); return true; } if (_part.Cast () != 0) { IViewPart::Pointer viewPart = _part.Cast (); try { page->ShowView(viewPart->GetViewSite()->GetId(), viewPart->GetViewSite()->GetSecondaryId(), IWorkbenchPage::VIEW_ACTIVATE); } catch (const PartInitException& /*e*/) { return false; } return true; } return false; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.h index b1e5f4e6c4..5b603210a0 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultSaveable.h @@ -1,97 +1,102 @@ /*=================================================================== 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 BERRYDEFAULTSAVEABLE_H_ #define BERRYDEFAULTSAVEABLE_H_ #include "berrySaveable.h" namespace berry { /** * A default {@link Saveable} implementation that wrappers a regular * workbench part (one that does not itself adapt to Saveable). * * @since 3.2 */ class DefaultSaveable : public Saveable { private: WeakPointer part; public: /** * Creates a new DefaultSaveable. * * @param part * the part represented by this model */ DefaultSaveable(SmartPointer part); /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#doSave(org.blueberry.core.runtime.IProgressMonitor) */ void DoSave(/*IProgressMonitor monitor*/); /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#getName() */ QString GetName() const; /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#getImageDescriptor() */ SmartPointer GetImageDescriptor() const; /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#getToolTipText() */ QString GetToolTipText() const; /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#isDirty() */ bool IsDirty() const; + /* (non-Javadoc) + * @see Object#HashCode() + */ + uint HashCode() const; + /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ - bool operator<(const Saveable* obj) const; + bool operator<(const Object* obj) const; /* (non-Javadoc) * @see org.blueberry.ui.Saveable#show(org.blueberry.ui.IWorkbenchPage) */ bool Show(SmartPointer page); }; } #endif /* BERRYDEFAULTSAVEABLE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultStackPresentationSite.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultStackPresentationSite.h index a5a9313780..bb32abdfac 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultStackPresentationSite.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDefaultStackPresentationSite.h @@ -1,99 +1,101 @@ /*=================================================================== 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 BERRYDEFAULTSTACKPRESENTATIONSITE_H_ #define BERRYDEFAULTSTACKPRESENTATIONSITE_H_ #include "presentations/berryIStackPresentationSite.h" #include "presentations/berryStackPresentation.h" namespace berry { class DefaultStackPresentationSite: public IStackPresentationSite { private: StackPresentation::Pointer presentation; int state; int activeState; public: - berryObjectMacro(DefaultStackPresentationSite); + berryObjectMacro(DefaultStackPresentationSite) DefaultStackPresentationSite(); void SetPresentation(StackPresentation::Pointer newPresentation); StackPresentation::Pointer GetPresentation(); int GetState(); void SetActive(int activeState); int GetActive(); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IStackPresentationSite#selectPart(org.blueberry.ui.internal.skins.IPresentablePart) */ void SelectPart(IPresentablePart::Pointer toSelect); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#setState(int) */ void SetState(int newState); void SetPresentationState(int newState); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentablePart#isClosable() */ bool IsCloseable(IPresentablePart::Pointer part); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#dragStart(org.blueberry.ui.internal.skins.IPresentablePart, boolean) */ void DragStart(IPresentablePart::Pointer beingDragged, Point& initialPosition, bool keyboard); + using IStackPresentationSite::Close; + /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#close(org.blueberry.ui.internal.skins.IPresentablePart) */ void Close(IPresentablePart::Pointer toClose); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#dragStart(boolean) */ void DragStart(Point& initialPosition, bool keyboard); /* (non-Javadoc) * @see org.blueberry.ui.presentations.IStackPresentationSite#supportsState(int) */ bool SupportsState(int state); // void AddSystemActions(IMenuManager menuManager) { // // } }; } #endif /* BERRYDEFAULTSTACKPRESENTATIONSITE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedPlaceHolder.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedPlaceHolder.cpp index f7243b0eee..3afc3ee7dd 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedPlaceHolder.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedPlaceHolder.cpp @@ -1,144 +1,146 @@ /*=================================================================== 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 "berryDetachedPlaceHolder.h" #include "berryILayoutContainer.h" #include "berryPartPlaceholder.h" #include "berryWorkbenchConstants.h" namespace berry { DetachedPlaceHolder::DetachedPlaceHolder(const QString& id, const Rectangle& b) : PartPlaceholder(id), bounds(b) { } void DetachedPlaceHolder::Add(LayoutPart::Pointer newPart) { if (newPart.Cast () == 0) { return; } children.push_back(newPart); } bool DetachedPlaceHolder::AllowsBorder() { return false; } bool DetachedPlaceHolder::AllowsAdd(LayoutPart::Pointer toAdd) { return PartPlaceholder::AllowsAdd(toAdd); } bool DetachedPlaceHolder::AllowsAutoFocus() { return PartPlaceholder::AllowsAutoFocus(); } Rectangle DetachedPlaceHolder::GetBounds() { return bounds; } QList DetachedPlaceHolder::GetChildren() { return children; } void DetachedPlaceHolder::Remove(LayoutPart::Pointer part) { children.removeAll(part); } void DetachedPlaceHolder::Replace(LayoutPart::Pointer oldPart, LayoutPart::Pointer newPart) { this->Remove(oldPart); this->Add(newPart); } void DetachedPlaceHolder::RestoreState(IMemento::Pointer memento) { // Read the bounds. int x = 0; memento->GetInteger(WorkbenchConstants::TAG_X, x); int y = 0; memento->GetInteger(WorkbenchConstants::TAG_Y, y); int width = 0; memento->GetInteger(WorkbenchConstants::TAG_WIDTH, width); int height = 0; memento->GetInteger(WorkbenchConstants::TAG_HEIGHT, height); bounds = Rectangle(x, y, width, height); // Restore the placeholders. QList childrenMem(memento ->GetChildren(WorkbenchConstants::TAG_VIEW)); - for (std::size_t i = 0; i < childrenMem.size(); i++) { + for (int i = 0; i < childrenMem.size(); i++) + { QString id; childrenMem[i]->GetString(WorkbenchConstants::TAG_ID, id); PartPlaceholder::Pointer holder(new PartPlaceholder(id)); holder->SetContainer(ILayoutContainer::Pointer(this)); children.push_back(holder); } } void DetachedPlaceHolder::SaveState(IMemento::Pointer memento) { // Save the bounds. memento->PutInteger(WorkbenchConstants::TAG_X, bounds.x); memento->PutInteger(WorkbenchConstants::TAG_Y, bounds.y); memento->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width); memento->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height); // Save the views. for (QList::iterator i = children.begin(); - i != children.end(); ++i) { + i != children.end(); ++i) + { IMemento::Pointer childMem = memento ->CreateChild(WorkbenchConstants::TAG_VIEW); childMem->PutString(WorkbenchConstants::TAG_ID, (*i)->GetID()); } } void DetachedPlaceHolder::FindSashes(LayoutPart::Pointer /*part*/, PartPane::Sashes& sashes) { ILayoutContainer::Pointer container = this->GetContainer(); if (container != 0) { container->FindSashes(LayoutPart::Pointer(this), sashes); } } ILayoutContainer::ChildrenType DetachedPlaceHolder::GetChildren() const { return children; } void DetachedPlaceHolder::ResizeChild(LayoutPart::Pointer childThatChanged) { PartPlaceholder::ResizeChild(childThatChanged); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.cpp index cf1cff0b4c..58084a7f33 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.cpp @@ -1,544 +1,540 @@ /*=================================================================== 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 "tweaklets/berryGuiWidgetsTweaklet.h" #include "berryDetachedWindow.h" #include "berryIWorkbenchPartConstants.h" #include "berryISaveablePart.h" #include "berryWorkbenchWindow.h" #include "berryWorkbenchConstants.h" #include "berryEditorManager.h" #include "berryDragUtil.h" namespace berry { DetachedWindow::ShellListener::ShellListener(DetachedWindow* wnd) : window(wnd) { } -void DetachedWindow::ShellListener::ShellClosed(ShellEvent::Pointer e) +void DetachedWindow::ShellListener::ShellClosed(const ShellEvent::Pointer& e) { // hold on to a reference of the DetachedWindow instance // (otherwise, wnd->HandleClose() woulde delete the DetachedWindow // instance too early, trying to write to members afterwards) DetachedWindow::Pointer wnd(window); // only continue to close if the handleClose // wasn't canceled e->doit = wnd->HandleClose(); } DetachedWindow::ShellControlListener::ShellControlListener(DetachedWindow* wnd) : window(wnd) { } GuiTk::IControlListener::Events::Types DetachedWindow::ShellControlListener::GetEventTypes() const { return Events::RESIZED; } void DetachedWindow::ShellControlListener::ControlResized( GuiTk::ControlEvent::Pointer e) { window->folder->SetBounds( Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(e->item)); } DetachedWindow::DetachedWindow(WorkbenchPage* workbenchPage) + : folder(new PartStack(workbenchPage, false)) + , page(workbenchPage) + , hideViewsOnClose(true) + , shellListener(new ShellListener(this)) + , resizeListener(new ShellControlListener(this)) { - shellListener = new ShellListener(this); - resizeListener = new ShellControlListener(this); - - this->page = workbenchPage; - hideViewsOnClose = true; - - folder = new PartStack(page, false); } -void DetachedWindow::PropertyChange(Object::Pointer /*source*/, int propId) +void DetachedWindow::PropertyChange(const Object::Pointer& /*source*/, int propId) { if (propId == IWorkbenchPartConstants::PROP_TITLE) { this->UpdateTitle(); } else if (propId == PartStack::PROP_SELECTION) { this->ActivePartChanged(this->GetPartReference(folder->GetSelection())); } } Shell::Pointer DetachedWindow::GetShell() { return windowShell; } void DetachedWindow::Create() { folder->AddListener(this); windowShell = page->GetWorkbenchWindow().Cast () ->GetDetachedWindowPool()->AllocateShell( - shellListener); + shellListener.data()); windowShell->SetData(Object::Pointer(this)); - windowShell->SetText(""); //$NON-NLS-1$ + windowShell->SetText(""); - DragUtil::AddDragTarget(windowShell->GetControl(), - IDragOverListener::Pointer(this)); + DragUtil::AddDragTarget(windowShell->GetControl(), this); hideViewsOnClose = true; if (bounds.IsEmpty()) { Rectangle windowRect = page->GetWorkbenchWindow()->GetShell()->GetBounds(); Point center(windowRect.x + windowRect.width / 2, windowRect.y - windowRect.height / 2); bounds = Rectangle(center.x - 150, center.y + 100, 300, 200); } // Force the rect into the current display Rectangle dispBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetAvailableScreenSize(); if (bounds.width > dispBounds.width) bounds.width = dispBounds.width; if (bounds.height > dispBounds.height) bounds.height = dispBounds.height; if (bounds.x + bounds.width > dispBounds.width) bounds.x = dispBounds.width - bounds.width; if (bounds.y + bounds.height > dispBounds.height) bounds.y = dispBounds.height - bounds.height; this->GetShell()->SetBounds(bounds); this->ConfigureShell(windowShell); this->CreateContents(windowShell->GetControl()); //windowShell->Layout(true); //folder->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(windowShell->GetControl())); } void DetachedWindow::Add(LayoutPart::Pointer part) { Shell::Pointer shell = this->GetShell(); if (shell != 0) { part->Reparent(shell->GetControl()); } folder->Add(part); this->UpdateMinimumSize(); } bool DetachedWindow::BelongsToWorkbenchPage( IWorkbenchPage::Pointer workbenchPage) { return (workbenchPage == this->page); } bool DetachedWindow::Close() { hideViewsOnClose = false; Shell::Pointer shell = this->GetShell(); if (shell != 0) { shell->Close(); } return true; } IDropTarget::Pointer DetachedWindow::Drag(void* /*currentControl*/, - Object::Pointer draggedObject, const Point& position, const Rectangle& /*dragRectangle*/) + const Object::Pointer& draggedObject, const Point& position, const Rectangle& /*dragRectangle*/) { if (draggedObject.Cast () == 0) { return IDropTarget::Pointer(0); } PartPane::Pointer sourcePart = draggedObject.Cast (); if (sourcePart->GetWorkbenchWindow() != page->GetWorkbenchWindow()) { return IDropTarget::Pointer(0); } // Only handle the event if the source part is acceptable to the particular PartStack IDropTarget::Pointer target; if (folder->AllowsDrop(sourcePart)) { target = folder->GetDropTarget(draggedObject, position); if (target == 0) { Rectangle displayBounds = DragUtil::GetDisplayBounds(folder->GetControl()); if (displayBounds.Contains(position)) { StackDropResult::Pointer stackDropResult(new StackDropResult( displayBounds, Object::Pointer(0))); target = folder->CreateDropTarget(sourcePart, stackDropResult); } else { return IDropTarget::Pointer(0); } } } return target; } ILayoutContainer::ChildrenType DetachedWindow::GetChildren() const { return folder->GetChildren(); } WorkbenchPage::Pointer DetachedWindow::GetWorkbenchPage() { return WorkbenchPage::Pointer(this->page); } void DetachedWindow::RestoreState(IMemento::Pointer memento) { // Read the bounds. int x = 0; memento->GetInteger(WorkbenchConstants::TAG_X, x); int y = 0; memento->GetInteger(WorkbenchConstants::TAG_Y, y); int width = 0; memento->GetInteger(WorkbenchConstants::TAG_WIDTH, width); int height = 0; memento->GetInteger(WorkbenchConstants::TAG_HEIGHT, height); // memento->GetInteger(WorkbenchConstants::TAG_FLOAT); // Set the bounds. bounds = Rectangle(x, y, width, height); if (GetShell()) { GetShell()->SetBounds(bounds); } // Create the folder. IMemento::Pointer childMem = memento->GetChild(WorkbenchConstants::TAG_FOLDER); if (childMem) { folder->RestoreState(childMem); } } void DetachedWindow::SaveState(IMemento::Pointer memento) { if (GetShell()) { bounds = GetShell()->GetBounds(); } // Save the bounds. memento->PutInteger(WorkbenchConstants::TAG_X, bounds.x); memento->PutInteger(WorkbenchConstants::TAG_Y, bounds.y); memento->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width); memento->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height); // Save the views. IMemento::Pointer childMem = memento->CreateChild( WorkbenchConstants::TAG_FOLDER); folder->SaveState(childMem); } void* DetachedWindow::GetControl() { return folder->GetControl(); } int DetachedWindow::Open() { if (this->GetShell() == 0) { this->Create(); } Rectangle bounds = this->GetShell()->GetBounds(); if (!(bounds == this->GetShell()->GetBounds())) { this->GetShell()->SetBounds(bounds); } this->GetShell()->SetVisible(true); folder->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(this->GetShell()->GetControl())); return 0; } void DetachedWindow::ActivePartChanged( IWorkbenchPartReference::Pointer partReference) { if (activePart == partReference) { return; } if (activePart != 0) { activePart->RemovePropertyListener(this); } activePart = partReference; if (partReference != 0) { partReference->AddPropertyListener(this); } this->UpdateTitle(); } void DetachedWindow::ConfigureShell(Shell::Pointer shell) { this->UpdateTitle(); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener( shell->GetControl(), resizeListener); //shell.addListener(SWT.Activate, activationListener); //shell.addListener(SWT.Deactivate, activationListener); //TODO DetachedWindow key bindings // // Register this detached view as a window (for key bindings). // IContextService contextService = (IContextService) getWorkbenchPage() // .getWorkbenchWindow().getWorkbench().getService(IContextService.class); // contextService.registerShell(shell, IContextService.TYPE_WINDOW); // // page.getWorkbenchWindow().getWorkbench().getHelpSystem().setHelp(shell, // IWorkbenchHelpContextIds.DETACHED_WINDOW); } void* DetachedWindow::CreateContents(void* parent) { // Create the tab folder. folder->CreateControl(parent); // Reparent each view in the tab folder. QList detachedChildren; this->CollectViewPanes(detachedChildren, this->GetChildren()); for (QList::iterator itr = detachedChildren.begin(); itr != detachedChildren.end(); ++itr) { PartPane::Pointer part = *itr; part->Reparent(parent); } //TODO DetachedWindow listen to folder events (update size?) // if (folder->GetPresentation() // instanceof TabbedStackPresentation) // { // TabbedStackPresentation stack = (TabbedStackPresentation) folder.getPresentation(); // AbstractTabFolder tabFolder = stack.getTabFolder(); // tabFolder.addListener(new TabFolderListener() // { // public void handleEvent(TabFolderEvent e) // { // switch (e.type) // { // case TabFolderEvent.EVENT_CLOSE: // { // updateMinimumSize(); // break; // } // case TabFolderEvent.EVENT_PREFERRED_SIZE: // { // updateMinimumSize(); // break; // } // } // } // }); // } // Return tab folder control. return folder->GetControl(); } void DetachedWindow::UpdateTitle() { if (activePart != 0) { // Uncomment to set the shell title to match the title of the active part // String text = activePart.getTitle(); // // if (!text.equals(s.getText())) { // s.setText(text); // } } } void DetachedWindow::UpdateMinimumSize() { // // We can only do this for 'Tabbed' stacked presentations. // if (folder.getPresentation().Cast() != 0) // { // TabbedStackPresentation stack = (TabbedStackPresentation) folder.getPresentation(); // // if (stack->GetPartList().size() == 1) // { // // Get the minimum space required for the part // int width = stack->ComputePreferredSize(true, Constants::INF, Constants::INF, 0); // int height = stack->ComputePreferredSize(false, Constants::INF, Constants::INF, 0); // // // Take the current shell 'trim' into account // int shellHeight = windowShell->GetBounds().height - windowShell->GetClientArea().height; // int shellWidth = windowShell->GetBounds().width - windowShell->GetClientArea().width; // // windowShell->SetMinimumSize(width + shellWidth, height + shellHeight); // } // } } IWorkbenchPartReference::Pointer DetachedWindow::GetPartReference( LayoutPart::Pointer pane) { if (pane == 0 || pane.Cast () == 0) { return IWorkbenchPartReference::Pointer(0); } return pane.Cast ()->GetPartReference(); } bool DetachedWindow::HandleClose() { if (hideViewsOnClose) { QList views; this->CollectViewPanes(views, this->GetChildren()); // Save any dirty views if (!this->HandleSaves(views)) { return false; // User canceled the save } // OK, go on with the closing for (QList::iterator itr = views.begin(); itr != views.end(); ++itr) { PartPane::Pointer child = *itr; // Only close if closable... if (child->IsCloseable()) { page->HideView(child->GetPartReference().Cast ()); // Was the close cancelled? if (child->GetContainer() != 0) return false; } else { page->AttachView(child->GetPartReference().Cast ()); } } } if (folder != 0) { folder->Dispose(); } if (windowShell != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener( windowShell->GetControl(), resizeListener); // windowShell.removeListener(SWT.Activate, activationListener); // windowShell.removeListener(SWT.Deactivate, activationListener); - DragUtil::RemoveDragTarget(windowShell->GetControl(), - IDragOverListener::Pointer(this)); + DragUtil::RemoveDragTarget(windowShell->GetControl(), this); bounds = windowShell->GetBounds(); //TODO DetachedWindow unregister key bindings // // Unregister this detached view as a window (for key bindings). // final IContextService contextService = (IContextService) getWorkbenchPage().getWorkbenchWindow().getWorkbench().getService(IContextService.class); // contextService.unregisterShell(windowShell); windowShell->SetData(Object::Pointer(0)); windowShell = 0; } return true; } bool DetachedWindow::HandleSaves(QList views) { QList dirtyViews; for (QList::iterator iterator = views.begin(); iterator != views.end(); ++iterator) { PartPane::Pointer pane = *iterator; IViewReference::Pointer ref = pane->GetPartReference().Cast (); IViewPart::Pointer part = ref->GetView(false); if (part.Cast () != 0) { ISaveablePart::Pointer saveable = part.Cast (); if (saveable->IsDirty() && saveable->IsSaveOnCloseNeeded()) { dirtyViews.push_back(part); } } } // If there are any prompt to save -before- any closing happens // FIXME: This code will result in a double prompt if the user // decides not to save a particular view at this stage they'll // get a second one from the 'hideView' call... if (dirtyViews.size() > 0) { IWorkbenchWindow::Pointer window = page->GetWorkbenchWindow(); bool success = EditorManager::SaveAll(dirtyViews, true, true, false, window); if (!success) { return false; // the user canceled. } } return true; } void DetachedWindow::CollectViewPanes(QList& result, const QList& parts) { for (QList::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (part.Cast () != 0) { result.push_back(part.Cast ()); } } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.h index 15574e42aa..938c7e4357 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDetachedWindow.h @@ -1,198 +1,197 @@ /*=================================================================== 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 BERRYDETACHEDWINDOW_H_ #define BERRYDETACHEDWINDOW_H_ #include "berryPartStack.h" #include "berryWorkbenchPage.h" #include "berryLayoutPart.h" #include "berryIDragOverListener.h" #include "berryIShellListener.h" #include "guitk/berryGuiTkIControlListener.h" #include "berryRectangle.h" #include "berryShell.h" namespace berry { /** * TODO: Drag from detached to fast view bar back to detached causes NPE - * - * @since 3.1 */ -class DetachedWindow: public IPropertyChangeListener, - public IDragOverListener +class DetachedWindow: public Object, private IPropertyChangeListener, + private IDragOverListener { public: berryObjectMacro(DetachedWindow) private: PartStack::Pointer folder; WorkbenchPage* page; Rectangle bounds; Shell::Pointer windowShell; bool hideViewsOnClose; struct ShellListener: public IShellListener { ShellListener(DetachedWindow* wnd); - void ShellClosed(ShellEvent::Pointer e); + void ShellClosed(const ShellEvent::Pointer& e); private: DetachedWindow* window; }; - IShellListener::Pointer shellListener; + QScopedPointer shellListener; struct ShellControlListener: public GuiTk::IControlListener { ShellControlListener(DetachedWindow* wnd); Events::Types GetEventTypes() const; void ControlResized(GuiTk::ControlEvent::Pointer e); private: DetachedWindow* window; }; GuiTk::IControlListener::Pointer resizeListener; // Listener activationListener = new Listener() { // public void handleEvent(Event event) { // switch (event.type) { // case SWT.Activate: // page.window.liftRestrictions(); // break; // case SWT.Deactivate: // page.window.imposeRestrictions(); // break; // } // } // }; IWorkbenchPartReference::Pointer activePart; public: /** * Create a new FloatingWindow. */ DetachedWindow(WorkbenchPage* workbenchPage); + using IPropertyChangeListener::PropertyChange; - void PropertyChange(Object::Pointer source, int propId); + void PropertyChange(const Object::Pointer& source, int propId); Shell::Pointer GetShell(); void Create(); /** * Adds a visual part to this window. * Supports reparenting. */ void Add(LayoutPart::Pointer part); bool BelongsToWorkbenchPage(IWorkbenchPage::Pointer workbenchPage); bool Close(); /* * @see org.blueberry.ui.internal.IDragOverListener#Drag(void*, Object::Pointer, const Point&, const Rectangle& ) */ IDropTarget::Pointer Drag(void* currentControl, - Object::Pointer draggedObject, const Point& position, + const Object::Pointer& draggedObject, const Point& position, const Rectangle& dragRectangle); ILayoutContainer::ChildrenType GetChildren() const; WorkbenchPage::Pointer GetWorkbenchPage(); /** * @see IPersistablePart */ void RestoreState(IMemento::Pointer memento); /** * @see IPersistablePart */ void SaveState(IMemento::Pointer memento); void* GetControl(); /** * Opens the detached window. */ int Open(); protected: void ActivePartChanged(IWorkbenchPartReference::Pointer partReference); /** * This method will be called to initialize the given Shell's layout */ void ConfigureShell(Shell::Pointer shell); /** * Override this method to create the widget tree that is used as the window's contents. */ void* CreateContents(void* parent); private: void UpdateTitle(); /** * Ensure that the shell's minimum size is equal to the minimum size * of the first part added to the shell. */ void UpdateMinimumSize(); static IWorkbenchPartReference::Pointer GetPartReference( LayoutPart::Pointer pane); /** * Closes this window and disposes its shell. */ bool HandleClose(); /** * Prompts for and handles the saving of dirty, saveable views * @param views The list of ViewPanes * @return true unless the user cancels the save(s) */ bool HandleSaves(QList views); /** * Answer a list of the view panes. */ void CollectViewPanes(QList& result, const QList& parts); }; } #endif /* BERRYDETACHEDWINDOW_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.cpp index ef9407b1fe..6960e0ec7b 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.cpp @@ -1,363 +1,362 @@ /*=================================================================== 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 "tweaklets/berryGuiWidgetsTweaklet.h" #include "berryDragUtil.h" #include "berryGeometry.h" #include "tweaklets/berryDnDTweaklet.h" #include "tweaklets/berryITracker.h" namespace berry { const QString DragUtil::DROP_TARGET_ID = "org.blueberry.ui.internal.dropTarget"; TestDropLocation::Pointer DragUtil::forcedDropTarget(0); -QList DragUtil::defaultTargets = QList< - IDragOverListener::Pointer>(); +QList DragUtil::defaultTargets = QList(); DragUtil::TrackerMoveListener::TrackerMoveListener(Object::Pointer draggedItem, const Rectangle& sourceBounds, const Point& initialLocation, bool allowSnapping) : allowSnapping(allowSnapping), draggedItem(draggedItem), sourceBounds( sourceBounds), initialLocation(initialLocation) { } GuiTk::IControlListener::Events::Types DragUtil::TrackerMoveListener::GetEventTypes() const { return Events::MOVED; } void DragUtil::TrackerMoveListener::ControlMoved( GuiTk::ControlEvent::Pointer event) { // Get the curslor location as a point Point location(event->x, event->y); // Select a drop target; use the global one by default IDropTarget::Pointer target; void* targetControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorControl(); // Get the ITracker which fired the event ITracker* tracker = static_cast (event->item); // Get the drop target for this location target = DragUtil::GetDropTarget(targetControl, draggedItem, location, tracker->GetRectangle()); // Set up the tracker feedback based on the target Rectangle snapTarget; if (target != 0) { snapTarget = target->GetSnapRectangle(); tracker->SetCursor(target->GetCursor()); } else { tracker->SetCursor(DnDTweaklet::CURSOR_INVALID); } // If snapping then reset the tracker's rectangle based on the current drop target if (allowSnapping) { if (snapTarget.width == 0 || snapTarget.height == 0) { snapTarget = Rectangle(sourceBounds.x + location.x - initialLocation.x, sourceBounds.y + location.y - initialLocation.y, sourceBounds.width, sourceBounds.height); } // Try to prevent flicker: don't change the rectangles if they're already in // the right location Rectangle currentRectangle = tracker->GetRectangle(); if (!(currentRectangle == snapTarget)) { tracker->SetRectangle(snapTarget); } } } DragUtil::TargetListType::Pointer DragUtil::GetTargetList(void* control) { Object::Pointer data = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetData( control, DROP_TARGET_ID); TargetListType::Pointer list = data.Cast (); return list; } -IDropTarget::Pointer DragUtil::GetDropTarget(const QList< - IDragOverListener::Pointer>& toSearch, void* mostSpecificControl, - Object::Pointer draggedObject, const Point& position, - const Rectangle& dragRectangle) +IDropTarget::Pointer DragUtil::GetDropTarget(const QList& toSearch, + void* mostSpecificControl, + Object::Pointer draggedObject, + const Point& position, + const Rectangle& dragRectangle) { - for (QList::const_iterator iter = + for (QList::const_iterator iter = toSearch.begin(); iter != toSearch.end(); ++iter) { - IDragOverListener::Pointer next = *iter; + IDragOverListener* next = *iter; IDropTarget::Pointer dropTarget = next->Drag(mostSpecificControl, draggedObject, position, dragRectangle); if (dropTarget != 0) { return dropTarget; } } return IDropTarget::Pointer(0); } -void DragUtil::AddDragTarget(void* control, IDragOverListener::Pointer target) +void DragUtil::AddDragTarget(void* control, IDragOverListener* target) { if (control == 0) { defaultTargets.push_back(target); } else { TargetListType::Pointer targetList = GetTargetList(control); if (targetList == 0) { targetList = new TargetListType(); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetData(control, DROP_TARGET_ID, targetList); } targetList->push_back(target); } } -void DragUtil::RemoveDragTarget(void* control, - IDragOverListener::Pointer target) +void DragUtil::RemoveDragTarget(void* control, IDragOverListener* target) { if (control == 0) { defaultTargets.removeAll(target); } else { TargetListType::Pointer targetList = GetTargetList(control); if (targetList != 0) { targetList->removeAll(target); if (targetList->empty()) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetData(control, DROP_TARGET_ID, Object::Pointer(0)); } } } } Rectangle DragUtil::GetDisplayBounds(void* boundsControl) { void* parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent( boundsControl); if (parent == 0) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(boundsControl); } Rectangle rect = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds( boundsControl); return Geometry::ToDisplay(parent, rect); } bool DragUtil::PerformDrag(Object::Pointer draggedItem, const Rectangle& sourceBounds, const Point& initialLocation, bool allowSnapping) { IDropTarget::Pointer target = DragToTarget(draggedItem, sourceBounds, initialLocation, allowSnapping); if (target == 0) { return false; } target->Drop(); target->DragFinished(true); return true; } void DragUtil::ForceDropLocation(TestDropLocation::Pointer forcedLocation) { forcedDropTarget = forcedLocation; } IDropTarget::Pointer DragUtil::DragToTarget(Object::Pointer draggedItem, const Rectangle& sourceBounds, const Point& initialLocation, bool allowSnapping) { //final Display display = Display.getCurrent(); // Testing...immediately 'drop' onto the test target if (forcedDropTarget != 0) { Point location = forcedDropTarget->GetLocation(); void* currentControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->FindControl( forcedDropTarget->GetShells(), location); return GetDropTarget(currentControl, draggedItem, location, sourceBounds); } // Create a tracker. This is just an XOR rect on the screen. // As it moves we notify the drag listeners. ITracker* tracker = Tweaklets::Get(DnDTweaklet::KEY)->CreateTracker(); //tracker.setStippled(true); GuiTk::IControlListener::Pointer trackerListener(new TrackerMoveListener( draggedItem, sourceBounds, initialLocation, allowSnapping)); tracker->AddControlListener(trackerListener); // Setup...when the drag starts we might already be over a valid target, check this... // If there is a 'global' target then skip the check IDropTarget::Pointer target; void* startControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorControl(); if (startControl != 0 && allowSnapping) { target = GetDropTarget(startControl, draggedItem, initialLocation, sourceBounds); } // Set up an initial tracker rectangle Rectangle startRect = sourceBounds; if (target != 0) { Rectangle rect = target->GetSnapRectangle(); if (rect.width != 0 && rect.height != 0) { startRect = rect; } tracker->SetCursor(target->GetCursor()); } if (startRect.width != 0 && startRect.height != 0) { tracker->SetRectangle(startRect); } // Tracking Loop...tracking is preformed on the 'SWT.Move' listener registered // against the tracker. // // HACK: // // Some control needs to capture the mouse during the drag or other // // controls will interfere with the cursor // Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); // if (shell != null) // { // shell.setCapture(true); // } // Run tracker until mouse up occurs or escape key pressed. bool trackingOk = tracker->Open(); // // HACK: // // Release the mouse now // if (shell != null) // { // shell.setCapture(false); // } // Done tracking... // Get the current drop target IDropTarget::Pointer dropTarget; Point finalLocation = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorLocation(); void* targetControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorControl(); dropTarget = GetDropTarget(targetControl, draggedItem, finalLocation, tracker->GetRectangle()); // Cleanup... delete tracker; // if we're going to perform a 'drop' then delay the issuing of the 'finished' // callback until after it's done... if (trackingOk) { return dropTarget; } else if (dropTarget != 0) { // If the target can handle a 'finished' notification then send one dropTarget->DragFinished(false); } return IDropTarget::Pointer(0); } IDropTarget::Pointer DragUtil::GetDropTarget(void* toSearch, Object::Pointer draggedObject, const Point& position, const Rectangle& dragRectangle) { // Search for a listener by walking the control's parent hierarchy for (void* current = toSearch; current != 0; current = Tweaklets::Get( GuiWidgetsTweaklet::KEY)->GetParent(current)) { TargetListType::Pointer targetList = GetTargetList(current); - QList targets; + QList targets; if (targetList != 0) targets = *targetList; IDropTarget::Pointer dropTarget = GetDropTarget(targets, toSearch, draggedObject, position, dragRectangle); if (dropTarget != 0) { return dropTarget; } // // Don't look to parent shells for drop targets // if (current instanceof Shell) { // break; // } } // No controls could handle this event -- check for default targets return GetDropTarget(defaultTargets, toSearch, draggedObject, position, dragRectangle); } //Point DragUtil::GetEventLoc(GuiTk::ControlEvent::Pointer event) //{ // Control ctrl = (Control) event.widget; // return ctrl.toDisplay(new Point(event.x, event.y)); //} } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.h index 51b4e96424..02ae03ceed 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDragUtil.h @@ -1,214 +1,214 @@ /*=================================================================== 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 BERRYDRAGUTIL_H_ #define BERRYDRAGUTIL_H_ #include #include "berryRectangle.h" #include "guitk/berryGuiTkIControlListener.h" #include "berryTestDropLocation.h" #include "berryIDragOverListener.h" #include "berryIDropTarget.h" #include #include namespace berry { /** * Provides the methods for attaching drag-and-drop listeners to SWT controls. */ -class BERRY_UI_QT DragUtil { +class BERRY_UI_QT DragUtil +{ public: - typedef ObjectList TargetListType; + typedef ObjectList TargetListType; private: - static const QString DROP_TARGET_ID; //$NON-NLS-1$ + static const QString DROP_TARGET_ID; /** * The location where all drags will end. If this is non-null, then * all user input is ignored in drag/drop. If null, we use user input * to determine where objects should be dropped. */ static TestDropLocation::Pointer forcedDropTarget; /** * List of IDragOverListener */ - static QList defaultTargets; + static QList defaultTargets; /** * Return the list of 'IDragOverListener' elements associated with * the given control. If there's a 'global' listener then always * return it. * * @param control * @return */ static TargetListType::Pointer GetTargetList(void* control); /** * Given a list of IDragOverListeners and a description of what is being dragged, it returns * a IDropTarget for the current drop. * * @param toSearch * @param mostSpecificControl * @param draggedObject * @param position * @param dragRectangle * @return */ - static IDropTarget::Pointer GetDropTarget(const QList& toSearch, + static IDropTarget::Pointer GetDropTarget(const QList& toSearch, void* mostSpecificControl, Object::Pointer draggedObject, const Point &position, const Rectangle& dragRectangle); struct TrackerMoveListener : public GuiTk::IControlListener { TrackerMoveListener(Object::Pointer draggedItem, const Rectangle& sourceBounds, const Point& initialLocation, bool allowSnapping); Events::Types GetEventTypes() const; void ControlMoved(GuiTk::ControlEvent::Pointer event); private: bool allowSnapping; Object::Pointer draggedItem; Rectangle sourceBounds; Point initialLocation; }; public: /** * Sets the drop target for the given control. It is possible to add one or more * targets for a "null" control. This becomes a default target that is used if no * other targets are found (for example, when dragging objects off the application * window). * * @param control the control that should be treated as a drag target, or null * to indicate the default target * @param target the drag target to handle the given control */ - static void AddDragTarget(void* control, IDragOverListener::Pointer target); + static void AddDragTarget(void* control, IDragOverListener* target); /** * Removes a drop target from the given control. * * @param control * @param target */ - static void RemoveDragTarget(void* control, - IDragOverListener::Pointer target); + static void RemoveDragTarget(void* control, IDragOverListener* target); /** * Shorthand method. Returns the bounding rectangle for the given control, in * display coordinates. * * @param draggedItem * @param boundsControl * @return */ static Rectangle GetDisplayBounds(void* boundsControl); static bool PerformDrag(Object::Pointer draggedItem, const Rectangle& sourceBounds, const Point& initialLocation, bool allowSnapping); // /** // * Drags the given item to the given location (in display coordinates). This // * method is intended for use by test suites. // * // * @param draggedItem object being dragged // * @param finalLocation location being dragged to // * @return true iff the drop was accepted // */ // static bool DragTo(Display display, Object draggedItem, // Point finalLocation, Rectangle dragRectangle) { // Control currentControl = SwtUtil.findControl(display, finalLocation); // // IDropTarget target = getDropTarget(currentControl, draggedItem, // finalLocation, dragRectangle); // // if (target == null) { // return false; // } // // target.drop(); // // return true; // } /** * Forces all drags to end at the given position (display coordinates). Intended * for use by test suites. If this method is called, then all subsequent calls * to performDrag will terminate immediately and behave as though the object were * dragged to the given location. Calling this method with null cancels this * behavior and causes performDrag to behave normally. * * @param forcedLocation location where objects will be dropped (or null to * cause drag/drop to behave normally). */ static void ForceDropLocation(TestDropLocation::Pointer forcedLocation); /** * Drags the given item, given an initial bounding rectangle in display coordinates. * Due to a quirk in the Tracker class, changing the tracking rectangle when using the * keyboard will also cause the mouse cursor to move. Since "snapping" causes the tracking * rectangle to change based on the position of the mouse cursor, it is impossible to do * drag-and-drop with the keyboard when snapping is enabled. * * @param draggedItem object being dragged * @param sourceBounds initial bounding rectangle for the dragged item * @param initialLocation initial position of the mouse cursor * @param allowSnapping true iff the rectangle should snap to the drop location. This must * be false if the user might be doing drag-and-drop using the keyboard. * * @return */ static IDropTarget::Pointer DragToTarget(Object::Pointer draggedItem, const Rectangle& sourceBounds, const Point& initialLocation, bool allowSnapping); /** * Returns the drag target for the given control or null if none. * * @param toSearch * @param e * @return */ static IDropTarget::Pointer GetDropTarget(void* toSearch, Object::Pointer draggedObject, const Point& position, const Rectangle& dragRectangle); /** * Returns the location of the given event, in display coordinates * @return */ //static Point GetEventLoc(GuiTk::ControlEvent::Pointer event); }; } #endif /* BERRYDRAGUTIL_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorManager.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorManager.cpp index a382aad45e..24a051bc3e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorManager.cpp @@ -1,1295 +1,1295 @@ /*=================================================================== 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 "berryEditorManager.h" #include "berryIWorkbenchPart.h" #include "berryIWorkbenchWindow.h" #include "berryIEditorRegistry.h" #include "berryUIException.h" #include "berryWorkbenchWindow.h" #include "berryWorkbenchPage.h" #include "berryEditorSite.h" #include "berryEditorReference.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include "berryNullEditorInput.h" #include "berryEditorAreaHelper.h" #include "berryPartStack.h" #include namespace berry { const QString EditorManager::PIN_EDITOR_KEY = "PIN_EDITOR"; const QString EditorManager::RESOURCES_TO_SAVE_MESSAGE = "Select resources to save:"; const QString EditorManager::SAVE_RESOURCES_TITLE = "Save Resources"; EditorManager::EditorManager(WorkbenchWindow::Pointer wind, WorkbenchPage::Pointer workbenchPage, EditorAreaHelper* pres) : editorPresentation(pres), window(wind.GetPointer()), page(workbenchPage.GetPointer()) { poco_check_ptr(editorPresentation); poco_assert(window != 0); poco_assert(page != 0); //page.getExtensionTracker().registerHandler(this, null); } void EditorManager::CheckDeleteEditorResources() { // // get the current number of editors // IEditorReference[] editors = page.getEditorReferences(); // // If there are no editors // if (editors.length == 0) // { // if (editorPropChangeListnener != null) // { // // remove property change listener for editors // IPreferenceStore prefStore = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // prefStore // .removePropertyChangeListener(editorPropChangeListnener); // editorPropChangeListnener = null; // } // if (pinEditorHandlerActivation != null) // { // // remove pin editor keyboard shortcut handler // final IHandlerService handlerService = (IHandlerService) window.getWorkbench().getService(IHandlerService.class); // handlerService.deactivateHandler(pinEditorHandlerActivation); // pinEditorHandlerActivation = null; // } // } } //void EditorManager::CheckCreateEditorPropListener() //{ // if (editorPropChangeListnener == null) // { // // Add a property change listener for closing editors automatically // // preference // // Add or remove the pin icon accordingly // editorPropChangeListnener = new IPropertyChangeListener() // { // public void propertyChange(PropertyChangeEvent event) // { // if (event.getProperty().equals( // IPreferenceConstants.REUSE_EDITORS_BOOLEAN)) // { // IEditorReference[] editors = getEditors(); // for (int i = 0; i < editors.length; i++) // { // ((EditorReference) editors[i]).pinStatusUpdated(); // } // } // } // }; // WorkbenchPlugin.getDefault().getPreferenceStore() // .addPropertyChangeListener(editorPropChangeListnener); // } //} //void EditorManager::CheckCreatePinEditorShortcutKeyHandler() //{ // if (pinEditorHandlerActivation == null) // { // final Shell shell = window.getShell(); // final IHandler pinEditorHandler = new AbstractHandler() // { // public final Object execute(final ExecutionEvent event) // { // // check if the "Close editors automatically" preference is // // set // IPreferenceStore store = WorkbenchPlugin.getDefault().getPreferenceStore(); // if (store // .getBoolean(IPreferenceConstants.REUSE_EDITORS_BOOLEAN) // || ((TabBehaviour)Tweaklets.get(TabBehaviour.KEY)).alwaysShowPinAction()) // { // // IWorkbenchPartReference ref = editorPresentation // .getVisibleEditor(); // if (ref instanceof WorkbenchPartReference) // { // WorkbenchPartReference concreteRef = (WorkbenchPartReference) ref; // // concreteRef.setPinned(concreteRef.isPinned()); // } // } // return null; // } // }; // // // Assign the handler for the pin editor keyboard shortcut. // final IHandlerService handlerService = (IHandlerService) window.getWorkbench().getService(IHandlerService.class); // pinEditorHandlerActivation = handlerService.activateHandler( // "org.blueberry.ui.window.pinEditor", pinEditorHandler, //$NON-NLS-1$ // new ActiveShellExpression(shell)); // } //} QList EditorManager::CollectDirtyEditors() { QList result; QList editors(page->GetEditorReferences()); for (QList::iterator i = editors.begin(); i != editors.end(); ++i) { IEditorPart::Pointer part = (*i)->GetPart(false).Cast(); if (part.IsNotNull() && part->IsDirty()) { result.push_back(part); } } return result; } bool EditorManager::ContainsEditor(IEditorReference::Pointer ref) { QList editors(page->GetEditorReferences()); return std::find(editors.begin(), editors.end(), ref) != editors.end(); } //EditorActionBars* EditorManager::CreateEditorActionBars( // EditorDescriptor::Pointer desc, IEditorSite::Pointer site) //{ // // Get the editor type. // String type = desc.getId(); // // // If an action bar already exists for this editor type return it. // EditorActionBars actionBars = (EditorActionBars) actionCache.get(type); // if (actionBars != null) // { // actionBars.addRef(); // return actionBars; // } // // // Create a new action bar set. // actionBars = new EditorActionBars(page, site.getWorkbenchWindow(), type); // actionBars.addRef(); // actionCache.put(type, actionBars); // // // Read base contributor. // IEditorActionBarContributor contr = desc.createActionBarContributor(); // if (contr != null) // { // actionBars.setEditorContributor(contr); // contr.init(actionBars, page); // } // // // Read action extensions. // EditorActionBuilder builder = new EditorActionBuilder(); // contr = builder.readActionExtensions(desc); // if (contr != null) // { // actionBars.setExtensionContributor(contr); // contr.init(actionBars, page); // } // // // Return action bars. // return actionBars; //} //EditorActionBars* EditorManager::CreateEmptyEditorActionBars( // IEditorSite::Pointer site) //{ // // Get the editor type. // String type = String.valueOf(System.currentTimeMillis()); // // // Create a new action bar set. // // Note: It is an empty set. // EditorActionBars actionBars = new EditorActionBars(page, site.getWorkbenchWindow(), type); // actionBars.addRef(); // actionCache.put(type, actionBars); // // // Return action bars. // return actionBars; //} //void EditorManager::DisposeEditorActionBars(EditorActionBars* actionBars) //{ // actionBars.removeRef(); // if (actionBars.getRef() <= 0) // { // String type = actionBars.getEditorType(); // actionCache.remove(type); // // refresh the cool bar manager before disposing of a cool item // ICoolBarManager2 coolBar = (ICoolBarManager2) window.getCoolBarManager2(); // if (coolBar != null) // { // coolBar.refresh(); // } // actionBars.dispose(); // } //} IEditorPart::Pointer EditorManager::FindEditor(IEditorInput::Pointer input) { return this->FindEditor("", input, IWorkbenchPage::MATCH_INPUT); } IEditorPart::Pointer EditorManager::FindEditor(const QString& editorId, IEditorInput::Pointer input, int matchFlags) { QList refs(this->FindEditors(input, editorId, matchFlags)); if (refs.size() == 0) { return IEditorPart::Pointer(); } return refs[0]->GetEditor(true); } QList EditorManager::FindEditors( IEditorInput::Pointer input, const QString& editorId, int matchFlags) { if (matchFlags == IWorkbenchPage::MATCH_NONE) { return QList(); } QList result; QList othersList(page->GetEditorReferences()); if (!othersList.empty()) { IEditorReference::Pointer active = page->GetActiveEditorReference(); if (active.IsNotNull()) { othersList.removeAll(active); QList activeList; activeList.push_back(active); this->FindEditors(activeList, input, editorId, matchFlags, result); } this->FindEditors(othersList, input, editorId, matchFlags, result); } return result; } void EditorManager::FindEditors( QList& editorList, IEditorInput::Pointer input, const QString& editorId, int matchFlags, QList& result) { if (matchFlags == IWorkbenchPage::MATCH_NONE) { return; } // Phase 0: Remove editors whose ids don't match (if matching by id) if (((matchFlags & IWorkbenchPage::MATCH_ID) != 0) && !editorId.isEmpty()) { for (QList::iterator i = editorList.begin(); i != editorList.end();) { if (editorId != (*i)->GetId()) { i = editorList.erase(i); continue; } ++i; } } // If not matching on editor input, just return the remaining editors. // In practice, this case is never used. if ((matchFlags & IWorkbenchPage::MATCH_INPUT) == 0) { result.append(editorList); return; } // Phase 1: check editors that have their own matching strategy for (QList::iterator i = editorList.begin(); i != editorList.end();) { EditorReference::Pointer editor = i->Cast(); IEditorDescriptor::Pointer desc = editor->GetDescriptor(); if (desc.IsNotNull()) { IEditorMatchingStrategy::Pointer matchingStrategy = desc ->GetEditorMatchingStrategy(); if (matchingStrategy.IsNotNull()) { i = editorList.erase(i); // We're handling this one here, so remove it // from the list. if (matchingStrategy->Matches(editor, input)) { result.push_back(editor); } continue; } } ++i; } // Phase 2: check materialized editors (without their own matching // strategy) for (QList::iterator i = editorList.begin(); i != editorList.end();) { EditorReference::Pointer editor = i->Cast(); IEditorPart::Pointer part = editor->GetPart(false).Cast(); if (part.IsNotNull()) { i = editorList.erase(i); // We're handling this one here, so remove it from // the list. if (part->GetEditorInput().IsNotNull() && part->GetEditorInput() == input) { result.push_back(editor); } } else ++i; } // Phase 3: check unmaterialized editors for input equality, // delaying plug-in activation further by only restoring the editor // input // if the editor reference's factory id and name match. // QString name = input->GetName(); // IPersistableElement persistable = input.getPersistable(); // if (name == null || persistable == null) // { // return; // } // String id = persistable.getFactoryId(); // if (id == null) // { // return; // } // for (Iterator i = editorList.iterator(); i.hasNext();) // { // EditorReference editor = (EditorReference) i.next(); // if (name.equals(editor.getName()) && id.equals(editor.getFactoryId())) // { // IEditorInput restoredInput; // try // { // restoredInput = editor.getEditorInput(); // if (Util.equals(restoredInput, input)) // { // result.add(editor); // } // } // catch (PartInitException e1) // { // WorkbenchPlugin.log(e1); // } // } // } } std::size_t EditorManager::GetEditorCount() { return page->GetEditorReferences().size(); } IEditorRegistry* EditorManager::GetEditorRegistry() { return WorkbenchPlugin::GetDefault()->GetEditorRegistry(); } QList EditorManager::GetDirtyEditors() { return this->CollectDirtyEditors(); } QList EditorManager::GetEditors() { return page->GetEditorReferences(); } IEditorPart::Pointer EditorManager::GetVisibleEditor() { IEditorReference::Pointer ref = editorPresentation->GetVisibleEditor(); if (ref.IsNull()) { return IEditorPart::Pointer(0); } return ref->GetPart(true).Cast(); } bool EditorManager::IsSaveAllNeeded() { QList editors(page->GetEditorReferences()); for (QList::iterator i = editors.begin(); i != editors.end(); ++i) { if ((*i)->IsDirty()) { return true; } } return false; } IEditorReference::Pointer EditorManager::FindReusableEditor( EditorDescriptor::Pointer /*desc*/) { //return ((TabBehaviour)Tweaklets.get(TabBehaviour.KEY)).findReusableEditor(page); return IEditorReference::Pointer(0); } IEditorReference::Pointer EditorManager::OpenEditor( const QString& editorId, IEditorInput::Pointer input, bool /*setVisible*/, IMemento::Pointer editorState) { if (input.IsNull()) { throw Poco::InvalidArgumentException(); } IEditorRegistry* reg = this->GetEditorRegistry(); EditorDescriptor::Pointer desc = reg->FindEditor(editorId).Cast(); if (desc.IsNull()) { throw PartInitException("Unable to open editor, unknown editor id: " + editorId); } return this->OpenEditorFromDescriptor(desc, input, editorState); } IEditorReference::Pointer EditorManager::OpenEditorFromDescriptor( EditorDescriptor::Pointer desc, IEditorInput::Pointer input, IMemento::Pointer editorState) { IEditorReference::Pointer result; if (desc->IsInternal()) { result = this->ReuseInternalEditor(desc, input); if (result.IsNull()) { result = new EditorReference(this, input, desc, editorState); } } // else if (desc->GetId() == IEditorRegistry::SYSTEM_INPLACE_EDITOR_ID) // { // if (ComponentSupport.inPlaceEditorSupported()) // { // result = new EditorReference(this, input, desc); // } // } // else if (desc->GetId() == IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID) // { // IPathEditorInput pathInput = getPathEditorInput(input); // if (pathInput != null) // { // result = openSystemExternalEditor(pathInput.getPath()); // } // else // { // throw new PartInitException( // WorkbenchMessages.EditorManager_systemEditorError); // } // } // else if (desc->IsOpenExternal()) // { // result = openExternalEditor(desc, input); // } else { // this should never happen throw PartInitException("Invalid editor descriptor for id:" + desc->GetId()); } if (result.IsNotNull()) { this->CreateEditorTab(result.Cast(), ""); //$NON-NLS-1$ } // Workbench wb = (Workbench) window.getWorkbench(); // wb.getEditorHistory().add(input, desc); return result; } //IEditorReference::Pointer EditorManager::OpenExternalEditor( // EditorDescriptor::Pointer desc, IEditorInput::Pointer input) //{ // final CoreException ex[] = new CoreException[1]; // // final IPathEditorInput pathInput = getPathEditorInput(input); // if (pathInput != null && pathInput.getPath() != null) // { // BusyIndicator.showWhile(getDisplay(), new Runnable() // { // public void run() // { // try // { // if (desc.getLauncher() != null) // { // // open using launcher // Object launcher = WorkbenchPlugin.createExtension( // desc.getConfigurationElement(), "launcher"); //$NON-NLS-1$ // ((IEditorLauncher) launcher).open(pathInput // .getPath()); // } // else // { // // open using command // ExternalEditor oEditor = new ExternalEditor( // pathInput.getPath(), desc); // oEditor.open(); // } // } // catch (CoreException e) // { // ex[0] = e; // } // } // } // ); // } // else // { // throw new PartInitException(NLS.bind( // WorkbenchMessages.EditorManager_errorOpeningExternalEditor, // desc.getFileName(), desc.getId())); // } // // if (ex[0] != null) // { // throw new PartInitException(NLS.bind( // WorkbenchMessages.EditorManager_errorOpeningExternalEditor, // desc.getFileName(), desc.getId()), ex[0]); // } // // // we do not have an editor part for external editors // return null; //} void EditorManager::CreateEditorTab(EditorReference::Pointer ref, const QString& workbookId) { editorPresentation->AddEditor(ref, workbookId); } EditorSite::Pointer EditorManager::CreateSite(IEditorReference::Pointer ref, IEditorPart::Pointer part, EditorDescriptor::Pointer desc, IEditorInput::Pointer input) const { EditorSite::Pointer site(new EditorSite(ref, part, page, desc)); if (desc.IsNotNull()) { //site.setActionBars(createEditorActionBars(desc, site)); } else { //site.setActionBars(createEmptyEditorActionBars(site)); } const QString label = part->GetPartName(); // debugging only try { part->Init(site, input); // Sanity-check the site if (!(part->GetSite() == site) || !(part->GetEditorSite() == site)) { throw PartInitException("Editor initialization failed: " + desc->GetId() + ". Site is incorrect."); } } catch (PartInitException e) { throw e; } catch (std::exception e) { throw PartInitException(QString("An exception was thrown during initialization: ") + e.what()); } return site; } IEditorReference::Pointer EditorManager::ReuseInternalEditor( EditorDescriptor::Pointer /*desc*/, IEditorInput::Pointer /*input*/) { // poco_assert(desc.IsNotNull()); // "descriptor must not be null"); //$NON-NLS-1$ // poco_assert(input.IsNotNull()); // "input must not be null"); //$NON-NLS-1$ // // IEditorReference::Pointer reusableEditorRef = this->FindReusableEditor(desc); // if (reusableEditorRef.IsNotNull()) // { // return this->ReuseInternalEditor(page, this, editorPresentation, desc, input, // reusableEditorRef); // } return IEditorReference::Pointer(0); } IEditorPart::Pointer EditorManager::CreatePart(EditorDescriptor::Pointer desc) const { // try // { IEditorPart::Pointer result = desc->CreateEditor(); // IConfigurationElement element = desc.getConfigurationElement(); // if (element != null) // { // page.getExtensionTracker().registerObject( // element.getDeclaringExtension(), result, // IExtensionTracker.REF_WEAK); // } return result; // } // catch (CoreException e) // { // throw PartInitException(StatusUtil.newStatus( // desc.getPluginID(), // WorkbenchMessages.EditorManager_instantiationError, e)); // } } //IEditorReference::Pointer EditorManager::OpenSystemExternalEditor( // Poco::Path location) //{ // if (location == null) // { // throw new IllegalArgumentException(); // } // // final boolean result[] = // { false}; // BusyIndicator.showWhile(getDisplay(), new Runnable() // { // public void run() // { // if (location != null) // { // result[0] = Program.launch(location.toOSString()); // } // } // } // ); // // if (!result[0]) // { // throw new PartInitException(NLS.bind( // WorkbenchMessages.EditorManager_unableToOpenExternalEditor, // location)); // } // // // We do not have an editor part for external editors // return null; // } // ImageDescriptor EditorManager::FindImage(EditorDescriptor::Pointer desc, // Poco::Path path) // { // if (desc == null) // { // // @issue what should be the default image? // return ImageDescriptor.getMissingImageDescriptor(); // } // // if (desc.isOpenExternal() && path != null) // { // return PlatformUI.getWorkbench().getEditorRegistry() // .getImageDescriptor(path.toOSString()); // } // // return desc.getImageDescriptor(); // } bool EditorManager::RestoreState(IMemento::Pointer memento) { // Restore the editor area workbooks layout/relationship // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.EditorManager_problemsRestoringEditors, null); bool result = true; QString activeWorkbookID; QList visibleEditors; QList activeEditor; IMemento::Pointer areaMem = memento->GetChild(WorkbenchConstants::TAG_AREA); if (areaMem) { //result.add(editorPresentation.restoreState(areaMem)); editorPresentation->RestoreState(areaMem); areaMem->GetString(WorkbenchConstants::TAG_ACTIVE_WORKBOOK, activeWorkbookID); } // Loop through the editors. QList editorMems(memento->GetChildren(WorkbenchConstants::TAG_EDITOR)); - for (std::size_t x = 0; x < editorMems.size(); x++) + for (int x = 0; x < editorMems.size(); x++) { // for dynamic UI - call restoreEditorState to replace code which is // commented out RestoreEditorState(editorMems[x], visibleEditors, activeEditor); //, result); } // restore the presentation if (areaMem) { //result.add(editorPresentation.restorePresentationState(areaMem)); result &= editorPresentation->RestorePresentationState(areaMem); } try { // StartupThreading.runWithThrowable(new StartupRunnable() // { // // public void runWithException() throws Throwable // { // Update each workbook with its visible editor. - for (std::size_t i = 0; i < visibleEditors.size(); i++) + for (int i = 0; i < visibleEditors.size(); i++) { SetVisibleEditor(visibleEditors[i], false); } // Update the active workbook if (!activeWorkbookID.isEmpty()) { editorPresentation->SetActiveEditorWorkbookFromID(activeWorkbookID); } if (!activeEditor.empty() && activeEditor[0]) { IWorkbenchPart::Pointer editor = activeEditor[0]->GetPart(true); if (editor) { page->Activate(editor); } } // }}); } catch (...) { // The exception is already logged. // result // .add(new Status( // IStatus.ERR, // PlatformUI.PLUGIN_ID, // 0, // WorkbenchMessages.EditorManager_exceptionRestoringEditor, // t)); result &= false; } return result; } bool EditorManager::SaveAll(bool confirm, bool closing, bool addNonPartSources) { // Get the list of dirty editors and views. If it is // empty just return. QList parts(page->GetDirtyParts()); if (parts.empty()) { return true; } QList wbParts; for (QList::const_iterator i = parts.begin(); i != parts.end(); ++i) { if (IWorkbenchPart::Pointer part = i->Cast()) { wbParts.push_back(part); } } // If confirmation is required .. return this->SaveAll(wbParts, confirm, closing, addNonPartSources, IWorkbenchWindow::Pointer(window)); } bool EditorManager::SaveAll( const QList& /*dirtyParts*/, bool /*confirm*/, bool /*closing*/, bool /*addNonPartSources*/, SmartPointer /*window*/) { // // clone the input list // dirtyParts = new ArrayList(dirtyParts); // List modelsToSave; // if (confirm) { // boolean saveable2Processed = false; // // Process all parts that implement ISaveablePart2. // // These parts are removed from the list after saving // // them. We then need to restore the workbench to // // its previous state, for now this is just last // // active perspective. // // Note that the given parts may come from multiple // // windows, pages and perspectives. // ListIterator listIterator = dirtyParts.listIterator(); // // WorkbenchPage currentPage = null; // Perspective currentPageOriginalPerspective = null; // while (listIterator.hasNext()) { // IWorkbenchPart part = (IWorkbenchPart) listIterator.next(); // if (part instanceof ISaveablePart2) { // WorkbenchPage page = (WorkbenchPage) part.getSite() // .getPage(); // if (!Util.equals(currentPage, page)) { // if (currentPage != null // && currentPageOriginalPerspective != null) { // if (!currentPageOriginalPerspective // .equals(currentPage.getActivePerspective())) { // currentPage // .setPerspective(currentPageOriginalPerspective // .getDesc()); // } // } // currentPage = page; // currentPageOriginalPerspective = page // .getActivePerspective(); // } // if (confirm) { // if (part instanceof IViewPart) { // Perspective perspective = page // .getFirstPerspectiveWithView((IViewPart) part); // if (perspective != null) { // page.setPerspective(perspective.getDesc()); // } // } // // show the window containing the page? // IWorkbenchWindow partsWindow = page // .getWorkbenchWindow(); // if (partsWindow != partsWindow.getWorkbench() // .getActiveWorkbenchWindow()) { // Shell shell = partsWindow.getShell(); // if (shell.getMinimized()) { // shell.setMinimized(false); // } // shell.setActive(); // } // page.bringToTop(part); // } // // try to save the part // int choice = SaveableHelper.savePart((ISaveablePart2) part, // page.getWorkbenchWindow(), confirm); // if (choice == ISaveablePart2.CANCEL) { // // If the user cancels, don't restore the previous // // workbench state, as that will // // be an unexpected switch from the current state. // return false; // } else if (choice != ISaveablePart2.DEFAULT) { // saveable2Processed = true; // listIterator.remove(); // } // } // } // // // try to restore the workbench to its previous state // if (currentPage != null && currentPageOriginalPerspective != null) { // if (!currentPageOriginalPerspective.equals(currentPage // .getActivePerspective())) { // currentPage.setPerspective(currentPageOriginalPerspective // .getDesc()); // } // } // // // if processing a ISaveablePart2 caused other parts to be // // saved, remove them from the list presented to the user. // if (saveable2Processed) { // listIterator = dirtyParts.listIterator(); // while (listIterator.hasNext()) { // ISaveablePart part = (ISaveablePart) listIterator.next(); // if (!part.isDirty()) { // listIterator.remove(); // } // } // } // // modelsToSave = convertToSaveables(dirtyParts, closing, addNonPartSources); // // // If nothing to save, return. // if (modelsToSave.isEmpty()) { // return true; // } // boolean canceled = SaveableHelper.waitForBackgroundSaveJobs(modelsToSave); // if (canceled) { // return false; // } // // Use a simpler dialog if there's only one // if (modelsToSave.size() == 1) { // Saveable model = (Saveable) modelsToSave.get(0); // String message = NLS.bind(WorkbenchMessages.EditorManager_saveChangesQuestion, model.getName()); // // Show a dialog. // String[] buttons = new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }; // MessageDialog d = new MessageDialog( // shellProvider.getShell(), WorkbenchMessages.Save_Resource, // null, message, MessageDialog.QUESTION, buttons, 0); // // int choice = SaveableHelper.testGetAutomatedResponse(); // if (SaveableHelper.testGetAutomatedResponse() == SaveableHelper.USER_RESPONSE) { // choice = d.open(); // } // // // Branch on the user choice. // // The choice id is based on the order of button labels // // above. // switch (choice) { // case ISaveablePart2.YES: // yes // break; // case ISaveablePart2.NO: // no // return true; // default: // case ISaveablePart2.CANCEL: // cancel // return false; // } // } // else { // ListSelectionDialog dlg = new ListSelectionDialog( // shellProvider.getShell(), modelsToSave, // new ArrayContentProvider(), // new WorkbenchPartLabelProvider(), RESOURCES_TO_SAVE_MESSAGE); // dlg.setInitialSelections(modelsToSave.toArray()); // dlg.setTitle(SAVE_RESOURCES_TITLE); // // // this "if" statement aids in testing. // if (SaveableHelper.testGetAutomatedResponse()==SaveableHelper.USER_RESPONSE) { // int result = dlg.open(); // //Just return false to prevent the operation continuing // if (result == IDialogConstants.CANCEL_ID) { // return false; // } // // modelsToSave = Arrays.asList(dlg.getResult()); // } // } // } // else { // modelsToSave = convertToSaveables(dirtyParts, closing, addNonPartSources); // } // // // If the editor list is empty return. // if (modelsToSave.isEmpty()) { // return true; // } // // // Create save block. // final List finalModels = modelsToSave; // IRunnableWithProgress progressOp = new IRunnableWithProgress() { // public void run(IProgressMonitor monitor) { // IProgressMonitor monitorWrap = new EventLoopProgressMonitor( // monitor); // monitorWrap.beginTask("", finalModels.size()); //$NON-NLS-1$ // for (Iterator i = finalModels.iterator(); i.hasNext();) { // Saveable model = (Saveable) i.next(); // // handle case where this model got saved as a result of saving another // if (!model.isDirty()) { // monitor.worked(1); // continue; // } // SaveableHelper.doSaveModel(model, new SubProgressMonitor(monitorWrap, 1), shellProvider, closing || confirm); // if (monitorWrap.isCanceled()) { // break; // } // } // monitorWrap.done(); // } // }; // // // Do the save. // return SaveableHelper.runProgressMonitorOperation( // WorkbenchMessages.Save_All, progressOp, runnableContext, shellProvider); return true; } bool EditorManager::SavePart(ISaveablePart::Pointer /*saveable*/, IWorkbenchPart::Pointer /*part*/, bool /*confirm*/) { //TODO EditorManager save part (SaveableHelper) //return SaveableHelper.savePart(saveable, part, window, confirm); return true; } bool EditorManager::SaveState(const IMemento::Pointer memento) { // final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.EditorManager_problemsSavingEditors, null); bool result = true; // Save the editor area workbooks layout/relationship IMemento::Pointer editorAreaMem = memento->CreateChild(WorkbenchConstants::TAG_AREA); //result.add(editorPresentation.saveState(editorAreaMem)); result &= editorPresentation->SaveState(editorAreaMem); // Save the active workbook id editorAreaMem->PutString(WorkbenchConstants::TAG_ACTIVE_WORKBOOK, editorPresentation->GetActiveEditorWorkbookID()); // Get each workbook QList workbooks(editorPresentation->GetWorkbooks()); for (QList::iterator iter = workbooks.begin(); iter != workbooks.end(); ++iter) { PartStack::Pointer workbook = *iter; // Use the list of editors found in EditorStack; fix for 24091 QList editorPanes(workbook->GetChildren()); for (QList::iterator i = editorPanes.begin(); i != editorPanes.end(); ++i) { // Save each open editor. EditorReference::Pointer editorReference = i->Cast()->GetPartReference().Cast(); IEditorPart::Pointer editor = editorReference->GetEditor(false); if (!editor) { if (editorReference->GetMemento()) { IMemento::Pointer editorMem = memento ->CreateChild(WorkbenchConstants::TAG_EDITOR); editorMem->PutMemento(editorReference->GetMemento()); } continue; } // for dynamic UI - add the next line to replace the subsequent // code which is commented out SaveEditorState(memento, editorReference); //, result); } } return result; } bool EditorManager::SetVisibleEditor(IEditorReference::Pointer newEd, bool setFocus) { return editorPresentation->SetVisibleEditor(newEd, setFocus); } IPathEditorInput::Pointer EditorManager::GetPathEditorInput( IEditorInput::Pointer input) { if (input.Cast().IsNotNull()) { return input.Cast(); } // return (IPathEditorInput) // Util.getAdapter(input, IPathEditorInput.class); return IPathEditorInput::Pointer(0); } void EditorManager::RestoreEditorState(IMemento::Pointer /*editorMem*/, QList& /*visibleEditors*/, QList& /*activeEditor*/) { // MultiStatus result) { //TODO Restore editor state // String strFocus = editorMem.getString(IWorkbenchConstants.TAG_FOCUS); // boolean visibleEditor = "true".equals(strFocus); //$NON-NLS-1$ // EditorReference::Pointer e = new EditorReference(this, editorMem); // // try // { // StartupThreading.runWithPartInitExceptions(new StartupRunnable () // { // // public void runWithException() throws Throwable // { // createEditorTab(e, workbookID); // }}); // // } // catch (PartInitException ex) // { // result.add(ex.getStatus()); // } // // String strActivePart = editorMem // .getString(IWorkbenchConstants.TAG_ACTIVE_PART); // if ("true".equals(strActivePart)) // { //$NON-NLS-1$ // activeEditor[0] = e; // } // // String strFocus = editorMem.getString(IWorkbenchConstants.TAG_FOCUS); // boolean visibleEditor = "true".equals(strFocus); //$NON-NLS-1$ // if (visibleEditor) // { // visibleEditors.add(e); // } } void EditorManager::SaveEditorState(IMemento::Pointer /*mem*/, IEditorReference::Pointer /*ed*/) { //TODO Save editor state // final EditorReference editorRef = (EditorReference) ed; // final IEditorPart editor = ed.getEditor(false); // final IMemento memento = mem; // final MultiStatus result = res; // if (!(editor.getEditorSite() instanceof EditorSite)) // { // return; // } // final EditorSite site = (EditorSite) editor.getEditorSite(); // if (site.getPane() instanceof MultiEditorInnerPane) // { // return; // } // // SafeRunner.run(new SafeRunnable() // { // public void run() // { // // Get the input. // IEditorInput input = editor.getEditorInput(); // if (!input.exists()) // { // return; // } // IPersistableElement persistable = input.getPersistable(); // if (persistable == null) // { // return; // } // // // Save editor. // IMemento editorMem = memento // .createChild(IWorkbenchConstants.TAG_EDITOR); // editorMem.putString(IWorkbenchConstants.TAG_TITLE, editorRef // .getTitle()); // editorMem.putString(IWorkbenchConstants.TAG_NAME, editorRef // .getName()); // editorMem.putString(IWorkbenchConstants.TAG_ID, editorRef // .getId()); // editorMem.putString(IWorkbenchConstants.TAG_TOOLTIP, editorRef // .getTitleToolTip()); // // editorMem.putString(IWorkbenchConstants.TAG_PART_NAME, // editorRef.getPartName()); // // if (editor instanceof IWorkbenchPart3) // { // Map properties = ((IWorkbenchPart3) editor) // .getPartProperties(); // if (!properties.isEmpty()) // { // IMemento propBag = editorMem // .createChild(IWorkbenchConstants.TAG_PROPERTIES); // Iterator i = properties.entrySet().iterator(); // while (i.hasNext()) // { // Map.Entry entry = (Map.Entry) i.next(); // IMemento p = propBag.createChild( // IWorkbenchConstants.TAG_PROPERTY, // (String) entry.getKey()); // p.putTextData((String) entry.getValue()); // } // } // } // // if (editorRef.isPinned()) // { // editorMem.putString(IWorkbenchConstants.TAG_PINNED, "true"); //$NON-NLS-1$ // } // // EditorPane editorPane = (EditorPane) ((EditorSite) editor // .getEditorSite()).getPane(); // editorMem.putString(IWorkbenchConstants.TAG_WORKBOOK, // editorPane.getWorkbook().getID()); // // if (editor == page.getActivePart()) // { // editorMem.putString(IWorkbenchConstants.TAG_ACTIVE_PART, // "true"); //$NON-NLS-1$ // } // // if (editorPane == editorPane.getWorkbook().getSelection()) // { // editorMem.putString(IWorkbenchConstants.TAG_FOCUS, "true"); //$NON-NLS-1$ // } // // if (input instanceof IPathEditorInput) // { // IPath path = ((IPathEditorInput) input).getPath(); // if (path != null) // { // editorMem.putString(IWorkbenchConstants.TAG_PATH, path // .toString()); // } // } // // // Save input. // IMemento inputMem = editorMem // .createChild(IWorkbenchConstants.TAG_INPUT); // inputMem.putString(IWorkbenchConstants.TAG_FACTORY_ID, // persistable.getFactoryId()); // persistable.saveState(inputMem); // // // any editors that want to persist state // if (editor instanceof IPersistableEditor) // { // IMemento editorState = editorMem // .createChild(IWorkbenchConstants.TAG_EDITOR_STATE); // ((IPersistableEditor) editor).saveState(editorState); // } // } // // public void handleException(Throwable e) // { // result // .add(new Status( // IStatus.ERR, // PlatformUI.PLUGIN_ID, // 0, // NLS // .bind( // WorkbenchMessages.EditorManager_unableToSaveEditor, // editorRef.getTitle()), e)); // } // } // ); } IMemento::Pointer EditorManager::GetMemento(IEditorReference::Pointer e) { if (e.Cast().IsNotNull()) { return e.Cast()->GetMemento(); } return IMemento::Pointer(0); } IEditorReference::Pointer EditorManager::OpenEmptyTab() { IEditorInput::Pointer input(new NullEditorInput()); EditorDescriptor::Pointer desc = (dynamic_cast(this->GetEditorRegistry())) ->FindEditor(EditorRegistry::EMPTY_EDITOR_ID).Cast(); EditorReference::Pointer result(new EditorReference(this, input, desc)); try { this->CreateEditorTab(result, ""); return result; } catch (const PartInitException& e) { // StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, e)); BERRY_ERROR << e.what() << std::endl; } return IEditorReference::Pointer(0); } bool EditorManager::UseIPersistableEditor() { // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // return store.getBoolean(IPreferenceConstants.USE_IPERSISTABLE_EDITORS); return false; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorReference.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorReference.cpp index ce01dc44bf..c0f205d6b5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorReference.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorReference.cpp @@ -1,573 +1,573 @@ /*=================================================================== 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 "tweaklets/berryWorkbenchPageTweaklet.h" #include "berryEditorReference.h" #include "berryEditorManager.h" #include "berryEditorDescriptor.h" #include "berryEditorRegistry.h" #include "berryEditorSite.h" #include "berryEditorAreaHelper.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchPage.h" #include "berryNullEditorInput.h" #include "berryPartTester.h" #include "berryImageDescriptor.h" #include "berryPlatformUI.h" #include "berryIWorkbenchPartConstants.h" namespace berry { EditorReference::EditorReference(EditorManager* man, IEditorInput::Pointer input, EditorDescriptor::Pointer desc, IMemento::Pointer editorState) : manager(man), expectingInputChange(false), reportedMalfunctioningEditor(false) { this->InitListenersAndHandlers(); restoredInput = input; this->editorState = editorState; this->Init(desc->GetId(), "", desc->GetImageDescriptor(), desc->GetLabel(), ""); } EditorReference::EditorReference(EditorManager* man, IMemento::Pointer memento) : manager(man), expectingInputChange(false), reportedMalfunctioningEditor(false) { this->InitListenersAndHandlers(); this->editorMemento = memento; if (manager->UseIPersistableEditor()) { //editorState = editorMemento->GetChild(WorkbenchConstants::TAG_EDITOR_STATE); } else { editorState = 0; } // String id = memento.getString(IWorkbenchConstants.TAG_ID); // String title = memento.getString(IWorkbenchConstants.TAG_TITLE); // String tooltip = Util.safeString(memento // .getString(IWorkbenchConstants.TAG_TOOLTIP)); // String partName = memento // .getString(IWorkbenchConstants.TAG_PART_NAME); // // IMemento propBag = memento.getChild(IWorkbenchConstants.TAG_PROPERTIES); // if (propBag != null) // { // IMemento[] props = propBag // .getChildren(IWorkbenchConstants.TAG_PROPERTY); // for (int i = 0; i < props.length; i++) // { // propertyCache.put(props[i].getID(), props[i].getTextData()); // } // } // For compatibility set the part name to the title if not found // if (partName.empty()) // { // partName = title; // } // Get the editor descriptor. // EditorDescriptor::Pointer desc; // if (id != null) // { // desc = getDescriptor(id); // } // // desc may be null if id is null or desc is not found, but findImage below handles this // String location = memento.getString(IWorkbenchConstants.TAG_PATH); // IPath path = location == null ? null : new Path(location); // ImageDescriptor iDesc = this.manager.findImage(desc, path); // // this.name = memento.getString(IWorkbenchConstants.TAG_NAME); // if (this.name == null) // { // this.name = title; // } // setPinned("true".equals(memento.getString(IWorkbenchConstants.TAG_PINNED))); //$NON-NLS-1$ // // IMemento inputMem = memento.getChild(IWorkbenchConstants.TAG_INPUT); // if (inputMem != null) // { // this.factoryId = inputMem // .getString(IWorkbenchConstants.TAG_FACTORY_ID); // } // // init(id, title, tooltip, iDesc, partName, ""); //$NON-NLS-1$ } EditorDescriptor::Pointer EditorReference::GetDescriptor() { return this->GetDescriptor(this->GetId()); } EditorDescriptor::Pointer EditorReference::GetDescriptor(const QString& id) { EditorDescriptor::Pointer desc; IEditorRegistry* reg = WorkbenchPlugin::GetDefault()->GetEditorRegistry(); desc = reg->FindEditor(id).Cast (); return desc; } void EditorReference::InitListenersAndHandlers() { // Create a property change listener to track the "close editors automatically" // preference and show/remove the pin icon on editors // Only 1 listener will be created in the EditorManager when necessary //this->manager->CheckCreateEditorPropListener(); // Create a keyboard shortcut handler for pinning editors // Only 1 handler will be created in the EditorManager when necessary //this->manager->CheckCreatePinEditorShortcutKeyHandler(); } PartPane::Pointer EditorReference::CreatePane() { PartPane::Pointer pane( new PartPane(IWorkbenchPartReference::Pointer(this), this->manager->page)); return pane; //return Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateEditorPane(this, // this->manager->page); } void EditorReference::PinStatusUpdated() { //firePropertyChange(IWorkbenchPart.PROP_TITLE); } QString EditorReference::GetFactoryId() { // IEditorPart editor = getEditor(false); // if (editor != null) // { // IPersistableElement persistable = editor.getEditorInput() // .getPersistable(); // if (persistable != null) // { // return persistable.getFactoryId(); // } // return null; // } // return factoryId; return ""; } -QString EditorReference::ComputePartName() +QString EditorReference::ComputePartName() const { return WorkbenchPartReference::ComputePartName(); } QString EditorReference::GetName() { if (part.IsNotNull()) { return this->GetEditor(false)->GetEditorInput()->GetName(); } return name; } IEditorPart::Pointer EditorReference::GetEditor(bool restore) { return this->GetPart(restore).Cast (); } void EditorReference::SetName(const QString& name) { this->name = name; } IMemento::Pointer EditorReference::GetMemento() { return editorMemento; } IWorkbenchPage::Pointer EditorReference::GetPage() const { return IWorkbenchPage::Pointer(this->manager->page); } IEditorInput::Pointer EditorReference::GetEditorInput() { IEditorPart::Pointer part = this->GetEditor(false); if (part.IsNotNull()) { return part->GetEditorInput(); } return this->GetRestoredInput(); } IEditorInput::Pointer EditorReference::GetRestoredInput() { if (restoredInput.IsNotNull()) { return restoredInput; } // Get the input factory. // IMemento::Pointer editorMem = this->GetMemento(); // if (editorMem == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_no_persisted_state, getId(), getName())); // } // IMemento inputMem = editorMem // .getChild(IWorkbenchConstants.TAG_INPUT); // String factoryID = null; // if (inputMem != null) // { // factoryID = inputMem // .getString(IWorkbenchConstants.TAG_FACTORY_ID); // } // if (factoryID == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_no_input_factory_ID, getId(), getName())); // } // IAdaptable input = null; // String label = null; // debugging only // if (UIStats.isDebugging(UIStats.CREATE_PART_INPUT)) // { // label = getName() != null ? getName() : factoryID; // } // try // { // UIStats.start(UIStats.CREATE_PART_INPUT, label); // IElementFactory factory = PlatformUI.getWorkbench() // .getElementFactory(factoryID); // if (factory == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_bad_element_factory, new Object[] // { factoryID, getId(), getName()})); // } // // // Get the input element. // input = factory.createElement(inputMem); // if (input == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_create_element_returned_null, new Object[] // { factoryID, getId(), getName()})); // } // }finally // { // UIStats.end(UIStats.CREATE_PART_INPUT, input, label); // } // if (!(input instanceof IEditorInput)) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_wrong_createElement_result, new Object[] // { factoryID, getId(), getName()})); // } // restoredInput = (IEditorInput) input; return restoredInput; } IWorkbenchPart::Pointer EditorReference::CreatePart() { if (EditorRegistry::EMPTY_EDITOR_ID == this->GetId()) { return this->GetEmptyEditor(this->GetDescriptor()); } IWorkbenchPart::Pointer result; // Try to restore the editor -- this does the real work of restoring the editor // try { result = this->CreatePartHelper().Cast (); } catch (PartInitException e) { // If unable to create the part, create an error part instead // and pass the error to the status handling facility // IStatus originalStatus = exception.getStatus(); // IStatus logStatus = StatusUtil.newStatus(originalStatus, // NLS.bind("Unable to create editor ID {0}: {1}", //$NON-NLS-1$ // getId(), originalStatus.getMessage())); // IStatus displayStatus = StatusUtil.newStatus(originalStatus, // NLS.bind(WorkbenchMessages.EditorManager_unableToCreateEditor, // originalStatus.getMessage())); WorkbenchPlugin::Log(QString("Unable to create editor ID ") + this->GetId() + ": " + e.what()); // Pass the error to the status handling facility //StatusManager.getManager().handle(logStatus); EditorDescriptor::Pointer descr = this->GetDescriptor(); QString label = this->GetId(); if (descr.IsNotNull()) label = descr->GetLabel(); IEditorPart::Pointer part = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreateErrorEditorPart(label, e.what()); if (part.IsNotNull()) { IEditorInput::Pointer input; try { input = this->GetEditorInput(); } catch (PartInitException e1) { input = new NullEditorInput(EditorReference::Pointer(this)); } PartPane::Pointer pane = this->GetPane(); pane->CreateControl( manager->page->GetEditorPresentation()->GetLayoutPart()->GetControl()); EditorSite::Pointer site( new EditorSite(IEditorReference::Pointer(this), part, manager->page, descr)); //site.setActionBars(new EditorActionBars(manager.page, site.getWorkbenchWindow(), getId())); part->Init(site, input); try { part->CreatePartControl(pane->GetControl()); } catch (...) { //content.dispose(); //StatusUtil.handleStatus(e, StatusManager.SHOW // | StatusManager.LOG); WorkbenchPlugin::Log("Error creating editor"); return IWorkbenchPart::Pointer(0); } result = part.Cast (); } } return result; } void EditorReference::PropertyChanged(Object::Pointer source, int propId) { // Detect badly behaved editors that don't fire PROP_INPUT events // when they're supposed to. This branch is only needed to handle // malfunctioning editors. if (propId == IWorkbenchPartConstants::PROP_INPUT) { expectingInputChange = false; } WorkbenchPartReference::PropertyChanged(source, propId); } bool EditorReference::SetInput(IEditorInput::Pointer input) { if (part.IsNotNull()) { if (part.Cast ().IsNotNull()) { IReusableEditor::Pointer editor = part.Cast (); expectingInputChange = true; editor->SetInput(input); // If the editor never fired a PROP_INPUT event, log the fact that we've discovered // a buggy editor and fire the event for free. Firing the event for free isn't required // and cannot be relied on (it only works if the input change was triggered by this // method, and there are definitely other cases where events will still be lost), // but older versions of the workbench did this so we fire it here in the spirit // of playing nice. if (expectingInputChange) { // Log the fact that this editor is broken this->ReportMalfunction( "Editor is not firing a PROP_INPUT event in response to IReusableEditor.setInput(...)"); //$NON-NLS-1$ // Fire the property for free (can't be relied on since there are other ways the input // can change, but we do it here to be consistent with older versions of the workbench) FirePropertyChange(IWorkbenchPartConstants::PROP_INPUT); } return editor->GetEditorInput() == input; } // Can't change the input if the editor already exists and isn't an IReusableEditor return false; } // Changing the input is trivial and always succeeds if the editor doesn't exist yet if (input != restoredInput) { restoredInput = input; //firePropertyChange(IWorkbenchPartConstants.PROP_INPUT); } return true; } void EditorReference::ReportMalfunction(const QString& string) { if (!reportedMalfunctioningEditor) { reportedMalfunctioningEditor = true; QString errorMessage = "Problem detected with part " + this->GetId(); //$NON-NLS-1$ if (part.IsNotNull()) { errorMessage.append("(class = ").append(part->GetClassName()).append( ")"); //$NON-NLS-1$ //$NON-NLS-2$ } errorMessage += ": " + string; //$NON-NLS-1$ //StatusManager.getManager().handle(StatusUtil.newStatus(getDescriptor().getPluginId(), errorMessage, null)); BERRY_ERROR << errorMessage << std::endl; } } IEditorPart::Pointer EditorReference::CreatePartHelper() { EditorSite::Pointer site; IEditorPart::Pointer part; try { IEditorInput::Pointer editorInput = this->GetEditorInput(); // Get the editor descriptor. QString editorID = this->GetId(); EditorDescriptor::Pointer desc = this->GetDescriptor(); if (desc.IsNull()) { throw PartInitException("No editor descriptor for id " + editorID); } if (desc->IsInternal()) { // Create an editor instance. part = manager->CreatePart(desc); this->CreatePartProperties(part); } // else if (desc->GetId() == IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID) // { // // part = ComponentSupport.getSystemInPlaceEditor(); // // if (part == null) // { // throw new PartInitException(WorkbenchMessages.EditorManager_no_in_place_support); // } // } else { throw PartInitException("Invalid editor descriptor for id " + editorID); } // Create a pane for this part PartPane::Pointer pane = this->GetPane(); pane->CreateControl(manager->page->GetEditorPresentation()->GetLayoutPart()->GetControl()); // Link everything up to the part reference (the part reference itself should not have // been modified until this point) site = manager->CreateSite(IEditorReference::Pointer(this), part, desc, editorInput); // if there is saved state that's appropriate, pass it on if (/*part instanceof IPersistableEditor &&*/editorState.IsNotNull()) { //part->RestoreState(editorState); } // Remember the site and the action bars (now that we've created them, we'll need to dispose // them if an exception occurs) //actionBars = (EditorActionBars) site.getActionBars(); part->CreatePartControl(pane->GetControl()); // The editor should now be fully created. Exercise its public interface, and sanity-check // it wherever possible. If it's going to throw exceptions or behave badly, it's much better // that it does so now while we can still cancel creation of the part. PartTester::TestEditor(part); return part; } catch (std::exception e) { throw PartInitException(e.what()); } } IEditorPart::Pointer EditorReference::GetEmptyEditor( EditorDescriptor::Pointer descr) { IEditorPart::Pointer part = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreateErrorEditorPart("(Empty)", ""); IEditorInput::Pointer input; try { input = this->GetEditorInput(); } catch (PartInitException e1) { input = new NullEditorInput(EditorReference::Pointer(this)); } PartPane::Pointer pane = this->GetPane(); pane->CreateControl( manager->page->GetEditorPresentation()->GetLayoutPart()->GetControl()); EditorSite::Pointer site(new EditorSite(IEditorReference::Pointer(this), part, manager->page, descr)); //site.setActionBars(new EditorActionBars(manager.page, site.getWorkbenchWindow(), getId())); part->Init(site, input); try { part->CreatePartControl(pane->GetControl()); } catch (std::exception e) { //StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, e)); BERRY_ERROR << e.what() << std::endl; return IEditorPart::Pointer(0); } this->part = part.Cast (); // Add a dispose listener to the part. This dispose listener does nothing but log an exception // if the part's widgets get disposed unexpectedly. The workbench part reference is the only // object that should dispose this control, and it will remove the listener before it does so. this->RefreshFromPart(); //this->ReleaseReferences(); if (this->GetPage().Cast ()->GetActiveEditorReference() != this) { //fireInternalPropertyChange(INTERNAL_PROPERTY_OPENED); } return part; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorReference.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorReference.h index 934b9ccad3..aaa64736e5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorReference.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorReference.h @@ -1,235 +1,236 @@ /*=================================================================== 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 BERRYEDITORREFERENCE_H_ #define BERRYEDITORREFERENCE_H_ #include "berryWorkbenchPartReference.h" #include "berryIEditorReference.h" #include "berryIEditorInput.h" #include "berryIMemento.h" #include "berryIWorkbenchPart.h" #include "berryIEditorPart.h" namespace berry { class EditorManager; class EditorDescriptor; class PartPane; struct IWorkbenchPage; /** * \ingroup org_blueberry_ui_internal * */ class EditorReference : public WorkbenchPartReference, public IEditorReference { private: const EditorManager* manager; private: IMemento::Pointer editorMemento; private: IMemento::Pointer editorState; /** * Flag that lets us detect malfunctioning editors that don't fire PROP_INPUT events. * It is never needed for a correctly-functioning */ private: bool expectingInputChange; /** * Flag that determines whether we've already reported that this editor is malfunctioning. * This prevents us from spamming the event log if we repeatedly detect the same error in * a particular editor. If we ever detect an editor is violating its public contract in * a way we can recover from (such as a missing property change event), we report the error * once and then silently ignore errors from the same editor. */ private: bool reportedMalfunctioningEditor; /** * User-readable name of the editor's input */ QString name; QString factoryId; IEditorInput::Pointer restoredInput; /** * @param manager * The editor manager for this reference * @param input * our input * @param desc * the descriptor from the declaration * @param editorState * propogate state from another editor. Can be null. */ public: berryObjectMacro(EditorReference); EditorReference(EditorManager* manager, IEditorInput::Pointer input, SmartPointer desc, IMemento::Pointer editorState = IMemento::Pointer(0)); /** * Constructs a new editor reference for use by editors being restored from * a memento. */ EditorReference(EditorManager* manager, IMemento::Pointer memento); public: SmartPointer GetDescriptor(); /** * @param id the id * @return the editor descriptor */ private: SmartPointer GetDescriptor(const QString& id); /** * Initializes the necessary editor listeners and handlers */ private: void InitListenersAndHandlers(); protected: SmartPointer CreatePane(); /** * This method is called when there should be a change in the editor pin * status (added or removed) so that it will ask its presentable part * to fire a PROP_TITLE event in order for the presentation to request * the new icon for this editor */ public: void PinStatusUpdated(); public: QString GetFactoryId(); protected: - QString ComputePartName(); + QString ComputePartName() const; public: QString GetName(); public: IEditorPart::Pointer GetEditor(bool restore); public: void SetName(const QString& name); public: IMemento::Pointer GetMemento(); public: SmartPointer GetPage() const; public: IEditorInput::Pointer GetEditorInput(); private: IEditorInput::Pointer GetRestoredInput(); /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartReference#getTitleImage() * This method will append a pin to the icon of the editor * if the "automatically close editors" option in the * preferences is enabled and the editor has been pinned. */ //public: ImageDescriptor computeImageDescriptor() { // ImageDescriptor descriptor = super.computeImageDescriptor(); // if (!isPinned()) { // return descriptor; // } // // // Check if the pinned preference is set // IPreferenceStore prefStore = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // boolean bUsePin = prefStore // .getBoolean(IPreferenceConstants.REUSE_EDITORS_BOOLEAN) // || ((TabBehaviour)Tweaklets.get(TabBehaviour.KEY)).alwaysShowPinAction(); // // if (!bUsePin) { // return descriptor; // } // // ImageDescriptor pinDesc = this.manager.getEditorPinImageDesc(); // if (pinDesc == null) { // return descriptor; // } // // return new OverlayIcon(descriptor, pinDesc, new Point(16, 16)); // } protected: /** * Wrapper for restoring the editor. First, this delegates to busyRestoreEditorHelper * to do the real work of restoring the view. If unable to restore the editor, this * method tries to substitute an error part and return success. * * @return the created part */ IWorkbenchPart::Pointer CreatePart(); + using WorkbenchPartReference::PropertyChanged; void PropertyChanged(Object::Pointer source, int propId); /** * Attempts to set the input of the editor to the given input. Note that the input * can't always be changed for an editor. Editors that don't implement IReusableEditor * can't have their input changed once they've been materialized. * * @param input new input * @return true iff the input was actually changed */ public: bool SetInput(IEditorInput::Pointer input); /** * Reports a recoverable malfunction in the system log. A recoverable malfunction would be * something like failure to fire an expected property change. Only the first malfunction is * * @param string */ private: void ReportMalfunction(const QString& string); private: IEditorPart::Pointer CreatePartHelper(); /** * Creates and returns an empty editor (ErrorEditorPart). * * @param descr the editor descriptor * @return the empty editor part or null in case of an exception */ public: IEditorPart::Pointer GetEmptyEditor(SmartPointer descr); }; } // namespace berry #endif /*BERRYEDITORREFERENCE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp index 11b9c6236d..cb61d3ab46 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorRegistry.cpp @@ -1,1299 +1,1299 @@ /*=================================================================== 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 "berryEditorRegistry.h" #include "berryWorkbenchPlugin.h" #include "berryEditorRegistryReader.h" #include "berryWorkbenchRegistryConstants.h" namespace berry { const QString EditorRegistry::EMPTY_EDITOR_ID = "org.blueberry.ui.internal.emptyEditorTab"; QHash EditorRegistry::EditorMap::defaultMap; QHash EditorRegistry::EditorMap::map; EditorRegistry::RelatedRegistry::RelatedRegistry(EditorRegistry* reg) : editorRegistry(reg) { } QList EditorRegistry::RelatedRegistry::GetRelatedObjects( const QString& fileName) { IFileEditorMapping::Pointer mapping = editorRegistry->GetMappingFor(fileName); if (mapping.IsNull()) { return QList(); } return mapping->GetEditors(); } EditorRegistry::EditorRegistry() : relatedRegistry(this) { this->InitialIdToEditorMap(mapIDtoEditor); this->InitializeFromStorage(); //IExtensionTracker tracker = PlatformUI.getWorkbench().getExtensionTracker(); //tracker.registerHandler(this, // ExtensionTracker.createExtensionPointFilter(getExtensionPointFilter())); } void EditorRegistry::AddEditorFromPlugin(EditorDescriptor::Pointer editor, const QList& extensions, const QList& filenames, const QList& /*contentTypeVector*/, bool bDefault) { //PlatformUI.getWorkbench().getExtensionTracker().registerObject(editor.getConfigurationElement().getDeclaringExtension(), editor, IExtensionTracker.REF_WEAK); // record it in our quick reference list sortedEditorsFromPlugins.push_back(editor); // add it to the table of mappings for (QList::const_iterator itr = extensions.begin(); itr != extensions.end(); ++itr) { QString fileExtension = *itr; if (!fileExtension.isEmpty()) { FileEditorMapping::Pointer mapping = this->GetMappingFor("*." + fileExtension); if (mapping.IsNull()) { // no mapping for that extension mapping = new FileEditorMapping(fileExtension); typeEditorMappings.PutDefault(this->MappingKeyFor(mapping), mapping); } mapping->AddEditor(editor); if (bDefault) { mapping->SetDefaultEditor(editor); } } } // add it to the table of mappings for (QList::const_iterator itr = filenames.begin(); itr != filenames.end(); ++itr) { QString filename = *itr; if (!filename.isEmpty()) { FileEditorMapping::Pointer mapping = this->GetMappingFor(filename); if (mapping.IsNull()) { // no mapping for that extension QString name; QString extension; int index = filename.indexOf('.'); if (index == -1) { name = filename; extension = ""; } else { name = filename.left(index); extension = filename.mid(index + 1); } mapping = new FileEditorMapping(name, extension); typeEditorMappings.PutDefault(this->MappingKeyFor(mapping), mapping); } mapping->AddEditor(editor); if (bDefault) { mapping->SetDefaultEditor(editor); } } } // for (QList::const_iterator itr = contentTypeVector.begin(); // itr != contentTypeVector.end(); ++itr) // { // QString contentTypeId = *itr; // if (!contentTypeId.empty()) // { // IContentType contentType = Platform.getContentTypeManager().getContentType(contentTypeId); // if (contentType != null) // { // IEditorDescriptor [] editorArray = (IEditorDescriptor[]) contentTypeToEditorMappings.get(contentType); // if (editorArray == null) // { // editorArray = new IEditorDescriptor[] // { editor}; // contentTypeToEditorMappings.put(contentType, editorArray); // } // else // { // IEditorDescriptor [] newArray = new IEditorDescriptor[editorArray.length + 1]; // if (bDefault) // { // default editors go to the front of the line // newArray[0] = editor; // System.arraycopy(editorArray, 0, newArray, 1, editorArray.length); // } // else // { // newArray[editorArray.length] = editor; // System.arraycopy(editorArray, 0, newArray, 0, editorArray.length); // } // contentTypeToEditorMappings.put(contentType, newArray); // } // } // } // } // Update editor map. mapIDtoEditor[editor->GetId()] = editor; } void EditorRegistry::AddExternalEditorsToEditorMap() { // Add registered editors (may include external editors). QList maps = typeEditorMappings.AllMappings(); - for (unsigned int i = 0; i < maps.size(); ++i) + for (int i = 0; i < maps.size(); ++i) { FileEditorMapping::Pointer map = maps[i]; QList descArray = map->GetEditors(); for (QList::iterator itr = descArray.begin(); itr != descArray.end(); ++itr) { mapIDtoEditor[(*itr)->GetId()] = itr->Cast (); } } } IEditorDescriptor::Pointer EditorRegistry::FindEditor(const QString& id) { return mapIDtoEditor[id]; } IEditorDescriptor::Pointer EditorRegistry::GetDefaultEditor() { // the default editor will always be the system external editor // this should never return null return this->FindEditor(IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID); } IEditorDescriptor::Pointer EditorRegistry::GetDefaultEditor( const QString& fileName) { //return this->GetDefaultEditor(filename, guessAtContentType(filename)); return this->GetEditorForContentType(fileName /*, contentType*/); } IEditorDescriptor::Pointer EditorRegistry::GetEditorForContentType( const QString& filename /*IContentType contentType*/) { IEditorDescriptor::Pointer desc; ; QList contentTypeResults = this->FindRelatedObjects(/*contentType,*/filename, relatedRegistry); if (contentTypeResults.size() > 0) { desc = contentTypeResults.front(); } return desc; } QList EditorRegistry::FindRelatedObjects( /*IContentType type,*/const QString& fileName, RelatedRegistry& /*registry*/) { QList allRelated; QList nonDefaultFileEditors; QList related; if (!fileName.isEmpty()) { FileEditorMapping::Pointer mapping = this->GetMappingFor(fileName); if (!mapping.IsNull()) { // backwards compatibility - add editors flagged as "default" related = mapping->GetDeclaredDefaultEditors(); for (QList::iterator itr = related.begin(); itr != related.end(); ++itr) { // we don't want to return duplicates if (std::find(allRelated.begin(), allRelated.end(), *itr) == allRelated.end()) { allRelated.push_back(*itr); } } // add all filename editors to the nonDefaultList // we'll later try to add them all after content types are resolved // duplicates (ie: default editors) will be ignored QList tmpList = mapping->GetEditors(); nonDefaultFileEditors.append(tmpList); } int index = fileName.indexOf('.'); if (index != -1) { QString extension = "*" + fileName.mid(index); mapping = this->GetMappingFor(extension); if (!mapping.IsNull()) { related = mapping->GetDeclaredDefaultEditors(); for (QList::iterator itr = related.begin(); itr != related.end(); ++itr) { // we don't want to return duplicates if (std::find(allRelated.begin(), allRelated.end(), *itr) == allRelated.end()) { allRelated.push_back(*itr); } } QList tmpList = mapping->GetEditors(); nonDefaultFileEditors.append(tmpList); } } } // if (type != null) { // // now add any objects directly related to the content type // related = registry.getRelatedObjects(type); // for (int i = 0; i < related.length; i++) { // // we don't want to return duplicates // if (!allRelated.contains(related[i])) { // // if it's not filtered, add it to the list // if (!WorkbenchActivityHelper.filterItem(related[i])) { // allRelated.add(related[i]); // } // } // } // // } // if (type != null) { // // now add any indirectly related objects, walking up the content type hierarchy // while ((type = type.getBaseType()) != null) { // related = registry.getRelatedObjects(type); // for (int i = 0; i < related.length; i++) { // // we don't want to return duplicates // if (!allRelated.contains(related[i])) { // // if it's not filtered, add it to the list // if (!WorkbenchActivityHelper.filterItem(related[i])) { // allRelated.add(related[i]); // } // } // } // } // } // add all non-default editors to the list for (QList::iterator i = nonDefaultFileEditors.begin(); i != nonDefaultFileEditors.end(); ++i) { IEditorDescriptor::Pointer editor = *i; if (std::find(allRelated.begin(), allRelated.end(), editor) == allRelated.end()) { allRelated.push_back(editor); } } return allRelated; } QList EditorRegistry::GetEditors( const QString& filename) { //return getEditors(filename, guessAtContentType(filename)); return this->FindRelatedObjects(/*contentType,*/filename, relatedRegistry); } QList EditorRegistry::GetFileEditorMappings() { QList array(typeEditorMappings.AllMappings()); std::sort(array.begin(), array.end(), CmpFileEditorMapping()); QList result; for (QList::iterator itr = array.begin(); itr != array.end(); ++itr) { result.push_back(itr->Cast ()); } return result; } FileEditorMapping::Pointer EditorRegistry::GetMappingFor(const QString& ext) { QString key = this->MappingKeyFor(ext); return typeEditorMappings.Get(key); } QList EditorRegistry::GetMappingForFilename( const QString& filename) { QList mapping; // Lookup on entire filename mapping[0] = this->GetMappingFor(filename); // Lookup on filename's extension int index = filename.indexOf('.'); if (index != -1) { QString extension = filename.mid(index); mapping[1] = this->GetMappingFor("*" + extension); } return mapping; } // QList EditorRegistry::GetSortedEditorsFromOS() // { // List externalEditors = new ArrayList(); // Program[] programs = Program.getPrograms(); // // for (int i = 0; i < programs.length; i++) // { // //1FPLRL2: ITPUI:WINNT - NOTEPAD editor cannot be launched // //Some entries start with %SystemRoot% // //For such cases just use the file name as they are generally // //in directories which are on the path // /* // * if (fileName.charAt(0) == '%') { fileName = name + ".exe"; } // */ // // EditorDescriptor editor = new EditorDescriptor(); // editor.setOpenMode(EditorDescriptor.OPEN_EXTERNAL); // editor.setProgram(programs[i]); // // // determine the program icon this editor would need (do not let it // // be cached in the workbench registry) // ImageDescriptor desc = new ExternalProgramImageDescriptor( // programs[i]); // editor.setImageDescriptor(desc); // externalEditors.add(editor); // } // // Object[] tempArray = sortEditors(externalEditors); // IEditorDescriptor[] array = new IEditorDescriptor[externalEditors // .size()]; // for (int i = 0; i < tempArray.length; i++) // { // array[i] = (IEditorDescriptor) tempArray[i]; // } // return array; // } QList EditorRegistry::GetSortedEditorsFromPlugins() { QList result; for (QList::iterator itr = sortedEditorsFromPlugins.begin(); itr != sortedEditorsFromPlugins.end(); ++itr) { result.push_back((*itr).Cast ()); } return result; } void EditorRegistry::InitialIdToEditorMap( QHash& map) { this->AddSystemEditors(map); } void EditorRegistry::AddSystemEditors( QHash& map) { // there will always be a system external editor descriptor EditorDescriptor::Pointer editor(new EditorDescriptor()); editor->SetID(IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID); editor->SetName("System Editor"); editor->SetOpenMode(EditorDescriptor::OPEN_EXTERNAL); // @issue we need a real icon for this editor? map[IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID] = editor; // there may be a system in-place editor if supported by platform // if (ComponentSupport.inPlaceEditorSupported()) // { // editor = new EditorDescriptor(); // editor.setID(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID); // editor.setName(WorkbenchMessages.SystemInPlaceDescription_name); // editor.setOpenMode(EditorDescriptor.OPEN_INPLACE); // // @issue we need a real icon for this editor? // map.put(IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID, editor); // } EditorDescriptor::Pointer emptyEditorDescriptor(new EditorDescriptor()); emptyEditorDescriptor->SetID(EMPTY_EDITOR_ID); emptyEditorDescriptor->SetName("(Empty)"); //$NON-NLS-1$ //emptyEditorDescriptor.setImageDescriptor(WorkbenchImages //.getImageDescriptor(IWorkbenchGraphicConstants.IMG_OBJ_ELEMENT)); map[EMPTY_EDITOR_ID] = emptyEditorDescriptor; } void EditorRegistry::InitializeFromStorage() { //Get editors from the registry EditorRegistryReader registryReader; registryReader.AddEditors(this); this->SortInternalEditors(); this->RebuildInternalEditorMap(); // IPreferenceStore store = PlatformUI.getPreferenceStore(); // String defaultEditors = store // .getString(IPreferenceConstants.DEFAULT_EDITORS); // String chachedDefaultEditors = store // .getString(IPreferenceConstants.DEFAULT_EDITORS_CACHE); //If defaults has changed load it afterwards so it overrides the users // associations. //if (defaultEditors == null // || defaultEditors.equals(chachedDefaultEditors)) //{ this->SetProductDefaults("");//defaultEditors); this->LoadAssociations(); //get saved earlier state // } // else // { // loadAssociations(); //get saved earlier state // setProductDefaults(defaultEditors); // store.putValue(IPreferenceConstants.DEFAULT_EDITORS_CACHE, // defaultEditors); // } this->AddExternalEditorsToEditorMap(); } void EditorRegistry::SetProductDefaults(const QString& defaultEditors) { if (defaultEditors.isEmpty()) { return; } // Poco::StringTokenizer extEditors(defaultEditors, // IPreferenceConstants::SEPARATOR, Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY); // while (extEditors.hasMoreTokens()) // { // String extEditor = extEditors.nextToken().trim(); // int index = extEditor.indexOf(':'); // if (extEditor.length() < 3 || index <= 0 || index // >= (extEditor.length() - 1)) // { // //Extension and id must have at least one char. // WorkbenchPlugin // .log("Error setting default editor. Could not parse '" + extEditor // + "'. Default editors should be specified as '*.ext1:editorId1;*.ext2:editorId2'"); //$NON-NLS-1$ //$NON-NLS-2$ // return; // } // String ext = extEditor.substring(0, index).trim(); // String editorId = extEditor.substring(index + 1).trim(); // FileEditorMapping mapping = getMappingFor(ext); // if (mapping == null) // { // WorkbenchPlugin // .log("Error setting default editor. Could not find mapping for '" // + ext + "'."); //$NON-NLS-1$ //$NON-NLS-2$ // continue; // } // EditorDescriptor editor = (EditorDescriptor) findEditor(editorId); // if (editor == null) // { // WorkbenchPlugin // .log("Error setting default editor. Could not find editor: '" // + editorId + "'."); //$NON-NLS-1$ //$NON-NLS-2$ // continue; // } // mapping.setDefaultEditor(editor); // } } bool EditorRegistry::ReadEditors( QHash& /*editorTable*/) { //Get the workbench plugin's working directory QString workbenchStatePath = WorkbenchPlugin::GetDefault()->GetDataLocation(); if (workbenchStatePath.isNull()) { return false; } // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // Reader reader = null; // try // { // // Get the editors defined in the preferences store // String xmlString = store.getString(IPreferenceConstants.EDITORS); // if (xmlString == null || xmlString.length() == 0) // { // FileInputStream stream = new FileInputStream(workbenchStatePath // .append(IWorkbenchConstants.EDITOR_FILE_NAME) // .toOSString()); // reader = new BufferedReader(new InputStreamReader(stream, // "utf-8")); //$NON-NLS-1$ // } // else // { // reader = new StringReader(xmlString); // } // XMLMemento memento = XMLMemento.createReadRoot(reader); // EditorDescriptor editor; // IMemento[] edMementos = memento // .getChildren(IWorkbenchConstants.TAG_DESCRIPTOR); // // Get the editors and validate each one // for (int i = 0; i < edMementos.length; i++) // { // editor = new EditorDescriptor(); // boolean valid = editor.loadValues(edMementos[i]); // if (!valid) // { // continue; // } // if (editor.getPluginID() != null) // { // //If the editor is from a plugin we use its ID to look it // // up in the mapping of editors we // //have obtained from plugins. This allows us to verify that // // the editor is still valid // //and allows us to get the editor description from the // // mapping table which has // //a valid config element field. // EditorDescriptor validEditorDescritor = (EditorDescriptor) mapIDtoEditor // .get(editor.getId()); // if (validEditorDescritor != null) // { // editorTable.put(validEditorDescritor.getId(), // validEditorDescritor); // } // } // else // { //This is either from a program or a user defined // // editor // ImageDescriptor descriptor; // if (editor.getProgram() == null) // { // descriptor = new ProgramImageDescriptor(editor // .getFileName(), 0); // } // else // { // descriptor = new ExternalProgramImageDescriptor(editor // .getProgram()); // } // editor.setImageDescriptor(descriptor); // editorTable.put(editor.getId(), editor); // } // } // } // catch (IOException e) // { // try // { // if (reader != null) // { // reader.close(); // } // } // catch (IOException ex) // { // e.printStackTrace(); // } // //Ignore this as the workbench may not yet have saved any state // return false; // } // catch (WorkbenchException e) // { // ErrorDialog.openError((Shell) null, WorkbenchMessages.EditorRegistry_errorTitle, // WorkbenchMessages.EditorRegistry_errorMessage, // e.getStatus()); // return false; // } return true; } void EditorRegistry::ReadResources( QHash& /*editorTable*/, std::ostream& /*reader*/) { // XMLMemento memento = XMLMemento.createReadRoot(reader); // String versionString = memento.getString(IWorkbenchConstants.TAG_VERSION); // boolean versionIs31 = "3.1".equals(versionString); //$NON-NLS-1$ // // IMemento[] extMementos = memento // .getChildren(IWorkbenchConstants.TAG_INFO); // for (int i = 0; i < extMementos.length; i++) // { // String name = extMementos[i] // .getString(IWorkbenchConstants.TAG_NAME); // if (name == null) // { // name = "*"; //$NON-NLS-1$ // } // String extension = extMementos[i] // .getString(IWorkbenchConstants.TAG_EXTENSION); // IMemento[] idMementos = extMementos[i] // .getChildren(IWorkbenchConstants.TAG_EDITOR); // String[] editorIDs = new String[idMementos.length]; // for (int j = 0; j < idMementos.length; j++) // { // editorIDs[j] = idMementos[j] // .getString(IWorkbenchConstants.TAG_ID); // } // idMementos = extMementos[i] // .getChildren(IWorkbenchConstants.TAG_DELETED_EDITOR); // String[] deletedEditorIDs = new String[idMementos.length]; // for (int j = 0; j < idMementos.length; j++) // { // deletedEditorIDs[j] = idMementos[j] // .getString(IWorkbenchConstants.TAG_ID); // } // FileEditorMapping mapping = getMappingFor(name + "." + extension); //$NON-NLS-1$ // if (mapping == null) // { // mapping = new FileEditorMapping(name, extension); // } // List editors = new ArrayList(); // for (int j = 0; j < editorIDs.length; j++) // { // if (editorIDs[j] != null) // { // EditorDescriptor editor = (EditorDescriptor) editorTable // .get(editorIDs[j]); // if (editor != null) // { // editors.add(editor); // } // } // } // List deletedEditors = new ArrayList(); // for (int j = 0; j < deletedEditorIDs.length; j++) // { // if (deletedEditorIDs[j] != null) // { // EditorDescriptor editor = (EditorDescriptor) editorTable // .get(deletedEditorIDs[j]); // if (editor != null) // { // deletedEditors.add(editor); // } // } // } // // List defaultEditors = new ArrayList(); // // if (versionIs31) // { // parse the new format // idMementos = extMementos[i] // .getChildren(IWorkbenchConstants.TAG_DEFAULT_EDITOR); // String[] defaultEditorIds = new String[idMementos.length]; // for (int j = 0; j < idMementos.length; j++) // { // defaultEditorIds[j] = idMementos[j] // .getString(IWorkbenchConstants.TAG_ID); // } // for (int j = 0; j < defaultEditorIds.length; j++) // { // if (defaultEditorIds[j] != null) // { // EditorDescriptor editor = (EditorDescriptor) editorTable // .get(defaultEditorIds[j]); // if (editor != null) // { // defaultEditors.add(editor); // } // } // } // } // else // { // guess at pre 3.1 format defaults // if (!editors.isEmpty()) // { // EditorDescriptor editor = (EditorDescriptor) editors.get(0); // if (editor != null) // { // defaultEditors.add(editor); // } // } // defaultEditors.addAll(Arrays.asList(mapping.getDeclaredDefaultEditors())); // } // // // Add any new editors that have already been read from the registry // // which were not deleted. // IEditorDescriptor[] editorsArray = mapping.getEditors(); // for (int j = 0; j < editorsArray.length; j++) // { // if (!contains(editors, editorsArray[j]) // && !deletedEditors.contains(editorsArray[j])) // { // editors.add(editorsArray[j]); // } // } // // Map the editor(s) to the file type // mapping.setEditorsList(editors); // mapping.setDeletedEditorsList(deletedEditors); // mapping.setDefaultEditors(defaultEditors); // typeEditorMappings.put(mappingKeyFor(mapping), mapping); // } } bool EditorRegistry::Contains( const QList& editorsArray, IEditorDescriptor::Pointer editorDescriptor) { IEditorDescriptor::Pointer currentEditorDescriptor; for (QList::const_iterator i = editorsArray.begin(); i != editorsArray.end(); ++i) { currentEditorDescriptor = *i; if (currentEditorDescriptor->GetId() == editorDescriptor->GetId()) { return true; } } return false; } bool EditorRegistry::ReadResources( QHash& /*editorTable*/) { //Get the workbench plugin's working directory QString workbenchStatePath = WorkbenchPlugin::GetDefault()->GetDataLocation(); // XXX: nobody cares about this return value if (workbenchStatePath.isNull()) { return false; } // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // Reader reader = null; // try // { // // Get the resource types // String xmlString = store.getString(IPreferenceConstants.RESOURCES); // if (xmlString == null || xmlString.length() == 0) // { // FileInputStream stream = new FileInputStream(workbenchStatePath // .append(IWorkbenchConstants.RESOURCE_TYPE_FILE_NAME) // .toOSString()); // reader = new BufferedReader(new InputStreamReader(stream, // "utf-8")); //$NON-NLS-1$ // } // else // { // reader = new StringReader(xmlString); // } // // Read the defined resources into the table // readResources(editorTable, reader); // } // catch (IOException e) // { // try // { // if (reader != null) // { // reader.close(); // } // } // catch (IOException ex) // { // ex.printStackTrace(); // } // MessageDialog.openError((Shell) null, WorkbenchMessages.EditorRegistry_errorTitle, // WorkbenchMessages.EditorRegistry_errorMessage); // return false; // } // catch (WorkbenchException e) // { // ErrorDialog.openError((Shell) null, WorkbenchMessages.EditorRegistry_errorTitle, // WorkbenchMessages.EditorRegistry_errorMessage, // e.getStatus()); // return false; // } return true; } bool EditorRegistry::LoadAssociations() { QHash editorTable; if (!this->ReadEditors(editorTable)) { return false; } return this->ReadResources(editorTable); } QString EditorRegistry::MappingKeyFor(const QString& type) { // keep everyting lower case for case-sensitive platforms return type.toLower(); } QString EditorRegistry::MappingKeyFor(FileEditorMapping::Pointer mapping) { return this->MappingKeyFor(mapping->GetName() + (mapping->GetExtension().size() == 0 ? "" : "." + mapping->GetExtension())); //$NON-NLS-1$ //$NON-NLS-2$ } void EditorRegistry::RebuildEditorMap() { this->RebuildInternalEditorMap(); this->AddExternalEditorsToEditorMap(); } void EditorRegistry::RebuildInternalEditorMap() { EditorDescriptor::Pointer desc; // Allocate a new map. mapIDtoEditor.clear(); this->InitialIdToEditorMap(mapIDtoEditor); // Add plugin editors. for (QList::iterator itr = sortedEditorsFromPlugins.begin(); itr != sortedEditorsFromPlugins.end(); ++itr) { desc = *itr; mapIDtoEditor[desc->GetId()] = desc; } } void EditorRegistry::SaveAssociations() { //Save the resource type descriptions // List editors = new ArrayList(); // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // // XMLMemento memento = XMLMemento // .createWriteRoot(IWorkbenchConstants.TAG_EDITORS); // memento.putString(IWorkbenchConstants.TAG_VERSION, "3.1"); //$NON-NLS-1$ // FileEditorMapping maps[] = typeEditorMappings.userMappings(); // for (int mapsIndex = 0; mapsIndex < maps.length; mapsIndex++) // { // FileEditorMapping type = maps[mapsIndex]; // IMemento editorMemento = memento // .createChild(IWorkbenchConstants.TAG_INFO); // editorMemento.putString(IWorkbenchConstants.TAG_NAME, type // .getName()); // editorMemento.putString(IWorkbenchConstants.TAG_EXTENSION, type // .getExtension()); // IEditorDescriptor[] editorArray = type.getEditors(); // for (int i = 0; i < editorArray.length; i++) // { // EditorDescriptor editor = (EditorDescriptor) editorArray[i]; // if (!editors.contains(editor)) // { // editors.add(editor); // } // IMemento idMemento = editorMemento // .createChild(IWorkbenchConstants.TAG_EDITOR); // idMemento.putString(IWorkbenchConstants.TAG_ID, editorArray[i] // .getId()); // } // editorArray = type.getDeletedEditors(); // for (int i = 0; i < editorArray.length; i++) // { // EditorDescriptor editor = (EditorDescriptor) editorArray[i]; // if (!editors.contains(editor)) // { // editors.add(editor); // } // IMemento idMemento = editorMemento // .createChild(IWorkbenchConstants.TAG_DELETED_EDITOR); // idMemento.putString(IWorkbenchConstants.TAG_ID, editorArray[i] // .getId()); // } // editorArray = type.getDeclaredDefaultEditors(); // for (int i = 0; i < editorArray.length; i++) // { // EditorDescriptor editor = (EditorDescriptor) editorArray[i]; // if (!editors.contains(editor)) // { // editors.add(editor); // } // IMemento idMemento = editorMemento // .createChild(IWorkbenchConstants.TAG_DEFAULT_EDITOR); // idMemento.putString(IWorkbenchConstants.TAG_ID, editorArray[i] // .getId()); // } // } // Writer writer = null; // try // { // writer = new StringWriter(); // memento.save(writer); // writer.close(); // store.setValue(IPreferenceConstants.RESOURCES, writer.toString()); // } // catch (IOException e) // { // try // { // if (writer != null) // { // writer.close(); // } // } // catch (IOException ex) // { // ex.printStackTrace(); // } // MessageDialog.openError((Shell) null, "Saving Problems", //$NON-NLS-1$ // "Unable to save resource associations."); //$NON-NLS-1$ // return; // } // // memento = XMLMemento.createWriteRoot(IWorkbenchConstants.TAG_EDITORS); // Iterator itr = editors.iterator(); // while (itr.hasNext()) // { // EditorDescriptor editor = (EditorDescriptor) itr.next(); // IMemento editorMemento = memento // .createChild(IWorkbenchConstants.TAG_DESCRIPTOR); // editor.saveValues(editorMemento); // } // writer = null; // try // { // writer = new StringWriter(); // memento.save(writer); // writer.close(); // store.setValue(IPreferenceConstants.EDITORS, writer.toString()); // } // catch (IOException e) // { // try // { // if (writer != null) // { // writer.close(); // } // } // catch (IOException ex) // { // ex.printStackTrace(); // } // MessageDialog.openError((Shell) null, // "Error", "Unable to save resource associations."); //$NON-NLS-1$ //$NON-NLS-2$ // return; // } } void EditorRegistry::SetFileEditorMappings( const QList& newResourceTypes) { typeEditorMappings.Clear(); - for (unsigned int i = 0; i < newResourceTypes.size(); i++) + for (int i = 0; i < newResourceTypes.size(); i++) { FileEditorMapping::Pointer mapping = newResourceTypes[i]; typeEditorMappings.Put(this->MappingKeyFor(mapping), mapping); } //extensionImages = new HashMap(); this->RebuildEditorMap(); //firePropertyChange(PROP_CONTENTS); } void EditorRegistry::SetDefaultEditor(const QString& fileName, const QString& editorId) { EditorDescriptor::Pointer desc = this->FindEditor(editorId).Cast< EditorDescriptor> (); QList mapping = this->GetMappingForFilename( fileName); if (!mapping[0].IsNull()) { mapping[0]->SetDefaultEditor(desc); } if (!mapping[1].IsNull()) { mapping[1]->SetDefaultEditor(desc); } } QList EditorRegistry::SortEditors( const QList& unsortedList) { QList result(unsortedList); std::sort(result.begin(), result.end(), CmpIEditorDescriptor()); return result; } void EditorRegistry::SortInternalEditors() { qSort(sortedEditorsFromPlugins.begin(), sortedEditorsFromPlugins.end(), CmpEditorDescriptor()); } void EditorRegistry::EditorMap::PutDefault(const QString& key, FileEditorMapping::Pointer value) { defaultMap[key] = value; } void EditorRegistry::EditorMap::Put(const QString& key, FileEditorMapping::Pointer value) { QHash::iterator result = defaultMap.find(key); if (result != defaultMap.end()) { map[key] = value; } } FileEditorMapping::Pointer EditorRegistry::EditorMap::Get( const QString& key) { QHash::const_iterator result = map.find(key); if (result == map.end()) { return defaultMap[key]; } return result.value(); } void EditorRegistry::EditorMap::Clear() { defaultMap.clear(); map.clear(); } QList EditorRegistry::EditorMap::AllMappings() { QSet resultSet; QHash::const_iterator iter; for (iter = defaultMap.begin(); iter != defaultMap.end(); ++iter) { resultSet.insert(iter.value()); } for (iter = map.begin(); iter != map.end(); ++iter) { resultSet.insert(iter.value()); } return resultSet.toList(); } QList EditorRegistry::EditorMap::UserMappings() { return map.values(); } bool EditorRegistry::IsSystemInPlaceEditorAvailable(const QString& /*filename*/) { //return ComponentSupport.inPlaceEditorAvailable(filename); return false; } bool EditorRegistry::IsSystemExternalEditorAvailable( const QString& /*filename*/) { // QString::size_type nDot = filename.find_last_of('.'); // if (nDot != QString::npos) // { // QString strName = filename.substr(nDot); // return Program.findProgram(strName) != null; // } return false; } void EditorRegistry::RemoveEditorFromMapping( QHash& map, IEditorDescriptor::Pointer desc) { FileEditorMapping::Pointer mapping; for (QHash::iterator iter = map.begin(); iter != map.end(); ++iter) { mapping = iter.value(); QList editors(mapping->GetEditors()); QList::iterator result = std::find( editors.begin(), editors.end(), desc); if (result != editors.end()) { mapping->RemoveEditor(result->Cast ()); editors.erase(result); } if (editors.empty()) { map.erase(iter); break; } } } IExtensionPoint::Pointer EditorRegistry::GetExtensionPointFilter() { return Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_EDITOR); } QList EditorRegistry::GetUnifiedMappings() { QList standardMappings( dynamic_cast (PlatformUI::GetWorkbench() ->GetEditorRegistry())->GetFileEditorMappings()); QList allMappings(standardMappings); // mock-up content type extensions into IFileEditorMappings // IContentType [] contentTypes = Platform.getContentTypeManager().getAllContentTypes(); // for (int i = 0; i < contentTypes.length; i++) // { // IContentType type = contentTypes[i]; // String [] extensions = type.getFileSpecs(IContentType.FILE_EXTENSION_SPEC); // for (int j = 0; j < extensions.length; j++) // { // String extension = extensions[j]; // boolean found = false; // for (Iterator k = allMappings.iterator(); k.hasNext();) // { // IFileEditorMapping mapping = (IFileEditorMapping) k.next(); // if ("*".equals(mapping.getName()) // && extension.equals(mapping.getExtension())) // { //$NON-NLS-1$ // found = true; // break; // } // } // if (!found) // { // MockMapping mockMapping = new MockMapping(type, "*", extension); //$NON-NLS-1$ // allMappings.add(mockMapping); // } // } // // String [] filenames = type.getFileSpecs(IContentType.FILE_NAME_SPEC); // for (int j = 0; j < filenames.length; j++) // { // String wholename = filenames[j]; // int idx = wholename.indexOf('.'); // String name = idx == -1 ? wholename : wholename.substring(0, idx); // String extension = idx == -1 ? "" : wholename.substring(idx + 1); //$NON-NLS-1$ // // boolean found = false; // for (Iterator k = allMappings.iterator(); k.hasNext();) // { // IFileEditorMapping mapping = (IFileEditorMapping) k.next(); // if (name.equals(mapping.getName()) // && extension.equals(mapping.getExtension())) // { // found = true; // break; // } // } // if (!found) // { // MockMapping mockMapping = new MockMapping(type, name, extension); // allMappings.add(mockMapping); // } // } // } return allMappings; } MockMapping::MockMapping(/*IContentType type,*/const QString& name, const QString& ext) : extension(ext), filename(name) { //this.contentType = type; } IEditorDescriptor::Pointer MockMapping::GetDefaultEditor() { // QList candidates = PlatformUI::GetWorkbench()->GetEditorRegistry() // ->GetEditorsForContentType(contentType); // if (candidates.empty()) // { // return IEditorDescriptor::Pointer(); // } // return candidates[0]; return IEditorDescriptor::Pointer(); } QList MockMapping::GetEditors() const { // QList editorsForContentType = (dynamic_cast(PlatformUI // ::GetWorkbench()->GetEditorRegistry()) // ->GetEditorsForContentType(contentType); // return editorsForContentType; return QList(); } QList MockMapping::GetDeletedEditors() const { return QList(); } -QString MockMapping::GetExtension() +QString MockMapping::GetExtension() const { return extension; } -QString MockMapping::GetLabel() +QString MockMapping::GetLabel() const { return filename + '.' + extension; } -QString MockMapping::GetName() +QString MockMapping::GetName() const { return filename; } bool MockMapping::operator==(const Object* obj) const { if (const MockMapping* other = dynamic_cast(obj)) { if (this == other) { return true; } //MockMapping mapping = (MockMapping) obj; if (!(this->filename == other->filename)) { return false; } if (!(this->extension == other->extension)) { return false; } if (!(this->GetEditors() == other->GetEditors())) { return false; } return this->GetDeletedEditors() == other->GetDeletedEditors(); } return false; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorRegistry.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorRegistry.h index dc6c63de3a..4247640933 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorRegistry.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorRegistry.h @@ -1,764 +1,764 @@ /*=================================================================== 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 BERRYEDITORREGISTRY_H_ #define BERRYEDITORREGISTRY_H_ #include #include "berryIEditorRegistry.h" #include "berryIFileEditorMapping.h" #include "berryEditorDescriptor.h" #include "berryFileEditorMapping.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * * Provides access to the collection of defined editors for resource types. */ class EditorRegistry : public IEditorRegistry { class RelatedRegistry { public: RelatedRegistry(EditorRegistry* editorRegistry); /** * Return the objects related to the type. * * @param type * @return the objects related to the type */ // public: QList GetRelatedObjects(IContentType type) { // IEditorDescriptor[] relatedObjects = (IEditorDescriptor[]) contentTypeToEditorMappings.get(type); // if (relatedObjects == null) { // return EMPTY; // } // return (IEditorDescriptor[]) WorkbenchActivityHelper.restrictArray(relatedObjects); // } /** * Return the objects related to the filename * @param fileName * @return the objects related to the filename */ public: QList GetRelatedObjects( const QString& fileName); private: EditorRegistry* editorRegistry; }; friend class RelatedRegistry; /** * Map of FileEditorMapping (extension to FileEditorMapping) Uses two * java.util.HashMap: one keeps the default which are set by the plugins and * the other keeps the changes made by the user through the preference page. */ class EditorMap { static QHash defaultMap; static QHash map; public: void Clear(); /** * Put a default mapping into the editor map. * * @param key the key to set * @param value the value to associate */ public: static void PutDefault(const QString& key, FileEditorMapping::Pointer value); /** * Put a mapping into the user editor map. * * @param key the key to set * @param value the value to associate */ public: void Put(const QString& key, FileEditorMapping::Pointer value); /** * Return the mapping associated to the key. First searches user * map, and then falls back to the default map if there is no match. May * return null * * @param key * the key to search for * @return the mapping associated to the key or null */ public: FileEditorMapping::Pointer Get(const QString& key); /** * Return all mappings. This will return default mappings overlayed with * user mappings. * * @return the mappings */ public: QList AllMappings(); /** * Return all user mappings. * * @return the mappings */ public: QList UserMappings(); }; struct CmpFileEditorMapping : public std::binary_function { bool operator()(const FileEditorMapping::Pointer& x, const FileEditorMapping::Pointer& y) const { return x->GetLabel() < y->GetLabel(); } }; struct CmpIEditorDescriptor : public std::binary_function { bool operator()(const IEditorDescriptor::Pointer& x, const IEditorDescriptor::Pointer& y) const { return x->GetLabel() < y->GetLabel(); } }; struct CmpEditorDescriptor : public std::binary_function { bool operator()(const EditorDescriptor::Pointer& x, const EditorDescriptor::Pointer& y) const { return x->GetLabel() < y->GetLabel(); } }; //private: Map contentTypeToEditorMappings = new HashMap(); /* * Cached images - these include images from registered editors (via * plugins) and others hence this table is not one to one with the mappings * table. It is in fact a superset of the keys one would find in * typeEditorMappings */ //private: Map extensionImages = new HashMap(); /** * Vector of EditorDescriptor - all the editors loaded from plugin files. * The list is kept in order to be able to show in the editor selection * dialog of the resource associations page. This list is sorted based on the * human readable label of the editor descriptor. * * @see #comparer */ private: QList sortedEditorsFromPlugins; // Map of EditorDescriptor - map editor id to editor. private: QHash mapIDtoEditor; // Map of FileEditorMapping (extension to FileEditorMapping) private: EditorMap typeEditorMappings; /* * Compares the labels from two IEditorDescriptor objects */ //private: // static final Comparator comparer = new Comparator() // { // private Collator collator = Collator.getInstance(); // // public int compare(Object arg0, Object arg1) // { // String s1 = ((IEditorDescriptor) arg0).getLabel(); // String s2 = ((IEditorDescriptor) arg1).getLabel(); // return collator.compare(s1, s2); // } // }; private: RelatedRegistry relatedRegistry; public: static const QString EMPTY_EDITOR_ID; // = "org.blueberry.ui.internal.emptyEditorTab" /** * Return an instance of the receiver. Adds listeners into the extension * registry for dynamic UI purposes. */ public: EditorRegistry(); /** * Add an editor for the given extensions with the specified (possibly null) * extended type. The editor is being registered from a plugin * * @param editor * The description of the editor (as obtained from the plugin * file and built by the registry reader) * @param extensions * Collection of file extensions the editor applies to * @param filenames * Collection of filenames the editor applies to * @param contentTypeVector * @param bDefault * Indicates whether the editor should be made the default editor * and hence appear first inside a FileEditorMapping * * This method is not API and should not be called outside the workbench * code. */ public: void AddEditorFromPlugin(EditorDescriptor::Pointer editor, const QList& extensions, const QList& filenames, const QList& contentTypeVector, bool bDefault); /** * Add external editors to the editor mapping. */ private: void AddExternalEditorsToEditorMap(); /* * (non-Javadoc) Method declared on IEditorRegistry. */ //public: void AddPropertyListener(IPropertyListener l) { // addListenerObject(l); // } /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: IEditorDescriptor::Pointer FindEditor(const QString& id); /** * Fires a property changed event to all registered listeners. * * @param type the type of event * @see IEditorRegistry#PROP_CONTENTS */ // private: void FirePropertyChange(final int type) { // Object[] array = getListeners(); // for (int nX = 0; nX < array.length; nX++) { // final IPropertyListener l = (IPropertyListener) array[nX]; // Platform.run(new SafeRunnable() { // public: void run() { // l.propertyChanged(EditorRegistry.this, type); // } // }); // } // } /* * (non-Javadoc) Method declared on IEditorRegistry. * * @deprecated */ public: IEditorDescriptor::Pointer GetDefaultEditor(); /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: IEditorDescriptor::Pointer GetDefaultEditor(const QString& filename); /** * Return the (approximated) content type for a file with the given name. * * @param filename the filename * @return the content type or null if it could not be determined * @since 3.1 */ // private: IContentType::Pointer GuessAtContentType(const QString& filename) { // return Platform.getContentTypeManager().findContentTypeFor(filename); // } /** * Returns the default file image descriptor. * * @return the image descriptor */ // private: ImageDescriptor GetDefaultImage() { // // @issue what should be the default image? // return WorkbenchImages.getImageDescriptor(ISharedImages.IMG_OBJ_FILE); // } /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: QList GetEditors(const QString& filename); /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: QList GetFileEditorMappings(); /* * (non-Javadoc) Method declared on IEditorRegistry. */ // public: ImageDescriptor GetImageDescriptor(String filename) { // return getImageDescriptor(filename, guessAtContentType(filename)); // } /** * Find the file editor mapping for the file extension. Returns * null if not found. * * @param ext * the file extension * @return the mapping, or null */ private: FileEditorMapping::Pointer GetMappingFor(const QString& ext); /** * Find the file editor mappings for the given filename. *

* Return an array of two FileEditorMapping items, where the first mapping * is for the entire filename, and the second mapping is for the filename's * extension only. These items can be null if no mapping exist on the * filename and/or filename's extension.

* * @param filename the filename * @return the mappings */ private: QList GetMappingForFilename(const QString& filename); /** * Return the editor descriptors pulled from the OS. *

* WARNING! The image described by each editor descriptor is *not* known by * the workbench's graphic registry. Therefore clients must take care to * ensure that if they access any of the images held by these editors that * they also dispose them *

* @return the editor descriptors */ //public: QList GetSortedEditorsFromOS(); /** * Return the editors loaded from plugins. * * @return the sorted array of editors declared in plugins * @see #comparer */ public: QList GetSortedEditorsFromPlugins(); /** * Answer an intial id to editor map. This will create a new map and * populate it with the default system editors. * * @param initialSize * the initial size of the map * @return the new map */ private: void InitialIdToEditorMap(QHash& map); /** * Add the system editors to the provided map. This will always add an * editor with an id of {@link #SYSTEM_EXTERNAL_EDITOR_ID} and may also add * an editor with id of {@link #SYSTEM_INPLACE_EDITOR_ID} if the system * configuration supports it. * * @param map the map to augment */ private: void AddSystemEditors(QHash& map); /** * Initialize the registry state from plugin declarations and preference * overrides. */ private: void InitializeFromStorage(); /** * Set the default editors according to the preference store which can be * overwritten in the file properties.ini. In the form: *

* ext1:id1;ext2:id2;... *

* * @param defaultEditors the default editors to set */ private: void SetProductDefaults(const QString& defaultEditors); /** * Read the editors defined in the preferences store. * * @param editorTable * Editor table to store the editor definitions. * @return true if the table is built succesfully. */ private: bool ReadEditors(QHash& editorTable); /** * Read the file types and associate them to their defined editor(s). * * @param editorTable * The editor table containing the defined editors. * @param reader * Reader containing the preferences content for the resources. * * @throws WorkbenchException */ public: void ReadResources(QHash& editorTable, std::ostream& reader); /** * Determine if the editors list contains the editor descriptor. * * @param editorsArray * The list of editors * @param editorDescriptor * The editor descriptor * @return true if the editors list contains the editor descriptor */ private: bool Contains(const QList& editorsArray, IEditorDescriptor::Pointer editorDescriptor); /** * Creates the reader for the resources preferences defined in the * preference store. * * @param editorTable * The editor table containing the defined editors. * @return true if the resources are read succesfully. */ private: bool ReadResources(QHash& editorTable); /** * Load the serialized resource associations Return true if the operation * was successful, false otherwise */ private: bool LoadAssociations(); /** * Return a friendly version of the given key suitable for use in the editor * map. */ private: QString MappingKeyFor(const QString& type); /** * Return a key that combines the file's name and extension of the given * mapping * * @param mapping the mapping to generate a key for */ private: QString MappingKeyFor(FileEditorMapping::Pointer mapping); /** * Rebuild the editor map */ private: void RebuildEditorMap(); /** * Rebuild the internal editor mapping. */ private: void RebuildInternalEditorMap(); /* * (non-Javadoc) Method declared on IEditorRegistry. */ // public: void RemovePropertyListener(IPropertyListener l) { // removeListenerObject(l); // } /** * Save the registry to the filesystem by serializing the current resource * associations. */ public: void SaveAssociations(); /** * Set the collection of FileEditorMappings. The given collection is * converted into the internal hash table for faster lookup Each mapping * goes from an extension to the collection of editors that work on it. This * operation will rebuild the internal editor mappings. * * @param newResourceTypes * te new file editor mappings. */ public: void SetFileEditorMappings(const QList& newResourceTypes); /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: void SetDefaultEditor(const QString& fileName, const QString& editorId); /** * Alphabetically sort the internal editors. * * @see #comparer */ private: QList SortEditors(const QList& unsortedList); /** * Alphabetically sort the internal editors. * * @see #comparer */ private: void SortInternalEditors(); /* * (non-Javadoc) * * @see org.blueberry.ui.IEditorRegistry#isSystemInPlaceEditorAvailable(String) */ public: bool IsSystemInPlaceEditorAvailable(const QString& filename); /* * (non-Javadoc) * * @see org.blueberry.ui.IEditorRegistry#isSystemExternalEditorAvailable(String) */ public: bool IsSystemExternalEditorAvailable(const QString& filename); /* * (non-Javadoc) * * @see org.blueberry.ui.IEditorRegistry#getSystemExternalEditorImageDescriptor(java.lang.String) */ // public: ImageDescriptor GetSystemExternalEditorImageDescriptor( // const QString& filename) { // Program externalProgram = null; // int extensionIndex = filename.lastIndexOf('.'); // if (extensionIndex >= 0) { // externalProgram = Program.findProgram(filename // .substring(extensionIndex)); // } // if (externalProgram == null) { // return null; // } // // return new ExternalProgramImageDescriptor(externalProgram); // } /** * Removes the entry with the value of the editor descriptor from the given * map. If the descriptor is the last descriptor in a given * FileEditorMapping then the mapping is removed from the map. * * @param map * the map to search * @param desc * the descriptor value to remove */ private: void RemoveEditorFromMapping(QHash& map, IEditorDescriptor::Pointer desc); private: IExtensionPoint::Pointer GetExtensionPointFilter(); /* (non-Javadoc) * @see org.blueberry.ui.IEditorRegistry#getDefaultEditor(java.lang.String, org.blueberry.core.runtime.content.IContentType) */ // public: IEditorDescriptor::Pointer GetDefaultEditor(const QString& fileName, IContentType contentType) { // return getEditorForContentType(fileName, contentType); // } /** * Return the editor for a file with a given content type. * * @param filename the file name * @param contentType the content type * @return the editor for a file with a given content type * @since 3.1 */ private: IEditorDescriptor::Pointer GetEditorForContentType(const QString& filename /*IContentType contentType*/); /* (non-Javadoc) * @see org.blueberry.ui.IEditorRegistry#getEditors(java.lang.String, org.blueberry.core.runtime.content.IContentType) */ // public: QList GetEditors(const QString& fileName, IContentType contentType) { // return findRelatedObjects(contentType, fileName, relatedRegistry); // } /* (non-Javadoc) * @see org.blueberry.ui.IEditorRegistry#getImageDescriptor(java.lang.String, org.blueberry.core.runtime.content.IContentType) */ // public: ImageDescriptor GetImageDescriptor(const QString filename, IContentType contentType) { // if (filename == null) { // return getDefaultImage(); // } // // if (contentType != null) { // IEditorDescriptor desc = getEditorForContentType(filename, contentType); // if (desc != null) { // ImageDescriptor anImage = (ImageDescriptor) extensionImages.get(desc); // if (anImage != null) { // return anImage; // } // anImage = desc.getImageDescriptor(); // extensionImages.put(desc, anImage); // return anImage; // } // } // // Lookup in the cache first... // String key = mappingKeyFor(filename); // ImageDescriptor anImage = (ImageDescriptor) extensionImages.get(key); // if (anImage != null) { // return anImage; // } // // // See if we have a mapping for the filename or extension // FileEditorMapping[] mapping = getMappingForFilename(filename); // for (int i = 0; i < 2; i++) { // if (mapping[i] != null) { // // Lookup in the cache first... // String mappingKey = mappingKeyFor(mapping[i]); // ImageDescriptor mappingImage = (ImageDescriptor) extensionImages // .get(key); // if (mappingImage != null) { // return mappingImage; // } // // Create it and cache it // IEditorDescriptor editor = mapping[i].getDefaultEditor(); // if (editor != null) { // mappingImage = editor.getImageDescriptor(); // extensionImages.put(mappingKey, mappingImage); // return mappingImage; // } // } // } // // // Nothing - time to look externally for the icon // anImage = getSystemExternalEditorImageDescriptor(filename); // if (anImage == null) { // anImage = getDefaultImage(); // } // // for dynamic UI - comment out the next line // //extensionImages.put(key, anImage); // return anImage; // // } /** * Find objects related to the content type. * * This method is temporary and exists only to back us off of the * soon-to-be-removed IContentTypeManager.IRelatedRegistry API. * * @param type * @param fileName * @param registry * @return the related objects */ private: QList FindRelatedObjects(/*IContentType type,*/ const QString& fileName, RelatedRegistry& registry); /** * Return the editors bound to this content type, either directly or indirectly. * * @param type the content type to check * @return the editors * @since 3.1 * * TODO: this should be rolled in with the above findRelatedObjects code */ // public: QList GetEditorsForContentType(IContentType type) { // ArrayList allRelated = new ArrayList(); // if (type == null) { // return new IEditorDescriptor [0]; // } // // Object [] related = relatedRegistry.getRelatedObjects(type); // for (int i = 0; i < related.length; i++) { // // we don't want to return duplicates // if (!allRelated.contains(related[i])) { // // if it's not filtered, add it to the list // if (!WorkbenchActivityHelper.filterItem(related[i])) { // allRelated.add(related[i]); // } // // } // } // // // now add any indirectly related objects, walking up the content type hierarchy // while ((type = type.getBaseType()) != null) { // related = relatedRegistry.getRelatedObjects(type); // for (int i = 0; i < related.length; i++) { // // we don't want to return duplicates // if (!allRelated.contains(related[i])) { // // if it's not filtered, add it to the list // if (!WorkbenchActivityHelper.filterItem(related[i])) { // allRelated.add(related[i]); // } // } // } // } // // return (IEditorDescriptor[]) allRelated.toArray(new IEditorDescriptor[allRelated.size()]); // } /** * Get filemappings for all defined filetypes, including those defined by content type. * * @return the filetypes * @since 3.1 */ public: QList GetUnifiedMappings(); }; class MockMapping : public IFileEditorMapping { //private: IContentType contentType; private: QString extension; private: QString filename; MockMapping(/*IContentType type,*/const QString& name, const QString& ext); public: IEditorDescriptor::Pointer GetDefaultEditor(); public: QList GetEditors() const; public: QList GetDeletedEditors() const; public: - QString GetExtension(); + QString GetExtension() const; // public: ImageDescriptor GetImageDescriptor() { // IEditorDescriptor editor = getDefaultEditor(); // if (editor == null) { // return WorkbenchImages // .getImageDescriptor(ISharedImages.IMG_OBJ_FILE); // } // // return editor.getImageDescriptor(); // } public: - QString GetLabel(); + QString GetLabel() const; public: - QString GetName(); + QString GetName() const; /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public: bool operator==(const Object* obj) const; }; } #endif /*BERRYEDITORREGISTRY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorRegistryReader.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorRegistryReader.cpp index 8e3658c7f5..ff960795ea 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorRegistryReader.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorRegistryReader.cpp @@ -1,115 +1,115 @@ /*=================================================================== 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 "berryEditorRegistryReader.h" #include "berryEditorRegistry.h" #include "berryEditorDescriptor.h" #include "berryWorkbenchRegistryConstants.h" #include "berryPlatformUI.h" #include namespace berry { void EditorRegistryReader::AddEditors(EditorRegistry* registry) { this->editorRegistry = registry; this->ReadRegistry(PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_EDITOR); } bool EditorRegistryReader::ReadElement(const IConfigurationElement::Pointer& element) { if (element->GetName() != WorkbenchRegistryConstants::TAG_EDITOR) { return false; } QString id = element->GetAttribute(WorkbenchRegistryConstants::ATT_ID); if (id.isEmpty()) { this->LogMissingAttribute(element, WorkbenchRegistryConstants::ATT_ID); return true; } EditorDescriptor::Pointer editor(new EditorDescriptor(id, element)); QList extensionsVector; QList filenamesVector; QList contentTypeVector; bool defaultEditor = false; QString value = element->GetAttribute(WorkbenchRegistryConstants::ATT_NAME); // Get editor name (required field). if (value.isEmpty()) { this->LogMissingAttribute(element, WorkbenchRegistryConstants::ATT_NAME); return true; } // Get target extensions (optional field) QString extensionsString = element->GetAttribute(WorkbenchRegistryConstants::ATT_EXTENSIONS); if (!extensionsString.isEmpty()) { QStringList tokens = extensionsString.split(',', QString::SkipEmptyParts); foreach(QString token, tokens) { extensionsVector.push_back(token.trimmed()); } } QString filenamesString = element->GetAttribute(WorkbenchRegistryConstants::ATT_FILENAMES); if (!filenamesString.isEmpty()) { QStringList tokens = filenamesString.split(',', QString::SkipEmptyParts); foreach(QString token, tokens) { filenamesVector.push_back(token.trimmed()); } } QList bindings = element->GetChildren( WorkbenchRegistryConstants::TAG_CONTENT_TYPE_BINDING); - for (unsigned int i = 0; i < bindings.size(); ++i) + for (int i = 0; i < bindings.size(); ++i) { QString contentTypeId = bindings[i]->GetAttribute( WorkbenchRegistryConstants::ATT_CONTENT_TYPE_ID); if (contentTypeId.isEmpty()) { continue; } contentTypeVector.push_back(contentTypeId); } // Is this the default editor? defaultEditor = element->GetAttribute(WorkbenchRegistryConstants::ATT_DEFAULT).compare("true", Qt::CaseInsensitive) == 0; // Add the editor to the manager. editorRegistry->AddEditorFromPlugin(editor, extensionsVector, filenamesVector, contentTypeVector, defaultEditor); return true; } void EditorRegistryReader::ReadElement(EditorRegistry* editorRegistry, const IConfigurationElement::Pointer& element) { this->editorRegistry = editorRegistry; this->ReadElement(element); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorSashContainer.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorSashContainer.cpp index a80bd3cefb..132f5ce9a2 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorSashContainer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorSashContainer.cpp @@ -1,609 +1,609 @@ /*=================================================================== 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 "berryEditorSashContainer.h" #include "berryPresentationSerializer.h" #include "berryWorkbenchConstants.h" #include "berryWorkbenchPlugin.h" #include "berryLayoutTree.h" #include "berryWorkbenchWindowConfigurer.h" #include "berryWorkbenchWindow.h" #include "berryQtDnDControlWidget.h" #include "tweaklets/berryGuiWidgetsTweaklet.h" #include #include namespace berry { const QString EditorSashContainer::DEFAULT_WORKBOOK_ID = "DefaultEditorWorkbook"; void EditorSashContainer::AddChild(const RelationshipInfo& info) { PartSashContainer::AddChild(info); this->UpdateStackButtons(); } void EditorSashContainer::ChildAdded(LayoutPart::Pointer child) { PartSashContainer::ChildAdded(child); if (child.Cast () != 0) { editorWorkbooks.push_back(child.Cast ()); } } void EditorSashContainer::ChildRemoved(LayoutPart::Pointer child) { PartSashContainer::ChildRemoved(child); if (child.Cast () != 0) { editorWorkbooks.removeAll(child.Cast()); if (activeEditorWorkbook == child) { this->SetActiveWorkbook(PartStack::Pointer(0), false); } this->UpdateStackButtons(); } } PartStack::Pointer EditorSashContainer::CreateDefaultWorkbook() { PartStack::Pointer newWorkbook = this->NewEditorWorkbook(); newWorkbook->SetID(DEFAULT_WORKBOOK_ID); this->Add(newWorkbook); return newWorkbook; } void EditorSashContainer::AddDropSupport() { WorkbenchWindowConfigurer::Pointer winConfigurer = page->GetWorkbenchWindow().Cast()->GetWindowConfigurer(); QtDnDControlWidget* dropWidget = static_cast(GetParent()); dropWidget->SetTransferTypes(winConfigurer->GetTransfers()); - dropWidget->AddDropListener(winConfigurer->GetDropTargetListener().GetPointer()); + dropWidget->AddDropListener(winConfigurer->GetDropTargetListener()); } PartStack::Pointer EditorSashContainer::NewEditorWorkbook() { PartStack::Pointer newWorkbook(new PartStack(page, true, PresentationFactoryUtil::ROLE_EDITOR)); QString str; QTextStream buf(&str); buf << newWorkbook->GetClassName() << newWorkbook.GetPointer(); newWorkbook->SetID(str); return newWorkbook; } void* EditorSashContainer::CreateParent(void* parentWidget) { //return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->CreateComposite(parentWidget); return new QtDnDControlWidget(static_cast(parentWidget)); } void EditorSashContainer::DisposeParent() { this->parent = 0; } bool EditorSashContainer::IsActiveWorkbook(PartStack::Pointer workbook) { return activeEditorWorkbook == workbook; } PartStack::Pointer EditorSashContainer::CreateStack() { return this->NewEditorWorkbook(); } void EditorSashContainer::SetVisiblePart( ILayoutContainer::Pointer container, PartPane::Pointer visiblePart) { PartStack::Pointer stack = container.Cast(); if (stack == 0) return; stack->GetContainer().Cast()->SetActiveWorkbook(stack, true); stack->SetSelection(visiblePart); } LayoutPart::Pointer EditorSashContainer::GetVisiblePart( ILayoutContainer::Pointer container) { PartStack::Pointer refPart = container.Cast(); return refPart->GetSelection(); } EditorSashContainer::EditorSashContainer(const QString& editorId, WorkbenchPage* page, void* parent) : PartSashContainer(editorId, page, parent) { this->CreateDefaultWorkbook(); } bool EditorSashContainer::AllowsAdd(LayoutPart::Pointer layoutPart) { return LayoutPart::AllowsAdd(layoutPart); } void EditorSashContainer::AddEditor(PartPane::Pointer pane, PartStack::Pointer stack) { //EditorStack workbook = getActiveWorkbook(); stack->Add(pane); } void EditorSashContainer::UpdateStackButtons() { // // This is applicable only when the new // // min/max behaviour is being used // Perspective persp = getPage().getActivePerspective(); // if (!Perspective.useNewMinMax(persp)) // return; // // // Find the upper Right editor stack // LayoutPart[] stacks = getChildren(); // EditorStack winner = getUpperRightEditorStack(stacks); // // // Now hide the buttons for all but the upper right stack // for (int i = 0; i < stacks.length; i++) // { // if (!(stacks[i] instanceof EditorStack) // ) // continue; // ((EditorStack) stacks[i]).showMinMax(stacks[i] == winner); // } // // // Force the stack's presentation state to match its perspective // persp.refreshEditorAreaVisibility(); } PartStack::Pointer EditorSashContainer::GetUpperRightEditorStack() { return this->GetUpperRightEditorStack(this->GetChildren()); } PartStack::Pointer EditorSashContainer::GetUpperRightEditorStack( const ILayoutContainer::ChildrenType& stacks) { // Find the upper Right editor stack PartStack::Pointer winner; Rectangle winnerRect; for (ILayoutContainer::ChildrenType::const_iterator iter = stacks.begin(); iter != stacks.end(); ++iter) { LayoutPart::Pointer part = *iter; if (part.Cast() == 0) continue; PartStack::Pointer stack = part.Cast(); Rectangle bb = stack->GetBounds(); if (iter == stacks.begin() || bb.y < winnerRect.y || (bb.y == winnerRect.y && bb.x > winnerRect.x)) { winner = stack; winnerRect = bb; } } return winner; } PartStack::Pointer EditorSashContainer::GetActiveWorkbook() { if (activeEditorWorkbook == 0) { if (editorWorkbooks.size() < 1) { this->SetActiveWorkbook(this->CreateDefaultWorkbook(), false); } else { this->SetActiveWorkbook(editorWorkbooks.front(), false); } } return activeEditorWorkbook; } QString EditorSashContainer::GetActiveWorkbookID() { return this->GetActiveWorkbook()->GetID(); } QList EditorSashContainer::GetEditorWorkbooks() { return editorWorkbooks; } std::size_t EditorSashContainer::GetEditorWorkbookCount() { return editorWorkbooks.size(); } void EditorSashContainer::FindSashes(LayoutPart::Pointer pane, PartPane::Sashes& sashes) { //Find the sashes around the current editor and //then the sashes around the editor area. PartSashContainer::FindSashes(pane, sashes); ILayoutContainer::Pointer container = this->GetContainer(); if (container != 0) { container->FindSashes(LayoutPart::Pointer(this), sashes); } } void EditorSashContainer::RemoveAllEditors() { PartStack::Pointer currentWorkbook = this->GetActiveWorkbook(); // Iterate over a copy so the original can be modified. QList workbooks(editorWorkbooks); for (QList::iterator iter = workbooks.begin(); iter != workbooks.end(); ++iter) { PartStack::Pointer workbook = *iter; QList children = workbook->GetChildren(); for (QList::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { workbook->Remove(*childIter); } if (workbook != currentWorkbook) { this->Remove(workbook); workbook->Dispose(); } } } void EditorSashContainer::RemoveEditor(PartPane::Pointer pane) { PartStack::Pointer workbook = pane->GetContainer().Cast(); if (workbook == 0) { return; } workbook->Remove(pane); // remove the editor workbook if empty if (workbook->GetItemCount() < 1 /* && editorWorkbooks.size() > 1*/) { // // If the user closes the last editor and the editor area // // is maximized, restore it // Perspective persp = getPage().getActivePerspective(); // if (Perspective.useNewMinMax(persp)) // { // if (persp.getPresentation().getMaximizedStack() instanceof EditorStack) // persp.getPresentation().getMaximizedStack(). // setState(IStackPresentationSite.STATE_RESTORED); // } this->Remove(workbook); workbook->Dispose(); } } bool EditorSashContainer::RestoreState(IMemento::Pointer memento) { //TODO EditorSashContainer restore state // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.RootLayoutContainer_problemsRestoringPerspective, 0); bool result = true; // Remove the default editor workbook that is // initialy created with the editor area. // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void runWithException() throws Throwable // { PartStack::Pointer defaultWorkbook; for (ILayoutContainer::ChildrenType::iterator i = children.begin(); i != children.end(); ++i) { LayoutPart::Pointer child = *i; if (child->GetID() == DEFAULT_WORKBOOK_ID) { defaultWorkbook = child.Cast(); if (defaultWorkbook->GetItemCount() > 0) { defaultWorkbook = 0; } } } if (defaultWorkbook) { Remove(defaultWorkbook); } // }} // ); // Restore the relationship/layout QList infos(memento->GetChildren(WorkbenchConstants::TAG_INFO)); QHash mapIDtoPart; - for (std::size_t i = 0; i < infos.size(); i++) + for (int i = 0; i < infos.size(); i++) { // Get the info details. IMemento::Pointer childMem = infos[i]; QString partID; childMem->GetString(WorkbenchConstants::TAG_PART, partID); QString relativeID; childMem->GetString(WorkbenchConstants::TAG_RELATIVE, relativeID); int relationship = 0; int left = 0, right = 0; if (!relativeID.isEmpty()) { childMem->GetInteger(WorkbenchConstants::TAG_RELATIONSHIP, relationship); childMem->GetInteger(WorkbenchConstants::TAG_RATIO_LEFT, left); childMem->GetInteger(WorkbenchConstants::TAG_RATIO_RIGHT, right); } PartStack::Pointer workbook; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void runWithException() throws Throwable // { // Create the part. workbook = NewEditorWorkbook(); workbook->SetID(partID); // 1FUN70C: ITPUI:WIN - Shouldn't set Container when not active workbook->SetContainer(ILayoutContainer::Pointer(this)); // }} // ); IMemento::Pointer workbookMemento = childMem->GetChild( WorkbenchConstants::TAG_FOLDER); if (workbookMemento) { //result.add(workbook[0].restoreState(workbookMemento)); result &= workbook->RestoreState(workbookMemento); } const int myLeft = left, myRight = right, myRelationship = relationship; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void runWithException() throws Throwable // { // Add the part to the layout if (relativeID.isEmpty()) { Add(workbook); } else { LayoutPart::Pointer refPart = mapIDtoPart[relativeID]; if (refPart) { Add(workbook, myRelationship, myLeft, myRight, refPart); } else { WorkbenchPlugin::Log("Unable to find part for ID: " + relativeID); } } // }} // ); mapIDtoPart[partID] = workbook; } return result; } bool EditorSashContainer::SaveState(IMemento::Pointer memento) { QList relationships(ComputeRelation()); // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.RootLayoutContainer_problemsSavingPerspective, 0); bool result = true; - for (std::size_t i = 0; i < relationships.size(); i++) + for (int i = 0; i < relationships.size(); i++) { // Save the relationship info .. // private LayoutPart part; // private int relationship; // private float ratio; // private LayoutPart relative; const RelationshipInfo& info = relationships[i]; IMemento::Pointer childMem = memento->CreateChild( WorkbenchConstants::TAG_INFO); childMem->PutString(WorkbenchConstants::TAG_PART, info.part->GetID()); PartStack::Pointer stack = info.part.Cast(); if (stack) { IMemento::Pointer folderMem = childMem->CreateChild( WorkbenchConstants::TAG_FOLDER); //result.add(stack.saveState(folderMem)); result &= stack->SaveState(folderMem); } if (info.relative != 0) { childMem->PutString(WorkbenchConstants::TAG_RELATIVE, info.relative->GetID()); childMem->PutInteger(WorkbenchConstants::TAG_RELATIONSHIP, info.relationship); childMem->PutInteger(WorkbenchConstants::TAG_RATIO_LEFT, info.left); childMem->PutInteger(WorkbenchConstants::TAG_RATIO_RIGHT, info.right); } } return result; } void EditorSashContainer::SetActiveWorkbook(PartStack::Pointer newWorkbook, bool hasFocus) { if (newWorkbook != 0) { if (std::find(editorWorkbooks.begin(), editorWorkbooks.end(), newWorkbook) == editorWorkbooks.end()) { return; } } PartStack::Pointer oldWorkbook = activeEditorWorkbook; activeEditorWorkbook = newWorkbook; if (oldWorkbook != 0 && oldWorkbook != newWorkbook) { oldWorkbook->SetActive(StackPresentation::AS_INACTIVE); } if (newWorkbook != 0) { if (hasFocus) { newWorkbook->SetActive(StackPresentation::AS_ACTIVE_FOCUS); } else { newWorkbook->SetActive(StackPresentation::AS_ACTIVE_NOFOCUS); } } this->UpdateTabList(); } void EditorSashContainer::SetActiveWorkbookFromID(const QString& id) { for (QList::iterator iter = editorWorkbooks.begin(); iter != editorWorkbooks.end(); ++iter) { PartStack::Pointer workbook = *iter; if (workbook->GetID() == id) { this->SetActiveWorkbook(workbook, false); } } } PartStack::Pointer EditorSashContainer::GetWorkbookFromID(const QString& id) { for (QList::iterator iter = editorWorkbooks.begin(); iter != editorWorkbooks.end(); ++iter) { PartStack::Pointer workbook = *iter; if (workbook->GetID() == id) { return workbook; } } return PartStack::Pointer(0); } void EditorSashContainer::UpdateTabList() { void* parent = this->GetParent(); if (parent != 0) { // parent may be 0 on startup PartStack::Pointer wb(this->GetActiveWorkbook()); //TODO EditorSashContainer update tab list // if (wb == 0) // { // parent.setTabList(new Control[0]); // } // else // { // parent.setTabList(wb.getTabList()); // } } } void EditorSashContainer::CreateControl(void* parent) { PartSashContainer::CreateControl(parent); ///let the user drop files/editor input on the editor area this->AddDropSupport(); } bool EditorSashContainer::IsCompressible() { //Added for bug 19524 return true; } bool EditorSashContainer::IsStackType(ILayoutContainer::Pointer toTest) { if (toTest.Cast() == 0) return false; return (toTest.Cast ()->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR); } bool EditorSashContainer::IsPaneType(LayoutPart::Pointer toTest) { if (toTest.Cast() == 0) return false; return (toTest.Cast ()->GetPartReference().Cast () != 0); } bool EditorSashContainer::RestorePresentationState(IMemento::Pointer /*areaMem*/) { QList workbooks = this->GetEditorWorkbooks(); for (QList::iterator iter = workbooks.begin(); iter != workbooks.end(); ++iter) { PartStack::Pointer workbook = *iter; IMemento::Pointer memento = workbook->GetSavedPresentationState(); if (memento == 0) { continue; } QList parts = workbook->GetPresentableParts(); PresentationSerializer serializer(parts); //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // public void runWithException() throws Throwable // { workbook->GetPresentation()->RestoreState(&serializer, memento); // }} // ); } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", 0); //$NON-NLS-1$ return true; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryElementReference.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryElementReference.cpp index c21d350e8f..6339b4326e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryElementReference.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryElementReference.cpp @@ -1,45 +1,50 @@ /*=================================================================== 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 "berryElementReference.h" #include namespace berry { ElementReference::ElementReference(const QString& id, const SmartPointer& adapt, const QHash& parms) : commandId(id), element(adapt), parameters(parms) { } SmartPointer ElementReference::GetElement() const { return element; } QString ElementReference::GetCommandId() const { return commandId; } QHash ElementReference::GetParameters() const { return parameters; } +void ElementReference::AddParameter(const QString &name, const Object::Pointer &value) +{ + parameters.insert(name, value); +} + } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryElementReference.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryElementReference.h index bb9bdad509..effd7d51cb 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryElementReference.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryElementReference.h @@ -1,71 +1,73 @@ /*=================================================================== 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 BERRYELEMENTREFERENCE_H #define BERRYELEMENTREFERENCE_H #include namespace berry { /** * Our element reference that is used during element * registration/unregistration. */ class ElementReference : public IElementReference { private: QString commandId; SmartPointer element; QHash parameters; public: /** * Construct the reference. * * @param id * command id. Must not be null. * @param adapt * the element. Must not be null. * @param parms. * parameters used for filtering. Must not be null. */ ElementReference(const QString& id, const SmartPointer& adapt, const QHash& parms); /* * @see IElementReference#GetElement() */ SmartPointer GetElement() const; /* * @see IElementReference#GetCommandId() */ QString GetCommandId() const; /* * @see IElementReference#GetParameters() */ QHash GetParameters() const; + + void AddParameter(const QString& name, const Object::Pointer& value); }; } #endif // BERRYELEMENTREFERENCE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.cpp index beada5ae82..24942ac9bb 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.cpp @@ -1,237 +1,237 @@ /*=================================================================== 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 "berryEvaluationAuthority.h" #include "berryExpressionInfo.h" #include "berryExpression.h" #include "berryEvaluationReference.h" #include "berryWorkbenchPlugin.h" #include #include #include #include #include namespace berry { const QString EvaluationAuthority::COMPONENT = "EVALUATION"; QStringList EvaluationAuthority::GetNames(const SmartPointer& ref) const { ExpressionInfo info; ref->GetExpression()->CollectExpressionInfo(&info); QSet allNames = info.GetAccessedVariableNames(); if (info.HasDefaultVariableAccess()) { allNames << ISources::ACTIVE_CURRENT_SELECTION_NAME(); } allNames.unite(info.GetAccessedPropertyNames()); return allNames.toList(); } void EvaluationAuthority::RefsWithSameExpression(const QList >& refs) { int k = 0; while (k < refs.size() && !refs[k]->IsPostingChanges()) { k++; } if (k >= refs.size()) { return; } EvaluationReference::Pointer ref = refs[k]; bool oldValue = Evaluate(ref); ref->ClearResult(); const bool newValue = Evaluate(ref); if (oldValue != newValue) { FirePropertyChange(ref, ValueOf(oldValue), ValueOf(newValue)); } for (k++; k < refs.size(); k++) { ref = refs[k]; // this is not as expensive as it looks if (ref->IsPostingChanges()) { oldValue = Evaluate(ref); if (oldValue != newValue) { ref->SetResult(newValue); FirePropertyChange(ref, ValueOf(oldValue), ValueOf(newValue)); } } } } -void EvaluationAuthority::StartSourceChange(const QStringList& sourceNames) +void EvaluationAuthority::StartSourceChange(const QStringList& /*sourceNames*/) { notifying++; if (notifying == 1) { FireServiceChange(IEvaluationService::PROP_NOTIFYING, ValueOf(false), ValueOf(true)); } } -void EvaluationAuthority::EndSourceChange(const QStringList& sourceNames) +void EvaluationAuthority::EndSourceChange(const QStringList& /*sourceNames*/) { if (notifying == 1) { FireServiceChange(IEvaluationService::PROP_NOTIFYING, ValueOf(true), ValueOf(false)); } notifying--; } void EvaluationAuthority::FirePropertyChange(const SmartPointer& ref, Object::Pointer oldValue, Object::Pointer newValue) { PropertyChangeEvent::Pointer event(new PropertyChangeEvent(ref, ref->GetProperty(), oldValue, newValue)); ref->GetListener()->PropertyChange(event); } void EvaluationAuthority::FireServiceChange(const QString& property, Object::Pointer oldValue, Object::Pointer newValue) { PropertyChangeEvent::Pointer event( new PropertyChangeEvent(Object::Pointer(this), property, oldValue, newValue)); serviceListeners.propertyChange(event); } void EvaluationAuthority::ServiceChangeException(const std::exception &exc) { WorkbenchPlugin::Log(exc.what()); } Object::Pointer EvaluationAuthority::ValueOf(bool result) { return ObjectBool::Pointer(new ObjectBool(result)); } -void EvaluationAuthority::SourceChanged(int sourcePriority) +void EvaluationAuthority::SourceChanged(int /*sourcePriority*/) { // no-op, we want the other one } void EvaluationAuthority::SourceChanged(const QStringList& sourceNames) { struct SourceChangeScope { EvaluationAuthority* const ea; const QStringList& sourceNames; SourceChangeScope(EvaluationAuthority* ea, const QStringList& sourceNames) : ea(ea), sourceNames(sourceNames) { ea->StartSourceChange(sourceNames); } ~SourceChangeScope() { ea->EndSourceChange(sourceNames); } }; SourceChangeScope(this, sourceNames); // evaluations to recompute for (int i = 0; i < sourceNames.size(); i++) { if (cachesBySourceName.contains(sourceNames[i])) { const ExprToEvalsMapType& cachesByExpression = cachesBySourceName[sourceNames[i]]; QList > expressionCaches = cachesByExpression.values(); for (int j = 0; j < expressionCaches.size(); j++) { if (!(expressionCaches[j].isEmpty())) { QList refs = expressionCaches[j].toList(); RefsWithSameExpression(refs); } } } } } EvaluationAuthority::EvaluationAuthority() : serviceExceptionHandler(this, &EvaluationAuthority::ServiceChangeException), notifying(0) { serviceListeners.propertyChange.SetExceptionHandler(serviceExceptionHandler); } -SmartPointer EvaluationAuthority::GetActiveShell() const +SmartPointer EvaluationAuthority::GetActiveShell() const { - return GetVariable(ISources::ACTIVE_SHELL_NAME()).Cast(); + return GetVariable(ISources::ACTIVE_SHELL_NAME()).Cast(); } void EvaluationAuthority::AddEvaluationListener(const SmartPointer& ref) { // we update the source priority bucket sort of activations. QStringList sourceNames = GetNames(ref); for (int i = 0; i < sourceNames.size(); i++) { ExprToEvalsMapType& cachesByExpression = cachesBySourceName[sourceNames[i]]; const Expression::Pointer expression = ref->GetExpression(); cachesByExpression[expression].insert(ref.Cast()); } bool result = Evaluate(ref); FirePropertyChange(ref, Object::Pointer(0), ValueOf(result)); } void EvaluationAuthority::RemoveEvaluationListener(const SmartPointer& ref) { // Next we update the source priority bucket sort of activations. QStringList sourceNames = GetNames(ref); for (int i = 0; i < sourceNames.size(); i++) { if (cachesBySourceName.contains(sourceNames[i])) { ExprToEvalsMapType& cachesByExpression = cachesBySourceName[sourceNames[i]]; if (cachesByExpression.contains(ref->GetExpression())) { QSet& caches = cachesByExpression[ref->GetExpression()]; caches.remove(ref.Cast()); if (caches.isEmpty()) { cachesByExpression.remove(ref->GetExpression()); } } if (cachesByExpression.isEmpty()) { cachesBySourceName.remove(sourceNames[i]); } } } bool result = Evaluate(ref); FirePropertyChange(ref, ValueOf(result), Object::Pointer(0)); } void EvaluationAuthority::AddServiceListener(IPropertyChangeListener* listener) { serviceListeners.AddListener(listener); } void EvaluationAuthority::RemoveServiceListener(IPropertyChangeListener* listener) { serviceListeners.RemoveListener(listener); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.h index e5ca3e8845..eeb0f65190 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.h @@ -1,140 +1,140 @@ /*=================================================================== 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 BERRYEVALUATIONAUTHORITY_H #define BERRYEVALUATIONAUTHORITY_H #include "berryExpressionAuthority.h" #include #include namespace berry { struct IEvaluationReference; class EvaluationReference; class Expression; class Shell; class EvaluationAuthority : public ExpressionAuthority { public: berryObjectMacro(berry::EvaluationAuthority) private: static const QString COMPONENT; typedef QHash, QSet > > ExprToEvalsMapType; /** * A bucket sort of the evaluation references based on source priority. Each * reference will appear only once per set, but may appear in multiple sets. * If no references are defined for a particular priority level, then the * array at that index will only contain null. */ QHash cachesBySourceName; IPropertyChangeListener::Events serviceListeners; MessageExceptionHandler serviceExceptionHandler; int notifying; // private final Map cachesByExpression = new HashMap(); QStringList GetNames(const SmartPointer& ref) const; /** * This will evaluate all refs with the same expression. * * @param refs */ void RefsWithSameExpression(const QList >& refs); /** * @param sourceNames */ void StartSourceChange(const QStringList& sourceNames); /** * @param sourceNames */ void EndSourceChange(const QStringList& sourceNames); /** * @param ref * @param oldValue * @param newValue */ void FirePropertyChange(const SmartPointer& ref, Object::Pointer oldValue, Object::Pointer newValue); void FireServiceChange(const QString& property, Object::Pointer oldValue, Object::Pointer newValue); void ServiceChangeException(const std::exception& exc); Object::Pointer ValueOf(bool result); protected: /** * Returns the currently active shell. * * @return The currently active shell; may be null. */ - SmartPointer GetActiveShell() const; + SmartPointer GetActiveShell() const; public: EvaluationAuthority(); /* * @see ExpressionAuthority#SourceChanged(int) */ void SourceChanged(int sourcePriority); /* * @see ExpressionAuthority#SourceChanged(QString) */ void SourceChanged(const QStringList& sourceNames); using ExpressionAuthority::SourceChanged; void AddEvaluationListener(const SmartPointer& ref); /** * @param ref */ void RemoveEvaluationListener(const SmartPointer& ref); /** * @param listener */ void AddServiceListener(IPropertyChangeListener* listener); /** * @param listener */ void RemoveServiceListener(IPropertyChangeListener* listener); }; } #endif // BERRYEVALUATIONAUTHORITY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationResultCache.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationResultCache.cpp index 7adc532057..d230e425e2 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationResultCache.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationResultCache.cpp @@ -1,94 +1,94 @@ /*=================================================================== 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 "berryEvaluationResultCache.h" #include "berrySourcePriorityNameMapping.h" #include "berryEvaluationResult.h" #include namespace berry { EvaluationResultCache::EvaluationResultCache(const SmartPointer& expression) : expression(expression), sourcePriority(SourcePriorityNameMapping::ComputeSourcePriority(expression)) { } EvaluationResultCache::~EvaluationResultCache() { } void EvaluationResultCache::ClearResult() { evaluationResult = 0; } bool EvaluationResultCache::Evaluate(IEvaluationContext* context) const { if (expression.IsNull()) { return true; } if (evaluationResult.IsNull()) { try { evaluationResult = expression->Evaluate(context); } - catch (const CoreException& e) + catch (const CoreException& /*e*/) { /* * Swallow the exception. It simply means the variable is not * valid it some (most frequently, that the value is null). This * kind of information is not really useful to us, so we can * just treat it as null. */ evaluationResult = EvaluationResult::FALSE_EVAL; return false; } } // return true if the result is FALSE or NOT_LOADED return evaluationResult != EvaluationResult::FALSE_EVAL; } SmartPointer EvaluationResultCache::GetExpression() const { return expression; } int EvaluationResultCache::GetSourcePriority() const { return sourcePriority; } void EvaluationResultCache::SetResult(bool result) { if (result) { evaluationResult = EvaluationResult::TRUE_EVAL; } else { evaluationResult = EvaluationResult::FALSE_EVAL; } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationService.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationService.cpp index d018d4c88a..75cbd780b1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationService.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationService.cpp @@ -1,105 +1,107 @@ /*=================================================================== 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 "berryEvaluationService.h" #include "berryEvaluationReference.h" #include "berryEvaluationAuthority.h" +#include "berryExpression.h" #include #include namespace berry { EvaluationService::EvaluationService() + : evaluationAuthority(new EvaluationAuthority()) { - evaluationAuthority = new EvaluationAuthority(); + evaluationAuthority->Register(); } EvaluationService::~EvaluationService() { this->Dispose(); } IEvaluationReference::Pointer EvaluationService::AddEvaluationListener(const SmartPointer& expression, IPropertyChangeListener* listener, const QString& property) { IEvaluationReference::Pointer expressionReference(new EvaluationReference( expression, listener, property)); evaluationAuthority->AddEvaluationListener(expressionReference); return expressionReference; } void EvaluationService::AddEvaluationReference(const SmartPointer& ref) { QString msg("Invalid type: "); msg.append(ref->GetClassName()); Q_ASSERT_X(ref.Cast(), "AddEvaluationReference", qPrintable(msg)); evaluationAuthority->AddEvaluationListener(ref); } void EvaluationService::RemoveEvaluationListener(const SmartPointer& ref) { evaluationAuthority->RemoveEvaluationListener(ref); } -void EvaluationService::AddSourceProvider(SmartPointer provider) +void EvaluationService::AddSourceProvider(const SmartPointer& provider) { evaluationAuthority->AddSourceProvider(provider); } -void EvaluationService::RemoveSourceProvider(SmartPointer provider) +void EvaluationService::RemoveSourceProvider(const SmartPointer& provider) { evaluationAuthority->RemoveSourceProvider(provider); } void EvaluationService::Dispose() { evaluationAuthority->Dispose(); } SmartPointer EvaluationService::GetCurrentState() const { return evaluationAuthority->GetCurrentState(); } void EvaluationService::AddServiceListener(IPropertyChangeListener* listener) { evaluationAuthority->AddServiceListener(listener); } void EvaluationService::RemoveServiceListener(IPropertyChangeListener* listener) { evaluationAuthority->RemoveServiceListener(listener); } void EvaluationService::RequestEvaluation(const QString& propertyName) { QStringList propertyNames; propertyNames.push_back(propertyName); evaluationAuthority->SourceChanged(propertyNames); } //void EvaluationService::UpdateShellKludge() //{ // evaluationAuthority->UpdateShellKludge(); //} } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationService.h index 1b53c87792..d2b338b2b0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationService.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationService.h @@ -1,100 +1,100 @@ /*=================================================================== 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 BERRYEVALUATIONSERVICE_H #define BERRYEVALUATIONSERVICE_H #include namespace berry { class EvaluationAuthority; class EvaluationService : public IEvaluationService { private: - SmartPointer evaluationAuthority; + QScopedPointer evaluationAuthority; public: berryObjectMacro(berry::EvaluationService) EvaluationService(); ~EvaluationService(); /* * @see IEvaluationService#AddEvaluationListener(Expression, IPropertyChangeListener, QString) */ SmartPointer AddEvaluationListener(const SmartPointer& expression, IPropertyChangeListener* listener, const QString& property); /* * @see IEvaluationService#AddEvaluationReference(IEvaluationReference) */ void AddEvaluationReference(const SmartPointer& ref); /* * @see IEvaluationService#RemoveEvaluationListener(IEvaluationReference) */ void RemoveEvaluationListener(const SmartPointer& ref); /* * @see IServiceWithSources#AddSourceProvider(ISourceProvider) */ - void AddSourceProvider(SmartPointer provider); + void AddSourceProvider(const SmartPointer& provider); /* * @see IServiceWithSources#RemoveSourceProvider(ISourceProvider) */ - void RemoveSourceProvider(SmartPointer provider); + void RemoveSourceProvider(const SmartPointer& provider); /* * @see IDisposable#Dispose() */ void Dispose(); /* * @see IEvaluationService#GetCurrentState() */ SmartPointer GetCurrentState() const; /* * @see IEvaluationService#AddServiceListener(IPropertyChangeListener) */ void AddServiceListener(IPropertyChangeListener *listener); /* * @see IEvaluationService#removeServiceListener(IPropertyChangeListener) */ void RemoveServiceListener(IPropertyChangeListener* listener); /* * @see IEvaluationService#RequestEvaluation(QString) */ void RequestEvaluation(const QString& propertyName); //void UpdateShellKludge(); }; } #endif // BERRYEVALUATIONSERVICE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryExpressionAuthority.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryExpressionAuthority.cpp index 96a3c37b80..b67f1b5835 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryExpressionAuthority.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryExpressionAuthority.cpp @@ -1,248 +1,248 @@ /*=================================================================== 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 "berryExpressionAuthority.h" #include #include "berryEvaluationContext.h" #include "berryIEvaluationResultCache.h" #include #include #include namespace berry { void ExpressionAuthority::SourceChanged(int sourcePriority, const QStringList& sourceNames) { SourceChanged(sourcePriority); SourceChanged(sourceNames); } ExpressionAuthority::ExpressionAuthority() : context(new EvaluationContext(0, Object::Pointer(this))) { // break smart-pointer self-cycle this->UnRegister(false); context->SetAllowPluginActivation(true); //context->AddVariable("org.blueberry.core.runtime.Platform", Platform.class); } bool ExpressionAuthority::Evaluate(const QList >& collection) const { foreach (IEvaluationResultCache::Pointer cache, collection) { if (Evaluate(cache)) { return true; } } return false; } bool ExpressionAuthority::Evaluate(const SmartPointer& expression) const { IEvaluationContext::Pointer contextWithDefaultVariable = GetCurrentState(); return expression->Evaluate(contextWithDefaultVariable.GetPointer()); } -Object::Pointer ExpressionAuthority::GetVariable(const QString& name) const +Object::ConstPointer ExpressionAuthority::GetVariable(const QString& name) const { return context->GetVariable(name); } -void ExpressionAuthority::ChangeVariable(const QString& name, const Object::Pointer& value) +void ExpressionAuthority::ChangeVariable(const QString& name, const Object::ConstPointer& value) { if (value.IsNull()) { context->RemoveVariable(name); } else { context->AddVariable(name, value); } } -void ExpressionAuthority::SourceChanged(const QStringList& sourceNames) +void ExpressionAuthority::SourceChanged(const QStringList& /*sourceNames*/) { // this is a no-op, since we're late in the game } void ExpressionAuthority::UpdateCurrentState() { foreach (ISourceProvider::Pointer provider, providers) { ISourceProvider::StateMapType currentState = provider->GetCurrentState(); - QHashIterator variableItr(currentState); + QHashIterator variableItr(currentState); while (variableItr.hasNext()) { variableItr.next(); const QString variableName = variableItr.key(); - const Object::Pointer variableValue = variableItr.value(); + const Object::ConstPointer variableValue = variableItr.value(); /* * Bug 84056. If we update the active workbench window, then we * risk falling back to that shell when the active shell has * registered as "none". */ if (!variableName.isNull() && ISources::ACTIVE_WORKBENCH_WINDOW_SHELL_NAME() != variableName) { ChangeVariable(variableName, variableValue); } } } } -void ExpressionAuthority::UpdateEvaluationContext(const QString& name, const Object::Pointer& value) +void ExpressionAuthority::UpdateEvaluationContext(const QString& name, const Object::ConstPointer& value) { if (!name.isNull()) { ChangeVariable(name, value); } } void ExpressionAuthority::AddSourceProvider(const SmartPointer& provider) { provider->AddSourceProviderListener(this); providers.push_back(provider); // Update the current state. ISourceProvider::StateMapType currentState = provider->GetCurrentState(); - QHashIterator variableItr(currentState); + QHashIterator variableItr(currentState); while (variableItr.hasNext()) { variableItr.next(); const QString variableName = variableItr.key(); - const Object::Pointer variableValue = variableItr.value(); + const Object::ConstPointer variableValue = variableItr.value(); /* * Bug 84056. If we update the active workbench window, then we risk * falling back to that shell when the active shell has registered * as "none". */ if (!variableName.isNull() && ISources::ACTIVE_WORKBENCH_WINDOW_SHELL_NAME() != variableName) { ChangeVariable(variableName, variableValue); } } SourceChanged(0, currentState); } ExpressionAuthority::~ExpressionAuthority() { this->Dispose(); } void ExpressionAuthority::Dispose() { foreach (ISourceProvider::Pointer provider, providers) { provider->RemoveSourceProviderListener(this); } providers.clear(); if (context.IsNotNull()) { // prevent double delete this->Register(); context = 0; //this->UnRegister(false); } } SmartPointer ExpressionAuthority::GetCurrentState() const { if (currentState.IsNull()) { - const Object::Pointer defaultVariable = + const Object::ConstPointer defaultVariable = context->GetVariable(ISources::ACTIVE_CURRENT_SELECTION_NAME()); IEvaluationContext::Pointer contextWithDefaultVariable; - if (IStructuredSelection::Pointer selection = defaultVariable.Cast()) + if (IStructuredSelection::ConstPointer selection = defaultVariable.Cast()) { contextWithDefaultVariable = new EvaluationContext(context.GetPointer(), selection->ToVector()); } - else if (defaultVariable.Cast() && - !defaultVariable.Cast()->IsEmpty()) + else if (defaultVariable.Cast() && + !defaultVariable.Cast()->IsEmpty()) { - ObjectList::Pointer defaultObj(new ObjectList()); + ObjectList::Pointer defaultObj(new ObjectList()); defaultObj->push_back(defaultVariable); contextWithDefaultVariable = new EvaluationContext(context.GetPointer(), defaultObj); } else { - ObjectList::Pointer defaultObj(new ObjectList()); + ObjectList::Pointer defaultObj(new ObjectList()); contextWithDefaultVariable = new EvaluationContext(context.GetPointer(), defaultObj); } currentState = contextWithDefaultVariable; } return currentState; } void ExpressionAuthority::RemoveSourceProvider(const SmartPointer& provider) { provider->RemoveSourceProviderListener(this); providers.removeAll(provider); ISourceProvider::StateMapType currentState = provider->GetCurrentState(); - QHashIterator variableItr(currentState); + QHashIterator variableItr(currentState); while (variableItr.hasNext()) { variableItr.next(); const QString variableName = variableItr.key(); ChangeVariable(variableName, Object::Pointer(0)); } } void ExpressionAuthority::SourceChanged(int sourcePriority, - const QHash &sourceValuesByName) + const QHash &sourceValuesByName) { // If the selection has changed, invalidate the current state. if (sourceValuesByName.contains(ISources::ACTIVE_CURRENT_SELECTION_NAME())) { currentState = 0; } - QHashIterator entryItr(sourceValuesByName); + QHashIterator entryItr(sourceValuesByName); while (entryItr.hasNext()) { entryItr.next(); const QString sourceName = entryItr.key(); - const Object::Pointer sourceValue = entryItr.value(); + const Object::ConstPointer sourceValue = entryItr.value(); UpdateEvaluationContext(sourceName, sourceValue); } SourceChanged(sourcePriority, sourceValuesByName.keys()); } void ExpressionAuthority::SourceChanged(int sourcePriority, const QString &sourceName, - Object::Pointer sourceValue) + Object::ConstPointer sourceValue) { // If the selection has changed, invalidate the current state. if (ISources::ACTIVE_CURRENT_SELECTION_NAME() == sourceName) { currentState = 0; } UpdateEvaluationContext(sourceName, sourceValue); SourceChanged(sourcePriority, QStringList(sourceName)); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryExpressionAuthority.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryExpressionAuthority.h index e3f65eab41..67ff3a76e9 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryExpressionAuthority.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryExpressionAuthority.h @@ -1,223 +1,223 @@ /*=================================================================== 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 BERRYEXPRESSIONAUTHORITY_H #define BERRYEXPRESSIONAUTHORITY_H #include namespace berry { struct IEvaluationContext; struct IEvaluationResultCache; struct ISourceProvider; /** *

* Provides common functionality for evaluating expressions and listening to * {@link ISourceProvider} (i.e., the common event framework for commands). *

*

* This class is not intended for use outside of the * org.eclipse.ui.qt plug-in. *

* * @see ISourceProvider * @see ISources * @see Expression * @see IEvaluationContext */ -class ExpressionAuthority : public ISourceProviderListener +class ExpressionAuthority : public Object, private ISourceProviderListener { public: berryObjectMacro(berry::ExpressionAuthority) private: /** * The evaluation context instance to use when evaluating expression. This * context is shared, and so all calls into sourceChanged * must happen on the event thread. */ SmartPointer context; /** * The current state of this authority. This is a child of the * {@link #context} that has been given the selection as the default * variable. This value is cleared to null whenever the * selection changes. */ mutable SmartPointer currentState; /** * The collection of source providers used by this authority. This * collection is consulted whenever a contribution is made. This collection * only contains instances of ISourceProvider. */ QList > providers; protected: /** * Constructs a new instance of ExpressionAuthority. */ ExpressionAuthority(); /** * Returns whether at least one of the IEvaluationResultCache * instances in collection evaluates to true. * * @param collection * The evaluation result caches to check; must not be * null, but may be empty. * @return true if there is at least one expression that * evaluates to true; false * otherwise. */ bool Evaluate(const QList >& collection) const; /** * Returns whether the IEvaluationResultCache evaluates to * true. * * @param expression * The evaluation result cache to check; must not be * null. * @return true if the expression evaluates to * true; false otherwise. */ bool Evaluate(const SmartPointer& expression) const; /** * Returns the variable of the given name. * * @param name * The name of the variable to get; must not be null. * @return The variable of the given name; null if none. */ - Object::Pointer GetVariable(const QString& name) const; + Object::ConstPointer GetVariable(const QString& name) const; /** * Changes the variable of the given name. If the value is * null, then the variable is removed. * * @param name * The name of the variable to change; must not be * null. * @param value * The new value; the variable should be removed if this is * null. */ - void ChangeVariable(const QString& name, const Object::Pointer& value); + void ChangeVariable(const QString& name, const Object::ConstPointer& value); /** * Carries out the actual source change notification. It assumed that by the * time this method is called, getEvaluationContext() is * up-to-date with the current state of the application. * * @param sourcePriority * A bit mask of all the source priorities that have changed. */ virtual void SourceChanged(int sourcePriority) = 0; /** * Similar to sourceChanged(int) this notifies the subclass about the * change, but using the array of source names that changed instead of the * priority ... int based. *

* Clients may override this method. *

* * @param sourceNames * The array of names that changed. */ virtual void SourceChanged(const QStringList& sourceNames); /** * @param sourcePriority * @param strings */ void SourceChanged(int sourcePriority, const QStringList& sourceNames); /** * Updates the evaluation context with the current state from all of the * source providers. */ void UpdateCurrentState(); /** * Updates this authority's evaluation context. * * @param name * The name of the variable to update; must not be * null. * @param value * The new value of the variable. If this value is * null, then the variable is removed. */ - void UpdateEvaluationContext(const QString& name, const Object::Pointer& value); + void UpdateEvaluationContext(const QString& name, const Object::ConstPointer& value); public: /** * Adds a source provider to a list of providers to check when updating. * This also attaches this authority as a listener to the provider. * * @param provider * The provider to add; must not be null. */ void AddSourceProvider(const SmartPointer& provider); /** * Removes all of the source provider listeners. */ void Dispose(); ~ExpressionAuthority(); /** * Creates a new evaluation context based on the current evaluation context * (i.e., the current state), and places the current selection as the * default variable. * * @return An evaluation context that can be used for evaluating * expressions; never null. */ SmartPointer GetCurrentState() const; /** * Removes this source provider from the list, and detaches this authority * as a listener. * * @param provider * The provider to remove; must not be null. */ void RemoveSourceProvider(const SmartPointer& provider); void SourceChanged(int sourcePriority, - const QHash& sourceValuesByName); + const QHash& sourceValuesByName); void SourceChanged(int sourcePriority, const QString& sourceName, - Object::Pointer sourceValue); + Object::ConstPointer sourceValue); }; } #endif // BERRYEXPRESSIONAUTHORITY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerActivation.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerActivation.cpp new file mode 100644 index 0000000000..706f4dddce --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerActivation.cpp @@ -0,0 +1,151 @@ +/*=================================================================== + +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 "berryHandlerActivation.h" + +#include "berryISources.h" +#include "berryIHandler.h" +#include "berryExpression.h" + +namespace berry { + +HandlerActivation::HandlerActivation(const QString& commandId, const SmartPointer& handler, + const SmartPointer& expression, int depth, + IHandlerService* handlerService) + : EvaluationResultCache(expression) + , commandId(commandId) + , depth(depth) + , handler(handler) + , handlerService(handlerService) +{ + if (commandId.isNull()) + { + throw ctkInvalidArgumentException( + "The command identifier for a handler activation cannot be null"); + } + + if (handlerService == NULL) + { + throw ctkInvalidArgumentException("The handler service for an activation cannot be null"); + } +} + +void HandlerActivation::ClearActive() +{ + ClearResult(); +} + +bool HandlerActivation::operator<(const Object* object) const +{ + const HandlerActivation* activation = dynamic_cast(object); + return this->CompareTo(activation) < 0; +} + +int berry::HandlerActivation::CompareTo(const HandlerActivation* other) const +{ + const IHandlerActivation* const activation = other; + int difference = 0; + + // Check the priorities + int thisPriority = this->GetSourcePriority(); + int thatPriority = activation->GetSourcePriority(); + + // rogue bit problem - ISources.ACTIVE_MENU + int thisLsb = 0; + int thatLsb = 0; + + if (((thisPriority & ISources::ACTIVE_MENU()) | (thatPriority & ISources::ACTIVE_MENU())) != 0) + { + thisLsb = thisPriority & 1; + thisPriority = (thisPriority >> 1) & 0x7fffffff; + thatLsb = thatPriority & 1; + thatPriority = (thatPriority >> 1) & 0x7fffffff; + } + + difference = thisPriority - thatPriority; + if (difference != 0) { + return difference; + } + + // if all of the higher bits are the same, check the + // difference of the LSB + difference = thisLsb - thatLsb; + if (difference != 0) { + return difference; + } + + // Check depth + const int thisDepth = this->GetDepth(); + const int thatDepth = activation->GetDepth(); + difference = thisDepth - thatDepth; + return difference; +} + +QString HandlerActivation::GetCommandId() const +{ + return commandId; +} + +int HandlerActivation::GetDepth() const +{ + return depth; +} + +SmartPointer HandlerActivation::GetHandler() const +{ + return handler; +} + +IHandlerService* HandlerActivation::GetHandlerService() const +{ + return handlerService; +} + +QString HandlerActivation::ToString() const +{ + QString str; + QDebug buffer(&str); + + const Expression::Pointer exp = GetExpression(); + buffer << "HandlerActivation(commandId=" << commandId << ','; + buffer << "\thandler=" << (handler.IsNull() ? QString("") : handler->ToString()) << ','; + buffer << "\texpression=" << (exp.IsNull() ? QString("") : exp->ToString()) + << ",sourcePriority=" << GetSourcePriority() << ')'; + + return str; +} + +SmartPointer HandlerActivation::GetReference() +{ + return reference; +} + +void HandlerActivation::SetReference(const SmartPointer& reference) +{ + this->reference = reference; +} + +void HandlerActivation::SetListener(IPropertyChangeListener* listener) +{ + this->listener.reset(listener); +} + +IPropertyChangeListener* HandlerActivation::GetListener() const +{ + return listener.data(); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerActivation.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerActivation.h new file mode 100644 index 0000000000..8ad6247ac5 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerActivation.h @@ -0,0 +1,158 @@ +/*=================================================================== + +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 BERRYHANDLERACTIVATION_H +#define BERRYHANDLERACTIVATION_H + +#include "berryIHandlerActivation.h" +#include "berryEvaluationResultCache.h" +#include "berryIEvaluationReference.h" +#include "berryIPropertyChangeListener.h" + +namespace berry { + +struct IEvaluationReference; +struct IPropertyChangeListener; + +/** + *

+ * A token representing the activation of a handler. This token can later be + * used to cancel that activation. Without this token, then handler will only + * become inactive if the component in which the handler was activated is + * destroyed. + *

+ *

+ * This caches the command id and the handler, so that they can later be + * identified. + *

+ *

+ * Note: this class has a natural ordering that is inconsistent with + * equals. + *

+ */ +class HandlerActivation : public EvaluationResultCache, public IHandlerActivation +{ + +public: + + berryObjectMacro(berry::HandlerActivation) + +private: + + /** + * The identifier for the command which the activated handler handles. This + * value is never null. + */ + const QString commandId; + + /** + * The depth of services at which this token was created. This is used as a + * final tie-breaker if all other things are equivalent. + */ + const int depth; + + /** + * The handler that has been activated. This value may be null. + */ + SmartPointer handler; + + /** + * The handler service from which this handler activation was request. This + * value is never null. + */ + IHandlerService* handlerService; + + SmartPointer reference; + + QScopedPointer listener; + +public: + + /** + * Constructs a new instance of HandlerActivation. + * + * @param commandId + * The identifier for the command which the activated handler + * handles. This value must not be null. + * @param handler ` + * The handler that has been activated. This value may be + * null. + * @param expression + * The expression that must evaluate to true + * before this handler is active. This value may be + * null if it is always active.
. + * @param depth + * The depth at which this activation was created within the + * services hierarchy. This is used as the final tie-breaker if + * all other conditions are equal. This should be a positive + * integer. + * @param handlerService + * The handler service from which the handler activation was + * requested; must not be null. + * @see ISources + */ + HandlerActivation(const QString& commandId, const SmartPointer& handler, + const SmartPointer& expression, int depth, + IHandlerService* handlerService); + + void ClearActive(); + + /** + * Implement {@link Object#operator<(const Object*)}. + *

+ * Note: this class has a natural ordering that is inconsistent with + * equals. + *

+ */ + bool operator<(const Object* object) const; + + int CompareTo(const HandlerActivation* other) const; + + QString GetCommandId() const; + + int GetDepth() const; + + SmartPointer GetHandler() const; + + IHandlerService* GetHandlerService() const; + + QString ToString() const; + + /** + * @return Returns the reference. + */ + SmartPointer GetReference(); + + /** + * @param reference + * The reference to set. + */ + void SetReference(const SmartPointer& reference); + + /** + * @param listener The listener to set. + */ + void SetListener(IPropertyChangeListener* listener); + + /** + * @return Returns the listener. + */ + IPropertyChangeListener* GetListener() const; +}; + +} + +#endif // BERRYHANDLERACTIVATION_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.cpp new file mode 100644 index 0000000000..d6ef1d8b0f --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.cpp @@ -0,0 +1,509 @@ +/*=================================================================== + +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 "berryHandlerAuthority.h" + +#include "berryISources.h" +#include "berryIServiceLocator.h" +#include "berryIEvaluationService.h" +#include "berryIEvaluationContext.h" +#include "berryIEvaluationReference.h" +#include "berryICommandService.h" +#include "berryIHandler.h" +#include "berryISourceProvider.h" +#include "services/berryISourceProviderService.h" + +#include "berryObjects.h" +#include "berryHandlerActivation.h" +#include "berryMultiStatus.h" +#include "berryPlatformUI.h" +#include "berryWorkbenchPlugin.h" +#include "berryCommandTracing.h" +#include "berryCommand.h" +#include "berryEvaluationContext.h" +#include "berryExpression.h" + +#include + +namespace berry { + +const bool HandlerAuthority::DEBUG = false; // = Policy.DEBUG_HANDLERS; +const bool HandlerAuthority::DEBUG_PERFORMANCE = false; // = Policy.DEBUG_HANDLERS_PERFORMANCE; +const bool HandlerAuthority::DEBUG_VERBOSE = false; // = Policy.DEBUG_HANDLERS && Policy.DEBUG_HANDLERS_VERBOSE; +const QString HandlerAuthority::DEBUG_VERBOSE_COMMAND_ID; // = Policy.DEBUG_HANDLERS_VERBOSE_COMMAND_ID; +const QString HandlerAuthority::TRACING_COMPONENT = "HANDLERS"; + +const QList HandlerAuthority::SELECTION_VARIABLES = QList() + << ISources::ACTIVE_CURRENT_SELECTION_NAME() + << ISources::ACTIVE_FOCUS_CONTROL_ID_NAME() + << ISources::ACTIVE_FOCUS_CONTROL_NAME() + << ISources::ACTIVE_MENU_EDITOR_INPUT_NAME() + << ISources::ACTIVE_MENU_NAME() + << ISources::ACTIVE_MENU_SELECTION_NAME(); + +class HandlerAuthority::HandlerPropertyListener : public IPropertyChangeListener +{ +private: + + HandlerAuthority* authority; + HandlerActivation::Pointer handler; + +public: + + HandlerPropertyListener(HandlerAuthority* authority, const HandlerActivation::Pointer& activation) + : authority(authority) + , handler(activation) + { + handler->SetListener(this); + } + + using IPropertyChangeListener::PropertyChange; + + void PropertyChange(const PropertyChangeEvent::Pointer& event) + { + if (handler->GetCommandId() == event->GetProperty()) + { + bool val = false; + if (ObjectBool::Pointer boolObj = event->GetNewValue().Cast()) + { + val = boolObj->GetValue(); + } + handler->SetResult(val); + authority->changedCommandIds.insert(handler->GetCommandId()); + } + } +}; + +IEvaluationService* HandlerAuthority::GetEvaluationService() const +{ + if (evalService == NULL) + { + evalService = locator->GetService(); + evalService->AddServiceListener(GetServiceListener()); + } + return evalService; +} + +IPropertyChangeListener* HandlerAuthority::GetServiceListener() const +{ + return const_cast(this); +} + +void HandlerAuthority::PropertyChange(const PropertyChangeEvent::Pointer& event) +{ + if (IEvaluationService::PROP_NOTIFYING == event->GetProperty()) + { + if (ObjectBool::Pointer boolObj = event->GetNewValue().Cast()) + { + bool startNotifying = boolObj->GetValue(); + if (startNotifying) + { + changedCommandIds.clear(); + } + else + { + ProcessChangedCommands(); + } + } + } +} + +HandlerAuthority::HandlerAuthority(ICommandService* commandService, + IServiceLocator* locator) + : commandService(commandService) + , locator(locator) + , evalService(NULL) +{ + if (commandService == NULL) + { + throw ctkInvalidArgumentException("The handler authority needs a command service"); + } +} + +HandlerAuthority::~HandlerAuthority() +{ + GetEvaluationService()->RemoveServiceListener(GetServiceListener()); +} + +void HandlerAuthority::ActivateHandler(const SmartPointer& activation) +{ + const HandlerActivation::Pointer handler = activation.Cast(); + + // First we update the handlerActivationsByCommandId map. + const QString commandId = handler->GetCommandId(); + MultiStatus::Pointer conflicts( + new MultiStatus(PlatformUI::PLUGIN_ID(), 0, + "A handler conflict occurred. This may disable some commands.", + BERRY_STATUS_LOC) + ); + IdToHandlerActivationMap::mapped_type& handlerActivations = handlerActivationsByCommandId[commandId]; + handlerActivations.insert(handler, Empty()); + if (handler->GetExpression().IsNotNull()) + { + HandlerPropertyListener* l = new HandlerPropertyListener(this, handler); + handler->SetReference(GetEvaluationService()->AddEvaluationListener( + handler->GetExpression(), l, + handler->GetCommandId())); + } + if (handlerActivations.size() > 1) + { + UpdateCommand(commandId, ResolveConflicts(commandId, handlerActivations, conflicts)); + } + else + { + UpdateCommand(commandId, (Evaluate(handler) ? handler : HandlerActivation::Pointer(0))); + } + + if (conflicts->GetSeverity() != IStatus::OK_TYPE) + { + WorkbenchPlugin::Log(conflicts); + } +} + +void HandlerAuthority::DeactivateHandler(const SmartPointer& activation) +{ + const HandlerActivation::Pointer handler = activation.Cast(); + + // First we update the handlerActivationsByCommandId map. + const QString commandId = handler->GetCommandId(); + MultiStatus::Pointer conflicts( + new MultiStatus("org.blueberry.ui", 0, "A handler conflict occurred. This may disable some commands.", BERRY_STATUS_LOC)); + IdToHandlerActivationMap::iterator value = handlerActivationsByCommandId.find(commandId); + if (value != handlerActivationsByCommandId.end()) + { + IdToHandlerActivationMap::mapped_type& handlerActivations = value.value(); + if (handlerActivations.remove(handler) > 0) + { + if (handler->GetReference().IsNotNull()) + { + GetEvaluationService()->RemoveEvaluationListener(handler->GetReference()); + handler->SetReference(IEvaluationReference::Pointer(0)); + handler->SetListener(NULL); + } + if (handlerActivations.isEmpty()) + { + handlerActivationsByCommandId.remove(commandId); + UpdateCommand(commandId, IHandlerActivation::Pointer(0)); + } + else if (handlerActivations.size() == 1) + { + IHandlerActivation::Pointer remainingActivation = handlerActivations.begin().key(); + UpdateCommand(commandId, (Evaluate(remainingActivation) ? remainingActivation : IHandlerActivation::Pointer(0))); + } + else + { + UpdateCommand(commandId, ResolveConflicts(commandId, handlerActivations, conflicts)); + } + } + } + + if (conflicts->GetSeverity() != IStatus::OK_TYPE) + { + WorkbenchPlugin::Log(conflicts); + } +} + +SmartPointer HandlerAuthority::ResolveConflicts( + const QString& commandId, + const QMap,Empty>& activations, + SmartPointer conflicts) +{ + // If we don't have any, then there is no match. + if (activations.isEmpty()) + { + return IHandlerActivation::Pointer(0); + } + + // Cycle over the activations, remembered the current best. + QMapIterator activationItr(activations); + HandlerActivation::Pointer bestActivation; + HandlerActivation::Pointer currentActivation; + bool conflict = false; + while (activationItr.hasNext()) + { + currentActivation = activationItr.next().key(); + if (!Evaluate(currentActivation)) + { + continue; // only consider potentially active handlers + } + + // Check to see if we haven't found a potentially active handler yet + if ((DEBUG_VERBOSE) && ((DEBUG_VERBOSE_COMMAND_ID.isNull()) || + (DEBUG_VERBOSE_COMMAND_ID == commandId))) + { + CommandTracing::PrintTrace(TRACING_COMPONENT, + " resolveConflicts: eval: " + currentActivation->ToString()); + } + if (bestActivation.IsNull()) + { + bestActivation = currentActivation; + conflict = false; + continue; + } + + // Compare the two handlers. + int comparison = bestActivation->CompareTo(currentActivation.GetPointer()); + if (comparison < 0) + { + bestActivation = currentActivation; + conflict = false; + } + else if (comparison == 0) + { + if (currentActivation->GetHandler() != bestActivation->GetHandler()) + { + conflict = true; + break; + } + } + else + { + break; + } + } + + // If we are logging information, now is the time to do it. + if (DEBUG) + { + if (conflict) + { + CommandTracing::PrintTrace(TRACING_COMPONENT, + "Unresolved conflict detected for '" + commandId + '\''); + } + else if ((bestActivation.IsNotNull()) && (DEBUG_VERBOSE) && + ((DEBUG_VERBOSE_COMMAND_ID.isNull()) || (DEBUG_VERBOSE_COMMAND_ID == commandId))) + { + CommandTracing::PrintTrace(TRACING_COMPONENT, + "Resolved conflict detected. The following activation won: "); + CommandTracing::PrintTrace(TRACING_COMPONENT, " " + bestActivation->ToString()); + } + } + + // Return the current best. + if (conflict) + { + if (!previousLogs.contains(commandId)) + { + previousLogs.insert(commandId); + QString str; + QDebug dbg(&str); + dbg << "Conflict for" << commandId << ":"; + dbg << bestActivation->ToString(); + dbg << currentActivation->ToString(); + + IStatus::Pointer s(new Status(IStatus::WARNING_TYPE, "org.blueberry.ui", str, BERRY_STATUS_LOC)); + conflicts->Add(s); + } + return IHandlerActivation::Pointer(0); + } + return bestActivation; +} + +void HandlerAuthority::UpdateCommand(const QString& commandId, + const SmartPointer& activation) +{ + const Command::Pointer command = commandService->GetCommand(commandId); + if (activation.IsNull()) + { + command->SetHandler(IHandler::Pointer(0)); + } + else + { + command->SetHandler(activation->GetHandler()); + commandService->RefreshElements(commandId, QHash()); + } +} + +SmartPointer HandlerAuthority::FindHandler(const QString& commandId, + IEvaluationContext* context) +{ + IdToHandlerActivationMap::mapped_type activations = handlerActivationsByCommandId.value(commandId); + + IHandlerActivation::Pointer lastActivation; + IHandlerActivation::Pointer currentActivation; + QMapIterator i(activations); + while (i.hasNext() && lastActivation.IsNull()) + { + HandlerActivation::Pointer activation = i.next().key(); + try + { + if (Eval(context, activation)) + { + lastActivation = currentActivation; + currentActivation = activation; + } + } + catch (const CoreException&) + { + // OK, this one is out of the running + } + } + if (currentActivation.IsNotNull()) + { + if (lastActivation.IsNull()) + { + return currentActivation->GetHandler(); + } + if (lastActivation->GetSourcePriority() != currentActivation->GetSourcePriority()) + { + return lastActivation->GetHandler(); + } + } + + return IHandler::Pointer(0); +} + +IEvaluationContext::Pointer HandlerAuthority::CreateContextSnapshot(bool includeSelection) +{ + IEvaluationContext::Pointer tmpContext = GetCurrentState(); + + EvaluationContext::Pointer context; + if (includeSelection) + { + context = new EvaluationContext(NULL, tmpContext->GetDefaultVariable()); + for (int i = 0; i < SELECTION_VARIABLES.size(); i++) + { + CopyVariable(context.GetPointer(), tmpContext.GetPointer(), SELECTION_VARIABLES[i]); + } + } + else + { + context = new EvaluationContext(NULL, Object::Pointer(0)); + } + + ISourceProviderService* sp = locator->GetService(); + QList providers = sp->GetSourceProviders(); + for (int i = 0; i < providers.size(); i++) + { + QList names = providers[i]->GetProvidedSourceNames(); + for (int j = 0; j < names.size(); j++) + { + if (!IsSelectionVariable(names[j])) + { + CopyVariable(context.GetPointer(), tmpContext.GetPointer(), names[j]); + } + } + } + + return context; +} + +bool HandlerAuthority::Eval(IEvaluationContext* context, + const SmartPointer& activation) +{ + Expression::Pointer expression = activation->GetExpression(); + if (expression.IsNull()) + { + return true; + } + return expression->Evaluate(context) == EvaluationResult::TRUE_EVAL; +} + +bool HandlerAuthority::IsSelectionVariable(const QString& name) +{ + for (int i = 0; i < SELECTION_VARIABLES.size(); i++) + { + if (SELECTION_VARIABLES[i] == name) + { + return true; + } + } + return false; +} + +void HandlerAuthority::CopyVariable(IEvaluationContext* context, + IEvaluationContext* tmpContext, const QString& var) +{ + Object::ConstPointer o = tmpContext->GetVariable(var); + if (o.IsNotNull()) + { + context->AddVariable(var, o); + } +} + +void HandlerAuthority::ProcessChangedCommands() +{ + // If tracing, then track how long it takes to process the activations. + QTime startTime; + if (DEBUG_PERFORMANCE) + { + startTime.start(); + } + + MultiStatus::Pointer conflicts( + new MultiStatus("org.blueberry.ui", 0, + "A handler conflict occurred. This may disable some commands.", BERRY_STATUS_LOC)); + + /* + * For every command identifier with a changed activation, we resolve + * conflicts and trigger an update. + */ + const QSet changedIds = changedCommandIds; + changedCommandIds.clear(); + foreach(const QString& commandId, changedIds) + { + IdToHandlerActivationMap::mapped_type activations = handlerActivationsByCommandId.value(commandId); + if (activations.size() == 1) + { + const IHandlerActivation::Pointer activation = activations.begin().key(); + UpdateCommand(commandId, (Evaluate(activation) ? activation : IHandlerActivation::Pointer(0))); + } + else + { + const IHandlerActivation::Pointer activation = ResolveConflicts( + commandId, activations, conflicts); + UpdateCommand(commandId, activation); + } + } + if (conflicts->GetSeverity() != IStatus::OK_TYPE) + { + WorkbenchPlugin::Log(conflicts); + } + + // If tracing performance, then print the results. + if (DEBUG_PERFORMANCE) + { + const int elapsedTime = startTime.elapsed(); + const int size = changedCommandIds.size(); + if (size > 0) + { + CommandTracing::PrintTrace(TRACING_COMPONENT, QString::number(size) + " command ids changed in " + elapsedTime + "ms"); + } + } +} + +bool HandlerAuthority::Evaluate(const SmartPointer& expression) +{ + IEvaluationContext::Pointer contextWithDefaultVariable = GetCurrentState(); + return expression->Evaluate(contextWithDefaultVariable.GetPointer()); +} + +SmartPointer HandlerAuthority::GetCurrentState() const +{ + return GetEvaluationService()->GetCurrentState(); +} + +//void HandlerAuthority::UpdateShellKludge() +//{ +// ((EvaluationService) getEvaluationService()).updateShellKludge(); +//} + +//void HandlerAuthority::UpdateShellKludge(const SmartPointer& shell) +//{ +// ((EvaluationService) getEvaluationService()).updateShellKludge(shell); +//} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.h new file mode 100644 index 0000000000..a9adfa245e --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.h @@ -0,0 +1,254 @@ +/*=================================================================== + +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 BERRYHANDLERAUTHORITY_H +#define BERRYHANDLERAUTHORITY_H + +#include "berryIPropertyChangeListener.h" + +#include +#include + +namespace berry { + +template class SmartPointer; + +struct ICommandService; +struct IEvaluationContext; +struct IEvaluationResultCache; +struct IEvaluationService; +struct IHandler; +struct IHandlerActivation; +struct IServiceLocator; + +class HandlerActivation; +class MultiStatus; +class Shell; + +/** + *

+ * A central authority for resolving conflicts between handlers. This authority + * listens to a variety of incoming sources, and updates the underlying commands + * if changes in the active handlers occur. + *

+ *

+ * This authority encapsulates all of the handler conflict resolution mechanisms + * for the workbench. A conflict occurs if two or more handlers are assigned to + * the same command identifier. To resolve this conflict, the authority + * considers which source the handler came from. + *

+ */ +class HandlerAuthority : private IPropertyChangeListener +{ + +private: + + /** + * Whether the workbench command support should kick into debugging mode. + * This causes the unresolvable handler conflicts to be printed to the + * console. + */ + static const bool DEBUG; // = Policy.DEBUG_HANDLERS; + + /** + * Whether the performance information should be printed about the + * performance of the handler authority. + */ + static const bool DEBUG_PERFORMANCE; // = Policy.DEBUG_HANDLERS_PERFORMANCE; + + /** + * Whether the workbench command support should kick into verbose debugging + * mode. This causes the resolvable handler conflicts to be printed to the + * console. + */ + static const bool DEBUG_VERBOSE; // = Policy.DEBUG_HANDLERS && Policy.DEBUG_HANDLERS_VERBOSE; + + /** + * The command identifier to which the verbose output should be restricted. + */ + static const QString DEBUG_VERBOSE_COMMAND_ID; // = Policy.DEBUG_HANDLERS_VERBOSE_COMMAND_ID; + + /** + * The component name to print when displaying tracing information. + */ + static const QString TRACING_COMPONENT; // = "HANDLERS"; + + static const QList SELECTION_VARIABLES; + + /** + * The command service that should be updated when the handlers are + * changing. This value is never null. + */ + ICommandService* const commandService; + + struct Empty {}; + typedef QHash, Empty> > IdToHandlerActivationMap; + /** + * This is a map of handler activations (SortedSet of + * IHandlerActivation) sorted by command identifier (String). + * If there is only one handler activation for a command, then the + * SortedSet is replaced by a IHandlerActivation. + * If there is no activation, the entry should be removed entirely. + */ + IdToHandlerActivationMap handlerActivationsByCommandId; + + QSet previousLogs; + + IServiceLocator* locator; + + QSet changedCommandIds; + + mutable IEvaluationService* evalService; + + IEvaluationService* GetEvaluationService() const; + + IPropertyChangeListener* GetServiceListener() const; + +public: + + /** + * Constructs a new instance of HandlerAuthority. + * + * @param commandService + * The command service from which commands can be retrieved (to + * update their handlers); must not be null. + * @param locator + * the appropriate service locator + */ + HandlerAuthority(ICommandService* commandService, + IServiceLocator* locator); + + ~HandlerAuthority(); + + /** + * Activates a handler on the workbench. This will add it to a master list. + * If conflicts exist, they will be resolved based on the source priority. + * If conflicts still exist, then no handler becomes active. + * + * @param activation + * The activation; must not be null. + */ + void ActivateHandler(const SmartPointer& activation); + + /** + * Removes an activation for a handler on the workbench. This will remove it + * from the master list, and update the appropriate command, if necessary. + * + * @param activation + * The activation; must not be null. + */ + void DeactivateHandler(const SmartPointer& activation); + +private: + + /** + * Resolves conflicts between multiple handlers for the same command + * identifier. This tries to select the best activation based on the source + * priority. For the sake of comparison, activations with the same handler + * are considered equivalent (i.e., non-conflicting). + * + * @param commandId + * The identifier of the command for which the conflicts should + * be detected; must not be null. This is only + * used for debugging purposes. + * @param activations + * All of the possible handler activations for the given command + * identifier; must not be null. + * @return The best matching handler activation. If none can be found (e.g., + * because of unresolvable conflicts), then this returns + * null. + */ + SmartPointer ResolveConflicts( + const QString& commandId, + const QMap,Empty>& activations, + SmartPointer conflicts); + + /** + * Updates the command with the given handler activation. + * + * @param commandId + * The identifier of the command which should be updated; must + * not be null. + * @param activation + * The activation to use; may be null if the + * command should have a null handler. + */ + void UpdateCommand(const QString& commandId, + const SmartPointer& activation); + +public: + + /** + * Currently this is a an internal method to help locate a handler. + *

+ * DO NOT CALL THIS METHOD. + *

+ * + * @param commandId + * the command id to check + * @param context + * the context to use for activations + */ + SmartPointer FindHandler(const QString& commandId, + IEvaluationContext* context); + + SmartPointer CreateContextSnapshot(bool includeSelection); + +private: + + using IPropertyChangeListener::PropertyChange; + void PropertyChange(const SmartPointer& event); + + /** + * Evaluate the expression for the handler and bypass the result cache. + *

+ * DO NOT CALL THIS METHOD. + *

+ * + * @param context + * @param activation + * @return true if the handler expression can evaluate to + * true. + * @throws CoreException + */ + bool Eval(IEvaluationContext* context, + const SmartPointer& activation); + + bool IsSelectionVariable(const QString& name); + + void CopyVariable(IEvaluationContext* context, + IEvaluationContext* tmpContext, const QString& var); + + class HandlerPropertyListener; + + void ProcessChangedCommands(); + +protected: + + bool Evaluate(const SmartPointer& expression); + +public: + + SmartPointer GetCurrentState() const; + +// void UpdateShellKludge(); + +// void UpdateShellKludge(const SmartPointer& shell); +}; + +} + +#endif // BERRYHANDLERAUTHORITY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerPersistence.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerPersistence.cpp new file mode 100644 index 0000000000..52cd7d25b4 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerPersistence.cpp @@ -0,0 +1,240 @@ +/*=================================================================== + +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 "berryHandlerPersistence.h" + +#include "berryIExtension.h" +#include "berryIExtensionRegistry.h" +#include "berryIConfigurationElement.h" +#include "berryIHandler.h" +#include "berryIHandlerService.h" +#include "berryIHandlerActivation.h" + +#include "berryHandlerProxy.h" +#include "berryPlatform.h" +#include "berryWorkbenchPlugin.h" +#include "berryExpression.h" + +namespace berry { + +const int HandlerPersistence::INDEX_COMMAND_DEFINITIONS = 0; +const int HandlerPersistence::INDEX_HANDLER_DEFINITIONS = 1; +//const int HandlerPersistence::INDEX_HANDLER_SUBMISSIONS = 2; +const int HandlerPersistence::INDEX_SIZE = 2; + + +HandlerPersistence::HandlerPersistence(IHandlerService* handlerService, + IEvaluationService* evaluationService) + : handlerService(handlerService) + , evaluationService(evaluationService) +{ +} + +HandlerPersistence::~HandlerPersistence() +{ + ClearActivations(handlerService); +} + +bool HandlerPersistence::HandlersNeedUpdating(const QList >& extensions) +{ + /* + * Handlers will need to be re-read (i.e., re-verified) if any of the + * handler extensions change (i.e., handlers, commands), or if any of + * the command extensions change (i.e., action definitions). + */ + foreach(const IExtension::Pointer& extension, extensions) + { + QString xpId = extension->GetExtensionPointUniqueIdentifier(); + if (xpId == EXTENSION_HANDLERS || + xpId == EXTENSION_COMMANDS || + xpId == EXTENSION_ACTION_DEFINITIONS) + { + return true; + } + } + return false; +} + +void HandlerPersistence::ReRead() +{ + // Create the extension registry mementos. + IExtensionRegistry* const registry = Platform::GetExtensionRegistry(); + QList > indexedConfigurationElements; + for (int i = 0; i < INDEX_SIZE; ++i) + { + indexedConfigurationElements.push_back(QList()); + } + + // Sort the commands extension point based on element name. + QList commandsExtensionPoint = registry + ->GetConfigurationElementsFor(EXTENSION_COMMANDS); + foreach (const IConfigurationElement::Pointer& configurationElement, commandsExtensionPoint) + { + const QString name = configurationElement->GetName(); + + /*// Check if it is a handler submission or a command definition. + if (TAG_HANDLER_SUBMISSION == name) + { + indexedConfigurationElements[INDEX_HANDLER_SUBMISSIONS].push_back(configurationElement); + } + else*/ + if (TAG_COMMAND == name) + { + indexedConfigurationElements[INDEX_COMMAND_DEFINITIONS].push_back(configurationElement); + } + } + + // Sort the handler extension point based on element name. + QList handlersExtensionPoint = registry + ->GetConfigurationElementsFor(EXTENSION_HANDLERS); + foreach (const IConfigurationElement::Pointer& configurationElement, handlersExtensionPoint) + { + const QString name = configurationElement->GetName(); + + // Check if it is a handler submission or a command definition. + if (TAG_HANDLER == name) + { + indexedConfigurationElements[INDEX_HANDLER_DEFINITIONS].push_back(configurationElement); + } + } + + ClearActivations(handlerService); + ReadDefaultHandlersFromRegistry(indexedConfigurationElements[INDEX_COMMAND_DEFINITIONS]); + //ReadHandlerSubmissionsFromRegistry(indexedConfigurationElements[INDEX_HANDLER_SUBMISSIONS]); + ReadHandlersFromRegistry(indexedConfigurationElements[INDEX_HANDLER_DEFINITIONS]); +} + +bool HandlerPersistence::IsChangeImportant(const QList >& /*extensions*/, + RegistryChangeType /*changeType*/) +{ + return false; +} + +bool HandlerPersistence::IsChangeImportant(const QList >& /*extensionPoints*/, + RegistryChangeType /*changeType*/) +{ + return false; +} + +void HandlerPersistence::Read() +{ + RegistryPersistence::Read(); + ReRead(); +} + +void HandlerPersistence::ClearActivations(IHandlerService* handlerService) +{ + handlerService->DeactivateHandlers(handlerActivations); + foreach (const IHandlerActivation::Pointer& activation, handlerActivations) + { + if (activation->GetHandler().IsNotNull()) + { + try + { + activation->GetHandler()->Dispose(); + } + catch (const ctkException& e) + { + WorkbenchPlugin::Log("Failed to dispose handler for " + activation->GetCommandId(), e); + } + catch (...) + { + WorkbenchPlugin::Log("Failed to dispose handler for " + activation->GetCommandId()); + } + } + } + handlerActivations.clear(); +} + +void HandlerPersistence::ReadDefaultHandlersFromRegistry( + const QList >& configurationElements) +{ + foreach (const IConfigurationElement::Pointer& configurationElement, configurationElements) + { + /* + * Read out the command identifier. This was already checked by + * CommandPersistence, so we'll just ignore any + * problems here. + */ + const QString commandId = ReadOptional(configurationElement, ATT_ID); + if (commandId.isNull()) + { + continue; + } + + // Check to see if we have a default handler of any kind. + if (configurationElement->GetAttribute(ATT_DEFAULT_HANDLER).isNull() && + configurationElement->GetChildren(TAG_DEFAULT_HANDLER).isEmpty()) + { + continue; + } + + IHandler::Pointer handler(new HandlerProxy(commandId, configurationElement, ATT_DEFAULT_HANDLER)); + handlerActivations.push_back(handlerService->ActivateHandler(commandId, handler)); + } +} + +void HandlerPersistence::ReadHandlersFromRegistry( + const QList >& configurationElements) +{ + QList warningsToLog; + + foreach (const IConfigurationElement::Pointer& configurationElement, configurationElements) + { + // Read out the command identifier. + const QString commandId = ReadRequired(configurationElement, + ATT_COMMAND_ID, warningsToLog, "Handlers need a command id"); + if (commandId.isNull()) + { + continue; + } + + // Check to see if we have a handler class. + if (!CheckClass(configurationElement, warningsToLog, + "Handlers need a class", commandId)) + { + continue; + } + + // Get the activeWhen and enabledWhen expressions. + const Expression::Pointer activeWhenExpression = ReadWhenElement( + configurationElement, TAG_ACTIVE_WHEN, commandId, warningsToLog); + if (activeWhenExpression == ERROR_EXPRESSION) + { + continue; + } + const Expression::Pointer enabledWhenExpression = ReadWhenElement( + configurationElement, TAG_ENABLED_WHEN, commandId, warningsToLog); + if (enabledWhenExpression == ERROR_EXPRESSION) + { + continue; + } + + const IHandler::Pointer proxy(new HandlerProxy(commandId, configurationElement, + ATT_CLASS, enabledWhenExpression, evaluationService)); + handlerActivations.push_back(handlerService->ActivateHandler(commandId, + proxy, activeWhenExpression)); + + // Read out the help context identifier. + const QString helpContextId = ReadOptional(configurationElement, ATT_HELP_CONTEXT_ID); + handlerService->SetHelpContextId(proxy, helpContextId); + } + + LogWarnings(warningsToLog, + "Warnings while parsing the handlers from the 'org.blueberry.ui.handlers' extension point."); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerPersistence.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerPersistence.h new file mode 100644 index 0000000000..3a5042e54f --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerPersistence.h @@ -0,0 +1,162 @@ +/*=================================================================== + +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 BERRYHANDLERPERSISTENCE_H +#define BERRYHANDLERPERSISTENCE_H + +#include "berryRegistryPersistence.h" + +namespace berry { + +struct IEvaluationService; +struct IHandlerActivation; +struct IHandlerService; + +/** + *

+ * A static class for accessing the registry. + *

+ */ +class HandlerPersistence : public RegistryPersistence +{ + +private: + + /** + * The index of the command elements in the indexed array. + * + * @see HandlerPersistence#read() + */ + static const int INDEX_COMMAND_DEFINITIONS; // = 0; + + /** + * The index of the command elements in the indexed array. + * + * @see HandlerPersistence#read() + */ + static const int INDEX_HANDLER_DEFINITIONS; // = 1; + + /** + * The index of the handler submissions in the indexed array. + * + * @see HandlerPersistence#read() + */ + //static const int INDEX_HANDLER_SUBMISSIONS; // = 2; + + static const int INDEX_SIZE; + + /** + * The handler activations that have come from the registry. This is used to + * flush the activations when the registry is re-read. This value is never + * null + */ + QList > handlerActivations; + + /** + * The handler service with which this persistence class is associated. This + * value must not be null. + */ + IHandlerService* const handlerService; + + IEvaluationService* const evaluationService; + +public: + + /** + * Constructs a new instance of HandlerPersistence. + * + * @param handlerService + * The handler service with which the handlers should be + * registered; must not be null. + * @param evaluationService + * The evaluation service used by handler proxies with enabled + * when expressions + */ + HandlerPersistence(IHandlerService* handlerService, + IEvaluationService* evaluationService); + + ~HandlerPersistence(); + + bool HandlersNeedUpdating(const QList >& extensions); + + void ReRead(); + +protected: + + friend class HandlerService; + + bool IsChangeImportant(const QList >& extensions, + RegistryChangeType changeType); + + bool IsChangeImportant(const QList >& extensionPoints, + RegistryChangeType changeType); + + /** + * Reads all of the handlers from the registry + * + * @param handlerService + * The handler service which should be populated with the values + * from the registry; must not be null. + */ + void Read(); + +private: + + /** + * Deactivates all of the activations made by this class, and then clears + * the collection. This should be called before every read. + * + * @param handlerService + * The service handling the activations; must not be + * null. + */ + void ClearActivations(IHandlerService* handlerService); + + /** + * Reads the default handlers from an array of command elements from the + * commands extension point. + * + * @param configurationElements + * The configuration elements in the commands extension point; + * must not be null, but may be empty. + * @param configurationElementCount + * The number of configuration elements that are really in the + * array. + */ + void ReadDefaultHandlersFromRegistry( + const QList >& configurationElements); + + /** + * Reads all of the handlers from the handlers extension point. + * + * @param configurationElements + * The configuration elements in the commands extension point; + * must not be null, but may be empty. + * @param configurationElementCount + * The number of configuration elements that are really in the + * array. + * @param handlerService + * The handler service to which the handlers should be added; + * must not be null. + */ + void ReadHandlersFromRegistry( + const QList >& configurationElements); + +}; + +} + +#endif // BERRYHANDLERPERSISTENCE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerProxy.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerProxy.cpp new file mode 100644 index 0000000000..803238c9ab --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerProxy.cpp @@ -0,0 +1,417 @@ +/*=================================================================== + +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 "berryHandlerProxy.h" + +#include "berryIConfigurationElement.h" +#include "berryIEvaluationContext.h" +#include "berryIEvaluationService.h" +#include "berryICommandService.h" +#include "berryIContributor.h" +#include "berryIEvaluationReference.h" + +#include "berryEvaluationResult.h" +#include "berryExpression.h" +#include "berryCoreException.h" +#include "berryCommandExceptions.h" +#include "berryUtil.h" +#include "berryShell.h" +#include "berryObjects.h" +#include "berryObjectString.h" +#include "berryUIElement.h" +#include "berryRadioState.h" +#include "berryRegistryToggleState.h" +#include "berryHandlerEvent.h" +#include "berryPlatformUI.h" +#include "berryBundleUtility.h" +#include "berryWorkbenchRegistryConstants.h" +#include "berryStatus.h" +#include "berryWorkbenchPlugin.h" + +#include + +namespace berry { + +QHash, HandlerProxy*> HandlerProxy::CEToProxyMap = + QHash(); +const QString HandlerProxy::PROP_ENABLED = "enabled"; + + +HandlerProxy::HandlerProxy(const QString commandId, + const SmartPointer& configurationElement, + const QString handlerAttributeName, + const SmartPointer enabledWhenExpression, + IEvaluationService* evaluationService) + : configurationElement(configurationElement) + , enabledWhenExpression(enabledWhenExpression) + , handlerAttributeName(handlerAttributeName) + , evaluationService(evaluationService) + , proxyEnabled(false) + , commandId(commandId) + , loadException(NULL) +{ + if (configurationElement.IsNull()) + { + throw ctkInvalidArgumentException( + "The configuration element backing a handler proxy cannot be null"); + } + + if (handlerAttributeName.isNull()) + { + throw ctkInvalidArgumentException( + "The attribute containing the handler class must be known"); + } + + if (enabledWhenExpression.IsNotNull() && evaluationService == NULL) + { + throw ctkInvalidArgumentException( + "We must have a handler service and evaluation service to support the enabledWhen expression"); + } + + if (enabledWhenExpression.IsNotNull()) + { + SetProxyEnabled(false); + RegisterEnablement(); + } + else + { + SetProxyEnabled(true); + } + + CEToProxyMap.insert(configurationElement, this); +} + +void HandlerProxy::UpdateStaleCEs(const QList >& replacements) +{ + foreach (const IConfigurationElement::Pointer& ce, replacements) + { + QHash::const_iterator i = CEToProxyMap.find(ce); + if (i != CEToProxyMap.end()) + { + (*i)->configurationElement = ce; + } + } +} + +void HandlerProxy::SetEnabled(const Object::Pointer& evaluationContext) +{ + IEvaluationContext* const context = dynamic_cast(evaluationContext.GetPointer()); + if (context == NULL) + { + return; + } + if (enabledWhenExpression.IsNotNull()) + { + try + { + SetProxyEnabled(enabledWhenExpression->Evaluate(context) == EvaluationResult::TRUE_EVAL); + } + catch (const CoreException& /*e*/) + { + // TODO should we log this exception, or just treat it as + // a failure + } + } + if (IsOkToLoad() && LoadHandler()) + { + handler->SetEnabled(evaluationContext); + } +} + +void HandlerProxy::Dispose() +{ + if (handler.IsNotNull()) + { + handler->RemoveHandlerListener(GetHandlerListener()); + handler->Dispose(); + handler = 0; + } + if (evaluationService) + { + evaluationService->RemoveEvaluationListener(enablementRef); + } + enablementRef = 0; + delete loadException; + loadException = NULL; +} + +Object::Pointer HandlerProxy::Execute(const SmartPointer& event) +{ + if (LoadHandler()) + { + if (!IsEnabled()) + { + Shell::Pointer shell = Util::GetShellToParentOn(); + QWidget* parent = NULL; + if (shell.IsNotNull()) parent = shell->GetControl(); + QMessageBox::information(parent, "Information", "The chosen operation is not enabled."); + return Object::Pointer(0); + } + return handler->Execute(event); + } + + if(loadException != NULL) + throw ExecutionException("Exception occured when loading the handler", *loadException); + + return Object::Pointer(0); +} + +bool HandlerProxy::IsEnabled() const +{ + if (enabledWhenExpression.IsNotNull()) + { + // proxyEnabled reflects the enabledWhen clause + if (!GetProxyEnabled()) + { + return false; + } + if (IsOkToLoad() && LoadHandler()) + { + return handler->IsEnabled(); + } + + return true; + } + + /* + * There is no enabled when expression, so we just need to consult the + * handler. + */ + if (IsOkToLoad() && LoadHandler()) + { + return handler->IsEnabled(); + } + return true; +} + +bool HandlerProxy::IsHandled() const +{ + if (configurationElement.IsNotNull() && handler.IsNull()) + { + return true; + } + + if (IsOkToLoad() && LoadHandler()) + { + return handler->IsHandled(); + } + + return false; +} + +QString HandlerProxy::ToString() const +{ + if (handler.IsNull()) + { + if (configurationElement.IsNotNull()) + { + const QString configurationElementAttribute = GetConfigurationElementAttribute(); + if (!configurationElementAttribute.isEmpty()) + { + return configurationElementAttribute; + } + } + return "HandlerProxy()"; + } + + return handler->ToString(); +} + +void HandlerProxy::UpdateElement(UIElement* element, const QHash& parameters) +{ + if (checkedState.IsNotNull()) + { + ObjectBool::Pointer value = checkedState->GetValue().Cast(); + element->SetChecked(value->GetValue()); + } + else if (radioState.IsNotNull()) + { + ObjectString::Pointer value = radioState->GetValue().Cast(); + Object::Pointer parameter = parameters[RadioState::PARAMETER_ID]; + element->SetChecked(value.IsNotNull() && parameter == value); + } + if (handler.IsNotNull()) + { + if (IElementUpdater::Pointer updater = handler.Cast()) + { + updater->UpdateElement(element, parameters); + } + } +} + +void HandlerProxy::HandleStateChange(const SmartPointer& state, const Object::Pointer& oldValue) +{ + if (state->GetId() == RegistryToggleState::STATE_ID) + { + checkedState = state; + RefreshElements(); + } + else if (state->GetId() == RadioState::STATE_ID) + { + radioState = state; + RefreshElements(); + } + if (IStateListener* stateListener = dynamic_cast(handler.GetPointer())) + { + stateListener->HandleStateChange(state, oldValue); + } +} + +SmartPointer HandlerProxy::GetConfigurationElement() const +{ + return configurationElement; +} + +QString HandlerProxy::GetAttributeName() const +{ + return handlerAttributeName; +} + +SmartPointer HandlerProxy::GetHandler() const +{ + return handler; +} + +void HandlerProxy::RegisterEnablement() +{ + enablementRef = evaluationService->AddEvaluationListener( + enabledWhenExpression, GetEnablementListener(), PROP_ENABLED); +} + +void HandlerProxy::SetProxyEnabled(bool enabled) +{ + proxyEnabled = enabled; +} + +bool HandlerProxy::GetProxyEnabled() const +{ + return proxyEnabled; +} + +IPropertyChangeListener* HandlerProxy::GetEnablementListener() const +{ + return const_cast(this); +} + +void HandlerProxy::PropertyChange(const SmartPointer& event) +{ + if (event->GetProperty() == PROP_ENABLED) + { + SetProxyEnabled(event->GetNewValue().IsNull() ? + false : event->GetNewValue().Cast()->GetValue()); + HandlerEvent::Pointer event(new HandlerEvent(IHandler::Pointer(this), true, false)); + FireHandlerChanged(event); + } +} + +bool HandlerProxy::LoadHandler() const +{ + if (handler.IsNull()) + { + HandlerProxy* self = const_cast(this); + // Load the handler. + try + { + if (configurationElement.IsNotNull()) + { + handler = configurationElement->CreateExecutableExtension(handlerAttributeName); + if (handler.IsNotNull()) + { + handler->AddHandlerListener(GetHandlerListener()); + self->SetEnabled(evaluationService == NULL ? IEvaluationContext::Pointer(0) : evaluationService->GetCurrentState()); + self->RefreshElements(); + return true; + } + else + { + const QString message = "The proxied handler was the wrong class"; + IStatus::Pointer status( + new Status(IStatus::ERROR_TYPE, PlatformUI::PLUGIN_ID(), 0, message, BERRY_STATUS_LOC)); + WorkbenchPlugin::Log(message, status); + configurationElement = 0; + loadException = new ctkException("Class cast exception"); + } + } + } + catch (const CoreException& e) + { + const QString message = "The proxied handler for '" + configurationElement->GetAttribute(handlerAttributeName) + + "' could not be loaded"; + IStatus::Pointer status( + new Status(IStatus::ERROR_TYPE, PlatformUI::PLUGIN_ID(), 0, message, e, BERRY_STATUS_LOC)); + WorkbenchPlugin::Log(message, status); + configurationElement = 0; + loadException = e.clone(); + } + return false; + } + + return true; +} + +IHandlerListener* HandlerProxy::GetHandlerListener() const +{ + return const_cast(this); +} + +void HandlerProxy::HandlerChanged(const SmartPointer& handlerEvent) +{ + HandlerEvent::Pointer event(new HandlerEvent(IHandler::Pointer(this), + handlerEvent->IsEnabledChanged(), + handlerEvent->IsHandledChanged())); + FireHandlerChanged(event); +} + +QString HandlerProxy::GetConfigurationElementAttribute() const +{ + const QString attribute = configurationElement->GetAttribute(handlerAttributeName); + if (attribute.isNull()) + { + QList children = configurationElement->GetChildren(handlerAttributeName); + foreach (const IConfigurationElement::Pointer& child, children) + { + const QString childAttribute = child->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS); + if (!childAttribute.isNull()) + { + return childAttribute; + } + } + } + return attribute; +} + +bool HandlerProxy::IsOkToLoad() const +{ + if (configurationElement.IsNotNull() && handler.IsNull()) + { + const QString bundleId = configurationElement->GetContributor()->GetName(); + return BundleUtility::IsActive(bundleId); + } + return true; +} + +void HandlerProxy::RefreshElements() +{ + if (commandId.isNull() || (!(handler.Cast()) + && (checkedState.IsNull() && radioState.IsNull()))) + { + return; + } + ICommandService* cs = PlatformUI::GetWorkbench()->GetService(); + cs->RefreshElements(commandId, QHash()); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerProxy.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerProxy.h new file mode 100644 index 0000000000..c7d1ed08ff --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerProxy.h @@ -0,0 +1,231 @@ +/*=================================================================== + +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 BERRYHANDLERPROXY_H +#define BERRYHANDLERPROXY_H + +#include "berryAbstractHandlerWithState.h" +#include "berryIElementUpdater.h" +#include "berryIHandlerListener.h" +#include "berryIPropertyChangeListener.h" + +namespace berry { + +struct IConfigurationElement; +struct IEvaluationReference; +struct IEvaluationService; + +class Expression; + +/** + *

+ * A proxy for a handler that has been defined in XML. This delays the class + * loading until the handler is really asked for information (besides the + * priority or the command identifier). Asking a proxy for anything but the + * attributes defined publicly in this class will cause the proxy to instantiate + * the proxied handler. + *

+ */ +class HandlerProxy : public AbstractHandlerWithState, public IElementUpdater, + private IHandlerListener, private IPropertyChangeListener +{ + +public: + + berryObjectMacro(berry::HandlerProxy) + +private: + + static QHash, HandlerProxy*> CEToProxyMap; + + /** + * + */ + static const QString PROP_ENABLED; // = "enabled"; + + /** + * The configuration element from which the handler can be created. This + * value will exist until the element is converted into a real class -- at + * which point this value will be set to null. + */ + mutable SmartPointer configurationElement; + + /** + * The enabledWhen expression for the handler. Only if this + * expression evaluates to true (or the value is + * null) should we consult the handler. + */ + const SmartPointer enabledWhenExpression; + + /** + * The real handler. This value is null until the proxy is + * forced to load the real handler. At this point, the configuration element + * is converted, nulled out, and this handler gains a reference. + */ + mutable SmartPointer handler; + + /** + * The name of the configuration element attribute which contains the + * information necessary to instantiate the real handler. + */ + const QString handlerAttributeName; + + /** + * The evaluation service to use when evaluating + * enabledWhenExpression. This value may be + * null only if the enabledWhenExpression is + * null. + */ + IEvaluationService* evaluationService; + + SmartPointer enablementRef; + + bool proxyEnabled; + + QString commandId; + + // + // state to support checked or radio commands. + SmartPointer checkedState; + + SmartPointer radioState; + + // Exception that occurs while loading the proxied handler class + mutable ctkException* loadException; + +public: + + /** + * Constructs a new instance of HandlerProxy with all the + * information it needs to try to avoid loading until it is needed. + * + * @param commandId the id for this handler + * @param configurationElement + * The configuration element from which the real class can be + * loaded at run-time; must not be null. + * @param handlerAttributeName + * The name of the attribute or element containing the handler + * executable extension; must not be null. + * @param enabledWhenExpression + * The name of the element containing the enabledWhen expression. + * This should be a child of the + * configurationElement. If this value is + * null, then there is no enablement expression + * (i.e., enablement will be delegated to the handler when + * possible). + * @param evaluationService + * The evaluation service to manage enabledWhen expressions + * trying to evaluate the enabledWhenExpression. + * This value may be null only if the + * enabledWhenExpression is null. + */ + HandlerProxy(const QString commandId, + const SmartPointer& configurationElement, + const QString handlerAttributeName, + const SmartPointer enabledWhenExpression = SmartPointer(), + IEvaluationService* evaluationService = NULL); + + static void UpdateStaleCEs(const QList >& replacements); + + void SetEnabled(const Object::Pointer& evaluationContext); + + /** + * Passes the dipose on to the proxied handler, if it has been loaded. + */ + void Dispose(); + + Object::Pointer Execute(const SmartPointer& event); + + bool IsEnabled() const; + + bool IsHandled() const; + + QString ToString() const; + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.commands.IElementUpdater#updateElement(org.eclipse.ui.menus.UIElement, + * java.util.Map) + */ + void UpdateElement(UIElement* element, const QHash& parameters); + + /* (non-Javadoc) + * @see org.eclipse.core.commands.IStateListener#handleStateChange(org.eclipse.core.commands.State, java.lang.Object) + */ + void HandleStateChange(const SmartPointer& state, const Object::Pointer& oldValue); + + /** + * @return the config element for use with the PDE framework. + */ + SmartPointer GetConfigurationElement() const; + + QString GetAttributeName() const; + + /** + * @return Returns the handler. + */ + SmartPointer GetHandler() const; + +private: + + /** + * + */ + void RegisterEnablement(); + + void SetProxyEnabled(bool enabled); + + bool GetProxyEnabled() const; + + /** + * @return + */ + IPropertyChangeListener* GetEnablementListener() const; + + using IPropertyChangeListener::PropertyChange; + void PropertyChange(const SmartPointer& event); + + /** + * Loads the handler, if possible. If the handler is loaded, then the member + * variables are updated accordingly. + * + * @return true if the handler is now non-null; + * false otherwise. + */ + bool LoadHandler() const; + + IHandlerListener* GetHandlerListener() const; + + void HandlerChanged(const SmartPointer& handlerEvent); + + /** + * Retrives the ConfigurationElement attribute according to the + * handlerAttributeName. + * + * @return the handlerAttributeName value, may be null. + */ + QString GetConfigurationElementAttribute() const; + + bool IsOkToLoad() const; + + void RefreshElements(); + +}; + +} + +#endif // BERRYHANDLERPROXY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerService.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerService.cpp new file mode 100644 index 0000000000..8f114d12ba --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerService.cpp @@ -0,0 +1,278 @@ +/*=================================================================== + +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 "berryHandlerService.h" + +#include "berryHandlerAuthority.h" +#include "berryHandlerPersistence.h" +#include "berryIHandler.h" +#include "berryHandlerActivation.h" +#include "berryExpression.h" +#include "berryExecutionEvent.h" +#include "berryParameterizedCommand.h" +#include "berryICommandService.h" +#include "berryUIElement.h" + +namespace berry { + +HandlerService::HandlerService(ICommandService* commandService, + IEvaluationService* evaluationService, + IServiceLocator* locator) + : commandService(commandService) + , handlerAuthority(new HandlerAuthority(commandService, locator)) + , handlerPersistence(new HandlerPersistence(this, evaluationService)) +{ + if (commandService == NULL) + { + throw ctkInvalidArgumentException("A handler service requires a command service"); + } +} + +SmartPointer HandlerService::ActivateHandler( + const SmartPointer& childActivation) +{ + const QString commandId = childActivation->GetCommandId(); + const IHandler::Pointer handler = childActivation->GetHandler(); + const Expression::Pointer expression = childActivation->GetExpression(); + const int depth = childActivation->GetDepth() + 1; + const IHandlerActivation::Pointer localActivation( + new HandlerActivation(commandId, handler, expression, depth, this)); + handlerAuthority->ActivateHandler(localActivation); + return localActivation; +} + +SmartPointer HandlerService::ActivateHandler(const QString& commandId, + const SmartPointer& handler) +{ + return ActivateHandler(commandId, handler, Expression::Pointer(0)); +} + +SmartPointer HandlerService::ActivateHandler(const QString& commandId, + const SmartPointer& handler, + const SmartPointer& expression) +{ + return ActivateHandler(commandId, handler, expression, false); +} + +SmartPointer HandlerService::ActivateHandler(const QString& commandId, + const SmartPointer& handler, + const SmartPointer& expression, + bool /*global*/) +{ + const IHandlerActivation::Pointer activation( + new HandlerActivation(commandId, handler, expression, IHandlerActivation::ROOT_DEPTH, this)); + handlerAuthority->ActivateHandler(activation); + return activation; +} + +void HandlerService::AddSourceProvider(const SmartPointer& /*provider*/) +{ + // no-op +} + +SmartPointer HandlerService::CreateExecutionEvent(const SmartPointer& command, + const SmartPointer& trigger) +{ + ExecutionEvent::Pointer event(new ExecutionEvent(command, ExecutionEvent::ParameterMap(), trigger, + Object::Pointer(GetCurrentState()))); + return event; +} + +SmartPointer HandlerService::CreateExecutionEvent( + const SmartPointer& command, + const SmartPointer& trigger) +{ + ExecutionEvent::Pointer event( + new ExecutionEvent(command->GetCommand(), command->GetParameterMap(), trigger, + Object::Pointer(GetCurrentState()))); + return event; +} + +void HandlerService::DeactivateHandler(const SmartPointer& activation) +{ + if (activation->GetHandlerService() == this) + { + handlerAuthority->DeactivateHandler(activation); + } +} + +void HandlerService::DeactivateHandlers(const QList >& activations) +{ + foreach (const IHandlerActivation::Pointer activation, activations) + { + DeactivateHandler(activation); + } +} + +void HandlerService::Dispose() +{ + handlerPersistence.reset(); + handlerAuthority.reset(); +} + +Object::Pointer HandlerService::ExecuteCommand(const SmartPointer& command, + const SmartPointer& trigger) +{ + return command->ExecuteWithChecks(trigger, Object::Pointer(GetCurrentState())); +} + +Object::Pointer HandlerService::ExecuteCommand(const QString& commandId, + const SmartPointer& trigger) +{ + const Command::Pointer command = commandService->GetCommand(commandId); + const ExecutionEvent::Pointer event( + new ExecutionEvent(command, ExecutionEvent::ParameterMap(), trigger, + Object::Pointer(GetCurrentState()))); + return command->ExecuteWithChecks(event); +} + +Object::Pointer HandlerService::ExecuteCommandInContext(const SmartPointer& command, + const SmartPointer& trigger, + const SmartPointer& context) +{ + IHandler::Pointer oldHandler = command->GetCommand()->GetHandler(); + + IHandler::Pointer handler = FindHandler(command->GetId(), context.GetPointer()); + handler->SetEnabled(context); + + struct RestoreHandlerState { + RestoreHandlerState(HandlerService* hs, ParameterizedCommand* cmd, IHandler* handler, IHandler* oldHandler) + : hs(hs), cmd(cmd), handler(handler), oldHandler(oldHandler) {} + ~RestoreHandlerState() { + cmd->GetCommand()->SetHandler(IHandler::Pointer(oldHandler)); + handler->SetEnabled(hs->GetCurrentState()); + } + private: + HandlerService* hs; + ParameterizedCommand* cmd; + IHandler* handler; + IHandler* oldHandler; + }; + + RestoreHandlerState restorer(this, command.GetPointer(), handler.GetPointer(), oldHandler.GetPointer()); + command->GetCommand()->SetHandler(handler); + return command->ExecuteWithChecks(trigger, context); + } + +SmartPointer HandlerService::GetCurrentState() const +{ + return handlerAuthority->GetCurrentState(); +} + +void HandlerService::ReadRegistry() +{ + handlerPersistence->Read(); +} + +void HandlerService::RemoveSourceProvider(const SmartPointer& /*provider*/) +{ + // this is a no-op +} + +void HandlerService::SetHelpContextId(const SmartPointer& handler, + const QString& helpContextId) +{ + commandService->SetHelpContextId(handler, helpContextId); +} + +/* + *

+ * Bug 95792. A mechanism by which the key binding architecture can force an + * update of the handlers (based on the active shell) before trying to + * execute a command. This mechanism is required for GTK+ only. + *

+ *

+ * DO NOT CALL THIS METHOD. + *

+ */ +// void UpdateShellKludge() { +// handlerAuthority.updateShellKludge(); +// } + +/* + *

+ * Bug 95792. A mechanism by which the key binding architecture can force an + * update of the handlers (based on the active shell) before trying to + * execute a command. This mechanism is required for GTK+ only. + *

+ *

+ * DO NOT CALL THIS METHOD. + *

+ * + * @param shell + * The shell that should be considered active; must not be + * null. + */ +// void UpdateShellKludge(const SmartPointer& shell) +// { +// handlerAuthority.updateShellKludge(shell); +// } + +SmartPointer HandlerService::FindHandler(const QString& commandId, + IEvaluationContext* context) +{ + return handlerAuthority->FindHandler(commandId, context); +} + +/* + * (non-Javadoc) + * + * @see org.eclipse.ui.handlers.IHandlerService#createContextSnapshot(boolean) + */ +SmartPointer HandlerService::CreateContextSnapshot(bool includeSelection) +{ + return handlerAuthority->CreateContextSnapshot(includeSelection); +} + +Object::Pointer HandlerService::ExecuteCommandInContext( + const SmartPointer& command, + const SmartPointer& trigger, + IEvaluationContext* context) +{ + IHandler::Pointer oldHandler = command->GetCommand()->GetHandler(); + + IHandler::Pointer handler = FindHandler(command->GetId(), context); + handler->SetEnabled(Object::Pointer(context)); + + struct RestoreHandler { + RestoreHandler(HandlerService* hs, ParameterizedCommand* cmd, IHandler* handler, IHandler* oldHandler) + : hs(hs), cmd(cmd), handler(handler), oldHandler(oldHandler) + {} + + ~RestoreHandler() + { + cmd->GetCommand()->SetHandler(IHandler::Pointer(oldHandler)); + handler->SetEnabled(Object::Pointer(hs->GetCurrentState())); + } + + HandlerService* const hs; + ParameterizedCommand* const cmd; + IHandler* const handler; + IHandler* const oldHandler; + }; + + RestoreHandler restorer(this, command.GetPointer(), handler.GetPointer(), oldHandler.GetPointer()); + command->GetCommand()->SetHandler(handler); + + return command->ExecuteWithChecks(trigger, Object::Pointer(context)); +} + +HandlerPersistence* HandlerService::GetHandlerPersistence() +{ + return handlerPersistence.data(); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerService.h new file mode 100644 index 0000000000..41ed303673 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerService.h @@ -0,0 +1,193 @@ +/*=================================================================== + +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 BERRYHANDLERSERVICE_H +#define BERRYHANDLERSERVICE_H + +#include "berryIHandlerService.h" + +namespace berry { + +struct ICommandService; +struct IEvaluationService; +struct IServiceLocator; + +class HandlerAuthority; +class HandlerPersistence; + +/** + *

+ * Provides services related to activating and deactivating handlers within the + * workbench. + *

+ */ +class HandlerService : public IHandlerService +{ + +private: + + /** + * The command service for this handler service. This value is never + * null. + */ + ICommandService* const commandService; + + /** + * The central authority for determining which handler we should use. + */ + QScopedPointer handlerAuthority; + + /** + * The class providing persistence for this service. + */ + QScopedPointer handlerPersistence; + +public: + + /** + * Constructs a new instance of CommandService using a + * command manager. + * + * @param commandService + * The command service to use; must not be null. + * @param evaluationService + * The evaluation service to use; must not be null. + * @param locator + * an appropriate service locator + */ + HandlerService(ICommandService* commandService, + IEvaluationService* evaluationService, + IServiceLocator* locator); + + SmartPointer ActivateHandler( + const SmartPointer& childActivation); + + SmartPointer ActivateHandler(const QString& commandId, + const SmartPointer& handler); + + SmartPointer ActivateHandler(const QString& commandId, + const SmartPointer& handler, + const SmartPointer& expression); + + SmartPointer ActivateHandler(const QString& commandId, + const SmartPointer& handler, + const SmartPointer& expression, + bool global); + + void AddSourceProvider(const SmartPointer& provider); + + SmartPointer CreateExecutionEvent(const SmartPointer& command, + const SmartPointer& trigger); + + SmartPointer CreateExecutionEvent( + const SmartPointer& command, + const SmartPointer& trigger); + + void DeactivateHandler(const SmartPointer& activation); + + void DeactivateHandlers(const QList >& activations); + + void Dispose(); + + Object::Pointer ExecuteCommand(const SmartPointer& command, + const SmartPointer& trigger); + + Object::Pointer ExecuteCommand(const QString& commandId, + const SmartPointer& trigger); + + Object::Pointer ExecuteCommandInContext(const SmartPointer& command, + const SmartPointer& trigger, + const SmartPointer& context); + + SmartPointer GetCurrentState() const; + + void ReadRegistry(); + + void RemoveSourceProvider(const SmartPointer& provider); + + void SetHelpContextId(const SmartPointer& handler, + const QString& helpContextId); + + /* + *

+ * Bug 95792. A mechanism by which the key binding architecture can force an + * update of the handlers (based on the active shell) before trying to + * execute a command. This mechanism is required for GTK+ only. + *

+ *

+ * DO NOT CALL THIS METHOD. + *

+ */ +// void UpdateShellKludge() { +// handlerAuthority.updateShellKludge(); +// } + + /* + *

+ * Bug 95792. A mechanism by which the key binding architecture can force an + * update of the handlers (based on the active shell) before trying to + * execute a command. This mechanism is required for GTK+ only. + *

+ *

+ * DO NOT CALL THIS METHOD. + *

+ * + * @param shell + * The shell that should be considered active; must not be + * null. + */ +// void UpdateShellKludge(const SmartPointer& shell) +// { +// handlerAuthority.updateShellKludge(shell); +// } + + /** + * Currently this is a an internal method to help locate a handler. + *

+ * DO NOT CALL THIS METHOD. + *

+ * + * @param commandId + * the command id to check + * @param context + * the context to use for activations + * @return the correct IHandler or null + * @since 3.3 + */ + SmartPointer FindHandler(const QString& commandId, + IEvaluationContext* context); + + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.handlers.IHandlerService#createContextSnapshot(boolean) + */ + SmartPointer CreateContextSnapshot(bool includeSelection); + + Object::Pointer ExecuteCommandInContext( + const SmartPointer& command, + const SmartPointer& trigger, + IEvaluationContext* context); + + /** + * @return Returns the handlerPersistence. + */ + HandlerPersistence* GetHandlerPersistence(); +}; + +} + +#endif // BERRYHANDLERSERVICE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerServiceFactory.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerServiceFactory.cpp new file mode 100644 index 0000000000..fb3b8eaa81 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerServiceFactory.cpp @@ -0,0 +1,85 @@ +/*=================================================================== + +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 "berryHandlerServiceFactory.h" + +#include "berryIHandlerService.h" +#include "berryIWorkbenchLocationService.h" +#include "berryIWorkbench.h" +#include "berryIWorkbenchWindow.h" +#include "berryIWorkbenchPartSite.h" +#include "berryICommandService.h" +#include "berryIEvaluationService.h" + +#include "berryExpression.h" +#include "berryHandlerService.h" +#include "berryActivePartExpression.h" +#include "berryWorkbenchWindowExpression.h" +#include "berrySlaveHandlerService.h" +#include "berryNestableHandlerService.h" + +namespace berry { + +Object* HandlerServiceFactory::Create( + const QString& serviceInterface, IServiceLocator* parentLocator, + IServiceLocator* locator) const +{ + if (serviceInterface != qobject_interface_iid()) + { + return NULL; + } + + IWorkbenchLocationService* wls = locator->GetService(); + IWorkbench* const wb = wls->GetWorkbench(); + if (wb == NULL) + { + return NULL; + } + + Object* parent = parentLocator->GetService(serviceInterface); + if (parent == NULL) + { + ICommandService* commands = locator->GetService(); + IEvaluationService* evals = locator->GetService(); + HandlerService* handlerService = new HandlerService(commands, evals, locator); + handlerService->ReadRegistry(); + return handlerService; + } + + return NULL; + + IWorkbenchWindow* const window = wls->GetWorkbenchWindow(); + IWorkbenchPartSite* const site = wls->GetPartSite(); + if (site == NULL) + { + Expression::Pointer exp(new WorkbenchWindowExpression(window)); + return new SlaveHandlerService(dynamic_cast(parent), exp); + } + + if (SlaveHandlerService* slaveParent = dynamic_cast(parent)) + { + Expression::Pointer parentExp = slaveParent->GetDefaultExpression(); + if (parentExp.Cast()) + { + return new NestableHandlerService(dynamic_cast(parent), parentExp); + } + } + + Expression::Pointer exp(new ActivePartExpression(site->GetPart().GetPointer())); + return new SlaveHandlerService(dynamic_cast(parent), exp); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtDnDTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerServiceFactory.h old mode 100755 new mode 100644 similarity index 57% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtDnDTweaklet.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerServiceFactory.h index 57589ad2f8..af96be2213 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtDnDTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerServiceFactory.h @@ -1,40 +1,37 @@ /*=================================================================== 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 BERRYHANDLERSERVICEFACTORY_H +#define BERRYHANDLERSERVICEFACTORY_H -#ifndef BERRYQTDNDTWEAKLET_H_ -#define BERRYQTDNDTWEAKLET_H_ - -#include +#include "berryIServiceFactory.h" namespace berry { -class QtDnDTweaklet : public QObject, public DnDTweaklet +class HandlerServiceFactory : public QObject, public IServiceFactory { Q_OBJECT - Q_INTERFACES(berry::DnDTweaklet) + Q_INTERFACES(berry::IServiceFactory) public: - QtDnDTweaklet(); - QtDnDTweaklet(const QtDnDTweaklet& other); - - ITracker* CreateTracker(); + Object* Create(const QString& serviceInterface, IServiceLocator* parentLocator, + IServiceLocator* locator) const; }; } -#endif /* BERRYQTDNDTWEAKLET_H_ */ +#endif // BERRYHANDLERSERVICEFACTORY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDragOverListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDragOverListener.cpp index a811c62bbd..2e79884de5 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDragOverListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDragOverListener.cpp @@ -1,41 +1,41 @@ /*=================================================================== 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 "berryIDragOverListener.h" namespace berry { -void -IDragOverListener::Events -::AddListener(IDragOverListener::Pointer l) +void IDragOverListener::Events::AddListener(IDragOverListener* l) { - if (l.IsNull()) return; + if (l == NULL) return; - drag += DragDelegate(l.GetPointer(), &IDragOverListener::Drag); + drag += DragDelegate(l, &IDragOverListener::Drag); } -void -IDragOverListener::Events -::RemoveListener(IDragOverListener::Pointer l) +void IDragOverListener::Events::RemoveListener(IDragOverListener* l) { - if (l.IsNull()) return; + if (l == NULL) return; - drag -= DragDelegate(l.GetPointer(), &IDragOverListener::Drag); + drag -= DragDelegate(l, &IDragOverListener::Drag); } +IDragOverListener::~IDragOverListener() +{ +} + } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDragOverListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDragOverListener.h index 9210699901..8ecc015846 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDragOverListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIDragOverListener.h @@ -1,67 +1,67 @@ /*=================================================================== 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 BERRYIDRAGOVERLISTENER_H_ #define BERRYIDRAGOVERLISTENER_H_ -#include #include #include "berryPoint.h" #include "berryRectangle.h" #include "berryIDropTarget.h" namespace berry { /** * Implementers of this interface will receive notifications when objects are dragged over * a particular control. */ -struct IDragOverListener : public virtual Object { - - berryObjectMacro(IDragOverListener); +struct IDragOverListener +{ struct Events { - typedef Message4 DragEventType; - typedef MessageDelegate4 DragDelegate; + typedef Message4 DragEventType; + typedef MessageDelegate4 DragDelegate; DragEventType drag; - void AddListener(IDragOverListener::Pointer listener); - void RemoveListener(IDragOverListener::Pointer listener); + void AddListener(IDragOverListener* listener); + void RemoveListener(IDragOverListener* listener); }; + virtual ~IDragOverListener(); + /** * Notifies the receiver that the given object has been dragged over * the given position. Returns a drop target if the object may be * dropped in this position. Returns null otherwise. * * @param draggedObject object being dragged over this location * @param position location of the cursor * @param dragRectangle current drag rectangle (may be an empty rectangle if none) * @return a valid drop target or null if none */ - virtual IDropTarget::Pointer Drag(void* currentControl, Object::Pointer draggedObject, + virtual IDropTarget::Pointer Drag(void* currentControl, const Object::Pointer& draggedObject, const Point& position, const Rectangle& dragRectangle) = 0; }; } #endif /* BERRYIDRAGOVERLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIEvaluationResultCache.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIEvaluationResultCache.h index 092513c78a..5f49986a7b 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIEvaluationResultCache.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIEvaluationResultCache.h @@ -1,100 +1,100 @@ /*=================================================================== 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 BERRYIEVALUATIONRESULTCACHE_H_ #define BERRYIEVALUATIONRESULTCACHE_H_ #include #include #include namespace berry { struct IEvaluationContext; class Expression; /** *

* A cache of the result of an expression. This also provides the source * priority for the expression. *

*

* This interface is not intended to be implemented or extended by clients. *

* * @see ISources * @see ISourceProvider */ -struct BERRY_UI_QT IEvaluationResultCache : public Object +struct BERRY_UI_QT IEvaluationResultCache : public virtual Object { - berryInterfaceMacro(IEvaluationResultCache, berry); + berryObjectMacro(berry::IEvaluationResultCache) ~IEvaluationResultCache(); /** * Clears the cached computation of the evaluate method, if * any. This method is only intended for internal use. It provides a * mechanism by which ISourceProvider events can invalidate * state on a IEvaluationResultCache instance. */ virtual void ClearResult() = 0; /** * Returns the expression controlling the activation or visibility of this * item. * * @return The expression associated with this item; may be * null. */ virtual SmartPointer GetExpression() const = 0; /** * Returns the priority that has been given to this expression. * * @return The priority. * @see ISources */ virtual int GetSourcePriority() const = 0; /** * Evaluates the expression -- given the current state of the workbench. * This method should cache its computation. The cache will be cleared by a * call to clearResult. * * @param context * The context in which this state should be evaluated; must not * be null. * @return true if the expression currently evaluates to * true; false otherwise. */ virtual bool Evaluate(IEvaluationContext* context) const = 0; /** * Forces the cached result to be a particular value. This will not * notify any users of the cache that it has changed. * * @param result * The cached result to use. */ virtual void SetResult(bool result) = 0; }; } #endif /* BERRYIEVALUATIONRESULTCACHE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIServiceLocatorCreator.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIServiceLocatorCreator.h index e5513f6d97..bd56143831 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIServiceLocatorCreator.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIServiceLocatorCreator.h @@ -1,92 +1,92 @@ /*=================================================================== 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 BERRYISERVICELOCATORCREATOR_H_ #define BERRYISERVICELOCATORCREATOR_H_ #include #include #include namespace berry { struct IServiceLocator; struct IServiceFactory; struct IDisposable; /** * When creating components this service can be used to create the appropriate * service locator for the new component. For use with the component framework. *

* Note: Must not be implemented or extended by clients. *

*

* PROVISIONAL. This class or interface has been added as part * of a work in progress. There is a guarantee neither that this API will work * nor that it will remain the same. Please do not use this API without * consulting with the Platform/UI team. This might disappear in 3.4 M5. *

* * * @since 3.4 */ struct BERRY_UI_QT IServiceLocatorCreator : public virtual Object { - berryInterfaceMacro(IServiceLocatorCreator, berry) + berryObjectMacro(berry::IServiceLocatorCreator) ~IServiceLocatorCreator(); /** * Creates a service locator that can be used for hosting a new service * context. It will have the appropriate child services created as needed, * and can be used with the Dependency Injection framework to reuse * components (by simply providing your own implementation for certain * services). * * @param parent * the parent locator * @param factory * a factory that can lazily provide services if requested. This * may be null * @param owner * an object whose {@link IDisposable#dispose()} method will be * called on the UI thread if the created service locator needs * to be disposed (typically, because a plug-in contributing * services to the service locator via an * {@link AbstractServiceFactory} is no longer available). The * owner can be any object that implements {@link IDisposable}. * The recommended implementation of the owner's dispose method * is to do whatever is necessary to stop using the created * service locator, and then to call * {@link IDisposable#dispose()} on the service locator. * @return the created service locator. The returned service locator will be * an instance of {@link IDisposable}. */ virtual SmartPointer CreateServiceLocator( IServiceLocator* parent, - const SmartPointer factory, + const IServiceFactory* factory, WeakPointer owner) = 0; }; } -Q_DECLARE_INTERFACE(berry::IServiceLocatorCreator, "org.blueberry.ui.qt.IServiceLocatorCreator") +Q_DECLARE_INTERFACE(berry::IServiceLocatorCreator, "org.blueberry.ui.IServiceLocatorCreator") #endif /* BERRYISERVICELOCATORCREATOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIStickyViewManager.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIStickyViewManager.h index ec9a1203a9..722d66ac2e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIStickyViewManager.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIStickyViewManager.h @@ -1,54 +1,55 @@ /*=================================================================== 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 BERRYISTICKYVIEWMANAGER_H_ #define BERRYISTICKYVIEWMANAGER_H_ #include #include #include #include namespace berry { class Perspective; -struct BERRY_UI_QT IStickyViewManager : public Object { +struct BERRY_UI_QT IStickyViewManager : public Object +{ - berryInterfaceMacro(IStickyViewManager, berry); + berryObjectMacro(berry::IStickyViewManager) ~IStickyViewManager(); virtual void Remove(const QString& perspectiveId) = 0; virtual void Add(const QString& perspectiveId, const std::set& stickyViewSet) = 0; virtual void Clear() = 0; virtual void Update(SmartPointer oldPersp, SmartPointer newPersp) = 0; virtual void Save(IMemento::Pointer memento) = 0; virtual void Restore(IMemento::Pointer memento) = 0; }; } #endif /* BERRYISTICKYVIEWMANAGER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIWorkbenchLocationService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIWorkbenchLocationService.h index de6bb1059a..ffcb45ff6f 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIWorkbenchLocationService.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryIWorkbenchLocationService.h @@ -1,86 +1,86 @@ /*=================================================================== 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 BERRYIWORKBENCHLOCATIONSERVICE_H_ #define BERRYIWORKBENCHLOCATIONSERVICE_H_ #include -#include #include namespace berry { struct IWorkbench; struct IWorkbenchWindow; struct IWorkbenchPartSite; struct IPageSite; /** * Query where you are in the workbench hierarchy. * */ -struct BERRY_UI_QT IWorkbenchLocationService : public Object +struct BERRY_UI_QT IWorkbenchLocationService : public virtual Object { - berryInterfaceMacro(IWorkbenchLocationService, berry); + berryObjectMacro(berry::IWorkbenchLocationService) ~IWorkbenchLocationService(); /** * Get the service scope. * * @return the service scope. May return null. * @see IServiceScopes#PARTSITE_SCOPE */ virtual QString GetServiceScope() const = 0; /** * A more numeric representation of the service level. * * @return the level - 0==workbench, 1==workbench window, etc */ virtual int GetServiceLevel() const = 0; /** * @return the workbench. May return null. */ virtual IWorkbench* GetWorkbench() const = 0; /** * @return the workbench window in this service locator hierarchy. May * return null. */ - virtual SmartPointer GetWorkbenchWindow() const = 0; + virtual IWorkbenchWindow* GetWorkbenchWindow() const = 0; /** * @return the part site in this service locator hierarchy. May return * null. */ - virtual SmartPointer GetPartSite() const = 0; + virtual IWorkbenchPartSite* GetPartSite() const = 0; /** * @return the inner page site for a page based view in this service locator * hierarchy. May return null. * @see PageBookView */ - virtual SmartPointer GetPageSite() const = 0; + //virtual SmartPointer GetPageSite() const = 0; }; } +Q_DECLARE_INTERFACE(berry::IWorkbenchLocationService, "org.blueberry.ui.IWorkbenchLocationService") #endif /* BERRYIWORKBENCHLOCATIONSERVICE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryInternalMenuService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryInternalMenuService.h index 36979b4c64..2386d0e003 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryInternalMenuService.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryInternalMenuService.h @@ -1,91 +1,91 @@ /*=================================================================== 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 BERRYINTERNALMENUSERVICE_H #define BERRYINTERNALMENUSERVICE_H #include #include namespace berry { struct IContributionItem; struct IEvaluationReference; struct IServiceLocator; class Expression; class MenuAdditionCacheEntry; /** * Internal baseclass for Workbench and Window menu service implementations. * Methods in this class might some day make sense to live in IMenuService. */ struct InternalMenuService : public IMenuService { /** * Ties an expression to {@link IContributionItem#SetVisible(bool)}. * * @param item * the item * @param visibleWhen * the expression * @param restriction * the restriction expression * @param identifierId * the activity identifier id */ virtual void RegisterVisibleWhen(const SmartPointer& item, const SmartPointer& visibleWhen, - const QSet >& restriction, + QSet >& restriction, const QString& identifierID) = 0; /** * Removes any expressions bound to * {@link IContributionItem#SetVisible(bool)} of the given item * * @param item * the item to unbind */ virtual void UnregisterVisibleWhen(const SmartPointer& item, - const QSet >& restriction) = 0; + QSet >& restriction) = 0; /** * Return a list of {@link MenuAdditionCacheEntry} objects that are * contributed at the given uri. * * @param uri * the uri to search on * @return the list of items */ virtual QList > GetAdditionsForURI(const QUrl& uri) = 0; virtual void PopulateContributionManager(IServiceLocator* serviceLocatorToUse, const QSet >& restriction, ContributionManager* mgr, const QString& uri, bool recurse) = 0; virtual void PopulateContributionManager(ContributionManager* mgr, const QString& uri, bool recurse) = 0; using IMenuService::PopulateContributionManager; }; } #endif // BERRYINTERNALMENUSERVICE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.cpp index ed929a1e63..00fc90488c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.cpp @@ -1,347 +1,347 @@ /*=================================================================== 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 "tweaklets/berryGuiWidgetsTweaklet.h" #include "berryLayoutPart.h" #include "berryILayoutContainer.h" #include "berryDetachedWindow.h" #include "berryIWorkbenchWindow.h" #include "berryConstants.h" namespace berry { const QString LayoutPart::PROP_VISIBILITY = "PROP_VISIBILITY"; LayoutPart::LayoutPart(const QString& id_) : container(0), id(id_), deferCount(0) { } LayoutPart::~LayoutPart() { } bool LayoutPart::AllowsAutoFocus() { if (container != 0) { return container->AllowsAutoFocus(); } return true; } void LayoutPart::Dispose() { } Rectangle LayoutPart::GetBounds() { if (this->GetControl() == 0) return Rectangle(); return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetControl()); } ILayoutContainer::Pointer LayoutPart::GetContainer() { return ILayoutContainer::Pointer(container); } bool LayoutPart::IsPlaceHolder() const { return false; } QString LayoutPart::GetID() const { return id; } bool LayoutPart::IsCompressible() { return false; } Point LayoutPart::GetSize() { Rectangle r = this->GetBounds(); Point ptSize(r.width, r.height); return ptSize; } int LayoutPart::GetSizeFlags(bool /*horizontal*/) { return Constants::MIN; } int LayoutPart::ComputePreferredSize(bool /*width*/, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredParallel) { return preferredParallel; } IDropTarget::Pointer LayoutPart::GetDropTarget(Object::Pointer /*draggedObject*/, const Point& /*displayCoordinates*/) { return IDropTarget::Pointer(0); } bool LayoutPart::IsDocked() { Shell::Pointer s = this->GetShell(); if (s == 0) { return false; } return s->GetData().Cast() != 0; } Shell::Pointer LayoutPart::GetShell() { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(ctrl); } return Shell::Pointer(0); } IWorkbenchWindow::Pointer LayoutPart::GetWorkbenchWindow() { Shell::Pointer s = this->GetShell(); if (s == 0) { return IWorkbenchWindow::Pointer(0); } Object::Pointer data = s->GetData(); if (data.Cast() != 0) { return data.Cast(); } else if (data.Cast() != 0) { return data.Cast()->GetWorkbenchPage()->GetWorkbenchWindow(); } return IWorkbenchWindow::Pointer(0); } void LayoutPart::MoveAbove(void* /*refControl*/) { } void LayoutPart::Reparent(void* newParent) { void* control = this->GetControl(); GuiWidgetsTweaklet* guiTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if ((control == 0) || (guiTweaklet->GetParent(control) == newParent)) { return; } if (guiTweaklet->IsReparentable(control)) { // make control small in case it is not resized with other controls //control.setBounds(0, 0, 0, 0); // By setting the control to disabled before moving it, // we ensure that the focus goes away from the control and its children // and moves somewhere else bool enabled = guiTweaklet->GetEnabled(control); guiTweaklet->SetEnabled(control, false); guiTweaklet->SetParent(control, newParent); guiTweaklet->SetEnabled(control, enabled); guiTweaklet->MoveAbove(control, 0); } } bool LayoutPart::GetVisible() { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(ctrl); } return false; } bool LayoutPart::IsVisible() { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsVisible(ctrl); } return false; } void LayoutPart::SetVisible(bool makeVisible) { void* ctrl = this->GetControl(); if (ctrl != 0) { if (makeVisible == Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(ctrl)) { return; } // if (!makeVisible && this->IsFocusAncestor(ctrl)) // { // // Workaround for Bug 60970 [EditorMgmt] setActive() called on an editor when it does not have focus. // // Force focus on the shell so that when ctrl is hidden, // // SWT does not try to send focus elsewhere, which may cause // // some other part to be activated, which affects the part // // activation order and can cause flicker. // ctrl.getShell().forceFocus(); // } Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(ctrl, makeVisible); } } bool LayoutPart::IsFocusAncestor(void* /*ctrl*/) { // Control f = ctrl.getDisplay().getFocusControl(); // while (f != null && f != ctrl) // { // f = f.getParent(); // } // return f == ctrl; return false; } void LayoutPart::SetBounds(const Rectangle& r) { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(ctrl, r); } } void LayoutPart::SetContainer(ILayoutContainer::Pointer container) { this->container = container.GetPointer(); //TODO Zoom // if (container != 0) // { // setZoomed(container.childIsZoomed(this)); // } } void LayoutPart::SetFocus() { } void LayoutPart::SetID(const QString& str) { id = str; } LayoutPart::Pointer LayoutPart::GetPart() { return LayoutPart::Pointer(this); } void LayoutPart::DeferUpdates(bool shouldDefer) { if (shouldDefer) { if (deferCount == 0) { this->StartDeferringEvents(); } deferCount++; } else { if (deferCount> 0) { deferCount--; if (deferCount == 0) { this->HandleDeferredEvents(); } } } } void LayoutPart::StartDeferringEvents() { } void LayoutPart::HandleDeferredEvents() { } bool LayoutPart::IsDeferred() { return deferCount> 0; } void LayoutPart::DescribeLayout(QString& /*buf*/) const { } QString LayoutPart::GetPlaceHolderId() { return this->GetID(); } void LayoutPart::ResizeChild(LayoutPart::Pointer /*childThatChanged*/) { } void LayoutPart::FlushLayout() { ILayoutContainer::Pointer container = this->GetContainer(); if (container != 0) { container->ResizeChild(LayoutPart::Pointer(this)); } } bool LayoutPart::AllowsAdd(LayoutPart::Pointer /*toAdd*/) { return false; } -QString LayoutPart::ToString() +QString LayoutPart::ToString() const { return ""; } void LayoutPart::TestInvariants() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.h index 70b2588d4f..182d188152 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPart.h @@ -1,305 +1,305 @@ /*=================================================================== 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 BERRYLAYOUTPART_H_ #define BERRYLAYOUTPART_H_ #include #include "berryIDropTarget.h" #include "berryISizeProvider.h" #include "berryRectangle.h" #include "berryPoint.h" #include "berryShell.h" namespace berry { struct ILayoutContainer; struct IWorkbenchWindow; /** * \ingroup org_blueberry_ui_internal * * A presentation part is used to build the presentation for the * workbench. Common subclasses are pane and folder. */ class LayoutPart : virtual public Object, public virtual ISizeProvider { public: berryObjectMacro(LayoutPart) protected: ILayoutContainer* container; protected: QString id; public: static const QString PROP_VISIBILITY;// = "PROP_VISIBILITY"; /** * Number of times deferUpdates(true) has been called without a corresponding * deferUpdates(false) */ private: int deferCount; /** * PresentationPart constructor comment. */ public: LayoutPart(const QString& id); public: virtual ~LayoutPart(); /** * When a layout part closes, focus will return to a previously active part. * This method determines whether this part should be considered for activation * when another part closes. If a group of parts are all closing at the same time, * they will all return false from this method while closing to ensure that the * parent does not activate a part that is in the process of closing. Parts will * also return false from this method if they are minimized, closed fast views, * obscured by zoom, etc. * * @return true iff the parts in this container may be given focus when the active * part is closed */ public: virtual bool AllowsAutoFocus(); /** * Creates the GUI control */ public: virtual void CreateControl(void* parent) = 0; /** * Disposes the GUI control * * This can be used to execute cleanup code or notify listeners * when a LayoutPart is no longer used, but is still referenced * by a SmartPointer (instead of putting the code in the LayoutPart * destructor). */ public: virtual void Dispose(); /** * Gets the presentation bounds. */ public: Rectangle GetBounds(); /** * Gets the parent for this part. *

* In general, this is non-null if the object has been added to a container and the * container's widgetry exists. The exception to this rule is PartPlaceholders * created when restoring a ViewStack using restoreState, which point to the * ViewStack even if its widgetry doesn't exist yet. Returns null in the remaining * cases. *

*

* TODO: change the semantics of this method to always point to the parent container, * regardless of whether its widgetry exists. Locate and refactor code that is currently * depending on the special cases. *

*/ public: virtual SmartPointer GetContainer(); /** * Get the part control. This method may return null. */ public: virtual void* GetControl() = 0; public: virtual bool IsPlaceHolder() const; /** * Gets the ID for this part. */ public: virtual QString GetID() const; public: virtual bool IsCompressible(); /** * Gets the presentation size. */ public: virtual Point GetSize(); /** * @see org.blueberry.ui.presentations.StackPresentation#getSizeFlags(boolean) * * @since 3.1 */ public: virtual int GetSizeFlags(bool horizontal); /** * @see org.blueberry.ui.presentations.StackPresentation#computePreferredSize(boolean, int, int, int) * * @since 3.1 */ public: virtual int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); public: virtual IDropTarget::Pointer GetDropTarget(Object::Pointer draggedObject, const Point& displayCoordinates); public: bool IsDocked(); public: virtual Shell::Pointer GetShell(); /** * Returns the workbench window window for a part. * * @return the workbench window, or null if there's no window * associated with this part. */ public: virtual SmartPointer GetWorkbenchWindow(); /** * Move the control over another one. */ public: virtual void MoveAbove(void* refControl); /** * Reparent a part. */ public: virtual void Reparent(void* newParent); /** * Returns true if this part was set visible. This returns whatever was last passed into * setVisible, but does not necessarily indicate that the part can be seen (ie: one of its * ancestors may be invisible) */ public: virtual bool GetVisible(); /** * Returns true if this part can be seen. Returns false if the part or any of its ancestors * are invisible. */ public: virtual bool IsVisible(); /** * Shows the receiver if visible is true otherwise hide it. */ public: virtual void SetVisible(bool makeVisible); /** * Returns true if the given control or any of its descendents has focus. */ private: virtual bool IsFocusAncestor(void* ctrl); /** * Sets the presentation bounds. */ public: virtual void SetBounds(const Rectangle& r); /** * Sets the parent for this part. */ public: virtual void SetContainer(SmartPointer container); /** * Sets focus to this part. */ public: virtual void SetFocus(); /** * Sets the part ID. */ public: virtual void SetID(const QString& str); /* (non-Javadoc) * @see org.blueberry.ui.internal.IWorkbenchDragDropPart#getPart() */ public: virtual LayoutPart::Pointer GetPart(); /** * deferUpdates(true) disables widget updates until a corresponding call to * deferUpdates(false). Exactly what gets deferred is the decision * of each LayoutPart, however the part may only defer operations in a manner * that does not affect the final result. * That is, the state of the receiver after the final call to deferUpdates(false) * must be exactly the same as it would have been if nothing had been deferred. * * @param shouldDefer true iff events should be deferred */ public: void DeferUpdates(bool shouldDefer); /** * This is called when deferUpdates(true) causes UI events for this * part to be deferred. Subclasses can overload to initialize any data * structures that they will use to collect deferred events. */ protected: virtual void StartDeferringEvents(); /** * Immediately processes all UI events which were deferred due to a call to * deferUpdates(true). This is called when the last call is made to * deferUpdates(false). Subclasses should overload this method if they * defer some or all UI processing during deferUpdates. */ protected: virtual void HandleDeferredEvents(); /** * Subclasses can call this method to determine whether UI updates should * be deferred. Returns true iff there have been any calls to deferUpdates(true) * without a corresponding call to deferUpdates(false). Any operation which is * deferred based on the result of this method should be performed later within * handleDeferredEvents(). * * @return true iff updates should be deferred. */ protected: bool IsDeferred(); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they do not need to be translated. * * @param buf */ public: virtual void DescribeLayout(QString& buf) const; /** * Returns an id representing this part, suitable for use in a placeholder. * * @since 3.0 */ public: virtual QString GetPlaceHolderId(); public: virtual void ResizeChild(LayoutPart::Pointer childThatChanged); public: void FlushLayout(); /** * Returns true iff the given part can be added to this ILayoutContainer * @param toAdd * @return * @since 3.1 */ public: virtual bool AllowsAdd(LayoutPart::Pointer toAdd); /** * Tests the integrity of this object. Throws an exception if the object's state * is not internally consistent. For use in test suites. */ public: virtual void TestInvariants(); - public: virtual QString ToString(); + public: virtual QString ToString() const; }; } #endif /*BERRYLAYOUTPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.cpp index f44e1ce87c..2d8dff9339 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.cpp @@ -1,306 +1,306 @@ /*=================================================================== 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 "tweaklets/berryGuiWidgetsTweaklet.h" #include "berryLayoutPartSash.h" #include "berryLayoutTree.h" #include "berryLayoutTreeNode.h" #include "berryWorkbenchPlugin.h" #include "berryConstants.h" namespace berry { LayoutPartSash::SelectionListener::SelectionListener(LayoutPartSash* lp) : layoutPartSash(lp) { } void LayoutPartSash::SelectionListener::WidgetSelected(GuiTk::SelectionEvent::Pointer e) { layoutPartSash->CheckDragLimit(e); if (e->detail != Constants::DRAG) { layoutPartSash->WidgetSelected(e->x, e->y, e->width, e->height); } } LayoutPartSash::LayoutPartSash(PartSashContainer* rootContainer, int style) : LayoutPart(""), sash(0), enabled(false), rootContainer(rootContainer), style(style), left(300), right(300), presFactory(0), isVisible(false) { selectionListener = new SelectionListener(this); } LayoutPartSash::~LayoutPartSash() { this->Dispose(); } void LayoutPartSash::CheckDragLimit(GuiTk::SelectionEvent::Pointer event) { LayoutTree::Pointer root = rootContainer->GetLayoutTree(); LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); Rectangle nodeBounds = node->GetBounds(); Rectangle eventRect(event->x, event->y, event->width, event->height); bool vertical = (style == Constants::VERTICAL); // If a horizontal sash, flip the coordinate system so that we // can handle horizontal and vertical sashes without special cases if (!vertical) { nodeBounds.FlipXY(); eventRect.FlipXY(); } int eventX = eventRect.x; int left = std::max(0, eventX - nodeBounds.x); left = std::min(left, nodeBounds.width - this->GetSashSize()); int right = nodeBounds.width - left - this->GetSashSize(); LayoutTreeNode::ChildSizes sizes = node->ComputeChildSizes(nodeBounds.width, nodeBounds.height, left, right, nodeBounds.width); eventRect.x = nodeBounds.x + sizes.left; // If it's a horizontal sash, restore eventRect to its original coordinate system if (!vertical) { eventRect.FlipXY(); } event->x = eventRect.x; event->y = eventRect.y; } void LayoutPartSash::CreateControl(void* /*parent*/) { // Defer creation of the control until it becomes visible if (isVisible) { this->DoCreateControl(); } } void LayoutPartSash::DoCreateControl() { if (sash == 0) { // ask the presentation factory to create the sash IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory(); int sashStyle = IPresentationFactory::SASHTYPE_NORMAL | style; sash = factory->CreateSash(this->rootContainer->GetParent(), sashStyle); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddSelectionListener(sash, selectionListener); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(sash, enabled); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(sash, bounds); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(sash, isVisible); } } void LayoutPartSash::SetBounds(const Rectangle& r) { LayoutPart::SetBounds(r); bounds = r; } void LayoutPartSash::SetVisible(bool visible) { if (visible == isVisible) { return; } if (visible) { this->DoCreateControl(); } else { this->Dispose(); } LayoutPart::SetVisible(visible); isVisible = visible; } bool LayoutPartSash::IsVisible() { return isVisible; } void LayoutPartSash::Dispose() { if (sash != 0) { bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(sash); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->Dispose(sash); } sash = 0; } Rectangle LayoutPartSash::GetBounds() { if (sash == 0) { return bounds; } return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(sash); } void* LayoutPartSash::GetControl() { return sash; } -QString LayoutPartSash::GetID() +QString LayoutPartSash::GetID() const { return ""; } LayoutPartSash::Pointer LayoutPartSash::GetPostLimit() { return postLimit; } LayoutPartSash::Pointer LayoutPartSash::GetPreLimit() { return preLimit; } int LayoutPartSash::GetLeft() { return left; } int LayoutPartSash::GetRight() { return right; } bool LayoutPartSash::IsHorizontal() { return ((style & Constants::HORIZONTAL) == Constants::HORIZONTAL); } bool LayoutPartSash::IsVertical() { return ((style & Constants::VERTICAL) == Constants::VERTICAL); } void LayoutPartSash::SetPostLimit(LayoutPartSash::Pointer newPostLimit) { postLimit = newPostLimit; } void LayoutPartSash::SetPreLimit(LayoutPartSash::Pointer newPreLimit) { preLimit = newPreLimit; } void LayoutPartSash::SetRatio(float newRatio) { int total = left + right; int newLeft = (int) (total * newRatio); this->SetSizes(newLeft, total - newLeft); } void LayoutPartSash::SetSizes(int left, int right) { if (left < 0 || right < 0) { return; } if (left == this->left && right == this->right) { return; } this->left = left; this->right = right; this->FlushCache(); } void LayoutPartSash::FlushCache() { LayoutTree::Pointer root = rootContainer->GetLayoutTree(); if (root != 0) { LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); if (node != 0) { node->FlushCache(); } } } void LayoutPartSash::WidgetSelected(int x, int y, int /*width*/, int /*height*/) { if (!enabled) { return; } LayoutTree::Pointer root = rootContainer->GetLayoutTree(); LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); Rectangle nodeBounds = node->GetBounds(); //Recompute ratio x -= nodeBounds.x; y -= nodeBounds.y; if (style == Constants::VERTICAL) { this->SetSizes(x, nodeBounds.width - x - this->GetSashSize()); } else { this->SetSizes(y, nodeBounds.height - y - this->GetSashSize()); } node->SetBounds(nodeBounds); } void LayoutPartSash::SetEnabled(bool resizable) { this->enabled = resizable; if (sash != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(sash, enabled); } } int LayoutPartSash::GetSashSize() const { IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory(); int sashStyle = IPresentationFactory::SASHTYPE_NORMAL | style; int size = factory->GetSashSize(sashStyle); return size; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.h index 53b87e91da..268407b6a1 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutPartSash.h @@ -1,182 +1,182 @@ /*=================================================================== 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 BERRYLAYOUTPARTSASH_H_ #define BERRYLAYOUTPARTSASH_H_ #include "berryLayoutPart.h" #include "berryPartSashContainer.h" #include "guitk/berryGuiTkISelectionListener.h" #include "presentations/berryIPresentationFactory.h" namespace berry { class LayoutPartSash: public LayoutPart { friend class WorkbenchPage; friend class PartSashContainer; friend class LayoutTreeNode; public: berryObjectMacro(LayoutPartSash); LayoutPartSash(PartSashContainer* rootContainer, int style); ~LayoutPartSash(); private: void* sash; bool enabled; PartSashContainer* rootContainer; int style; LayoutPartSash::Pointer preLimit; LayoutPartSash::Pointer postLimit; int left; int right; Rectangle bounds; IPresentationFactory* presFactory; /** * Stores whether or not the sash is visible. (This is expected to have a meaningful * value even if the underlying control doesn't exist). */ bool isVisible; struct SelectionListener : public GuiTk::ISelectionListener { SelectionListener(LayoutPartSash* layoutPartSash); void WidgetSelected(GuiTk::SelectionEvent::Pointer e); private: LayoutPartSash* layoutPartSash; }; GuiTk::ISelectionListener::Pointer selectionListener; // checkDragLimit contains changes by cagatayk@acm.org void CheckDragLimit(GuiTk::SelectionEvent::Pointer event); /** * Creates the control. As an optimization, creation of the control is deferred if * the control is invisible. */ public: void CreateControl(void* parent); /** * Creates the underlying SWT control. * * @since 3.1 */ private: void DoCreateControl(); public: void SetBounds(const Rectangle& r); /** * Makes the sash visible or invisible. Note: as an optimization, the actual widget is destroyed when the * sash is invisible. */ public: void SetVisible(bool visible); public: bool IsVisible(); /** * See LayoutPart#dispose */ public: void Dispose(); /** * Gets the presentation bounds. */ public: Rectangle GetBounds(); /** * Returns the part control. */ public: void* GetControl(); /** * */ public: - QString GetID(); + QString GetID() const; protected: LayoutPartSash::Pointer GetPostLimit(); LayoutPartSash::Pointer GetPreLimit(); int GetLeft(); int GetRight(); bool IsHorizontal(); bool IsVertical(); void SetPostLimit(LayoutPartSash::Pointer newPostLimit); void SetPreLimit(LayoutPartSash::Pointer newPreLimit); void SetRatio(float newRatio); void SetSizes(int left, int right); private: void FlushCache(); private: void WidgetSelected(int x, int y, int width, int height); /** * @param resizable * @since 3.1 */ public: void SetEnabled(bool resizable); protected: /* package */int GetSashSize() const; }; } #endif /* BERRYLAYOUTPARTSASH_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.cpp index 54f3f65e48..fa15915437 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.cpp @@ -1,719 +1,719 @@ /*=================================================================== 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 "berryLayoutTreeNode.h" #include "berryConstants.h" #include "berryIPageLayout.h" #include namespace berry { LayoutTreeNode::ChildSizes::ChildSizes (int l, int r, bool resize) { left = l; right = r; resizable = resize; } LayoutTreeNode::LayoutTreeNode(LayoutPartSash::Pointer sash) : LayoutTree(sash) { children[0] = 0; children[1] = 0; } LayoutTreeNode::~LayoutTreeNode() { } void LayoutTreeNode::FlushChildren() { LayoutTree::FlushChildren(); children[0]->FlushChildren(); children[1]->FlushChildren(); } LayoutPart::Pointer LayoutTreeNode::FindPart(const Point& toFind) { if (!children[0]->IsVisible()) { if (!children[1]->IsVisible()) { return LayoutPart::Pointer(0); } return children[1]->FindPart(toFind); } else { if (!children[1]->IsVisible()) { return children[0]->FindPart(toFind); } } LayoutPartSash::Pointer sash = this->GetSash(); Rectangle bounds = sash->GetBounds(); if (sash->IsVertical()) { if (toFind.x < bounds.x + (bounds.width / 2)) { return children[0]->FindPart(toFind); } return children[1]->FindPart(toFind); } else { if (toFind.y < bounds.y + (bounds.height / 2)) { return children[0]->FindPart(toFind); } return children[1]->FindPart(toFind); } } LayoutPart::Pointer LayoutTreeNode::ComputeRelation( QList& relations) { PartSashContainer::RelationshipInfo r = PartSashContainer::RelationshipInfo(); r.relative = children[0]->ComputeRelation(relations); r.part = children[1]->ComputeRelation(relations); r.left = this->GetSash()->GetLeft(); r.right = this->GetSash()->GetRight(); r.relationship = this->GetSash()->IsVertical() ? IPageLayout::RIGHT : IPageLayout::BOTTOM; relations.push_front(r); return r.relative; } void LayoutTreeNode::DisposeSashes() { children[0]->DisposeSashes(); children[1]->DisposeSashes(); this->GetSash()->Dispose(); } LayoutTree::Pointer LayoutTreeNode::Find(LayoutPart::Pointer child) { LayoutTree::Pointer node = children[0]->Find(child); if (node != 0) { return node; } node = children[1]->Find(child); return node; } LayoutPart::Pointer LayoutTreeNode::FindBottomRight() { if (children[1]->IsVisible()) { return children[1]->FindBottomRight(); } return children[0]->FindBottomRight(); } LayoutTreeNode* LayoutTreeNode::FindCommonParent(LayoutPart::Pointer child1, LayoutPart::Pointer child2, bool foundChild1, bool foundChild2) { if (!foundChild1) { foundChild1 = this->Find(child1) != 0; } if (!foundChild2) { foundChild2 = this->Find(child2) != 0; } if (foundChild1 && foundChild2) { return this; } if (parent == 0) { return 0; } return parent ->FindCommonParent(child1, child2, foundChild1, foundChild2); } LayoutTreeNode::Pointer LayoutTreeNode::FindSash(LayoutPartSash::Pointer sash) { if (this->GetSash() == sash) { return LayoutTreeNode::Pointer(this); } LayoutTreeNode::Pointer node = children[0]->FindSash(sash); if (node != 0) { return node; } node = children[1]->FindSash(sash); if (node != 0) { return node; } return LayoutTreeNode::Pointer(0); } void LayoutTreeNode::FindSashes(LayoutTree::Pointer child, PartPane::Sashes sashes) { void* sash = this->GetSash()->GetControl(); bool leftOrTop = children[0] == child; if (sash != 0) { LayoutPartSash::Pointer partSash = this->GetSash(); //If the child is in the left, the sash //is in the rigth and so on. if (leftOrTop) { if (partSash->IsVertical()) { if (sashes.right == 0) { sashes.right = sash; } } else { if (sashes.bottom == 0) { sashes.bottom = sash; } } } else { if (partSash->IsVertical()) { if (sashes.left == 0) { sashes.left = sash; } } else { if (sashes.top == 0) { sashes.top = sash; } } } } if (this->GetParent() != 0) { this->GetParent()->FindSashes(LayoutTree::Pointer(this), sashes); } } LayoutPartSash::Pointer LayoutTreeNode::GetSash() const { return part.Cast(); } int LayoutTreeNode::GetSashSize() const { return this->GetSash()->GetSashSize(); } bool LayoutTreeNode::IsVisible() { return children[0]->IsVisible() || children[1]->IsVisible(); } LayoutTree::Pointer LayoutTreeNode::Remove(LayoutTree::Pointer child) { this->GetSash()->Dispose(); if (parent == 0) { //This is the root. Return the other child to be the new root. if (children[0] == child) { children[1]->SetParent(0); return children[1]; } children[0]->SetParent(0); return children[0]; } LayoutTreeNode::Pointer oldParent(parent); if (children[0] == child) { oldParent->ReplaceChild(LayoutTree::Pointer(this), children[1]); } else { oldParent->ReplaceChild(LayoutTree::Pointer(this), children[0]); } return oldParent; } void LayoutTreeNode::ReplaceChild(LayoutTree::Pointer oldChild, LayoutTree::Pointer newChild) { if (children[0] == oldChild) { children[0] = newChild; } else if (children[1] == oldChild) { children[1] = newChild; } newChild->SetParent(this); if (!children[0]->IsVisible() || !children[0]->IsVisible()) { this->GetSash()->Dispose(); } this->FlushCache(); } bool LayoutTreeNode::SameDirection(bool isVertical, LayoutTreeNode::Pointer subTree) { bool treeVertical = this->GetSash()->IsVertical(); if (treeVertical != isVertical) { return false; } while (subTree != 0) { if (this == subTree.GetPointer()) { return true; } if (subTree->children[0]->IsVisible() && subTree->children[1]->IsVisible()) { if (subTree->GetSash()->IsVertical() != isVertical) { return false; } } subTree = subTree->GetParent(); } return true; } int LayoutTreeNode::DoComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { this->AssertValidSize(availablePerpendicular); this->AssertValidSize(availableParallel); this->AssertValidSize(preferredParallel); // If one child is invisible, defer to the other child if (!children[0]->IsVisible()) { return children[1]->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } if (!children[1]->IsVisible()) { return children[0]->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } if (availableParallel == 0) { return 0; } // If computing the dimension perpendicular to our sash if (width == this->GetSash()->IsVertical()) { // Compute the child sizes ChildSizes sizes = this->ComputeChildSizes(availableParallel, availablePerpendicular, GetSash()->GetLeft(), GetSash()->GetRight(), preferredParallel); // Return the sum of the child sizes plus the sash size return this->Add(sizes.left, this->Add(sizes.right, this->GetSashSize())); } else { // Computing the dimension parallel to the sash. We will compute and return the preferred size // of whichever child is closest to the ideal size. // First compute the dimension of the child sizes perpendicular to the sash ChildSizes sizes = this->ComputeChildSizes(availablePerpendicular, availableParallel, GetSash()->GetLeft(), GetSash()->GetRight(), availablePerpendicular); // Use this information to compute the dimension of the child sizes parallel to the sash. // Return the preferred size of whichever child is largest int leftSize = children[0]->ComputePreferredSize(width, availableParallel, sizes.left, preferredParallel); // Compute the preferred size of the right child int rightSize = children[1]->ComputePreferredSize(width, availableParallel, sizes.right, preferredParallel); // Return leftSize or rightSize: whichever one is largest int result = rightSize; if (leftSize > rightSize) { result = leftSize; } this->AssertValidSize(result); return result; } } LayoutTreeNode::ChildSizes LayoutTreeNode::ComputeChildSizes(int width, int height, int left, int right, int preferredWidth) { poco_assert(children[0]->IsVisible()); poco_assert(children[1]->IsVisible()); this->AssertValidSize(width); this->AssertValidSize(height); this->AssertValidSize(preferredWidth); poco_assert(left >= 0); poco_assert(right >= 0); poco_assert(preferredWidth >= 0); poco_assert(preferredWidth <= width); bool vertical = this->GetSash()->IsVertical(); if (width <= this->GetSashSize()) { return ChildSizes(0,0, false); } if (width == INF) { if (preferredWidth == INF) { return ChildSizes(children[0]->ComputeMaximumSize(vertical, height), children[1]->ComputeMaximumSize(vertical, height), false); } if (preferredWidth == 0) { return ChildSizes(children[0]->ComputeMinimumSize(vertical, height), children[1]->ComputeMinimumSize(vertical, height), false); } } int total = left + right; // Use all-or-none weighting double wLeft = left, wRight = right; switch (this->GetCompressionBias()) { case -1: wLeft = 0.0; break; case 1: wRight = 0.0; break; default: break; } double wTotal = wLeft + wRight; // Subtract the SASH_WIDTH from preferredWidth and width. From here on, we'll deal with the // width available to the controls and neglect the space used by the sash. preferredWidth = std::max(0, this->Subtract(preferredWidth, this->GetSashSize())); width = std::max(0, this->Subtract(width, this->GetSashSize())); int redistribute = this->Subtract(preferredWidth, total); // Compute the minimum and maximum sizes for each child int leftMinimum = children[0]->ComputeMinimumSize(vertical, height); int rightMinimum = children[1]->ComputeMinimumSize(vertical, height); int leftMaximum = children[0]->ComputeMaximumSize(vertical, height); int rightMaximum = children[1]->ComputeMaximumSize(vertical, height); int idealLeft = 0; int idealRight = 0; if (PartSashContainer::leftToRight) { // Keep track of the available space for each child, given the minimum size of the other child int leftAvailable = std::min(leftMaximum, std::max(0, this->Subtract(width, rightMinimum))); int rightAvailable = std::min(rightMaximum, std::max(0, this->Subtract(width, leftMinimum))); // Figure out the ideal size of the left child idealLeft = std::max(leftMinimum, std::min(preferredWidth, left + (int)(redistribute * wLeft / wTotal))); // If the right child can't use all its available space, let the left child fill it in idealLeft = std::max(idealLeft, preferredWidth - rightAvailable); // Ensure the left child doesn't get larger than its available space idealLeft = std::min(idealLeft, leftAvailable); // Check if the left child would prefer to be a different size idealLeft = children[0]->ComputePreferredSize(vertical, leftAvailable, height, idealLeft); // Ensure that the left child is larger than its minimum size idealLeft = std::max(idealLeft, leftMinimum); idealLeft = std::min(idealLeft, leftAvailable); // Compute the right child width idealRight = std::max(rightMinimum, preferredWidth - idealLeft); rightAvailable = std::max(0, std::min(rightAvailable, this->Subtract(width, idealLeft))); idealRight = std::min(idealRight, rightAvailable); idealRight = children[1]->ComputePreferredSize(vertical, rightAvailable, height, idealRight); idealRight = std::max(idealRight, rightMinimum); } else { // Keep track of the available space for each child, given the minimum size of the other child int rightAvailable = std::min(rightMaximum, std::max(0, this->Subtract(width, leftMinimum))); int leftAvailable = std::min(leftMaximum, std::max(0, this->Subtract(width, rightMinimum))); // Figure out the ideal size of the right child idealRight = std::max(rightMinimum, std::min(preferredWidth, right + (int)(redistribute * wRight / wTotal))); // If the left child can't use all its available space, let the right child fill it in idealRight = std::max(idealRight, preferredWidth - leftAvailable); // Ensure the right child doesn't get larger than its available space idealRight = std::min(idealRight, rightAvailable); // Check if the right child would prefer to be a different size idealRight = children[1]->ComputePreferredSize(vertical, rightAvailable, height, idealRight); // Ensure that the right child is larger than its minimum size idealRight = std::max(idealRight, rightMinimum); idealRight = std::min(idealRight, rightAvailable); // Compute the left child width idealLeft = std::max(leftMinimum, preferredWidth - idealRight); leftAvailable = std::max(0, std::min(leftAvailable, this->Subtract(width, idealRight))); idealLeft = std::min(idealLeft, leftAvailable); idealLeft = children[0]->ComputePreferredSize(vertical, leftAvailable, height, idealLeft); idealLeft = std::max(idealLeft, leftMinimum); } return ChildSizes(idealLeft, idealRight, leftMaximum> leftMinimum && rightMaximum> rightMinimum && leftMinimum + rightMinimum < width); } int LayoutTreeNode::DoGetSizeFlags(bool width) { if (!children[0]->IsVisible()) { return children[1]->GetSizeFlags(width); } if (!children[1]->IsVisible()) { return children[0]->GetSizeFlags(width); } int leftFlags = children[0]->GetSizeFlags(width); int rightFlags = children[1]->GetSizeFlags(width); return ((leftFlags | rightFlags) & ~Constants::MAX) | (leftFlags & rightFlags & Constants::MAX); } void LayoutTreeNode::DoSetBounds(const Rectangle& b) { if (!children[0]->IsVisible()) { children[1]->SetBounds(b); this->GetSash()->SetVisible(false); return; } if (!children[1]->IsVisible()) { children[0]->SetBounds(b); this->GetSash()->SetVisible(false); return; } Rectangle bounds = b; bool vertical = this->GetSash()->IsVertical(); // If this is a horizontal sash, flip coordinate systems so // that we can eliminate special cases if (!vertical) { bounds.FlipXY(); } ChildSizes childSizes = this->ComputeChildSizes(bounds.width, bounds.height, this->GetSash()->GetLeft(), this->GetSash()->GetRight(), bounds.width); this->GetSash()->SetVisible(true); this->GetSash()->SetEnabled(childSizes.resizable); Rectangle leftBounds = Rectangle(bounds.x, bounds.y, childSizes.left, bounds.height); Rectangle sashBounds = Rectangle(leftBounds.x + leftBounds.width, bounds.y, this->GetSashSize(), bounds.height); Rectangle rightBounds = Rectangle(sashBounds.x + sashBounds.width, bounds.y, childSizes.right, bounds.height); if (!vertical) { leftBounds.FlipXY(); sashBounds.FlipXY(); rightBounds.FlipXY(); } this->GetSash()->SetBounds(sashBounds); children[0]->SetBounds(leftBounds); children[1]->SetBounds(rightBounds); } void LayoutTreeNode::CreateControl(void* parent) { children[0]->CreateControl(parent); children[1]->CreateControl(parent); this->GetSash()->CreateControl(parent); LayoutTree::CreateControl(parent); } bool LayoutTreeNode::IsCompressible() { return children[0]->IsCompressible() || children[1]->IsCompressible(); } int LayoutTreeNode::GetCompressionBias() { bool left = children[0]->IsCompressible(); bool right = children[1]->IsCompressible(); if (left == right) { return 0; } if (right) { return -1; } return 1; } bool LayoutTreeNode::IsLeftChild(LayoutTree::ConstPointer toTest) { return children[0] == toTest; } LayoutTree::Pointer LayoutTreeNode::GetChild(bool left) { int index = left ? 0 : 1; return (children[index]); } void LayoutTreeNode::SetChild(bool left, LayoutPart::Pointer part) { LayoutTree::Pointer child(new LayoutTree(part)); this->SetChild(left, child); this->FlushCache(); } void LayoutTreeNode::SetChild(bool left, LayoutTree::Pointer child) { int index = left ? 0 : 1; children[index] = child; child->SetParent(this); this->FlushCache(); } -QString LayoutTreeNode::ToString() +QString LayoutTreeNode::ToString() const { QString str; QTextStream s(&str); s << "\n"; if (part->GetControl() != 0) { s << "<@" << part->GetControl() << ">\n"; } QString str2; QTextStream result(&str2); result << "["; if (children[0]->GetParent() != this) { result << str2 << "{" << children[0] << "}" << str; } else { result << str2 << children[0] << str; } if (children[1]->GetParent() != this) { result << str2 << "{" << children[1] << "}]"; } else { result << str2 << children[1] << "]"; } return str2; } //void LayoutTreeNode::UpdateSashes(void* parent) { // if (parent == 0) // return; // children[0]->UpdateSashes(parent); // children[1]->UpdateSashes(parent); // if (children[0]->IsVisible() && children[1]->IsVisible()) // this->GetSash()->CreateControl(parent); // else // this->GetSash()->Dispose(); // } void LayoutTreeNode::DescribeLayout(QString& buf) const { if (!(children[0]->IsVisible())) { if (!children[1]->IsVisible()) { return; } children[1]->DescribeLayout(buf); return; } if (!children[1]->IsVisible()) { children[0]->DescribeLayout(buf); return; } buf.append("("); //$NON-NLS-1$ children[0]->DescribeLayout(buf); buf.append(this->GetSash()->IsVertical() ? "|" : "-"); children[1]->DescribeLayout(buf); buf.append(")"); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.h index e466c70309..2f2dc90cd3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryLayoutTreeNode.h @@ -1,222 +1,226 @@ /*=================================================================== 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 BERRYLAYOUTTREENODE_H_ #define BERRYLAYOUTTREENODE_H_ #include "berryLayoutTree.h" #include "berryLayoutPartSash.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * * Implementation of a tree node. The node represents a * sash and it allways has two children. */ class LayoutTreeNode : public LayoutTree { public: berryObjectMacro(LayoutTreeNode) struct ChildSizes { int left; int right; bool resizable; ChildSizes (int l, int r, bool resize); }; /* The node children witch may be another node or a leaf */ private: LayoutTree::Pointer children[2]; /** * Initialize this tree with its sash. */ public: LayoutTreeNode(LayoutPartSash::Pointer sash); public: ~LayoutTreeNode(); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutTree#flushChildren() */ public: void FlushChildren(); /** * Traverses the tree to find the part that intersects the given point * * @param toFind * @return the part that intersects the given point */ public: LayoutPart::Pointer FindPart(const Point& toFind); /** * Add the relation ship between the children in the list * and returns the left children. */ public: LayoutPart::Pointer ComputeRelation(QList& relations); /** * Dispose all Sashs in this tree */ public: void DisposeSashes(); /** * Find a LayoutPart in the tree and return its sub-tree. Returns * null if the child is not found. */ public: SmartPointer Find(LayoutPart::Pointer child); /** * Find the part that is in the bottom right position. */ public: LayoutPart::Pointer FindBottomRight(); /** * Go up in the tree finding a parent that is common of both children. * Return the subtree. */ LayoutTreeNode* FindCommonParent(LayoutPart::Pointer child1, LayoutPart::Pointer child2, bool foundChild1 = false, bool foundChild2 = false); /** * Find a sash in the tree and return its sub-tree. Returns * null if the sash is not found. */ public: SmartPointer FindSash(LayoutPartSash::Pointer sash); + using LayoutTree::FindSashes; + /** * Sets the elements in the array of sashes with the * Left,Rigth,Top and Botton sashes. The elements * may be null depending whether there is a shash * beside the part */ void FindSashes(SmartPointer child, PartPane::Sashes sashes); /** * Returns the sash of this node. */ public: LayoutPartSash::Pointer GetSash() const; private: int GetSashSize() const; /** * Returns true if this tree has visible parts otherwise returns false. */ public: bool IsVisible(); + using LayoutTree::Remove; + /** * Remove the child and this node from the tree */ SmartPointer Remove(SmartPointer child); /** * Replace a child with a new child and sets the new child's parent. */ void ReplaceChild(SmartPointer oldChild, SmartPointer newChild); /** * Go up from the subtree and return true if all the sash are * in the direction specified by isVertical */ public: bool SameDirection(bool isVertical, SmartPointer subTree); public: int DoComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); /** * Computes the pixel sizes of this node's children, given the available * space for this node. Note that "width" and "height" actually refer * to the distance perpendicular and parallel to the sash respectively. * That is, their meaning is reversed when computing a horizontal sash. * * @param width the pixel width of a vertical node, or the pixel height * of a horizontal node (INF if unbounded) * @param height the pixel height of a vertical node, or the pixel width * of a horizontal node (INF if unbounded) * @return a struct describing the pixel sizes of the left and right children * (this is a width for horizontal nodes and a height for vertical nodes) */ ChildSizes ComputeChildSizes(int width, int height, int left, int right, int preferredWidth); protected: int DoGetSizeFlags(bool width); /** * Resize the parts on this tree to fit in bounds. */ public: void DoSetBounds(const Rectangle& bounds); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutTree#createControl(org.blueberry.swt.widgets.Composite) */ public: void CreateControl(void* parent); //Added by hudsonr@us.ibm.com - bug 19524 public: bool IsCompressible(); /** * Returns 0 if there is no bias. Returns -1 if the first child should be of * fixed size, and the second child should be compressed. Returns 1 if the * second child should be of fixed size. * @return the bias */ public: int GetCompressionBias(); bool IsLeftChild(SmartPointer toTest); SmartPointer GetChild(bool left); /** * Sets a child in this node */ void SetChild(bool left, LayoutPart::Pointer part); /** * Sets a child in this node */ void SetChild(bool left, SmartPointer child); /** * Returns a string representation of this object. */ - public: QString ToString(); + public: QString ToString() const; /** * Create the sashes if the children are visible * and dispose it if they are not. */ //public: void UpdateSashes(void* parent); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they should not be translated or equality tests will fail. * * @param buf */ public: void DescribeLayout(QString& buf) const; }; } #endif /*BERRYLAYOUTTREENODE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h index 628477146b..1fd4128836 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h @@ -1,45 +1,45 @@ /*=================================================================== 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 BERRYMMMENULISTENER_H #define BERRYMMMENULISTENER_H #include namespace berry { -struct MenuManager; +class MenuManager; class MMMenuListener : public QObject { Q_OBJECT berry::MenuManager* mm; public: MMMenuListener(berry::MenuManager* mm); private: Q_SLOT void HandleAboutToShow(); }; } #endif // BERRYMMMENULISTENER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMenuServiceFactory.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMenuServiceFactory.cpp new file mode 100644 index 0000000000..03c58a5dab --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMenuServiceFactory.cpp @@ -0,0 +1,54 @@ +/*=================================================================== + +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 "berryMenuServiceFactory.h" + +#include "berryIEvaluationReference.h" +#include "berryIWorkbenchLocationService.h" +#include "berryIWorkbenchWindow.h" + +#include "berrySlaveMenuService.h" +#include "berryWorkbenchWindow.h" + +namespace berry { + +Object* MenuServiceFactory::Create(const QString& serviceInterface, IServiceLocator* parentLocator, + IServiceLocator* locator) const +{ + if (serviceInterface != qobject_interface_iid()) + { + return NULL; + } + + IWorkbenchLocationService* wls = locator->GetService(); + IWorkbench* const wb = wls->GetWorkbench(); + if (wb == NULL) + { + return NULL; + } + + Object* parent = parentLocator->GetService(serviceInterface); + if (parent == NULL) + { + // we are registering the global services in the Workbench + return NULL; + } + IWorkbenchWindow* const window = wls->GetWorkbenchWindow(); + return new SlaveMenuService(dynamic_cast(parent), locator, + dynamic_cast(window)->GetMenuRestrictions()); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtDnDTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMenuServiceFactory.h old mode 100755 new mode 100644 similarity index 58% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtDnDTweaklet.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMenuServiceFactory.h index 57589ad2f8..c5d4a1ee51 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtDnDTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMenuServiceFactory.h @@ -1,40 +1,38 @@ /*=================================================================== 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 BERRYMENUSERVICEFACTORY_H +#define BERRYMENUSERVICEFACTORY_H -#ifndef BERRYQTDNDTWEAKLET_H_ -#define BERRYQTDNDTWEAKLET_H_ - -#include +#include "berryIServiceFactory.h" namespace berry { -class QtDnDTweaklet : public QObject, public DnDTweaklet +class MenuServiceFactory : public QObject, public IServiceFactory { Q_OBJECT - Q_INTERFACES(berry::DnDTweaklet) + Q_INTERFACES(berry::IServiceFactory) public: - QtDnDTweaklet(); - QtDnDTweaklet(const QtDnDTweaklet& other); + Object* Create(const QString& serviceInterface, IServiceLocator* parentLocator, + IServiceLocator* locator) const; - ITracker* CreateTracker(); }; } -#endif /* BERRYQTDNDTWEAKLET_H_ */ +#endif // BERRYMENUSERVICEFACTORY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryNestableHandlerService.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryNestableHandlerService.cpp new file mode 100644 index 0000000000..9bace18147 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryNestableHandlerService.cpp @@ -0,0 +1,85 @@ +/*=================================================================== + +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 "berryNestableHandlerService.h" + +#include "berryExpression.h" +#include "berryIHandlerActivation.h" +#include "berryISourceProvider.h" + +namespace berry { + +NestableHandlerService::NestableHandlerService(IHandlerService* parentHandlerService, + const SmartPointer& defaultExpression) + : SlaveHandlerService(parentHandlerService, defaultExpression) + , active(false) +{ +} + +void NestableHandlerService::Activate() +{ + if (active) + { + return; + } + + QList localActivations = localActivationsToParentActivations.keys(); + for (int i = 0; i < localActivations.size(); i++) + { + // Ignore activations that have been cleared since the copy + // was made. + if (localActivationsToParentActivations.contains(localActivations[i])) + { + SlaveHandlerService::DoActivation(localActivations[i]); + } + } + active = true; +} + +void NestableHandlerService::Deactivate() +{ + if (!active) + { + return; + } + + DeactivateHandlers(parentActivations.toList()); + parentActivations.clear(); + + QList localActivations = localActivationsToParentActivations.keys(); + for (int i = 0; i < localActivations.size(); i++) + { + if (localActivationsToParentActivations.contains(localActivations[i])) + { + localActivationsToParentActivations.insert(localActivations[i], NULL); + } + } + + active = false; +} + +SmartPointer NestableHandlerService::DoActivation( + const SmartPointer& localActivation) +{ + if (active) + { + return SlaveHandlerService::DoActivation(localActivation); + } + localActivationsToParentActivations.insert(localActivation, NULL); + return localActivation; +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryNestableHandlerService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryNestableHandlerService.h new file mode 100644 index 0000000000..eaa99afebe --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryNestableHandlerService.h @@ -0,0 +1,78 @@ +/*=================================================================== + +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 BERRYNESTABLEHANDLERSERVICE_H +#define BERRYNESTABLEHANDLERSERVICE_H + +#include "berrySlaveHandlerService.h" +#include "berryINestable.h" + +namespace berry { + +/** + *

+ * A handler service which delegates almost all responsibility to the parent + * service. It is capable of being nested inside a component that is not + * recognizable by the "sources" event mechanism. This means that the handlers + * must be activated and deactivated manually. + *

+ *

+ * This class is not intended for use outside of the + * org.eclipse.ui.workbench plug-in. + *

+ */ +class NestableHandlerService : public SlaveHandlerService, public INestable +{ + +private: + + /** + * Whether the component with which this service is associated is active. + */ + bool active; + +public: + + berryObjectMacro(berry::NestableHandlerService) + + /** + * Constructs a new instance. + * + * @param parentHandlerService + * The parent handler service for this slave; must not be + * null. + * @param defaultExpression + * The default expression to use if none is provided. This is + * primarily used for conflict resolution. This value may be + * null. + */ + NestableHandlerService(IHandlerService* parentHandlerService, + const SmartPointer& defaultExpression); + + void Activate(); + + void Deactivate(); + +protected: + + SmartPointer DoActivation( + const SmartPointer& localActivation); + +}; + +} + +#endif // BERRYNESTABLEHANDLERSERVICE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPagePartSelectionTracker.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPagePartSelectionTracker.cpp index 88a04f68d8..2797bd470b 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPagePartSelectionTracker.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPagePartSelectionTracker.cpp @@ -1,275 +1,275 @@ /*=================================================================== 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 "berryPagePartSelectionTracker.h" #include "berryIPostSelectionProvider.h" namespace berry { class SelTrackerPartListener: public IPartListener { public: SelTrackerPartListener(PagePartSelectionTracker* tracker) : tracker(tracker) {} Events::Types GetPartEventTypes() const { return Events::CLOSED | Events::OPENED; } - void PartClosed(IWorkbenchPartReference::Pointer partRef) + void PartClosed(const IWorkbenchPartReference::Pointer& partRef) { if (tracker->GetPartId(partRef->GetPart(false)) == tracker->AbstractPartSelectionTracker::GetPartId()) { tracker->SetPart(IWorkbenchPart::Pointer(0), true); } } - void PartOpened(IWorkbenchPartReference::Pointer partRef) + void PartOpened(const IWorkbenchPartReference::Pointer& partRef) { if (tracker->GetPartId(partRef->GetPart(false)) == tracker->AbstractPartSelectionTracker::GetPartId()) { tracker->SetPart(partRef->GetPart(false), true); } } private: PagePartSelectionTracker* tracker; }; class SelTrackerPerspectiveListener: public IPerspectiveListener { public: SelTrackerPerspectiveListener(PagePartSelectionTracker* tracker) : tracker(tracker) {} IPerspectiveListener::Events::Types GetPerspectiveEventTypes() const { return IPerspectiveListener::Events::PART_CHANGED; } - void PerspectiveChanged(IWorkbenchPage::Pointer, - IPerspectiveDescriptor::Pointer, - IWorkbenchPartReference::Pointer partRef, const QString& changeId) + using IPerspectiveListener::PerspectiveChanged; + void PerspectiveChanged(const IWorkbenchPage::Pointer&, + const IPerspectiveDescriptor::Pointer&, + const IWorkbenchPartReference::Pointer& partRef, + const QString& changeId) { if (!partRef) return; IWorkbenchPart::Pointer part = partRef->GetPart(false); if (!part) return; if (IWorkbenchPage::CHANGE_VIEW_SHOW == changeId) { if (tracker->GetPart()) // quick check first, plus avoids double setting return; if (tracker->GetPartId(part) == tracker->AbstractPartSelectionTracker::GetPartId()) tracker->SetPart(part, true); } } private: PagePartSelectionTracker* tracker; }; class SelTrackerSelectionChangedListener: public ISelectionChangedListener { public: SelTrackerSelectionChangedListener(PagePartSelectionTracker* tracker) : tracker(tracker) {} - void SelectionChanged(SelectionChangedEvent::Pointer event) + void SelectionChanged(const SelectionChangedEvent::Pointer& event) { tracker->FireSelection(tracker->GetPart(), event->GetSelection()); } private: PagePartSelectionTracker* tracker; }; PagePartSelectionTracker::PostSelectionListener::PostSelectionListener( PagePartSelectionTracker* tracker) : m_Tracker(tracker) { } void PagePartSelectionTracker::PostSelectionListener::SelectionChanged( - SelectionChangedEvent::Pointer event) + const SelectionChangedEvent::Pointer& event) { m_Tracker->FirePostSelection(m_Tracker->GetPart(), event->GetSelection()); } PagePartSelectionTracker::PagePartSelectionTracker( IWorkbenchPage* page, const QString& partId) : AbstractPartSelectionTracker(partId) { - postSelectionListener = new PostSelectionListener(this); - perspListener = new SelTrackerPerspectiveListener(this); - selChangedListener = new SelTrackerSelectionChangedListener(this); - partListener = new SelTrackerPartListener(this); + postSelectionListener.reset(new PostSelectionListener(this)); + perspListener.reset(new SelTrackerPerspectiveListener(this)); + selChangedListener.reset(new SelTrackerSelectionChangedListener(this)); + partListener.reset(new SelTrackerPartListener(this)); this->SetPage(page); - page->AddPartListener(partListener); - page->GetWorkbenchWindow()->AddPerspectiveListener( - perspListener); + page->AddPartListener(partListener.data()); + page->GetWorkbenchWindow()->AddPerspectiveListener(perspListener.data()); QString secondaryId; QString primaryId = partId; int indexOfColon; if ((indexOfColon = partId.indexOf(':')) != -1) { secondaryId = partId.mid(indexOfColon + 1); primaryId = partId.left(indexOfColon); } IViewReference::Pointer part = page->FindViewReference(primaryId, secondaryId); if (part.IsNotNull() && part->GetView(false).IsNotNull()) { this->SetPart(part->GetView(false), false); } } ISelection::ConstPointer PagePartSelectionTracker::GetSelection() { IWorkbenchPart::Pointer part = this->GetPart(); if (part.IsNotNull()) { ISelectionProvider::Pointer sp = part->GetSite()->GetSelectionProvider(); if (sp.IsNotNull()) { return sp->GetSelection(); } } return ISelection::Pointer(0); } PagePartSelectionTracker::~PagePartSelectionTracker() { IWorkbenchPage::Pointer page = GetPage(); - page->GetWorkbenchWindow()->RemovePerspectiveListener( - perspListener); - page->RemovePartListener(partListener); + page->GetWorkbenchWindow()->RemovePerspectiveListener(perspListener.data()); + page->RemovePartListener(partListener.data()); this->SetPart(IWorkbenchPart::Pointer(0), false); this->SetPage(0); } IWorkbenchPart::Pointer PagePartSelectionTracker::GetPart() { return fPart; } IWorkbenchPage::Pointer PagePartSelectionTracker::GetPage() { return IWorkbenchPage::Pointer(fPage); } ISelectionProvider::Pointer PagePartSelectionTracker::GetSelectionProvider() { IWorkbenchPart::Pointer part = this->GetPart(); if (part.IsNotNull()) { return part->GetSite()->GetSelectionProvider(); } return ISelectionProvider::Pointer(0); } QString PagePartSelectionTracker::GetPartId(IWorkbenchPart::Pointer part) { QString id = part->GetSite()->GetId(); if (part.Cast ().IsNotNull()) { QString secondaryId = part.Cast ()->GetViewSite() ->GetSecondaryId(); if (secondaryId != "") { id = id + ':' + secondaryId; } } return id; } void PagePartSelectionTracker::SetPage(IWorkbenchPage* page) { fPage = page; } void PagePartSelectionTracker::SetPart(IWorkbenchPart::Pointer part, bool notify) { if (fPart.IsNotNull()) { // remove myself as a listener from the existing part ISelectionProvider::Pointer sp = fPart->GetSite()->GetSelectionProvider(); if (sp.IsNotNull()) { - sp->RemoveSelectionChangedListener(selChangedListener); + sp->RemoveSelectionChangedListener(selChangedListener.data()); if (sp.Cast ().IsNotNull()) { sp.Cast () ->RemovePostSelectionChangedListener( - postSelectionListener); + postSelectionListener.data()); } else { - sp->RemoveSelectionChangedListener(postSelectionListener); + sp->RemoveSelectionChangedListener(postSelectionListener.data()); } } } fPart = part; ISelection::ConstPointer sel; if (part.IsNotNull()) { ISelectionProvider::Pointer sp = part->GetSite()->GetSelectionProvider(); if (sp.IsNotNull()) { - sp->AddSelectionChangedListener(selChangedListener); + sp->AddSelectionChangedListener(selChangedListener.data()); if (sp.Cast ().IsNotNull()) { sp.Cast () ->AddPostSelectionChangedListener( - postSelectionListener); + postSelectionListener.data()); } else { - sp->AddSelectionChangedListener(postSelectionListener); + sp->AddSelectionChangedListener(postSelectionListener.data()); } if (notify) { // get the selection to send below sel = sp->GetSelection(); } } } if (notify) { this->FireSelection(part, sel); this->FirePostSelection(part, sel); } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPagePartSelectionTracker.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPagePartSelectionTracker.h index aa4bd8e286..66130219b0 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPagePartSelectionTracker.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPagePartSelectionTracker.h @@ -1,143 +1,143 @@ /*=================================================================== 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 BERRYPAGEPARTSELECTIONTRACKER_H_ #define BERRYPAGEPARTSELECTIONTRACKER_H_ #include "berryIPartListener.h" #include "berryISelectionChangedListener.h" #include "berryISelectionService.h" #include "berryISelectionProvider.h" #include "berrySelectionChangedEvent.h" #include "berryIWorkbenchPage.h" #include "berryAbstractPartSelectionTracker.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * * Provides per-part selection tracking for the selection service. */ class PagePartSelectionTracker : public AbstractPartSelectionTracker { public: berryObjectMacro(PagePartSelectionTracker) private: /** * The workbench page for which this is tracking selection. */ IWorkbenchPage* fPage; /** * The part in this tracker's page, or null if one is not open. */ IWorkbenchPart::Pointer fPart; struct PostSelectionListener : public ISelectionChangedListener { PostSelectionListener(PagePartSelectionTracker* tracker); - void SelectionChanged(SelectionChangedEvent::Pointer event); + void SelectionChanged(const SelectionChangedEvent::Pointer& event); PagePartSelectionTracker* m_Tracker; }; friend struct PostSelectionListener; friend class SelTrackerPartListener; friend class SelTrackerPerspectiveListener; friend class SelTrackerSelectionChangedListener; - ISelectionChangedListener::Pointer postSelectionListener; - IPerspectiveListener::Pointer perspListener; - ISelectionChangedListener::Pointer selChangedListener; - IPartListener::Pointer partListener; + QScopedPointer postSelectionListener; + QScopedPointer perspListener; + QScopedPointer selChangedListener; + QScopedPointer partListener; public: /** * Constructs a part selection tracker for the part with the given id. * * @param id part identifier */ PagePartSelectionTracker(IWorkbenchPage* page, const QString& partId); /** * Returns the selection from the part being tracked, * or null if the part is closed or has no selection. */ ISelection::ConstPointer GetSelection(); /** * Disposes this selection tracker. This removes all listeners currently registered. */ ~PagePartSelectionTracker(); protected: /** * Returns the part this is tracking, * or null if it is not open * * @return part., or null */ IWorkbenchPart::Pointer GetPart(); /** * Returns the page this selection provider works for * * @return workbench page */ IWorkbenchPage::Pointer GetPage(); ISelectionProvider::Pointer GetSelectionProvider(); private: /** * Returns the id for the given part, taking into account * multi-view instances which may have a secondary id. * */ QString GetPartId(IWorkbenchPart::Pointer part); /** * Sets the page this selection provider works for * * @param page workbench page */ void SetPage(IWorkbenchPage* page); /** * Sets the part for this selection tracker. * * @param part the part * @param notify whether to send notification that the selection has changed. */ void SetPart(IWorkbenchPart::Pointer part, bool notify); }; } #endif /*BERRYPAGEPARTSELECTIONTRACKER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryParameterValueConverterProxy.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryParameterValueConverterProxy.cpp new file mode 100644 index 0000000000..a008a56801 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryParameterValueConverterProxy.cpp @@ -0,0 +1,72 @@ +/*=================================================================== + +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 "berryParameterValueConverterProxy.h" + +#include "berryWorkbenchRegistryConstants.h" +#include "berryCommandExceptions.h" +#include "berryIConfigurationElement.h" +#include "berryCoreException.h" + +namespace berry { + +IParameterValueConverter* ParameterValueConverterProxy::GetConverter() const +{ + if (parameterValueConverter.isNull()) + { + try + { + parameterValueConverter = QSharedPointer( + converterConfigurationElement->CreateExecutableExtension(WorkbenchRegistryConstants::ATT_CONVERTER) + ); + } + catch (const CoreException& e) + { + throw ParameterValueConversionException( + "Problem creating parameter value converter", e); + } + + if (parameterValueConverter.isNull()) + { + throw ParameterValueConversionException( + "Parameter value converter was not a subclass of AbstractParameterValueConverter"); + } + } + return parameterValueConverter.data(); +} + +ParameterValueConverterProxy::ParameterValueConverterProxy( + const SmartPointer& converterConfigurationElement) + : converterConfigurationElement(converterConfigurationElement) +{ + if (converterConfigurationElement.IsNull()) + { + throw ctkInvalidArgumentException( + "converterConfigurationElement must not be null"); + } +} + +Object::Pointer ParameterValueConverterProxy::ConvertToObject(const QString& parameterValue) +{ + return GetConverter()->ConvertToObject(parameterValue); +} + +QString ParameterValueConverterProxy::ConvertToString(const Object::Pointer& parameterValue) +{ + return GetConverter()->ConvertToString(parameterValue); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryParameterValueConverterProxy.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryParameterValueConverterProxy.h new file mode 100644 index 0000000000..11da0641d6 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryParameterValueConverterProxy.h @@ -0,0 +1,82 @@ +/*=================================================================== + +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 BERRYPARAMETERVALUECONVERTERPROXY_H +#define BERRYPARAMETERVALUECONVERTERPROXY_H + +#include "berryIParameterValueConverter.h" + +#include + +namespace berry { + +struct IConfigurationElement; + +/** + * A proxy for a parameter value converter that has been defined in the regisry. + * This delays the class loading until the converter is really asked to do + * string/object conversions. + */ +class ParameterValueConverterProxy : public IParameterValueConverter +{ + +private: + + /** + * The configuration element providing the executable extension that will + * extend AbstractParameterValueConverter. This value will + * not be null. + */ + const SmartPointer converterConfigurationElement; + + /** + * The real parameter value converter instance. This will be + * null until one of the conversion methods are used. + */ + mutable QSharedPointer parameterValueConverter; + + /** + * Returns the real parameter value converter for this proxy or throws an + * exception indicating the converter could not be obtained. + * + * @return the real converter for this proxy; never null. + * @throws ParameterValueConversionException + * if the converter could not be obtained + */ + IParameterValueConverter* GetConverter() const; + +public: + + /** + * Constructs a ParameterValueConverterProxy to represent the + * real converter until it is needed. + * + * @param converterConfigurationElement + * The configuration element from which the real converter can be + * loaded. + */ + ParameterValueConverterProxy( + const SmartPointer& converterConfigurationElement); + + Object::Pointer ConvertToObject(const QString& parameterValue); + + QString ConvertToString(const Object::Pointer& parameterValue); + +}; + +} + +#endif // BERRYPARAMETERVALUECONVERTERPROXY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartList.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartList.cpp index ebb3af2294..532a16014c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartList.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartList.cpp @@ -1,367 +1,367 @@ /*=================================================================== 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 "berryPartList.h" #include "berrySaveablesList.h" #include "berryPartPane.h" #include "berryIWorkbenchPartConstants.h" #include "berryIWorkbenchPartSite.h" #include namespace berry { -void PartList::PropertyChange(Object::Pointer source, int propId) +void PartList::PropertyChange(const Object::Pointer& source, int propId) { WorkbenchPartReference::Pointer ref = source.Cast< WorkbenchPartReference> (); if (propId == IWorkbenchPartConstants::PROP_OPENED) { this->PartOpened(ref); } else if (propId == IWorkbenchPartConstants::PROP_CLOSED) { this->PartClosed(ref); } else if (propId == IWorkbenchPartConstants::PROP_VISIBLE) { if (ref->GetVisible()) { this->PartVisible(ref); } else { this->PartHidden(ref); } } else if (propId == IWorkbenchPartConstants::PROP_INPUT) { this->PartInputChanged(ref); } } IWorkbenchPartReference::Pointer PartList::GetActivePartReference() { return activePartReference.Lock(); } IEditorReference::Pointer PartList::GetActiveEditorReference() { return activeEditorReference.Lock(); } IEditorPart::Pointer PartList::GetActiveEditor() { return activeEditorReference.Expired() ? IEditorPart::Pointer(0) : activeEditorReference.Lock()->GetEditor( false); } IWorkbenchPart::Pointer PartList::GetActivePart() { return activePartReference.Expired() ? IWorkbenchPart::Pointer(0) : activePartReference.Lock()->GetPart(false); } //QList PartList::GetEditors() //{ // QList result; // for (std::deque::iterator iter = // parts.begin(); iter != parts.end(); ++iter) // { // if (iter->Cast () != 0) // result.push_back(iter->Cast ()); // } // // return result; //} void PartList::AddPart(WorkbenchPartReference::Pointer ref) { poco_assert(ref.IsNotNull()); ref->AddPropertyListener(this); // if (!this->Contains(ref)) // { // parts.push_back(ref); // } // parts.add(ref); this->FirePartAdded(ref); // If this part is already open, fire the "part opened" event // immediately if (ref->GetPart(false).IsNotNull()) { this->PartOpened(ref); } // If this part is already visible, fire the visibility event // immediately if (ref->GetVisible()) { this->PartVisible(ref); } } void PartList::SetActivePart(IWorkbenchPartReference::Pointer ref) { if (activePartReference.Lock() == ref) { return; } IWorkbenchPartReference::Pointer oldPart = activePartReference.Lock(); // A part can't be activated until it is added //poco_assert(ref == 0 || this->Contains(ref)); //std::remove(parts.begin(), parts.end(), ref); //parts.push_front(ref); activePartReference = ref; this->FireActivePartChanged(oldPart, ref); } void PartList::SetActiveEditor(IEditorReference::Pointer ref) { if (activeEditorReference.Lock() == ref) { return; } // A part can't be activated until it is added //poco_assert(ref == 0 || this->Contains(ref)); activeEditorReference = ref; //std::remove(parts.begin(), parts.end(), ref); //parts.push_front(ref); this->FireActiveEditorChanged(ref); } void PartList::RemovePart(WorkbenchPartReference::Pointer ref) { poco_assert(ref.IsNotNull()); // It is an error to remove a part that isn't in the list //poco_assert(this->Contains(ref)); // We're not allowed to remove the active part. We must deactivate it // first. poco_assert(activePartReference.Lock() != ref); // We're not allowed to remove the active editor. We must deactivate it // first. if (ref.Cast()) { poco_assert(activeEditorReference.Lock() != ref.Cast()); } if (ref->GetVisible()) { ref->SetVisible(false); } // If this part is currently open, fire the "part closed" event before // removal if (ref->GetPart(false).IsNotNull()) { this->PartClosed(ref); } //std::remove(parts.begin(), parts.end(), ref); ref->RemovePropertyListener(this); this->FirePartRemoved(ref); } //int PartList::IndexOf(const IWorkbenchPartReference::Pointer ref) const //{ // std::deque::const_iterator result = std::find(parts.begin(), parts.end(), ref); // if (result == parts.end()) return -1; // else return result - parts.begin(); //} //void PartList::BringToTop(IWorkbenchPartReference::Pointer ref) //{ // ILayoutContainer::Pointer targetContainer; // if (ref != 0) // { // PartPane::Pointer pane = ref.Cast()->GetPane(); // if (pane != 0) // { // targetContainer = pane->GetContainer(); // } // } // // std::deque::iterator newIndex = this->LastIndexOfContainer(targetContainer); // // // //New index can be -1 if there is no last index // // if (newIndex >= 0 && ref == parts.get(newIndex)) // // return; // // std::remove(parts.begin(), parts.end(), ref); // if(newIndex != parts.end()) // { // parts.insert(newIndex, ref); // } // else // parts.push_front(ref); //} //QList //PartList::GetParts(const QList& views) //{ // QList resultList; // for (std::deque::iterator partIter = parts.begin(); // partIter != parts.end(); ++partIter) // { // IWorkbenchPartReference::Pointer ref = *partIter; // if (ref.Cast() != 0) // { // //Filter views from other perspectives // for (unsigned int i = 0; i < views.size(); i++) // { // if (ref == views[i]) // { // resultList.push_back(ref); // break; // } // } // } // else // { // resultList.push_back(ref); // } // } // return resultList; //} //std::deque::iterator //PartList::LastIndexOfContainer(ILayoutContainer::Pointer container) //{ // for (std::deque::iterator iter = parts.begin(); // iter != parts.end(); ++iter) // { // IWorkbenchPartReference::Pointer ref = *iter; // // ILayoutContainer::Pointer cnt; // PartPane::Pointer pane = ref.Cast()->GetPane(); // if (pane != 0) // { // cnt = pane->GetContainer(); // } // if (cnt == container) // { // return iter; // } // } // // return parts.end(); //} //bool PartList::Contains(IWorkbenchPartReference::Pointer ref) //{ // return std::find(parts.begin(), parts.end(), ref) != parts.end(); //} void PartList::PartInputChanged(WorkbenchPartReference::Pointer ref) { this->FirePartInputChanged(ref); } void PartList::PartHidden(WorkbenchPartReference::Pointer ref) { // Part should not be null poco_assert(ref.IsNotNull()); // This event should only be fired if the part is actually visible poco_assert(!ref->GetVisible()); // We shouldn't be receiving events from parts until they are in the // list //poco_assert(this->Contains(ref)); this->FirePartHidden(ref); } void PartList::PartOpened(WorkbenchPartReference::Pointer ref) { poco_assert(ref.IsNotNull()); IWorkbenchPart::Pointer actualPart = ref->GetPart(false); // We're firing the event that says "the part was just created"... so // there better be a part there. poco_assert(actualPart.IsNotNull()); // Must be called after the part is inserted into the part list //poco_assert(this->Contains(ref)); // The active part must be opened before it is activated, so we should // never get an open event for a part that is already active. // (This either indicates that a redundant // open event was fired or that a closed part was somehow activated) poco_assert(activePartReference.Lock() != ref); // The active editor must be opened before it is activated, so we should // never get an open event for an editor that is already active. // (This either indicates that a redundant // open event was fired or that a closed editor was somehow activated) poco_assert((void*)activeEditorReference.Lock().GetPointer() != (void*)ref.GetPointer()); SaveablesList* modelManager = dynamic_cast( actualPart->GetSite()->GetService()); modelManager->PostOpen(actualPart); // Fire the "part opened" event this->FirePartOpened(ref); } void PartList::PartClosed(WorkbenchPartReference::Pointer ref) { poco_assert(ref.IsNotNull()); IWorkbenchPart::Pointer actualPart = ref->GetPart(false); // Called before the part is disposed, so the part should still be // there. poco_assert(actualPart.IsNotNull()); // Must be called before the part is actually removed from the part list // poco_assert(this->Contains(ref)); // Not allowed to close the active part. The part must be deactivated // before it may be closed. poco_assert(activePartReference.Lock() != ref); // Not allowed to close the active editor. The editor must be // deactivated before it may be closed. if (ref.Cast()) { poco_assert(activeEditorReference.Lock() != ref.Cast()); } this->FirePartClosed(ref); } void PartList::PartVisible(WorkbenchPartReference::Pointer ref) { // Part should not be null poco_assert(ref.IsNotNull()); // This event should only be fired if the part is actually visible poco_assert(ref->GetVisible()); // We shouldn't be receiving events from parts until they are in the // list //poco_assert(this->Contains(ref)); // Part must be open before it can be made visible poco_assert(ref->GetPart(false).IsNotNull()); this->FirePartVisible(ref); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartList.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartList.h index 209e5b5d64..a4f7dc9d09 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartList.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartList.h @@ -1,189 +1,190 @@ /*=================================================================== 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 BERRYPARTLIST_H_ #define BERRYPARTLIST_H_ #include "berryWorkbenchPartReference.h" #include "berryILayoutContainer.h" #include "berryIEditorReference.h" #include "berryIViewReference.h" #include namespace berry { class PartList : public IPropertyChangeListener { private: // list of parts in the activation order (oldest last) //std::deque parts; IWorkbenchPartReference::WeakPtr activePartReference; IEditorReference::WeakPtr activeEditorReference; public: - void PropertyChange(Object::Pointer source, int propId); + using IPropertyChangeListener::PropertyChange; + void PropertyChange(const Object::Pointer& source, int propId); IWorkbenchPartReference::Pointer GetActivePartReference(); IEditorReference::Pointer GetActiveEditorReference(); IEditorPart::Pointer GetActiveEditor(); IWorkbenchPart::Pointer GetActivePart(); //QList GetEditors(); void AddPart(WorkbenchPartReference::Pointer ref); /** * Sets the active part. * * @param ref */ void SetActivePart(IWorkbenchPartReference::Pointer ref); void SetActiveEditor(IEditorReference::Pointer ref); /** * In order to remove a part, it must first be deactivated. */ void RemovePart(WorkbenchPartReference::Pointer ref); //int IndexOf(const IWorkbenchPartReference::Pointer ref) const; /* * Ensures that the given part appears AFTER any other part in the same * container. */ //void BringToTop(IWorkbenchPartReference::Pointer ref); /* * Return a list with all parts (editors and views). */ //QList GetParts(const QList& views); private: /* * Returns the last (most recent) index of the given container in the activation list, or returns * -1 if the given container does not appear in the activation list. */ //std::deque::iterator // LastIndexOfContainer(ILayoutContainer::Pointer container); void PartInputChanged(WorkbenchPartReference::Pointer ref); void PartHidden(WorkbenchPartReference::Pointer ref); void PartOpened(WorkbenchPartReference::Pointer ref); /** * Called when a concrete part is about to be destroyed. This is called * BEFORE disposal happens, so the part should still be accessable from the * part reference. * * @param ref */ void PartClosed(WorkbenchPartReference::Pointer ref); void PartVisible(WorkbenchPartReference::Pointer ref); //bool Contains(IWorkbenchPartReference::Pointer ref); protected: /** * Fire the event indicating that a part reference was just realized. That * is, the concrete IWorkbenchPart has been attached to the part reference. * * @param part * the reference that was create */ virtual void FirePartOpened(IWorkbenchPartReference::Pointer part) = 0; /** * Fire the event indicating that a part reference was just realized. That * is, the concrete IWorkbenchPart has been attached to the part reference. * * @param part * the reference that was create */ virtual void FirePartClosed(IWorkbenchPartReference::Pointer part) = 0; /** * Indicates that a new part reference was added to the list. * * @param part */ virtual void FirePartAdded(IWorkbenchPartReference::Pointer part) = 0; /** * Indicates that a part reference was removed from the list * * @param part */ virtual void FirePartRemoved(IWorkbenchPartReference::Pointer part) = 0; /** * Indicates that the active editor changed * * @param part * active part reference or null if none */ virtual void FireActiveEditorChanged(IWorkbenchPartReference::Pointer ref) = 0; /** * Indicates that the active part has changed * * @param part * active part reference or null if none */ virtual void FireActivePartChanged( IWorkbenchPartReference::Pointer oldPart, IWorkbenchPartReference::Pointer newPart) = 0; /** * Indicates that the part has been made visible * * @param ref */ virtual void FirePartVisible(IWorkbenchPartReference::Pointer ref) = 0; /** * Indicates that the part has been hidden * * @param ref */ virtual void FirePartHidden(IWorkbenchPartReference::Pointer ref) = 0; /** * Indicates that the part input has changed * * @param ref */ virtual void FirePartInputChanged(IWorkbenchPartReference::Pointer ref) = 0; virtual void FirePartBroughtToTop(IWorkbenchPartReference::Pointer ref) = 0; }; } #endif /*BERRYPARTLIST_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.cpp index 973ea5fbbd..4528612f65 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.cpp @@ -1,464 +1,464 @@ /*=================================================================== 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 "tweaklets/berryGuiWidgetsTweaklet.h" #include "berryPartPane.h" #include "tweaklets/berryWorkbenchPageTweaklet.h" #include "berryWorkbenchPage.h" #include "berryPartStack.h" #include "berryEditorAreaHelper.h" #include "berryPerspective.h" #include "berryPartStack.h" #include "berryDragUtil.h" namespace berry { PartPane::Sashes::Sashes() : left(0), right(0), top(0), bottom(0) { } PartPane::PartPane(IWorkbenchPartReference::Pointer partReference, WorkbenchPage* workbenchPage) : LayoutPart(partReference->GetId()), control(0), inLayout(true), busy(false), hasFocus(false) { //super(partReference.getId()); this->partReference = partReference; this->page = workbenchPage; } void PartPane::CreateControl(void* parent) { if (this->GetControl() != 0) { return; } partReference.Lock()->AddPropertyListener(this); // Create view form. control = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreatePaneControl(parent); // the part should never be visible by default. It will be made visible // by activation. This allows us to have views appear in tabs without // becoming active by default. Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(control, false); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->MoveAbove(control, 0); // Create a title bar. //this->CreateTitleBar(); // When the pane or any child gains focus, notify the workbench. Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(control, GuiTk::IControlListener::Pointer(this)); //control.addTraverseListener(traverseListener); } PartPane::~PartPane() { // super.dispose(); // this->Register(); if (control != 0) { BERRY_DEBUG << "Deleting PartPane control"; Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(control, GuiTk::IControlListener::Pointer(this)); // control.removeTraverseListener(traverseListener); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->Dispose(control); control = 0; } // if ((paneMenuManager != null)) // { // paneMenuManager.dispose(); // paneMenuManager = null; // } // if (!partReference.Expired()) { partReference.Lock()->RemovePropertyListener(this); } // partReference.removePartPropertyListener(this); this->UnRegister(false); } void PartPane::DoHide() { if (partReference.Lock().Cast() != 0) { this->GetPage()->HideView(partReference.Lock().Cast()); } else if (partReference.Lock().Cast() != 0) { this->GetPage()->CloseEditor(partReference.Lock().Cast(), true); } } Rectangle PartPane::GetParentBounds() { void* ctrl = this->GetControl(); if (this->GetContainer() != 0 && this->GetContainer().Cast() != 0) { LayoutPart::Pointer part = this->GetContainer().Cast(); if (part->GetControl() != 0) { ctrl = part->GetControl(); } } return DragUtil::GetDisplayBounds(ctrl); } void* PartPane::GetControl() { return control; } IWorkbenchPartReference::Pointer PartPane::GetPartReference() const { return partReference.Lock(); } void PartPane::ControlActivated(GuiTk::ControlEvent::Pointer /*e*/) { if (inLayout) { this->RequestActivation(); } } GuiTk::IControlListener::Events::Types PartPane::GetEventTypes() const { return GuiTk::IControlListener::Events::ACTIVATED; } void PartPane::MoveAbove(void* refControl) { if (this->GetControl() != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->MoveAbove(this->GetControl(), refControl); } } void PartPane::RequestActivation() { IWorkbenchPart::Pointer part = partReference.Lock()->GetPart(true); this->page->RequestActivation(part); } //PartStack::Pointer PartPane::GetStack() //{ // return partStack; //} PartPane::Sashes PartPane::FindSashes() { Sashes result; ILayoutContainer::Pointer container = this->GetContainer(); if (container == 0) { return result; } container->FindSashes(LayoutPart::Pointer(this), result); return result; } WorkbenchPage::Pointer PartPane::GetPage() { return WorkbenchPage::Pointer(page); } void PartPane::SetContainer(ILayoutContainer::Pointer container) { if (hasFocus) { ILayoutContainer::Pointer oldContainer = this->GetContainer(); if (PartStack::Pointer oldStack = oldContainer.Cast()) { oldStack->SetActive(StackPresentation::AS_INACTIVE); } if (PartStack::Pointer newContainer = container.Cast()) { newContainer->SetActive(StackPresentation::AS_ACTIVE_FOCUS); } } void* containerControl = container == 0 ? 0 : container.Cast()->GetControl(); if (containerControl != 0) { void* control = this->GetControl(); void* newParent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(containerControl); if (control != 0 && newParent != Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(control)) { this->Reparent(newParent); } } LayoutPart::SetContainer(container); } void PartPane::Reparent(void* newParent) { void* control = this->GetControl(); GuiWidgetsTweaklet* guiTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if ((control == 0) || (guiTweaklet->GetParent(control) == newParent)) { return; } if (guiTweaklet->IsReparentable(control)) { // make control small in case it is not resized with other controls //control.setBounds(0, 0, 0, 0); // By setting the control to disabled before moving it, // we ensure that the focus goes away from the control and its children // and moves somewhere else bool enabled = guiTweaklet->GetEnabled(control); guiTweaklet->SetEnabled(control, false); guiTweaklet->SetParent(control, newParent); guiTweaklet->SetEnabled(control, enabled); guiTweaklet->MoveAbove(control, 0); } } void PartPane::ShowFocus(bool inFocus) { if (partReference.Lock().Cast() != 0) { hasFocus = inFocus; } if (PartStack::Pointer stack = this->GetContainer().Cast()) { if (partReference.Lock().Cast() != 0) { stack->SetActive(inFocus ? StackPresentation::AS_ACTIVE_FOCUS : StackPresentation::AS_INACTIVE); } else if (partReference.Lock().Cast() != 0) { if (inFocus) { page->GetEditorPresentation()->SetActiveWorkbook(stack, true); } else { stack->SetActive(page->GetEditorPresentation()->GetActiveWorkbook() == stack ? StackPresentation::AS_ACTIVE_NOFOCUS : StackPresentation::AS_INACTIVE); } } } } PartStack::Pointer PartPane::GetStack() { ILayoutContainer::Pointer container = this->GetContainer(); return container.Cast(); } void PartPane::SetVisible(bool makeVisible) { // Avoid redundant visibility changes if (makeVisible == this->GetVisible()) { return; } if (makeVisible) { partReference.Lock()->GetPart(true); } if (this->GetControl() != 0) Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(this->GetControl(), makeVisible); partReference.Lock().Cast()->FireVisibilityChange(); } bool PartPane::GetVisible() { if (this->GetControl() != 0) return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(this->GetControl()); return false; } void PartPane::SetFocus() { this->RequestActivation(); IWorkbenchPart::Pointer part = partReference.Lock()->GetPart(true); if (part.IsNotNull()) { // Control control = getControl(); // if (!SwtUtil.isFocusAncestor(control)) // { // First try to call part.setFocus part->SetFocus(); //} } } void PartPane::SetWorkbenchPage(WorkbenchPage::Pointer workbenchPage) { this->page = workbenchPage.GetPointer(); } void PartPane::DoDock() { // do nothing } void PartPane::SetBusy(bool isBusy) { if (isBusy != busy) { busy = isBusy; //firePropertyChange(IPresentablePart.PROP_BUSY); } } void PartPane::ShowHighlight() { //No nothing by default } void* PartPane::GetToolBar() { return 0; } bool PartPane::HasViewMenu() { return false; } bool PartPane::IsBusy() { return busy; } void PartPane::DescribeLayout(QString& buf) const { IWorkbenchPartReference::Pointer part = this->GetPartReference(); if (part.IsNotNull()) { buf.append(part->GetPartName()); return; } } bool PartPane::IsCloseable() { if (partReference.Lock().Cast() != 0) { Perspective::Pointer perspective = page->GetActivePerspective(); if (perspective == 0) { // Shouldn't happen -- can't have a ViewStack without a // perspective return true; } return perspective->IsCloseable(partReference.Lock().Cast()); } return true; } void PartPane::SetInLayout(bool inLayout) { this->inLayout = inLayout; } bool PartPane::GetInLayout() { return inLayout; } bool PartPane::AllowsAutoFocus() { if (!inLayout) { return false; } //return super.allowsAutoFocus(); return true; } void PartPane::RemoveContributions() { } void PartPane::AddPropertyListener(IPropertyChangeListener *listener) { propertyChangeEvents.AddListener(listener); } void PartPane::RemovePropertyListener(IPropertyChangeListener *listener) { propertyChangeEvents.RemoveListener(listener); } -void PartPane::FirePropertyChange(PropertyChangeEvent::Pointer event) +void PartPane::FirePropertyChange(const PropertyChangeEvent::Pointer& event) { propertyChangeEvents.propertyChange(event); } -void PartPane::PropertyChange(PropertyChangeEvent::Pointer event) +void PartPane::PropertyChange(const PropertyChangeEvent::Pointer& event) { this->FirePropertyChange(event); } int PartPane::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { return partReference.Lock().Cast()->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } int PartPane::GetSizeFlags(bool horizontal) { return partReference.Lock().Cast()->GetSizeFlags(horizontal); } void PartPane::ShellActivated() { } void PartPane::ShellDeactivated() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.h index f27e55e8f2..0dcb80ac98 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartPane.h @@ -1,434 +1,437 @@ /*=================================================================== 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 BERRYPARTPANE_H_ #define BERRYPARTPANE_H_ #include "berryWorkbenchPartReference.h" #include "berryLayoutPart.h" #include "berryRectangle.h" #include "berryIPropertyChangeListener.h" #include "guitk/berryGuiTkIControlListener.h" namespace berry { class WorkbenchPage; class PartStack; struct ILayoutContainer; /** * Provides the common behavior for both views * and editor panes. * */ class PartPane : public LayoutPart, public IPropertyChangeListener, public GuiTk::IControlListener { public: berryObjectMacro(PartPane) friend class PartSashContainer; friend class EditorSashContainer; friend class WorkbenchPage; friend struct ILayoutContainer; friend class PartStack; friend class ContainerPlaceholder; friend class LayoutTree; friend class LayoutTreeNode; friend class DetachedPlaceHolder; friend class PerspectiveHelper; // private: MenuManager paneMenuManager; // private: ListenerList listeners = new ListenerList(); // private: ListenerList partListeners = new ListenerList(); private: IPropertyChangeListener::Events propertyChangeEvents; protected: IWorkbenchPartReference::WeakPtr partReference; protected: WorkbenchPage* page; protected: void* control; private: bool inLayout; // private: TraverseListener traverseListener = new TraverseListener() { // /* (non-Javadoc) // * @see org.blueberry.swt.events.TraverseListener#keyTraversed(org.blueberry.swt.events.TraverseEvent) // */ // public: void keyTraversed(TraverseEvent e) { // // Hack: Currently, SWT sets focus whenever we call Control.traverse. This doesn't // // cause too much of a problem for ctrl-pgup and ctrl-pgdn, but it is seriously unexpected // // for other traversal events. When (and if) it becomes possible to call traverse() without // // forcing a focus change, this if statement should be removed and ALL events should be // // forwarded to the container. // if (e.detail == SWT.TRAVERSE_PAGE_NEXT // || e.detail == SWT.TRAVERSE_PAGE_PREVIOUS) { // ILayoutContainer container = getContainer(); // if (container != null && container instanceof LayoutPart) { // LayoutPart parent = (LayoutPart) container; // Control parentControl = parent.getControl(); // if (parentControl != null && !parentControl.isDisposed()) { // e.doit = parentControl.traverse(e.detail); // if (e.doit) { // e.detail = SWT.TRAVERSE_NONE; // } // } // } // } // } // // }; private: bool busy; private: bool hasFocus; //private: SmartPointer partStack; protected: /*static*/ class Sashes { public: Sashes(); /*Sash*/ void* left; /*Sash*/ void* right; /*Sash*/ void* top; /*Sash*/ void* bottom; }; /** * Construct a pane for a part. */ public: PartPane(IWorkbenchPartReference::Pointer partReference, WorkbenchPage* workbenchPage); // public: void addSizeMenuItem(Menu menu, int index) { // //Add size menu // MenuItem item = new MenuItem(menu, SWT.CASCADE, index); // item.setText(WorkbenchMessages.PartPane_size); // Menu sizeMenu = new Menu(menu); // item.setMenu(sizeMenu); // addSizeItems(sizeMenu); // } /** * * Creates the GUI-dependent container control * for the part widgets. This is passed to * IWorkbenchPart::CreatePartControl(void*) */ public: virtual void CreateControl(void* parent); //public: virtual void SetControlEnabled(bool enabled) = 0; /** * Create a title bar for the pane if required. */ // protected: virtual void CreateTitleBar() = 0; /** * @private: */ public: virtual ~PartPane(); /** * User has requested to close the pane. * Take appropriate action depending on type. */ public: void DoHide(); protected: Rectangle GetParentBounds(); /** * Get the control. */ public: void* GetControl(); /** * Answer the part child. */ public: IWorkbenchPartReference::Pointer GetPartReference() const; /** * @see GuiTk::IControlListener */ public: void ControlActivated(GuiTk::ControlEvent::Pointer e); /** * @see GuiTk::IControlListener */ public: GuiTk::IControlListener::Events::Types GetEventTypes() const; /** * Move the control over another one. */ public: void MoveAbove(void* refControl); /** * Notify the workbook page that the part pane has * been activated by the user. */ public: void RequestActivation(); /** * Shows the receiver if visible is true otherwise hide it. */ public: void SetVisible(bool makeVisible); public: virtual bool GetVisible(); /** * Sets focus to this part. */ public: void SetFocus(); /** * Sets the workbench page of the view. */ public: void SetWorkbenchPage(SmartPointer workbenchPage); public: void Reparent(void* newParent); /** * Indicate focus in part. */ public: void ShowFocus(bool inFocus); /** * @see IPartDropTarget::targetPartFor */ // public: LayoutPart targetPartFor(LayoutPart dragSource) { // return this; // } /** * Returns the PartStack that contains this PartPane, or null if none. * * @return */ public: SmartPointer GetStack(); public: void SetContainer(SmartPointer stack); /** * Show a title label menu for this pane. */ // public: void ShowPaneMenu() { // PartStack folder = getStack(); // // if (folder != null) { // folder.showPaneMenu(); // } // } /** * Show the context menu for this part. */ // public: void showSystemMenu() { // PartStack folder = getStack(); // // if (folder != null) { // folder.showSystemMenu(); // } // } /** * Finds and return the sashes around this part. */ protected: Sashes FindSashes(); /** * Enable the user to resize this part using * the keyboard to move the specified sash */ // protected: void moveSash(final Sash sash) { // moveSash(sash, this); // } // public: static void moveSash(final Sash sash, // final LayoutPart toGetFocusWhenDone) { // final KeyListener listener = new KeyAdapter() { // public: void keyPressed(KeyEvent e) { // if (e.character == SWT.ESC || e.character == '\r') { // if (toGetFocusWhenDone != null) { // toGetFocusWhenDone.setFocus(); // } // } // } // }; // sash.addFocusListener(new FocusAdapter() { // public: void focusGained(FocusEvent e) { // sash.setBackground(sash.getDisplay().getSystemColor( // SWT.COLOR_LIST_SELECTION)); // sash.addKeyListener(listener); // } // // public: void focusLost(FocusEvent e) { // sash.setBackground(null); // sash.removeKeyListener(listener); // } // }); // sash.setFocus(); // // } /** * Add a menu item to the Size Menu */ // protected: void addSizeItem(Menu sizeMenu, String labelMessage, // final Sash sash) { // MenuItem item = new MenuItem(sizeMenu, SWT.NONE); // item.setText(labelMessage); // item.addSelectionListener(new SelectionAdapter() { // public: void widgetSelected(SelectionEvent e) { // moveSash(sash); // } // }); // item.setEnabled(!isZoomed() && sash != null); // } /** * Returns the workbench page of this pane. */ public: SmartPointer GetPage(); /** * Add the Left,Right,Up,Botton menu items to the Size menu. */ // protected: void addSizeItems(Menu sizeMenu) { // Sashes sashes = findSashes(); // addSizeItem(sizeMenu, // WorkbenchMessages.PartPane_sizeLeft, sashes.left); // addSizeItem(sizeMenu, // WorkbenchMessages.PartPane_sizeRight, sashes.right); // addSizeItem(sizeMenu, // WorkbenchMessages.PartPane_sizeTop, sashes.top); // addSizeItem(sizeMenu, WorkbenchMessages.PartPane_sizeBottom, sashes.bottom); // } /** * Pin this part. */ protected: virtual void DoDock(); /** * Set the busy state of the pane. */ public: virtual void SetBusy(bool isBusy); /** * Show a highlight for the receiver if it is * not currently the part in the front of its * presentation. * */ public: virtual void ShowHighlight(); /** * @return */ public: virtual void* GetToolBar(); /** * @return */ public: bool HasViewMenu(); /** * @param location */ // public: void ShowViewMenu(Point location) { // // } public: bool IsBusy(); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they do not need to be translated. * * @param buf */ public: void DescribeLayout(QString& buf) const; /** * @return * @since 3.1 */ public: bool IsCloseable(); public: void SetInLayout(bool inLayout); public: bool GetInLayout(); public: bool AllowsAutoFocus(); /** * Clears all contribution items from the contribution managers (this is done separately * from dispose() since it is done after the part is disposed). This is a bit of a hack. * Really, the contribution managers should be part of the site, not the PartPane. If these * were moved elsewhere, then disposal of the PartPane would be atomic and this method could * be removed. */ public: virtual void RemoveContributions(); public: void AddPropertyListener(IPropertyChangeListener* listener); public: void RemovePropertyListener(IPropertyChangeListener* listener); - public: void FirePropertyChange(PropertyChangeEvent::Pointer event); + public: void FirePropertyChange(const PropertyChangeEvent::Pointer& event); /* (non-Javadoc) * @see IPropertyChangeListener#PropertyChange(PropertyChangeEvent::Pointer) */ - public: void PropertyChange(PropertyChangeEvent::Pointer event); + public: + + using IPropertyChangeListener::PropertyChange; + void PropertyChange(const PropertyChangeEvent::Pointer& event); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#computePreferredSize(boolean, int, int, int) */ public: int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#getSizeFlags(boolean) */ public: int GetSizeFlags(bool horizontal); /** * Informs the pane that it's window shell has * been activated. */ public: virtual void ShellActivated(); /** * Informs the pane that it's window shell has * been deactivated. */ public: virtual void ShellDeactivated(); }; } #endif /*BERRYPARTPANE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp index 0a1472c229..6bf4bd7481 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.cpp @@ -1,1272 +1,1272 @@ /*=================================================================== 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 "tweaklets/berryGuiWidgetsTweaklet.h" #include "berryPartSashContainer.h" #include "berryLayoutTree.h" #include "berryLayoutTreeNode.h" #include "berryPartStack.h" #include "berryPageLayout.h" #include "berryPerspective.h" #include "berryPerspectiveHelper.h" #include "berryDragUtil.h" #include "berryWorkbenchPlugin.h" #include "berryIPreferencesService.h" #include "berryIPreferences.h" #include "berryWorkbenchPreferenceConstants.h" #include "berryGeometry.h" #include "berryPartPane.h" #include "berryConstants.h" namespace berry { bool PartSashContainer::leftToRight = true; PartSashContainer::ControlListener::ControlListener( PartSashContainer* container) : partSashContainer(container) { } GuiTk::IControlListener::Events::Types PartSashContainer::ControlListener::GetEventTypes() const { return Events::RESIZED; } void PartSashContainer::ControlListener::ControlResized( GuiTk::ControlEvent::Pointer /*e*/) { partSashContainer->ResizeSashes(); } PartSashContainer::SashContainerDropTarget::SashContainerDropTarget( PartSashContainer* partSashContainer, Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) : partSashContainer(partSashContainer) { this->SetTarget(sourcePart, side, cursor, targetPart); } void PartSashContainer::SashContainerDropTarget::SetTarget( Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) { this->side = side; this->targetPart = targetPart; this->sourcePart = sourcePart; this->cursor = cursor; } void PartSashContainer::SashContainerDropTarget::Drop() { if (side != Constants::NONE) { LayoutPart::Pointer visiblePart = sourcePart.Cast (); if (sourcePart.Cast () != 0) { visiblePart = partSashContainer->GetVisiblePart(sourcePart.Cast< ILayoutContainer> ()); } partSashContainer->DropObject( partSashContainer->GetVisibleParts(sourcePart), visiblePart, targetPart, side); } } void PartSashContainer::DropObject(const QList& toDrop, LayoutPart::Pointer visiblePart, Object::Pointer targetPart, int side) { //getControl().setRedraw(false); // Targetpart is null if there isn't a part under the cursor (all the parts are // hidden or the container is empty). In this case, the actual side doesn't really // since we'll be the only visible container and will fill the entire space. However, // we can't leave it as Constants::CENTER since we can't stack if we don't have something // to stack on. In this case, we pick Constants::BOTTOM -- this will insert the new pane // below any currently-hidden parts. if (targetPart == 0 && side == Constants::CENTER) { side = Constants::BOTTOM; } PartStack::Pointer targetStack = targetPart.Cast (); if (targetStack == 0 && targetPart.Cast() != 0) { targetStack = targetPart.Cast ()->GetStack(); } LayoutPart::Pointer targetLayoutPart = targetStack; // if targetLayoutPart == 0 then we normally got a EditorSashContainer if (targetLayoutPart == 0) targetLayoutPart = targetPart.Cast(); if (side == Constants::CENTER) { if (this->IsStackType(targetStack)) { - for (unsigned int idx = 0; idx < toDrop.size(); idx++) + for (int idx = 0; idx < toDrop.size(); idx++) { LayoutPart::Pointer next = toDrop[idx]; this->Stack(next, targetStack); } } } else { PartStack::Pointer newPart = this->CreateStack(); // if the toDrop array has 1 item propagate the stack // appearance if (toDrop.size() == 1 && toDrop[0]->GetStack() != 0) { toDrop[0]->GetStack()->CopyAppearanceProperties(newPart); } - for (unsigned int idx = 0; idx < toDrop.size(); idx++) + for (int idx = 0; idx < toDrop.size(); idx++) { LayoutPart::Pointer next = toDrop[idx]; this->Stack(next, newPart); } this->AddEnhanced(newPart, side, this->GetDockingRatio(newPart, targetStack), targetLayoutPart); } if (visiblePart != 0) { this->SetVisiblePart(visiblePart->GetContainer(), visiblePart.Cast ()); } //getControl().setRedraw(true); if (visiblePart != 0) { visiblePart->SetFocus(); } } DnDTweaklet::CursorType PartSashContainer::SashContainerDropTarget::GetCursor() { return DnDTweaklet::PositionToCursorType(cursor); } Rectangle PartSashContainer::SashContainerDropTarget::GetSnapRectangle() { Rectangle targetBounds; if (targetPart.Cast () != 0) { targetBounds = DragUtil::GetDisplayBounds( targetPart.Cast ()->GetControl()); } else if (targetPart.Cast () != 0) { targetBounds = DragUtil::GetDisplayBounds( targetPart.Cast ()->GetControl()); } else { targetBounds = DragUtil::GetDisplayBounds(partSashContainer->GetParent()); } if (side == Constants::CENTER || side == Constants::NONE) { return targetBounds; } int distance = Geometry::GetDimension(targetBounds, !Geometry::IsHorizontal( side)); ILayoutContainer::Pointer stack = targetPart.Cast (); if (stack == 0 && targetPart.Cast () != 0) { stack = targetPart.Cast ()->GetContainer(); } return Geometry::GetExtrudedEdge(targetBounds, (int) (distance * partSashContainer->GetDockingRatio(sourcePart, stack)), side); } PartSashContainer::PartSashContainer(const QString& id, WorkbenchPage* _page, void* _parentWidget) : LayoutPart(id), parentWidget(_parentWidget), parent(0), page(_page), active( false), layoutDirty(false) { resizeListener = new ControlListener(this); QString layout = WorkbenchPlugin::GetDefault()->GetPreferencesService()-> GetSystemPreferences()->Get(WorkbenchPreferenceConstants::PREFERRED_SASH_LAYOUT, WorkbenchPreferenceConstants::LEFT); if (layout == WorkbenchPreferenceConstants::RIGHT) { leftToRight = false; } } QList PartSashContainer::GetVisibleParts( Object::Pointer pane) { QList parts; if (pane.Cast ().IsNotNull()) { parts.push_back(pane.Cast ()); } else if (pane.Cast ().IsNotNull()) { PartStack::Pointer stack = pane.Cast (); QList children = stack->GetChildren(); for (QList::iterator iter = children.begin(); iter != children.end(); ++iter) { if (iter->Cast () != 0) { parts.push_back(iter->Cast ()); } } } return parts; } PartSashContainer::~PartSashContainer() { } void PartSashContainer::FindSashes(LayoutPart::Pointer pane, PartPane::Sashes& sashes) { if (root == 0) { return; } LayoutTree::Pointer part = root->Find(pane); if (part == 0) { return; } part->FindSashes(sashes); } void PartSashContainer::Add(LayoutPart::Pointer child) { if (child.IsNull()) { return; } this->AddEnhanced(child, Constants::RIGHT, 0.5f, this->FindBottomRight()); } void PartSashContainer::AddPart(LayoutPart::Pointer child) { if (child.IsNull()) { return; } PartStack::Pointer newFolder = this->CreateStack(); newFolder->Add(child); this->AddEnhanced(newFolder, Constants::RIGHT, 0.5f, this->FindBottomRight()); } void PartSashContainer::AddEnhanced(LayoutPart::Pointer child, int directionConstant, float ratioForNewPart, LayoutPart::Pointer relative) { int relativePosition = PageLayout::ConstantToLayoutPosition(directionConstant); float ratioForUpperLeftPart; if (relativePosition == IPageLayout::RIGHT || relativePosition == IPageLayout::BOTTOM) { ratioForUpperLeftPart = 1.0f - ratioForNewPart; } else { ratioForUpperLeftPart = ratioForNewPart; } this->Add(child, relativePosition, ratioForUpperLeftPart, relative); } void PartSashContainer::Add(LayoutPart::Pointer child, int relationship, float ratio, LayoutPart::Pointer relative) { bool isHorizontal = (relationship == IPageLayout::LEFT || relationship == IPageLayout::RIGHT); LayoutTree::Pointer node; if (root != 0 && relative != 0) { node = root->Find(relative); } Rectangle bounds; if (this->GetParent() == 0) { void* control = this->GetPage()->GetClientComposite(); if (control != 0) { bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(control); } else { bounds = Rectangle(0, 0, 800, 600); } bounds.x = 0; bounds.y = 0; } else { bounds = this->GetBounds(); } int totalSize = this->MeasureTree(bounds, node, isHorizontal); int left = (int) (totalSize * ratio); int right = totalSize - left; this->Add(child, relationship, left, right, relative); } int PartSashContainer::MeasureTree(const Rectangle& outerBounds, LayoutTree::ConstPointer toMeasure, bool horizontal) { if (toMeasure == 0) { return outerBounds.GetDimension(horizontal); } LayoutTreeNode* parent = toMeasure->GetParent(); if (parent == 0) { return outerBounds.GetDimension(horizontal); } if (parent->GetSash()->IsHorizontal() == horizontal) { return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal); } bool isLeft = parent->IsLeftChild(toMeasure); LayoutTree::Pointer otherChild = parent->GetChild(!isLeft); if (otherChild->IsVisible()) { int left = parent->GetSash()->GetLeft(); int right = parent->GetSash()->GetRight(); int childSize = isLeft ? left : right; int bias = parent->GetCompressionBias(); // Normalize bias: 1 = we're fixed, -1 = other child is fixed if (isLeft) { bias = -bias; } if (bias == 1) { // If we're fixed, return the fixed size return childSize; } else if (bias == -1) { // If the other child is fixed, return the size of the parent minus the fixed size of the // other child return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal) - (left + right - childSize); } // Else return the size of the parent, scaled appropriately return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal) * childSize / (left + right); } return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal); } void PartSashContainer::AddChild(const RelationshipInfo& info) { LayoutPart::Pointer child = info.part; children.push_back(child); if (root == 0) { root = new LayoutTree(child); } else { //Add the part to the tree. int vertical = (info.relationship == IPageLayout::LEFT || info.relationship == IPageLayout::RIGHT) ? Constants::VERTICAL : Constants::HORIZONTAL; bool left = info.relationship == IPageLayout::LEFT || info.relationship == IPageLayout::TOP; LayoutPartSash::Pointer sash(new LayoutPartSash(this, vertical)); sash->SetSizes(info.left, info.right); if ((parent != 0) && child.Cast ().IsNull()) { sash->CreateControl(parent); } LayoutTree::Pointer newroot = root->Insert(child, left, sash, info.relative); root = newroot; } this->ChildAdded(child); if (active) { child->CreateControl(parent); child->SetVisible(true); child->SetContainer(ILayoutContainer::Pointer(this)); this->ResizeChild(child); } } void PartSashContainer::AddChildForPlaceholder(LayoutPart::Pointer child, LayoutPart::Pointer placeholder) { RelationshipInfo newRelationshipInfo; newRelationshipInfo.part = child; if (root != 0) { newRelationshipInfo.relationship = IPageLayout::RIGHT; newRelationshipInfo.relative = root->FindBottomRight(); newRelationshipInfo.left = 200; newRelationshipInfo.right = 200; } // find the relationship info for the placeholder QList relationships = this->ComputeRelation(); - for (unsigned int i = 0; i < relationships.size(); i++) + for (int i = 0; i < relationships.size(); i++) { RelationshipInfo info = relationships[i]; if (info.part == placeholder) { newRelationshipInfo.left = info.left; newRelationshipInfo.right = info.right; newRelationshipInfo.relationship = info.relationship; newRelationshipInfo.relative = info.relative; } } this->AddChild(newRelationshipInfo); this->FlushLayout(); } bool PartSashContainer::AllowsBorder() { return true; } void PartSashContainer::ChildAdded(LayoutPart::Pointer child) { if (this->IsDeferred()) { child->DeferUpdates(true); } } void PartSashContainer::ChildRemoved(LayoutPart::Pointer child) { if (this->IsDeferred()) { child->DeferUpdates(false); } } QList PartSashContainer::ComputeRelation() { LayoutTree::Pointer treeRoot = root; QList list; if (treeRoot == 0) { return QList(); } RelationshipInfo r; r.part = treeRoot->ComputeRelation(list); list.push_front(r); return list; } void PartSashContainer::SetActive(bool isActive) { if (isActive == active) { return; } active = isActive; ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { if (childIter->Cast ().IsNotNull()) { PartStack::Pointer stack = childIter->Cast (); stack->SetActive(isActive); } } if (isActive) { this->CreateControl(parentWidget); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(parent, resizeListener); - DragUtil::AddDragTarget(parent, IDragOverListener::Pointer(this)); - DragUtil::AddDragTarget(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parent)->GetControl(), IDragOverListener::Pointer(this)); + DragUtil::AddDragTarget(parent, this); + DragUtil::AddDragTarget(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parent)->GetControl(), this); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { LayoutPart::Pointer child = *childIter; child->SetContainer(ILayoutContainer::Pointer(this)); child->SetVisible(true); //zoomedPart == null || child == zoomedPart); if (child.Cast ().IsNull()) { if (root != 0) { LayoutTree::Pointer node = root->Find(child); if (node != 0) { node->FlushCache(); } } } } if (root != 0) { //root.flushChildren(); //if (!isZoomed()) { root->CreateControl(parent); } } this->ResizeSashes(); } else { - DragUtil::RemoveDragTarget(parent, IDragOverListener::Pointer(this)); - DragUtil::RemoveDragTarget(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parent)->GetControl(), IDragOverListener::Pointer(this)); + DragUtil::RemoveDragTarget(parent, this); + DragUtil::RemoveDragTarget(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parent)->GetControl(), this); // remove all Listeners if (resizeListener != 0 && parent != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(parent, resizeListener); } for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { LayoutPart::Pointer child = *iter; child->SetContainer(ILayoutContainer::Pointer(0)); if (child.Cast ().IsNotNull()) { child->SetVisible(false); } } this->DisposeSashes(); //dispose(); } } void PartSashContainer::CreateControl(void* parentWidget) { if (this->parent != 0) { return; } parent = this->CreateParent(parentWidget); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { (*childIter)->CreateControl(parent); } } void PartSashContainer::Dispose() { if (parent == 0) { return; } for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { // In PartSashContainer dispose really means deactivate, so we // only dispose PartTabFolders. if (iter->Cast() != 0) { (*iter)->Dispose(); } } this->DisposeParent(); this->parent = 0; } void PartSashContainer::DisposeSashes() { if (root != 0) { root->DisposeSashes(); } } void PartSashContainer::SetVisible(bool makeVisible) { if (makeVisible == this->GetVisible()) { return; } //if (!SwtUtil.isDisposed(this.parent)) //{ Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(this->parent, makeVisible); //} LayoutPart::SetVisible(makeVisible); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { (*childIter)->SetVisible(makeVisible); // && (zoomedPart == null || child == zoomedPart)); } } LayoutPart::Pointer PartSashContainer::FindBottomRight() { if (root == 0) { return LayoutPart::Pointer(0); } return root->FindBottomRight(); } Rectangle PartSashContainer::GetBounds() { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->parent); } ILayoutContainer::ChildrenType PartSashContainer::GetChildren() const { return children; } void* PartSashContainer::GetControl() { return this->parent; } LayoutTree::Pointer PartSashContainer::GetLayoutTree() { return root; } WorkbenchPage::Pointer PartSashContainer::GetPage() { return WorkbenchPage::Pointer(page); } void* PartSashContainer::GetParent() { return parent; } bool PartSashContainer::IsChild(LayoutPart::Pointer part) { return std::find(children.begin(), children.end(), part) != children.end(); } void PartSashContainer::ResizeChild(LayoutPart::Pointer childThatChanged) { if (root != 0) { LayoutTree::Pointer tree = root->Find(childThatChanged); if (tree != 0) { tree->FlushCache(); } } this->FlushLayout(); } void PartSashContainer::Remove(LayoutPart::Pointer child) { // if (child == getZoomedPart()) // { // childRequestZoomOut(); // } if (!this->IsChild(child)) { return; } children.removeAll(child); if (root != 0) { root = root->Remove(child); } this->ChildRemoved(child); if (active) { child->SetVisible(false); child->SetContainer(ILayoutContainer::Pointer(0)); this->FlushLayout(); } } void PartSashContainer::FlushLayout() { layoutDirty = true; LayoutPart::FlushLayout(); if (layoutDirty) { this->ResizeSashes(); } } void PartSashContainer::Replace(LayoutPart::Pointer oldChild, LayoutPart::Pointer newChild) { if (!this->IsChild(oldChild)) { return; } // if (oldChild == getZoomedPart()) // { // if (newChild.Cast ().IsNotNull()) // { // childRequestZoomOut(); // } // else // { // zoomedPart.setZoomed(false); // zoomedPart = newChild; // zoomedPart.setZoomed(true); // } // } children.erase(std::find(children.begin(), children.end(), oldChild)); children.push_back(newChild); this->ChildAdded(newChild); if (root != 0) { LayoutTree::Pointer leaf; leaf = root->Find(oldChild); if (leaf != 0) { leaf->SetPart(newChild); } } this->ChildRemoved(oldChild); if (active) { oldChild->SetVisible(false); oldChild->SetContainer(ILayoutContainer::Pointer(0)); newChild->CreateControl(parent); newChild->SetContainer(ILayoutContainer::Pointer(this)); newChild->SetVisible(true); //zoomedPart == null || zoomedPart == newChild); this->ResizeChild(newChild); } } void PartSashContainer::ResizeSashes() { layoutDirty = false; if (!active) { return; } // if (isZoomed()) // { // getZoomedPart().setBounds(parent.getClientArea()); // } // else { if (root != 0) { root->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea( parent)); } } } int PartSashContainer::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { // if (isZoomed()) // { // return getZoomedPart().computePreferredSize(width, availableParallel, // availablePerpendicular, preferredParallel); // } if (root != 0) { return root->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } return preferredParallel; } int PartSashContainer::GetSizeFlags(bool width) { // if (isZoomed()) // { // return getZoomedPart().getSizeFlags(width); // } if (root != 0) { return root->GetSizeFlags(width); } return 0; } void PartSashContainer::SetBounds(const Rectangle& r) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(this->parent, r); } IDropTarget::Pointer PartSashContainer::Drag(void* /*currentControl*/, - Object::Pointer draggedObject, const Point& position, + const Object::Pointer& draggedObject, const Point& position, const Rectangle& /*dragRectangle*/) { if (!(draggedObject.Cast () != 0 || draggedObject.Cast () != 0)) { return IDropTarget::Pointer(0); } PartPane::Pointer sourcePart = draggedObject.Cast (); PartStack::Pointer sourceContainer = draggedObject.Cast (); if (sourceContainer == 0) { sourceContainer = sourcePart->GetStack(); } if (!this->IsStackType(sourceContainer) && !this->IsPaneType(sourcePart)) { return IDropTarget::Pointer(0); } IWorkbenchWindow::Pointer window = sourcePart ? sourcePart->GetWorkbenchWindow() : sourceContainer->GetWorkbenchWindow(); bool differentWindows = window != this->GetWorkbenchWindow(); bool editorDropOK = ((sourceContainer->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) && window->GetWorkbench() == this->GetWorkbenchWindow()->GetWorkbench()); if (differentWindows && !editorDropOK) { return IDropTarget::Pointer(0); } Rectangle containerBounds = DragUtil::GetDisplayBounds(parent); LayoutPart::Pointer targetPart; // If this container has no visible children if (this->GetVisibleChildrenCount(ILayoutContainer::Pointer(this)) == 0) { return this->CreateDropTarget(draggedObject, Constants::CENTER, Constants::CENTER, Object::Pointer(0)); } if (containerBounds.Contains(position)) { if (root != 0) { targetPart = root->FindPart( Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl(parent, position)); } if (targetPart != 0) { void* targetControl = targetPart->GetControl(); Rectangle targetBounds = DragUtil::GetDisplayBounds(targetControl); int side = Geometry::GetClosestSide(targetBounds, position); int distance = Geometry::GetDistanceFromEdge(targetBounds, position, side); // is the source coming from a standalone part bool standalone = (this->IsStackType(sourceContainer) && sourceContainer->IsStandalone()) || (this->IsPaneType(sourcePart) && sourcePart->GetStack()->IsStandalone()); // Only allow dropping onto an existing stack from different windows if (differentWindows && targetPart.Cast () != 0 && targetPart.Cast ()->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) { IDropTarget::Pointer target = targetPart->GetDropTarget(draggedObject, position); return target; } // Reserve the 5 pixels around the edge of the part for the drop-on-edge cursor if (distance >= 5 && !standalone) { // Otherwise, ask the part if it has any special meaning for this drop location IDropTarget::Pointer target = targetPart->GetDropTarget(draggedObject, position); if (target != 0) { return target; } } if (distance > 30 && this->IsStackType(targetPart.Cast ()) && !standalone) { PartStack::Pointer targetContainer = targetPart.Cast (); if (targetContainer->AllowsAdd(sourcePart)) { side = Constants::CENTER; } } // If the part doesn't want to override this drop location then drop on the edge // A "pointless drop" would be one that will put the dragged object back where it started. // Note that it should be perfectly valid to drag an object back to where it came from -- however, // the drop should be ignored. bool pointlessDrop = false; // = isZoomed(); if (!sourcePart && sourceContainer == targetPart) { pointlessDrop = true; } if ((sourceContainer != 0) && (sourceContainer == targetPart) && this->GetVisibleChildrenCount(sourceContainer.Cast()) <= 1) { pointlessDrop = true; } if (side == Constants::CENTER && sourceContainer == targetPart) { pointlessDrop = true; } int cursor = side; if (pointlessDrop) { side = Constants::NONE; cursor = Constants::CENTER; } if (sourcePart) return this->CreateDropTarget(sourcePart, side, cursor, targetPart); else return this->CreateDropTarget(sourceContainer, side, cursor, targetPart); } } else { // We only allow dropping into a stack, not creating one if (differentWindows) return IDropTarget::Pointer(0); int side = Geometry::GetClosestSide(containerBounds, position); bool pointlessDrop = false; // = isZoomed(); if (/*(this->IsStackType(sourceContainer) && sourceContainer == this) ||*/ (this->IsPaneType(sourcePart) && this->GetVisibleChildrenCount( sourceContainer.Cast()) <= 1) && sourceContainer->GetContainer() == this) { if (root == 0 || this->GetVisibleChildrenCount(ILayoutContainer::Pointer(this)) <= 1) { pointlessDrop = true; } } int cursor = Geometry::GetOppositeSide(side); if (pointlessDrop) { side = Constants::NONE; } if (sourcePart) return this->CreateDropTarget(sourcePart, side, cursor, Object::Pointer(0)); else return this->CreateDropTarget(sourceContainer, side, cursor, Object::Pointer(0)); } return IDropTarget::Pointer(0); } PartSashContainer::SashContainerDropTarget::Pointer PartSashContainer::CreateDropTarget( Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) { if (dropTarget == 0) { dropTarget = new SashContainerDropTarget(this, sourcePart, side, cursor, targetPart); } else { dropTarget->SetTarget(sourcePart, side, cursor, targetPart); } return dropTarget; } void PartSashContainer::Stack(LayoutPart::Pointer newPart, ILayoutContainer::Pointer container) { //this->GetControl().setRedraw(false); // Only deref the part if it is being referenced in -this- perspective Perspective::Pointer persp = page->GetActivePerspective(); PerspectiveHelper* pres = (persp != 0) ? persp->GetPresentation() : 0; if (pres != 0 && container.Cast()->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) { IWorkbenchPartReference::Pointer newPartRef = newPart.Cast ()->GetPartReference(); IViewReference::Pointer vRef = newPartRef.Cast (); if (vRef != 0) { LayoutPart::Pointer fpp = pres->FindPart(vRef->GetId(), vRef->GetSecondaryId()); if (fpp != 0) { // Remove the part from old container. this->DerefPart(newPart); } } } else { // Remove the part from old container. this->DerefPart(newPart); } // Reparent part and add it to the workbook newPart->Reparent(this->GetParent()); container->Add(newPart); //getControl().setRedraw(true); } void PartSashContainer::DerefPart(LayoutPart::Pointer sourcePart) { ILayoutContainer::Pointer container = sourcePart->GetContainer(); if (container != 0) { container->Remove(sourcePart); if (this->IsStackType(container) && container.Cast () != 0) { if (container->GetChildren().size() == 0) { LayoutPart::Pointer stack = container.Cast (); this->Remove(stack); stack->Dispose(); } } } } std::size_t PartSashContainer::GetVisibleChildrenCount( ILayoutContainer::Pointer container) { // Treat null as an empty container if (container == 0) { return 0; } ILayoutContainer::ChildrenType children = container->GetChildren(); std::size_t count = 0; for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if (!(*iter)->IsPlaceHolder()) { count++; } } return count; } float PartSashContainer::GetDockingRatio(Object::Pointer /*dragged*/, ILayoutContainer::Pointer /*target*/) { return 0.5f; } void PartSashContainer::DescribeLayout(QString& buf) const { if (root == 0) { return; } // if (isZoomed()) // { // buf.append("zoomed "); //$NON-NLS-1$ // root.describeLayout(buf); // } // else { buf.append("layout "); //$NON-NLS-1$ root->DescribeLayout(buf); } } void PartSashContainer::Add(LayoutPart::Pointer child, int relationship, int left, int right, LayoutPart::Pointer relative) { if (child == 0) { return; } if (relative != 0 && !this->IsChild(relative)) { return; } if (relationship < IPageLayout::LEFT || relationship > IPageLayout::BOTTOM) { relationship = IPageLayout::LEFT; } // store info about relative positions RelationshipInfo info; info.part = child; info.relationship = relationship; info.left = left; info.right = right; info.relative = relative; this->AddChild(info); } bool PartSashContainer::AllowsAutoFocus() { return true; } void PartSashContainer::StartDeferringEvents() { LayoutPart::StartDeferringEvents(); ILayoutContainer::ChildrenType deferredChildren = children; for (ILayoutContainer::ChildrenType::iterator iter = deferredChildren.begin(); iter != deferredChildren.end(); ++iter) { (*iter)->DeferUpdates(true); } } void PartSashContainer::HandleDeferredEvents() { LayoutPart::HandleDeferredEvents(); ILayoutContainer::ChildrenType deferredChildren = children; for (ILayoutContainer::ChildrenType::iterator iter = deferredChildren.begin(); iter != deferredChildren.end(); ++iter) { (*iter)->DeferUpdates(false); } } void PartSashContainer::TestInvariants() { LayoutPart::TestInvariants(); // If we have a parent container, ensure that we are displaying the zoomed appearance iff // our parent is zoomed in on us // if (this->GetContainer() != 0) // { // Assert.isTrue((getZoomedPart() != null) == (getContainer().childIsZoomed( // this))); // } ILayoutContainer::ChildrenType childArray = this->GetChildren(); for (ILayoutContainer::ChildrenType::iterator iter = childArray.begin(); iter != childArray.end(); ++iter) { (*iter)->TestInvariants(); } // If we're zoomed, ensure that we're actually zoomed into one of our children // if (isZoomed()) // { // Assert.isTrue(children.contains(zoomedPart)); // } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.h index 8988a1b8bf..54bf71059c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSashContainer.h @@ -1,702 +1,702 @@ /*=================================================================== 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 BERRYPARTSASHCONTAINER_H_ #define BERRYPARTSASHCONTAINER_H_ #include "berryLayoutPart.h" #include "berryILayoutContainer.h" #include "berryILayoutContainer.h" #include "berryIDragOverListener.h" #include "berryAbstractDropTarget.h" #include "tweaklets/berryDnDTweaklet.h" #include "berryRectangle.h" #include "guitk/berryGuiTkIControlListener.h" namespace berry { class WorkbenchPage; class PartPane; class LayoutTree; class PartStack; /** * \ingroup org_blueberry_ui_internal * * Abstract container that groups various layout * parts (possibly other containers) together as * a unit. Manages the placement and size of these * layout parts based on the location of sashes within * the container. * * GUI specializations must override the following methods * (read their documentation for implementation details): * *