diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommand.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommand.cpp index c1bfc88bd3..0517b35522 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommand.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommand.cpp @@ -1,559 +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 = true; +bool Command::DEBUG_COMMAND_EXECUTION = false; -bool Command::DEBUG_HANDLERS = true; +bool Command::DEBUG_HANDLERS = false; -QString Command::DEBUG_HANDLERS_COMMAND_ID = ""; +QString Command::DEBUG_HANDLERS_COMMAND_ID = QString::null; 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) { 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.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 (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(const Object::Pointer& 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 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; } IHandlerListener* Command::GetHandlerListener() { return this; } 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 (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 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 (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/berryCommandEvent.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandEvent.cpp index de06fab9aa..5b6396da1b 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandEvent.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandEvent.cpp @@ -1,110 +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 "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; +int CommandEvent::CHANGED_CATEGORY() { static int i = CommandEvent::LAST_USED_BIT() << 1; return i; } +int CommandEvent::CHANGED_HANDLED() { static int i = CommandEvent::LAST_USED_BIT() << 2; return i; } +int CommandEvent::CHANGED_PARAMETERS() { static int i = CommandEvent::LAST_USED_BIT() << 3; return i; } +int CommandEvent::CHANGED_RETURN_TYPE() { static int i = CommandEvent::LAST_USED_BIT() << 4; return i; } +int CommandEvent::CHANGED_HELP_CONTEXT_ID() { static int i = CommandEvent::LAST_USED_BIT() << 5; return i; } +int CommandEvent::CHANGED_ENABLED() { static int i = CommandEvent::LAST_USED_BIT() << 6; return i; } 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; + changedValues |= CHANGED_CATEGORY(); } if (handledChanged) { - changedValues |= CHANGED_HANDLED; + changedValues |= CHANGED_HANDLED(); } if (parametersChanged) { - changedValues |= CHANGED_PARAMETERS; + changedValues |= CHANGED_PARAMETERS(); } if (returnTypeChanged) { - changedValues |= CHANGED_RETURN_TYPE; + changedValues |= CHANGED_RETURN_TYPE(); } if (helpContextIdChanged) { - changedValues |= CHANGED_HELP_CONTEXT_ID; + changedValues |= CHANGED_HELP_CONTEXT_ID(); } if (enabledChanged) { - changedValues |= CHANGED_ENABLED; + changedValues |= CHANGED_ENABLED(); } } Command::Pointer CommandEvent::GetCommand() const { return command; } bool CommandEvent::IsCategoryChanged() const { - return ((changedValues & CHANGED_CATEGORY) != 0); + return ((changedValues & CHANGED_CATEGORY()) != 0); } bool CommandEvent::IsHandledChanged() const { - return ((changedValues & CHANGED_HANDLED) != 0); + return ((changedValues & CHANGED_HANDLED()) != 0); } bool CommandEvent::IsHelpContextIdChanged() const { - return ((changedValues & CHANGED_HELP_CONTEXT_ID) != 0); + return ((changedValues & CHANGED_HELP_CONTEXT_ID()) != 0); } bool CommandEvent::IsParametersChanged() const { - return ((changedValues & CHANGED_PARAMETERS) != 0); + return ((changedValues & CHANGED_PARAMETERS()) != 0); } bool CommandEvent::IsReturnTypeChanged() const { - return ((changedValues & CHANGED_RETURN_TYPE) != 0); + return ((changedValues & CHANGED_RETURN_TYPE()) != 0); } bool CommandEvent::IsEnabledChanged() const { - return ((changedValues & CHANGED_ENABLED) != 0); + return ((changedValues & CHANGED_ENABLED()) != 0); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandEvent.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandEvent.h index 8fa8427613..938adce34f 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandEvent.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryCommandEvent.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 BERRYCOMMANDEVENT_H_ #define BERRYCOMMANDEVENT_H_ #include "common/berryAbstractNamedHandleEvent.h" #include namespace berry { class Command; /** * An instance of this class describes changes to an instance of * Command. *

* This class is not intended to be extended by clients. *

* * @see ICommandListener#CommandChanged(CommandEvent::Pointer) */ class BERRY_COMMANDS CommandEvent : public AbstractNamedHandleEvent { public: berryObjectMacro(CommandEvent); /** * Creates a new instance of this class. * * @param command * the instance of the interface that changed. * @param categoryChanged * true, iff the category property changed. * @param definedChanged * true, iff the defined property changed. * @param descriptionChanged * true, iff the description property changed. * @param handledChanged * true, iff the handled property changed. * @param nameChanged * true, iff the name property changed. * @param parametersChanged * true if the parameters have changed; * false otherwise. * @param returnTypeChanged * true iff the return type property changed; * false otherwise. * @param helpContextIdChanged * true iff the help context identifier changed; * false otherwise. * @param enabledChanged * true iff the comand enablement changed; * false otherwise. * @since 3.3 */ CommandEvent(const SmartPointer command, bool categoryChanged, bool definedChanged, bool descriptionChanged, bool handledChanged, bool nameChanged, bool parametersChanged, bool returnTypeChanged = false, bool helpContextIdChanged = false, bool enabledChanged = false); /** * Returns the instance of the interface that changed. * * @return the instance of the interface that changed. Guaranteed not to be * null. */ SmartPointer GetCommand() const; /** * Returns whether or not the category property changed. * * @return true, iff the category property changed. */ bool IsCategoryChanged() const; /** * Returns whether or not the handled property changed. * * @return true, iff the handled property changed. */ bool IsHandledChanged() const; /** * Returns whether or not the help context identifier changed. * * @return true, iff the help context identifier changed. * @since 3.2 */ bool IsHelpContextIdChanged() const; /** * Returns whether or not the parameters have changed. * * @return true, iff the parameters property changed. */ bool IsParametersChanged() const; /** * Returns whether or not the return type property changed. * * @return true, iff the return type property changed. * @since 3.2 */ bool IsReturnTypeChanged() const; /** * Return whether the enable property changed. * * @return true iff the comand enablement changed * @since 3.3 */ bool IsEnabledChanged() const; private: /** * The bit used to represent whether the command has changed its category. */ - static const int CHANGED_CATEGORY; // = LAST_USED_BIT << 1; + static int CHANGED_CATEGORY(); // = LAST_USED_BIT << 1; /** * The bit used to represent whether the command has changed its handler. */ - static const int CHANGED_HANDLED; // = LAST_USED_BIT << 2; + static int CHANGED_HANDLED(); // = LAST_USED_BIT << 2; /** * The bit used to represent whether the command has changed its parameters. */ - static const int CHANGED_PARAMETERS; // = LAST_USED_BIT << 3; + static int CHANGED_PARAMETERS(); // = LAST_USED_BIT << 3; /** * The bit used to represent whether the command has changed its return * type. * * @since 3.2 */ - static const int CHANGED_RETURN_TYPE; // = LAST_USED_BIT << 4; + static int CHANGED_RETURN_TYPE(); // = LAST_USED_BIT << 4; /** * The bit used to represent whether the command has changed its help * context identifier. * * @since 3.2 */ - static const int CHANGED_HELP_CONTEXT_ID; // = LAST_USED_BIT << 5; + static int CHANGED_HELP_CONTEXT_ID(); // = LAST_USED_BIT << 5; /** * The bit used to represent whether this commands active handler has * changed its enablement state. * * @since 3.3 */ - static const int CHANGED_ENABLED; // = LAST_USED_BIT << 6; + static int CHANGED_ENABLED(); // = LAST_USED_BIT << 6; /** * The command that has changed; this value is never null. */ const SmartPointer command; }; } #endif /* BERRYCOMMANDEVENT_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValues.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValues.h index 56c70b1f0a..9ca0067964 100644 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValues.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryIParameterValues.h @@ -1,53 +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 BERRYIPARAMETERVALUES_H #define BERRYIPARAMETERVALUES_H #include "berryObject.h" +#include + #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 +struct BERRY_COMMANDS 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/berryParameterizedCommand.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterizedCommand.cpp index c18f6df375..5b8928b3a5 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterizedCommand.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/berryParameterizedCommand.cpp @@ -1,449 +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. ===================================================================*/ #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 (int j = 0; j < parameters.size(); j++) { 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::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*/) { /* * 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 (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 (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 (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())); + QString val = i.value()->ToString(); parms.push_back(Parameterization(parameter, val)); } else { IParameterValueConverter* valueConverter(parameterType->GetValueConverter()); if (valueConverter) { QString val(valueConverter->ConvertToString(i.value())); parms.push_back(Parameterization(parameter, val)); } else { - QString val(*(i.value().Cast())); + QString val = i.value()->ToString(); 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 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()); } 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/common/berryAbstractHandleObjectEvent.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractHandleObjectEvent.cpp index 3d0e0210e3..c85c3f269f 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractHandleObjectEvent.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractHandleObjectEvent.cpp @@ -1,39 +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. ===================================================================*/ #include "berryAbstractHandleObjectEvent.h" namespace berry { -const int AbstractHandleObjectEvent::CHANGED_DEFINED = 1; -const int AbstractHandleObjectEvent::LAST_BIT_USED_ABSTRACT_HANDLE = - AbstractHandleObjectEvent::CHANGED_DEFINED; +int AbstractHandleObjectEvent::CHANGED_DEFINED() { static int i = 1; return i; } +int AbstractHandleObjectEvent::LAST_BIT_USED_ABSTRACT_HANDLE() { return CHANGED_DEFINED(); } AbstractHandleObjectEvent::AbstractHandleObjectEvent(bool definedChanged) { if (definedChanged) { - changedValues |= CHANGED_DEFINED; + changedValues |= CHANGED_DEFINED(); } } bool AbstractHandleObjectEvent::IsDefinedChanged() const { - return ((changedValues & CHANGED_DEFINED) != 0); + return ((changedValues & CHANGED_DEFINED()) != 0); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractHandleObjectEvent.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractHandleObjectEvent.h index 16eb72b19e..d962a79e91 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractHandleObjectEvent.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractHandleObjectEvent.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 BERRYABSTRACTHANDLEOBJECTEVENT_H_ #define BERRYABSTRACTHANDLEOBJECTEVENT_H_ #include "berryAbstractBitSetEvent.h" namespace berry { /** *

* An event fired from a NamedHandleObject. This provides * notification of changes to the defined state, the name and the description. *

* * @since 3.2 */ class BERRY_COMMANDS AbstractHandleObjectEvent : public AbstractBitSetEvent { public: berryObjectMacro(AbstractHandleObjectEvent); /** * Returns whether or not the defined property changed. * * @return true, iff the defined property changed. */ bool IsDefinedChanged() const; protected: /** * The bit used to represent whether the category has changed its defined * state. */ - static const int CHANGED_DEFINED; // = 1; + static int CHANGED_DEFINED(); // = 1; /** * The last used bit so that subclasses can add more properties. */ - static const int LAST_BIT_USED_ABSTRACT_HANDLE; // = CHANGED_DEFINED; + static int LAST_BIT_USED_ABSTRACT_HANDLE(); // = CHANGED_DEFINED; /** * Constructs a new instance of AbstractHandleObjectEvent. * * @param definedChanged * true, iff the defined property changed. */ AbstractHandleObjectEvent(bool definedChanged); }; } #endif /* BERRYABSTRACTHANDLEOBJECTEVENT_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractNamedHandleEvent.cpp b/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractNamedHandleEvent.cpp index 266ab314a4..b6d8c7e9cb 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractNamedHandleEvent.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractNamedHandleEvent.cpp @@ -1,51 +1,51 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryAbstractNamedHandleEvent.h" namespace berry { -const int AbstractNamedHandleEvent::CHANGED_DESCRIPTION = AbstractNamedHandleEvent::LAST_BIT_USED_ABSTRACT_HANDLE << 1; -const int AbstractNamedHandleEvent::CHANGED_NAME = AbstractNamedHandleEvent::LAST_BIT_USED_ABSTRACT_HANDLE << 2; -const int AbstractNamedHandleEvent::LAST_USED_BIT = AbstractNamedHandleEvent::CHANGED_NAME; +int AbstractNamedHandleEvent::CHANGED_DESCRIPTION() { static int i = AbstractNamedHandleEvent::LAST_BIT_USED_ABSTRACT_HANDLE() << 1; return i; } +int AbstractNamedHandleEvent::CHANGED_NAME() { static int i = AbstractNamedHandleEvent::LAST_BIT_USED_ABSTRACT_HANDLE() << 2; return i; } +int AbstractNamedHandleEvent::LAST_USED_BIT() { static int i = AbstractNamedHandleEvent::CHANGED_NAME(); return i; } bool AbstractNamedHandleEvent::IsDescriptionChanged() const { - return ((changedValues & CHANGED_DESCRIPTION) != 0); + return ((changedValues & CHANGED_DESCRIPTION()) != 0); } bool AbstractNamedHandleEvent::IsNameChanged() const { - return ((changedValues & CHANGED_NAME) != 0); + return ((changedValues & CHANGED_NAME()) != 0); } AbstractNamedHandleEvent::AbstractNamedHandleEvent(bool definedChanged, bool descriptionChanged, bool nameChanged) : AbstractHandleObjectEvent(definedChanged) { if (descriptionChanged) { - changedValues |= CHANGED_DESCRIPTION; + changedValues |= CHANGED_DESCRIPTION(); } if (nameChanged) { - changedValues |= CHANGED_NAME; + changedValues |= CHANGED_NAME(); } } } diff --git a/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractNamedHandleEvent.h b/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractNamedHandleEvent.h index 45136e9200..3231de1f9a 100755 --- a/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractNamedHandleEvent.h +++ b/BlueBerry/Bundles/org.blueberry.core.commands/src/common/berryAbstractNamedHandleEvent.h @@ -1,87 +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 BERRYABSTRACTNAMEDHANDLEEVENT_H_ #define BERRYABSTRACTNAMEDHANDLEEVENT_H_ #include "berryAbstractHandleObjectEvent.h" namespace berry { /** *

* An event fired from a NamedHandleObject. This provides * notification of changes to the defined state, the name and the description. *

* */ class BERRY_COMMANDS AbstractNamedHandleEvent : public AbstractHandleObjectEvent { public: berryObjectMacro(AbstractNamedHandleEvent); /** * Returns whether or not the description property changed. * * @return true, iff the description property changed. */ bool IsDescriptionChanged() const; /** * Returns whether or not the name property changed. * * @return true, iff the name property changed. */ bool IsNameChanged() const; protected: /** * The bit used to represent whether the category has changed its * description. */ - static const int CHANGED_DESCRIPTION; // = LAST_BIT_USED_ABSTRACT_HANDLE << 1; + static int CHANGED_DESCRIPTION(); // = LAST_BIT_USED_ABSTRACT_HANDLE << 1; /** * The bit used to represent whether the category has changed its name. */ - static const int CHANGED_NAME; // = LAST_BIT_USED_ABSTRACT_HANDLE << 2; + static int CHANGED_NAME(); // = LAST_BIT_USED_ABSTRACT_HANDLE << 2; /** * The last used bit so that subclasses can add more properties. */ - static const int LAST_USED_BIT; // = CHANGED_NAME; + static int LAST_USED_BIT(); // = CHANGED_NAME; /** * Constructs a new instance of AbstractHandleObjectEvent. * * @param definedChanged * true, iff the defined property changed. * @param descriptionChanged * true, iff the description property changed. * @param nameChanged * true, iff the name property changed. */ AbstractNamedHandleEvent(bool definedChanged, bool descriptionChanged, bool nameChanged); }; } #endif /* BERRYABSTRACTNAMEDHANDLEEVENT_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/files.cmake b/BlueBerry/Bundles/org.blueberry.core.expressions/files.cmake index a38c51dd5b..8d410d5d88 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/files.cmake +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/files.cmake @@ -1,59 +1,63 @@ set(MOC_H_FILES + src/berryPropertyTester.h + + src/internal/berryPlatformPropertyTester.h src/internal/berryExpressionPlugin.h ) 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 + berryPlatformPropertyTester.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/plugin.xml b/BlueBerry/Bundles/org.blueberry.core.expressions/plugin.xml index 2bb386d815..a05b11cb6e 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/plugin.xml +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/plugin.xml @@ -1,7 +1,17 @@ + + + + + diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionInfo.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionInfo.cpp index 86eb8f468a..a32347958f 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionInfo.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionInfo.cpp @@ -1,152 +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 "berryExpressionInfo.h" #include namespace berry { +ExpressionInfo::ExpressionInfo() + : fHasDefaultVariableAccess(false) + , fHasSystemPropertyAccess(false) +{ +} + bool ExpressionInfo::HasDefaultVariableAccess() const { return fHasDefaultVariableAccess; } void ExpressionInfo::MarkDefaultVariableAccessed() { fHasDefaultVariableAccess= true; } bool ExpressionInfo::HasSystemPropertyAccess() const { return fHasSystemPropertyAccess; } void ExpressionInfo::MarkSystemPropertyAccessed() { fHasSystemPropertyAccess= true; } QSet ExpressionInfo::GetAccessedVariableNames() const { return fAccessedVariableNames; } void ExpressionInfo::AddVariableNameAccess(const QString &name) { fAccessedVariableNames.insert(name); } QSet ExpressionInfo::GetAccessedPropertyNames() const { return fAccessedPropertyNames; } void ExpressionInfo::AddAccessedPropertyName(const QString &name) { fAccessedPropertyNames.insert(name); } QSet ExpressionInfo::GetMisbehavingExpressionTypes() const { return fMisbehavingExpressionTypes; } void ExpressionInfo::AddMisBehavingExpressionType(const std::type_info& clazz) { fMisbehavingExpressionTypes.insert(QString(clazz.name())); } void ExpressionInfo::Merge(ExpressionInfo* other) { this->MergeDefaultVariableAccess(other); this->MergeSystemPropertyAccess(other); this->MergeAccessedVariableNames(other); this->MergeAccessedPropertyNames(other); this->MergeMisbehavingExpressionTypes(other); } void ExpressionInfo::MergeExceptDefaultVariable(ExpressionInfo* other) { this->MergeSystemPropertyAccess(other); this->MergeAccessedVariableNames(other); this->MergeAccessedPropertyNames(other); this->MergeMisbehavingExpressionTypes(other); } void ExpressionInfo::MergeDefaultVariableAccess(ExpressionInfo* other) { fHasDefaultVariableAccess= fHasDefaultVariableAccess || other->fHasDefaultVariableAccess; } void ExpressionInfo::MergeSystemPropertyAccess(ExpressionInfo* other) { fHasSystemPropertyAccess= fHasSystemPropertyAccess || other->fHasSystemPropertyAccess; } void ExpressionInfo::MergeAccessedVariableNames(ExpressionInfo* other) { if (fAccessedVariableNames.size() == 0) { fAccessedVariableNames= other->fAccessedVariableNames; } else { fAccessedVariableNames.unite(other->fAccessedVariableNames); } } void ExpressionInfo::MergeAccessedPropertyNames(ExpressionInfo* other) { if (fAccessedPropertyNames.size() == 0) { fAccessedPropertyNames = other->fAccessedPropertyNames; } else { fAccessedPropertyNames.unite(other->fAccessedPropertyNames); } } void ExpressionInfo::MergeMisbehavingExpressionTypes(ExpressionInfo* other) { if (fMisbehavingExpressionTypes.size() == 0) { fMisbehavingExpressionTypes= other->fMisbehavingExpressionTypes; } else { fMisbehavingExpressionTypes.unite(other->fMisbehavingExpressionTypes); } } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionInfo.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionInfo.h index 81c5157cfb..5d7ca7cc78 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionInfo.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryExpressionInfo.h @@ -1,187 +1,189 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYEXPRESSIONINFO_H_ #define BERRYEXPRESSIONINFO_H_ #include #include #include namespace berry { /** * A status object describing information about an expression tree. * This information can for example be used to decide whether a * expression tree as to be reevaluated if the value of some * variables changes. *

* This class is not intended to be extended by clients. *

* * @since 3.2 */ class BERRY_EXPRESSIONS ExpressionInfo { private: bool fHasDefaultVariableAccess; bool fHasSystemPropertyAccess; // Although we are using this as sets we use lists since // they are faster for smaller numbers of elements QSet fAccessedVariableNames; QSet fMisbehavingExpressionTypes; QSet fAccessedPropertyNames; public: + ExpressionInfo(); + /** * Returns true if the default variable is accessed * by the expression tree. * * @return whether the default variable is accessed or not */ bool HasDefaultVariableAccess() const; /** * Marks the default variable as accessed. */ void MarkDefaultVariableAccessed(); /** * Returns true if the system property is accessed * by the expression tree. * * @return whether the system property is accessed or not */ bool HasSystemPropertyAccess() const; /** * Marks the system property as accessed. */ void MarkSystemPropertyAccessed(); /** * Returns the set off accessed variables. * * @return the set off accessed variables */ QSet GetAccessedVariableNames() const; /** * Marks the given variable as accessed. * * @param name the accessed variable */ void AddVariableNameAccess(const QString& name); /** * Returns the set of accessed properties. * * @return the set of accessed properties, or an empty array */ QSet GetAccessedPropertyNames() const; /** * Marks that this expression access this property. It should be the fully * qualified property name. * * @param name * the fully qualified property name */ void AddAccessedPropertyName(const QString& name); /** * Returns the set of expression types which don't implement the * new (@link Expression#computeReevaluationInfo(IEvaluationContext)} * method. If one expression didn't implement the method the expression * tree no optimizations can be done. Returns null if * all expressions implement the method. * * @return the set of expression types which don't implement the * computeReevaluationInfo method. */ QSet GetMisbehavingExpressionTypes() const; /** * Adds the given class to the list of misbehaving classes. * * @param clazz the class to add. */ void AddMisBehavingExpressionType(const std::type_info& clazz); /** * Merges this reevaluation information with the given info. * * @param other the information to merge with */ void Merge(ExpressionInfo* other); /** * Merges this reevaluation information with the given info * ignoring the default variable access. * * @param other the information to merge with */ void MergeExceptDefaultVariable(ExpressionInfo* other); private: /** * Merges only the default variable access. * * @param other the information to merge with */ void MergeDefaultVariableAccess(ExpressionInfo* other); /** * Merges only the system property access. * * @param other the information to merge with */ void MergeSystemPropertyAccess(ExpressionInfo* other); /** * Merges only the accessed variable names. * * @param other the information to merge with */ void MergeAccessedVariableNames(ExpressionInfo* other); /** * Merges only the accessed property names. * * @param other the information to merge with * @since 3.4 */ void MergeAccessedPropertyNames(ExpressionInfo* other); /** * Merges only the misbehaving expression types. * * @param other the information to merge with */ void MergeMisbehavingExpressionTypes(ExpressionInfo* other); }; } // namespace berry #endif /*BERRYEXPRESSIONINFO_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryPropertyTester.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryPropertyTester.h index e838a721a9..fe018cd8c7 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryPropertyTester.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/berryPropertyTester.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 BERRYPROPERTYTESTER_H_ #define BERRYPROPERTYTESTER_H_ #include #include "internal/berryPropertyTesterDescriptor.h" #include namespace berry { /** * Abstract superclass of all property testers. Implementation classes of * the extension point org.blueberry.core.expresssions.propertyTesters * must extend PropertyTester. *

* A property tester implements the property tests enumerated in the property * tester extension point. For the following property test extension *

  *   <propertyTester
  *       namespace="org.blueberry.jdt.core"
  *       id="org.blueberry.jdt.core.IPackageFragmentTester"
  *       properties="isDefaultPackage"
  *       type="org.blueberry.jdt.core.IPackageFragment"
  *       class="org.blueberry.demo.MyPackageFragmentTester">
  *     </propertyTester>
  * 
* the corresponding implementation class looks like: *
  *   public class MyPackageFragmentTester {
  *       public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
  *           IPackageFragment fragement= (IPackageFragment)receiver;
  *           if ("isDefaultPackage".equals(property)) {
  *               return expectedValue == null
  *                ? fragement.isDefaultPackage()
  *                : fragement.isDefaultPackage() == ((Boolean)expectedValue).booleanValue();
  *           }
  *           Assert.isTrue(false);
  *           return false;
  *       }
  *   }
  * 
* The property can then be used in a test expression as follows: *
  *   <instanceof value="org.blueberry.core.IPackageFragment"/>
  *   <test property="org.blueberry.jdt.core.isDefaultPackage"/>
  * 
*

*

* There is no guarantee that the same instance of a property tester is used * to handle <test property="..."/> requests. So property testers * should always be implemented in a stateless fashion. *

- * @since 3.0 */ -class BERRY_EXPRESSIONS PropertyTester : public IPropertyTester +class BERRY_EXPRESSIONS PropertyTester : public QObject, public IPropertyTester { + Q_OBJECT + Q_INTERFACES(berry::IPropertyTester) private: IConfigurationElement::Pointer fConfigElement; QString fNamespace; QString fProperties; public: /** * Initialize the property tester with the given name space and property. *

* Note: this method is for internal use only. Clients must not call * this method. *

* @param descriptor the descriptor object for this tester */ void InternalInitialize(PropertyTesterDescriptor::Pointer descriptor); /** * Note: this method is for internal use only. Clients must not call * this method. * * @return the property tester descriptor */ PropertyTesterDescriptor::Pointer InternalCreateDescriptor(); /** * {@inheritDoc} */ bool Handles(const QString& namespaze, const QString& property); /** * {@inheritDoc} */ bool IsInstantiated(); /** * {@inheritDoc} */ bool IsDeclaringPluginActive(); /** * {@inheritDoc} */ IPropertyTester* Instantiate(); }; } // namespace berry #endif /*BERRYPROPERTYTESTER_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 b8a0266b37..dee8cd0d7e 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" +#include namespace berry { -const uint CompositeExpression::HASH_INITIAL = Poco::Hash()("berry::CompositeExpression"); +const uint CompositeExpression::HASH_INITIAL = qHash("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) const { if (fExpressions.size() == 0) return; foreach (Expression::Pointer iter, fExpressions) { iter->CollectExpressionInfo(info); } } 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/berryEqualsExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryEqualsExpression.cpp index 64ddef9856..2ed10cc4cf 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryEqualsExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryEqualsExpression.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 "berryEqualsExpression.h" #include "berryExpressions.h" #include #include #include #include namespace berry { -const std::size_t EqualsExpression::HASH_INITIAL= Poco::Hash()("berry::EqualsExpression"); +const uint EqualsExpression::HASH_INITIAL= qHash("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::ConstPointer element= context->GetDefaultVariable(); return EvaluationResult::ValueOf(element == fExpectedValue); } void 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; } 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 62384f53dc..2f58540d52 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; + static const uint 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) const; bool operator==(const Object* object) const; protected: uint ComputeHashCode() const; }; } // namespace berry #endif // __BERRY_EQUALS_EXPRESSION_H__ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressionPlugin.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressionPlugin.cpp index e4e1aeaf0a..af1ae91bf0 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressionPlugin.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressionPlugin.cpp @@ -1,61 +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 "berryExpressionPlugin.h" +#include "berryExpressions.h" +#include "berryTypeExtensionManager.h" +#include "berryPlatformPropertyTester.h" + +#include "berryPlatform.h" + #include namespace berry { QObject* ExpressionPlugin::m_PluginListener = NULL; ExpressionPlugin* ExpressionPlugin::m_Default = NULL; ExpressionPlugin::ExpressionPlugin() { m_Default = this; } ExpressionPlugin* ExpressionPlugin::GetDefault() { return m_Default; } QString ExpressionPlugin::GetPluginId() { return "org.blueberry.core.expressions"; } +void ExpressionPlugin::start(ctkPluginContext* context) +{ + BERRY_REGISTER_EXTENSION_CLASS(PlatformPropertyTester, context) + + Expressions::TRACING = Platform::GetDebugOption("org.blueberry.core.expressions/tracePropertyResolving").toBool(); + TypeExtensionManager::DEBUG = Platform::GetDebugOption("org.blueberry.core.expressions/debug/TypeExtensionManager").toBool(); +} + void ExpressionPlugin::stop(ctkPluginContext* context) { if (m_PluginListener != NULL) { context->disconnectPluginListener(m_PluginListener); } m_PluginListener = NULL; Plugin::stop(context); } ctkPluginContext* ExpressionPlugin::GetPluginContext() const { return m_Context; } } #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) Q_EXPORT_PLUGIN2(org_blueberry_core_expressions, berry::ExpressionPlugin) #endif diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressionPlugin.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressionPlugin.h index 643cf75327..7caf34e4ca 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressionPlugin.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressionPlugin.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 BERRYEXPRESSIONPLUGIN_H #define BERRYEXPRESSIONPLUGIN_H #include "berryPlugin.h" namespace berry { class ExpressionPlugin : public Plugin { Q_OBJECT #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) Q_PLUGIN_METADATA(IID "org_blueberry_core_expressions") #endif Q_INTERFACES(ctkPluginActivator) public: static QObject* m_PluginListener; ExpressionPlugin(); static ExpressionPlugin* GetDefault(); static QString GetPluginId(); + void start(ctkPluginContext *context); void stop(ctkPluginContext* context); ctkPluginContext* GetPluginContext() const; private: static ExpressionPlugin* m_Default; }; } #endif // BERRYEXPRESSIONPLUGIN_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 b177dcdfa7..33a4187342 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressions.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressions.cpp @@ -1,334 +1,345 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 +#include namespace berry { - const bool Expressions::TRACING = true; + bool Expressions::TRACING = false; 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; + return IsSubtype(element->GetTypeInfo(), 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::ConstPointer Expressions::GetAsIIterable(Object::ConstPointer var, Expression::ConstPointer expression) { IIterable::ConstPointer iterable(var.Cast()); if (!iterable.IsNull()) { return iterable; } else { IAdapterManager* manager= Platform::GetAdapterManager(); iterable = manager->GetAdapter(var.GetPointer()); if (iterable) { return iterable; } 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::ConstPointer Expressions::GetAsICountable(Object::ConstPointer var, Expression::ConstPointer expression) { ICountable::ConstPointer countable(var.Cast()); if (!countable.IsNull()) { return countable; } else { IAdapterManager* manager = Platform::GetAdapterManager(); ICountable::ConstPointer result(manager->GetAdapter(var.GetPointer())); if (result) { return result; } 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 (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; } + bool Expressions::IsSubtype(const Reflection::TypeInfo& typeInfo, const QString& type) + { + if (typeInfo.GetName() == type) return true; + QList superClasses = typeInfo.GetSuperclasses(); + for (int i = 0; i < superClasses.size(); ++i) + { + if (IsSubtype(superClasses[i], type)) + { + return true; + } + } + return false; + } + 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 (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 e9475b0c1a..0386d25121 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,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 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; +namespace Reflection { class TypeInfo; } + class Expressions { private: Expressions(); static int FindNextComma(const QString& str, int start); + static bool IsSubtype(const Reflection::TypeInfo& typeInfo, const QString& type); + public: /* debugging flag to enable tracing */ - static const bool TRACING; + static 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::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::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/berryNotExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryNotExpression.cpp index b23c0be84c..7f84ffa3e1 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,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 "berryNotExpression.h" #include -#include namespace berry { -const std::size_t NotExpression::HASH_INITIAL = Poco::hash("berry::NotExpression"); +const uint NotExpression::HASH_INITIAL = qHash("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) 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; } 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 8f5e920418..297ab15e99 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; + static const uint HASH_INITIAL; Expression::Pointer fExpression; public: NotExpression(Expression::Pointer expression); EvaluationResult::ConstPointer Evaluate(IEvaluationContext* context) const; void CollectExpressionInfo(ExpressionInfo* info) const; bool operator==(const Object* object) const; protected: uint ComputeHashCode() const; }; } // namespace berry #endif // __BERRY_NOT_EXPRESSION_H__ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPlatformPropertyTester.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPlatformPropertyTester.cpp new file mode 100644 index 0000000000..f66a912071 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPlatformPropertyTester.cpp @@ -0,0 +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. + +===================================================================*/ + +#include "berryPlatformPropertyTester.h" + +#include "berryPlatform.h" +#include +#include + +#include + + +namespace berry { + +const QString PlatformPropertyTester::PROPERTY_PRODUCT = "product"; +const QString PlatformPropertyTester::PROPERTY_IS_PLUGIN_INSTALLED = "isPluginInstalled"; +const QString PlatformPropertyTester::PROPERTY_PLUGIN_STATE = "pluginState"; + + +bool PlatformPropertyTester::Test(Object::ConstPointer receiver, const QString &property, + const QList &args, Object::Pointer expectedValue) +{ + if (ObjectTypeInfo::ConstPointer typeInfo = receiver.Cast()) + { + if (!(*typeInfo == Reflection::TypeInfo::New())) + { + return false; + } + + if (PROPERTY_PRODUCT == property) + { + IProduct* product= Platform::GetProduct(); + if (product != nullptr) + { + return product->GetId() == expectedValue->ToString(); + } + return false; + } + else if (PROPERTY_IS_PLUGIN_INSTALLED == property && !args.isEmpty() && args[0].Cast()) + { + return !Platform::GetPlugin(args[0]->ToString()).isNull(); + } + else if (PROPERTY_PLUGIN_STATE == property && + !args.isEmpty() && args[0].Cast()) + { + QSharedPointer p = Platform::GetPlugin(args[0]->ToString()); + if (!p.isNull()) + { + return PluginState(p->getState(), expectedValue->ToString()); + } + return false; + } + } + return false; +} + +bool PlatformPropertyTester::PluginState(ctkPlugin::State pluginState, const QString& expectedValue) +{ + switch (pluginState) + { + case ctkPlugin::UNINSTALLED: + return expectedValue == QString("UNINSTALLED"); + case ctkPlugin::INSTALLED: + return expectedValue == QString("INSTALLED"); + case ctkPlugin::RESOLVED: + return expectedValue == QString("RESOLVED"); + case ctkPlugin::STARTING: + return expectedValue == QString("STARTING"); + case ctkPlugin::STOPPING: + return expectedValue == QString("STOPPING"); + case ctkPlugin::ACTIVE: + return expectedValue == QString("ACTIVE"); + default: + return false; + } + return false; +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPlatformPropertyTester.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPlatformPropertyTester.h new file mode 100644 index 0000000000..3de27e2a75 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPlatformPropertyTester.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 BERRYPLATFORMPROPERTYTESTER_H +#define BERRYPLATFORMPROPERTYTESTER_H + +#include + +#include + +namespace berry { + +/** + * A property tester for testing platform properties. Can test whether or + * not a given plugin is installed in the running environment, as well as + * the id of the currently active product. + *

+ * For example:
+ * <test property="org.blueberry.core.runtime.product" value="org.mitk.qt.Workbench"/>
+ * <test property="org.blueberry.core.runtime.isPluginInstalled" args="org.blueberry.core.expressions"/>
+ * <test property="org.blueberry.core.runtime.pluginState" args="org.blueberry.core.expressions" value="ACTIVE"/> + *

+ */ +class PlatformPropertyTester : public PropertyTester +{ + Q_OBJECT +private: + + static const QString PROPERTY_PRODUCT; // = "product"; + static const QString PROPERTY_IS_PLUGIN_INSTALLED; // = "isPluginInstalled"; + static const QString PROPERTY_PLUGIN_STATE; // = "pluginState"; + +public: + + bool Test(Object::ConstPointer receiver, const QString& property, + const QList& args, Object::Pointer expectedValue); + +private: + + bool PluginState(ctkPlugin::State pluginState, const QString &expectedValue); + +}; + +} + +#endif // BERRYPLATFORMPROPERTYTESTER_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 267a218754..3ea8bafffd 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,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. ===================================================================*/ #include "berryProperty.h" -#include -#include +#include namespace berry { -Property::Property(Object::ConstPointer type, +Property::Property(const Reflection::TypeInfo& typeInfo, const QString &namespaze, const QString &name) - : fType(type), fNamespace(namespaze), fName(name) + : fType(typeInfo), fNamespace(namespaze), fName(name) { } void Property::SetPropertyTester(IPropertyTester::Pointer tester) { - poco_check_ptr(tester); - - fTester= tester; + assert(tester.GetPointer() != 0); + fTester = tester; } -bool Property::IsInstantiated() +bool Property::IsInstantiated() const { return fTester->IsInstantiated(); } -bool Property::IsDeclaringPluginActive() +bool Property::IsDeclaringPluginActive() const { return fTester->IsDeclaringPluginActive(); } -bool Property::IsValidCacheEntry(bool forcePluginActivation) +bool Property::IsValidCacheEntry(bool forcePluginActivation) const { if (forcePluginActivation) { return this->IsInstantiated() && this->IsDeclaringPluginActive(); } else { return (this->IsInstantiated() && this->IsDeclaringPluginActive()) || (!this->IsInstantiated() && !this->IsDeclaringPluginActive()); } } bool Property::Test(Object::ConstPointer receiver, const QList& args, Object::Pointer expectedValue) { return fTester->Test(receiver, fName, args, expectedValue); } -bool Property::operator==(Property& obj) +bool Property::operator==(const Object* obj) const { - return fType == obj.fType && fNamespace == obj.fNamespace && - fName == obj.fName; - } + if (const Property* other = dynamic_cast(obj)) + { + return fType == other->fType && fNamespace == other->fNamespace && + fName == other->fName; + } + return false; +} -bool Property::operator==(Property* obj) +bool Property::operator<(const Object* obj) const { - return this->operator==(*obj); + return this->HashCode() < obj->HashCode(); } -int Property::HashCode() +uint Property::HashCode() const { - return (int) ((Poco::Hash()(typeid(fType).name()) << 16) | - (Poco::Hash()(fNamespace.toStdString()) << 8) | - Poco::Hash()(fName.toStdString())); + return qHash(fType.GetName()) << 16 | + qHash(fNamespace) << 8 | + qHash(fName); } } 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 9ca3b844d1..8e850560ac 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,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 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 { +class Property : public Object { public: - typedef Property Self; - typedef Poco::SharedPtr Pointer; - typedef Poco::SharedPtr ConstPointer; + + berryObjectMacro(Property) private: - Object::ConstPointer fType; + Reflection::TypeInfo fType; QString fNamespace; QString fName; IPropertyTester::Pointer fTester; friend class TypeExtensionManager; - /* package */ Property(Object::ConstPointer type, + /* package */ Property(const Reflection::TypeInfo& typeInfo, const QString& namespaze, const QString& name); /* package */ void SetPropertyTester(IPropertyTester::Pointer tester); public: - bool IsInstantiated(); + bool IsInstantiated() const; - bool IsDeclaringPluginActive(); + bool IsDeclaringPluginActive() const; - bool IsValidCacheEntry(bool forcePluginActivation); + bool IsValidCacheEntry(bool forcePluginActivation) const; bool Test(Object::ConstPointer receiver, const QList& args, Object::Pointer expectedValue); - bool operator==(Property& obj); + bool operator==(const Object* obj) const; - bool operator==(Property* obj); + bool operator<(const Object* obj) const; - int HashCode(); + uint HashCode() const; }; } // namespace berry #endif /*BERRYPROPERTY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyCache.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyCache.h index b52d704abd..cb18b8b413 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyCache.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyCache.h @@ -1,52 +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 BERRYPROPERTYCACHE_H_ #define BERRYPROPERTYCACHE_H_ #include "Poco/LRUCache.h" #include "berryProperty.h" namespace berry { class PropertyCache { private: - Poco::LRUCache fCache; + + struct PropertyHandle + { + Property* m_Property; + }; + + Poco::LRUCache fCache; public: PropertyCache(const int cacheSize) : fCache(cacheSize) { } Property::Pointer Get(Property::Pointer key) { - return fCache.get(key); + Poco::SharedPtr value = fCache.get(key); + return value.isNull() ? Property::Pointer(0) : Property::Pointer(value->m_Property); } void Put(Property::Pointer method) { - fCache.add(method, method); + PropertyHandle handle = { method.GetPointer() }; + fCache.add(method, handle); } void Remove(Property::Pointer method) { fCache.remove(method); } }; } // namespace berry #endif /*BERRYPROPERTYCACHE_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 cc87312074..dbba850507 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,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 "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"); +const QString ReferenceExpression::ATT_DEFINITION_ID = "definitionId"; +const uint ReferenceExpression::HASH_INITIAL= qHash(QString("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) const { Expression::Pointer expr; try { expr= GetDefinitionRegistry().GetExpression(fDefinitionId); } 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; } uint ReferenceExpression::ComputeHashCode() const { - return HASH_INITIAL * HASH_FACTOR + Poco::Hash()(fDefinitionId.toStdString()); + return HASH_INITIAL * HASH_FACTOR + qHash(fDefinitionId); } } 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 2bf6021639..f7a30d572e 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; + static const uint 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) const; bool operator==(const Object* object) const; protected: uint ComputeHashCode() const; }; } // namespace berry #endif // __BERRY_REFERENCE_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 97a48c8965..102216e58c 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,189 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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"); +TypeExtensionManager& TestExpression::GetTypeExtensionManager() +{ + static TypeExtensionManager mgr("propertyTesters"); + return mgr; +} 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::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; + return EvaluationResult::ValueOf(str == fArgs[0]->ToString()); } - Property::Pointer property= fgTypeExtensionManager.GetProperty(element, fNamespace, fProperty, context->GetAllowPluginActivation() && fForcePluginActivation); + Property::Pointer property= GetTypeExtensionManager().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) 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() const { return HASH_INITIAL * HASH_FACTOR + this->HashCode(fArgs) - * HASH_FACTOR + fExpectedValue->HashCode() + * HASH_FACTOR + (fExpectedValue.IsNull() ? 0 : fExpectedValue->HashCode()) * HASH_FACTOR + qHash(fNamespace) * HASH_FACTOR + qHash(fProperty) * HASH_FACTOR + (fForcePluginActivation ? 1 : 0); } QString TestExpression::ToString() const { QString args(""); 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; + return GetTypeExtensionManager(); } } 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 f8807fc433..d887c69ea9 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; + static TypeExtensionManager& GetTypeExtensionManager(); 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) const; bool operator==(const Object* object) const; protected: 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 79459c51fd..2a34b47828 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,157 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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) +TypeExtension::TypeExtension() + : fExtendersLoaded(false) + , fInheritsLoaded(false) { + // special constructor to create the CONTINUE instance +} +TypeExtension::TypeExtension(const Reflection::TypeInfo& typeInfo) + : fTypeInfo(typeInfo) + , fExtendersLoaded(false) + , fInheritsLoaded(false) +{ } IPropertyTester::Pointer TypeExtension::FindTypeExtender( TypeExtensionManager& manager, const QString& namespaze, const QString& method, bool staticMethod, bool forcePluginActivation) { if (!fExtendersLoaded) { - fExtenders = manager.LoadTesters(fTypeInfo); + fExtenders = manager.LoadTesters(fTypeInfo.GetName()); fExtendersLoaded = true; } IPropertyTester::Pointer result; // handle extenders associated with this type extender 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; -// } + if (!fInheritsLoaded) + { + fInherits.clear(); + QList superClasses = fTypeInfo.GetSuperclasses(); + foreach(const Reflection::TypeInfo& superClass, superClasses) + { + fInherits.push_back(manager.Get(superClass)); + } + fInheritsLoaded = true; + } + foreach(const TypeExtension::Pointer& typeExtension, fInherits) + { + result = typeExtension->FindTypeExtender(manager, namespaze, method, staticMethod, forcePluginActivation); + if (result.Cast().IsNull()) + { + return result; + } + } + return CONTINUE_::Pointer(new CONTINUE_()); +} + +bool TypeExtension::CONTINUE_::Handles(const QString&, const QString&) { + return false; +} + +bool TypeExtension::CONTINUE_::IsInstantiated() { + return true; +} + +bool TypeExtension::CONTINUE_::IsDeclaringPluginActive() { + return true; +} + +IPropertyTester*TypeExtension::CONTINUE_::Instantiate() { + return this; +} + +bool TypeExtension::CONTINUE_::Test(Object::ConstPointer, const QString&, const QList&, Object::Pointer) { + return false; +} + +IPropertyTester::Pointer END_POINT_::FindTypeExtender(TypeExtensionManager&, const QString&, const QString&, bool, bool) +{ 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 47e044eec7..6f37bc6227 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,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 BERRYTYPEEXTENSION_H_ #define BERRYTYPEEXTENSION_H_ #include #include #include "berryIPropertyTester.h" namespace berry { class TypeExtensionManager; class END_POINT_; class TypeExtension : public Object { public: - berryObjectMacro(TypeExtension); + berryObjectMacro(TypeExtension) private: /* the type this extension is extending */ - QString fTypeInfo; + Reflection::TypeInfo 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 - } + QList fInherits; + bool fInheritsLoaded; + TypeExtension(); 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::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); + class CONTINUE_ : public IPropertyTester { + + public: + + berryObjectMacro(CONTINUE_) + + bool Handles(const QString& /*namespaze*/, const QString& /*method*/); + bool IsInstantiated(); + bool IsDeclaringPluginActive(); + IPropertyTester* Instantiate(); + bool Test(Object::ConstPointer /*receiver*/, const QString& /*method*/, + const QList& /*args*/, Object::Pointer /*expectedValue*/); + }; + + static const CONTINUE_ CONTINUE; + static const END_POINT_ END_POINT; + + TypeExtension(const Reflection::TypeInfo& typeInfo); + + 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_()); - } + const QString& /*namespaze*/, const QString& /*name*/, + bool /*staticMethod*/, bool /*forcePluginActivation*/); }; } // 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 139559f5a9..bb418d8a67 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,199 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 { + /** + * Tells whether this class is in debug mode. + */ + bool TypeExtensionManager::DEBUG = false; + const QString TypeExtensionManager::TYPE= "type"; TypeExtensionManager::TypeExtensionManager(const QString& extensionPoint) : fExtensionPoint(extensionPoint) { - //Platform.getExtensionRegistry().addRegistryChangeListener(this); + Platform::GetExtensionRegistry()->AddListener(this); this->InitializeCaches(); } 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::ConstPointer receiver, const QString& namespaze, const QString& method, bool forcePluginActivation) { std::clock_t start= 0; if (Expressions::TRACING) - start = std::clock(); + { + 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 result(new Property(receiver->GetTypeInfo(), namespaze, method)); Property::Pointer cached(fPropertyCache->Get(result)); - if (!cached.isNull()) + if (!cached.IsNull()) { if (cached->IsValidCacheEntry(forcePluginActivation)) { if (Expressions::TRACING) { BERRY_INFO << "[Type Extension] - method " - << receiver->ToString() << "#" << method.toStdString() + << receiver->GetClassName() << "#" << 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())); + TypeExtension::Pointer extension(this->Get(receiver->GetTypeInfo())); 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 + << receiver->GetClassName() << "#" << 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 TypeExtensionManager::Get(const Reflection::TypeInfo& typeInfo) { - TypeExtension::Pointer result(fTypeExtensionMap[type]); + TypeExtension::Pointer result(fTypeExtensionMap[typeInfo.GetName()]); if (result.IsNull()) { - result = new TypeExtension(type); - fTypeExtensionMap[type] = result; + result = new TypeExtension(typeInfo); + fTypeExtensionMap[typeInfo.GetName()] = 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 (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 (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()); + BERRY_ERROR << e.what(); 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(); } + void TypeExtensionManager::Added(const QList >& /*extensions*/) + { + this->InitializeCaches(); + } + + void TypeExtensionManager::Removed(const QList >& /*extensions*/) + { + this->InitializeCaches(); + } + + void TypeExtensionManager::Added(const QList >& /*extensionPoints*/) + { + this->InitializeCaches(); + } + + void TypeExtensionManager::Removed(const QList >& /*extensionPoints*/) + { + this->InitializeCaches(); + } + TypeExtensionManager::~TypeExtensionManager() { + IExtensionRegistry* registry = Platform::GetExtensionRegistry(); + if (registry) + { + registry->RemoveListener(this); + } 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 144bd59507..8388e430ec 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,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 BERRYTYPEEXTENSIONMANAGER_H_ #define BERRYTYPEEXTENSIONMANAGER_H_ #include "berryIPropertyTester.h" #include "berryTypeExtension.h" #include "berryPropertyCache.h" #include "berryProperty.h" #include +#include #include #include namespace berry { -class TypeExtensionManager { // implements IRegistryChangeListener { +class TypeExtensionManager : private IRegistryEventListener +{ 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::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: + static bool DEBUG; + TypeExtensionManager(const QString& extensionPoint); ~TypeExtensionManager(); Property::Pointer GetProperty(Object::ConstPointer receiver, const QString& namespaze, const QString& method); /*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); + TypeExtension::Pointer Get(const Reflection::TypeInfo& typeInfo); /* * 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(); - // } - // } + QList LoadTesters(const QString& typeName); private: /*synchronized*/void InitializeCaches(); + + virtual void Added(const QList >& extensions); + virtual void Removed(const QList >& extensions); + virtual void Added(const QList >& extensionPoints); + virtual void Removed(const QList >& extensionPoints); }; } #endif /*BERRYTYPEEXTENSIONMANAGER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeListener.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeListener.h index 24ab1c42b7..680871ee7a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeListener.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/berryIJobChangeListener.h @@ -1,159 +1,157 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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 { - berryObjectMacro(berry::IJobChangeListener) - struct BERRY_JOBS Events { typedef Message1 JobChangeEventType; enum Type { NONE = 0x00000000, ABOUT_TO_RUN = 0x00000001, AWAKE = 0x00000002, DONE = 0x00000004, RUNNING = 0x00000008, SCHEDULED = 0x00000010, SLEEPING = 0x00000020, ALL = 0xffffffff }; Q_DECLARE_FLAGS(Types, Type) JobChangeEventType jobAboutToRun; JobChangeEventType jobAwake; JobChangeEventType jobDone; JobChangeEventType jobRunning; JobChangeEventType jobScheduled; JobChangeEventType jobSleeping; void AddListener(IJobChangeListener* listener); void RemoveListener(IJobChangeListener* listener); void SetExceptionHandler(const AbstractExceptionHandler& handler); 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*/) { } /** * 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*/) { } /** * 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*/) { } /** * Notification that a job has started running. * * @param event the event details */ 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*/) { } /** * 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*/) { } }; } Q_DECLARE_OPERATORS_FOR_FLAGS(berry::IJobChangeListener::Events::Types) #endif /* BERRYIJOBCHANGELISTENER_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 a80f9e9311..b863335a2a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.cpp @@ -1,164 +1,165 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 namespace berry { struct AboutToRunDoit: public JobListeners::IListenerDoit { void Notify(const IJobChangeListener::Events& events, const IJobChangeEvent::ConstPointer& event) const { events.jobAboutToRun(event); } }; struct AwakeDoit: public JobListeners::IListenerDoit { void Notify(const IJobChangeListener::Events& events, const IJobChangeEvent::ConstPointer& event) const { events.jobAwake(event); } }; struct DoneDoit: public JobListeners::IListenerDoit { void Notify(const IJobChangeListener::Events& events, const IJobChangeEvent::ConstPointer& event) const { events.jobDone(event); } }; struct RunningDoit: public JobListeners::IListenerDoit { void Notify(const IJobChangeListener::Events& events, const IJobChangeEvent::ConstPointer& event) const { events.jobRunning(event); } }; struct ScheduledDoit: public JobListeners::IListenerDoit { void Notify(const IJobChangeListener::Events& events, const IJobChangeEvent::ConstPointer& event) const { events.jobScheduled(event); } }; struct SleepingDoit: public JobListeners::IListenerDoit { void Notify(const IJobChangeListener::Events& events, 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() { 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) { //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 + if(dynamic_cast(&e)) { - dynamic_cast (e); return; } - catch (const std::bad_cast&) + else { // TODO get bundle id (find a C++ way) //std::string pluginId = JobOSGiUtils.getDefault().getBundleId(listener); QString pluginId; if (pluginId.isEmpty()) + { pluginId = JobManager::PI_JOBS(); + } QString message = "Problems occurred when invoking code from plug-in: " - + pluginId; + + pluginId; 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/berryWorker.cpp b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorker.cpp index ceb943a222..16d46672d5 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorker.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorker.cpp @@ -1,134 +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 "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(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(); //result must not be null if (sptr_result.IsNull()) { 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 ); 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) { 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( + Poco::Thread("Worker-" + std::to_string(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/CMakeLists.txt b/BlueBerry/Bundles/org.blueberry.core.runtime/CMakeLists.txt index f2597a4a60..378e17bfbd 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/CMakeLists.txt +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/CMakeLists.txt @@ -1,45 +1,50 @@ project(org_blueberry_core_runtime) set(QT_USE_QTXML 1) MACRO_CREATE_CTK_PLUGIN(EXPORT_DIRECTIVE org_blueberry_core_runtime_EXPORT - EXPORTED_INCLUDE_SUFFIXES src src/application src/registry) + EXPORTED_INCLUDE_SUFFIXES src + src/application + src/debug + src/dynamichelpers + src/registry +) target_link_libraries(${PLUGIN_TARGET} PUBLIC Poco::Foundation Poco::Util Poco::XML) if(MITK_USE_Qt5) target_link_libraries(${PLUGIN_TARGET} PRIVATE Qt5::Gui Qt5::Xml) endif() # Set compiler flags target_compile_definitions(${PLUGIN_TARGET} PUBLIC "$<$:POCO_NO_UNWINDOWS;WIN32_LEAN_AND_MEAN>") add_executable(${OSGI_APP} MACOSX_BUNDLE "src/application/berryMain.cpp") target_link_libraries(${OSGI_APP} PRIVATE ${PROJECT_NAME} mbilog) if(_ctk_test_plugins) add_dependencies(${OSGI_APP} ${_ctk_test_plugins}) add_dependencies(BlueBerry ${OSGI_APP}) set_property(TARGET ${OSGI_APP} APPEND PROPERTY LABELS BlueBerry) endif() configure_file(src/application/solstice.ini ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${OSGI_APP}.ini) add_executable(${OSGI_UI_APP} MACOSX_BUNDLE "src/application/berryMainUI.cpp") target_link_libraries(${OSGI_UI_APP} PRIVATE ${PROJECT_NAME} mbilog) if(MITK_USE_Qt5) target_link_libraries(${OSGI_UI_APP} PRIVATE Qt5::Widgets) endif() if(_ctk_test_plugins) add_dependencies(${OSGI_UI_APP} ${_ctk_test_plugins}) add_dependencies(BlueBerry ${OSGI_UI_APP}) set_property(TARGET ${OSGI_UI_APP} APPEND PROPERTY LABELS BlueBerry) endif() configure_file(src/application/solstice.ini ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${OSGI_UI_APP}.ini) configure_file("${CMAKE_CURRENT_SOURCE_DIR}/src/berryConfig.h.in" "${CMAKE_CURRENT_BINARY_DIR}/berryConfig.h" @ONLY) diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/files.cmake b/BlueBerry/Bundles/org.blueberry.core.runtime/files.cmake index 4b1d810f09..8dd98f286c 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/files.cmake +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/files.cmake @@ -1,119 +1,133 @@ set(MOC_H_FILES src/berryPlugin.h src/internal/berryCTKPluginListener.h src/internal/berryCTKPluginActivator.h + src/internal/berryDebugOptions.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 + berryIProduct.cpp berryIBerryPreferences.cpp berryIPreferencesService.cpp berryListenerList.h berryLog.cpp berryMultiStatus.cpp berryObject.cpp berryObjectGeneric.h berryObjectList.h berryObjects.cpp berryObjectString.cpp berryObjectStringMap.cpp + berryObjectTypeInfo.cpp berryOperationCanceledException.cpp berryPlatform.cpp berryPlatformException.cpp berryPlatformObject.cpp berryPlugin.cpp + berryReflection.cpp berrySafeRunner.cpp berrySmartPointer.h berryStatus.cpp berryWeakPointer.h # application application/berryIApplication.cpp application/berryStarter.cpp + debug/berryDebugOptionsListener.cpp + debug/berryIDebugOptions.cpp + + dynamichelpers/berryExtensionTracker.cpp + dynamichelpers/berryIExtensionChangeHandler.cpp + dynamichelpers/berryIExtensionTracker.cpp + # registry registry/berryIConfigurationElement.cpp registry/berryIContributor.cpp registry/berryIExecutableExtension.cpp registry/berryIExecutableExtensionFactory.cpp registry/berryIExtension.cpp registry/berryIExtensionPoint.cpp + registry/berryIExtensionPointFilter.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 + berryDebugOptions.cpp berryExtension.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 berryRegistryObjectFactory.cpp berryRegistryIndexChildren.cpp berryRegistryIndexElement.cpp berryRegistryMessages.cpp berryRegistryObject.cpp berryRegistryObjectManager.cpp berryRegistryObjectReferenceMap.cpp berryRegistryProperties.cpp berryRegistryStrategy.cpp berryRegistryTimestamp.cpp berryRegistrySupport.cpp + berrySimpleExtensionPointFilter.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/berryIAdaptable.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIAdaptable.h index 04cde820b9..c73dfb1200 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIAdaptable.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIAdaptable.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 _BERRY_IADAPTABLE_H_ #define _BERRY_IADAPTABLE_H_ #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 { public: /** * 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 Object* GetAdapter(const QString& adapterType) = 0; + virtual Object* GetAdapter(const QString& adapterType) const = 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()) + BERRY_WARN << "Error getting adapter for '" << Reflection::DemangleName(typeid(*this).name()) << "': " + << "Cannot get the interface id for type '" << Reflection::GetClassName() << "'. 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 6c3384cb1d..981432f675 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIAdapterManager.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIAdapterManager.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 BERRYIADAPTERMANAGER_H_ #define BERRYIADAPTERMANAGER_H_ #include #include #include "berryPlatformObject.h" #include "berryIAdapterFactory.h" #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 { 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 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 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()) + BERRY_WARN << "Error getting adapter for '" << Reflection::GetClassName(adaptable) << "': " + << "Cannot get the interface id for type '" << Reflection::GetClassName() << "'. 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 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()) + BERRY_WARN << "Error querying adapter manager for '" << Reflection::GetClassName(adaptable) << "': " + << "Cannot get the interface id for type '" << Reflection::GetClassName() << "'. 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:

* @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 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 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()) + BERRY_WARN << "Error getting adapter for '" << Reflection::GetClassName(adaptable) << "': " + << "Cannot get the interface id for type '" << Reflection::GetClassName() << "'. 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 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 QString& adaptableTypeName) = 0; private: 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.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp index 3b9d740123..b0d98e82d3 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp @@ -1,25 +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 "berryIBerryPreferences.h" namespace berry { IBerryPreferences::~IBerryPreferences () { } +IBerryPreferences::ChangeEvent::ChangeEvent(IBerryPreferences* source, const QString& property, + const QString& oldValue, const QString& newValue) + : m_Source(source) + , m_Property(property) + , m_OldValue(oldValue) + , m_NewValue(newValue) +{ +} + +IBerryPreferences* IBerryPreferences::ChangeEvent::GetSource() const +{ + return m_Source; +} + +QString IBerryPreferences::ChangeEvent::GetProperty() const +{ + return m_Property; +} + +QString IBerryPreferences::ChangeEvent::GetOldValue() const +{ + return m_OldValue; +} + +QString IBerryPreferences::ChangeEvent::GetNewValue() const +{ + return m_NewValue; +} + } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.h index 7e6586a608..391cc75784 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.h @@ -1,48 +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 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. - /// + /** + * 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 { berryObjectMacro(berry::IBerryPreferences) + class org_blueberry_core_runtime_EXPORT ChangeEvent { + IBerryPreferences* const m_Source; + const QString m_Property; + const QString m_OldValue; + const QString m_NewValue; + + public: + + ChangeEvent(IBerryPreferences* source, const QString& property, + const QString& oldValue, const QString& newValue); + + IBerryPreferences* GetSource() const; + QString GetProperty() const; + QString GetOldValue() const; + QString GetNewValue() const; + }; + virtual ~IBerryPreferences(); - /// - /// Invoked when this node was changed, that is when a property - /// was changed or when a new child node was inserted. - /// + /** + * Invoked when this node was changed, that is when a property + * was changed or when a new child node was inserted. + */ berry::Message1 OnChanged; + /** + * Adds a property change listener to this preferences node. + * The listener will be informed about property changes of + * this preference node, but not about changes to child nodes. + */ + berry::Message1 OnPropertyChanged; }; } // namespace berry #endif /*BERRYIBERRYPREFERENCES_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferencesService.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferencesService.h index f64675296e..369670c13a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferencesService.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferencesService.h @@ -1,42 +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 BERRYIBERRYPREFERENCESSERVICE_H_ #define BERRYIBERRYPREFERENCESSERVICE_H_ #include "berryIPreferencesService.h" namespace berry { - struct IBerryPreferencesService : public IPreferencesService - { - /// - /// Try to import the prefs from the given file. - /// Existing properties will be overridden! - /// Returns true if the preferences could be imported. - /// - virtual void ImportPreferences(const QString& f, const QString& name="") = 0; - - /// - /// Exports the current system preferences to the given file. - /// - virtual void ExportPreferences(const QString& f, const QString& name="") = 0; - - }; + +struct IBerryPreferencesService : public IPreferencesService +{ + /** + * Try to import the prefs from the given file. + * Existing properties will be overridden! + * Returns true if the preferences could be imported. + */ + virtual void ImportPreferences(const QString& f, const QString& name="") = 0; + + /** + * Exports the current system preferences to the given file. + */ + virtual void ExportPreferences(const QString& f, const QString& name="") = 0; + +}; + } // namespace berry Q_DECLARE_INTERFACE(berry::IBerryPreferencesService, "org.blueberry.core.runtime.IBerryPreferencesService") #endif /*BERRYIBERRYPREFERENCESSERVICE_H_*/ diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionConstants.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIProduct.cpp similarity index 76% copy from Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionConstants.cpp copy to BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIProduct.cpp index 4c9481b513..4a429a0961 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionConstants.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIProduct.cpp @@ -1,21 +1,26 @@ /*=================================================================== -The Medical Imaging Interaction Toolkit (MITK) +BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryIProduct.h" -#include "QmitkExtActionConstants.h" +namespace berry { -const QString QmitkExtActionConstants::M_WINDOW = "window"; +IProduct::~IProduct() +{ +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIProduct.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIProduct.h new file mode 100644 index 0000000000..9a4b535d73 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIProduct.h @@ -0,0 +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 BERRYIPRODUCT_H +#define BERRYIPRODUCT_H + +#include + +#include +#include + +class ctkPlugin; + +namespace berry { + +/** + * Products are the BlueBerry unit of branding. From the runtime point of view they have + * a name, id and description and identify the BlueBerry application to run. + *

+ * Since the bulk of the branding related information is + * specific to the UI, products also carry an arbitrary set of properties. The valid set of + * key-value pairs and their interpretation defined by the UI of the target environment. + * For example, in the standard BlueBerry UI, IProductConstants + * the properties of interest to the UI. Other clients may specify additional properties. + *

+ * Products can be defined directly using extensions to the org.blueberry.core.runtime.products + * extension point or by using facilities provided by IProductProvider implementations. + * + * @see IProductProvider + */ +struct org_blueberry_core_runtime_EXPORT IProduct +{ + virtual ~IProduct(); + + /** + * Returns the application associated with this product. This information is used + * to guide the runtime as to what application extension to create and execute. + * + * @return this product's application or null if none + */ + virtual QString GetApplication() const = 0; + + /** + * Returns the name of this product. The name is typically used in the title + * bar of UI windows. + * + * @return the name of this product or null if none + */ + virtual QString GetName() const = 0; + + /** + * Returns the text description of this product + * + * @return the description of this product or null if none + */ + virtual QString GetDescription() const = 0; + + /** Returns the unique product id of this product. + * + * @return the id of this product + */ + virtual QString GetId() const = 0; + + /** + * Returns the property of this product with the given key. + * null is returned if there is no such key/value pair. + * + * @param key the name of the property to return + * @return the value associated with the given key or null if none + */ + virtual QString GetProperty(const QString& key) const = 0; + + /** + * Returns the plug-in which is responsible for the definition of this product. + * Typically this is used as a base for searching for images and other files + * that are needed in presenting the product. + * + * @return the plug-in which defines this product or null if none + */ + virtual QSharedPointer GetDefiningPlugin() const = 0; +}; + +} + +#endif // BERRYIPRODUCT_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryISafeRunnable.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryISafeRunnable.h index d5d434628b..18df36fb2b 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 { 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; + virtual void HandleException(const ctkException& 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) + void HandleException(const ctkException& 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/berryMacros.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMacros.h index 2dc5b376ea..4b6ad43fb6 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMacros.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryMacros.h @@ -1,41 +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_MACROS_H__ #define __BERRY_MACROS_H__ #include "berryWeakPointer.h" +#include "berryReflection.h" #include "berryExtensionType.h" +class QStringList; -#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() \ +#define berryArgGlue(x, y) x y +#define berryArgCount(_1,_2,_3,_4,_5,_6,_7,_8,count,...) count +#define berryExpandArgs(args) berryArgCount args +#define berryCountArgsMax8(...) berryExpandArgs((__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1, 0)) + +#define berryOverloadMacro2(name, count) name##count +#define berryOverloadMacro1(name, count) berryOverloadMacro2(name, count) +#define berryOverloadMacro(name, count) berryOverloadMacro1(name, count) +#define berryCallOverload(name, ...) berryArgGlue(berryOverloadMacro(name, berryCountArgsMax8(__VA_ARGS__)), (__VA_ARGS__)) + +#define berryObjectMacro(...) berryCallOverload(berryObjectMacro, __VA_ARGS__) + +#define berryObjectTypeInfo(...) \ + static ::berry::Reflection::TypeInfo GetStaticTypeInfo() \ + { return ::berry::Reflection::TypeInfo::New(); } \ + ::berry::Reflection::TypeInfo GetTypeInfo() const override \ + { return Self::GetStaticTypeInfo(); } \ + typedef ::berry::Reflection::TypeList<__VA_ARGS__> SuperclassTypes; \ + static QList< ::berry::Reflection::TypeInfo> GetStaticSuperclasses() \ + { return ::berry::Reflection::GetSuperclasses(); } \ + QList< ::berry::Reflection::TypeInfo> GetSuperclasses() const override \ + { return Self::GetStaticSuperclasses(); } + +#define berryObjectMacro1(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 BERRY_REGISTER_EXTENSION_CLASS(_ClassType, _PluginContext)\ -{\ - QString typeName = _PluginContext->getPlugin()->getSymbolicName();\ - typeName = (typeName + "_") + _ClassType::staticMetaObject.className();\ - ::berry::registerExtensionType<_ClassType>(typeName.toLatin1().data());\ +#define berryObjectMacro2(className, super1) \ + berryObjectMacro1(className) \ + berryObjectTypeInfo(super1) +#define berryObjectMacro3(className, super1, super2) \ + berryObjectMacro1(className) \ + berryObjectTypeInfo(super1, super2) +#define berryObjectMacro4(className, super1, super2, super3) \ + berryObjectMacro1(className) \ + berryObjectTypeInfo(super1, super2, super3) +#define berryObjectMacro5(className, super1, super2, super3, super4) \ + berryObjectMacro1(className) \ + berryObjectTypeInfo(super1, super2, super3, super4) +#define berryObjectMacro6(className, super1, super2, super3, super4, super5) \ + berryObjectMacro1(className) \ + berryObjectTypeInfo(super1, super2, super3, super4, super5) +#define berryObjectMacro7(className, super1, super2, super3, super4, super5, super6) \ + berryObjectMacro1(className) \ + berryObjectTypeInfo(super1, super2, super3, super4, super5, super6) +#define berryObjectMacro8(className, super1, super2, super3, super4, super5, super6, super7) \ + berryObjectMacro1(className) \ + berryObjectTypeInfo(super1, super2, super3, super4, super5, super6, super7) +#define berryObjectMacro9(className, super1, super2, super3, super4, super5, super6, super7, super8) \ + berryObjectMacro1(className) \ + berryObjectTypeInfo(super1, super2, super3, super4, super5, super6, super7, super8) + +#define BERRY_REGISTER_EXTENSION_CLASS(_ClassType, _PluginContext) \ +{ \ + Q_UNUSED(_PluginContext) \ + QString typeName = _ClassType::staticMetaObject.className(); \ + ::berry::registerExtensionType<_ClassType>(typeName.toLatin1().data()); \ } #endif /*__BERRY_MACROS_H__*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.cpp index b55ab7ab43..b3a714b5cf 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.cpp @@ -1,322 +1,302 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryReflection.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()); + return Reflection::DemangleName(typeid(*this).name()); +} + +Reflection::TypeInfo Object::GetStaticTypeInfo() +{ + return Reflection::TypeInfo::New(); +} + +Reflection::TypeInfo Object::GetTypeInfo() const +{ + return Self::GetStaticTypeInfo(); +} + +QList Object::GetStaticSuperclasses() +{ + return QList(); +} + +QList Object::GetSuperclasses() const +{ + return GetStaticSuperclasses(); } 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); #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) m_ReferenceCount.store(ref); #else m_ReferenceCount = ref; #endif 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 (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) if (m_ReferenceCount.load() > 0) #else if (m_ReferenceCount > 0) #endif { // 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 { - QString demangledName = DemangleName(typeid(*this).name()); + QString demangledName = Reflection::DemangleName(typeid(*this).name()); os << Indent << "RTTI typeinfo: " << demangledName << '\n'; os << Indent << "Reference Count: " << #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) m_ReferenceCount.load() #else m_ReferenceCount #endif << '\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::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 47ad990cf0..663afd2395 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObject.h @@ -1,247 +1,251 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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_ +#ifndef BERRYOBJECT_H_ +#define BERRYOBJECT_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; /** Construct the object with an initial Indentation level. */ Indent(int ind = 0) { m_Indent=ind; } /** * 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 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 { private: mutable Message<> m_DestroyMessage; public: 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; + static Reflection::TypeInfo GetStaticTypeInfo(); + virtual Reflection::TypeInfo GetTypeInfo() const; + + static QList GetStaticSuperclasses(); + virtual QList GetSuperclasses() 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 { #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) return m_ReferenceCount.load(); #else return m_ReferenceCount; #endif } /** 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 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_*/ +#endif /*BERRYOBJECT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectTypeInfo.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectTypeInfo.cpp new file mode 100644 index 0000000000..0ad5f76465 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectTypeInfo.cpp @@ -0,0 +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. + +===================================================================*/ + +#include "berryObjectTypeInfo.h" + +namespace berry { + +ObjectTypeInfo::ObjectTypeInfo() +{ + +} + +ObjectTypeInfo::ObjectTypeInfo(const Reflection::TypeInfo &typeInfo) + : Reflection::TypeInfo(typeInfo) +{ +} + +bool ObjectTypeInfo::operator==(const Object *other) const +{ + if (const ObjectTypeInfo* otherStr = dynamic_cast(other)) + { + return static_cast(*this) == static_cast(*otherStr); + } + return false; +} + +bool ObjectTypeInfo::operator==(const Reflection::TypeInfo &other) const +{ + return static_cast(*this) == other; +} + +} + diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectTypeInfo.h similarity index 50% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h copy to BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectTypeInfo.h index 90365ba2c1..f227f4a4f1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryObjectTypeInfo.h @@ -1,45 +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 BERRYQTWORKBENCHTWEAKLET_H_ -#define BERRYQTWORKBENCHTWEAKLET_H_ +#ifndef BERRYOBJECTTYPEINFO_H +#define BERRYOBJECTTYPEINFO_H -#include +#include -#include +#include namespace berry { -class BERRY_UI_QT QtWorkbenchTweaklet : public QObject, public WorkbenchTweaklet +class org_blueberry_core_runtime_EXPORT ObjectTypeInfo : public Reflection::TypeInfo, public Object { - Q_OBJECT - Q_INTERFACES(berry::WorkbenchTweaklet) - public: - berryObjectMacro(QtWorkbenchTweaklet) - - QtWorkbenchTweaklet(); + berryObjectMacro(ObjectTypeInfo, Reflection::TypeInfo, Object) - Display* CreateDisplay(); + ObjectTypeInfo(); + ObjectTypeInfo(const Reflection::TypeInfo& typeInfo); - bool IsRunning(); + bool operator==(const Object* other) const; + bool operator==(const Reflection::TypeInfo& other) const; }; -} // namespace berry +} -#endif /*BERRYQTWORKBENCHTWEAKLET_H_*/ +#endif // BERRYOBJECTTYPEINFO_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatform.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatform.cpp index 48debef554..8423167ca1 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatform.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatform.cpp @@ -1,240 +1,257 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryPlatform.h" #include "internal/berryInternalPlatform.h" +#include "internal/berryIRuntimeConstants.h" namespace berry { +const QString Platform::PI_RUNTIME = IRuntimeConstants::PI_RUNTIME(); + int Platform::OS_FREE_BSD = BERRY_OS_FREE_BSD; int Platform::OS_AIX = BERRY_OS_AIX; int Platform::OS_HPUX = BERRY_OS_HPUX; int Platform::OS_TRU64 = BERRY_OS_TRU64; int Platform::OS_LINUX = BERRY_OS_LINUX; int Platform::OS_MAC_OS_X = BERRY_OS_MAC_OS_X; int Platform::OS_NET_BSD = BERRY_OS_NET_BSD; int Platform::OS_OPEN_BSD = BERRY_OS_OPEN_BSD; int Platform::OS_IRIX = BERRY_OS_IRIX; int Platform::OS_SOLARIS = BERRY_OS_SOLARIS; int Platform::OS_QNX = BERRY_OS_QNX; int Platform::OS_VXWORKS = BERRY_OS_VXWORKS; int Platform::OS_CYGWIN = BERRY_OS_CYGWIN; int Platform::OS_UNKNOWN_UNIX = BERRY_OS_UNKNOWN_UNIX; int Platform::OS_WINDOWS_NT = BERRY_OS_WINDOWS_NT; int Platform::OS_WINDOWS_CE = BERRY_OS_WINDOWS_CE; int Platform::OS_VMS = BERRY_OS_VMS; int Platform::ARCH_ALPHA = BERRY_ARCH_ALPHA; int Platform::ARCH_IA32 = BERRY_ARCH_IA32; int Platform::ARCH_IA64 = BERRY_ARCH_IA64; int Platform::ARCH_MIPS = BERRY_ARCH_MIPS; int Platform::ARCH_HPPA = BERRY_ARCH_HPPA; int Platform::ARCH_PPC = BERRY_ARCH_PPC; int Platform::ARCH_POWER = BERRY_ARCH_POWER; int Platform::ARCH_SPARC = BERRY_ARCH_SPARC; int Platform::ARCH_AMD64 = BERRY_ARCH_AMD64; int Platform::ARCH_ARM = BERRY_ARCH_ARM; QString Platform::PROP_QTPLUGIN_PATH = "BlueBerry.qtplugin_path"; QString Platform::ARG_NEWINSTANCE = "BlueBerry.newInstance"; QString Platform::ARG_CLEAN = "BlueBerry.clean"; QString Platform::ARG_APPLICATION = "BlueBerry.application"; QString Platform::ARG_HOME = "BlueBerry.home"; QString Platform::ARG_STORAGE_DIR = "BlueBerry.storageDir"; QString Platform::ARG_PLUGIN_CACHE = "BlueBerry.plugin_cache_dir"; QString Platform::ARG_PLUGIN_DIRS = "BlueBerry.plugin_dirs"; QString Platform::ARG_FORCE_PLUGIN_INSTALL = "BlueBerry.forcePlugins"; QString Platform::ARG_PRELOAD_LIBRARY = "BlueBerry.preloadLibrary"; QString Platform::ARG_PROVISIONING = "BlueBerry.provisioning"; +QString Platform::ARG_DEBUG = "BlueBerry.debug"; QString Platform::ARG_CONSOLELOG = "BlueBerry.consoleLog"; QString Platform::ARG_TESTPLUGIN = "BlueBerry.testplugin"; QString Platform::ARG_TESTAPPLICATION = "BlueBerry.testapplication"; QString Platform::ARG_NO_REGISTRY_CACHE = "BlueBerry.noRegistryCache"; QString Platform::ARG_NO_LAZY_REGISTRY_CACHE_LOADING = "BlueBerry.noLazyRegistryCacheLoading"; QString Platform::ARG_REGISTRY_MULTI_LANGUAGE = "BlueBerry.registryMultiLanguage"; QString Platform::ARG_XARGS = "xargs"; QDir Platform::GetConfigurationPath() { return InternalPlatform::GetInstance()->GetConfigurationPath(); } IAdapterManager* Platform::GetAdapterManager() { return InternalPlatform::GetInstance()->GetAdapterManager(); } IExtensionRegistry *Platform::GetExtensionRegistry() { return InternalPlatform::GetInstance()->GetExtensionRegistry(); } IPreferencesService *Platform::GetPreferencesService() { return InternalPlatform::GetInstance()->GetPreferencesService(); } //PlatformEvents& Platform::GetEvents() //{ // return InternalPlatform::GetInstance()->GetEvents(); //} QDir Platform::GetInstallPath() { return InternalPlatform::GetInstance()->GetInstallPath(); } QDir Platform::GetInstancePath() { return InternalPlatform::GetInstance()->GetInstancePath(); } int Platform::GetOS() { return BERRY_OS; } int Platform::GetOSArch() { return BERRY_ARCH; } bool Platform::IsUnix() { #ifdef BERRY_OS_FAMILY_UNIX return true; #else return false; #endif } bool Platform::IsWindows() { #ifdef BERRY_OS_FAMILY_WINDOWS return true; #else return false; #endif } bool Platform::IsBSD() { #ifdef BERRY_OS_FAMILY_BSD return true; #else return false; #endif } bool Platform::IsLinux() { #ifdef BERRY_OS_FAMILY_LINUX return true; #else return false; #endif } bool Platform::IsVMS() { #ifdef BERRY_OS_FAMILY_VMS return true; #else return false; #endif } bool Platform::GetStatePath(QDir& statePath, const QSharedPointer& plugin, bool create) { return InternalPlatform::GetInstance()->GetStatePath(statePath, plugin, create); } QDir Platform::GetUserPath() { return InternalPlatform::GetInstance()->GetUserPath(); } QString Platform::GetProperty(const QString& key) { + if (!GetConfiguration().hasProperty(key.toStdString())) return QString::null; return QString::fromStdString(GetConfiguration().getString(key.toStdString(), "")); } bool Platform::IsRunning() { return InternalPlatform::GetInstance()->IsRunning(); } int& Platform::GetRawApplicationArgs(char**& argv) { return InternalPlatform::GetInstance()->GetRawApplicationArgs(argv); } QStringList Platform::GetApplicationArgs() { return InternalPlatform::GetInstance()->GetApplicationArgs(); } QString Platform::GetExtendedApplicationArgs() { return QString::fromStdString(InternalPlatform::GetInstance()->GetConfiguration().getString(ARG_XARGS.toStdString(), "")); } void Platform::GetOptionSet(Poco::Util::OptionSet& os) { InternalPlatform::GetInstance()->defineOptions(os); } Poco::Util::LayeredConfiguration& Platform::GetConfiguration() { return InternalPlatform::GetInstance()->GetConfiguration(); } QSharedPointer Platform::GetCTKPlugin(const QString& symbolicName) { QList > plugins = InternalPlatform::GetInstance()->GetCTKPluginFrameworkContext()->getPlugins(); foreach(QSharedPointer plugin, plugins) { if (plugin->getSymbolicName() == symbolicName) return plugin; } return QSharedPointer(0); } QSharedPointer Platform::GetCTKPlugin(long id) { return InternalPlatform::GetInstance()->GetCTKPluginFrameworkContext()->getPlugin(id); } QSharedPointer Platform::GetPlugin(const QString& symbolicName) { return InternalPlatform::GetInstance()->GetPlugin(symbolicName); } QList > Platform::GetPlugins(const QString& symbolicName, const QString& version) { return InternalPlatform::GetInstance()->GetPlugins(symbolicName, version); } +QVariant berry::Platform::GetDebugOption(const QString& option) +{ + return InternalPlatform::GetInstance()->GetOption(option); +} + +IProduct* berry::Platform::GetProduct() +{ + //TODO + //return InternalPlatform::GetDefault()->GetProduct(); + return nullptr; +} + } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatform.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatform.h index 17729b8601..c3951dc491 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatform.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatform.h @@ -1,432 +1,458 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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_Platform_INCLUDED #define BERRY_Platform_INCLUDED // // Platform Identification // #define BERRY_OS_FREE_BSD 0x0001 #define BERRY_OS_AIX 0x0002 #define BERRY_OS_HPUX 0x0003 #define BERRY_OS_TRU64 0x0004 #define BERRY_OS_LINUX 0x0005 #define BERRY_OS_MAC_OS_X 0x0006 #define BERRY_OS_NET_BSD 0x0007 #define BERRY_OS_OPEN_BSD 0x0008 #define BERRY_OS_IRIX 0x0009 #define BERRY_OS_SOLARIS 0x000a #define BERRY_OS_QNX 0x000b #define BERRY_OS_VXWORKS 0x000c #define BERRY_OS_CYGWIN 0x000d #define BERRY_OS_UNKNOWN_UNIX 0x00ff #define BERRY_OS_WINDOWS_NT 0x1001 #define BERRY_OS_WINDOWS_CE 0x1011 #define BERRY_OS_VMS 0x2001 #if defined(__FreeBSD__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS_FAMILY_BSD 1 #define BERRY_OS BERRY_OS_FREE_BSD #elif defined(_AIX) || defined(__TOS_AIX__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_AIX #elif defined(hpux) || defined(_hpux) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_HPUX #elif defined(__digital__) || defined(__osf__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_TRU64 #elif defined(linux) || defined(__linux) || defined(__linux__) || defined(__TOS_LINUX__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_LINUX #elif defined(__APPLE__) || defined(__TOS_MACOS__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS_FAMILY_BSD 1 #define BERRY_OS BERRY_OS_MAC_OS_X #elif defined(__NetBSD__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS_FAMILY_BSD 1 #define BERRY_OS BERRY_OS_NET_BSD #elif defined(__OpenBSD__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS_FAMILY_BSD 1 #define BERRY_OS BERRY_OS_OPEN_BSD #elif defined(sgi) || defined(__sgi) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_IRIX #elif defined(sun) || defined(__sun) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_SOLARIS #elif defined(__QNX__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_QNX #elif defined(unix) || defined(__unix) || defined(__unix__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_UNKNOWN_UNIX #elif defined(_WIN32_WCE) #define BERRY_OS_FAMILY_WINDOWS 1 #define BERRY_OS BERRY_OS_WINDOWS_CE #elif defined(_WIN32) || defined(_WIN64) #define BERRY_OS_FAMILY_WINDOWS 1 #define BERRY_OS BERRY_OS_WINDOWS_NT #elif defined(__CYGWIN__) #define BERRY_OS_FAMILY_UNIX 1 #define BERRY_OS BERRY_OS_CYGWIN #elif defined(__VMS) #define BERRY_OS_FAMILY_VMS 1 #define BERRY_OS BERRY_OS_VMS #endif // // Hardware Architecture and Byte Order // #define BERRY_ARCH_ALPHA 0x01 #define BERRY_ARCH_IA32 0x02 #define BERRY_ARCH_IA64 0x03 #define BERRY_ARCH_MIPS 0x04 #define BERRY_ARCH_HPPA 0x05 #define BERRY_ARCH_PPC 0x06 #define BERRY_ARCH_POWER 0x07 #define BERRY_ARCH_SPARC 0x08 #define BERRY_ARCH_AMD64 0x09 #define BERRY_ARCH_ARM 0x0a #if defined(__ALPHA) || defined(__alpha) || defined(__alpha__) || defined(_M_ALPHA) #define BERRY_ARCH BERRY_ARCH_ALPHA #define BERRY_ARCH_LITTLE_ENDIAN 1 #elif defined(i386) || defined(__i386) || defined(__i386__) || defined(_M_IX86) #define BERRY_ARCH BERRY_ARCH_IA32 #define BERRY_ARCH_LITTLE_ENDIAN 1 #elif defined(_IA64) || defined(__IA64__) || defined(__ia64__) || defined(__ia64) || defined(_M_IA64) #define BERRY_ARCH BERRY_ARCH_IA64 #if defined(hpux) || defined(_hpux) #define BERRY_ARCH_BIG_ENDIAN 1 #else #define BERRY_ARCH_LITTLE_ENDIAN 1 #endif #elif defined(__x86_64__) #define BERRY_ARCH BERRY_ARCH_AMD64 #define BERRY_ARCH_LITTLE_ENDIAN 1 #elif defined(_M_X64) #define BERRY_ARCH BERRY_ARCH_AMD64 #define BERRY_ARCH_LITTLE_ENDIAN 1 #elif defined(__mips__) || defined(__mips) || defined(__MIPS__) || defined(_M_MRX000) #define BERRY_ARCH BERRY_ARCH_MIPS #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(__hppa) || defined(__hppa__) #define BERRY_ARCH BERRY_ARCH_HPPA #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(__PPC) || defined(__POWERPC__) || defined(__powerpc) || defined(__PPC__) || \ defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC) || defined(_M_PPC) #define BERRY_ARCH BERRY_ARCH_PPC #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(_POWER) || defined(_ARCH_PWR) || defined(_ARCH_PWR2) || defined(_ARCH_PWR3) || \ defined(_ARCH_PWR4) || defined(__THW_RS6000) #define BERRY_ARCH BERRY_ARCH_POWER #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(__sparc__) || defined(__sparc) || defined(sparc) #define BERRY_ARCH BERRY_ARCH_SPARC #define BERRY_ARCH_BIG_ENDIAN 1 #elif defined(__arm__) || defined(__arm) || defined(ARM) || defined(_ARM_) || defined(__ARM__) || defined(_M_ARM) #define BERRY_ARCH BERRY_ARCH_ARM #if defined(__ARMEB__) #define BERRY_ARCH_BIG_ENDIAN 1 #else #define BERRY_ARCH_LITTLE_ENDIAN 1 #endif #endif #include #include #include #include #include class ctkPlugin; namespace Poco { class Path; } namespace berry { struct IAdapterManager; struct IBundle; struct IExtensionPointService; struct IExtensionRegistry; struct IPreferencesService; +struct IProduct; /** * The central class of the BlueBerry Platform Runtime. This class cannot * be instantiated or subclassed by clients; all functionality is provided * by static methods. Features include: *
    *
  • the platform registry of installed plug-ins
  • *
  • the platform adapter manager
  • *
  • the platform log
  • *
*

* Most users don't have to worry about Platform's lifecycle. However, if your * code can call methods of this class when Platform is not running, it becomes * necessary to check {@link #IsRunning()} before making the call. A runtime * exception might be thrown or incorrect result might be returned if a method * from this class is called while Platform is not running. *

*/ class org_blueberry_core_runtime_EXPORT Platform { public: + + static const QString PI_RUNTIME; + static int OS_FREE_BSD; static int OS_AIX; static int OS_HPUX; static int OS_TRU64; static int OS_LINUX; static int OS_MAC_OS_X; static int OS_NET_BSD; static int OS_OPEN_BSD; static int OS_IRIX; static int OS_SOLARIS; static int OS_QNX; static int OS_VXWORKS; static int OS_CYGWIN; static int OS_UNKNOWN_UNIX; static int OS_WINDOWS_NT; static int OS_WINDOWS_CE; static int OS_VMS; static int ARCH_ALPHA; static int ARCH_IA32; static int ARCH_IA64; static int ARCH_MIPS; static int ARCH_HPPA; static int ARCH_PPC; static int ARCH_POWER; static int ARCH_SPARC; static int ARCH_AMD64; static int ARCH_ARM; static QString PROP_QTPLUGIN_PATH; static QString ARG_NEWINSTANCE; static QString ARG_CLEAN; static QString ARG_APPLICATION; static QString ARG_HOME; static QString ARG_STORAGE_DIR; static QString ARG_PLUGIN_CACHE; static QString ARG_PLUGIN_DIRS; static QString ARG_FORCE_PLUGIN_INSTALL; static QString ARG_PRELOAD_LIBRARY; static QString ARG_PROVISIONING; + static QString ARG_DEBUG; static QString ARG_CONSOLELOG; static QString ARG_TESTPLUGIN; static QString ARG_TESTAPPLICATION; static QString ARG_NO_REGISTRY_CACHE; static QString ARG_NO_LAZY_REGISTRY_CACHE_LOADING; static QString ARG_REGISTRY_MULTI_LANGUAGE; static QString ARG_XARGS; /** * Returns the adapter manager used for extending * IAdaptable objects. * * @return the adapter manager for this platform * @see IAdapterManager */ static IAdapterManager* GetAdapterManager(); /** * Returns the extension registry for this platform. * May return null if the registry has not been created yet. * * @return existing extension registry or null * @see IExtensionRegistry */ static IExtensionRegistry* GetExtensionRegistry(); /** * Return the interface into the preference mechanism. The returned * object can be used for such operations as searching for preference * values across multiple scopes and preference import/export. *

* Clients are also able to acquire the IPreferencesService service via * CTK mechanisms and use it for preference functions. *

* * @return an object to interface into the preference mechanism */ static IPreferencesService* GetPreferencesService(); + /** + * Returns the product which was selected when running this BlueBerry instance + * or null if none + * @return the current product or null if none + */ + static IProduct* GetProduct(); + + /** + * Returns the identified option. A null QString + * is returned if no such option is found. Options are specified + * in the general form <plug-in id>/<option-path>. + * For example, org.blueberry.core.runtime/debug + *

+ * Clients are also able to acquire the {@link DebugOptions} service + * and query it for debug options. + *

+ * @param option the name of the option to lookup + * @return the value of the requested debug option or QString::null + */ + static QVariant GetDebugOption(const QString& option); + /** * Returns the path of the configuration information * used to run this instance of the BlueBerry platform. * The configuration area typically * contains the list of plug-ins available for use, various settings * (those shared across different instances of the same configuration) * and any other such data needed by plug-ins. * An empty path is returned if the platform is running without a configuration location. * * @return the location of the platform's configuration data area */ static QDir GetConfigurationPath(); /** * Returns the path of the base installation for the running platform * * @return the location of the platform's installation area or null if none */ static QDir GetInstallPath(); /** * Returns the path of the platform's working directory (also known as the instance data area). * An empty path is returned if the platform is running without an instance location. * * @return the location of the platform's instance data area or null if none */ static QDir GetInstancePath(); /** * Returns the path in the local file system of the * plug-in state area for the given plug-in. * If the plug-in state area did not exist prior to this call, * it is created. *

* The plug-in state area is a file directory within the * platform's metadata area where a plug-in is free to create files. * The content and structure of this area is defined by the plug-in, * and the particular plug-in is solely responsible for any files * it puts there. It is recommended for plug-in preference settings and * other configuration parameters. *

* * @param plugin the plug-in whose state location is returned * @return a local file system path * TODO Investigate the usage of a service factory */ static bool GetStatePath(QDir& statePath, const QSharedPointer& plugin, bool create = true); /** * Returns the path of the platform's user data area. The user data area is a location on the system * which is specific to the system's current user. By default it is located relative to the * location given by the System property "user.home". * An empty path is returned if the platform is running without an user location. * * @return the location of the platform's user data area or null if none */ static QDir GetUserPath(); static int GetOS(); static int GetOSArch(); static bool IsUnix(); static bool IsWindows(); static bool IsBSD(); static bool IsLinux(); static bool IsVMS(); static QString GetProperty(const QString& key); static bool IsRunning(); static Poco::Util::LayeredConfiguration& GetConfiguration(); /** * Returns the unmodified, original command line arguments * */ static int& GetRawApplicationArgs(char**& argv); /** * Returns the applications command line arguments which * have not been consumed by the platform. */ static QStringList GetApplicationArgs(); /** * Returns the "extended" command line arguments. This is * just the string given as argument to the "--xargs" option. */ static QString GetExtendedApplicationArgs(); static void GetOptionSet(Poco::Util::OptionSet &os); /** * @param symbolicName * @deprecated Use GetPlugin(const QString&) instead */ static QSharedPointer GetCTKPlugin(const QString& symbolicName); /** * @brief GetCTKPlugin * @param id * @deprecated Use GetPlugin(long) instead */ static QSharedPointer GetCTKPlugin(long id); /** * Returns the resolved plug-in with the specified symbolic name that has the * highest version. If no resolved plug-ins are installed that have the * specified symbolic name then null is returned. *

* Note that clients may want to filter * the results based on the state of the plug-ins. *

* @param symbolicName the symbolic name of the plug-in to be returned. * @return the plug-in that has the specified symbolic name with the * highest version, or null if no plug-in is found. */ static QSharedPointer GetPlugin(const QString& symbolicName); /** * Returns all plug-ins with the specified symbolic name. If no resolved plug-ins * with the specified symbolic name can be found, an empty list is returned. * If the version argument is not null then only the plug-ins that have * the specified symbolic name and a version greater than or equal to the * specified version are returned. The returned plug-ins are ordered in * descending plug-in version order. *

* Note that clients may want to filter * the results based on the state of the plug-ins. *

* @param symbolicName the symbolic name of the plug-ins that are to be returned. * @param version the version that the returned plug-in versions must match, * or QString() if no version matching is to be done. * @return the list of plug-ins with the specified name that match the * specified version and match rule, or null if no plug-ins are found. */ static QList > GetPlugins(const QString& symbolicName, const QString& version = QString()); private: Platform(); }; } // namespace #endif // BERRY_Platform_INCLUDED diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.cpp index 459d37d793..b6983a0ab1 100755 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.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 "berryPlatformObject.h" #include "berryPlatform.h" #include "berryIAdapterManager.h" namespace berry { PlatformObject::PlatformObject() { } -Object* PlatformObject::GetAdapter(const QString& adapter) +Object* PlatformObject::GetAdapter(const QString& adapter) const { IAdapterManager* adapterManager = Platform::GetAdapterManager(); if (adapterManager) { return adapterManager->GetAdapter(this, adapter); } else { 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 ceaeb41b66..8ffc870a5d 100755 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.h @@ -1,84 +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 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 virtual Object, public IAdaptable { +class org_blueberry_core_runtime_EXPORT PlatformObject : public virtual Object, public virtual IAdaptable +{ public: - berryObjectMacro(berry::PlatformObject); + 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 */ - Object* GetAdapter(const QString& adapter); + Object* GetAdapter(const QString& adapter) const; }; } #endif /* BERRYPLATFORMOBJECT_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryReflection.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryReflection.cpp new file mode 100644 index 0000000000..ed6db9c471 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryReflection.cpp @@ -0,0 +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 "berryReflection.h" + +#include "berryObject.h" + +// 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 { + +namespace Reflection { + +QString 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) + { + QString unmangledName(unmangled); + name = unmangledName.split(' ', QString::SkipEmptyParts).back(); + free(unmangled); + } +#else + name = name.split(' ', QString::SkipEmptyParts).back(); +#endif + return name; +} + +#ifdef GetClassName +// clash with WinUser.h definition +#undef GetClassName +#endif + +QString GetClassName(const Object* obj) +{ + return DemangleName(typeid(*const_cast(obj)).name()); +} + +TypeInfo::Concept::~Concept(){} + +template<> +struct TypeInfo::Model : Concept { + QString GetName() const { return QString(); } + QList GetSuperclasses() const { return QList(); } +}; + +TypeInfo::TypeInfo() + : m_Self(std::make_shared >()) +{ +} + +bool TypeInfo::operator==(const TypeInfo& other) const +{ + return this->GetName() == other.GetName(); +} + +QString TypeInfo::GetName() const +{ + return m_Self->GetName(); +} + +QList TypeInfo::GetSuperclasses() const +{ + return m_Self->GetSuperclasses(); +} + +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryReflection.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryReflection.h new file mode 100644 index 0000000000..94723ac4ba --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryReflection.h @@ -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. + +===================================================================*/ + +#ifndef BERRYREFLECTION_H +#define BERRYREFLECTION_H + +#include + +#include +#include + +#include +#include + +#ifdef GetClassName +// clash with WinUser.h definition +#undef GetClassName +#endif + +namespace berry { + +class Object; + +namespace Reflection { + +org_blueberry_core_runtime_EXPORT QString DemangleName(const char* typeName); + +org_blueberry_core_runtime_EXPORT QString GetClassName(const Object* obj); + +template +QString GetClassName() +{ + return DemangleName(typeid(T).name()); +} + +class TypeInfo; + +template +QList GetSuperclasses(); + +struct EmptyType {}; + +template< + typename T0=EmptyType, + typename T1=EmptyType, + typename T2=EmptyType, + typename T3=EmptyType, + typename T4=EmptyType, + typename T5=EmptyType, + typename T6=EmptyType, + typename T7=EmptyType, + typename T8=EmptyType, + typename T9=EmptyType +> struct TypeList; + +template< + typename T0, + typename T1, + typename T2, + typename T3, + typename T4, + typename T5, + typename T6, + typename T7, + typename T8, + typename T9 +> struct TypeList +{ + typedef T0 head; + typedef TypeList tail; + enum + { + length = tail::length+1 + }; +}; + +template<> +struct TypeList +{ + enum + { + length = 0 + }; +}; + +// MapReduce +template< + typename TL, + template class Map, + template class Reduce +> +struct MapReduce +{ + typedef typename Map::type map_type; + typedef typename Reduce::result type; + + static type& value(type& result) + { + return MapReduce::value(Reduce::value(result, Map::value())); + } + + static type value() + { + type result; + return MapReduce::value(Reduce::value(result, Map::value())); + } +}; + +template< + template class Map, + template class Reduce +> +struct MapReduce, Map, Reduce> +{ + typedef typename Map::type map_type; + typedef typename Reduce::result type; + + static type value() + { + return type(); + } + + static type& value(type& result) + { + return result; + } +}; + +class org_blueberry_core_runtime_EXPORT TypeInfo +{ +public: + + TypeInfo(); + + template + explicit TypeInfo(T* /*dummy*/) + : m_Self(std::make_shared >()) + {} + + bool operator==(const TypeInfo& other) const; + + template + static TypeInfo New() + { T* dummy = nullptr; return TypeInfo(dummy); } + + QString GetName() const; + QList GetSuperclasses() const; + + +private: + + struct org_blueberry_core_runtime_EXPORT Concept { + virtual ~Concept(); + virtual QString GetName() const = 0; + virtual QList GetSuperclasses() const = 0; + }; + + template + struct Model : Concept { + QString GetName() const + { return GetClassName(); } + + QList GetSuperclasses() const; + }; + + std::shared_ptr m_Self; +}; + +template +struct MapToTypeInfo +{ + typedef TypeInfo type; + static type value() + { + return TypeInfo::New(); + } +}; + +template +struct ReduceToList +{ + typedef T type; + typedef QList result; + static result& value(result& list, const type& item) + { + list.push_back(item); + return list; + } +}; + +template +class HasTypeSuperclass +{ + typedef char Small; + struct Big { char dummy[2]; }; + + template static Small Test(typename U::SuperclassTypes*); + template static Big Test(...); +public: + enum { value = sizeof(Test(NULL)) == sizeof(Small) }; +}; + +template +struct GetSuperclassTypeList { typedef TypeList<> value; }; + +template +struct GetSuperclassTypeList { typedef typename T::SuperclassTypes value; }; + +template +QList GetSuperclasses() +{ + return MapReduce::value>::value, MapToTypeInfo, ReduceToList>::value(); +} + +template +QList TypeInfo::Model::GetSuperclasses() const +{ + return ::berry::Reflection::GetSuperclasses(); +} + +} // end namespace Reflection + +} // end namespace berry + +#endif // BERRYREFLECTION_H + diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berrySmartPointer.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berrySmartPointer.h index 1bd6883d49..fcc266124f 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berrySmartPointer.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/berrySmartPointer.h @@ -1,435 +1,443 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYSMARTPOINTER_H_ #define BERRYSMARTPOINTER_H_ #include #include #include #include +#include + #if defined(BLUEBERRY_DEBUG_SMARTPOINTER) #include #endif namespace berry { template class WeakPointer; /** \class SmartPointer * \brief Implements transparent reference counting. * * SmartPointer is a copy of itk::SmartPointer. * It implements reference counting by overloading * operator -> (and *) among others. This allows natural interface * to the class referred to by the pointer without having to invoke * special Register()/UnRegister() methods directly. * */ template class SmartPointer { public: typedef TObjectType ObjectType; typedef SmartPointer Self; /** Constructor */ SmartPointer() : m_Pointer(0) { #if defined(BLUEBERRY_DEBUG_SMARTPOINTER) DebugInitSmartPointer(); #endif } /** Constructor to pointer p */ explicit SmartPointer(ObjectType *p) : m_Pointer(p) { if (m_Pointer) this->Register(); #if defined(BLUEBERRY_DEBUG_SMARTPOINTER) DebugInitSmartPointer(); #endif } /** Copy constructor */ SmartPointer(const SmartPointer &p) : m_Pointer(p.m_Pointer) { this->Register(); #if defined(BLUEBERRY_DEBUG_SMARTPOINTER) DebugInitSmartPointer(); #endif } template SmartPointer(const SmartPointer& ptr) : m_Pointer(const_cast (ptr.GetPointer())) { if (m_Pointer) this->Register(); #if defined(BLUEBERRY_DEBUG_SMARTPOINTER) DebugInitSmartPointer(); #endif } template explicit SmartPointer(const WeakPointer& wp); /** Destructor */ ~SmartPointer() { #if defined(BLUEBERRY_DEBUG_SMARTPOINTER) if (m_Pointer) DebugRemoveSmartPointer(); #endif this->UnRegister(); m_Pointer = 0; } template SmartPointer Cast() const { Other* pOther = dynamic_cast (m_Pointer); return SmartPointer (pOther); } /** Overload operator -> */ ObjectType *operator ->() const { return m_Pointer; } // /** Return pointer to object. */ // operator ObjectType *() const // { // return m_Pointer; // } ObjectType & operator*() const { poco_assert( m_Pointer != 0 ); return *m_Pointer; } /** Test if the pointer has been initialized */ bool IsNotNull() const { return m_Pointer != 0; } bool IsNull() const { return m_Pointer == 0; } typedef ObjectType * Self::*unspecified_bool_type; operator unspecified_bool_type () const { return m_Pointer == 0 ? 0: &Self::m_Pointer; } /** Template comparison operators. */ template bool operator ==(const R* o) const { return (m_Pointer == 0 ? o == 0 : (o && m_Pointer->operator==(o))); } template bool operator ==(const SmartPointer& r) const { const R* o = r.GetPointer(); return (m_Pointer == 0 ? o == 0 : (o && m_Pointer->operator==(o))); } bool operator ==(int r) const { if (r == 0) return m_Pointer == 0; throw std::invalid_argument("Can only compare to 0"); } template bool operator !=(const R* r) const { return !(this->operator==(r)); } template bool operator !=(const SmartPointer& r) const { return !(this->operator==(r)); } bool operator !=(int r) const { if (r == 0) return m_Pointer != 0; throw std::invalid_argument("Can only compare to 0"); } // /** Template comparison operators using operator==. */ // template // bool CompareTo(const SmartPointer& r) const // { // return m_Pointer == 0 ? r == 0 : r.GetPointer() && m_Pointer->operator==(r.GetPointer()); // } // template // bool CompareTo(R r) const // { // //const ObjectType* o = static_cast (r); // return m_Pointer == 0 ? r == 0 : (r && m_Pointer->operator==(r)); // } /** Access function to pointer. */ ObjectType *GetPointer() const { return m_Pointer; } /** Comparison of pointers. Less than comparison. */ - bool operator <(const SmartPointer &r) const + template + bool operator <(const SmartPointer& r) const { - return (void*) m_Pointer < (void*) r.m_Pointer; + const R* o = r.GetPointer(); + return m_Pointer == 0 ? o == 0 : o && m_Pointer->operator<(o); } /** Comparison of pointers. Greater than comparison. */ - bool operator>(const SmartPointer &r) const + template + bool operator>(const SmartPointer& r) const { - return (void*) m_Pointer > (void*) r.m_Pointer; + const R* o = r.GetPointer(); + return m_Pointer == 0 ? o == 0 : o && m_Pointer->operator>(o); } /** Comparison of pointers. Less than or equal to comparison. */ - bool operator <=(const SmartPointer &r) const + template + bool operator <=(const SmartPointer& r) const { - return (void*) m_Pointer <= (void*) r.m_Pointer; + return this->operator<(r) || this->operator==(r); } /** Comparison of pointers. Greater than or equal to comparison. */ - bool operator >=(const SmartPointer &r) const + template + bool operator >=(const SmartPointer& r) const { - return (void*) m_Pointer >= (void*) r.m_Pointer; + return this->operator>(r) || this->operator==(r); } /** Overload operator assignment. */ SmartPointer &operator =(const SmartPointer &r) { return this->operator =(r.GetPointer()); } /** Overload operator assignment. */ template SmartPointer &operator =(const SmartPointer& r) { return this->operator =(r.GetPointer()); } /** Overload operator assignment. */ SmartPointer &operator =(ObjectType *r) { if (m_Pointer != r) { #if defined(BLUEBERRY_DEBUG_SMARTPOINTER) DebugAssignSmartPointer(r, m_Pointer); #endif ObjectType* tmp = m_Pointer; //avoid recursive unregisters by retaining temporarily m_Pointer = r; this->Register(); if (tmp) { tmp->UnRegister(); } } return *this; } /** Function to print object pointed to */ QDebug Print(QDebug os) const; private: /** The pointer to the object referred to by this smart pointer. */ ObjectType* m_Pointer; void Register() { if (m_Pointer) { m_Pointer->Register(); } } void UnRegister() { if (m_Pointer) { m_Pointer->UnRegister(); } } #if defined(BLUEBERRY_DEBUG_SMARTPOINTER) unsigned int m_Id; QMutex m_Mutex; void DebugInitSmartPointer(); void DebugRemoveSmartPointer(); void DebugAssignSmartPointer(const ObjectType* newObject, const ObjectType* oldObject); public: int GetId(); private: #endif }; template std::ostream& operator<<(std::ostream& os, const SmartPointer& p) { os << p->ToString().toStdString(); return os; } } // namespace berry template uint qHash(const berry::SmartPointer& sp) { return sp->HashCode(); } template uint qHash(const berry::WeakPointer& wp) { berry::SmartPointer sp(wp.Lock()); if (sp.IsNull()) { return 0; } return sp->HashCode(); } #include "berryException.h" #include namespace berry { template template SmartPointer::SmartPointer(const WeakPointer& wp) { if (wp.m_Pointer) { this->m_Pointer = wp.m_Pointer; this->Register(); #if defined(BLUEBERRY_DEBUG_SMARTPOINTER) DebugInitSmartPointer(); #endif } else { throw BadWeakPointerException("Weak pointer is NULL"); } } /** Function to print object pointed to */ template QDebug SmartPointer::Print(QDebug os) const { // This prints the object pointed to by the pointer (*m_Pointer).Print(os); return os; } } #if defined(BLUEBERRY_DEBUG_SMARTPOINTER) #include "berryDebugUtil.h" namespace berry { template void SmartPointer::DebugInitSmartPointer() { { QMutexLocker lock(&m_Mutex); if (m_Pointer) { unsigned int& counter = DebugUtil::GetSmartPointerCounter(); m_Id = ++counter; DebugUtil::RegisterSmartPointer(m_Id, m_Pointer); } else m_Id = 0; } //if (DebugUtil::GetSmartPointerCounter() == Platform::GetConfiguration().getInt(Platform::DEBUG_ARG_SMARTPOINTER_ID)) //throw 1; } template void SmartPointer::DebugRemoveSmartPointer() { QMutexLocker lock(&m_Mutex); DebugUtil::UnregisterSmartPointer(m_Id, m_Pointer); } template void SmartPointer::DebugAssignSmartPointer(const ObjectType* newObject, const ObjectType* oldObject) { QMutexLocker lock(&m_Mutex); if (oldObject) DebugUtil::UnregisterSmartPointer(m_Id, oldObject); if (newObject) { if (m_Id < 1) { unsigned int& counter = DebugUtil::GetSmartPointerCounter(); m_Id = ++counter; } DebugUtil::RegisterSmartPointer(m_Id, newObject); } } template int SmartPointer::GetId() { return m_Id; } } #endif #endif /*BERRYSMARTPOINTER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/debug/berryDebugOptionsListener.cpp similarity index 85% copy from BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp copy to BlueBerry/Bundles/org.blueberry.core.runtime/src/debug/berryDebugOptionsListener.cpp index 3b9d740123..152bf5bccc 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/debug/berryDebugOptionsListener.cpp @@ -1,25 +1,25 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryIBerryPreferences.h" +#include "berryDebugOptionsListener.h" namespace berry { -IBerryPreferences::~IBerryPreferences () +DebugOptionsListener::~DebugOptionsListener() { } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/debug/berryDebugOptionsListener.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/debug/berryDebugOptionsListener.h new file mode 100644 index 0000000000..5c67ce6ff3 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/debug/berryDebugOptionsListener.h @@ -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. + +===================================================================*/ + +#ifndef BERRYDEBUGOPTIONSLISTENER_H +#define BERRYDEBUGOPTIONSLISTENER_H + +#include + +#include + +namespace berry { + +class DebugOptions; + +/** + * A debug options listener is notified whenever one of its plug-in option-path entries is + * changed. A listener is registered as a service using the DebugOptions#LISTENER_SYMBOLICNAME + * service property to specify the symbolic name of the debug options listener. + *

+ * The DebugOptionsListener#OptionsChanged(const DebugOptions&) method will automatically + * be called upon registration of the debug options listener service. This allows the + * listener to obtain the initial debug options. This initial call to the listener + * will happen even if debug is not enabled at the time of registration + * DebugOptions#IsDebugEnabled() will return false in this case). + *

+ * A debug options listener allows a plug-in to cache trace option values in boolean fields for performance + * and code cleanliness. For example: + *
+ * class Activator : ctkPluginActivator, DebugOptionsListener
+ * {
+ *   static bool DEBUG = false;
+ *
+ *   void Start(ctkPluginContext* context)
+ *   {
+ *     ctkDictionary props;
+ *     props.insert(DebugOptions::LISTENER_SYMBOLICNAME, "com.mycompany.mybundle");
+ *     context->registerService(this, props);
+ *   }
+ *
+ *   void OptionsChanged(const DebugOptions& options)
+ *   {
+ *     DEBUG = options->GetBooleanOption("com.mycompany.mybundle/debug", false);
+ *   }
+ *
+ *   void DoSomeWork()
+ *   {
+ *     if (DEBUG) BERRY_INFO << "foo";
+ *   }
+ *   ...
+ * }
+ * 
+ */ +struct org_blueberry_core_runtime_EXPORT DebugOptionsListener +{ + virtual ~DebugOptionsListener(); + + /** + * Notifies this listener that an option-path for its plug-in has changed. + * This method is also called initially by the DebugOptions implementation + * when the listener is registered as a service. This allows the listener + * to obtain the initial set of debug options without the need to + * acquire the debug options service. + * @param options a reference to the DebugOptions + */ + virtual void OptionsChanged(const DebugOptions& options) = 0; +}; + +} + +Q_DECLARE_INTERFACE(berry::DebugOptionsListener, "org.blueberry.DebugOptionsListener") + +#endif // BERRYDEBUGOPTIONSLISTENER_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/debug/berryIDebugOptions.cpp similarity index 77% copy from BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp copy to BlueBerry/Bundles/org.blueberry.core.runtime/src/debug/berryIDebugOptions.cpp index 3b9d740123..07a8387355 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/debug/berryIDebugOptions.cpp @@ -1,25 +1,27 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryIBerryPreferences.h" +#include "berryIDebugOptions.h" namespace berry { -IBerryPreferences::~IBerryPreferences () +const QString IDebugOptions::LISTENER_SYMBOLICNAME = "listener.symbolic.name"; + +IDebugOptions::~IDebugOptions() { } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/debug/berryIDebugOptions.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/debug/berryIDebugOptions.h new file mode 100644 index 0000000000..8e55c6ec83 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/debug/berryIDebugOptions.h @@ -0,0 +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 BERRYIDEBUGOPTIONS_H +#define BERRYIDEBUGOPTIONS_H + +#include + +#include +#include +#include + +namespace berry { + +/** + * Used to get debug options settings. + */ +struct org_blueberry_core_runtime_EXPORT IDebugOptions +{ + + virtual ~IDebugOptions(); + + /** + * The service property (named "listener.symbolic.name") which specifies + * the bundle symbolic name of a {@link DebugOptionsListener} service. + */ + static const QString LISTENER_SYMBOLICNAME; // = "listener.symbolic.name"; + + /** + * Returns the identified option as a boolean value. The specified + * defaultValue is returned if no such option is found or if debug is not enabled. + * + *

+ * Options are specified in the general form <Plugin-SymbolicName>/<option-path>. + * For example, org.blueberry.core.runtime/debug + *

+ * + * @param option the name of the option to lookup + * @param defaultValue the value to return if no such option is found + * @return the value of the requested debug option or the + * defaultValue if no such option is found. + */ + virtual bool GetBooleanOption(const QString& option, bool defaultValue) const = 0; + + /** + * Returns the identified option. A null value + * is returned if no such option is found or if debug is not enabled. + * + *

+ * Options are specified + * in the general form <Plugin-SymbolicName>/<option-path>. + * For example, org.blueberry.core.runtime/debug + *

+ * + * @param option the name of the option to lookup + * @return the value of the requested debug option or null + */ + virtual QVariant GetOption(const QString& option) const = 0; + + /** + * Returns the identified option. The specified defaultValue is + * returned if no such option is found or if debug is not enabled. + * + *

+ * Options are specified + * in the general form <Plugin-SymbolicName>/<option-path>. + * For example, org.blueberry.core.runtime/debug + *

+ * + * @param option the name of the option to lookup + * @param defaultValue the value to return if no such option is found + * @return the value of the requested debug option or the + * defaultValue if no such option is found. + */ + virtual QVariant GetOption(const QString& option, const QVariant& defaultValue) const = 0; + + /** + * Returns the identified option as an int value. The specified + * defaultValue is returned if no such option is found or if an + * error occurs while converting the option value + * to an integer or if debug is not enabled. + * + *

+ * Options are specified + * in the general form <Plugin-SymbolicName>/<option-path>. + * For example, org.blueberry.core.runtime/debug + *

+ * + * @param option the name of the option to lookup + * @param defaultValue the value to return if no such option is found + * @return the value of the requested debug option or the + * defaultValue if no such option is found. + */ + virtual int GetIntegerOption(const QString& option, int defaultValue) const = 0; + + /** + * Returns a snapshot of the current options. All + * keys and values are of type string. If no + * options are set then an empty map is returned. + *

+ * If debug is not enabled then the snapshot of the current disabled + * values is returned. See SetDebugEnabled(bool). + *

+ * @return a snapshot of the current options. + */ + virtual QHash GetOptions() const = 0; + + /** + * Sets the identified option to the identified value. If debug is + * not enabled then the specified option is not changed. + * @param option the name of the option to set + * @param value the value of the option to set + */ + virtual void SetOption(const QString& option, const QVariant& value) = 0; + + /** + * Sets the current option key/value pairs to the specified options. + * The specified map replaces all keys and values of the current debug options. + *

+ * If debug is not enabled then the specified options are saved as + * the disabled values and no notifications will be sent. + * See SetDebugEnabled(bool). + * If debug is enabled then notifications will be sent to the + * listeners which have options that have been changed, added or removed. + *

+ * + * @param options the new set of options + */ + virtual void SetOptions(const QHash& ops) = 0; + + /** + * Removes the identified option. If debug is not enabled then + * the specified option is not removed. + * @param option the name of the option to remove + */ + virtual void RemoveOption(const QString& option) = 0; + + /** + * Returns true if debugging/tracing is currently enabled. + * @return true if debugging/tracing is currently enabled; Otherwise false is returned. + */ + virtual bool IsDebugEnabled() const = 0; + + /** + * Enables or disables debugging/tracing. + *

+ * When debug is disabled all debug options are unset. + * When disabling debug the current debug option values are + * stored in memory as disabled values. If debug is re-enabled the + * disabled values will be set back and enabled. The disabled values + * are only stored in memory and if the framework is restarted then + * the disabled option values will be lost. + *

+ * @param value If true, debug is enabled, otherwise + * debug is disabled. + */ + virtual void SetDebugEnabled(bool enabled) = 0; + +}; + +} + +Q_DECLARE_INTERFACE(berry::IDebugOptions, "org.blueberry.IDebugOptions") + +#endif // BERRYIDEBUGOPTIONS_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryExtensionTracker.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryExtensionTracker.cpp new file mode 100644 index 0000000000..3f27628960 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryExtensionTracker.cpp @@ -0,0 +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 "berryExtensionTracker.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include "internal/berrySimpleExtensionPointFilter.h" +#include + +#include +#include +#include + +namespace berry { + +struct ExtensionTracker::Impl +{ + struct HandlerWrapper; + + ExtensionTracker* const q; + QHash > extensionToStrongObjects; + QHash > extensionToWeakObjects; + //ListenerList handlers; + QHash handlerToWrapper; + QMutex mutex; + bool closed; + IExtensionRegistry* registry; // the registry that this tacker works with + + Impl(ExtensionTracker* q, IExtensionRegistry* theRegistry) + : q(q) + , closed(false) + , registry(theRegistry) + {} + +}; + +struct ExtensionTracker::Impl::HandlerWrapper : public IRegistryEventListener +{ + ExtensionTracker* const q; + IExtensionChangeHandler* const handler; + + HandlerWrapper(ExtensionTracker* q, IExtensionChangeHandler* handler) + : q(q) + , handler(handler) + {} + + bool operator==(const HandlerWrapper& target) const + { + return handler == target.handler; + } + + virtual void Added(const QList& extensions) + { + for (int i = 0; i < extensions.size(); ++i) + { + q->ApplyAdd(handler, extensions[i]); + } + } + + virtual void Removed(const QList& extensions) + { + QList > removedObjects; + { + QMutexLocker lock(&q->d->mutex); + for (int i = 0; i < extensions.size(); ++i) + { + QSet associatedObjects = q->d->extensionToStrongObjects.take(extensions[i]); + foreach(const Object::WeakPtr& ptr, q->d->extensionToWeakObjects.take(extensions[i])) + { + if (!ptr.Expired()) + { + associatedObjects.insert(ptr.Lock()); + } + } + removedObjects.push_back(associatedObjects.toList()); + } + } + for (int i = 0; i < extensions.size(); ++i) + { + q->ApplyRemove(handler, extensions[i], removedObjects[i]); + } + } + + virtual void Added(const QList& /*extensionPoints*/) + { + // do nothing + } + + virtual void Removed(const QList& /*extensionPoints*/) + { + // do nothing + } +}; + +ExtensionTracker::ExtensionTracker() +{ + this->Init(Platform::GetExtensionRegistry()); +} + +ExtensionTracker::~ExtensionTracker() +{ +} + +ExtensionTracker::ExtensionTracker(IExtensionRegistry* theRegistry) + : d() +{ + this->Init(theRegistry); +} + +void ExtensionTracker::Init(IExtensionRegistry* registry) +{ + d.reset(new Impl(this, registry)); + if (registry == nullptr) + { + //RuntimeLog.log(new Status(IStatus.ERROR, RegistryMessages.OWNER_NAME, 0, RegistryMessages.registry_no_default, null)); + BERRY_ERROR << "Extension tracker was unable to obtain BlueBerry extension registry."; + d->closed = true; + } +} + +void ExtensionTracker::RegisterHandler(IExtensionChangeHandler* handler, const IExtensionPointFilter& filter) +{ + QMutexLocker lock(&d->mutex); + if (d->closed) return; + auto iter = d->handlerToWrapper.insert(handler, new Impl::HandlerWrapper(this, handler)); + d->registry->AddListener(iter.value(), filter); +} + +void ExtensionTracker::RegisterHandler(IExtensionChangeHandler* handler, const QString& extensionPointId) +{ + this->RegisterHandler(handler, extensionPointId.isEmpty() ? IExtensionPointFilter(nullptr) + : IExtensionPointFilter(new SimpleExtensionPointFilter(extensionPointId))); +} + +void ExtensionTracker::UnregisterHandler(IExtensionChangeHandler* handler) +{ + QMutexLocker lock(&d->mutex); + if (d->closed) return; + IRegistryEventListener* listener = d->handlerToWrapper.take(handler); + d->registry->RemoveListener(listener); + delete listener; +} + +void ExtensionTracker::RegisterObject(const SmartPointer& element, const SmartPointer& object, IExtensionTracker::ReferenceType referenceType) +{ + if (element.IsNull() || object.IsNull()) return; + + QMutexLocker lock(&d->mutex); + if (d->closed) return; + + if (referenceType == REF_STRONG) + { + d->extensionToStrongObjects[element].insert(object); + } + else if (referenceType == REF_WEAK) + { + d->extensionToWeakObjects[element].insert(Object::WeakPtr(object)); + } +} + +QList > ExtensionTracker::GetObjects(const IExtension::Pointer& element) const +{ + QSet objectSet; + + QMutexLocker lock(&d->mutex); + if (d->closed) return objectSet.toList(); + + auto iter = d->extensionToStrongObjects.find(element); + if (iter != d->extensionToStrongObjects.end()) + { + objectSet.unite(iter.value()); + } + auto iter2 = d->extensionToWeakObjects.find(element); + if (iter2 != d->extensionToWeakObjects.end()) + { + foreach(const Object::WeakPtr& ptr, iter2.value()) + { + if (!ptr.Expired()) objectSet.insert(ptr.Lock()); + } + } + return objectSet.toList(); +} + +void ExtensionTracker::Close() +{ + QMutexLocker lock(&d->mutex); + if (d->closed) return; + foreach(Impl::HandlerWrapper* wrapper, d->handlerToWrapper.values()) + { + d->registry->RemoveListener(wrapper); + delete wrapper; + } + d->extensionToStrongObjects.clear(); + d->extensionToWeakObjects.clear(); + d->handlerToWrapper.clear(); + + d->closed = true; +} + +void ExtensionTracker::UnregisterObject(const SmartPointer& extension, const SmartPointer& object) +{ + QMutexLocker lock(&d->mutex); + if (d->closed) return; + + auto iter = d->extensionToStrongObjects.find(extension); + if (iter != d->extensionToStrongObjects.end()) + { + iter.value().remove(object); + } + auto iter2 = d->extensionToWeakObjects.find(extension); + if (iter2 != d->extensionToWeakObjects.end()) + { + iter2.value().remove(Object::WeakPtr(object)); + } +} + +QList > ExtensionTracker::UnregisterObject(const SmartPointer& extension) +{ + QSet objectSet; + + QMutexLocker lock(&d->mutex); + if (d->closed) return objectSet.toList(); + + auto iter = d->extensionToStrongObjects.find(extension); + if (iter != d->extensionToStrongObjects.end()) + { + objectSet.unite(iter.value()); + d->extensionToStrongObjects.erase(iter); + } + auto iter2 = d->extensionToWeakObjects.find(extension); + if (iter2 != d->extensionToWeakObjects.end()) + { + foreach(const Object::WeakPtr& ptr, iter2.value()) + { + if (!ptr.Expired()) objectSet.insert(ptr.Lock()); + } + d->extensionToWeakObjects.erase(iter2); + } + + return objectSet.toList(); +} + +IExtensionPointFilter ExtensionTracker::CreateExtensionPointFilter(const SmartPointer& xpt) +{ + struct F : IExtensionPointFilter::Concept { + const IExtensionPoint::Pointer m_Xpt; + + F(const IExtensionPoint::Pointer& xp) + : m_Xpt(xp) + {} + + bool Matches(const IExtensionPoint* target) const + { + return m_Xpt == target; + } + }; + + return IExtensionPointFilter(new F(xpt)); +} + +IExtensionPointFilter ExtensionTracker::CreateExtensionPointFilter(const QList >& xpts) +{ + struct F : IExtensionPointFilter::Concept { + const QList m_Xpts; + + F(const QList& xps) + : m_Xpts(xps) + {} + + bool Matches(const IExtensionPoint* target) const + { + for (int i = 0; i < m_Xpts.size(); i++) + { + if (m_Xpts[i] == target) + { + return true; + } + } + return false; + } + }; + + return IExtensionPointFilter(new F(xpts)); +} + +IExtensionPointFilter ExtensionTracker::CreateNamespaceFilter(const QString& id) +{ + struct F : IExtensionPointFilter::Concept { + const QString m_Id; + + F(const QString& id) + : m_Id(id) + {} + + bool Matches(const IExtensionPoint* target) const + { + return m_Id == target->GetNamespaceIdentifier(); + } + }; + + return IExtensionPointFilter(new F(id)); +} + +void ExtensionTracker::ApplyAdd(IExtensionChangeHandler* handler, const SmartPointer& extension) +{ + handler->AddExtension(this, extension); +} + +void ExtensionTracker::ApplyRemove(IExtensionChangeHandler* handler, const SmartPointer& removedExtension, const QList& removedObjects) +{ + handler->RemoveExtension(removedExtension, removedObjects); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryExtensionTracker.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryExtensionTracker.h new file mode 100644 index 0000000000..554621844e --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryExtensionTracker.h @@ -0,0 +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 BERRYEXTENSIONTRACKER_H +#define BERRYEXTENSIONTRACKER_H + +#include + +namespace berry { + +struct IExtension; +struct IExtensionPoint; +struct IExtensionRegistry; +struct IExtensionPointFilter; + +/** + * Implementation of the IExtensionTracker. + * + * @see IExtensionTracker + */ +class org_blueberry_core_runtime_EXPORT ExtensionTracker : public IExtensionTracker +{ + struct Impl; + QScopedPointer d; + +public: + + ExtensionTracker(); + ~ExtensionTracker(); + + /** + * Construct a new instance of the extension tracker using the given registry + * containing tracked extensions and extension points. + * + * @param theRegistry the extension registry to track + */ + ExtensionTracker(IExtensionRegistry* theRegistry); + + void RegisterHandler(IExtensionChangeHandler* handler, const IExtensionPointFilter& filter); + + void RegisterHandler(IExtensionChangeHandler* handler, const QString& extensionPointId); + + void UnregisterHandler(IExtensionChangeHandler* handler); + + void RegisterObject(const SmartPointer& element, + const SmartPointer& object, ReferenceType referenceType); + + QList > GetObjects(const SmartPointer& element) const; + + void Close(); + + void UnregisterObject(const SmartPointer& extension, const SmartPointer& object); + + QList > UnregisterObject(const SmartPointer& extension); + + /** + * Return an instance of filter matching all changes for the given extension point. + * + * @param xpt the extension point + * @return a filter + */ + static IExtensionPointFilter CreateExtensionPointFilter(const SmartPointer& xpt); + + /** + * Return an instance of filter matching all changes for the given extension points. + * + * @param xpts the extension points used to filter + * @return a filter + */ + static IExtensionPointFilter CreateExtensionPointFilter(const QList >& xpts); + + /** + * Return an instance of filter matching all changes from a given plugin. + * + * @param id the plugin id + * @return a filter + */ + static IExtensionPointFilter CreateNamespaceFilter(const QString& id); + + +protected: + + virtual void ApplyAdd(IExtensionChangeHandler* handler, const SmartPointer& extension); + + virtual void ApplyRemove(IExtensionChangeHandler* handler, const SmartPointer& removedExtension, + const QList >& removedObjects); + +private: + + void Init(IExtensionRegistry* registry); +}; + +} + +#endif // BERRYEXTENSIONTRACKER_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryIExtensionChangeHandler.cpp similarity index 84% copy from BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp copy to BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryIExtensionChangeHandler.cpp index 3b9d740123..732ac81e08 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryIExtensionChangeHandler.cpp @@ -1,25 +1,25 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryIBerryPreferences.h" +#include "berryIExtensionChangeHandler.h" namespace berry { -IBerryPreferences::~IBerryPreferences () +IExtensionChangeHandler::~IExtensionChangeHandler() { } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryIExtensionChangeHandler.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryIExtensionChangeHandler.h new file mode 100644 index 0000000000..b94d466d6c --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryIExtensionChangeHandler.h @@ -0,0 +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 BERRYIEXTENSIONCHANGEHANDLER_H +#define BERRYIEXTENSIONCHANGEHANDLER_H + +#include + +#include + +namespace berry { + +struct IExtension; +struct IExtensionTracker; + +class Object; + +/** + * Extension change handlers are notified of changes for a given extension + * point in the context of an extension tracker. + *

+ * This interface can be used without OSGi running. + *

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

+ */ +struct org_blueberry_core_runtime_EXPORT IExtensionChangeHandler +{ + virtual ~IExtensionChangeHandler(); + + /** + * This method is called whenever an extension conforming to the extension point filter + * is being added to the registry. This method does not automatically register objects + * to the tracker. + * + * @param tracker a tracker to which the handler has been registered + * @param extension the extension being added + */ + virtual void AddExtension(IExtensionTracker* tracker, const SmartPointer& extension) = 0; + + /** + * This method is called after the removal of an extension. + * + * @param extension the extension being removed + * @param objects the objects that were associated with the removed extension + */ + virtual void RemoveExtension(const SmartPointer& extension, + const QList >& objects) = 0; +}; + + +} + +#endif // BERRYIEXTENSIONCHANGEHANDLER_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryIExtensionTracker.cpp similarity index 86% copy from BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp copy to BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryIExtensionTracker.cpp index 3b9d740123..7338e32890 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryIExtensionTracker.cpp @@ -1,25 +1,25 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryIBerryPreferences.h" +#include "berryIExtensionTracker.h" namespace berry { -IBerryPreferences::~IBerryPreferences () +IExtensionTracker::~IExtensionTracker() { } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryIExtensionTracker.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryIExtensionTracker.h new file mode 100644 index 0000000000..9de3b7068c --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/dynamichelpers/berryIExtensionTracker.h @@ -0,0 +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. + +===================================================================*//*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#ifndef BERRYIEXTENSIONTRACKER_H +#define BERRYIEXTENSIONTRACKER_H + +#include + +#include "berrySmartPointer.h" + +#include + +namespace berry { + +struct IExtension; +struct IExtensionChangeHandler; +struct IExtensionPointFilter; + +class Object; + +/** + * An extension tracker keeps associations between extensions and their derived + * objects on an extension basis. All extensions being added in a tracker will + * automatically be removed when the extension is uninstalled from the registry. + * Users interested in extension removal can register a handler that will let + * them know when an object is being removed. + *

+ * 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 IExtensionTracker +{ + + enum ReferenceType { + /** + * Constant for strong (normal) reference holding. + */ + REF_STRONG, + + /** + * Constant for weak reference holding. + */ + REF_WEAK + }; + + virtual ~IExtensionTracker(); + + /** + * Register an extension change handler with this tracker using the given filter. + * + * @param handler the handler to be registered + * @param filter the filter to use to choose interesting changes + */ + virtual void RegisterHandler(IExtensionChangeHandler* handler, const IExtensionPointFilter& filter) = 0; + + /** + * Register an extension change handler with this tracker for the given extension point id. + * + * @param handler the handler to be registered + * @param extensionPointId the extension point id to track + */ + virtual void RegisterHandler(IExtensionChangeHandler *handler, const QString& extensionPointId = QString()) = 0; + + /** + * Unregister the given extension change handler previously registered with this tracker. + * + * @param handler the handler to be unregistered + */ + virtual void UnregisterHandler(IExtensionChangeHandler* handler) = 0; + + /** + * Create an association between the given extension and the given object. + * The referenceType indicates how strongly the object is being kept in memory. + * There are 2 possible values: REF_STRONG and REF_WEAK. + * + * @param extension the extension + * @param object the object to associate with the extension + * @param referenceType one of REF_STRONG, REF_WEAK + */ + virtual void RegisterObject(const SmartPointer& extension, + const SmartPointer& object, ReferenceType referenceType) = 0; + + /** + * Remove an association between the given extension and the given object. + * + * @param extension the extension under which the object has been registered + * @param object the object to unregister + */ + virtual void UnregisterObject(const SmartPointer& extension, + const SmartPointer& object) = 0; + + /** + * Remove all the objects associated with the given extension. Return + * the removed objects. + * + * @param extension the extension for which the objects are removed + * @return the objects that were associated with the extension + */ + virtual QList > UnregisterObject(const SmartPointer& extension) = 0; + + /** + * Return all the objects that have been associated with the given extension. + * All objects registered strongly will be return unless they have been unregistered. + * The objects registered softly or weakly may not be returned if they have been garbage collected. + * Return an empty array if no associations exist. + * + * @param extension the extension for which the object must be returned + * @return the array of associated objects + */ + virtual QList > GetObjects(const SmartPointer& extension) const = 0; + + /** + * Close the tracker. All registered objects are freed and all handlers are being automatically removed. + */ + virtual void Close() = 0; +}; + +} + +#endif // BERRYIEXTENSIONTRACKER_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 423418f7a4..1eb07d5a88 100755 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCTKPluginActivator.cpp @@ -1,223 +1,234 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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 "berryDebugOptions.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; + debugOptions.reset(new DebugOptions()); + debugOptions->Start(context); + debugOptionsReg = context->registerService(debugOptions.data()); + 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()); + + InternalPlatform::GetInstance()->Start(context); } void org_blueberry_core_runtime_Activator::stop(ctkPluginContext* context) { - Q_UNUSED(context) + InternalPlatform::GetInstance()->Stop(context); //pluginListener.reset(); //Platform::GetServiceRegistry().UnRegisterService(IExtensionPointService::SERVICE_ID); prefServiceReg.unregister(); preferencesService->ShutDown(); preferencesService.reset(); prefServiceReg = 0; this->stopRegistry(); RegistryProperties::SetContext(NULL); + debugOptionsReg.unregister(); + debugOptions->Stop(context); + debugOptions.reset(); + 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(); // } } } #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) Q_EXPORT_PLUGIN2(org_blueberry_core_runtime, berry::org_blueberry_core_runtime_Activator) #endif 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 de5679f01f..ca258b867b 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,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 BERRYCTKPLUGINACTIVATOR_H #define BERRYCTKPLUGINACTIVATOR_H #include #include #include namespace berry { //class CTKPluginListener; +class DebugOptions; class PreferencesService; 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_core_runtime") #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 debugOptions; + ctkServiceRegistration debugOptionsReg; + 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/berryCombinedEventDelta.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCombinedEventDelta.cpp index 0e43f0c16d..5bd2294af2 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCombinedEventDelta.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCombinedEventDelta.cpp @@ -1,206 +1,249 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryIExtensionPointFilter.h" #include "berryIObjectManager.h" +#include "berrySimpleExtensionPointFilter.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)) { } +QList CombinedEventDelta::FilterExtensions(const IExtensionPointFilter& filter) const +{ + if (const SimpleExtensionPointFilter* simpleFilter = dynamic_cast(filter.GetConcept())) + { + if (simpleFilter->m_Id.isEmpty()) return d->allExtensions; + return d->extensionsByID[simpleFilter->m_Id]; + } + + QList result; + foreach(int extPt, d->allExtensionPoints) + { + ExtensionPointHandle handle(d->objectManager, extPt); + if (filter.Matches(&handle)) + { + result.append(d->extensionsByID[handle.GetUniqueIdentifier()]); + } + } + return result; +} + +QList CombinedEventDelta::FilterExtensionPoints(const IExtensionPointFilter& filter) const +{ + if (const SimpleExtensionPointFilter* simpleFilter = dynamic_cast(filter.GetConcept())) + { + if (simpleFilter->m_Id.isEmpty()) return d->allExtensionPoints; + return d->extPointsByID[simpleFilter->m_Id]; + } + + QList result; + foreach(int extPt, d->allExtensionPoints) + { + ExtensionPointHandle handle(d->objectManager, extPt); + if (filter.Matches(&handle)) + { + result.push_back(extPt); + } + } + return result; +} + 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 > CombinedEventDelta::GetExtensionPoints(const IExtensionPointFilter& filter) const { QList extensionPoints; - if (!id.isEmpty() && !d->extPointsByID.isEmpty()) + if (!filter.IsNull() && !d->extPointsByID.isEmpty()) { - extensionPoints = d->extPointsByID[id]; + extensionPoints = FilterExtensionPoints(filter); } - else if (id.isEmpty()) + else if (filter.IsNull()) { 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 > CombinedEventDelta::GetExtensions(const IExtensionPointFilter& filter) const { QList extensions; - if (!id.isEmpty() && !d->extensionsByID.isEmpty()) + if (!filter.IsNull() && !d->extensionsByID.isEmpty()) { - extensions = d->extensionsByID[id]; + extensions = FilterExtensions(filter); } - else if (id.isEmpty()) + else if (filter.IsNull()) { 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/berryCombinedEventDelta.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCombinedEventDelta.h index b9de2073b9..5e6aab5961 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCombinedEventDelta.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryCombinedEventDelta.h @@ -1,83 +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 BERRYCOMBINEDEVENTDELTA_H #define BERRYCOMBINEDEVENTDELTA_H #include #include namespace berry { struct CombinedEventDeltaData; struct IExtension; struct IExtensionPoint; +struct IExtensionPointFilter; struct IObjectManager; class ExtensionPoint; /** * The class stores extensions and extensions points that have been actually * modified by a registry operation. * * For performance, modified extensions and extension points are stored in two forms: * - organized in buckets by IDs of extension points (for listeners on specific ext.point) * - aggregated in one list (for global listeners) */ class CombinedEventDelta { public: CombinedEventDelta(); CombinedEventDelta(const CombinedEventDelta& other); ~CombinedEventDelta(); CombinedEventDelta& operator=(const CombinedEventDelta& other); void Reset(); bool IsNull() const; static CombinedEventDelta RecordAddition(); static CombinedEventDelta RecordRemoval(); bool IsAddition() const; bool IsRemoval() const; void SetObjectManager(const SmartPointer &manager); SmartPointer GetObjectManager() const; void RememberExtensionPoint(const SmartPointer& extensionPoint); void RememberExtension(const SmartPointer& extensionPoint, int ext); void RememberExtensions(const SmartPointer& extensionPoint, const QList& exts); - QList > GetExtensionPoints(const QString& id) const; - QList > GetExtensions(const QString& id) const; + QList > GetExtensionPoints(const IExtensionPointFilter& id) const; + QList > GetExtensions(const IExtensionPointFilter& id) const; private: CombinedEventDelta(bool addition); + QList FilterExtensionPoints(const IExtensionPointFilter& filter) const; + QList FilterExtensions(const IExtensionPointFilter& filter) const; + QExplicitlySharedDataPointer d; }; } #endif // BERRYCOMBINEDEVENTDELTA_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryDebugOptions.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryDebugOptions.cpp new file mode 100644 index 0000000000..cf1691e561 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryDebugOptions.cpp @@ -0,0 +1,350 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY 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 "berryDebugOptions.h" + +#include +#include + +#include +#include + +#include +#include +#include +#if (QT_VERSION < QT_VERSION_CHECK(5,0,0)) +#include +#else +#include +#endif + +namespace berry { + + +const QString DebugOptions::BLUEBERRY_DEBUG = "blueberry.debug"; +const QString DebugOptions::OPTIONS = ".blueberry.options"; + + +DebugOptions::DebugOptions() + : enabled(false) + , context(nullptr) +{ + // if no debug option was specified, don't even bother to try. + // Must ensure that the options slot is null as this is the signal to the + // platform that debugging is not enabled. + QString debugOptionsFilename = Platform::GetProperty(BLUEBERRY_DEBUG); + if (debugOptionsFilename.isNull()) return; + + if (debugOptionsFilename.isEmpty()) + { + // default options location is user.dir (install location may be r/o so + // is not a good candidate for a trace options that need to be updatable by + // by the user) +#if (QT_VERSION < QT_VERSION_CHECK(5,0,0)) + QDir userDir(QDesktopServices::storageLocation(QDesktopServices::HomeLocation)); +#else + QDir userDir(QStandardPaths::standardLocations(QStandardPaths::HomeLocation).front()); +#endif + debugOptionsFilename = userDir.absoluteFilePath(OPTIONS); + } + QFile optionsFile(debugOptionsFilename); + QString msgState; + if (!optionsFile.exists()) + { + msgState = "not found"; + } + else + { + QSettings settings(debugOptionsFilename, QSettings::IniFormat); + if (settings.status() != QSettings::NoError) + { + msgState = ".... did not parse"; + } + else + { + foreach (const QString& key, settings.allKeys()) + { + this->options.insert(key, settings.value(key)); + } + this->enabled = true; + } + } + BERRY_INFO << "Debug options:\n " << optionsFile.fileName() << " " << msgState; +} + +void DebugOptions::Start(ctkPluginContext* pc) +{ + this->context = pc; + this->listenerTracker.reset(new ctkServiceTracker(pc, this)); + this->listenerTracker->open(); +} + +void DebugOptions::Stop(ctkPluginContext* /*pc*/) +{ + this->listenerTracker->close(); + this->listenerTracker.reset(); + this->context = nullptr; +} + +bool DebugOptions::GetBooleanOption(const QString& option, bool defaultValue) const +{ + return this->GetOption(option, defaultValue).toBool(); +} + +QVariant DebugOptions::GetOption(const QString& option) const +{ + return GetOption(option, QVariant()); +} + +QVariant DebugOptions::GetOption(const QString& option, const QVariant& defaultValue) const +{ + QMutexLocker lock(&this->mutex); + return this->options.value(option, defaultValue); +} + +int DebugOptions::GetIntegerOption(const QString& option, int defaultValue) const +{ + return this->options.value(option, defaultValue).toInt(); +} + +QHash DebugOptions::GetOptions() const +{ + QHash snapShot; + { + QMutexLocker lock(&this->mutex); + if (this->IsDebugEnabled()) + { + snapShot = this->options; + } + else + { + snapShot = this->disabledOptions; + } + } + return snapShot; +} + +void DebugOptions::SetOption(const QString& option, const QVariant& value) +{ + if (!this->IsDebugEnabled()) return; + + QString fireChangedEvent; + { + QMutexLocker lock(&this->mutex); + // get the current value + auto currentValue = this->options.find(option); + if (currentValue != this->options.end()) + { + if (currentValue.value() != value) + { + fireChangedEvent = this->GetSymbolicName(option); + } + } + else + { + if (!value.isNull()) + { + fireChangedEvent = this->GetSymbolicName(option); + } + } + if (!fireChangedEvent.isEmpty()) + { + this->options.insert(option, value); + } + } + // Send the options change event outside the sync block + if (!fireChangedEvent.isEmpty()) + { + this->OptionsChanged(fireChangedEvent); + } +} + +void DebugOptions::SetOptions(const QHash& ops) +{ + QHash newOptions = ops; + QSet fireChangesTo; + { + QMutexLocker lock(&this->mutex); + if (!this->IsDebugEnabled()) + { + this->disabledOptions = newOptions; + // no events to fire + return; + } + // first check for removals + foreach (const QString& key, this->options.keys()) + { + if (!newOptions.contains(key)) + { + QString symbolicName = this->GetSymbolicName(key); + if (!symbolicName.isEmpty()) + { + fireChangesTo.insert(symbolicName); + } + } + } + // now check for changes to existing values + for(auto iter = newOptions.begin(); iter != newOptions.end(); ++iter) + { + QVariant existingValue = this->options.value(iter.key()); + if (iter.value() != existingValue) + { + QString symbolicName = this->GetSymbolicName(iter.key()); + if (!symbolicName.isEmpty()) + { + fireChangesTo.insert(symbolicName); + } + } + } + // finally set the actual options + this->options = newOptions; + } + foreach (const QString& symbolicName, fireChangesTo) + { + this->OptionsChanged(symbolicName); + } +} + +void DebugOptions::RemoveOption(const QString& option) +{ + if (!this->IsDebugEnabled()) return; + QString fireChangedEvent; + { + QMutexLocker lock(&this->mutex); + if (this->options.remove(option)) + { + fireChangedEvent = this->GetSymbolicName(option); + } + } + // Send the options change event outside the sync block + if (!fireChangedEvent.isEmpty()) + { + this->OptionsChanged(fireChangedEvent); + } +} + +bool DebugOptions::IsDebugEnabled() const +{ + QMutexLocker lock(&this->mutex); + return this->enabled; +} + +void DebugOptions::SetDebugEnabled(bool enabled) +{ + bool fireChangedEvent = false; + { + QMutexLocker lock(&this->mutex); + if (enabled) + { + if (this->IsDebugEnabled()) return; + + // enable platform debugging - there is no .options file + Platform::GetConfiguration().setString(BLUEBERRY_DEBUG.toStdString(), ""); + this->options = this->disabledOptions; + this->disabledOptions.clear(); + this->enabled = true; + if (!this->options.isEmpty()) + { + // fire changed event to indicate some options were re-enabled + fireChangedEvent = true; + } + } + else + { + if (!this->IsDebugEnabled()) return; + // disable platform debugging. + Platform::GetConfiguration().remove(BLUEBERRY_DEBUG.toStdString()); + if (!this->options.isEmpty()) + { + // Save the current options off in case debug is re-enabled + this->disabledOptions = this->options; + // fire changed event to indicate some options were disabled + fireChangedEvent = true; + } + this->options.clear(); + this->enabled = false; + } + } + if (fireChangedEvent) + { + // need to fire event to listeners that options have been disabled + this->OptionsChanged("*"); + } +} + +QString DebugOptions::GetSymbolicName(const QString& option) const +{ + int firstSlashIndex = option.indexOf("/"); + if (firstSlashIndex > 0) + return option.left(firstSlashIndex); + return QString::null; +} + +void DebugOptions::OptionsChanged(const QString& pluginSymbolicName) +{ + // use osgi services to get the listeners + if (context == nullptr) + return; + // do not use the service tracker because that is only used to call all listeners initially when they are registered + // here we only want the services with the specified name. + QList listenerRefs; + try + { + listenerRefs = context->getServiceReferences( "(" + DebugOptions::LISTENER_SYMBOLICNAME + "=" + pluginSymbolicName + ")"); + } + catch (const ctkInvalidArgumentException& /*e*/) + { + // consider logging; should not happen + } + if (listenerRefs.empty()) return; + + foreach (const ctkServiceReference& ref, listenerRefs) + { + DebugOptionsListener* service = context->getService(ref); + if (service == nullptr) continue; + + try + { + service->OptionsChanged(*this); + } + catch (const std::exception& /*e*/) + { + // TODO consider logging + } + context->ungetService(ref); + } +} + +DebugOptionsListener* DebugOptions::addingService(const ctkServiceReference& reference) +{ + DebugOptionsListener* listener = context->getService(reference); + listener->OptionsChanged(*this); + return listener; +} + +void DebugOptions::modifiedService(const ctkServiceReference& /*reference*/, + DebugOptionsListener* /*service*/) +{ + // nothing +} + +void DebugOptions::removedService(const ctkServiceReference& reference, + DebugOptionsListener* /*service*/) +{ + context->ungetService(reference); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryDebugOptions.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryDebugOptions.h new file mode 100644 index 0000000000..509c5da1ee --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryDebugOptions.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 BERRYDEBUGOPTIONS_H +#define BERRYDEBUGOPTIONS_H + +#include + +#include "berryDebugOptionsListener.h" + +#include +#include + +namespace berry { + +/** + * Used to get debug options settings. + */ +class org_blueberry_core_runtime_EXPORT DebugOptions : public QObject, public IDebugOptions, + private ctkServiceTrackerCustomizer +{ + Q_OBJECT + Q_INTERFACES(berry::IDebugOptions) + +public: + + DebugOptions(); + + void Start(ctkPluginContext* pc); + void Stop(ctkPluginContext* pc); + + bool GetBooleanOption(const QString& option, bool defaultValue) const; + QVariant GetOption(const QString& option) const; + QVariant GetOption(const QString& option, const QVariant& defaultValue) const; + + int GetIntegerOption(const QString& option, int defaultValue) const; + + QHash GetOptions() const; + + void SetOption(const QString& option, const QVariant& value); + + void SetOptions(const QHash& ops); + + void RemoveOption(const QString& option); + + bool IsDebugEnabled() const; + + void SetDebugEnabled(bool enabled); + +private: + + static const QString BLUEBERRY_DEBUG; + + /** mutex used to lock the options maps */ + mutable QMutex mutex; + /** A boolean value indicating if debug was enabled */ + bool enabled; + /** A current map of all the options with values set */ + QHash options; + /** A map of all the disabled options with values set at the time debug was disabled */ + QHash disabledOptions; + /** The singleton object of this class */ + //static Impl* singleton = nullptr; + /** The default name of the .options file if loading when the -debug command-line argument is used */ + static const QString OPTIONS; + + ctkPluginContext* context; + QScopedPointer > listenerTracker; + + QString GetSymbolicName(const QString& option) const; + + /** + * Notifies the trace listener for the specified plug-in that its option-path has changed. + * @param pluginSymbolicName The plug-in of the owning trace listener to notify. + */ + void OptionsChanged(const QString& bundleSymbolicName); + + DebugOptionsListener* addingService(const ctkServiceReference& reference); + void modifiedService(const ctkServiceReference& reference, + DebugOptionsListener* service); + void removedService(const ctkServiceReference& reference, + DebugOptionsListener* service); + +}; + +} + +#endif // BERRYDEBUGOPTIONS_H 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 03ba36eaf7..8e2a51a902 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,1345 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berrySimpleExtensionPointFilter.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; + IExtensionPointFilter filter; IRegistryEventListener* listener; - ListenerInfo(IRegistryEventListener* listener, const QString& filter) + ListenerInfo(IRegistryEventListener* listener, const IExtensionPointFilter& 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) +void ExtensionRegistry::AddListenerInternal(IRegistryEventListener* listener, const IExtensionPointFilter& 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*/) { // 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); + AddListenerInternal(listener, extensionPointId.isEmpty() ? IExtensionPointFilter(nullptr) + : IExtensionPointFilter(new SimpleExtensionPointFilter(extensionPointId))); +} + +void ExtensionRegistry::AddListener(IRegistryEventListener* listener, const IExtensionPointFilter& filter) +{ + this->AddListenerInternal(listener, filter); } 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())); + listeners.Remove(ListenerInfo(listener, IExtensionPointFilter(nullptr))); } 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*/) { // 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/berryExtensionRegistry.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.h index e7010407d2..ab1a71ab76 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryExtensionRegistry.h @@ -1,451 +1,452 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYEXTENSIONREGISTRY_H #define BERRYEXTENSIONREGISTRY_H #include #include #include "berryRegistryTimestamp.h" #include "berryCombinedEventDelta.h" #include "berryListenerList.h" #include #include class QTranslator; namespace berry { struct IContributor; struct IStatus; class ConfigurationElementDescription; class RegistryContribution; class RegistryContributor; class RegistryObject; class RegistryObjectFactory; class RegistryObjectManager; class RegistryStrategy; /** * An implementation for the extension registry API. */ class ExtensionRegistry : public QObject, public IExtensionRegistry { Q_OBJECT Q_INTERFACES(berry::IExtensionRegistry) private: struct ListenerInfo; class RegistryEventThread; // used to enforce concurrent access policy for readers/writers mutable QReadWriteLock access; // all registry event listeners ListenerList listeners; QScopedPointer debugRegistryListener; SmartPointer registryObjects; QObject* masterToken; // use to get full control of the registry; objects created as "static" QObject* userToken; // use to modify non-persisted registry elements RegistryTimestamp aggregatedTimestamp; // tracks current contents of the registry // encapsulates processing of new registry deltas CombinedEventDelta eventDelta; // marks a new extended delta. The namespace that normally would not exists is used for this purpose const static QString notNamespace; // does this instance of the extension registry has multiple language support enabled? bool isMultiLanguage; // have we already logged a error on usage of an unsupported multi-language method? mutable bool mlErrorLogged; QScopedPointer eventThread; // registry event loop // The pair of values we store in the event queue struct QueueElement; class Queue : public QList { QMutex mutex; QWaitCondition waitCond; public: class Locker { private: Queue* q; public: Locker(Queue* q) : q(q) { q->mutex.lock(); } ~Locker() { q->mutex.unlock(); } }; void wait() { waitCond.wait(&mutex); } void notify() { waitCond.wakeOne(); } }; Queue queue; // stores registry events info /** * Adds and resolves all extensions and extension points provided by the * plug-in. *

* A corresponding IRegistryChangeEvent will be broadcast to all listeners * interested on changes in the given plug-in. *

*/ void Add(const SmartPointer& element); QString AddExtension(int extension); /** * Looks for existing orphan extensions to connect to the given extension * point. If none is found, there is nothing to do. Otherwise, link them. */ QString AddExtensionPoint(int extPoint); QSet AddExtensionsAndExtensionPoints(const SmartPointer& element); - void AddListenerInternal(IRegistryEventListener* listener, const QString& filter); + void AddListenerInternal(IRegistryEventListener* listener, const IExtensionPointFilter& filter); void BasicAdd(const SmartPointer& element, bool link); void SetObjectManagers(const SmartPointer &manager); void BasicRemove(const QString& contributorId); /** * Broadcasts (asynchronously) the event to all interested parties. */ void FireRegistryChangeEvent(); //RegistryDelta GetDelta(const QString& namespaze) const; void Link(const SmartPointer& extPoint, const QList& extensions); /* * Records an extension addition/removal. */ //QString RecordChange(const SmartPointer& extPoint, int extension, int kind); /* * Records a set of extension additions/removals. */ //QString RecordChange(const SmartPointer& extPoint, const QList& extensions, int kind); //Return the affected namespace QString RemoveExtension(int extensionId); QString RemoveExtensionPoint(int extPoint); QSet RemoveExtensionsAndExtensionPoints(const QString& contributorId); /** * Access check for add/remove operations: * - Master key allows all operations * - User key allows modifications of non-persisted elements * * @param key key to the registry supplied by the user * @param persist true if operation affects persisted elements * @return true is the key grants read/write access to the registry */ bool CheckReadWriteAccess(QObject* key, bool persist) const; void LogError(const QString& owner, const QString& contributionName, const ctkException& e); void LogError(const QString& owner, const QString& contributionName); // Fill in the actual content of this extension void CreateExtensionData(const QString& contributorId, const ConfigurationElementDescription& description, const SmartPointer& parent, bool persist); bool RemoveObject(const SmartPointer& registryObject, bool isExtensionPoint, QObject* token); protected: //storage manager associated with the registry cache //StorageManager cacheStorageManager; // Table reader associated with this extension registry //TableReader theTableReader = new TableReader(this); QScopedPointer strategy; // overridable portions of the registry functionality /** * Sets new cache file manager. If existing file manager was owned by the registry, * closes it. * * @param cacheBase the base location for the registry cache * @param isCacheReadOnly whether the file cache is read only */ void SetFileManager(const QString& cacheBase, bool isCacheReadOnly); // allow other objects in the registry to use the same lock void EnterRead(); // allow other objects in the registry to use the same lock void ExitRead(); ///////////////////////////////////////////////////////////////////////////////////////////////// // Registry Object Factory // The factory produces contributions, extension points, extensions, and configuration elements // to be stored in the extension registry. QScopedPointer theRegistryObjectFactory; // Override to provide domain-specific elements to be stored in the extension registry void SetElementFactory(); //TableReader getTableReader() const; // Find the first location that contains a cache table file and set file manager to it. bool CheckCache(); void StopChangeEventScheduler(); public: SmartPointer GetObjectManager() const; void AddListener(IRegistryEventListener* listener, const QString& extensionPointId = QString()); + void AddListener(IRegistryEventListener *listener, const IExtensionPointFilter& filter); /* * @see IExtensionRegistry#getConfigurationElementsFor(java.lang. QString) */ QList > GetConfigurationElementsFor(const QString& extensionPointId) const; /* * @see org.eclipse.core.runtime.IExtensionRegistry#getConfigurationElementsFor(java.lang. QString, java.lang. QString) */ QList > GetConfigurationElementsFor(const QString& pluginId, const QString& extensionPointSimpleId) const; /* * @see org.eclipse.core.runtime.IExtensionRegistry#getConfigurationElementsFor(java.lang. QString, java.lang. QString, java.lang. QString) */ QList > GetConfigurationElementsFor(const QString& pluginId, const QString& extensionPointName, const QString& extensionId) const; /* * @see org.eclipse.core.runtime.IExtensionRegistry#getExtension(java.lang. QString) */ SmartPointer GetExtension(const QString& extensionId) const; /* * @see org.eclipse.core.runtime.IExtensionRegistry#getExtension(java.lang. QString, java.lang. QString) */ SmartPointer GetExtension(const QString& extensionPointId, const QString& extensionId) const; /* * @see org.eclipse.core.runtime.IExtensionRegistry#getExtension(java.lang. QString, java.lang. QString, java.lang. QString) */ SmartPointer GetExtension(const QString& pluginId, const QString& extensionPointName, const QString& extensionId) const; /* * @see org.eclipse.core.runtime.IExtensionRegistry#getExtensionPoint(java.lang. QString) */ SmartPointer GetExtensionPoint(const QString& xptUniqueId) const; /* * @see org.eclipse.core.runtime.IExtensionRegistry#getExtensionPoint(java.lang. QString, java.lang. QString) */ SmartPointer GetExtensionPoint(const QString& elementName, const QString& xpt) const; /* * @see org.eclipse.core.runtime.IExtensionRegistry#getExtensionPoints() */ QList > GetExtensionPoints() const; /* * @see org.eclipse.core.runtime.IExtensionRegistry#getExtensionPoints(java.lang. QString) */ QList > GetExtensionPoints(const QString& namespaceName) const; /* * @see org.eclipse.core.runtime.IExtensionRegistry#getExtensions(java.lang. QString) */ QList > GetExtensions(const QString& namespaceName) const; QList > GetExtensions(const SmartPointer& contributor) const; QList > GetExtensionPoints(const SmartPointer& contributor) const; /* * @see org.eclipse.core.runtime.IExtensionRegistry#getNamespaces() */ QList GetNamespaces() const; bool HasContributor(const SmartPointer& contributor) const; bool HasContributor(const QString& contributorId) const; void Remove(const QString& removedContributorId, long timestamp); void RemoveContributor(const SmartPointer& contributor, QObject* key); /** * Unresolves and removes all extensions and extension points provided by * the plug-in. *

* A corresponding IRegistryChangeEvent will be broadcast to all listeners * interested on changes in the given plug-in. *

*/ void Remove(const QString& removedContributorId); void RemoveListener(IRegistryEventListener* listener); ExtensionRegistry(RegistryStrategy* registryStrategy, QObject* masterToken, QObject* userToken); ~ExtensionRegistry(); /** * Stops the registry. Registry has to be stopped to properly * close cache and dispose of listeners. * @param key - key token for this registry */ void Stop(QObject* key); /* * Clear the registry cache files from the file manager so on next start-up we recompute it. */ void ClearRegistryCache(); // Lazy initialization. RegistryObjectFactory* GetElementFactory(); void Log(const SmartPointer& status) const; /** * With multi-locale support enabled this method returns the non-translated * key so that they can be cached and translated later into desired languages. * In the absence of the multi-locale support the key gets translated immediately * and only translated values is cached. */ QString Translate(const QString& key, QTranslator* resources) const; bool Debug() const; bool DebugEvents() const; bool UseLazyCacheLoading() const; long ComputeState() const; QObject* CreateExecutableExtension(const SmartPointer& defaultContributor, const QString& className, const QString& requestedContributorName); ////////////////////////////////////////////////////////////////////////////////////////// // Registry change events processing void ProcessChangeEvent(const QList& listenerInfos, const CombinedEventDelta &scheduledDelta); // Registry events notifications are done on a separate thread in a sequential manner // (first in - first processed) void ScheduleChangeEvent(const QList& listenerInfos, const CombinedEventDelta& scheduledDeltas); bool AddContribution(QIODevice* is, const SmartPointer& contributor, bool persist, const QString& contributionName, QTranslator* translationBundle, QObject* key, long timestamp); bool AddContribution(QIODevice* is, const SmartPointer& contributor, bool persist, const QString& contributionName, QTranslator* translationBundle, QObject* key); /** * Adds an extension point to the extension registry. *

* If the registry is not modifiable, this method is an access controlled method. * Proper token should be passed as an argument for non-modifiable registries. *

* @param identifier Id of the extension point. If non-qualified names is supplied, * it will be converted internally into a fully qualified name * @param contributor the contributor of this extension point * @param persist indicates if contribution should be stored in the registry cache. If false, * contribution is not persisted in the registry cache and is lost on Eclipse restart * @param label display string for the extension point * @param schemaReference reference to the extension point schema. The schema reference * is a URL path relative to the plug-in installation URL. May be null * @param token the key used to check permissions. Two registry keys are set in the registry * constructor {@link RegistryFactory#createRegistry(org.eclipse.core.runtime.spi.RegistryStrategy, Object, Object)}: * master token and a user token. Master token allows all operations; user token * allows non-persisted registry elements to be modified. * @return true if successful, false if a problem was encountered * @throws IllegalArgumentException if incorrect token is passed in */ bool AddExtensionPoint(const QString& identifier, const SmartPointer& contributor, bool persist, const QString& label, const QString& schemaReference, QObject* token); /** * Adds an extension to the extension registry. *

* If the registry is not modifiable, this method is an access controlled method. * Proper token should be passed as an argument for non-modifiable registries. *

* @see org.eclipse.core.internal.registry.spi.ConfigurationElementDescription * * @param identifier Id of the extension. If non-qualified name is supplied, * it will be converted internally into a fully qualified name * @param contributor the contributor of this extension * @param persist indicates if contribution should be stored in the registry cache. If false, * contribution is not persisted in the registry cache and is lost on Eclipse restart * @param label display string for this extension * @param extensionPointId Id of the point being extended. If non-qualified * name is supplied, it is assumed to have the same contributorId as this extension * @param configurationElements contents of the extension * @param token the key used to check permissions. Two registry keys are set in the registry * constructor {@link RegistryFactory#createRegistry(org.eclipse.core.runtime.spi.RegistryStrategy, Object, Object)}: * master token and a user token. Master token allows all operations; user token * allows non-persisted registry elements to be modified. * @return true if successful, false if a problem was encountered * @throws IllegalArgumentException if incorrect token is passed in */ bool AddExtension(const QString& identifier, const SmartPointer& contributor, bool persist, const QString& label, const QString& extensionPointId, const ConfigurationElementDescription& configurationElements, QObject* token); bool RemoveExtension(const SmartPointer& extension, QObject* token); bool RemoveExtensionPoint(const SmartPointer& extensionPoint, QObject* token); QList > GetAllContributors() const; bool IsMultiLanguage() const; QList Translate(const QList& nonTranslated, const SmartPointer& contributor, const QLocale& locale) const; QLocale GetLocale() const; void LogMultiLangError() const; }; } #endif // BERRYEXTENSIONREGISTRY_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 751969f15f..5c96496672 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryInternalPlatform.cpp @@ -1,597 +1,677 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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 "berryDebugOptions.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; +bool InternalPlatform::DEBUG = false; +bool InternalPlatform::DEBUG_PLUGIN_PREFERENCES = false; + InternalPlatform::InternalPlatform() : m_Initialized(false) , m_Running(false) , m_ConsoleLog(false) + , m_Context(nullptr) , 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; } +QVariant InternalPlatform::GetOption(const QString& option, const QVariant& defaultValue) const +{ + IDebugOptions* options = GetDebugOptions(); + if (options != nullptr) + { + return options->GetOption(option, defaultValue); + } + return QVariant(); +} + 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()).c_str()); #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; } } } +IDebugOptions* InternalPlatform::GetDebugOptions() const +{ + return m_DebugTracker.isNull() ? nullptr : m_DebugTracker->getService(); +} + 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::Start(ctkPluginContext* context) +{ + this->m_Context = context; + OpenServiceTrackers(); + InitializeDebugFlags(); +} + +void InternalPlatform::Stop(ctkPluginContext* /*context*/) +{ + CloseServiceTrackers(); + this->m_Context = nullptr; +} + void InternalPlatform::AssertInitialized() const { if (!m_Initialized) throw Poco::SystemException("The Platform has not been initialized yet!"); } -IExtensionRegistry* InternalPlatform::GetExtensionRegistry() +void InternalPlatform::OpenServiceTrackers() +{ + ctkPluginContext* context = this->m_Context; + + m_PreferencesTracker.reset(new ctkServiceTracker(context)); + m_PreferencesTracker->open(); + + m_RegistryTracker.reset(new ctkServiceTracker(context)); + m_RegistryTracker->open(); + + m_DebugTracker.reset(new ctkServiceTracker(context)); + m_DebugTracker->open(); +} + +void InternalPlatform::CloseServiceTrackers() { - if (m_RegistryTracker.isNull()) + if (!m_PreferencesTracker.isNull()) + { + m_PreferencesTracker->close(); + m_PreferencesTracker.reset(); + } + if (!m_RegistryTracker.isNull()) { - m_RegistryTracker.reset(new ctkServiceTracker(berry::CTKPluginActivator::getPluginContext())); - m_RegistryTracker->open(); + m_RegistryTracker->close(); + m_RegistryTracker.reset(); + } + if (!m_DebugTracker.isNull()) + { + m_DebugTracker->close(); + m_DebugTracker.reset(); } - return m_RegistryTracker->getService(); } -IPreferencesService *InternalPlatform::GetPreferencesService() +void InternalPlatform::InitializeDebugFlags() { - if (m_PreferencesTracker.isNull()) + DEBUG = this->GetOption(Platform::PI_RUNTIME + "/debug", false).toBool(); + if (DEBUG) { - m_PreferencesTracker.reset(new ctkServiceTracker(berry::CTKPluginActivator::getPluginContext())); - m_PreferencesTracker->open(); + DEBUG_PLUGIN_PREFERENCES = GetOption(Platform::PI_RUNTIME + "/preferences/plugin", false).toBool(); } - return m_PreferencesTracker->getService(); +} + +IExtensionRegistry* InternalPlatform::GetExtensionRegistry() +{ + return m_RegistryTracker.isNull() ? nullptr : m_RegistryTracker->getService(); +} + +IPreferencesService *InternalPlatform::GetPreferencesService() +{ + return m_PreferencesTracker.isNull() ? nullptr : 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 debugOption(Platform::ARG_DEBUG.toStdString(), "", "enable debug mode"); + debugOption.argument("", false).binding("blueberry.debug"); + options.addOption(debugOption); + 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) { 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); + try + { + context->getPlugin(pluginId)->start(ctkPlugin::START_TRANSIENT | ctkPlugin::START_ACTIVATION_POLICY); + } + catch (const ctkException& e) + { + qDebug() << e.printStackTrace(); + } + catch (const std::exception& e) + { + qDebug() << e.what(); + } } 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/berryInternalPlatform.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryInternalPlatform.h index 9e603cf546..b6943910af 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryInternalPlatform.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryInternalPlatform.h @@ -1,158 +1,177 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYINTERNALPLATFORM_H_ #define BERRYINTERNALPLATFORM_H_ #include #include #include #include #include #include #include #include class ctkPluginFrameworkFactory; class ctkPluginContext; namespace berry { struct IAdapterManager; struct IExtensionRegistry; struct IPreferencesService; struct ILog; +struct IDebugOptions; class LogImpl; class PlatformLogChannel; class InternalPlatform : private Poco::Util::Application { private: static Poco::Mutex m_Mutex; bool m_Initialized; bool m_Running; bool m_ConsoleLog; + ctkPluginContext* m_Context; + QScopedPointer > m_PreferencesTracker; QScopedPointer > m_RegistryTracker; + QScopedPointer > m_DebugTracker; QDir m_BaseStatePath; QDir m_InstallPath; QDir m_InstancePath; QDir m_UserPath; QDir m_ConfigPath; QStringList m_FilteredArgs; Poco::AutoPtr m_PlatformLogChannel; Poco::Logger* m_PlatformLogger; mutable QHash m_Logs; ctkPluginFrameworkFactory* m_ctkPluginFrameworkFactory; QList m_CTKPluginsToStart; //PlatformEvents m_Events; //PlatformEvent m_EventStarted; int* m_Argc; char** m_Argv; //std::map m_ArgMap; InternalPlatform(); //InternalPlatform(const InternalPlatform&) : m_EventStarted(PlatformEvent::EV_PLATFORM_STARTED) {}; void AssertInitialized() const; + void OpenServiceTrackers(); + void CloseServiceTrackers(); + void InitializeDebugFlags(); + void handlePreloadLibraryOption(const std::string &name, const std::string &value); int main(const std::vector& args); void uninstallPugin(const QUrl& pluginUrl, ctkPluginContext* pfwContext); + IDebugOptions* GetDebugOptions() const; + public: + + static bool DEBUG; + static bool DEBUG_PLUGIN_PREFERENCES; + virtual ~InternalPlatform(); // Poco::Application method overrides void defineOptions(Poco::Util::OptionSet& options); void PrintHelp(const std::string& name, const std::string& value); static InternalPlatform* GetInstance(); void Initialize(int& argc, char** argv, Poco::Util::AbstractConfiguration* config = 0); void Launch(); void Shutdown(); + void Start(ctkPluginContext* context); + void Stop(ctkPluginContext* context); + ctkPluginContext* GetCTKPluginFrameworkContext() const; IAdapterManager* GetAdapterManager() const; IExtensionRegistry* GetExtensionRegistry(); IPreferencesService* GetPreferencesService(); bool ConsoleLog() const; + QVariant GetOption(const QString& option, const QVariant& defaultValue = QVariant()) const; + QDir GetConfigurationPath(); QDir GetInstallPath(); QDir GetInstancePath(); bool GetStatePath(QDir& statePath, const QSharedPointer& plugin, bool create = true); QDir GetUserPath(); /** * Returns a log for the given plugin. Creates a new one if needed. * XXX change this into a LogMgr service that would keep track of the map. See if it can be a service factory. * It would contain all the logging methods that are here. * Relate to RuntimeLog if appropriate. * The system log listener needs to be optional: turned on or off. What about a system property? :-) */ ILog* GetLog(const QSharedPointer& plugin) const; //PlatformEvents& GetEvents(); bool IsRunning() const; Poco::Util::LayeredConfiguration& GetConfiguration() const; QStringList GetApplicationArgs() const; int& GetRawApplicationArgs(char**& argv); QSharedPointer GetPlugin(const QString& symbolicName); QList > GetPlugins(const QString& symbolicName, const QString& version); Poco::Logger* GetLogger(); }; } // namespace berry #endif /*BERRYINTERNALPLATFORM_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferences.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferences.cpp index 28203b93bc..89a9226427 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferences.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferences.cpp @@ -1,498 +1,503 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryPreferences.h" #include "berryAbstractPreferencesStorage.h" #include #include namespace berry { Preferences::Preferences(const PropertyMap& _Properties , const QString& _Name , Preferences* _Parent , AbstractPreferencesStorage* _Storage) : m_Properties(_Properties) , m_Path(_Parent ? _Parent->AbsolutePath() + (_Parent->AbsolutePath() == "/" ? "": "/") + _Name : "/") , m_Name(_Name) , m_Parent(_Parent) , m_Root(_Parent ? _Parent->m_Root : this) , m_Removed(false) , m_Storage(_Storage) { // root node if parent is 0 if (_Parent != 0) { // save as child in parent _Parent->m_Children.push_back(Preferences::Pointer(this)); } } bool Preferences::Has(const QString& key ) const { QMutexLocker scopedMutex(&m_Mutex); return this->Has_unlocked(key); } bool Preferences::Has_unlocked(const QString& key ) const { return (m_Properties.find(key) != m_Properties.end()); } bool Preferences::IsDirty() const { QMutexLocker scopedMutex(&m_Mutex); bool dirty = m_Dirty; for (ChildrenList::const_iterator it = m_Children.begin() ; it != m_Children.end(); ++it) { // break condition: if one node is dirty the whole tree is dirty if(dirty) break; else dirty = (*it)->IsDirty(); } return dirty; } QString Preferences::ToString() const { return QString("Preferences[") + m_Path + "]"; } bool Preferences::Equals(const Preferences* rhs) const { if(rhs == 0) return false; return (this->m_Path == rhs->m_Path); } Preferences::PropertyMap Preferences::GetProperties() const { QMutexLocker scopedMutex(&m_Mutex); return m_Properties; } Preferences::ChildrenList Preferences::GetChildren() const { QMutexLocker scopedMutex(&m_Mutex); return m_Children; } QString Preferences::AbsolutePath() const { return m_Path; } QStringList Preferences::ChildrenNames() const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); QStringList names; for (ChildrenList::const_iterator it = m_Children.begin() ; it != m_Children.end(); ++it) { names.push_back((*it)->Name()); } return names; } AbstractPreferencesStorage* Preferences::GetStorage() const { return m_Storage; } void Preferences::Clear() { { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); m_Properties.clear(); } this->SetDirty(true); } void Preferences::Flush() { { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); } m_Storage->Flush(this); // if something is written, make the tree undirty // there is a race condition here: after flushing, another thread // could modify this object before we can set dirty to false, // but we cannot hold a lock before flushing because the operation // will call other methods on this object, which would lead // to a recursive lock. this->SetDirty(false); } QString Preferences::Get(const QString& key, const QString& def) const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return this->Has_unlocked(key) ? m_Properties[key] : def; } bool Preferences::GetBool(const QString& key, bool def) const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return this->Has_unlocked(key) ? (m_Properties[key] == "true" ? true: false) : def; } QByteArray Preferences::GetByteArray(const QString& key, const QByteArray& def) const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return this->Has_unlocked(key) ? QByteArray::fromBase64(m_Properties[key].toLatin1()) : def; } double Preferences::GetDouble(const QString& key, double def) const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return this->Has_unlocked(key) ? m_Properties[key].toDouble() : def; } float Preferences::GetFloat(const QString& key, float def) const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return this->Has_unlocked(key) ? m_Properties[key].toFloat() : def; } int Preferences::GetInt(const QString& key, int def) const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return this->Has_unlocked(key) ? m_Properties[key].toInt() : def; } long Preferences::GetLong(const QString& key, long def) const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return this->Has_unlocked(key) ? m_Properties[key].toLong() : def; } QStringList Preferences::Keys() const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return m_Properties.keys(); } QString Preferences::Name() const { return m_Name; } IPreferences::Pointer Preferences::Node(const QString& path) { QMutexLocker scopedMutex(&m_Mutex); return this->Node_unlocked(path); } Preferences::Pointer Preferences::Node_unlocked(const QString& path) { QString pathName = path; AssertValid_unlocked(); AssertPath_unlocked(pathName); Preferences::Pointer node; // self reference if(pathName == "") return Preferences::Pointer(this); // absolute path else if(pathName[0] == '/') { pathName = pathName.mid(1); // call root with this relative path if (this == m_Root) return m_Root->Node_unlocked(pathName); else return m_Root->Node(pathName).Cast(); } // relative path else { // check if pathName contains anymore names QString name = pathName; // create new child nodes as long as there are names in the path int pos = pathName.indexOf('/'); // cut from the beginning if(pos != -1) { name = pathName.left(pos); pathName = pathName.mid(pos+1); } // now check if node exists->if not: make new for (ChildrenList::iterator it = m_Children.begin() ; it != m_Children.end(); it++) { // node found if((*it)->Name() == name && (*it)->IsRemoved() == false) { node = *it; break; } } // node not found create new one if(node.IsNull()) { // the new node automatically pushes itself into the children array of *this* Preferences::Pointer newNode(new Preferences(PropertyMap(), name, this, m_Storage)); node = newNode.GetPointer(); // this branch is dirty now -> prefs must be rewritten persistently this->SetDirty_unlocked(true); } // call Node() again if there are any names left on the path if(pos != -1) { if (this == node.GetPointer()) node = node->Node_unlocked(pathName); else node = node->Node(pathName).Cast(); } } return node; } bool Preferences::NodeExists(const QString& path) const { QString pathName = path; QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); AssertPath_unlocked(pathName); bool nodeExists = false; // absolute path if(pathName[0] == '/') { pathName = pathName.mid(1); // call root with this relative path return m_Root->NodeExists(pathName); } // relative path else { // check if pathName contains anymore names QString name = pathName; // create new child nodes as long as there are names in the path int pos = pathName.indexOf("/"); // cut from the beginning if(pos != -1) { name = pathName.left(pos); pathName = pathName.mid(pos+1); } // now check if node exists->if not: make new for (ChildrenList::const_iterator it = m_Children.begin() ; it != m_Children.end(); it++) { // node found if((*it)->Name() == name) { // call recursively if more names on the path exist if(pos != -1) nodeExists = (*it)->NodeExists(pathName); else nodeExists = true; break; } } } return nodeExists; } void Preferences::Put(const QString& key, const QString& value) { + QString oldValue; { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); - + oldValue = m_Properties[key]; m_Properties[key] = value; } - this->SetDirty(true); + if (oldValue != value) + { + this->SetDirty(true); + this->OnPropertyChanged(ChangeEvent(this, key, oldValue, value)); + } } void Preferences::PutByteArray(const QString& key, const QByteArray& value) { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); this->Put(key, value.toBase64().data()); } void Preferences::PutBool(const QString& key, bool value) { this->Put(key, value ? "true" : "false"); } void Preferences::PutDouble(const QString& key, double value) { this->Put(key, QString::number(value)); } void Preferences::PutFloat(const QString& key, float value) { this->Put(key, QString::number(value)); } void Preferences::PutInt(const QString& key, int value) { this->Put(key, QString::number(value)); } void Preferences::PutLong(const QString& key, long value) { this->Put(key, QString::number(value)); } void Preferences::Remove(const QString& key) { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); PropertyMap::iterator it = m_Properties.find(key); if(it != m_Properties.end()) m_Properties.erase(it); } void Preferences::RemoveNode() { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); this->SetRemoved_unlocked(true); m_Parent->m_Children.erase(std::find(m_Parent->m_Children.begin(), m_Parent->m_Children.end(), Preferences::Pointer(this))); } void Preferences::Sync() { this->Flush(); } void Preferences::AssertValid_unlocked() const { if(m_Removed) { throw ctkIllegalStateException(QString("no node at '") + m_Path + "'"); } } void Preferences::AssertPath_unlocked(const QString& pathName) { if(pathName.indexOf("//") != -1) { throw ctkInvalidArgumentException(QString("Illegal // in m_Path m_Name '") + pathName + "'"); } int strLength = pathName.size(); if(strLength > 1 && pathName[strLength-1] == '/') { throw ctkInvalidArgumentException(QString("Trailing / in m_Path m_Name '") + pathName + "'"); } } IPreferences::Pointer Preferences::Parent() const { QMutexLocker scopedMutex(&m_Mutex); AssertValid_unlocked(); return IPreferences::Pointer(m_Parent); } void Preferences::SetDirty( bool _Dirty ) { { QMutexLocker scopedMutex(&m_Mutex); m_Dirty = _Dirty; } if(_Dirty) { this->OnChanged.Send(this); } } void Preferences::SetDirty_unlocked( bool _Dirty ) { m_Dirty = _Dirty; if(_Dirty) this->OnChanged.Send(this); /* for (ChildrenList::iterator it = m_Children.begin() ; it != m_Children.end(); ++it) { (*it)->SetDirty(_Dirty); } */ } void Preferences::SetRemoved( bool _Removed ) { QMutexLocker scopedMutex(&m_Mutex); this->SetRemoved_unlocked(_Removed); } void Preferences::SetRemoved_unlocked( bool _Removed ) { m_Removed = _Removed; for (ChildrenList::iterator it = m_Children.begin() ; it != m_Children.end(); ++it) { (*it)->SetRemoved(_Removed); } } /* Preferences::ChildrenList& Preferences::GetChildren() const { return m_Children; }*/ bool Preferences::IsRemoved() const { QMutexLocker scopedMutex(&m_Mutex); return m_Removed; } Preferences::~Preferences() { } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferences.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferences.h index 0922e94b19..762dd21202 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferences.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferences.h @@ -1,325 +1,342 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYPREFERENCES_H_ #define BERRYPREFERENCES_H_ #include #include "berryIBerryPreferences.h" #include #include namespace berry { class AbstractPreferencesStorage; - /// - /// Implementation of the OSGI Preferences Interface. - /// Wraps a DOMNode. - /// + + /** + * Implementation of the OSGI Preferences Interface. + * Wraps a DOMNode. + */ class org_blueberry_core_runtime_EXPORT Preferences: public IBerryPreferences { public: - /// - /// For use with berry::SmartPtr - /// - berryObjectMacro(berry::Preferences); - /// - /// Maps a string key to a string value - /// + + berryObjectMacro(berry::Preferences) + + /** + * Maps a string key to a string value + */ typedef QHash PropertyMap; - /// - /// The list of Child nodes - /// + + /** + * The list of Child nodes + */ typedef QList ChildrenList; - /// - /// Constructs a new preference node. - /// \param _Properties the key->value pairs of this preference node - /// \param _Path the absolute path to this node, e.g. "/general/editors/font" - /// \param _Name the name of this node, e.g. "font" - /// \param _FileName the absolute path to the file in which this preferences tree will be saved to - /// \param _Parent the parent node or 0 if this is the root - /// \param _Root the root of this preference tree - /// - Preferences(const PropertyMap& _Properties - , const QString& _Name - , Preferences* _Parent - , AbstractPreferencesStorage* _Storage); - - /// - /// Nothing to do here - /// + /** + * Constructs a new preference node. + * \param _Properties the key->value pairs of this preference node + * \param _Path the absolute path to this node, e.g. "/general/editors/font" + * \param _Name the name of this node, e.g. "font" + * \param _FileName the absolute path to the file in which this preferences tree will be saved to + * \param _Parent the parent node or 0 if this is the root + * \param _Root the root of this preference tree + */ + Preferences(const PropertyMap& _Properties, + const QString& _Name, + Preferences* _Parent, + AbstractPreferencesStorage* _Storage); + virtual ~Preferences(); - /// - /// Prints out the absolute path of the preference node. - /// + /** + * Prints out the absolute path of the preference node. + */ QString ToString() const; - /// - /// Returns if this node and his silblings have to be rewritten persistently - /// + + /** + * Returns if this node and his silblings have to be rewritten persistently + */ bool IsDirty() const; - /// - /// Returns if this node is removed - /// + + /** + * Returns if this node is removed + */ bool IsRemoved() const; - /// - /// Returns if this node has property with a specific key - /// + + /** + * Returns if this node has property with a specific key + */ bool Has(const QString& key) const; - /// - /// Returns true if the absolute paths are the same - /// + + /** + * Returns true if the absolute paths are the same + */ bool Equals(const Preferences* rhs) const; - /// - /// Returns all Properties as map. - /// + + /** + * Returns all Properties as map. + */ PropertyMap GetProperties() const; - /// - /// Returns a reference to the children list in order to add or remove nodes. - /// *ATTENTION*: Should only be used - /// when constructing the preferences tree from a persistent location. Normally, one would - /// only use the IPreferences methods - /// + + /** + * Returns a reference to the children list in order to add or remove nodes. + * *ATTENTION*: Should only be used + * when constructing the preferences tree from a persistent location. Normally, one would + * only use the IPreferences methods + */ ChildrenList GetChildren() const; //# Begin of IPreferences methods - /// - /// \see IPreferences::AbsolutePath() - /// + /** + * \see IPreferences::AbsolutePath() + */ virtual QString AbsolutePath() const; - /// - /// \see IPreferences::ChildrenNames() - /// + /** + * \see IPreferences::ChildrenNames() + */ virtual QStringList ChildrenNames() const; - /// - /// \see IPreferences::ChildrenNames() - /// + /** + * \see IPreferences::ChildrenNames() + */ virtual AbstractPreferencesStorage* GetStorage() const; - /// - /// \see IPreferences::Clear() - /// + /** + * \see IPreferences::Clear() + */ virtual void Clear(); - /// - /// \see IPreferences::Flush() - /// + /** + * \see IPreferences::Flush() + */ virtual void Flush(); - /// - /// \see IPreferences::Get() - /// + /** + * \see IPreferences::Get() + */ virtual QString Get(const QString& key, const QString& def) const; - /// - /// \see IPreferences::GetBool() - /// + /** + * \see IPreferences::GetBool() + */ virtual bool GetBool(const QString& key, bool def) const; - /// - /// \see IPreferences::GetByteArray() - /// + /** + * \see IPreferences::GetByteArray() + */ virtual QByteArray GetByteArray(const QString& key, const QByteArray& def) const; - /// - /// \see IPreferences::GetDouble() - /// + /** + * \see IPreferences::GetDouble() + */ virtual double GetDouble(const QString& key, double def) const; - /// - /// \see IPreferences::GetFloat() - /// + /** + * \see IPreferences::GetFloat() + */ virtual float GetFloat(const QString& key, float def) const; - /// - /// \see IPreferences::GetInt() - /// + /** + * \see IPreferences::GetInt() + */ virtual int GetInt(const QString& key, int def) const; - /// - /// \see IPreferences::GetLong() - /// + /** + * \see IPreferences::GetLong() + */ virtual long GetLong(const QString& key, long def) const; - /// - /// \see IPreferences::Keys() - /// + /** + * \see IPreferences::Keys() + */ QStringList Keys() const; - /// - /// \see IPreferences::Name() - /// + /** + * \see IPreferences::Name() + */ virtual QString Name() const; - /// - /// \see IPreferences::Node() - /// + /** + * \see IPreferences::Node() + */ virtual IPreferences::Pointer Node(const QString& pathName); - /// - /// \see IPreferences::NodeExists() - /// + /** + * \see IPreferences::NodeExists() + */ virtual bool NodeExists(const QString& pathName) const; - /// - /// \see IPreferences::Parent() - /// + /** + * \see IPreferences::Parent() + */ virtual IPreferences::Pointer Parent() const; - /// - /// \see IPreferences::Put() - /// + /** + * \see IPreferences::Put() + */ virtual void Put(const QString& key, const QString& value); - /// - /// \see IPreferences::PutByteArray() - /// + /** + * \see IPreferences::PutByteArray() + */ virtual void PutByteArray(const QString& key, const QByteArray& value); - /// - /// \see IPreferences::PutBool() - /// + /** + * \see IPreferences::PutBool() + */ virtual void PutBool(const QString& key, bool value); - /// - /// \see IPreferences::PutDouble() - /// + /** + * \see IPreferences::PutDouble() + */ virtual void PutDouble(const QString& key, double value); - /// - /// \see IPreferences::Sync() - /// + /** + * \see IPreferences::Sync() + */ virtual void PutFloat(const QString& key, float value); - /// - /// \see IPreferences::PutInt() - /// + /** + * \see IPreferences::PutInt() + */ virtual void PutInt(const QString& key, int value); - /// - /// \see IPreferences::PutLong() - /// + /** + * \see IPreferences::PutLong() + */ virtual void PutLong(const QString& key, long value); - /// - /// \see IPreferences::Remove() - /// + /** + * \see IPreferences::Remove() + */ virtual void Remove(const QString& key); - /// - /// \see IPreferences::RemoveNode() - /// + /** + * \see IPreferences::RemoveNode() + */ virtual void RemoveNode(); - /// - /// \see IPreferences::Sync() - /// + /** + * \see IPreferences::Sync() + */ virtual void Sync(); //# End of IPreferences methods protected: - /// - /// Checks if this node is about to be removed. - /// \throws IllegalStateException - /// + /** + * Checks if this node is about to be removed. + * \throws IllegalStateException + */ void AssertValid_unlocked() const; - /// - /// Checks a path value for validity. - /// \throws invalid_argument - /// + + /** + * Checks a path value for validity. + * \throws invalid_argument + */ static void AssertPath_unlocked(const QString& pathName); -// /// -// /// Converts any value to a string (using stream operator "<<") -// /// + +// /** +// * Converts any value to a string (using stream operator "<<") +// */ // template // static QString ToString(const T& obj, int precision = 12 ) // { // std::ostringstream s; // std::locale C("C"); // s.imbue(C); // s.precision(precision); s << obj; return s.str(); // } bool Has_unlocked(const QString& key) const; Preferences::Pointer Node_unlocked(const QString& pathName); - /// - /// Sets the dirty flag recursively on all child nodes. - /// + /** + * Sets the dirty flag recursively on all child nodes. + */ void SetDirty(bool _Dirty); void SetDirty_unlocked(bool _Dirty); - /// - /// Sets the removed flag recursively on all child nodes. - /// + + /** + * Sets the removed flag recursively on all child nodes. + */ void SetRemoved(bool _Removed); void SetRemoved_unlocked(bool _Removed); protected: - /// - /// Holds all Key/Value Pairs. - /// + + /** + * Holds all Key/Value Pairs. + */ QHash m_Properties; - /// - /// Holds all child nodes (explicit ownership). - /// + + /** + * Holds all child nodes (explicit ownership). + */ QList m_Children; - /// - /// Saves the absolute path of this node (calculated in the constructor) - /// + + /** + * Saves the absolute path of this node (calculated in the constructor) + */ const QString m_Path; - /// - /// Saves the name of this node (set when read from backend) - /// + + /** + * Saves the name of this node (set when read from backend) + */ const QString m_Name; - /// - /// Saves the parent of this node - /// + + /** + * Saves the parent of this node + */ Preferences* const m_Parent; - /// - /// Saves the root of this tree - /// + + /** + * Saves the root of this tree + */ Preferences* const m_Root; - /// - /// Saves if something changed on this branch. - /// Meaning that you would have to rewrite it. - /// + + /** + * Saves if something changed on this branch. + * Meaning that you would have to rewrite it. + */ bool m_Dirty; - /// - /// Saves if this Node is removed (will not be saved to the backend). - /// + + /** + * Saves if this Node is removed (will not be saved to the backend). + */ bool m_Removed; - /// - /// A storage to call the flush method. - /// + + /** + * A storage to call the flush method. + */ AbstractPreferencesStorage* const m_Storage; - /// - /// A mutex to avoid concurrency crashes. Mutable because we need to use Mutex::lock() in const functions - /// + + /** + * A mutex to avoid concurrency crashes. Mutable because we need to use Mutex::lock() in const functions + */ mutable QMutex m_Mutex; }; } #endif /* BERRYPREFERENCES_H_ */ 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 7d35c5c3f0..9edae74bc4 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,273 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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*/) { 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; + //QString typeName = contributor->GetActualName() + "_" + className; + QString typeName = className; int extensionTypeId = ExtensionType::type(typeName.toLatin1().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*/) { return nonTranslated; } QLocale RegistryStrategy::GetLocale() const { return QLocale(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berrySimpleExtensionPointFilter.cpp similarity index 61% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.cpp copy to BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berrySimpleExtensionPointFilter.cpp index ffd8e80060..0e585d89ca 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berrySimpleExtensionPointFilter.cpp @@ -1,37 +1,32 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berrySimpleExtensionPointFilter.h" -#include "berryMMMenuListener.h" - -#include +#include namespace berry { -MMMenuListener::MMMenuListener(berry::MenuManager* mm) - : QObject(), mm(mm) +SimpleExtensionPointFilter::SimpleExtensionPointFilter(const QString& id) + : m_Id(id) {} -void MMMenuListener::HandleAboutToShow() +bool SimpleExtensionPointFilter::Matches(const IExtensionPoint* target) const { - if (mm->removeAllWhenShown) - { - mm->RemoveAll(); - } - mm->Update(false, false); + return m_Id.isEmpty() ? true : m_Id == target->GetUniqueIdentifier(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berrySimpleExtensionPointFilter.h similarity index 57% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.h copy to BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berrySimpleExtensionPointFilter.h index babfd77662..eaf713af45 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berrySimpleExtensionPointFilter.h @@ -1,39 +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 BERRYSIMPLEEXTENSIONPOINTFILTER_H +#define BERRYSIMPLEEXTENSIONPOINTFILTER_H -#ifndef BERRYWORKBENCHACTIONCONSTANTS_H -#define BERRYWORKBENCHACTIONCONSTANTS_H +#include #include -#include - namespace berry { -struct BERRY_UI_QT WorkbenchActionConstants +struct SimpleExtensionPointFilter : IExtensionPointFilter::Concept { + const QString m_Id; + + SimpleExtensionPointFilter(const QString& id); - // Standard area for adding top level menus: - /** - * Name of group for adding new top-level menus (value "additions"). - */ - static const QString MB_ADDITIONS; + bool Matches(const IExtensionPoint* target) const; }; } -#endif // BERRYWORKBENCHACTIONCONSTANTS_H +#endif // BERRYSIMPLEEXTENSIONPOINTFILTER_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExecutableExtensionFactory.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExecutableExtensionFactory.h index 232a7e7a57..619d7bf0cd 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExecutableExtensionFactory.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExecutableExtensionFactory.h @@ -1,67 +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 BERRYIEXECUTABLEEXTENSIONFACTORY_H #define BERRYIEXECUTABLEEXTENSIONFACTORY_H #include +#include + namespace berry { /** * This interface allows extension providers to control how the instances provided * to extension-points are being created by referring to the factory instead of * referring to a class. For example, the following extension to the preference page * extension-point uses a factory called PreferencePageFactory. * \code * * * * * \endcode * *

* Effectively, factories give full control over the create executable extension process. *

* The factories are responsible for handling the case where the concrete instance * implements {@link IExecutableExtension}. *

* Given that factories are instantiated as executable extensions, they must provide a * 0-argument public constructor. * Like any other executable extension, they can be configured by implementing * the IExecutableExtension interface. *

* * @see IConfigurationElement */ -struct IExecutableExtensionFactory { +struct org_blueberry_core_runtime_EXPORT IExecutableExtensionFactory +{ virtual ~IExecutableExtensionFactory(); /** * Creates and returns a new instance. * * @exception CoreException if an instance of the executable extension * could not be created for any reason */ virtual QObject* Create() = 0; }; } Q_DECLARE_INTERFACE(berry::IExecutableExtensionFactory, "org.blueberry.IExecutableExtensionFactory") #endif // BERRYIEXECUTABLEEXTENSIONFACTORY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryAbstractGroupMarker.cpp b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtensionPointFilter.cpp similarity index 51% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryAbstractGroupMarker.cpp copy to BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtensionPointFilter.cpp index 813b474fd8..e72882ac11 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryAbstractGroupMarker.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtensionPointFilter.cpp @@ -1,42 +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. ===================================================================*/ - -#include "berryAbstractGroupMarker.h" +#include "berryIExtensionPointFilter.h" namespace berry { -AbstractGroupMarker::AbstractGroupMarker() +IExtensionPointFilter::IExtensionPointFilter(const IExtensionPointFilter::Concept* concept) + : m_Self(concept) { } -AbstractGroupMarker::AbstractGroupMarker(const QString& groupName) - : ContributionItem(groupName) +IExtensionPointFilter::Concept::~Concept() +{ + +} + +bool IExtensionPointFilter::IsNull() const { - Q_ASSERT(!groupName.isEmpty()); + return m_Self.get() == nullptr; } -QString AbstractGroupMarker::GetGroupName() const +const IExtensionPointFilter::Concept* IExtensionPointFilter::GetConcept() const { - return GetId(); + return m_Self.get(); } -bool AbstractGroupMarker::IsGroupMarker() const +bool IExtensionPointFilter::Matches(const IExtensionPoint* target) const { - return !(GetId().isEmpty()); + return m_Self->Matches(target); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtensionPointFilter.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtensionPointFilter.h new file mode 100644 index 0000000000..7bf4849c4a --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtensionPointFilter.h @@ -0,0 +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 BERRYIEXTENSIONPOINTFILTER_H +#define BERRYIEXTENSIONPOINTFILTER_H + +#include + +#include + +namespace berry { + +struct IExtensionPoint; + +/** + * A filter compares the given object to some pattern and returns + * true if the two match and false otherwise. + *

+ * This interface may be implemented by clients, however factory methods are + * available on IExtensionTracker. + *

+ */ +struct org_blueberry_core_runtime_EXPORT IExtensionPointFilter +{ + struct org_blueberry_core_runtime_EXPORT Concept { + virtual bool Matches(const IExtensionPoint* target) const = 0; + + virtual ~Concept(); + }; + + IExtensionPointFilter(const Concept* concept); + + bool IsNull() const; + + const Concept* GetConcept() const; + + /** + * Return true if the given object matches the criteria + * for this filter. + * + * @param target the object to match + * @return true if the target matches this filter + * and false otherwise + */ + bool Matches(const IExtensionPoint* target) const; + +private: + + std::shared_ptr m_Self; +}; + +} + +#endif // BERRYIEXTENSIONPOINTFILTER_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtensionRegistry.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtensionRegistry.h index f1824b0fe8..876cfd02d7 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtensionRegistry.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/registry/berryIExtensionRegistry.h @@ -1,383 +1,405 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIEXTENSIONREGISTRY_H #define BERRYIEXTENSIONREGISTRY_H #include "org_blueberry_core_runtime_Export.h" #include #include class QTranslator; namespace berry { struct IConfigurationElement; struct IContributor; struct IExtension; struct IExtensionPoint; +struct IExtensionPointFilter; struct IRegistryEventListener; /** * The extension registry holds the master list of all * discovered namespaces, extension points and extensions. *

* The extension registry can be queried, by name, for * extension points and extensions. *

*

* The various objects that describe the contents of the extension registry * ({@link IExtensionPoint}, {@link IExtension}, and {@link IConfigurationElement}) * 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 on these object except * isValid() will throw {@link org.eclipse.core.runtime.InvalidRegistryObjectException}. * 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 if it accesses extension registry objects, * because it's at risk if plug-in are removed. Similarly, tools that analyze * or display the extension registry are vulnerable. Client code can pre-test for * invalid objects by calling isValid(), which never throws this exception. * However, pre-tests are usually not sufficient because of the possibility of the * extension registry 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. *

*

* Extensions and extension points are declared by generic entities called * namespaces. The only fact known about namespaces is that they * have unique string-based identifiers. One example of a namespace * is a plug-in, for which the namespace id is the plug-in id. *

* 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 IExtensionRegistry { virtual ~IExtensionRegistry(); /** * Returns all configuration elements from all extensions configured * into the identified extension point. Returns an empty list if the extension * point does not exist, has no extensions configured, or none of the extensions * contain configuration elements. * * @param extensionPointId the unique identifier of the extension point * (e.g. "org.blueberry.core.applications") * @return the configuration elements */ virtual QList > GetConfigurationElementsFor( const QString& extensionPointId) const = 0; /** * Returns all configuration elements from all extensions configured * into the identified extension point. Returns an empty list if the extension * point does not exist, has no extensions configured, or none of the extensions * contain configuration elements. * * @param namespace the namespace for the extension point * (e.g. "org.eclipse.core.resources") * @param extensionPointName the simple identifier of the * extension point (e.g. "builders") * @return the configuration elements */ virtual QList > GetConfigurationElementsFor( const QString& namespaze, const QString& extensionPointName) const = 0; /** * Returns all configuration elements from the identified extension. * Returns an empty array if the extension does not exist or * contains no configuration elements. * * @param namespace the namespace for the extension point * (e.g. "org.eclipse.core.resources") * @param extensionPointName the simple identifier of the * extension point (e.g. "builders") * @param extensionId the unique identifier of the extension * (e.g. "com.example.acme.coolbuilder") * @return the configuration elements */ virtual QList > GetConfigurationElementsFor( const QString& namespaze, const QString& extensionPointName, const QString& extensionId) const = 0; /** * Returns the specified extension in this extension registry, * or null if there is no such extension. * * @param extensionId the unique identifier of the extension * (e.g. "com.example.acme.coolbuilder") * @return the extension, or null */ virtual SmartPointer GetExtension(const QString& extensionId) const = 0; /** * Returns the specified extension in this extension registry, * or null if there is no such extension. * The first parameter identifies the extension point, and the second * parameter identifies an extension plugged in to that extension point. * * @param extensionPointId the unique identifier of the extension point * (e.g. "org.eclipse.core.resources.builders") * @param extensionId the unique identifier of the extension * (e.g. "com.example.acme.coolbuilder") * @return the extension, or null */ virtual SmartPointer GetExtension(const QString& extensionPointId, const QString& extensionId) const = 0; /** * Returns the specified extension in this extension registry, * or null if there is no such extension. * The first two parameters identify the extension point, and the third * parameter identifies an extension plugged in to that extension point. * * @param namespace the namespace for the extension point * (e.g. "org.eclipse.core.resources") * @param extensionPointName the simple identifier of the * extension point (e.g. "builders") * @param extensionId the unique identifier of the extension * (e.g. "com.example.acme.coolbuilder") * @return the extension, or null */ virtual SmartPointer GetExtension(const QString& namespaze, const QString& extensionPointName, const QString& extensionId) const = 0; /** * Returns the extension point with the given extension point identifier * in this extension registry, or null if there is no such * extension point. * * @param extensionPointId the unique identifier of the extension point * (e.g., "org.blueberry.core.applications") * @return the extension point, or null */ virtual SmartPointer GetExtensionPoint(const QString& extensionPointId) const = 0; /** * Returns the extension point in this extension registry * with the given namespace and extension point simple identifier, * or null if there is no such extension point. * * @param namespace the namespace for the given extension point * (e.g. "org.eclipse.core.resources") * @param extensionPointName the simple identifier of the * extension point (e.g. "builders") * @return the extension point, or null */ virtual SmartPointer GetExtensionPoint(const QString& namespaze, const QString& extensionPointName) const = 0; /** * Returns all extension points known to this extension registry. * Returns an empty array if there are no extension points. * * @return the extension points known to this extension registry */ virtual QList > GetExtensionPoints() const = 0; /** * Returns all extension points declared in the given namespace. Returns an empty array if * there are no extension points declared in the namespace. * * @param namespace the namespace for the extension points * (e.g. "org.eclipse.core.resources") * @return the extension points in this registry declared in the given namespace */ virtual QList > GetExtensionPoints(const QString& namespaze) const = 0; /** * Returns all extension points supplied by the contributor, or null * if there are no such extension points. * * @param contributor the contributor for the extensions (for OSGi registry, bundles and * fragments are different contributors) * @return the extension points, or null * @since 3.4 */ virtual QList > GetExtensionPoints( const SmartPointer& contributor) const = 0; /** * Returns all extensions declared in the given namespace. Returns an empty array if * no extensions are declared in the namespace. * * @param namespace the namespace for the extensions * (e.g. "org.eclipse.core.resources") * @return the extensions in this registry declared in the given namespace */ virtual QList > GetExtensions(const QString& namespaze) const = 0; /** * Returns all extensions supplied by the contributor, or null if there * are no such extensions. * @param contributor the contributor for the extensions (for OSGi registry, bundles and * fragments are different contributors) * @return the extensions, or null */ virtual QList > GetExtensions(const SmartPointer& contributor) const = 0; /** * Returns all namespaces currently used by extensions and extension points in this * registry. Returns an empty array if there are no known extensions/extension points * in this registry. *

* The fully-qualified name of an extension point or an extension consist of * a namespace and a simple name (much like a qualified Java class name consist * of a package name and a class name). The simple names are presumed to be unique * in the namespace. *

* @return all namespaces known to this registry */ virtual QList GetNamespaces() const = 0; /** * Adds to this extension registry an extension point(s), extension(s), or * a combination of those described by the XML file. The information in * the XML file should be supplied in the same format as the plugin.xml; in fact, * Plug-in Manifest editor can be used to prepare the XML file. The top token * of the contribution (normally, "plugin" or "fragment" in the Plug-in Manifest * editor) is ignored by this method. *

* This method is an access controlled method. Proper token (master token or user token) should * be passed as an argument. Two registry keys are set in the registry constructor * {@link RegistryFactory#CreateRegistry(RegistryStrategy*, QObject*, QObject*)}: * master token and a user token. Master token allows all operations; user token allows * non-persisted registry elements to be modified. *

* * @param is stream open on the XML file. The XML file can contain an extension * point(s) or/and extension(s) described in the format similar to plugin.xml. The method * closes the device before returning. * @param contributor the contributor making this contribution. * @param persist indicates if the contribution(s) should be stored in the registry cache. If false, * contribution is not persisted in the registry cache and is lost on BlueBerry restart * @param name optional name of the contribution. Used for error reporting; might be QString() * @param translationBundle optional translator used for translations; might be NULL * @param token the key used to check permissions * @return true if the contribution was successfully processed and false otherwise * @throws ctkInvalidArgumentException if an incorrect token is passed * * @see IContributor */ virtual bool AddContribution(QIODevice* is, const SmartPointer& contributor, bool persist, const QString& name, QTranslator* translationBundle, QObject* token) = 0; /** * Removes the given extension from this registry. *

* This method is an access controlled method. Proper token (master token or user token) should * be passed as an argument. Two registry keys are set in the registry constructor * {@link RegistryFactory#CreateRegistry(RegistryStrategy*, QObject*, QObject*)}: * master token and a user token. Master token allows all operations; user token only * allows non-persisted registry elements to be modified. *

* * @param extension extension to be removed * @param token the key used to check permissions * @return true if the extension was successfully removed, and false otherwise * @throws ctkInvalidArgumentException if an incorrect token is passed */ virtual bool RemoveExtension(const SmartPointer& extension, QObject* token) = 0; /** * Removes the specified extension point from this registry. *

* This method is an access controlled method. Proper token (master token or user token) should * be passed as an argument. Two registry keys are set in the registry constructor * {@link RegistryFactory#CreateRegistry(RegistryStrategy*, QObject*, QObject*)}: * master token and a user token. Master token allows all operations; user token only * allows non-persisted registry elements to be modified. *

* * @param extensionPoint extension point to be removed * @param token the key used to check permissions * @return true if the extension point was successfully removed, and * false otherwise * @throws ctkInvalidArgumentException if incorrect token is passed */ virtual bool RemoveExtensionPoint(const SmartPointer& extensionPoint, QObject* token) = 0; /** * Call this method to properly stop the registry. The method stops registry event processing * and writes out cache information to be used in the next run. This is an access controlled * method; master token is required. *

* This method is an access controlled method. Master token should be passed as an argument. *

* @see RegistryFactory#CreateRegistry(RegistryStrategy*, QObject*, QObject*) * @param token master token for the registry * @throws IllegalArgumentException if incorrect token is passed */ virtual void Stop(QObject* token) = 0; /** * Adds the given listener for registry change events related to the specified * extension point or for changes to all extension points and underlying * extensions if the \c extensionPointId argument is empty. *

* Depending on activity, listeners of this type might receive a large number * of modifications and negatively impact overall system performance. Whenever * possible, consider registering listener specific to an extension point rather * than a "global" listener. *

* Once registered, a listener starts receiving notification of changes to * the registry. Registry change notifications are sent asynchronously. * The listener continues to receive notifications until it is removed. *

* This method has no effect if the listener is already registered. *

* @param listener the listener * @param extensionPointId the unique identifier of extension point * @see IExtensionPoint#GetUniqueIdentifier() */ virtual void AddListener(IRegistryEventListener* listener, const QString& extensionPointId = QString()) = 0; + /** + * Adds the given listener for registry change events for extension points + * matching the provided filter. + *

+ * Depending on activity, listeners of this type might receive a large number + * of modifications and negatively impact overall system performance. Whenever + * possible, consider registering listener specific to an extension point rather + * than a "global" listener. + *

+ * Once registered, a listener starts receiving notification of changes to + * the registry. Registry change notifications are sent asynchronously. + * The listener continues to receive notifications until it is removed. + *

+ * This method has no effect if the listener is already registered. + *

+ * @param listener the listener + * @param filter An extension point filter + * @see ExtensionTracker + */ + virtual void AddListener(IRegistryEventListener *listener, const IExtensionPointFilter& filter) = 0; + /** * Removes the given registry change listener from this registry. *

* This method has no effect if the listener is not registered. *

* @param listener the listener * @see #AddListener(IRegistryEventListener*, const QString&) */ virtual void RemoveListener(IRegistryEventListener* listener) = 0; /** * Call this method to determine if this extension registry supports multiple languages. *

* See the runtime option "-registryMultiLanguage" for enabling multi-language * support. *

* @return true if multiple languages are supported by this * instance of the extension registry; false otherwise. */ virtual bool IsMultiLanguage() const = 0; }; } Q_DECLARE_INTERFACE(berry::IExtensionRegistry, "org.blueberry.service.IExtensionRegistry") #endif // BERRYIEXTENSIONREGISTRY_H diff --git a/BlueBerry/Bundles/org.blueberry.test/src/harness/berryTestCase.cpp b/BlueBerry/Bundles/org.blueberry.test/src/harness/berryTestCase.cpp index a4e80f72a8..63ae33cce8 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/harness/berryTestCase.cpp +++ b/BlueBerry/Bundles/org.blueberry.test/src/harness/berryTestCase.cpp @@ -1,75 +1,77 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryTestCase.h" #include #include #ifdef BLUEBERRY_DEBUG_SMARTPOINTER #include #endif #include +#include + berry::TestCase::TestCase(const QString& testName) : CppUnit::TestCase(testName.toStdString()), m_LeakDetails(false), m_IgnoreLeakage(false) { } void berry::TestCase::LeakDetailsOn() { m_LeakDetails = true; } void berry::TestCase::IgnoreLeakingObjects() { BERRY_WARN << "Ignoring Leaking Objects!!"; m_IgnoreLeakage = true; } void berry::TestCase::DoSetUp() { } void berry::TestCase::DoTearDown() { } void berry::TestCase::setUp() { CppUnit::TestCase::setUp(); #ifdef BLUEBERRY_DEBUG_SMARTPOINTER DebugUtil::ResetObjectSummary(); #endif DoSetUp(); } void berry::TestCase::tearDown() { CppUnit::TestCase::tearDown(); DoTearDown(); #ifdef BLUEBERRY_DEBUG_SMARTPOINTER assert(m_IgnoreLeakage || !DebugUtil::PrintObjectSummary(m_LeakDetails)); #endif m_LeakDetails = false; } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.help/files.cmake b/BlueBerry/Bundles/org.blueberry.ui.qt.help/files.cmake index 3481e5662d..d83091471a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.help/files.cmake +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.help/files.cmake @@ -1,59 +1,61 @@ set(SRC_CPP_FILES ) set(INTERNAL_CPP_FILES berryHelpContentView.cpp berryHelpEditor.cpp berryHelpEditorFindWidget.cpp berryHelpEditorInput.cpp + berryHelpEditorInputFactory.cpp berryHelpIndexView.cpp berryHelpPerspective.cpp berryHelpPluginActivator.cpp berryHelpSearchView.cpp berryHelpTopicChooser.cpp berryHelpWebView.cpp berryQHelpEngineConfiguration.cpp berryQHelpEngineWrapper.cpp ) set(CPP_FILES ) set(MOC_H_FILES src/internal/berryHelpContentView.h src/internal/berryHelpEditor.h src/internal/berryHelpEditorFindWidget.h + src/internal/berryHelpEditorInputFactory.h src/internal/berryHelpIndexView.h src/internal/berryHelpPerspective.h src/internal/berryHelpPluginActivator.h src/internal/berryHelpSearchView.h src/internal/berryHelpTopicChooser.h src/internal/berryHelpWebView.h src/internal/berryQHelpEngineConfiguration.h src/internal/berryQHelpEngineWrapper.h ) set(CACHED_RESOURCE_FILES plugin.xml resources/help.png resources/helpIndex.png resources/helpSearch.png ) set(QRC_FILES resources/org_blueberry_ui_qt_help.qrc ) set(UI_FILES src/internal/berryHelpTopicChooser.ui ) 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.help/plugin.xml b/BlueBerry/Bundles/org.blueberry.ui.qt.help/plugin.xml index c7bd593c26..369ca172a6 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.help/plugin.xml +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.help/plugin.xml @@ -1,43 +1,49 @@ + + + + + diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInput.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInput.cpp index 9cbbefcb91..497d13aa63 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInput.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInput.cpp @@ -1,59 +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. ===================================================================*/ #include "berryHelpEditorInput.h" +#include "berryHelpEditorInputFactory.h" #include +#include + namespace berry { HelpEditorInput::HelpEditorInput(const QUrl &url) : url(url) { } bool HelpEditorInput::Exists() const { return !url.isEmpty(); } QString HelpEditorInput::GetName() const { if (url.isEmpty()) return "Untitled"; return url.toString(); } QString HelpEditorInput::GetToolTipText() const { return url.toString(); } +QIcon HelpEditorInput::GetIcon() const +{ + return QIcon(); +} + +const IPersistableElement* HelpEditorInput::GetPersistable() const +{ + return this; +} + +Object* HelpEditorInput::GetAdapter(const QString& adapterType) const +{ + return PlatformObject::GetAdapter(adapterType); +} + +QString HelpEditorInput::GetFactoryId() const +{ + return HelpEditorInputFactory::GetFactoryId(); +} + +void HelpEditorInput::SaveState(const SmartPointer& memento) const +{ + HelpEditorInputFactory::SaveState(memento, this); +} + bool HelpEditorInput::operator==(const berry::Object* o) const { if (const HelpEditorInput* input = dynamic_cast(o)) return this->url == input->url; return false; } QUrl HelpEditorInput::GetUrl() const { return url; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInput.h b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInput.h index 946b68170d..569af315e5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInput.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInput.h @@ -1,49 +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 BERRYHELPEDITORINPUT_H_ #define BERRYHELPEDITORINPUT_H_ #include +#include + +#include #include namespace berry { -class HelpEditorInput : public berry::IEditorInput +class HelpEditorInput : public PlatformObject, public IEditorInput, public IPersistableElement { public: - berryObjectMacro(HelpEditorInput); + berryObjectMacro(HelpEditorInput) HelpEditorInput(const QUrl& url = QUrl()); bool Exists() const; QString GetName() const; QString GetToolTipText() const; + QIcon GetIcon() const; + + const IPersistableElement* GetPersistable() const; + Object* GetAdapter(const QString &adapterType) const; + + QString GetFactoryId() const; + void SaveState(const SmartPointer& memento) const; + bool operator==(const berry::Object*) const; QUrl GetUrl() const; private: QUrl url; }; } #endif /*BERRYHELPEDITORINPUT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInputFactory.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInputFactory.cpp new file mode 100644 index 0000000000..e6c6b446ac --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInputFactory.cpp @@ -0,0 +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. + +===================================================================*/ + +#include "berryHelpEditorInputFactory.h" + +#include + +#include "berryHelpEditorInput.h" + +namespace berry { + +static QString TAG_PATH = "path"; +static QString ID_FACTORY = "org.blueberry.ui.internal.HelpEditorInputFactory"; + +IAdaptable* HelpEditorInputFactory::CreateElement(const SmartPointer& memento) +{ + QString url; + if (!memento->GetString(TAG_PATH, url)) + { + return nullptr; + } + + QUrl qUrl(url); + if (qUrl.isValid()) + { + return new HelpEditorInput(qUrl); + } + return nullptr; +} + +QString HelpEditorInputFactory::GetFactoryId() +{ + return ID_FACTORY; +} + +void HelpEditorInputFactory::SaveState(const SmartPointer& memento, const HelpEditorInput* input) +{ + QUrl url = input->GetUrl(); + memento->PutString(TAG_PATH, url.toString()); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInputFactory.h similarity index 52% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h copy to BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInputFactory.h index 90365ba2c1..874f76d1c0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.help/src/internal/berryHelpEditorInputFactory.h @@ -1,45 +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 BERRYQTWORKBENCHTWEAKLET_H_ -#define BERRYQTWORKBENCHTWEAKLET_H_ +#ifndef BERRYHELPEDITORINPUTFACTORY_H +#define BERRYHELPEDITORINPUTFACTORY_H -#include - -#include +#include namespace berry { -class BERRY_UI_QT QtWorkbenchTweaklet : public QObject, public WorkbenchTweaklet +class HelpEditorInput; + +class HelpEditorInputFactory : public QObject, public IElementFactory { Q_OBJECT - Q_INTERFACES(berry::WorkbenchTweaklet) + Q_INTERFACES(berry::IElementFactory) public: - berryObjectMacro(QtWorkbenchTweaklet) - - QtWorkbenchTweaklet(); - - Display* CreateDisplay(); + IAdaptable* CreateElement(const SmartPointer& memento); - bool IsRunning(); + static QString GetFactoryId(); + static void SaveState(const SmartPointer& memento, const HelpEditorInput* input); }; -} // namespace berry +} -#endif /*BERRYQTWORKBENCHTWEAKLET_H_*/ +#endif // BERRYHELPEDITORINPUTFACTORY_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 e7b331f78f..91bd69132f 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,478 +1,480 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryHelpEditorInputFactory.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; 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(const IWorkbenchWindow::Pointer& window); void WindowOpened(const IWorkbenchWindow::Pointer& window); private: // We use the same perspective listener for every window 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::HelpEditorInputFactory, 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.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.data()); } 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; 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(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(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.data()); } } HelpWindowListener::~HelpWindowListener() { if (!PlatformUI::IsWorkbenchRunning()) return; typedef QList WndVec; WndVec windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows(); for (WndVec::iterator i = windows.begin(); i != windows.end(); ++i) { (*i)->RemovePerspectiveListener(perspListener.data()); } } void HelpWindowListener::WindowClosed(const IWorkbenchWindow::Pointer& window) { window->RemovePerspectiveListener(perspListener.data()); } void HelpWindowListener::WindowOpened(const IWorkbenchWindow::Pointer& window) { 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/CMakeLists.txt b/BlueBerry/Bundles/org.blueberry.ui.qt/CMakeLists.txt index 918d7a02fc..d14d94e072 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/CMakeLists.txt +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/CMakeLists.txt @@ -1,23 +1,24 @@ project(org_blueberry_ui_qt) set(PLUGIN_exported_include_suffixes src src/actions src/application src/commands src/guitk src/handlers src/intro + src/model src/presentations src/services src/testing src/tweaklets src/util ) MACRO_CREATE_CTK_PLUGIN(EXPORT_DIRECTIVE BERRY_UI_QT EXPORTED_INCLUDE_SUFFIXES ${PLUGIN_exported_include_suffixes}) if(MITK_USE_Qt5) target_link_libraries(${PLUGIN_TARGET} PUBLIC Qt5::Widgets) endif() diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake b/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake index 8d56f4963a..0e5ebe0ec8 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/files.cmake @@ -1,447 +1,514 @@ set(SRC_CPP_FILES berryAbstractSourceProvider.cpp berryAbstractUICTKPlugin.cpp berryConstants.cpp berryDisplay.cpp berryEditorPart.cpp + berryExtensionFactory.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 + berryIElementFactory.cpp berryIFileEditorMapping.cpp berryIFolderLayout.cpp berryIMemento.cpp berryINullSelectionListener.cpp berryIPageLayout.cpp berryIPartListener.cpp berryIPageService.cpp berryIPartService.cpp berryIPathEditorInput.cpp + berryIPersistable.cpp + berryIPersistableElement.h 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 berryPropertyChangeEvent.cpp berryQModelIndexObject.cpp berryQtEditorPart.cpp berryQtItemSelection.cpp berryQtIntroPart.cpp berryQtPreferences.cpp berryQtSelectionProvider.cpp berryQtViewPart.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/berryCommandContributionItem.h actions/berryCommandContributionItem.cpp + actions/berryCommandContributionItemParameter.cpp actions/berryContributionItem.cpp actions/berryContributionItemFactory.cpp actions/berryContributionManager.cpp + actions/berryGroupMarker.cpp actions/berryIContributionItem.h actions/berryIContributionManager.h actions/berryIContributionManagerOverrides.cpp actions/berryIMenuManager.h #actions/berryMenuBarManager.cpp actions/berryMenuManager.cpp + actions/berryQActionContributionItem.cpp + actions/berryQActionProperties.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 #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 + #models + model/berryPerspectiveListModel.cpp + model/berryViewTreeModel.cpp + #tweaklets tweaklets/berryGuiWidgetsTweaklet.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 + dialogs/berryPerspectivesPreferencePage.cpp + dialogs/berrySavePerspectiveDialog.cpp + + handlers/berryCloseAllPerspectivesHandler.cpp + handlers/berryClosePerspectiveHandler.cpp + handlers/berryDynamicHelpHandler.cpp + handlers/berryHelpContentsHandler.cpp + handlers/berryIntroHandler.cpp + handlers/berryNewEditorHandler.cpp + handlers/berryOpenInNewWindowHandler.cpp + handlers/berryQuitHandler.cpp + handlers/berryResetPerspectiveHandler.cpp + handlers/berrySavePerspectiveHandler.cpp + handlers/berryShowPerspectiveHandler.cpp + handlers/berryShowViewHandler.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 + berryAbstractGroupMarker.cpp berryAbstractMenuAdditionCacheEntry.cpp berryAbstractPartSelectionTracker.cpp berryAbstractSelectionService.cpp berryActivePartExpression.cpp berryAlwaysEnabledExpression.cpp berryAndExpression.cpp berryBundleUtility.cpp - berryCommandContributionItemParameter.cpp + berryChangeToPerspectiveMenu.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 + berryDirtyPerspectiveMarker.cpp berryDragUtil.cpp berryEditorAreaHelper.cpp berryEditorDescriptor.cpp + berryEditorHistory.cpp + berryEditorHistoryItem.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 + berryKeywordRegistry.cpp berryLayoutHelper.cpp berryLayoutPart.cpp berryLayoutPartSash.cpp berryLayoutTree.cpp berryLayoutTreeNode.cpp berryMenuServiceFactory.cpp - berryMMMenuListener.cpp berryNestableHandlerService.cpp berryNullEditorInput.cpp + berryOpenPerspectivePropertyTester.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 + berryPerspectiveParameterValues.cpp berryPerspectiveRegistry.cpp berryPerspectiveRegistryReader.cpp berryPlaceholderFolderLayout.cpp + berryPolicy.cpp berryPreferenceConstants.cpp + berryPreferencePageParameterValues.cpp berryPresentablePart.cpp berryPresentationFactoryUtil.cpp berryPresentationSerializer.cpp berryQtControlWidget.cpp berryQtDnDControlWidget.cpp berryQtDisplay.cpp berryQtGlobalEventFilter.cpp berryQtMainWindowControl.cpp berryQtOpenPerspectiveAction.cpp berryQtPerspectiveSwitcher.cpp berryQtSafeApplication.cpp berryQtSash.cpp berryQtShell.cpp + berryQtShowPerspectiveDialog.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 + berryReopenEditorMenu.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 + berrySwitchToWindowMenu.cpp berryTweaklets.cpp + berryUIExtensionTracker.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/berryAbstractUICTKPlugin.h src/berryEditorPart.h + src/berryExtensionFactory.h src/berryQtSelectionProvider.h src/berryViewPart.h src/berryWorkbenchPart.h src/actions/berryCommandContributionItem.h + src/actions/berryMenuManager.h src/intro/berryIntroPart.h - src/handlers/berryShowViewHandler.h + src/model/berryPerspectiveListModel.h + src/model/berryViewTreeModel.h + src/internal/berryChangeToPerspectiveMenu.h src/internal/berryCommandServiceFactory.h src/internal/berryHandlerServiceFactory.h src/internal/berryMenuServiceFactory.h - src/internal/berryMMMenuListener.h + src/internal/berryOpenPerspectivePropertyTester.h + src/internal/berryPerspectiveParameterValues.h + src/internal/berryPreferencePageParameterValues.h src/internal/berryQtDisplay.h src/internal/berryQtGlobalEventFilter.h src/internal/berryQtMainWindowControl.h src/internal/berryQtOpenPerspectiveAction.h src/internal/berryQtPerspectiveSwitcher.h src/internal/berryQtSash.h + src/internal/berryQtShowPerspectiveDialog.h src/internal/berryQtShowViewAction.h + src/internal/berryQtShowViewDialog.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/berryReopenEditorMenu.h + src/internal/berryShowViewMenu.h + src/internal/berrySwitchToWindowMenu.h src/internal/berryWorkbenchPlugin.h src/internal/berryWorkbenchSourceProvider.h src/internal/defaultpresentation/berryNativeTabFolder.h src/internal/defaultpresentation/berryNativeTabItem.h src/internal/defaultpresentation/berryQCTabBar.h src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.h + src/internal/dialogs/berryPerspectivesPreferencePage.h + src/internal/dialogs/berrySavePerspectiveDialog.h + + src/internal/handlers/berryCloseAllPerspectivesHandler.h + src/internal/handlers/berryClosePerspectiveHandler.h + src/internal/handlers/berryDynamicHelpHandler.h + src/internal/handlers/berryHelpContentsHandler.h + src/internal/handlers/berryIntroHandler.h + src/internal/handlers/berryNewEditorHandler.h + src/internal/handlers/berryOpenInNewWindowHandler.h + src/internal/handlers/berryQuitHandler.h + src/internal/handlers/berryResetPerspectiveHandler.h + src/internal/handlers/berrySavePerspectiveHandler.h + src/internal/handlers/berryShowPerspectiveHandler.h + src/internal/handlers/berryShowViewHandler.h + src/internal/intro/berryEditorIntroAdapterPart.h ) set(UI_FILES + src/internal/berryQtShowPerspectiveDialog.ui src/internal/berryQtShowViewDialog.ui src/internal/berryQtStylePreferencePage.ui src/internal/berryQtStatusPart.ui + + src/internal/dialogs/berryPerspectivesPreferencePage.ui + src/internal/dialogs/berrySavePerspectiveDialog.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 7b93c3b156..f4402e5325 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/plugin.xml +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/plugin.xml @@ -1,167 +1,466 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - + + diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/schema/elementFactories.exsd b/BlueBerry/Bundles/org.blueberry.ui.qt/schema/elementFactories.exsd new file mode 100644 index 0000000000..ac2acf1c37 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/schema/elementFactories.exsd @@ -0,0 +1,167 @@ + + + + + + + + + This extension point is used to add element factories +to the workbench. An element factory is used to +recreate <samp>IAdaptable</samp> objects which are +persisted during workbench shutdown. +<p> +As an example, the element factory is used to +persist editor input. The input for an +editor must implement +<samp>berry::EditorInput</samp>. +The life cycle of an <samp>berry::IEditorInput</samp> within +an editor has a number of phases. +<ol> +<li> +The initial input for an editor is passed in during +editor creation. +</li> +<li> +On shutdown the workbench state is captured. +In this process the workbench will create a memento +for each open editor and its input. The input is +saved as a two part memento containing a factory ID +and any primitive data required to recreate the +element on startup. For more information see +the documentation on +<samp>berry::IPersistableElement</samp>. +</li> +<li> +On startup the workbench state is read and the +editors from the previous session are recreated. +In this process the workbench will recreate the input +element for each open editor. To do this it will +map the original factory ID for the input element +to a concrete factory class defined in the registry. +If a mapping exists, and the factory class is valid, +an instance of the factory class is created. Then +the workbench asks the factory to recreate the original +element from the remaining primitive data within the +memento. The resulting <samp>berry::IAdaptable</samp> is cast +to an <samp>berry::IEditorInput</samp> and passed to the +new editor. +</li> +</ol> + + + + + + + + + + + + a fully qualified identifier of the target extension point + + + + + + + an optional identifier of the extension instance + + + + + + + an optional name of the extension instance + + + + + + + + + + + + + + + a unique name that will be used to identify this factory. + + + + + + + a fully qualified name of a class that implements +<samp>berry::IElementFactory</samp> + + + + + + + + + + + + + + + The following is an example of an element factory extension: +<p> +<pre> + <extension + point = "org.blueberry.ui.elementFactories"> + <factory + id ="com.xyz.ElementFactory" + class="xyz::ElementFactory"> + </factory> + </extension> +</pre> +</p> + + + + + + + + + The value of the <samp>class</samp> attribute must +be a fully qualified name of a class that implements +<samp>berry::IElementFactory</samp>. An instance +of this class must create an <samp>berry::IAdaptable</samp> +object from a workbench memento. + + + + + + + + + The workbench provides an <samp>IResource</samp> factory. +Additional factories should be added to recreate other +<samp>berry::IAdaptable</samp> types commonly found in other +object models. + + + + + + + + + Copyright (c) 2002, 2005 IBM Corporation and others.<br> +All rights reserved. This program and the accompanying materials are made +available under the terms of the Eclipse Public License v1.0 which accompanies +this distribution, and is available at <a +href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a> + + + + diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/schema/menus.exsd b/BlueBerry/Bundles/org.blueberry.ui.qt/schema/menus.exsd new file mode 100644 index 0000000000..ecae8da9b0 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/schema/menus.exsd @@ -0,0 +1,646 @@ + + + + + + + + +<p> +This extension point allows the plug-in developer to add (contribute) a variety of custom additions to the BlueBerry framework: +<ul> + <li>Main Menu</li> + <li>Main Toolbars</li> + <li>View Menus/Toolbars: + <ul> + <li>View Dropdown Menu</li> + <li>View Toolbar</li> + <li>Context Menu(s)</li> + </ul> + </li> + <li>Trim</li> +</ul> +</p> +<p> +The general strategy for this mechanism is to separate the 'location' where the contributions should be inserted from the visibility and enablement state of the element. Each contribution first defines its insertion location through a Menu 'URI', a string (loosely) formatted according to the jave.net.URI format: +</p><p> +<b>"[Scheme]:[ID]?[ArgList]"</b> +<ul> +<li><b>Scheme</b> - The 'type' of the UI component into which the contributions will be added. It may be either "menu", "popup" or "toolbar". While 'popup' is indeed a form of menu it is provided to allow a distinction between a view's 'chevron' menu (for which we use the "menu" scheme) and its default context menu which, by convention, should be registered using the "popup" scheme.</li> +<li><b>ID</b> - This is the id of menu or toolbar into which the contributions should be added. By convention views should use their view id as the id of the root of their chevron and default popup menu. Note that there is no explicit distinction between contributions supporting editors and 'normal' contributions into the Menu Menu or Toolbar; both global contributions and editor contributions would use the "org.blueberry.ui.main.menu" id or "org.blueberry.ui.main.toolbar". A special id used with popup:, "org.blueberry.ui.popup.any", is reserved to handle contributions which are candidates to appear on any (top level) context menu. Note that these contributions are expected to implement a 'visibleWhen' expression sufficient to limit their visibility to appropriate menus</li> +<li><b>Query</b> - This field allows fine-grained definition of the specific location <i>within</i> a given menu. It has the form "[placement]=[id]" where placement is one of "before", "after", or "endof" and the id is expected to be the id of some IContributionItem in the menu.</li> +</ul> +<p> +This will define the location at which the contributions will appear in the BlueBerry UI. Once the insertion point has been defined the rest of the contributions describe the UI elements that will be added at that location. Each element supports a 'visibleWhen' expression that determines at run time whether a particular item should appear in the menu based on the system's current state (selection, active view/editor, context...). See <code>berry::ISources</code> for a list of currently +supported variables. +</p> + + + + + + + + + + + + + + + + + + + + + org.blueberry.ui.menus + + + + + + + An optional identifier of the extension instance. + + + + + + + An optional name of the extension instance. + + + + + + + + + + + + + A class element supporting the executable extension parsing syntax for both <code>widget</code> and <code>dynamic</code> elements. + + + + + + + + + + The class to load as an <code>IExecutableExtension</code>. + + + + + + + + + + + + + A core Expression that controls the visibility of the given element. + + + + + + + + + + + + + + + + + + + + + + If this attribute is set to <code>true</code>, then there should be no sub-elements. This just checks the enabled state of the command, and makes the corresponding element visible if the command is enabled. + + + + + + + + + + A parameter to either an executable extension or a command -- depending on where it appears in the extension. + + + + + + + The name is either the name of the parameter to pass to the executable extension, or the identifier of the parameter for the command. + + + + + + + + + + The value to pass for this parameter. + + + + + + + + + + <p>Defines an ordered set of additions to the command UI structure. The defined elements will be added into the command UI structure at the location specified by the <code>locationURI</code> element. +</p><p> +This should be the starting point for <i>all</i> contributions into menus, toolbars or trim, wherever they occur in the UI. +</p> + + + + + + + + + + + + + + + A <code>URI</code> specification that defines the insertion point at which the contained additions will be added. + +The format for the URI is comprised of three basic parts: + +Scheme: One of "menu", "popup" or "toolbar. Indicates the type of the manager used to handle the contributions +Id: This is either the id of an existing menu, a view id or the id of the editor 'type' +Query: The query format is &lt;placement&gt;=&lt;id&gt; where: + &lt;placement&gt; is either "before", "after", or "endof" and + &lt;id&gt; is the id of an existing menu item. The placement modifier is executed when this contribution is processed. Following contributions may change the final shape of the menu when they are processed. + + + + + + + If this optional attribute is specified the provided class will be instantiated and used to provide menu contributions at this location. If provided, all child elements will be ignored. + + + + + + + + + + By default popup contributions are not contributed to context menus that do not include an <b>additions</b> marker. + + + + + + + + + + Defines a new menu contribution at the given insertion point. + + + + + + + + + + + + + + + + The label to be displayed for this element when it is placed in either a menu or a toolbar. This value should be translatable. + + + + + + + + + + The 'id' of this menu contribution. If defined then it can be extended through other 'menuAddition' elements or the id can be used as a reference in the Query part of the location defining whether the additions are to go before or after this element. + + + + + + + The character of the Label that should be given the mnemonic affordance. This is to allow the menu system to re-define the value during translation without having to understand the various platforms' conventions for menu label definition (i.e. using the '&amp;' character...). + + + + + + + + + + A plugin relative path to the image to be used as the icon for this menu in either a menu or a toolbar. + + + + + + + + + + The tooltip to be displayed for this element when it is placed in a toolbar. This value should be translatable. + + + + + + + + + + Th commandId is used to update the submenu text with a keyboard shortcut. The command should have a handler that can launch a quickmenu version of this menu. + + + + + + + + + + + + + Defines a new Command Contribution at the defined insertion point. + + + + + + + + + + + The label to be displayed for this element when it is placed in either a menu. This value should be translatable. + + + + + + + + + + This is the id of the Command that is to be bound to this element. This is the hook into the Commands/Handlers/Key binding services that actually do the work should this item be selected. In many cases this command will have been defined in a previous extension declaration. + + + + + + + + + + The 'id' of this contribution. If defined then it can be used as a reference in the Query part of the location defining whether the additions are to go before or after this element. + + + + + + + The character of the Label that should be given the mnemonic affordance. This is to allow the menu system to re-define the value during translation without having to understand the various platforms' conventions for menu label definition (i.e. using the '&amp;' character...). + + + + + + + + + + a relative path of an icon used to visually represent the action in its context. +If omitted and the action appears in the toolbar, the Workbench will use a placeholder icon. The path is relative to the location of the plugin.xml file of the contributing plug-in, or the <code>ISharedImages</code> constant. + + + + + + + + + + a relative path of an icon used to visually represent the action in its context when the action is disabled. If omitted, the normal icon will simply appear greyed out. The path is relative to the location of the plugin.xml file of the contributing plug-in. The disabled icon will appear in toolbars but not in menus. Icons for disabled actions in menus will be supplied by the OS. + + + + + + + + + + a relative path of an icon used to visually represent the action in its context when the mouse pointer is over the action. If omitted, the normal icon will be used. The path is relative to the location of the plugin.xml file of the contributing plug-in. + + + + + + + + + + The tooltip to be displayed for this element when it is placed in a toolbar. This value should be translatable. + + + + + + + + + + a unique identifier indicating the help context for this action. If the action appears as a menu item, then pressing F1 while the menu item is highlighted will display help. This overrides the help context id provided by the active handler or command. + + + + + + + an attribute to define the user interface style type for the action. If omitted, then it is <samp>push</samp> by default. The attribute value will be one of the following: + <table border="0" width="80%"> + <tr> + <td valign="top" width="25"></td> + <td valign="top" nowrap><b>push</b></td> + <td valign="top">- as a regular menu item or tool item.</td> + </tr> + <tr> + <td valign="top" width="25"></td> + <td valign="top" nowrap><b>radio</b></td> + <td valign="top">- as a radio style menu item or tool item. Actions with the radio style within the same menu or toolbar group behave as a radio set. The initial value is specified by the <samp>state</samp> attribute.</td> + </tr> + <tr> + <td valign="top" width="25"></td> + <td valign="top" nowrap><b>toggle</b></td> + <td valign="top">- as a checked style menu item or as a toggle tool item. The initial value is specified by the <samp>state</samp> attribute.</td> + </tr> + <tr> + <td valign="top" width="25"></td> + <td valign="top" nowrap><b>pulldown</b></td> + <td valign="top">- (ToolBar only) Creates a ToolItem with the <code>SWT.DROP_DOWN</code> affordance. The URI of the menu is "menu:" + this item's ID.</td> + </tr> + </table> + + + + + + + + + + + + + + + + + + + For commands appearing in a toolbar, <code>FORCE_TEXT</code> will show text even if there is an icon. See CommandContributionItem. + + + + + + + + + + + + + + + + Inserts a separator at the current insertion point. + + + + + + + The 'id' of this contribution. If defined then it can be used as a reference in the Query part of the location defining whether the additions are to go before or after this element (or at the end of the logical group containing this element using the 'endof' value). +<p> +Separator contributions that have an id define the start of a logical group so the result of using the 'endof' value for placement is to search forward in the current menu to locate the next separator and to place the inserted elements before that element. If no trailing separator is found then the items are placed at the end of the menu. +</p> + + + + + + + Indicates whether or not the separator should be visible in the UI. <code>false</code> by default. + + + + + + + + + + Contributes a new ToolBar at the current insertion point. This element is only currently valid for CoolBarManagers, which can contain toolbars. For example, the trim location URIs specified in <code>org.blueberry.ui.menus.MenuUtil</code>. + + + + + + + + + + + + + + + + The 'id' of this toolbar contribution. If defined then it can be extended through other 'menuAddition' elements or the id can be used as a reference in the Query part of the location defining whether the additions are to go before or after this element. + + + + + + + The label to be displayed for this element when it is displayed in the customize perspective dialog. This value should be translatable. + + + + + + + + + + + + + Used to contribute controls to ToolBars in the workbench. The 'class' attribute must be a derivative of the +WorkbenchWindowControlContribution base class. +<p> +<b>NOTE:</b> Due to platform restrictions control contributions are only supported for toolbars; Attempts to contribute controls into a menu or popup will be treated as a NO-OP. +</p> + + + + + + + + + + The 'id' of this menu contribution. If defined then it can be used as a reference in the Query part of the location defining whether the additions are to go before or after this element. + + + + + + + The class which will be used to create the control that is to be hosted in a ToolBar. This must be a subclass of +WorkbenchWindowControlContribution which provides information as to the control's location (i.e. which workbench window it's being hosted in and the side of the window that it is currently being displayed on. + + + + + + + + + + + + + The element provides a mechanism that will call back into the defined class to provide an IContributionItem to be shown when the menu or toolbar is built. The defined class must be a derivative of the org.blueberry.jface.action.ContributionItem base class. It can also use org.blueberry.ui.action.CompoundContributionItem and provide an implementation for the abstract <code>getContributionItems</code> method to provide a dynamic menu item. + + + + + + + + + + + A unique identifier for this contribution. It is recommended that the identifier be prefixed by the plug-in name, to guarantee uniqueness. For example, a widget contributed by <code>org.blueberry.ui</code> might be called <code>org.blueberry.ui.widget1</code>. +<p> +If defined then it can be used as a reference in the Query part of the location defining whether the additions are to go before or after this element (or at the end of the logical group containing this element using the 'endof' value). +</p> + + + + + + + This class is expected to be a subclass of ContributionItem. The item may implement IWorkbenchContribution to be provided an IServiceLocator. + + + + + + + + + + + + + + + <p> +It is preferred that menu contributions be added in the <code>plugin.xml</code>. Plugins can +programmatically add their own menu contributions using <code>org.blueberry.ui.menus.IMenuService</code> and <code>org.blueberry.ui.menus.AbstractContributionFactory</code>, but should be sure to remove them if the plugin is unloaded. The <code>IMenuService</code> can be retrieved through any of the <code>IServiceLocators</code>, the workbench, the workbench window, or the part site. +</p> +<p> +See <a href="org_blueberry_ui_commands.html">org.blueberry.ui.commands</a> to define a command and <a href="org_blueberry_ui_handlers.html">org.blueberry.ui.handlers</a> to define an implementation for the command. +</p> +<p>To register a context menu, use the <code>IWorkbenchPartSite.registerContextMenu</code> methods.</p> + + + + + + + + + 3.3 + + + + + + + + + <p> +A basic extension looks like this. +</p> +<pre> + <extension + id="add.item" + point="org.blueberry.ui.menus"> + <menuContribution + locationURI="menu:someorg.somemenu.id?after=additions"> + <command + commandId="someorg.someid.someCommand" + icon="icons/anything.gif" + id="someorg.someid.BasicCmdItem" + label="Simple Item" + mnemonic="S"> + </command> + </menuContribution> + </extension> +</pre> +<p> +This is the simplest example; adding a command contribution after an existing menu's additions group. +</p> + + + + + + + + + + Copyright (c) 2005,2007 IBM Corporation and others.<br> +All rights reserved. This program and the accompanying materials are made +available under the terms of the Eclipse Public License v1.0 which accompanies +this distribution, and is available at <a +href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a> + + + + diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/schema/perspectiveExtensions.exsd b/BlueBerry/Bundles/org.blueberry.ui.qt/schema/perspectiveExtensions.exsd new file mode 100644 index 0000000000..d908729c13 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/schema/perspectiveExtensions.exsd @@ -0,0 +1,373 @@ + + + + + + + + + This extension point is used to extend perspectives +registered by other plug-ins. A perspective defines +the initial contents of the window action bars +(menu and toolbar) and the initial set of views +and their layout within a workbench page. +Other plug-ins may contribute actions or views to +the perspective which appear when the perspective +is selected. Optional additions by other plug-ins +are appended to the initial definition. + + + + + + + + + + + + + + + + + a fully qualified identifier of the target extension point + + + + + + + an optional identifier of the extension instance + + + + + + + an optional name of the extension instance + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + the unique identifier of the perspective (as specified in the registry) into which the contribution is made. If the value is set to "*" the extension is applied to all perspectives. + + + + + + + + + + + + + + + + + + + + + the unique identifier of the action set which will be added to the perspective. + + + + + + + + + + + + + + + the unique identifier of the view which will be added to the perspective's "Show View" submenu of the "Window" menu. + + + + + + + + + + + + + + + the unique identifier of the perspective which will be added to the perspective's "Open Perspective" submenu of the "Window" menu. + + + + + + + + + + + + + + + the unique identifier of the new wizard which will be added to the perspective's "New" submenu of the "File" menu. + + + + + + + + + + + + + + + the unique identifier of the view which will be added to the perspective's "Show In..." prompter in the Navigate menu. + + + + + + + + + + + + + + + the unique identifier of the view which will be added to the perspective layout. + + + + + + + + + + the unique identifier of a view which already exists in the perspective. This will be used as a reference point for placement of the view. The relationship between these two views is defined by <samp>relationship</samp>. Ignored if relationship is "fast". + + + + + + + + + + + + + + + + specifies the relationship between <samp>id</samp> and +<samp>relative</samp>. +The following values are supported: +<ul> +<b>fast</b> - the view extension will be created as a fast view. +<br><b>stack</b> - the view extension will be stacked with the relative +view in a folder. +<br><b>left, right, top, bottom</b> - the view extension will be placed +beside the relative view. In this case a <samp>ratio</samp> must also +be defined.</ul> + + + + + + + + + + + + + + + + + + + + + + + the percentage of area within the relative view which will be donated to the view extension. If the view extension is a fast view, the ratio is the percentage of the workbench the fast view will cover when active. This must be defined as a floating point value and lie between 0.05 and 0.95. + + + + + + + whether the view is initially visible when the perspective is opened. This attribute should have a value of "true" or "false" if used. +If this attribute is not used, the view will be initially visible by default. + + + + + + + whether the view is closeable in the target perspective. This attribute should have a value of "true" or "false" if used. If this attribute is not used, the view will be closeable, unless the perspective itself is marked as fixed. + + + + + + + whether the view is moveable. A non-moveable view cannot be moved either within the same folder, or moved between folders in the perspective. This attribute should have a value of "true" or "false" if used. +If this attribute is not used, the view will be moveable, unless the perspective itself is marked as fixed. + + + + + + + whether the view is a standalone view. A standalone view cannot be docked together with others in the same folder. This attribute should have a value of "true" or "false" if used. This attribute is ignored if the relationship attribute is "fast" or "stacked". If this attribute is not used, the view will be a regular view, not a standalone view (default is "false"). + + + + + + + whether the view's title is shown. This attribute should have a value of "true" or "false" if used. This attribute only applies to standalone views. If this attribute is not used, the view's title will be shown (default is "true"). + + + + + + + If the perspective extension will result in a new view stack being created (i.e. the 'relationship' attribute is one of left, right, top or bottom) this field determines the new stack's initial display state. + + + + + + + + + + + + The unique identifier of the Command which is to be removed from the menu. + +<strong>WARNING:</strong> This is considered to be a 'Product level' extension and should not be used in consumable plugins without great care. + + + + + + + + + + + + The unique identifier of the Command which is to be removed from thetoolbar. + +<strong>WARNING:</strong> This is considered to be a 'Product level' extension and should not be used in consumable plugins without great care. + + + + + + + + + + + + The following is an example of a perspective extension (note the subelements and the way attributes are used): +<p> +<pre> + <extension point="org.blueberry.ui.perspectiveExtensions"> + <perspectiveExtension + targetID="org.blueberry.ui.resourcePerspective"> + <actionSet id="org.xyz.MyActionSet"/> + <viewShortcut id="org.xyz.views.PackageExplorer"/> + <newWizardShortcut id="org.xyz.wizards.NewProjectCreationWizard"/> + <perspectiveShortcut id="org.xyz.MyPerspective"/> + <view id="org.xyz.views.PackageExplorer" + relative="org.blueberry.ui.views.ResourceNavigator" + relationship="stack"/> + <view id="org.xyz.views.TypeHierarchy" + relative="org.blueberry.ui.views.ResourceNavigator" + relationship="left" + ratio="0.50"/> + </perspectiveExtension> + </extension> +</pre> +</p> +<p> +In the example above, an action set, view shortcut, +new wizard shortcut, and perspective shortcut are +contributed to the initial contents of the +Resource Perspective. In addition, the +Package Explorer view is stacked on the +Resource Navigator and the Type Hierarchy View is +added beside the Resource Navigator. +</p> + + + + + + + + + The items defined within the perspective extension are contributed to the initial contents of the target perspective. Following this, the user may remove any contribution or add others to a perspective from within the workbench user interface. + + + + + + + + + + + Copyright (c) 2002, 2007 IBM Corporation and others.<br> +All rights reserved. This program and the accompanying materials are made +available under the terms of the Eclipse Public License v1.0 which accompanies +this distribution, and is available at <a +href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a> + + + + 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 48b5f29083..23b0e06648 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.cpp @@ -1,749 +1,725 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 #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 #if (QT_VERSION >= QT_VERSION_CHECK(5,0,0)) #include #endif namespace berry { ContributionItem::Modes CommandContributionItem::modes = ContributionItem::MODE_FORCE_TEXT; //class CommandUIElementListener : public IUIElementListener //{ //private: // CommandContributionItem* item; // public: // CommandUIElementListener(CommandContributionItem* item); // void UIElementDisposed(UIElement* item); //void UIElementSelected(SmartPointer item); //}; CommandContributionItem::CommandContributionItem( const SmartPointer& contributionParameters) : ContributionItem(contributionParameters->id) , action(0) , checkedState(false) { this->icon = contributionParameters->icon; this->label = contributionParameters->label; this->mnemonic = contributionParameters->mnemonic; this->tooltip = contributionParameters->tooltip; this->style = contributionParameters->style; this->helpContextId = contributionParameters->helpContextId; this->visibleEnabled = contributionParameters->visibleEnabled; this->mode = contributionParameters->mode; menuService = contributionParameters->serviceLocator->GetService(); commandService = contributionParameters->serviceLocator->GetService(); handlerService = contributionParameters->serviceLocator->GetService(); // bindingService = (IBindingService) contributionParameters.serviceLocator // .getService(IBindingService.class); this->CreateCommand(contributionParameters->commandId, contributionParameters->parameters); if (command) { try { class CommandUIElement : public UIElement { private: CommandContributionItem* item; public: CommandUIElement(CommandContributionItem* item, IServiceLocator* serviceLocator) : UIElement(serviceLocator), item(item) {} void SetText(const QString& text) { item->SetText(text); } void SetToolTip(const QString& text) { item->SetToolTip(text); } void SetIcon(const QIcon& icon) { item->SetIcon(icon); } void SetChecked(bool checked) { item->SetChecked(checked); } void SetDropDownId(const QString& id) { item->dropDownMenuOverride = id; } }; UIElement::Pointer callback(new CommandUIElement(this, contributionParameters->serviceLocator)); elementRef = commandService->RegisterElementForCommand(command, callback); command->GetCommand()->AddCommandListener(this->GetCommandListener()); this->SetImages(contributionParameters->serviceLocator, contributionParameters->iconStyle); if (contributionParameters->helpContextId.isEmpty()) { try { this->helpContextId = commandService->GetHelpContextId( contributionParameters->commandId); } catch (const NotDefinedException& /*e*/) { // it's OK to not have a helpContextId } } // IWorkbenchLocationService::Pointer wls = contributionParameters.serviceLocator // ->GetService(IWorkbenchLocationService::GetManifestName()).Cast(); // const IWorkbench* workbench = wls->GetWorkbench();; // if (workbench != 0 && !helpContextId.empty()) { // this->workbenchHelpSystem = workbench->GetHelpSystem(); // } } catch (const NotDefinedException& /*e*/) { WorkbenchPlugin::Log(QString("Unable to register menu item \"") + this->GetId() + "\", command \"" + contributionParameters->commandId + "\" not defined"); } } } -QAction* CommandContributionItem::Fill(QMenu* parent, QAction* before) +void CommandContributionItem::Fill(QMenu* parent, QAction* before) { - if (!command) + if (!command || action || parent == 0) { - return 0; - } - if (action || parent == 0) - { - return 0; + return; } // Menus don't support the pulldown style Style tmpStyle = style; if (tmpStyle == STYLE_PULLDOWN) tmpStyle = STYLE_PUSH; QAction* item = 0; if (before) { item = new QAction(icon, label, parent); parent->insertAction(before, item); } else { item = parent->addAction(icon, label); } item->setData(QVariant::fromValue(Object::Pointer(this))); item->setProperty("contributionItem", QVariant::fromValue(Object::Pointer(this))); + // if (workbenchHelpSystem != null) // { // workbenchHelpSystem.setHelp(item, helpContextId); // } - connect(item, SIGNAL(triggered()), this, SLOT(HandleWidgetSelection())); + connect(item, SIGNAL(triggered()), SLOT(HandleWidgetSelection())); + connect(item, SIGNAL(destroyed()), SLOT(HandleActionDestroyed())); action = item; this->Update(); this->UpdateIcons(); //bindingService.addBindingManagerListener(bindingManagerListener); - - return item; } -QAction *CommandContributionItem::Fill(QToolBar *parent, QAction *before) +void CommandContributionItem::Fill(QToolBar *parent, QAction *before) { - if (!command) - { - return 0; - } - if (action || parent == 0) + if (!command || action || parent == 0) { - return 0; + return; } 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()); + connect(item, SIGNAL(triggered()), SLOT(HandleWidgetSelection())); + connect(item, SIGNAL(destroyed()), SLOT(HandleActionDestroyed())); action = item; this->Update(); this->UpdateIcons(); //bindingService.addBindingManagerListener(bindingManagerListener); - - return item; } void CommandContributionItem::Update() { - this->Update(QString()); + this->Update(QString::null); } void CommandContributionItem::Update(const QString& /*id*/) { if (action) { QWidget* parent = action->parentWidget(); if(qobject_cast(parent)) { this->UpdateMenuItem(); } else if (qobject_cast(parent)) { this->UpdateMenuItem(); } else if (qobject_cast(parent)) { this->UpdateToolItem(); } } } void CommandContributionItem::UpdateMenuItem() { QString text = label; if (text.isEmpty()) { if (command.IsNotNull()) { try { text = command->GetCommand()->GetName(); } catch (const NotDefinedException& e) { // StatusManager.getManager().handle( // StatusUtil.newStatus(IStatus.ERROR, // "Update item failed " // + getId(), e)); BERRY_ERROR << "Update item failed " << GetId() << e.what(); } } } text = UpdateMnemonic(text); // String keyBindingText = null; // if (command != null) // { // TriggerSequence binding = bindingService // .getBestActiveBindingFor(command); // if (binding != null) // { // keyBindingText = binding.format(); // } // } // if (text != null) // { // if (keyBindingText == null) // { // item.setText(text); // } // else // { // item.setText(text + '\t' + keyBindingText); // } // } if (action->isChecked() != checkedState) { action->setChecked(checkedState); } // allow the handler update its enablement bool shouldBeEnabled = IsEnabled(); if (action->isEnabled() != shouldBeEnabled) { action->setEnabled(shouldBeEnabled); } } void CommandContributionItem::UpdateToolItem() { QString text = label; QString tooltip = label; if (text.isNull()) { if (command.IsNotNull()) { try { text = command->GetCommand()->GetName(); tooltip = command->GetCommand()->GetDescription(); if (tooltip.trimmed().isEmpty()) { tooltip = text; } } catch (const NotDefinedException& e) { // StatusManager.getManager().handle( // StatusUtil.newStatus(IStatus.ERROR, // "Update item failed " // + getId(), e)); BERRY_ERROR << "Update item failed " << GetId() << e.what(); } } } if ((icon.isNull() || (mode & MODE_FORCE_TEXT) == MODE_FORCE_TEXT) && !text.isNull()) { action->setText(text); } QString toolTipText = GetToolTipText(tooltip); action->setToolTip(toolTipText); if (action->isChecked() != checkedState) { action->setChecked(checkedState); } // allow the handler update its enablement bool shouldBeEnabled = IsEnabled(); if (action->isEnabled() != shouldBeEnabled) { action->setEnabled(shouldBeEnabled); } } CommandContributionItem::~CommandContributionItem() { if (elementRef) { commandService->UnregisterElement(elementRef); } if (commandListener) { command->GetCommand()->RemoveCommandListener(commandListener.data()); } } bool CommandContributionItem::IsEnabled() const { if (command) { command->GetCommand()->SetEnabled(menuService->GetCurrentState()); return command->GetCommand()->IsEnabled(); } return false; } bool CommandContributionItem::IsVisible() const { if (visibleEnabled) { return ContributionItem::IsVisible() && this->IsEnabled(); } return ContributionItem::IsVisible(); } void CommandContributionItem::SetImages(IServiceLocator* locator, const QString& iconStyle) { if (icon.isNull()) { ICommandImageService* service = locator->GetService(); if (service) { icon = service->GetImage(command->GetId(), iconStyle); } } } ICommandListener* CommandContributionItem::GetCommandListener() { if (!commandListener) { class MyCommandListener : public ICommandListener { private: CommandContributionItem* item; public: MyCommandListener(CommandContributionItem* item) : item(item) {} void CommandChanged(const SmartPointer& commandEvent) { if (commandEvent->IsHandledChanged() || commandEvent->IsEnabledChanged() || commandEvent->IsDefinedChanged()) { item->UpdateCommandProperties(commandEvent); } } }; commandListener.reset(new MyCommandListener(this)); } return commandListener.data(); } void CommandContributionItem::UpdateCommandProperties(const SmartPointer< const CommandEvent> commandEvent) { if (commandEvent->IsHandledChanged()) { dropDownMenuOverride = ""; } if (!action) { return; } Display* display = Display::GetDefault(); typedef AsyncRunnable, CommandContributionItem > UpdateRunnable; Poco::Runnable* update = new UpdateRunnable(this, &CommandContributionItem::UpdateCommandPropertiesInUI, commandEvent); if (display->InDisplayThread()) { update->run(); } else { display->AsyncExec(update); } } void CommandContributionItem::UpdateCommandPropertiesInUI(const SmartPointer< const CommandEvent>& commandEvent) { if (commandEvent->GetCommand()->IsDefined()) - { - this->Update(); - } - if (commandEvent->IsEnabledChanged() - || commandEvent->IsHandledChanged()) - { - if (visibleEnabled) - { - IContributionManager* parent = this->GetParent(); - if (parent) - { - parent->Update(true); - } - } - } + { + this->Update(); + } + if (commandEvent->IsEnabledChanged() + || commandEvent->IsHandledChanged()) + { + if (visibleEnabled) + { + IContributionManager* parent = this->GetParent(); + if (parent) + { + parent->Update(true); + } + } + } +} + +void CommandContributionItem::HandleActionDestroyed() +{ + this->action = nullptr; } bool CommandContributionItem::ShouldRestoreAppearance(const SmartPointer& handler) { // if no handler or handler doesn't implement IElementUpdater, // restore the contributed elements if (handler.IsNull()) return true; if (!(handler.Cast())) return true; // special case, if its HandlerProxy, then check the actual handler // if (handler instanceof HandlerProxy) { // HandlerProxy handlerProxy = (HandlerProxy) handler; // IHandler actualHandler = handlerProxy.getHandler(); // return shouldRestoreAppearance(actualHandler); // } return false; } SmartPointer CommandContributionItem::GetCommand() const { return command; } void CommandContributionItem::CreateCommand(const QString &commandId, const QHash ¶meters) { if (commandId.isEmpty()) { // StatusManager.getManager().handle(StatusUtil.newStatus(IStatus.ERROR, // "Unable to create menu item \"" + getId() // + "\", no command id", null)); BERRY_ERROR << "Unable to create menu item \"" << this->GetId().toStdString() << "\", no command id"; return; } Command::Pointer cmd = commandService->GetCommand(commandId); if (!cmd->IsDefined()) { // StatusManager.getManager().handle(StatusUtil.newStatus( // IStatus.ERROR, "Unable to create menu item \"" + getId() // + "\", command \"" + commandId + "\" not defined", null)); BERRY_ERROR << "Unable to create menu item \"" << this->GetId().toStdString() << "\", command \"" << commandId.toStdString() << "\" not defined"; return; } command = ParameterizedCommand::GenerateCommand(cmd, parameters); } QString CommandContributionItem::GetToolTipText(const QString& text) const { QString tooltipText = tooltip; if (tooltip.isNull()) { if (!text.isNull()) { tooltipText = text; } else { tooltipText = ""; } } // TriggerSequence activeBinding = bindingService // .getBestActiveBindingFor(command); // if (activeBinding != null && !activeBinding.isEmpty()) // { // String acceleratorText = activeBinding.format(); // if (acceleratorText != null // && acceleratorText.length() != 0) // { // tooltipText = NLS.bind(CommandMessages.Tooltip_Accelerator, // tooltipText, acceleratorText); // } // } return tooltipText; } QString CommandContributionItem::UpdateMnemonic(const QString &s) { if (mnemonic.isNull() || s.isEmpty()) { return s; } int idx = s.indexOf(mnemonic); if (idx == -1) { return s; } return s.left(idx) + '&' + s.mid(idx); } //SmartPointer CommandContributionItem::GetItemListener() //{ // if (!itemListener) // { // itemListener = new CommandUIElementListener(this); // } // return itemListener; //} void CommandContributionItem::HandleWidgetSelection() { // // Special check for ToolBar dropdowns... // if (this->OpenDropDownMenu(event)) // //return; if ((style & STYLE_CHECK) != 0) { checkedState = action->isChecked(); } try { handlerService->ExecuteCommand(command, UIElement::Pointer(0)); } catch (const ExecutionException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotDefinedException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotEnabledException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } catch (const NotHandledException& e) { WorkbenchPlugin::Log("Failed to execute item " + GetId(), e); } } -#if (QT_VERSION < QT_VERSION_CHECK(5,0,0)) -void CommandContributionItem::connectNotify(const char *signal) -{ - qDebug() << "Connected to:" << signal; -} -void CommandContributionItem::disconnectNotify(const char *signal) -{ - qDebug() << "Disconnected from:" << signal; -} -#else -void CommandContributionItem::connectNotify(const QMetaMethod& signal) -{ - qDebug() << "Connected to:" << signal.name(); -} -void CommandContributionItem::disconnectNotify(const QMetaMethod& signal) -{ - qDebug() << "Disconnected from:" << signal.name(); -} -#endif - //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 f8028c05ba..72601d7424 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItem.h @@ -1,218 +1,212 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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 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; 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); + void Fill(QMenu* parent, QAction* before); - QAction* Fill(QToolBar* parent, QAction* before); + void Fill(QToolBar* parent, QAction* before); void Update(); void Update(const QString& id); bool IsEnabled() const; bool IsVisible() const; void UpdateCommandPropertiesInUI(const SmartPointer& 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(); -#if (QT_VERSION < QT_VERSION_CHECK(5,0,0)) - void connectNotify(const char *signal); - void disconnectNotify(const char *signal); -#else - void connectNotify(const QMetaMethod& signal); - void disconnectNotify(const QMetaMethod& signal); -#endif /** * 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 HandleActionDestroyed(); void HandleWidgetSelection(); }; } #endif /* BERRYCOMMANDCONTRIBUTIONITEM_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandContributionItemParameter.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItemParameter.cpp similarity index 97% rename from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandContributionItemParameter.cpp rename to BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItemParameter.cpp index e68f37da4c..5935e92d90 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandContributionItemParameter.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItemParameter.cpp @@ -1,50 +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 "berryCommandContributionItemParameter.h" namespace berry { CommandContributionItemParameter::CommandContributionItemParameter(IServiceLocator* serviceLocator, const QString& id, const QString& commandId, CommandContributionItem::Style style) - : serviceLocator(serviceLocator), id(id), commandId(commandId), style(style), visibleEnabled(true) + : serviceLocator(serviceLocator), id(id), commandId(commandId), style(style), visibleEnabled(false) { } CommandContributionItemParameter::CommandContributionItemParameter(IServiceLocator* serviceLocator, const QString& id, const QString& commandId, const QHash& parameters, const QIcon& icon, const QString label, const QChar& mnemonic, const QString& tooltip, CommandContributionItem::Style style, const QString& helpContextId, bool visibleEnabled) : serviceLocator(serviceLocator) , id(id) , commandId(commandId) , parameters(parameters) , icon(icon) , label(label) , mnemonic(mnemonic) , tooltip(tooltip) , style(style) , helpContextId(helpContextId) , visibleEnabled(visibleEnabled) { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandContributionItemParameter.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItemParameter.h similarity index 98% rename from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandContributionItemParameter.h rename to BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryCommandContributionItemParameter.h index 03dc837172..b954e9afa9 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCommandContributionItemParameter.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/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 virtual Object +class BERRY_UI_QT 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/actions/berryContributionItem.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItem.cpp index 85eb593c3c..4563bcfbd7 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItem.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItem.cpp @@ -1,126 +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 "berryContributionItem.h" #include "berryIContributionManager.h" namespace berry { void ContributionItem::Fill(QStatusBar* /*parent*/) { } -QAction* ContributionItem::Fill(QMenu* /*menu*/, QAction * /*before*/) +void ContributionItem::Fill(QMenu* /*menu*/, QAction * /*before*/) { - return 0; } -QAction *ContributionItem::Fill(QMenuBar* /*menu*/, QAction* /*before*/) +void ContributionItem::Fill(QMenuBar* /*menu*/, QAction* /*before*/) { - return 0; } -QAction* ContributionItem::Fill(QToolBar* /*parent*/, QAction * /*before*/) +void ContributionItem::Fill(QToolBar* /*parent*/, QAction * /*before*/) { - return 0; } void ContributionItem::SaveWidgetState() { } QString ContributionItem::GetId() const { return id; } IContributionManager* ContributionItem::GetParent() const { return parent; } bool ContributionItem::IsDirty() const { // @issue should this be false instead of calling isDynamic()? return IsDynamic(); } bool ContributionItem::IsEnabled() const { return true; } bool ContributionItem::IsDynamic() const { return false; } bool ContributionItem::IsGroupMarker() const { return false; } bool ContributionItem::IsSeparator() const { return false; } bool ContributionItem::IsVisible() const { return visible; } void ContributionItem::SetVisible(bool visible) { this->visible = visible; } QString ContributionItem::ToString() const { return QString(GetClassName()) + "(id=" + this->GetId() + ")"; } void ContributionItem::Update() { } void ContributionItem::SetParent(IContributionManager* parent) { this->parent = parent; } void ContributionItem::Update(const QString& /*id*/) { } void ContributionItem::SetId(const QString& itemId) { id = itemId; } ContributionItem::ContributionItem() : visible(true), parent(0) { } ContributionItem::ContributionItem(const QString& id) : id(id), visible(true), parent(0) { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItem.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItem.h index 33939c2f4e..cdb73651e9 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItem.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItem.h @@ -1,231 +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 BERRYCONTRIBUTIONITEM_H #define BERRYCONTRIBUTIONITEM_H #include "berryIContributionItem.h" #include namespace berry { /** * An abstract base implementation for contribution items. */ -class ContributionItem : public IContributionItem +class BERRY_UI_QT ContributionItem : public IContributionItem { public: berryObjectMacro(ContributionItem) enum Mode { DEFAULT = 0x00, /** * 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. */ MODE_FORCE_TEXT = 0x01 }; Q_DECLARE_FLAGS(Modes, Mode) enum Style { /** * A push button tool item or menu item. */ STYLE_PUSH = 0x01, /** * A checked tool item or menu item. */ STYLE_CHECK = 0x02, /** * A radio-button style menu item. */ STYLE_RADIO = 0x04, /** * A ToolBar pulldown item. */ STYLE_PULLDOWN = 0x08 }; /** * The default implementation of this IContributionItem * method does nothing. Subclasses may override. */ void Fill(QStatusBar* parent); /** * The default implementation of this IContributionItem * method does nothing. Subclasses may override. */ - QAction* Fill(QMenu* menu, QAction* before); + void Fill(QMenu* menu, QAction* before); /** * The default implementation of this IContributionItem * method does nothing. Subclasses may override. */ - QAction* Fill(QMenuBar* menu, QAction* before); + void Fill(QMenuBar* menu, QAction* before); /** * The default implementation of this IContributionItem * method does nothing. Subclasses may override. */ - QAction* Fill(QToolBar* parent, QAction* before); + void Fill(QToolBar* parent, QAction* before); /** * The default implementation of this IContributionItem * method does nothing. Subclasses may override. */ void SaveWidgetState(); /* * Method declared on IContributionItem. */ QString GetId() const; /** * Returns the parent contribution manager, or null if this * contribution item is not currently added to a contribution manager. * * @return the parent contribution manager, or null */ IContributionManager *GetParent() const; /** * The default implementation of this IContributionItem * method returns false. Subclasses may override. */ bool IsDirty() const; /** * The default implementation of this IContributionItem * method returns true. Subclasses may override. */ bool IsEnabled() const; /** * The default implementation of this IContributionItem * method returns false. Subclasses may override. */ bool IsDynamic() const; /** * The default implementation of this IContributionItem * method returns false. Subclasses may override. */ bool IsGroupMarker() const; /** * The default implementation of this IContributionItem * method returns false. Subclasses may override. */ bool IsSeparator() const; /** * The default implementation of this IContributionItem * method returns the value recorded in an internal state variable, * which is true by default. setVisible * should be used to change this setting. */ bool IsVisible() const; /** * The default implementation of this IContributionItem * method stores the value in an internal state variable, * which is true by default. */ void SetVisible(bool visible); /** * Returns a string representation of this contribution item * suitable only for debugging. */ QString ToString() const; /** * The default implementation of this IContributionItem * method does nothing. Subclasses may override. */ void Update(); /* * Method declared on IContributionItem. */ void SetParent(IContributionManager* parent); /** * The ContributionItem implementation of this * method declared on IContributionItem does nothing. * Subclasses should override to update their state. */ void Update(const QString& id); /** * The ID for this contribution item. It should be set once either in the * constructor or using this method. * * @param itemId * @see #getId() */ void SetId(const QString& itemId); protected: /** * Creates a contribution item with a null id. * Calls this(String) with null. */ ContributionItem(); /** * Creates a contribution item with the given (optional) id. * The given id is used to find items in a contribution manager, * and for positioning items relative to other items. * * @param id the contribution item identifier, or null */ ContributionItem(const QString& id); private: /** * The identifier for this contribution item, of null if none. */ QString id; /** * Indicates this item is visible in its manager; true * by default. */ bool visible; /** * The parent contribution manager for this item */ IContributionManager* parent; }; } #endif // BERRYCONTRIBUTIONITEM_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItemFactory.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItemFactory.cpp index 09111163c6..2467dcc804 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItemFactory.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItemFactory.cpp @@ -1,57 +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. ===================================================================*/ #include "berryContributionItemFactory.h" #include #include +#include "internal/berryChangeToPerspectiveMenu.h" #include "internal/berryShowViewMenu.h" +#include "internal/berryReopenEditorMenu.h" +#include "internal/berrySwitchToWindowMenu.h" namespace berry { ContributionItemFactory::ContributionItemFactory(const QString& contributionItemId) : contributionItemId(contributionItemId) {} QString ContributionItemFactory::GetId() const { return contributionItemId; } +class OpenWindowsFactory : public ContributionItemFactory +{ +public: + + OpenWindowsFactory() + : ContributionItemFactory("openWindows") + {} + + IContributionItem::Pointer Create(IWorkbenchWindow *window) + { + if (window == nullptr) + { + throw ctkInvalidArgumentException("window must not be null"); + } + IContributionItem::Pointer item(new SwitchToWindowMenu(window, GetId(), true)); + return item; + } +}; + +const QScopedPointer +ContributionItemFactory::OPEN_WINDOWS(new OpenWindowsFactory()); + class ViewsShortlistFactory : public ContributionItemFactory { public: ViewsShortlistFactory() : ContributionItemFactory("viewsShortlist") {} IContributionItem::Pointer Create(IWorkbenchWindow* window) { if (window == 0) { - throw std::invalid_argument("window must not be null"); + throw ctkInvalidArgumentException("window must not be null"); } IContributionItem::Pointer item(new ShowViewMenu(window, GetId())); return item; } }; -ContributionItemFactory* const ContributionItemFactory::VIEWS_SHORTLIST = new ViewsShortlistFactory(); +const QScopedPointer +ContributionItemFactory::VIEWS_SHORTLIST(new ViewsShortlistFactory()); + +class ReopenEditorsFactory : public ContributionItemFactory +{ +public: + + ReopenEditorsFactory() + : ContributionItemFactory("reopenEditors") + {} + + IContributionItem::Pointer Create(IWorkbenchWindow* window) + { + if (window == nullptr) + { + throw ctkInvalidArgumentException("window must not be null"); + } + IContributionItem::Pointer item(new ReopenEditorMenu(window, GetId(), true)); + return item; + } +}; + +const QScopedPointer +ContributionItemFactory::REOPEN_EDITORS(new ReopenEditorsFactory()); + +class PerspectivesShortlistFactory : public ContributionItemFactory +{ +public: + + PerspectivesShortlistFactory() + : ContributionItemFactory("perspectivesShortlist") + {} + + IContributionItem::Pointer Create(IWorkbenchWindow* window) + { + if (window == nullptr) + { + throw ctkInvalidArgumentException("window must not be null"); + } + IContributionItem::Pointer item(new ChangeToPerspectiveMenu(window, GetId())); + return item; + } +}; + +const QScopedPointer +ContributionItemFactory::PERSPECTIVES_SHORTLIST(new PerspectivesShortlistFactory()); } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItemFactory.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItemFactory.h index fd6732c66d..6cd54e8dda 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItemFactory.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionItemFactory.h @@ -1,106 +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. ===================================================================*/ #ifndef BERRYCONTRIBUTIONITEMFACTORY_H #define BERRYCONTRIBUTIONITEMFACTORY_H #include #include #include namespace berry { struct IContributionItem; struct IWorkbenchWindow; /** * Access to standard contribution items provided by the workbench. *

* Most of the functionality of this class is provided by * static methods and fields. * Example usage: *

  * MenuManager menu = ...;
- * IContributionItem reEdit
- *     = ContributionItemFactory.REOPEN_EDITORS.create(window);
- * menu.add(reEdit);
+ * IContributionItem::Pointer reEdit
+ *     = ContributionItemFactory::REOPEN_EDITORS->Create(window);
+ * menu->Add(reEdit);
  * 
*

*

* Clients may declare subclasses that provide additional application-specific * contribution item factories. *

*/ class BERRY_UI_QT ContributionItemFactory { private: /** * Id of contribution items created by this factory. */ const QString contributionItemId; protected: /** * Creates a new workbench contribution item factory with the given id. * * @param contributionItemId the id of contribution items created by this factory */ ContributionItemFactory(const QString& contributionItemId); public: /** * Creates a new standard contribution item for the given workbench window. *

* A typical contribution item automatically registers listeners against the * workbench window so that it can keep its enablement state up to date. * Ordinarily, the window's references to these listeners will be dropped * automatically when the window closes. However, if the client needs to get * rid of a contribution item while the window is still open, the client must * call IContributionItem#dispose to give the item an * opportunity to deregister its listeners and to perform any other cleanup. *

* * @param window the workbench window * @return the workbench contribution item */ virtual SmartPointer Create(IWorkbenchWindow* window) = 0; /** * Returns the id of this contribution item factory. * * @return the id of contribution items created by this factory */ QString GetId() const; + /** + * Workbench contribution item (id "openWindows"): A list of windows + * currently open in the workbench. Selecting one of the items makes the + * corresponding window the active window. + * This action dynamically maintains the list of windows. + */ + static const QScopedPointer OPEN_WINDOWS; + /** * Workbench contribution item (id "viewsShortlist"): A list of views * available to be opened in the window, arranged as a shortlist of * promising views and an "Other" subitem. Selecting * one of the items opens the corresponding view in the active window. * This action dynamically maintains the view shortlist. */ - static ContributionItemFactory* const VIEWS_SHORTLIST; + static const QScopedPointer VIEWS_SHORTLIST; + + /** + * Workbench contribution item (id "reopenEditors"): A list of recent + * editors (with inputs) available to be reopened in the window. Selecting + * one of the items reopens the corresponding editor on its input in the + * active window. This action dynamically maintains the list of editors. + */ + static const QScopedPointer REOPEN_EDITORS; + + /** + * Workbench contribution item (id "perspectivesShortlist"): A list of + * perspectives available to be opened, arranged as a shortlist of + * promising perspectives and an "Other" subitem. Selecting + * one of the items makes the corresponding perspective active. Should a + * new perspective need to be opened, a workbench user preference controls + * whether the prespective is opened in the active window or a new window. + * This action dynamically maintains the perspectives shortlist. + */ + static const QScopedPointer PERSPECTIVES_SHORTLIST; + }; } #endif // BERRYCONTRIBUTIONITEMFACTORY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionManager.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionManager.cpp index 16ed9d2653..45c671b789 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionManager.cpp @@ -1,376 +1,393 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include "berryContributionManager.h" #include "berryIContributionManagerOverrides.h" #include "berryIContributionItem.h" +#include + namespace berry { +ContributionManager::~ContributionManager() +{ +} + +void ContributionManager::Add(QAction* action, const QString& id) +{ + Q_ASSERT_X(action, "nullcheck", "QAction must not be null"); + this->Add(IContributionItem::Pointer(new QActionContributionItem(action, id))); +} + void ContributionManager::Add(const SmartPointer& item) { Q_ASSERT_X(item, "nullcheck", "Item must not be null"); if (AllowItem(item.GetPointer())) { contributions.append(item); ItemAdded(item); } } +void ContributionManager::AppendToGroup(const QString& groupName, QAction* action, const QString& id) +{ + AddToGroup(groupName, IContributionItem::Pointer(new QActionContributionItem(action, id)), true); +} + void ContributionManager::AppendToGroup(const QString& groupName, const SmartPointer& item) { AddToGroup(groupName, item, true); } SmartPointer ContributionManager::Find(const QString& id) const { QListIterator e(contributions); while (e.hasNext()) { IContributionItem::Pointer item = e.next(); QString itemId = item->GetId(); if (itemId.compare(id, Qt::CaseInsensitive) != 0) { return item; } } return IContributionItem::Pointer(0); } QList > ContributionManager::GetItems() const { return contributions; } int ContributionManager::GetSize() { return contributions.size(); } SmartPointer ContributionManager::GetOverrides() { if (overrides.IsNull()) { struct _DefaultOverride : public IContributionManagerOverrides { int GetEnabled(const IContributionItem* /*item*/) const { return -1; } int GetVisible(const IContributionItem* /*item*/) const { return -1; } }; overrides = new _DefaultOverride; } return overrides; } int ContributionManager::IndexOf(const QString& id) { int i = 0; foreach(IContributionItem::Pointer item, contributions) { QString itemId = item->GetId(); if (item->GetId().compare(id, Qt::CaseInsensitive) == 0) { return i; } ++i; } return -1; } void ContributionManager::Insert(int index, const SmartPointer& item) { if (index > contributions.size()) { QString msg = QString("inserting ") + item->GetId() + " at " + QString::number(index); throw std::invalid_argument(msg.toStdString()); } if (AllowItem(item.GetPointer())) { contributions.insert(index, item); ItemAdded(item); } } void ContributionManager::InsertAfter(const QString& ID, const SmartPointer& item) { IContributionItem::Pointer ci = Find(ID); if (ci.IsNull()) { throw ctkInvalidArgumentException(QString("can't find ID") + ID); } int ix = contributions.indexOf(ci); if (ix >= 0) { // BERRY_INFO << "insert after: " << ix; if (AllowItem(item.GetPointer())) { contributions.insert(ix + 1, item); ItemAdded(item); } } } void ContributionManager::InsertBefore(const QString& ID, const SmartPointer& item) { IContributionItem::Pointer ci = Find(ID); if (ci.IsNull()) { throw ctkInvalidArgumentException(QString("can't find ID ") + ID); } int ix = contributions.indexOf(ci); if (ix >= 0) { // BERRY_INFO << "insert before: " << ix; if (AllowItem(item.GetPointer())) { contributions.insert(ix, item); ItemAdded(item); } } } bool ContributionManager::IsDirty() const { if (isDirty) { return true; } if (HasDynamicItems()) { foreach (IContributionItem::Pointer item, contributions) { if (item->IsDirty()) { return true; } } } return false; } bool ContributionManager::IsEmpty() const { return contributions.empty(); } void ContributionManager::MarkDirty() { SetDirty(true); } void ContributionManager::PrependToGroup(const QString& groupName, const SmartPointer& item) { AddToGroup(groupName, item, false); } SmartPointer ContributionManager::Remove(const QString& ID) { IContributionItem::Pointer ci = Find(ID); if (ci.IsNull()) { return ci; } return Remove(ci); } SmartPointer ContributionManager::Remove(const SmartPointer& item) { if (contributions.removeAll(item)) { ItemRemoved(item); return item; } return IContributionItem::Pointer(0); } void ContributionManager::RemoveAll() { QList items = GetItems(); contributions.clear(); foreach (IContributionItem::Pointer item, items) { ItemRemoved(item); } dynamicItems = 0; MarkDirty(); } bool ContributionManager::ReplaceItem(const QString& identifier, const SmartPointer& replacementItem) { if (identifier.isNull()) { return false; } const int index = IndexOf(identifier); if (index < 0) { return false; // couldn't find the item. } // Remove the old item. const IContributionItem::Pointer oldItem = contributions.at(index); ItemRemoved(oldItem); // Add the new item. contributions.replace(index, replacementItem); ItemAdded(replacementItem); // throws NPE if (replacementItem == null) // Go through and remove duplicates. QMutableListIterator i(contributions); i.toBack(); while (i.hasPrevious()) { IContributionItem::Pointer item = i.previous(); if ((item.IsNotNull()) && (identifier == item->GetId())) { // if (Policy.TRACE_TOOLBAR) { // System.out // .println("Removing duplicate on replace: " + identifier); // } i.remove(); ItemRemoved(item); } } return true; // success } void ContributionManager::SetOverrides(const SmartPointer& newOverrides) { overrides = newOverrides; } ContributionManager::ContributionManager() : isDirty(true), dynamicItems(0) { // Do nothing. } bool ContributionManager::AllowItem(IContributionItem* /*itemToAdd*/) { return true; } void ContributionManager::DumpStatistics() { int size = contributions.size(); BERRY_INFO << this->ToString(); BERRY_INFO << " Number of elements: " << size; int sum = 0; for (int i = 0; i < size; i++) { if (contributions.at(i)->IsVisible()) { ++sum; } } BERRY_INFO << " Number of visible elements: " << sum; BERRY_INFO << " Is dirty: " << IsDirty(); } bool ContributionManager::HasDynamicItems() const { return (dynamicItems > 0); } int ContributionManager::IndexOf(const SmartPointer& item) const { return contributions.indexOf(item); } void ContributionManager::ItemAdded(const SmartPointer& item) { item->SetParent(this); MarkDirty(); if (item->IsDynamic()) { dynamicItems++; } } void ContributionManager::ItemRemoved(const SmartPointer& item) { item->SetParent(0); MarkDirty(); if (item->IsDynamic()) { dynamicItems--; } } void ContributionManager::SetDirty(bool dirty) { isDirty = dirty; } void ContributionManager::InternalSetItems(const QList >& items) { contributions.clear(); for (int i = 0; i < items.size(); ++i) { if (AllowItem(items[i].GetPointer())) { contributions.append(items[i]); } } } void ContributionManager::AddToGroup(const QString& groupName, const SmartPointer& item, bool append) { QMutableListIterator items(contributions); for (int i = 0; items.hasNext(); ++i) { IContributionItem::Pointer o = items.next(); if (o->IsGroupMarker()) { QString id = o->GetId(); if (id.compare(groupName, Qt::CaseInsensitive) == 0) { ++i; if (append) { for (; items.hasNext(); ++i) { IContributionItem::Pointer ci = items.next(); if (ci->IsGroupMarker()) { break; } } } if (AllowItem(item.GetPointer())) { contributions.insert(i, item); ItemAdded(item); } return; } } } throw ctkInvalidArgumentException(QString("Group not found: ") + groupName); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionManager.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionManager.h index 2a302e6623..b46b37f1b1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionManager.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryContributionManager.h @@ -1,339 +1,343 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYCONTRIBUTIONMANAGER_H #define BERRYCONTRIBUTIONMANAGER_H #include "berryIContributionManager.h" namespace berry { +struct IContributionManagerOverrides; + /** * Abstract base class for all contribution managers, and standard * implementation of IContributionManager. This class provides * functionality common across the specific managers defined by this framework. *

* This class maintains a list of contribution items and a dirty flag, both as * internal state. In addition to providing implementations of most * IContributionManager methods, this class automatically * coalesces adjacent separators, hides beginning and ending separators, and * deals with dynamically changing sets of contributions. When the set of * contributions does change dynamically, the changes are propagated to the * control via the update method, which subclasses must * implement. *

*

* Note: A ContributionItem cannot be shared between different * ContributionManagers. *

*/ class ContributionManager : public virtual IContributionManager { protected: // Internal debug flag. // static final boolean DEBUG = false; public: berryObjectMacro(berry::ContributionManager) + ~ContributionManager(); + /* * Method declared on IContributionManager. */ - //void Add(Action* action); + void Add(QAction* action, const QString& id); /* * Method declared on IContributionManager. */ void Add(const SmartPointer& item); /* * Method declared on IContributionManager. */ - //void AppendToGroup(const QString& groupName, Action* action); + void AppendToGroup(const QString& groupName, QAction* action, const QString& id); /* * Method declared on IContributionManager. */ void AppendToGroup(const QString& groupName, const SmartPointer& item); /* * Method declared on IContributionManager. */ SmartPointer Find(const QString& id) const; /* * Method declared on IContributionManager. */ QList > GetItems() const; /** * Return the number of contributions in this manager. * * @return the number of contributions in this manager */ int GetSize(); /** * The ContributionManager implementation of this method * declared on IContributionManager returns the current * overrides. If there is no overrides it lazily creates one which overrides * no item state. */ SmartPointer GetOverrides(); /** * Returns the index of the item with the given id. * * @param id * The id of the item whose index is requested. * * @return int the index or -1 if the item is not found */ int IndexOf(const QString& id); /** * Insert the item at the given index. * * @param index * The index to be used for insertion * @param item * The item to be inserted */ void Insert(int index, const SmartPointer& item); /* * (non-Javadoc) Method declared on IContributionManager. */ //void InsertAfter(const QString& ID, Action* action); /* * (non-Javadoc) Method declared on IContributionManager. */ void InsertAfter(const QString& ID, const SmartPointer& item); /* * (non-Javadoc) Method declared on IContributionManager. */ //void InsertBefore(const QString& ID, Action* action); /* * Method declared on IContributionManager. */ void InsertBefore(const QString& ID, const SmartPointer& item); /* * Method declared on IContributionManager. */ bool IsDirty() const; /* * Method declared on IContributionManager. */ bool IsEmpty() const; /* * Method declared on IContributionManager. */ void MarkDirty(); /* * Method declared on IContributionManager. */ //void PrependToGroup(const QString& groupName, Action* action); /* * Method declared on IContributionManager. */ void PrependToGroup(const QString& groupName, const SmartPointer& item); /* * Method declared on IContributionManager. */ SmartPointer Remove(const QString& ID); /* * Method declared on IContributionManager. */ SmartPointer Remove(const SmartPointer &item); /* * (non-Javadoc) Method declared on IContributionManager. */ void RemoveAll(); /** * Replaces the item of the given identifier with another contribution item. * This can be used, for example, to replace large contribution items with * placeholders to avoid memory leaks. If the identifier cannot be found in * the current list of items, then this does nothing. If multiple * occurrences are found, then the replacement items is put in the first * position and the other positions are removed. * * @param identifier * The identifier to look for in the list of contributions; * should not be null. * @param replacementItem * The contribution item to replace the old item; must not be * null. Use * {@link org.eclipse.jface.action.ContributionManager#remove(java.lang.String) remove} * if that is what you want to do. * @return true if the given identifier can be; */ bool ReplaceItem(const QString &identifier, const SmartPointer& replacementItem); /** * Sets the overrides for this contribution manager * * @param newOverrides * the overrides for the items of this manager */ void SetOverrides(const SmartPointer& newOverrides); protected: /** * Creates a new contribution manager. */ ContributionManager(); /** * This method allows subclasses of ContributionManager to * prevent certain items in the contributions list. * ContributionManager will either block or allow an addition * based on the result of this method call. This can be used to prevent * duplication, for example. * * @param itemToAdd * The contribution item to be added; may be null. * @return true if the addition should be allowed; * false otherwise. The default implementation allows * all items. */ virtual bool AllowItem(IContributionItem* itemToAdd); /** * Internal debug method for printing statistics about this manager to * cout. */ void DumpStatistics(); /** * Returns whether this contribution manager contains dynamic items. A * dynamic contribution item contributes items conditionally, dependent on * some internal state. * * @return true if this manager contains dynamic items, and * false otherwise */ bool HasDynamicItems() const; /** * Returns the index of the object in the internal structure. This is * different from indexOf(String id) since some contribution * items may not have an id. * * @param item * The contribution item * @return the index, or -1 if the item is not found */ int IndexOf(const SmartPointer& item) const; /** * The given item was added to the list of contributions. Marks the manager * as dirty and updates the number of dynamic items, and the memento. * * @param item * the item to be added * */ void ItemAdded(const SmartPointer& item); /** * The given item was removed from the list of contributions. Marks the * manager as dirty and updates the number of dynamic items. * * @param item * remove given parent from list of contributions */ void ItemRemoved(const SmartPointer& item); /** * Sets whether this manager is dirty. When dirty, the list of contributions * is not accurately reflected in the corresponding widgets. * * @param dirty * true if this manager is dirty, and * false if it is up-to-date */ void SetDirty(bool dirty); /** * An internal method for setting the order of the contribution items. * * @param items * the contribution items in the specified order */ void InternalSetItems(const QList >& items); private: /** * The list of contribution items. */ QList > contributions; /** * Indicates whether the widgets are in sync with the contributions. */ bool isDirty; /** * Number of dynamic contribution items. */ int dynamicItems; /** * The overrides for items of this manager */ SmartPointer overrides; /** * Adds a contribution item to the start or end of the group with the given * name. * * @param groupName * the name of the group * @param item * the contribution item * @param append * true to add to the end of the group, and * false to add the beginning of the group * @exception IllegalArgumentException * if there is no group with the given name */ void AddToGroup(const QString& groupName, const SmartPointer& item, bool append); }; } #endif // BERRYCONTRIBUTIONMANAGER_H diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryGroupMarker.cpp similarity index 74% copy from BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryGroupMarker.cpp index 3b9d740123..1260f223ce 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryGroupMarker.cpp @@ -1,25 +1,31 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryIBerryPreferences.h" +#include "berryGroupMarker.h" namespace berry { -IBerryPreferences::~IBerryPreferences () +GroupMarker::GroupMarker(const QString& groupName) + : AbstractGroupMarker(groupName) { } +bool GroupMarker::IsVisible() const +{ + return false; +} + } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryAbstractGroupMarker.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryGroupMarker.h similarity index 50% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryAbstractGroupMarker.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryGroupMarker.h index 62c4e7b403..5e162f4c0d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryAbstractGroupMarker.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryGroupMarker.h @@ -1,69 +1,58 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ +#ifndef BERRYGROUPMARKER_H +#define BERRYGROUPMARKER_H -#ifndef BERRYABSTRACTGROUPMARKER_H -#define BERRYABSTRACTGROUPMARKER_H - -#include "berryContributionItem.h" +#include namespace berry { /** - * Abstract superclass for group marker classes. + * A group marker is a special kind of contribution item denoting + * the beginning of a group. These groups are used to structure + * the list of items. Unlike regular contribution items and + * separators, group markers have no visual representation. + * The name of the group is synonymous with the contribution item id. *

- * This class is not intended to be subclassed outside the framework. + * 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 AbstractGroupMarker : public ContributionItem +class BERRY_UI_QT GroupMarker : public AbstractGroupMarker { -protected: - - /** - * Constructor for use by subclasses. - */ - AbstractGroupMarker(); +public: /** * Create a new group marker with the given 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 name of the group */ - AbstractGroupMarker(const QString& groupName); - -public: - - /** - * Returns the group name. - * - * @return the group name - */ - QString GetGroupName() const; + GroupMarker(const QString& groupName); /** - * The AbstractGroupMarker implementation of this IContributionItem - * method returns true iff the id is not null. Subclasses may override. + * The GroupMarker implementation of this method + * returns false since group markers are always invisible. */ - bool IsGroupMarker() const; + virtual bool IsVisible() const override; }; } - -#endif // BERRYABSTRACTGROUPMARKER_H +#endif // BERRYGROUPMARKER_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 64b29f748a..61d70fbebd 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 { 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; + virtual void 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; + virtual void 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; + virtual void 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 d060f54bc3..5761fa82d1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIContributionManager.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIContributionManager.h @@ -1,192 +1,216 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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 +class QAction; + namespace berry { -//struct Action; struct IContributionItem; struct IContributionManagerOverrides; /** * A contribution manager organizes contributions to such UI components * as menus, toolbars and status lines. *

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

*

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

*

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

*/ struct IContributionManager : public virtual Object { berryObjectMacro(berry::IContributionManager) + /** + * Adds an action as a contribution item to this manager. + * Equivalent to Add(IContributionItem::Pointer(new QActionContributionItem(action, id))). + * + * @param action the action, this cannot be null + * @param id the unique action id + */ + virtual void Add(QAction* action, const QString& id) = 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,IContributionItem::Pointer(new QActionContributionItem(action, id))). + * + * @param groupName the name of the group + * @param action the action + * @param id the unique action id + * @exception ctkInvalidArgumentException if there is no group with + * the given name + */ + virtual void AppendToGroup(const QString& groupName, QAction* action, const QString& id) = 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 + * @exception ctkInvalidArgumentException 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 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 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 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/berryIMenuManager.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryIMenuManager.h index 2223488de7..6ff6606dc2 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; 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 { 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; + virtual void AddMenuListener(QObject* listener) = 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; + 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 4e5cbf423c..086d8c2389 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryMenuManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryMenuManager.cpp @@ -1,728 +1,679 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryQActionProperties.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); } + QAction* getParentItem() const + { + return menu ? menu->menuAction() : nullptr; + } + }; namespace berry { struct NullOverrides: public IContributionManagerOverrides { public: int GetEnabled(const IContributionItem* /*item*/) const { return -1; } int GetVisible(const IContributionItem* /*item*/) const { return -1; } }; -//struct GuiTkMenuListener : public GuiTk::IMenuListener -//{ -//public: - -// GuiTkMenuListener(MenuManager::Pointer manager) : -// manager(manager) -// { - -// } - -// void MenuAboutToHide() -// { -// // ApplicationWindow.resetDescription(e.widget); -// MenuManager::Pointer(manager)->HandleAboutToHide(); -// } - -// void MenuAboutToShow() -// { -// MenuManager::Pointer(manager)->HandleAboutToShow(); -// } - -//private: +void MenuManager::HandleAboutToShow() +{ + if (this->removeAllWhenShown) + { + this->RemoveAll(); + } + emit AboutToShow(this); + this->Update(false, false); +} -// MenuManager::WeakPtr manager; -//}; +void MenuManager::HandleAboutToHide() +{ + emit AboutToHide(this); +} MenuManager::MenuManager(const QString& text, const QString& id) - : id(id), menu(0), menuItem(0), menuListener(new MMMenuListener(this)) + : id(id), menu(0), menuItem(0) , 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)) + : id(id), menu(0), menuItem(0) , menuText(text), image(image) , parent(0), removeAllWhenShown(false), visible(true) { } bool MenuManager::IsDirty() const { return ContributionManager::IsDirty(); } MenuManager::~MenuManager() { delete menu; } -//void MenuManager::AddMenuListener(SmartPointer listener) -//{ -// menuEvents.AddListener(listener); -//} - QMenu* MenuManager::CreateContextMenu(QWidget* parent) { if (!menu) { menu = new QMenuProxy(QMenuProxy::Menu, parent); this->InitializeMenu(); } return menu->menu; } QMenuBar* MenuManager::CreateMenuBar(QWidget* parent) { if (!menu) { menu = new QMenuProxy(QMenuProxy::MenuBar, parent); this->Update(false); } return menu->menuBar; } +void MenuManager::AddMenuListener(QObject* listener) +{ + this->connect(this, SIGNAL(AboutToShow(IMenuManager*)), listener, SLOT(MenuAboutToShow(IMenuManager*))); + this->connect(this, SIGNAL(AboutToHide(IMenuManager*)), listener, SLOT(MenuAboutToHide(IMenuManager*))); +} + +void MenuManager::RemoveMenuListener(QObject* listener) +{ + this->disconnect(listener); +} + void MenuManager::Fill(QStatusBar* /*parent*/) { } -QAction* MenuManager::Fill(QToolBar* /*parent*/, QAction* /*before*/) +void MenuManager::Fill(QToolBar* /*parent*/, QAction* /*before*/) { - return 0; } -QAction* MenuManager::Fill(QMenu* parent, QAction* before) +void MenuManager::Fill(QMenu* parent, QAction* before) { - return this->FillMenu(parent, before); + this->FillMenu(parent, before); } -QAction* MenuManager::Fill(QMenuBar* parent, QAction* before) +void MenuManager::Fill(QMenuBar* parent, QAction* before) { - return this->FillMenu(parent, before); + this->FillMenu(parent, before); } -QAction* MenuManager::FillMenu(QWidget* parent, QAction* before) +void 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) +void MenuManager::SetCommandId(const QString& definitionId) { this->definitionId = definitionId; } void MenuManager::Update() { this->UpdateMenuItem(); } -void MenuManager::Update(const QString& /*property*/) +void MenuManager::Update(const QString& property) { + QList items = GetItems(); + for (int i = 0; i < items.size(); i++) + { + items[i]->Update(property); + } + + if (menu != nullptr && menu->getParentItem() != nullptr) + { + if (QActionProperties::TEXT == property) + { + QString text = GetMenuText(); + if (!text.isNull()) + { + menu->getParentItem()->setText(text); + } + } + else if (QActionProperties::IMAGE == property && !image.isNull()) + { + menu->getParentItem()->setIcon(image); + } + } } 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())); + this->connect(menu->menu, SIGNAL(aboutToShow()), SLOT(HandleAboutToShow())); + this->connect(menu->menu, SIGNAL(aboutToHide()), SLOT(HandleAboutToHide())); } - //menu->AddMenuListener(menuListener); // Don't do an update(true) here, in case menu is never opened. // Always do it lazily in handleAboutToShow(). } -//void MenuManager::DisposeOldImages() -//{ -// if (imageManager) -// { -// imageManager.dispose(); -// imageManager = null; -// } -//} - void MenuManager::UpdateMenuItem() { if (menuItem && menu) { bool enabled = removeAllWhenShown || menu->actions().size() > 0; if (menu->isEnabled() != enabled) { menuItem->setEnabled(enabled); } } } -//QList > MenuManager::GetMenuItems() -//{ -// if (menu) -// { -// return menu->GetItems(); -// } -// return QList(); -//} - -//SmartPointer MenuManager::GetMenuItem(unsigned int index) -//{ -// if (menu) -// { -// return menu->GetItem(index); -// } -// return IMenuItem::Pointer(0); -//} - -//unsigned int MenuManager::GetMenuItemCount() -//{ -// if (menu) -// { -// return menu->GetItemCount(); -// } -// return 0; -//} - void MenuManager::DoItemFill(IContributionItem::Pointer ci, QAction* before) { if (menu->isMenuBar()) { ci->Fill(menu->menuBar, before); } else { ci->Fill(menu->menu, before); } } void MenuManager::Update(bool force, bool recursive) { if (ContributionManager::IsDirty() || force) { if (menu) { // clean contains all active items without double separators QList items = this->GetItems(); QList clean; IContributionItem::Pointer separator; foreach (IContributionItem::Pointer ci, items) { if (!ci->IsVisible()) { continue; } if (ci->IsSeparator()) { // delay creation until necessary // (handles both adjacent separators, and separator at end) separator = ci; } else { if (separator) { if (clean.size() > 0) { clean.push_back(separator); } separator = 0; } clean.push_back(ci); } } // remove obsolete (removed or non active) QList mi = menu->actions(); for (int i = 0; i < mi.size(); i++) { Object::Pointer data = mi[i]->data().value(); if (!data || !clean.contains(data.Cast())) { menu->removeAction(mi[i]); } else if (IContributionItem::Pointer ci = data.Cast()) { if(ci->IsDynamic() && ci->IsDirty()) { menu->removeAction(mi[i]); delete mi[i]; } } } // add new mi = menu->actions(); int srcIx = 0; int destIx = 0; for (QList::Iterator e = clean.begin(); e != clean.end(); ++e) { IContributionItem::Pointer src(*e); IContributionItem::Pointer dest; // get corresponding item in widget if (srcIx < mi.size()) { dest = mi[srcIx]->data().value().Cast(); } else { dest = 0; } if (dest && src == dest) { srcIx++; destIx++; } else if (dest && dest->IsSeparator() && src->IsSeparator()) { mi[srcIx]->setData(QVariant::fromValue(src)); srcIx++; destIx++; } else { int start = menu->actions().size(); - qDebug() << "***** Filling item destIx = " << destIx << " (size: " << start << ")"; + //qDebug() << "***** Filling item destIx = " << destIx << " (size: " << start << ")"; this->DoItemFill(src, destIx >= start ? NULL : menu->actions().at(destIx)); int newItems = menu->actions().size() - start; - qDebug() << "***** New items: " << newItems; + //qDebug() << "***** New items: " << newItems; for (int i = 0; i < newItems; ++i) { menu->actions().at(destIx++)->setData(QVariant::fromValue(src)); } } // May be we can optimize this call. If the menu has just // been created via the call src.fill(fMenuBar, destIx) then // the menu has already been updated with update(true) // (see MenuManager). So if force is true we do it again. But // we can't set force to false since then information for the // sub sub menus is lost. if (recursive) { IContributionItem::Pointer item(src); if (SubContributionItem::Pointer subItem = item.Cast()) { item = subItem->GetInnerItem(); } if (IMenuManager::Pointer mm = item.Cast()) { mm->UpdateAll(force); } } } // remove any old menu items not accounted for for (; srcIx < mi.size(); srcIx++) { menu->removeAction(mi[srcIx]); delete mi[srcIx]; } this->SetDirty(false); } } else { // I am not dirty. Check if I must recursivly walk down the hierarchy. if (recursive) { foreach (IContributionItem::Pointer ci, this->GetItems()) { if (IMenuManager::Pointer mm = ci.Cast()) { if (mm->IsVisible()) { mm->UpdateAll(force); } } } } } this->UpdateMenuItem(); } void MenuManager::DumpActionInfo(QMenuProxy* menu) { if (menu->isMenuBar()) { - qDebug() << "QMenuBar [" << menu->menuBar << "]"; + //qDebug() << "QMenuBar [" << menu->menuBar << "]"; DumpActionInfo(menu->menuBar, 1); } else { - qDebug() << "QMenu [" << menu->menu << "]" << menu->menu; + //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 2a8f0e5e59..b6fcbc4eae 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryMenuManager.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryMenuManager.h @@ -1,469 +1,407 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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 +class BERRY_UI_QT MenuManager: public QObject, public ContributionManager, public IMenuManager { + Q_OBJECT 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; +private: + + Q_SLOT void HandleAboutToShow(); + Q_SLOT void HandleAboutToHide(); + protected: /** * Indicates this item is visible in its manager; true * by default. */ bool visible; public: + Q_SIGNAL void AboutToShow(IMenuManager* mm); + Q_SIGNAL void AboutToHide(IMenuManager* mm); + /** * 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); + void AddMenuListener(QObject* listener); + void RemoveMenuListener(QObject *listener); + /* * @see IContributionItem#Fill(QStatusBar*) */ void Fill(QStatusBar* parent); /* * @see IContributionItem#Fill(QToolBar*, int) */ - QAction* Fill(QToolBar* parent, QAction *index); + void Fill(QToolBar* parent, QAction *index); /* * @see IContributionItem#Fill(QMenu*, int) */ - QAction* Fill(QMenu* parent, QAction *before); + void Fill(QMenu* parent, QAction *before); /* * @see IContributionItem#Fill(QMenuBar*, int) */ - QAction* Fill(QMenuBar* parent, QAction *before); + void 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 + * Sets the command 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); + void SetCommandId(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 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/berryQActionContributionItem.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryQActionContributionItem.cpp new file mode 100644 index 0000000000..2780ccfd3c --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryQActionContributionItem.cpp @@ -0,0 +1,968 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY 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 "berryQActionContributionItem.h" + +#include +#include + +#include + +namespace berry { + +QActionContributionItem::QActionContributionItem(QAction* action, const QString& id) + : ContributionItem(id), action(action) +{ +} + +bool QActionContributionItem::operator==(const Object* o) const +{ + if (const QActionContributionItem* aci = dynamic_cast(o)) + { + return action == aci->action; + } + return false; +} + +uint QActionContributionItem::HashCode() const +{ + return qHash(action); +} + +void QActionContributionItem::Fill(QStatusBar* /*parent*/) +{ +// if (widget == null && parent != null) { +// int flags = SWT.PUSH; +// if (action != null) { +// if (action.getStyle() == IAction.AS_CHECK_BOX) { +// flags = SWT.TOGGLE; +// } +// if (action.getStyle() == IAction.AS_RADIO_BUTTON) { +// flags = SWT.RADIO; +// } +// } + +// Button b = new Button(parent, flags); +// b.setData(this); +// b.addListener(SWT.Dispose, getButtonListener()); +// // Don't hook a dispose listener on the parent +// b.addListener(SWT.Selection, getButtonListener()); +// if (action.getHelpListener() != null) { +// b.addHelpListener(action.getHelpListener()); +// } +// widget = b; + +// update(null); + +// // Attach some extra listeners. +// action.addPropertyChangeListener(propertyListener); +// if (action != null) { +// String commandId = action.getActionDefinitionId(); +// ExternalActionManager.ICallback callback = ExternalActionManager +// .getInstance().getCallback(); + +// if ((callback != null) && (commandId != null)) { +// callback.addPropertyChangeListener(commandId, +// actionTextListener); +// } +// } +// } +} + +void QActionContributionItem::Fill(QMenu* parent, QAction* before) +{ + if (parent != 0) + { + if (before) + { + parent->insertAction(before, action); + } + else + { + parent->addAction(action); + } + action->setData(QVariant::fromValue(Object::Pointer(this))); + action->setProperty("contributionItem", QVariant::fromValue(Object::Pointer(this))); + //action.addListener(SWT.Dispose, getMenuItemListener()); + //action.addListener(SWT.Selection, getMenuItemListener()); + //if (action.getHelpListener() != null) + //{ + // mi.addHelpListener(action.getHelpListener()); + //} + + if (action->menu()) + { +// // just create a proxy for now, if the user shows it then +// // fill it in +// Menu subMenu = new Menu(parent); +// subMenu.addListener(SWT.Show, getMenuCreatorListener()); +// subMenu.addListener(SWT.Hide, getMenuCreatorListener()); +// mi.setMenu(subMenu); + } + + Update(QString()); + +// // Attach some extra listeners. +// action.addPropertyChangeListener(propertyListener); +// if (action != null) { +// String commandId = action.getActionDefinitionId(); +// ExternalActionManager.ICallback callback = ExternalActionManager +// .getInstance().getCallback(); + +// if ((callback != null) && (commandId != null)) { +// callback.addPropertyChangeListener(commandId, +// actionTextListener); +// } +// } + } +} + +void QActionContributionItem::Fill(QToolBar* /*parent*/, QAction* /*before*/) +{ +// if (widget == null && parent != null) { +// int flags = SWT.PUSH; +// if (action != null) { +// int style = action.getStyle(); +// if (style == IAction.AS_CHECK_BOX) { +// flags = SWT.CHECK; +// } else if (style == IAction.AS_RADIO_BUTTON) { +// flags = SWT.RADIO; +// } else if (style == IAction.AS_DROP_DOWN_MENU) { +// flags = SWT.DROP_DOWN; +// } +// } + +// ToolItem ti = null; +// if (index >= 0) { +// ti = new ToolItem(parent, flags, index); +// } else { +// ti = new ToolItem(parent, flags); +// } +// ti.setData(this); +// ti.addListener(SWT.Selection, getToolItemListener()); +// ti.addListener(SWT.Dispose, getToolItemListener()); + +// widget = ti; + +// update(null); + +// // Attach some extra listeners. +// action.addPropertyChangeListener(propertyListener); +// if (action != null) { +// String commandId = action.getActionDefinitionId(); +// ExternalActionManager.ICallback callback = ExternalActionManager +// .getInstance().getCallback(); + +// if ((callback != null) && (commandId != null)) { +// callback.addPropertyChangeListener(commandId, +// actionTextListener); +// } +// } +// } +} + +QAction* QActionContributionItem::GetAction() const +{ + return action; +} + +QActionContributionItem::~QActionContributionItem() +{ + //holdMenu = null; +} + +ContributionItem::Modes QActionContributionItem::GetMode() const +{ + return mode; +} + +bool QActionContributionItem::IsDynamic() const +{ +// if (qobject_cast(action->parentWidget())) +// { +// // Optimization. Only recreate the item is the check or radio style +// // has changed. +// boolean itemIsCheck = (widget.getStyle() & SWT.CHECK) != 0; +// boolean actionIsCheck = getAction() != null +// && getAction().getStyle() == IAction.AS_CHECK_BOX; +// boolean itemIsRadio = (widget.getStyle() & SWT.RADIO) != 0; +// boolean actionIsRadio = getAction() != null +// && getAction().getStyle() == IAction.AS_RADIO_BUTTON; +// return (itemIsCheck != actionIsCheck) +// || (itemIsRadio != actionIsRadio); +// } + return false; +} + +bool QActionContributionItem::IsEnabled() const +{ + return action != 0 && action->isEnabled(); +} + +bool QActionContributionItem::IsVisible() const +{ + return ContributionItem::IsVisible() && IsCommandActive(); +} + +void QActionContributionItem::SetMode(Modes mode) +{ + this->mode = mode; + Update(); +} + +void QActionContributionItem::Update() +{ + Update(QString()); +} + +void QActionContributionItem::Update(const QString& /*propertyName*/) +{ +// if (widget != 0) +// { +// // determine what to do +// boolean textChanged = propertyName == null +// || propertyName.equals(IAction.TEXT); +// boolean imageChanged = propertyName == null +// || propertyName.equals(IAction.IMAGE); +// boolean tooltipTextChanged = propertyName == null +// || propertyName.equals(IAction.TOOL_TIP_TEXT); +// boolean enableStateChanged = propertyName == null +// || propertyName.equals(IAction.ENABLED) +// || propertyName +// .equals(IContributionManagerOverrides.P_ENABLED); +// boolean checkChanged = (action.getStyle() == IAction.AS_CHECK_BOX || action +// .getStyle() == IAction.AS_RADIO_BUTTON) +// && (propertyName == null || propertyName +// .equals(IAction.CHECKED)); + +// if (widget instanceof ToolItem) { +// ToolItem ti = (ToolItem) widget; +// String text = action.getText(); +// // the set text is shown only if there is no image or if forced +// // by MODE_FORCE_TEXT +// boolean showText = text != null +// && ((getMode() & MODE_FORCE_TEXT) != 0 || !hasImages(action)); + +// // only do the trimming if the text will be used +// if (showText && text != null) { +// text = Action.removeAcceleratorText(text); +// text = Action.removeMnemonics(text); +// } + +// if (textChanged) { +// String textToSet = showText ? text : ""; //$NON-NLS-1$ +// boolean rightStyle = (ti.getParent().getStyle() & SWT.RIGHT) != 0; +// if (rightStyle || !ti.getText().equals(textToSet)) { +// // In addition to being required to update the text if +// // it +// // gets nulled out in the action, this is also a +// // workaround +// // for bug 50151: Using SWT.RIGHT on a ToolBar leaves +// // blank space +// ti.setText(textToSet); +// } +// } + +// if (imageChanged) { +// // only substitute a missing image if it has no text +// updateImages(!showText); +// } + +// if (tooltipTextChanged || textChanged) { +// String toolTip = action.getToolTipText(); +// if ((toolTip == null) || (toolTip.length() == 0)) { +// toolTip = text; +// } + +// ExternalActionManager.ICallback callback = ExternalActionManager +// .getInstance().getCallback(); +// String commandId = action.getActionDefinitionId(); +// if ((callback != null) && (commandId != null) +// && (toolTip != null)) { +// String acceleratorText = callback +// .getAcceleratorText(commandId); +// if (acceleratorText != null +// && acceleratorText.length() != 0) { +// toolTip = JFaceResources.format( +// "Toolbar_Tooltip_Accelerator", //$NON-NLS-1$ +// new Object[] { toolTip, acceleratorText }); +// } +// } + +// // if the text is showing, then only set the tooltip if +// // different +// if (!showText || toolTip != null && !toolTip.equals(text)) { +// ti.setToolTipText(toolTip); +// } else { +// ti.setToolTipText(null); +// } +// } + +// if (enableStateChanged) { +// boolean shouldBeEnabled = action.isEnabled() +// && isEnabledAllowed(); + +// if (ti.getEnabled() != shouldBeEnabled) { +// ti.setEnabled(shouldBeEnabled); +// } +// } + +// if (checkChanged) { +// boolean bv = action.isChecked(); + +// if (ti.getSelection() != bv) { +// ti.setSelection(bv); +// } +// } +// return; +// } + +// if (widget instanceof MenuItem) { +// MenuItem mi = (MenuItem) widget; + +// if (textChanged) { +// int accelerator = 0; +// String acceleratorText = null; +// IAction updatedAction = getAction(); +// String text = null; +// accelerator = updatedAction.getAccelerator(); +// ExternalActionManager.ICallback callback = ExternalActionManager +// .getInstance().getCallback(); + +// // Block accelerators that are already in use. +// if ((accelerator != 0) && (callback != null) +// && (callback.isAcceleratorInUse(accelerator))) { +// accelerator = 0; +// } + +// /* +// * Process accelerators on GTK in a special way to avoid Bug +// * 42009. We will override the native input method by +// * allowing these reserved accelerators to be placed on the +// * menu. We will only do this for "Ctrl+Shift+[0-9A-FU]". +// */ +// final String commandId = updatedAction +// .getActionDefinitionId(); +// if ((Util.isGtk()) && (callback instanceof IBindingManagerCallback) +// && (commandId != null)) { +// final IBindingManagerCallback bindingManagerCallback = (IBindingManagerCallback) callback; +// final IKeyLookup lookup = KeyLookupFactory.getDefault(); +// final TriggerSequence[] triggerSequences = bindingManagerCallback +// .getActiveBindingsFor(commandId); +// for (int i = 0; i < triggerSequences.length; i++) { +// final TriggerSequence triggerSequence = triggerSequences[i]; +// final Trigger[] triggers = triggerSequence +// .getTriggers(); +// if (triggers.length == 1) { +// final Trigger trigger = triggers[0]; +// if (trigger instanceof KeyStroke) { +// final KeyStroke currentKeyStroke = (KeyStroke) trigger; +// final int currentNaturalKey = currentKeyStroke +// .getNaturalKey(); +// if ((currentKeyStroke.getModifierKeys() == (lookup +// .getCtrl() | lookup.getShift())) +// && ((currentNaturalKey >= '0' && currentNaturalKey <= '9') +// || (currentNaturalKey >= 'A' && currentNaturalKey <= 'F') || (currentNaturalKey == 'U'))) { +// accelerator = currentKeyStroke +// .getModifierKeys() +// | currentNaturalKey; +// acceleratorText = triggerSequence +// .format(); +// break; +// } +// } +// } +// } +// } + +// if (accelerator == 0) { +// if ((callback != null) && (commandId != null)) { +// acceleratorText = callback +// .getAcceleratorText(commandId); +// } +// } + +// IContributionManagerOverrides overrides = null; + +// if (getParent() != null) { +// overrides = getParent().getOverrides(); +// } + +// if (overrides != null) { +// text = getParent().getOverrides().getText(this); +// } + +// mi.setAccelerator(accelerator); + +// if (text == null) { +// text = updatedAction.getText(); +// } + +// if (text != null && acceleratorText == null) { +// // use extracted accelerator text in case accelerator +// // cannot be fully represented in one int (e.g. +// // multi-stroke keys) +// acceleratorText = LegacyActionTools +// .extractAcceleratorText(text); +// if (acceleratorText == null && accelerator != 0) { +// acceleratorText = Action +// .convertAccelerator(accelerator); +// } +// } + +// if (text == null) { +// text = ""; //$NON-NLS-1$ +// } else { +// text = Action.removeAcceleratorText(text); +// } + +// if (acceleratorText == null) { +// mi.setText(text); +// } else { +// mi.setText(text + '\t' + acceleratorText); +// } +// } + +// if (imageChanged) { +// updateImages(false); +// } + +// if (enableStateChanged) { +// boolean shouldBeEnabled = action.isEnabled() +// && isEnabledAllowed(); + +// if (mi.getEnabled() != shouldBeEnabled) { +// mi.setEnabled(shouldBeEnabled); +// } +// } + +// if (checkChanged) { +// boolean bv = action.isChecked(); + +// if (mi.getSelection() != bv) { +// mi.setSelection(bv); +// } +// } + +// return; +// } + +// if (widget instanceof Button) { +// Button button = (Button) widget; + +// if (imageChanged) { +// updateImages(false); +// } + +// if (textChanged) { +// String text = action.getText(); +// boolean showText = text != null && ((getMode() & MODE_FORCE_TEXT) != 0 || !hasImages(action)); +// // only do the trimming if the text will be used +// if (showText) { +// text = Action.removeAcceleratorText(text); +// } +// String textToSet = showText ? text : ""; //$NON-NLS-1$ +// button.setText(textToSet); +// } + +// if (tooltipTextChanged) { +// button.setToolTipText(action.getToolTipText()); +// } + +// if (enableStateChanged) { +// boolean shouldBeEnabled = action.isEnabled() +// && isEnabledAllowed(); + +// if (button.getEnabled() != shouldBeEnabled) { +// button.setEnabled(shouldBeEnabled); +// } +// } + +// if (checkChanged) { +// boolean bv = action.isChecked(); + +// if (button.getSelection() != bv) { +// button.setSelection(bv); +// } +// } +// return; +// } +//} +} + +bool QActionContributionItem::IsEnabledAllowed() const +{ + if (this->GetParent() == 0) + { + return true; + } + int value = GetParent()->GetOverrides()->GetEnabled(this); + return (value == -1) ? true : value; +} + +//QString QActionContributionItem::ShortenText(const QString& textValue, QToolButton* item) +//{ +//if (textValue == null) { +// return null; +//} + +//GC gc = new GC(item.getParent()); + +//int maxWidth = item.getImage().getBounds().width * 4; + +//if (gc.textExtent(textValue).x < maxWidth) { +// gc.dispose(); +// return textValue; +//} + +//for (int i = textValue.length(); i > 0; i--) { +// String test = textValue.substring(0, i); +// test = test + ellipsis; +// if (gc.textExtent(test).x < maxWidth) { +// gc.dispose(); +// return test; +// } + +//} +//gc.dispose(); +//// If for some reason we fall through abort +//return textValue; +//} + +//Listener QActionContributionItem::GetToolItemListener() +//{ +//if (toolItemListener == null) { +// toolItemListener = new Listener() { +// public void handleEvent(Event event) { +// switch (event.type) { +// case SWT.Dispose: +// handleWidgetDispose(event); +// break; +// case SWT.Selection: +// Widget ew = event.widget; +// if (ew != null) { +// handleWidgetSelection(event, ((ToolItem) ew) +// .getSelection()); +// } +// break; +// } +// } +// }; +//} +//return toolItemListener; +//} + +//void QActionContributionItem::HandleWidgetDispose(Event e) +//{ +//// Check if our widget is the one being disposed. +//if (e.widget == widget) { +// // Dispose of the menu creator. +// if (action.getStyle() == IAction.AS_DROP_DOWN_MENU +// && menuCreatorCalled) { +// IMenuCreator mc = action.getMenuCreator(); +// if (mc != null) { +// mc.dispose(); +// } +// } + +// // Unhook all of the listeners. +// action.removePropertyChangeListener(propertyListener); +// if (action != null) { +// String commandId = action.getActionDefinitionId(); +// ExternalActionManager.ICallback callback = ExternalActionManager +// .getInstance().getCallback(); + +// if ((callback != null) && (commandId != null)) { +// callback.removePropertyChangeListener(commandId, +// actionTextListener); +// } +// } + +// // Clear the widget field. +// widget = null; + +// disposeOldImages(); +//} +//} + +//void QActionContributionItem::HandleWidgetSelection(Event e, bool selection) +//{ + +//Widget item = e.widget; +//if (item != null) { +// int style = item.getStyle(); + +// if ((style & (SWT.TOGGLE | SWT.CHECK)) != 0) { +// if (action.getStyle() == IAction.AS_CHECK_BOX) { +// action.setChecked(selection); +// } +// } else if ((style & SWT.RADIO) != 0) { +// if (action.getStyle() == IAction.AS_RADIO_BUTTON) { +// action.setChecked(selection); +// } +// } else if ((style & SWT.DROP_DOWN) != 0) { +// if (e.detail == 4) { // on drop-down button +// if (action.getStyle() == IAction.AS_DROP_DOWN_MENU) { +// IMenuCreator mc = action.getMenuCreator(); +// menuCreatorCalled = true; +// ToolItem ti = (ToolItem) item; +// // we create the menu as a sub-menu of "dummy" so that +// // we can use +// // it in a cascading menu too. +// // If created on a SWT control we would get an SWT +// // error... +// // Menu dummy= new Menu(ti.getParent()); +// // Menu m= mc.getMenu(dummy); +// // dummy.dispose(); +// if (mc != null) { +// Menu m = mc.getMenu(ti.getParent()); +// if (m != null) { +// // position the menu below the drop down item +// Point point = ti.getParent().toDisplay( +// new Point(e.x, e.y)); +// m.setLocation(point.x, point.y); // waiting +// // for SWT +// // 0.42 +// m.setVisible(true); +// return; // we don't fire the action +// } +// } +// } +// } +// } + +// ExternalActionManager.IExecuteCallback callback = null; +// String actionDefinitionId = action.getActionDefinitionId(); +// if (actionDefinitionId != null) { +// Object obj = ExternalActionManager.getInstance() +// .getCallback(); +// if (obj instanceof ExternalActionManager.IExecuteCallback) { +// callback = (ExternalActionManager.IExecuteCallback) obj; +// } +// } + +// // Ensure action is enabled first. +// // See 1GAN3M6: ITPUI:WINNT - Any IAction in the workbench can be +// // executed while disabled. +// if (action.isEnabled()) { +// boolean trace = Policy.TRACE_ACTIONS; + +// long ms = 0L; +// if (trace) { +// ms = System.currentTimeMillis(); +// System.out.println("Running action: " + action.getText()); //$NON-NLS-1$ +// } + +// IPropertyChangeListener resultListener = null; +// if (callback != null) { +// resultListener = new IPropertyChangeListener() { +// public void propertyChange(PropertyChangeEvent event) { +// // Check on result +// if (event.getProperty().equals(IAction.RESULT)) { +// if (event.getNewValue() instanceof Boolean) { +// result = (Boolean) event.getNewValue(); +// } +// } +// } +// }; +// action.addPropertyChangeListener(resultListener); +// callback.preExecute(action, e); +// } + +// action.runWithEvent(e); + +// if (callback != null) { +// if (result == null || result.equals(Boolean.TRUE)) { +// callback.postExecuteSuccess(action, Boolean.TRUE); +// } else { +// callback.postExecuteFailure(action, +// new ExecutionException(action.getText() +// + " returned failure.")); //$NON-NLS-1$ +// } +// } + +// if (resultListener!=null) { +// result = null; +// action.removePropertyChangeListener(resultListener); +// } +// if (trace) { +// System.out.println((System.currentTimeMillis() - ms) +// + " ms to run action: " + action.getText()); //$NON-NLS-1$ +// } +// } else { +// if (callback != null) { +// callback.notEnabled(action, new NotEnabledException(action +// .getText() +// + " is not enabled.")); //$NON-NLS-1$ +// } +// } +//} +//} + +//bool QActionContributionItem::HasImages(Action* actionToCheck) const +//{ +// return actionToCheck.getImageDescriptor() != null +// || actionToCheck.getHoverImageDescriptor() != null +// || actionToCheck.getDisabledImageDescriptor() != null; +//} + +bool QActionContributionItem::IsCommandActive() const +{ + return action ? action->isVisible() : true; +} + +//bool QActionContributionItem::UpdateImages(bool forceImage) +//{ + +// ResourceManager parentResourceManager = JFaceResources.getResources(); + +// if (widget instanceof ToolItem) { +// if (USE_COLOR_ICONS) { +// ImageDescriptor image = action.getHoverImageDescriptor(); +// if (image == null) { +// image = action.getImageDescriptor(); +// } +// ImageDescriptor disabledImage = action +// .getDisabledImageDescriptor(); + +// // Make sure there is a valid image. +// if (image == null && forceImage) { +// image = ImageDescriptor.getMissingImageDescriptor(); +// } + +// LocalResourceManager localManager = new LocalResourceManager( +// parentResourceManager); + +// // performance: more efficient in SWT to set disabled and hot +// // image before regular image +// ((ToolItem) widget) +// .setDisabledImage(disabledImage == null ? null +// : localManager +// .createImageWithDefault(disabledImage)); +// ((ToolItem) widget).setImage(image == null ? null +// : localManager.createImageWithDefault(image)); + +// disposeOldImages(); +// imageManager = localManager; + +// return image != null; +// } +// ImageDescriptor image = action.getImageDescriptor(); +// ImageDescriptor hoverImage = action.getHoverImageDescriptor(); +// ImageDescriptor disabledImage = action.getDisabledImageDescriptor(); + +// // If there is no regular image, but there is a hover image, +// // convert the hover image to gray and use it as the regular image. +// if (image == null && hoverImage != null) { +// image = ImageDescriptor.createWithFlags(action +// .getHoverImageDescriptor(), SWT.IMAGE_GRAY); +// } else { +// // If there is no hover image, use the regular image as the +// // hover image, +// // and convert the regular image to gray +// if (hoverImage == null && image != null) { +// hoverImage = image; +// image = ImageDescriptor.createWithFlags(action +// .getImageDescriptor(), SWT.IMAGE_GRAY); +// } +// } + +// // Make sure there is a valid image. +// if (hoverImage == null && image == null && forceImage) { +// image = ImageDescriptor.getMissingImageDescriptor(); +// } + +// // Create a local resource manager to remember the images we've +// // allocated for this tool item +// LocalResourceManager localManager = new LocalResourceManager( +// parentResourceManager); + +// // performance: more efficient in SWT to set disabled and hot image +// // before regular image +// ((ToolItem) widget).setDisabledImage(disabledImage == null ? null +// : localManager.createImageWithDefault(disabledImage)); +// ((ToolItem) widget).setHotImage(hoverImage == null ? null +// : localManager.createImageWithDefault(hoverImage)); +// ((ToolItem) widget).setImage(image == null ? null : localManager +// .createImageWithDefault(image)); + +// // Now that we're no longer referencing the old images, clear them +// // out. +// disposeOldImages(); +// imageManager = localManager; + +// return image != null; +// } else if (widget instanceof Item || widget instanceof Button) { + +// // Use hover image if there is one, otherwise use regular image. +// ImageDescriptor image = action.getHoverImageDescriptor(); +// if (image == null) { +// image = action.getImageDescriptor(); +// } +// // Make sure there is a valid image. +// if (image == null && forceImage) { +// image = ImageDescriptor.getMissingImageDescriptor(); +// } + +// // Create a local resource manager to remember the images we've +// // allocated for this widget +// LocalResourceManager localManager = new LocalResourceManager( +// parentResourceManager); + +// if (widget instanceof Item) { +// ((Item) widget).setImage(image == null ? null : localManager +// .createImageWithDefault(image)); +// } else if (widget instanceof Button) { +// ((Button) widget).setImage(image == null ? null : localManager +// .createImageWithDefault(image)); +// } + +// // Now that we're no longer referencing the old images, clear them +// // out. +// disposeOldImages(); +// imageManager = localManager; + +// return image != null; +// } +// return false; +//} + +//void QActionContributionItem::DisposeOldImages() +//{ +// if (imageManager != null) { +// imageManager.dispose(); +// imageManager = null; +// } +//} + +//Listener QActionContributionItem::getMenuCreatorListener() { +// if (menuCreatorListener == null) { +// menuCreatorListener = new Listener() { +// public void handleEvent(Event event) { +// switch (event.type) { +// case SWT.Show: +// handleShowProxy((Menu) event.widget); +// break; +// case SWT.Hide: +// handleHideProxy((Menu) event.widget); +// break; +// } +// } +// }; +// } +// return menuCreatorListener; +//} + +//void QActionContributionItem::HandleShowProxy(QMenu* proxy) +//{ +// proxy.removeListener(SWT.Show, getMenuCreatorListener()); +// IMenuCreator mc = action.getMenuCreator(); +// menuCreatorCalled = true; +// if (mc == null) { +// return; +// } +// holdMenu = mc.getMenu(proxy.getParentMenu()); +// if (holdMenu == null) { +// return; +// } +// copyMenu(holdMenu, proxy); +//} + +//void QActionContributionItem::CopyMenu(QMenu* realMenu, QMenu* proxy) { +// if (realMenu.isDisposed() || proxy.isDisposed()) { +// return; +// } + +// // we notify the real menu so it can populate itself if it was +// // listening for SWT.Show +// realMenu.notifyListeners(SWT.Show, null); + +// final Listener passThrough = new Listener() { +// public void handleEvent(Event event) { +// if (!event.widget.isDisposed()) { +// Widget realItem = (Widget) event.widget.getData(); +// if (!realItem.isDisposed()) { +// int style = event.widget.getStyle(); +// if (event.type == SWT.Selection +// && ((style & (SWT.TOGGLE | SWT.CHECK | SWT.RADIO)) != 0) +// && realItem instanceof MenuItem) { +// ((MenuItem) realItem) +// .setSelection(((MenuItem) event.widget) +// .getSelection()); +// } +// event.widget = realItem; +// realItem.notifyListeners(event.type, event); +// } +// } +// } +// }; + +// MenuItem[] items = realMenu.getItems(); +// for (int i = 0; i < items.length; i++) { +// final MenuItem realItem = items[i]; +// final MenuItem proxyItem = new MenuItem(proxy, realItem.getStyle()); +// proxyItem.setData(realItem); +// proxyItem.setAccelerator(realItem.getAccelerator()); +// proxyItem.setEnabled(realItem.getEnabled()); +// proxyItem.setImage(realItem.getImage()); +// proxyItem.setSelection(realItem.getSelection()); +// proxyItem.setText(realItem.getText()); + +// // pass through any events +// proxyItem.addListener(SWT.Selection, passThrough); +// proxyItem.addListener(SWT.Arm, passThrough); +// proxyItem.addListener(SWT.Help, passThrough); + +// final Menu itemMenu = realItem.getMenu(); +// if (itemMenu != null) { +// // create a proxy for any sub menu items +// final Menu subMenu = new Menu(proxy); +// subMenu.setData(itemMenu); +// proxyItem.setMenu(subMenu); +// subMenu.addListener(SWT.Show, new Listener() { +// public void handleEvent(Event event) { +// event.widget.removeListener(SWT.Show, this); +// if (event.type == SWT.Show) { +// copyMenu(itemMenu, subMenu); +// } +// } +// }); +// subMenu.addListener(SWT.Help, passThrough); +// subMenu.addListener(SWT.Hide, passThrough); +// } +// } +//} + +//void QActionContributionItem::HandleHideProxy(QMenu* proxy) +//{ +// proxy.removeListener(SWT.Hide, getMenuCreatorListener()); +// proxy.getDisplay().asyncExec(new Runnable() { +// public void run() { +// if (!proxy.isDisposed()) { +// MenuItem parentItem = proxy.getParentItem(); +// proxy.dispose(); +// parentItem.setMenu(holdMenu); +// } +// if (holdMenu != null && !holdMenu.isDisposed()) { +// holdMenu.notifyListeners(SWT.Hide, null); +// } +// holdMenu = null; +// } +// }); +//} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryQActionContributionItem.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryQActionContributionItem.h new file mode 100644 index 0000000000..8147c8939a --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryQActionContributionItem.h @@ -0,0 +1,291 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + + +#ifndef BERRYQACTIONCONTRIBUTIONITEM_H +#define BERRYQACTIONCONTRIBUTIONITEM_H + +#include "berryContributionItem.h" + +namespace berry { + +/** + * A contribution item which delegates to a QAction. + *

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

+ * @noextend This class is not intended to be subclassed by clients. + */ +class BERRY_UI_QT QActionContributionItem : public ContributionItem +{ + +public: + + /** + * Creates a new contribution item from the given action and id. + * + * @param action + * the action + */ + QActionContributionItem(QAction* action, const QString& id); + + ~QActionContributionItem(); + + /** + * Compares this action contribution item with another object. Two action + * contribution items are equal if they refer to the identical QAction. + */ + bool operator==(const Object* o) const; + + uint HashCode() const; + + /** + * The QActionContributionItem implementation of this + * IContributionItem method creates an SWT + * Button for the action using the action's style. If the + * action's checked property has been set, the button is created and primed + * to the value of the checked property. + */ + void Fill(QStatusBar* parent); + + /** + * The ActionContributionItem implementation of this + * IContributionItem method creates an SWT + * MenuItem for the action using the action's style. If the + * action's checked property has been set, a button is created and primed to + * the value of the checked property. If the action's menu creator property + * has been set, a cascading submenu is created. + */ + void Fill(QMenu* parent, QAction *before); + + /** + * The ActionContributionItem implementation of this , + * IContributionItem method creates an SWT + * ToolItem for the action using the action's style. If the + * action's checked property has been set, a button is created and primed to + * the value of the checked property. If the action's menu creator property + * has been set, a drop-down tool item is created. + */ + void Fill(QToolBar* parent, QAction* before); + + using ContributionItem::Fill; + + /** + * Returns the action associated with this contribution item. + * + * @return the action + */ + QAction* GetAction() const; + + /** + * Returns the presentation mode, which is the bitwise-or of the + * MODE_* constants. The default mode setting is 0, meaning + * that for menu items, both text and image are shown (if present), but for + * tool items, the text is shown only if there is no image. + * + * @return the presentation mode settings + */ + Modes GetMode() const; + + /** + * The action item implementation of this IContributionItem + * method returns true for menu items and false + * for everything else. + */ + bool IsDynamic() const; + + /* + * Method declared on IContributionItem. + */ + bool IsEnabled() const; + + /** + * The ActionContributionItem implementation of this + * ContributionItem method extends the super implementation + * by also checking whether the command corresponding to this action is + * active. + */ + bool IsVisible() const; + + /** + * Sets the presentation mode, which is the bitwise-or of the + * MODE_* constants. + * + * @param mode + * the presentation mode settings + */ + void SetMode(Modes mode); + + /** + * The action item implementation of this IContributionItem + * method calls update(null). + */ + void Update(); + + /** + * Synchronizes the UI with the given property. + * + * @param propertyName + * the name of the property, or null meaning all + * applicable properties + */ + void Update(const QString& propertyName); + +protected: + + /** + * Returns true if this item is allowed to enable, + * false otherwise. + * + * @return if this item is allowed to be enabled + */ + bool IsEnabledAllowed() const; + + /** + * Shorten the given text t so that its length doesn't exceed + * the width of the given ToolItem.The default implementation replaces + * characters in the center of the original string with an ellipsis ("..."). + * Override if you need a different strategy. + * + * @param textValue + * the text to shorten + * @param item + * the tool item the text belongs to + * @return the shortened string + * + */ + //QString ShortenText(const QString& textValue, QToolButton* item); + +private: + + /** + * Returns the listener for SWT tool item widget events. + * + * @return a listener for tool item events + */ + //Listener GetToolItemListener(); + + /** + * Handles a widget dispose event for the widget corresponding to this item. + */ + //void HandleWidgetDispose(Event e); + + /** + * Handles a widget selection event. + */ + //void HandleWidgetSelection(Event e, bool selection); + + /** + * Returns whether the given action has any images. + * + * @param actionToCheck + * the action + * @return true if the action has any images, + * false if not + */ + //bool HasImages(Action* actionToCheck) const; + + /** + * Returns whether the command corresponding to this action is active. + */ + bool IsCommandActive() const; + + /** + * Updates the images for this action. + * + * @param forceImage + * true if some form of image is compulsory, and + * false if it is acceptable for this item to have + * no image + * @return true if there are images for this action, + * false if not + */ + //bool UpdateImages(bool forceImage); + + /** + * Dispose any images allocated for this contribution item + */ + //void DisposeOldImages(); + + /** + * Handle show and hide on the proxy menu for IAction.AS_DROP_DOWN_MENU + * actions. + * + * @return the appropriate listener + */ + //Listener getMenuCreatorListener(); + + /** + * The proxy menu is being shown, we better get the real menu. + * + * @param proxy + * the proxy menu + */ + //void HandleShowProxy(QMenu* proxy); + + /** + * Create MenuItems in the proxy menu that can execute the real menu items + * if selected. Create proxy menus for any real item submenus. + * + * @param realMenu + * the real menu to copy from + * @param proxy + * the proxy menu to populate + */ + //void CopyMenu(QMenu* realMenu, QMenu* proxy); + + /** + * The proxy menu is being hidden, so we need to make it go away. + * + * @param proxy + * the proxy menu + */ + //void HandleHideProxy(QMenu* proxy); + +private: + + /** + * This is the easiest way to hold the menu until we can swap it in to the + * proxy. + */ + //QMenu* holdMenu = null; + + //bool menuCreatorCalled = false; + + + /** a string inserted in the middle of text that has been shortened */ + //static const QString ellipsis = "..."; + + /** + * Stores the result of the action. False when the action returned failure. + */ + bool result; // = null; + + /** + * The presentation mode. + */ + Modes mode; // = 0; + + /** + * The action. + */ + QAction* action; + +}; + +} + +#endif // BERRYQACTIONCONTRIBUTIONITEM_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryQActionProperties.cpp similarity index 78% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.cpp copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryQActionProperties.cpp index 0c29554981..e008991636 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryQActionProperties.cpp @@ -1,24 +1,24 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryWorkbenchActionConstants.h" +#include "berryQActionProperties.h" namespace berry { -const QString WorkbenchActionConstants::MB_ADDITIONS = "additions"; +const QString QActionProperties::TEXT = "text"; +const QString QActionProperties::IMAGE = "icon"; } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryQActionProperties.h similarity index 63% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.cpp copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryQActionProperties.h index ffd8e80060..11356759db 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryQActionProperties.h @@ -1,37 +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 BERRYQACTIONPROPERTIES_H +#define BERRYQACTIONPROPERTIES_H -#include "berryMMMenuListener.h" +#include -#include +#include namespace berry { -MMMenuListener::MMMenuListener(berry::MenuManager* mm) - : QObject(), mm(mm) -{} - -void MMMenuListener::HandleAboutToShow() +struct BERRY_UI_QT QActionProperties { - if (mm->removeAllWhenShown) - { - mm->RemoveAll(); - } - mm->Update(false, false); -} + static const QString TEXT; // = "text"; + static const QString IMAGE; // = "icon"; +}; } +#endif // BERRYQACTIONPROPERTIES_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySeparator.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySeparator.cpp index 83b46decbb..714d396095 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySeparator.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySeparator.cpp @@ -1,57 +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 "berrySeparator.h" #include #include namespace berry { Separator::Separator() { } Separator::Separator(const QString& groupName) : AbstractGroupMarker(groupName) { } -QAction* Separator::Fill(QMenu* menu, QAction* before) +void Separator::Fill(QMenu* menu, QAction* before) { if (before) { - return menu->insertSeparator(before); + menu->insertSeparator(before); + } + else + { + menu->addSeparator(); } - return menu->addSeparator(); } -QAction* Separator::Fill(QToolBar* toolbar, QAction* before) +void Separator::Fill(QToolBar* toolbar, QAction* before) { if (before) { - return toolbar->insertSeparator(before); + toolbar->insertSeparator(before); + } + else + { + toolbar->addSeparator(); } - return toolbar->addSeparator(); } bool Separator::IsSeparator() const { return true; } } 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 0f21bcbef0..e83917fac5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySeparator.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySeparator.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 BERRYSEPARATOR_H #define BERRYSEPARATOR_H -#include "berryAbstractGroupMarker.h" +#include "internal/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 +class BERRY_UI_QT 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); + void Fill(QMenu* menu, QAction* before); - QAction* Fill(QToolBar* toolbar, QAction* before); + void 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 4ef6d00ed0..7230532404 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,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 "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) +void SubContributionItem::Fill(QMenu *parent, QAction *before) { if (visible) { - return innerItem->Fill(parent, before); + innerItem->Fill(parent, before); } - return 0; } -QAction *SubContributionItem::Fill(QToolBar *parent, QAction *before) +void SubContributionItem::Fill(QToolBar *parent, QAction *before) { if (visible) { - return innerItem->Fill(parent, before); + 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*/) { // 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 31ed6f1ac2..c60c90062a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySubContributionItem.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berrySubContributionItem.h @@ -1,151 +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); + void Fill(QMenu* parent, QAction* before); /* * Method declared on IContributionItem. */ - QAction* Fill(QToolBar* parent, QAction* before); + void 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 5d57857588..b068bc51be 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryActionBarAdvisor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryActionBarAdvisor.cpp @@ -1,88 +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 "berryActionBarAdvisor.h" #include #include #include #include +#include + namespace berry { +ActionBarAdvisor::~ActionBarAdvisor() +{ + qDeleteAll(actions); +} + 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)) + 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::Register(QAction* action, const QString& id) +{ + Q_ASSERT_X(action, "nullcheck", "QAction must not be null"); + actions.insert(id, action); +} + +QAction* ActionBarAdvisor::GetAction(const QString& id) const +{ + auto iter = actions.find(id); + return iter == actions.end() ? NULL : iter.value(); +} + 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/berryActionBarAdvisor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryActionBarAdvisor.h index 82adec745a..4f93c7ed8b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryActionBarAdvisor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryActionBarAdvisor.h @@ -1,268 +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 BERRYACTIONBARADVISOR_H_ #define BERRYACTIONBARADVISOR_H_ #include #include +class QAction; + namespace berry { struct IMenuManager; struct IToolBarManager; struct IStatusLineManager; struct IActionBarConfigurer; struct IMemento; struct IWorkbenchWindow; /** * Public base class for configuring the action bars of a workbench window. *

* An application should declare a subclass of ActionBarAdvisor * and override methods to configure a window's action bars to suit the needs of the * particular application. *

*

* The following advisor methods are called at strategic points in the * workbench's lifecycle (all occur within the dynamic scope of the call * to {@link PlatformUI#createAndRunWorkbench PlatformUI.createAndRunWorkbench}): *

    *
  • fillActionBars - called after WorkbenchWindowAdvisor.preWindowOpen * to configure a window's action bars
  • *
*

* * @see WorkbenchWindowAdvisor#createActionBarAdvisor(IActionBarConfigurer) */ class BERRY_UI_QT ActionBarAdvisor : public Object { public: berryObjectMacro(berry::ActionBarAdvisor) enum FillType { /** * Bit flag for {@link #fillActionBars fillActionBars} indicating that the * operation is not filling the action bars of an actual workbench window, * but rather a proxy (used for perspective customization). */ FILL_PROXY = 0x01, /** * Bit flag for {@link #fillActionBars fillActionBars} indicating that the * operation is supposed to fill (or describe) the workbench window's menu * bar. */ FILL_MENU_BAR = 0x02, /** * Bit flag for {@link #fillActionBars fillActionBars} indicating that the * operation is supposed to fill (or describe) the workbench window's cool * bar. */ FILL_TOOL_BAR = 0x04, /** * Bit flag for {@link #fillActionBars fillActionBars} indicating that the * operation is supposed to fill (or describe) the workbench window's status * line. */ FILL_STATUS_LINE = 0x08 }; Q_DECLARE_FLAGS(FillFlags, FillType) public: + ~ActionBarAdvisor(); + /** * Creates a new action bar advisor to configure a workbench * window's action bars via the given action bar configurer. * * @param configurer the action bar configurer */ ActionBarAdvisor(const SmartPointer& configurer); /** * Configures the action bars using the given action bar configurer. * Under normal circumstances, flags does not include * FILL_PROXY, meaning this is a request to fill the action * bars of the corresponding workbench window; the * remaining flags indicate which combination of * the menu bar (FILL_MENU_BAR), - * the tool bar (FILL_COOL_BAR), + * the tool bar (FILL_TOOL_BAR), * and the status line (FILL_STATUS_LINE) are to be filled. *

* If flags does include FILL_PROXY, then this * is a request to describe the actions bars of the given workbench window * (which will already have been filled); * again, the remaining flags indicate which combination of the menu bar, * the tool bar, and the status line are to be described. * The actions included in the proxy action bars can be the same instances - * as in the actual window's action bars. Calling ActionFactory - * to create new action instances is not recommended, because these - * actions internally register listeners with the window and there is no - * opportunity to dispose of these actions. + * as in the actual window's action bars. *

*

- * This method is called just after {@link WorkbenchWindowAdvisor#preWindowOpen()}. + * This method is called just after {@link WorkbenchWindowAdvisor#PreWindowOpen()}. * Clients must not call this method directly (although super calls are okay). - * The default implementation calls makeActions if - * FILL_PROXY is specified, then calls fillMenuBar, - * fillCoolBar, and fillStatusLine + * The default implementation calls MakeActions if + * FILL_PROXY is specified, then calls FillMenuBar, + * FillToolBar, and FillStatusLine * if the corresponding flags are specified. *

*

* Subclasses may override, but it is recommended that they override the * methods mentioned above instead. *

* * @param flags bit mask composed from the constants * {@link #FILL_MENU_BAR FILL_MENU_BAR}, - * {@link #FILL_COOL_BAR FILL_COOL_BAR}, + * {@link #FILL_TOOL_BAR FILL_TOOL_BAR}, * {@link #FILL_STATUS_LINE FILL_STATUS_LINE}, * and {@link #FILL_PROXY FILL_PROXY} */ virtual void FillActionBars(FillFlags flags); /** * Saves arbitrary application-specific state information * for this action bar advisor. *

* The default implementation simply returns an OK status. * Subclasses may extend or override. *

* * @param memento the memento in which to save the advisor's state * @return a status object indicating whether the save was successful */ virtual bool SaveState(SmartPointer memento); /** * Restores arbitrary application-specific state information * for this action bar advisor. *

* The default implementation simply returns an OK status. * Subclasses may extend or override. *

* * @param memento the memento from which to restore the advisor's state * @return a status object indicating whether the restore was successful */ public: virtual bool RestoreState(SmartPointer memento); + using Object::Register; + protected: /** * Returns the action bar configurer. * * @return the action bar configurer */ virtual SmartPointer GetActionBarConfigurer() const; /** * Instantiates the actions used in the fill methods. - * Use {@link #register(IAction)} to register the action with the key binding service - * and add it to the list of actions to be disposed when the window is closed. + * Use {@link #Register(QAction*)} to add it to the list of actions to + * be disposed when the window is closed. * * @param window the window containing the action bars */ virtual void MakeActions(IWorkbenchWindow* window); - /* - * Registers the given action with the key binding service - * (by calling {@link IActionBarConfigurer#registerGlobalAction(IAction)}), - * and adds it to the list of actions to be disposed when the window is closed. - *

- * In order to participate in key bindings, the action must have an action - * definition id (aka command id), and a corresponding command extension. - * See the org.blueberry.ui.commands extension point documentation - * for more details. - *

+ /** + * Adds the given action to the list of actions to be disposed when the window is closed. * * @param action the action to register, this cannot be null - * - * @see IAction#setActionDefinitionId(String) - * @see #disposeAction(IAction) + * @param id the unique action id */ -// protected: virtual void Register(IAction action) { -// Assert.isNotNull(action, "Action must not be null"); //$NON-NLS-1$ -// String id = action.getId(); -// Assert.isNotNull(id, "Action must not have null id"); //$NON-NLS-1$ -// getActionBarConfigurer().registerGlobalAction(action); -// actions.put(id, action); -// } - - /* + virtual void Register(QAction* action, const QString& id); + + /** * Returns the action with the given id, or null if not found. * * @param id the action id * @return the action with the given id, or null if not found - * @see IAction#getId() */ -// protected: virtual IAction GetAction(const QString& id) { -// return (IAction) actions.get(id); -// } + virtual QAction* GetAction(const QString& id) const; /** * Fills the menu bar with the main menus for the window. *

* The default implementation does nothing. * Subclasses may override. *

* * @param menuBar the menu manager for the menu bar */ virtual void FillMenuBar(IMenuManager* menuBar); /** * Fills the tool bar with the main toolbars for the window. *

* The default implementation does nothing. * Subclasses may override. *

* * @param toolBar the bar manager */ virtual void FillToolBar(IToolBarManager* toolBar); /** * Fills the status line with the main status line contributions * for the window. *

* The default implementation does nothing. * Subclasses may override. *

* * @param statusLine the status line manager */ virtual void FillStatusLine(IStatusLineManager* statusLine); private: SmartPointer actionBarConfigurer; - //private: Map actions = new HashMap(); + QHash actions; }; } Q_DECLARE_OPERATORS_FOR_FLAGS(berry::ActionBarAdvisor::FillFlags) #endif /*BERRYACTIONBARADVISOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchAdvisor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchAdvisor.h index 46acbf3c1f..b11c68ab0e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchAdvisor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryWorkbenchAdvisor.h @@ -1,410 +1,410 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYWORKBENCHADVISOR_H_ #define BERRYWORKBENCHADVISOR_H_ #include #include "berryIMemento.h" #include #include "berryWorkbenchWindowAdvisor.h" #include "berryIWorkbenchConfigurer.h" namespace berry { /** * public: base class for configuring the workbench. *

* Note that the workbench advisor object is created in advance of creating the * workbench. However, by the time the workbench starts calling methods on this * class, PlatformUI#GetWorkbench() is guaranteed to have been * properly initialized. *

*

* Example of creating and running a workbench (in an * berry#IApplication): * *

  * 
  *           class MyApplication : public %berry::IApplication {
  *
  *             public:
  *
  *             int Start()
  *             {
  *               WorkbenchAdvisor* workbenchAdvisor = new MyWorkbenchAdvisor();
  *               %berry::Display* display = %berry::PlatformUI::CreateDisplay();
  *               int returnCode = berry::PlatformUI::CreateAndRunWorkbench(display, workbenchAdvisor);
  *
  *               if (returnCode == %PlatformUI::RETURN_RESTART) {
  *                  return %berry::IApplication::EXIT_RESTART;
  *               } else {
  *                  return %berry::IApplication::EXIT_OK;
  *             }
  *           };
  * 
  * 
* *

*

* An application should declare a subclass of berry::WorkbenchAdvisor * and override methods to configure the workbench to suit the needs of the * particular application. *

*

* The following advisor methods are called at strategic points in the * workbench's lifecycle (all occur within the dynamic scope of the call to * PlatformUI#CreateAndRunWorkbench()): *

    *
  • Initialize() - called first; before any windows; use to * register things
  • *
  • PreStartup() - called second; after initialize but before * first window is opened; use to temporarily disable things during startup or * restore
  • *
  • PostStartup() - called third; after first window is opened; * use to reenable things temporarily disabled in previous step
  • *
  • EventLoopException() - called to handle the case where the * event loop has crashed; use to inform the user that things are not well (not implemented yet)
  • *
  • EventLoopIdle() - called when there are currently no more * events to be processed; use to perform other work or to yield until new * events enter the queue (not implemented yet)
  • *
  • PreShutdown() - called immediately prior to workbench * shutdown before any windows have been closed; allows the advisor to veto the * shutdown
  • *
  • PostShutdown() - called last; after event loop has * terminated and all windows have been closed; use to deregister things * registered during initialize
  • *
*

* */ class BERRY_UI_QT WorkbenchAdvisor { /** * The workbench configurer. */ private: IWorkbenchConfigurer::Pointer workbenchConfigurer; /* * The workbench error handler. */ //private: AbstractStatusHandler workbenchErrorHandler; - private: bool introOpened; + //private: bool introOpened; /** * Creates and initializes a new workbench advisor instance. */ protected: WorkbenchAdvisor(); virtual ~WorkbenchAdvisor(); /** * Remembers the configurer and calls Initialize(). *

* For internal use by the workbench only. *

* * @param configurer * an object for configuring the workbench */ public: void InternalBasicInitialize(IWorkbenchConfigurer::Pointer configurer); /** * Performs arbitrary initialization before the workbench starts running. *

* This method is called during workbench initialization prior to any * windows being opened. Clients must not call this method directly * (although super calls are okay). The default implementation does nothing. * Subclasses may override. Typical clients will use the configurer passed * in to tweak the workbench. If further tweaking is required in the future, * the configurer may be obtained using GetWorkbenchConfigurer(). *

* * @param configurer * an object for configuring the workbench */ public: virtual void Initialize(IWorkbenchConfigurer::Pointer configurer); /** * Returns the workbench configurer for the advisor. Can be * null if the advisor is not initialized yet. * * @return the workbench configurer, or null if the advisor * is not initialized yet */ protected: IWorkbenchConfigurer::Pointer GetWorkbenchConfigurer(); /* * Returns the workbench error handler for the advisor. * * @return the workbench error handler * @since 3.3 */ // public: AbstractStatusHandler getWorkbenchErrorHandler() { // if (workbenchErrorHandler == null) { // workbenchErrorHandler = new WorkbenchErrorHandler(); // } // return workbenchErrorHandler; // } /** * Performs arbitrary actions just before the first workbench window is * opened (or restored). *

* This method is called after the workbench has been initialized and just * before the first window is about to be opened. Clients must not call this * method directly (although super calls are okay). The default * implementation does nothing. Subclasses may override. *

*/ public: virtual void PreStartup(); /** * Performs arbitrary actions after the workbench windows have been opened * (or restored), but before the main event loop is run. *

* This method is called just after the windows have been opened. Clients * must not call this method directly (although super calls are okay). The * default implementation does nothing. Subclasses may override. It is okay * to call IWorkbench#Close() from this method. *

*/ public: virtual void PostStartup(); /** * Performs arbitrary finalization before the workbench is about to shut * down. *

* This method is called immediately prior to workbench shutdown before any * windows have been closed. Clients must not call this method directly * (although super calls are okay). The default implementation returns * true. Subclasses may override. *

*

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

* * @return true to allow the workbench to proceed with * shutdown, false to veto a non-forced shutdown */ public: virtual bool PreShutdown(); /** * Performs arbitrary finalization after the workbench stops running. *

* This method is called during workbench shutdown after all windows have * been closed. Clients must not call this method directly (although super * calls are okay). The default implementation does nothing. Subclasses may * override. *

*/ public: virtual void PostShutdown(); /* * Performs arbitrary actions when the event loop crashes (the code that * handles a UI event throws an exception that is not caught). *

* This method is called when the code handling a UI event throws an * exception. In a perfectly functioning application, this method would * never be called. In practice, it comes into play when there are bugs in * the code that trigger unchecked runtime exceptions. It is also activated * when the system runs short of memory, etc. Fatal errors (ThreadDeath) are * not passed on to this method, as there is nothing that could be done. *

*

* Clients must not call this method directly (although super calls are * okay). The default implementation logs the problem so that it does not go * unnoticed. Subclasses may override or extend this method. It is generally * a bad idea to override with an empty method, and you should be especially * careful when handling Errors. *

* * @param exception * the uncaught exception that was thrown inside the UI event * loop */ // public: void eventLoopException(Throwable exception) { // // Protection from client doing super(null) call // if (exception == null) { // return; // } // // try { // StatusManager.getManager().handle( // new Status(IStatus.ERR, WorkbenchPlugin.PI_WORKBENCH, // "Unhandled event loop exception", exception)); //$NON-NLS-1$ // // if (WorkbenchPlugin.DEBUG) { // exception.printStackTrace(); // } // } catch (Throwable e) { // // One of the log listeners probably failed. Core should have logged // // the // // exception since its the first listener. // System.err.println("Error while logging event loop exception:"); //$NON-NLS-1$ // exception.printStackTrace(); // System.err.println("Logging exception:"); //$NON-NLS-1$ // e.printStackTrace(); // } // } /* * Performs arbitrary work or yields when there are no events to be * processed. *

* This method is called when there are currently no more events on the * queue to be processed at the moment. *

*

* Clients must not call this method directly (although super calls are * okay). The default implementation yields until new events enter the * queue. Subclasses may override or extend this method. It is generally a * bad idea to override with an empty method. It is okay to call * IWorkbench.close() from this method. *

* * @param display * the main display of the workbench UI */ // public: void eventLoopIdle(Display display) { // // default: yield cpu until new events enter the queue // display.sleep(); // } /** * Creates a new workbench window advisor for configuring a new workbench * window via the given workbench window configurer. Clients should override * to provide their own window configurer. * * @param configurer * the workbench window configurer * @return a new workbench window advisor */ public: virtual WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( IWorkbenchWindowConfigurer::Pointer configurer) = 0; /** * Returns the default input for newly created workbench pages when the * input is not explicitly specified. *

* The default implementation returns null. Subclasses may * override. *

* * @return the default input for a new workbench window page, or * null if none * * @see #CreateWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer::Pointer) */ public: virtual IAdaptable* GetDefaultPageInput(); /** * Returns the id of the perspective to use for the initial workbench * window, or null if no initial perspective should be shown * in the initial workbench window. *

* This method is called during startup when the workbench is creating the * first new window. Subclasses must implement. *

*

* If the WorkbenchPreferenceConstants#DEFAULT_PERSPECTIVE_ID * preference is specified, it supercedes the perspective specified here. *

* * @return the id of the perspective for the initial window, or * null if no initial perspective should be shown */ public: virtual QString GetInitialWindowPerspectiveId() = 0; /** * Returns the id of the preference page that should be presented most * prominently. *

* The default implementation returns null. Subclasses may * override. *

* * @return the id of the preference page, or null if none */ public: virtual QString GetMainPreferencePageId(); /** * Opens the workbench windows on startup. The default implementation tries * to restore the previously saved workbench state using * IWorkbenchConfigurer#RestoreState(). If there * was no previously saved state, or if the restore failed, then a * first-time window is opened using * IWorkbenchConfigurer#OpenFirstTimeWindow(). * * @return true to proceed with workbench startup, or * false to exit */ public: virtual bool OpenWindows(); /** * Saves arbitrary application-specific state information for this workbench * advisor. *

* The default implementation simply returns an OK status. Subclasses may * extend or override. *

* * @param memento * the memento in which to save the advisor's state * @return a status object indicating whether the save was successful */ public: virtual bool SaveState(IMemento::Pointer memento); /** * Restores arbitrary application-specific state information for this * workbench advisor. *

* The default implementation simply returns an OK status. Subclasses may * extend or override. *

* * @param memento * the memento from which to restore the advisor's state * @return a status object indicating whether the restore was successful */ public: virtual bool RestoreState(IMemento::Pointer memento); /* * Return the contribution comparator for the particular type of * contribution. The default implementation of this class returns a * comparator that sorts the items by label. * * The contributionType may be one of the constants in * {@link IContributionService} or it can be a value defined by the user. * * @param contributionType * the contribution type * @return the comparator, must not return null * @see IContributionService#GetComparatorFor(const QString&) */ // public: ContributionComparator getComparatorFor(String contributionType) { // return new ContributionComparator(); // } }; } #endif /*BERRYWORKBENCHADVISOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractSourceProvider.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractSourceProvider.cpp index be749e9771..b35d8f11ea 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 = false; //Policy.DEBUG_SOURCES; void AbstractSourceProvider::FireSourceChanged(int sourcePriority, const QString &sourceName, Object::ConstPointer sourceValue) { sourceEvents.singleSourceChanged(sourcePriority, sourceName, sourceValue); } void AbstractSourceProvider::FireSourceChanged(int sourcePriority, const QHash &sourceValuesByName) { sourceEvents.multipleSourcesChanged(sourcePriority, sourceValuesByName); } void AbstractSourceProvider::LogDebuggingInfo(const QString& message) { if (DEBUG && (message != "")) { - BERRY_INFO << "SOURCES" << " >>> " << message; + BERRY_INFO << "SOURCES >>> " << message; } } void AbstractSourceProvider::AddSourceProviderListener( ISourceProviderListener* listener) { if (listener == 0) { 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"); } sourceEvents.RemoveListener(listener); } 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 a9830f28e2..ee341eafbf 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractSourceProvider.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryAbstractSourceProvider.h @@ -1,114 +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. *

*/ class AbstractSourceProvider : public ISourceProvider { protected: - /** - * Whether source providers should print out debugging information to the - * console when events arrive. - */ - 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::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); /** * 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. */ void LogDebuggingInfo(const QString& message); private: ISourceProviderListener::Events sourceEvents; public: + /** + * Whether source providers should print out debugging information to the + * console when events arrive. + */ + static bool DEBUG; // = Policy.DEBUG_SOURCES; + 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 */ virtual void Initialize(IServiceLocator* locator); }; } #endif /* BERRYABSTRACTSOURCEPROVIDER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryEditorPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryEditorPart.h index 96f324bc04..4573484595 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryEditorPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryEditorPart.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 BERRYEDITORPART_H_ #define BERRYEDITORPART_H_ #include #include "berryIEditorPart.h" #include "berryIEditorInput.h" #include "berryIEditorSite.h" #include "berryWorkbenchPart.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * Abstract base implementation of all workbench editors. *

* This class should be subclassed by clients wishing to define new editors. * The name of the subclass should be given as the "class" * attribute in a editor extension contributed to the workbench's * editor extension point (named "org.mitk.ui.editors"). * For example, the plug-in's XML markup might contain: *

  * <extension point="org.blueberry.ui.editors">
  *      <editor id="com.example.myplugin.ed"
  *         name="My Editor"
  *         icon="./images/cedit.gif"
  *       extensions="foo"
  *       class="com.example.myplugin.MyFooEditor"
  *       contributorClass="com.example.myplugin.MyFooEditorContributor"
  *      />
  * </extension>
  * 
* where com.example.myplugin.MyEditor is the name of the * EditorPart subclass. *

*

* Subclasses must implement the following methods: *

    *
  • IEditorPart.init - to initialize editor when assigned its site
  • *
  • IWorkbenchPart.createPartControl - to create the editor's controls
  • *
  • IWorkbenchPart.setFocus - to accept focus
  • *
  • IEditorPart.isDirty - to decide whether a significant change has * occurred
  • *
  • IEditorPart.doSave - to save contents of editor
  • *
  • IEditorPart.doSaveAs - to save contents of editor
  • *
  • IEditorPart.isSaveAsAllowed - to control Save As
  • *
*

*

* Subclasses may extend or reimplement the following methods as required: *

    *
  • IExecutableExtension.setInitializationData - extend to provide additional * initialization when editor extension is instantiated
  • *
  • IWorkbenchPart.dispose - extend to provide additional cleanup
  • *
  • IAdaptable.getAdapter - reimplement to make the editor * adaptable
  • *
*

*/ class BERRY_UI_QT EditorPart : public WorkbenchPart , public virtual IEditorPart { Q_OBJECT Q_INTERFACES(berry::IEditorPart) public: - berryObjectMacro(EditorPart); + berryObjectMacro(EditorPart, WorkbenchPart, IEditorPart) private: /** * Editor input, or null if none. */ IEditorInput::Pointer editorInput; protected: /** * Creates a new workbench editor. */ EditorPart(); /** * Sets the input to this editor. This method simply updates the internal * member variable. * *

Unlike most of the other set methods on this class, this method does * not fire a property change. Clients that call this method from a subclass * must ensure that they fire an IWorkbenchPartConstants.PROP_INPUT property * change after calling this method but before leaving whatever public method * they are in. Clients that expose this method as public API must fire * the property change within their implementation of setInput.

* *

Note that firing a property change may cause listeners to immediately * reach back and call methods on this editor. Care should be taken not to * fire the property change until the editor has fully updated its internal * state to reflect the new input.

* * @param input the editor input * * @see #setInputWithNotify(IEditorInput) */ virtual void SetInput(IEditorInput::Pointer input) ; /** * Sets the input to this editor and fires a PROP_INPUT property change if * the input has changed. This is the convenience method implementation. * *

Note that firing a property change may cause other objects to reach back * and invoke methods on the editor. Care should be taken not to call this method * until the editor has fully updated its internal state to reflect the * new input.

* * @since 3.2 * * @param input the editor input */ virtual void SetInputWithNotify(IEditorInput::Pointer input); /* (non-Javadoc) * @see org.blueberry.ui.part.WorkbenchPart#setContentDescription(java.lang.String) */ virtual void SetContentDescription(const QString& description); /* (non-Javadoc) * @see org.blueberry.ui.part.WorkbenchPart#setPartName(java.lang.String) */ virtual void SetPartName(const QString& partName); /** * Checks that the given site is valid for this type of part. * The site for an editor must be an IEditorSite. * * @param site the site to check * @since 3.1 */ void CheckSite(IWorkbenchPartSite::Pointer site); public: /* (non-Javadoc) * Saves the contents of this editor. *

* Subclasses must override this method to implement the open-save-close lifecycle * for an editor. For greater details, see IEditorPart *

* * @see IEditorPart */ virtual void DoSave(/*IProgressMonitor monitor*/) = 0; /* (non-Javadoc) * Saves the contents of this editor to another object. *

* Subclasses must override this method to implement the open-save-close lifecycle * for an editor. For greater details, see IEditorPart *

* * @see IEditorPart */ virtual void DoSaveAs() = 0; /* (non-Javadoc) * Method declared on IEditorPart. */ IEditorInput::Pointer GetEditorInput() const; /* (non-Javadoc) * Method declared on IEditorPart. */ IEditorSite::Pointer GetEditorSite() const; /* (non-Javadoc) * Gets the title tool tip text of this part. * * @return the tool tip text */ QString GetTitleToolTip() const; /* (non-Javadoc) * Initializes the editor part with a site and input. *

* Subclasses of EditorPart must implement this method. Within * the implementation subclasses should verify that the input type is acceptable * and then save the site and input. Here is sample code: *

*
      *    if (!(input instanceof IFileEditorInput))
      *      throw new PartInitException("Invalid Input: Must be IFileEditorInput");
      *    setSite(site);
      *    setInput(input);
      * 
*/ virtual void Init(IEditorSite::Pointer site, IEditorInput::Pointer input) = 0; /* (non-Javadoc) * Returns whether the contents of this editor have changed since the last save * operation. *

* Subclasses must override this method to implement the open-save-close lifecycle * for an editor. For greater details, see IEditorPart *

* * @see IEditorPart */ virtual bool IsDirty() const = 0; /* (non-Javadoc) * Returns whether the "save as" operation is supported by this editor. *

* Subclasses must override this method to implement the open-save-close lifecycle * for an editor. For greater details, see IEditorPart *

* * @see IEditorPart */ virtual bool IsSaveAsAllowed() const = 0; /* (non-Javadoc) * Returns whether the contents of this editor should be saved when the editor * is closed. *

* This method returns true if and only if the editor is dirty * (isDirty). *

*/ virtual bool IsSaveOnCloseNeeded() const; }; } #endif /*BERRYEDITORPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryExtensionFactory.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryExtensionFactory.cpp new file mode 100644 index 0000000000..d40588ad82 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryExtensionFactory.cpp @@ -0,0 +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. + +===================================================================*/ + +#include "berryExtensionFactory.h" + +#include "berryIConfigurationElement.h" + +#include "berryCoreException.h" +#include "berryObjectString.h" +#include "berryPlatformUI.h" +#include "berryStatus.h" + +#include "internal/berryQtStylePreferencePage.h" +#include "internal/dialogs/berryPerspectivesPreferencePage.h" + +namespace berry { + +const QString ExtensionFactory::STYLE_PREFERENCE_PAGE = "stylePreferencePage"; +const QString ExtensionFactory::PERSPECTIVES_PREFERENCE_PAGE = "perspectivesPreferencePage"; + +ExtensionFactory::~ExtensionFactory() +{ +} + +QObject* ExtensionFactory::Create() +{ + if (STYLE_PREFERENCE_PAGE == id) + { + return Configure(new QtStylePreferencePage()); + } + if (PERSPECTIVES_PREFERENCE_PAGE == id) + { + return Configure(new PerspectivesPreferencePage()); + } +// if (SHOW_IN_CONTRIBUTION == id) +// { +// ShowInMenu showInMenu = new ShowInMenu(); +// return showInMenu; +// } + + IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, PlatformUI::PLUGIN_ID(), 0, + QString("Unknown id in data argument for ") + this->metaObject()->className(), + BERRY_STATUS_LOC)); + throw CoreException(status); +} + +void ExtensionFactory::SetInitializationData(const SmartPointer& config, const QString& propertyName, const Object::Pointer& data) +{ + if (ObjectString::Pointer strData = data.Cast()) + { + id = *strData; + } + else + { + IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, PlatformUI::PLUGIN_ID(), 0, + QString("Data argument must be a String for ") + this->metaObject()->className(), + BERRY_STATUS_LOC)); + throw CoreException(status); + } + this->config = config; + this->propertyName = propertyName; +} + +QObject*ExtensionFactory::Configure(QObject* obj) +{ + if (IExecutableExtension* execExt = qobject_cast(obj)) + { + execExt->SetInitializationData(config, propertyName, Object::Pointer()); + } + return obj; +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryExtensionFactory.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryExtensionFactory.h new file mode 100644 index 0000000000..b5bb06f780 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryExtensionFactory.h @@ -0,0 +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 BERRYEXTENSIONFACTORY_H +#define BERRYEXTENSIONFACTORY_H + +#include +#include +#include + +#include + +namespace berry { + +/** + * Factory for the workbench's public extensions. + *

+ * This allows the extensions to be made available for use by RCP applications + * without exposing their concrete implementation classes. + *

+ */ +class BERRY_UI_QT ExtensionFactory : public QObject, public IExecutableExtensionFactory, + public IExecutableExtension +{ + Q_OBJECT + Q_INTERFACES(berry::IExecutableExtensionFactory berry::IExecutableExtension) + +public: + + ~ExtensionFactory(); + + /** + * Factory ID for the Appearance preference page. + */ + static const QString STYLE_PREFERENCE_PAGE; // = "stylePreferencePage"; + + /** + * Factory ID for the Perspectives preference page. + */ + static const QString PERSPECTIVES_PREFERENCE_PAGE; // = "perspectivesPreferencePage"; + + /* + * Factory ID for the show in contribution. + */ + //static const QString SHOW_IN_CONTRIBUTION = "showInContribution"; + + + /** + * Creates the object referenced by the factory id obtained from the + * extension data. + */ + QObject* Create(); + + /* + * @see IExecutableExtension#SetInitializationData + */ + void SetInitializationData(const SmartPointer& config, + const QString& propertyName, const Object::Pointer& data); + +private: + + QObject* Configure(QObject* obj); + + IConfigurationElement::Pointer config; + + QString id; + + QString propertyName; + +}; + +} + +#endif // BERRYEXTENSIONFACTORY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryFileEditorInput.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryFileEditorInput.cpp index 18716fb263..13ed6c5147 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryFileEditorInput.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryFileEditorInput.cpp @@ -1,58 +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. ===================================================================*/ #include "berryFileEditorInput.h" +#include namespace berry { FileEditorInput::FileEditorInput(const QString& path) : m_Path(path) { } QString FileEditorInput::GetPath() const { return m_Path.absolutePath(); } bool FileEditorInput::Exists() const { return m_Path.exists(); } QString FileEditorInput::GetName() const { return m_Path.fileName(); } QString FileEditorInput::GetToolTipText() const { return m_Path.absolutePath(); } +QIcon FileEditorInput::GetIcon() const +{ + return QIcon(); +} + +const IPersistableElement*FileEditorInput::GetPersistable() const +{ + return nullptr; +} + +Object* FileEditorInput::GetAdapter(const QString& /*adapterType*/) const +{ + return nullptr; +} + bool FileEditorInput::operator==(const Object* o) const { if (const IPathEditorInput* other = dynamic_cast(o)) { return other->GetPath() == this->GetPath(); } return false; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryFileEditorInput.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryFileEditorInput.h index c03932ab76..ee93eff2f4 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryFileEditorInput.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryFileEditorInput.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 BERRYFILEEDITORINPUT_H_ #define BERRYFILEEDITORINPUT_H_ #include "berryIPathEditorInput.h" #include #include namespace berry { class BERRY_UI_QT FileEditorInput : public IPathEditorInput { public: berryObjectMacro(FileEditorInput); FileEditorInput(const QString& path); QString GetPath() const; bool Exists() const; QString GetName() const ; QString GetToolTipText() const; + QIcon GetIcon() const; + + const IPersistableElement* GetPersistable() const; + + Object* GetAdapter(const QString &adapterType) const; + bool operator==(const Object* o) const; private: QFileInfo m_Path; }; } #endif /* BERRYFILEEDITORINPUT_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIActionBars.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIActionBars.h index 2236893cea..9547f5586b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIActionBars.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIActionBars.h @@ -1,171 +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 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. + * 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 { 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.ui.qt/src/berryIEditorInput.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorInput.h index cc4a571f7f..7106bacbf0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorInput.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorInput.h @@ -1,143 +1,136 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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 + #include namespace berry { +struct IPersistableElement; + /** * \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 +struct BERRY_UI_QT IEditorInput : public virtual Object, public virtual IAdaptable { 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()). - *

+ * Returns the icon for this input. * - * @return the image descriptor for this input; may be null if + * @return the icon for this input; may be null icon if * there is no image. */ - //virtual ImageDescriptor GetImageDescriptor() = 0; + virtual QIcon GetIcon() const = 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; + virtual const IPersistableElement* GetPersistable() const = 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/berryIEditorPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorPart.h index dab8c1b2f2..eb94c812f1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIEditorPart.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 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 { - berryObjectMacro(berry::IEditorPart) + berryObjectMacro(berry::IEditorPart, IWorkbenchPart, ISaveablePart) 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.ui.IEditorPart") #endif /*BERRYIEDITORPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIElementFactory.cpp similarity index 86% copy from BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIElementFactory.cpp index 3b9d740123..71e8446c21 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIElementFactory.cpp @@ -1,25 +1,25 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryIBerryPreferences.h" +#include "berryIElementFactory.h" namespace berry { -IBerryPreferences::~IBerryPreferences () +IElementFactory::~IElementFactory() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIElementFactory.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIElementFactory.h new file mode 100644 index 0000000000..a3a821e884 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIElementFactory.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 BERRYIELEMENTFACTORY_H +#define BERRYIELEMENTFACTORY_H + +#include + +#include + +namespace berry { + +struct IAdaptable; +struct IMemento; + +/** + * A factory for re-creating objects from a previously saved memento. + *

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

+ * <extension point="org.blueberry.ui.elementFactories">
+ *    <factory id="com.example.myplugin.MyFactory" class="MyFactory" />
+ * </extension>
+ * 
+ *

+ * + * @see IPersistableElement + * @see IMemento + * @see IWorkbench#GetElementFactory + */ +struct BERRY_UI_QT IElementFactory +{ + ~IElementFactory(); + + /** + * Re-creates and returns an object from the state captured within the given + * memento. + *

+ * If the result is not null, it should be persistable; that is, + *

+   * result.getAdapter(org.eclipse.ui.IPersistableElement.class)
+   * 
+ * should not return null. The caller takes ownership of the + * result and must delete it when it is not needed any more. + *

+ * + * @param memento + * a memento containing the state for the object + * @return an object, or nullptr if the element could not be + * created + */ + virtual IAdaptable* CreateElement(const SmartPointer& memento) = 0; +}; + +} + +Q_DECLARE_INTERFACE(berry::IElementFactory, "org.blueberry.ui.IElementFactory") + +#endif // BERRYIELEMENTFACTORY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryINullSelectionListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryINullSelectionListener.h index 3eb43cc838..8c5df5db49 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryINullSelectionListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryINullSelectionListener.h @@ -1,103 +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 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 { - 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)(const IWorkbenchPart::Pointer&, const ISelection::ConstPointer&); NullSelectionChangedAdapter(R* l, Callback c) : listener(l), callback(c) { poco_assert(listener); poco_assert(callback); } 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.core.runtime/src/berryIBerryPreferences.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPersistable.cpp similarity index 85% copy from BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPersistable.cpp index 3b9d740123..1a5070904c 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPersistable.cpp @@ -1,25 +1,24 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryIBerryPreferences.h" +#include namespace berry { -IBerryPreferences::~IBerryPreferences () -{ -} +IPersistable::~IPersistable() +{} } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPersistable.h similarity index 52% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPersistable.h index babfd77662..e786a95ea4 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPersistable.h @@ -1,39 +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 BERRYWORKBENCHACTIONCONSTANTS_H -#define BERRYWORKBENCHACTIONCONSTANTS_H - -#include +#ifndef BERRYIPERSISTABLE_H +#define BERRYIPERSISTABLE_H #include +#include + namespace berry { -struct BERRY_UI_QT WorkbenchActionConstants +struct IMemento; + +/** + * Objects implementing this interface are capable of saving their + * state in an {@link IMemento}. + */ +struct BERRY_UI_QT IPersistable { + virtual ~IPersistable(); - // Standard area for adding top level menus: /** - * Name of group for adding new top-level menus (value "additions"). + * Saves the state of the object in the given memento. + * + * @param memento the storage area for object's state */ - static const QString MB_ADDITIONS; + virtual void SaveState(const SmartPointer& memento) const = 0; }; } -#endif // BERRYWORKBENCHACTIONCONSTANTS_H +#endif // BERRYIPERSISTABLE_H + diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPersistableEditor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPersistableEditor.h new file mode 100644 index 0000000000..3ffa48f36f --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPersistableEditor.h @@ -0,0 +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 BERRYIPERSISTABLEEDITOR_H +#define BERRYIPERSISTABLEEDITOR_H + +#include + +namespace berry { + +/** + * An editor can implement this interface and participate in the workbench + * session save/restore cycle using IMemento, similar to how + * IViewPart currently works. + *

+ * Refer to IWorkbenchPart for the part lifecycle. + *

+ *

+ * If a memento is available, RestoreState(*) will be inserted into the editor + * startup. + *

    + *
  1. editor.Init(site, input)
  2. + *
  3. editor.RestoreState(memento)
  4. + *
  5. editor.CreatePartControl(parent)
  6. + *
  7. ...
  8. + *
+ *

+ *

+ * On workbench shutdown, the editor state will be persisted when the editor + * references are saved. + *

+ */ +struct IPersistableEditor : public IPersistable +{ + /** + * Called with a memento for this editor. The editor can parse the data or + * save the memento. This method may not be called. + * + * @param memento + * the saved state for this editor. May be null. + */ + virtual void RestoreState(const SmartPointer& memento) = 0; +}; + +} + +#endif // BERRYIPERSISTABLEEDITOR_H + diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPersistableElement.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPersistableElement.h new file mode 100644 index 0000000000..84574013c3 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPersistableElement.h @@ -0,0 +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 BERRYIPERSISTABLEELEMENT_H +#define BERRYIPERSISTABLEELEMENT_H + +#include + +namespace berry { + +/** + * Interface for asking an object to store its state in a memento. + *

+ * This interface is typically included in interfaces where + * persistance is required. + *

+ * When the workbench is shutdown objects which implement this interface + * will be persisted. At this time the GetFactoryId method + * is invoked to discover the id of the element factory that will be used + * to re-create the object from a memento. Then the SaveState + * method is invoked to store the element data into a newly created memento. + * The resulting mementos are collected up and written out to a single file. + *

+ *

+ * During workbench startup these mementos are read from the file. The + * factory Id for each is retrieved and mapped to an IElementFactory + * which has been registered in the element factory extension point. If a + * factory exists for the Id it will be engaged to re-create the original + * object. + *

+ * + * @see IAdaptable + * @see IMemento + * @see IElementFactory + */ +struct IPersistableElement : public IPersistable +{ + /** + * Returns the id of the element factory which should be used to re-create this + * object. + *

+ * Factory ids are declared in extensions to the standard extension point + * "org.eclipse.ui.elementFactories". + *

+ * + * @return the element factory id + * @see IElementFactory + */ + virtual QString GetFactoryId() const = 0; +}; + +} + +#endif // BERRYIPERSISTABLEELEMENT_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h index f9582311c2..28db67fe3b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveDescriptor.h @@ -1,122 +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 BERRYIPERSPECTIVEDESCRIPTOR_H_ #define BERRYIPERSPECTIVEDESCRIPTOR_H_ #include #include #include 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 virtual Object { 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 QIcon 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; + //virtual bool IsPredefined() const = 0; /** * Return the category path of this descriptor * * @return the category path of this descriptor */ virtual QStringList GetCategoryPath() const = 0; - virtual QStringList GetKeywordReferences() const = 0; + /** + * Returns a list of ids belonging to keyword reference extensions. + * + * The keywords listed in each referenced id can be used to filter + * this perspective. + * + * @return A list of ids for keyword reference extensions. + */ + virtual QStringList GetKeywordReferences() const = 0; }; } #endif /*BERRYIPERSPECTIVEDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveListener.cpp index 0e05fa426c..27dd088a32 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveListener.cpp @@ -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. ===================================================================*/ #include "berryIPerspectiveListener.h" #include "berryIWorkbenchPage.h" namespace berry { void IPerspectiveListener::Events ::AddListener(IPerspectiveListener* listener) { if (listener == NULL) return; Types types = listener->GetPerspectiveEventTypes(); if (types & ACTIVATED) this->perspectiveActivated += Delegate2(listener, &IPerspectiveListener::PerspectiveActivated); if (types & CHANGED) this->perspectiveChanged += PerspChangedDelegate(listener, &IPerspectiveListener::PerspectiveChanged); if (types & PART_CHANGED) this->perspectivePartChanged += PerspPartChangedDelegate(listener, &IPerspectiveListener::PerspectiveChanged); if (types & OPENED) this->perspectiveOpened += Delegate2(listener, &IPerspectiveListener::PerspectiveOpened); if (types & CLOSED) this->perspectiveClosed += Delegate2(listener, &IPerspectiveListener::PerspectiveClosed); if (types & DEACTIVATED) this->perspectiveDeactivated += Delegate2(listener, &IPerspectiveListener::PerspectiveDeactivated); if (types & SAVED_AS) this->perspectiveSavedAs += PerspSavedAsDelegate(listener, &IPerspectiveListener::PerspectiveSavedAs); if (types & PRE_DEACTIVATE) this->perspectivePreDeactivate += Delegate2(listener, &IPerspectiveListener::PerspectivePreDeactivate); } void IPerspectiveListener::Events ::RemoveListener(IPerspectiveListener* listener) { 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); } IPerspectiveListener::~IPerspectiveListener() { } void IPerspectiveListener::PerspectiveActivated(const SmartPointer& /*page*/, const IPerspectiveDescriptor::Pointer& /*perspective*/) {} void IPerspectiveListener::PerspectiveChanged(const SmartPointer& /*page*/, const IPerspectiveDescriptor::Pointer& /*perspective*/, const QString& /*changeId*/) {} void IPerspectiveListener::PerspectiveChanged(const SmartPointer& /*page*/, const IPerspectiveDescriptor::Pointer& /*perspective*/, const IWorkbenchPartReference::Pointer& /*partRef*/, const QString& /*changeId*/) {} void IPerspectiveListener::PerspectiveOpened(const SmartPointer& /*page*/, const IPerspectiveDescriptor::Pointer& /*perspective*/) {} void IPerspectiveListener::PerspectiveClosed(const SmartPointer& /*page*/, const IPerspectiveDescriptor::Pointer& /*perspective*/) {} void IPerspectiveListener::PerspectiveDeactivated(const SmartPointer& /*page*/, const IPerspectiveDescriptor::Pointer& /*perspective*/) {} void IPerspectiveListener::PerspectiveSavedAs(const SmartPointer& /*page*/, const IPerspectiveDescriptor::Pointer& /*oldPerspective*/, const IPerspectiveDescriptor::Pointer& /*newPerspective*/) -{}; +{} void IPerspectiveListener::PerspectivePreDeactivate(const SmartPointer& /*page*/, const IPerspectiveDescriptor::Pointer& /*perspective*/) {} } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveRegistry.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveRegistry.h index ad1f0adb69..7dbab3380c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveRegistry.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIPerspectiveRegistry.h @@ -1,138 +1,138 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIPERSPECTIVEREGISTRY_H_ #define BERRYIPERSPECTIVEREGISTRY_H_ #include "berryIPerspectiveDescriptor.h" #include namespace berry { /** * \ingroup org_blueberry_ui * * The workbench's global registry of perspectives. *

* This registry contains a descriptor for each perspectives in the workbench. * It is initially populated with stock perspectives from the workbench's * perspective extension point ("org.blueberry.ui.perspectives") and * with custom perspectives defined by the user. *

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

* @see IWorkbench#getPerspectiveRegistry * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI_QT IPerspectiveRegistry { virtual ~IPerspectiveRegistry(); /** * Create a new perspective. * * @param label * the name of the new descriptor * @param originalDescriptor * the descriptor on which to base the new descriptor * @return a new perspective descriptor or null if the * creation failed. */ - virtual IPerspectiveDescriptor::Pointer CreatePerspective(const QString& label, - IPerspectiveDescriptor::Pointer originalDescriptor) = 0; + //virtual IPerspectiveDescriptor::Pointer CreatePerspective(const QString& label, + // IPerspectiveDescriptor::Pointer originalDescriptor) = 0; /** * Clones an existing perspective. * * @param id the id for the cloned perspective, which must not already be used by * any registered perspective * @param label the label assigned to the cloned perspective * @param desc the perspective to clone * @return the cloned perspective descriptor * @throws IllegalArgumentException if there is already a perspective with the given id */ virtual IPerspectiveDescriptor::Pointer ClonePerspective(const QString& id, const QString& label, IPerspectiveDescriptor::Pointer desc) = 0; /** * Deletes a perspective. Has no effect if the perspective is defined in an * extension. * * @param persp the perspective to delete */ virtual void DeletePerspective(IPerspectiveDescriptor::Pointer persp) = 0; /** * Finds and returns the registered perspective with the given perspective id. * * @param perspectiveId the perspective id * @return the perspective, or null if none * @see IPerspectiveDescriptor#getId */ virtual IPerspectiveDescriptor::Pointer FindPerspectiveWithId(const QString& perspectiveId) = 0; /** * Finds and returns the registered perspective with the given label. * * @param label the label * @return the perspective, or null if none * @see IPerspectiveDescriptor#getLabel */ virtual IPerspectiveDescriptor::Pointer FindPerspectiveWithLabel(const QString& label) = 0; /** * Returns the id of the default perspective for the workbench. This identifies one * perspective extension within the workbench's perspective registry. *

* Returns null if there is no default perspective. *

* * @return the default perspective id, or null */ virtual QString GetDefaultPerspective() = 0; /** * Returns a list of the perspectives known to the workbench. * * @return a list of perspectives */ virtual QList GetPerspectives() = 0; /** * Sets the default perspective for the workbench to the given perspective id. * If non-null, the id must correspond to a perspective extension * within the workbench's perspective registry. *

* A null id indicates no default perspective. *

* * @param id a perspective id, or null */ virtual void SetDefaultPerspective(const QString& id) = 0; /** * Reverts a perspective back to its original definition * as specified in the plug-in manifest. * * @param perspToRevert the perspective to revert */ virtual void RevertPerspective(IPerspectiveDescriptor::Pointer perspToRevert) = 0; }; } #endif /*BERRYIPERSPECTIVEREGISTRY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellProvider.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellProvider.h index a5d90564d5..11e7ae4550 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellProvider.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIShellProvider.h @@ -1,54 +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 { - berryObjectMacro(berry::IShellProvider) + berryObjectMacro(berry::IShellProvider, Object) ~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() const = 0; }; } #endif /* BERRYISHELLPROVIDER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewCategory.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewCategory.h index 6a3d267a31..ade9f15eb6 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 +struct BERRY_UI_QT IViewCategory : public virtual Object { 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 3579329f94..82c62c5a59 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewDescriptor.h @@ -1,105 +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 BERRYIVIEWDESCRIPTOR_H_ #define BERRYIVIEWDESCRIPTOR_H_ #include #include "berryIWorkbenchPartDescriptor.h" #include "berryIViewPart.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 { 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; + /** + * Returns a list of ids belonging to keyword reference extensions. + * + * The keywords listed in each referenced id can be used to filter + * this view. + * + * @return A list of ids for keyword reference extensions. + */ virtual QStringList 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 QStringList 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 QIcon 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/berryIViewPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewPart.h index c1d428b5f8..d52962caed 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIViewPart.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 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 { - berryObjectMacro(berry::IViewPart) + berryObjectMacro(berry::IViewPart, IWorkbenchPart) 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.ui.IViewPart") #endif /*BERRYIVIEWPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbench.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbench.h index 0919f8449c..dc59984508 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbench.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbench.h @@ -1,399 +1,427 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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 "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 IElementFactory; +struct IExtensionTracker; 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 { 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; + virtual Display* GetDisplay() const = 0; /** * Adds a workbench listener. * * @param listener * the workbench listener to add * @since 3.2 */ virtual void AddWorkbenchListener(IWorkbenchListener* listener) = 0; /** * Removes a workbench listener. * * @param listener * the workbench listener to remove * @since 3.2 */ 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* listener) = 0; /** * Removes a window listener. * * @param listener * the window listener to remove * @since 2.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() const = 0; + /** + * Return the extension tracker for the workbench. This tracker may be used + * by plug-ins to ensure responsiveness to changes to the plug-in registry. + *

+ * The tracker at this level of the workbench is typically used to track + * elements that persist for the life of the workbench. For example, + * IEditorDescriptor objects fall into this category. + *

+ * + * @return the extension tracker + * @see IWorkbenchWindow#GetExtensionTracker() + * @see IWorkbenchPage#GetExtensionTracker() + */ + virtual IExtensionTracker* GetExtensionTracker() const = 0; + /** * Returns the perspective registry for the workbench. * * @return the workbench perspective registry */ - virtual IPerspectiveRegistry* GetPerspectiveRegistry() = 0; + virtual IPerspectiveRegistry* GetPerspectiveRegistry() const = 0; /** * Returns the view registry for the workbench. * * @return the workbench view registry * @since 3.1 */ - virtual IViewRegistry* GetViewRegistry() = 0; + virtual IViewRegistry* GetViewRegistry() const = 0; /** * Returns the editor registry for the workbench. * * @return the workbench editor registry */ - virtual IEditorRegistry* GetEditorRegistry() = 0; + virtual IEditorRegistry* GetEditorRegistry() const = 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; + virtual std::size_t GetWorkbenchWindowCount() const = 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; + virtual QList GetWorkbenchWindows() const = 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; + /** + * Returns the element factory with the given id. The calles takes + * ownership of the returned pointer. + * + * @param factoryId + * the id of the element factory + * @return the element factory, or null if none + * @see IElementFactory + */ + virtual IElementFactory* GetElementFactory(const QString& factoryId) const = 0; + /** * Return the intro manager for this workbench. * * @return the intro manager for this workbench. Guaranteed not to be * null. */ - virtual IIntroManager* GetIntroManager() = 0; + virtual IIntroManager* GetIntroManager() const = 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; + virtual bool IsClosing() const = 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/berryIWorkbenchCommandConstants.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchCommandConstants.cpp index 806e5c6f20..a36411deca 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchCommandConstants.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchCommandConstants.cpp @@ -1,31 +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. ===================================================================*/ #include "berryIWorkbenchCommandConstants.h" namespace berry { -QString IWorkbenchCommandConstants::VIEWS_SHOW_VIEW = "org.blueberry.ui.views.showView"; -QString IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_PARM_ID = "org.blueberry.ui.views.showView.viewId"; -QString IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_SECONDARY_ID = "org.blueberry.ui.views.showView.secondaryId"; -QString IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_PARM_FASTVIEW = "org.blueberry.ui.views.showView.makeFast"; - -QString IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE = "org.blueberry.ui.perspectives.showPerspective"; -QString IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_ID = "org.blueberry.ui.perspectives.showPerspective.perspectiveId"; -QString IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_NEWWINDOW = "org.blueberry.ui.perspectives.showPerspective.newWindow"; +const QString IWorkbenchCommandConstants::FILE_NEW = "org.blueberry.ui.newWizard"; +const QString IWorkbenchCommandConstants::FILE_OPEN = "org.blueberry.ui.file.openLocal"; +const QString IWorkbenchCommandConstants::FILE_SAVE = "org.blueberry.ui.file.save"; +const QString IWorkbenchCommandConstants::FILE_EXIT = "org.blueberry.ui.file.exit"; + +const QString IWorkbenchCommandConstants::EDIT_UNDO = "org.blueberry.ui.edit.undo"; +const QString IWorkbenchCommandConstants::EDIT_REDO = "org.blueberry.ui.edit.redo"; +const QString IWorkbenchCommandConstants::EDIT_CUT = "org.blueberry.ui.edit.cut"; +const QString IWorkbenchCommandConstants::EDIT_COPY = "org.blueberry.ui.edit.copy"; +const QString IWorkbenchCommandConstants::EDIT_PASTE = "org.blueberry.ui.edit.paste"; +const QString IWorkbenchCommandConstants::EDIT_DELETE = "org.blueberry.ui.edit.delete"; + +const QString IWorkbenchCommandConstants::WINDOW_NEW_WINDOW = "org.blueberry.ui.window.newWindow"; +const QString IWorkbenchCommandConstants::WINDOW_NEW_EDITOR = "org.blueberry.ui.window.newEditor"; +const QString IWorkbenchCommandConstants::WINDOW_SHOW_VIEW_MENU = "org.blueberry.ui.window.showViewMenu"; +const QString IWorkbenchCommandConstants::WINDOW_ACTIVATE_EDITOR = "org.blueberry.ui.window.activateEditor"; +const QString IWorkbenchCommandConstants::WINDOW_MAXIMIZE_ACTIVE_VIEW_OR_EDITOR = "org.blueberry.ui.window.maximizePart"; +const QString IWorkbenchCommandConstants::WINDOW_MINIMIZE_ACTIVE_VIEW_OR_EDITOR = "org.blueberry.ui.window.minimizePart"; +const QString IWorkbenchCommandConstants::WINDOW_NEXT_EDITOR = "org.blueberry.ui.window.nextEditor"; +const QString IWorkbenchCommandConstants::WINDOW_PREVIOUS_EDITOR = "org.blueberry.ui.window.previousEditor"; +const QString IWorkbenchCommandConstants::WINDOW_NEXT_VIEW = "org.blueberry.ui.window.nextView"; +const QString IWorkbenchCommandConstants::WINDOW_PREVIOUS_VIEW = "org.blueberry.ui.window.previousView"; +const QString IWorkbenchCommandConstants::WINDOW_NEXT_PERSPECTIVE = "org.blueberry.ui.window.nextPerspective"; +const QString IWorkbenchCommandConstants::WINDOW_PREVIOUS_PERSPECTIVE = "org.blueberry.ui.window.previousPerspective"; +const QString IWorkbenchCommandConstants::WINDOW_CLOSE_ALL_PERSPECTIVES = "org.blueberry.ui.window.closeAllPerspectives"; +const QString IWorkbenchCommandConstants::WINDOW_CLOSE_PERSPECTIVE = "org.blueberry.ui.window.closePerspective"; +const QString IWorkbenchCommandConstants::WINDOW_CLOSE_PERSPECTIVE_PARM_ID = "org.blueberry.ui.window.closePerspective.perspectiveId"; +const QString IWorkbenchCommandConstants::WINDOW_CLOSE_PART = "org.blueberry.ui.file.closePart"; +const QString IWorkbenchCommandConstants::WINDOW_CUSTOMIZE_PERSPECTIVE = "org.blueberry.ui.window.customizePerspective"; +const QString IWorkbenchCommandConstants::WINDOW_PIN_EDITOR = "org.blueberry.ui.window.pinEditor"; +const QString IWorkbenchCommandConstants::WINDOW_PREFERENCES = "org.blueberry.ui.window.preferences"; +const QString IWorkbenchCommandConstants::WINDOW_PREFERENCES_PARM_PAGEID = "preferencePageId"; +const QString IWorkbenchCommandConstants::WINDOW_RESET_PERSPECTIVE = "org.blueberry.ui.window.resetPerspective"; +const QString IWorkbenchCommandConstants::WINDOW_SAVE_PERSPECTIVE_AS = "org.blueberry.ui.window.savePerspective"; +const QString IWorkbenchCommandConstants::WINDOW_SHOW_KEY_ASSIST = "org.blueberry.ui.window.showKeyAssist"; + +const QString IWorkbenchCommandConstants::HELP_HELP_CONTENTS = "org.blueberry.ui.help.helpContents"; +const QString IWorkbenchCommandConstants::HELP_HELP_SEARCH = "org.blueberry.ui.help.helpSearch"; +const QString IWorkbenchCommandConstants::HELP_DYNAMIC_HELP = "org.blueberry.ui.help.dynamicHelp"; +const QString IWorkbenchCommandConstants::HELP_WELCOME = "org.blueberry.ui.help.intro"; +const QString IWorkbenchCommandConstants::HELP_ABOUT = "org.blueberry.ui.help.aboutAction"; + +const QString IWorkbenchCommandConstants::VIEWS_SHOW_VIEW = "org.blueberry.ui.views.showView"; +const QString IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_PARM_ID = "org.blueberry.ui.views.showView.viewId"; +const QString IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_SECONDARY_ID = "org.blueberry.ui.views.showView.secondaryId"; +const QString IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_PARM_FASTVIEW = "org.blueberry.ui.views.showView.makeFast"; + +const QString IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE = "org.blueberry.ui.perspectives.showPerspective"; +const QString IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_ID = "org.blueberry.ui.perspectives.showPerspective.perspectiveId"; +const QString IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_NEWWINDOW = "org.blueberry.ui.perspectives.showPerspective.newWindow"; } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchCommandConstants.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchCommandConstants.h index ea5c380688..9abbdfc443 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchCommandConstants.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchCommandConstants.h @@ -1,88 +1,328 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYIWORKBENCHCOMMANDCONSTANTS_H #define BERRYIWORKBENCHCOMMANDCONSTANTS_H +#include + #include namespace berry { /** * Constants for all commands defined by the BlueBerry workbench. * * @noextend This interface is not intended to be extended by clients. * @noimplement This interface is not intended to be implemented by clients. */ -struct IWorkbenchCommandConstants { +struct BERRY_UI_QT IWorkbenchCommandConstants { + + // File Category + + /** + * Id for command "New" in category "File" + * (value is "org.blueberry.ui.newWizard"). + */ + static const QString FILE_NEW; // = "org.blueberry.ui.newWizard"; + + /** + * Id for command "Open File" in category "File" + * (value is "org.blueberry.ui.file.openLocal"). + */ + static const QString FILE_OPEN; // = "org.blueberry.ui.file.openLocal"; + + /** + * Id for command "Save" in category "File" + * (value is "org.blueberry.ui.file.save"). + */ + static const QString FILE_SAVE; // = "org.blueberry.ui.file.save"; + + /** + * Id for command "Exit" in category "File" + * (value is "org.blueberry.ui.file.exit"). + */ + static const QString FILE_EXIT; // = "org.blueberry.ui.file.exit"; + + // Edit Category: + + /** + * Id for command "Undo" in category "Edit" + * (value is "org.blueberry.ui.edit.undo"). + */ + static const QString EDIT_UNDO; // = "org.blueberry.ui.edit.undo"; + + /** + * Id for command "Redo" in category "Edit" + * (value is "org.blueberry.ui.edit.redo"). + */ + static const QString EDIT_REDO; // = "org.blueberry.ui.edit.redo"; + + /** + * Id for command "Cut" in category "Edit" + * (value is "org.blueberry.ui.edit.cut"). + */ + static const QString EDIT_CUT; // = "org.blueberry.ui.edit.cut"; + + /** + * Id for command "Copy" in category "Edit" + * (value is "org.blueberry.ui.edit.copy"). + */ + static const QString EDIT_COPY; // = "org.blueberry.ui.edit.copy"; + + /** + * Id for command "Paste" in category "Edit" + * (value is "org.blueberry.ui.edit.paste"). + */ + static const QString EDIT_PASTE; // = "org.blueberry.ui.edit.paste"; + + /** + * Id for command "Delete" in category "Edit" + * (value is "org.blueberry.ui.edit.delete"). + */ + static const QString EDIT_DELETE; // = "org.blueberry.ui.edit.delete"; + + // Window Category: + + /** + * Id for command "New Window" in category "Window" + * (value is "org.eclipse.ui.window.newWindow"). + */ + static const QString WINDOW_NEW_WINDOW; // = "org.blueberry.ui.window.newWindow"; + + /** + * Id for command "New Editor" in category "Window" + * (value is "org.eclipse.ui.window.newEditor"). + */ + static const QString WINDOW_NEW_EDITOR; // = "org.blueberry.ui.window.newEditor"; + + /** + * Id for command "Show View Menu" in category "Window" + * (value is "org.eclipse.ui.window.showViewMenu"). + */ + static const QString WINDOW_SHOW_VIEW_MENU; // = "org.blueberry.ui.window.showViewMenu"; + + /** + * Id for command "Activate Editor" in category "Window" + * (value is "org.eclipse.ui.window.activateEditor"). + */ + static const QString WINDOW_ACTIVATE_EDITOR; // = "org.blueberry.ui.window.activateEditor"; + + /** + * Id for command "Maximize Active View or Editor" in category "Window" + * (value is "org.eclipse.ui.window.maximizePart"). + */ + static const QString WINDOW_MAXIMIZE_ACTIVE_VIEW_OR_EDITOR; // = "org.blueberry.ui.window.maximizePart"; + + /** + * Id for command "Minimize Active View or Editor" in category "Window" + * (value is "org.eclipse.ui.window.minimizePart"). + */ + static const QString WINDOW_MINIMIZE_ACTIVE_VIEW_OR_EDITOR; // = "org.blueberry.ui.window.minimizePart"; + + /** + * Id for command "Next Editor" in category "Window" + * (value is "org.eclipse.ui.window.nextEditor"). + */ + static const QString WINDOW_NEXT_EDITOR; // = "org.blueberry.ui.window.nextEditor"; + + /** + * Id for command "Previous Editor" in category "Window" + * (value is "org.eclipse.ui.window.previousEditor"). + */ + static const QString WINDOW_PREVIOUS_EDITOR; // = "org.blueberry.ui.window.previousEditor"; + + /** + * Id for command "Next View" in category "Window" + * (value is "org.eclipse.ui.window.nextView"). + */ + static const QString WINDOW_NEXT_VIEW; // = "org.blueberry.ui.window.nextView"; + + /** + * Id for command "Previous View" in category "Window" + * (value is "org.eclipse.ui.window.previousView"). + */ + static const QString WINDOW_PREVIOUS_VIEW; // = "org.blueberry.ui.window.previousView"; + + /** + * Id for command "Next Perspective" in category "Window" + * (value is "org.eclipse.ui.window.nextPerspective"). + */ + static const QString WINDOW_NEXT_PERSPECTIVE; // = "org.blueberry.ui.window.nextPerspective"; + + /** + * Id for command "Previous Perspective" in category "Window" + * (value is "org.eclipse.ui.window.previousPerspective"). + */ + static const QString WINDOW_PREVIOUS_PERSPECTIVE; // = "org.blueberry.ui.window.previousPerspective"; + + /** + * Id for command "Close All Perspectives" in category "Window" + * (value is "org.eclipse.ui.window.closeAllPerspectives"). + */ + static const QString WINDOW_CLOSE_ALL_PERSPECTIVES; // = "org.blueberry.ui.window.closeAllPerspectives"; + + /** + * Id for command "Close Perspective" in category "Window" + * (value is "org.eclipse.ui.window.closePerspective"). + */ + static const QString WINDOW_CLOSE_PERSPECTIVE; // = "org.blueberry.ui.window.closePerspective"; + + /** + * Id for parameter "Perspective Id" in command "Close Perspective" in + * category "Window" (value is + * "org.eclipse.ui.window.closePerspective.perspectiveId"). + * Optional. + */ + static const QString WINDOW_CLOSE_PERSPECTIVE_PARM_ID; // = "org.blueberry.ui.window.closePerspective.perspectiveId"; + + /** + * Id for command "Close Part" in category "Window" (value is + * "org.eclipse.ui.file.closePart"). + */ + static const QString WINDOW_CLOSE_PART; // = "org.blueberry.ui.file.closePart"; + + /** + * Id for command "Customize Perspective" in category "Window" + * (value is "org.eclipse.ui.window.customizePerspective"). + */ + static const QString WINDOW_CUSTOMIZE_PERSPECTIVE; // = "org.blueberry.ui.window.customizePerspective"; + + /** + * Id for command "Pin Editor" in category "Window" + * (value is "org.eclipse.ui.window.pinEditor"). + */ + static const QString WINDOW_PIN_EDITOR; // = "org.blueberry.ui.window.pinEditor"; + + /** + * Id for command "Preferences" in category "Window" + * (value is "org.eclipse.ui.window.preferences"). + */ + static const QString WINDOW_PREFERENCES; // = "org.blueberry.ui.window.preferences"; + + /** + * Id for parameter "Preference Page Id" in command "Preferences" in + * category "Window" (value is "preferencePageId"). Optional. + */ + static const QString WINDOW_PREFERENCES_PARM_PAGEID; // = "preferencePageId"; + + /** + * Id for command "Reset Perspective" in category "Window" (value is + * "org.eclipse.ui.window.resetPerspective"). + */ + static const QString WINDOW_RESET_PERSPECTIVE; // = "org.blueberry.ui.window.resetPerspective"; + + /** + * Id for command "Save Perspective As" in category "Window" + * (value is "org.eclipse.ui.window.savePerspective"). + */ + static const QString WINDOW_SAVE_PERSPECTIVE_AS; // = "org.blueberry.ui.window.savePerspective"; + + /** + * Id for command "Show Key Assist" in category "Window" + * (value is "org.eclipse.ui.window.showKeyAssist"). + */ + static const QString WINDOW_SHOW_KEY_ASSIST; // = "org.blueberry.ui.window.showKeyAssist"; + + // Help Category: + + /** + * Id for command "Help Contents" in category "Help" + * (value is "org.blueberry.ui.help.helpContents"). + */ + static const QString HELP_HELP_CONTENTS; // = "org.blueberry.ui.help.helpContents"; + + /** + * Id for command "Help Search" in category "Help" + * (value is "org.blueberry.ui.help.helpSearch"). + */ + static const QString HELP_HELP_SEARCH; // = "org.blueberry.ui.help.helpSearch"; + + /** + * Id for command "Dynamic Help" in category "Help" + * (value is "org.blueberry.ui.help.dynamicHelp"). + */ + static const QString HELP_DYNAMIC_HELP; // = "org.blueberry.ui.help.dynamicHelp"; + + /** + * Id for command "Welcome" in category "Help" + * (value is "org.blueberry.ui.help.quickStartAction"). + */ + static const QString HELP_WELCOME; // = "org.blueberry.ui.help.intro"; + + /** + * Id for command "About" in category "Help" + * (value is "org.blueberry.ui.help.aboutAction"). + */ + static const QString HELP_ABOUT; // = "org.blueberry.ui.help.aboutAction"; // Views Category: /** * Id for command "Show View" in category "Views" * (value is "org.blueberry.ui.views.showView"). */ - static QString VIEWS_SHOW_VIEW; // = "org.blueberry.ui.views.showView"; + static const QString VIEWS_SHOW_VIEW; // = "org.blueberry.ui.views.showView"; /** * Id for parameter "View Id" in command "Show View" in category "Views" * (value is "org.blueberry.ui.views.showView.viewId"). */ - static QString VIEWS_SHOW_VIEW_PARM_ID; // = "org.blueberry.ui.views.showView.viewId"; + static const QString VIEWS_SHOW_VIEW_PARM_ID; // = "org.blueberry.ui.views.showView.viewId"; /** * Id for parameter "Secondary Id" in command "Show View" in category "Views" * (value is "org.blueberry.ui.views.showView.secondaryId"). */ - static QString VIEWS_SHOW_VIEW_SECONDARY_ID; // = "org.blueberry.ui.views.showView.secondaryId"; + static const QString VIEWS_SHOW_VIEW_SECONDARY_ID; // = "org.blueberry.ui.views.showView.secondaryId"; /** * Id for parameter "As Fastview" in command "Show View" in category "Views" * (value is "org.blueberry.ui.views.showView.makeFast"). * Optional. */ - static QString VIEWS_SHOW_VIEW_PARM_FASTVIEW; // = "org.blueberry.ui.views.showView.makeFast"; + static const QString VIEWS_SHOW_VIEW_PARM_FASTVIEW; // = "org.blueberry.ui.views.showView.makeFast"; // Perspectives Category: /** * Id for command "Show Perspective" in category "Perspectives" * (value is "org.blueberry.ui.perspectives.showPerspective"). */ - static QString PERSPECTIVES_SHOW_PERSPECTIVE; // = "org.blueberry.ui.perspectives.showPerspective"; + static const QString PERSPECTIVES_SHOW_PERSPECTIVE; // = "org.blueberry.ui.perspectives.showPerspective"; /** * Id for parameter "Perspective Id" in command "Show Perspective" in * category "Perspectives" (value is * "org.blueberry.ui.perspectives.showPerspective.perspectiveId" * ). */ - static QString PERSPECTIVES_SHOW_PERSPECTIVE_PARM_ID; // = "org.blueberry.ui.perspectives.showPerspective.perspectiveId"; + static const QString PERSPECTIVES_SHOW_PERSPECTIVE_PARM_ID; // = "org.blueberry.ui.perspectives.showPerspective.perspectiveId"; /** * Id for parameter "In New Window" in command "Show Perspective" in * category "Perspectives" (value is * "org.blueberry.ui.perspectives.showPerspective.newWindow"). * Optional. */ - static QString PERSPECTIVES_SHOW_PERSPECTIVE_PARM_NEWWINDOW; // = "org.blueberry.ui.perspectives.showPerspective.newWindow"; + static const QString PERSPECTIVES_SHOW_PERSPECTIVE_PARM_NEWWINDOW; // = "org.blueberry.ui.perspectives.showPerspective.newWindow"; }; } #endif // BERRYIWORKBENCHCOMMANDCONSTANTS_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPage.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPage.h index 21f7db8adf..3467c1316a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPage.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPage.h @@ -1,854 +1,871 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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 { +struct IExtensionTracker; + /** * 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 { 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; + virtual IWorkbenchWindow::Pointer GetWorkbenchWindow() const = 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 QString& perspectiveId, const QString& viewId) = 0; + //virtual bool HasView(const QString& perspectiveId, const QString& 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; + //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; + //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; + /** + * Return the extension tracker for the workbench. This tracker may be used + * by plug-ins to ensure responsiveness to changes to the plug-in registry. + *

+ * The tracker at this level of the workbench is typically used to track + * elements that only exist over the lifespan of a page. For example, + * ViewPart objects fall into this category. + *

+ * + * @return the extension tracker + * @see IWorkbench#GetExtensionTracker() + * @see IWorkbenchWindow#GetExtensionTracker() + */ + virtual IExtensionTracker* GetExtensionTracker() const = 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 c06b63bfb3..3f05176358 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 { - berryObjectMacro(berry::IWorkbenchPart) + berryObjectMacro(berry::IWorkbenchPart, Object) 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(QWidget* 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 QIcon 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/berryIWorkbenchPartSite.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchPartSite.h index 59b44ad6a4..6d55435d3c 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 { - berryObjectMacro(berry::IWorkbenchPartSite) + berryObjectMacro(berry::IWorkbenchPartSite, IWorkbenchSite) ~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() 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() 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() 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 82eb8e7d80..13fe20fe03 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 { - berryObjectMacro(berry::IWorkbenchSite) + berryObjectMacro(berry::IWorkbenchSite, IServiceLocator) 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 5c21b6ff59..238d8060e5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryIWorkbenchWindow.h @@ -1,213 +1,222 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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 { - berryObjectMacro(berry::IWorkbenchWindow) + berryObjectMacro(berry::IWorkbenchWindow, IPageService, IServiceLocator, Object) /** * 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) const = 0; + /** + * Returns a list of the pages in this workbench window. + *

+ * Note that each window has its own pages; pages are never shared between + * different windows. + *

+ * + * @return a list of pages + */ + virtual QList > GetPages() const = 0; /** * Returns the currently active page for this workbench window. * * @return the active page, or null if none */ 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; + virtual ISelectionService* GetSelectionService() const = 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() const = 0; /** * Returns the workbench for this window. * * @return the workbench */ - virtual IWorkbench* GetWorkbench() = 0; + virtual IWorkbench* GetWorkbench() const = 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(const QStringList& v) = 0; - virtual QStringList GetPerspectiveExcludeList() const = 0; + //virtual void SetPerspectiveExcludeList(const QStringList& v) = 0; + //virtual QStringList GetPerspectiveExcludeList() const = 0; - virtual void SetViewExcludeList(const QStringList& v) = 0; - virtual QStringList GetViewExcludeList() const = 0; + //virtual void SetViewExcludeList(const QStringList& v) = 0; + //virtual QStringList GetViewExcludeList() const = 0; virtual ~IWorkbenchWindow(); }; } #endif /*BERRYIWORKBENCHWINDOW_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPlatformUI.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPlatformUI.cpp index 81986ae14c..a8b5ab09b4 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPlatformUI.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPlatformUI.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 "berryPlatformUI.h" #include "berryPlatform.h" #include "berryIConfigurationElement.h" #include "internal/berryWorkbench.h" #include "berryUIException.h" #include namespace berry { -const QString PlatformUI::PLUGIN_ID() { static QString str = "org.blueberry.ui"; return str; } +QString PlatformUI::PLUGIN_ID() { static QString str = "org.blueberry.ui"; return str; } const QString PlatformUI::XP_WORKBENCH = PlatformUI::PLUGIN_ID() + ".workbench"; const QString PlatformUI::XP_VIEWS = PlatformUI::PLUGIN_ID() + ".views"; const int PlatformUI::RETURN_OK = 0; const int PlatformUI::RETURN_RESTART = 1; const int PlatformUI::RETURN_UNSTARTABLE = 2; const int PlatformUI::RETURN_EMERGENCY_CLOSE = 3; int PlatformUI::CreateAndRunWorkbench(Display* display, WorkbenchAdvisor* advisor) { return Workbench::CreateAndRunWorkbench(display, advisor); } Display* PlatformUI::CreateDisplay() { return Workbench::CreateDisplay(); } IWorkbench* PlatformUI::GetWorkbench() { if (Workbench::GetInstance() == 0) { // app forgot to call createAndRunWorkbench beforehand throw Poco::IllegalStateException("Workbench has not been created yet."); } return Workbench::GetInstance(); } bool PlatformUI::IsWorkbenchRunning() { return Workbench::GetInstance() != 0 && Workbench::GetInstance()->IsRunning(); } TestableObject::Pointer PlatformUI::GetTestableObject() { return Workbench::GetWorkbenchTestable(); } PlatformUI::PlatformUI() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPlatformUI.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPlatformUI.h index 4d3e1607d9..ab10fdb033 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPlatformUI.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryPlatformUI.h @@ -1,174 +1,174 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYPLATFORMUI_H_ #define BERRYPLATFORMUI_H_ #include #include "berryDisplay.h" #include "application/berryWorkbenchAdvisor.h" #include "testing/berryTestableObject.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * The central class for access to the BlueBerry Platform User Interface. * This class cannot be instantiated; all functionality is provided by * static methods. * * Features provided: *
    *
  • creation of the workbench.
  • *
  • access to the workbench.
  • *
*

* * @see IWorkbench */ class BERRY_UI_QT PlatformUI { public: - static const QString PLUGIN_ID(); + static QString PLUGIN_ID(); static const QString XP_WORKBENCH; static const QString XP_VIEWS; /** * Return code (value 0) indicating that the workbench terminated normally. * * @see #CreateAndRunWorkbench * @since 3.0 */ static const int RETURN_OK; /** * Return code (value 1) indicating that the workbench was terminated with * a call to IWorkbench.restart. * * @see #CreateAndRunWorkbench * @see IWorkbench#Restart * @since 3.0 */ static const int RETURN_RESTART; /** * Return code (value 2) indicating that the workbench failed to start. * * @see #CreateAndRunWorkbench * @see IWorkbench#Restart * @since 3.0 */ static const int RETURN_UNSTARTABLE; /** * Return code (value 3) indicating that the workbench was terminated with * a call to IWorkbenchConfigurer#emergencyClose. * * @see #CreateAndRunWorkbench * @since 3.0 */ static const int RETURN_EMERGENCY_CLOSE; /** * Creates the workbench and associates it with the given display and workbench * advisor, and runs the workbench UI. This entails processing and dispatching * events until the workbench is closed or restarted. *

* This method is intended to be called by the main class (the "application"). * Fails if the workbench UI has already been created. *

*

* Use {@link #createDisplay createDisplay} to create the display to pass in. *

*

* Note that this method is intended to be called by the application * (org.blueberry.core.boot.IPlatformRunnable). It must be * called exactly once, and early on before anyone else asks * getWorkbench() for the workbench. *

* * @param display the display to be used for all UI interactions with the workbench * @param advisor the application-specific advisor that configures and * specializes the workbench * @return return code {@link #RETURN_OK RETURN_OK} for normal exit; * {@link #RETURN_RESTART RETURN_RESTART} if the workbench was terminated * with a call to {@link IWorkbench#restart IWorkbench.restart}; * {@link #RETURN_UNSTARTABLE RETURN_UNSTARTABLE} if the workbench could * not be started; * {@link #RETURN_EMERGENCY_CLOSE RETURN_EMERGENCY_CLOSE} if the UI quit * because of an emergency; other values reserved for future use */ static int CreateAndRunWorkbench(Display* display, WorkbenchAdvisor* advisor); /** * Creates the Display to be used by the workbench. * It is the caller's responsibility to dispose the resulting Display, * not the workbench's. * * @return the display */ static Display* CreateDisplay(); /** * Returns the workbench. Fails if the workbench has not been created yet. * * @return the workbench. A raw pointer is returned because you normally * should not hold a smart pointer to it (and possibly create reference * cycles) */ static IWorkbench* GetWorkbench(); /** * Returns whether {@link #createAndRunWorkbench createAndRunWorkbench} has * been called to create the workbench, and the workbench has yet to * terminate. *

* Note that this method may return true while the workbench * is still being initialized, so it may not be safe to call workbench API * methods even if this method returns true. See bug 49316 for details. *

* * @return true if the workbench has been created and is * still running, and false if the workbench has not * yet been created or has completed * @since 3.0 */ static bool IsWorkbenchRunning(); /** * Returns the testable object facade, for use by the test harness. *

* IMPORTANT: This method is only for use by the test harness. * Applications and regular plug-ins should not call this method. *

* * @return the testable object facade * @since 3.0 */ static TestableObject::Pointer GetTestableObject(); private: PlatformUI(); }; } #endif /*BERRYPLATFORMUI_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtEditorPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtEditorPart.h index 2938b63b49..f502b32f41 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtEditorPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQtEditorPart.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 BERRYQTEDITORPART_H_ #define BERRYQTEDITORPART_H_ #include #include #include namespace berry { class BERRY_UI_QT QtEditorPart : public EditorPart { public: - berryObjectMacro(QtEditorPart) + berryObjectMacro(QtEditorPart, EditorPart) void CreatePartControl(QWidget* parent); protected: virtual void CreateQtPartControl(QWidget* parent) = 0; }; } #endif /*BERRYQTEDITORPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.cpp index ac907723d3..88a2d5f4b1 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); // } } -Object* Saveable::GetAdapter(const QString& /*adapter*/) +Object* Saveable::GetAdapter(const QString& /*adapter*/) const { 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 235f7411f4..8745f1f3bc 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berrySaveable.h @@ -1,286 +1,286 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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 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 QIcon 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 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 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 Object* GetAdapter(const QString& adapter); + virtual Object* GetAdapter(const QString& adapter) const; }; } #endif /* BERRYSAVEABLE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h index f5cdedcf91..063637cdf7 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryShell.h @@ -1,328 +1,328 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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" 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. *

*/ class BERRY_UI_QT Shell : public virtual Object { public: berryObjectMacro(Shell) Shell(); Object::Pointer GetData(const QString& id = "") const; 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 QRect& bounds) = 0; virtual QRect GetBounds() const = 0; virtual void SetLocation(int x, int y) = 0; virtual QPoint 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() const = 0; virtual void SetVisible(bool visible) = 0; - virtual QWidget* GetControl() = 0; + virtual QWidget* GetControl() const = 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() const = 0; /** * Returns true if the receiver is currently * minimized, and false otherwise. *

* * @return the minimized state * * @see #SetMinimized */ virtual bool GetMinimized() const = 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* 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* 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/berryViewPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryViewPart.h index 64c55c2cfa..8a2ed065ca 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryViewPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryViewPart.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 BERRYVIEWPART_H_ #define BERRYVIEWPART_H_ #include "berryIViewPart.h" #include "berryIViewSite.h" #include "berryWorkbenchPart.h" #include "berryIMemento.h" namespace berry { /** * \ingroup org_blueberry_ui_qt * * Abstract base implementation of all workbench views. *

* This class should be subclassed by clients wishing to define new views. * The name of the subclass should be given as the "class" * attribute in a view extension contributed to the workbench's * view extension point (named "org.blueberry.ui.views"). * For example, the plug-in's XML markup might contain: *

  * <extension point="org.blueberry.ui.views">
  *      <view id="com.example.myplugin.view"
  *         name="My View"
  *         class="com.example.myplugin.MyView"
  *         icon="images/eview.gif"
  *      />
  * </extension>
  * 
* where com.example.myplugin.MyView is the name of the * ViewPart subclass. *

*

* Subclasses must implement the following methods: *

    *
  • createPartControl - to create the view's controls
  • *
  • setFocus - to accept focus
  • *
*

*

* Subclasses may extend or reimplement the following methods as required: *

    *
  • setInitializationData - extend to provide additional * initialization when view extension is instantiated
  • *
  • init(IWorkbenchPartSite) - extend to provide additional * initialization when view is assigned its site
  • *
  • dispose - extend to provide additional cleanup
  • *
  • getAdapter - reimplement to make their view adaptable
  • *
*

*/ class BERRY_UI_QT ViewPart : public WorkbenchPart, public IViewPart { Q_OBJECT Q_INTERFACES(berry::IViewPart) protected: ViewPart(); /** * Checks that the given site is valid for this type of part. * The site for a view must be an IViewSite. * * @param site the site to check * @since 3.1 */ void CheckSite(IWorkbenchPartSite::Pointer site); public: - berryObjectMacro(ViewPart) + berryObjectMacro(ViewPart, WorkbenchPart, IViewPart) void Init(IViewSite::Pointer site, IMemento::Pointer memento = IMemento::Pointer(0)); void SaveState(IMemento::Pointer memento); /* * Method declared on IViewPart. */ IViewSite::Pointer GetViewSite(); }; } // namespace berry #endif /*BERRYVIEWPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.cpp index 3a74a5a213..b9d9b79f23 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.cpp @@ -1,579 +1,579 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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(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() 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--) + int size = toSearch.size(); + for (int 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 // QRect bounds = shell.getBounds(); // QRect constrained = getConstrainedShellBounds(bounds); // if (!bounds.equals(constrained)) // { // shell.setBounds(constrained); // } //} QWidget* 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; } QWidget* Window::GetContents() { return contents; } QPoint Window::GetInitialLocation(const QPoint& initialSize) { QWidget* parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(shell->GetControl()); QPoint centerPoint(0,0); QRect parentBounds(0,0,0,0); if (parent != 0) { parentBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(parent); centerPoint.setX(parentBounds.x() + parentBounds.width()/2); centerPoint.setY(parentBounds.y() - parentBounds.height()/2); } else { parentBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY) ->GetScreenSize(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetPrimaryScreenNumber()); centerPoint.setX(parentBounds.width()/2); centerPoint.setY(parentBounds.height()/2); } return QPoint(centerPoint.x() - (initialSize.x() / 2), std::max(parentBounds.y(), std::min(centerPoint.y() - (initialSize.y() * 2 / 3), parentBounds.y() + parentBounds.height() - initialSize.y()))); } QPoint 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* Window::GetShellListener() { if (windowShellListener.isNull()) windowShellListener.reset(new WindowShellListener(this)); 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; // } QPoint size = this->GetInitialSize(); QPoint location = this->GetInitialLocation(size); shell->SetBounds(this->GetConstrainedShellBounds(QRect(location.x(), location.y(), size.x(), size.y()))); } QRect Window::GetConstrainedShellBounds(const QRect& preferredSize) { QRect result(preferredSize); GuiWidgetsTweaklet* guiTweaklet(Tweaklets::Get(GuiWidgetsTweaklet::KEY)); int screenNum = guiTweaklet->GetClosestScreenNumber(result); QRect bounds(guiTweaklet->GetAvailableScreenSize(screenNum)); if (result.height() > bounds.height()) { result.setHeight(bounds.height()); } if (result.width() > bounds.width()) { result.setWidth(bounds.width()); } result.setX( std::max(bounds.x(), std::min(result.x(), bounds.x() + bounds.width() - result.width()))); result.setY(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(); } QIcon Window::GetDefaultImage() { return (defaultImages.size() < 1) ? QIcon() : defaultImages[0]; } QList Window::GetDefaultImages() { return defaultImages; } int Window::GetReturnCode() { return returnCode; } 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(const QIcon& image) { if (!image.isNull()) 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 (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 13b974c5fe..ecbb2dd75c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWindow.h @@ -1,731 +1,731 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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 "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) + berryObjectMacro(Window, IShellProvider) /** * 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(const ShellEvent::Pointer& event); private: Window* window; }; 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() 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 */ QWidget* 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 * */ QRect GetConstrainedShellBounds(const QRect& 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 QWidget* 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 QWidget* 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 QPoint GetInitialLocation(const QPoint& 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 QPoint 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* 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 QIcon 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() 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(const QIcon& 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/berryWorkbenchActionConstants.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.cpp index 0c29554981..eefa721942 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.cpp @@ -1,24 +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 "berryWorkbenchActionConstants.h" namespace berry { const QString WorkbenchActionConstants::MB_ADDITIONS = "additions"; +const QString WorkbenchActionConstants::M_FILE = "file"; +const QString WorkbenchActionConstants::M_EDIT = "edit"; +const QString WorkbenchActionConstants::M_WINDOW = "window"; +const QString WorkbenchActionConstants::M_HELP = "help"; + +const QString WorkbenchActionConstants::FILE_START = "fileStart"; // Group. +const QString WorkbenchActionConstants::FILE_END = "fileEnd"; // Group. +const QString WorkbenchActionConstants::NEW_EXT = "new.ext"; // Group. +const QString WorkbenchActionConstants::CLOSE_EXT = "close.ext"; // Group. +const QString WorkbenchActionConstants::SAVE_EXT = "save.ext"; // Group. + +const QString WorkbenchActionConstants::MRU = "mru"; + +const QString WorkbenchActionConstants::EDIT_START = "editStart"; // Group. +const QString WorkbenchActionConstants::EDIT_END = "editEnd"; // Group. +const QString WorkbenchActionConstants::UNDO_EXT = "undo.ext"; // Group. +const QString WorkbenchActionConstants::CUT_EXT = "cut.ext"; // Group. +const QString WorkbenchActionConstants::FIND_EXT = "find.ext"; // Group. +const QString WorkbenchActionConstants::ADD_EXT = "add.ext"; // Group. + +const QString WorkbenchActionConstants::HELP_START = "helpStart"; +const QString WorkbenchActionConstants::HELP_END = "helpEnd"; + } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.h index babfd77662..23d7b01fac 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.h @@ -1,39 +1,243 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYWORKBENCHACTIONCONSTANTS_H #define BERRYWORKBENCHACTIONCONSTANTS_H #include #include +#ifdef FILE_END +// defined in winbase.h +#undef FILE_END +#endif + namespace berry { +/** + * Action ids for standard actions, groups in the workbench menu bar, and + * global actions. + *

+ * This interface contains constants only; it is not intended to be implemented + * or extended. + *

+ *

Standard menus

+ *
    + *
  • File menu (M_FILE)
  • + *
  • Edit menu (M_EDIT)
  • + *
  • Window menu (M_WINDOW)
  • + *
  • Help menu (M_HELP)
  • + *
+ *

Standard group for adding top level menus

+ *
    + *
  • Extra top level menu group (MB_ADDITIONS)
  • + *
+ *

Global actions

+ *
    + *
  • Undo (UNDO)
  • + *
  • Redo (REDO)
  • + *
  • Cut (CUT)
  • + *
  • Copy (COPY)
  • + *
  • Paste (PASTE)
  • + *
  • Delete (DELETE)
  • + *
  • Find (FIND)
  • + *
  • Select All (SELECT_ALL)
  • + *
  • Add Bookmark (BOOKMARK)
  • + *
+ *

Standard File menu actions

+ *
    + *
  • Start group (FILE_START)
  • + *
  • End group (FILE_END)
  • + *
  • New action (NEW)
  • + *
  • Extra New-like action group (NEW_EXT)
  • + *
  • Close action (CLOSE)
  • + *
  • Close All action (CLOSE_ALL)
  • + *
  • Extra Close-like action group (CLOSE_EXT)
  • + *
  • Save action (SAVE)
  • + *
  • Save As action (SAVE_AS)
  • + *
  • Save All action (SAVE_ALL)
  • + *
  • Extra Save-like action group (SAVE_EXT)
  • + *
  • Import action (IMPORT)
  • + *
  • Export action (EXPORT)
  • + *
  • Extra Import-like action group (IMPORT_EXT)
  • + *
  • Quit action (QUIT)
  • + *
+ *

Standard Edit menu actions

+ *
    + *
  • Start group (EDIT_START)
  • + *
  • End group (EDIT_END)
  • + *
  • Undo global action (UNDO)
  • + *
  • Redo global action (REDO)
  • + *
  • Extra Undo-like action group (UNDO_EXT)
  • + *
  • Cut global action (CUT)
  • + *
  • Copy global action (COPY)
  • + *
  • Paste global action (PASTE)
  • + *
  • Extra Cut-like action group (CUT_EXT)
  • + *
  • Delete global action (DELETE)
  • + *
  • Find global action (FIND)
  • + *
  • Select All global action (SELECT_ALL)
  • + *
  • Bookmark global action (BOOKMARK)
  • + *
+ *

Standard Perspective menu actions

+ *
    + *
  • Extra Perspective-like action group (VIEW_EXT)
  • + *
+ *

Standard Workbench menu actions

+ *
    + *
  • Start group (WB_START)
  • + *
  • End group (WB_END)
  • + *
  • Extra Build-like action group (BUILD_EXT)
  • + *
  • Build action (BUILD)
  • + *
  • Rebuild All action (REBUILD_ALL)
  • + *
+ *

Standard Window menu actions

+ *
    + *
  • Extra Window-like action group (WINDOW_EXT)
  • + *
+ *

Standard Help menu actions

+ *
    + *
  • Start group (HELP_START)
  • + *
  • End group (HELP_END)
  • + *
  • About action (ABOUT)
  • + *
+ *

Standard pop-up menu groups

+ *
    + *
  • Managing group (GROUP_MANAGING)
  • + *
  • Reorganize group (GROUP_REORGANIZE)
  • + *
  • Add group (GROUP_ADD)
  • + *
  • File group (GROUP_FILE)
  • + *
+ *

+ * To hook a global action handler, a view should use the following code: + * + * IAction copyHandler = ...; + * view.getSite().getActionBars().setGlobalActionHandler( + * IWorkbenchActionConstants.COPY, + * copyHandler); + * + * For editors, this should be done in the IEditorActionBarContributor. + *

+ */ struct BERRY_UI_QT WorkbenchActionConstants { // Standard area for adding top level menus: /** * Name of group for adding new top-level menus (value "additions"). */ static const QString MB_ADDITIONS; + + /** + * Name of standard File menu (value "file"). + */ + static const QString M_FILE; // "file" + + /** + * Name of standard Edit menu (value "edit"). + */ + static const QString M_EDIT; // "edit" + + /** + * Name of standard Window menu (value "window"). + */ + static const QString M_WINDOW; // = "window" + + /** + * Name of standard Help menu (value "help"). + */ + static const QString M_HELP; // "help"; + + /** + * File menu: name of group for start of menu (value "fileStart"). + */ + static const QString FILE_START; // = "fileStart"; // Group. + + /** + * File menu: name of group for end of menu (value "fileEnd"). + */ + static const QString FILE_END; // = "fileEnd"; // Group. + + /** + * File menu: name of group for extra New-like actions (value "new.ext"). + */ + static const QString NEW_EXT; // = "new.ext"; // Group. + + /** + * File menu: name of group for extra Close-like actions (value "close.ext"). + */ + static const QString CLOSE_EXT; // = "close.ext"; // Group. + + /** + * File menu: name of group for extra Save-like actions (value "save.ext"). + */ + static const QString SAVE_EXT; // = "save.ext"; // Group. + + /** + * File menu: name of "Most Recently Used File" group. + * (value "mru"). + */ + static const QString MRU; // = "mru"; + + // Standard edit actions: + /** + * Edit menu: name of group for start of menu (value "editStart"). + */ + static const QString EDIT_START; // = "editStart"; // Group. + + /** + * Edit menu: name of group for end of menu (value "editEnd"). + */ + static const QString EDIT_END; // = "editEnd"; // Group. + + /** + * Edit menu: name of group for extra Undo-like actions (value "undo.ext"). + */ + static const QString UNDO_EXT; // = "undo.ext"; // Group. + + /** + * Edit menu: name of group for extra Cut-like actions (value "cut.ext"). + */ + static const QString CUT_EXT; // = "cut.ext"; // Group. + + /** + * Edit menu: name of group for extra Find-like actions (value "find.ext"). + */ + static const QString FIND_EXT; // = "find.ext"; // Group. + + /** + * Edit menu: name of group for extra Add-like actions (value "add.ext"). + */ + static const QString ADD_EXT; // = "add.ext"; // Group. + + // Standard help actions: + /** + * Help menu: name of group for start of menu + * (value "helpStart"). + */ + static const QString HELP_START; // = "helpStart"; // Group. + + /** + * Help menu: name of group for end of menu + * (value "helpEnd"). + */ + static const QString HELP_END; // = "helpEnd"; // Group. }; } #endif // BERRYWORKBENCHACTIONCONSTANTS_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.h index 9f6bae8aac..299c843d4b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchPart.h @@ -1,256 +1,256 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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_WORKBENCH_PART_H__ #define __BERRY_WORKBENCH_PART_H__ #include "berryIWorkbenchPart.h" #include "berryIWorkbenchPartSite.h" #include #include #include namespace berry { /** * \ingroup org_blueberry_ui_qt * * Abstract base implementation of all workbench parts. *

* This class is not intended to be subclassed by clients outside this * package; clients should instead subclass ViewPart or * EditorPart. *

* * @see org.blueberry.ui.part.ViewPart * @see org.blueberry.ui.part.EditorPart * @noextend This class is not intended to be subclassed by clients. */ class BERRY_UI_QT WorkbenchPart : public QObject, public virtual IWorkbenchPart, public IExecutableExtension { Q_OBJECT Q_INTERFACES(berry::IExecutableExtension); public: - berryObjectMacro(WorkbenchPart) + berryObjectMacro(WorkbenchPart, QObject, IWorkbenchPart, IExecutableExtension) ~WorkbenchPart(); private: QString m_Title; QIcon m_TitleImage; QString m_ToolTip; IConfigurationElement::Pointer m_ConfigElement; IWorkbenchPartSite::Pointer m_PartSite; QString m_PartName; QString m_ContentDescription; QHash partProperties; IPropertyChangeListener::Events partChangeEvents; void InternalSetContentDescription(const QString& description); void InternalSetPartName(const QString& partName); protected: WorkbenchPart(); /** * Returns the configuration element for this part. The configuration element * comes from the plug-in registry entry for the extension defining this part. * * @return the configuration element for this part */ IConfigurationElement::Pointer GetConfigurationElement() const { return m_ConfigElement; } /** * Returns the default title image. * * @return the default image */ // protected Image getDefaultImage() { // return PlatformUI.getWorkbench().getSharedImages().getImage( // ISharedImages.IMG_DEF_VIEW); // } /** * Sets the part site. *

* Subclasses must invoke this method from IEditorPart.init * and IViewPart.init. * * @param site the workbench part site */ void SetSite(IWorkbenchPartSite::Pointer site); /** * Checks that the given site is valid for this type of part. * The default implementation does nothing. * * @param site the site to check */ virtual void CheckSite(IWorkbenchPartSite::Pointer site); /** * Sets or clears the title image of this part. * * @param titleImage the title image, or null to clear */ virtual void SetTitleImage(const QIcon& titleImage); /** * Sets or clears the title tool tip text of this part. Clients should * call this method instead of overriding getTitleToolTip * * @param toolTip the new tool tip text, or null to clear */ virtual void SetTitleToolTip(const QString& toolTip); /** * Sets the name of this part. The name will be shown in the tab area for * the part. Clients should call this method instead of overriding getPartName. * Setting this to the empty string will cause a default part name to be used. * * @param partName the part name, as it should be displayed in tabs. */ virtual void SetPartName(const QString& partName); /** * Sets the content description for this part. The content description is typically * a short string describing the current contents of the part. Setting this to the * empty string will cause a default content description to be used. Clients should * call this method instead of overriding getContentDescription(). For views, the * content description is shown (by default) in a line near the top of the view. For * editors, the content description is shown beside the part name when showing a * list of editors. If the editor is open on a file, this typically contains the path * to the input file, without the filename or trailing slash. * * @param description the content description */ virtual void SetContentDescription(const QString& description); void FirePropertyChanged(const QString& key, const QString& oldValue, const QString& newValue); void FirePropertyChange(int propertyId); public: /* (non-Javadoc) * Method declared on IWorkbenchPart. */ void AddPropertyListener(IPropertyChangeListener* l); void RemovePropertyListener(IPropertyChangeListener* l); void SetPartProperty(const QString& key, const QString& value); /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPart3#getPartProperty(java.lang.String) */ QString GetPartProperty(const QString& key) const; /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPart3#getPartProperties() */ const QHash& GetPartProperties() const; /** * {@inheritDoc} * The WorkbenchPart implementation of this * IExecutableExtension records the configuration element in * and internal state variable (accessible via getConfigElement). * It also loads the title image, if one is specified in the configuration element. * Subclasses may extend. * * Should not be called by clients. It is called by the core plugin when creating * this executable extension. */ void SetInitializationData(const IConfigurationElement::Pointer& cfig, const QString& propertyName, const Object::Pointer& data); /* * Creates the controls for this workbench part. *

* Subclasses must implement this method. For a detailed description of the * requirements see IWorkbenchPart *

* * @param parent the parent control * @see IWorkbenchPart */ virtual void CreatePartControl(QWidget* parent) = 0; /* (non-Javadoc) * Asks this part to take focus within the workbench. *

* Subclasses must implement this method. For a detailed description of the * requirements see IWorkbenchPart *

* * @see IWorkbenchPart */ virtual void SetFocus() = 0; /* * Method declared on IWorkbenchPart. */ IWorkbenchPartSite::Pointer GetSite() const; /** * {@inheritDoc} *

* It is considered bad practise to overload or extend this method. * Parts should call setPartName to change their part name. *

*/ QString GetPartName() const; /** * {@inheritDoc} *

* It is considered bad practise to overload or extend this method. * Parts should call setContentDescription to change their content description. *

*/ QString GetContentDescription() const; /* (non-Javadoc) * Method declared on IWorkbenchPart. */ QIcon GetTitleImage() const; /* (non-Javadoc) * Gets the title tool tip text of this part. * * @return the tool tip text */ QString GetTitleToolTip() const; }; } // namespace berry #endif // __BERRY_WORKBENCH_PART_H__ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkIMenuListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkIMenuListener.cpp deleted file mode 100755 index a787471c2f..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkIMenuListener.cpp +++ /dev/null @@ -1,45 +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 "berryGuiTkIMenuListener.h" - -namespace berry { - -namespace GuiTk { - -void -IMenuListener::Events -::AddListener(IMenuListener::Pointer l) -{ - if (l.IsNull()) return; - - menuAboutToShow += Delegate(l.GetPointer(), &IMenuListener::MenuAboutToShow); - menuAboutToHide += Delegate(l.GetPointer(), &IMenuListener::MenuAboutToHide); -} - -void -IMenuListener::Events -::RemoveListener(IMenuListener::Pointer l) -{ - if (l.IsNull()) return; - - menuAboutToShow -= Delegate(l.GetPointer(), &IMenuListener::MenuAboutToShow); - menuAboutToHide -= Delegate(l.GetPointer(), &IMenuListener::MenuAboutToHide); -} - -} - -} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkIMenuListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkIMenuListener.h deleted file mode 100755 index b16bd5a77f..0000000000 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/guitk/berryGuiTkIMenuListener.h +++ /dev/null @@ -1,78 +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 BERRYGUITKIMENULISTENER_H_ -#define BERRYGUITKIMENULISTENER_H_ - -#include -#include - -#include - -#include - -namespace berry -{ - -namespace GuiTk -{ - -/** - * A menu listener that gets informed when a menu is about to show. - * - * @see MenuManager#addMenuListener - */ -struct BERRY_UI_QT IMenuListener: public virtual Object -{ - 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 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/handlers/berryHandlerUtil.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryHandlerUtil.cpp index ef0e53de46..967805c09f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryHandlerUtil.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryHandlerUtil.cpp @@ -1,413 +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(const ExecutionEvent::ConstPointer& event, const QString& name) { throw ExecutionException("No " + name + " found while executing " + event->GetCommand()->GetId()); } 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::ConstPointer HandlerUtil::GetVariable( const ExecutionEvent::ConstPointer& event, const QString& name) { if (IEvaluationContext::ConstPointer evalContext = event->GetApplicationContext().Cast()) { Object::ConstPointer var = evalContext->GetVariable(name); return var == IEvaluationContext::UNDEFINED_VARIABLE ? Object::ConstPointer() : var; } return Object::ConstPointer(); } Object::ConstPointer HandlerUtil::GetVariableChecked( const ExecutionEvent::ConstPointer& event, const QString& name) { Object::ConstPointer o(HandlerUtil::GetVariable(event, name)); if (o.IsNull()) { HandlerUtil::NoVariableFound(event, name); } return o; } Object::ConstPointer HandlerUtil::GetVariable( Object::Pointer context, const QString& name) { IEvaluationContext::Pointer eval(context.Cast()); if (eval.IsNotNull()) { Object::ConstPointer var = eval->GetVariable(name); return var == IEvaluationContext::UNDEFINED_VARIABLE ? Object::ConstPointer() : var; } return Object::ConstPointer(0); } HandlerUtil::StringVectorType::ConstPointer HandlerUtil::GetActiveContexts( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o(HandlerUtil::GetVariable(event, ISources::ACTIVE_CONTEXT_NAME())); return o.Cast(); } HandlerUtil::StringVectorType::ConstPointer HandlerUtil::GetActiveContextsChecked( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o(HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_CONTEXT_NAME())); if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_CONTEXT_NAME(), "StringVectorType", o->GetClassName()); } return o.Cast(); } //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( // 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::ConstPointer HandlerUtil::GetActiveEditorId(const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_EDITOR_ID_NAME()); return o.Cast(); } ObjectString::ConstPointer HandlerUtil::GetActiveEditorIdChecked( const ExecutionEvent::ConstPointer& event) { 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()); } return o.Cast(); } -IWorkbenchPart::ConstPointer HandlerUtil::GetActivePart(const ExecutionEvent::ConstPointer& event) +IWorkbenchPart::Pointer HandlerUtil::GetActivePart(const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_PART_NAME()); - return o.Cast(); + return IWorkbenchPart::Pointer(const_cast(dynamic_cast(o.GetPointer()))); } -IWorkbenchPart::ConstPointer HandlerUtil::GetActivePartChecked( +IWorkbenchPart::Pointer HandlerUtil::GetActivePartChecked( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_PART_NAME()); if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_PART_NAME(), "IWorkbenchPart", o->GetClassName()); } - return o.Cast(); + return IWorkbenchPart::Pointer(const_cast(dynamic_cast(o.GetPointer()))); } ObjectString::ConstPointer HandlerUtil::GetActivePartId(const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_PART_ID_NAME()); return o.Cast(); } ObjectString::ConstPointer HandlerUtil::GetActivePartIdChecked( const ExecutionEvent::ConstPointer& event) { 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()); } return o.Cast(); } -IWorkbenchPartSite::ConstPointer HandlerUtil::GetActiveSite( +IWorkbenchPartSite::Pointer HandlerUtil::GetActiveSite( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_SITE_NAME()); - return o.Cast(); + return IWorkbenchPartSite::Pointer(const_cast(dynamic_cast(o.GetPointer()))); } -IWorkbenchPartSite::ConstPointer HandlerUtil::GetActiveSiteChecked( +IWorkbenchPartSite::Pointer HandlerUtil::GetActiveSiteChecked( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_SITE_NAME()); if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_SITE_NAME(), "IWorkbenchSitePart", o->GetClassName()); } - return o.Cast(); + return IWorkbenchPartSite::Pointer(const_cast(dynamic_cast(o.GetPointer()))); } ISelection::ConstPointer HandlerUtil::GetCurrentSelection( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_CURRENT_SELECTION_NAME()); return o.Cast(); } ISelection::ConstPointer HandlerUtil::GetCurrentSelectionChecked( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_CURRENT_SELECTION_NAME()); if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_CURRENT_SELECTION_NAME(), "ISelection", o->GetClassName()); } return o.Cast(); } HandlerUtil::StringVectorType::ConstPointer HandlerUtil::GetActiveMenus( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_MENU_NAME()); return o.Cast(); } HandlerUtil::StringVectorType::ConstPointer HandlerUtil::GetActiveMenusChecked( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_MENU_NAME()); if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_MENU_NAME(), "StringVectorType", o->GetClassName()); } return o.Cast(); } ISelection::ConstPointer HandlerUtil::GetActiveMenuSelection( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_MENU_SELECTION_NAME()); return o.Cast(); } ISelection::ConstPointer HandlerUtil::GetActiveMenuSelectionChecked( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_MENU_SELECTION_NAME()); if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_MENU_SELECTION_NAME(), "ISelection", o->GetClassName()); } return o.Cast(); } -IWorkbenchWindow::ConstPointer HandlerUtil::GetActiveWorkbenchWindow( +IWorkbenchWindow::Pointer HandlerUtil::GetActiveWorkbenchWindow( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_WORKBENCH_WINDOW_NAME()); - return o.Cast(); + return IWorkbenchWindow::Pointer(const_cast(dynamic_cast(o.GetPointer()))); } -IWorkbenchWindow::ConstPointer HandlerUtil::GetActiveWorkbenchWindowChecked( +IWorkbenchWindow::Pointer HandlerUtil::GetActiveWorkbenchWindowChecked( const ExecutionEvent::ConstPointer& event) { 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()); } - return o.Cast(); + return IWorkbenchWindow::Pointer(const_cast(dynamic_cast(o.GetPointer()))); } ISelection::ConstPointer HandlerUtil::GetActiveMenuEditorInput( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_MENU_EDITOR_INPUT_NAME()); return o.Cast(); } ISelection::ConstPointer HandlerUtil::GetActiveMenuEditorInputChecked( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_MENU_EDITOR_INPUT_NAME()); if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_MENU_EDITOR_INPUT_NAME(), "ISelection", o->GetClassName()); } return o.Cast(); } ISelection::ConstPointer HandlerUtil::GetShowInSelection( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariable(event, ISources::SHOW_IN_SELECTION()); return o.Cast(); } ISelection::ConstPointer HandlerUtil::GetShowInSelectionChecked( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer o = HandlerUtil::GetVariableChecked(event, ISources::SHOW_IN_SELECTION()); if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::SHOW_IN_SELECTION(), "ISelection", o->GetClassName()); } return o.Cast(); } Object::ConstPointer HandlerUtil::GetShowInInput( const ExecutionEvent::ConstPointer& event) { Object::ConstPointer var = HandlerUtil::GetVariable(event, ISources::SHOW_IN_INPUT()); // if (var == IEvaluationContext.UNDEFINED_VARIABLE) { // return null; // } return var; } Object::ConstPointer HandlerUtil::GetShowInInputChecked( const ExecutionEvent::ConstPointer& 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 6e0c7fa199..2a5e4cd9ad 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryHandlerUtil.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryHandlerUtil.h @@ -1,444 +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(const ExecutionEvent::ConstPointer& 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::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::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::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::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::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(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(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::ConstPointer GetActiveWorkbenchWindow(const ExecutionEvent::ConstPointer& event); + static IWorkbenchWindow::Pointer 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::ConstPointer GetActiveWorkbenchWindowChecked( + static IWorkbenchWindow::Pointer 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(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(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::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::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::ConstPointer GetActivePart(const ExecutionEvent::ConstPointer& event); + static IWorkbenchPart::Pointer 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::ConstPointer GetActivePartChecked(const ExecutionEvent::ConstPointer& event); + static IWorkbenchPart::Pointer 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::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::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::ConstPointer GetActiveSite(const ExecutionEvent::ConstPointer& event); + static IWorkbenchPartSite::Pointer 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::ConstPointer GetActiveSiteChecked(const ExecutionEvent::ConstPointer& event); + static IWorkbenchPartSite::Pointer 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::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::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::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::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::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::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::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::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::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::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::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::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/actions/berryAbstractGroupMarker.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractGroupMarker.cpp similarity index 100% rename from BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryAbstractGroupMarker.cpp rename to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractGroupMarker.cpp diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryAbstractGroupMarker.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractGroupMarker.h similarity index 100% rename from BlueBerry/Bundles/org.blueberry.ui.qt/src/actions/berryAbstractGroupMarker.h rename to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryAbstractGroupMarker.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 0e432524de..00b2339c45 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,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 BERRYCATEGORY_H_ #define BERRYCATEGORY_H_ #include -#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 +template class Category : /*IWorkbenchAdapter*/ public IPluginContribution, public IAdaptable { public: - berryObjectMacro(Category) + berryObjectMacro(Category, IPluginContribution, IAdaptable) 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; + QString pluginId; + 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 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) + /* + * @see IWorkbenchAdapter#GetParent(Object) */ ElementType* GetParent(const ElementType& o); + /* + * @see IPluginContribution#GetLocalId() + */ + QString GetLocalId() const; + + /* + * @see IPluginContribution#GetPluginId() + */ + QString GetPluginId() const; + /** * Clear all elements from this category. * */ void Clear(); protected: /* (non-Javadoc) * Method declared on IAdaptable. */ - Object* GetAdapter(const QString& adapter); + Object* GetAdapter(const QString& adapter) const; }; } // 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 ef019a0808..24a032e2fc 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,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 __BERRY_CATEGORY_TXX__ #define __BERRY_CATEGORY_TXX__ #include "berryWorkbenchRegistryConstants.h" -#include "../berryUIException.h" + +#include +#include #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; + this->pluginId = MISC_ID; } 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); + id = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ID); - if (id == "" || GetLabel() == "") + if (id.isEmpty() || GetLabel().isEmpty()) { throw WorkbenchException(QString("Invalid category: ") + id); } } template void Category::AddElement(ElementType element) { elements.push_back(element); } template -Object* Category::GetAdapter(const QString& adapter) +Object* Category::GetAdapter(const QString& adapter) const { if (adapter == qobject_interface_iid()) { return configurationElement.GetPointer(); } else { 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) +T* Category::GetParent(const ElementType& /*o*/) { return 0; } +template +QString Category::GetLocalId() const +{ + return id; +} + +template +QString Category::GetPluginId() const +{ + return configurationElement.IsNull() ? + pluginId : configurationElement->GetContributor()->GetName(); +} + template void Category::Clear() { elements.clear(); } } // namespace berry #endif // __BERRY_CATEGORY_TXX__ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp new file mode 100644 index 0000000000..810dffb13d --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.cpp @@ -0,0 +1,251 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY 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 "berryChangeToPerspectiveMenu.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "berryCommandContributionItemParameter.h" +#include "berryWorkbenchPlugin.h" +#include "berryWorkbenchPreferenceConstants.h" +#include "berryPreferenceConstants.h" + +#include + +namespace berry { + +const QString ChangeToPerspectiveMenu::NO_TARGETS_MSG = ""; + +bool PerspectiveComparator(const IPerspectiveDescriptor::Pointer& d1, + const IPerspectiveDescriptor::Pointer& d2) +{ + return d1->GetLabel() < d2->GetLabel(); +} + +ChangeToPerspectiveMenu::ChangeToPerspectiveMenu(IWorkbenchWindow* window, const QString& id) + : ContributionItem(id) + , window(window) + , reg(window->GetWorkbench()->GetPerspectiveRegistry()) + , showActive(true) + , dirty(true) +{ + + CommandContributionItemParameter::Pointer showDlgItemParms( + new CommandContributionItemParameter( + window, QString::null, IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE, + CommandContributionItem::STYLE_PUSH)); + showDlgItemParms->label = "&Other..."; + showDlgItem = new CommandContributionItem(showDlgItemParms); + + // indicate that a open perspectives submenu has been created + /* + if (WorkbenchWindow* window = dynamic_cast(window)) + { + window->AddSubmenu(WorkbenchWindow::OPEN_PERSPECTIVE_SUBMENU); + } + */ +} + +void ChangeToPerspectiveMenu::Fill(QMenu* menu, QAction* before) +{ + if (MenuManager* mm = dynamic_cast(GetParent())) + { + this->connect(mm, SIGNAL(AboutToShow(IMenuManager*)), SLOT(AboutToShow(IMenuManager*))); + } + + if (!dirty) + { + return; + } + + MenuManager::Pointer manager(new MenuManager()); + FillMenu(manager.GetPointer()); + + QList items = manager->GetItems(); + if (items.isEmpty()) + { + QAction* action = new QAction(NO_TARGETS_MSG, menu); + action->setEnabled(false); + menu->insertAction(before, action); + } + else + { + foreach (IContributionItem::Pointer item, items) + { + item->Fill(menu, before); + } + } + dirty = false; +} + +bool ChangeToPerspectiveMenu::IsDirty() const +{ + return dirty; +} + +bool ChangeToPerspectiveMenu::IsDynamic() const +{ + return true; +} + +void ChangeToPerspectiveMenu::AboutToShow(IMenuManager* manager) +{ + manager->MarkDirty(); + dirty = true; +} + +void ChangeToPerspectiveMenu::FillMenu(IMenuManager* manager) +{ + // Clear out the manager so that we have a blank slate. + manager->RemoveAll(); + + // Collect and sort perspective descriptors. + QList persps = GetPerspectiveShortcuts(); + qSort(persps.begin(), persps.end(), PerspectiveComparator); + + /* + * Convert the perspective descriptors to command parameters, and filter + * using the activity/capability mechanism. + */ + for (IPerspectiveDescriptor::Pointer descriptor : persps) + { + CommandContributionItemParameter::Pointer ccip = GetItem(descriptor); + + // if (WorkbenchActivityHelper.filterItem(ccip)) { + // continue; + // } + CommandContributionItem::Pointer item(new CommandContributionItem(ccip)); + manager->Add(item); + } + + IPreferences::Pointer prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); + bool showOther = true; + prefs->GetBool(WorkbenchPreferenceConstants::SHOW_OTHER_IN_PERSPECTIVE_MENU, showOther); + if (showOther) + { + // Add a separator and then "Other..." + if (!manager->IsEmpty()) + { + IContributionItem::Pointer separator(new Separator()); + manager->Add(separator); + } + manager->Add(showDlgItem); + } +} + +SmartPointer ChangeToPerspectiveMenu::GetItem(const IPerspectiveDescriptor::Pointer& desc) const +{ + IPreferences::Pointer prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); + int mode = prefs->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE); + IWorkbenchPage::Pointer page = window->GetActivePage(); + IPerspectiveDescriptor::Pointer persp; + if (page.IsNotNull()) + { + persp = page->GetPerspective(); + } + + QString perspId = desc->GetId(); + + class PluginCCIP : public CommandContributionItemParameter, public IPluginContribution + { + QString localId; + QString pluginId; + + public: + + berryObjectMacro(PluginCCIP, CommandContributionItemParameter, IPluginContribution) + + PluginCCIP(const IPerspectiveDescriptor::Pointer& v, IServiceLocator* serviceLocator, + const QString& id, const QString& commandId, CommandContributionItem::Style style) + : CommandContributionItemParameter(serviceLocator, id, commandId, style) + { + PerspectiveDescriptor::Pointer vd = v.Cast(); + localId = vd->GetLocalId(); + pluginId = vd->GetPluginId(); + } + + QString GetLocalId() const + { + return localId; + } + + QString GetPluginId() const + { + return pluginId; + } + }; + + CommandContributionItemParameter::Pointer parms(new PluginCCIP(desc, + window, perspId, IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE, + CommandContributionItem::STYLE_PUSH)); + parms->label = desc->GetLabel(); + parms->icon = desc->GetImageDescriptor(); + + Object::Pointer strId(new ObjectString(perspId)); + parms->parameters.insert(IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_ID, strId); + + // Only open a new window if user preference is set and the window + // has an active perspective. + if (PreferenceConstants::OPM_NEW_WINDOW == mode && persp.IsNotNull()) + { + Object::Pointer bNewWnd(new ObjectBool(true)); + parms->parameters.insert(IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_NEWWINDOW, + bNewWnd); + } + + return parms; +} + +QList > ChangeToPerspectiveMenu::GetPerspectiveShortcuts() const +{ + QList list; + + IWorkbenchPage::Pointer page = window->GetActivePage(); + if (page.IsNull()) + { + return list; + } + + QList ids = page->GetPerspectiveShortcuts(); + for (int i = 0; i < ids.size(); i++) + { + IPerspectiveDescriptor::Pointer desc = reg->FindPerspectiveWithId(ids[i]); + if (desc.IsNotNull() && !list.contains(desc)) + { + /* + if (WorkbenchActivityHelper::FilterItem(desc)) + { + continue; + } + */ + list.push_back(desc); + } + } + + return list; +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.h new file mode 100644 index 0000000000..febdc8b4a4 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryChangeToPerspectiveMenu.h @@ -0,0 +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. + +===================================================================*/ + +#ifndef BERRYCHANGETOPERSPECTIVEMENU_H +#define BERRYCHANGETOPERSPECTIVEMENU_H + +#include + +namespace berry { + +struct IPerspectiveDescriptor; +struct IPerspectiveRegistry; +struct IWorkbenchWindow; +struct IMenuManager; + +class CommandContributionItemParameter; + +/** + * A menu for perspective selection. + *

+ * A ChangeToPerspectiveMenu is used to populate a menu with + * perspective shortcut items. If the user selects one of these items + * the perspective of the active page in the window is changed to the + * selected one. + *

+ * The visible perspective items within the menu are dynamic and consists + * of the perspective shortcut list of the current perspective. + *

+ */ +class ChangeToPerspectiveMenu : public QObject, public ContributionItem +{ + Q_OBJECT + +public: + + /** + * Constructs a new instance of PerspectiveMenu. + * + * @param window the window containing this menu + * @param id the menu id + */ + ChangeToPerspectiveMenu(IWorkbenchWindow* window, const QString& id); + + /* + * Fills the menu with perspective items. + */ + void Fill(QMenu* menu, QAction* before); + + using ContributionItem::Fill; + + /* + * Returns whether this menu is dynamic. + */ + bool IsDirty() const override; + + /* + * Returns whether this menu is dynamic. + */ + bool IsDynamic() const override; + + +private: + + IWorkbenchWindow* window; + IPerspectiveRegistry* reg; + bool showActive; + bool dirty; + + IContributionItem::Pointer showDlgItem; + + /** + * The translatable message to show when there are no perspectives. + */ + static const QString NO_TARGETS_MSG; + + Q_SLOT void AboutToShow(IMenuManager* manager); + + /** + * Fills the given menu manager with all the open perspective actions + * appropriate for the currently active perspective. Filtering is applied to + * the actions based on the activities and capabilities mechanism. + * + * @param manager + * The menu manager that should receive the menu items; must not + * be null. + */ + void FillMenu(IMenuManager* manager); + + SmartPointer GetItem(const SmartPointer& desc) const; + + /* + * Returns the perspective shortcut items for the active perspective. + * + * @return a list of IPerspectiveDescriptor items + */ + QList > GetPerspectiveShortcuts() const; + +}; + +} + +#endif // BERRYCHANGETOPERSPECTIVEMENU_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 a85d8e8d60..e23086c32b 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"); } } 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() { /* * All state on all commands neeeds to be disposed. This is so that the * state has a chance to persist any changes. */ 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(); } 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) + void HandleException(const ctkException& 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()); } } } const CommandPersistence* CommandService::GetCommandPersistence() const { return &commandPersistence; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCompositeExpression.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCompositeExpression.cpp index b8a0266b37..17e07314d4 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCompositeExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryCompositeExpression.cpp @@ -1,82 +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 "berryCompositeExpression.h" -#include "Poco/Hash.h" - namespace berry { -const uint CompositeExpression::HASH_INITIAL = Poco::Hash()("berry::CompositeExpression"); +const uint CompositeExpression::HASH_INITIAL = qHash("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) const { if (fExpressions.size() == 0) return; foreach (Expression::Pointer iter, fExpressions) { iter->CollectExpressionInfo(info); } } uint CompositeExpression::ComputeHashCode() const { return HASH_INITIAL * HASH_FACTOR + this->HashCode(fExpressions); } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDirtyPerspectiveMarker.cpp old mode 100755 new mode 100644 similarity index 54% copy from BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.cpp copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDirtyPerspectiveMarker.cpp index 459d37d793..8ab9882267 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryPlatformObject.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDirtyPerspectiveMarker.cpp @@ -1,41 +1,40 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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" +#include "berryDirtyPerspectiveMarker.h" namespace berry { -PlatformObject::PlatformObject() +DirtyPerspectiveMarker::DirtyPerspectiveMarker(const QString& id) + : perspectiveId(id) { } -Object* PlatformObject::GetAdapter(const QString& adapter) +uint DirtyPerspectiveMarker::HashCode() const { - IAdapterManager* adapterManager = Platform::GetAdapterManager(); - if (adapterManager) - { - return adapterManager->GetAdapter(this, adapter); - } - else + return qHash(perspectiveId); +} + +bool DirtyPerspectiveMarker::operator==(const Object* o) const +{ + if (const DirtyPerspectiveMarker* other = dynamic_cast(o)) { - return NULL; + return perspectiveId == other->perspectiveId; } + return false; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDirtyPerspectiveMarker.h similarity index 57% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDirtyPerspectiveMarker.h index babfd77662..123b8d02f8 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryWorkbenchActionConstants.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryDirtyPerspectiveMarker.h @@ -1,39 +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 BERRYDIRTYPERSPECTIVEMARKER_H +#define BERRYDIRTYPERSPECTIVEMARKER_H -#ifndef BERRYWORKBENCHACTIONCONSTANTS_H -#define BERRYWORKBENCHACTIONCONSTANTS_H +#include #include -#include - namespace berry { -struct BERRY_UI_QT WorkbenchActionConstants +class DirtyPerspectiveMarker : public Object { +public: + + berryObjectMacro(DirtyPerspectiveMarker) + + QString perspectiveId; - // Standard area for adding top level menus: /** - * Name of group for adding new top-level menus (value "additions"). + * @param id */ - static const QString MB_ADDITIONS; + DirtyPerspectiveMarker(const QString& id); + + uint HashCode() const; + + bool operator==(const Object* o) const; }; } -#endif // BERRYWORKBENCHACTIONCONSTANTS_H +#endif // BERRYDIRTYPERSPECTIVEMARKER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorHistory.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorHistory.cpp new file mode 100644 index 0000000000..c538caaed3 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorHistory.cpp @@ -0,0 +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. + +===================================================================*/ + +#include "berryEditorHistory.h" + +#include "berryIEditorInput.h" +#include "berryIEditorDescriptor.h" +#include "berryIMemento.h" + +#include "berryStatus.h" + +#include "berryEditorHistoryItem.h" +#include "berryWorkbenchConstants.h" + +namespace berry { + +const int EditorHistory::MAX_SIZE = 15; + +EditorHistory::EditorHistory() +{ +} + +void EditorHistory::Add(const SmartPointer& input, const SmartPointer& desc) +{ + if (input.IsNotNull() && input->Exists()) + { + EditorHistoryItem::Pointer item(new EditorHistoryItem(input, desc)); + Add(item, 0); + } +} + +QList > EditorHistory::GetItems() +{ + Refresh(); + return fifoList; +} + +void EditorHistory::Refresh() +{ + auto iter = fifoList.begin(); + while (iter != fifoList.end()) + { + if ((*iter)->IsRestored()) + { + IEditorInput::Pointer input = (*iter)->GetInput(); + if (input.IsNotNull() && !input->Exists()) + { + iter = fifoList.erase(iter); + continue; + } + } + ++iter; + } +} + +void EditorHistory::Remove(const SmartPointer& item) +{ + fifoList.removeAll(item); +} + +void EditorHistory::Remove(const SmartPointer& input) +{ + if (input.IsNull()) + { + return; + } + auto iter = fifoList.begin(); + while (iter != fifoList.end()) + { + if ((*iter)->Matches(input)) + { + iter = fifoList.erase(iter); + } + else + { + ++iter; + } + } +} + +SmartPointer EditorHistory::RestoreState(const SmartPointer& memento) +{ + QList mementos = memento->GetChildren(WorkbenchConstants::TAG_FILE); + for (int i = 0; i < mementos.size(); i++) + { + EditorHistoryItem::Pointer item(new EditorHistoryItem(mementos[i])); + if (!item->GetName().isEmpty() || !item->GetToolTipText().isEmpty()) + { + this->Add(item, fifoList.size()); + } + } + return Status::OK_STATUS(BERRY_STATUS_LOC); +} + +SmartPointer EditorHistory::SaveState(const SmartPointer& memento) const +{ + for (auto iter = fifoList.begin(); iter != fifoList.end(); ++iter) + { + if ((*iter)->CanSave()) + { + IMemento::Pointer itemMemento = memento->CreateChild(WorkbenchConstants::TAG_FILE); + (*iter)->SaveState(itemMemento); + } + } + return Status::OK_STATUS(BERRY_STATUS_LOC); +} + +void EditorHistory::Add(const SmartPointer& newItem, int index) +{ + // Remove the item if it already exists so that it will be put + // at the top of the list. + if (newItem->IsRestored()) + { + this->Remove(newItem->GetInput()); + } + + // Remove the oldest one + if (fifoList.size() == MAX_SIZE) + { + fifoList.pop_back(); + } + + // Add the new item. + fifoList.insert(index < MAX_SIZE ? index : MAX_SIZE - 1, newItem); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorHistory.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorHistory.h new file mode 100644 index 0000000000..babe92f8ee --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorHistory.h @@ -0,0 +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 BERRYEDITORHISTORY_H +#define BERRYEDITORHISTORY_H + +#include + +#include + +namespace berry { + +struct IEditorInput; +struct IEditorDescriptor; +struct IMemento; +struct IStatus; + +class EditorHistoryItem; + +/** + * This class is used to record "open editor" actions as they + * happen. The input and type of each editor are recorded so that + * the user can reopen an item from the recently used files list. + */ +class EditorHistory +{ + +public: + + /** + * The maximum of entries in the history. + */ + static const int MAX_SIZE; // = 15; + + /** + * Constructs a new history. + */ + EditorHistory(); + + /** + * Adds an item to the history. Added in fifo fashion. + */ + void Add(const SmartPointer& input, const SmartPointer& desc); + + /** + * Returns an array of editor history items. The items are returned in order + * of most recent first. + */ + QList > GetItems(); + + /** + * Refresh the editor list. Any stale items are removed. + * Only restored items are considered. + */ + void Refresh(); + + /** + * Removes the given history item. + */ + void Remove(const SmartPointer& item); + + /** + * Removes all traces of an editor input from the history. + */ + void Remove(const SmartPointer& input); + + /** + * Restore the most-recently-used history from the given memento. + * + * @param memento the memento to restore the mru history from + */ + SmartPointer RestoreState(const SmartPointer& memento); + + /** + * Save the most-recently-used history in the given memento. + * + * @param memento the memento to save the mru history in + */ + SmartPointer SaveState(const SmartPointer& memento) const; + +private: + + /** + * The list of editor entries, in FIFO order. + */ + QList > fifoList; + + /** + * Adds an item to the history. + */ + void Add(const SmartPointer& newItem, int index); + +}; + +} +#endif // BERRYEDITORHISTORY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorHistoryItem.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorHistoryItem.cpp new file mode 100644 index 0000000000..536cd23d97 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorHistoryItem.cpp @@ -0,0 +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. + +===================================================================*/ + +#include "berryEditorHistoryItem.h" + +#include "berryIEditorInput.h" +#include "berryIEditorDescriptor.h" +#include "berryIElementFactory.h" +#include "berryIMemento.h" +#include "berryIPersistableElement.h" + +#include "berryStatus.h" +#include "berryWorkbenchConstants.h" +#include "berryWorkbenchPlugin.h" + +namespace berry { + +EditorHistoryItem::EditorHistoryItem(const SmartPointer& input, + const SmartPointer& descriptor) + : input(input) + , descriptor(descriptor) +{ +} + +EditorHistoryItem::EditorHistoryItem(const SmartPointer& memento) + : memento(memento) +{ +} + +SmartPointer EditorHistoryItem::GetDescriptor() const +{ + return descriptor; +} + +SmartPointer EditorHistoryItem::GetInput() const +{ + return input; +} + +bool EditorHistoryItem::IsRestored() const +{ + return memento.IsNull(); +} + +QString EditorHistoryItem::GetName() const +{ + QString result; + if (IsRestored() && GetInput().IsNotNull()) + { + result = GetInput()->GetName(); + } + else if (memento.IsNotNull()) + { + memento->GetString(WorkbenchConstants::TAG_NAME, result); + } + return result; +} + +QString EditorHistoryItem::GetToolTipText() const +{ + QString result; + if (IsRestored() && GetInput().IsNotNull()) + { + result = GetInput()->GetToolTipText(); + } + else if (memento.IsNotNull()) + { + memento->GetString(WorkbenchConstants::TAG_TOOLTIP, result); + } + return result; +} + +bool EditorHistoryItem::Matches(const SmartPointer& input) const +{ + if (IsRestored()) + { + return input == GetInput(); + } + // if not restored, compare name, tool tip text and factory id, + // avoiding as much work as possible + if (GetName() != input->GetName()) + { + return false; + } + if (GetToolTipText() != input->GetToolTipText()) + { + return false; + } + + const IPersistableElement* persistable = input->GetPersistable(); + QString inputId = persistable ? QString::null : persistable->GetFactoryId(); + QString myId = GetFactoryId(); + return myId.isEmpty() ? inputId.isEmpty() : myId == inputId; +} + +QString EditorHistoryItem::GetFactoryId() const +{ + QString result; + if (IsRestored()) + { + if (input.IsNotNull()) + { + const IPersistableElement* persistable = input->GetPersistable(); + if (persistable != nullptr) + { + result = persistable->GetFactoryId(); + } + } + } + else if (memento.IsNotNull()) + { + memento->GetString(WorkbenchConstants::TAG_FACTORY_ID, result); + } + return result; +} + +SmartPointer EditorHistoryItem::RestoreState() +{ + Q_ASSERT_X(!IsRestored(), "RestoreState", "already restored"); + + IStatus::ConstPointer result = Status::OK_STATUS(BERRY_STATUS_LOC); + IMemento::Pointer memento = this->memento; + this->memento = 0; + + QString factoryId; + memento->GetString(WorkbenchConstants::TAG_FACTORY_ID, factoryId); + if (factoryId.isEmpty()) + { + WorkbenchPlugin::Log("Unable to restore mru list - no input factory ID."); + return result; + } + QScopedPointer factory( + PlatformUI::GetWorkbench()->GetElementFactory(factoryId)); + if (!factory) + { + return result; + } + IMemento::Pointer persistableMemento = memento->GetChild(WorkbenchConstants::TAG_PERSISTABLE); + if (persistableMemento.IsNull()) + { + WorkbenchPlugin::Log("Unable to restore mru list - no input element state: " + factoryId); + return result; + } + QScopedPointer adaptable(factory->CreateElement(persistableMemento)); + if (adaptable == nullptr || dynamic_cast(adaptable.data()) == nullptr) + { + return result; + } + input = dynamic_cast(adaptable.data()); + // Get the editor descriptor. + QString editorId; + memento->GetString(WorkbenchConstants::TAG_ID, editorId); + if (!editorId.isEmpty()) + { + IEditorRegistry* registry = WorkbenchPlugin::GetDefault()->GetEditorRegistry(); + descriptor = registry->FindEditor(editorId); + } + return result; +} + +bool EditorHistoryItem::CanSave() const +{ + return !IsRestored() + || (GetInput().IsNotNull() && GetInput()->GetPersistable() != nullptr); +} + +SmartPointer EditorHistoryItem::SaveState(const SmartPointer& memento) +{ + if (!IsRestored()) + { + memento->PutMemento(this->memento); + } + else if (input.IsNotNull()) + { + + const IPersistableElement* persistable = input->GetPersistable(); + if (persistable != nullptr) + { + /* + * Store IPersistable of the IEditorInput in a separate section + * since it could potentially use a tag already used in the parent + * memento and thus overwrite data. + */ + IMemento::Pointer persistableMemento = memento->CreateChild(WorkbenchConstants::TAG_PERSISTABLE); + persistable->SaveState(persistableMemento); + memento->PutString(WorkbenchConstants::TAG_FACTORY_ID, + persistable->GetFactoryId()); + if (descriptor.IsNotNull() && !descriptor->GetId().isEmpty()) + { + memento->PutString(WorkbenchConstants::TAG_ID, descriptor->GetId()); + } + // save the name and tooltip separately so they can be restored + // without having to instantiate the input, which can activate plugins + memento->PutString(WorkbenchConstants::TAG_NAME, input->GetName()); + memento->PutString(WorkbenchConstants::TAG_TOOLTIP, input->GetToolTipText()); + } + } + return Status::OK_STATUS(BERRY_STATUS_LOC); +} + + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorHistoryItem.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorHistoryItem.h new file mode 100644 index 0000000000..ab15947c74 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEditorHistoryItem.h @@ -0,0 +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 BERRYEDITORHISTORYITEM_H +#define BERRYEDITORHISTORYITEM_H + +#include +#include + +namespace berry { + +struct IEditorInput; +struct IEditorDescriptor; +struct IMemento; +struct IStatus; + +/** + * An item in the editor history. + */ +class EditorHistoryItem : public Object +{ + +private: + + SmartPointer input; + + SmartPointer descriptor; + + SmartPointer memento; + +public: + + berryObjectMacro(EditorHistoryItem) + + /** + * Constructs a new item. + */ + EditorHistoryItem(const SmartPointer& input, const SmartPointer& descriptor); + + /** + * Constructs a new item from a memento. + */ + EditorHistoryItem(const SmartPointer& memento); + + /** + * Returns the editor descriptor. + * + * @return the editor descriptor. + */ + SmartPointer GetDescriptor() const; + + /** + * Returns the editor input. + * + * @return the editor input. + */ + SmartPointer GetInput() const; + + /** + * Returns whether this item has been restored from the memento. + */ + bool IsRestored() const; + + /** + * Returns the name of this item, either from the input if restored, + * otherwise from the memento. + */ + QString GetName() const; + + /** + * Returns the tooltip text of this item, either from the input if restored, + * otherwise from the memento. + */ + QString GetToolTipText() const; + + /** + * Returns whether this item matches the given editor input. + */ + bool Matches(const SmartPointer& input) const; + + /** + * Returns the factory id of this item, either from the input if restored, + * otherwise from the memento. + * Returns null if there is no factory id. + */ + QString GetFactoryId() const; + + /** + * Restores the object state from the memento. + */ + SmartPointer RestoreState(); + + /** + * Returns whether this history item can be saved. + */ + bool CanSave() const; + + /** + * Saves the object state in the given memento. + * + * @param memento the memento to save the object state in + */ + SmartPointer SaveState(const SmartPointer& memento); + +}; + +} + +Q_DECLARE_METATYPE(berry::EditorHistoryItem::Pointer) + +#endif // BERRYEDITORHISTORYITEM_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 ff960795ea..a9d9d1bb7e 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,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 "berryEditorRegistryReader.h" #include "berryEditorRegistry.h" #include "berryEditorDescriptor.h" #include "berryWorkbenchRegistryConstants.h" #include "berryPlatformUI.h" +#include "berryPlatform.h" #include namespace berry { void EditorRegistryReader::AddEditors(EditorRegistry* registry) { this->editorRegistry = registry; - this->ReadRegistry(PlatformUI::PLUGIN_ID(), + this->ReadRegistry(Platform::GetExtensionRegistry(), + 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 (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/berryEvaluationAuthority.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationAuthority.cpp index 24942ac9bb..5a884f2bf9 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,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 "berryEvaluationAuthority.h" +#include "berryCommandTracing.h" #include "berryExpressionInfo.h" #include "berryExpression.h" #include "berryEvaluationReference.h" +#include "berryPolicy.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) { + if (Policy::DEBUG_SOURCES()) + { + CommandTracing::PrintTrace(COMPONENT, "start source changed: " + sourceNames.join(", ")); + } 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) { + if (Policy::DEBUG_SOURCES()) + { + CommandTracing::PrintTrace(COMPONENT, "end source changed: " + sourceNames.join(", ")); + } + 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*/) { // 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 { 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/berryEvaluationReference.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationReference.cpp index be27df1fc2..90c2b9d2ce 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationReference.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationReference.cpp @@ -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. ===================================================================*/ #include "berryEvaluationReference.h" #include namespace berry { EvaluationReference::EvaluationReference(const SmartPointer& expression, IPropertyChangeListener* listener, const QString& property) : EvaluationResultCache(expression), listener(listener), property(property), postingChanges(true) { } IPropertyChangeListener* EvaluationReference::GetListener() const { - return listener.data(); + return listener; } QString EvaluationReference::GetProperty() const { return property; } void EvaluationReference::SetPostingChanges(bool evaluationEnabled) { this->postingChanges = evaluationEnabled; } bool EvaluationReference::IsPostingChanges() const { return postingChanges; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationReference.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationReference.h index 426b99828d..1a00931cc4 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationReference.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryEvaluationReference.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 BERRYEVALUATIONREFERENCE_H #define BERRYEVALUATIONREFERENCE_H #include "berryEvaluationResultCache.h" #include namespace berry { class EvaluationReference : public EvaluationResultCache, public IEvaluationReference { private: - QScopedPointer listener; + IPropertyChangeListener* listener; QString property; bool postingChanges; public: berryObjectMacro(berry::EvaluationReference) /** * @param expression */ EvaluationReference(const SmartPointer& expression, IPropertyChangeListener *listener, const QString& property); /* * @see IEvaluationReference#GetListener() */ IPropertyChangeListener* GetListener() const; QString GetProperty() const; /* * @see IEvaluationReference#SetFlopping(bool) */ void SetPostingChanges(bool evaluationEnabled); /* * @see IEvaluationReference#IsFlopping() */ bool IsPostingChanges() const; }; } #endif // BERRYEVALUATIONREFERENCE_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 b67f1b5835..8a8b5c477c 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,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. ===================================================================*/ #include "berryExpressionAuthority.h" #include +#include +#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); + Object::Pointer platformVariable(new ObjectTypeInfo(Reflection::TypeInfo::New())); + context->AddVariable("org.blueberry.core.runtime.Platform", platformVariable); } 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::ConstPointer ExpressionAuthority::GetVariable(const QString& name) const { return context->GetVariable(name); } 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*/) { // 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); while (variableItr.hasNext()) { variableItr.next(); const QString variableName = variableItr.key(); 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::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); while (variableItr.hasNext()) { variableItr.next(); const QString variableName = variableItr.key(); 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::ConstPointer defaultVariable = context->GetVariable(ISources::ACTIVE_CURRENT_SELECTION_NAME()); IEvaluationContext::Pointer contextWithDefaultVariable; if (IStructuredSelection::ConstPointer selection = defaultVariable.Cast()) { contextWithDefaultVariable = new EvaluationContext(context.GetPointer(), selection->ToVector()); } else if (defaultVariable.Cast() && !defaultVariable.Cast()->IsEmpty()) { ObjectList::Pointer defaultObj(new ObjectList()); defaultObj->push_back(defaultVariable); contextWithDefaultVariable = new EvaluationContext(context.GetPointer(), defaultObj); } else { 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); while (variableItr.hasNext()) { variableItr.next(); const QString variableName = variableItr.key(); ChangeVariable(variableName, Object::Pointer(0)); } } void ExpressionAuthority::SourceChanged(int sourcePriority, 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); while (entryItr.hasNext()) { entryItr.next(); const QString sourceName = entryItr.key(); const Object::ConstPointer sourceValue = entryItr.value(); UpdateEvaluationContext(sourceName, sourceValue); } SourceChanged(sourcePriority, sourceValuesByName.keys()); } void ExpressionAuthority::SourceChanged(int sourcePriority, const QString &sourceName, 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/berryFolderLayout.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryFolderLayout.cpp index 06f0a9d855..1b19091399 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryFolderLayout.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryFolderLayout.cpp @@ -1,96 +1,95 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryFolderLayout.h" #include "berryPartPlaceholder.h" #include "berryWorkbenchPlugin.h" #include "berryPageLayout.h" #include "berryLayoutHelper.h" #include "berryUIException.h" namespace berry { FolderLayout::FolderLayout(PageLayout::Pointer pageLayout, PartStack::Pointer folder, ViewFactory* viewFactory) { this->folder = folder; this->viewFactory = viewFactory; this->pageLayout = pageLayout; } void FolderLayout::AddPlaceholder(const QString& viewId) { if (!pageLayout->CheckValidPlaceholderId(viewId)) { return; } // Create the placeholder. LayoutPart::Pointer newPart(new PartPlaceholder(viewId)); this->LinkPartToPageLayout(viewId, newPart); // Add it to the folder layout. folder->Add(newPart); } void FolderLayout::AddView(const QString& viewId) { - pageLayout->AddShowViewShortcut(viewId); if (pageLayout->CheckPartInLayout(viewId)) { return; } try { IViewDescriptor::Pointer descriptor = viewFactory->GetViewRegistry()->Find( ViewFactory::ExtractPrimaryId(viewId)); if (descriptor == 0) { throw PartInitException("View descriptor not found: " + viewId); } PartPane::Pointer newPart = LayoutHelper::CreateView(pageLayout->GetViewFactory(), viewId); this->LinkPartToPageLayout(viewId, newPart); folder->Add(newPart); } catch (const PartInitException& e) { // cannot safely open the dialog so log the problem WorkbenchPlugin::Log(this->GetClassName(), "AddView(const QString&)", e); } } QString FolderLayout::GetProperty(const QString& id) { return folder->GetProperty(id); } void FolderLayout::SetProperty(const QString& id, const QString& value) { folder->SetProperty(id, value); } void FolderLayout::LinkPartToPageLayout(const QString& viewId, LayoutPart::Pointer newPart) { pageLayout->SetRefPart(viewId, newPart); pageLayout->SetFolderPart(viewId, folder); // force creation of the view layout rec pageLayout->GetViewLayoutRec(viewId, true); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.cpp index d6ef1d8b0f..caa21b3292 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.cpp @@ -1,509 +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; +bool HandlerAuthority::DEBUG = false; // = Policy.DEBUG_HANDLERS; +bool HandlerAuthority::DEBUG_PERFORMANCE = false; // = Policy.DEBUG_HANDLERS_PERFORMANCE; +bool HandlerAuthority::DEBUG_VERBOSE = false; // = Policy.DEBUG_HANDLERS && Policy.DEBUG_HANDLERS_VERBOSE; +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 index a9adfa245e..5a3ae78666 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerAuthority.h @@ -1,254 +1,255 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; 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: + /** + * Whether the workbench command support should kick into debugging mode. + * This causes the unresolvable handler conflicts to be printed to the + * console. + */ + static bool DEBUG; // = Policy.DEBUG_HANDLERS; + + /** + * Whether the performance information should be printed about the + * performance of the handler authority. + */ + static 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 bool DEBUG_VERBOSE; // = Policy.DEBUG_HANDLERS && Policy.DEBUG_HANDLERS_VERBOSE; + + /** + * The command identifier to which the verbose output should be restricted. + */ + static QString DEBUG_VERBOSE_COMMAND_ID; // = Policy.DEBUG_HANDLERS_VERBOSE_COMMAND_ID; + + /** * 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/berryHandlerProxy.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerProxy.cpp index 803238c9ab..32854afe6e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerProxy.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerProxy.cpp @@ -1,417 +1,419 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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) { + this->Register(); 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); + this->UnRegister(false); } 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) + if (evaluationService && enablementRef) { 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/berryHandlerServiceFactory.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerServiceFactory.cpp index fb3b8eaa81..437cede608 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerServiceFactory.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryHandlerServiceFactory.cpp @@ -1,85 +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. ===================================================================*/ #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->Register(); handlerService->ReadRegistry(); + handlerService->UnRegister(false); 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/berryKeywordRegistry.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryKeywordRegistry.cpp new file mode 100644 index 0000000000..e110a3a0b1 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryKeywordRegistry.cpp @@ -0,0 +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. + +===================================================================*/ + +#include "berryKeywordRegistry.h" + +#include "berryIConfigurationElement.h" +#include "berryIExtension.h" +#include "berryIExtensionPoint.h" +#include "berryIExtensionPointFilter.h" +#include "berryIExtensionRegistry.h" + +#include "berryExtensionTracker.h" +#include "berryObjectString.h" +#include "berryPlatform.h" +#include "berryPlatformUI.h" +#include "berryWorkbenchRegistryConstants.h" + +namespace berry { + +const QString KeywordRegistry::ATT_ID = "id"; +const QString KeywordRegistry::ATT_LABEL = "label"; +const QString KeywordRegistry::TAG_KEYWORD = "keyword"; + +KeywordRegistry::KeywordRegistry() +{ + IExtensionTracker* tracker = PlatformUI::GetWorkbench()->GetExtensionTracker(); + tracker->RegisterHandler(this, ExtensionTracker::CreateExtensionPointFilter(GetExtensionPointFilter())); + QList extensions = GetExtensionPointFilter()->GetExtensions(); + for (auto& extension : extensions) + { + AddExtension(tracker, extension); + } +} + +SmartPointer KeywordRegistry::GetExtensionPointFilter() const +{ + return Platform::GetExtensionRegistry()->GetExtensionPoint( + PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_KEYWORDS); +} + +KeywordRegistry*KeywordRegistry::GetInstance() +{ + static KeywordRegistry instance; + return &instance; +} + +void KeywordRegistry::AddExtension(IExtensionTracker* tracker, const SmartPointer& extension) +{ + for (auto element : extension->GetConfigurationElements()) + { + if (element->GetName() == TAG_KEYWORD) + { + QString name = element->GetAttribute(ATT_LABEL); + QString id = element->GetAttribute(ATT_ID); + internalKeywordMap.insert(id, name); + Object::Pointer trackedObject(new ObjectString(id)); + tracker->RegisterObject(extension, trackedObject, IExtensionTracker::REF_STRONG); + } + } +} + +QString KeywordRegistry::GetKeywordLabel(const QString& id) +{ + auto it = internalKeywordMap.find(id); + return it == internalKeywordMap.end() ? QString::null : *it; +} + +void KeywordRegistry::RemoveExtension(const SmartPointer& /*extension*/, const QList >& objects) +{ + for (auto object : objects) + { + if (ObjectString::Pointer objString = object.Cast()) + { + internalKeywordMap.remove(*objString); + } + } +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryKeywordRegistry.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryKeywordRegistry.h new file mode 100644 index 0000000000..2ad66f8e14 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryKeywordRegistry.h @@ -0,0 +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 BERRYKEYWORDREGISTRY_H +#define BERRYKEYWORDREGISTRY_H + +#include + +namespace berry { + +struct IExtensionPoint; + +/** + * Contains extensions defined on the keywords extension point. + */ +class KeywordRegistry : public IExtensionChangeHandler +{ + +private: + + static const QString ATT_ID; // = "id" + + static const QString ATT_LABEL; // = "label" + + static const QString TAG_KEYWORD; // = "keyword" + + /** + * Map of id->labels. + */ + QHash internalKeywordMap; + + /** + * Private constructor. + */ + KeywordRegistry(); + + + SmartPointer GetExtensionPointFilter() const; + + +public: + + /** + * Return the singleton instance of the KeywordRegistry. + * + * @return the singleton registry + */ + static KeywordRegistry* GetInstance(); + + void AddExtension(IExtensionTracker* tracker, const SmartPointer& extension) override; + + /** + * Return the label associated with the given keyword. + * + * @param id the keyword id + * @return the label or null + */ + QString GetKeywordLabel(const QString& id); + + void RemoveExtension(const SmartPointer& extension, const QList >& objects) override; + +}; + +} + +#endif // BERRYKEYWORDREGISTRY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryNullEditorInput.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryNullEditorInput.cpp index 84c6f9f163..bf418c4a0f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryNullEditorInput.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryNullEditorInput.cpp @@ -1,61 +1,77 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryNullEditorInput.h" -#include "berryPartPane.h" +#include "berryPartPane.h" +#include "berryAbstractUICTKPlugin.h" namespace berry { NullEditorInput::NullEditorInput() { } NullEditorInput::NullEditorInput(EditorReference::Pointer editorReference) { //poco_assert(editorReference.IsNotNull()); this->editorReference = editorReference; } bool NullEditorInput::Exists() const { return false; } +QIcon NullEditorInput::GetIcon() const +{ + return AbstractUICTKPlugin::GetMissingIcon(); +} + QString NullEditorInput::GetName() const { if (editorReference.IsNotNull()) return editorReference->GetName(); return ""; } +const IPersistableElement* NullEditorInput::GetPersistable() const +{ + return nullptr; +} + QString NullEditorInput::GetToolTipText() const { if (editorReference.IsNotNull()) return editorReference->GetTitleToolTip(); return ""; } +Object*NullEditorInput::GetAdapter(const QString& /*adapterType*/) const +{ + return nullptr; +} + bool NullEditorInput::operator==(const Object* o) const { const NullEditorInput* input = dynamic_cast(o); if (input == 0) return false; return true; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryNullEditorInput.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryNullEditorInput.h index 80fd7c841a..b45a0af1f3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryNullEditorInput.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryNullEditorInput.h @@ -1,76 +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 BERRYNULLEDITORINPUT_H_ #define BERRYNULLEDITORINPUT_H_ #include "berryIEditorInput.h" #include "berryEditorReference.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * */ class NullEditorInput : public IEditorInput { private: EditorReference::Pointer editorReference; public: - berryObjectMacro(NullEditorInput); + berryObjectMacro(NullEditorInput) NullEditorInput(); /** * Creates a NullEditorInput for the * given editor reference. * * @param editorReference the editor reference - * @since 3.4 */ NullEditorInput(EditorReference::Pointer editorReference); - /* (non-Javadoc) - * @see org.blueberry.ui.IEditorInput#exists() - */ bool Exists() const; - /* (non-Javadoc) - * @see org.blueberry.ui.IEditorInput#getImageDescriptor() - */ -// ImageDescriptor getImageDescriptor() { -// return ImageDescriptor.getMissingImageDescriptor(); -// } - - /* (non-Javadoc) - * @see org.blueberry.ui.IEditorInput#getName() - */ - QString GetName() const; - - /* (non-Javadoc) - * @see org.blueberry.ui.IEditorInput#getToolTipText() - */ - QString GetToolTipText() const; + QIcon GetIcon() const; + + QString GetName() const; + + const IPersistableElement* GetPersistable() const; + + QString GetToolTipText() const; + + Object* GetAdapter(const QString &adapterType) const; bool operator==(const Object* o) const; }; } #endif /*BERRYNULLEDITORINPUT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryOpenPerspectivePropertyTester.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryOpenPerspectivePropertyTester.cpp new file mode 100644 index 0000000000..8c9b9f67f1 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryOpenPerspectivePropertyTester.cpp @@ -0,0 +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 "berryOpenPerspectivePropertyTester.h" + +#include "berryWorkbenchWindow.h" + + +#include + +namespace berry { + +QString OpenPerspectivePropertyTester::PROPERTY_IS_PERSPECTIVE_OPEN = "isPerspectiveOpen"; + +bool OpenPerspectivePropertyTester::Test(Object::ConstPointer receiver, const QString& property, + const QList& args, Object::Pointer /*expectedValue*/) +{ + if (args.empty() && dynamic_cast(receiver.GetPointer())) + { + WorkbenchWindow::ConstPointer window = receiver.Cast(); + if (PROPERTY_IS_PERSPECTIVE_OPEN == property) + { + IWorkbenchPage::Pointer page = window->GetActivePage(); + if (page.IsNotNull()) + { + return page->GetPerspective().IsNotNull(); + } + } + } + return false; +} + +} + diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryOpenPerspectivePropertyTester.h similarity index 50% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryOpenPerspectivePropertyTester.h index 90365ba2c1..765a20fc87 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryOpenPerspectivePropertyTester.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 BERRYQTWORKBENCHTWEAKLET_H_ -#define BERRYQTWORKBENCHTWEAKLET_H_ +#ifndef BERRYOPENPERSPECTIVEPROPERTYTESTER_H +#define BERRYOPENPERSPECTIVEPROPERTYTESTER_H -#include - -#include +#include namespace berry { -class BERRY_UI_QT QtWorkbenchTweaklet : public QObject, public WorkbenchTweaklet +/** + * Tests if any Perspective is open or not. + */ +class OpenPerspectivePropertyTester : public PropertyTester { Q_OBJECT - Q_INTERFACES(berry::WorkbenchTweaklet) - -public: - berryObjectMacro(QtWorkbenchTweaklet) +private: - QtWorkbenchTweaklet(); + static QString PROPERTY_IS_PERSPECTIVE_OPEN; // = "isPerspectiveOpen"; - Display* CreateDisplay(); +public: - bool IsRunning(); + bool Test(Object::ConstPointer receiver, const QString& property, + const QList &args, Object::Pointer expectedValue); }; -} // namespace berry +} -#endif /*BERRYQTWORKBENCHTWEAKLET_H_*/ +#endif // BERRYOPENPERSPECTIVEPROPERTYTESTER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPageLayout.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPageLayout.cpp index f1df69cbf9..2fa91d2f05 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPageLayout.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPageLayout.cpp @@ -1,673 +1,672 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryPageLayout.h" #include "berryWorkbenchPlugin.h" #include "berryLayoutHelper.h" #include "berryViewLayout.h" #include "berryPresentationFactoryUtil.h" #include "berryFolderLayout.h" #include "berryPlaceholderFolderLayout.h" #include "berryUIException.h" #include "berryConstants.h" namespace berry { PageLayout::PageLayout() : editorVisible(true) { //no-op } PageLayout::PageLayout(ViewSashContainer::Pointer container, ViewFactory* viewFactory, LayoutPart::Pointer editorFolder, IPerspectiveDescriptor::Pointer descriptor) : editorVisible(true) { this->viewFactory = viewFactory; this->rootLayoutContainer = container; this->editorFolder = editorFolder; this->descriptor = descriptor; this->Prefill(); } void PageLayout::AddEditorArea() { try { // Create the part. LayoutPart::Pointer newPart = this->CreateView(ID_EDITOR_AREA); if (newPart == 0) { // this should never happen as long as newID is the editor ID. return; } this->SetRefPart(ID_EDITOR_AREA, newPart); // Add it to the layout. rootLayoutContainer->Add(newPart); } catch (PartInitException& e) { WorkbenchPlugin::Log(this->GetClassName(), "AddEditorArea()", e); //$NON-NLS-1$ } } ViewLayoutRec::Pointer PageLayout::GetViewLayoutRec(const QString& id, bool create) { ViewLayoutRec::Pointer rec = mapIDtoViewLayoutRec[id]; if (rec == 0 && create) { rec = new ViewLayoutRec(); // set up the view layout appropriately if the page layout is fixed if (this->IsFixed()) { rec->isCloseable = false; rec->isMoveable = false; } mapIDtoViewLayoutRec[id] = rec; } return rec; } void PageLayout::AddPart(LayoutPart::Pointer newPart, const QString& partId, int relationship, float ratio, const QString& refId) { this->SetRefPart(partId, newPart); // If the referenced part is inside a folder, // then use the folder as the reference part. LayoutPart::Pointer refPart = this->GetFolderPart(refId); if (refPart == 0) { refPart = this->GetRefPart(refId); } // Add it to the layout. if (refPart != 0) { ratio = this->NormalizeRatio(ratio); rootLayoutContainer->Add(newPart, this->GetPartSashConst(relationship), ratio, refPart); } else { WorkbenchPlugin::Log("Reference part does not exist yet: " + refId); rootLayoutContainer->Add(newPart); } } void PageLayout::AddPerspectiveShortcut(const QString& id) { - if (std::find(perspectiveShortcuts.begin(), - perspectiveShortcuts.end(), id) == perspectiveShortcuts.end()) + if (!perspectiveShortcuts.contains(id)) { perspectiveShortcuts.push_back(id); } } void PageLayout::AddPlaceholder(const QString& viewId, int relationship, float ratio, const QString& refId) { if (!this->CheckValidPlaceholderId(viewId)) { return; } // Create the placeholder. PartPlaceholder::Pointer newPart(new PartPlaceholder(viewId)); this->AddPart(newPart, viewId, relationship, ratio, refId); // force creation of the view layout rec this->GetViewLayoutRec(viewId, true); } bool PageLayout::CheckValidPlaceholderId(const QString& id) { // Check that view is not already in layout. // This check is done even if the id has a wildcard, since it's incorrect to create // multiple placeholders with the same id, wildcard or not. if (this->CheckPartInLayout(id)) { return false; } // check that primary view id is valid, but only if it has no wildcard QString primaryId = ViewFactory::ExtractPrimaryId(id); if (!ViewFactory::HasWildcard(primaryId)) { IViewRegistry* reg = WorkbenchPlugin::GetDefault()->GetViewRegistry(); IViewDescriptor::Pointer desc = reg->Find(primaryId); if (desc == 0) { // cannot safely open the dialog so log the problem WorkbenchPlugin::Log("Unable to find view with id: " + primaryId + ", when creating perspective " + this->GetDescriptor()->GetId()); //$NON-NLS-1$ //$NON-NLS-2$ return false; } } return true; } void PageLayout::AddShowInPart(const QString& id) { if (!showInPartIds.contains(id)) { showInPartIds.push_back(id); } } void PageLayout::AddShowViewShortcut(const QString& id) { if (!showViewShortcuts.contains(id)) { showViewShortcuts.push_back(id); } } void PageLayout::AddView(const QString& viewId, int relationship, float ratio, const QString& refId) { this->AddView(viewId, relationship, ratio, refId, false, false, true); } void PageLayout::AddView(const QString& viewId, int relationship, float ratio, const QString& refId, bool minimized) { this->AddView(viewId, relationship, ratio, refId, minimized, false, true); } void PageLayout::AddView(const QString& viewId, int relationship, float ratio, const QString& refId, bool /*minimized*/, bool standalone, bool showTitle) { this->AddShowViewShortcut(viewId); if (this->CheckPartInLayout(viewId)) { return; } try { // Create the part. LayoutPart::Pointer newPart = this->CreateView(viewId); if (newPart == 0) { this->AddPlaceholder(viewId, relationship, ratio, refId); LayoutHelper::AddViewActivator(PageLayout::Pointer(this), viewId); } else { int appearance = PresentationFactoryUtil::ROLE_VIEW; if (standalone) { if (showTitle) { appearance = PresentationFactoryUtil::ROLE_STANDALONE; } else { appearance = PresentationFactoryUtil::ROLE_STANDALONE_NOTITLE; } } // PartStack for views PartStack::Pointer newFolder(new PartStack(rootLayoutContainer->page, true, appearance, 0)); newFolder->Add(newPart); this->SetFolderPart(viewId, newFolder); this->AddPart(newFolder, viewId, relationship, ratio, refId); // force creation of the view layout rec this->GetViewLayoutRec(viewId, true); // Capture any minimized stacks // if (minimized) // { // // Remember the minimized stacks so we can // // move them to the trim when the Perspective // // activates... // minimizedStacks.add(newFolder); // } } } catch (PartInitException& e) { WorkbenchPlugin::Log(this->GetClassName(), "AddView()", e); //$NON-NLS-1$ } } // List getMinimizedStacks() { // return minimizedStacks; // } bool PageLayout::CheckPartInLayout(const QString& partId) { if (partId == ID_EDITOR_AREA) return true; if (this->GetRefPart(partId) != 0) // || this->IsFastViewId(partId)) { WorkbenchPlugin::Log("Part already exists in page layout: " + partId); return true; } if (this->GetFolderPart(partId) != 0) // || this->IsFastViewId(partId)) { WorkbenchPlugin::Log("Part already exists in page layout: " + partId); return true; } return false; } IFolderLayout::Pointer PageLayout::CreateFolder(const QString& folderId, int relationship, float ratio, const QString& refId) { if (this->CheckPartInLayout(folderId)) { ILayoutContainer::Pointer folder = this->GetFolderPart(folderId); return mapFolderToFolderLayout[folder].Cast(); } // Create the folder. PartStack::Pointer folder(new PartStack(rootLayoutContainer->page)); folder->SetID(folderId); this->AddPart(folder, folderId, relationship, ratio, refId); // Create a wrapper. FolderLayout::Pointer layout(new FolderLayout(PageLayout::Pointer(this), folder, viewFactory)); mapFolderToFolderLayout.insert(folder, layout); return layout; } IPlaceholderFolderLayout::Pointer PageLayout::CreatePlaceholderFolder( const QString& folderId, int relationship, float ratio, const QString& refId) { if (this->CheckPartInLayout(folderId)) { ContainerPlaceholder::Pointer folder = this->GetRefPart(folderId).Cast(); return mapFolderToFolderLayout[folder]; } // Create the folder. ContainerPlaceholder::Pointer folder(new ContainerPlaceholder("")); folder->SetContainer(rootLayoutContainer); folder->SetRealContainer(ILayoutContainer::Pointer(new PartStack(rootLayoutContainer->page))); folder->SetID(folderId); this->AddPart(folder, folderId, relationship, ratio, refId); // Create a wrapper. IPlaceholderFolderLayout::Pointer layout(new PlaceholderFolderLayout(this, folder)); mapFolderToFolderLayout.insert(folder, layout); return layout; } LayoutPart::Pointer PageLayout::CreateView(const QString& partID) { if (partID == ID_EDITOR_AREA) { return editorFolder; } // IViewDescriptor::Pointer viewDescriptor = viewFactory->GetViewRegistry() // ->Find(ViewFactory::ExtractPrimaryId(partID)); // if (WorkbenchActivityHelper.filterItem(viewDescriptor)) // { // return null; // } return LayoutHelper::CreateView(this->GetViewFactory(), partID); } IPerspectiveDescriptor::Pointer PageLayout::GetDescriptor() { return descriptor; } QString PageLayout::GetEditorArea() { return ID_EDITOR_AREA; } PartStack::Pointer PageLayout::GetFolderPart(const QString& viewId) { return mapIDtoFolder[viewId].Cast(); } int PageLayout::GetPartSashConst(int nRelationship) { return nRelationship; } QList PageLayout::GetPerspectiveShortcuts() { return perspectiveShortcuts; } LayoutPart::Pointer PageLayout::GetRefPart(const QString& partID) { return mapIDtoPart[partID]; } PartSashContainer::Pointer PageLayout::GetRootLayoutContainer() { return rootLayoutContainer; } QList PageLayout::GetShowInPartIds() { return showInPartIds; } QList PageLayout::GetShowViewShortcuts() { return showViewShortcuts; } ViewFactory* PageLayout::GetViewFactory() { return viewFactory; } bool PageLayout::IsEditorAreaVisible() { return editorVisible; } float PageLayout::NormalizeRatio(float in) { if (in < RATIO_MIN) { in = RATIO_MIN; } if (in > RATIO_MAX) { in = RATIO_MAX; } return in; } void PageLayout::Prefill() { this->AddEditorArea(); //TODO action sets // Add default action sets. // ActionSetRegistry reg = WorkbenchPlugin.getDefault() // .getActionSetRegistry(); // IActionSetDescriptor[] array = reg.getActionSets(); // int count = array.length; // for (int nX = 0; nX < count; nX++) // { // IActionSetDescriptor desc = array[nX]; // if (desc.isInitiallyVisible()) // { // addActionSet(desc.getId()); // } // } } void PageLayout::SetEditorAreaVisible(bool showEditorArea) { editorVisible = showEditorArea; } void PageLayout::SetFixed(bool fixed) { this->fixed = fixed; } bool PageLayout::IsFixed() { return fixed; } void PageLayout::SetFolderPart(const QString& viewId, ContainerPlaceholder::Pointer container) { LayoutPart::Pointer tabFolder = container->GetRealContainer(); mapIDtoFolder[viewId] = tabFolder.Cast(); } void PageLayout::SetFolderPart(const QString& viewId, PartStack::Pointer folder) { mapIDtoFolder[viewId] = folder.Cast(); } void PageLayout::SetFolderPart(const QString& viewId, ILayoutContainer::Pointer folder) { mapIDtoFolder[viewId] = folder; } void PageLayout::SetRefPart(const QString& partID, LayoutPart::Pointer part) { mapIDtoPart[partID] = part; } void PageLayout::StackPart(LayoutPart::Pointer newPart, const QString& viewId, const QString& refId) { this->SetRefPart(viewId, newPart); // force creation of the view layout rec this->GetViewLayoutRec(viewId, true); // If ref part is in a folder than just add the // new view to that folder. PartStack::Pointer folder = this->GetFolderPart(refId).Cast(); if (folder != 0) { folder->Add(newPart); this->SetFolderPart(viewId, folder); return; } // parts are now always contained in folders // // If the ref part is in the page layout then create // // a new folder and add the new view. // LayoutPart::Pointer refPart = this->GetRefPart(refId); // if (refPart != 0) // && (refPart instanceof PartPane || refPart instanceof PartPlaceholder)) // { // PartStack::Pointer newFolder(new PartStack(rootLayoutContainer->page)); // rootLayoutContainer->Replace(refPart, newFolder); // newFolder->Add(refPart); // newFolder->Add(newPart); // this->SetFolderPart(refId, newFolder); // this->SetFolderPart(viewId, newFolder); // return; // } // If ref part is not found then just do add. WorkbenchPlugin::Log("Referenced part does not exist yet: " + refId); PartStack::Pointer newFolder(new PartStack(rootLayoutContainer->page)); newFolder->Add(newPart); this->SetFolderPart(viewId, newFolder); rootLayoutContainer->Add(newFolder); } void PageLayout::StackPlaceholder(const QString& viewId, const QString& refId) { if (this->CheckPartInLayout(viewId)) { return; } // Create the placeholder. PartPlaceholder::Pointer newPart(new PartPlaceholder(viewId)); LayoutPart::Pointer refPart = this->GetRefPart(refId); if (refPart != 0) { newPart->SetContainer(refPart->GetContainer()); } this->StackPart(newPart, viewId, refId); } void PageLayout::StackView(const QString& viewId, const QString& refId) { if (this->CheckPartInLayout(viewId)) { return; } // Create the new part. try { LayoutPart::Pointer newPart = this->CreateView(viewId); if (newPart == 0) { this->StackPlaceholder(viewId, refId); LayoutHelper::AddViewActivator(PageLayout::Pointer(this), viewId); } else { this->StackPart(newPart, viewId, refId); } } catch (PartInitException& e) { WorkbenchPlugin::Log(this->GetClassName(), "StackView", e); //$NON-NLS-1$ } } int PageLayout::ConstantToLayoutPosition(int constant) { if (constant == Constants::TOP) return IPageLayout::TOP; if (constant == Constants::BOTTOM) return IPageLayout::BOTTOM; if (constant == Constants::RIGHT) return IPageLayout::RIGHT; if (constant == Constants::LEFT) return IPageLayout::LEFT; return -1; } void PageLayout::AddStandaloneView(const QString& viewId, bool showTitle, int relationship, float ratio, const QString& refId) { this->AddView(viewId, relationship, ratio, refId, false, true, showTitle); ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(viewId, true); rec->isStandalone = true; rec->showTitle = showTitle; } void PageLayout::AddStandaloneViewPlaceholder(const QString& viewId, int relationship, float ratio, const QString& refId, bool showTitle) { QString stackId = viewId + ".standalonefolder"; //$NON-NLS-1$ // Check to see if the view is already in the layout if (!this->CheckValidPlaceholderId(viewId)) { return; } // Create the folder. ContainerPlaceholder::Pointer folder(new ContainerPlaceholder("")); folder->SetContainer(rootLayoutContainer); int appearance = PresentationFactoryUtil::ROLE_STANDALONE; if (!showTitle) { appearance = PresentationFactoryUtil::ROLE_STANDALONE_NOTITLE; } folder->SetRealContainer(ILayoutContainer::Pointer(new PartStack(rootLayoutContainer->page, true, appearance, 0))); folder->SetID(stackId); this->AddPart(folder, stackId, relationship, ratio, refId); // Create a wrapper. PlaceholderFolderLayout::Pointer placeHolder(new PlaceholderFolderLayout(this, folder)); // Add the standalone view immediately placeHolder->AddPlaceholder(viewId); ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(viewId, true); rec->isStandalone = true; rec->showTitle = showTitle; } IViewLayout::Pointer PageLayout::GetViewLayout(const QString& viewId) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(viewId, true); if (rec == 0) { return IViewLayout::Pointer(0); } return IViewLayout::Pointer(new ViewLayout(PageLayout::Pointer(this), rec)); } QHash PageLayout::GetIDtoViewLayoutRecMap() { return mapIDtoViewLayoutRec; } void PageLayout::RemovePlaceholder(const QString& id) { LayoutPart::Pointer part = this->GetRefPart(id); - if (part->IsPlaceHolder()) + if (part != nullptr && part->IsPlaceHolder()) { ILayoutContainer::Pointer stack = this->GetFolderPart(id); if (stack != 0) { stack->Remove(part); } else { //rootLayoutContainer->Remove(part); WorkbenchPlugin::Log("Not removing placeholder: Folder for placeholder " + id + " not found"); } mapIDtoPart.remove(id); mapIDtoFolder.remove(id); mapIDtoViewLayoutRec.remove(id); } } IPlaceholderFolderLayout::Pointer PageLayout::GetFolderForView( const QString& viewId) { if (mapIDtoFolder[viewId] == 0) return IPlaceholderFolderLayout::Pointer(0); ILayoutContainer::Pointer folder = mapIDtoFolder[viewId]; IPlaceholderFolderLayout::Pointer layout; if (mapFolderToFolderLayout[folder] == 0) { layout = new FolderLayout(PageLayout::Pointer(this), folder.Cast(), viewFactory); mapFolderToFolderLayout[folder] = layout; } else { layout = mapFolderToFolderLayout[folder]; } return layout; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSite.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSite.h index 2fcecd935a..ea505ae0aa 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSite.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPartSite.h @@ -1,314 +1,314 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYPARTSITE_H_ #define BERRYPARTSITE_H_ #include #include "berryServiceLocator.h" #include "berryIWorkbenchPartSite.h" #include "berryIWorkbenchPartReference.h" #include "berryISelectionProvider.h" namespace berry { struct IWorkbenchPart; struct IWorkbenchPage; struct IWorkbenchWindow; struct IWorkbenchLocationService; class PartPane; class Shell; /** * \ingroup org_blueberry_ui_internal * * PartSite is the general implementation for an * IWorkbenchPartSite. A site maintains the context for a part, * including the part, its pane, active contributions, selection provider, etc. * Together, these components make up the complete behavior for a part as if it * was implemented by one person. * * The PartSite lifecycle is as follows .. * *
    *
  1. a site is constructed
  2. *
  3. a part is constructed and stored in the part
  4. *
  5. the site calls part.init()
  6. *
  7. a pane is constructed and stored in the site
  8. *
  9. the action bars for a part are constructed and stored in the site
  10. *
  11. the pane is added to a presentation
  12. *
  13. the SWT widgets for the pane and part are created
  14. *
  15. the site is activated, causing the actions to become visible
  16. *
*/ class PartSite : public virtual IWorkbenchPartSite { public: - berryObjectMacro(PartSite) + berryObjectMacro(PartSite, IWorkbenchPartSite) /** * This is a helper method for the register context menu functionality. It * is provided so that different implementations of the * IWorkbenchPartSite interface don't have to worry about how * context menus should work. * * @param menuId * the menu id * @param menuManager * the menu manager * @param selectionProvider * the selection provider * @param includeEditorInput * whether editor inputs should be included in the structured * selection when calculating contributions * @param part * the part for this site * @param menuExtenders * the collection of menu extenders for this site * @see IWorkbenchPartSite#registerContextMenu(MenuManager, * ISelectionProvider) */ //public: static void RegisterContextMenu(const QString& menuId, // const MenuManager menuManager, // const ISelectionProvider selectionProvider, // bool includeEditorInput, IWorkbenchPart::ConstPointer part, // const Collection menuExtenders); private: IWorkbenchPartReference::WeakPtr partReference; WeakPointer part; IWorkbenchPage* page; QString extensionID; QString pluginID; QString extensionName; ISelectionProvider::Pointer selectionProvider; //SubActionBars actionBars; //KeyBindingService keyBindingService; //ArrayList menuExtenders; //WorkbenchSiteProgressService progressService; struct ServiceLocatorOwner : public IDisposable { ServiceLocatorOwner(PartSite* site); PartSite* site; void Dispose(); }; ServiceLocatorOwner::Pointer serviceLocatorOwner; QScopedPointer workbenchLocationService; protected: ServiceLocator::Pointer serviceLocator; /** * Build the part site. * * @param ref * the part reference * @param part * the part * @param page * the page it belongs to */ public: PartSite(IWorkbenchPartReference::Pointer ref, SmartPointer part, IWorkbenchPage* page); /** * Initialize the local services. */ private: void InitializeDefaultServices(); /** * Dispose the contributions. */ public: ~PartSite(); /** * Returns the action bars for the part. If this part is a view then it has * exclusive use of the action bars. If this part is an editor then the * action bars are shared among this editor and other editors of the same * type. */ //public: virtual IActionBars GetActionBars(); /** * Returns the part registry extension ID. * * @return the registry extension ID */ public: virtual QString GetId() const; /** * Returns the page containing this workbench site's part. * * @return the page containing this part */ public: virtual SmartPointer GetPage(); /** * Gets the part pane. */ public: SmartPointer GetPane(); /** * Returns the part. */ public: virtual SmartPointer GetPart(); /** * Returns the part reference. */ public: virtual IWorkbenchPartReference::Pointer GetPartReference(); /** * Returns the part registry plugin ID. It cannot be null. * * @return the registry plugin ID */ public: virtual QString GetPluginId() const; /** * Returns the registered name for this part. */ public: virtual QString GetRegisteredName() const; /** * Returns the selection provider for a part. */ public: virtual ISelectionProvider::Pointer GetSelectionProvider(); /** * Returns the shell containing this part. * * @return the shell containing this part */ public: SmartPointer GetShell(); /** * Returns the workbench window containing this part. * * @return the workbench window containing this part */ public: virtual SmartPointer GetWorkbenchWindow(); /** * Register a popup menu for extension. */ //public: virtual void RegisterContextMenu(const QString& menuID, // MenuManager menuMgr, // ISelectionProvider selProvider); /** * Register a popup menu with the default id for extension. */ //public: virtual void RegisterContextMenu(MenuManager menuMgr, // ISelectionProvider selProvider); // getContextMenuIds() added by Dan Rubel (dan_rubel@instantiations.com) /** * Get the registered popup menu identifiers */ //public: virtual void GetContextMenuIds(QList& menuIds); /** * Sets the action bars for the part. */ //public: virtual void SetActionBars(SubActionBars bars); /** * Sets the configuration element for a part. */ public: virtual void SetConfigurationElement(IConfigurationElement::Pointer configElement); protected: virtual void SetPluginId(const QString& pluginId); /** * Sets the part registry extension ID. * * @param id * the registry extension ID */ protected: virtual void SetId(const QString& id); /** * Sets the part. */ public: virtual void SetPart(SmartPointer newPart); /** * Sets the registered name for this part. * * @param name * the registered name */ protected: virtual void SetRegisteredName(const QString& name); /** * Set the selection provider for a part. */ public: virtual void SetSelectionProvider(ISelectionProvider::Pointer provider); /* * @see IWorkbenchPartSite#getKeyBindingService() * * TODO deprecated: use IHandlerService instead */ //public: virtual IKeyBindingService GetKeyBindingService(); protected: virtual QString GetInitialScopeId(); /** * Get an adapter for this type. * * @param adapter * @return */ protected: void* GetAdapterImpl(const std::type_info& adapter) const; //public: virtual void ActivateActionBars(bool forceVisibility); //public: virtual void DeactivateActionBars(bool forceHide); /** * Get a progress service for the receiver. * * @return WorkbenchSiteProgressService */ //public: virtual WorkbenchSiteProgressService GetSiteProgressService(); public: Object* GetService(const QString& api); public: bool HasService(const QString& api) const; /** * Prints out the identifier, the plug-in identifier and the registered * name. This is for debugging purposes only. * * @since 3.2 */ public: virtual QString ToString() const; }; } // namespace berry #endif /*BERRYPARTSITE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.cpp index c59c886af9..283c01c688 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.cpp @@ -1,1813 +1,1813 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryPerspective.h" #include "berryPerspectiveHelper.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include "berryPerspectiveExtensionReader.h" #include "berryEditorSashContainer.h" #include "berryPartSite.h" #include "berryViewSite.h" #include "berryEditorAreaHelper.h" #include "intro/berryIntroConstants.h" #include "berryWorkbenchWindow.h" #include "berryStatusUtil.h" +#include "berryMultiStatus.h" +#include "berryXMLMemento.h" #include "presentations/berryIStackPresentationSite.h" #include "berryIContextService.h" #include namespace berry { const QString Perspective::VERSION_STRING = "0.016"; Perspective::Perspective(PerspectiveDescriptor::Pointer desc, WorkbenchPage::Pointer page) : descriptor(desc) { + this->Register(); this->Init(page); if (desc.IsNotNull()) { this->CreatePresentation(desc); } + this->UnRegister(false); } Perspective::Perspective(WorkbenchPage::Pointer page) { this->Init(page); } void Perspective::Init(WorkbenchPage::Pointer page) { editorHidden = false; editorAreaState = IStackPresentationSite::STATE_RESTORED; fixed = false; presentation = 0; shouldHideEditorsOnActivate = false; this->page = page.GetPointer(); this->editorArea = page->GetEditorPresentation()->GetLayoutPart(); this->viewFactory = page->GetViewFactory(); } bool Perspective::BringToTop(IViewReference::Pointer ref) { return presentation->BringPartToTop(this->GetPane(ref)); } bool Perspective::ContainsView(IViewPart::Pointer view) { IViewSite::Pointer site = view->GetViewSite(); IViewReference::Pointer ref = this->FindView(site->GetId(), site->GetSecondaryId()); if (ref.IsNull()) { return false; } return (view.Cast() == ref->GetPart(false)); } bool Perspective::ContainsView(const QString& viewId) const { return mapIDtoViewLayoutRec.contains(viewId); } void Perspective::CreatePresentation(PerspectiveDescriptor::Pointer persp) { if (persp->HasCustomDefinition()) { this->LoadCustomPersp(persp); } else { this->LoadPredefinedPersp(persp); } } Perspective::~Perspective() { // Get rid of presentation. if (presentation == 0) { DisposeViewRefs(); return; } presentation->Deactivate(); // Release each view. QList refs(this->GetViewReferences()); for (QList::size_type i = 0, length = refs.size(); i < length; i++) { this->GetViewFactory()->ReleaseView(refs[i]); } mapIDtoViewLayoutRec.clear(); delete presentation; } void Perspective::DisposeViewRefs() { if (!memento) { return; } QList views(memento->GetChildren(WorkbenchConstants::TAG_VIEW)); for (int x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; QString id; childMem->GetString(WorkbenchConstants::TAG_ID, id); // skip creation of the intro reference - it's handled elsewhere. if (id == IntroConstants::INTRO_VIEW_ID) { continue; } QString secondaryId = ViewFactory::ExtractSecondaryId(id); if (!secondaryId.isEmpty()) { id = ViewFactory::ExtractPrimaryId(id); } QString removed; childMem->GetString(WorkbenchConstants::TAG_REMOVED, removed); if (removed != "true") { IViewReference::Pointer ref = viewFactory->GetView(id, secondaryId); if (ref) { viewFactory->ReleaseView(ref); } } } } IViewReference::Pointer Perspective::FindView(const QString& viewId) { return this->FindView(viewId, ""); } IViewReference::Pointer Perspective::FindView(const QString& id, const QString& secondaryId) { QList refs(this->GetViewReferences()); for (int i = 0; i < refs.size(); i++) { IViewReference::Pointer ref = refs[i]; if (id == ref->GetId() && (secondaryId == ref->GetSecondaryId())) { return ref; } } return IViewReference::Pointer(0); } QWidget* Perspective::GetClientComposite() { return page->GetClientComposite(); } IPerspectiveDescriptor::Pointer Perspective::GetDesc() { return descriptor; } PartPane::Pointer Perspective::GetPane(IViewReference::Pointer ref) { return ref.Cast()->GetPane(); } QList Perspective::GetPerspectiveShortcuts() { return perspectiveShortcuts; } PerspectiveHelper* Perspective::GetPresentation() const { return presentation; } QList Perspective::GetShowViewShortcuts() { return showViewShortcuts; } ViewFactory* Perspective::GetViewFactory() { return viewFactory; } QList Perspective::GetViewReferences() { // Get normal views. if (presentation == 0) { return QList(); } QList panes; presentation->CollectViewPanes(panes); QList result; // List fastViews = (fastViewManager != 0) ? // fastViewManager.getFastViews(0) // : new ArrayList(); // IViewReference[] resultArray = new IViewReference[panes.size() // + fastViews.size()]; // // // Copy fast views. // int nView = 0; // for (int i = 0; i < fastViews.size(); i++) // { // resultArray[nView] = (IViewReference) fastViews.get(i); // ++nView; // } // Copy normal views. for (QList::iterator iter = panes.begin(); iter != panes.end(); ++iter) { PartPane::Pointer pane = *iter; result.push_back(pane->GetPartReference().Cast()); } return result; } void Perspective::HideEditorArea() { if (!this->IsEditorAreaVisible()) { return; } // Show the editor in the appropriate location if (this->UseNewMinMax(Perspective::Pointer(this))) { // If it's the currently maximized part we have to restore first // if (this->GetPresentation().getMaximizedStack().Cast() != 0) // { // getPresentation().getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); // } bool isMinimized = editorAreaState == IStackPresentationSite::STATE_MINIMIZED; if (!isMinimized) this->HideEditorAreaLocal(); //else // this->SetEditorAreaTrimVisibility(false); } else { this->HideEditorAreaLocal(); } editorHidden = true; } void Perspective::HideEditorAreaLocal() { if (editorHolder != 0) { return; } // Replace the editor area with a placeholder so we // know where to put it back on show editor area request. editorHolder = new PartPlaceholder(editorArea->GetID()); presentation->GetLayout()->Replace(editorArea, editorHolder); } bool Perspective::HideView(IViewReference::Pointer ref) { // If the view is locked just return. PartPane::Pointer pane = this->GetPane(ref); presentation->RemovePart(pane); // Dispose view if ref count == 0. this->GetViewFactory()->ReleaseView(ref); return true; } bool Perspective::IsEditorAreaVisible() { return !editorHidden; } ViewLayoutRec::Pointer Perspective::GetViewLayoutRec(IViewReference::Pointer ref, bool create) { ViewLayoutRec::Pointer result = this->GetViewLayoutRec(ViewFactory::GetKey(ref), create); if (result.IsNull() && create==false) { result = this->GetViewLayoutRec(ref->GetId(), false); } return result; } ViewLayoutRec::Pointer Perspective::GetViewLayoutRec(const QString& viewId, bool create) { ViewLayoutRec::Pointer rec = mapIDtoViewLayoutRec[viewId]; if (rec.IsNull() && create) { rec = new ViewLayoutRec(); mapIDtoViewLayoutRec[viewId] = rec; } return rec; } bool Perspective::IsFixedLayout() { //@issue is there a difference between a fixed //layout and a fixed perspective?? If not the API //may need some polish, WorkbenchPage, PageLayout //and Perspective all have isFixed methods. //PageLayout and Perspective have their own fixed //attribute, we are assuming they are always in sync. //WorkbenchPage delegates to the perspective. return fixed; } bool Perspective::IsStandaloneView(IViewReference::Pointer ref) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(ref, false); return rec.IsNotNull() && rec->isStandalone; } bool Perspective::GetShowTitleView(IViewReference::Pointer ref) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(ref, false); return rec.IsNotNull() && rec->showTitle; } void Perspective::LoadCustomPersp(PerspectiveDescriptor::Pointer persp) { //get the layout from the registry PerspectiveRegistry* perspRegistry = dynamic_cast(WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()); try { IMemento::Pointer memento = perspRegistry->GetCustomPersp(persp->GetId()); // Restore the layout state. // MultiStatus status = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // NLS.bind(WorkbenchMessages.Perspective_unableToRestorePerspective, persp.getLabel()), // 0); // status.merge(restoreState(memento)); // status.merge(restoreState()); bool okay = true; okay &= this->RestoreState(memento); okay &= this->RestoreState(); if (!okay) { this->UnableToOpenPerspective(persp, "Unable to open perspective: " + persp->GetLabel()); } } //catch (IOException e) //{ // unableToOpenPerspective(persp, 0); //} catch (const WorkbenchException& e) { this->UnableToOpenPerspective(persp, e.what()); } } void Perspective::UnableToOpenPerspective(PerspectiveDescriptor::Pointer persp, const QString& status) { PerspectiveRegistry* perspRegistry = dynamic_cast(WorkbenchPlugin ::GetDefault()->GetPerspectiveRegistry()); perspRegistry->DeletePerspective(persp); // If this is a predefined perspective, we will not be able to delete // the perspective (we wouldn't want to). But make sure to delete the // customized portion. persp->DeleteCustomDefinition(); QString title = "Restoring problems"; QString msg = "Unable to read workbench state."; if (status == "") { QMessageBox::critical(NULL, title, msg); } else { //TODO error dialog //ErrorDialog.openError((Shell) 0, title, msg, status); QMessageBox::critical(NULL, title, msg + "\n" + status); } } void Perspective::LoadPredefinedPersp(PerspectiveDescriptor::Pointer persp) { // Create layout engine. IPerspectiveFactory::Pointer factory; try { factory = persp->CreateFactory(); } catch (CoreException& /*e*/) { throw WorkbenchException("Unable to load perspective: " + persp->GetId()); } /* * IPerspectiveFactory#createFactory() can return 0 */ if (factory == 0) { throw WorkbenchException("Unable to load perspective: " + persp->GetId()); } // Create layout factory. ViewSashContainer::Pointer container(new ViewSashContainer(page, this->GetClientComposite())); layout = new PageLayout(container, this->GetViewFactory(), editorArea, descriptor); layout->SetFixed(descriptor->GetFixed()); // // add the placeholders for the sticky folders and their contents IPlaceholderFolderLayout::Pointer stickyFolderRight, stickyFolderLeft, stickyFolderTop, stickyFolderBottom; QList descs(WorkbenchPlugin::GetDefault() ->GetViewRegistry()->GetStickyViews()); for (int i = 0; i < descs.size(); i++) { IStickyViewDescriptor::Pointer stickyViewDescriptor = descs[i]; QString id = stickyViewDescriptor->GetId(); int location = stickyViewDescriptor->GetLocation(); if (location == IPageLayout::RIGHT) { if (stickyFolderRight == 0) { stickyFolderRight = layout ->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_RIGHT, IPageLayout::RIGHT, .75f, IPageLayout::ID_EDITOR_AREA); } stickyFolderRight->AddPlaceholder(id); } else if (location == IPageLayout::LEFT) { if (stickyFolderLeft == 0) { stickyFolderLeft = layout->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_LEFT, IPageLayout::LEFT, .25f, IPageLayout::ID_EDITOR_AREA); } stickyFolderLeft->AddPlaceholder(id); } else if (location == IPageLayout::TOP) { if (stickyFolderTop == 0) { stickyFolderTop = layout->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_TOP, IPageLayout::TOP, .25f, IPageLayout::ID_EDITOR_AREA); } stickyFolderTop->AddPlaceholder(id); } else if (location == IPageLayout::BOTTOM) { if (stickyFolderBottom == 0) { stickyFolderBottom = layout->CreatePlaceholderFolder( StickyViewDescriptor::STICKY_FOLDER_BOTTOM, IPageLayout::BOTTOM, .75f, IPageLayout::ID_EDITOR_AREA); } stickyFolderBottom->AddPlaceholder(id); } //should never be 0 as we've just added the view above IViewLayout::Pointer viewLayout = layout->GetViewLayout(id); viewLayout->SetCloseable(stickyViewDescriptor->IsCloseable()); viewLayout->SetMoveable(stickyViewDescriptor->IsMoveable()); } // Run layout engine. factory->CreateInitialLayout(layout); PerspectiveExtensionReader extender; - extender.ExtendLayout(descriptor->GetId(), layout); + extender.ExtendLayout(page->GetExtensionTracker(), descriptor->GetId(), layout); // Retrieve view layout info stored in the page layout. QHash layoutInfo = layout->GetIDtoViewLayoutRecMap(); mapIDtoViewLayoutRec.unite(layoutInfo); //TODO Perspective action sets // Create action sets. //List temp = new ArrayList(); //this->CreateInitialActionSets(temp, layout.getActionSets()); // IContextService* service = 0; // if (page != 0) // { // service = page->GetWorkbenchWindow()->GetService(); // } // try // { // if (service != 0) // { // service->DeferUpdates(true); // } // for (Iterator iter = temp.iterator(); iter.hasNext();) // { // IActionSetDescriptor descriptor = (IActionSetDescriptor) iter // .next(); // addAlwaysOn(descriptor); // } // }finally // { // if (service!=0) // { // service.activateContext(ContextAuthority.SEND_EVENTS); // } // } // newWizardShortcuts = layout.getNewWizardShortcuts(); showViewShortcuts = layout->GetShowViewShortcuts(); -// perspectiveShortcuts = layout.getPerspectiveShortcuts(); -// showInPartIds = layout.getShowInPartIds(); -// + perspectiveShortcuts = layout->GetPerspectiveShortcuts(); + showInPartIds = layout->GetShowInPartIds(); + // // Retrieve fast views // if (fastViewManager != 0) // { // ArrayList fastViews = layout.getFastViews(); // for (Iterator fvIter = fastViews.iterator(); fvIter.hasNext();) // { // IViewReference ref = (IViewReference) fvIter.next(); // fastViewManager.addViewReference(FastViewBar.FASTVIEWBAR_ID, -1, ref, // !fvIter.hasNext()); // } // } // Is the layout fixed fixed = layout->IsFixed(); showViewShortcuts = layout->GetShowViewShortcuts(); // Create presentation. presentation = new PerspectiveHelper(page, container, this); // Hide editor area if requested by factory if (!layout->IsEditorAreaVisible()) { this->HideEditorArea(); } } void Perspective::OnActivate() { // Update editor area state. if (editorArea->GetControl() != 0) { bool visible = this->IsEditorAreaVisible(); bool inTrim = editorAreaState == IStackPresentationSite::STATE_MINIMIZED; editorArea->SetVisible(visible && !inTrim); } // // Update fast views. // // Make sure the control for the fastviews are created so they can // // be activated. // if (fastViewManager != 0) // { // List fastViews = fastViewManager.getFastViews(0); // for (int i = 0; i < fastViews.size(); i++) // { // ViewPane pane = getPane((IViewReference) fastViews.get(i)); // if (pane != 0) // { // Control ctrl = pane.getControl(); // if (ctrl == 0) // { // pane.createControl(getClientComposite()); // ctrl = pane.getControl(); // } // ctrl.setEnabled(false); // Remove focus support. // } // } // } // // Set the visibility of all fast view pins // setAllPinsVisible(true); // Trim Stack Support bool useNewMinMax = Perspective::UseNewMinMax(Perspective::Pointer(this)); bool hideEditorArea = shouldHideEditorsOnActivate || (editorHidden && editorHolder == 0); // We have to set the editor area's stack state -before- // activating the presentation since it's used there to determine // size of the resulting stack if (useNewMinMax && !hideEditorArea) { this->RefreshEditorAreaVisibility(); } // Show the layout presentation->Activate(this->GetClientComposite()); // if (useNewMinMax) // { // fastViewManager.activate(); // // // Move any minimized extension stacks to the trim // if (layout != 0) // { // // Turn aimations off // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // bool useAnimations = preferenceStore // .getbool(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS); // preferenceStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, false); // // List minStacks = layout.getMinimizedStacks(); // for (Iterator msIter = minStacks.iterator(); msIter.hasNext();) // { // ViewStack vs = (ViewStack) msIter.next(); // vs.setMinimized(true); // } // // // Restore the animation pref // preferenceStore.setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, useAnimations); // // // this is a one-off deal...set during the extension reading // minStacks.clear(); // layout = 0; // } // } // else // { // // Update the FVB only if not using the new min/max // // // WorkbenchWindow wbw = (WorkbenchWindow) page.getWorkbenchWindow(); //// if (wbw != 0) //// { //// ITrimManager tbm = wbw.getTrimManager(); //// if (tbm != 0) //// { //// IWindowTrim fvb = tbm.getTrim(FastViewBar.FASTVIEWBAR_ID); //// if (fvb instanceof FastViewBar) //// { //// ((FastViewBar)fvb).update(true); //// } //// } //// } // } // // If we are -not- using the new min/max then ensure that there // // are no stacks in the trim. This can happen when a user switches // // back to the 3.0 presentation... // if (!Perspective.useNewMinMax(this) && fastViewManager != 0) // { // bool stacksWereRestored = fastViewManager.restoreAllTrimStacks(); // setEditorAreaTrimVisibility(false); // // // Restore any 'maximized' view stack since we've restored // // the minimized stacks // if (stacksWereRestored && presentation.getMaximizedStack().Cast() != 0) // { // ViewStack vs = (ViewStack) presentation.getMaximizedStack(); // vs.setPresentationState(IStackPresentationSite.STATE_RESTORED); // presentation.setMaximizedStack(0); // } // } // We hide the editor area -after- the presentation activates if (hideEditorArea) { // We do this here to ensure that createPartControl is called on the // top editor // before it is hidden. See bug 20166. this->HideEditorArea(); shouldHideEditorsOnActivate = false; // // this is an override so it should handle both states // if (useNewMinMax) // setEditorAreaTrimVisibility(editorAreaState == IStackPresentationSite.STATE_MINIMIZED); } + // Fix perspectives whose contributing bundle has gone away FixOrphan(); } void Perspective::FixOrphan() { PerspectiveRegistry* reg = static_cast(PlatformUI::GetWorkbench()->GetPerspectiveRegistry()); IPerspectiveDescriptor::Pointer regDesc = reg->FindPerspectiveWithId(descriptor->GetId()); if (regDesc.IsNull()) { QString msg = "Perspective " + descriptor->GetLabel() + " has been made into a local copy"; IStatus::Pointer status = StatusUtil::NewStatus(IStatus::WARNING_TYPE, msg, BERRY_STATUS_LOC); //StatusManager.getManager().handle(status, StatusManager.LOG); WorkbenchPlugin::Log(status); QString localCopyLabel("<%1>"); QString newDescId = localCopyLabel.arg(descriptor->GetLabel()); while (reg->FindPerspectiveWithId(newDescId).IsNotNull()) { newDescId = localCopyLabel.arg(newDescId); } IPerspectiveDescriptor::Pointer newDesc = reg->CreatePerspective(newDescId, descriptor); page->SavePerspectiveAs(newDesc); } } void Perspective::OnDeactivate() { presentation->Deactivate(); //setActiveFastView(0); //setAllPinsVisible(false); // // Update fast views. // if (fastViewManager != 0) // { // List fastViews = fastViewManager.getFastViews(0); // for (int i = 0; i < fastViews.size(); i++) // { // ViewPane pane = getPane((IViewReference) fastViews.get(i)); // if (pane != 0) // { // Control ctrl = pane.getControl(); // if (ctrl != 0) // { // ctrl.setEnabled(true); // Add focus support. // } // } // } // // fastViewManager.deActivate(); // } // // // Ensure that the editor area trim is hidden as well // setEditorAreaTrimVisibility(false); } void Perspective::PartActivated(IWorkbenchPart::Pointer /*activePart*/) { // // If a fastview is open close it. // if (activeFastView != 0 // && activeFastView.getPart(false) != activePart) // { // setActiveFastView(0); // } } void Perspective::PerformedShowIn(const QString& /*partId*/) { //showInTimes.insert(std::make_pair(partId, new Long(System.currentTimeMillis()))); } bool Perspective::RestoreState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsRestoringPerspective, 0); bool result = true; // Create persp descriptor. descriptor = new PerspectiveDescriptor("", "", PerspectiveDescriptor::Pointer(0)); //result.add(descriptor.restoreState(memento)); result &= descriptor->RestoreState(memento); PerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()-> GetPerspectiveRegistry()->FindPerspectiveWithId(descriptor->GetId()).Cast(); if (desc) { descriptor = desc; } - else - { - try - { - WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->CreatePerspective(descriptor->GetLabel(), descriptor.Cast()); - } - catch (...) - { - std::cout << "Perspective could not be loaded" << std::endl; - } - } this->memento = memento; // Add the visible views. QList views(memento->GetChildren(WorkbenchConstants::TAG_VIEW)); //result.merge(createReferences(views)); result &= this->CreateReferences(views); memento = memento->GetChild(WorkbenchConstants::TAG_FAST_VIEWS); if (memento) { views = memento->GetChildren(WorkbenchConstants::TAG_VIEW); //result.merge(createReferences(views)); result &= this->CreateReferences(views); } return result; } bool Perspective::CreateReferences(const QList& views) { // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.Perspective_problemsRestoringViews, 0); bool result = true; for (int x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; QString id; childMem->GetString(WorkbenchConstants::TAG_ID, id); // skip creation of the intro reference - it's handled elsewhere. if (id == IntroConstants::INTRO_VIEW_ID) { continue; } QString secondaryId(ViewFactory::ExtractSecondaryId(id)); if (!secondaryId.isEmpty()) { id = ViewFactory::ExtractPrimaryId(id); } // Create and open the view. try { QString rm; childMem->GetString(WorkbenchConstants::TAG_REMOVED, rm); if (rm != "true") { viewFactory->CreateView(id, secondaryId); } } catch (const PartInitException& e) { childMem->PutString(WorkbenchConstants::TAG_REMOVED, "true"); // result.add(StatusUtil.newStatus(IStatus.ERR, // e.getMessage() == 0 ? "" : e.getMessage(), //$NON-NLS-1$ // e)); WorkbenchPlugin::Log(e.what(), e); result &= true; } } return result; } bool Perspective::RestoreState() { if (this->memento == 0) { //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", 0); //$NON-NLS-1$ return true; } // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsRestoringPerspective, 0); bool result = true; IMemento::Pointer memento = this->memento; this->memento = 0; const IMemento::Pointer boundsMem(memento->GetChild(WorkbenchConstants::TAG_WINDOW)); if (boundsMem) { int x, y, w, h; boundsMem->GetInteger(WorkbenchConstants::TAG_X, x); boundsMem->GetInteger(WorkbenchConstants::TAG_Y, y); boundsMem->GetInteger(WorkbenchConstants::TAG_HEIGHT, h); boundsMem->GetInteger(WorkbenchConstants::TAG_WIDTH, w); QRect r(x, y, w, h); //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { if (page->GetWorkbenchWindow()->GetActivePage() == 0) { page->GetWorkbenchWindow()->GetShell()->SetBounds(r); } // } // }); } // Create an empty presentation.. PerspectiveHelper* pres; //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { ViewSashContainer::Pointer mainLayout(new ViewSashContainer(page, this->GetClientComposite())); pres = new PerspectiveHelper(page, mainLayout, this); // }}); // Read the layout. // result.merge(pres.restoreState(memento // .getChild(IWorkbenchConstants.TAG_LAYOUT))); result &= pres->RestoreState(memento->GetChild(WorkbenchConstants::TAG_LAYOUT)); //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // Add the editor workbook. Do not hide it now. pres->ReplacePlaceholderWithPart(editorArea); // }}); // Add the visible views. QList views(memento->GetChildren(WorkbenchConstants::TAG_VIEW)); for (int x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; QString id; childMem->GetString(WorkbenchConstants::TAG_ID, id); QString secondaryId(ViewFactory::ExtractSecondaryId(id)); if (!secondaryId.isEmpty()) { id = ViewFactory::ExtractPrimaryId(id); } // skip the intro as it is restored higher up in workbench. if (id == IntroConstants::INTRO_VIEW_ID) { continue; } // Create and open the view. IViewReference::Pointer viewRef = viewFactory->GetView(id, secondaryId); WorkbenchPartReference::Pointer ref = viewRef.Cast(); // report error if (ref == 0) { QString key = ViewFactory::GetKey(id, secondaryId); // result.add(new Status(IStatus.ERR, PlatformUI.PLUGIN_ID, 0, // NLS.bind(WorkbenchMessages.Perspective_couldNotFind, key ), 0)); WorkbenchPlugin::Log("Could not find view: " + key); continue; } bool willPartBeVisible = pres->WillPartBeVisible(ref->GetId(), secondaryId); if (willPartBeVisible) { IViewPart::Pointer view = ref->GetPart(true).Cast(); if (view) { ViewSite::Pointer site = view->GetSite().Cast(); pres->ReplacePlaceholderWithPart(site->GetPane().Cast()); } } else { pres->ReplacePlaceholderWithPart(ref->GetPane()); } } // // Load the fast views // if (fastViewManager != 0) // fastViewManager.restoreState(memento, result); // Load the view layout recs QList recMementos(memento ->GetChildren(WorkbenchConstants::TAG_VIEW_LAYOUT_REC)); for (int i = 0; i < recMementos.size(); i++) { IMemento::Pointer recMemento = recMementos[i]; QString compoundId; if (recMemento->GetString(WorkbenchConstants::TAG_ID, compoundId)) { ViewLayoutRec::Pointer rec = GetViewLayoutRec(compoundId, true); QString closeablestr; recMemento->GetString(WorkbenchConstants::TAG_CLOSEABLE, closeablestr); if (WorkbenchConstants::FALSE_VAL == closeablestr) { rec->isCloseable = false; } QString moveablestr; recMemento->GetString(WorkbenchConstants::TAG_MOVEABLE, moveablestr); if (WorkbenchConstants::FALSE_VAL == moveablestr) { rec->isMoveable = false; } QString standalonestr; recMemento->GetString(WorkbenchConstants::TAG_STANDALONE, standalonestr); if (WorkbenchConstants::TRUE_VAL == standalonestr) { rec->isStandalone = true; QString showstr; recMemento->GetString(WorkbenchConstants::TAG_SHOW_TITLE, showstr); rec->showTitle = WorkbenchConstants::FALSE_VAL != showstr; } } } //final IContextService service = (IContextService)page.getWorkbenchWindow().getService(IContextService.class); try { // one big try block, don't kill me here // // defer context events // if (service != 0) // { // service.activateContext(ContextAuthority.DEFER_EVENTS); // } // // HashSet knownActionSetIds = new HashSet(); // // // Load the always on action sets. QList actions; // = memento // .getChildren(IWorkbenchConstants.TAG_ALWAYS_ON_ACTION_SET); // for (int x = 0; x < actions.length; x++) // { // String actionSetID = actions[x] // .getString(IWorkbenchConstants.TAG_ID); // final IActionSetDescriptor d = WorkbenchPlugin.getDefault() // .getActionSetRegistry().findActionSet(actionSetID); // if (d != 0) // { // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // addAlwaysOn(d); // } // }); // // knownActionSetIds.add(actionSetID); // } // } // // // Load the always off action sets. // actions = memento // .getChildren(IWorkbenchConstants.TAG_ALWAYS_OFF_ACTION_SET); // for (int x = 0; x < actions.length; x++) // { // String actionSetID = actions[x] // .getString(IWorkbenchConstants.TAG_ID); // final IActionSetDescriptor d = WorkbenchPlugin.getDefault() // .getActionSetRegistry().findActionSet(actionSetID); // if (d != 0) // { // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // addAlwaysOff(d); // } // }); // knownActionSetIds.add(actionSetID); // } // } // Load "show view actions". actions = memento->GetChildren(WorkbenchConstants::TAG_SHOW_VIEW_ACTION); for (int x = 0; x < actions.size(); x++) { QString id; actions[x]->GetString(WorkbenchConstants::TAG_ID, id); showViewShortcuts.push_back(id); } // // Load "show in times". // actions = memento.getChildren(IWorkbenchConstants.TAG_SHOW_IN_TIME); // for (int x = 0; x < actions.length; x++) // { // String id = actions[x].getString(IWorkbenchConstants.TAG_ID); // String timeStr = actions[x] // .getString(IWorkbenchConstants.TAG_TIME); // if (id != 0 && timeStr != 0) // { // try // { // long time = Long.parseLong(timeStr); // showInTimes.put(id, new Long(time)); // } // catch (NumberFormatException e) // { // // skip this one // } // } // } // Load "show in parts" from registry, not memento showInPartIds = this->GetShowInIdsFromRegistry(); // // Load "new wizard actions". // actions = memento // .getChildren(IWorkbenchConstants.TAG_NEW_WIZARD_ACTION); // newWizardShortcuts = new ArrayList(actions.length); // for (int x = 0; x < actions.length; x++) // { // String id = actions[x].getString(IWorkbenchConstants.TAG_ID); // newWizardShortcuts.add(id); // } // Load "perspective actions". actions = memento->GetChildren(WorkbenchConstants::TAG_PERSPECTIVE_ACTION); for (int x = 0; x < actions.size(); x++) { QString id; actions[x]->GetString(WorkbenchConstants::TAG_ID, id); perspectiveShortcuts.push_back(id); } // ArrayList extActionSets = getPerspectiveExtensionActionSets(); // for (int i = 0; i < extActionSets.size(); i++) // { // String actionSetID = (String) extActionSets.get(i); // if (knownActionSetIds.contains(actionSetID)) // { // continue; // } // final IActionSetDescriptor d = WorkbenchPlugin.getDefault() // .getActionSetRegistry().findActionSet(actionSetID); // if (d != 0) // { // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // addAlwaysOn(d); // } // }); // knownActionSetIds.add(d.getId()); // } // } // // Add the visible set of action sets to our knownActionSetIds // // Now go through the registry to ensure we pick up any new action // // sets // // that have been added but not yet considered by this perspective. // ActionSetRegistry reg = WorkbenchPlugin.getDefault() // .getActionSetRegistry(); // IActionSetDescriptor[] array = reg.getActionSets(); // int count = array.length; // for (int i = 0; i < count; i++) // { // IActionSetDescriptor desc = array[i]; // if ((!knownActionSetIds.contains(desc.getId())) // && (desc.isInitiallyVisible())) // { // addActionSet(desc); // } // } } catch (...) { // // restart context changes // if (service != 0) // { // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { // service.activateContext(ContextAuthority.SEND_EVENTS); // } // }); // } } // Save presentation. presentation = pres; // Hide the editor area if needed. Need to wait for the // presentation to be fully setup first. int areaVisible = 0; bool areaVisibleExists = memento->GetInteger(WorkbenchConstants::TAG_AREA_VISIBLE, areaVisible); // Rather than hiding the editors now we must wait until after their // controls // are created. This ensures that if an editor is instantiated, // createPartControl // is also called. See bug 20166. shouldHideEditorsOnActivate = (areaVisibleExists && areaVisible == 0); // // Restore the trim state of the editor area // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); // if (useNewMinMax) // { // Integer trimStateInt = memento.getInteger(IWorkbenchConstants.TAG_AREA_TRIM_STATE); // if (trimStateInt != 0) // { // editorAreaState = trimStateInt.intValue() & 0x3; // low order two bits contain the state // editorAreaRestoreOnUnzoom = (trimStateInt.intValue() & 4) != 0; // } // } // restore the fixed state int isFixed = 0; fixed = (memento->GetInteger(WorkbenchConstants::TAG_FIXED, isFixed) && isFixed == 1); return true; } QList Perspective::GetShowInIdsFromRegistry() { PerspectiveExtensionReader reader; QList tags; tags.push_back(WorkbenchRegistryConstants::TAG_SHOW_IN_PART); reader.SetIncludeOnlyTags(tags); PageLayout::Pointer layout(new PageLayout()); - reader.ExtendLayout(descriptor->GetOriginalId(), layout); + reader.ExtendLayout(nullptr, descriptor->GetOriginalId(), layout); return layout->GetShowInPartIds(); } void Perspective::SaveDesc() { this->SaveDescAs(descriptor); } -void Perspective::SaveDescAs(IPerspectiveDescriptor::Pointer /*desc*/) +void Perspective::SaveDescAs(IPerspectiveDescriptor::Pointer desc) { - //TODO Perspective SaveDescAs -// PerspectiveDescriptor::Pointer realDesc = desc.Cast(); -// //get the layout from the registry -// PerspectiveRegistry* perspRegistry = dynamic_cast(WorkbenchPlugin -// ::GetDefault()->GetPerspectiveRegistry()); -// // Capture the layout state. -// XMLMemento memento = XMLMemento.createWriteRoot("perspective");//$NON-NLS-1$ -// IStatus status = saveState(memento, realDesc, false); -// if (status.getSeverity() == IStatus.ERR) + PerspectiveDescriptor::Pointer realDesc = desc.Cast(); + //get the layout from the registry + PerspectiveRegistry* perspRegistry = dynamic_cast( + WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()); + // Capture the layout state. + XMLMemento::Pointer memento = XMLMemento::CreateWriteRoot("perspective"); + //IStatus::Pointer status = SaveState(memento, realDesc, false); +// if (status->GetSeverity() == IStatus::ERROR_TYPE) // { -// ErrorDialog.openError((Shell) 0, WorkbenchMessages.Perspective_problemSavingTitle, -// WorkbenchMessages.Perspective_problemSavingMessage, +// ErrorDialog.openError((Shell) 0, "Saving Problems", +// "Unable to store layout state.", // status); // return; // } -// //save it to the preference store -// try -// { -// perspRegistry.saveCustomPersp(realDesc, memento); -// descriptor = realDesc; -// } -// catch (IOException e) -// { -// perspRegistry.deletePerspective(realDesc); -// MessageDialog.openError((Shell) 0, WorkbenchMessages.Perspective_problemSavingTitle, -// WorkbenchMessages.Perspective_problemSavingMessage); -// } + bool status = SaveState(memento, realDesc, false); + if (!status) + { + QMessageBox::critical(nullptr, "Saving Problems", "Unable to store layout state."); + return; + } + + //save it to the preference store + try + { + perspRegistry->SaveCustomPersp(realDesc, memento.GetPointer()); + descriptor = realDesc; + } + catch (const std::exception& /*e*/) + { + perspRegistry->DeletePerspective(realDesc); + QMessageBox::critical(nullptr, "Saving Problems", "Unable to store layout state."); + } } bool Perspective::SaveState(IMemento::Pointer memento) { -// MultiStatus result = new MultiStatus( -// PlatformUI.PLUGIN_ID, -// IStatus.OK, -// WorkbenchMessages.Perspective_problemsSavingPerspective, 0); -// -// result.merge(saveState(memento, descriptor, true)); +// MultiStatus::Pointer result(new MultiStatus( +// PlatformUI::PLUGIN_ID(), +// IStatus::OK_TYPE, +// "Problems occurred saving perspective.", +// BERRY_STATUS_LOC)); +// result->Merge(SaveState(memento, descriptor, true)); bool result = true; result &= this->SaveState(memento, descriptor, true); return result; } bool Perspective::SaveState(IMemento::Pointer memento, PerspectiveDescriptor::Pointer p, bool saveInnerViewState) { -// MultiStatus result = new MultiStatus( -// PlatformUI.PLUGIN_ID, -// IStatus.OK, -// WorkbenchMessages.Perspective_problemsSavingPerspective, 0); +// MultiStatus::Pointer result(new MultiStatus( +// PlatformUI::PLUGIN_ID(), +// IStatus::OK_TYPE, +// "Problems occurred saving perspective.", +// BERRY_STATUS_LOC)); bool result = true; if (this->memento) { memento->PutMemento(this->memento); return result; } // Save the version number. memento->PutString(WorkbenchConstants::TAG_VERSION, VERSION_STRING); //result.add(p.saveState(memento)); result &= p->SaveState(memento); if (!saveInnerViewState) { QRect bounds(page->GetWorkbenchWindow()->GetShell()->GetBounds()); IMemento::Pointer boundsMem = memento ->CreateChild(WorkbenchConstants::TAG_WINDOW); boundsMem->PutInteger(WorkbenchConstants::TAG_X, bounds.x()); boundsMem->PutInteger(WorkbenchConstants::TAG_Y, bounds.y()); boundsMem->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height()); boundsMem->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width()); } // // Save the "always on" action sets. // Iterator itr = alwaysOnActionSets.iterator(); // while (itr.hasNext()) // { // IActionSetDescriptor desc = (IActionSetDescriptor) itr.next(); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_ALWAYS_ON_ACTION_SET); // child.putString(IWorkbenchConstants.TAG_ID, desc.getId()); // } // // Save the "always off" action sets. // itr = alwaysOffActionSets.iterator(); // while (itr.hasNext()) // { // IActionSetDescriptor desc = (IActionSetDescriptor) itr.next(); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_ALWAYS_OFF_ACTION_SET); // child.putString(IWorkbenchConstants.TAG_ID, desc.getId()); // } // Save "show view actions" for (QList::iterator itr = showViewShortcuts.begin(); itr != showViewShortcuts.end(); ++itr) { IMemento::Pointer child = memento ->CreateChild(WorkbenchConstants::TAG_SHOW_VIEW_ACTION); child->PutString(WorkbenchConstants::TAG_ID, *itr); } // // Save "show in times" // itr = showInTimes.keySet().iterator(); // while (itr.hasNext()) // { // String id = (String) itr.next(); // Long time = (Long) showInTimes.get(id); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_SHOW_IN_TIME); // child.putString(IWorkbenchConstants.TAG_ID, id); // child.putString(IWorkbenchConstants.TAG_TIME, time.toString()); // } // // Save "new wizard actions". // itr = newWizardShortcuts.iterator(); // while (itr.hasNext()) // { // String str = (String) itr.next(); // IMemento child = memento // .createChild(IWorkbenchConstants.TAG_NEW_WIZARD_ACTION); // child.putString(IWorkbenchConstants.TAG_ID, str); // } // Save "perspective actions". for (QList::iterator itr = perspectiveShortcuts.begin(); itr != perspectiveShortcuts.end(); ++itr) { IMemento::Pointer child = memento ->CreateChild(WorkbenchConstants::TAG_PERSPECTIVE_ACTION); child->PutString(WorkbenchConstants::TAG_ID, *itr); } // Get visible views. QList viewPanes; presentation->CollectViewPanes(viewPanes); // Save the views. for (QList::iterator itr = viewPanes.begin(); itr != viewPanes.end(); ++itr) { IWorkbenchPartReference::Pointer ref((*itr)->GetPartReference()); IViewDescriptor::Pointer desc = page->GetViewFactory()->GetViewRegistry() ->Find(ref->GetId()); if(desc && desc->IsRestorable()) { IMemento::Pointer viewMemento = memento ->CreateChild(WorkbenchConstants::TAG_VIEW); viewMemento->PutString(WorkbenchConstants::TAG_ID, ViewFactory::GetKey(ref.Cast())); } } // // save all fastview state // if (fastViewManager != 0) // fastViewManager.saveState(memento); // Save the view layout recs. for (QHash::iterator i = mapIDtoViewLayoutRec.begin(); i != mapIDtoViewLayoutRec.end(); ++i) { QString compoundId(i.key()); ViewLayoutRec::Pointer rec(i.value()); if (rec && (!rec->isCloseable || !rec->isMoveable || rec->isStandalone)) { IMemento::Pointer layoutMemento(memento ->CreateChild(WorkbenchConstants::TAG_VIEW_LAYOUT_REC)); layoutMemento->PutString(WorkbenchConstants::TAG_ID, compoundId); if (!rec->isCloseable) { layoutMemento->PutString(WorkbenchConstants::TAG_CLOSEABLE, WorkbenchConstants::FALSE_VAL); } if (!rec->isMoveable) { layoutMemento->PutString(WorkbenchConstants::TAG_MOVEABLE, WorkbenchConstants::FALSE_VAL); } if (rec->isStandalone) { layoutMemento->PutString(WorkbenchConstants::TAG_STANDALONE, WorkbenchConstants::TRUE_VAL); layoutMemento->PutString(WorkbenchConstants::TAG_SHOW_TITLE, rec->showTitle ? WorkbenchConstants::TRUE_VAL : WorkbenchConstants::FALSE_VAL); } } } // Save the layout. IMemento::Pointer childMem(memento->CreateChild(WorkbenchConstants::TAG_LAYOUT)); - //result.add(presentation.saveState(childMem)); + //result->Add(presentation->SaveState(childMem)); result &= presentation->SaveState(childMem); // Save the editor visibility state if (this->IsEditorAreaVisible()) { memento->PutInteger(WorkbenchConstants::TAG_AREA_VISIBLE, 1); } else { memento->PutInteger(WorkbenchConstants::TAG_AREA_VISIBLE, 0); } // // Save the trim state of the editor area if using the new min/max // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); // if (useNewMinMax) // { // int trimState = editorAreaState; // trimState |= editorAreaRestoreOnUnzoom ? 4 : 0; // memento.putInteger(IWorkbenchConstants.TAG_AREA_TRIM_STATE, trimState); // } // Save the fixed state if (fixed) { memento->PutInteger(WorkbenchConstants::TAG_FIXED, 1); } else { memento->PutInteger(WorkbenchConstants::TAG_FIXED, 0); } return result; } void Perspective::SetPerspectiveActionIds(const QList& list) { perspectiveShortcuts = list; } void Perspective::SetShowInPartIds(const QList& list) { showInPartIds = list; } void Perspective::SetShowViewActionIds(const QList& list) { showViewShortcuts = list; } void Perspective::ShowEditorArea() { if (this->IsEditorAreaVisible()) { return; } editorHidden = false; // Show the editor in the appropriate location if (this->UseNewMinMax(Perspective::Pointer(this))) { bool isMinimized = editorAreaState == IStackPresentationSite::STATE_MINIMIZED; if (!isMinimized) { // If the editor area is going to show then we have to restore // if (getPresentation().getMaximizedStack() != 0) // getPresentation().getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); this->ShowEditorAreaLocal(); } // else // setEditorAreaTrimVisibility(true); } else { this->ShowEditorAreaLocal(); } } void Perspective::ShowEditorAreaLocal() { if (editorHolder == 0 || editorHidden) { return; } // Replace the part holder with the editor area. presentation->GetLayout()->Replace(editorHolder, editorArea); editorHolder = 0; } void Perspective::SetEditorAreaState(int newState) { if (newState == editorAreaState) return; editorAreaState = newState; // // reset the restore flag if we're not minimized // if (newState != IStackPresentationSite::STATE_MINIMIZED) // editorAreaRestoreOnUnzoom = false; this->RefreshEditorAreaVisibility(); } int Perspective::GetEditorAreaState() { return editorAreaState; } void Perspective::RefreshEditorAreaVisibility() { // Nothing shows up if the editor area isn't visible at all if (editorHidden) { this->HideEditorAreaLocal(); //setEditorAreaTrimVisibility(false); return; } PartStack::Pointer editorStack = editorArea.Cast()->GetUpperRightEditorStack(); if (editorStack == 0) return; // Whatever we're doing, make the current editor stack match it //editorStack->SetStateLocal(editorAreaState); // If it's minimized then it's in the trim if (editorAreaState == IStackPresentationSite::STATE_MINIMIZED) { // Hide the editor area and show its trim this->HideEditorAreaLocal(); //setEditorAreaTrimVisibility(true); } else { // Show the editor area and hide its trim //setEditorAreaTrimVisibility(false); this->ShowEditorAreaLocal(); // if (editorAreaState == IStackPresentationSite::STATE_MAXIMIZED) // getPresentation().setMaximizedStack(editorStack); } } IViewReference::Pointer Perspective::GetViewReference(const QString& viewId, const QString& secondaryId) { IViewReference::Pointer ref = page->FindViewReference(viewId, secondaryId); if (ref == 0) { ViewFactory* factory = this->GetViewFactory(); try { ref = factory->CreateView(viewId, secondaryId); } catch (PartInitException& /*e*/) { // IStatus status = StatusUtil.newStatus(IStatus.ERR, // e.getMessage() == 0 ? "" : e.getMessage(), //$NON-NLS-1$ // e); // StatusUtil.handleStatus(status, "Failed to create view: id=" + viewId, //$NON-NLS-1$ // StatusManager.LOG); //TODO Perspective status message WorkbenchPlugin::Log("Failed to create view: id=" + viewId); } } return ref; } IViewPart::Pointer Perspective::ShowView(const QString& viewId, const QString& secondaryId) { ViewFactory* factory = this->GetViewFactory(); IViewReference::Pointer ref = factory->CreateView(viewId, secondaryId); IViewPart::Pointer part = ref->GetPart(true).Cast(); if (part == 0) { throw PartInitException("Could not create view: " + ref->GetId()); } PartSite::Pointer site = part->GetSite().Cast(); PartPane::Pointer pane = site->GetPane(); //TODO Perspective preference store // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // int openViewMode = store.getInt(IPreferenceConstants.OPEN_VIEW_MODE); // // if (openViewMode == IPreferenceConstants.OVM_FAST && // fastViewManager != 0) // { // fastViewManager.addViewReference(FastViewBar.FASTVIEWBAR_ID, -1, ref, true); // setActiveFastView(ref); // } // else if (openViewMode == IPreferenceConstants.OVM_FLOAT // && presentation.canDetach()) // { // presentation.addDetachedPart(pane); // } // else // { if (this->UseNewMinMax(Perspective::Pointer(this))) { // Is this view going to show in the trim? // LayoutPart vPart = presentation.findPart(viewId, secondaryId); // Determine if there is a trim stack that should get the view QString trimId; // // If we can locate the correct trim stack then do so // if (vPart != 0) // { // String id = 0; // ILayoutContainer container = vPart.getContainer(); // if (container.Cast() != 0) // id = ((ContainerPlaceholder)container).getID(); // else if (container.Cast() != 0) // id = ((ViewStack)container).getID(); // // // Is this place-holder in the trim? // if (id != 0 && fastViewManager.getFastViews(id).size()> 0) // { // trimId = id; // } // } // // // No explicit trim found; If we're maximized then we either have to find an // // arbitrary stack... // if (trimId == 0 && presentation.getMaximizedStack() != 0) // { // if (vPart == 0) // { // ViewStackTrimToolBar blTrimStack = fastViewManager.getBottomRightTrimStack(); // if (blTrimStack != 0) // { // // OK, we've found a trim stack to add it to... // trimId = blTrimStack.getId(); // // // Since there was no placeholder we have to add one // LayoutPart blPart = presentation.findPart(trimId, 0); // if (blPart.Cast() != 0) // { // ContainerPlaceholder cph = (ContainerPlaceholder) blPart; // if (cph.getRealContainer().Cast() != 0) // { // ViewStack vs = (ViewStack) cph.getRealContainer(); // // // Create a 'compound' id if this is a multi-instance part // String compoundId = ref.getId(); // if (ref.getSecondaryId() != 0) // compoundId = compoundId + ':' + ref.getSecondaryId(); // // // Add the new placeholder // vs.add(new PartPlaceholder(compoundId)); // } // } // } // } // } // // // If we have a trim stack located then add the view to it // if (trimId != "") // { // fastViewManager.addViewReference(trimId, -1, ref, true); // } // else // { // bool inMaximizedStack = vPart != 0 && vPart.getContainer() == presentation.getMaximizedStack(); // Do the default behavior presentation->AddPart(pane); // // Now, if we're maximized then we have to minimize the new stack // if (presentation.getMaximizedStack() != 0 && !inMaximizedStack) // { // vPart = presentation.findPart(viewId, secondaryId); // if (vPart != 0 && vPart.getContainer().Cast() != 0) // { // ViewStack vs = (ViewStack)vPart.getContainer(); // vs.setState(IStackPresentationSite.STATE_MINIMIZED); // // // setting the state to minimized will create the trim toolbar // // so we don't need a 0 pointer check here... // fastViewManager.getViewStackTrimToolbar(vs.getID()).setRestoreOnUnzoom(true); // } // } // } } else { presentation->AddPart(pane); } //} // Ensure that the newly showing part is enabled if (pane != 0 && pane->GetControl() != 0) Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(pane->GetControl(), true); return part; } IWorkbenchPartReference::Pointer Perspective::GetOldPartRef() { return oldPartRef; } void Perspective::SetOldPartRef(IWorkbenchPartReference::Pointer oldPartRef) { this->oldPartRef = oldPartRef; } bool Perspective::IsCloseable(IViewReference::Pointer reference) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(reference, false); if (rec != 0) { return rec->isCloseable; } return true; } bool Perspective::IsMoveable(IViewReference::Pointer reference) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(reference, false); if (rec != 0) { return rec->isMoveable; } return true; } void Perspective::DescribeLayout(QString& buf) const { // QList fastViews = getFastViews(); // // if (fastViews.length != 0) // { // buf.append("fastviews ("); //$NON-NLS-1$ // for (int idx = 0; idx < fastViews.length; idx++) // { // IViewReference ref = fastViews[idx]; // // if (idx> 0) // { // buf.append(", "); //$NON-NLS-1$ // } // // buf.append(ref.getPartName()); // } // buf.append("), "); //$NON-NLS-1$ // } this->GetPresentation()->DescribeLayout(buf); } void Perspective::TestInvariants() { this->GetPresentation()->GetLayout()->TestInvariants(); } bool Perspective::UseNewMinMax(Perspective::Pointer activePerspective) { // We need to have an active perspective if (activePerspective == 0) return false; // We need to have a trim manager (if we don't then we // don't create a FastViewManager because it'd be useless) // if (activePerspective->GetFastViewManager() == 0) // return false; // Make sure we don't NPE anyplace WorkbenchWindow::Pointer wbw = activePerspective->page->GetWorkbenchWindow().Cast(); if (wbw == 0) return false; // WorkbenchWindowConfigurer* configurer = wbw->GetWindowConfigurer(); // if (configurer == 0) // return false; IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory(); if (factory == 0) return false; // Ok, we should be good to go, return the pref //IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); //bool useNewMinMax = preferenceStore.getbool(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); return true; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.h index 49d1c9a6de..053d73a014 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspective.h @@ -1,636 +1,637 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYPERSPECTIVE_H_ #define BERRYPERSPECTIVE_H_ #include #include "berryPerspectiveDescriptor.h" #include "berryPartPlaceholder.h" #include "berryViewLayoutRec.h" #include "berryWorkbenchPage.h" #include "berryLayoutPart.h" #include "berryPageLayout.h" #include "berryPartPane.h" #include "berryIWorkbenchPartReference.h" #include "berryIViewReference.h" #include "berryIViewPart.h" +#include "berryIStatus.h" namespace berry { class ViewFactory; class PerspectiveHelper; /** * \ingroup org_blueberry_ui_internal * */ class Perspective : public Object { public: berryObjectMacro(Perspective) friend class WorkbenchPage; bool ContainsView(const QString& viewId) const; private: ViewFactory* viewFactory; QHash mapIDtoViewLayoutRec; static const QString VERSION_STRING; // = "0.016"; /** * Reference to the part that was previously active * when this perspective was deactivated. */ IWorkbenchPartReference::Pointer oldPartRef; protected: PerspectiveDescriptor::Pointer descriptor; WorkbenchPage* page; // Editor Area management LayoutPart::Pointer editorArea; PartPlaceholder::Pointer editorHolder; bool editorHidden; int editorAreaState; //ArrayList alwaysOnActionSets; //ArrayList alwaysOffActionSets; QList showViewShortcuts; QList perspectiveShortcuts; bool fixed; QList showInPartIds; //HashMap showInTimes; IMemento::Pointer memento; PerspectiveHelper* presentation; bool shouldHideEditorsOnActivate; PageLayout::Pointer layout; /** * ViewManager constructor comment. */ public: Perspective(PerspectiveDescriptor::Pointer desc, WorkbenchPage::Pointer page); /** * ViewManager constructor comment. */ protected: Perspective(WorkbenchPage::Pointer page); protected: void Init(WorkbenchPage::Pointer page); /** * Moves a part forward in the Z order of a perspective so it is visible. * * @param part the part to bring to move forward * @return true if the part was brought to top, false if not. */ public: bool BringToTop(IViewReference::Pointer ref); /** * Returns whether a view exists within the perspective. */ public: bool ContainsView(IViewPart::Pointer view); /** * Create the initial list of action sets. */ // protected: void CreateInitialActionSets(List outputList, List stringList) { // ActionSetRegistry reg = WorkbenchPlugin.getDefault() // .getActionSetRegistry(); // Iterator iter = stringList.iterator(); // while (iter.hasNext()) { // String id = (String) iter.next(); // IActionSetDescriptor desc = reg.findActionSet(id); // if (desc != null) { // outputList.add(desc); // } else { // WorkbenchPlugin.log("Unable to find Action Set: " + id);//$NON-NLS-1$ // } // } // } /** * Create a presentation for a perspective. */ private: void CreatePresentation(PerspectiveDescriptor::Pointer persp); /** * Dispose the perspective and all views contained within. */ public: ~Perspective(); private: void DisposeViewRefs(); /** * Finds the view with the given ID that is open in this page, or null * if not found. * * @param viewId the view ID */ public: IViewReference::Pointer FindView(const QString& viewId); /** * Finds the view with the given id and secondary id that is open in this page, * or null if not found. * * @param viewId the view ID * @param secondaryId the secondary ID */ public: IViewReference::Pointer FindView(const QString& id, const QString& secondaryId); /** * Returns the window's client composite widget * which views and editor area will be parented. */ public: QWidget* GetClientComposite(); /** * Returns the perspective. */ public: IPerspectiveDescriptor::Pointer GetDesc(); /** * Returns the pane for a view reference. */ protected: PartPane::Pointer GetPane(IViewReference::Pointer ref); /** * Returns the perspective shortcuts associated with this perspective. * * @return an array of perspective identifiers */ public: QList GetPerspectiveShortcuts(); /** * Returns the presentation. */ public: PerspectiveHelper* GetPresentation() const; /** * Returns the show view shortcuts associated with this perspective. * * @return an array of view identifiers */ public: QList GetShowViewShortcuts(); /** * Returns the view factory. */ public: ViewFactory* GetViewFactory(); /** * See IWorkbenchPage. */ public: QList GetViewReferences(); /** * Hide the editor area if visible */ protected: void HideEditorArea(); /** * Hide the editor area if visible */ protected: void HideEditorAreaLocal(); public: bool HideView(IViewReference::Pointer ref); /* * Return whether the editor area is visible or not. */ protected: bool IsEditorAreaVisible(); /** * Returns the view layout rec for the given view reference, * or null if not found. If create is true, it creates the record * if not already created. */ public: ViewLayoutRec::Pointer GetViewLayoutRec(IViewReference::Pointer ref, bool create); /** * Returns the view layout record for the given view id * or null if not found. If create is true, it creates the record * if not already created. */ private: ViewLayoutRec::Pointer GetViewLayoutRec(const QString& viewId, bool create); /** * Returns true if a layout or perspective is fixed. */ public: bool IsFixedLayout(); /** * Returns true if a view is standalone. * * @since 3.0 */ public: bool IsStandaloneView(IViewReference::Pointer ref); /** * Returns whether the title for a view should * be shown. This applies only to standalone views. * * @since 3.0 */ public: bool GetShowTitleView(IViewReference::Pointer ref); /** * Creates a new presentation from a persistence file. * Note: This method should not modify the current state of the perspective. */ private: void LoadCustomPersp(PerspectiveDescriptor::Pointer persp); private: void UnableToOpenPerspective(PerspectiveDescriptor::Pointer persp, const QString& status); /** * Create a presentation for a perspective. * Note: This method should not modify the current state of the perspective. */ protected: void LoadPredefinedPersp(PerspectiveDescriptor::Pointer persp); // private: void RemoveAlwaysOn(IActionSetDescriptor::Pointer descriptor) { // if (descriptor == null) { // return; // } // if (!alwaysOnActionSets.contains(descriptor)) { // return; // } // // alwaysOnActionSets.remove(descriptor); // if (page != null) { // page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_HIDE); // } // } // protected: void AddAlwaysOff(IActionSetDescriptor descriptor) { // if (descriptor == null) { // return; // } // if (alwaysOffActionSets.contains(descriptor)) { // return; // } // alwaysOffActionSets.add(descriptor); // if (page != null) { // page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_MASK); // } // removeAlwaysOn(descriptor); // } // protected: void AddAlwaysOn(IActionSetDescriptor descriptor) { // if (descriptor == null) { // return; // } // if (alwaysOnActionSets.contains(descriptor)) { // return; // } // alwaysOnActionSets.add(descriptor); // if (page != null) { // page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_SHOW); // } // removeAlwaysOff(descriptor); // } // private: void RemoveAlwaysOff(IActionSetDescriptor descriptor) { // if (descriptor == null) { // return; // } // if (!alwaysOffActionSets.contains(descriptor)) { // return; // } // alwaysOffActionSets.remove(descriptor); // if (page != null) { // page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_UNMASK); // } // } /** * activate. */ protected: void OnActivate(); private: /** * An 'orphan' perspective is one that was originally created through a * contribution but whose contributing bundle is no longer available. In * order to allow it to behave correctly within the environment (for Close, * Reset...) we turn it into a 'custom' perspective on its first activation. */ void FixOrphan(); /** * deactivate. */ protected: void OnDeactivate(); /** * Notifies that a part has been activated. */ public: void PartActivated(IWorkbenchPart::Pointer activePart); /** * The user successfully performed a Show In... action on the specified part. * Update the history. */ public: void PerformedShowIn(const QString& partId); /** * Fills a presentation with layout data. * Note: This method should not modify the current state of the perspective. */ public: bool RestoreState(IMemento::Pointer memento); bool CreateReferences(const QList& views); /** * Fills a presentation with layout data. * Note: This method should not modify the current state of the perspective. */ public: bool RestoreState(); /** * Returns the ActionSets read from perspectiveExtensions in the registry. */ // protected: ArrayList GetPerspectiveExtensionActionSets() { // PerspectiveExtensionReader reader = new PerspectiveExtensionReader(); // reader // .setIncludeOnlyTags(new String[] { IWorkbenchRegistryConstants.TAG_ACTION_SET }); // PageLayout layout = new PageLayout(); // reader.extendLayout(null, descriptor.getOriginalId(), layout); // return layout.getActionSets(); // } /** * Returns the Show In... part ids read from the registry. */ protected: QList GetShowInIdsFromRegistry(); /** * Save the layout. */ public: void SaveDesc(); /** * Save the layout. */ public: void SaveDescAs(IPerspectiveDescriptor::Pointer desc); /** * Save the layout. */ - public: bool SaveState(IMemento::Pointer memento); +public: bool SaveState(IMemento::Pointer memento); /** * Save the layout. */ - private: bool SaveState(IMemento::Pointer memento, PerspectiveDescriptor::Pointer p, +private: bool SaveState(IMemento::Pointer memento, PerspectiveDescriptor::Pointer p, bool saveInnerViewState); // public: void turnOnActionSets(IActionSetDescriptor[] newArray) { // for (int i = 0; i < newArray.length; i++) { // IActionSetDescriptor descriptor = newArray[i]; // // addAlwaysOn(descriptor); // } // } // public: void turnOffActionSets(IActionSetDescriptor[] toDisable) { // for (int i = 0; i < toDisable.length; i++) { // IActionSetDescriptor descriptor = toDisable[i]; // // turnOffActionSet(descriptor); // } // } // public: void turnOffActionSet(IActionSetDescriptor toDisable) { // addAlwaysOff(toDisable); // } /** * Sets the perspective actions for this page. * This is List of Strings. */ public: void SetPerspectiveActionIds(const QList& list); /** * Sets the ids of the parts to list in the Show In... prompter. * This is a List of Strings. */ public: void SetShowInPartIds(const QList& list); /** * Sets the ids of the views to list in the Show View shortcuts. * This is a List of Strings. */ public: void SetShowViewActionIds(const QList& list); /** * Show the editor area if not visible */ protected: void ShowEditorArea(); /** * Show the editor area if not visible */ protected: void ShowEditorAreaLocal(); public: void SetEditorAreaState(int newState); public: int GetEditorAreaState(); /** * */ public: void RefreshEditorAreaVisibility(); /** * Resolves a view's id into its reference, creating the * view if necessary. * * @param viewId The primary id of the view (must not be * null * @param secondaryId The secondary id of a multiple-instance view * (may be null). * * @return The reference to the specified view. This may be null if the * view fails to create (i.e. thrown a PartInitException) */ public: IViewReference::Pointer GetViewReference(const QString& viewId, const QString& secondaryId); /** * Shows the view with the given id and secondary id. */ public: IViewPart::Pointer ShowView(const QString& viewId, const QString& secondaryId); /** * Returns the old part reference. * Returns null if there was no previously active part. * * @return the old part reference or null */ public: IWorkbenchPartReference::Pointer GetOldPartRef(); /** * Sets the old part reference. * * @param oldPartRef The old part reference to set, or null */ public: void SetOldPartRef(IWorkbenchPartReference::Pointer oldPartRef); // //for dynamic UI // protected: void AddActionSet(IActionSetDescriptor newDesc) { // IContextService service = (IContextService)page.getWorkbenchWindow().getService(IContextService.class); // try { // service.activateContext(ContextAuthority.DEFER_EVENTS); // for (int i = 0; i < alwaysOnActionSets.size(); i++) { // IActionSetDescriptor desc = (IActionSetDescriptor) alwaysOnActionSets // .get(i); // if (desc.getId().equals(newDesc.getId())) { // removeAlwaysOn(desc); // removeAlwaysOff(desc); // break; // } // } // addAlwaysOn(newDesc); // } finally { // service.activateContext(ContextAuthority.SEND_EVENTS); // } // } // // for dynamic UI // /* package */void removeActionSet(String id) { // IContextService service = (IContextService)page.getWorkbenchWindow().getService(IContextService.class); // try { // service.activateContext(ContextAuthority.DEFER_EVENTS); // for (int i = 0; i < alwaysOnActionSets.size(); i++) { // IActionSetDescriptor desc = (IActionSetDescriptor) alwaysOnActionSets // .get(i); // if (desc.getId().equals(id)) { // removeAlwaysOn(desc); // break; // } // } // // for (int i = 0; i < alwaysOffActionSets.size(); i++) { // IActionSetDescriptor desc = (IActionSetDescriptor) alwaysOffActionSets // .get(i); // if (desc.getId().equals(id)) { // removeAlwaysOff(desc); // break; // } // } // } finally { // service.activateContext(ContextAuthority.SEND_EVENTS); // } // } // void removeActionSet(IActionSetDescriptor toRemove) { // removeAlwaysOn(toRemove); // removeAlwaysOff(toRemove); // } /** * Returns whether the given view is closeable in this perspective. * * @since 3.0 */ public: bool IsCloseable(IViewReference::Pointer reference); /** * Returns whether the given view is moveable in this perspective. * * @since 3.0 */ public: bool IsMoveable(IViewReference::Pointer reference); /** * 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. *

* This is only intended for use by test suites. *

* * @param buf */ public: void DescribeLayout(QString& buf) const; /** * Sanity-checks the LayoutParts in this perspective. Throws an Assertation exception * if an object's internal state is invalid. */ public: void TestInvariants(); // public: IActionSetDescriptor[] getAlwaysOnActionSets() { // return (IActionSetDescriptor[]) alwaysOnActionSets.toArray(new IActionSetDescriptor[alwaysOnActionSets.size()]); // } // public: IActionSetDescriptor[] getAlwaysOffActionSets() { // return (IActionSetDescriptor[]) alwaysOffActionSets.toArray(new IActionSetDescriptor[alwaysOffActionSets.size()]); // } /** * Used to restrict the use of the new min/max behavior to envoronments * in which it has a chance of working... * * @param activePerspective We pass this in as an arg so others won't have * to check it for 'null' (which is one of the failure cases) * */ public: static bool UseNewMinMax(Perspective::Pointer activePerspective); }; } #endif /*BERRYPERSPECTIVE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp index b16b321cc9..4b03804919 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.cpp @@ -1,333 +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. ===================================================================*/ #include "berryPerspectiveDescriptor.h" #include "berryWorkbenchRegistryConstants.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include "berryPerspectiveRegistry.h" #include "berryStatus.h" #include "berryIContributor.h" #include namespace berry { PerspectiveDescriptor::PerspectiveDescriptor(const QString& id, const QString& label, PerspectiveDescriptor::Pointer originalDescriptor) : singleton(false), fixed(false) { this->id = id; this->label = label; if (originalDescriptor != 0) { this->originalId = originalDescriptor->GetOriginalId(); this->imageDescriptor = originalDescriptor->imageDescriptor; // This perspective is based on a perspective in some bundle -- if // that // bundle goes away then I think it makes sense to treat this // perspective // the same as any other -- so store it with the original // descriptor's // bundle's list. // // It might also make sense the other way...removing the following // line // will allow the perspective to stay around when the originating // bundle // is unloaded. // // This might also have an impact on upgrade cases -- should we // really be // destroying all user customized perspectives when the older // version is // removed? // // I'm leaving this here for now since its a good example, but // wouldn't be // surprised if we ultimately decide on the opposite. // // The reason this line is important is that this is the value used // to // put the object into the UI level registry. When that bundle goes // away, // the registry will remove the entire list of objects. So if this // desc // has been put into that list -- it will go away. this->pluginId = originalDescriptor->GetPluginId(); } } PerspectiveDescriptor::PerspectiveDescriptor(const QString& id, IConfigurationElement::Pointer configElement) : singleton(false), fixed(false) { this->configElement = configElement; this->id = id; // Sanity check. if ((this->GetId() == "") || (this->GetLabel() == "") || (this->GetFactoryClassName() == "")) { IStatus::Pointer status(new Status( IStatus::ERROR_TYPE, PlatformUI::PLUGIN_ID(), 0, QString("Invalid extension (missing label, id or class name): ") + GetId())); throw CoreException(status); } } IPerspectiveFactory::Pointer PerspectiveDescriptor::CreateFactory() { // if there is an originalId, then use that descriptor instead if (originalId != "") { // Get the original descriptor to create the factory. If the // original is gone then nothing can be done. IPerspectiveDescriptor::Pointer target = dynamic_cast (WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()) ->FindPerspectiveWithId( originalId); return target == 0 ? IPerspectiveFactory::Pointer(0) : target.Cast< PerspectiveDescriptor> ()->CreateFactory(); } // otherwise try to create the executable extension if (configElement != 0) { try { IPerspectiveFactory::Pointer factory( configElement ->CreateExecutableExtension ( WorkbenchRegistryConstants::ATT_CLASS)); return factory; } catch (const CoreException& /*e*/) { // do nothing } } return IPerspectiveFactory::Pointer(0); } void PerspectiveDescriptor::DeleteCustomDefinition() { dynamic_cast (WorkbenchPlugin::GetDefault() ->GetPerspectiveRegistry())->DeleteCustomDefinition( PerspectiveDescriptor::Pointer(this)); } QString PerspectiveDescriptor::GetDescription() const { return configElement == 0 ? description : RegistryReader::GetDescription( configElement); } void PerspectiveDescriptor::SetDescription(const QString& desc) { description = desc; } bool PerspectiveDescriptor::GetFixed() const { if (configElement == 0) return fixed; return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_FIXED).compare("true", Qt::CaseInsensitive) == 0; } QStringList PerspectiveDescriptor::GetKeywordReferences() const { QStringList result; if (configElement.IsNull()) { return result; } auto keywordRefs = configElement->GetChildren("keywordReference"); for (auto keywordRefsIt = keywordRefs.begin(); keywordRefsIt != keywordRefs.end(); ++keywordRefsIt) // iterate over all refs { result.push_back((*keywordRefsIt)->GetAttribute("id")); } return result; } QString PerspectiveDescriptor::GetId() const { return id; } +QString PerspectiveDescriptor::GetLocalId() const +{ + return GetId(); +} + QString PerspectiveDescriptor::GetPluginId() const { return configElement == 0 ? pluginId : configElement->GetContributor()->GetName(); } QIcon PerspectiveDescriptor::GetImageDescriptor() const { if (!imageDescriptor.isNull()) return imageDescriptor; if (configElement) { QString icon = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ICON); if (!icon.isEmpty()) { imageDescriptor = AbstractUICTKPlugin::ImageDescriptorFromPlugin( configElement->GetContributor()->GetName(), icon); } } if (imageDescriptor.isNull()) { imageDescriptor = AbstractUICTKPlugin::GetMissingIcon(); } return imageDescriptor; } QStringList PerspectiveDescriptor::GetCategoryPath() const { if(!categoryPath.empty()) return categoryPath; if (configElement.IsNotNull()) { QString category = configElement->GetAttribute(WorkbenchRegistryConstants::TAG_CATEGORY); categoryPath = category.split('/', QString::SkipEmptyParts); } return categoryPath; } QString PerspectiveDescriptor::GetLabel() const { if (configElement == 0) return label; return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME); } QString PerspectiveDescriptor::GetOriginalId() const { if (originalId == "") { return this->GetId(); } return originalId; } bool PerspectiveDescriptor::HasCustomDefinition() const { return dynamic_cast (WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry())->HasCustomDefinition( PerspectiveDescriptor::ConstPointer(this)); } bool PerspectiveDescriptor::HasDefaultFlag() const { if (configElement == 0) { return false; } return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_DEFAULT).compare("true", Qt::CaseInsensitive) == 0; } bool PerspectiveDescriptor::IsPredefined() const { return this->GetFactoryClassName() != "" && configElement != 0; } bool PerspectiveDescriptor::IsSingleton() const { if (configElement == 0) return singleton; return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_SINGLETON).compare("true", Qt::CaseInsensitive) == 0; } bool PerspectiveDescriptor::RestoreState(IMemento::Pointer memento) { IMemento::Pointer childMem(memento->GetChild( WorkbenchConstants::TAG_DESCRIPTOR)); if (childMem) { childMem->GetString(WorkbenchConstants::TAG_ID, id); childMem->GetString(WorkbenchConstants::TAG_DESCRIPTOR, originalId); childMem->GetString(WorkbenchConstants::TAG_LABEL, label); childMem->GetString(WorkbenchConstants::TAG_CLASS, className); int singletonVal; singleton = childMem->GetInteger(WorkbenchConstants::TAG_SINGLETON, singletonVal); // Find a descriptor in the registry. IPerspectiveDescriptor::Pointer descriptor = WorkbenchPlugin::GetDefault() ->GetPerspectiveRegistry()->FindPerspectiveWithId( this->GetOriginalId()); if (descriptor) { // Copy the state from the registred descriptor. imageDescriptor = descriptor->GetImageDescriptor(); } } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ return true; } void PerspectiveDescriptor::RevertToPredefined() { if (this->IsPredefined()) { this->DeleteCustomDefinition(); } } bool PerspectiveDescriptor::SaveState(IMemento::Pointer memento) { IMemento::Pointer childMem(memento->CreateChild( WorkbenchConstants::TAG_DESCRIPTOR)); childMem->PutString(WorkbenchConstants::TAG_ID, GetId()); if (!originalId.isEmpty()) { childMem->PutString(WorkbenchConstants::TAG_DESCRIPTOR, originalId); } childMem->PutString(WorkbenchConstants::TAG_LABEL, GetLabel()); childMem->PutString(WorkbenchConstants::TAG_CLASS, GetFactoryClassName()); if (singleton) { childMem->PutInteger(WorkbenchConstants::TAG_SINGLETON, 1); } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", null); return true; } IConfigurationElement::Pointer PerspectiveDescriptor::GetConfigElement() const { return configElement; } QString PerspectiveDescriptor::GetFactoryClassName() const { return configElement == 0 ? className : RegistryReader::GetClassValue( configElement, WorkbenchRegistryConstants::ATT_CLASS); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.h index 7d2f0119cf..96ad72dbef 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveDescriptor.h @@ -1,246 +1,242 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYPERSPECTIVEDESCRIPTOR_H_ #define BERRYPERSPECTIVEDESCRIPTOR_H_ #include #include "berryIPerspectiveDescriptor.h" #include "berryIPerspectiveFactory.h" +#include "berryIPluginContribution.h" #include "berryIMemento.h" #include #include namespace berry { /** * \ingroup org_blueberry_ui_internal * * PerspectiveDescriptor. *

* A PerspectiveDesciptor has 3 states: *

*
    *
  1. It isPredefined(), in which case it was defined from an * extension point.
  2. *
  3. It isPredefined() and hasCustomFile, in * which case the user has customized a predefined perspective.
  4. *
  5. It hasCustomFile, in which case the user created a new * perspective.
  6. *
* */ -class PerspectiveDescriptor : public IPerspectiveDescriptor { +class PerspectiveDescriptor : public IPerspectiveDescriptor, public IPluginContribution { public: - berryObjectMacro(PerspectiveDescriptor); + berryObjectMacro(PerspectiveDescriptor, IPerspectiveDescriptor, IPluginContribution) private: QString id; QString pluginId; QString originalId; QString label; QString className; QString description; bool singleton; bool fixed; mutable QIcon imageDescriptor; IConfigurationElement::Pointer configElement; mutable QStringList categoryPath; +public: + /** * Create a new empty descriptor. * * @param id * the id of the new descriptor * @param label * the label of the new descriptor * @param originalDescriptor * the descriptor that this descriptor is based on */ - public: PerspectiveDescriptor(const QString& id, const QString& label, - PerspectiveDescriptor::Pointer originalDescriptor); + PerspectiveDescriptor(const QString& id, const QString& label, + PerspectiveDescriptor::Pointer originalDescriptor); /** * Create a descriptor from a config element. * * @param id * the id of the element to create * @param configElement * the element to base this perspective on * @throws CoreException * thrown if there are any missing attributes */ - public: PerspectiveDescriptor(const QString& id, IConfigurationElement::Pointer configElement); + PerspectiveDescriptor(const QString& id, IConfigurationElement::Pointer configElement); /** * Creates a factory for a predefined perspective. If the perspective is not * predefined return null. * * @return the IPerspectiveFactory or null * @throws CoreException * if the object could not be instantiated. */ - public: IPerspectiveFactory::Pointer CreateFactory(); + IPerspectiveFactory::Pointer CreateFactory(); /** * Deletes the custom definition for a perspective.. */ - public: void DeleteCustomDefinition(); + void DeleteCustomDefinition(); /* - * (non-Javadoc) - * - * @see org.blueberry.ui.IPerspectiveDescriptor#getDescription() + * @see IPerspectiveDescriptor#getDescription() */ - public: QString GetDescription() const; + QString GetDescription() const; - public: void SetDescription(const QString& desc); + void SetDescription(const QString& desc); QStringList GetKeywordReferences() const; /** * Returns whether or not this perspective is fixed. * * @return whether or not this perspective is fixed */ - public: bool GetFixed() const; + bool GetFixed() const; /* - * (non-Javadoc) - * - * @see org.blueberry.ui.IPerspectiveDescriptor#getId() + * @see IPerspectiveDescriptor#GetId() */ - public: QString GetId() const; + QString GetId() const; - public: QString GetPluginId() const; + QString GetLocalId() const; + + QString GetPluginId() const; /* - * (non-Javadoc) - * - * @see org.blueberry.ui.IPerspectiveDescriptor#getImageDescriptor() + * @see IPerspectiveDescriptor#GetImageDescriptor() */ - public: QIcon GetImageDescriptor() const; + QIcon GetImageDescriptor() const; /* - * (non-Javadoc) - * - * @see org.blueberry.ui.IPerspectiveDescriptor#getLabel() + * @see IPerspectiveDescriptor#GetLabel() */ - public: QString GetLabel() const; + QString GetLabel() const; + /** * Return the original id of this descriptor. * * @return the original id of this descriptor */ - public: QString GetOriginalId() const; + QString GetOriginalId() const; /** * Returns true if this perspective has a custom definition. * * @return whether this perspective has a custom definition */ - public: bool HasCustomDefinition() const; + bool HasCustomDefinition() const; /** * Returns true if this perspective wants to be default. * * @return whether this perspective wants to be default */ - public: bool HasDefaultFlag() const; + bool HasDefaultFlag() const; /** * Returns true if this perspective is predefined by an * extension. * * @return boolean whether this perspective is predefined by an extension */ - public: bool IsPredefined() const; + bool IsPredefined() const; /** * Returns true if this perspective is a singleton. * * @return whether this perspective is a singleton */ - public: bool IsSingleton() const; + bool IsSingleton() const; /** * Restore the state of a perspective from a memento. * * @param memento * the memento to restore from * @return the IStatus of the operation * @see org.blueberry.ui.IPersistableElement */ - public: bool RestoreState(IMemento::Pointer memento); + bool RestoreState(IMemento::Pointer memento); /** * Revert to the predefined extension template. Does nothing if this * descriptor is user defined. */ - public: void RevertToPredefined(); + void RevertToPredefined(); /** * Save the state of a perspective to a memento. * * @param memento * the memento to restore from * @return the IStatus of the operation * @see org.blueberry.ui.IPersistableElement */ - public: bool SaveState(IMemento::Pointer memento); + bool SaveState(IMemento::Pointer memento); /** * Return the configuration element used to create this perspective, if one * was used. * * @return the configuration element used to create this perspective - * @since 3.0 */ - public: IConfigurationElement::Pointer GetConfigElement() const; + IConfigurationElement::Pointer GetConfigElement() const; /** * Returns the factory class name for this descriptor. * * @return the factory class name for this descriptor - * @since 3.1 */ - public: QString GetFactoryClassName() const; + QString GetFactoryClassName() const; /** * Return the category path of this descriptor * * @return the category path of this descriptor */ - public: QStringList GetCategoryPath() const; + QStringList GetCategoryPath() const; }; } #endif /*BERRYPERSPECTIVEDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveExtensionReader.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveExtensionReader.cpp index fa1bd55595..c3a2f35f06 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveExtensionReader.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveExtensionReader.cpp @@ -1,370 +1,376 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryPerspectiveExtensionReader.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchRegistryConstants.h" +#include "berryDirtyPerspectiveMarker.h" #include +#include namespace berry { const QString PerspectiveExtensionReader::VAL_LEFT = "left"; const QString PerspectiveExtensionReader::VAL_RIGHT = "right"; const QString PerspectiveExtensionReader::VAL_TOP = "top"; const QString PerspectiveExtensionReader::VAL_BOTTOM = "bottom"; const QString PerspectiveExtensionReader::VAL_STACK = "stack"; const QString PerspectiveExtensionReader::VAL_FAST = "fast"; const QString PerspectiveExtensionReader::VAL_TRUE = "true"; //const QString PerspectiveExtensionReader::VAL_FALSE = "false"; bool PerspectiveExtensionReader::IncludeTag(const QString& tag) { return includeOnlyTags.empty() || std::find(includeOnlyTags.begin(), includeOnlyTags.end(), tag) != includeOnlyTags.end(); } bool PerspectiveExtensionReader::ProcessActionSet( const IConfigurationElement::Pointer& element) { QString id = element->GetAttribute(WorkbenchRegistryConstants::ATT_ID); if (!id.isEmpty()) { //TODO PerspectiveExtensionReader action set //pageLayout->AddActionSet(id); } return true; } bool PerspectiveExtensionReader::ProcessExtension( const IConfigurationElement::Pointer& element) { foreach (IConfigurationElement::Pointer child, element->GetChildren()) { QString type = child->GetName(); if (this->IncludeTag(type)) { bool result = false; if (type == WorkbenchRegistryConstants::TAG_ACTION_SET) { result = this->ProcessActionSet(child); } else if (type == WorkbenchRegistryConstants::TAG_VIEW) { result = this->ProcessView(child); } else if (type == WorkbenchRegistryConstants::TAG_VIEW_SHORTCUT) { result = this->ProcessViewShortcut(child); } // else if (type == IorkbenchRegistryConstants::TAG_NEW_WIZARD_SHORTCUT) // { // result = processWizardShortcut(child); // } else if (type == WorkbenchRegistryConstants::TAG_PERSP_SHORTCUT) { result = this->ProcessPerspectiveShortcut(child); } else if (type == WorkbenchRegistryConstants::TAG_SHOW_IN_PART) { result = this->ProcessShowInPart(child); } if (!result) { WorkbenchPlugin::Log("Unable to process element: " + type + " in perspective extension: " + element->GetDeclaringExtension()->GetUniqueIdentifier()); } } } return true; } bool PerspectiveExtensionReader::ProcessPerspectiveShortcut( const IConfigurationElement::Pointer& element) { QString id = element->GetAttribute(WorkbenchRegistryConstants::ATT_ID); if (!id.isEmpty()) { pageLayout->AddPerspectiveShortcut(id); } return true; } bool PerspectiveExtensionReader::ProcessShowInPart( const IConfigurationElement::Pointer& element) { QString id = element->GetAttribute(WorkbenchRegistryConstants::ATT_ID); if (!id.isEmpty()) { pageLayout->AddShowInPart(id); } return true; } bool PerspectiveExtensionReader::ProcessView( const IConfigurationElement::Pointer& element) { // Get id, relative, and relationship. QString id = element->GetAttribute(WorkbenchRegistryConstants::ATT_ID); if (id.isEmpty()) { this->LogMissingAttribute(element, WorkbenchRegistryConstants::ATT_ID); return false; } QString relative = element->GetAttribute(WorkbenchRegistryConstants::ATT_RELATIVE); QString relationship = element->GetAttribute(WorkbenchRegistryConstants::ATT_RELATIONSHIP); - if (!relationship.isEmpty()) + if (relationship.isEmpty()) { this->LogMissingAttribute(element, WorkbenchRegistryConstants::ATT_RELATIONSHIP); return false; } if (VAL_FAST != relationship && relative.isEmpty()) { this->LogError(element, "Attribute '" + WorkbenchRegistryConstants::ATT_RELATIVE + "' not defined. This attribute is required when " + WorkbenchRegistryConstants::ATT_RELATIONSHIP + "=\"" + relationship + "\"."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ return false; } // Get relationship details. bool stack = false; //bool fast = false; int intRelation = 0; if (relationship == VAL_LEFT) { intRelation = IPageLayout::LEFT; } else if (relationship == VAL_RIGHT) { intRelation = IPageLayout::RIGHT; } else if (relationship == VAL_TOP) { intRelation = IPageLayout::TOP; } else if (relationship == VAL_BOTTOM) { intRelation = IPageLayout::BOTTOM; } else if (relationship == VAL_STACK) { stack = true; } // else if (relationship == VAL_FAST) // { // fast = true; // } else { return false; } float ratio = 0.5f; QString ratioString = element->GetAttribute(WorkbenchRegistryConstants::ATT_RATIO); if (!ratioString.isEmpty()) { bool ok = false; ratio = ratioString.toFloat(&ok); if (!ok) return false; // If the ratio is outside the allowable range, mark it as invalid. if (ratio < IPageLayout::RATIO_MIN || ratio > IPageLayout::RATIO_MAX) { ratio = IPageLayout::INVALID_RATIO; } } else { // The ratio has not been specified. ratio = IPageLayout::NULL_RATIO; } QString strVisible = element->GetAttribute(WorkbenchRegistryConstants::ATT_VISIBLE); bool visible = (VAL_TRUE == strVisible); QString closeable = element->GetAttribute(WorkbenchRegistryConstants::ATT_CLOSEABLE); QString moveable = element->GetAttribute(WorkbenchRegistryConstants::ATT_MOVEABLE); QString standalone = element->GetAttribute(WorkbenchRegistryConstants::ATT_STANDALONE); QString showTitle = element->GetAttribute(WorkbenchRegistryConstants::ATT_SHOW_TITLE); QString minVal = element->GetAttribute(WorkbenchRegistryConstants::ATT_MINIMIZED); // Default to 'false' bool minimized = (VAL_TRUE == minVal); if (visible) { // If adding a view (not just a placeholder), remove any existing placeholder. // See bug 85948 [Perspectives] Adding register & expressions view by default to debug perspective fails pageLayout->RemovePlaceholder(id); } // If stack .. if (stack) { if (visible) { pageLayout->StackView(id, relative); } else { pageLayout->StackPlaceholder(id, relative); } } // // If the view is a fast view... // else if (fast) // { // if (ratio == IPageLayout::NULL_RATIO) // { // // The ratio has not been specified. // pageLayout->AddFastView(id); // } // else // { // pageLayout->AddFastView(id, ratio); // } // } else { // The view is a regular view. // If the ratio is not specified or is invalid, use the default ratio. if (ratio == IPageLayout::NULL_RATIO || ratio == IPageLayout::INVALID_RATIO) { ratio = IPageLayout::DEFAULT_VIEW_RATIO; } if (visible) { if (VAL_TRUE == standalone) { pageLayout->AddStandaloneView(id, VAL_TRUE == showTitle, intRelation, ratio, relative); } else { pageLayout->AddView(id, intRelation, ratio, relative, minimized); } } else { // Fix for 99155, CGross (schtoo@schtoo.com) // Adding standalone placeholder for standalone views if (VAL_TRUE == standalone) { pageLayout->AddStandaloneViewPlaceholder(id, intRelation, ratio, relative, VAL_TRUE == showTitle); } else { pageLayout->AddPlaceholder(id, intRelation, ratio, relative); } } } IViewLayout::Pointer viewLayout = pageLayout->GetViewLayout(id); // may be null if it's been filtered by activity if (viewLayout != 0) { if (!closeable.isEmpty()) { viewLayout->SetCloseable(VAL_TRUE == closeable); } if (!moveable.isEmpty()) { viewLayout->SetMoveable(VAL_TRUE == moveable); } } return true; } bool PerspectiveExtensionReader::ProcessViewShortcut( const IConfigurationElement::Pointer& element) { QString id = element->GetAttribute(WorkbenchRegistryConstants::ATT_ID); if (!id.isEmpty()) { pageLayout->AddShowViewShortcut(id); } return true; } //bool PerspectiveExtensionReader::ProcessWizardShortcut( // IConfigurationElement::Pointer element) //{ // QString id = element.getAttribute(IWorkbenchRegistryConstants.ATT_ID); // if (id != null) // { // pageLayout.addNewWizardShortcut(id); // } // return true; //} bool PerspectiveExtensionReader::ReadElement( const IConfigurationElement::Pointer& element) { QString type = element->GetName(); if (type == WorkbenchRegistryConstants::TAG_PERSPECTIVE_EXTENSION) { QString id = element->GetAttribute(WorkbenchRegistryConstants::ATT_TARGET_ID); if (targetID == id || "*" == id) { -// if (tracker != null) -// { -// tracker.registerObject(element.getDeclaringExtension(), -// new DirtyPerspectiveMarker(id), IExtensionTracker.REF_STRONG); -// } + if (tracker != nullptr) + { + Object::Pointer obj(new DirtyPerspectiveMarker(id)); + tracker->RegisterObject(element->GetDeclaringExtension(), + obj, IExtensionTracker::REF_STRONG); + } return this->ProcessExtension(element); } return true; } return false; } PerspectiveExtensionReader::PerspectiveExtensionReader() + : tracker(nullptr) { // do nothing } -void PerspectiveExtensionReader::ExtendLayout(const QString& id, - PageLayout::Pointer out) +void PerspectiveExtensionReader::ExtendLayout(IExtensionTracker* extensionTracker, + const QString& id, + PageLayout::Pointer out) { - //tracker = extensionTracker; + tracker = extensionTracker; targetID = id; pageLayout = out; - this->ReadRegistry(PlatformUI::PLUGIN_ID(), - WorkbenchRegistryConstants::PL_PERSPECTIVE_EXTENSIONS); + this->ReadRegistry(Platform::GetExtensionRegistry(), + PlatformUI::PLUGIN_ID(), + WorkbenchRegistryConstants::PL_PERSPECTIVE_EXTENSIONS); } void PerspectiveExtensionReader::SetIncludeOnlyTags( const QList& tags) { includeOnlyTags = tags; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveExtensionReader.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveExtensionReader.h index 4aa06ce9f7..e319ba481c 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveExtensionReader.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveExtensionReader.h @@ -1,136 +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. ===================================================================*/ #ifndef BERRYPERSPECTIVEEXTENSIONREADER_H_ #define BERRYPERSPECTIVEEXTENSIONREADER_H_ #include "berryRegistryReader.h" #include "berryPageLayout.h" namespace berry { +struct IExtensionTracker; + /** * A strategy to read perspective extension from the registry. * A pespective extension is one of a view, viewAction, perspAction, * newWizardAction, or actionSet. */ class PerspectiveExtensionReader: public RegistryReader { private: QString targetID; PageLayout::Pointer pageLayout; QList includeOnlyTags; static const QString VAL_LEFT; // = "left";//$NON-NLS-1$ static const QString VAL_RIGHT; // = "right";//$NON-NLS-1$ static const QString VAL_TOP; // = "top";//$NON-NLS-1$ static const QString VAL_BOTTOM; // = "bottom";//$NON-NLS-1$ static const QString VAL_STACK; // = "stack";//$NON-NLS-1$ static const QString VAL_FAST; // = "fast";//$NON-NLS-1$ static const QString VAL_TRUE; // = "true";//$NON-NLS-1$ // VAL_FALSE added by dan_rubel@instantiations.com // TODO: this logic is backwards... we should be checking for true, but // technically this is API now... //static const QString VAL_FALSE; // = "false";//$NON-NLS-1$ - // IExtensionTracker tracker; + IExtensionTracker* tracker; /** * Returns whether the given tag should be included. */ bool IncludeTag(const QString& tag); /** * Process an action set. */ bool ProcessActionSet(const IConfigurationElement::Pointer& element); /** * Process an extension. * Assumption: Extension is for current perspective. */ bool ProcessExtension(const IConfigurationElement::Pointer& element); /** * Process a perspective shortcut */ bool ProcessPerspectiveShortcut(const IConfigurationElement::Pointer& element); /** * Process a show in element. */ bool ProcessShowInPart(const IConfigurationElement::Pointer& element); // processView(IConfigurationElement) modified by dan_rubel@instantiations.com /** * Process a view */ bool ProcessView(const IConfigurationElement::Pointer& element); /** * Process a view shortcut */ bool ProcessViewShortcut(const IConfigurationElement::Pointer& element); /** * Process a wizard shortcut */ //bool ProcessWizardShortcut(IConfigurationElement::Pointer element); protected: bool ReadElement(const IConfigurationElement::Pointer& element); public: /** * PerspectiveExtensionReader constructor.. */ PerspectiveExtensionReader(); /** * Read the view extensions within a registry. * * @param extensionTracker the tracker * @param id the id * @param out the layout */ - void ExtendLayout(const QString& id, - PageLayout::Pointer out); + void ExtendLayout(IExtensionTracker* extensionTracker, + const QString& id, + PageLayout::Pointer out); /** * Sets the tags to include. All others are ignored. * * @param tags the tags to include */ void SetIncludeOnlyTags(const QList& tags); }; } #endif /* BERRYPERSPECTIVEEXTENSIONREADER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp index 2828e3a19a..b5516bf647 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.cpp @@ -1,1492 +1,1519 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryPerspectiveHelper.h" #include "berryLayoutTree.h" #include "berryEditorSashContainer.h" #include "berryDragUtil.h" #include "berryPresentationFactoryUtil.h" #include "berryWorkbenchConstants.h" +#include "berryWorkbenchPlugin.h" +#include "berryPolicy.h" #include namespace berry { const int PerspectiveHelper::MIN_DETACH_WIDTH = 150; const int PerspectiveHelper::MIN_DETACH_HEIGHT = 250; PerspectiveHelper::DragOverListener::DragOverListener(PerspectiveHelper* perspHelper) : perspHelper(perspHelper) { } IDropTarget::Pointer PerspectiveHelper::DragOverListener::Drag( QWidget* /*currentControl*/, const Object::Pointer& draggedObject, const QPoint& /*position*/, const QRect& dragRectangle) { if (draggedObject.Cast() != 0) { PartPane::Pointer part = draggedObject.Cast(); if (part->GetContainer().Cast()->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) return IDropTarget::Pointer(0); // Views that haven't been shown yet have no 'control' which causes // 'GetWorkbenchWindow' to return 'null' so check explicitly if (part->GetPage() != perspHelper->page) return IDropTarget::Pointer(0); else if (part->GetWorkbenchWindow() != perspHelper->page->GetWorkbenchWindow()) return IDropTarget::Pointer(0); if (perspHelper->dropTarget == 0) perspHelper->dropTarget = new ActualDropTarget(perspHelper, part, dragRectangle); else perspHelper->dropTarget->SetTarget(part, dragRectangle); } else if (draggedObject.Cast() != 0) { PartStack::Pointer stack = draggedObject.Cast(); if (stack->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) return IDropTarget::Pointer(0); if (stack->GetWorkbenchWindow() != perspHelper->page->GetWorkbenchWindow()) return IDropTarget::Pointer(0); if (perspHelper->dropTarget == 0) perspHelper->dropTarget = new ActualDropTarget(perspHelper, stack, dragRectangle); else perspHelper->dropTarget->SetTarget(stack, dragRectangle); } return perspHelper->dropTarget; } void PerspectiveHelper::ActualDropTarget::SetTarget(PartPane::Pointer part, const QRect& dragRectangle) { this->stack = 0; this->part = part; this->dragRectangle = dragRectangle; } void PerspectiveHelper::ActualDropTarget::SetTarget(PartStack::Pointer stack, const QRect& dragRectangle) { this->stack = stack; this->part = 0; this->dragRectangle = dragRectangle; } PerspectiveHelper::ActualDropTarget::ActualDropTarget(PerspectiveHelper* perspHelper, PartPane::Pointer part, const QRect& dragRectangle) : AbstractDropTarget(), perspHelper(perspHelper) { this->SetTarget(part, dragRectangle); } PerspectiveHelper::ActualDropTarget::ActualDropTarget(PerspectiveHelper* perspHelper, PartStack::Pointer stack, const QRect& dragRectangle) : AbstractDropTarget(), perspHelper(perspHelper) { this->SetTarget(stack, dragRectangle); } void PerspectiveHelper::ActualDropTarget::Drop() { if (part != 0) { Shell::Pointer shell = part->GetShell(); if (shell->GetData().Cast () != 0) { // if only one view in tab folder then do a window move ILayoutContainer::Pointer container = part->GetContainer(); if (container.Cast () != 0) { if (container.Cast()->GetItemCount() == 1) { shell->SetLocation(dragRectangle.x(), dragRectangle.y()); return; } } } // // If layout is modified always zoom out. // if (isZoomed()) // { // zoomOut(); // } // do a normal part detach perspHelper->DetachPart(part, dragRectangle.x(), dragRectangle.y()); } else if (stack != 0) { Shell::Pointer shell = stack->GetShell(); if (shell->GetData().Cast () != 0) { // only one tab folder in a detach window, so do window // move shell->SetLocation(dragRectangle.x(), dragRectangle.y()); return; } // // If layout is modified always zoom out. // if (isZoomed()) // { // zoomOut(); // } // do a normal part detach perspHelper->Detach(stack, dragRectangle.x(), dragRectangle.y()); } } CursorType PerspectiveHelper::ActualDropTarget::GetCursor() { return CURSOR_OFFSCREEN; } PerspectiveHelper::MatchingPart::MatchingPart(const QString& pid, const QString& sid, LayoutPart::Pointer part) { this->pid = pid; this->sid = sid; this->part = part; this->len = pid.size() + sid.size(); this->hasWildcard = (pid.indexOf(PartPlaceholder::WILD_CARD) != -1) || (sid.indexOf(PartPlaceholder::WILD_CARD) != -1); } bool PerspectiveHelper::CompareMatchingParts::operator()(const MatchingPart& m1, const MatchingPart& m2) const { // specific ids always outweigh ids with wildcards if (m1.hasWildcard && !m2.hasWildcard) { return true; } if (!m1.hasWildcard && m2.hasWildcard) { return false; } // if both are specific or both have wildcards, simply compare based on length return m1.len > m2.len; } PerspectiveHelper::PerspectiveHelper(WorkbenchPage* workbenchPage, ViewSashContainer::Pointer mainLayout, Perspective* persp) : page(workbenchPage), perspective(persp), mainLayout(mainLayout), detachable(false), active(false) { // Views can be detached if the feature is enabled (true by default, // use the plug-in customization file to disable), and if the platform // supports detaching. this->dragTarget.reset(new DragOverListener(this)); //TODO preference store // IPreferenceStore store = PlatformUI.getPreferenceStore(); // this.detachable = store.getBoolean( // IWorkbenchPreferenceConstants.ENABLE_DETACHED_VIEWS); this->detachable = true; if (this->detachable) { // Check if some arbitrary Composite supports reparenting. If it // doesn't, views cannot be detached. QWidget* client = workbenchPage->GetClientComposite(); if (client == 0) { // The workbench page is not initialized. I don't think this can happen, // but if it does, silently set detachable to false. this->detachable = false; } else { this->detachable = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsReparentable(client); } } } void PerspectiveHelper::Activate(QWidget* parent) { if (active) { return; } parentWidget = parent; // Activate main layout // make sure all the views have been properly parented QList children; this->CollectViewPanes(children, mainLayout->GetChildren()); for (QList::iterator iter = children.begin(); iter != children.end(); ++iter) { PartPane::Pointer part = *iter; part->Reparent(parent); } mainLayout->CreateControl(parent); mainLayout->SetActive(true); // Open the detached windows. for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { (*iter)->Open(); } this->EnableAllDrag(); // // Ensure that the maximized stack's presentation state is correct // if (maximizedStackId != 0) // { // LayoutPart part = this->FindPart(maximizedStackId); // if (part.Cast() != 0) // { // maximizedStack = (PartStack) part; // maximizedStackId = 0; // } // } // // // NOTE: we only handle ViewStacks here; Editor Stacks are handled by the // // perspective // if (maximizedStack instanceof ViewStack) // { // maximizedStack.setPresentationState(IStackPresentationSite.STATE_MAXIMIZED); // } active = true; } void PerspectiveHelper::AddPart(LayoutPart::Pointer part) { // Look for a placeholder. PartPlaceholder::Pointer placeholder; LayoutPart::Pointer testPart; QString primaryId = part->GetID(); QString secondaryId; IViewReference::Pointer ref; if (part.Cast () != 0) { PartPane::Pointer pane = part.Cast (); ref = pane->GetPartReference().Cast (); if (ref != 0) secondaryId = ref->GetSecondaryId(); } if (secondaryId != "") { testPart = this->FindPart(primaryId, secondaryId); } else { testPart = this->FindPart(primaryId); } // validate the testPart if (testPart != 0 && testPart.Cast() != 0) { placeholder = testPart.Cast (); } // If there is no placeholder do a simple add. Otherwise, replace the // placeholder if its not a pattern matching placholder if (placeholder == 0) { part->Reparent(mainLayout->GetParent()); LayoutPart::Pointer relative = mainLayout->FindBottomRight(); if (relative != 0 && relative.Cast() != 0) { ILayoutContainer::Pointer stack = relative.Cast (); if (stack->AllowsAdd(part)) { mainLayout->Stack(part, stack); } else { mainLayout->AddPart(part); } } else { mainLayout->AddPart(part); } } else { ILayoutContainer::Pointer container = placeholder->GetContainer(); if (container != 0) { if (container.Cast () != 0) { //Create a detached window add the part on it. DetachedPlaceHolder::Pointer holder = container.Cast(); detachedPlaceHolderList.removeAll(holder); container->Remove(testPart); DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); window->Create(); part->CreateControl(window->GetShell()->GetControl()); // Open window. window->GetShell()->SetBounds(holder->GetBounds()); window->Open(); // add part to detached window. PartPane::Pointer pane = part.Cast(); window->Add(pane); QList otherChildren = holder->GetChildren(); for (QList::iterator iter = otherChildren.begin(); iter != otherChildren.end(); ++iter) { part->GetContainer()->Add(*iter); } } else { // show parent if necessary if (container.Cast () != 0) { ContainerPlaceholder::Pointer containerPlaceholder = container.Cast(); ILayoutContainer::Pointer parentContainer = containerPlaceholder->GetContainer(); - if (parentContainer == 0) return; + if (parentContainer == 0) + { + if (Policy::DEBUG_PERSPECTIVES()) + { + QString msg = "Previous ContainerPlaceholder for " + tmpViewId; + if (tmpStackTrace.isNull()) + { + WorkbenchPlugin::Log(msg); + } + else + { + WorkbenchPlugin::Log(msg, *tmpStackTrace.data()); + } + tmpViewId.clear(); + tmpStackTrace.reset(new ctkException("")); + WorkbenchPlugin::Log("Current ContainerPlaceholder with null parent for " + + primaryId + ":" + secondaryId, *tmpStackTrace.data()); + tmpStackTrace.reset(); + } + return; + } + if (Policy::DEBUG_PERSPECTIVES()) + { + tmpViewId = primaryId + ":" + secondaryId; + tmpStackTrace.reset(new ctkException("")); + } container = containerPlaceholder->GetRealContainer().Cast(); if (container.Cast () != 0) { parentContainer->Replace(containerPlaceholder, container.Cast()); } containerPlaceholder->SetRealContainer(ILayoutContainer::Pointer(0)); } // // reparent part. // if (container.Cast() == 0) // { // // We don't need to reparent children of PartTabFolders since they will automatically // // reparent their children when they become visible. This if statement used to be // // part of an else branch. Investigate if it is still necessary. // part->Reparent(mainLayout->GetParent()); // } // see if we should replace the placeholder if (placeholder->HasWildCard()) { if (PartSashContainer::Pointer sashContainer = container.Cast()) { sashContainer->AddChildForPlaceholder(part, placeholder); } else { container->Add(part); } } else { container->Replace(placeholder, part); } } } } } void PerspectiveHelper::AttachPart(IViewReference::Pointer ref) { PartPane::Pointer pane = ref.Cast()->GetPane(); // Restore any maximized part before re-attaching. // Note that 'getMaximizedStack != 0' implies 'useNewMinMax' // if (getMaximizedStack() != 0) // { // getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); // } this->DerefPart(pane); this->AddPart(pane); this->BringPartToTop(pane); pane->SetFocus(); } bool PerspectiveHelper::CanDetach() { return detachable; } bool PerspectiveHelper::BringPartToTop(LayoutPart::Pointer part) { ILayoutContainer::Pointer container = part->GetContainer(); if (container != 0 && container.Cast () != 0) { PartStack::Pointer folder = container.Cast (); if (folder->GetSelection() != part) { folder->SetSelection(part); return true; } } return false; } bool PerspectiveHelper::IsPartVisible(IWorkbenchPartReference::Pointer partRef) { LayoutPart::Pointer foundPart; if (partRef.Cast () != 0) { foundPart = this->FindPart(partRef->GetId(), partRef.Cast()->GetSecondaryId()); } else { foundPart = this->FindPart(partRef->GetId()); } if (foundPart == 0) { return false; } if (foundPart.Cast () != 0) { return false; } ILayoutContainer::Pointer container = foundPart->GetContainer(); if (container.Cast () != 0) { return false; } if (container.Cast () != 0) { PartStack::Pointer folder = container.Cast(); LayoutPart::Pointer visiblePart = folder->GetSelection(); if (visiblePart == 0) { return false; } return partRef == visiblePart.Cast()->GetPartReference(); } return true; } bool PerspectiveHelper::WillPartBeVisible(const QString& partId) { return this->WillPartBeVisible(partId, 0); } bool PerspectiveHelper::WillPartBeVisible(const QString& partId, const QString& secondaryId) { LayoutPart::Pointer part = this->FindPart(partId, secondaryId); if (part == 0) { return false; } ILayoutContainer::Pointer container = part->GetContainer(); if (container != 0 && container.Cast () != 0) { container = container.Cast()->GetRealContainer().Cast(); } if (container != 0 && container.Cast () != 0) { PartStack::Pointer folder = container.Cast(); if (folder->GetSelection() == 0) { return false; } return part->GetID() == folder->GetSelection()->GetID(); } return true; } QList PerspectiveHelper::CollectPlaceholders() { // Scan the main window. QList results = this->CollectPlaceholders( mainLayout->GetChildren()); // Scan each detached window. if (detachable) { for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::Pointer win = *winIter; QList moreResults = win->GetChildren(); if (moreResults.size()> 0) { for (QList::iterator iter = moreResults.begin(); iter != moreResults.end(); ++iter) { if (iter->Cast() != 0) results.push_back(iter->Cast()); } } } } return results; } QList PerspectiveHelper::CollectPlaceholders( const QList& parts) { QList result; for (QList::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (ILayoutContainer::Pointer container = part.Cast()) { // iterate through sub containers to find sub-parts QList newParts = this->CollectPlaceholders( container->GetChildren()); result.append(newParts); } else if (PartPlaceholder::Pointer placeholder = part.Cast()) { result.push_back(placeholder); } } return result; } void PerspectiveHelper::CollectViewPanes(QList& result) { // Scan the main window. this->CollectViewPanes(result, mainLayout->GetChildren()); // Scan each detached window. if (detachable) { for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::Pointer win = *winIter; CollectViewPanes(result, win->GetChildren()); } } } void PerspectiveHelper::CollectViewPanes(QList& result, const QList& parts) { for (QList::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (PartPane::Pointer partPane = part.Cast()) { if(partPane->GetPartReference().Cast()) { result.push_back(partPane); } } else if (ILayoutContainer::Pointer container = part.Cast ()) { this->CollectViewPanes(result, container->GetChildren()); } } } void PerspectiveHelper::Deactivate() { if (!active) { return; } this->DisableAllDrag(); // Reparent all views to the main window QWidget* parent = mainLayout->GetParent(); QList children; this->CollectViewPanes(children, mainLayout->GetChildren()); for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::Pointer window = *winIter; CollectViewPanes(children, window->GetChildren()); } // *** Do we even need to do this if detached windows not supported? for (QList::iterator itr = children.begin(); itr != children.end(); ++itr) { PartPane::Pointer part = *itr; part->Reparent(parent); } // Dispose main layout. mainLayout->SetActive(false); // Dispose the detached windows for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { (*iter)->Close(); } active = false; } PerspectiveHelper::~PerspectiveHelper() { mainLayout->Dispose(); mainLayout->DisposeSashes(); } void PerspectiveHelper::DescribeLayout(QString& buf) const { if (detachable) { if (detachedWindowList.size() != 0) { buf.append("detachedWindows ("); //$NON-NLS-1$ for (DetachedWindowsType::const_iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::ConstPointer window = *winIter; QList children = window->GetChildren(); int j = 0; if (children.size() != 0) { buf.append("dWindow ("); //$NON-NLS-1$ for (QList::iterator partIter = children.begin(); partIter != children.end(); ++partIter, ++j) { if (partIter->Cast() != 0) buf.append(partIter->Cast()->GetPlaceHolderId()); else if (partIter->Cast() != 0) buf.append( partIter->Cast()->GetPartReference()->GetPartName()); if (j < (children.size() - 1)) { buf.append(", "); //$NON-NLS-1$ } } buf.append(")"); //$NON-NLS-1$ } } buf.append("), "); //$NON-NLS-1$ } } this->GetLayout()->DescribeLayout(buf); } void PerspectiveHelper::DerefPart(LayoutPart::Pointer part) { // if (part.Cast () != 0) // { // IViewReference::Pointer ref = ((ViewPane) part).getViewReference(); // if (perspective.isFastView(ref)) // { // // Special check: if it's a fast view then it's actual ViewStack // // may only contain placeholders and the stack is represented in // // the presentation by a container placeholder...make sure the // // PartPlaceHolder for 'ref' is removed from the ViewStack // String id = perspective.getFastViewManager().getIdForRef(ref); // LayoutPart parentPart = findPart(id, 0); // if (parentPart.Cast () != 0) // { // ViewStack vs = // (ViewStack) ((ContainerPlaceholder) parentPart).getRealContainer(); // QList kids = vs.getChildren(); // for (int i = 0; i < kids.length; i++) // { // if (kids[i].Cast () != 0) // { // if (ref.getId().equals(kids[i].id)) // vs.remove(kids[i]); // } // } // } // perspective.getFastViewManager().removeViewReference(ref, true, true); // } // } // Get vital part stats before reparenting. ILayoutContainer::Pointer oldContainer = part->GetContainer(); bool wasDocked = part->IsDocked(); Shell::Pointer oldShell = part->GetShell(); // Reparent the part back to the main window part->Reparent(mainLayout->GetParent()); // Update container. if (oldContainer == 0) { return; } oldContainer->Remove(part); ILayoutContainer::ChildrenType children = oldContainer->GetChildren(); if (wasDocked) { bool hasChildren = (children.size()> 0); if (hasChildren) { // make sure one is at least visible int childVisible = 0; for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if ((*iter)->GetControl() != 0) { childVisible++; } } // none visible, then reprarent and remove container if (oldContainer.Cast () != 0) { PartStack::Pointer folder = oldContainer.Cast(); // Is the part in the trim? bool inTrim = false; // // Safety check...there may be no FastViewManager // if (perspective.getFastViewManager() != 0) // inTrim // = perspective.getFastViewManager().getFastViews(folder.getID()).size() // > 0; if (childVisible == 0 && !inTrim) { ILayoutContainer::Pointer parentContainer = folder->GetContainer(); hasChildren = folder->GetChildren().size()> 0; // We maintain the stack as a place-holder if it has children // (which at this point would represent view place-holders) if (hasChildren) { folder->Dispose(); // replace the real container with a ContainerPlaceholder ContainerPlaceholder::Pointer placeholder( new ContainerPlaceholder(folder->GetID())); placeholder->SetRealContainer(folder); parentContainer->Replace(folder, placeholder); } } else if (childVisible == 1) { LayoutTree::Pointer layout = mainLayout->GetLayoutTree(); layout = layout->Find(folder); layout->SetBounds(layout->GetBounds()); } } } if (!hasChildren) { // There are no more children in this container, so get rid of // it if (oldContainer.Cast () != 0) { //BERRY_INFO << "No children left, removing container\n"; LayoutPart::Pointer parent = oldContainer.Cast(); ILayoutContainer::Pointer parentContainer = parent->GetContainer(); if (parentContainer != 0) { parentContainer->Remove(parent); parent->Print(qDebug()); parent->Dispose(); } } } } else if (!wasDocked) { if (children.empty()) { // There are no more children in this container, so get rid of // it // Turn on redraw again just in case it was off. //oldShell.setRedraw(true); DetachedWindow::Pointer w = oldShell->GetData().Cast(); oldShell->Close(); detachedWindowList.removeAll(w); } else { // There are children. If none are visible hide detached // window. bool allInvisible = true; for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if (iter->Cast () == 0) { allInvisible = false; break; } } if (allInvisible) { DetachedPlaceHolder::Pointer placeholder(new DetachedPlaceHolder("", oldShell->GetBounds())); for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { oldContainer->Remove(*iter); (*iter)->SetContainer(placeholder); placeholder->Add(*iter); } detachedPlaceHolderList.push_back(placeholder); DetachedWindow::Pointer w = oldShell->GetData().Cast(); oldShell->Close(); detachedWindowList.removeAll(w); } } } } void PerspectiveHelper::Detach(LayoutPart::Pointer part, int x, int y) { // Detaching is disabled on some platforms .. if (!detachable) { return; } // Calculate detached window size. QSize size = part->GetSize(); if (size.width() == 0 || size.height() == 0) { ILayoutContainer::Pointer container = part->GetContainer(); if (container.Cast () != 0) { size = container.Cast()->GetSize(); } } int width = std::max(size.width(), MIN_DETACH_WIDTH); int height = std::max(size.height(), MIN_DETACH_HEIGHT); // Create detached window. DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); // Open window. window->Create(); window->GetShell()->SetBounds(x, y, width, height); window->Open(); if (part.Cast () != 0) { //window.getShell().setRedraw(false); //parentWidget.setRedraw(false); PartStack::Pointer stack = part.Cast(); LayoutPart::Pointer visiblePart = stack->GetSelection(); ILayoutContainer::ChildrenType children = stack->GetChildren(); for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if (PartPane::Pointer partPane = iter->Cast() // && check it is a view? ) { // remove the part from its current container this->DerefPart(*iter); // add part to detached window. window->Add(*iter); } } if (visiblePart != 0) { this->BringPartToTop(visiblePart); visiblePart->SetFocus(); } //window.getShell().setRedraw(true); //parentWidget.setRedraw(true); } } void PerspectiveHelper::DetachPart(LayoutPart::Pointer part, int x, int y) { // Detaching is disabled on some platforms .. if (!detachable) { return; } // Calculate detached window size. QSize size = part->GetSize(); if (size.width() == 0 || size.height() == 0) { ILayoutContainer::Pointer container = part->GetContainer(); if (container.Cast () != 0) { size = container.Cast()->GetSize(); } } int width = std::max(size.width(), MIN_DETACH_WIDTH); int height = std::max(size.height(), MIN_DETACH_HEIGHT); // Create detached window. DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); // Open window. window->Create(); window->GetShell()->SetBounds(x, y, width, height); window->Open(); // remove the part from its current container this->DerefPart(part); // add part to detached window. window->Add(part); part->SetFocus(); } void PerspectiveHelper::DetachPart(IViewReference::Pointer ref) { PartPane::Pointer pane = ref.Cast()->GetPane(); if (this->CanDetach() && pane != 0) { // if (getMaximizedStack() != 0) // getMaximizedStack().setState(IStackPresentationSite.STATE_RESTORED); QRect bounds = pane->GetParentBounds(); this->DetachPart(pane, bounds.x(), bounds.y()); } } void PerspectiveHelper::AddDetachedPart(LayoutPart::Pointer part) { // Calculate detached window size. QRect bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parentWidget)->GetBounds(); bounds.setX(bounds.x() + (bounds.width() - 300) / 2); bounds.setY(bounds.y() + (bounds.height() - 300) / 2); this->AddDetachedPart(part, bounds); } void PerspectiveHelper::AddDetachedPart(LayoutPart::Pointer part, const QRect& bounds) { // Detaching is disabled on some platforms .. if (!detachable) { this->AddPart(part); return; } // Create detached window. DetachedWindow::Pointer window(new DetachedWindow(page)); detachedWindowList.push_back(window); window->Create(); // add part to detached window. part->CreateControl(window->GetShell()->GetControl()); window->Add(part); // Open window. window->GetShell()->SetBounds(bounds.x(), bounds.y(), bounds.width(), bounds.height()); window->Open(); part->SetFocus(); } void PerspectiveHelper::DisableAllDrag() { DragUtil::RemoveDragTarget(0, dragTarget.data()); } void PerspectiveHelper::EnableAllDrag() { DragUtil::AddDragTarget(0, dragTarget.data()); } LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& id) { return this->FindPart(id, ""); } LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& primaryId, const QString& secondaryId) { //BERRY_INFO << "Looking for part: " << primaryId << ":" << secondaryId << std::endl; // check main window. QList matchingParts; LayoutPart::Pointer part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId, mainLayout->GetChildren(), matchingParts) : this->FindPart(primaryId, mainLayout->GetChildren(), matchingParts); if (part != 0) { return part; } // check each detached windows. for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { DetachedWindow::Pointer window = *iter; part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId, window->GetChildren(), matchingParts) : this->FindPart(primaryId, window->GetChildren(), matchingParts); if (part != 0) { return part; } } for (DetachedPlaceHoldersType::iterator iter = detachedPlaceHolderList.begin(); iter != detachedPlaceHolderList.end(); ++iter) { DetachedPlaceHolder::Pointer holder = *iter; part = (secondaryId != "") ? this->FindPart(primaryId, secondaryId, holder->GetChildren(), matchingParts) : this->FindPart(primaryId, holder->GetChildren(), matchingParts); if (part != 0) { return part; } } //BERRY_INFO << "Looking through the matched parts (count: " << matchingParts.size() << ")\n"; // sort the matching parts if (matchingParts.size()> 0) { std::partial_sort(matchingParts.begin(), (matchingParts.begin()), matchingParts.end(), CompareMatchingParts()); const MatchingPart& mostSignificantPart = matchingParts.front(); return mostSignificantPart.part; } // Not found. return LayoutPart::Pointer(0); } LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& id, const QList& parts, QList& matchingParts) { for (QList::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; // check for part equality, parts with secondary ids fail if (part->GetID() == id) { if (part.Cast () != 0) { PartPane::Pointer pane = part.Cast(); IViewReference::Pointer ref = pane->GetPartReference().Cast(); if (ref->GetSecondaryId() != "") { continue; } } return part; } // check pattern matching placeholders else if (part->IsPlaceHolder() && part.Cast()->HasWildCard()) { QRegExp re(id, Qt::CaseInsensitive); if (re.exactMatch(part->GetID())) { matchingParts.push_back(MatchingPart(part->GetID(), "", part)); } // StringMatcher sm = new StringMatcher(part.getID(), true, false); // if (sm.match(id)) // { // matchingParts .add(new MatchingPart(part.getID(), 0, part)); // } } else if (ILayoutContainer::Pointer layoutContainer = part.Cast()) { part = FindPart(id, layoutContainer->GetChildren(), matchingParts); if (part) { return part; } } } //BERRY_INFO << "Returning 0\n"; return LayoutPart::Pointer(0); } LayoutPart::Pointer PerspectiveHelper::FindPart(const QString& primaryId, const QString& secondaryId, const QList& parts, QList& matchingParts) { for (QList::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; // check containers first if (ILayoutContainer::Pointer layoutContainer = part.Cast()) { LayoutPart::Pointer testPart = FindPart(primaryId, secondaryId, layoutContainer->GetChildren(), matchingParts); if (testPart) { return testPart; } } // check for view part equality if (part.Cast () != 0) { PartPane::Pointer pane = part.Cast(); IViewReference::Pointer ref = pane->GetPartReference().Cast(); if (ref->GetId() == primaryId && ref->GetSecondaryId() == secondaryId) { return part; } } // check placeholders else if (part.Cast () != 0) { QString id = part->GetID(); // optimization: don't bother parsing id if it has no separator -- it can't match QString phSecondaryId = ViewFactory::ExtractSecondaryId(id); if (phSecondaryId == "") { // but still need to check for wildcard case if (id == PartPlaceholder::WILD_CARD) { matchingParts.push_back(MatchingPart(id, "", part)); } continue; } QString phPrimaryId = ViewFactory::ExtractPrimaryId(id); // perfect matching pair if (phPrimaryId == primaryId && phSecondaryId == secondaryId) { return part; } // check for partial matching pair QRegExp pre(phPrimaryId, Qt::CaseInsensitive); if (pre.exactMatch(primaryId)) { QRegExp sre(phSecondaryId, Qt::CaseInsensitive); if (sre.exactMatch(secondaryId)) { matchingParts.push_back(MatchingPart(phPrimaryId, phSecondaryId, part)); } } } } return LayoutPart::Pointer(0); } bool PerspectiveHelper::HasPlaceholder(const QString& id) { return this->HasPlaceholder(id, 0); } bool PerspectiveHelper::HasPlaceholder(const QString& primaryId, const QString& secondaryId) { LayoutPart::Pointer testPart; if (secondaryId == "") { testPart = this->FindPart(primaryId); } else { testPart = this->FindPart(primaryId, secondaryId); } return (testPart != 0 && testPart.Cast () != 0); } PartSashContainer::Pointer PerspectiveHelper::GetLayout() const { return mainLayout; } bool PerspectiveHelper::IsActive() { return active; } float PerspectiveHelper::GetDockingRatio(LayoutPart::Pointer source, LayoutPart::Pointer target) { if ((source.Cast () != 0 || source.Cast () != 0) && target.Cast () != 0) { return 0.25f; } return 0.5f; } void PerspectiveHelper::RemovePart(LayoutPart::Pointer part) { // Reparent the part back to the main window QWidget* parent = mainLayout->GetParent(); part->Reparent(parent); // Replace part with a placeholder ILayoutContainer::Pointer container = part->GetContainer(); if (container != 0) { QString placeHolderId = part->GetPlaceHolderId(); container->Replace(part, LayoutPart::Pointer(new PartPlaceholder(placeHolderId))); // // If the parent is root we're done. Do not try to replace // // it with placeholder. // if (container == mainLayout) // { // return; // } // If the parent is empty replace it with a placeholder. QList children = container->GetChildren(); bool allInvisible = true; for (QList::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { if (childIter->Cast () == 0) { allInvisible = false; break; } } if (allInvisible && (container.Cast () != 0)) { // what type of window are we in? LayoutPart::Pointer cPart = container.Cast(); //Window oldWindow = cPart.getWindow(); bool wasDocked = cPart->IsDocked(); Shell::Pointer oldShell = cPart->GetShell(); if (wasDocked) { // PR 1GDFVBY: ViewStack not disposed when page // closed. if (container.Cast () != 0) { container.Cast()->Dispose(); } // replace the real container with a // ContainerPlaceholder ILayoutContainer::Pointer parentContainer = cPart->GetContainer(); ContainerPlaceholder::Pointer placeholder( new ContainerPlaceholder(cPart->GetID())); placeholder->SetRealContainer(container); parentContainer->Replace(cPart, placeholder); } else { DetachedPlaceHolder::Pointer placeholder( new DetachedPlaceHolder("", oldShell->GetBounds())); //$NON-NLS-1$ for (QList::iterator childIter2 = children.begin(); childIter2 != children.end(); ++childIter2) { (*childIter2)->GetContainer()->Remove(*childIter2); (*childIter2)->SetContainer(placeholder); placeholder->Add(*childIter2); } detachedPlaceHolderList.push_back(placeholder); DetachedWindow::Pointer w = oldShell->GetData().Cast(); oldShell->Close(); detachedWindowList.removeAll(w); } } } } void PerspectiveHelper::ReplacePlaceholderWithPart(LayoutPart::Pointer part) { // Look for a PartPlaceholder that will tell us how to position this // object QList placeholders = this->CollectPlaceholders(); for (int i = 0; i < placeholders.size(); i++) { if (placeholders[i]->GetID() == part->GetID()) { // found a matching placeholder which we can replace with the // new View ILayoutContainer::Pointer container = placeholders[i]->GetContainer(); if (container != 0) { if (ContainerPlaceholder::Pointer containerPlaceholder = container.Cast ()) { // One of the children is now visible so replace the // ContainerPlaceholder with the real container ILayoutContainer::Pointer parentContainer = containerPlaceholder->GetContainer(); container = containerPlaceholder->GetRealContainer().Cast(); if (LayoutPart::Pointer layoutPart = container.Cast ()) { parentContainer->Replace(containerPlaceholder, layoutPart); } containerPlaceholder->SetRealContainer(ILayoutContainer::Pointer(0)); } container->Replace(placeholders[i], part); return; } } } } bool PerspectiveHelper::RestoreState(IMemento::Pointer memento) { // Restore main window. IMemento::Pointer childMem = memento->GetChild(WorkbenchConstants::TAG_MAIN_WINDOW); //IStatus r = mainLayout->RestoreState(childMem); bool r = mainLayout->RestoreState(childMem); // Restore each floating window. if (detachable) { QList detachedWindows(memento->GetChildren( WorkbenchConstants::TAG_DETACHED_WINDOW)); for (QList::iterator iter = detachedWindows.begin(); iter != detachedWindows.end(); ++iter) { DetachedWindow::Pointer win(new DetachedWindow(page)); detachedWindowList.push_back(win); win->RestoreState(*iter); } QList childrenMem(memento->GetChildren( WorkbenchConstants::TAG_HIDDEN_WINDOW)); for (QList::iterator iter = childrenMem.begin(); iter != childrenMem.end(); ++iter) { DetachedPlaceHolder::Pointer holder( new DetachedPlaceHolder("", QRect(0, 0, 0, 0))); holder->RestoreState(*iter); detachedPlaceHolderList.push_back(holder); } } // Get the cached id of the currently maximized stack //maximizedStackId = childMem.getString(IWorkbenchConstants.TAG_MAXIMIZED); return r; } bool PerspectiveHelper::SaveState(IMemento::Pointer memento) { // Persist main window. IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_MAIN_WINDOW); //IStatus r = mainLayout->SaveState(childMem); bool r = mainLayout->SaveState(childMem); if (detachable) { // Persist each detached window. for (DetachedWindowsType::iterator iter = detachedWindowList.begin(); iter != detachedWindowList.end(); ++iter) { childMem = memento->CreateChild(WorkbenchConstants::TAG_DETACHED_WINDOW); (*iter)->SaveState(childMem); } for (DetachedPlaceHoldersType::iterator iter = detachedPlaceHolderList.begin(); iter != detachedPlaceHolderList.end(); ++iter) { childMem = memento->CreateChild(WorkbenchConstants::TAG_HIDDEN_WINDOW); (*iter)->SaveState(childMem); } } // Write out the id of the maximized (View) stack (if any) // NOTE: we only write this out if it's a ViewStack since the // Editor Area is handled by the perspective // if (maximizedStack.Cast () != 0) // { // childMem.putString(IWorkbenchConstants.TAG_MAXIMIZED, // maximizedStack.getID()); // } // else if (maximizedStackId != 0) // { // // Maintain the cache if the perspective has never been activated // childMem.putString(IWorkbenchConstants.TAG_MAXIMIZED, maximizedStackId); // } return r; } void PerspectiveHelper::UpdateBoundsMap() { boundsMap.clear(); // Walk the layout gathering the current bounds of each stack // and the editor area QList kids = mainLayout->GetChildren(); for (QList::iterator iter = kids.begin(); iter != kids.end(); ++iter) { if (iter->Cast () != 0) { PartStack::Pointer vs = iter->Cast(); boundsMap.insert(vs->GetID(), vs->GetBounds()); } else if (iter->Cast () != 0) { EditorSashContainer::Pointer esc = iter->Cast(); boundsMap.insert(esc->GetID(), esc->GetBounds()); } } } void PerspectiveHelper::ResetBoundsMap() { boundsMap.clear(); } QRect PerspectiveHelper::GetCachedBoundsFor(const QString& id) { return boundsMap[id]; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.h index e40519c66a..c63f06bbfc 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveHelper.h @@ -1,573 +1,556 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYPERSPECTIVEHELPER_H_ #define BERRYPERSPECTIVEHELPER_H_ #include "berryWorkbenchPage.h" #include "berryPartPlaceholder.h" #include "berryPerspective.h" #include "berryViewSashContainer.h" #include "berryPartPlaceholder.h" #include "berryDetachedWindow.h" #include "berryDetachedPlaceHolder.h" #include "berryIDragOverListener.h" #include "berryAbstractDropTarget.h" #include "berryPartPane.h" namespace berry { class WorkbenchPage; /** * A perspective presentation is a collection of parts with a layout. Each part * is parented to a main window, so you can create more than one presentation * on a set of parts and change the layout just by activating / deactivating a * presentation. * * In addition, the user can change the position of any part by mouse * manipulation (drag & drop). If a part is removed, we leave a placeholder * behind to indicate where it goes should the part be added back. */ class PerspectiveHelper { friend class PartStack; friend class ViewSashContainer; private: + QScopedPointer tmpStackTrace; + QString tmpViewId; + WorkbenchPage* page; protected: Perspective* perspective; - -protected: QWidget* parentWidget; private: ViewSashContainer::Pointer mainLayout; //private: PartStack maximizedStack; /** * If there is a ViewStack maximized on shutdown the id is * cached and restored into this field on 'restoreState'. * This is then used to bash the ViewStack's presentation state * into the correct value on activation (the startup life-cycle * is such that we have to use this 'latch' because the window * state isn't valid until the activate happens. */ //private: String maximizedStackId; private: typedef QList DetachedWindowsType; DetachedWindowsType detachedWindowList; -private: typedef QList DetachedPlaceHoldersType; DetachedPlaceHoldersType detachedPlaceHolderList; /** * Maps a stack's id to its current bounds * this is used to capture the current bounds of all * stacks -before- starting a maximize (since the * iterative 'minimize' calls cause the intial stack's * bounds to change. */ -private: QHash boundsMap; -private: bool detachable; protected: bool active; // key is the LayoutPart object, value is the PartDragDrop object //private: IPartDropListener partDropListener; private: static const int MIN_DETACH_WIDTH; - -private: static const int MIN_DETACH_HEIGHT; struct DragOverListener: public IDragOverListener { DragOverListener(PerspectiveHelper* perspHelper); IDropTarget::Pointer Drag(QWidget* currentControl, const Object::Pointer& draggedObject, const QPoint& position, const QRect& dragRectangle); private: PerspectiveHelper* perspHelper; }; QScopedPointer dragTarget; struct ActualDropTarget: public AbstractDropTarget { berryObjectMacro(ActualDropTarget); /** * @param part * @param dragRectangle * @since 3.1 */ void SetTarget(PartPane::Pointer part, const QRect& dragRectangle); /** * @param part * @param dragRectangle * @since 3.1 */ void SetTarget(PartStack::Pointer part, const QRect& dragRectangle); ActualDropTarget(PerspectiveHelper* perspHelper, PartPane::Pointer part, const QRect& dragRectangle); ActualDropTarget(PerspectiveHelper* perspHelper, PartStack::Pointer part, const QRect& dragRectangle); void Drop(); CursorType GetCursor(); private: PartPane::Pointer part; PartStack::Pointer stack; QRect dragRectangle; PerspectiveHelper* perspHelper; }; ActualDropTarget::Pointer dropTarget; private: struct MatchingPart { QString pid; QString sid; LayoutPart::Pointer part; bool hasWildcard; int len; MatchingPart(const QString& pid, const QString& sid, LayoutPart::Pointer part); }; struct CompareMatchingParts: public std::binary_function { bool operator()(const MatchingPart& m1, const MatchingPart& m2) const; }; +public: + /** * Constructs a new object. */ -public: PerspectiveHelper(WorkbenchPage* workbenchPage, ViewSashContainer::Pointer mainLayout, Perspective* perspective); /** * Show the presentation. */ -public: void Activate(QWidget* parent); /** * Adds a part to the presentation. If a placeholder exists for the part * then swap the part in. Otherwise, add the part in the bottom right * corner of the presentation. */ -public: void AddPart(LayoutPart::Pointer part); /** * Attaches a part that was previously detached to the mainLayout. * * @param ref */ -public: void AttachPart(IViewReference::Pointer ref); /** * Return whether detachable parts can be supported. */ -public: bool CanDetach(); /** * Bring a part forward so it is visible. * * @return true if the part was brought to top, false if not. */ -public: bool BringPartToTop(LayoutPart::Pointer part); /** * Returns true if the given part is visible. * A part is visible if it's top-level (not in a tab folder) or if it is the top one * in a tab folder. */ -public: bool IsPartVisible(IWorkbenchPartReference::Pointer partRef); /** * Returns true is not in a tab folder or if it is the top one in a tab * folder. */ -public: bool WillPartBeVisible(const QString& partId); -public: bool WillPartBeVisible(const QString& partId, const QString& secondaryId); - /** - * Answer a list of the PartPlaceholder objects. - */ -private: - QList CollectPlaceholders(); - - /** - * Answer a list of the PartPlaceholder objects. - */ -private: - QList CollectPlaceholders( - const QList& parts); - /** * Answer a list of the view panes. */ -public: void CollectViewPanes(QList& result); - /** - * Answer a list of the view panes. - */ -private: - void CollectViewPanes(QList& result, - const QList& parts); - /** * Hide the presentation. */ -public: void Deactivate(); -public: ~PerspectiveHelper(); /** * 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. *

* This is only intended for use by test suites. *

* * @param buf */ -public: void DescribeLayout(QString& buf) const; +private: + /** - * Deref a given part. Deconstruct its container as required. Do not remove - * drag listeners. + * Answer a list of the PartPlaceholder objects. */ -protected: - /* package */void DerefPart(LayoutPart::Pointer part); + QList CollectPlaceholders(); + + /** + * Answer a list of the PartPlaceholder objects. + */ + QList CollectPlaceholders( + const QList& parts); + + /** + * Answer a list of the view panes. + */ + void CollectViewPanes(QList& result, + const QList& parts); /** * Create a detached window containing a part. */ -private: void DetachPart(LayoutPart::Pointer source, int x, int y); -private: void Detach(LayoutPart::Pointer source, int x, int y); +protected: + + /** + * Deref a given part. Deconstruct its container as required. Do not remove + * drag listeners. + */ + void DerefPart(LayoutPart::Pointer part); + /** * Detached a part from the mainLayout. Presently this does not use placeholders * since the current implementation is not robust enough to remember a view's position * in more than one root container. For now the view is simply derefed and will dock * in the default position when attachPart is called. * * By default parts detached this way are set to float on top of the workbench * without docking. It is assumed that people that want to drag a part back onto * the WorkbenchWindow will detach it via drag and drop. * * @param ref */ public: void DetachPart(IViewReference::Pointer ref); /** * Create a detached window containing a part. */ public: void AddDetachedPart(LayoutPart::Pointer part); public: void AddDetachedPart(LayoutPart::Pointer part, const QRect& bounds); /** * disableDragging. */ private: void DisableAllDrag(); /** * enableDragging. */ private: void EnableAllDrag(); /** * Find the first part with a given ID in the presentation. * Wild cards now supported. */ private: LayoutPart::Pointer FindPart(const QString& id); /** * Find the first part that matches the specified * primary and secondary id pair. Wild cards * are supported. */ public: LayoutPart::Pointer FindPart(const QString& primaryId, const QString& secondaryId); /** * Find the first part with a given ID in the presentation. */ private: LayoutPart::Pointer FindPart(const QString& id, const QList& parts, QList& matchingParts); /** * Find the first part that matches the specified * primary and secondary id pair. Wild cards * are supported. */ private: LayoutPart::Pointer FindPart(const QString& primaryId, const QString& secondaryId, const QList& parts, QList& matchingParts); /** * Returns true if a placeholder exists for a given ID. */ public: bool HasPlaceholder(const QString& id); /** * Returns true if a placeholder exists for a given ID. * @since 3.0 */ public: bool HasPlaceholder(const QString& primaryId, const QString& secondaryId); /** * Returns the layout container. */ public: PartSashContainer::Pointer GetLayout() const; /** * Gets the active state. */ public: bool IsActive(); /** * Returns whether the presentation is zoomed. * * NOTE: As of 3.3 this method should always return 'false' * when using the new min/max behavior. It is only used for * legacy 'zoom' handling. */ // public: bool IsZoomed() { // return mainLayout.getZoomedPart() != null; // } /** * @return The currently maxmized stack (if any) */ // public: PartStack::Pointer GetMaximizedStack() { // return maximizedStack; // } /** * Sets the currently maximized stack. Used for query * and 'unZoom' purposes in the 3.3 presentation. * * @param stack The newly maximized stack */ // public: void SetMaximizedStack(PartStack::Pointer stack) { // if (stack == maximizedStack) // return; // // maximizedStack = stack; // } /** * Returns the ratio that should be used when docking the given source * part onto the given target * * @param source newly added part * @param target existing part being dragged over * @return the final size of the source part (wrt the current size of target) * after it is docked */ public: static float GetDockingRatio(LayoutPart::Pointer source, LayoutPart::Pointer target); /** * Returns whether changes to a part will affect zoom. There are a few * conditions for this .. - we are zoomed. - the part is contained in the * main window. - the part is not the zoom part - the part is not a fast * view - the part and the zoom part are not in the same editor workbook * - the part and the zoom part are not in the same view stack. */ // public: bool PartChangeAffectsZoom(LayoutPart::Pointer pane) { // return pane.isObscuredByZoom(); // } /** * Remove all references to a part. */ public: void RemovePart(LayoutPart::Pointer part); /** * Add a part to the presentation. * * Note: unlike all other LayoutParts, PartPlaceholders will still point to * their parent container even when it is inactive. This method relies on this * fact to locate the parent. */ public: void ReplacePlaceholderWithPart(LayoutPart::Pointer part); /** * @see org.blueberry.ui.IPersistable */ public: bool RestoreState(IMemento::Pointer memento); /** * @see org.blueberry.ui.IPersistable */ public: bool SaveState(IMemento::Pointer memento); /** * Zoom in on a particular layout part. */ // public: void zoomIn(IWorkbenchPartReference ref) { // PartPane pane = ((WorkbenchPartReference) ref).getPane(); // // // parentWidget.setRedraw(false); // try { // pane.requestZoomIn(); // } finally { // parentWidget.setRedraw(true); // } // } /** * Zoom out. */ // public: void zoomOut() { // // New 3.3 behavior // if (Perspective.useNewMinMax(perspective)) { // if (maximizedStack != null) // maximizedStack.setState(IStackPresentationSite.STATE_RESTORED); // return; // } // // LayoutPart zoomPart = mainLayout.getZoomedPart(); // if (zoomPart != null) { // zoomPart.requestZoomOut(); // } // } /** * Forces the perspective to have no zoomed or minimized parts. * This is used when switching to the 3.3 presentation... */ // public: void forceNoZoom() { // // Ensure that nobody's zoomed // zoomOut(); // // // Now, walk the layout ensuring that nothing is minimized // LayoutPart[] kids = mainLayout.getChildren(); // for (int i = 0; i < kids.length; i++) { // if (kids[i] instanceof ViewStack) { // ((ViewStack)kids[i]).setMinimized(false); // } // else if (kids[i] instanceof EditorSashContainer) { // LayoutPart[] editorStacks = ((EditorSashContainer)kids[i]).getChildren(); // for (int j = 0; j < editorStacks.length; j++) { // if (editorStacks[j] instanceof EditorStack) { // ((EditorStack)editorStacks[j]).setMinimized(false); // } // } // } // } // } /** * Captures the current bounds of all ViewStacks and the editor * area and puts them into an ID -> QRect map. This info is * used to cache the bounds so that we can correctly place minimized * stacks during a 'maximized' operation (where the iterative min's * affect the current layout while being performed. */ public: void UpdateBoundsMap(); /** * Resets the bounds map so that it won't interfere with normal minimize * operations */ public: void ResetBoundsMap(); public: QRect GetCachedBoundsFor(const QString& id); }; } #endif /* BERRYPERSPECTIVEHELPER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveParameterValues.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveParameterValues.cpp new file mode 100644 index 0000000000..ec913195d0 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveParameterValues.cpp @@ -0,0 +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 "berryPerspectiveParameterValues.h" + +#include +#include + +#include + +namespace berry { + +QHash PerspectiveParameterValues::GetParameterValues() const +{ + QHash values; + + const QList perspectives = PlatformUI::GetWorkbench() + ->GetPerspectiveRegistry()->GetPerspectives(); + for (int i = 0; i < perspectives.size(); i++) + { + const IPerspectiveDescriptor::Pointer& perspective = perspectives[i]; + values.insert(perspective->GetLabel(), perspective->GetId()); + } + + return values; +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveParameterValues.h similarity index 56% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveParameterValues.h index 1fd4128836..4371bdec06 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveParameterValues.h @@ -1,45 +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 BERRYPERSPECTIVEPARAMETERVALUES_H +#define BERRYPERSPECTIVEPARAMETERVALUES_H -#ifndef BERRYMMMENULISTENER_H -#define BERRYMMMENULISTENER_H +#include -#include +namespace berry { -namespace berry -{ - -class MenuManager; - -class MMMenuListener : public QObject +/** + * Provides the parameter values for the show perspective command. + */ +class PerspectiveParameterValues : public QObject, public IParameterValues { Q_OBJECT - berry::MenuManager* mm; - public: - MMMenuListener(berry::MenuManager* mm); - -private: - - Q_SLOT void HandleAboutToShow(); + QHash GetParameterValues() const; }; } -#endif // BERRYMMMENULISTENER_H +#endif // BERRYPERSPECTIVEPARAMETERVALUES_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp index a8b181b43c..6f4c0eda2b 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.cpp @@ -1,590 +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. ===================================================================*/ #include "berryPerspectiveRegistry.h" #include "berryWorkbench.h" +#include "berryWorkbenchPage.h" #include "berryWorkbenchPlugin.h" +#include "berryPreferenceConstants.h" +#include "berryPerspective.h" #include "berryPerspectiveRegistryReader.h" +#include "berryPlatformUI.h" +#include "handlers/berryClosePerspectiveHandler.h" +#include "berryIPreferencesService.h" +#include "berryIBerryPreferences.h" +#include "berryIExtension.h" +#include "berryIExtensionTracker.h" namespace berry { const QString PerspectiveRegistry::EXT = "_persp.xml"; const QString PerspectiveRegistry::ID_DEF_PERSP = "PerspectiveRegistry.DEFAULT_PERSP"; const QString PerspectiveRegistry::PERSP = "_persp"; const char PerspectiveRegistry::SPACE_DELIMITER = ' '; -PerspectiveRegistry::PerspectiveRegistry() +class PerspectiveRegistry::PreferenceChangeListener { - //IExtensionTracker tracker = PlatformUI.getWorkbench() .getExtensionTracker(); - //tracker.registerHandler(this, null); - //this->InitializePreferenceChangeListener(); - //WorkbenchPlugin::GetDefault()->GetPreferenceStore()->AddPropertyChangeListener( - // preferenceListener); + PerspectiveRegistry* m_Registry; + +public: + + PreferenceChangeListener(PerspectiveRegistry* registry) + : m_Registry(registry) + {} + + void PropertyChange(const IBerryPreferences::ChangeEvent& event) + { + /* + * To ensure that no custom perspective definitions are + * deleted when preferences are imported, merge old and new + * values + */ + if (event.GetProperty().endsWith(PERSP)) + { + /* A Perspective is being changed, merge */ + this->MergePerspectives(event); + } + else if (event.GetProperty() == PreferenceConstants::PERSPECTIVES) + { + /* The list of perpsectives is being changed, merge */ + UpdatePreferenceList(event.GetSource()); + } + } + + void MergePerspectives(const IBerryPreferences::ChangeEvent& event) + { + IBerryPreferences* store = event.GetSource(); + if (event.GetNewValue().isNull() || + event.GetNewValue().isEmpty()) + { + /* + * Perpsective is being removed; if the user has deleted or + * reverted a custom perspective, let the change pass + * through. Otherwise, restore the custom perspective entry + */ + + // Find the matching descriptor in the registry + QList perspectiveList = m_Registry->GetPerspectives(); + for (int i = 0; i < perspectiveList.size(); i++) + { + QString id = perspectiveList[i]->GetId(); + if (event.GetProperty() == id + PERSP) + { // found + // descriptor + // see if the perspective has been flagged for + // reverting or deleting + if (!m_Registry->perspToRemove.contains(id)) + { // restore + store->Put(id + PERSP, event.GetOldValue()); + } + else + { // remove element from the list + m_Registry->perspToRemove.removeAll(id); + } + } + } + } + else if ((event.GetOldValue().isNull() || event.GetOldValue().isEmpty())) + { + + /* + * New perspective is being added, update the + * perspectiveRegistry to contain the new custom perspective + */ + + QString id = event.GetProperty().left(event.GetProperty().lastIndexOf(PERSP)); + if (m_Registry->FindPerspectiveWithId(id).IsNull()) + { + // perspective does not already exist in registry, add + // it + PerspectiveDescriptor::Pointer desc(new PerspectiveDescriptor( + QString::null, QString::null, PerspectiveDescriptor::Pointer())); + std::stringstream reader; + std::string xmlStr = event.GetNewValue().toStdString(); + reader.str(xmlStr); + try + { + XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(reader); + desc->RestoreState(memento); + m_Registry->AddPerspective(desc); + } + catch (const WorkbenchException& e) + { + //m_Registry->UnableToLoadPerspective(e.getStatus()); + m_Registry->UnableToLoadPerspective(e.what()); + } + } + } + /* If necessary, add to the list of perspectives */ + this->UpdatePreferenceList(store); + } + + void UpdatePreferenceList(IBerryPreferences* store) + { + QList perspectiveList = m_Registry->GetPerspectives(); + QStringList perspBuffer; + for (int i = 0; i < perspectiveList.size(); i++) + { + PerspectiveDescriptor::Pointer desc = perspectiveList[i].Cast(); + if (m_Registry->HasCustomDefinition(desc)) + { + perspBuffer.push_back(desc->GetId()); + } + } + store->Put(PreferenceConstants::PERSPECTIVES, perspBuffer.join(QString(SPACE_DELIMITER))); + } +}; +PerspectiveRegistry::PerspectiveRegistry() + : preferenceListener(new PreferenceChangeListener(this)) +{ + IExtensionTracker* tracker = PlatformUI::GetWorkbench()->GetExtensionTracker(); + tracker->RegisterHandler(this, QString("org.blueberry.ui.perspectives")); + + berry::IBerryPreferences::Pointer prefs = + WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences().Cast(); + prefs->OnPropertyChanged += + berry::MessageDelegate1( + preferenceListener.data(), &PreferenceChangeListener::PropertyChange); } void PerspectiveRegistry::AddPerspective(PerspectiveDescriptor::Pointer desc) { if (desc == 0) { return; } this->Add(desc); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::CreatePerspective(const QString& label, IPerspectiveDescriptor::Pointer originalDescriptor) { // Sanity check to avoid invalid or duplicate labels. if (!this->ValidateLabel(label)) { return IPerspectiveDescriptor::Pointer(0); } if (this->FindPerspectiveWithLabel(label) != 0) { return IPerspectiveDescriptor::Pointer(0); } // Calculate ID. QString id(label); id = id.replace(' ', '_').trimmed(); // Create descriptor. PerspectiveDescriptor::Pointer desc( new PerspectiveDescriptor(id, label, originalDescriptor.Cast())); this->Add(desc); return IPerspectiveDescriptor::Pointer(static_cast(desc.GetPointer())); } void PerspectiveRegistry::RevertPerspectives( const QList& perspToRevert) { // indicate that the user is removing these perspectives for (QList::const_iterator iter = perspToRevert.begin(); iter != perspToRevert.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; perspToRemove.push_back(desc->GetId()); desc->RevertToPredefined(); } } void PerspectiveRegistry::DeletePerspectives( const QList& perspToDelete) { for (QList::const_iterator iter = perspToDelete.begin(); iter != perspToDelete.end(); ++iter) { this->DeletePerspective(*iter); } } void PerspectiveRegistry::DeletePerspective(IPerspectiveDescriptor::Pointer in) { PerspectiveDescriptor::Pointer desc = in.Cast(); // Don't delete predefined perspectives if (!desc->IsPredefined()) { perspToRemove.push_back(desc->GetId()); perspectives.removeAll(desc); desc->DeleteCustomDefinition(); this->VerifyDefaultPerspective(); } } IPerspectiveDescriptor::Pointer PerspectiveRegistry::FindPerspectiveWithId(const QString& id) { for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; if (desc->GetId() == id) { // if (WorkbenchActivityHelper.restrictUseOf(desc)) // { // return null; // } return desc; } } return IPerspectiveDescriptor::Pointer(0); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::FindPerspectiveWithLabel( const QString& label) { for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { PerspectiveDescriptor::Pointer desc = *iter; if (desc->GetLabel() == label) { // if (WorkbenchActivityHelper.restrictUseOf(desc)) // { // return 0; // } return desc; } } return IPerspectiveDescriptor::Pointer(0); } QString PerspectiveRegistry::GetDefaultPerspective() { return defaultPerspID; } QList PerspectiveRegistry::GetPerspectives() { // Collection descs = WorkbenchActivityHelper.restrictCollection(perspectives, // new ArrayList()); // return (IPerspectiveDescriptor[]) descs.toArray( // new IPerspectiveDescriptor[descs.size()]); QList result; for (QList::iterator iter = perspectives.begin(); iter != perspectives.end(); ++iter) { result.push_back(iter->Cast()); } return result; } void PerspectiveRegistry::Load() { // Load the registries. this->LoadPredefined(); this->LoadCustom(); // Get default perspective. // Get it from the R1.0 dialog settings first. Fixes bug 17039 // IDialogSettings dialogSettings = // WorkbenchPlugin.getDefault() .getDialogSettings(); // QString str = dialogSettings.get(ID_DEF_PERSP); // if (str != null && str.length() > 0) // { // this->SetDefaultPerspective(str); // dialogSettings.put(ID_DEF_PERSP, ""); //$NON-NLS-1$ // } this->VerifyDefaultPerspective(); } -//void PerspectiveRegistry::SaveCustomPersp(PerspectiveDescriptor::Pointer desc, -// XMLMemento::Pointer memento) -//{ -// -// IPreferenceStore store = WorkbenchPlugin.getDefault() .getPreferenceStore(); -// -// // Save it to the preference store. -// Writer writer = new StringWriter(); -// -// memento.save(writer); -// writer.close(); -// store.setValue(desc.getId() + PERSP, writer.toString()); -// -//} - -IMemento::Pointer PerspectiveRegistry::GetCustomPersp(const QString& /*id*/) +void PerspectiveRegistry::SaveCustomPersp(PerspectiveDescriptor::Pointer desc, + XMLMemento* memento) { - //TODO CustomPersp -// Reader reader = null; -// -// IPreferenceStore store = WorkbenchPlugin.getDefault() .getPreferenceStore(); -// QString xmlString = store.getString(id + PERSP); -// if (xmlString != null && xmlString.length() != 0) -// { // defined in store -// reader = new StringReader(xmlString); -// } -// XMLMemento memento = XMLMemento.createReadRoot(reader); -// reader.close(); -// return memento; - return IMemento::Pointer(0); + IPreferencesService* prefs = WorkbenchPlugin::GetDefault()->GetPreferencesService(); + + // Save it to the preference store. + std::stringstream ss; + memento->Save(ss); + prefs->GetSystemPreferences()->Put(desc->GetId() + PERSP, QString::fromStdString(ss.str())); +} + +IMemento::Pointer PerspectiveRegistry::GetCustomPersp(const QString& id) +{ + std::stringstream ss; + + IPreferencesService* prefs = WorkbenchPlugin::GetDefault()->GetPreferencesService(); + std::string xmlString = prefs->GetSystemPreferences()->Get(id + PERSP, QString::null).toStdString(); + if (!xmlString.empty()) + { // defined in store + ss.str(xmlString); + } + XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(ss); + return memento; } void PerspectiveRegistry::SetDefaultPerspective(const QString& id) { IPerspectiveDescriptor::Pointer desc = this->FindPerspectiveWithId(id); if (desc != 0) { defaultPerspID = id; //TODO Preferences // PrefUtil.getAPIPreferenceStore().setValue( // IWorkbenchPreferenceConstants.DEFAULT_PERSPECTIVE_ID, id); } } bool PerspectiveRegistry::ValidateLabel(const QString& label) { return !label.trimmed().isEmpty(); } IPerspectiveDescriptor::Pointer PerspectiveRegistry::ClonePerspective(const QString& id, const QString& label, IPerspectiveDescriptor::Pointer originalDescriptor) { // Check for invalid labels if (label == "" || label.trimmed().isEmpty()) { throw Poco::InvalidArgumentException(); } // Check for duplicates IPerspectiveDescriptor::Pointer desc = this->FindPerspectiveWithId(id); if (desc != 0) { throw Poco::InvalidArgumentException(); } // Create descriptor. desc = new PerspectiveDescriptor(id, label, originalDescriptor.Cast()); this->Add(desc.Cast()); return desc; } void PerspectiveRegistry::RevertPerspective(IPerspectiveDescriptor::Pointer perspToRevert) { PerspectiveDescriptor::Pointer desc = perspToRevert.Cast(); perspToRemove.push_back(desc->GetId()); desc->RevertToPredefined(); } PerspectiveRegistry::~PerspectiveRegistry() { -// PlatformUI.getWorkbench().getExtensionTracker().unregisterHandler(this); -// WorkbenchPlugin.getDefault().getPreferenceStore() .removePropertyChangeListener( +// PlatformUI::GetWorkbench()->GetExtensionTracker()->UnregisterHandler(this); +// WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences()->RemovePropertyChangeListener( // preferenceListener); } -void PerspectiveRegistry::DeleteCustomDefinition(PerspectiveDescriptor::Pointer /*desc*/) +void PerspectiveRegistry::DeleteCustomDefinition(PerspectiveDescriptor::Pointer desc) { - //TODO Preferences // remove the entry from the preference store. - //IPreferenceStore store = WorkbenchPlugin.getDefault() .getPreferenceStore(); - - /* - * To delete the perspective definition from the preference store, use - * the setToDefault method. Since no default is defined, this will - * remove the entry - */ - //store.setToDefault(desc.getId() + PERSP); + IPreferencesService* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); + store->GetSystemPreferences()->Remove(desc->GetId() + PERSP); } -bool PerspectiveRegistry::HasCustomDefinition(PerspectiveDescriptor::ConstPointer /*desc*/) const +bool PerspectiveRegistry::HasCustomDefinition(PerspectiveDescriptor::ConstPointer desc) const { - //TODO Preferences - //IPreferenceStore store = WorkbenchPlugin::GetDefault()->GetPreferenceStore(); - //return store.contains(desc.getId() + PERSP); - return false; -} - -void PerspectiveRegistry::InitializePreferenceChangeListener() -{ -// preferenceListener = new IPropertyChangeListener() -// { -// public void propertyChange(PropertyChangeEvent event) -// { -// /* -// * To ensure the that no custom perspective definitions are -// * deleted when preferences are imported, merge old and new -// * values -// */ -// if (event.getProperty().endsWith(PERSP)) -// { -// /* A Perspective is being changed, merge */ -// mergePerspectives(event); -// } -// else if (event.getProperty().equals( -// IPreferenceConstants.PERSPECTIVES)) -// { -// /* The list of perpsectives is being changed, merge */ -// updatePreferenceList((IPreferenceStore) event.getSource()); -// } -// } -// -// void MergePerspectives(PropertyChangeEvent::Pointer event) -// { -// IPreferenceStore store = (IPreferenceStore) event.getSource(); -// if (event.getNewValue() == null -// || event.getNewValue().equals("")) -// { //$NON-NLS-1$ -// /* -// * Perpsective is being removed; if the user has deleted or -// * reverted a custom perspective, let the change pass -// * through. Otherwise, restore the custom perspective entry -// */ -// -// // Find the matching descriptor in the registry -// IPerspectiveDescriptor[] perspectiveList = getPerspectives(); -// for (int i = 0; i < perspectiveList.length; i++) -// { -// QString id = perspectiveList[i].getId(); -// if (event.getProperty().equals(id + PERSP)) -// { // found -// // descriptor -// // see if the perspective has been flagged for -// // reverting or deleting -// if (!perspToRemove.contains(id)) -// { // restore -// store.setValue(id + PERSP, (QString) event -// .getOldValue()); -// } -// else -// { // remove element from the list -// perspToRemove.remove(id); -// } -// } -// } -// } -// else if ((event.getOldValue() == null || event.getOldValue() -// .equals(""))) -// { //$NON-NLS-1$ -// -// /* -// * New perspective is being added, update the -// * perspectiveRegistry to contain the new custom perspective -// */ -// -// QString id = event.getProperty().substring(0, -// event.getProperty().lastIndexOf(PERSP)); -// if (findPerspectiveWithId(id) == null) -// { -// // perspective does not already exist in registry, add -// // it -// PerspectiveDescriptor desc = new PerspectiveDescriptor( -// null, null, null); -// StringReader reader = new StringReader((QString) event -// .getNewValue()); -// try -// { -// XMLMemento memento = XMLMemento -// .createReadRoot(reader); -// desc.restoreState(memento); -// addPerspective(desc); -// } -// catch (WorkbenchException e) -// { -// unableToLoadPerspective(e.getStatus()); -// } -// } -// } -// /* If necessary, add to the list of perspectives */ -// updatePreferenceList(store); -// } -// -// void UpdatePreferenceList(IPreferenceStore store) -// { -// IPerspectiveDescriptor[] perspectiveList = getPerspectives(); -// StringBuffer perspBuffer = new StringBuffer(); -// for (int i = 0; i < perspectiveList.length; i++) -// { -// PerspectiveDescriptor desc = (PerspectiveDescriptor) perspectiveList[i]; -// if (hasCustomDefinition(desc)) -// { -// perspBuffer.append(desc.getId()) -// .append(SPACE_DELIMITER); -// } -// } -// QString newList = perspBuffer.toString().trim(); -// store.setValue(IPreferenceConstants.PERSPECTIVES, newList); -// } -// }; + IPreferencesService* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); + return store->GetSystemPreferences()->Keys().contains(desc->GetId() + PERSP); } void PerspectiveRegistry::Add(PerspectiveDescriptor::Pointer desc) { perspectives.push_back(desc); -// IConfigurationElement::Pointer element = desc->GetConfigElement(); -// if (element != 0) -// { -// PlatformUI::GetWorkbench().getExtensionTracker().registerObject( -// element.getDeclaringExtension(), desc, IExtensionTracker.REF_WEAK); -// } + IConfigurationElement::Pointer element = desc->GetConfigElement(); + if (element.IsNotNull()) + { + PlatformUI::GetWorkbench()->GetExtensionTracker()->RegisterObject( + element->GetDeclaringExtension(), desc, IExtensionTracker::REF_WEAK); + } } void PerspectiveRegistry::InternalDeletePerspective(PerspectiveDescriptor::Pointer desc) { perspToRemove.push_back(desc->GetId()); perspectives.removeAll(desc); desc->DeleteCustomDefinition(); this->VerifyDefaultPerspective(); } void PerspectiveRegistry::LoadCustom() { -// Reader reader = null; -// -// /* Get the entries from the Preference store */ -// IPreferenceStore store = WorkbenchPlugin.getDefault() .getPreferenceStore(); -// -// /* Get the space-delimited list of custom perspective ids */ -// QString customPerspectives = store .getString( -// IPreferenceConstants.PERSPECTIVES); -// QString[] perspectivesList = StringConverter.asArray(customPerspectives); -// -// for (int i = 0; i < perspectivesList.length; i++) -// { -// try -// { -// QString xmlString = store.getString(perspectivesList[i] + PERSP); -// if (xmlString != null && xmlString.length() != 0) -// { -// reader = new StringReader(xmlString); -// } -// -// // Restore the layout state. -// XMLMemento memento = XMLMemento.createReadRoot(reader); -// PerspectiveDescriptor newPersp = -// new PerspectiveDescriptor(null, null, null); -// newPersp.restoreState(memento); -// QString id = newPersp.getId(); -// IPerspectiveDescriptor oldPersp = findPerspectiveWithId(id); -// if (oldPersp == null) -// { -// add(newPersp); -// } -// reader.close(); -// } catch (IOException e) -// { -// unableToLoadPerspective(null); -// } catch (WorkbenchException e) -// { -// unableToLoadPerspective(e.getStatus()); -// } -// } -// + QScopedPointer reader; + + /* Get the entries from the Preference store */ + IPreferencesService* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); + + IPreferences::Pointer prefs = store->GetSystemPreferences(); + + /* Get the space-delimited list of custom perspective ids */ + QString customPerspectives = prefs->Get(PreferenceConstants::PERSPECTIVES, QString::null); + QStringList perspectivesList = customPerspectives.split(' ', QString::SkipEmptyParts); + + for (int i = 0; i < perspectivesList.size(); i++) + { + try + { + std::string xmlString = prefs->Get(perspectivesList[i] + PERSP, QString::null).toStdString(); + if (!xmlString.empty()) + { + reader.reset(new std::stringstream(xmlString)); + //reader->exceptions(std::ios_base::failbit); + } + else + { + throw WorkbenchException(QString("Description of '%1' perspective could not be found.").arg(perspectivesList[i])); + } + + // Restore the layout state. + XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(*reader); + PerspectiveDescriptor::Pointer newPersp(new PerspectiveDescriptor( + QString::null, QString::null, + PerspectiveDescriptor::Pointer(nullptr))); + newPersp->RestoreState(memento); + QString id = newPersp->GetId(); + IPerspectiveDescriptor::Pointer oldPersp = FindPerspectiveWithId(id); + if (oldPersp.IsNull()) + { + Add(newPersp); + } + } + catch (const std::ios_base::failure&) + { + UnableToLoadPerspective(QString::null); + } + catch (const WorkbenchException& e) + { + UnableToLoadPerspective(e.message()); + } + } + // // Get the entries from files, if any // // if -data @noDefault specified the state location may not be // // initialized // IPath path = WorkbenchPlugin.getDefault().getDataLocation(); // if (path == null) // { // return; // } -// + // File folder = path.toFile(); -// + // if (folder.isDirectory()) // { // File[] fileList = folder.listFiles(); // int nSize = fileList.length; // for (int nX = 0; nX < nSize; nX++) // { // File file = fileList[nX]; // if (file.getName().endsWith(EXT)) // { // // get the memento // InputStream stream = null; // try // { // stream = new FileInputStream(file); // reader = new BufferedReader(new InputStreamReader(stream, "utf-8")); //$NON-NLS-1$ -// + // // Restore the layout state. // XMLMemento memento = XMLMemento.createReadRoot(reader); // PerspectiveDescriptor newPersp = // new PerspectiveDescriptor(null, null, null); // newPersp.restoreState(memento); // IPerspectiveDescriptor oldPersp = findPerspectiveWithId( // newPersp .getId()); // if (oldPersp == null) // { // add(newPersp); // } -// + // // save to the preference store // saveCustomPersp(newPersp, memento); -// + // // delete the file // file.delete(); -// + // reader.close(); // stream.close(); // } catch (IOException e) // { // unableToLoadPerspective(null); // } catch (WorkbenchException e) // { // unableToLoadPerspective(e.getStatus()); // } // } // } // } } void PerspectiveRegistry::UnableToLoadPerspective(const QString& status) { QString msg = "Unable to load perspective"; if (status == "") { WorkbenchPlugin::Log(msg); //IStatus errStatus = // new Status(IStatus.ERR, WorkbenchPlugin.PI_WORKBENCH, msg); //StatusManager.getManager().handle(errStatus, StatusManager.SHOW); } else { WorkbenchPlugin::Log(status + ": " + msg); //IStatus errStatus = StatusUtil.newStatus(status, msg); //StatusManager.getManager().handle(errStatus, StatusManager.SHOW); } } void PerspectiveRegistry::LoadPredefined() { - PerspectiveRegistryReader reader; - reader.ReadPerspectives(this); + PerspectiveRegistryReader reader(this); + reader.ReadPerspectives(Platform::GetExtensionRegistry()); } void PerspectiveRegistry::VerifyDefaultPerspective() { // Step 1: Try current defPerspId value. IPerspectiveDescriptor::Pointer desc; if (defaultPerspID != "") { desc = this->FindPerspectiveWithId(defaultPerspID); } if (desc != 0) { return; } // Step 2. Read default value. //TODO Preferences // QString str = PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.DEFAULT_PERSPECTIVE_ID); // if (str != null && str.length() > 0) // { // desc = this->FindPerspectiveWithId(str); // } // if (desc != 0) // { // defaultPerspID = str; // return; // } // Step 3. Use application-specific default defaultPerspID = Workbench::GetInstance()->GetDefaultPerspectiveId(); } +void PerspectiveRegistry::RemoveExtension(const IExtension::Pointer& /*source*/, + const QList& objects) +{ + for (int i = 0; i < objects.size(); i++) + { + if (PerspectiveDescriptor::Pointer desc = objects[i].Cast()) + { + // close the perspective in all windows + QList windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows(); + for (int w = 0; w < windows.size(); ++w) + { + IWorkbenchWindow::Pointer window = windows[w]; + QList pages = window->GetPages(); + for (int p = 0; p < pages.size(); ++p) + { + WorkbenchPage::Pointer page = pages[p].Cast(); + ClosePerspectiveHandler::ClosePerspective(page, page->FindPerspective(desc)); + } + } + + // ((Workbench)PlatformUI.getWorkbench()).getPerspectiveHistory().removeItem(desc); + + this->InternalDeletePerspective(desc); + } + } +} + +void PerspectiveRegistry::AddExtension(IExtensionTracker* /*tracker*/, + const IExtension::Pointer& addedExtension) +{ + QList addedElements = addedExtension->GetConfigurationElements(); + for (int i = 0; i < addedElements.size(); i++) + { + PerspectiveRegistryReader reader(this); + reader.ReadElement(addedElements[i]); + } + } + } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.h index e533a370c7..b94ec5ab96 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistry.h @@ -1,309 +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. ===================================================================*/ #ifndef BERRYPERSPECTIVEREGISTRY_H_ #define BERRYPERSPECTIVEREGISTRY_H_ #include "berryIPerspectiveRegistry.h" +#include "berryIExtensionChangeHandler.h" #include "berryPerspectiveDescriptor.h" #include namespace berry { +class XMLMemento; + /** * Perspective registry. */ -class PerspectiveRegistry : public IPerspectiveRegistry { - // IExtensionChangeHandler { +class PerspectiveRegistry : public IPerspectiveRegistry, + public IExtensionChangeHandler +{ friend class PerspectiveDescriptor; private: QString defaultPerspID; static const QString EXT; // = "_persp.xml"; static const QString ID_DEF_PERSP; // = "PerspectiveRegistry.DEFAULT_PERSP"; static const QString PERSP; // = "_persp"; static const char SPACE_DELIMITER; // = ' '; QList perspectives; // keep track of the perspectives the user has selected to remove or revert QList perspToRemove; - //IPropertyChangeListener::Pointer preferenceListener; + class PreferenceChangeListener; + QScopedPointer preferenceListener; + + virtual void AddExtension(IExtensionTracker* tracker, const SmartPointer& extension); + + virtual void RemoveExtension(const SmartPointer& extension, + const QList >& objects); public: /** * Construct a new registry. */ PerspectiveRegistry(); /** - * Adds a perspective. This is typically used by the reader. - * - * @param desc - */ - void AddPerspective(PerspectiveDescriptor::Pointer desc); - - /** - * Create a new perspective. - * - * @param label - * the name of the new descriptor - * @param originalDescriptor - * the descriptor on which to base the new descriptor - * @return a new perspective descriptor or null if the - * creation failed. - */ - IPerspectiveDescriptor::Pointer CreatePerspective(const QString& label, - IPerspectiveDescriptor::Pointer originalDescriptor); - - /** - * Reverts a list of perspectives back to the plugin definition - * - * @param perspToRevert - */ - void RevertPerspectives(const QList& perspToRevert); - - /** - * Deletes a list of perspectives - * - * @param perspToDelete - */ - void DeletePerspectives(const QList& perspToDelete); - - /** - * Delete a perspective. Has no effect if the perspective is defined in an - * extension. - * - * @param in - */ - void DeletePerspective(IPerspectiveDescriptor::Pointer in); - - /* - * (non-Javadoc) - * - * @see org.blueberry.ui.IPerspectiveRegistry#findPerspectiveWithId(java.lang.QString) - */ - IPerspectiveDescriptor::Pointer FindPerspectiveWithId(const QString& id); - - /* - * (non-Javadoc) - * - * @see org.blueberry.ui.IPerspectiveRegistry#findPerspectiveWithLabel(java.lang.QString) - */ - IPerspectiveDescriptor::Pointer FindPerspectiveWithLabel(const QString& label); - - /** - * @see IPerspectiveRegistry#getDefaultPerspective() - */ - QString GetDefaultPerspective(); - - /* - * (non-Javadoc) - * - * @see org.blueberry.ui.IPerspectiveRegistry#getPerspectives() - */ - QList GetPerspectives(); - - /** - * Loads the registry. - */ - void Load(); - - /** - * Saves a custom perspective definition to the preference store. - * - * @param desc - * the perspective - * @param memento - * the memento to save to - * @throws IOException - */ - // void SaveCustomPersp(PerspectiveDescriptor::Pointer desc, XMLMemento::Pointer memento); - - /** - * Gets the Custom perspective definition from the preference store. - * - * @param id - * the id of the perspective to find - * @return IMemento a memento containing the perspective description - * - * @throws WorkbenchException - * @throws IOException - */ - IMemento::Pointer GetCustomPersp(const QString& id); - - /** - * @see IPerspectiveRegistry#setDefaultPerspective(QString) - */ - void SetDefaultPerspective(const QString& id); - - /** - * Return true if a label is valid. This checks only the - * given label in isolation. It does not check whether the given label is - * used by any existing perspectives. - * - * @param label - * the label to test - * @return whether the label is valid - */ - bool ValidateLabel(const QString& label); - - /* - * (non-Javadoc) - * - * @see org.blueberry.ui.IPerspectiveRegistry#clonePerspective(java.lang.QString, - * java.lang.QString, org.blueberry.ui.IPerspectiveDescriptor) - */ - IPerspectiveDescriptor::Pointer ClonePerspective(const QString& id, const QString& label, - IPerspectiveDescriptor::Pointer originalDescriptor); - - /* - * (non-Javadoc) - * - * @see org.blueberry.ui.IPerspectiveRegistry#revertPerspective(org.blueberry.ui.IPerspectiveDescriptor) - */ - void RevertPerspective(IPerspectiveDescriptor::Pointer perspToRevert); - - /** - * Dispose the receiver. - */ - ~PerspectiveRegistry(); - - /* - * (non-Javadoc) - * - * @see org.blueberry.core.runtime.dynamicHelpers.IExtensionChangeHandler#removeExtension(org.blueberry.core.runtime.IExtension, - * java.lang.Object[]) - */ -// void removeExtension(IExtension source, Object[] objects) { -// for (int i = 0; i < objects.length; i++) { -// if (objects[i] instanceof PerspectiveDescriptor) { -// // close the perspective in all windows -// IWorkbenchWindow[] windows = PlatformUI.getWorkbench() -// .getWorkbenchWindows(); -// PerspectiveDescriptor desc = (PerspectiveDescriptor) objects[i]; -// for (int w = 0; w < windows.length; ++w) { -// IWorkbenchWindow window = windows[w]; -// IWorkbenchPage[] pages = window.getPages(); -// for (int p = 0; p < pages.length; ++p) { -// WorkbenchPage page = (WorkbenchPage) pages[p]; -// ClosePerspectiveHandler.closePerspective(page, page -// .findPerspective(desc)); -// } -// } -// -// // ((Workbench)PlatformUI.getWorkbench()).getPerspectiveHistory().removeItem(desc); -// -// internalDeletePerspective(desc); -// } -// -// } -// } - - /* - * (non-Javadoc) - * - * @see org.blueberry.core.runtime.dynamicHelpers.IExtensionChangeHandler#addExtension(org.blueberry.core.runtime.dynamicHelpers.IExtensionTracker, - * org.blueberry.core.runtime.IExtension) - */ -// void addExtension(IExtensionTracker tracker, -// IExtension addedExtension) { -// IConfigurationElement[] addedElements = addedExtension -// .getConfigurationElements(); -// for (int i = 0; i < addedElements.length; i++) { -// PerspectiveRegistryReader reader = new PerspectiveRegistryReader( -// this); -// reader.readElement(addedElements[i]); -// } -// } + * Adds a perspective. This is typically used by the reader. + * + * @param desc + */ + void AddPerspective(PerspectiveDescriptor::Pointer desc); + + /** + * Create a new perspective. + * + * @param label + * the name of the new descriptor + * @param originalDescriptor + * the descriptor on which to base the new descriptor + * @return a new perspective descriptor or null if the + * creation failed. + */ + IPerspectiveDescriptor::Pointer CreatePerspective(const QString& label, + IPerspectiveDescriptor::Pointer originalDescriptor); + + /** + * Reverts a list of perspectives back to the plugin definition + * + * @param perspToRevert + */ + void RevertPerspectives(const QList& perspToRevert); + + /** + * Deletes a list of perspectives + * + * @param perspToDelete + */ + void DeletePerspectives(const QList& perspToDelete); + + /** + * Delete a perspective. Has no effect if the perspective is defined in an + * extension. + * + * @param in + */ + void DeletePerspective(IPerspectiveDescriptor::Pointer in); + + /** + * Loads the registry. + */ + void Load(); + + /** + * Saves a custom perspective definition to the preference store. + * + * @param desc + * the perspective + * @param memento + * the memento to save to + * @throws IOException + */ + void SaveCustomPersp(PerspectiveDescriptor::Pointer desc, XMLMemento* memento); + + /** + * Gets the Custom perspective definition from the preference store. + * + * @param id + * the id of the perspective to find + * @return IMemento a memento containing the perspective description + * + * @throws WorkbenchException + * @throws IOException + */ + IMemento::Pointer GetCustomPersp(const QString& id); + + /** + * Return true if a label is valid. This checks only the + * given label in isolation. It does not check whether the given label is + * used by any existing perspectives. + * + * @param label + * the label to test + * @return whether the label is valid + */ + bool ValidateLabel(const QString& label); + + /** + * Dispose the receiver. + */ + ~PerspectiveRegistry(); + + // ---------- IPerspectiveRegistry methods ------------ + + virtual IPerspectiveDescriptor::Pointer FindPerspectiveWithId(const QString& id); + virtual IPerspectiveDescriptor::Pointer FindPerspectiveWithLabel(const QString& label); + + virtual QString GetDefaultPerspective(); + + virtual QList GetPerspectives(); + + virtual void SetDefaultPerspective(const QString& id); + + virtual IPerspectiveDescriptor::Pointer ClonePerspective(const QString& id, const QString& label, + IPerspectiveDescriptor::Pointer originalDescriptor); + + virtual void RevertPerspective(IPerspectiveDescriptor::Pointer perspToRevert); protected: /** - * Removes the custom definition of a perspective from the preference store - * - * @param desc - */ - /* package */ - void DeleteCustomDefinition(PerspectiveDescriptor::Pointer desc); - - /** - * Method hasCustomDefinition. - * - * @param desc - */ - /* package */ - bool HasCustomDefinition(PerspectiveDescriptor::ConstPointer desc) const; + * Removes the custom definition of a perspective from the preference store + * + * @param desc + */ + void DeleteCustomDefinition(PerspectiveDescriptor::Pointer desc); + + /** + * Method hasCustomDefinition. + * + * @param desc + */ + bool HasCustomDefinition(PerspectiveDescriptor::ConstPointer desc) const; private: /** * Initialize the preference change listener. */ void InitializePreferenceChangeListener(); /** * @param desc */ void Add(PerspectiveDescriptor::Pointer desc); /** * Delete a perspective. This will remove perspectives defined in * extensions. * * @param desc * the perspective to delete - * @since 3.1 */ void InternalDeletePerspective(PerspectiveDescriptor::Pointer desc); /** * Read children from the file system. */ void LoadCustom(); /** * @param status */ void UnableToLoadPerspective(const QString& status); /** * Read children from the plugin registry. */ void LoadPredefined(); /** * Verifies the id of the default perspective. If the default perspective is * invalid use the workbench default. */ void VerifyDefaultPerspective(); }; } #endif /* BERRYPERSPECTIVEREGISTRY_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistryReader.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistryReader.cpp index 8b3d63e71b..2772a62a59 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistryReader.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistryReader.cpp @@ -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. ===================================================================*/ #include "berryPerspectiveRegistryReader.h" #include "berryPerspectiveRegistry.h" #include "berryWorkbenchPlugin.h" #include "berryPlatformUI.h" #include "berryWorkbenchRegistryConstants.h" namespace berry { -PerspectiveRegistryReader::PerspectiveRegistryReader() +PerspectiveRegistryReader::PerspectiveRegistryReader(PerspectiveRegistry* out) + : registry(out) { - } -void PerspectiveRegistryReader::ReadPerspectives(PerspectiveRegistry* out) +void PerspectiveRegistryReader::ReadPerspectives(IExtensionRegistry* in) { - registry = out; - this->ReadRegistry(PlatformUI::PLUGIN_ID(), + this->ReadRegistry(in, PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_PERSPECTIVES); } bool PerspectiveRegistryReader::ReadElement(const IConfigurationElement::Pointer &element) { if (element->GetName() == WorkbenchRegistryConstants::TAG_PERSPECTIVE) { try { QString id = element->GetAttribute(WorkbenchRegistryConstants::ATT_ID); PerspectiveDescriptor::Pointer desc( new PerspectiveDescriptor(id, element)); QList childs = element->GetChildren("description"); if (!childs.isEmpty()) { desc->SetDescription(childs[0]->GetValue()); } registry->AddPerspective(desc); } - catch (CoreException e) + catch (const CoreException& e) { // log an error since its not safe to open a dialog here WorkbenchPlugin::Log("Unable to create layout descriptor.", e);//$NON-NLS-1$ } return true; } return false; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistryReader.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistryReader.h index c11a1c25ef..89de1c2d18 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistryReader.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPerspectiveRegistryReader.h @@ -1,64 +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 BERRYPERSPECTIVEREGISTRYREADER_H_ #define BERRYPERSPECTIVEREGISTRYREADER_H_ #include "berryRegistryReader.h" #include namespace berry { +struct IExtensionRegistry; class PerspectiveRegistry; /** * A strategy to read perspective extensions from the registry. */ class PerspectiveRegistryReader : public RegistryReader { private: PerspectiveRegistry* registry; public: - /** - * RegistryViewReader constructor comment. - */ - PerspectiveRegistryReader(); - - /** - * Read the view extensions within a registry. - * - * @param out the perspective registry to use - */ - void ReadPerspectives(PerspectiveRegistry* out); - -protected: - - /** - * readElement method comment. - */ - // for dynamic UI - change access from protected to public - bool ReadElement(const IConfigurationElement::Pointer& element); + /** + * RegistryViewReader constructor comment. + */ + PerspectiveRegistryReader(PerspectiveRegistry* out); + + /** + * Read the view extensions within a registry. + * + * @param out the perspective registry to use + */ + void ReadPerspectives(IExtensionRegistry* in); + + /** + * readElement method comment. + */ + bool ReadElement(const IConfigurationElement::Pointer& element); }; } #endif /* BERRYPERSPECTIVEREGISTRYREADER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPolicy.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPolicy.cpp new file mode 100644 index 0000000000..0566bb1908 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPolicy.cpp @@ -0,0 +1,153 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY 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 "berryPolicy.h" + +#include +#include + +#include + +namespace berry { + +const bool Policy::DEFAULT = false; + +bool Policy::DEBUG_UI_GLOBAL() +{ + static bool b = GetDebugOption("/debug"); + return b; +} + +bool Policy::DEBUG_DRAG_DROP() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/trace/dragDrop") : DEFAULT; + return b; +} + +bool Policy::DEBUG_PERSPECTIVES() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/trace/perspectives") : DEFAULT; + return b; +} + +bool Policy::DEBUG_STALE_JOBS() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/debug/job.stale") : DEFAULT; + return b; +} + +bool Policy::DEBUG_SOURCES() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/trace/sources") : DEFAULT; + return b; +} + +bool Policy::DEBUG_KEY_BINDINGS() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/trace/keyBindings") : DEFAULT; + return b; +} + +bool Policy::DEBUG_KEY_BINDINGS_VERBOSE() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/trace/keyBindings.verbose") : DEFAULT; + return b; +} + +bool Policy::DEBUG_COMMANDS() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/trace/commands") : DEFAULT; + return b; +} + +bool Policy::DEBUG_CONTEXTS() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/trace/contexts") : DEFAULT; + return b; +} + +bool Policy::DEBUG_CONTEXTS_PERFORMANCE() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/trace/contexts.performance") : DEFAULT; + return b; +} + +bool Policy::DEBUG_CONTEXTS_VERBOSE() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/trace/contexts.verbose") : DEFAULT; + return b; +} + +bool Policy::DEBUG_HANDLERS() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/trace/handlers") : DEFAULT; + return b; +} + +bool Policy::DEBUG_HANDLERS_PERFORMANCE() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/trace/handlers.performance") : DEFAULT; + return b; +} + +bool Policy::DEBUG_HANDLERS_VERBOSE() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/trace/handlers.verbose") : DEFAULT; + return b; +} + +bool Policy::DEBUG_OPERATIONS() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/trace/operations") : DEFAULT; + return b; +} + +bool Policy::DEBUG_OPERATIONS_VERBOSE() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/trace/operations.verbose") : DEFAULT; + return b; +} + +bool Policy::DEBUG_SHOW_ALL_JOBS() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/debug/showAllJobs") : DEFAULT; + return b; +} + +bool Policy::DEBUG_CONTRIBUTIONS() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/debug/contributions") : DEFAULT; + return b; +} + +QString Policy::DEBUG_HANDLERS_VERBOSE_COMMAND_ID() +{ + static QString s = Platform::GetDebugOption(PlatformUI::PLUGIN_ID() + "/trace/handlers.verbose.commandId").toString(); + return s; +} + +bool Policy::DEBUG_WORKING_SETS() +{ + static bool b = DEBUG_UI_GLOBAL() ? GetDebugOption("/debug/workingSets") : DEFAULT; + return b; +} + +bool Policy::GetDebugOption(const QString& option) +{ + return Platform::GetDebugOption(PlatformUI::PLUGIN_ID() + option).toBool(); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPolicy.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPolicy.h new file mode 100644 index 0000000000..d496d4d88e --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPolicy.h @@ -0,0 +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. + +===================================================================*/ + +#ifndef BERRYPOLICY_H +#define BERRYPOLICY_H + +class QString; + +namespace berry { +/** + * A common facility for parsing the org.eclipse.ui/.options + * file. + */ +class Policy +{ +public: + + static const bool DEFAULT; + + static bool DEBUG_UI_GLOBAL(); + + static bool DEBUG_DRAG_DROP(); + + static bool DEBUG_PERSPECTIVES(); + + /** + * Flag to log stale jobs + */ + static bool DEBUG_STALE_JOBS(); + + /** + * Whether to report all events entering through the common event framework + * used by the commands architecture. + * + * @see ISourceProvider + */ + static bool DEBUG_SOURCES(); + + /** + * Whether to print information about key bindings that are successfully + * recognized within the system (as the keys are pressed). + */ + static bool DEBUG_KEY_BINDINGS(); + + /** + * Whether to print information about every key seen by the system. + */ + static bool DEBUG_KEY_BINDINGS_VERBOSE(); + + /** + * Whether to print debugging information about the execution of commands + */ + static bool DEBUG_COMMANDS(); + + /** + * Whether to print debugging information about the internal state of the + * context support within the workbench. + */ + static bool DEBUG_CONTEXTS(); + + /** + * Whether to print debugging information about the performance of context + * computations. + */ + static bool DEBUG_CONTEXTS_PERFORMANCE(); + + /** + * Whether to print even more debugging information about the internal state + * of the context support within the workbench. + */ + static bool DEBUG_CONTEXTS_VERBOSE(); + + /** + * Whether to print debugging information about the internal state of the + * command support (in relation to handlers) within the workbench. + */ + static bool DEBUG_HANDLERS(); + + /** + * Whether to print debugging information about the performance of handler + * computations. + */ + static bool DEBUG_HANDLERS_PERFORMANCE(); + + /** + * Whether to print out verbose information about changing handlers in the + * workbench. + */ + static bool DEBUG_HANDLERS_VERBOSE(); + + /** + * Whether to print debugging information about unexpected occurrences and + * important state changes in the operation history. + */ + static bool DEBUG_OPERATIONS(); + + /** + * Whether to print out verbose information about the operation histories, + * including all notifications sent. + */ + static bool DEBUG_OPERATIONS_VERBOSE(); + + /** + * Whether or not to show system jobs at all times. + */ + static bool DEBUG_SHOW_ALL_JOBS(); + + /** + * Whether or not to print contribution-related issues. + */ + static bool DEBUG_CONTRIBUTIONS(); + + /** + * Which command identifier to print handler information for. This + * restricts the debugging output, so a developer can focus on one command + * at a time. + */ + static QString DEBUG_HANDLERS_VERBOSE_COMMAND_ID(); + + /** + * Whether or not additional working set logging will occur. + */ + static bool DEBUG_WORKING_SETS(); + +private: + + static bool GetDebugOption(const QString& option); +}; + +} + +#endif // BERRYPOLICY_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPreferencePageParameterValues.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPreferencePageParameterValues.cpp new file mode 100644 index 0000000000..0f936379db --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPreferencePageParameterValues.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 "berryPreferencePageParameterValues.h" + +#include "berryPlatform.h" +#include "berryPlatformUI.h" +#include "berryWorkbenchRegistryConstants.h" + +#include "berryIConfigurationElement.h" +#include "berryIExtensionRegistry.h" +#include "berryIWorkbench.h" + +namespace berry { + +PreferencePageParameterValues::PreferencePageParameterValues() +{ + QString xpId = PlatformUI::PLUGIN_ID() + "." + WorkbenchRegistryConstants::PL_PREFERENCES; + Platform::GetExtensionRegistry()->AddListener(this, xpId); +} + +QHash PreferencePageParameterValues::GetParameterValues() const +{ + if (preferenceMap.empty()) + { + IExtensionRegistry* registry = Platform::GetExtensionRegistry(); + if (registry) + { + QList configElements = + registry->GetConfigurationElementsFor(PlatformUI::PLUGIN_ID(), + WorkbenchRegistryConstants::PL_PREFERENCES); + for (auto configElement : configElements) + { + if(configElement->GetName() == "page") + { + preferenceMap.insert(configElement->GetAttribute("name"), configElement->GetAttribute("id")); + } + } + } + } + + return preferenceMap; +} + +void PreferencePageParameterValues::Added(const QList >& /*extensions*/) +{ + preferenceMap.clear(); +} + +void berry::PreferencePageParameterValues::Removed(const QList >& /*extensions*/) +{ + preferenceMap.clear(); +} + +void PreferencePageParameterValues::Added(const QList >& /*extensionPoints*/) +{ + preferenceMap.clear(); +} + +void PreferencePageParameterValues::Removed(const QList >& /*extensionPoints*/) +{ + preferenceMap.clear(); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPreferencePageParameterValues.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPreferencePageParameterValues.h new file mode 100644 index 0000000000..72a7af0cc3 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryPreferencePageParameterValues.h @@ -0,0 +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 BERRYPREFERENCEPAGEPARAMETERVALUES_H +#define BERRYPREFERENCEPAGEPARAMETERVALUES_H + +#include +#include + +namespace berry { + +struct IPreferences; + +/** + *

+ * Provides the parameter values for the show preferences command. + *

+ *

+ * To disambiguate preference pages with the same local label, names are + * constructed incorporating the full path of preference page labels. For + * instance names like General > Appearance and + * Java > Appearance avoid the problem of trying to put two + * Appearance keys into the parameter values map. + *

+ *

+ * This is only intended for use within the + * org.blueberry.ui.qt.workbench plug-in. + *

+ */ +class PreferencePageParameterValues : public QObject, public IParameterValues, private IRegistryEventListener +{ + Q_OBJECT + +public: + + PreferencePageParameterValues(); + + QHash GetParameterValues() const override; + + +private: + + mutable QHash preferenceMap; + + void Added(const QList >& extensions) override; + void Removed(const QList >& extensions) override; + void Added(const QList >& extensionPoints) override; + void Removed(const QList >& extensionPoints) override; + +}; + +} + +#endif // BERRYPREFERENCEPAGEPARAMETERVALUES_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.cpp index c7e0e4346a..013df3d0a4 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.cpp @@ -1,203 +1,203 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryQtShell.h" #include "berryQtWidgetsTweakletImpl.h" #include "berryQtMainWindowControl.h" #include #include #include #include #include namespace berry { QtShell::QtShell(QWidget* parent, Qt::WindowFlags flags) : updatesDisabled(false) { if (parent == 0 || flags.testFlag(Qt::Window)) { widget = new QtMainWindowControl(this, parent, flags); widget->setUpdatesEnabled(false); updatesDisabled = true; widget->setAttribute(Qt::WA_DeleteOnClose); } else { widget = new QtControlWidget(parent, this, flags | Qt::Dialog); widget->setObjectName("shell widget"); } widget->setProperty("shell", QVariant::fromValue(static_cast(this))); } QtShell::~QtShell() { widget->deleteLater(); } void QtShell::SetBounds(const QRect& bounds) { widget->setGeometry(bounds); } QRect QtShell::GetBounds() const { return widget->frameGeometry(); } void QtShell::SetLocation(int x, int y) { widget->move(x, y); } QPoint QtShell::ComputeSize(int /*wHint*/, int /*hHint*/, bool changed) { if (changed) widget->updateGeometry(); QSize size(widget->size()); QPoint point(size.width(), size.height()); return point; } QString QtShell::GetText() const { return widget->windowTitle(); } void QtShell::SetText(const QString& title) { widget->setWindowTitle(title); widget->setObjectName(title); } bool QtShell::IsVisible() const { return widget->isVisible(); } void QtShell::SetVisible(bool visible) { widget->setVisible(visible); } void QtShell::SetActive() { widget->activateWindow(); widget->raise(); } -QWidget *QtShell::GetControl() +QWidget *QtShell::GetControl() const { return widget; } void QtShell::SetImages(const QList& /*images*/) { } bool QtShell::GetMaximized() const { return widget->isMaximized(); } bool QtShell::GetMinimized() const { return widget->isMinimized(); } void QtShell::SetMaximized(bool maximized) { maximized ? widget->showMaximized() : widget->showNormal(); } void QtShell::SetMinimized(bool minimized) { minimized ? widget->showMinimized() : widget->showNormal(); } void QtShell::AddShellListener(IShellListener* listener) { QVariant variant = widget->property(QtWidgetController::PROPERTY_ID); poco_assert(variant.isValid()); QtWidgetController::Pointer controller = variant.value(); poco_assert(controller != 0); controller->AddShellListener(listener); } void QtShell::RemoveShellListener(IShellListener* listener) { QVariant variant = widget->property(QtWidgetController::PROPERTY_ID); if (variant.isValid()) { QtWidgetController::Pointer controller = variant.value(); if (controller != 0) controller->RemoveShellListener(listener); } } void QtShell::Open(bool block) { if (updatesDisabled) { widget->setUpdatesEnabled(true); updatesDisabled = false; } widget->setWindowModality(block ? Qt::WindowModal : Qt::NonModal); widget->show(); } void QtShell::Close() { widget->close(); } QList QtShell::GetShells() { GuiWidgetsTweaklet* widgetTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); QList allShells(widgetTweaklet->GetShells()); QList descendants; for (int i = 0; i < allShells.size(); ++i) { Shell::Pointer shell = allShells[i]; if (widgetTweaklet->GetShell(shell->GetControl()) == this) { descendants.push_back(shell); } } return descendants; } Qt::WindowFlags QtShell::GetStyle() const { return widget->windowFlags(); } QWidget* QtShell::GetWidget() { return widget; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.h index be720b76bc..7ae7974568 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShell.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 BERRYQTMAINWINDOWSHELL_H_ #define BERRYQTMAINWINDOWSHELL_H_ #include #include namespace berry { class QtAbstractControlWidget; class QtShell : public Shell { public: QtShell(QWidget* parent = 0, Qt::WindowFlags flags = 0); ~QtShell(); // berry::Shell void SetBounds(const QRect& bounds); QRect GetBounds() const; void SetLocation(int x, int y); QPoint ComputeSize(int wHint, int hHint, bool changed); QString GetText() const; void SetText(const QString& text); bool IsVisible() const; void SetVisible(bool visible); void SetActive(); - QWidget* GetControl(); + QWidget* GetControl() const; void SetImages(const QList& images); bool GetMaximized() const; bool GetMinimized() const; void SetMaximized(bool maximized); void SetMinimized(bool minimized); void AddShellListener(IShellListener* listener); void RemoveShellListener(IShellListener* listener); void Open(bool block = false); void Close(); QList GetShells(); Qt::WindowFlags GetStyle () const; QWidget* GetWidget(); private: QWidget* widget; bool updatesDisabled; }; } #endif /* BERRYQTMAINWINDOWSHELL_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.cpp new file mode 100644 index 0000000000..05d26c3056 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.cpp @@ -0,0 +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 "berryQtShowPerspectiveDialog.h" +#include "ui_berryQtShowPerspectiveDialog.h" + +#include + +#include + +namespace berry { + +QtShowPerspectiveDialog::QtShowPerspectiveDialog(IPerspectiveRegistry* perspReg, QWidget *parent) + : QDialog(parent) + , ui(new Ui::QtShowPerspectiveDialog) +{ + ui->setupUi(this); + + QAbstractItemModel* model = new PerspectiveListModel(*perspReg, true, this); + + QSortFilterProxyModel* proxyModel = new QSortFilterProxyModel(this); + proxyModel->setSourceModel(model); + proxyModel->sort(0); + + ui->m_ListView->setModel(proxyModel); + ui->m_ListView->setSelectionMode(QAbstractItemView::SingleSelection); + ui->m_ListView->selectionModel()->select(model->index(0, 0), QItemSelectionModel::ClearAndSelect); + ui->m_ListView->setIconSize(QSize(16, 16)); + + connect(ui->m_ListView, SIGNAL(clicked(QModelIndex)), this, SLOT(setDescription(QModelIndex))); + connect(ui->m_ListView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); + connect(ui->m_ListView, SIGNAL(activated(QModelIndex)), this, SLOT(accept())); + +} + +QtShowPerspectiveDialog::~QtShowPerspectiveDialog() +{ + delete ui; +} + +QString QtShowPerspectiveDialog::GetSelection() const +{ + const QItemSelection selection = ui->m_ListView->selectionModel()->selection(); + if (selection.isEmpty()) return QString::null; + + return selection.indexes().front().data(PerspectiveListModel::Id).toString(); +} + +void QtShowPerspectiveDialog::setDescription(const QModelIndex& index) +{ + ui->m_Description->setText(ui->m_ListView->model()->data(index, PerspectiveListModel::Description).toString()); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.h new file mode 100644 index 0000000000..c592dd8a89 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.h @@ -0,0 +1,51 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#ifndef BERRYQTSHOWPERSPECTIVEDIALOG_H +#define BERRYQTSHOWPERSPECTIVEDIALOG_H + +#include + +class QModelIndex; + +namespace Ui { +class QtShowPerspectiveDialog; +} + +namespace berry { + +struct IPerspectiveRegistry; + +class QtShowPerspectiveDialog : public QDialog +{ + Q_OBJECT + +public: + explicit QtShowPerspectiveDialog(IPerspectiveRegistry* perspReg, QWidget *parent = 0); + ~QtShowPerspectiveDialog(); + + QString GetSelection() const; + +private: + + Q_SLOT void setDescription(const QModelIndex& index); + + Ui::QtShowPerspectiveDialog *ui; +}; + +} + +#endif // BERRYQTSHOWPERSPECTIVEDIALOG_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.ui b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.ui new file mode 100644 index 0000000000..11ed23567b --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowPerspectiveDialog.ui @@ -0,0 +1,93 @@ + + + QtShowPerspectiveDialog + + + + 0 + 0 + 400 + 300 + + + + Open Perspective + + + + + + + 0 + 5 + + + + + + + + + 0 + 1 + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + true + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + m_ButtonBox + accepted() + QtShowPerspectiveDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + m_ButtonBox + rejected() + QtShowPerspectiveDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.cpp index 946c9980d2..6d12af26f5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.cpp @@ -1,39 +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. ===================================================================*/ #include "berryQtShowViewDialog.h" +#include +#include + +#include + +#include "berryWorkbenchPlugin.h" +#include "berryXMLMemento.h" + +#include +#include + namespace berry { +static const QString TAG_SHOWVIEWDIALOG = "ShowViewDialog"; +static const QString TAG_CATEGORY = "category"; +static const QString TAG_SELECTION = "selection"; +static const QString TAG_GEOMETRY = "geometry"; + +class ViewFilterProxyModel : public QSortFilterProxyModel +{ +public: + ViewFilterProxyModel(QObject* parent = nullptr) + : QSortFilterProxyModel(parent) + , m_FilterOnKeywords(true) + { + this->setFilterCaseSensitivity(Qt::CaseInsensitive); + } + + bool filterOnKeywords() const + { + return m_FilterOnKeywords; + } + + void setFilterOnKeywords(bool filterOnKeywords) + { + if (m_FilterOnKeywords != filterOnKeywords) + { + m_FilterOnKeywords = filterOnKeywords; + this->filterChanged(); + } + } + +protected: + + bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override + { + QRegExp regExp = filterRegExp(); + if (!regExp.isValid() || regExp.isEmpty()) return true; + + QModelIndex sourceIndex = sourceModel()->index(sourceRow, 0, sourceParent); + QStringList keywords; + + if (m_FilterOnKeywords) + { + keywords = sourceModel()->data(sourceIndex, ViewTreeModel::Keywords).toStringList(); + } + else + { + if (sourceModel()->hasChildren(sourceIndex)) + { + // this is a category item + int numChildren = sourceModel()->rowCount(sourceIndex); + for (int i = 0; i < numChildren; ++i) + { + keywords.push_back(sourceModel()->data(sourceIndex.child(i, 0)).toString()); + } + } + else + { + // this is a view item + keywords.push_back(sourceModel()->data(sourceIndex).toString()); + } + } + + for(auto& keyword : keywords) + { + if (keyword.contains(regExp)) return true; + } + return false; + } + +private: + + bool m_FilterOnKeywords; +}; + QtShowViewDialog::QtShowViewDialog(const IWorkbenchWindow* window, IViewRegistry* registry, QWidget* parent, Qt::WindowFlags f) : QDialog(parent, f) , m_Window(window) , m_ViewReg(registry) + , m_FilterModel(nullptr) { m_UserInterface.setupUi(this); + m_UserInterface.m_TreeView->header()->setVisible(false); + m_UserInterface.m_TreeView->setSelectionMode(QAbstractItemView::ExtendedSelection); + + m_FilterModel = new ViewFilterProxyModel(this); + ViewTreeModel* sourceModel = new ViewTreeModel(window, m_FilterModel); + m_FilterModel->setSourceModel(sourceModel); + m_UserInterface.m_TreeView->setModel(m_FilterModel); + + connect(m_UserInterface.m_Filter, SIGNAL(textChanged(QString)), this, SLOT(setFilter(QString))); + connect(m_UserInterface.m_TreeView, SIGNAL(clicked(QModelIndex)), this, SLOT(setDescription(QModelIndex))); + connect(m_UserInterface.m_TreeView, SIGNAL(collapsed(QModelIndex)), this, SLOT(categoryCollapsed(QModelIndex))); + connect(m_UserInterface.m_TreeView, SIGNAL(expanded(QModelIndex)), this, SLOT(categoryExpanded(QModelIndex))); + connect(m_UserInterface.m_TreeView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); + connect(m_UserInterface.m_TreeView, SIGNAL(activated(QModelIndex)), this, SLOT(accept())); + connect(m_UserInterface.m_TreeView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged(QItemSelection,QItemSelection))); + connect(m_UserInterface.m_KeywordFilter, SIGNAL(clicked(bool)), this, SLOT(enableKeywordFilter(bool))); + + this->RestoreState(); + m_UserInterface.m_Filter->selectAll(); + this->UpdateButtons(); +} + +void QtShowViewDialog::setDescription(const QModelIndex& index) +{ + QString description = m_UserInterface.m_TreeView->model()->data(index, Qt::WhatsThisRole).toString(); + m_UserInterface.m_Description->setText(description); +} + +void QtShowViewDialog::enableKeywordFilter(bool enable) +{ + m_FilterModel->setFilterOnKeywords(enable); + this->RestoreExpandedState(); +} + +void QtShowViewDialog::setFilter(const QString& filter) +{ + m_FilterModel->setFilterWildcard(filter); + this->RestoreExpandedState(); +} + +void QtShowViewDialog::categoryCollapsed(const QModelIndex& index) +{ + m_ExpandedCategories.removeAll(m_FilterModel->mapToSource(index)); +} + +void QtShowViewDialog::categoryExpanded(const QModelIndex& index) +{ + m_ExpandedCategories.push_back(m_FilterModel->mapToSource(index)); +} + +void QtShowViewDialog::selectionChanged(const QItemSelection& /*selected*/, const QItemSelection& /*deselected*/) +{ + UpdateButtons(); +} + +void QtShowViewDialog::RestoreExpandedState() +{ + int rowCount = m_FilterModel->rowCount(); + for (int i = 0; i < rowCount; ++i) + { + QModelIndex index = m_FilterModel->index(i, 0); + if (m_ExpandedCategories.contains(m_FilterModel->mapToSource(index))) + { + m_UserInterface.m_TreeView->expand(index); + } + } +} + +void QtShowViewDialog::UpdateButtons() +{ + QPushButton* okBtn = m_UserInterface.m_ButtonBox->button(QDialogButtonBox::Ok); + if (okBtn) + { + okBtn->setEnabled(!m_UserInterface.m_TreeView->selectionModel()->selection().isEmpty()); + } +} + +void QtShowViewDialog::RestoreState() +{ + IPreferences::Pointer prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); + QString str = prefs->Get(TAG_SHOWVIEWDIALOG, QString::null); + if (str.isEmpty()) return; + + std::stringstream ss(str.toStdString()); + + XMLMemento::Pointer memento = XMLMemento::CreateReadRoot(ss); + + bool keywordFilter = false; + if (memento->GetBoolean("keywordFilter", keywordFilter)) + { + m_UserInterface.m_KeywordFilter->setChecked(keywordFilter); + m_FilterModel->setFilterOnKeywords(keywordFilter); + } + + QString filter; + if (memento->GetString("filter", filter)) + { + m_UserInterface.m_Filter->setText(filter); + } + + IMemento::Pointer geomChild = memento->GetChild(TAG_GEOMETRY); + if (geomChild.IsNotNull()) + { + QString geom = geomChild->GetTextData(); + if (!geom.isEmpty()) + { + QByteArray ba = QByteArray::fromBase64(geom.toLatin1()); + this->restoreGeometry(ba); + } + } + + QHash rootIndices; + int rowCount = m_FilterModel->sourceModel()->rowCount(); + for (int i = 0; i < rowCount; ++i) + { + QModelIndex sourceIndex = m_FilterModel->sourceModel()->index(i, 0); + QString id = sourceIndex.data(ViewTreeModel::Id).toString(); + if (!id.isEmpty()) + { + rootIndices[id] = sourceIndex; + } + } + for (IMemento::Pointer categoryChild : memento->GetChildren(TAG_CATEGORY)) + { + QString id = categoryChild->GetID(); + if (!id.isEmpty()) + { + if (rootIndices.contains(id)) + { + m_ExpandedCategories.push_back(rootIndices[id]); + } + } + } + this->RestoreExpandedState(); + + QItemSelection itemSelection; + for (IMemento::Pointer selectionChild : memento->GetChildren(TAG_SELECTION)) + { + QString id = selectionChild->GetID(); + if (!id.isEmpty()) + { + QModelIndexList indexList = m_FilterModel->match(m_FilterModel->index(0, 0), ViewTreeModel::Id, QVariant::fromValue(id), + 1, Qt::MatchExactly | Qt::MatchRecursive); + if (!indexList.isEmpty()) + { + QItemSelection subSelection(indexList.front(), indexList.front()); + itemSelection.merge(subSelection, QItemSelectionModel::SelectCurrent); + } + } + } + m_UserInterface.m_TreeView->selectionModel()->select(itemSelection, QItemSelectionModel::ClearAndSelect); +} + +void QtShowViewDialog::SaveState() +{ + XMLMemento::Pointer memento = XMLMemento::CreateWriteRoot(TAG_SHOWVIEWDIALOG); + memento->PutString("filter", m_UserInterface.m_Filter->text()); + memento->PutBoolean("keywordFilter", m_UserInterface.m_KeywordFilter->isChecked()); + + // dialog geometry + QByteArray geom = this->saveGeometry(); + IMemento::Pointer geomChild = memento->CreateChild(TAG_GEOMETRY); + geomChild->PutTextData(geom.toBase64().constData()); + + // expanded categories + for (QPersistentModelIndex index : m_ExpandedCategories) + { + if (index.isValid()) + { + QString id = index.data(ViewTreeModel::Id).toString(); + if (!id.isEmpty()) + { + memento->CreateChild(TAG_CATEGORY, id); + } + } + } + + // we only record a single selected item. restoring a multi-selection might be + // confusing for the user + QModelIndexList selectedIndices = m_UserInterface.m_TreeView->selectionModel()->selectedIndexes(); + if (!selectedIndices.isEmpty()) + { + QString id = selectedIndices.back().data(ViewTreeModel::Id).toString(); + if (!id.isEmpty()) + { + memento->CreateChild(TAG_SELECTION, id); + } + } + + std::stringstream ss; + memento->Save(ss); + + IPreferences::Pointer prefs = WorkbenchPlugin::GetDefault()->GetPreferences(); + prefs->Put(TAG_SHOWVIEWDIALOG, QString::fromStdString(ss.str())); + prefs->Sync(); } +void QtShowViewDialog::done(int r) +{ + this->SaveState(); + QDialog::done(r); +} -QList +QList QtShowViewDialog::GetSelection() const { - QList selected; + QList selected; + + QModelIndexList indices = m_UserInterface.m_TreeView->selectionModel()->selectedIndexes(); + for(QModelIndex index : indices) + { + QString id = m_FilterModel->data(index, ViewTreeModel::Id).toString(); + selected.push_back(id); + } return selected; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.h index 57f3c763f7..0325557e1e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.h @@ -1,54 +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 BERRYQTSHOWVIEWDIALOG_H_ #define BERRYQTSHOWVIEWDIALOG_H_ -#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 "ui_berryQtShowViewDialog.h" namespace berry { +struct IViewRegistry; +struct IWorkbenchWindow; + +class ViewFilterProxyModel; + class QtShowViewDialog : public QDialog { + Q_OBJECT public: QtShowViewDialog(const IWorkbenchWindow* window, IViewRegistry* registry, QWidget* parent = 0, Qt::WindowFlags f = 0); - QList GetSelection() const; + QList GetSelection() const; private: + Q_SLOT void setDescription(const QModelIndex& index); + Q_SLOT void enableKeywordFilter(bool enable); + + Q_SLOT void setFilter(const QString& filter); + + Q_SLOT void categoryCollapsed(const QModelIndex& index); + Q_SLOT void categoryExpanded(const QModelIndex& index); + + Q_SLOT void selectionChanged(const QItemSelection& selected, const QItemSelection& deselected); + + void RestoreExpandedState(); + void UpdateButtons(); + + void RestoreState(); + void SaveState(); + + void done(int r) override; + const IWorkbenchWindow* m_Window; IViewRegistry* m_ViewReg; Ui::QtShowViewDialog_ m_UserInterface; + ViewFilterProxyModel* m_FilterModel; + QList m_ExpandedCategories; }; } #endif /*BERRYQTSHOWVIEWDIALOG_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.ui b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.ui index 5302f817e0..a061656e85 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.ui +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtShowViewDialog.ui @@ -1,82 +1,123 @@ - + + QtShowViewDialog_ - - + + Qt::NonModal - + 0 0 406 341 - - Dialog + + Show View - + true - + true - + - + - + + + filter... + + + + + + + Enable keyword filter + + + true + + + + + + + + 0 + 5 + + + - + + + + 0 + 1 + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + true + + - - + + Qt::Horizontal - - QDialogButtonBox::Cancel|QDialogButtonBox::NoButton|QDialogButtonBox::Ok + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok - buttonBox + m_ButtonBox accepted() QtShowViewDialog_ accept() - + 248 254 - + 157 274 - buttonBox + m_ButtonBox rejected() QtShowViewDialog_ reject() - + 316 260 - + 286 274 diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.cpp index b9e8c0d8e3..c1f49c420c 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWidgetsTweakletImpl.cpp @@ -1,433 +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 "berryLog.h" #include "berryQtWidgetsTweakletImpl.h" #include "berryQtSash.h" #include "berryQtShell.h" #include #include #include #include #include #include namespace berry { QtSelectionListenerWrapper::QtSelectionListenerWrapper(QWidget* w) : widget(w) { } void QtSelectionListenerWrapper::AddListener(GuiTk::ISelectionListener::Pointer listener) { QAbstractButton* button = qobject_cast(widget); if (button != 0) { this->connect(button, "clicked(bool)", this, "QAbstractButtonClicked(bool)"); selectionEvents.AddListener(listener); } BERRY_WARN << "WARNING: QtWidgetsTweaklet: no suitable type for listening for selections found!\n"; } int QtSelectionListenerWrapper::RemoveListener(GuiTk::ISelectionListener::Pointer listener) { selectionEvents.RemoveListener(listener); return static_cast(std::max(selectionEvents.selected.GetListeners().size(), selectionEvents.defaultSelected.GetListeners().size())); } void QtSelectionListenerWrapper::QAbstractButtonClicked(bool /*checked*/) { GuiTk::SelectionEvent::Pointer event(new GuiTk::SelectionEvent(widget)); selectionEvents.selected(event); } void QtWidgetsTweakletImpl::AddSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener) { if (widget == 0) return; // special handling for berry::QtSash QtSash* sash = qobject_cast(widget); if (sash != 0) { sash->AddSelectionListener(listener); return; } // "normal" Qt widgets get wrapped QtSelectionListenerWrapper* wrapper = selectionListenerMap[widget]; if (wrapper == 0) { wrapper = new QtSelectionListenerWrapper(widget); selectionListenerMap[widget] = wrapper; } wrapper->AddListener(listener); } void QtWidgetsTweakletImpl::RemoveSelectionListener(QWidget* widget, GuiTk::ISelectionListener::Pointer listener) { if (widget == 0) return; // special handling for berry::QtSash QtSash* sash = qobject_cast(widget); if (sash != 0) { sash->RemoveSelectionListener(listener); return; } QtSelectionListenerWrapper* wrapper = selectionListenerMap[widget]; if (wrapper == 0) return; if (wrapper->RemoveListener(listener) == 0) { selectionListenerMap.remove(widget); delete wrapper; } } QRect QtWidgetsTweakletImpl::GetScreenSize(int i) { QDesktopWidget *desktop = QApplication::desktop(); if (i < 0) return desktop->screen()->geometry(); return desktop->screenGeometry(i); } unsigned int QtWidgetsTweakletImpl::GetScreenNumber() { QDesktopWidget *desktop = QApplication::desktop(); // get the primary screen unsigned int numScreens = desktop->numScreens(); return numScreens; } int QtWidgetsTweakletImpl::GetPrimaryScreenNumber() { QDesktopWidget *desktop = QApplication::desktop(); // get the primary screen int primaryScreenNr = desktop->primaryScreen(); return primaryScreenNr; } QRect QtWidgetsTweakletImpl::GetAvailableScreenSize(int i) { QDesktopWidget *desktop = QApplication::desktop(); if (i < 0) return desktop->screen()->geometry(); return desktop->availableGeometry(i); } int QtWidgetsTweakletImpl::GetClosestScreenNumber(const QRect& r) { QDesktopWidget *desktop = QApplication::desktop(); return desktop->screenNumber(QPoint(r.x() + r.width()/2, r.y() + r.height()/2)); } void QtWidgetsTweakletImpl::AddControlListener(QtWidgetController* controller, GuiTk::IControlListener::Pointer listener) { controller->AddControlListener(listener); } void QtWidgetsTweakletImpl::RemoveControlListener(QtWidgetController* controller, GuiTk::IControlListener::Pointer listener) { controller->RemoveControlListener(listener); } bool QtWidgetsTweakletImpl::GetEnabled(QWidget* widget) { return widget->isEnabled(); } void QtWidgetsTweakletImpl::SetEnabled(QWidget* widget, bool enabled) { widget->setEnabled(enabled); } void QtWidgetsTweakletImpl::SetBounds(QWidget* widget, const QRect& bounds) { widget->setGeometry(bounds); } QRect QtWidgetsTweakletImpl::GetBounds(QWidget* widget) { const QRect& geometry = widget->geometry(); QRect rect(geometry.x(), geometry.y(), geometry.width(), geometry.height()); return rect; } void QtWidgetsTweakletImpl::SetVisible(QWidget* widget, bool visible) { widget->setVisible(visible); } bool QtWidgetsTweakletImpl::GetVisible(QWidget* widget) { return !widget->isHidden(); } bool QtWidgetsTweakletImpl::IsVisible(QWidget* widget) { return widget->isVisible(); } QRect QtWidgetsTweakletImpl::GetClientArea(QWidget* widget) { return widget->contentsRect(); } QWidget* QtWidgetsTweakletImpl::GetParent(QWidget* widget) { return widget->parentWidget(); } bool QtWidgetsTweakletImpl::SetParent(QWidget* widget, QWidget* parent) { if (parent != widget->parentWidget()) { widget->setParent(parent); return true; } return false; } void QtWidgetsTweakletImpl::SetData(QWidget* object, const QString& id, Object::Pointer data) { if (object == 0) return; QVariant variant; if (data != 0) variant.setValue(data); object->setProperty(qPrintable(id), variant); } Object::Pointer QtWidgetsTweakletImpl::GetData(QWidget* object, const QString& id) { if (object == 0) return Object::Pointer(0); QVariant variant = object->property(qPrintable(id)); if (variant.isValid()) { return variant.value(); } return Object::Pointer(0); } QPoint QtWidgetsTweakletImpl::GetCursorLocation() { QPoint qpoint = QCursor::pos(); return QPoint(qpoint.x(), qpoint.y()); } QWidget* QtWidgetsTweakletImpl::GetCursorControl() { return QApplication::widgetAt(QCursor::pos()); } QWidget* QtWidgetsTweakletImpl::FindControl(const QList& shells, const QPoint& location) { for (QList::const_iterator iter = shells.begin(); iter != shells.end(); ++iter) { QWidget* shellWidget = static_cast((*iter)->GetControl()); QWidget* control = shellWidget->childAt(location.x(), location.y()); if (control) return control; } return 0; } bool QtWidgetsTweakletImpl::IsChild(QObject* parentToTest, QObject* childToTest) { bool found = false; QObject* parent = childToTest->parent(); while (!found && parent != 0) { if (parent == parentToTest) found = true; parent = parent->parent(); } return found; } QWidget* QtWidgetsTweakletImpl::GetFocusControl() { return QApplication::focusWidget(); } bool QtWidgetsTweakletImpl::IsReparentable(QWidget* /*widget*/) { return true; } void QtWidgetsTweakletImpl::MoveAbove(QWidget* widgetToMove, QWidget* /*widget*/) { widgetToMove->raise(); } void QtWidgetsTweakletImpl::MoveBelow(QWidget* widgetToMove, QWidget* /*widget*/) { widgetToMove->lower(); } void QtWidgetsTweakletImpl::Dispose(QWidget* widget) { delete widget; widget = 0; } Shell::Pointer QtWidgetsTweakletImpl::CreateShell(Shell::Pointer parent, int style) { #ifdef __APPLE__ Qt::WindowFlags qtFlags(0); #else Qt::WindowFlags qtFlags(Qt::CustomizeWindowHint); #endif if (style & Constants::MAX) qtFlags |= Qt::WindowMaximizeButtonHint; if (style & Constants::MIN) qtFlags |= Qt::WindowMinimizeButtonHint; if (style & Constants::CLOSE) { qtFlags |= Qt::WindowSystemMenuHint; #if QT_VERSION >= 0x040500 qtFlags |= Qt::WindowCloseButtonHint; #endif } if (!(style & Constants::BORDER)) qtFlags |= Qt::FramelessWindowHint; if (style & Constants::TITLE) qtFlags |= Qt::WindowTitleHint; if (style & Constants::TOOL) qtFlags |= Qt::Tool; QWidget* parentWidget = 0; if (parent != 0) parentWidget = static_cast(parent->GetControl()); QtShell* qtshell = new QtShell(parentWidget, qtFlags); Shell::Pointer shell(qtshell); shellList.push_back(shell); if ((style & Constants::APPLICATION_MODAL) || (style & Constants::SYSTEM_MODAL)) qtshell->GetWidget()->setWindowModality(Qt::ApplicationModal); if (style & Constants::PRIMARY_MODAL) qtshell->GetWidget()->setWindowModality(Qt::WindowModal); return shell; } QWidget* QtWidgetsTweakletImpl::CreateComposite(QWidget* parent) { QWidget* composite = new QtControlWidget(parent, 0); composite->setObjectName("created composite"); return composite; } void QtWidgetsTweakletImpl::DisposeShell(Shell::Pointer shell) { shellList.removeAll(shell); + shell->SetVisible(false); } QList QtWidgetsTweakletImpl::GetShells() { return shellList; } Shell::Pointer QtWidgetsTweakletImpl::GetShell(QWidget* widget) { QWidget* qwindow = widget->window(); QVariant variant = qwindow->property(QtWidgetController::PROPERTY_ID); if (variant.isValid()) { QtWidgetController::Pointer controller = variant.value(); poco_assert(controller != 0); return controller->GetShell(); } return Shell::Pointer(0); } Shell::Pointer QtWidgetsTweakletImpl::GetActiveShell() { QWidget* qwidget = QApplication::activeWindow(); if (qwidget == 0) return Shell::Pointer(0); QVariant variant = qwidget->property(QtWidgetController::PROPERTY_ID); if (variant.isValid()) { return variant.value()->GetShell(); } return Shell::Pointer(0); } QRect QtWidgetsTweakletImpl::ToControl(QWidget* coordinateSystem, const QRect& toConvert) { QPoint globalUpperLeft = toConvert.topLeft(); QPoint globalLowerRight = toConvert.bottomRight(); QPoint upperLeft = coordinateSystem->mapFromGlobal(globalUpperLeft); QPoint lowerRight = coordinateSystem->mapFromGlobal(globalLowerRight); return QRect(upperLeft.x(), upperLeft.y(), lowerRight.x() - upperLeft.x(), lowerRight.y() - upperLeft.y()); } QPoint QtWidgetsTweakletImpl::ToControl(QWidget* coordinateSystem, const QPoint& toConvert) { return coordinateSystem->mapFromGlobal(toConvert); } QRect QtWidgetsTweakletImpl::ToDisplay(QWidget* coordinateSystem, const QRect& toConvert) { QPoint upperLeft = toConvert.topLeft(); QPoint lowerRight = toConvert.bottomRight(); QPoint globalUpperLeft = coordinateSystem->mapToGlobal(upperLeft); QPoint globalLowerRight = coordinateSystem->mapToGlobal(lowerRight); return QRect(globalUpperLeft.x(), globalUpperLeft.y(), globalLowerRight.x() - globalUpperLeft.x(), globalLowerRight.y() - globalUpperLeft.y()); } QPoint QtWidgetsTweakletImpl::ToDisplay(QWidget* coordinateSystem, const QPoint& toConvert) { return coordinateSystem->mapToGlobal(toConvert); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchPageTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchPageTweaklet.h index de9446d400..d8543263dd 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchPageTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchPageTweaklet.h @@ -1,49 +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 BERRYQTWORKBENCHPAGETWEAKLET_H_ #define BERRYQTWORKBENCHPAGETWEAKLET_H_ #include #include namespace berry { class BERRY_UI_QT QtWorkbenchPageTweaklet : public QObject, public WorkbenchPageTweaklet { Q_OBJECT Q_INTERFACES(berry::WorkbenchPageTweaklet) public: - berryObjectMacro(QtWorkbenchPageTweaklet) - QtWorkbenchPageTweaklet(); QWidget* CreateClientComposite(QWidget* pageControl); QWidget* CreatePaneControl(QWidget* parent); Object::Pointer CreateStatusPart(QWidget* parent, const QString& title, const QString& msg); IEditorPart::Pointer CreateErrorEditorPart(const QString& partName, const QString& msg); }; } #endif /* BERRYQTWORKBENCHPAGETWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h index 90365ba2c1..ae00345efd 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h @@ -1,45 +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. ===================================================================*/ #ifndef BERRYQTWORKBENCHTWEAKLET_H_ #define BERRYQTWORKBENCHTWEAKLET_H_ #include #include namespace berry { class BERRY_UI_QT QtWorkbenchTweaklet : public QObject, public WorkbenchTweaklet { Q_OBJECT Q_INTERFACES(berry::WorkbenchTweaklet) public: - berryObjectMacro(QtWorkbenchTweaklet) - QtWorkbenchTweaklet(); Display* CreateDisplay(); bool IsRunning(); }; } // namespace berry #endif /*BERRYQTWORKBENCHTWEAKLET_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp index 0a3e3aa809..9f9044d5cc 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryRegistryReader.cpp @@ -1,163 +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. ===================================================================*/ #include #include #include #include #include "berryRegistryReader.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchRegistryConstants.h" namespace { bool CompareExtensionsByContributor(const berry::IExtension::Pointer& e1, const berry::IExtension::Pointer& e2) { return e1->GetContributor()->GetName().compare(e2->GetContributor()->GetName(), Qt::CaseInsensitive) < 0; } } namespace berry { RegistryReader::RegistryReader() { } RegistryReader::~RegistryReader() { } void RegistryReader::LogError(const IConfigurationElement::Pointer& element, const QString& text) { IExtension::Pointer extension = element->GetDeclaringExtension(); QString buf = QString("Plugin ") + extension->GetContributor()->GetName() + ", extension " + extension->GetExtensionPointUniqueIdentifier(); // look for an ID if available - this should help debugging QString id = element->GetAttribute("id"); if (!id.isEmpty()) { buf.append(", id "); buf.append(id); } buf.append(": " + text); WorkbenchPlugin::Log(buf); } void RegistryReader::LogMissingAttribute( const IConfigurationElement::Pointer& element, const QString& attributeName) { RegistryReader::LogError(element, "Required attribute '" + attributeName + "' not defined"); } void RegistryReader::LogMissingElement( const IConfigurationElement::Pointer& element, const QString& elementName) { RegistryReader::LogError(element, "Required sub element '" + elementName + "' not defined"); } void RegistryReader::LogUnknownElement( const IConfigurationElement::Pointer& element) { RegistryReader::LogError(element, "Unknown extension tag found: " + element->GetName()); } QList RegistryReader::OrderExtensions( const QList& extensions) { // By default, the order is based on plugin id sorted // in ascending order. The order for a plugin providing // more than one extension for an extension point is // dependent in the order listed in the XML file. QList sortedExtension(extensions); qStableSort(sortedExtension.begin(), sortedExtension.end(), CompareExtensionsByContributor); return sortedExtension; } void RegistryReader::ReadElementChildren( const IConfigurationElement::Pointer& element) { this->ReadElements(element->GetChildren()); } void RegistryReader::ReadElements( const QList& elements) { for (int i = 0; i < elements.size(); i++) { if (!this->ReadElement(elements[i])) { RegistryReader::LogUnknownElement(elements[i]); } } } void RegistryReader::ReadExtension(const IExtension::Pointer& extension) { this->ReadElements(extension->GetConfigurationElements()); } -void RegistryReader::ReadRegistry( - const QString& pluginId, const QString& extensionPoint) +void RegistryReader::ReadRegistry(IExtensionRegistry* registry, + const QString& pluginId, const QString& extensionPoint) { - IExtensionPoint::Pointer point = Platform::GetExtensionRegistry()->GetExtensionPoint(pluginId + "." + extensionPoint); + IExtensionPoint::Pointer point = registry->GetExtensionPoint(pluginId, extensionPoint); if (point == 0) { return; } QList extensions(point->GetExtensions()); extensions = this->OrderExtensions(extensions); for (int i = 0; i < extensions.size(); i++) { this->ReadExtension(extensions[i]); } } QString RegistryReader::GetDescription(const IConfigurationElement::Pointer& configElement) { QList children(configElement->GetChildren(WorkbenchRegistryConstants::TAG_DESCRIPTION)); if (children.size() >= 1) { return children[0]->GetValue(); } return ""; } QString RegistryReader::GetClassValue( const IConfigurationElement::Pointer& configElement, const QString& classAttributeName) { QString className = configElement->GetAttribute(classAttributeName); if (!className.isEmpty()) { return className; } QList candidateChildren(configElement->GetChildren(classAttributeName)); if (candidateChildren.isEmpty()) { return ""; } return candidateChildren[0]->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryRegistryReader.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryRegistryReader.h index 8a160272cf..83f3993bec 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryRegistryReader.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryRegistryReader.h @@ -1,167 +1,169 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYREGISTRYREADER_H_ #define BERRYREGISTRYREADER_H_ #include #include namespace berry { struct IExtension; +struct IExtensionRegistry; struct IConfigurationElement; /** * \ingroup org_blueberry_ui_internal * * Template implementation of a registry reader that creates objects * representing registry contents. Typically, an extension * contains one element, but this reader handles multiple * elements per extension. * * To start reading the extensions from the registry for an * extension point, call the method readRegistry. * * To read children of an IConfigurationElement, call the * method readElementChildren from your implementation * of the method readElement, as it will not be * done by default. */ class RegistryReader { // for dynamic UI - remove this cache to avoid inconsistency //protected static Hashtable extensionPoints = new Hashtable(); /** * The constructor. */ protected: RegistryReader(); virtual ~RegistryReader(); /** * Logs the error in the workbench log using the provided * text and the information in the configuration element. */ static void LogError(const SmartPointer& element, const QString& text); /** * Logs a very common registry error when a required attribute is missing. */ static void LogMissingAttribute(const SmartPointer& element, const QString& attributeName); /** * Logs a very common registry error when a required child is missing. */ static void LogMissingElement(const SmartPointer& element, const QString& elementName); /** * Logs a registry error when the configuration element is unknown. */ static void LogUnknownElement(const SmartPointer& element); public: /** * Apply a reproducable order to the list of extensions * provided, such that the order will not change as * extensions are added or removed. * @param extensions the extensions to order * @return ordered extensions */ static QList > OrderExtensions(const QList >& extensions); protected: /** * Implement this method to read element's attributes. * If children should also be read, then implementor * is responsible for calling readElementChildren. * Implementor is also responsible for logging missing * attributes. * * @return true if element was recognized, false if not. */ virtual bool ReadElement(const SmartPointer& element) = 0; /** * Read the element's children. This is called by * the subclass' readElement method when it wants * to read the children of the element. */ virtual void ReadElementChildren(const SmartPointer& element); /** * Read each element one at a time by calling the * subclass implementation of readElement. * * Logs an error if the element was not recognized. */ virtual void ReadElements(const QList >& elements); /** * Read one extension by looping through its * configuration elements. */ virtual void ReadExtension(const SmartPointer& extension); public: /** * Start the registry reading process using the * supplied plugin ID and extension point. * * @param registry the registry to read from * @param pluginId the plugin id of the extenion point * @param extensionPoint the extension point id */ - virtual void ReadRegistry(const QString& pluginId, + virtual void ReadRegistry(IExtensionRegistry* registry, + const QString& pluginId, const QString& extensionPoint); /** * Utility for extracting the description child of an element. * * @param configElement the element * @return the description */ static QString GetDescription(const SmartPointer& configElement); /** * Utility for extracting the value of a class attribute or a nested class * element that follows the pattern set forth by * {@link org.blueberry.core.runtime.IExecutableExtension}. * * @param configElement * the element * @param classAttributeName * the name of the class attribute to check * @return the value of the attribute or nested class element */ static QString GetClassValue(const SmartPointer& configElement, const QString& classAttributeName); }; } #endif /*BERRYREGISTRYREADER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryReopenEditorMenu.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryReopenEditorMenu.cpp new file mode 100644 index 0000000000..84b51b10b1 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryReopenEditorMenu.cpp @@ -0,0 +1,303 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY 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 "berryReopenEditorMenu.h" + +#include +#include +#include + +#include +#include + +#include "berryEditorHistory.h" +#include "berryEditorHistoryItem.h" +#include "berryWorkbench.h" +#include "berryWorkbenchPlugin.h" +#include "berryPreferenceConstants.h" + +#include +#include +#include + +namespace berry { + +ReopenEditorMenu::ReopenEditorMenu(IWorkbenchWindow* window, const QString& id, bool showSeparator) + : ContributionItem(id) + , window(window) + , history(nullptr) + , showSeparator(showSeparator) + , dirty(true) +{ + IWorkbench* workbench = window->GetWorkbench(); + if (Workbench* w = dynamic_cast(workbench)) + { + history = w->GetEditorHistory(); + } +} + +QString ReopenEditorMenu::CalcText(int index, const QString& name, const QString& toolTip, bool rtl) +{ + QString sb; + + int mnemonic = index + 1; + QString nm = QString::number(mnemonic); + if (mnemonic <= MAX_MNEMONIC_SIZE) + { + nm.prepend('&'); + } + + QString fileName = name; + QString pathName = toolTip; + if (pathName == fileName) + { + // tool tip text isn't necessarily a path; + // sometimes it's the same as name, so it shouldn't be treated as a path then + pathName.clear(); + } + QFileInfo path(pathName); + // if last segment in path is the fileName, remove it + if (path.fileName() == fileName) + { + path.setFile(path.path()); + pathName = path.absoluteFilePath(); + } + + if ((fileName.size() + pathName.size()) <= (MAX_TEXT_LENGTH - 4)) + { + // entire item name fits within maximum length + sb += fileName; + if (!pathName.isEmpty()) + { + sb += " [" + pathName + "]"; + } + } + else + { + // need to shorten the item name + int length = fileName.size(); + if (length > MAX_TEXT_LENGTH) + { + // file name does not fit within length, truncate it + sb += fileName.left(MAX_TEXT_LENGTH - 3); + sb += "..."; + } + else if (length > MAX_TEXT_LENGTH - 7) + { + sb += fileName; + } + else + { + sb += fileName; + QStringList pathSegments = path.absoluteFilePath().split('/', QString::SkipEmptyParts); + int segmentCount = pathSegments.size(); + if (segmentCount > 0) + { + length += 7; // 7 chars are taken for " [...]" + + sb += " ["; + + // Add first n segments that fit + int i = 0; + while (i < segmentCount && length < MAX_TEXT_LENGTH) + { + const QString& segment = pathSegments[i]; + if (length + segment.size() < MAX_TEXT_LENGTH) + { + sb += segment + QDir::separator(); + length += segment.size() + 1; + i++; + } + else if (i == 0) + { + // append at least part of the first segment + sb += segment.left(MAX_TEXT_LENGTH - length); + length = MAX_TEXT_LENGTH; + break; + } + else + { + break; + } + } + + sb += "..."; + + i = segmentCount - 1; + // Add last n segments that fit + while (i > 0 && length < MAX_TEXT_LENGTH) + { + const QString& segment = pathSegments[i]; + if (length + segment.size() < MAX_TEXT_LENGTH) + { + sb += QDir::separator(); + sb += segment; + length += segment.size() + 1; + i--; + } + else + { + break; + } + } + + sb.append("]"); + } + } + } + QString process; + if (rtl) + { + process = sb + " " + nm; + } + else + { + process = nm + " " + sb; + } + //return TextProcessor.process(process, TextProcessor.getDefaultDelimiters() + "[]"); + return process; +} + +void ReopenEditorMenu::Fill(QMenu* menu, QAction* before) +{ + if (window->GetActivePage() == nullptr + || window->GetActivePage()->GetPerspective().IsNull()) + { + return; + } + + if (MenuManager* mm = dynamic_cast(this->GetParent())) + { + mm->connect(mm, SIGNAL(AboutToShow(IMenuManager*)), this, SLOT(MenuAboutToShow(IMenuManager*))); + } + + int itemsToShow = WorkbenchPlugin::GetDefault()->GetPreferences()->GetInt(PreferenceConstants::RECENT_FILES, 6); + if (itemsToShow == 0 || history == nullptr) + { + return; + } + + // Get items. + QList historyItems = history->GetItems(); + + int n = std::min(itemsToShow, historyItems.size()); + if (n <= 0) + { + return; + } + + if (showSeparator) + { + menu->addSeparator(); + } + + struct _SafeRunnable : public ISafeRunnable + { + QMenu* menu; + QAction* before; + EditorHistoryItem::Pointer item; + const int historyIndex; + + _SafeRunnable(QMenu* menu, QAction* before, EditorHistoryItem::Pointer item, int index) + : menu(menu), before(before), item(item), historyIndex(index) {} + + void Run() override + { + QString text = ReopenEditorMenu::CalcText(historyIndex, item); + QAction* mi = new QAction(text, nullptr); + menu->insertAction(before, mi); + mi->setData(QVariant::fromValue(item)); + } + + void HandleException(const ctkException& e) override + { + // just skip the item if there's an error, + // e.g. in the calculation of the shortened name + WorkbenchPlugin::Log(this->GetClassName(), "Fill", e); + } + }; + + for (int i = 0; i < n; i++) + { + EditorHistoryItem::Pointer item = historyItems[i]; + ISafeRunnable::Pointer runnable(new _SafeRunnable(menu, before, item, i)); + SafeRunner::Run(runnable); + } + dirty = false; +} + +bool ReopenEditorMenu::IsDirty() const +{ + return dirty; +} + +bool ReopenEditorMenu::IsDynamic() const +{ + return true; +} + +void ReopenEditorMenu::Open(const EditorHistoryItem::Pointer& item) +{ + IWorkbenchPage::Pointer page = window->GetActivePage(); + if (page.IsNotNull()) + { + try + { + QString itemName = item->GetName(); + if (!item->IsRestored()) + { + item->RestoreState(); + } + IEditorInput::Pointer input = item->GetInput(); + IEditorDescriptor::Pointer desc = item->GetDescriptor(); + if (!input || !desc) + { + QString title = "Problems opening editor"; + QString msg = QString("Unable to open %1.").arg(itemName); + QMessageBox::warning(window->GetShell()->GetControl(), title, msg); + history->Remove(item); + } + else + { + page->OpenEditor(input, desc->GetId()); + } + } + catch (const PartInitException& e2) + { + QString title = "Problems opening editor"; + QMessageBox::warning(window->GetShell()->GetControl(), title, e2.what()); + history->Remove(item); + } + } +} + +QString ReopenEditorMenu::CalcText(int index, const EditorHistoryItem::Pointer& item) +{ + // IMPORTANT: avoid accessing the item's input since + // this can require activating plugins. + // Instead, ask the item for the info, which can + // consult its memento if it is not restored yet. + return CalcText(index, item->GetName(), item->GetToolTipText(), false); + // Window::GetDefaultOrientation() == SWT.RIGHT_TO_LEFT); +} + +void ReopenEditorMenu::MenuAboutToShow(IMenuManager* manager) +{ + manager->MarkDirty(); + dirty = true; +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryReopenEditorMenu.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryReopenEditorMenu.h new file mode 100644 index 0000000000..e9db24de65 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryReopenEditorMenu.h @@ -0,0 +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 BERRYREOPENEDITORMENU_H +#define BERRYREOPENEDITORMENU_H + +#include + +namespace berry { + +struct IMenuManager; +struct IWorkbenchWindow; + +class EditorHistory; +class EditorHistoryItem; + +/** + * A dynamic menu item which supports to switch to other Windows. + */ +class ReopenEditorMenu : public QObject, public ContributionItem +{ + Q_OBJECT + +public: + + berryObjectMacro(ReopenEditorMenu) + + /** + * Create a new instance. + * @param window the window on which the menu is to be created + * @param id menu's id + * @param showSeparator whether or not to show a separator + */ + ReopenEditorMenu(IWorkbenchWindow* window, const QString& id, + bool showSeparator); + + /** + * Return a string suitable for a file MRU list. This should not be called + * outside the framework. + * + * @param index the index in the MRU list + * @param name the file name + * @param toolTip potentially the path + * @param rtl should it be right-to-left + * @return a string suitable for an MRU file menu + */ + static QString CalcText(int index, const QString& name, const QString& toolTip, bool rtl); + + /** + * Fills the given menu with + * menu items for all windows. + */ + void Fill(QMenu* menu, QAction* before) override; + + using ContributionItem::Fill; + + /** + * Overridden to always return true and force dynamic menu building. + */ + bool IsDirty() const override; + + /** + * Overridden to always return true and force dynamic menu building. + */ + bool IsDynamic() const override; + +private: + + /** + * Reopens the editor for the given history item. + */ + void Open(const SmartPointer& item); + + /** + * Returns the text for a history item. This may be truncated to fit + * within the MAX_TEXT_LENGTH. + */ + static QString CalcText(int index, const SmartPointer& item); + + IWorkbenchWindow* window; + + EditorHistory* history; + + bool showSeparator; + + bool dirty; + + Q_SLOT void MenuAboutToShow(IMenuManager* manager); + + // the maximum length for a file name; must be >= 4 + static const int MAX_TEXT_LENGTH = 40; + + // only assign mnemonic to the first nine items + static const int MAX_MNEMONIC_SIZE = 9; + +}; + +} +#endif // BERRYREOPENEDITORMENU_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp index c61f397d45..09ef83e7cf 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryShowViewMenu.cpp @@ -1,267 +1,277 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryShowViewMenu.h" #include #include #include #include #include #include #include #include #include #include "berryCommandContributionItemParameter.h" #include "berryWorkbenchPlugin.h" #include "berryViewDescriptor.h" #include "intro/berryIntroConstants.h" #include #include #include namespace berry { +const QString ShowViewMenu::NO_TARGETS_MSG = ""; + struct ActionComparator { bool operator()(const CommandContributionItemParameter::Pointer& p1, const CommandContributionItemParameter::Pointer& p2) const { return p1->label < p2->label; } }; ShowViewMenu::ShowViewMenu(IWorkbenchWindow *window, const QString& id) : ContributionItem(id), dirty(true), window(window) { CommandContributionItemParameter::Pointer showDlgItemParms( new CommandContributionItemParameter( window, QString::null, IWorkbenchCommandConstants::VIEWS_SHOW_VIEW, CommandContributionItem::STYLE_PUSH)); showDlgItemParms->label = "&Other..."; showDlgItem = new CommandContributionItem(showDlgItemParms); // window.getWorkbench().getHelpSystem().setHelp(showDlgAction, // IWorkbenchHelpContextIds.SHOW_VIEW_OTHER_ACTION); // // indicate that a show views submenu has been created // if (window instanceof WorkbenchWindow) { // ((WorkbenchWindow) window) // .addSubmenu(WorkbenchWindow.SHOW_VIEW_SUBMENU); // } } bool ShowViewMenu::IsDirty() const { return dirty; } /** * Overridden to always return true and force dynamic menu building. */ bool ShowViewMenu::IsDynamic() const { return true; } -QAction* ShowViewMenu::Fill(QMenu* menu, QAction* before) +void ShowViewMenu::Fill(QMenu* menu, QAction* before) { -// if (MenuManager::Pointer mm = GetParent().Cast()) -// { -// mm->AddMenuListener(menuListener); -// } + if (MenuManager* mm = dynamic_cast(GetParent())) + { + this->connect(mm, SIGNAL(AboutToShow(IMenuManager*)), SLOT(AboutToShow(IMenuManager*))); + } if (!dirty) { - return 0; + return; } MenuManager::Pointer manager(new MenuManager()); FillMenu(manager.GetPointer()); QList items = manager->GetItems(); - if (items.size() == 0) + if (items.isEmpty()) { - QAction* action = new QAction("No Views registered", menu); + QAction* action = new QAction(NO_TARGETS_MSG, menu); action->setEnabled(false); menu->insertAction(before, action); } else { foreach (IContributionItem::Pointer item, items) { - before = item->Fill(menu, before); + item->Fill(menu, before); } } dirty = false; - return before; } void ShowViewMenu::FillMenu(IMenuManager* innerMgr) { // Remove all. innerMgr->RemoveAll(); // If no page disable all. IWorkbenchPage::Pointer page = window->GetActivePage(); if (page.IsNull()) { return; } // If no active perspective disable all if (page->GetPerspective().IsNull()) { return; } typedef QPair ViewIdPair; // Get visible actions. QSet viewIds = GetShortcuts(page.GetPointer()); // add all open views viewIds = AddOpenedViews(page.GetPointer(), viewIds); QList actions; foreach (ViewIdPair id, viewIds) { if (id.first == IntroConstants::INTRO_VIEW_ID) { continue; } CommandContributionItemParameter::Pointer item = GetItem(id.first, id.second); if (item) { actions.append(item); } } qSort(actions.begin(), actions.end(), ActionComparator()); foreach (CommandContributionItemParameter::Pointer ccip, actions) { // if (WorkbenchActivityHelper.filterItem(ccip)) { // continue; // } CommandContributionItem::Pointer item(new CommandContributionItem(ccip)); innerMgr->Add(item); } // We only want to add the separator if there are show view shortcuts, // otherwise, there will be a separator and then the 'Other...' entry // and that looks weird as the separator is separating nothing if (!innerMgr->IsEmpty()) { IContributionItem::Pointer separator(new Separator()); innerMgr->Add(separator); } // Add Other... innerMgr->Add(showDlgItem); } QSet > ShowViewMenu::GetShortcuts(IWorkbenchPage* page) const { QSet > list; QList shortcuts(page->GetShowViewShortcuts()); for (int i = 0; i < shortcuts.size(); ++i) { list.insert(qMakePair(shortcuts[i], QString())); } return list; } +void ShowViewMenu::AboutToShow(IMenuManager* manager) +{ + manager->MarkDirty(); + this->dirty = true; +} + CommandContributionItemParameter::Pointer ShowViewMenu::GetItem(const QString& viewId, const QString& secondaryId) const { IViewRegistry* reg = WorkbenchPlugin::GetDefault()->GetViewRegistry(); IViewDescriptor::Pointer desc = reg->Find(viewId); if (desc.IsNull()) { return CommandContributionItemParameter::Pointer(0); } QString label = desc->GetLabel(); class PluginCCIP : public CommandContributionItemParameter, public IPluginContribution { QString localId; QString pluginId; public: + + berryObjectMacro(PluginCCIP, CommandContributionItemParameter, IPluginContribution) + PluginCCIP(const IViewDescriptor::Pointer& v, IServiceLocator* serviceLocator, const QString& id, const QString& commandId, CommandContributionItem::Style style) : CommandContributionItemParameter(serviceLocator, id, commandId, style) { ViewDescriptor::Pointer vd = v.Cast(); localId = vd->GetLocalId(); pluginId = vd->GetPluginId(); } QString GetLocalId() const { return localId; } QString GetPluginId() const { return pluginId; } }; CommandContributionItemParameter::Pointer parms(new PluginCCIP(desc, window, viewId, IWorkbenchCommandConstants::VIEWS_SHOW_VIEW, CommandContributionItem::STYLE_PUSH)); parms->label = label; parms->icon = desc->GetImageDescriptor(); Object::Pointer strViewId(new ObjectString(viewId)); parms->parameters.insert(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_PARM_ID, strViewId); // if (makeFast) // { // parms.parameters.put( // IWorkbenchCommandConstants.VIEWS_SHOW_VIEW_PARM_FASTVIEW, // "true"); //$NON-NLS-1$ // } if (!secondaryId.isEmpty()) { Object::Pointer strSecondaryId(new ObjectString(secondaryId)); parms->parameters.insert(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_SECONDARY_ID, strSecondaryId); } return parms; } QSet > ShowViewMenu::AddOpenedViews(IWorkbenchPage* page, QSet >& actions) const { QSet > views = GetParts(page); return views.unite(actions); } QSet > ShowViewMenu::GetParts(IWorkbenchPage* page) const { QSet > parts; QList refs = page->GetViewReferences(); for (int i = 0; i < refs.size(); ++i) { parts.insert(qMakePair(refs[i]->GetId(), refs[i]->GetSecondaryId())); } return parts; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryShowViewMenu.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryShowViewMenu.h index 400633eeb9..edf59d7704 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryShowViewMenu.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryShowViewMenu.h @@ -1,124 +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 BERRYSHOWVIEWMENU_H #define BERRYSHOWVIEWMENU_H #include #include namespace berry { struct IWorkbenchPage; struct IWorkbenchWindow; struct IMenuManager; class CommandContributionItemParameter; /** * A ShowViewMenu is used to populate a menu manager with Show * View actions. The visible views are determined by user preference from the * Perspective Customize dialog. */ -class ShowViewMenu : public ContributionItem +class ShowViewMenu : public QObject, public ContributionItem { + Q_OBJECT public: /** * Creates a Show View menu. * * @param window * the window containing the menu * @param id * the id */ ShowViewMenu(IWorkbenchWindow* window, const QString& id); bool IsDirty() const; /** * Overridden to always return true and force dynamic menu building. */ bool IsDynamic() const; using ContributionItem::Fill; - QAction* Fill(QMenu* menu, QAction *before); + void Fill(QMenu* menu, QAction *before); private: bool dirty; IWorkbenchWindow* window; - //static const QString NO_TARGETS_MSG = WorkbenchMessages.Workbench_showInNoTargets; + static const QString NO_TARGETS_MSG; /** * Fills the menu with Show View actions. */ void FillMenu(IMenuManager* innerMgr); QSet > GetShortcuts(IWorkbenchPage* page) const; IContributionItem::Pointer showDlgItem; -// IMenuListener menuListener = new IMenuListener() { -// public void menuAboutToShow(IMenuManager manager) { -// manager.markDirty(); -// dirty = true; -// } -// }; - // bool makeFast; + Q_SLOT void AboutToShow(IMenuManager* manager); SmartPointer GetItem(const QString& viewId, const QString& secondaryId) const; QSet > AddOpenedViews(IWorkbenchPage* page, QSet >& actions) const; QSet > GetParts(IWorkbenchPage* page) const; /** * @param commandService * @param makeFast */ // ParameterizedCommand GetCommand(ICommandService* commandService, // bool makeFast) // { // Command c = commandService.getCommand(IWorkbenchCommandConstants.VIEWS_SHOW_VIEW); // Parameterization[] parms = null; // if (makeFast) { // try { // IParameter parmDef = c // .getParameter(IWorkbenchCommandConstants.VIEWS_SHOW_VIEW_PARM_FASTVIEW); // parms = new Parameterization[] { new Parameterization(parmDef, // "true") //$NON-NLS-1$ // }; // } catch (NotDefinedException e) { // // this should never happen // } // } // return new ParameterizedCommand(c, parms); // } }; } #endif // BERRYSHOWVIEWMENU_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berrySwitchToWindowMenu.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berrySwitchToWindowMenu.cpp new file mode 100644 index 0000000000..943e4b35c0 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berrySwitchToWindowMenu.cpp @@ -0,0 +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 "berrySwitchToWindowMenu.h" + +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace berry { + +void SwitchToWindowMenu::AboutToShow(IMenuManager* manager) +{ + manager->MarkDirty(); + dirty = true; +} + +void SwitchToWindowMenu::MenuItemTriggered(int index) +{ + if (index < 0 || index >= windows.size()) return; + + IWorkbenchWindow* window = windows[index]; + Shell::Pointer windowShell = window->GetShell(); + if (windowShell->GetMinimized()) + { + windowShell->SetMinimized(false); + } + windowShell->SetActive(); + windowShell->GetControl()->raise(); + +} + +QString SwitchToWindowMenu::CalcText(int number, IWorkbenchWindow* window) +{ + QString suffix = window->GetShell()->GetText(); + if (suffix.isEmpty()) + { + return QString::null; + } + + QString sb; + if (number < 10) + { + sb.append('&'); + } + sb.append(QString::number(number)); + sb.append(' '); + if (suffix.size() <= MAX_TEXT_LENGTH) + { + sb.append(suffix); + } + else + { + sb.append(suffix.left(MAX_TEXT_LENGTH)); + sb.append("..."); + } + return sb; +} + +SwitchToWindowMenu::SwitchToWindowMenu(IWorkbenchWindow* window, const QString& id, bool showSeparator) + : ContributionItem(id) + , workbenchWindow(window) + , showSeparator(showSeparator) + , dirty(true) +{ +} + +void SwitchToWindowMenu::Fill(QMenu* menu, QAction* before) +{ + + // Get workbench windows. + IWorkbench* workbench = workbenchWindow->GetWorkbench(); + windows.clear(); + for (auto window : workbench->GetWorkbenchWindows()) + { + windows.push_back(window.GetPointer()); + } + + // avoid showing the separator and list for 0 or 1 items + if (windows.size() < 2) + { + return; + } + + if (MenuManager* mm = dynamic_cast(GetParent())) + { + this->connect(mm, SIGNAL(AboutToShow(IMenuManager*)), SLOT(AboutToShow(IMenuManager*))); + } + + if (!dirty) + { + return; + } + + // Add separator. + if (showSeparator) + { + menu->insertSeparator(before); + } + + // Add one item for each window. + QActionGroup* actionGroup = new QActionGroup(menu); + actionGroup->setExclusive(true); + QSignalMapper* signalMapper = new QSignalMapper(menu); + connect(signalMapper, SIGNAL(mapped(int)), SLOT(MenuItemTriggered(int))); + int count = 0; + for (auto window : windows) + { + // can encounter disposed shells if this update is in response to a shell closing + //if (!window->GetShell()->IsDisposed()) + //{ + QString name = CalcText(count, window); + if (!name.isEmpty()) + { + QAction* mi = new QAction(name, menu); + mi->setCheckable(true); + mi->setChecked(window == workbenchWindow); + actionGroup->addAction(mi); + menu->insertAction(before, mi); + signalMapper->setMapping(mi, count); + connect(mi, SIGNAL(triggered()), signalMapper, SLOT(map())); + } + ++count; + } + //} + dirty = false; +} + +bool SwitchToWindowMenu::IsDirty() const +{ + return dirty; +} + +bool SwitchToWindowMenu::IsDynamic() const +{ + return true; +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berrySwitchToWindowMenu.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berrySwitchToWindowMenu.h new file mode 100644 index 0000000000..75531ac26b --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berrySwitchToWindowMenu.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 BERRYSWITCHTOWINDOWMENU_H +#define BERRYSWITCHTOWINDOWMENU_H + +#include "berryContributionItem.h" + +namespace berry { + +struct IMenuManager; +struct IWorkbenchWindow; + +/** + * A dynamic menu item to switch to other opened workbench windows. + */ +class SwitchToWindowMenu : public QObject, public ContributionItem +{ + Q_OBJECT + +private: + + static const int MAX_TEXT_LENGTH = 40; + + IWorkbenchWindow* workbenchWindow; + + QList windows; + + bool showSeparator; + + bool dirty; + + Q_SLOT void AboutToShow(IMenuManager* manager); + + Q_SLOT void MenuItemTriggered(int index); + + /** + * Returns the text for a window. This may be truncated to fit + * within the MAX_TEXT_LENGTH. + */ + QString CalcText(int number, IWorkbenchWindow* window); + +public: + + /** + * Creates a new instance of this class. + * + * @param window the workbench window this action applies to + * @param showSeparator whether to add a separator in the menu + */ + SwitchToWindowMenu(IWorkbenchWindow* window, const QString& id, + bool showSeparator); + + /** + * Fills the given menu with menu items for all + * opened workbench windows. + */ + void Fill(QMenu* menu, QAction* before); + + using ContributionItem::Fill; + + /** + * Overridden to always return true and force dynamic menu building. + */ + bool IsDirty() const; + + /** + * Overridden to always return true and force dynamic menu building. + */ + bool IsDynamic() const; + +}; + +} + +#endif // BERRYSWITCHTOWINDOWMENU_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryUIExtensionTracker.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryUIExtensionTracker.cpp new file mode 100644 index 0000000000..d5b80ce442 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryUIExtensionTracker.cpp @@ -0,0 +1,97 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY 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 "berryUIExtensionTracker.h" + +#include +#include +#include +#include "berryWorkbenchPlugin.h" + +namespace berry { + +UIExtensionTracker::UIExtensionTracker(Display* display) + : display(display) +{ +} + +void UIExtensionTracker::ApplyRemove(IExtensionChangeHandler* handler, const SmartPointer& removedExtension, const QList >& objects) +{ + if (display == nullptr) return; + + struct RemoveRunnable : public Poco::Runnable { + + IExtensionChangeHandler* const h; + const IExtension::Pointer extension; + const QList objs; + + RemoveRunnable(IExtensionChangeHandler* h, const IExtension::Pointer& extension, const QList& objs) + : h(h) + , extension(extension) + , objs(objs) + {} + + void run() + { + try + { + h->RemoveExtension(extension, objs); + } + catch (const ctkException& e) + { + WorkbenchPlugin::Log("berry::UIExtensionTracker", "ApplyRemove", e); + } + } + }; + + RemoveRunnable runnable(handler, removedExtension, objects); + display->SyncExec(&runnable); +} + +void UIExtensionTracker::ApplyAdd(IExtensionChangeHandler* handler, const SmartPointer& addedExtension) +{ + if (display == nullptr) return; + + struct AddRunnable : public Poco::Runnable + { + IExtensionTracker* const tracker; + IExtensionChangeHandler* const h; + const IExtension::Pointer extension; + + AddRunnable(IExtensionTracker* tracker, IExtensionChangeHandler* h, const IExtension::Pointer& extension) + : tracker(tracker) + , h(h) + , extension(extension) + {} + + void run() + { + try + { + h->AddExtension(tracker, extension); + } + catch (const ctkException& e) + { + WorkbenchPlugin::Log("berry::UIExtensionTracker", "ApplyAdd", e); + } + } + }; + + AddRunnable runnable(this, handler, addedExtension); + display->SyncExec(&runnable); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryUIExtensionTracker.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryUIExtensionTracker.h new file mode 100644 index 0000000000..b958ed368e --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryUIExtensionTracker.h @@ -0,0 +1,51 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#ifndef BERRYUIEXTENSIONTRACKER_H +#define BERRYUIEXTENSIONTRACKER_H + +#include + +namespace berry { + +class Display; + +class UIExtensionTracker : public ExtensionTracker +{ +private: + + Display* display; + +public: + + /** + * @param display + */ + UIExtensionTracker(Display* display); + +protected: + + void ApplyRemove(IExtensionChangeHandler* handler, + const SmartPointer& removedExtension, + const QList >& objects); + + void ApplyAdd(IExtensionChangeHandler* handler, + const SmartPointer& addedExtension); +}; + +} + +#endif // BERRYUIEXTENSIONTRACKER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp index 2f999bd082..38561aea57 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.cpp @@ -1,210 +1,210 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryViewDescriptor.h" #include "berryIConfigurationElement.h" #include "berryCoreException.h" #include "berryIExtension.h" #include "berryIContributor.h" #include "berryStatus.h" #include "berryRegistryReader.h" #include "berryWorkbenchRegistryConstants.h" #include "berryAbstractUICTKPlugin.h" #include "handlers/berryIHandlerActivation.h" namespace berry { ViewDescriptor::ViewDescriptor(const IConfigurationElement::Pointer& e) : configElement(e) { this->LoadFromExtension(); } IViewPart::Pointer ViewDescriptor::CreateView() { IViewPart::Pointer part(configElement->CreateExecutableExtension ( WorkbenchRegistryConstants::ATT_CLASS)); return part; } QStringList ViewDescriptor::GetCategoryPath() const { return categoryPath; } IConfigurationElement::Pointer ViewDescriptor::GetConfigurationElement() const { return configElement; } QString ViewDescriptor::GetDescription() const { return RegistryReader::GetDescription(configElement); } QString ViewDescriptor::GetId() const { return id; } bool ViewDescriptor::operator==(const Object* o) const { if (const IViewDescriptor* other = dynamic_cast(o)) return this->GetId() == other->GetId(); return false; } QIcon ViewDescriptor::GetImageDescriptor() const { if (!imageDescriptor.isNull()) { return imageDescriptor; } QString iconName = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ICON); // If the icon attribute was omitted, use the default one if (iconName.isEmpty()) { //TODO default image descriptor //return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_DEF_VIEW); return AbstractUICTKPlugin::GetMissingIcon(); } IExtension::Pointer extension(configElement->GetDeclaringExtension()); const QString extendingPluginId(extension->GetContributor()->GetName()); imageDescriptor = AbstractUICTKPlugin::ImageDescriptorFromPlugin( extendingPluginId, iconName); // If the icon attribute was invalid, use the error icon if (imageDescriptor.isNull()) { imageDescriptor = AbstractUICTKPlugin::GetMissingIcon(); } return imageDescriptor; } QString ViewDescriptor::GetLabel() const { return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME); } QString ViewDescriptor::GetAccelerator() const { return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ACCELERATOR); } bool ViewDescriptor::GetAllowMultiple() const { return configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ALLOW_MULTIPLE).compare("true", Qt::CaseInsensitive) == 0; } bool ViewDescriptor::IsRestorable() const { QString str = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_RESTORABLE); return str.isNull() ? true : str.compare("true", Qt::CaseInsensitive) == 0; } -Object* ViewDescriptor::GetAdapter(const QString& adapter) +Object* ViewDescriptor::GetAdapter(const QString& adapter) const { if (adapter == qobject_interface_iid()) { return GetConfigurationElement().GetPointer(); } return NULL; } void ViewDescriptor::ActivateHandler() { //TODO ViewDescriptor handler activation // if (!handlerActivation) // { // IHandler::Pointer handler(new ShowViewHandler(this->GetId())); // IHandlerService::Pointer handlerService( // PlatformUI::GetWorkbench()->GetService(IHandlerService::GetManifestName()).Cast()); // handlerActivation = handlerService // ->ActivateHandler(this->GetId(), handler); // } } void ViewDescriptor::DeactivateHandler() { //TODO ViewDescriptor handler deactivation // if (handlerActivation) // { // IHandlerService::Pointer handlerService( // PlatformUI::GetWorkbench()->GetService(IHandlerService::GetManifestName()).Cast()); // handlerService->DeactivateHandler(handlerActivation); // handlerActivation = 0; // } } QStringList ViewDescriptor::GetKeywordReferences() const { QStringList result; auto keywordRefs = configElement->GetChildren("keywordReference"); for (auto keywordRefsIt = keywordRefs.begin(); keywordRefsIt != keywordRefs.end(); ++keywordRefsIt) // iterate over all refs { result.push_back((*keywordRefsIt)->GetAttribute("id")); } return result; } QString ViewDescriptor::GetPluginId() const { return configElement->GetContributor()->GetName(); } QString ViewDescriptor::GetLocalId() const { return this->GetId(); } void ViewDescriptor::LoadFromExtension() { id = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ID); // Sanity check. QString name = configElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME); if (name.isEmpty() || RegistryReader::GetClassValue(configElement, WorkbenchRegistryConstants::ATT_CLASS).isEmpty()) { IStatus::Pointer status(new Status(IStatus::ERROR_TYPE, configElement->GetContributor()->GetName(), 0, QString("Invalid extension (missing label or class name): ") + id)); throw CoreException(status); } QString category = configElement->GetAttribute(WorkbenchRegistryConstants::TAG_CATEGORY); if (!category.isEmpty()) { // Parse the path tokens and store them foreach (QString pathElement, category.split('/', QString::SkipEmptyParts)) { if (!pathElement.trimmed().isEmpty()) { categoryPath.push_back(pathElement.trimmed()); } } } } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.h index 650dfc7188..36c7369020 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewDescriptor.h @@ -1,164 +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 BERRYVIEWDESCRIPTOR_H_ #define BERRYVIEWDESCRIPTOR_H_ #include "berryIViewPart.h" #include "berryIViewDescriptor.h" #include "berryIPluginContribution.h" #include #include namespace berry { struct IConfigurationElement; struct IHandlerActivation; /** * \ingroup org_blueberry_ui_internal * */ class ViewDescriptor : public IViewDescriptor, public IPluginContribution { private: QString id; mutable QIcon imageDescriptor; IConfigurationElement::Pointer configElement; QStringList categoryPath; /** * The activation token returned when activating the show view handler with * the workbench. */ SmartPointer handlerActivation; public: berryObjectMacro(ViewDescriptor); /** * Create a new ViewDescriptor for an extension. * * @param e the configuration element * @throws CoreException thrown if there are errors in the configuration */ ViewDescriptor(const SmartPointer& e); /* (non-Javadoc) * @see org.blueberry.ui.internal.registry.IViewDescriptor#createView() */ IViewPart::Pointer CreateView(); /* (non-Javadoc) * @see org.blueberry.ui.internal.registry.IViewDescriptor#getCategoryPath() */ QStringList GetCategoryPath() const; /** * Return the configuration element for this descriptor. * * @return the configuration element */ IConfigurationElement::Pointer GetConfigurationElement() const; /* (non-Javadoc) * @see org.blueberry.ui.internal.registry.IViewDescriptor#getDescription() */ QString GetDescription() const; QStringList GetKeywordReferences() const; /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartDescriptor#getId() */ QString GetId() const; /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartDescriptor#getImageDescriptor() */ QIcon GetImageDescriptor() const; /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartDescriptor#getLabel() */ QString GetLabel() const; /** * Return the accelerator attribute. * * @return the accelerator attribute */ QString GetAccelerator() const; /* (non-Javadoc) * @see org.blueberry.ui.internal.registry.IViewDescriptor#getAllowMultiple() */ bool GetAllowMultiple() const; /* (non-Javadoc) * @see org.eclipse.ui.views.IViewDescriptor#getRestorable() */ bool IsRestorable() const; bool operator==(const Object*) const; /** * Activates a show view handler for this descriptor. This handler can later * be deactivated by calling {@link ViewDescriptor#deactivateHandler()}. * This method will only activate the handler if it is not currently active. * */ void ActivateHandler(); /** * Deactivates the show view handler for this descriptor. This handler was * previously activated by calling {@link ViewDescriptor#activateHandler()}. * This method will only deactivative the handler if it is currently active. * */ void DeactivateHandler(); /* * @see IPluginContribution#GetPluginId() */ QString GetPluginId() const; /* * @see IPluginContribution#GetLocalId() */ QString GetLocalId() const; protected: /* (non-Javadoc) * @see IAdaptable#GetAdapterImpl(const std::type_info&) */ - Object* GetAdapter(const QString& adapter); + Object* GetAdapter(const QString& adapter) const; private: /** * load a view descriptor from the registry. */ void LoadFromExtension(); }; } #endif /*BERRYVIEWDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewFactory.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewFactory.cpp index e425e6b43d..d8248adf5a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewFactory.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewFactory.cpp @@ -1,323 +1,323 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryViewFactory.h" #include "berryUIException.h" #include "berryIViewRegistry.h" #include "berryViewReference.h" #include "berryViewDescriptor.h" #include "berryWorkbenchPage.h" #include "berryWorkbenchConstants.h" #include "util/berrySafeRunnable.h" #include namespace berry { const QString ViewFactory::ID_SEP = ":"; //$NON-NLS-1$ QString ViewFactory::GetKey(const QString& id, const QString& secondaryId) { return secondaryId.isEmpty() ? id : id + ID_SEP + secondaryId; } QString ViewFactory::GetKey(IViewReference::Pointer viewRef) { return GetKey(viewRef->GetId(), viewRef->GetSecondaryId()); } QString ViewFactory::ExtractPrimaryId(const QString& compoundId) { int i = compoundId.lastIndexOf(ID_SEP); if (i == -1) { return compoundId; } return compoundId.left(i); } QString ViewFactory::ExtractSecondaryId(const QString& compoundId) { int i = compoundId.lastIndexOf(ID_SEP); if (i == -1) { return QString(); } return compoundId.mid(i + 1); } bool ViewFactory::HasWildcard(const QString& viewId) { return viewId.indexOf('*') != -1; } ViewFactory::ViewFactory(WorkbenchPage* p, IViewRegistry* reg) : page(p), viewReg(reg) { //page.getExtensionTracker().registerHandler(this, null); } IViewReference::Pointer ViewFactory::CreateView(const QString& id, const QString& secondaryId) { IViewDescriptor::Pointer desc = viewReg->Find(id); // ensure that the view id is valid if (desc.IsNull()) { throw PartInitException(QString("Could not create view: ") + id); } // ensure that multiple instances are allowed if a secondary id is given if (secondaryId != "") { if (!desc->GetAllowMultiple()) { throw PartInitException(QString("View does not allow multiple instances:") + id); } } QString key = this->GetKey(id, secondaryId); IViewReference::Pointer ref = counter.Get(key); if (ref.IsNull()) { IMemento::Pointer memento = mementoTable[key]; ref = new ViewReference(this, id, secondaryId, memento); mementoTable.remove(key); counter.Put(key, ref); this->GetWorkbenchPage()->PartAdded(ref.Cast ()); } else { counter.AddRef(key); } return ref; } QList ViewFactory::GetViewReferences() { QList values(counter.Values()); return values; } IViewReference::Pointer ViewFactory::GetView(const QString& id) { return this->GetView(id, ""); } IViewReference::Pointer ViewFactory::GetView(const QString& id, const QString& secondaryId) { QString key = this->GetKey(id, secondaryId); return counter.Get(key); } const IViewRegistry* ViewFactory::GetViewRegistry() const { return viewReg; } QList ViewFactory::GetViews() { QList values(counter.Values()); return values; } WorkbenchPage* ViewFactory::GetWorkbenchPage() const { return page; } int ViewFactory::GetReferenceCount(IViewReference::Pointer viewRef) { QString key = this->GetKey(viewRef); IViewReference::Pointer ref = counter.Get(key); return ref.IsNull() ? 0 : counter.GetRef(key); } void ViewFactory::ReleaseView(IViewReference::Pointer viewRef) { QString key = this->GetKey(viewRef); IViewReference::Pointer ref = counter.Get(key); if (ref.IsNull()) { return; } int count = counter.RemoveRef(key); if (count <= 0) { this->GetWorkbenchPage()->PartRemoved(ref.Cast ()); } } bool ViewFactory::RestoreState(IMemento::Pointer memento) { QList mem(memento->GetChildren( WorkbenchConstants::TAG_VIEW)); for (int i = 0; i < mem.size(); i++) { //for dynamic UI - add the next line to replace subsequent code that is commented out RestoreViewState(mem[i]); } // return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ return true; } bool ViewFactory::SaveState(IMemento::Pointer memento) { // final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, // IStatus.OK, WorkbenchMessages.ViewFactory_problemsSavingViews, null); bool result = true; QList refs(GetViews()); for (int i = 0; i < refs.size(); i++) { IViewDescriptor::Pointer desc = viewReg->Find(refs[i]->GetId()); if (desc->IsRestorable()) { //for dynamic UI - add the following line to replace subsequent code which is commented out SaveViewState(memento, refs[i], result); } } return result; } struct SaveViewRunnable: public SafeRunnable { SaveViewRunnable(IViewPart::Pointer view, IMemento::Pointer viewMemento, bool& result) : view(view), viewMemento(viewMemento), result(result) { } void Run() { const QHash& properties = view->GetPartProperties(); if (!properties.empty()) { IMemento::Pointer propBag = viewMemento ->CreateChild( WorkbenchConstants::TAG_PROPERTIES); for (QHash::const_iterator i = properties.begin(); i != properties.end(); ++i) { IMemento::Pointer p = propBag->CreateChild( WorkbenchConstants::TAG_PROPERTY, i.key()); p->PutTextData(i.value()); } } view->SaveState(viewMemento ->CreateChild( WorkbenchConstants::TAG_VIEW_STATE)); } - void HandleException(const std::exception& /*e*/) + void HandleException(const ctkException& /*e*/) { // result // .add(new Status( // IStatus.ERR, // PlatformUI.PLUGIN_ID, // 0, // NLS.bind(WorkbenchMessages.ViewFactory_couldNotSave, viewRef.getTitle() ), // e)); result = false; } private: IViewPart::Pointer view; IMemento::Pointer viewMemento; bool& result; }; // for dynamic UI IMemento::Pointer ViewFactory::SaveViewState(IMemento::Pointer memento, IViewReference::Pointer ref, bool& res) { //final MultiStatus result = res; bool& result = res; IMemento::Pointer viewMemento = memento->CreateChild( WorkbenchConstants::TAG_VIEW); viewMemento->PutString(WorkbenchConstants::TAG_ID, ViewFactory::GetKey(ref)); if (ViewReference::Pointer viewRef = ref.Cast()) { viewMemento->PutString(WorkbenchConstants::TAG_PART_NAME, viewRef->GetPartName()); } const IViewReference::Pointer viewRef = ref; const IViewPart::Pointer view = ref->GetPart(false).Cast (); if (view) { ISafeRunnable::Pointer runnable(new SaveViewRunnable(view, viewMemento, result)); SafeRunner::Run(runnable); } else { IMemento::Pointer mem; IMemento::Pointer props; // if we've created the reference once, any previous workbench // state memento is there. After once, there is no previous // session state, so it should be null. if (ref.Cast ()) { mem = ref.Cast ()->GetMemento(); if (mem) { props = mem->GetChild(WorkbenchConstants::TAG_PROPERTIES); mem = mem->GetChild(WorkbenchConstants::TAG_VIEW_STATE); } } if (props) { viewMemento->CreateChild(WorkbenchConstants::TAG_PROPERTIES) ->PutMemento( props); } if (mem) { IMemento::Pointer child = viewMemento ->CreateChild( WorkbenchConstants::TAG_VIEW_STATE); child->PutMemento(mem); } } return viewMemento; } // for dynamic UI void ViewFactory::RestoreViewState(IMemento::Pointer memento) { QString compoundId; memento->GetString(WorkbenchConstants::TAG_ID, compoundId); mementoTable.insert(compoundId, memento); } IMemento::Pointer ViewFactory::GetViewState(const QString& key) { IMemento::Pointer memento = mementoTable[key]; if (!memento) return IMemento::Pointer(0); return memento->GetChild(WorkbenchConstants::TAG_VIEW_STATE); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistry.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistry.cpp index 2abf399801..41c4b80509 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistry.cpp @@ -1,275 +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. ===================================================================*/ #include "berryViewRegistry.h" #include "berryPlatformUI.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchRegistryConstants.h" #include "berryPlatform.h" namespace berry { ViewRegistry::ViewCategoryProxy::ViewCategoryProxy( IViewDescriptorCategoryPtr rawCategory) : rawCategory(rawCategory) { } QList ViewRegistry::ViewCategoryProxy::GetViews() const { return rawCategory->GetElements(); } QString ViewRegistry::ViewCategoryProxy::GetId() const { return rawCategory->GetId(); } QStringList ViewRegistry::ViewCategoryProxy::GetPath() const { QList path; QString rawParentPath = rawCategory->GetRawParentPath(); // nested categories are not supported yet // assume an empty raw parent path path.push_back(rawParentPath); return path; } QString ViewRegistry::ViewCategoryProxy::GetLabel() const { return rawCategory->GetLabel(); } +QString ViewRegistry::ViewCategoryProxy::GetLocalId() const +{ + return GetId(); +} + +QString ViewRegistry::ViewCategoryProxy::GetPluginId() const +{ + return rawCategory->GetPluginId(); +} + bool ViewRegistry::ViewCategoryProxy::operator==(const Object* o) const { if (const IViewCategory* other = dynamic_cast(o)) return this->GetId() == other->GetId(); return false; } uint ViewRegistry::ViewCategoryProxy::HashCode() const { return qHash(GetId()); } QString ViewRegistry::EXTENSIONPOINT_UNIQUE_ID = "org.blueberry.ui.views"; // PlatformUI::PLUGIN_ID + "." + WorkbenchRegistryConstants::PL_VIEWS; Category::Pointer ViewRegistry::InternalFindCategory(const QString& id) { for (QList::iterator itr = categories.begin(); itr != categories.end(); ++itr) { if (id == (*itr)->GetRootPath()) { return *itr; } } return IViewDescriptorCategoryPtr(0); } IExtensionPoint::Pointer ViewRegistry::GetExtensionPointFilter() { return Platform::GetExtensionRegistry()->GetExtensionPoint(EXTENSIONPOINT_UNIQUE_ID); } const QString ViewRegistry::TAG_DESCRIPTION = "description"; ViewRegistry::ViewRegistry() : dirtyViewCategoryMappings(true) { miscCategory = new IViewDescriptorCategory(); this->Add(miscCategory); //PlatformUI.getWorkbench().getExtensionTracker().registerHandler(this, // ExtensionTracker.createExtensionPointFilter(getExtensionPointFilter())); - reader.ReadViews(this); + reader.ReadViews(Platform::GetExtensionRegistry(), this); } void ViewRegistry::Add(IViewDescriptorCategoryPtr desc) { /* fix for 1877 */ if (this->InternalFindCategory(desc->GetId()).IsNull()) { dirtyViewCategoryMappings = true; // Mark categories list as dirty categories.push_back(desc); // IConfigurationElement::Pointer element( // dynamic_cast( // desc->GetAdapter(typeid(IConfigurationElement)) // )); // if (element.IsNull()) // { // return; // } // PlatformUI::GetWorkbench()->GetExtensionTracker() // .registerObject(element->GetDeclaringExtension(), desc, // IExtensionTracker::REF_WEAK); } } void ViewRegistry::Add(ViewDescriptor::Pointer desc) { for (QList::const_iterator itr = views.begin(); itr != views.end(); ++itr) { if (desc.GetPointer() == itr->GetPointer()) return; } views.push_back(desc); dirtyViewCategoryMappings = true; //desc.activateHandler(); } void ViewRegistry::Add(StickyViewDescriptor::Pointer desc) { if (std::find(sticky.begin(), sticky.end(), desc) == sticky.end()) { sticky.push_back(desc); // PlatformUI::GetWorkbench()->GetExtensionTracker() // .registerObject(desc.getConfigurationElement().getDeclaringExtension(), // desc, IExtensionTracker.REF_WEAK); } } IViewDescriptor::Pointer ViewRegistry::Find(const QString& id) const { for (QList::const_iterator itr = views.begin(); itr != views.end(); ++itr) { if (id == (*itr)->GetId()) { return *itr; } } return IViewDescriptor::Pointer(0); } IViewCategory::Pointer ViewRegistry::FindCategory(const QString& id) { this->MapViewsToCategories(); IViewDescriptorCategoryPtr category(this->InternalFindCategory(id)); if (category.IsNull()) { return IViewCategory::Pointer(0); } IViewCategory::Pointer cat(new ViewCategoryProxy(category)); return cat; } QList ViewRegistry::GetCategories() { this->MapViewsToCategories(); QList retArray; for (QList::iterator itr = categories.begin(); itr != categories.end(); ++itr) { retArray.push_back(IViewCategory::Pointer(new ViewCategoryProxy(*itr))); } return retArray; } QList ViewRegistry::GetStickyViews() const { return sticky; } Category::Pointer ViewRegistry::GetMiscCategory() const { return miscCategory; } QList ViewRegistry::GetViews() const { return views; } void ViewRegistry::MapViewsToCategories() { if (dirtyViewCategoryMappings) { dirtyViewCategoryMappings = false; // clear all category mappings for (QList::iterator i = categories.begin(); i != categories.end(); ++i) { (*i)->Clear(); // this is bad } miscCategory->Clear(); for (QList::iterator i = views.begin(); i != views.end(); ++i) { IViewDescriptor::Pointer desc(*i); IViewDescriptorCategoryPtr cat(0); const QList& catPath = desc->GetCategoryPath(); if (catPath.size() > 0) { cat = this->InternalFindCategory(catPath[0]); } if (cat.IsNotNull()) { if (!cat->HasElement(desc)) { cat->AddElement(desc); } } else { if (catPath.size() > 0) { // If we get here, this view specified a category which // does not exist. Add this view to the 'Other' category // but give out a message (to the log only) indicating // this has been done. QString fmt("Category %1 not found for view %2. This view added to ''%3'' category."); WorkbenchPlugin::Log(fmt.arg(catPath[0]).arg(desc->GetId()).arg(miscCategory->GetLabel())); } miscCategory->AddElement(desc); } } } } //void ViewRegistry::AddExtension(IExtensionTracker tracker, // IExtension addedExtension) //{ // IConfigurationElement[] addedElements = addedExtension.getConfigurationElements(); // for (int i = 0; i < addedElements.length; i++) // { // IConfigurationElement element = addedElements[i]; // if (element.getName().equals(IWorkbenchRegistryConstants.TAG_VIEW)) // { // reader.readView(element); // } // else if (element.getName().equals(IWorkbenchRegistryConstants.TAG_CATEGORY)) // { // reader.readCategory(element); // } // else if (element.getName().equals(IWorkbenchRegistryConstants.TAG_STICKYVIEW)) // { // reader.readSticky(element); // } // } //} } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistry.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistry.h index 890c461239..b694b93b97 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistry.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistry.h @@ -1,221 +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 BERRYVIEWREGISTRY_H_ #define BERRYVIEWREGISTRY_H_ #include "berryIViewRegistry.h" #include "berryIViewCategory.h" #include "berryIViewDescriptor.h" #include "berryCategory.h" #include "berryViewDescriptor.h" #include "berryViewRegistryReader.h" #include "berryStickyViewDescriptor.h" #include "berryIExtensionPoint.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * * The central manager for view descriptors. */ class ViewRegistry : public IViewRegistry { public: typedef Category IViewDescriptorCategory; typedef IViewDescriptorCategory::Pointer IViewDescriptorCategoryPtr; private: /** * Proxies a Category implementation. * */ - class ViewCategoryProxy : public IViewCategory + class ViewCategoryProxy : public IViewCategory, public IPluginContribution { private: typedef Category IViewDescriptorCategory; IViewDescriptorCategoryPtr rawCategory; /** * Create a new instance of this class * * @param rawCategory the category */ public: ViewCategoryProxy(IViewDescriptorCategoryPtr rawCategory); - /* (non-Javadoc) - * @see org.blueberry.ui.views.IViewCategory#getViews() + /* + * @see IViewCategory#GetViews() */ QList GetViews() const; - /* (non-Javadoc) - * @see org.blueberry.ui.views.IViewCategory#getId() + /* + * @see IViewCategory#GetId() */ QString GetId() const; - /* (non-Javadoc) - * @see org.blueberry.ui.views.IViewCategory#getPath() + /* + * @see IViewCategory#GetPath() */ QStringList GetPath() const; - /* (non-Javadoc) - * @see org.blueberry.ui.views.IViewCategory#getLabel() + /* + * @see IViewCategory#GetLabel() */ QString GetLabel() const; - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) + /* + * @see IPluginContribution#GetLocalId() + */ + QString GetLocalId() const; + + /* + * @see IPluginContribution#GetPluginId() + */ + QString GetPluginId() const; + + /* + * @see Object#operator==(Object*) */ bool operator==(const Object* o) const; - /* (non-Javadoc) - * @see java.lang.Object#hashCode() + /* + * @see Object#HashCode() */ uint HashCode() const; }; private: static QString EXTENSIONPOINT_UNIQUE_ID; /** * A set that will only ever contain ViewDescriptors. */ QList views; // = new TreeSet(new Comparator() { // public int compare(Object o1, Object o2) { // String id1 = ((ViewDescriptor) o1).getId(); // String id2 = ((ViewDescriptor) o2).getId(); // // return id1.compareTo(id2); // }}); QList sticky; QList categories; IViewDescriptorCategoryPtr miscCategory; ViewRegistryReader reader; bool dirtyViewCategoryMappings; /** * Returns the category with no updating of the view/category mappings. * * @param id the category id * @return the Category * @since 3.1 */ IViewDescriptorCategoryPtr InternalFindCategory(const QString& id); SmartPointer GetExtensionPointFilter(); protected: static const QString TAG_DESCRIPTION; // = "description"; public: ViewRegistry(); /** * Add a category to the registry. * * @param desc the descriptor to add */ void Add(IViewDescriptorCategoryPtr desc); /** * Add a descriptor to the registry. * * @param desc the descriptor to add */ void Add(ViewDescriptor::Pointer desc); /** * Add a sticky descriptor to the registry. * * @param desc the descriptor to add */ void Add(StickyViewDescriptor::Pointer desc); /** * Find a descriptor in the registry. */ IViewDescriptor::Pointer Find(const QString& id) const; /** * Find a category with a given name. * * @param id the id to search for * @return the category or null */ IViewCategory::Pointer FindCategory(const QString& id); /** * Get the list of view categories. */ QList GetCategories(); /** * Get the list of sticky views minus the sticky views which failed the * Expressions check. */ QList GetStickyViews() const; /** * Returns the Misc category. This may be null if there are * no miscellaneous views. * * @return the misc category or null */ IViewDescriptorCategoryPtr GetMiscCategory() const; /** * Get an enumeration of view descriptors. */ QList GetViews() const; /** * Adds each view in the registry to a particular category. * The view category may be defined in xml. If not, the view is * added to the "misc" category. */ void MapViewsToCategories(); /* (non-Javadoc) * @see org.blueberry.core.runtime.dynamicHelpers.IExtensionChangeHandler#addExtension(org.blueberry.core.runtime.dynamicHelpers.IExtensionTracker, org.blueberry.core.runtime.IExtension) */ //void AddExtension(IExtensionTracker tracker, IExtension addedExtension); }; } // namespace berry #endif /*BERRYVIEWREGISTRY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistryReader.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistryReader.cpp index 86f10e2f9f..39f44724bb 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistryReader.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistryReader.cpp @@ -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. ===================================================================*/ #include "berryViewRegistryReader.h" #include "berryViewRegistry.h" #include "berryWorkbenchRegistryConstants.h" #include "berryWorkbenchPlugin.h" #include "berryPlatformUI.h" namespace berry { QString ViewRegistryReader::GENERAL_VIEW_ID = "org.blueberry.ui"; ViewRegistryReader::ViewRegistryReader() : RegistryReader() { } -void ViewRegistryReader::ReadViews(ViewRegistry* out) +void ViewRegistryReader::ReadViews(IExtensionRegistry* in, ViewRegistry* out) { // this does not seem to really ever be throwing an the exception viewRegistry = out; - this->ReadRegistry(PlatformUI::PLUGIN_ID(), + this->ReadRegistry(in, PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_VIEWS); } void ViewRegistryReader::ReadCategory(const IConfigurationElement::Pointer& element) { try { Category::Pointer cat(new Category(element)); viewRegistry->Add(cat); } catch (CoreException e) { // log an error since its not safe to show a dialog here WorkbenchPlugin::Log( - "Unable to create view category.", e);//$NON-NLS-1$ + "Unable to create view category.", e); } } bool ViewRegistryReader::ReadElement(const SmartPointer &element) { QString elementName = element->GetName(); if (elementName == WorkbenchRegistryConstants::TAG_VIEW) { this->ReadView(element); return true; } if (elementName == WorkbenchRegistryConstants::TAG_CATEGORY) { this->ReadCategory(element); this->ReadElementChildren(element); return true; } if (elementName == WorkbenchRegistryConstants::TAG_STICKYVIEW) { this->ReadSticky(element); return true; } return false; } void ViewRegistryReader::ReadSticky(const SmartPointer &element) { try { viewRegistry->Add(StickyViewDescriptor::Pointer(new StickyViewDescriptor(element))); } catch (CoreException& e) { //TODO IStatus // log an error since its not safe to open a dialog here // WorkbenchPlugin.log( // "Unable to create sticky view descriptor.", e.getStatus());//$NON-NLS-1$ WorkbenchPlugin::Log("Unable to create sticky view descriptor.", e); } } void ViewRegistryReader::ReadView(const SmartPointer &element) { try { ViewDescriptor::Pointer desc(new ViewDescriptor(element)); viewRegistry->Add(desc); } catch (CoreException e) { // log an error since its not safe to open a dialog here WorkbenchPlugin::Log( "Unable to create view descriptor.", e);//$NON-NLS-1$ } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistryReader.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistryReader.h index e53c39013a..7d1d89343a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistryReader.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryViewRegistryReader.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 BERRYVIEWREGISTRYREADER_H_ #define BERRYVIEWREGISTRYREADER_H_ #include "berryRegistryReader.h" namespace berry { class ViewRegistry; /** * \ingroup org_blueberry_ui_internal * * A strategy to read view extensions from the registry. */ class ViewRegistryReader : public RegistryReader { public: /** * General view category id */ static QString GENERAL_VIEW_ID ; /** * RegistryViewReader constructor comment. */ ViewRegistryReader(); /** * Read the view extensions within a registry. * @param in the extension registry * @param out the view registry */ - void ReadViews(ViewRegistry* out); + void ReadViews(IExtensionRegistry* in, ViewRegistry* out); protected: /** * Reads the category element. */ void ReadCategory(const SmartPointer& element); /** * readElement method comment. */ bool ReadElement(const SmartPointer& element); /** * Reads the sticky view element. */ void ReadSticky(const SmartPointer& element); /** * Reads the view element. */ void ReadView(const SmartPointer& element); private: ViewRegistry* viewRegistry; }; } // namespace berry #endif /*BERRYVIEWREGISTRYREADER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWWinPartService.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWWinPartService.cpp index 1d3492faa9..890dd2c8de 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWWinPartService.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWWinPartService.cpp @@ -1,231 +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. ===================================================================*/ #include "berryWWinPartService.h" #include "berryIWorkbenchWindow.h" #include "berryWorkbenchPage.h" namespace berry { struct WWinListener: public IPartListener { //, IPageChangedListener { WWinListener(WWinPartService* wwps) : wwps(wwps) { } Events::Types GetPartEventTypes() const { return Events::ALL; } void PartActivated(const IWorkbenchPartReference::Pointer& /*ref*/) { wwps->UpdateActivePart(); } void PartBroughtToTop(const IWorkbenchPartReference::Pointer& ref) { wwps->partService.FirePartBroughtToTop(ref); } void PartClosed(const IWorkbenchPartReference::Pointer& ref) { wwps->partService.FirePartClosed(ref); } void PartDeactivated(const IWorkbenchPartReference::Pointer& /*ref*/) { wwps->UpdateActivePart(); } void PartOpened(const IWorkbenchPartReference::Pointer& ref) { wwps->partService.FirePartOpened(ref); } void PartHidden(const IWorkbenchPartReference::Pointer& ref) { wwps->partService.FirePartHidden(ref); } void PartVisible(const IWorkbenchPartReference::Pointer& ref) { wwps->partService.FirePartVisible(ref); } void PartInputChanged(const IWorkbenchPartReference::Pointer& ref) { wwps->partService.FirePartInputChanged(ref); } // void PageChanged(PageChangedEvent::Pointer event) { // partService.firePageChanged(event); // } private: WWinPartService* wwps; }; WWinPartService::WWinPartService(IWorkbenchWindow* window) : partService("", ""), selectionService(window), activePage(0), partListener(new WWinListener( this)) { } void WWinPartService::AddPartListener(IPartListener* l) { partService.AddPartListener(l); } void WWinPartService::RemovePartListener(IPartListener* l) { partService.RemovePartListener(l); } IWorkbenchPart::Pointer WWinPartService::GetActivePart() { return partService.GetActivePart(); } void WWinPartService::UpdateActivePart() { IWorkbenchPartReference::Pointer activeRef; IWorkbenchPart::Pointer activePart; if (activePage) { activePart = activePage->GetActivePart(); activeRef = activePage->GetActivePartReference(); } partService.SetActivePart(activeRef); selectionService.SetActivePart(activePart); } IWorkbenchPartReference::Pointer WWinPartService::GetActivePartReference() { return partService.GetActivePartReference(); } -ISelectionService* WWinPartService::GetSelectionService() +ISelectionService* WWinPartService::GetSelectionService() const { - return &selectionService; + return const_cast(&selectionService); } void WWinPartService::PageActivated(SmartPointer newPage) { // Optimize. if (newPage == activePage) { return; } // Fire events in the following order: // 1. For each open part in the new page, open it and then (if applicable) make it visible // 2. Deactivate old active part // 3. Activate the new active part // 4. For each open part in the old page, make it invisible then close it // Hook listener on the new page. if (newPage) { QList refs(newPage.Cast< WorkbenchPage> ()->GetOpenParts()); for (int i = 0; i < refs.size(); i++) { IWorkbenchPartReference::Pointer reference = refs[i]; partService.FirePartOpened(reference); IWorkbenchPart::Pointer part = reference->GetPart(false); if (part && newPage->IsPartVisible(part)) { partService.FirePartVisible(reference); } } partService.SetActivePart(newPage->GetActivePartReference()); selectionService.SetActivePart(newPage->GetActivePart()); } else { partService.SetActivePart(IWorkbenchPartReference::Pointer(0)); selectionService.SetActivePart(IWorkbenchPart::Pointer(0)); } // Unhook listener from the old page. Reset(); // Update active page. activePage = newPage.GetPointer(); if (newPage) { newPage->AddPartListener(partListener.data()); } } void WWinPartService::PageClosed(SmartPointer page) { // Unhook listener from the old page. if (page == activePage) { Reset(); } } void WWinPartService::PageOpened(SmartPointer page) { PageActivated(page); } void WWinPartService::Reset() { IWorkbenchPage* tempPage = activePage; activePage = 0; if (tempPage) { WorkbenchPage* page = dynamic_cast(tempPage); QList refs(page->GetOpenParts()); for (int i = 0; i < refs.size(); i++) { IWorkbenchPartReference::Pointer reference = refs[i]; if (page->IsPartVisible(reference)) { partService.FirePartHidden(reference); } partService.FirePartClosed(reference); } tempPage->RemovePartListener(partListener.data()); } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWWinPartService.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWWinPartService.h index 664a8b0094..bf3dc2f452 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWWinPartService.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWWinPartService.h @@ -1,111 +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 BERRYWWINPARTSERVICE_H_ #define BERRYWWINPARTSERVICE_H_ #include "berryIPartService.h" #include "berryPartService.h" #include "berryWindowSelectionService.h" namespace berry { /** * A part service for a workbench window. */ class WWinPartService: public IPartService { private: friend struct WWinListener; PartService partService; // (UIListenerLogging.WINDOW_PARTLISTENER_EVENTS, UIListenerLogging.WINDOW_PARTLISTENER2_EVENTS); WindowSelectionService selectionService; IWorkbenchPage* activePage; QScopedPointer partListener; // = new WWinListener(); public: /** * Creates a new part service for a workbench window. */ WWinPartService(IWorkbenchWindow* window); /* * (non-Javadoc) * Method declared on IPartService */ void AddPartListener(IPartListener* l); /* * (non-Javadoc) * Method declared on IPartService */ void RemovePartListener(IPartListener* l); /* * (non-Javadoc) * Method declared on IPartService */ IWorkbenchPart::Pointer GetActivePart(); /* * (non-Javadoc) * Method declared on IPartService */ IWorkbenchPartReference::Pointer GetActivePartReference(); /* * Returns the selection service. */ - ISelectionService* GetSelectionService(); + ISelectionService* GetSelectionService() const; /* * Notifies that a page has been activated. */ void PageActivated(SmartPointer newPage); /* * Notifies that a page has been closed */ void PageClosed(SmartPointer page); /* * Notifies that a page has been opened. */ void PageOpened(SmartPointer page); private: void UpdateActivePart(); /* * Resets the part service. The active page, part and selection are * dereferenced. */ void Reset(); }; } #endif /* BERRYWWINPARTSERVICE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWindowManager.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWindowManager.cpp index 33f8b08ca3..998fedb4f4 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWindowManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWindowManager.cpp @@ -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. ===================================================================*/ #include "berryWindowManager.h" #include "berryWindow.h" #include namespace berry { void WindowManager::AddWindowManager(WindowManager* wm) { if (std::find(subManagers.begin(), subManagers.end(), wm) == subManagers.end()) { subManagers.push_back(wm); } } WindowManager::WindowManager() { } WindowManager::WindowManager(WindowManager* parent) { poco_assert(parent != 0); parent->AddWindowManager(this); } void WindowManager::Add(Window::Pointer window) { if (std::find(windows.begin(), windows.end(), window) == windows.end()) { windows.push_back(window); window->SetWindowManager(this); } } bool WindowManager::Close() { QList t = windows; // make iteration robust for (QList::iterator iter = t.begin(); iter != t.end(); ++iter) { bool closed = (*iter)->Close(); if (!closed) { return false; } } if (!subManagers.empty()) { for (QList::iterator iter = subManagers.begin(); iter != subManagers.end(); ++iter) { WindowManager* wm = *iter; bool closed = wm->Close(); if (!closed) { return false; } } } return true; } -std::size_t WindowManager::GetWindowCount() +std::size_t WindowManager::GetWindowCount() const { return windows.size(); } -QList WindowManager::GetWindows() +QList WindowManager::GetWindows() const { return windows; } void WindowManager::Remove(Window::Pointer window) { QList::iterator iter = std::find(windows.begin(), windows.end(), window); if (iter != windows.end()) { windows.erase(iter); window->SetWindowManager(0); } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWindowManager.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWindowManager.h index 4f6ff67c56..c56db9d446 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWindowManager.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWindowManager.h @@ -1,134 +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. ===================================================================*/ #ifndef BERRYWINDOWMANAGER_H_ #define BERRYWINDOWMANAGER_H_ #include #include #include namespace berry { class Window; /** * A manager for a group of windows. Window managers are an optional JFace * feature used in applications which create many different windows (dialogs, * wizards, etc.) in addition to a main window. A window manager can be used to * remember all the windows that an application has created (independent of * whether they are presently open or closed). There can be several window * managers, and they can be arranged into a tree. This kind of organization * makes it simple to close whole subgroupings of windows. *

* Creating a window manager is as simple as creating an instance of * WindowManager. Associating a window with a window manager is * done with WindowManager.add(Window). A window is automatically * removed from its window manager as a side effect of closing the window. *

* * @see Window */ class WindowManager { private: /** * List of windows managed by this window manager * (element type: Window). */ QList > windows; /** * List of window managers who have this window manager * as their parent (element type: WindowManager). */ QList subManagers; /** * Adds the given window manager to the list of * window managers that have this one as a parent. *

* @param wm the child window manager */ void AddWindowManager(WindowManager* wm); public: /** * Creates an empty window manager without a parent window * manager (that is, a root window manager). */ WindowManager(); /** * Creates an empty window manager with the given * window manager as parent. * * @param parent the parent window manager */ WindowManager(WindowManager* parent); /** * Adds the given window to the set of windows managed by * this window manager. Does nothing is this window is * already managed by this window manager. * * @param window the window */ void Add(SmartPointer window); /** * Attempts to close all windows managed by this window manager, * as well as windows managed by any descendent window managers. * * @return true if all windows were sucessfully closed, * and false if any window refused to close */ bool Close(); /** * Returns this window manager's number of windows * * @return the number of windows * @since 3.0 */ - std::size_t GetWindowCount(); + std::size_t GetWindowCount() const; /** * Returns this window manager's set of windows. * * @return a possibly empty list of window */ - QList > GetWindows(); + QList > GetWindows() const; /** * Removes the given window from the set of windows managed by * this window manager. Does nothing is this window is * not managed by this window manager. * * @param window the window */ void Remove(SmartPointer window); }; } #endif /* BERRYWINDOWMANAGER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp index 3abe6841e1..7822cda85d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbench.cpp @@ -1,1868 +1,1981 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "tweaklets/berryWorkbenchTweaklet.h" #include "berryWorkbench.h" #include +#include "berryPolicy.h" #include "berrySaveablesList.h" #include "berryViewRegistry.h" #include "berryEditorRegistry.h" +#include "berryEditorHistory.h" +#include "berryEditorHistoryItem.h" #include "berryServiceLocatorCreator.h" #include "berryWorkbenchPage.h" #include "berryPerspective.h" #include "berryPreferenceConstants.h" +#include "berryUIExtensionTracker.h" #include "berryWorkbenchWindow.h" #include "berryDisplay.h" #include "services/berryIServiceFactory.h" #include "util/berrySafeRunnable.h" #include "berryWorkbenchServiceRegistry.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include "berryWorkbenchMenuService.h" #include "berryEvaluationService.h" #include "berryCommandService.h" #include "berryCommandManager.h" +#include "berryMenuManager.h" #include "berryParameterType.h" +#include "berryQActionProperties.h" #include "berrySourceProviderService.h" #include "berryWorkbenchLocationService.h" +#include #include +#include #include #include #include #include #include #include #include #include #include -//#include -//#include #include namespace berry { Workbench* Workbench::instance = 0; WorkbenchTestable::Pointer Workbench::testableObject; const unsigned int Workbench::VERSION_STRING_COUNT = 1; const QString Workbench::VERSION_STRING[Workbench::VERSION_STRING_COUNT] = { "1.0" }; const QString Workbench::DEFAULT_WORKBENCH_STATE_FILENAME = "workbench.xml"; class RestoreStateRunnable: public SafeRunnable { private: Workbench* workbench; Poco::File stateFile; bool& result; public: RestoreStateRunnable(Workbench* workbench, const QString& stateFile, bool& result) : SafeRunnable( "Unable to read workbench state. Workbench UI layout will be reset."), workbench(workbench), stateFile(stateFile.toStdString()), result(result) { } void Run() { Poco::FileInputStream input(stateFile.path()); IMemento::Pointer memento = XMLMemento::CreateReadRoot(input); // Validate known version format QString version; memento->GetString(WorkbenchConstants::TAG_VERSION, version); bool valid = false; for (std::size_t i = 0; i < Workbench::VERSION_STRING_COUNT; i++) { if (Workbench::VERSION_STRING[i] == version) { valid = true; break; } } if (!valid) { input.close(); QString msg = "Invalid workbench state version. workbench.xml will be deleted"; QMessageBox::critical(NULL, "Restoring Problems", msg); stateFile.remove(); // result[0] = new Status(IStatus.ERROR, // WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); result = false; return; } // // Validate compatible version format // // We no longer support the release 1.0 format // if (VERSION_STRING[0].equals(version)) // { // reader.close(); // QString msg = "The saved user interface layout is in an " // "obsolete format and cannot be preserved. Your projects and files " // "will not be affected. Press OK to convert to the new format. Press " // "Cancel to exit with no changes."; // QList dlgLabels; // dlgLabels.push_back("Ok"); // dlgLabels.push_back("Cancel"); // IDialog::Pointer dlg = MessageDialog::CreateDialog(Shell::Pointer(0), // "Cannot Preserve Layout", 0, msg, IDialog::WARNING, dlgLabels, 0); // IDialog::ReturnCode ignoreSavedState = dlg->Open(); // // OK is the default // if (ignoreSavedState == IDialog::OK) // { // stateFile.remove(); // // result[0] = new Status(IStatus.WARNING, // // WorkbenchPlugin.PI_WORKBENCH, // // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, // // null); // result = false; // } // else // { // // result[0] = new Status(IStatus.WARNING, // // WorkbenchPlugin.PI_WORKBENCH, // // IWorkbenchConfigurer.RESTORE_CODE_EXIT, msg, // // null); // result = false; // } // return; // } // Restore the saved state //final IStatus restoreResult = restoreState(memento); /*bool restoreResult =*/ workbench->RestoreState(memento); input.close(); // if (restoreResult.getSeverity() == IStatus.ERROR) { // StartupThreading // .runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { // StatusManager.getManager().handle(restoreResult, StatusManager.LOG); // } // }); // // } } - void HandleException(const std::exception& e) + void HandleException(const ctkException& e) { //StartupThreading.runWithoutExceptions(new StartupRunnable() { //public void runWithException() { Handle(e); // QString msg = e.getMessage() == null ? "" : e.getMessage(); //$NON-NLS-1$ // result[0] = new Status(IStatus.ERROR, // WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, e); result = false; stateFile.remove(); // }}); } private: - void Handle(const std::exception& e) + void Handle(const ctkException& e) { SafeRunnable::HandleException(e); } }; + int Workbench::CreateAndRunWorkbench(Display* display, WorkbenchAdvisor* advisor) { // create the workbench instance Workbench workbench(display, advisor); // run the workbench event loop int returnCode = workbench.RunUI(); return returnCode; } Display* Workbench::CreateDisplay() { // create the display Display* newDisplay = Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateDisplay(); // workaround for 1GEZ9UR and 1GF07HN //newDisplay.setWarnings(false); // Set the priority higher than normal so as to be higher // than the JobManager. //Poco::Thread::current()->setPriority(Poco::Thread::PRIO_HIGH); //initializeImages(); return newDisplay; } Workbench::ServiceLocatorOwner::ServiceLocatorOwner(Workbench* wb) : workbench(wb) { } void Workbench::ServiceLocatorOwner::Dispose() { QMessageBox::information( NULL, "Restart needed", "A required plug-in is no longer available and the Workbench needs " "to be restarted. You will be prompted to save if there is any unsaved work."); workbench->Close(PlatformUI::RETURN_RESTART, true); } Workbench::Workbench(Display* display, WorkbenchAdvisor* advisor) : commandManager(0), progressCount(-1) , serviceLocatorOwner(new ServiceLocatorOwner(this)) , largeUpdates(0), introManager(0), isStarting(true), isClosing(false) + , activeWorkbenchWindow(nullptr) { poco_check_ptr(display) ; poco_check_ptr(advisor); // the reference count to the one and only workbench instance // is increased, so that temporary smart pointer to the workbench // do not delete it this->Register(); this->display = display; this->advisor = advisor; Workbench::instance = this; serviceLocatorCreator.reset(new ServiceLocatorCreator()); serviceLocatorCreator->Register(); this->serviceLocator = serviceLocatorCreator->CreateServiceLocator( NULL, NULL, IDisposable::WeakPtr(serviceLocatorOwner)).Cast(); serviceLocator->RegisterService(serviceLocatorCreator.data()); workbenchLocationService.reset( new WorkbenchLocationService(IServiceScopes::WORKBENCH_SCOPE, this, NULL, NULL, 0)); workbenchLocationService->Register(); serviceLocator->RegisterService(workbenchLocationService.data()); returnCode = PlatformUI::RETURN_UNSTARTABLE; } -Display* Workbench::GetDisplay() +Display* Workbench::GetDisplay() const { return display; } Workbench* Workbench::GetInstance() { return instance; } WorkbenchTestable::Pointer Workbench::GetWorkbenchTestable() { if (!testableObject) { testableObject = new WorkbenchTestable(); } return testableObject; } Workbench::~Workbench() { this->instance = 0; this->UnRegister(false); } Object* Workbench::GetService(const QString& key) { return serviceLocator->GetService(key); } bool Workbench::HasService(const QString& key) const { return serviceLocator->HasService(key); } bool Workbench::Init() { // // setup debug mode if required. // if (WorkbenchPlugin.getDefault().isDebugging()) { // WorkbenchPlugin.DEBUG = true; // ModalContext.setDebugMode(true); // } bool bail = false; // create workbench window manager //windowManager = new WindowManager(); IIntroRegistry* introRegistry = WorkbenchPlugin::GetDefault() ->GetIntroRegistry(); if (introRegistry->GetIntroCount() > 0) { //TODO Product support //IProduct product = Platform.getProduct(); //if (product != null) { introDescriptor = introRegistry ->GetIntroForProduct("").Cast(); //product.getId()); //} } // TODO Correctly order service initialization // there needs to be some serious consideration given to // the services, and hooking them up in the correct order evaluationService.reset(new EvaluationService()); evaluationService->Register(); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { serviceLocator->RegisterService(evaluationService.data()); // } // }); // Initialize the activity support. //workbenchActivitySupport = new WorkbenchActivitySupport(); //activityHelper = ActivityPersistanceHelper.getInstance(); this->InitializeDefaultServices(); // initializeFonts(); // initializeColors(); // initializeApplicationColors(); // now that the workbench is sufficiently initialized, let the advisor // have a turn. advisor->InternalBasicInitialize(this->GetWorkbenchConfigurer()); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { StartSourceProviders(); // } // }); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { // activateWorkbenchContext(); // } // }); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { // createApplicationMenu(); // } // }); // attempt to restore a previous workbench state advisor->PreStartup(); if (!advisor->OpenWindows()) { bail = true; } if (bail) return false; //forceOpenPerspective(); return true; } bool Workbench::RestoreState() { //return false; if (!GetWorkbenchConfigurer()->GetSaveAndRestore()) { // QString msg = "This application does not save and restore previously saved state."; // return new Status(IStatus.WARNING, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); return false; } // Read the workbench state file. QString stateFile = GetWorkbenchStateFile(); // If there is no state file cause one to open. if (stateFile.isEmpty() || !QFile::exists(stateFile)) { // QString msg = "No previously saved state to restore."; // return new Status(IStatus.WARNING, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); return false; } // final IStatus result[] = { new Status(IStatus.OK, // WorkbenchPlugin.PI_WORKBENCH, IStatus.OK, "", null) }; //$NON-NLS-1$ bool result = true; ISafeRunnable::Pointer runnable(new RestoreStateRunnable(this, stateFile, result)); SafeRunner::Run(runnable); // ensure at least one window was opened //if (result[0].isOK() && windowManager.getWindows().length == 0) if (result && windowManager.GetWindowCount() == 0) { QString msg = "No windows restored."; // result[0] = new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, // IWorkbenchConfigurer.RESTORE_CODE_RESET, msg, null); result &= false; } return result; } bool Workbench::RestoreState(IMemento::Pointer memento) { // final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, // IStatus.OK, WorkbenchMessages.Workbench_problemsRestoring, null); bool result = true; const bool showProgress = false; //TODO restore state progress // final boolean showProgress = PrefUtil.getAPIPreferenceStore() // .getBoolean( // IWorkbenchPreferenceConstants.SHOW_PROGRESS_ON_STARTUP); try { /* * Restored windows will be set in the createdWindows field to be * used by the openWindowsAfterRestore() method */ if (!showProgress) { DoRestoreState(memento, result); } else { // Retrieve how many plug-ins were loaded while restoring the // workbench int lastProgressCount = -1; memento->GetInteger(WorkbenchConstants::TAG_PROGRESS_COUNT, lastProgressCount); // If we don't know how many plug-ins were loaded last time, // assume we are loading half of the installed plug-ins. /*const std::size_t expectedProgressCount =*/ std::max(1, lastProgressCount == -1 ? WorkbenchPlugin::GetDefault()->GetBundleCount() / 2 : lastProgressCount); //TODO restore state progress // RunStartupWithProgress(expectedProgressCount, new Runnable() { // public void Run() { // DoRestoreState(memento, result); // } // }); } } catch (...) { OpenWindowsAfterRestore(); throw; } OpenWindowsAfterRestore(); return result; } void Workbench::DoRestoreState(IMemento::Pointer memento, bool& status) // final MultiStatus status) { IMemento::Pointer childMem; try { // UIStats.start(UIStats.RESTORE_WORKBENCH, "MRUList"); //$NON-NLS-1$ IMemento::Pointer mruMemento = memento ->GetChild(WorkbenchConstants::TAG_MRU_LIST); if (mruMemento) { // TODO restore editor history //status.add(getEditorHistory().restoreState(mruMemento)); } //UIStats.end(UIStats.RESTORE_WORKBENCH, this, "MRUList"); //$NON-NLS-1$ } catch (...) { //UIStats.end(UIStats.RESTORE_WORKBENCH, this, "MRUList"); //$NON-NLS-1$ throw; } // Restore advisor state. IMemento::Pointer advisorState = memento ->GetChild(WorkbenchConstants::TAG_WORKBENCH_ADVISOR); if (advisorState) { //status.add(getAdvisor().restoreState(advisorState)); status &= GetAdvisor()->RestoreState(advisorState); } // Get the child windows. QList children = memento ->GetChildren(WorkbenchConstants::TAG_WINDOW); createdWindows.clear(); // Read the workbench windows. for (int i = 0; i < children.size(); i++) { childMem = children[i]; WorkbenchWindow::Pointer newWindow; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { newWindow = NewWorkbenchWindow(); newWindow->Create(); // }}); createdWindows.push_back(newWindow); // allow the application to specify an initial perspective to open // @issue temporary workaround for ignoring initial perspective // String initialPerspectiveId = // getAdvisor().getInitialWindowPerspectiveId(); // if (initialPerspectiveId != null) { // IPerspectiveDescriptor desc = // getPerspectiveRegistry().findPerspectiveWithId(initialPerspectiveId); // result.merge(newWindow.restoreState(childMem, desc)); // } // add the window so that any work done in newWindow.restoreState // that relies on Workbench methods has windows to work with windowManager.Add(newWindow); // now that we've added it to the window manager we need to listen // for any exception that might hose us before we get a chance to // open it. If one occurs, remove the new window from the manager. // Assume that the new window is a phantom for now try { //status.merge(newWindow[0].restoreState(childMem, null)); status &= newWindow->RestoreState(childMem, IPerspectiveDescriptor::Pointer(0)); try { newWindow->FireWindowRestored(); } catch (const WorkbenchException& /*e*/) { //status.add(e.getStatus()); status &= false; } // everything worked so far, don't close now } catch (...) { // null the window in newWindowHolder so that it won't be // opened later on createdWindows[i] = 0; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { newWindow->Close(); // }}); } } } void Workbench::OpenWindowsAfterRestore() { if (createdWindows.empty()) { return; } // now open the windows (except the ones that were nulled because we // closed them above) for (int i = 0; i < createdWindows.size(); i++) { if (createdWindows[i]) { WorkbenchWindow::Pointer myWindow = createdWindows[i]; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { try { myWindow->Open(); } catch (...) { myWindow->Close(); throw; } // }}); } } createdWindows.clear(); } void Workbench::InitializeDefaultServices() { // final IContributionService contributionService = new ContributionService( // getAdvisor()); // serviceLocator.registerService(IContributionService.class, // contributionService); // // // TODO Correctly order service initialization // // there needs to be some serious consideration given to // // the services, and hooking them up in the correct order // // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { saveablesList.reset(new SaveablesList()); saveablesList->Register(); serviceLocator->RegisterService(saveablesList.data()); // }}); // /* * Phase 1 of the initialization of commands. When this phase completes, * all the services and managers will exist, and be accessible via the * getService(Object) method. */ // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { - // Command.DEBUG_COMMAND_EXECUTION = Policy.DEBUG_COMMANDS; + Command::DEBUG_COMMAND_EXECUTION = Policy::DEBUG_COMMANDS(); + Command::DEBUG_HANDLERS = Policy::DEBUG_HANDLERS_VERBOSE(); + Command::DEBUG_HANDLERS_COMMAND_ID = Policy::DEBUG_HANDLERS_VERBOSE_COMMAND_ID(); commandManager.reset(new CommandManager()); // }}); // // final CommandService [] commandService = new CommandService[1]; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { commandService.reset(new CommandService(commandManager.data())); commandService->Register(); commandService->ReadRegistry(); serviceLocator->RegisterService(commandService.data()); // }}); // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // ContextManager.DEBUG = Policy.DEBUG_CONTEXTS; // contextManager = new ContextManager(); // }}); // // final IContextService contextService = new ContextService( // contextManager); // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // contextService.readRegistry(); // }}); // // serviceLocator.registerService(IContextService.class, contextService); // // // final IBindingService [] bindingService = new BindingService[1]; // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // BindingManager.DEBUG = Policy.DEBUG_KEY_BINDINGS; // bindingManager = new BindingManager(contextManager, commandManager); // bindingService[0] = new BindingService( // bindingManager, commandService[0], Workbench.this); // // }}); // // bindingService[0].readRegistryAndPreferences(commandService[0]); // serviceLocator.registerService(IBindingService.class, bindingService[0]); // // final CommandImageManager commandImageManager = new CommandImageManager(); // final CommandImageService commandImageService = new CommandImageService( // commandImageManager, commandService[0]); // commandImageService.readRegistry(); // serviceLocator.registerService(ICommandImageService.class, // commandImageService); WorkbenchMenuService* wms = new WorkbenchMenuService(serviceLocator.GetPointer()); menuService.reset(wms); menuService->Register(); serviceLocator->RegisterService(menuService.data()); // the service must be registered before it is initialized - its // initialization uses the service locator to address a dependency on // the menu service //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { wms->ReadRegistry(); // }}); // the source providers are now initialized in phase 3, but source // priorities have to be set before handler initialization // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { InitializeSourcePriorities(); // } // }); /* * Phase 2 of the initialization of commands. This handles the creation * of wrappers for legacy APIs. By the time this phase completes, any * code trying to access commands through legacy APIs should work. */ //IHandlerService* handlerService = NULL; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { /*handlerService = */serviceLocator->GetService(); // } // }); // workbenchContextSupport = new WorkbenchContextSupport(this, // contextManager); // workbenchCommandSupport = new WorkbenchCommandSupport(bindingManager, // commandManager, contextManager, handlerService[0]); // initializeCommandResolver(); -// addWindowListener(windowListener); + this->AddWindowListener(this); // bindingManager.addBindingManagerListener(bindingManagerListener); // serviceLocator.registerService(ISelectionConversionService.class, // new SelectionConversionService()); } int Workbench::RunUI() { // initialize workbench and restore or open one window bool initOK = this->Init(); // let the advisor run its start up code if (initOK) { advisor->PostStartup(); // may trigger a close/restart } //TODO start eager plug-ins //startPlugins(); //addStartupRegistryListener(); isStarting = false; BERRY_INFO << "BlueBerry Workbench ready"; this->GetWorkbenchTestable()->Init(Display::GetDefault(), this); // spin event loop return display->RunEventLoop(); } -QString Workbench::GetDefaultPerspectiveId() +QString Workbench::GetDefaultPerspectiveId() const { return this->GetAdvisor()->GetInitialWindowPerspectiveId(); } -IAdaptable* Workbench::GetDefaultPageInput() +IAdaptable* Workbench::GetDefaultPageInput() const { return this->GetAdvisor()->GetDefaultPageInput(); } -QString Workbench::GetPresentationId() +QString Workbench::GetPresentationId() const { if (factoryID != "") { return factoryID; } //factoryID = PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.PRESENTATION_FACTORY_ID); // Workaround for bug 58975 - New preference mechanism does not properly // initialize defaults // Ensure that the UI plugin has started too. factoryID = WorkbenchConstants::DEFAULT_PRESENTATION_ID; return factoryID; } +IElementFactory* Workbench::GetElementFactory(const QString& factoryId) const +{ + return WorkbenchPlugin::GetDefault()->GetElementFactory(factoryId); +} + void Workbench::UpdateTheme() { WorkbenchPlugin::GetDefault()->GetPresentationFactory()->UpdateTheme(); } void Workbench::LargeUpdateStart() { if (largeUpdates++ == 0) { // TODO Consider whether these lines still need to be here. // workbenchCommandSupport.setProcessing(false); // workbenchContextSupport.setProcessing(false); QList windows = this->GetWorkbenchWindows(); for (int i = 0; i < windows.size(); i++) { IWorkbenchWindow::Pointer window = windows[i]; if (window.Cast() != 0) { window.Cast()->LargeUpdateStart(); } } } } void Workbench::LargeUpdateEnd() { if (--largeUpdates == 0) { // TODO Consider whether these lines still need to be here. // workbenchCommandSupport.setProcessing(true); // workbenchContextSupport.setProcessing(true); // Perform window-specific blocking. QList windows = this->GetWorkbenchWindows(); for (int i = 0; i < windows.size(); i++) { IWorkbenchWindow::Pointer window = windows[i]; if (window.Cast() != 0) { window.Cast()->LargeUpdateEnd(); } } } } +IExtensionTracker*Workbench::GetExtensionTracker() const +{ + if (tracker.isNull()) + { + tracker.reset(new UIExtensionTracker(this->GetDisplay())); + } + return tracker.data(); +} + void Workbench::OpenFirstTimeWindow() { try { IAdaptable* input; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { input = this->GetDefaultPageInput(); // }}); this->BusyOpenWorkbenchWindow(this->GetPerspectiveRegistry()->GetDefaultPerspective(), input); } catch (WorkbenchException& e) { // Don't use the window's shell as the dialog parent, // as the window is not open yet (bug 76724). //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { // ErrorDialog.openError(null, // WorkbenchMessages.Problems_Opening_Page, e.getMessage(), e // .getStatus()); // }}); BERRY_ERROR << "Error: Problems opening page. " << e.what() << std::endl; } } WorkbenchConfigurer::Pointer Workbench::GetWorkbenchConfigurer() { if (workbenchConfigurer.IsNull()) { workbenchConfigurer = new WorkbenchConfigurer(); } return workbenchConfigurer; } -WorkbenchAdvisor* Workbench::GetAdvisor() +WorkbenchAdvisor* Workbench::GetAdvisor() const { return advisor; } -IViewRegistry* Workbench::GetViewRegistry() +IViewRegistry* Workbench::GetViewRegistry() const { return WorkbenchPlugin::GetDefault()->GetViewRegistry(); } -IEditorRegistry* Workbench::GetEditorRegistry() +IEditorRegistry* Workbench::GetEditorRegistry() const { return WorkbenchPlugin::GetDefault()->GetEditorRegistry(); } -IPerspectiveRegistry* Workbench::GetPerspectiveRegistry() +EditorHistory* Workbench::GetEditorHistory() const +{ + if (editorHistory.isNull()) + { + editorHistory.reset(new EditorHistory()); + } + return editorHistory.data(); +} + +IPerspectiveRegistry* Workbench::GetPerspectiveRegistry() const { return WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry(); } bool Workbench::Close() { return this->Close(PlatformUI::RETURN_OK, false); } bool Workbench::Close(int returnCode, bool force) { BERRY_INFO << "Closing workbench..."; this->returnCode = returnCode; bool ret; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { ret = this->BusyClose(force); // } //}); return ret; } /** * Closes the workbench. Assumes that the busy cursor is active. * * @param force * true if the close is mandatory, and false if the close is * allowed to fail * @return true if the close succeeded, and false otherwise */ bool Workbench::BusyClose(bool force) { // notify the advisor of preShutdown and allow it to veto if not forced isClosing = advisor->PreShutdown(); if (!force && !isClosing) { return false; } // notify regular workbench clients of preShutdown and allow them to // veto if not forced isClosing = this->FirePreShutdown(force); if (!force && !isClosing) { return false; } // save any open editors if they are dirty isClosing = this->SaveAllEditors(!force); if (!force && !isClosing) { return false; } bool closeEditors = !force && false; // false is the default for the not yet implemented preference below // && PrefUtil.getAPIPreferenceStore().getBoolean( // IWorkbenchPreferenceConstants.CLOSE_EDITORS_ON_EXIT); if (closeEditors) { // SafeRunner.run(new SafeRunnable() { // public void run() { QList windows = this->GetWorkbenchWindows(); for (int i = 0; i < windows.size(); i++) { IWorkbenchPage::Pointer page = windows[i]->GetActivePage(); if (page) isClosing = isClosing && page->CloseAllEditors(false); } // } //}); if (!force && !isClosing) { return false; } } if (this->GetWorkbenchConfigurer()->GetSaveAndRestore()) { try { // SafeRunner.run(new SafeRunnable() { // public void run() { XMLMemento::Pointer mem = RecordWorkbenchState(); // Save the IMemento to a file. SaveMementoToFile(mem); // } } catch(const ctkException& e) { // public void handleException(Throwable e) { QString message; if (e.what() == 0) { message = "An error has occurred. See error log for more details. Do you want to exit?"; } else { message = QString("An error has occurred: ") + e.what() + ". See error log for more details. Do you want to exit?"; } if (QMessageBox::question(NULL, "Error", message) != QMessageBox::Yes) { isClosing = false; } } // } // }); } if (!force && !isClosing) { return false; } //SafeRunner.run(new SafeRunnable(WorkbenchMessages.ErrorClosing) { // public void run() { if (isClosing || force) { isClosing = windowManager.Close(); } // } //}); if (!force && !isClosing) { return false; } this->Shutdown(); display->ExitEventLoop(0); return true; } QString Workbench::GetWorkbenchStateFile() const { QString path = WorkbenchPlugin::GetDefault()->GetDataLocation(); if (path.isNull()) { return QString(); } return QDir::cleanPath(path + "/" + DEFAULT_WORKBENCH_STATE_FILENAME); } /* * Save the workbench UI in a persistence file. */ bool Workbench::SaveMementoToFile(XMLMemento::Pointer memento) { // Save it to a file. // XXX: nobody currently checks the return value of this method. QString stateFile = GetWorkbenchStateFile(); if (stateFile.isNull()) { return false; } //BERRY_INFO << "Saving state to: " << stateFile.path() << std::endl; try { Poco::FileOutputStream stream(stateFile.toStdString()); memento->Save(stream); } catch (const Poco::IOException& /*e*/) { QFile::remove(stateFile); QMessageBox::critical(NULL, "Saving Problems", "Unable to store workbench state."); return false; } // Success ! return true; } IWorkbenchWindow::Pointer Workbench::GetActiveWorkbenchWindow() const { // Look for the window that was last known being // the active one WorkbenchWindow::Pointer win = this->GetActivatedWindow(); return win; } -std::size_t Workbench::GetWorkbenchWindowCount() +std::size_t Workbench::GetWorkbenchWindowCount() const { return windowManager.GetWindowCount(); } -QList Workbench::GetWorkbenchWindows() +QList Workbench::GetWorkbenchWindows() const { QList windows = windowManager.GetWindows(); QList result; for (QList::iterator iter = windows.begin(); iter != windows.end(); ++iter) { result.push_back(iter->Cast()); } return result; } IWorkbenchWindow::Pointer Workbench::OpenWorkbenchWindow( const QString& perspID, IAdaptable* input) { // Run op in busy cursor. //final Object[] result = new Object[1]; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { // try { return this->BusyOpenWorkbenchWindow(perspID, input); // } catch (WorkbenchException e) { // result[0] = e; // } // } //}); } IWorkbenchWindow::Pointer Workbench::OpenWorkbenchWindow(IAdaptable* input) { return this->OpenWorkbenchWindow(this->GetPerspectiveRegistry() ->GetDefaultPerspective(), input); } IWorkbenchPage::Pointer Workbench::ShowPerspective( const QString& perspectiveId, IWorkbenchWindow::Pointer window) { // 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. WorkbenchWindow::Pointer win = window.Cast (); if (win) { IWorkbenchPage::Pointer page = win->GetActivePage(); if (page) { QList perspectives(page ->GetOpenPerspectives()); for (int i = 0; i < perspectives.size(); i++) { IPerspectiveDescriptor::Pointer persp = perspectives[i]; if (perspectiveId == persp->GetId()) { win->MakeVisible(); page->SetPerspective(persp); return page; } } } } // If another window that has the workspace root as input and the // requested // perpective open and active, then the window is given focus. IAdaptable* input = GetDefaultPageInput(); QList windows(GetWorkbenchWindows()); for (int i = 0; i < windows.size(); i++) { win = windows[i].Cast(); if (window != win) { WorkbenchPage::Pointer page = win->GetActivePage().Cast(); if (page) { bool inputSame = false; if (input == 0) { inputSame = (page->GetInput() == 0); } else { inputSame = input == page->GetInput(); } if (inputSame) { Perspective::Pointer persp = page->GetActivePerspective(); if (persp) { IPerspectiveDescriptor::Pointer desc = persp->GetDesc(); if (desc) { if (perspectiveId == desc->GetId()) { Shell::Pointer shell = win->GetShell(); shell->Open(); if (shell->GetMinimized()) { shell->SetMinimized(false); } return page; } } } } } } } // 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. win = window.Cast(); if (win) { IPreferencesService* store = WorkbenchPlugin::GetDefault()->GetPreferencesService(); int mode = store->GetSystemPreferences()->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE); IWorkbenchPage::Pointer page = win->GetActivePage(); IPerspectiveDescriptor::Pointer persp; if (page) { persp = page->GetPerspective(); } // Only open a new window if user preference is set and the window // has an active perspective. if (PreferenceConstants::OPM_NEW_WINDOW == mode && persp) { IWorkbenchWindow::Pointer newWindow = OpenWorkbenchWindow(perspectiveId, input); return newWindow->GetActivePage(); } IPerspectiveDescriptor::Pointer desc = GetPerspectiveRegistry() ->FindPerspectiveWithId(perspectiveId); if (desc == 0) { throw WorkbenchException( "Unable to create perspective \"" + perspectiveId + "\". There is no corresponding perspective extension."); } win->GetShell()->Open(); if (page == 0) { page = win->OpenPage(perspectiveId, input); } else { page->SetPerspective(desc); } return page; } // Just throw an exception.... throw WorkbenchException("Problems opening perspective \"" + perspectiveId + "\""); } IWorkbenchPage::Pointer Workbench::ShowPerspective( const QString& /*perspectiveId*/, IWorkbenchWindow::Pointer /*window*/, IAdaptable* /*input*/) { return IWorkbenchPage::Pointer(0); // // 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. // bool inputSameAsWindow = false; // WorkbenchWindow::Pointer win = window.Cast(); // if (win.IsNotNull()) { // WorkbenchPage::Pointer page = win->GetActiveWorkbenchPage(); // if (page.IsNotNull()) { // bool inputSame = false; // if (input == 0) { // inputSame = (page->GetInput() == 0); // } else { // inputSame = input.equals(page.getInput()); // } // if (inputSame) { // inputSameAsWindow = true; // IPerspectiveDescriptor perspectives[] = page // .getOpenPerspectives(); // for (int i = 0; i < perspectives.length; i++) { // IPerspectiveDescriptor persp = perspectives[i]; // if (perspectiveId.equals(persp.getId())) { // win.makeVisible(); // page.setPerspective(persp); // return page; // } // } // } // } // } // // // If another window has the requested input and the requested // // perpective open and active, then that window is given focus. // IWorkbenchWindow[] windows = getWorkbenchWindows(); // for (int i = 0; i < windows.length; i++) { // win = (WorkbenchWindow) windows[i]; // if (window != win) { // WorkbenchPage page = win.getActiveWorkbenchPage(); // if (page != null) { // boolean inputSame = false; // if (input == null) { // inputSame = (page.getInput() == null); // } else { // inputSame = input.equals(page.getInput()); // } // if (inputSame) { // Perspective persp = page.getActivePerspective(); // if (persp != null) { // IPerspectiveDescriptor desc = persp.getDesc(); // if (desc != null) { // if (perspectiveId.equals(desc.getId())) { // win.getShell().open(); // return page; // } // } // } // } // } // } // } // // // 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. // win = (WorkbenchWindow) window; // if (inputSameAsWindow && win != null) { // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // int mode = store.getInt(IPreferenceConstants.OPEN_PERSP_MODE); // // if (IPreferenceConstants.OPM_NEW_WINDOW != mode) { // IWorkbenchPage page = win.getActiveWorkbenchPage(); // IPerspectiveDescriptor desc = getPerspectiveRegistry() // .findPerspectiveWithId(perspectiveId); // if (desc == null) { // throw new WorkbenchException( // NLS // .bind( // WorkbenchMessages.WorkbenchPage_ErrorCreatingPerspective, // perspectiveId)); // } // win.getShell().open(); // if (page == null) { // page = win.openPage(perspectiveId, input); // } else { // page.setPerspective(desc); // } // return page; // } // } // // // If the specified window has no active perspective, then open the // // requested perspective and show the specified window. // if (win != null) { // IWorkbenchPage page = win.getActiveWorkbenchPage(); // IPerspectiveDescriptor persp = null; // if (page != null) { // persp = page.getPerspective(); // } // if (persp == null) { // IPerspectiveDescriptor desc = getPerspectiveRegistry() // .findPerspectiveWithId(perspectiveId); // if (desc == null) { // throw new WorkbenchException( // NLS // .bind( // WorkbenchMessages.WorkbenchPage_ErrorCreatingPerspective, // perspectiveId)); // } // win.getShell().open(); // if (page == null) { // page = win.openPage(perspectiveId, input); // } else { // page.setPerspective(desc); // } // return page; // } // } // // // Otherwise the requested perspective is opened and shown in a new // // window, and the // // window is given focus. // IWorkbenchWindow newWindow = openWorkbenchWindow(perspectiveId, input); // return newWindow.getActivePage(); } bool Workbench::SaveAllEditors(bool /*confirm*/) { return true; } -IIntroManager* Workbench::GetIntroManager() +IIntroManager* Workbench::GetIntroManager() const { return GetWorkbenchIntroManager(); } -WorkbenchIntroManager* Workbench::GetWorkbenchIntroManager() +WorkbenchIntroManager* Workbench::GetWorkbenchIntroManager() const { if (introManager.isNull()) { - introManager.reset(new WorkbenchIntroManager(this)); + introManager.reset(new WorkbenchIntroManager(const_cast(this))); } return introManager.data(); } IntroDescriptor::Pointer Workbench::GetIntroDescriptor() const { return introDescriptor; } void Workbench::SetIntroDescriptor(IntroDescriptor::Pointer descriptor) { if (GetIntroManager()->GetIntro()) { GetIntroManager()->CloseIntro(GetIntroManager()->GetIntro()); } introDescriptor = descriptor; } -bool Workbench::IsRunning() +bool Workbench::IsRunning() const { return Tweaklets::Get(WorkbenchTweaklet::KEY)->IsRunning(); } -bool Workbench::IsStarting() +bool Workbench::IsStarting() const { return isStarting; } -bool Workbench::IsClosing() +bool Workbench::IsClosing() const { return isClosing; } WorkbenchWindow::Pointer Workbench::GetActivatedWindow() const { return activatedWindow; } /* * Sets the workbench window which was last known being the active one, or * null . */ void Workbench::SetActivatedWindow(WorkbenchWindow::Pointer window) { activatedWindow = window; } WorkbenchWindow::Pointer Workbench::NewWorkbenchWindow() { WorkbenchWindow::Pointer wbw(new WorkbenchWindow(this->GetNewWindowNumber())); return wbw; } int Workbench::GetNewWindowNumber() { // Get window list. QList windows = windowManager.GetWindows(); int count = static_cast(windows.size()); // Create an array of booleans (size = window count). // Cross off every number found in the window list. bool *checkArray = new bool[count]; for (int nX = 0; nX < count; ++nX) { if (windows[nX].Cast ().IsNotNull()) { WorkbenchWindow::Pointer ww = windows[nX].Cast (); int index = ww->GetNumber() - 1; if (index >= 0 && index < count) { checkArray[index] = true; } } } // Return first index which is not used. // If no empty index was found then every slot is full. // Return next index. for (int index = 0; index < count; index++) { if (!checkArray[index]) { delete[] checkArray; return index + 1; } } delete[] checkArray; return static_cast(count + 1); } IWorkbenchWindow::Pointer Workbench::BusyOpenWorkbenchWindow( const QString& perspID, IAdaptable* input) { // Create a workbench window (becomes active window) //final WorkbenchWindow newWindowArray[] = new WorkbenchWindow[1]; //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() { // newWindowArray[0] = newWorkbenchWindow(); WorkbenchWindow::Pointer newWindow = this->NewWorkbenchWindow(); // } //}); //final WorkbenchWindow newWindow = newWindowArray[0]; //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() { newWindow->Create(); // must be created before adding to window // manager // } //}); windowManager.Add(newWindow); //final WorkbenchException [] exceptions = new WorkbenchException[1]; // Create the initial page. if (perspID != "") { //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { try { newWindow->BusyOpenPage(perspID, input); } catch (WorkbenchException& e) { windowManager.Remove(newWindow); throw e; } } // Open window after opening page, to avoid flicker. //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() { newWindow->Open(); // } //}); return newWindow; } bool Workbench::SaveState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.Workbench_problemsSaving, null); bool result = true; // Save the version number. memento->PutString(WorkbenchConstants::TAG_VERSION, VERSION_STRING[0]); // Save how many plug-ins were loaded while restoring the workbench if (progressCount != -1) { memento->PutInteger(WorkbenchConstants::TAG_PROGRESS_COUNT, progressCount); } // Save the advisor state. IMemento::Pointer advisorState = memento ->CreateChild(WorkbenchConstants::TAG_WORKBENCH_ADVISOR); //result.add(getAdvisor().saveState(advisorState)); result &= GetAdvisor()->SaveState(advisorState); // Save the workbench windows. QList windows(GetWorkbenchWindows()); for (int nX = 0; nX < windows.size(); nX++) { WorkbenchWindow::Pointer window = windows[nX].Cast(); IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_WINDOW); //result.merge(window.saveState(childMem)); result &= window->SaveState(childMem); } // result.add(getEditorHistory().saveState( // memento.createChild(IWorkbenchConstants.TAG_MRU_LIST))); return result; } XMLMemento::Pointer Workbench::RecordWorkbenchState() { XMLMemento::Pointer memento = XMLMemento ::CreateWriteRoot(WorkbenchConstants::TAG_WORKBENCH); //final IStatus status = saveState(memento); bool status = SaveState(memento); //if (status.getSeverity() != IStatus.OK) { if (!status) { // // don't use newWindow as parent because it has not yet been opened // // (bug 76724) // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { // ErrorDialog.openError(null, // WorkbenchMessages.Workbench_problemsSaving, // WorkbenchMessages.Workbench_problemsSavingMsg, status); // }}); } return memento; } void Workbench::AddWorkbenchListener(IWorkbenchListener* listener) { workbenchEvents.AddListener(listener); } void Workbench::RemoveWorkbenchListener(IWorkbenchListener* listener) { workbenchEvents.RemoveListener(listener); } IWorkbenchListener::Events& Workbench::GetWorkbenchEvents() { return workbenchEvents; } void Workbench::AddWindowListener(IWindowListener* l) { windowEvents.AddListener(l); } void Workbench::RemoveWindowListener(IWindowListener* l) { windowEvents.RemoveListener(l); } IWindowListener::Events& Workbench::GetWindowEvents() { return windowEvents; } bool Workbench::FirePreShutdown(bool forced) { //SafeRunnable.run(new SafeRunnable() { // public void run() { typedef IWorkbenchListener::Events::PreShutdownEvent::ListenerList ListenerList; const ListenerList& listeners = workbenchEvents.preShutdown.GetListeners(); for ( ListenerList::const_iterator iter = listeners.begin(); iter != listeners.end(); ++iter ) { // notify each listener if (! (*iter)->Execute(dynamic_cast(this), forced)) return false; } // } return true; } /** * Fire workbench postShutdown event. * * @since 3.2 */ void Workbench::FirePostShutdown() { // SafeRunnable.run(new SafeRunnable() { // public void run() { workbenchEvents.postShutdown(this); // } } void Workbench::FireWindowOpened(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowOpened(window); // } } void Workbench::FireWindowClosed(IWorkbenchWindow::Pointer window) { if (activatedWindow == window) { // Do not hang onto it so it can be GC'ed activatedWindow = 0; } // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowClosed(window); // } } void Workbench::FireWindowActivated(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowActivated(window); // } } void Workbench::FireWindowDeactivated(IWorkbenchWindow::Pointer window) { // SafeRunner.run(new SafeRunnable() { // public void run() { windowEvents.windowDeactivated(window); // } } IWorkbenchWindow::Pointer Workbench::RestoreWorkbenchWindow(IMemento::Pointer memento) { WorkbenchWindow::Pointer newWindow = this->NewWorkbenchWindow(); //newWindow.create(); windowManager.Add(newWindow); // whether the window was opened bool opened = false; try { newWindow->RestoreState(memento, IPerspectiveDescriptor::Pointer(0)); newWindow->FireWindowRestored(); newWindow->Open(); opened = true; } catch (...) { if (!opened) { newWindow->Close(); } } return newWindow; } void Workbench::Shutdown() { // shutdown application-specific portions first advisor->PostShutdown(); // notify regular workbench clients of shutdown, and clear the list when // done this->FirePostShutdown(); //workbenchListeners.clear(); //cancelEarlyStartup(); // for dynamic UI // Platform.getExtensionRegistry().removeRegistryChangeListener( // extensionEventHandler); // Platform.getExtensionRegistry().removeRegistryChangeListener( // startupRegistryListener); // ((GrabFocus) Tweaklets.get(GrabFocus.KEY)).dispose(); // Bring down all of the services. serviceLocator->Dispose(); // workbenchActivitySupport.dispose(); // WorkbenchHelpSystem.disposeIfNecessary(); // shutdown the rest of the workbench // WorkbenchColors.shutdown(); // activityHelper.shutdown(); // uninitializeImages(); // if (WorkbenchPlugin.getDefault() != null) { // WorkbenchPlugin.getDefault().reset(); // } // WorkbenchThemeManager.getInstance().dispose(); // PropertyPageContributorManager.getManager().dispose(); // ObjectActionContributorManager.getManager().dispose(); // if (tracker != null) { // tracker.close(); // } Tweaklets::Clear(); } void Workbench::InitializeSourcePriorities() { WorkbenchServiceRegistry::GetRegistry()->InitializeSourcePriorities(); } void Workbench::StartSourceProviders() { /* * Phase 3 of the initialization of commands. The source providers that * the workbench provides are creating and registered with the above * services. These source providers notify the services when particular * pieces of workbench state change. */ IEvaluationService* const evaluationService = serviceLocator->GetService(); //IContextService* const contextService = serviceLocator->GetService(); SourceProviderService* sps = new SourceProviderService(serviceLocator.GetPointer()); sourceProviderService.reset(sps); sourceProviderService->Register(); serviceLocator->RegisterService(sourceProviderService.data()); struct SafeSourceProviderRunnable : public ISafeRunnable { SafeSourceProviderRunnable(SourceProviderService* sps, IEvaluationService* es) : sps(sps), es(es) {} void Run() { // this currently instantiates all players ... sigh sps->ReadRegistry(); QList sp = sps->GetSourceProviders(); for (int i = 0; i < sp.size(); i++) { es->AddSourceProvider(sp[i]); //if (!(sp[i] instanceof ActiveContextSourceProvider)) //{ // contextService.addSourceProvider(sp[i]); //} } } - void HandleException(const std::exception& exception) + void HandleException(const ctkException& exception) { - WorkbenchPlugin::Log("Failed to initialize a source provider", ctkException(QString(exception.what()))); + WorkbenchPlugin::Log("Failed to initialize a source provider", exception); } private: SourceProviderService* sps; IEvaluationService* es; }; ISafeRunnable::Pointer sourceProviderRunnable( new SafeSourceProviderRunnable(sps, evaluationService)); SafeRunner::Run(sourceProviderRunnable); // SafeRunner.run(new ISafeRunnable() { // public void run() throws Exception { // // these guys are need to provide the variables they say // // they source // actionSetSourceProvider = (ActionSetSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_ACTION_SETS_NAME); // FocusControlSourceProvider focusControl = (FocusControlSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_FOCUS_CONTROL_ID_NAME); // serviceLocator.registerService(IFocusService.class, focusControl); // menuSourceProvider = (MenuSourceProvider) sourceProviderService // .getSourceProvider(ISources.ACTIVE_MENU_NAME); // } // public void handleException(Throwable exception) { // WorkbenchPlugin.log("Failed to initialize a source provider", exception); //$NON-NLS-1$ // } // }); } +void Workbench::UpdateActiveWorkbenchWindowMenuManager(bool textOnly) +{ + if (activeWorkbenchWindow != nullptr) + { +// if (actionSetSourceProvider != null) +// { +// activeWorkbenchWindow->RemoveActionSetsListener(actionSetSourceProvider); +// } + activeWorkbenchWindow = nullptr; + } + //bool actionSetsUpdated = false; + + IWorkbenchWindow::Pointer workbenchWindow = GetActiveWorkbenchWindow(); + + if (WorkbenchWindow::Pointer wbWnd = workbenchWindow.Cast()) + { + activeWorkbenchWindow = wbWnd.GetPointer(); + if (activeWorkbenchWindow->IsClosing()) + { + return; + } + + // Update the action sets. +// Shell::Pointer windowShell = activeWorkbenchWindow->GetShell(); +// Shell::Pointer activeShell = GetDisplay()->GetActiveShell(); +// IContextService* service = GetService(); +// if ((Util.equals(windowShell, activeShell) || service.getShellType(activeShell) == IContextService.TYPE_WINDOW) +// && actionSetSourceProvider != null) +// { +// activeWorkbenchWindow->AddActionSetsListener(actionSetSourceProvider); +// final WorkbenchPage page = activeWorkbenchWindow.getActiveWorkbenchPage(); +// final IActionSetDescriptor[] newActionSets; +// if (page != null) +// { +// newActionSets = page.getActionSets(); +// final ActionSetsEvent event = new ActionSetsEvent(newActionSets); +// actionSetSourceProvider.actionSetsChanged(event); +// actionSetsUpdated = true; +// } +// } + + MenuManager* menuManager = activeWorkbenchWindow->GetMenuManager(); + + if (textOnly) + { + menuManager->Update(QActionProperties::TEXT); + } + else + { + menuManager->Update(true); + } + } + +// if (!actionSetsUpdated && actionSetSourceProvider != null) +// { +// ActionSetsEvent event = new ActionSetsEvent(null); +// actionSetSourceProvider.actionSetsChanged(event); + // } +} + +void Workbench::WindowActivated(const IWorkbenchWindow::Pointer&) +{ + this->UpdateActiveWorkbenchWindowMenuManager(true); +} + +void Workbench::WindowDeactivated(const IWorkbenchWindow::Pointer&) +{ + this->UpdateActiveWorkbenchWindowMenuManager(true); +} + +void Workbench::WindowClosed(const IWorkbenchWindow::Pointer&) +{ + this->UpdateActiveWorkbenchWindowMenuManager(true); +} + +void Workbench::WindowOpened(const IWorkbenchWindow::Pointer&) +{ + this->UpdateActiveWorkbenchWindowMenuManager(true); +} + } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbench.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbench.h index 9464cb456f..8fe5493b3c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbench.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbench.h @@ -1,635 +1,653 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYWORKBENCH_H_ #define BERRYWORKBENCH_H_ #include "berryIViewPart.h" #include "berryIWorkbench.h" #include "berryWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "berryIWorkbenchPartReference.h" #include "berryXMLMemento.h" #include "berryPartPane.h" #include "berryEditorAreaHelper.h" #include "berryWindowManager.h" #include "berryWorkbenchConfigurer.h" #include "application/berryWorkbenchAdvisor.h" #include "berryWorkbenchTestable.h" #include "intro/berryIntroDescriptor.h" #include "intro/berryWorkbenchIntroManager.h" #include "berryILayoutContainer.h" #include "berryServiceLocator.h" #include #include namespace berry { struct ICommandService; struct IEvaluationService; struct IMenuService; struct IServiceLocatorCreator; struct ISaveablesLifecycleListener; struct ISourceProviderService; struct IWorkbenchLocationService; class CommandManager; +class EditorHistory; class ViewRegistry; class EditorRegistry; class WorkbenchWindowConfigurer; /** * \ingroup org_blueberry_ui_qt * * The workbench class represents the top of the BlueBerry user interface. Its * primary responsibility is the management of workbench windows, dialogs, * wizards, and other workbench-related windows. *

* Note that any code that is run during the creation of a workbench instance * should not required access to the display. */ -class BERRY_UI_QT Workbench : public IWorkbench +class BERRY_UI_QT Workbench : public IWorkbench, private IWindowListener { public: berryObjectMacro(Workbench) friend class RestoreStateRunnable; /** * Creates the workbench and associates it with the the given display and * workbench advisor, and runs the workbench UI. This entails processing and * dispatching events until the workbench is closed or restarted. *

* This method is intended to be called by PlatformUI. Fails * if the workbench UI has already been created. *

*

* The display passed in must be the default display. *

* * @param display * the display to be used for all UI interactions with the * workbench * @param advisor * the application-specific advisor that configures and * specializes the workbench * @return return code {@link PlatformUI#RETURN_OK RETURN_OK}for normal * exit; {@link PlatformUI#RETURN_RESTART RETURN_RESTART}if the * workbench was terminated with a call to * {@link IWorkbench#restart IWorkbench.restart}; other values * reserved for future use */ static int CreateAndRunWorkbench(Display* display, WorkbenchAdvisor* advisor); /** * Creates the Display to be used by the workbench. * * @return the display */ static Display* CreateDisplay(); /** * Returns the one and only instance of the workbench, if there is one. * * @return the workbench, or null if the workbench has not * been created, or has been created and already completed */ static Workbench* GetInstance(); virtual ~Workbench(); /* * (non-Javadoc) * * @see org.blueberry.ui.services.IServiceLocator#getService(java.lang.Object) */ Object* GetService(const QString& key); /* * (non-Javadoc) * * @see org.blueberry.ui.services.IServiceLocator#hasService(java.lang.Object) */ bool HasService(const QString& key) const; /* * Method declared on IWorkbench. */ bool Close(); /** * Returns the testable object facade, for use by the test harness. * * @return the testable object facade * @since 3.0 */ static WorkbenchTestable::Pointer GetWorkbenchTestable(); /* * Method declared on IWorkbench. */ void AddWorkbenchListener(IWorkbenchListener* listener); /* * Method declared on IWorkbench. */ void RemoveWorkbenchListener(IWorkbenchListener* listener); /* * Method declared on IWorkbench. */ IWorkbenchListener::Events& GetWorkbenchEvents(); /* * Method declared on IWorkbench. */ void AddWindowListener(IWindowListener* l); /* * Method declared on IWorkbench. */ void RemoveWindowListener(IWindowListener* l); /* * Method declared on IWorkbench. */ IWindowListener::Events& GetWindowEvents(); IWorkbenchWindow::Pointer GetActiveWorkbenchWindow() const; - IViewRegistry* GetViewRegistry(); - IEditorRegistry* GetEditorRegistry(); - IPerspectiveRegistry* GetPerspectiveRegistry(); + IViewRegistry* GetViewRegistry() const; + IEditorRegistry* GetEditorRegistry() const; + EditorHistory* GetEditorHistory() const; + IPerspectiveRegistry* GetPerspectiveRegistry() const; - std::size_t GetWorkbenchWindowCount(); - QList GetWorkbenchWindows(); + std::size_t GetWorkbenchWindowCount() const; + QList GetWorkbenchWindows() const; IWorkbenchWindow::Pointer OpenWorkbenchWindow(const QString& perspectiveId, IAdaptable* input); IWorkbenchWindow::Pointer OpenWorkbenchWindow(IAdaptable* input); IWorkbenchPage::Pointer ShowPerspective(const QString& perspectiveId, IWorkbenchWindow::Pointer window); IWorkbenchPage::Pointer ShowPerspective(const QString& perspectiveId, IWorkbenchWindow::Pointer window, IAdaptable* input); bool SaveAllEditors(bool confirm); - IIntroManager* GetIntroManager(); + IIntroManager* GetIntroManager() const; /** * @return the workbench intro manager */ - WorkbenchIntroManager* GetWorkbenchIntroManager(); + WorkbenchIntroManager* GetWorkbenchIntroManager() const; /** * @return the intro extension for this workbench. */ IntroDescriptor::Pointer GetIntroDescriptor() const; /** * This method exists as a test hook. This method should NEVER * be called by clients. * * @param descriptor * The intro descriptor to use. */ void SetIntroDescriptor(IntroDescriptor::Pointer descriptor); /** * Returns true if the workbench is running, * false if it has been terminated. * * @return true if the workbench is running, * false if it has been terminated. */ - bool IsRunning(); + bool IsRunning() const; /** * Returns true if the Workbench is in the process of starting. * * @return true if the Workbench is starting, but not yet * running the event loop. */ - bool IsStarting(); + bool IsStarting() const; - bool IsClosing(); + bool IsClosing() const; /** * Returns the default perspective id, which may be null. * * @return the default perspective id, or null */ - QString GetDefaultPerspectiveId(); + QString GetDefaultPerspectiveId() const; /** * Returns the default workbench window page input. * * @return the default window page input or null if none */ - IAdaptable* GetDefaultPageInput(); + IAdaptable* GetDefaultPageInput() const; /** * Return the presentation ID specified by the preference or the default ID * if undefined. * * @return the presentation ID * @see IWorkbenchPreferenceConstants#PRESENTATION_FACTORY_ID */ - QString GetPresentationId(); + QString GetPresentationId() const; + + IElementFactory* GetElementFactory(const QString& factoryId) const; void UpdateTheme(); /** *

* Indicates the start of a large update within the workbench. This is used * to disable CPU-intensive, change-sensitive services that were temporarily * disabled in the midst of large changes. This method should always be * called in tandem with largeUpdateEnd, and the event loop * should not be allowed to spin before that method is called. *

*

* Important: always use with largeUpdateEnd! *

*/ void LargeUpdateStart(); /** *

* Indicates the end of a large update within the workbench. This is used to * re-enable services that were temporarily disabled in the midst of large * changes. This method should always be called in tandem with * largeUpdateStart, and the event loop should not be * allowed to spin before this method is called. *

*

* Important: always protect this call by using finally! *

*/ void LargeUpdateEnd(); + IExtensionTracker* GetExtensionTracker() const; protected: friend class PlatformUI; friend class WorkbenchConfigurer; friend class WorkbenchWindowConfigurer; friend class WorkbenchWindow; friend struct WorkbenchWindow::ShellEventFilter; int RunUI(); void OpenFirstTimeWindow(); IWorkbenchWindow::Pointer RestoreWorkbenchWindow(IMemento::Pointer memento); bool Init(); /* * Restores the workbench UI from the workbench state file (workbench.xml). * * @return a status object indicating OK if a window was opened, * RESTORE_CODE_RESET if no window was opened but one should be, and * RESTORE_CODE_EXIT if the workbench should close immediately */ /* package */ bool RestoreState(); /** * Closes the workbench, returning the given return code from the run * method. If forced, the workbench is closed no matter what. * * @param returnCode * {@link PlatformUI#RETURN_OK RETURN_OK}for normal exit; * {@link PlatformUI#RETURN_RESTART RETURN_RESTART}if the * workbench was terminated with a call to * {@link IWorkbench#restart IWorkbench.restart}; * {@link PlatformUI#RETURN_EMERGENCY_CLOSE} for an emergency * shutdown * {@link PlatformUI#RETURN_UNSTARTABLE RETURN_UNSTARTABLE}if * the workbench could not be started; other values reserved for * future use * * @param force * true to force the workbench close, and false for a "soft" * close that can be canceled * @return true if the close was successful, and false if the close was * canceled */ /* package */ bool Close(int returnCode, bool force); /** * Returns the unique object that applications use to configure the * workbench. *

* IMPORTANT This method is declared protected to prevent regular * plug-ins from downcasting IWorkbench to Workbench and getting hold of the * workbench configurer that would allow them to tamper with the workbench. * The workbench configurer is available only to the application. *

*/ WorkbenchConfigurer::Pointer GetWorkbenchConfigurer(); /** * Returns the workbench advisor that created this workbench. *

* IMPORTANT This method is declared protected to prevent regular * plug-ins from downcasting IWorkbench to Workbench and getting hold of the * workbench advisor that would allow them to tamper with the workbench. The * workbench advisor is internal to the application. *

*/ - WorkbenchAdvisor* GetAdvisor(); + WorkbenchAdvisor* GetAdvisor() const; /* * Returns the workbench window which was last known being the active one, * or null . */ SmartPointer GetActivatedWindow() const; /* * Sets the workbench window which was last known being the active one, or * null . */ void SetActivatedWindow(SmartPointer window); /** * Fire workbench preShutdown event, stopping at the first one to veto * * @param forced * flag indicating whether the shutdown is being forced * @return true to allow the workbench to proceed with * shutdown, false to veto a non-forced shutdown * @since 3.2 */ bool FirePreShutdown(bool forced); /** * Fire workbench postShutdown event. * * @since 3.2 */ void FirePostShutdown(); /** * Fire window opened event. * * @param window * The window which just opened; should not be null. */ void FireWindowOpened(IWorkbenchWindow::Pointer window); /** * Fire window closed event. * * @param window * The window which just closed; should not be null. */ void FireWindowClosed(IWorkbenchWindow::Pointer window); /** * Fire window activated event. * * @param window * The window which was just activated; should not be * null. */ void FireWindowActivated(IWorkbenchWindow::Pointer window); /** * Fire window deactivated event. * * @param window * The window which was just deactivated; should not be * null. */ void FireWindowDeactivated(IWorkbenchWindow::Pointer window); private: /** * Holds onto the only instance of Workbench. */ static Workbench* instance; /** * The testable object facade. */ static WorkbenchTestable::Pointer testableObject; static const unsigned int VERSION_STRING_COUNT; // = 1; static const QString VERSION_STRING[1]; static const QString DEFAULT_WORKBENCH_STATE_FILENAME; // = "workbench.xml"; IWorkbenchListener::Events workbenchEvents; IWindowListener::Events windowEvents; WorkbenchAdvisor* advisor; WorkbenchConfigurer::Pointer workbenchConfigurer; /** * The service locator maintained by the workbench. These services are * initialized during workbench during the init method. */ ServiceLocator::Pointer serviceLocator; QScopedPointer evaluationService; QScopedPointer saveablesList; /** * The single instance of the command manager used by the workbench. This is * initialized in Workbench.init(Display) and then never * changed. This value will only be null if the * initialization call has not yet completed. */ QScopedPointer commandManager; QScopedPointer commandService; QScopedPointer menuService; + mutable QScopedPointer tracker; + /** * A count of how many plug-ins were loaded while restoring the workbench * state. Initially -1 for unknown number. */ int progressCount; /** * A field to hold the workbench windows that have been restored. In the * event that not all windows have been restored, this field allows the * openWindowsAfterRestore method to open some windows. */ QList createdWindows; struct ServiceLocatorOwner : public IDisposable { ServiceLocatorOwner(Workbench* workbench); void Dispose(); private: Workbench* workbench; }; friend struct ServiceLocatorOwner; IDisposable::Pointer serviceLocatorOwner; QScopedPointer serviceLocatorCreator; QScopedPointer workbenchLocationService; QScopedPointer sourceProviderService; /** * A count of how many large updates are going on. This tracks nesting of * requests to disable services during a large update -- similar to the * setRedraw functionality on Control. When * this value becomes greater than zero, services are disabled. When this * value becomes zero, services are enabled. Please see * largeUpdateStart() and largeUpdateEnd(). */ int largeUpdates; /** * The display used for all UI interactions with this workbench. */ Display* display; WindowManager windowManager; SmartPointer activatedWindow; - QScopedPointer introManager; + mutable QScopedPointer editorHistory; + + mutable QScopedPointer introManager; /** * The descriptor for the intro extension that is valid for this workspace, * null if none. */ IntroDescriptor::Pointer introDescriptor; bool isStarting; bool isClosing; int returnCode; - QString factoryID; + mutable QString factoryID; + + WorkbenchWindow* activeWorkbenchWindow; /** * Creates a new workbench. * * @param display * the display to be used for all UI interactions with the * workbench * @param advisor * the application-specific advisor that configures and * specializes this workbench instance */ Workbench(Display*, WorkbenchAdvisor* advisor); /** * see IWorkbench#GetDisplay */ - Display* GetDisplay(); + Display* GetDisplay() const; /* * Creates a new workbench window. * * @return the new workbench window */ SmartPointer NewWorkbenchWindow(); void OpenWindowsAfterRestore(); /* * Returns the number for a new window. This will be the first number > 0 * which is not used to identify another window in the workbench. */ int GetNewWindowNumber(); /** * Initializes all of the default services for the workbench. For * initializing the command-based services, this also parses the registry * and hooks up all the required listeners. */ void InitializeDefaultServices(); /** * Closes the workbench. Assumes that the busy cursor is active. * * @param force * true if the close is mandatory, and false if the close is * allowed to fail * @return true if the close succeeded, and false otherwise */ bool BusyClose(bool force); /* * Record the workbench UI in a document */ XMLMemento::Pointer RecordWorkbenchState(); /* * Restores the state of the previously saved workbench */ bool RestoreState(IMemento::Pointer memento); void DoRestoreState(IMemento::Pointer memento, bool& result); /* * Saves the current state of the workbench so it can be restored later on */ bool SaveState(IMemento::Pointer memento); /* * Save the workbench UI in a persistence file. */ bool SaveMementoToFile(XMLMemento::Pointer memento); /* * Answer the workbench state file. */ QString GetWorkbenchStateFile() const; /* * Shuts down the application. */ void Shutdown(); /** * Opens a new workbench window and page with a specific perspective. * * Assumes that busy cursor is active. */ IWorkbenchWindow::Pointer BusyOpenWorkbenchWindow(const QString& perspID, IAdaptable* input); void InitializeSourcePriorities(); void StartSourceProviders(); + + void UpdateActiveWorkbenchWindowMenuManager(bool textOnly); + + void WindowActivated(const IWorkbenchWindow::Pointer& /*window*/) override; + void WindowDeactivated(const IWorkbenchWindow::Pointer& /*window*/) override; + void WindowClosed(const IWorkbenchWindow::Pointer& /*window*/) override; + void WindowOpened(const IWorkbenchWindow::Pointer& /*window*/) override; }; } // namespace berry #endif /*BERRYWORKBENCH_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchMenuService.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchMenuService.cpp index 72b34854b3..1abfe6544c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchMenuService.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchMenuService.cpp @@ -1,1071 +1,1071 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryWorkbenchMenuService.h" #include #include #include #include #include #include #include -#include #include #include #include +#include "berryAbstractGroupMarker.h" #include "berryAbstractMenuAdditionCacheEntry.h" #include "berryAlwaysEnabledExpression.h" #include "berryContributionItem.h" #include "berryContributionRoot.h" #include "berryMenuManager.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchWindow.h" #if (QT_VERSION >= QT_VERSION_CHECK(5,0,0)) #include #endif namespace berry { const QString WorkbenchMenuService::INDEX_AFTER_ADDITIONS_QK = "after"; const QString WorkbenchMenuService::INDEX_AFTER_ADDITIONS_QV = "additions"; const QString WorkbenchMenuService::PROP_VISIBLE = "visible"; /** * A combined property and activity listener that updates the visibility of * contribution items in the new menu system. */ class ContributionItemUpdater : public IPropertyChangeListener //, public IIdentifierListener { private: const IContributionItem::Pointer item; //IIdentifier identifier; bool lastExpressionResult; WorkbenchMenuService* wms; void UpdateVisibility() { //bool visible = identifier.IsNotNull() ? (identifier->IsEnabled() && lastExpressionResult) // : lastExpressionResult; bool visible = lastExpressionResult; item->SetVisible(visible); IContributionManager* parent = 0; if (ContributionItem::Pointer ci = item.Cast()) { parent = ci->GetParent(); } else if (MenuManager::Pointer mm = item.Cast()) { parent = mm->GetParent(); } if (parent != 0) { parent->MarkDirty(); wms->managersAwaitingUpdates.insert(parent); } } public: ContributionItemUpdater(WorkbenchMenuService* wms, const IContributionItem::Pointer& item) //, IIdentifier identifier) : item(item), lastExpressionResult(true), wms(wms) { // if (identifier.IsNotNull()) // { // this->identifier = identifier; // this->identifier->AddIdentifierListener(this); // UpdateVisibility(); // force initial visibility to fall in line // // with activity enablement // } } /** * Dispose of this updater */ ~ContributionItemUpdater() { // if (identifier.IsNotNull()) // identifier->RemoveIdentifierListener(this); } using IPropertyChangeListener::PropertyChange; /* * @see IPropertyChangeListener#PropertyChange(PropertyChangeEvent) */ void PropertyChange(const PropertyChangeEvent::Pointer& event) { if (event->GetProperty() == WorkbenchMenuService::PROP_VISIBLE) { if (event->GetNewValue().IsNotNull()) { lastExpressionResult = event->GetNewValue(); } else { lastExpressionResult = false; } UpdateVisibility(); } } /* * @see IIdentifierListener#IdentifierChanged(IdentifierEvent) */ // void identifierChanged(IdentifierEvent identifierEvent) // { // UpdateVisibility(); // } }; WorkbenchMenuService::ManagerPopulationRecord::ManagerPopulationRecord() : wms(0), serviceLocatorToUse(0), recurse(false) { } WorkbenchMenuService::ManagerPopulationRecord:: ManagerPopulationRecord(WorkbenchMenuService* wms, IServiceLocator* serviceLocatorToUse, const QSet >& restriction, const QString& uri, bool recurse) : wms(wms), serviceLocatorToUse(serviceLocatorToUse), restriction(restriction), uri(uri), recurse(recurse) { } void WorkbenchMenuService::ManagerPopulationRecord:: AddFactoryContribution(const SmartPointer& factory, const SmartPointer& ciList) { // Remove any existing cache info for this factory RemoveFactoryContribution(factory); // save the new info factoryToItems.insert(factory, ciList); } void WorkbenchMenuService::ManagerPopulationRecord:: RemoveFactoryContribution(const SmartPointer& factory) { ContributionRoot::Pointer items = factoryToItems.take(factory); if (items.IsNotNull()) { wms->ReleaseContributions(items.GetPointer()); } } SmartPointer WorkbenchMenuService::ManagerPopulationRecord:: GetContributions(const SmartPointer& factory) const { if (factoryToItems.contains(factory)) return factoryToItems[factory]; return ContributionRoot::Pointer(0); } void WorkbenchMenuService::ManagerPopulationRecord:: ReleaseContributions() { foreach (ContributionRoot::Pointer items, factoryToItems.values()) { wms->ReleaseContributions(items.GetPointer()); } factoryToItems.clear(); } WorkbenchMenuService::WorkbenchMenuService(IServiceLocator* serviceLocator) : evaluationService(0), serviceLocator(serviceLocator) { //this.menuPersistence = new MenuPersistence(this); evaluationService = serviceLocator->GetService(); evaluationService->AddServiceListener(GetServiceListener()); // IWorkbenchLocationService wls = (IWorkbenchLocationService) serviceLocator // .getService(IWorkbenchLocationService.class); // wls.getWorkbench() // .getActivitySupport().getActivityManager() // .addActivityManagerListener(getActivityManagerListener()); // final IExtensionRegistry registry = Platform.getExtensionRegistry(); // registryChangeListener = new IRegistryChangeListener() { // public void registryChanged(final IRegistryChangeEvent event) { // final Display display = PlatformUI.getWorkbench().getDisplay(); // if (display.isDisposed()) { // return; // } // display.syncExec(new Runnable() { // public void run() { // handleRegistryChanges(event); // } // }); // } // }; // registry.addRegistryChangeListener(registryChangeListener); } WorkbenchMenuService::~WorkbenchMenuService() { this->Dispose(); } void WorkbenchMenuService::Dispose() { //menuPersistence.dispose(); // if (registryChangeListener != null) // { // final IExtensionRegistry registry = Platform.getExtensionRegistry(); // registry.removeRegistryChangeListener(registryChangeListener); // registryChangeListener = null; // } foreach (IEvaluationReference::Pointer ref, evaluationsByItem.values()) { evaluationService->RemoveEvaluationListener(ref); } evaluationsByItem.clear(); managersAwaitingUpdates.clear(); evaluationService->RemoveServiceListener(GetServiceListener()); // if (activityManagerListener != null) // { // IWorkbenchLocationService wls = (IWorkbenchLocationService) serviceLocator // .getService(IWorkbenchLocationService.class); // IWorkbench workbench = wls.getWorkbench(); // if (workbench != null) // { // workbench.getActivitySupport().getActivityManager() // .removeActivityManagerListener(activityManagerListener); // } // } } void WorkbenchMenuService::AddSourceProvider(const SmartPointer& /*provider*/) { // no-op } void WorkbenchMenuService::ReadRegistry() { //menuPersistence.read(); } void WorkbenchMenuService::RemoveSourceProvider(const SmartPointer& /*provider*/) { // no-op } void WorkbenchMenuService::UpdateManagers() { QList managers = managersAwaitingUpdates.toList(); managersAwaitingUpdates.clear(); foreach (IContributionManager* mgr, managers) { mgr->Update(true); // if (ToolBarManager* tbMgr = dynamic_cast(mgr)) // { // if (!UpdateToolBar(tbMgr)) // { // //UpdateTrim((ToolBarManager) mgr); // } // } // else if (MenuManager* mMgr = dynamic_cast(mgr)) { IContributionManager* parent = mMgr->GetParent(); if (parent != 0) { parent->Update(true); } } } } WorkbenchMenuService::FactoryListType WorkbenchMenuService::GetAdditionsForURI(const QUrl& uri) { if (uri.isEmpty()) return FactoryListType(); return uriToFactories[GetIdFromURI(uri)]; } void WorkbenchMenuService::AddContributionFactory(const SmartPointer& factory) { if (factory.IsNull() || factory->GetLocation().isNull()) return; QUrl uri(factory->GetLocation()); QString factoryId = GetIdFromURI(uri); FactoryListType& factories = uriToFactories[factoryId]; { // MenuAdditionCacheEntry::Pointer mace = factory.Cast(); // if (mace && mace->HasAdditions()) // { // factories.push_front(factory); // } // else { factories.push_back(factory); } } // OK, now update any managers that use this uri FactoryListType factoryList; factoryList.push_back(factory); foreach (IContributionManager* mgr, GetManagersFor(factoryId)) { const ManagerPopulationRecord& mpr = populatedManagers[mgr]; AddContributionsToManager(mpr.serviceLocatorToUse, mpr.restriction, dynamic_cast(mgr), mpr.uri, mpr.recurse, factoryList); mgr->Update(true); } } void WorkbenchMenuService::RemoveContributionFactory(const SmartPointer& factory) { if (factory.IsNull() || factory->GetLocation().isNull()) return; QUrl uri(factory->GetLocation()); QString factoryId = GetIdFromURI(uri); if (uriToFactories.contains(factoryId)) { FactoryListType& factories = uriToFactories[factoryId]; // // Before we remove the top-level cache we recursively // // remove any sub-caches created by this one // if (MenuAdditionCacheEntry::Pointer mace = factory.Cast()) // { // QList subCaches = mace->GetSubCaches(); // foreach (AbstractMenuAdditionCacheEntry::Pointer amace, subCaches) // { // RemoveContributionFactory(amace); // } // } factories.removeAll(factory); } // OK, now update any managers that use this uri FactoryListType factoryList; factoryList.push_back(factory); foreach (IContributionManager* mgr, GetManagersFor(factoryId)) { RemoveContributionsForFactory(mgr, factory); mgr->Update(true); } } void WorkbenchMenuService::PopulateContributionManager(ContributionManager* mgr, const QString& uri) { PopulateContributionManager(serviceLocator, QSet >(), mgr, uri, true); } void WorkbenchMenuService::PopulateContributionManager(IServiceLocator* serviceLocatorToUse, const QSet >& restriction, ContributionManager* mgr, const QString& uri, bool recurse) { // Track this attempt to populate the menu, remembering all the parameters if (!populatedManagers.contains(mgr)) { populatedManagers.insert(mgr, ManagerPopulationRecord(this, serviceLocatorToUse, restriction, uri, recurse)); } QUrl contributionLocation(uri); FactoryListType factories = GetAdditionsForURI(contributionLocation); AddContributionsToManager(serviceLocatorToUse, restriction, mgr, uri, recurse, factories); } void WorkbenchMenuService::AddContributionsToManager(IServiceLocator* serviceLocatorToUse, const QSet >& restriction, ContributionManager* mgr, const QString& uri, bool recurse, const QList >& factories) { QUrl contributionLocation(uri); QList retryList; QSet itemsAdded; foreach (AbstractContributionFactory::Pointer cache, factories) { if (!ProcessAdditions(serviceLocatorToUse, restriction, mgr, cache, itemsAdded)) { retryList.push_back(cache); } } // OK, iteratively loop through entries whose URI's could not // be resolved until we either run out of entries or the list // doesn't change size (indicating that the remaining entries // can never be resolved). bool done = retryList.isEmpty(); while (!done) { // Clone the retry list and clear it QList curRetry = retryList; int retryCount = retryList.size(); retryList.clear(); // Walk the current list seeing if any entries can now be resolved foreach (AbstractContributionFactory::Pointer cache, curRetry) { if (!ProcessAdditions(serviceLocatorToUse, restriction, mgr, cache, itemsAdded)) { retryList.push_back(cache); } } // We're done if the retryList is now empty (everything done) or // if the list hasn't changed at all (no hope) done = retryList.isEmpty() || (retryList.size() == retryCount); } // Now, recurse through any sub-menus foreach (IContributionItem::Pointer curItem, mgr->GetItems()) { if (ContributionManager::Pointer cm = curItem.Cast()) { QString id = curItem->GetId(); if (!id.isEmpty() && (recurse || itemsAdded.contains(id))) { PopulateContributionManager(serviceLocatorToUse, restriction, cm.GetPointer(), contributionLocation.scheme() + ":" + id, true); } } // else if (IToolBarContributionItem::Pointer tbci = curItem.Cast()) // { // if (!(tbci->GetId().isEmpty()) && (recurse || itemsAdded.contains(tbci->GetId()))) // { // PopulateContributionManager(serviceLocatorToUse, // restriction, dynamic_cast(tbci->GetToolBarManager()), // contributionLocation.scheme() + ":" + tbci->GetId(), true); // } // } } } SmartPointer WorkbenchMenuService::GetCurrentState() const { return evaluationService->GetCurrentState(); } void WorkbenchMenuService::RegisterVisibleWhen(const SmartPointer& item, const SmartPointer& visibleWhen, QSet >& /*restriction*/, const QString& /*identifierID*/) { if (item.IsNull()) { throw std::invalid_argument("item cannot be null"); } if (visibleWhen.IsNull()) { throw std::invalid_argument("visibleWhen expression cannot be null"); } if (evaluationsByItem.contains(item)) { QString id = item->GetId(); WorkbenchPlugin::Log(QString("item is already registered: ") + (id.isEmpty() ? QString("no id") : id)); return; } // TODO activity support // IIdentifier identifier = null; // if (identifierID != null) { // identifier = PlatformUI.getWorkbench().getActivitySupport() // .getActivityManager().getIdentifier(identifierID); // } // ContributionItemUpdater* listener = // new ContributionItemUpdater(item, identifier); // if (visibleWhen != AlwaysEnabledExpression::INSTANCE) // { // IEvaluationReference::Pointer ref = evaluationService->AddEvaluationListener( // visibleWhen, listener, PROP_VISIBLE); // restriction.insert(ref); // evaluationsByItem.insert(item, ref); // } // activityListenersByItem.put(item, listener); } void WorkbenchMenuService::UnregisterVisibleWhen(const SmartPointer& item, QSet >& restriction) { // TODO activity support // ContributionItemUpdater identifierListener = (ContributionItemUpdater) activityListenersByItem // .remove(item); // if (identifierListener != null) { // identifierListener.dispose(); // } IEvaluationReference::Pointer ref = evaluationsByItem.take(item); if (ref.IsNull()) { return; } evaluationService->RemoveEvaluationListener(ref); restriction.remove(ref); } void WorkbenchMenuService::ReleaseContributions(ContributionManager* mgr) { if (mgr == 0) return; // Recursively remove any contributions from sub-menus foreach (IContributionItem::Pointer item, mgr->GetItems()) { if (ContributionManager::Pointer cm = item.Cast()) { ReleaseContributions(cm.GetPointer()); } // else if (IToolBarContributionItem::Pointer tbci = item.Cast()) // { // ReleaseContributions(tbci->GetToolBarManager()); // } } // Now remove any cached information if (populatedManagers.contains(mgr)) { populatedManagers[mgr].ReleaseContributions(); populatedManagers.remove(mgr); } managersAwaitingUpdates.remove(mgr); } //void WorkbenchMenuService::HandleDynamicAdditions(const QList >& menuAdditions) //{ // for (Iterator additionsIter = menuAdditions.iterator(); additionsIter.hasNext();) { // AbstractContributionFactory newFactory = null; // final IConfigurationElement menuAddition = (IConfigurationElement) additionsIter.next(); // if (isProgramaticContribution(menuAddition)) // newFactory = new ProxyMenuAdditionCacheEntry( // menuAddition // .getAttribute(IWorkbenchRegistryConstants.TAG_LOCATION_URI), // menuAddition.getNamespaceIdentifier(), menuAddition); // else // newFactory = new MenuAdditionCacheEntry( // this, // menuAddition, // menuAddition // .getAttribute(IWorkbenchRegistryConstants.TAG_LOCATION_URI), // menuAddition.getNamespaceIdentifier()); // if (newFactory != null) // addContributionFactory(newFactory); // } //} //void WorkbenchMenuService::HandleDynamicRemovals(const QList >& menuRemovals) //{ // for (Iterator additionsIter = menuRemovals.iterator(); additionsIter.hasNext();) { // IConfigurationElement ceToRemove = (IConfigurationElement) additionsIter.next(); // AbstractMenuAdditionCacheEntry factoryToRemove = findFactory(ceToRemove); // removeContributionFactory(factoryToRemove); // } //} //void WorkbenchMenuService::HandleRegistryChanges(const SmartPointer& event) //{ // // HACK!! determine if this is an addition or deletion from the first delta // IExtensionDelta[] deltas = event.getExtensionDeltas(); // if (deltas.length == 0) // return; // boolean isAddition = deltas[0].getKind() == IExtensionDelta.ADDED; // // access all the necessary service persistence handlers // HandlerService handlerSvc = (HandlerService) serviceLocator.getService(IHandlerService.class); // HandlerPersistence handlerPersistence = handlerSvc.getHandlerPersistence(); // CommandService cmdSvc = (CommandService) serviceLocator.getService(ICommandService.class); // CommandPersistence cmdPersistence = cmdSvc.getCommandPersistence(); // BindingService bindingSvc = (BindingService) serviceLocator.getService(IBindingService.class); // BindingPersistence bindingPersistence = bindingSvc.getBindingPersistence(); // boolean needsUpdate = false; // // determine order from the type of delta // if (isAddition) { // // additions order: Commands, Handlers, Bindings, Menus // if (cmdPersistence.commandsNeedUpdating(event)) { // cmdPersistence.reRead(); // needsUpdate = true; // } // if (handlerPersistence.handlersNeedUpdating(event)) { // handlerPersistence.reRead(); // needsUpdate = true; // } // if (bindingPersistence.bindingsNeedUpdating(event)) { // bindingPersistence.reRead(); // needsUpdate = true; // } // if (menuPersistence.menusNeedUpdating(event)) { // handleMenuChanges(event); // needsUpdate = true; // } // } // else { // // Removal order: Menus, Bindings, Handlers, Commands // if (menuPersistence.menusNeedUpdating(event)) { // handleMenuChanges(event); // needsUpdate = true; // } // if (bindingPersistence.bindingsNeedUpdating(event)) { // bindingPersistence.reRead(); // needsUpdate = true; // } // if (handlerPersistence.handlersNeedUpdating(event)) { // final IExtensionDelta[] handlerDeltas = event.getExtensionDeltas( // PlatformUI.PLUGIN_ID, IWorkbenchRegistryConstants.PL_HANDLERS); // for (int i = 0; i < handlerDeltas.length; i++) { // IConfigurationElement[] ices = handlerDeltas[i].getExtension().getConfigurationElements(); // HandlerProxy.updateStaleCEs(ices); // } // handlerPersistence.reRead(); // needsUpdate = true; // } // if (cmdPersistence.commandsNeedUpdating(event)) { // cmdPersistence.reRead(); // needsUpdate = true; // } // } // if (needsUpdate) { // ContributionManager[] managers = (ContributionManager[]) populatedManagers // .keySet().toArray( // new ContributionManager[populatedManagers.keySet() // .size()]); // for (int i = 0; i < managers.length; i++) { // ContributionManager mgr = managers[i]; // mgr.update(false); // } // } //} //MenuPersistence* WorkbenchMenuService::GetMenuPersistence() //{ // return menuPersistence; //} void WorkbenchMenuService::PopulateContributionManager(ContributionManager* mgr, const QString& uri, bool recurse) { PopulateContributionManager(serviceLocator, QSet(), mgr, uri, recurse); } void WorkbenchMenuService::RemoveContributionsForFactory(IContributionManager* manager, const SmartPointer& factory) { populatedManagers[manager].RemoveFactoryContribution(factory); // automatically cleans its caches } void WorkbenchMenuService::ReleaseContributions(ContributionRoot* items) { ContributionManager* mgr = items->GetManager(); foreach(IContributionItem::Pointer item, items->GetItems()) { ReleaseItem(item, items->restriction); mgr->Remove(item); } ReleaseCache(items); } void WorkbenchMenuService::PropertyChange(const PropertyChangeEvent::Pointer& event) { if (event->GetProperty() == IEvaluationService::PROP_NOTIFYING) { if (!(event->GetNewValue().Cast()->GetValue())) { // if it's false, the evaluation service has // finished with its latest round of updates this->UpdateManagers(); } } } //SmartPointer WorkbenchMenuService::GetActivityManagerListener() //{ // if (activityManagerListener == null) { // activityManagerListener = new IActivityManagerListener() { // public void activityManagerChanged( // ActivityManagerEvent activityManagerEvent) { // if (activityManagerEvent.haveEnabledActivityIdsChanged()) { // updateManagers(); // called after all identifiers have // // been update - now update the // // managers // } // } // }; // } // return activityManagerListener; //} IPropertyChangeListener* WorkbenchMenuService::GetServiceListener() { return this; } //void WorkbenchMenuService::UpdateTrim(ToolBarManager* mgr) //{ // Control control = mgr.getControl(); // if (control == null || control.isDisposed()) { // return; // } // LayoutUtil.resize(control); //} bool WorkbenchMenuService::UpdateToolBar(ToolBarManager* /*mgr*/) { // QList windows = PlatformUI::GetWorkbench()->GetWorkbenchWindows(); // QList::iterator wend = windows.end(); // for (QList::iterator i = windows.begin(); i != wend; ++i) // { // WorkbenchWindow::Pointer window = i->Cast(); // IToolBarManager* tb = window->GetToolBarManager(); // if (tb != 0) // { // foreach (IContributionItem::Pointer item, tb->GetItems()) // { // if (ToolBarContributionItem::Pointer tbci = item.Cast()) // { // IToolBarManager* tbm = tbci->GetToolBarManager(); // if (mgr == tbm) // { // tb->Update(true); // return true; // } // } // } // } // } return false; } QString WorkbenchMenuService::GetIdFromURI(const QUrl& uri) { return uri.scheme() + ":" + uri.path(); } QList WorkbenchMenuService::GetManagersFor(const QString& factoryId) { QList mgrs; QHashIterator mgrIter(populatedManagers); while(mgrIter.hasNext()) { if (factoryId == mgrIter.value().uri) { mgrs.push_back(mgrIter.key()); } } return mgrs; } bool WorkbenchMenuService::ProcessAdditions(IServiceLocator* serviceLocatorToUse, const QSet >& restriction, ContributionManager* mgr, const AbstractContributionFactory::Pointer& cache, QSet& itemsAdded) { if (!ProcessFactory(mgr, cache)) return true; const int idx = GetInsertionIndex(mgr, cache->GetLocation()); if (idx == -1) return false; // can't process (yet) struct _SafeRunnable : public ISafeRunnable { WorkbenchMenuService* wms; int insertionIndex; IServiceLocator* serviceLocatorToUse; QSet > restriction; ContributionManager* mgr; AbstractContributionFactory::Pointer cache; QSet& itemsAdded; _SafeRunnable(WorkbenchMenuService* wms, int idx, IServiceLocator* serviceLocatorToUse, const QSet >& restriction, ContributionManager* mgr, AbstractContributionFactory::Pointer cache, QSet& itemsAdded) : wms(wms), insertionIndex(idx), serviceLocatorToUse(serviceLocatorToUse), restriction(restriction), mgr(mgr), cache(cache), itemsAdded(itemsAdded) {} - void HandleException(const std::exception&) + void HandleException(const ctkException&) {} void Run() { // Get the additions ContributionRoot::Pointer ciList(new ContributionRoot(wms, restriction, mgr, cache.GetPointer())); cache->CreateContributionItems(serviceLocatorToUse, ciList); // If we have any then add them at the correct location if (!ciList->GetItems().isEmpty()) { // Cache the items for future cleanup ManagerPopulationRecord& mpr = wms->populatedManagers[mgr]; ContributionRoot::Pointer contributions = mpr.GetContributions(cache); if (contributions.IsNotNull()) { // Existing contributions in the mgr will be released. // Adjust the insertionIndex foreach (IContributionItem::Pointer item, contributions->GetItems()) { if (item == mgr->Find(item->GetId())) insertionIndex--; } } mpr.AddFactoryContribution(cache, ciList); foreach (IContributionItem::Pointer ici, ciList->GetItems()) { if ((ici.Cast() || //ici.Cast || ici.Cast()) && !(ici->GetId().isEmpty())) { IContributionItem::Pointer foundIci = mgr->Find(ici->GetId()); // really, this is a very specific scenario that // allows merging but, if it is a contribution manager that also // contains items, then we would be throwing stuff away. if (ContributionManager::Pointer cm = foundIci.Cast()) { if (cm->GetSize() > 0) { // IStatus status = new Status( // IStatus.WARNING, // WorkbenchPlugin.PI_WORKBENCH, // "Menu contribution id collision: " // + ici.getId()); // StatusManager.getManager().handle(status); BERRY_WARN << "Menu contribution id collision: " << ici->GetId().toStdString(); } continue; } // else if (IToolBarContributionItem::Pointer tbci = foundIci.Cast()) // { // IToolBarManager* toolBarManager = tbci->GetToolBarManager(); // if (ContributionManager::Pointer tbcm = dynamic_cast(toolBarManager) // && tbcm->GetSize() > 0) // { //// IStatus status = new Status( //// IStatus.WARNING, //// WorkbenchPlugin.PI_WORKBENCH, //// "Toolbar contribution id collision: " //$NON-NLS-1$ //// + ici.getId()); //// StatusManager.getManager().handle(status); // BERRY_WARN << "Toolbar contribution id collision: " << ici->GetId().toStdString(); // } // continue; // } else if (foundIci.Cast()) { continue; } } const int oldSize = mgr->GetSize(); mgr->Insert(insertionIndex, ici); if (!ici->GetId().isEmpty()) { itemsAdded.insert(ici->GetId()); } if (mgr->GetSize() > oldSize) insertionIndex++; } } } }; ISafeRunnable::Pointer run (new _SafeRunnable(this, idx, serviceLocatorToUse, restriction, mgr, cache, itemsAdded)); SafeRunner::Run(run); return true; } bool WorkbenchMenuService::ProcessFactory(ContributionManager* mgr, const AbstractContributionFactory::Pointer& factory) { QUrl uri(factory->GetLocation()); if (MenuUtil::ANY_POPUP == (uri.scheme() + ':' + uri.path())) { // its any popup. check whether manager has additions if (mgr->IndexOf(WorkbenchActionConstants::MB_ADDITIONS) == -1) { // // menu has no additions. Add only if allPopups = true // if (MenuAdditionCacheEntry::Pointer menuEntry = factory.Cast()) // { // return menuEntry->ContributeToAllPopups(); // } } } return true; } void WorkbenchMenuService::ReleaseCache(ContributionRoot* items) { items->Release(); } int WorkbenchMenuService::GetInsertionIndex(ContributionManager* mgr, const QString& location) { QUrl uri(location); #if (QT_VERSION < QT_VERSION_CHECK(5,0,0)) QList > queryParts = uri.queryItems(); bool indexAfterAdditions = uri.queryItemValue(INDEX_AFTER_ADDITIONS_QK) == INDEX_AFTER_ADDITIONS_QV; #else QUrlQuery query(uri); QList > queryParts = query.queryItems(); bool indexAfterAdditions = query.queryItemValue(INDEX_AFTER_ADDITIONS_QK) == INDEX_AFTER_ADDITIONS_QV; #endif int additionsIndex = -1; // No Query means 'after=additions' (if there) or // the end of the menu if (queryParts.isEmpty() || indexAfterAdditions) { additionsIndex = mgr->IndexOf(WorkbenchActionConstants::MB_ADDITIONS); if (additionsIndex == -1) additionsIndex = mgr->GetItems().size(); else ++additionsIndex; } else { // Should be in the form "[before|after|endof]=id" if (queryParts.size() > 0 && !(queryParts[0].second.isEmpty())) { QString modifier = queryParts[0].first; QString id = queryParts[0].second; additionsIndex = mgr->IndexOf(id); if (additionsIndex != -1) { if (MenuUtil::QUERY_BEFORE == modifier) { // this is OK, the additionsIndex will either be correct // or -1 (which is a no-op) } else if (MenuUtil::QUERY_AFTER == modifier) { additionsIndex++; } else if (MenuUtil::QUERY_ENDOF == modifier) { // OK, this one is exciting QList items = mgr->GetItems(); for (additionsIndex++; additionsIndex < items.size(); additionsIndex++) { if (items[additionsIndex]->IsGroupMarker()) { break; } } } } } } return additionsIndex; } void WorkbenchMenuService::ReleaseItem(const SmartPointer& item, QSet >& restriction) { UnregisterVisibleWhen(item, restriction); if (ContributionManager::Pointer cm = item.Cast()) { ReleaseContributions(cm.GetPointer()); } // else if (IToolBarContributionItem::Pointer tbci = item.Cast()) // { // ReleaseContributions(dynamic_cast(tbci->GetToolBarManager())); // } } bool WorkbenchMenuService::IsProgramaticContribution(const SmartPointer& menuAddition) const { return !menuAddition->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS).isEmpty(); } SmartPointer WorkbenchMenuService::FindFactory(const SmartPointer& ceToRemove) { QUrl uri = ceToRemove->GetAttribute(WorkbenchRegistryConstants::TAG_LOCATION_URI); FactoryListType factories = GetAdditionsForURI(uri); foreach (AbstractContributionFactory::Pointer factory, GetAdditionsForURI(uri)) { if (AbstractMenuAdditionCacheEntry::Pointer mace = factory.Cast()) { if (mace->GetConfigElement() == ceToRemove) return mace; } } return AbstractMenuAdditionCacheEntry::Pointer(0); } //void WorkbenchMenuService::HandleMenuChanges(const SmartPointer& event) //{ // final IExtensionDelta[] menuDeltas = event.getExtensionDeltas( // PlatformUI.PLUGIN_ID, IWorkbenchRegistryConstants.PL_MENUS); // final List menuAdditions = new ArrayList(); // final List menuRemovals = new ArrayList(); // for (int i = 0; i < menuDeltas.length; i++) { // IConfigurationElement[] ices = menuDeltas[i].getExtension().getConfigurationElements(); // for (int j = 0; j < ices.length; j++) { // if (IWorkbenchRegistryConstants.PL_MENU_CONTRIBUTION.equals(ices[j].getName())) { // if (menuDeltas[i].getKind() == IExtensionDelta.ADDED) // menuAdditions.add(ices[j]); // else // menuRemovals.add(ices[j]); // } // } // } // // Handle additions // if (menuAdditions.size() > 0) { // handleDynamicAdditions(menuAdditions); // } // // Handle Removals // if (menuRemovals.size() > 0) { // handleDynamicRemovals(menuRemovals); // } //} } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp index 04988c47c6..9bf6cc5193 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.cpp @@ -1,4104 +1,4104 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "tweaklets/berryGuiWidgetsTweaklet.h" #include "tweaklets/berryWorkbenchPageTweaklet.h" #include "berryWorkbenchPage.h" #include "berryPartSite.h" #include "berryWorkbenchRegistryConstants.h" #include "berryPerspective.h" #include "berryLayoutPartSash.h" #include "berryWorkbenchPlugin.h" #include "berryEditorAreaHelper.h" #include "berrySaveablesList.h" #include "berryPerspectiveHelper.h" #include "berryLayoutTreeNode.h" #include "berryWorkbench.h" #include "berryWorkbenchConstants.h" #include "berryPartService.h" #include "berryStickyViewManager.h" +#include "berryUIExtensionTracker.h" #include "intro/berryIntroConstants.h" #include "intro/berryViewIntroAdapterPart.h" #include "berryWorkbenchWindow.h" #include "berryUIException.h" #include "berryPlatformUI.h" #include "berryPartPane.h" #include #include namespace berry { WorkbenchPage::ActivationOrderPred::ActivationOrderPred( WorkbenchPage::ActivationList* al) : activationList(al) { } bool WorkbenchPage::ActivationOrderPred::operator()( const IViewReference::Pointer o1, const IViewReference::Pointer o2) const { WorkbenchPage::ActivationList::PartListIter pos1 = activationList->IndexOf( o1.Cast ()); WorkbenchPage::ActivationList::PartListIter pos2 = activationList->IndexOf( o2.Cast ()); return pos1 < pos2; } void WorkbenchPage::PerspectiveList::UpdateActionSets( Perspective::Pointer /*oldPersp*/, Perspective::Pointer /*newPersp*/) { //TODO WorkbenchPage action sets // // Update action sets // // IContextService service = (IContextService) window // .getService(IContextService.class); // try { // service.activateContext(ContextAuthority.DEFER_EVENTS); // if (newPersp != 0) { // IActionSetDescriptor[] newAlwaysOn = newPersp // .getAlwaysOnActionSets(); // for (int i = 0; i < newAlwaysOn.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOn[i]; // // actionSets.showAction(descriptor); // } // // IActionSetDescriptor[] newAlwaysOff = newPersp // .getAlwaysOffActionSets(); // for (int i = 0; i < newAlwaysOff.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOff[i]; // // actionSets.maskAction(descriptor); // } // } // // if (oldPersp != 0) { // IActionSetDescriptor[] newAlwaysOn = oldPersp // .getAlwaysOnActionSets(); // for (int i = 0; i < newAlwaysOn.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOn[i]; // // actionSets.hideAction(descriptor); // } // // IActionSetDescriptor[] newAlwaysOff = oldPersp // .getAlwaysOffActionSets(); // for (int i = 0; i < newAlwaysOff.length; i++) { // IActionSetDescriptor descriptor = newAlwaysOff[i]; // // actionSets.unmaskAction(descriptor); // } // } // } finally { // service.activateContext(ContextAuthority.SEND_EVENTS); // } } WorkbenchPage::PerspectiveList::PerspectiveList() { } void WorkbenchPage::PerspectiveList::Reorder( IPerspectiveDescriptor::Pointer perspective, int newLoc) { PerspectiveListType::iterator oldLocation = openedList.end(); Perspective::Pointer movedPerspective; for (PerspectiveListType::iterator iterator = openedList.begin(); iterator != openedList.end(); ++iterator) { Perspective::Pointer openPerspective = *iterator; if (openPerspective->GetDesc() == perspective) { oldLocation = std::find(openedList.begin(), openedList.end(), openPerspective); movedPerspective = openPerspective; } } PerspectiveListType::iterator newLocation = openedList.begin(); for (int i = 0; i < newLoc; ++i, ++newLocation) ; if (oldLocation == newLocation) { return; } openedList.erase(oldLocation); openedList.insert(newLocation, movedPerspective); } WorkbenchPage::PerspectiveList::PerspectiveListType WorkbenchPage::PerspectiveList::GetSortedPerspectives() { return usedList; } bool WorkbenchPage::PerspectiveList::Add(Perspective::Pointer perspective) { openedList.push_back(perspective); usedList.push_front(perspective); //It will be moved to top only when activated. return true; } WorkbenchPage::PerspectiveList::PerspectiveListType::iterator WorkbenchPage::PerspectiveList::Begin() { return openedList.begin(); } WorkbenchPage::PerspectiveList::PerspectiveListType::iterator WorkbenchPage::PerspectiveList::End() { return openedList.end(); } WorkbenchPage::PerspectiveList::PerspectiveListType WorkbenchPage::PerspectiveList::GetOpenedPerspectives() { return openedList; } bool WorkbenchPage::PerspectiveList::Remove(Perspective::Pointer perspective) { if (active == perspective) { this->UpdateActionSets(active, Perspective::Pointer(0)); active = 0; } usedList.removeAll(perspective); PerspectiveListType::size_type origSize = openedList.size(); openedList.removeAll(perspective); return openedList.size() != origSize; } void WorkbenchPage::PerspectiveList::Swap(Perspective::Pointer oldPerspective, Perspective::Pointer newPerspective) { PerspectiveListType::iterator oldIter = std::find(openedList.begin(), openedList.end(), oldPerspective); PerspectiveListType::iterator newIter = std::find(openedList.begin(), openedList.end(), newPerspective); if (oldIter == openedList.end() || newIter == openedList.end()) { return; } std::iter_swap(oldIter, newIter); } bool WorkbenchPage::PerspectiveList::IsEmpty() { return openedList.empty(); } Perspective::Pointer WorkbenchPage::PerspectiveList::GetActive() { return active; } Perspective::Pointer WorkbenchPage::PerspectiveList::GetNextActive() { if (active == 0) { if (usedList.empty()) { return Perspective::Pointer(0); } else { return usedList.back(); } } else { if (usedList.size() < 2) { return Perspective::Pointer(0); } else { - return *(--usedList.end()); + return *(usedList.end() - 2); } } } WorkbenchPage::PerspectiveList::PerspectiveListType::size_type WorkbenchPage::PerspectiveList::Size() { return openedList.size(); } void WorkbenchPage::PerspectiveList::SetActive(Perspective::Pointer perspective) { if (perspective == active) { return; } this->UpdateActionSets(active, perspective); active = perspective; if (perspective != 0) { usedList.removeAll(perspective); usedList.push_back(perspective); } } WorkbenchPage::ActivationList::ActivationList(WorkbenchPage* page) : page(page) { } void WorkbenchPage::ActivationList::SetActive(SmartPointer part) { if (parts.empty()) { return; } IWorkbenchPartReference::Pointer ref(page->GetReference(part)); if (ref) { if (ref == parts.back()) { return; } parts.erase(std::find(parts.begin(), parts.end(), ref)); parts.push_back(ref); } } void WorkbenchPage::ActivationList::BringToTop(SmartPointer< IWorkbenchPartReference> ref) { ILayoutContainer::Pointer targetContainer(page->GetContainer(ref)); PartListIter newIndex = this->LastIndexOfContainer(targetContainer); if (newIndex != parts.end() && ref == *newIndex) { return; } if (newIndex == parts.end()) { parts.push_back(ref); } else { PartListType::size_type index = newIndex - parts.begin(); parts.erase(std::find(parts.begin(), parts.end(), ref)); PartListIter insertIndex = parts.begin() + index; parts.insert(insertIndex, ref); } } WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::LastIndexOfContainer( SmartPointer container) { PartListReverseIter i = parts.rbegin(); while (i != parts.rend()) { IWorkbenchPartReference::Pointer ref(*i); ILayoutContainer::Pointer cnt(page->GetContainer(ref)); if (cnt == container) { return --i.base(); } ++i; } return parts.end(); } void WorkbenchPage::ActivationList::SetActive(SmartPointer< IWorkbenchPartReference> ref) { this->SetActive(ref->GetPart(true)); } void WorkbenchPage::ActivationList::Add( SmartPointer ref) { if (std::find(parts.begin(), parts.end(), ref) != parts.end()) { return; } ref->GetPart(false); parts.push_front(ref); } SmartPointer WorkbenchPage::ActivationList::GetActive() { if (parts.empty()) { return IWorkbenchPart::Pointer(0); } return this->GetActive(parts.end()); } SmartPointer WorkbenchPage::ActivationList::GetPreviouslyActive() { if (parts.size() < 2) { return IWorkbenchPart::Pointer(0); } return this->GetActive(--parts.end()); } SmartPointer WorkbenchPage::ActivationList::GetActiveReference( bool editorsOnly) { return this->GetActiveReference(parts.end(), editorsOnly); } WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::IndexOf( SmartPointer part) { IWorkbenchPartReference::Pointer ref(page->GetReference(part)); if (ref == 0) { return parts.end(); } return std::find(parts.begin(), parts.end(), ref); } WorkbenchPage::ActivationList::PartListIter WorkbenchPage::ActivationList::IndexOf( SmartPointer ref) { return std::find(parts.begin(), parts.end(), ref); } bool WorkbenchPage::ActivationList::Remove( SmartPointer ref) { bool contains = std::find(parts.begin(), parts.end(), ref) != parts.end(); parts.erase(std::find(parts.begin(), parts.end(), ref)); return contains; } SmartPointer WorkbenchPage::ActivationList::GetTopEditor() { IEditorReference::Pointer editor = this->GetActiveReference(parts.end(), true).Cast (); if (editor == 0) { return IEditorPart::Pointer(0); } return editor->GetEditor(true); } SmartPointer WorkbenchPage::ActivationList::GetActive( PartListIter start) { IWorkbenchPartReference::Pointer ref(this->GetActiveReference(start, false)); if (!ref) { return IWorkbenchPart::Pointer(0); } return ref->GetPart(true); } SmartPointer WorkbenchPage::ActivationList::GetActiveReference( PartListIter start, bool editorsOnly) { // First look for parts that aren't obscured by the current zoom state IWorkbenchPartReference::Pointer nonObscured = this->GetActiveReference( start, editorsOnly, true); if (nonObscured) { return nonObscured; } // Now try all the rest of the parts return this->GetActiveReference(start, editorsOnly, false); } SmartPointer WorkbenchPage::ActivationList::GetActiveReference( PartListIter start, bool editorsOnly, bool /*skipPartsObscuredByZoom*/) { QList views = page->GetViewReferences(); PartListReverseIter i(start); while (i != parts.rend()) { WorkbenchPartReference::Pointer ref(i->Cast ()); if (editorsOnly && (ref.Cast () == 0)) { ++i; continue; } // Skip parts whose containers have disabled auto-focus PartPane::Pointer pane(ref->GetPane()); if (pane) { if (!pane->AllowsAutoFocus()) { ++i; continue; } // if (skipPartsObscuredByZoom) { // if (pane.isObscuredByZoom()) { // continue; // } // } } // Skip fastviews (unless overridden) if (IViewReference::Pointer viewRef = ref.Cast()) { //if (ref == getActiveFastView() || !((IViewReference) ref).isFastView()) { for (int j = 0; j < views.size(); j++) { if (views[j] == viewRef) { return viewRef.Cast (); } } //} } else { return ref.Cast (); } ++i; } return IWorkbenchPartReference::Pointer(0); } QList > WorkbenchPage::ActivationList::GetEditors() { QList editors; for (PartListIter i = parts.begin(); i != parts.end(); ++i) { if (IEditorReference::Pointer part = i->Cast()) { editors.push_back(part); } } return editors; } QList > WorkbenchPage::ActivationList::GetParts() { QList views(page->GetViewReferences()); QList resultList; for (PartListIter iterator = parts.begin(); iterator != parts.end(); ++iterator) { if (IViewReference::Pointer ref = iterator->Cast()) { //Filter views from other perspectives for (int i = 0; i < views.size(); i++) { if (ref == views[i]) { resultList.push_back(ref); break; } } } else { resultList.push_back(*iterator); } } return resultList; } +WorkbenchPage::ActionSwitcher::ActionSwitcher(WorkbenchPage* page) + : page(page) +{ +} + void WorkbenchPage::ActionSwitcher::UpdateActivePart( IWorkbenchPart::Pointer newPart) { IWorkbenchPart::Pointer _activePart = this->activePart.Lock(); IEditorPart::Pointer _topEditor = this->topEditor.Lock(); if (_activePart == newPart) { return; } bool isNewPartAnEditor = newPart.Cast ().IsNotNull(); if (isNewPartAnEditor) { QString oldId; if (_topEditor) { oldId = _topEditor->GetSite()->GetId(); } QString newId = newPart->GetSite()->GetId(); // if the active part is an editor and the new editor // is the same kind of editor, then we don't have to do // anything if (activePart == topEditor && newId == oldId) { activePart = newPart; topEditor = newPart.Cast (); return; } // remove the contributions of the old editor // if it is a different kind of editor if (oldId != newId) { this->DeactivateContributions(_topEditor, true); } // if a view was the active part, disable its contributions if (_activePart && _activePart != _topEditor) { this->DeactivateContributions(_activePart, true); } // show (and enable) the contributions of the new editor // if it is a different kind of editor or if the // old active part was a view if (newId != oldId || _activePart != _topEditor) { this->ActivateContributions(newPart, true); } } else if (newPart.IsNull()) { if (_activePart) { // remove all contributions this->DeactivateContributions(_activePart, true); } } else { // new part is a view // if old active part is a view, remove all contributions, // but if old part is an editor only disable if (_activePart) { this->DeactivateContributions(_activePart, _activePart.Cast ().IsNotNull()); } this->ActivateContributions(newPart, true); } //TODO WorkbenchPage action sets // ArrayList newActionSets = 0; // if (isNewPartAnEditor || (activePart == topEditor && newPart == 0)) // { // newActionSets = calculateActionSets(newPart, 0); // } // else // { // newActionSets = calculateActionSets(newPart, topEditor); // } // // if (!updateActionSets(newActionSets)) // { - // updateActionBars(); + page->UpdateActionBars(); // } if (isNewPartAnEditor) { topEditor = newPart.Cast (); } else if (activePart == topEditor && newPart.IsNull()) { // since we removed all the contributions, we clear the top // editor topEditor.Reset(); } activePart = newPart; } void WorkbenchPage::ActionSwitcher::UpdateTopEditor( IEditorPart::Pointer newEditor) { if (topEditor.Lock() == newEditor) { return; } if (activePart == topEditor) { this->UpdateActivePart(newEditor); return; } QString oldId; if (!topEditor.Expired()) { oldId = topEditor.Lock()->GetSite()->GetId(); } QString newId; if (newEditor.IsNotNull()) { newId = newEditor->GetSite()->GetId(); } if (oldId == newId) { // we don't have to change anything topEditor = newEditor; return; } // Remove the contributions of the old editor if (!topEditor.Expired()) { this->DeactivateContributions(topEditor.Lock(), true); } // Show (disabled) the contributions of the new editor if (newEditor.IsNotNull()) { this->ActivateContributions(newEditor, false); } // ArrayList newActionSets = calculateActionSets(activePart, newEditor); // if (!updateActionSets(newActionSets)) // { - // updateActionBars(); + page->UpdateActionBars(); // } topEditor = newEditor; } void WorkbenchPage::ActionSwitcher::ActivateContributions( IWorkbenchPart::Pointer /*part*/, bool /*enable*/) { //PartSite::Pointer site = part->GetSite().Cast (); //site->ActivateActionBars(enable); } void WorkbenchPage::ActionSwitcher::DeactivateContributions( IWorkbenchPart::Pointer /*part*/, bool /*remove*/) { //PartSite::Pointer site = part->GetSite().Cast (); //site->DeactivateActionBars(remove); } IExtensionPoint::Pointer WorkbenchPage::GetPerspectiveExtensionPoint() { return Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID(), WorkbenchRegistryConstants::PL_PERSPECTIVE_EXTENSIONS); } WorkbenchPage::WorkbenchPage(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input) + : actionSwitcher(this) { if (layoutID == "") { throw WorkbenchException("Perspective ID is undefined"); } this->Register(); this->Init(w, layoutID, input, true); this->UnRegister(false); } WorkbenchPage::WorkbenchPage(WorkbenchWindow* w, IAdaptable* input) + : actionSwitcher(this) { this->Register(); this->Init(w, "", input, false); this->UnRegister(false); } void WorkbenchPage::Activate(IWorkbenchPart::Pointer part) { // Sanity check. if (!this->CertifyPart(part)) { return; } if (window->IsClosing()) { return; } // if (composite!=0 && composite.isVisible() && !((GrabFocus)Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part)) // { // return; // } // Activate part. //if (window.getActivePage() == this) { IWorkbenchPartReference::Pointer ref = this->GetReference(part); this->InternalBringToTop(ref); this->SetActivePart(part); } void WorkbenchPage::ActivatePart(const IWorkbenchPart::Pointer part) { // Platform.run(new SafeRunnable(WorkbenchMessages.WorkbenchPage_ErrorActivatingView) // { // public void WorkbenchPage::run() // { if (part.IsNotNull()) { //part.setFocus(); PartPane::Pointer pane = this->GetPane(part); pane->SetFocus(); PartSite::Pointer site = part->GetSite().Cast (); pane->ShowFocus(true); //this->UpdateTabList(part); //SubActionBars bars = (SubActionBars) site.getActionBars(); //bars.partChanged(part); } // } // } // ); } void WorkbenchPage::AddPartListener(IPartListener* l) { partList->GetPartService()->AddPartListener(l); } void WorkbenchPage::AddSelectionListener(ISelectionListener* listener) { selectionService->AddSelectionListener(listener); } void WorkbenchPage::AddSelectionListener(const QString& partId, ISelectionListener* listener) { selectionService->AddSelectionListener(partId, listener); } void WorkbenchPage::AddPostSelectionListener( ISelectionListener* listener) { selectionService->AddPostSelectionListener(listener); } void WorkbenchPage::AddPostSelectionListener(const QString& partId, ISelectionListener* listener) { selectionService->AddPostSelectionListener(partId, listener); } ILayoutContainer::Pointer WorkbenchPage::GetContainer( IWorkbenchPart::Pointer part) { PartPane::Pointer pane = this->GetPane(part); if (pane == 0) { return ILayoutContainer::Pointer(0); } return pane->GetContainer(); } ILayoutContainer::Pointer WorkbenchPage::GetContainer( IWorkbenchPartReference::Pointer part) { PartPane::Pointer pane = this->GetPane(part); if (pane == 0) { return ILayoutContainer::Pointer(0); } return pane->GetContainer(); } PartPane::Pointer WorkbenchPage::GetPane(IWorkbenchPart::Pointer part) { if (part.IsNull()) { return PartPane::Pointer(0); } return this->GetPane(this->GetReference(part)); } PartPane::Pointer WorkbenchPage::GetPane(IWorkbenchPartReference::Pointer part) { if (part.IsNull()) { return PartPane::Pointer(0); } return part.Cast ()->GetPane(); } bool WorkbenchPage::InternalBringToTop(IWorkbenchPartReference::Pointer part) { bool broughtToTop = false; // Move part. if (part.Cast ().IsNotNull()) { ILayoutContainer::Pointer container = this->GetContainer(part); if (container.Cast () != 0) { PartStack::Pointer stack = container.Cast (); PartPane::Pointer newPart = this->GetPane(part); if (stack->GetSelection() != newPart) { stack->SetSelection(newPart); } broughtToTop = true; } } else if (part.Cast ().IsNotNull()) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { broughtToTop = persp->BringToTop(part.Cast ()); } } // Ensure that this part is considered the most recently activated part // in this stack activationList->BringToTop(part); return broughtToTop; } void WorkbenchPage::BringToTop(IWorkbenchPart::Pointer part) { // Sanity check. Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0 || !this->CertifyPart(part)) { return; } // if (!((GrabFocus)Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part)) // { // return; // } // QString label; // debugging only // if (UIStats.isDebugging(UIStats.BRING_PART_TO_TOP)) // { // label = part != 0 ? part.getTitle() : "none"; //$NON-NLS-1$ // } IWorkbenchPartReference::Pointer ref = this->GetReference(part); ILayoutContainer::Pointer activeEditorContainer = this->GetContainer( this->GetActiveEditor().Cast ()); ILayoutContainer::Pointer activePartContainer = this->GetContainer( this->GetActivePart()); ILayoutContainer::Pointer newPartContainer = this->GetContainer(part); if (newPartContainer == activePartContainer) { this->MakeActive(ref); } else if (newPartContainer == activeEditorContainer) { if (ref.Cast () != 0) { if (part != 0) { IWorkbenchPartSite::Pointer site = part->GetSite(); if (site.Cast () != 0) { ref = site.Cast ()->GetPane()->GetPartReference(); } } this->MakeActiveEditor(ref.Cast ()); } else { this->MakeActiveEditor(IEditorReference::Pointer(0)); } } else { this->InternalBringToTop(ref); if (ref != 0) { partList->FirePartBroughtToTop(ref); } } } void WorkbenchPage::BusyResetPerspective() { ViewIntroAdapterPart::Pointer introViewAdapter = dynamic_cast (GetWorkbenchWindow() ->GetWorkbench()->GetIntroManager())->GetIntroAdapterPart().Cast< ViewIntroAdapterPart> (); // PartPane introPane = 0; // boolean introFullScreen = false; // if (introViewAdapter != 0) // { // introPane = ((PartSite) introViewAdapter.getSite()).getPane(); // introViewAdapter.setHandleZoomEvents(false); // introFullScreen = introPane.isZoomed(); // } // //try to prevent intro flicker. // if (introFullScreen) // { // window.getShell().setRedraw(false); // } // try // { // // Always unzoom // if (isZoomed()) // { // zoomOut(); // } // Get the current perspective. // This describes the working layout of the page and differs from // the original template. Perspective::Pointer oldPersp = this->GetActivePerspective(); // Map the current perspective to the original template. // If the original template cannot be found then it has been deleted. // In that case just return. (PR#1GDSABU). IPerspectiveRegistry* reg = WorkbenchPlugin::GetDefault() ->GetPerspectiveRegistry(); PerspectiveDescriptor::Pointer desc = reg->FindPerspectiveWithId( oldPersp->GetDesc()->GetId()).Cast (); if (desc == 0) { desc = reg->FindPerspectiveWithId(oldPersp ->GetDesc().Cast< PerspectiveDescriptor> ()->GetOriginalId()).Cast< PerspectiveDescriptor> (); } if (desc == 0) { return; } // Notify listeners that we are doing a reset. window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc, CHANGE_RESET); // Create new persp from original template. // Suppress the perspectiveOpened and perspectiveClosed events otherwise it looks like two // instances of the same perspective are open temporarily (see bug 127470). Perspective::Pointer newPersp = this->CreatePerspective(desc, false); if (newPersp == 0) { // We're not going through with the reset, so it is complete. window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc, CHANGE_RESET_COMPLETE); return; } // Update the perspective list and shortcut perspList.Swap(oldPersp, newPersp); // Install new persp. this->SetPerspective(newPersp); // Destroy old persp. this->DisposePerspective(oldPersp, false); // Update the Coolbar layout. this->ResetToolBarLayout(); // restore the maximized intro if (introViewAdapter) { try { // ensure that the intro is visible in the new perspective ShowView(IntroConstants::INTRO_VIEW_ID); // if (introFullScreen) // { // toggleZoom(introPane.getPartReference()); // } } catch (PartInitException& e) { //TODO IStatus WorkbenchPlugin::Log("Could not restore intro", e); // WorkbenchPlugin.getStatus(e)); } // finally // { // // we want the intro back to a normal state before we fire the event // introViewAdapter.setHandleZoomEvents(true); // } } // Notify listeners that we have completed our reset. window->FirePerspectiveChanged(IWorkbenchPage::Pointer(this), desc, CHANGE_RESET_COMPLETE); // } // finally // { // // reset the handling of zoom events (possibly for the second time) in case there was // // an exception thrown // if (introViewAdapter != 0) // { // introViewAdapter.setHandleZoomEvents(true); // } // // if (introFullScreen) // { // window.getShell().setRedraw(true); // } // } } void WorkbenchPage::RemovePerspective(IPerspectiveDescriptor::Pointer desc) { Perspective::Pointer newPersp; PerspectiveDescriptor::Pointer realDesc = desc.Cast (); newPersp = this->FindPerspective(desc); perspList.Remove(newPersp); } void WorkbenchPage::BusySetPerspective(IPerspectiveDescriptor::Pointer desc) { // Create new layout. QString label = desc->GetId(); // debugging only Perspective::Pointer newPersp; //try //{ //UIStats.start(UIStats.SWITCH_PERSPECTIVE, label); PerspectiveDescriptor::Pointer realDesc = desc.Cast (); newPersp = this->FindPerspective(realDesc); if (newPersp == 0) { newPersp = this->CreatePerspective(realDesc, true); if (newPersp == 0) { return; } } // Change layout. this->SetPerspective(newPersp); // } // catch (std::exception& e) // { // UIStats.end(UIStats.SWITCH_PERSPECTIVE, desc.getId(), label); // throw e; // } } IViewPart::Pointer WorkbenchPage::BusyShowView(const QString& viewID, const QString& secondaryID, int mode) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return IViewPart::Pointer(0); } // If this view is already visible just return. IViewReference::Pointer ref = persp->FindView(viewID, secondaryID); IViewPart::Pointer view; if (ref != 0) { view = ref->GetView(true); } if (view != 0) { this->BusyShowView(view, mode); return view; } // Show the view. view = persp->ShowView(viewID, secondaryID); if (view != 0) { this->BusyShowView(view, mode); IWorkbenchPartReference::Pointer partReference = this->GetReference(view); PartPane::Pointer partPane = this->GetPane(partReference); partPane->SetInLayout(true); IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, GetPerspective(), partReference, CHANGE_VIEW_SHOW); window->FirePerspectiveChanged(thisPage, GetPerspective(), CHANGE_VIEW_SHOW); } return view; } +void WorkbenchPage::UpdateActionBars() +{ + window->UpdateActionBars(); +} + void WorkbenchPage::BusyShowView(IViewPart::Pointer part, int mode) { // if (!((GrabFocus) Tweaklets.get(GrabFocus.KEY)).grabFocusAllowed(part)) // { // return; // } if (mode == VIEW_ACTIVATE) { this->Activate(part); } else if (mode == VIEW_VISIBLE) { IWorkbenchPartReference::Pointer ref = this->GetActivePartReference(); // if there is no active part or it's not a view, bring to top if (ref == 0 || ref.Cast () == 0) { this->BringToTop(part); } else { // otherwise check to see if the we're in the same stack as the active view IViewReference::Pointer activeView = ref.Cast (); QList viewStack = this->GetViewReferenceStack(part); for (int i = 0; i < viewStack.size(); i++) { if (viewStack[i] == activeView) { return; } } this->BringToTop(part); } } } bool WorkbenchPage::CertifyPart(IWorkbenchPart::Pointer part) { //Workaround for bug 22325 if (part != 0 && part->GetSite().Cast () == 0) { return false; } if (part.Cast () != 0) { IEditorReference::Pointer ref = this->GetReference(part).Cast< IEditorReference> (); return ref != 0 && this->GetEditorManager()->ContainsEditor(ref); } if (part.Cast () != 0) { Perspective::Pointer persp = this->GetActivePerspective(); return persp != 0 && persp->ContainsView(part.Cast ()); } return false; } bool WorkbenchPage::Close() { bool ret; //BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { ret = window->ClosePage(IWorkbenchPage::Pointer(this), true); // } // }); return ret; } bool WorkbenchPage::CloseAllSavedEditors() { // get the Saved editors QList editors = this->GetEditorReferences(); QList savedEditors; for (QList::iterator iter = editors.begin(); iter != editors.end(); ++iter) { IEditorReference::Pointer editor = *iter; if (!editor->IsDirty()) { savedEditors.push_back(editor); } } //there are no unsaved editors if (savedEditors.empty()) { return true; } return this->CloseEditors(savedEditors, false); } bool WorkbenchPage::CloseAllEditors(bool save) { return this->CloseEditors(this->GetEditorReferences(), save); } void WorkbenchPage::UpdateActivePart() { if (this->IsDeferred()) { return; } IWorkbenchPartReference::Pointer oldActivePart = partList->GetActivePartReference(); IWorkbenchPartReference::Pointer oldActiveEditor = partList->GetActiveEditorReference(); IWorkbenchPartReference::Pointer newActivePart; IEditorReference::Pointer newActiveEditor; if (!window->IsClosing()) { // If an editor is active, try to keep an editor active if (oldActiveEditor && oldActivePart == oldActiveEditor) { newActiveEditor = activationList->GetActiveReference(true).Cast< IEditorReference> (); newActivePart = newActiveEditor; if (newActivePart == 0) { // Only activate a non-editor if there's no editors left newActivePart = activationList->GetActiveReference(false); } } else { // If a non-editor is active, activate whatever was activated most recently newActivePart = activationList->GetActiveReference(false); if (newActivePart.Cast () != 0) { // If that happens to be an editor, make it the active editor as well newActiveEditor = newActivePart.Cast (); } else { // Otherwise, select whatever editor was most recently active newActiveEditor = activationList->GetActiveReference(true).Cast< IEditorReference> (); } } } if (oldActiveEditor != newActiveEditor) { this->MakeActiveEditor(newActiveEditor); } if (newActivePart != oldActivePart) { this->MakeActive(newActivePart); } } void WorkbenchPage::MakeActive(IWorkbenchPartReference::Pointer ref) { if (ref == 0) { this->SetActivePart(IWorkbenchPart::Pointer(0)); } else { IWorkbenchPart::Pointer newActive = ref->GetPart(true); if (newActive == 0) { this->SetActivePart(IWorkbenchPart::Pointer(0)); } else { this->Activate(newActive); } } } void WorkbenchPage::MakeActiveEditor(IEditorReference::Pointer ref) { if (ref == this->GetActiveEditorReference()) { return; } IEditorPart::Pointer part = (ref == 0) ? IEditorPart::Pointer(0) : ref->GetEditor(true); if (part) { editorMgr->SetVisibleEditor(ref, false); //navigationHistory.MarkEditor(part); } actionSwitcher.UpdateTopEditor(part); if (ref) { activationList->BringToTop(this->GetReference(part)); } partList->SetActiveEditor(ref); } bool WorkbenchPage::CloseEditors( const QList& refArray, bool save) { if (refArray.empty()) { return true; } IWorkbenchPage::Pointer thisPage(this); // Check if we're being asked to close any parts that are already closed or cannot // be closed at this time QList editorRefs; for (QList::const_iterator iter = refArray.begin(); iter != refArray.end(); ++iter) { IEditorReference::Pointer reference = *iter; // If we're in the middle of creating this part, this is a programming error. Abort the entire // close operation. This usually occurs if someone tries to open a dialog in a method that // isn't allowed to do so, and a *syncExec tries to close the part. If this shows up in a log // file with a dialog's event loop on the stack, then the code that opened the dialog is usually // at fault. if (partBeingActivated == reference) { ctkRuntimeException re( "WARNING: Blocked recursive attempt to close part " + partBeingActivated->GetId() + " while still in the middle of activating it"); WorkbenchPlugin::Log(re); return false; } // if (reference.Cast () != 0) // { // WorkbenchPartReference::Pointer ref = reference.Cast(); // // // If we're being asked to close a part that is disposed (ie: already closed), // // skip it and proceed with closing the remaining parts. // if (ref.isDisposed()) // { // continue; // } // } editorRefs.push_back(reference); } // notify the model manager before the close QList partsToClose; for (int i = 0; i < editorRefs.size(); i++) { IWorkbenchPart::Pointer refPart = editorRefs[i]->GetPart(false); if (refPart != 0) { partsToClose.push_back(refPart); } } SaveablesList::Pointer modelManager; SaveablesList::PostCloseInfo::Pointer postCloseInfo; if (partsToClose.size() > 0) { modelManager = dynamic_cast( this->GetWorkbenchWindow()->GetService()); // this may prompt for saving and return 0 if the user canceled: postCloseInfo = modelManager->PreCloseParts(partsToClose, save, this->GetWorkbenchWindow()); if (postCloseInfo == 0) { return false; } } // Fire pre-removal changes for (int i = 0; i < editorRefs.size(); i++) { IEditorReference::Pointer ref = editorRefs[i]; // Notify interested listeners before the close window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_CLOSE); } this->DeferUpdates(true); try { if (modelManager != 0) { modelManager->PostClose(postCloseInfo); } // Close all editors. for (int i = 0; i < editorRefs.size(); i++) { IEditorReference::Pointer ref = editorRefs[i]; // Remove editor from the presentation editorPresentation->CloseEditor(ref); this->PartRemoved(ref.Cast ()); } } catch (...) { } this->DeferUpdates(false); // Notify interested listeners after the close window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_CLOSE); // Return true on success. return true; } void WorkbenchPage::DeferUpdates(bool shouldDefer) { if (shouldDefer) { if (deferCount == 0) { this->StartDeferring(); } deferCount++; } else { deferCount--; if (deferCount == 0) { this->HandleDeferredEvents(); } } } void WorkbenchPage::StartDeferring() { //editorPresentation.getLayoutPart().deferUpdates(true); } void WorkbenchPage::HandleDeferredEvents() { editorPresentation->GetLayoutPart()->DeferUpdates(false); this->UpdateActivePart(); QList disposals = pendingDisposals; pendingDisposals.clear(); for (int i = 0; i < disposals.size(); i++) { this->DisposePart(disposals[i]); } } bool WorkbenchPage::IsDeferred() { return deferCount > 0; } bool WorkbenchPage::CloseEditor(IEditorReference::Pointer editorRef, bool save) { QList list; list.push_back(editorRef); return this->CloseEditors(list, save); } bool WorkbenchPage::CloseEditor(IEditorPart::Pointer editor, bool save) { IWorkbenchPartReference::Pointer ref = this->GetReference(editor); if (ref.Cast ().IsNotNull()) { QList list; list.push_back(ref.Cast ()); return this->CloseEditors(list, save); } return false; } void WorkbenchPage::CloseCurrentPerspective(bool saveParts, bool closePage) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { this->ClosePerspective(persp, saveParts, closePage); } } void WorkbenchPage::ClosePerspective(IPerspectiveDescriptor::Pointer desc, bool saveParts, bool closePage) { Perspective::Pointer persp = this->FindPerspective(desc); if (persp != 0) { this->ClosePerspective(persp, saveParts, closePage); } } void WorkbenchPage::ClosePerspective(Perspective::Pointer persp, bool saveParts, bool closePage) { // // Always unzoom // if (isZoomed()) // { // zoomOut(); // } QList partsToSave; QList viewsToClose; // collect views that will go away and views that are dirty QList viewReferences = persp->GetViewReferences(); for (int i = 0; i < viewReferences.size(); i++) { IViewReference::Pointer reference = viewReferences[i]; if (this->GetViewFactory()->GetReferenceCount(reference) == 1) { IViewPart::Pointer viewPart = reference->GetView(false); if (viewPart != 0) { viewsToClose.push_back(viewPart); if (saveParts && reference->IsDirty()) { partsToSave.push_back(viewPart); } } } } if (saveParts && perspList.Size() == 1) { // collect editors that are dirty QList editorReferences = this->GetEditorReferences(); for (QList::iterator refIter = editorReferences.begin(); refIter != editorReferences.end(); ++refIter) { IEditorReference::Pointer reference = *refIter; if (reference->IsDirty()) { IEditorPart::Pointer editorPart = reference->GetEditor(false); if (editorPart != 0) { partsToSave.push_back(editorPart); } } } } if (saveParts && !partsToSave.empty()) { if (!EditorManager::SaveAll(partsToSave, true, true, false, IWorkbenchWindow::Pointer(window))) { // user canceled return; } } // Close all editors on last perspective close if (perspList.Size() == 1 && this->GetEditorManager()->GetEditorCount() > 0) { // Close all editors if (!this->CloseAllEditors(false)) { return; } } // closeAllEditors already notified the saveables list about the editors. SaveablesList::Pointer saveablesList( dynamic_cast( this->GetWorkbenchWindow()->GetWorkbench()->GetService())); // we took care of the saving already, so pass in false (postCloseInfo will be non-0) SaveablesList::PostCloseInfo::Pointer postCloseInfo = saveablesList->PreCloseParts(viewsToClose, false, this->GetWorkbenchWindow()); saveablesList->PostClose(postCloseInfo); // Dispose of the perspective bool isActive = (perspList.GetActive() == persp); if (isActive) { this->SetPerspective(perspList.GetNextActive()); } this->DisposePerspective(persp, true); if (closePage && perspList.Size() == 0) { this->Close(); } } void WorkbenchPage::CloseAllPerspectives(bool saveEditors, bool closePage) { if (perspList.IsEmpty()) { return; } // // Always unzoom // if (isZoomed()) // { // zoomOut(); // } if (saveEditors) { if (!this->SaveAllEditors(true)) { return; } } // Close all editors if (!this->CloseAllEditors(false)) { return; } // Deactivate the active perspective and part this->SetPerspective(Perspective::Pointer(0)); // Close each perspective in turn PerspectiveList oldList = perspList; perspList = PerspectiveList(); for (PerspectiveList::iterator itr = oldList.Begin(); itr != oldList.End(); ++itr) { this->ClosePerspective(*itr, false, false); } if (closePage) { this->Close(); } } void WorkbenchPage::CreateClientComposite() { QWidget* parent = window->GetPageComposite(); // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() // { composite = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreateClientComposite( parent); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, false); // Make visible on activate. // force the client composite to be layed out // parent.layout(); // } // }); } Perspective::Pointer WorkbenchPage::CreatePerspective( PerspectiveDescriptor::Pointer desc, bool notify) { QString label = desc->GetId(); // debugging only try { //UIStats.start(UIStats.CREATE_PERSPECTIVE, label); WorkbenchPage::Pointer thisPage(this); Perspective::Pointer persp(new Perspective(desc, thisPage)); perspList.Add(persp); if (notify) { window->FirePerspectiveOpened(thisPage, desc); } //if the perspective is fresh and uncustomzied then it is not dirty //no reset will be prompted for if (!desc->HasCustomDefinition()) { dirtyPerspectives.erase(desc->GetId()); } return persp; } catch (WorkbenchException& /*e*/) { if (!window->GetWorkbenchImpl()->IsStarting()) { QMessageBox::critical(reinterpret_cast(window->GetShell()->GetControl()), "Error", "Problems opening perspective \"" + desc->GetId() + "\""); } return Perspective::Pointer(0); } // finally // { // UIStats.end(UIStats.CREATE_PERSPECTIVE, desc.getId(), label); // } } void WorkbenchPage::PartAdded(WorkbenchPartReference::Pointer ref) { activationList->Add(ref); partList->AddPart(ref); this->UpdateActivePart(); } void WorkbenchPage::PartRemoved(WorkbenchPartReference::Pointer ref) { activationList->Remove(ref); this->DisposePart(ref); } void WorkbenchPage::DisposePart(WorkbenchPartReference::Pointer ref) { if (this->IsDeferred()) { pendingDisposals.push_back(ref); } else { partList->RemovePart(ref); ref->Dispose(); } } void WorkbenchPage::DeactivatePart(IWorkbenchPart::Pointer part) { if (part.IsNotNull()) { PartSite::Pointer site = part->GetSite().Cast (); site->GetPane()->ShowFocus(false); } } void WorkbenchPage::DetachView(IViewReference::Pointer ref) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } PerspectiveHelper* presentation = persp->GetPresentation(); presentation->DetachPart(ref); } void WorkbenchPage::AttachView(IViewReference::Pointer ref) { PerspectiveHelper* presentation = this->GetPerspectivePresentation(); presentation->AttachPart(ref); } WorkbenchPage::~WorkbenchPage() { // increment reference count to prevent recursive deletes this->Register(); { { this->MakeActiveEditor(IEditorReference::Pointer(0)); this->MakeActive(IWorkbenchPartReference::Pointer(0)); // Close and dispose the editors. this->CloseAllEditors(false); // Need to make sure model data is cleaned up when the page is // disposed. Collect all the views on the page and notify the // saveable list of a pre/post close. This will free model data. QList partsToClose = this->GetOpenParts(); QList dirtyParts; for (int i = 0; i < partsToClose.size(); i++) { IWorkbenchPart::Pointer part = partsToClose[i]->GetPart(false); if (part != 0 && part.Cast () != 0) { dirtyParts.push_back(part); } } SaveablesList::Pointer saveablesList(dynamic_cast( this->GetWorkbenchWindow()->GetWorkbench()->GetService())); SaveablesList::PostCloseInfo::Pointer postCloseInfo = saveablesList->PreCloseParts(dirtyParts, false, this->GetWorkbenchWindow()); saveablesList->PostClose(postCloseInfo); IWorkbenchPage::Pointer thisPage(this); // Get rid of perspectives. This will close the views for (PerspectiveList::iterator itr = perspList.Begin(); itr != perspList.End(); ++itr) { Perspective::Pointer perspective = *itr; window->FirePerspectiveClosed(thisPage, perspective->GetDesc()); //perspective->Dispose(); } perspList = PerspectiveList(); // Get rid of editor presentation. //editorPresentation->Dispose(); // Get rid of composite. //composite.dispose(); //navigationHistory.dispose(); //stickyViewMan.clear(); // if (tracker != 0) // { // tracker.close(); // } // // if we're destroying a window in a non-shutdown situation then we should // // clean up the working set we made. // if (!window->GetWorkbench()->IsClosing()) // { // if (aggregateWorkingSet != 0) // { // PlatformUI.getWorkbench().getWorkingSetManager().removeWorkingSet( // aggregateWorkingSet); // } // } } partBeingActivated = 0; pendingDisposals.clear(); stickyViewMan = 0; delete viewFactory; delete editorPresentation; delete editorMgr; delete activationList; deferredActivePersp = 0; dirtyPerspectives.clear(); delete selectionService; partList.reset(); } // decrement reference count again, without explicit deletion this->UnRegister(false); } void WorkbenchPage::DisposePerspective(Perspective::Pointer persp, bool notify) { // Get rid of perspective. perspList.Remove(persp); if (notify) { IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveClosed(thisPage, persp->GetDesc()); } //persp->Dispose(); stickyViewMan->Remove(persp->GetDesc()->GetId()); } Perspective::Pointer WorkbenchPage::FindPerspective( IPerspectiveDescriptor::Pointer desc) { for (PerspectiveList::iterator itr = perspList.Begin(); itr != perspList.End(); ++itr) { Perspective::Pointer mgr = *itr; if (desc->GetId() == mgr->GetDesc()->GetId()) { return mgr; } } return Perspective::Pointer(0); } IViewPart::Pointer WorkbenchPage::FindView(const QString& id) { IViewReference::Pointer ref = this->FindViewReference(id); if (ref == 0) { return IViewPart::Pointer(0); } return ref->GetView(true); } IViewReference::Pointer WorkbenchPage::FindViewReference( const QString& viewId) { return this->FindViewReference(viewId, ""); } IViewReference::Pointer WorkbenchPage::FindViewReference( const QString& viewId, const QString& secondaryId) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return IViewReference::Pointer(0); } return persp->FindView(viewId, secondaryId); } IEditorPart::Pointer WorkbenchPage::GetActiveEditor() { return partList->GetActiveEditor(); } IEditorReference::Pointer WorkbenchPage::GetActiveEditorReference() { return partList->GetActiveEditorReference(); } IWorkbenchPart::Pointer WorkbenchPage::GetActivePart() { return partList->GetActivePart(); } IWorkbenchPartReference::Pointer WorkbenchPage::GetActivePartReference() { return partList->GetActivePartReference(); } Perspective::Pointer WorkbenchPage::GetActivePerspective() { return perspList.GetActive(); } QWidget* WorkbenchPage::GetClientComposite() { return composite; } EditorManager* WorkbenchPage::GetEditorManager() { return editorMgr; } PerspectiveHelper* WorkbenchPage::GetPerspectivePresentation() { if (this->GetActivePerspective() != 0) { return this->GetActivePerspective()->GetPresentation(); } return 0; } bool WorkbenchPage::HasView(const QString& perspectiveId, const QString& viewId) { PerspectiveList::PerspectiveListType list = perspList.GetSortedPerspectives(); for ( PerspectiveList::PerspectiveListType::iterator it = list.begin(); it!=list.end(); it++) { SmartPointer p = *it; if (p->GetDesc()->GetId() == perspectiveId) { if (p->ContainsView(viewId)) { return true; } } } return false; } /** * Answer the editor presentation. */ EditorAreaHelper* WorkbenchPage::GetEditorPresentation() { return editorPresentation; } QList WorkbenchPage::GetEditors() { QList refs = this->GetEditorReferences(); QList result; //Display d = getWorkbenchWindow().getShell().getDisplay(); //Must be backward compatible. // d.syncExec(new Runnable() // { // public void WorkbenchPage::run() // { for (QList::iterator iter = refs.begin(); iter != refs.end(); ++iter) { IEditorPart::Pointer part = (*iter)->GetEditor(true); if (part != 0) { result.push_back(part); } } // } // }); return result; } QList WorkbenchPage::GetDirtyEditors() { return this->GetEditorManager()->GetDirtyEditors(); } QList WorkbenchPage::GetDirtyParts() { QList result; QList allParts = this->GetAllParts(); for (int i = 0; i < allParts.size(); i++) { IWorkbenchPartReference::Pointer reference = allParts[i]; IWorkbenchPart::Pointer part = reference->GetPart(false); if (part != 0 && part.Cast () != 0) { ISaveablePart::Pointer saveable = part.Cast (); if (saveable->IsDirty()) { result.push_back(saveable); } } } return result; } IEditorPart::Pointer WorkbenchPage::FindEditor(IEditorInput::Pointer input) { return this->GetEditorManager()->FindEditor(input); } QList WorkbenchPage::FindEditors( IEditorInput::Pointer input, const QString& editorId, int matchFlags) { return this->GetEditorManager()->FindEditors(input, editorId, matchFlags); } QList WorkbenchPage::GetEditorReferences() { return editorPresentation->GetEditors(); } IAdaptable* WorkbenchPage::GetInput() { return input; } QString WorkbenchPage::GetLabel() { QString label = ""; // IWorkbenchAdapter adapter = (IWorkbenchAdapter) Util.getAdapter(input, // IWorkbenchAdapter.class); // if (adapter != 0) // { // label = adapter.getLabel(input); // } Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { label = label + " - " + persp->GetDesc()->GetLabel(); } else if (deferredActivePersp != 0) { label = label + " - " + deferredActivePersp->GetLabel(); } return label; } IPerspectiveDescriptor::Pointer WorkbenchPage::GetPerspective() { if (deferredActivePersp != 0) { return deferredActivePersp; } Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->GetDesc(); } else { return IPerspectiveDescriptor::Pointer(0); } } ISelection::ConstPointer WorkbenchPage::GetSelection() const { return selectionService->GetSelection(); } ISelection::ConstPointer WorkbenchPage::GetSelection(const QString& partId) { return selectionService->GetSelection(partId); } //ISelectionService::SelectionEvents& WorkbenchPage::GetSelectionEvents(const QString& partId) //{ // return selectionService->GetSelectionEvents(partId); //} ViewFactory* WorkbenchPage::GetViewFactory() { if (viewFactory == 0) { viewFactory = new ViewFactory(this, WorkbenchPlugin::GetDefault()->GetViewRegistry()); } return viewFactory; } QList WorkbenchPage::GetViewReferences() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->GetViewReferences(); } else { return QList(); } } QList WorkbenchPage::GetViews() { return this->GetViews(Perspective::Pointer(0), true); } QList WorkbenchPage::GetViews( Perspective::Pointer persp, bool restore) { if (persp == 0) { persp = this->GetActivePerspective(); } QList parts; if (persp != 0) { QList refs = persp->GetViewReferences(); for (int i = 0; i < refs.size(); i++) { IViewPart::Pointer part = refs[i]->GetPart(restore).Cast (); if (part != 0) { parts.push_back(part); } } } return parts; } -IWorkbenchWindow::Pointer WorkbenchPage::GetWorkbenchWindow() +IWorkbenchWindow::Pointer WorkbenchPage::GetWorkbenchWindow() const { return IWorkbenchWindow::Pointer(window); } void WorkbenchPage::HideView(IViewReference::Pointer ref) { // Sanity check. if (ref == 0) { return; } Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } bool promptedForSave = false; IViewPart::Pointer view = ref->GetView(false); if (view != 0) { if (!this->CertifyPart(view)) { return; } // Confirm. if (view.Cast () != 0) { ISaveablePart::Pointer saveable = view.Cast (); if (saveable->IsSaveOnCloseNeeded()) { IWorkbenchWindow::Pointer window = view->GetSite()->GetWorkbenchWindow(); QList partsToSave; partsToSave.push_back(view); bool success = EditorManager::SaveAll(partsToSave, true, true, false, window); if (!success) { // the user cancelled. return; } promptedForSave = true; } } } int refCount = this->GetViewFactory()->GetReferenceCount(ref); SaveablesList* saveablesList = NULL; SaveablesList::PostCloseInfo::Pointer postCloseInfo; if (refCount == 1) { IWorkbenchPart::Pointer actualPart = ref->GetPart(false); if (actualPart != 0) { saveablesList = dynamic_cast( actualPart->GetSite()->GetService()); QList partsToClose; partsToClose.push_back(actualPart); postCloseInfo = saveablesList->PreCloseParts(partsToClose, !promptedForSave, this->GetWorkbenchWindow()); if (postCloseInfo == 0) { // cancel return; } } } IWorkbenchPage::Pointer thisPage(this); // Notify interested listeners before the hide window->FirePerspectiveChanged(thisPage, persp->GetDesc(), ref, CHANGE_VIEW_HIDE); PartPane::Pointer pane = this->GetPane(ref.Cast ()); pane->SetInLayout(false); this->UpdateActivePart(); if (saveablesList != 0) { saveablesList->PostClose(postCloseInfo); } // Hide the part. persp->HideView(ref); // Notify interested listeners after the hide window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_VIEW_HIDE); } void WorkbenchPage::RefreshActiveView() { this->UpdateActivePart(); } void WorkbenchPage::HideView(IViewPart::Pointer view) { this->HideView(this->GetReference(view).Cast ()); } void WorkbenchPage::Init(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input, bool openExtras) { // Save args. this->window = w; this->input = input; this->composite = 0; this->viewFactory = 0; this->activationList = new ActivationList(this); this->selectionService = new PageSelectionService(this); this->partList.reset(new WorkbenchPagePartList(this->selectionService)); this->stickyViewMan = new StickyViewManager(this); //actionSets = new ActionSetManager(w); deferCount = 0; // Create presentation. this->CreateClientComposite(); editorPresentation = new EditorAreaHelper(this); editorMgr = new EditorManager(WorkbenchWindow::Pointer(window), WorkbenchPage::Pointer(this), editorPresentation); //TODO WorkbenchPage perspective reorder listener? // // add this page as a client to be notified when the UI has re-ordered perspectives // // so that the order can be properly maintained in the receiver. // // E.g. a UI might support drag-and-drop and will need to make this known to ensure // // #saveState and #restoreState do not lose this re-ordering // w.addPerspectiveReorderListener(new IReorderListener() // { // public void WorkbenchPage::reorder(Object perspective, int newLoc) // { // perspList.reorder((IPerspectiveDescriptor)perspective, newLoc); // } // }); if (openExtras) { this->OpenPerspectiveExtras(); } // Get perspective descriptor. if (layoutID != "") { PerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->FindPerspectiveWithId( layoutID).Cast (); if (desc == 0) { throw WorkbenchException("Unable to create Perspective " + layoutID + ". There is no corresponding perspective extension."); } Perspective::Pointer persp = this->FindPerspective(desc); if (persp == 0) { persp = this->CreatePerspective(desc, true); } perspList.SetActive(persp); window->FirePerspectiveActivated(IWorkbenchPage::Pointer(this), desc); } - // getExtensionTracker() .registerHandler(perspectiveChangeHandler, - // ExtensionTracker .createExtensionPointFilter( - // getPerspectiveExtensionPoint())); + //this->GetExtensionTracker()->RegisterHandler(perspectiveChangeHandler, + // ExtensionTracker::CreateExtensionPointFilter( + // GetPerspectiveExtensionPoint())); } void WorkbenchPage::OpenPerspectiveExtras() { //TODO WorkbenchPage perspectice extras QString extras = ""; //PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.PERSPECTIVE_BAR_EXTRAS); QList descs; foreach (QString id, extras.split(", ", QString::SkipEmptyParts)) { if (id.trimmed().isEmpty()) continue; IPerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()->FindPerspectiveWithId(id); if (desc != 0) { descs.push_back(desc); } } // HACK: The perspective switcher currently adds the button for a new perspective to the beginning of the list. // So, we process the extra perspectives in reverse order here to have their buttons appear in the order declared. for (int i = (int) descs.size(); --i >= 0;) { PerspectiveDescriptor::Pointer desc = descs[i].Cast (); if (this->FindPerspective(desc) == 0) { this->CreatePerspective(desc, true); } } } bool WorkbenchPage::IsPartVisible(IWorkbenchPart::Pointer part) { PartPane::Pointer pane = this->GetPane(part); return pane != 0 && pane->GetVisible(); } bool WorkbenchPage::IsEditorAreaVisible() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return false; } return persp->IsEditorAreaVisible(); } bool WorkbenchPage::IsFastView(IViewReference::Pointer /*ref*/) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { //return persp->IsFastView(ref); return false; } else { return false; } } bool WorkbenchPage::IsCloseable(IViewReference::Pointer ref) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsCloseable(ref); } return false; } bool WorkbenchPage::IsMoveable(IViewReference::Pointer ref) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsMoveable(ref); } return false; } bool WorkbenchPage::IsFixedLayout() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->IsFixedLayout(); } else { return false; } } bool WorkbenchPage::IsSaveNeeded() { return this->GetEditorManager()->IsSaveAllNeeded(); } void WorkbenchPage::OnActivate() { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, true); Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { persp->OnActivate(); this->UpdateVisibility(Perspective::Pointer(0), persp); } } void WorkbenchPage::OnDeactivate() { this->MakeActiveEditor(IEditorReference::Pointer(0)); this->MakeActive(IWorkbenchPartReference::Pointer(0)); if (this->GetActivePerspective() != 0) { this->GetActivePerspective()->OnDeactivate(); } Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(composite, false); } void WorkbenchPage::ReuseEditor(IReusableEditor::Pointer editor, IEditorInput::Pointer input) { // Rather than calling editor.setInput on the editor directly, we do it through the part reference. // This case lets us detect badly behaved editors that are not firing a PROP_INPUT event in response // to the input change... but if all editors obeyed their API contract, the "else" branch would be // sufficient. IWorkbenchPartReference::Pointer ref = this->GetReference(editor); if (ref.Cast () != 0) { EditorReference::Pointer editorRef = ref.Cast (); editorRef->SetInput(input); } else { editor->SetInput(input); } //navigationHistory.markEditor(editor); } IEditorPart::Pointer WorkbenchPage::OpenEditor(IEditorInput::Pointer input, const QString& editorID) { return this->OpenEditor(input, editorID, true, MATCH_INPUT); } IEditorPart::Pointer WorkbenchPage::OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate) { return this->OpenEditor(input, editorID, activate, MATCH_INPUT); } IEditorPart::Pointer WorkbenchPage::OpenEditor( const IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags) { return this->OpenEditor(input, editorID, activate, matchFlags, IMemento::Pointer(0)); } IEditorPart::Pointer WorkbenchPage::OpenEditor( const IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { if (input == 0 || editorID == "") { throw Poco::InvalidArgumentException(); } // BusyIndicator.showWhile(window.getWorkbench().getDisplay(), // new Runnable() // { // public void WorkbenchPage::run() // { return this->BusyOpenEditor(input, editorID, activate, matchFlags, editorState); } IEditorPart::Pointer WorkbenchPage::OpenEditorFromDescriptor( IEditorInput::Pointer input, IEditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { if (input == 0 || !(editorDescriptor.Cast () != 0)) { throw Poco::InvalidArgumentException(); } // BusyIndicator.showWhile(window.getWorkbench().getDisplay(), // new Runnable() // { // public void WorkbenchPage::run() // { return this->BusyOpenEditorFromDescriptor(input, editorDescriptor.Cast< EditorDescriptor> (), activate, editorState); // } // }); } IEditorPart::Pointer WorkbenchPage::BusyOpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { Workbench* workbench = this->GetWorkbenchWindow().Cast ()->GetWorkbenchImpl(); workbench->LargeUpdateStart(); IEditorPart::Pointer result; try { result = this->BusyOpenEditorBatched(input, editorID, activate, matchFlags, editorState); } catch (std::exception& e) { workbench->LargeUpdateEnd(); throw e; } workbench->LargeUpdateEnd(); return result; } IEditorPart::Pointer WorkbenchPage::BusyOpenEditorFromDescriptor( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { Workbench* workbench = this->GetWorkbenchWindow().Cast ()->GetWorkbenchImpl(); workbench->LargeUpdateStart(); IEditorPart::Pointer result; try { result = this->BusyOpenEditorFromDescriptorBatched(input, editorDescriptor, activate, editorState); } catch (std::exception& e) { workbench->LargeUpdateEnd(); throw e; } workbench->LargeUpdateEnd(); return result; } IEditorPart::Pointer WorkbenchPage::BusyOpenEditorBatched( IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState) { // If an editor already exists for the input, use it. IEditorPart::Pointer editor; // Reuse an existing open editor, unless we are in "new editor tab management" mode editor = this->GetEditorManager()->FindEditor(editorID, input, matchFlags); if (editor != 0) { if (IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID == editorID) { if (editor->IsDirty()) { QMessageBox::StandardButton saveFile = QMessageBox::question( this->GetWorkbenchWindow()->GetShell()->GetControl(), "Save", "\"" + input->GetName() + "\" is opened and has unsaved changes. Do you want to save it?", QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Cancel); if (saveFile == QMessageBox::Yes) { // try // { IEditorPart::Pointer editorToSave = editor; // getWorkbenchWindow().run(false, false, // new IRunnableWithProgress() // { // public void WorkbenchPage::run(IProgressMonitor monitor) // throws InvocationTargetException, // InterruptedException // { //TODO progress monitor editorToSave->DoSave();//monitor); // } // }); // } // catch (InvocationTargetException& e) // { // throw(RuntimeException) e->GetTargetException(); // } // catch (InterruptedException& e) // { // return 0; // } } else if (saveFile == QMessageBox::Cancel) { return IEditorPart::Pointer(0); } } } else { // // do the IShowEditorInput notification before showing the editor // // to reduce flicker // if (editor.Cast () != 0) // { // ((IShowEditorInput) editor).showEditorInput(input); // } this->ShowEditor(activate, editor); return editor; } } // Otherwise, create a new one. This may cause the new editor to // become the visible (i.e top) editor. IEditorReference::Pointer ref = this->GetEditorManager()->OpenEditor( editorID, input, true, editorState); if (ref != 0) { editor = ref->GetEditor(true); } if (editor != 0) { this->SetEditorAreaVisible(true); if (activate) { this->Activate(editor); } else { this->BringToTop(editor); } IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } return editor; } /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * See openEditorFromDescriptor(). */ IEditorPart::Pointer WorkbenchPage::BusyOpenEditorFromDescriptorBatched( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState) { IEditorPart::Pointer editor; // Create a new one. This may cause the new editor to // become the visible (i.e top) editor. IEditorReference::Pointer ref; ref = this->GetEditorManager()->OpenEditorFromDescriptor(editorDescriptor, input, editorState); if (ref != 0) { editor = ref->GetEditor(true); } if (editor != 0) { this->SetEditorAreaVisible(true); if (activate) { this->Activate(editor); } else { this->BringToTop(editor); } IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } return editor; } void WorkbenchPage::OpenEmptyTab() { IEditorPart::Pointer editor; EditorReference::Pointer ref; ref = this->GetEditorManager()->OpenEmptyTab().Cast (); if (ref != 0) { editor = ref->GetEmptyEditor( dynamic_cast (WorkbenchPlugin::GetDefault()->GetEditorRegistry())->FindEditor( EditorRegistry::EMPTY_EDITOR_ID).Cast ()); } if (editor != 0) { this->SetEditorAreaVisible(true); this->Activate(editor); IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), ref, CHANGE_EDITOR_OPEN); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_OPEN); } } void WorkbenchPage::ShowEditor(bool activate, IEditorPart::Pointer editor) { this->SetEditorAreaVisible(true); if (activate) { //zoomOutIfNecessary(editor); this->Activate(editor); } else { this->BringToTop(editor); } } bool WorkbenchPage::IsEditorPinned(IEditorPart::Pointer editor) { WorkbenchPartReference::Pointer ref = this->GetReference(editor).Cast< WorkbenchPartReference> (); return ref != 0 && ref->IsPinned(); } /** * Removes an IPartListener from the part service. */ void WorkbenchPage::RemovePartListener(IPartListener* l) { partList->GetPartService()->RemovePartListener(l); } /** * Implements IWorkbenchPage * * @see org.blueberry.ui.IWorkbenchPage#removePropertyChangeListener(IPropertyChangeListener) * @since 2.0 * @deprecated individual views should store a working set if needed and * register a property change listener directly with the * working set manager to receive notification when the view * working set is removed. */ // void WorkbenchPage::RemovePropertyChangeListener(IPropertyChangeListener listener) { // propertyChangeListeners.remove(listener); // } void WorkbenchPage::RemoveSelectionListener(ISelectionListener* listener) { selectionService->RemoveSelectionListener(listener); } void WorkbenchPage::RemoveSelectionListener(const QString& partId, ISelectionListener* listener) { selectionService->RemoveSelectionListener(partId, listener); } void WorkbenchPage::RemovePostSelectionListener(ISelectionListener* listener) { selectionService->RemovePostSelectionListener(listener); } void WorkbenchPage::RemovePostSelectionListener(const QString& partId, ISelectionListener* listener) { selectionService->RemovePostSelectionListener(partId, listener); } void WorkbenchPage::RequestActivation(IWorkbenchPart::Pointer part) { // Sanity check. if (!this->CertifyPart(part)) { return; } // Real work. this->SetActivePart(part); } /** * Resets the layout for the perspective. The active part in the old layout * is activated in the new layout for consistent user context. */ void WorkbenchPage::ResetPerspective() { // Run op in busy cursor. // Use set redraw to eliminate the "flash" that can occur in the // coolbar as the perspective is reset. // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); // try // { // mgr.getControl2().setRedraw(false); // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { this->BusyResetPerspective(); // } // }); // }finally // { // mgr.getControl2().setRedraw(true); // } } bool WorkbenchPage::RestoreState(IMemento::Pointer memento, const IPerspectiveDescriptor::Pointer activeDescriptor) { // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { this->DeferUpdates(true); // }}); try { // Restore working set QString pageName; memento->GetString(WorkbenchConstants::TAG_LABEL, pageName); // String label = 0; // debugging only // if (UIStats.isDebugging(UIStats.RESTORE_WORKBENCH)) // { // label = pageName == 0 ? "" : "::" + pageName; //$NON-NLS-1$ //$NON-NLS-2$ // } try { //UIStats.start(UIStats.RESTORE_WORKBENCH, "WorkbenchPage" + label); //$NON-NLS-1$ // MultiStatus result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, NLS.bind( // WorkbenchMessages.WorkbenchPage_unableToRestorePerspective, // pageName), 0); bool result = true; // String workingSetName = memento .getString( // IWorkbenchConstants.TAG_WORKING_SET); // if (workingSetName != 0) // { // AbstractWorkingSetManager // workingSetManager = // (AbstractWorkingSetManager) getWorkbenchWindow() .getWorkbench().getWorkingSetManager(); // setWorkingSet(workingSetManager.getWorkingSet(workingSetName)); // } // // IMemento workingSetMem = memento .getChild( // IWorkbenchConstants.TAG_WORKING_SETS); // if (workingSetMem != 0) // { // QList workingSetChildren = // workingSetMem .getChildren(IWorkbenchConstants.TAG_WORKING_SET); // List workingSetList = new ArrayList(workingSetChildren.length); // for (int i = 0; i < workingSetChildren.length; i++) // { // IWorkingSet // set = // getWorkbenchWindow().getWorkbench() .getWorkingSetManager().getWorkingSet( // workingSetChildren[i].getID()); // if (set != 0) // { // workingSetList.add(set); // } // } // // workingSets = (IWorkingSet[]) workingSetList .toArray( // new IWorkingSet[workingSetList.size()]); // } // // aggregateWorkingSetId = memento.getString(ATT_AGGREGATE_WORKING_SET_ID); // // IWorkingSet setWithId = // window.getWorkbench().getWorkingSetManager().getWorkingSet( // aggregateWorkingSetId); // // // check to see if the set has already been made and assign it if it has // if (setWithId.Cast () != 0) // { // aggregateWorkingSet = (AggregateWorkingSet) setWithId; // } // Restore editor manager. IMemento::Pointer childMem = memento->GetChild( WorkbenchConstants::TAG_EDITORS); //result.merge(getEditorManager().restoreState(childMem)); result &= this->GetEditorManager()->RestoreState(childMem); childMem = memento->GetChild(WorkbenchConstants::TAG_VIEWS); if (childMem) { //result.merge(getViewFactory().restoreState(childMem)); result &= this->GetViewFactory()->RestoreState(childMem); } // Get persp block. childMem = memento->GetChild(WorkbenchConstants::TAG_PERSPECTIVES); QString activePartID; childMem->GetString(WorkbenchConstants::TAG_ACTIVE_PART, activePartID); QString activePartSecondaryID; if (!activePartID.isEmpty()) { activePartSecondaryID = ViewFactory::ExtractSecondaryId(activePartID); if (!activePartSecondaryID.isEmpty()) { activePartID = ViewFactory::ExtractPrimaryId(activePartID); } } QString activePerspectiveID; childMem->GetString(WorkbenchConstants::TAG_ACTIVE_PERSPECTIVE, activePerspectiveID); // Restore perspectives. QList perspMems(childMem->GetChildren( WorkbenchConstants::TAG_PERSPECTIVE)); Perspective::Pointer activePerspective; - IPerspectiveDescriptor::Pointer validPersp; for (int i = 0; i < perspMems.size(); i++) { IMemento::Pointer current = perspMems[i]; // StartupThreading // .runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { Perspective::Pointer persp(new Perspective( PerspectiveDescriptor::Pointer(0), WorkbenchPage::Pointer(this))); //result.merge(persp.restoreState(current)); result &= persp->RestoreState(current); IPerspectiveDescriptor::Pointer desc = persp->GetDesc(); - if (desc.IsNotNull()) - { - validPersp=desc; - } else - { - IPerspectiveDescriptor::Pointer desc = WorkbenchPlugin::GetDefault()-> - GetPerspectiveRegistry()->CreatePerspective("Hallo",validPersp); - } if (desc == activeDescriptor) { activePerspective = persp; } else if ((activePerspective == 0) && desc->GetId() == activePerspectiveID) { activePerspective = persp; } perspList.Add(persp); - //berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry()->Add window->FirePerspectiveOpened(WorkbenchPage::Pointer(this), desc); // } // }); } bool restoreActivePerspective = false; if (!activeDescriptor) { restoreActivePerspective = true; } else if (activePerspective && activePerspective->GetDesc() == activeDescriptor) { restoreActivePerspective = true; } else { restoreActivePerspective = false; activePerspective = this->CreatePerspective(activeDescriptor.Cast< PerspectiveDescriptor> (), true); if (activePerspective == 0) { // result .merge( // new Status(IStatus.ERR, PlatformUI.PLUGIN_ID, 0, NLS.bind( // WorkbenchMessages.Workbench_showPerspectiveError, // activeDescriptor.getId()), 0)); result &= false; } } perspList.SetActive(activePerspective); // Make sure we have a valid perspective to work with, // otherwise return. activePerspective = perspList.GetActive(); if (activePerspective == 0) { activePerspective = perspList.GetNextActive(); perspList.SetActive(activePerspective); } if (activePerspective && restoreActivePerspective) { //result.merge(activePerspective.restoreState()); result &= activePerspective->RestoreState(); } if (activePerspective) { Perspective::Pointer myPerspective = activePerspective; QString myActivePartId = activePartID; QString mySecondaryId = activePartSecondaryID; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { window->FirePerspectiveActivated(WorkbenchPage::Pointer(this), myPerspective->GetDesc()); // Restore active part. if (!myActivePartId.isEmpty()) { IWorkbenchPartReference::Pointer ref = myPerspective->FindView( myActivePartId, mySecondaryId); if (ref) { activationList->SetActive(ref); } } // }}); } // childMem = memento->GetChild(WorkbenchConstants::TAG_NAVIGATION_HISTORY); // if (childMem) // { // navigationHistory.restoreState(childMem); // } // else if (GetActiveEditor()) // { // navigationHistory.markEditor(getActiveEditor()); // } // // restore sticky view state stickyViewMan->Restore(memento); // QString blame = activeDescriptor == 0 ? pageName // : activeDescriptor.getId(); // UIStats.end(UIStats.RESTORE_WORKBENCH, blame, "WorkbenchPage" + label); //$NON-NLS-1$ // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // public void WorkbenchPage::runWithException() throws Throwable // { DeferUpdates(false); // } // }); return result; } catch (...) { // QString blame = activeDescriptor == 0 ? pageName // : activeDescriptor.getId(); // UIStats.end(UIStats.RESTORE_WORKBENCH, blame, "WorkbenchPage" + label); //$NON-NLS-1$ throw ; } } catch (...) { // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // public void WorkbenchPage::runWithException() throws Throwable // { DeferUpdates(false); // } // }); throw; } } bool WorkbenchPage::SaveAllEditors(bool confirm) { return this->SaveAllEditors(confirm, false); } bool WorkbenchPage::SaveAllEditors(bool confirm, bool addNonPartSources) { return this->GetEditorManager()->SaveAll(confirm, false, addNonPartSources); } bool WorkbenchPage::SavePart(ISaveablePart::Pointer saveable, IWorkbenchPart::Pointer part, bool confirm) { // Do not certify part do allow editors inside a multipageeditor to // call this. return this->GetEditorManager()->SavePart(saveable, part, confirm); } bool WorkbenchPage::SaveEditor(IEditorPart::Pointer editor, bool confirm) { return this->SavePart(editor, editor, confirm); } /** * Saves the current perspective. */ void WorkbenchPage::SavePerspective() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } // // Always unzoom. // if (isZoomed()) // { // zoomOut(); // } persp->SaveDesc(); } /** * Saves the perspective. */ void WorkbenchPage::SavePerspectiveAs(IPerspectiveDescriptor::Pointer newDesc) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } IPerspectiveDescriptor::Pointer oldDesc = persp->GetDesc(); // // Always unzoom. // if (isZoomed()) // { // zoomOut(); // } persp->SaveDescAs(newDesc); window->FirePerspectiveSavedAs(IWorkbenchPage::Pointer(this), oldDesc, newDesc); } /** * Save the state of the page. */ bool WorkbenchPage::SaveState(IMemento::Pointer memento) { // // We must unzoom to get correct layout. // if (isZoomed()) // { // zoomOut(); // } // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, NLS.bind( // WorkbenchMessages.WorkbenchPage_unableToSavePerspective, // getLabel()), 0); bool result = true; // Save editor manager. IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_EDITORS); //result.merge(editorMgr.saveState(childMem)); result &= editorMgr->SaveState(childMem); childMem = memento->CreateChild(WorkbenchConstants::TAG_VIEWS); //result.merge(getViewFactory().saveState(childMem)); result &= this->GetViewFactory()->SaveState(childMem); // Create persp block. childMem = memento->CreateChild(WorkbenchConstants::TAG_PERSPECTIVES); if (this->GetPerspective()) { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PERSPECTIVE, this->GetPerspective()->GetId()); } if (this->GetActivePart() != 0) { if (this->GetActivePart().Cast ()) { IViewReference::Pointer ref = this->GetReference(this->GetActivePart()).Cast(); if (ref) { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PART, ViewFactory::GetKey(ref)); } } else { childMem->PutString(WorkbenchConstants::TAG_ACTIVE_PART, this->GetActivePart()->GetSite()->GetId()); } } // Save each perspective in opened order for (PerspectiveList::PerspectiveListType::iterator itr = perspList.Begin(); itr != perspList.End(); ++itr) { IMemento::Pointer gChildMem = childMem->CreateChild( WorkbenchConstants::TAG_PERSPECTIVE); //result.merge(persp.saveState(gChildMem)); result &= (*itr)->SaveState(gChildMem); } // // Save working set if set // if (workingSet != 0) // { // memento.putString(IWorkbenchConstants.TAG_WORKING_SET, // workingSet .getName()); // } // // IMemento workingSetMem = memento .createChild( // IWorkbenchConstants.TAG_WORKING_SETS); // for (int i = 0; i < workingSets.length; i++) // { // workingSetMem.createChild(IWorkbenchConstants.TAG_WORKING_SET, // workingSets[i].getName()); // } // // if (aggregateWorkingSetId != 0) // { // memento.putString(ATT_AGGREGATE_WORKING_SET_ID, aggregateWorkingSetId); // } // // navigationHistory.saveState(memento .createChild( // IWorkbenchConstants.TAG_NAVIGATION_HISTORY)); // // save the sticky activation state stickyViewMan->Save(memento); return result; } QString WorkbenchPage::GetId(IWorkbenchPart::Pointer part) { return this->GetId(this->GetReference(part)); } QString WorkbenchPage::GetId(IWorkbenchPartReference::Pointer ref) { if (ref == 0) { return "0"; //$NON-NLS-1$ } return ref->GetId(); } void WorkbenchPage::SetActivePart(IWorkbenchPart::Pointer newPart) { // Optimize it. if (this->GetActivePart() == newPart) { return; } if (partBeingActivated != 0) { if (partBeingActivated->GetPart(false) != newPart) { WorkbenchPlugin::Log(ctkRuntimeException( QString("WARNING: Prevented recursive attempt to activate part ") + this->GetId(newPart) + " while still in the middle of activating part " + this->GetId( partBeingActivated))); } return; } //No need to change the history if the active editor is becoming the // active part // String label = 0; // debugging only // if (UIStats.isDebugging(UIStats.ACTIVATE_PART)) // { // label = newPart != 0 ? newPart.getTitle() : "none"; //$NON-NLS-1$ // } try { IWorkbenchPartReference::Pointer partref = this->GetReference(newPart); IWorkbenchPartReference::Pointer realPartRef; if (newPart != 0) { IWorkbenchPartSite::Pointer site = newPart->GetSite(); if (site.Cast () != 0) { realPartRef = site.Cast ()->GetPane()->GetPartReference(); } } partBeingActivated = realPartRef; //UIStats.start(UIStats.ACTIVATE_PART, label); // Notify perspective. It may deactivate fast view. Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { persp->PartActivated(newPart); } // Deactivate old part IWorkbenchPart::Pointer oldPart = this->GetActivePart(); if (oldPart != 0) { this->DeactivatePart(oldPart); } // Set active part. if (newPart != 0) { activationList->SetActive(newPart); if (newPart.Cast () != 0) { this->MakeActiveEditor(realPartRef.Cast ()); } } this->ActivatePart(newPart); actionSwitcher.UpdateActivePart(newPart); partList->SetActivePart(partref); } catch (std::exception& e) { partBeingActivated = 0; // Object blame = newPart == 0 ? (Object) this : newPart; // UIStats.end(UIStats.ACTIVATE_PART, blame, label); throw e; } partBeingActivated = 0; } void WorkbenchPage::SetEditorAreaVisible(bool showEditorArea) { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return; } if (showEditorArea == persp->IsEditorAreaVisible()) { return; } // // If parts change always update zoom. // if (isZoomed()) // { // zoomOut(); // } // Update editor area visibility. IWorkbenchPage::Pointer thisPage(this); if (showEditorArea) { persp->ShowEditorArea(); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_AREA_SHOW); } else { persp->HideEditorArea(); this->UpdateActivePart(); window->FirePerspectiveChanged(thisPage, this->GetPerspective(), CHANGE_EDITOR_AREA_HIDE); } } /** * Sets the layout of the page. Assumes the new perspective is not 0. * Keeps the active part if possible. Updates the window menubar and * toolbar if necessary. */ void WorkbenchPage::SetPerspective(Perspective::Pointer newPersp) { // Don't do anything if already active layout Perspective::Pointer oldPersp = this->GetActivePerspective(); if (oldPersp == newPersp) { return; } window->LargeUpdateStart(); std::exception exc; bool exceptionOccured = false; try { IWorkbenchPage::Pointer thisPage(this); if (oldPersp != 0) { // fire the pre-deactivate window->FirePerspectivePreDeactivate(thisPage, oldPersp->GetDesc()); } if (newPersp != 0) { bool status = newPersp->RestoreState(); if (!status) { QString title = "Restoring problems"; QString msg = "Unable to read workbench state."; QMessageBox::critical(reinterpret_cast(this->GetWorkbenchWindow()->GetShell()->GetControl()), title, msg); } } // Deactivate the old layout if (oldPersp != 0) { oldPersp->OnDeactivate(); // Notify listeners of deactivation window->FirePerspectiveDeactivated(thisPage, oldPersp->GetDesc()); } // Activate the new layout perspList.SetActive(newPersp); if (newPersp != 0) { newPersp->OnActivate(); // Notify listeners of activation window->FirePerspectiveActivated(thisPage, newPersp->GetDesc()); } this->UpdateVisibility(oldPersp, newPersp); // Update the window //TODO action sets //window->UpdateActionSets(); // Update sticky views stickyViewMan->Update(oldPersp, newPersp); } catch (std::exception& e) { exc = e; exceptionOccured = true; } window->LargeUpdateEnd(); if (newPersp == 0) { return; } IPerspectiveDescriptor::Pointer desc = newPersp->GetDesc(); if (desc == 0) { return; } if (dirtyPerspectives.erase(desc->GetId())) { this->SuggestReset(); } if (exceptionOccured) throw exc; } void WorkbenchPage::UpdateVisibility(Perspective::Pointer oldPersp, Perspective::Pointer newPersp) { // Flag all parts in the old perspective QList oldRefs; if (oldPersp != 0) { oldRefs = oldPersp->GetViewReferences(); for (int i = 0; i < oldRefs.size(); i++) { PartPane::Pointer pane = oldRefs[i].Cast ()->GetPane(); pane->SetInLayout(false); } } PerspectiveHelper* pres = 0; // Make parts in the new perspective visible if (newPersp != 0) { pres = newPersp->GetPresentation(); QList newRefs = newPersp->GetViewReferences(); for (int i = 0; i < newRefs.size(); i++) { WorkbenchPartReference::Pointer ref = newRefs[i].Cast< WorkbenchPartReference> (); PartPane::Pointer pane = ref->GetPane(); if (pres->IsPartVisible(ref)) { activationList->BringToTop(ref); } pane->SetInLayout(true); } } this->UpdateActivePart(); // Hide any parts in the old perspective that are no longer visible for (int i = 0; i < oldRefs.size(); i++) { WorkbenchPartReference::Pointer ref = oldRefs[i].Cast< WorkbenchPartReference> (); PartPane::Pointer pane = ref->GetPane(); if (pres == 0 || !pres->IsPartVisible(ref)) { pane->SetVisible(false); } } } /** * Sets the perspective. * * @param desc * identifies the new perspective. */ void WorkbenchPage::SetPerspective(IPerspectiveDescriptor::Pointer desc) { if (this->GetPerspective() == desc) { return; } // // Going from multiple to single rows can make the coolbar // // and its adjacent views appear jumpy as perspectives are // // switched. Turn off redraw to help with this. // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); std::exception exc; bool exceptionOccured = false; try { //mgr.getControl2().setRedraw(false); //getClientComposite().setRedraw(false); // Run op in busy cursor. // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { this->BusySetPerspective(desc); // } // }); } catch (std::exception& e) { exc = e; exceptionOccured = true; } // getClientComposite().setRedraw(true); // mgr.getControl2().setRedraw(true); IWorkbenchPart::Pointer part = this->GetActivePart(); if (part != 0) { part->SetFocus(); } if (exceptionOccured) throw exc; } PartService* WorkbenchPage::GetPartService() { return dynamic_cast (partList->GetPartService()); } void WorkbenchPage::ResetToolBarLayout() { // ICoolBarManager2 mgr = (ICoolBarManager2) window.getCoolBarManager2(); // mgr.resetItemOrder(); } IViewPart::Pointer WorkbenchPage::ShowView(const QString& viewID) { return this->ShowView(viewID, "", VIEW_ACTIVATE); } IViewPart::Pointer WorkbenchPage::ShowView(const QString& viewID, const QString& secondaryID, int mode) { if (secondaryID != "") { if (secondaryID.size() == 0 || secondaryID.indexOf(ViewFactory::ID_SEP) != -1) { throw ctkInvalidArgumentException( "Illegal secondary id (cannot be empty or contain a colon)"); } } if (!this->CertifyMode(mode)) { throw ctkInvalidArgumentException("Illegal view mode"); } // Run op in busy cursor. // BusyIndicator.showWhile(0, new Runnable() // { // public void WorkbenchPage::run() // { // try // { return this->BusyShowView(viewID, secondaryID, mode); // } catch (PartInitException& e) // { // result = e; // } // } // }); } bool WorkbenchPage::CertifyMode(int mode) { if (mode == VIEW_ACTIVATE || mode == VIEW_VISIBLE || mode == VIEW_CREATE) return true; return false; } QList WorkbenchPage::GetSortedEditors() { return activationList->GetEditors(); } QList WorkbenchPage::GetOpenPerspectives() { QList opened = perspList.GetOpenedPerspectives(); QList result; for (QList::iterator iter = opened.begin(); iter != opened.end(); ++iter) { result.push_back((*iter)->GetDesc()); } return result; } QList WorkbenchPage::GetOpenInternalPerspectives() { return perspList.GetOpenedPerspectives(); } Perspective::Pointer WorkbenchPage::GetFirstPerspectiveWithView( IViewPart::Pointer part) { QListIterator iter(perspList.GetSortedPerspectives()); iter.toBack(); while(iter.hasPrevious()) { Perspective::Pointer p = iter.previous(); if (p->ContainsView(part)) { return p; } }; // we should never get here return Perspective::Pointer(0); } QList WorkbenchPage::GetSortedPerspectives() { QList sortedArray = perspList.GetSortedPerspectives(); QList result; for (QList::iterator iter = sortedArray.begin(); iter != sortedArray.end(); ++iter) { result.push_back((*iter)->GetDesc()); } return result; } QList WorkbenchPage::GetSortedParts() { //return partList->GetParts(this->GetViewReferences()); return activationList->GetParts(); } IWorkbenchPartReference::Pointer WorkbenchPage::GetReference( IWorkbenchPart::Pointer part) { if (part == 0) { return IWorkbenchPartReference::Pointer(0); } IWorkbenchPartSite::Pointer site = part->GetSite(); if (site.Cast () == 0) { return IWorkbenchPartReference::Pointer(0); } PartSite::Pointer partSite = site.Cast (); PartPane::Pointer pane = partSite->GetPane(); return partSite->GetPartReference(); } // for dynamic UI void WorkbenchPage::AddPerspective(Perspective::Pointer persp) { perspList.Add(persp); IWorkbenchPage::Pointer thisPage(this); window->FirePerspectiveOpened(thisPage, persp->GetDesc()); } QList WorkbenchPage::GetViewReferenceStack( IViewPart::Pointer part) { // Sanity check. Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0 || !this->CertifyPart(part)) { return QList(); } ILayoutContainer::Pointer container = part->GetSite().Cast ()->GetPane()->GetContainer(); if (container.Cast () != 0) { PartStack::Pointer folder = container.Cast (); QList list; ILayoutContainer::ChildrenType children = folder->GetChildren(); for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { LayoutPart::Pointer stackablePart = *childIter; if (stackablePart.Cast () != 0) { IViewReference::Pointer view = stackablePart.Cast ()->GetPartReference().Cast< IViewReference> (); if (view != 0) { list.push_back(view); } } } // sort the list by activation order (most recently activated first) std::sort(list.begin(), list.end(), ActivationOrderPred(activationList)); return list; } QList result; result.push_back(this->GetReference(part).Cast ()); return result; } QList WorkbenchPage::GetViewStack( IViewPart::Pointer part) { QList refStack = this->GetViewReferenceStack( part); QList result; for (int i = 0; i < refStack.size(); i++) { IViewPart::Pointer next = refStack[i]->GetView(false); if (next != 0) { result.push_back(next); } } return result; } void WorkbenchPage::ResizeView(IViewPart::Pointer part, int width, int height) { SashInfo sashInfo; PartPane::Pointer pane = part->GetSite().Cast ()->GetPane(); ILayoutContainer::Pointer container = pane->GetContainer(); LayoutTree::Pointer tree = this->GetPerspectivePresentation()->GetLayout()->GetLayoutTree()->Find( container.Cast ()); // retrieve our layout sashes from the layout tree this->FindSashParts(tree, pane->FindSashes(), sashInfo); // first set the width int deltaWidth = width - pane->GetBounds().width(); if (sashInfo.right != 0) { QRect rightBounds = sashInfo.rightNode->GetBounds(); // set the new ratio sashInfo.right->SetRatio(static_cast((deltaWidth + sashInfo.right->GetBounds().x()) - rightBounds.x()) / rightBounds.width()); // complete the resize sashInfo.rightNode->SetBounds(rightBounds); } else if (sashInfo.left != 0) { QRect leftBounds = sashInfo.leftNode->GetBounds(); // set the ratio sashInfo.left->SetRatio(static_cast((sashInfo.left->GetBounds().x() - deltaWidth) - leftBounds.x()) / leftBounds.width()); // complete the resize sashInfo.leftNode->SetBounds(sashInfo.leftNode->GetBounds()); } // next set the height int deltaHeight = height - pane->GetBounds().height(); if (sashInfo.bottom != 0) { QRect bottomBounds = sashInfo.bottomNode->GetBounds(); // set the new ratio sashInfo.bottom->SetRatio(static_cast((deltaHeight + sashInfo.bottom->GetBounds().y()) - bottomBounds.y()) / bottomBounds.height()); // complete the resize sashInfo.bottomNode->SetBounds(bottomBounds); } else if (sashInfo.top != 0) { QRect topBounds = sashInfo.topNode->GetBounds(); // set the ratio sashInfo.top->SetRatio(static_cast((sashInfo.top->GetBounds().y() - deltaHeight) - topBounds.y()) / topBounds.height()); // complete the resize sashInfo.topNode->SetBounds(topBounds); } } void WorkbenchPage::FindSashParts(LayoutTree::Pointer tree, const PartPane::Sashes& sashes, SashInfo& info) { LayoutTree::Pointer parent(tree->GetParent()); if (parent == 0) { return; } if (parent->part.Cast () != 0) { // get the layout part sash from this tree node LayoutPartSash::Pointer sash = parent->part.Cast (); // make sure it has a sash control QWidget* control = sash->GetControl(); if (control != 0) { // check for a vertical sash if (sash->IsVertical()) { if (sashes.left == control) { info.left = sash; info.leftNode = parent->FindSash(sash); } else if (sashes.right == control) { info.right = sash; info.rightNode = parent->FindSash(sash); } } // check for a horizontal sash else { if (sashes.top == control) { info.top = sash; info.topNode = parent->FindSash(sash); } else if (sashes.bottom == control) { info.bottom = sash; info.bottomNode = parent->FindSash(sash); } } } } // recursive call to continue up the tree this->FindSashParts(parent, sashes, info); } QList WorkbenchPage::GetAllParts() { - QList views = viewFactory->GetViews(); + QList views = this->GetViewFactory()->GetViews(); QList editors = this->GetEditorReferences(); QList result; for (int i = 0; i < views.size(); i++) { result.push_back(views[i]); } for (QList::iterator iter = editors.begin(); iter != editors.end(); ++iter) { result.push_back(*iter); } return result; } QList WorkbenchPage::GetOpenParts() { QList refs = this->GetAllParts(); QList result; for (int i = 0; i < refs.size(); i++) { IWorkbenchPartReference::Pointer reference = refs[i]; IWorkbenchPart::Pointer part = reference->GetPart(false); if (part != 0) { result.push_back(reference); } } return result; } void WorkbenchPage::TestInvariants() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { persp->TestInvariants(); // When we have widgets, ensure that there is no situation where the editor area is visible // and the perspective doesn't want an editor area. if (this->GetClientComposite() && editorPresentation->GetLayoutPart()->IsVisible()) { poco_assert(persp->IsEditorAreaVisible()); } } } -/* (non-Javadoc) - * @see org.blueberry.ui.IWorkbenchPage#getExtensionTracker() - */ -// IExtensionTracker WorkbenchPage::GetExtensionTracker() -// { -// if (tracker == 0) -// { -// tracker = new UIExtensionTracker(getWorkbenchWindow().getWorkbench().getDisplay()); -// } -// return tracker; -// } +IExtensionTracker* WorkbenchPage::GetExtensionTracker() const +{ + if (tracker.isNull()) + { + tracker.reset(new UIExtensionTracker(GetWorkbenchWindow()->GetWorkbench()->GetDisplay())); + } + return tracker.data(); +} /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getPerspectiveShortcuts() */ QList WorkbenchPage::GetPerspectiveShortcuts() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return QList(); } return persp->GetPerspectiveShortcuts(); } QList WorkbenchPage::GetShowViewShortcuts() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return QList(); } return persp->GetShowViewShortcuts(); } void WorkbenchPage::SuggestReset() { IWorkbench* workbench = this->GetWorkbenchWindow()->GetWorkbench(); // workbench.getDisplay().asyncExec(new Runnable() // { // public void WorkbenchPage::run() // { Shell::Pointer parentShell; IWorkbenchWindow::Pointer window = workbench->GetActiveWorkbenchWindow(); if (window == 0) { if (workbench->GetWorkbenchWindowCount() == 0) { return; } window = workbench->GetWorkbenchWindows()[0]; } parentShell = window->GetShell(); if (QMessageBox::question(parentShell.IsNull() ? NULL : reinterpret_cast(parentShell->GetControl()), "Reset Perspective?", "Changes to installed plug-ins have affected this perspective. Would you like to reset this perspective to accept these changes?") == QMessageBox::Yes) { IWorkbenchPage::Pointer page = window->GetActivePage(); if (page == 0) { return; } page->ResetPerspective(); } // } // }); } bool WorkbenchPage::IsPartVisible( IWorkbenchPartReference::Pointer reference) { IWorkbenchPart::Pointer part = reference->GetPart(false); // Can't be visible if it isn't created yet if (part == 0) { return false; } return this->IsPartVisible(part); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h index cc8746e90e..e3eb3574d5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPage.h @@ -1,1813 +1,1433 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYWORKBENCHPAGE_H_ #define BERRYWORKBENCHPAGE_H_ #include #include "berryIWorkbenchPage.h" #include "berryIWorkbenchPartReference.h" #include "berryIReusableEditor.h" #include "berryILayoutContainer.h" #include "berryIStickyViewManager.h" #include "berryWorkbenchPagePartList.h" #include "berryWorkbenchPartReference.h" #include "berryPageSelectionService.h" #include "berryEditorManager.h" #include "berryViewFactory.h" #include "berryPartPane.h" #include namespace berry { struct IExtensionPoint; +struct IExtensionTracker; //class PartPane; //class PartPane::Sashes; class EditorAreaHelper; class WorkbenchWindow; class Perspective; class PerspectiveHelper; class PerspectiveDescriptor; class LayoutPartSash; class LayoutTree; class LayoutTreeNode; class PartService; /** * \ingroup org_blueberry_ui_internal * * A collection of views and editors in a workbench. */ class BERRY_UI_QT WorkbenchPage: public IWorkbenchPage { public: - berryObjectMacro(WorkbenchPage); + berryObjectMacro(WorkbenchPage) protected: //TODO Weakpointer WorkbenchWindow* window; friend class ViewFactory; friend class WorkbenchWindow; friend class EditorAreaHelper; friend class WWinPartService; private: /** * Manages editor contributions and action set part associations. */ class ActionSwitcher { - private: - IWorkbenchPart::WeakPtr activePart; + public: - IEditorPart::WeakPtr topEditor; + ActionSwitcher(WorkbenchPage* page); /** * Updates the contributions given the new part as the active part. * * @param newPart * the new active part, may be null */ - public: void UpdateActivePart(IWorkbenchPart::Pointer newPart); /** * Updates the contributions given the new part as the topEditor. * * @param newEditor * the new top editor, may be null */ - public: void UpdateTopEditor(IEditorPart::Pointer newEditor); + private: + /** * Activates the contributions of the given part. If enable * is true the contributions are visible and enabled, * otherwise they are disabled. * * @param part * the part whose contributions are to be activated * @param enable * true the contributions are to be enabled, * not just visible. */ - private: void ActivateContributions(IWorkbenchPart::Pointer part, bool enable); /** * Deactivates the contributions of the given part. If remove * is true the contributions are removed, otherwise they * are disabled. * * @param part * the part whose contributions are to be deactivated * @param remove * true the contributions are to be removed, * not just disabled. */ - private: void DeactivateContributions(IWorkbenchPart::Pointer part, bool remove); + WorkbenchPage* page; + + IWorkbenchPart::WeakPtr activePart; + + IEditorPart::WeakPtr topEditor; + }; class ActivationList { public: //List of parts in the activation order (oldest first) typedef std::deque PartListType; typedef std::deque::iterator PartListIter; typedef std::deque::reverse_iterator PartListReverseIter; private: PartListType parts; WorkbenchPage* page; public: ActivationList(WorkbenchPage* page); /* * Add/Move the active part to end of the list; */ void SetActive(SmartPointer part); /* * Ensures that the given part appears AFTER any other part in the same * container. */ void BringToTop(SmartPointer ref); /* * Returns the last (most recent) iterator (index) of the given container in the activation list, or returns * end() if the given container does not appear in the activation list. */ PartListIter LastIndexOfContainer(SmartPointer container); /* * Add/Move the active part to end of the list; */ void SetActive(SmartPointer ref); /* * Add the active part to the beginning of the list. */ void Add(SmartPointer ref); /* * Return the active part. Filter fast views. */ SmartPointer GetActive(); /* * Return the previously active part. Filter fast views. */ SmartPointer GetPreviouslyActive(); SmartPointer GetActiveReference(bool editorsOnly); /* * Retuns the index of the part within the activation list. The higher * the index, the more recently it was used. */ PartListIter IndexOf(SmartPointer part); /* * Returns the index of the part reference within the activation list. * The higher the index, the more recent it was used. */ PartListIter IndexOf(SmartPointer ref); /* * Remove a part from the list */ bool Remove(SmartPointer ref); /* * Returns the topmost editor on the stack, or null if none. */ SmartPointer GetTopEditor(); /* * Returns the editors in activation order (oldest first). */ QList > GetEditors(); /* * Return a list with all parts (editors and views). */ QList > GetParts(); private: SmartPointer GetActive(PartListIter start); SmartPointer GetActiveReference(PartListIter start, bool editorsOnly); /* * Find a part in the list starting from the end and filter * and views from other perspectives. Will filter fast views * unless 'includeActiveFastViews' is true; */ SmartPointer GetActiveReference(PartListIter start, bool editorsOnly, bool skipPartsObscuredByZoom); }; /** * Helper class to keep track of all opened perspective. Both the opened * and used order is kept. */ struct PerspectiveList { public: typedef QList > PerspectiveListType; typedef PerspectiveListType::iterator iterator; private: /** * List of perspectives in the order they were opened; */ PerspectiveListType openedList; /** * List of perspectives in the order they were used. Last element is * the most recently used, and first element is the least recently * used. */ PerspectiveListType usedList; /** * The perspective explicitly set as being the active one */ SmartPointer active; void UpdateActionSets(SmartPointer oldPersp, SmartPointer newPersp); public: /** * Creates an empty instance of the perspective list */ PerspectiveList(); /** * Update the order of the perspectives in the opened list * * @param perspective * @param newLoc */ void Reorder(IPerspectiveDescriptor::Pointer perspective, int newLoc); /** * Return all perspectives in the order they were activated. * * @return an array of perspectives sorted by activation order, least * recently activated perspective last. */ PerspectiveListType GetSortedPerspectives(); /** * Adds a perspective to the list. No check is done for a duplicate when * adding. * @param perspective the perspective to add * @return boolean true if the perspective was added */ bool Add(SmartPointer perspective); /** * Returns an iterator on the perspective list in the order they were * opened. */ PerspectiveListType::iterator Begin(); PerspectiveListType::iterator End(); /** * Returns an array with all opened perspectives */ PerspectiveListType GetOpenedPerspectives(); /** * Removes a perspective from the list. */ bool Remove(SmartPointer perspective); /** * Swap the opened order of old perspective with the new perspective. */ void Swap(SmartPointer oldPerspective, SmartPointer newPerspective); /** * Returns whether the list contains any perspectives */ bool IsEmpty(); /** * Returns the most recently used perspective in the list. */ SmartPointer GetActive(); /** * Returns the next most recently used perspective in the list. */ SmartPointer GetNextActive(); /** * Returns the number of perspectives opened */ PerspectiveListType::size_type Size(); /** * Marks the specified perspective as the most recently used one in the * list. */ void SetActive(SmartPointer perspective); }; IAdaptable* input; QWidget* composite; //Could be delete. This information is in the active part list; ActivationList* activationList; EditorManager* editorMgr; EditorAreaHelper* editorPresentation; //ListenerList propertyChangeListeners = new ListenerList(); PageSelectionService* selectionService; QScopedPointer partList; // = new WorkbenchPagePartList(selectionService); //IActionBars actionBars; ViewFactory* viewFactory; PerspectiveList perspList; SmartPointer deferredActivePersp; //NavigationHistory navigationHistory = new NavigationHistory(this); IStickyViewManager::Pointer stickyViewMan; /** * Returns true if perspective with given id contains view with given id */ bool HasView(const QString& perspectiveId, const QString& viewId); /** * If we're in the process of activating a part, this points to the new part. * Otherwise, this is null. */ IWorkbenchPartReference::Pointer partBeingActivated; /** * Contains a list of perspectives that may be dirty due to plugin * installation and removal. */ std::set dirtyPerspectives; ActionSwitcher actionSwitcher; - //IExtensionTracker tracker; + mutable QScopedPointer tracker; // Deferral count... delays disposing parts and sending certain events if nonzero int deferCount; // Parts waiting to be disposed QList pendingDisposals; SmartPointer GetPerspectiveExtensionPoint(); public: /** * Constructs a new page with a given perspective and input. * * @param w * the parent window * @param layoutID * must not be null * @param input * the page input * @throws WorkbenchException * on null layout id */ WorkbenchPage(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input); /** * Constructs a page. restoreState(IMemento) should be * called to restore this page from data stored in a persistance file. * * @param w * the parent window * @param input * the page input * @throws WorkbenchException */ WorkbenchPage(WorkbenchWindow* w, IAdaptable* input); ~WorkbenchPage(); /** * Activates a part. The part will be brought to the front and given focus. * * @param part * the part to activate */ void Activate(IWorkbenchPart::Pointer part); - /** - * Activates a part. The part is given focus, the pane is hilighted. - */ -private: - void ActivatePart(const IWorkbenchPart::Pointer part); - /** * Adds an IPartListener to the part service. */ -public: void AddPartListener(IPartListener* l); /* * (non-Javadoc) Method declared on ISelectionListener. */ -public: void AddSelectionListener(ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ -public: void AddSelectionListener(const QString& partId, ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ -public: void AddPostSelectionListener(ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ -public: void AddPostSelectionListener(const QString& partId, ISelectionListener* listener); + /** + * Moves a part forward in the Z order of a perspective so it is visible. + * If the part is in the same stack as the active part, the new part is + * activated. + * + * @param part + * the part to bring to move forward + */ + void BringToTop(IWorkbenchPart::Pointer part); + private: + + /** + * Activates a part. The part is given focus, the pane is hilighted. + */ + void ActivatePart(const IWorkbenchPart::Pointer part); + ILayoutContainer::Pointer GetContainer(IWorkbenchPart::Pointer part); -private: ILayoutContainer::Pointer GetContainer(IWorkbenchPartReference::Pointer part); -private: SmartPointer GetPane(IWorkbenchPart::Pointer part); -private: SmartPointer GetPane(IWorkbenchPartReference::Pointer part); /** * Brings a part to the front of its stack. Does not update the active part or * active editor. This should only be called if the caller knows that the part * is not in the same stack as the active part or active editor, or if the caller * is prepared to update activation after the call. * * @param part */ -private: bool InternalBringToTop(IWorkbenchPartReference::Pointer part); - /** - * Moves a part forward in the Z order of a perspective so it is visible. - * If the part is in the same stack as the active part, the new part is - * activated. - * - * @param part - * the part to bring to move forward - */ -public: - void BringToTop(IWorkbenchPart::Pointer part); - /** * Resets the layout for the perspective. The active part in the old layout * is activated in the new layout for consistent user context. * * Assumes the busy cursor is active. */ -private: void BusyResetPerspective(); /** * Implements setPerspective. * * Assumes that busy cursor is active. * * @param desc * identifies the new perspective. */ -private: void BusySetPerspective(IPerspectiveDescriptor::Pointer desc); + /* + * Performs showing of the view in the given mode. + */ + void BusyShowView(IViewPart::Pointer part, int mode); + /** - * Removes the perspective which match the given description. - * - * @param desc - * identifies the perspective to be removed. + * Returns whether a part exists in the current page. */ -public: - void RemovePerspective(IPerspectiveDescriptor::Pointer desc); + bool CertifyPart(IWorkbenchPart::Pointer part); + +protected: /** * Shows a view. * * Assumes that a busy cursor is active. */ -protected: IViewPart::Pointer BusyShowView(const QString& viewID, const QString& secondaryID, int mode); - /* - * Performs showing of the view in the given mode. - */ -private: - void BusyShowView(IViewPart::Pointer part, int mode); +public: + + void UpdateActionBars(); /** - * Returns whether a part exists in the current page. + * Removes the perspective which match the given description. + * + * @param desc + * identifies the perspective to be removed. */ -private: - bool CertifyPart(IWorkbenchPart::Pointer part); + void RemovePerspective(IPerspectiveDescriptor::Pointer desc); /** * Closes the perspective. */ -public: bool Close(); /** * See IWorkbenchPage */ -public: bool CloseAllSavedEditors(); /** * See IWorkbenchPage */ -public: bool CloseAllEditors(bool save); + /** + * See IWorkbenchPage + */ + bool CloseEditors(const QList& refArray, + bool save); + private: + void UpdateActivePart(); /** * Makes the given part active. Brings it in front if necessary. Permits null * (indicating that no part should be active). * - * @since 3.1 - * * @param ref new active part (or null) */ -private: void MakeActive(IWorkbenchPartReference::Pointer ref); /** * Makes the given editor active. Brings it to front if necessary. Permits null * (indicating that no editor is active). * - * @since 3.1 - * * @param ref the editor to make active, or null for no active editor */ -private: void MakeActiveEditor(IEditorReference::Pointer ref); - /** - * See IWorkbenchPage - */ -public: - bool CloseEditors(const QList& refArray, - bool save); - /** * Enables or disables listener notifications. This is used to delay listener notifications until the * end of a public method. * * @param shouldDefer */ -private: void DeferUpdates(bool shouldDefer); -private: void StartDeferring(); -private: void HandleDeferredEvents(); -private: bool IsDeferred(); +public: + /** * See IWorkbenchPage#closeEditor */ -public: bool CloseEditor(IEditorReference::Pointer editorRef, bool save); /** * See IWorkbenchPage#closeEditor */ -public: bool CloseEditor(IEditorPart::Pointer editor, bool save); /** * 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 */ -public: void CloseCurrentPerspective(bool saveParts, bool closePage); /** * @see IWorkbenchPage#closePerspective(IPerspectiveDescriptor, boolean, boolean) */ -public: void ClosePerspective(IPerspectiveDescriptor::Pointer desc, bool saveParts, bool closePage); + /** + * @see IWorkbenchPage#closeAllPerspectives(boolean, boolean) + */ + void CloseAllPerspectives(bool saveEditors, bool closePage); + +protected: + /** * Closes the specified perspective. If last perspective, then entire page * is closed. * * @param persp * the perspective to be closed * @param saveParts * whether the parts that are being closed should be saved * (editors if last perspective, views if not shown in other * parspectives) */ - /* package */ -protected: void ClosePerspective(SmartPointer persp, bool saveParts, bool closePage); /** - * @see IWorkbenchPage#closeAllPerspectives(boolean, boolean) + * This is called by child objects after a part has been added to the page. + * The page will in turn notify its listeners. */ -public: - void CloseAllPerspectives(bool saveEditors, bool closePage); + void PartAdded(WorkbenchPartReference::Pointer ref); /** - * Creates the client composite. + * This is called by child objects after a part has been added to the page. + * The part will be queued for disposal after all listeners have been notified */ + void PartRemoved(WorkbenchPartReference::Pointer ref); + private: + + /** + * Creates the client composite. + */ void CreateClientComposite(); /** * Creates a new view set. Return null on failure. * * @param desc the perspective descriptor * @param notify whether to fire a perspective opened event */ -private: SmartPointer CreatePerspective(SmartPointer desc, bool notify); - /** - * This is called by child objects after a part has been added to the page. - * The page will in turn notify its listeners. - */ - /* package */ -protected: - void PartAdded(WorkbenchPartReference::Pointer ref); - - /** - * This is called by child objects after a part has been added to the page. - * The part will be queued for disposal after all listeners have been notified - */ - /* package */ -protected: - void PartRemoved(WorkbenchPartReference::Pointer ref); - -private: void DisposePart(WorkbenchPartReference::Pointer ref); /** * Deactivates a part. The pane is unhilighted. */ -private: void DeactivatePart(IWorkbenchPart::Pointer part); /** - * Detaches a view from the WorkbenchWindow. + * Dispose a perspective. + * + * @param persp the perspective descriptor + * @param notify whether to fire a perspective closed event */ + void DisposePerspective(SmartPointer persp, bool notify); + public: - void DetachView(IViewReference::Pointer ref); /** - * Removes a detachedwindow. + * Detaches a view from the WorkbenchWindow. */ -public: - void AttachView(IViewReference::Pointer ref); + void DetachView(IViewReference::Pointer ref); /** - * Dispose a perspective. - * - * @param persp the perspective descriptor - * @param notify whether to fire a perspective closed event + * Removes a detachedwindow. */ -private: - void DisposePerspective(SmartPointer persp, bool notify); + void AttachView(IViewReference::Pointer ref); /** * Returns the first view manager with given ID. */ -public: SmartPointer FindPerspective(IPerspectiveDescriptor::Pointer desc); /** * See IWorkbenchPage@findView. */ -public: IViewPart::Pointer FindView(const QString& id); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage */ -public: IViewReference::Pointer FindViewReference(const QString& viewId); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage */ -public: IViewReference::Pointer FindViewReference(const QString& viewId, const QString& secondaryId); /** * Notify property change listeners about a property change. * * @param changeId * the change id * @param oldValue * old property value * @param newValue * new property value */ //private: void FirePropertyChange(String changeId, Object oldValue, // Object newValue) { // // UIListenerLogging.logPagePropertyChanged(this, changeId, oldValue, newValue); // // Object[] listeners = propertyChangeListeners.getListeners(); // PropertyChangeEvent event = new PropertyChangeEvent(this, changeId, // oldValue, newValue); // // for (int i = 0; i < listeners.length; i++) { // ((IPropertyChangeListener) listeners[i]).propertyChange(event); // } // } /** * @see IWorkbenchPage */ -public: IEditorPart::Pointer GetActiveEditor(); /** * Returns the reference for the active editor, or null * if there is no active editor. * * @return the active editor reference or null */ -public: IEditorReference::Pointer GetActiveEditorReference(); /* * (non-Javadoc) Method declared on IPartService */ -public: IWorkbenchPart::Pointer GetActivePart(); /* * (non-Javadoc) Method declared on IPartService */ -public: IWorkbenchPartReference::Pointer GetActivePartReference(); /** * Returns the active perspective for the page, null if * none. */ -public: SmartPointer GetActivePerspective(); /** * Returns the client composite. */ -public: QWidget* GetClientComposite(); // for dynamic UI - change access from private to protected // for testing purposes only, changed from protected to public /** * Answer the editor manager for this window. */ -public: EditorManager* GetEditorManager(); /** * Answer the perspective presentation. */ -public: PerspectiveHelper* GetPerspectivePresentation(); /** * Answer the editor presentation. */ -public: EditorAreaHelper* GetEditorPresentation(); /** * Allow access to the part service for this page ... used internally to * propogate certain types of events to the page part listeners. * @return the part service for this page. */ -public: PartService* GetPartService(); + PartService* GetPartService(); /** * See IWorkbenchPage. */ -public: QList GetEditors(); -public: QList GetDirtyEditors(); -public: QList GetDirtyParts(); /** * See IWorkbenchPage. */ -public: IEditorPart::Pointer FindEditor(IEditorInput::Pointer input); /** * See IWorkbenchPage. */ -public: QList FindEditors( IEditorInput::Pointer input, const QString& editorId, int matchFlags); /** * See IWorkbenchPage. */ -public: QList GetEditorReferences(); /** * @see IWorkbenchPage */ -public: IAdaptable* GetInput(); /** * Returns the page label. This is a combination of the page input and * active perspective. */ -public: QString GetLabel(); /** * Returns the perspective. */ -public: IPerspectiveDescriptor::Pointer GetPerspective(); /* * (non-Javadoc) Method declared on ISelectionService */ -public: ISelection::ConstPointer GetSelection() const; /* * (non-Javadoc) Method declared on ISelectionService */ -public: ISelection::ConstPointer GetSelection(const QString& partId); //public: // SelectionEvents& GetSelectionEvents(const QString& partId = ""); /* * Returns the view factory. */ -public: ViewFactory* GetViewFactory(); /** * See IWorkbenchPage. */ -public: QList GetViewReferences(); /** * See IWorkbenchPage. */ -public: QList GetViews(); +protected: + /** * Returns all view parts in the specified perspective * * @param persp the perspective * @return an array of view parts - * @since 3.1 */ /*package*/ -protected: QList GetViews(SmartPointer persp, bool restore); + /* package */ + void RefreshActiveView(); + +public: + /** * See IWorkbenchPage. */ -public: - IWorkbenchWindow::Pointer GetWorkbenchWindow(); + IWorkbenchWindow::Pointer GetWorkbenchWindow() const; /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#hideView(org.blueberry.ui.IViewReference) */ -public: void HideView(IViewReference::Pointer ref); - /* package */ -protected: - void RefreshActiveView(); - /** * See IPerspective */ -public: void HideView(IViewPart::Pointer view); +private: + /** * Initialize the page. * * @param w * the parent window * @param layoutID * may be null if restoring from file * @param input * the page input * @param openExtras * whether to process the perspective extras preference */ -private: void Init(WorkbenchWindow* w, const QString& layoutID, IAdaptable* input, bool openExtras); /** * Opens the perspectives specified in the PERSPECTIVE_BAR_EXTRAS preference (see bug 84226). */ public: void OpenPerspectiveExtras(); /** * See IWorkbenchPage. */ -public: bool IsPartVisible(IWorkbenchPart::Pointer part); /** * See IWorkbenchPage. */ -public: bool IsEditorAreaVisible(); /** * Returns whether the view is fast. */ -public: bool IsFastView(IViewReference::Pointer ref); /** * Return whether the view is closeable or not. * * @param ref the view reference to check. Must not be null. * @return true if the part is closeable. - * @since 3.1.1 */ -public: bool IsCloseable(IViewReference::Pointer ref); /** * Return whether the view is moveable or not. * * @param ref the view reference to check. Must not be null. * @return true if the part is moveable. - * @since 3.1.1 */ -public: bool IsMoveable(IViewReference::Pointer ref); /** * Returns whether the layout of the active * perspective is fixed. */ -public: bool IsFixedLayout(); +protected: + /** * Return true if the perspective has a dirty editor. */ -protected: bool IsSaveNeeded(); /** * This method is called when the page is activated. */ -protected: void OnActivate(); /** * This method is called when the page is deactivated. */ -protected: void OnDeactivate(); +public: + /** * See IWorkbenchPage. */ -public: - void - ReuseEditor(IReusableEditor::Pointer editor, IEditorInput::Pointer input); + void ReuseEditor(IReusableEditor::Pointer editor, IEditorInput::Pointer input); /** * See IWorkbenchPage. */ -public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID); /** * See IWorkbenchPage. */ -public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate); /** * See IWorkbenchPage. */ -public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags); /** * This is not public API but for use internally. editorState can be null. */ -public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState); /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * Opens a new editor using the given input and descriptor. (Normally, editors are opened using * an editor ID and an input.) */ -public: IEditorPart::Pointer OpenEditorFromDescriptor(IEditorInput::Pointer input, IEditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState); +private: + /** * @see #openEditor(IEditorInput, String, boolean, int) */ -private: IEditorPart::Pointer BusyOpenEditor(IEditorInput::Pointer input, const QString& editorID, bool activate, int matchFlags, IMemento::Pointer editorState); /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * See openEditorFromDescriptor(). */ -private: IEditorPart::Pointer BusyOpenEditorFromDescriptor( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState); - /** - * Do not call this method. Use busyOpenEditor. - * - * @see IWorkbenchPage#openEditor(IEditorInput, String, boolean) - */ -protected: - IEditorPart::Pointer BusyOpenEditorBatched(IEditorInput::Pointer input, - const QString& editorID, bool activate, int matchFlags, - IMemento::Pointer editorState); - /* * Added to fix Bug 178235 [EditorMgmt] DBCS 3.3 - Cannot open file with external program. * See openEditorFromDescriptor(). */ -private: IEditorPart::Pointer BusyOpenEditorFromDescriptorBatched( IEditorInput::Pointer input, EditorDescriptor::Pointer editorDescriptor, bool activate, IMemento::Pointer editorState); public: - void OpenEmptyTab(); -protected: - void ShowEditor(bool activate, IEditorPart::Pointer editor); + void OpenEmptyTab(); /** * See IWorkbenchPage. */ -public: bool IsEditorPinned(IEditorPart::Pointer editor); /** * Removes an IPartListener from the part service. */ -public: void RemovePartListener(IPartListener* l); /* * (non-Javadoc) Method declared on ISelectionListener. */ -public: void RemoveSelectionListener(ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ -public: void RemoveSelectionListener(const QString& partId, ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ -public: void RemovePostSelectionListener(ISelectionListener* listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ -public: void RemovePostSelectionListener(const QString& partId, ISelectionListener* listener); /** * This method is called when a part is activated by clicking within it. In * response, the part, the pane, and all of its actions will be activated. * * In the current design this method is invoked by the part pane when the * pane, the part, or any children gain focus. */ -public: void RequestActivation(IWorkbenchPart::Pointer part); /** * Resets the layout for the perspective. The active part in the old layout * is activated in the new layout for consistent user context. */ -public: void ResetPerspective(); /** * Restore this page from the memento and ensure that the active * perspective is equals the active descriptor otherwise create a new * perspective for that descriptor. If activeDescriptor is null active the * old perspective. */ -public: /*IStatus*/bool RestoreState(IMemento::Pointer memento, IPerspectiveDescriptor::Pointer activeDescriptor); /** * See IWorkbenchPage */ -public: bool SaveAllEditors(bool confirm); /** * @param confirm * @param addNonPartSources true if saveables from non-part sources should be saved too * @return false if the user cancelled * */ -public: bool SaveAllEditors(bool confirm, bool addNonPartSources); - /* - * Saves the workbench part. - */ -protected: - bool SavePart(ISaveablePart::Pointer saveable, IWorkbenchPart::Pointer part, - bool confirm); - /** * Saves an editors in the workbench. If confirm is true * the user is prompted to confirm the command. * * @param confirm * if user confirmation should be sought * @return true if the command succeeded, or false * if the user cancels the command */ -public: bool SaveEditor(IEditorPart::Pointer editor, bool confirm); /** * Saves the current perspective. */ -public: void SavePerspective(); /** * Saves the perspective. */ -public: void SavePerspectiveAs(IPerspectiveDescriptor::Pointer newDesc); /** * Save the state of the page. */ -public: /*IStatus*/bool SaveState(IMemento::Pointer memento); -private: - QString GetId(IWorkbenchPart::Pointer part); - -private: - QString GetId(IWorkbenchPartReference::Pointer ref); - - /** - * Sets the active part. - */ -private: - void SetActivePart(IWorkbenchPart::Pointer newPart); - /** * See IWorkbenchPage. */ -public: void SetEditorAreaVisible(bool showEditorArea); - /** - * Sets the layout of the page. Assumes the new perspective is not null. - * Keeps the active part if possible. Updates the window menubar and - * toolbar if necessary. - */ -private: - void SetPerspective(SmartPointer newPersp); - - /* - * Update visibility state of all views. - */ -private: - void UpdateVisibility(SmartPointer oldPersp, - SmartPointer newPersp); - /** * Sets the perspective. * * @param desc * identifies the new perspective. */ -public: void SetPerspective(IPerspectiveDescriptor::Pointer desc); - /** - * Restore the toolbar layout for the active perspective. - */ -protected: - void ResetToolBarLayout(); - /** * See IWorkbenchPage. */ -public: IViewPart::Pointer ShowView(const QString& viewID); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#showView(java.lang.String, * java.lang.String, int) */ -public: IViewPart::Pointer ShowView(const QString& viewID, const QString& secondaryID, int mode); - /** - * @param mode the mode to test - * @return whether the mode is recognized - * @since 3.0 - */ -private: - bool CertifyMode(int mode); /* * Returns the editors in activation order (oldest first). */ -public: QList GetSortedEditors(); /** * @see IWorkbenchPage#getOpenPerspectives() */ -public: QList GetOpenPerspectives(); +protected: + + /** + * Do not call this method. Use busyOpenEditor. + * + * @see IWorkbenchPage#openEditor(IEditorInput, String, boolean) + */ + IEditorPart::Pointer BusyOpenEditorBatched(IEditorInput::Pointer input, + const QString& editorID, bool activate, int matchFlags, + IMemento::Pointer editorState); + + void ShowEditor(bool activate, IEditorPart::Pointer editor); + + /* + * Saves the workbench part. + */ + bool SavePart(ISaveablePart::Pointer saveable, IWorkbenchPart::Pointer part, + bool confirm); + + /** + * Restore the toolbar layout for the active perspective. + */ + void ResetToolBarLayout(); + /** * Return all open Perspective objects. * * @return all open Perspective objects - * @since 3.1 */ /*package*/ -protected: QList > GetOpenInternalPerspectives(); /** * Checks perspectives in the order they were activiated * for the specfied part. The first sorted perspective * that contains the specified part is returned. * * @param part specified part to search for * @return the first sorted perspespective containing the part - * @since 3.1 */ /*package*/ -protected: SmartPointer GetFirstPerspectiveWithView(IViewPart::Pointer part); + // for dynamic UI + void AddPerspective(SmartPointer persp); + +public: + /** * Returns the perspectives in activation order (oldest first). */ -public: QList GetSortedPerspectives(); /* * Returns the parts in activation order (oldest first). */ -public: QList GetSortedParts(); /** * Returns the reference to the given part, or null if it has no reference * (i.e. it is not a top-level part in this workbench page). * * @param part the part * @return the part's reference or null if the given part does not belong * to this workbench page */ -public: IWorkbenchPartReference::Pointer GetReference(IWorkbenchPart::Pointer part); - // private: class ActivationList { - // //List of parts in the activation order (oldest first) - // List parts = new ArrayList(); - // - // /* - // * Add/Move the active part to end of the list; - // */ - // void setActive(IWorkbenchPart part) { - // if (parts.size() <= 0) { - // return; - // } - // IWorkbenchPartReference ref = getReference(part); - // if (ref != null) { - // if (ref == parts.get(parts.size() - 1)) { - // return; - // } - // parts.remove(ref); - // parts.add(ref); - // } - // } - // - // /* - // * Ensures that the given part appears AFTER any other part in the same - // * container. - // */ - // void bringToTop(IWorkbenchPartReference ref) { - // ILayoutContainer targetContainer = getContainer(ref); - // - // int newIndex = lastIndexOfContainer(targetContainer); - // - // //New index can be -1 if there is no last index - // if (newIndex >= 0 && ref == parts.get(newIndex)) - // return; - // - // parts.remove(ref); - // if(newIndex >= 0) - // parts.add(newIndex, ref); - // else - // parts.add(ref); - // } - // - // /* - // * 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. - // */ - // int lastIndexOfContainer(ILayoutContainer container) { - // for (int i = parts.size() - 1; i >= 0; i--) { - // IWorkbenchPartReference ref = (IWorkbenchPartReference)parts.get(i); - // - // ILayoutContainer cnt = getContainer(ref); - // if (cnt == container) { - // return i; - // } - // } - // - // return -1; - // } - // - // /* - // * Add/Move the active part to end of the list; - // */ - // void setActive(IWorkbenchPartReference ref) { - // setActive(ref.getPart(true)); - // } - // - // /* - // * Add the active part to the beginning of the list. - // */ - // void add(IWorkbenchPartReference ref) { - // if (parts.indexOf(ref) >= 0) { - // return; - // } - // - // IWorkbenchPart part = ref.getPart(false); - // if (part != null) { - // PartPane pane = ((PartSite) part.getSite()).getPane(); - // if (pane instanceof MultiEditorInnerPane) { - // MultiEditorInnerPane innerPane = (MultiEditorInnerPane) pane; - // add(innerPane.getParentPane().getPartReference()); - // return; - // } - // } - // parts.add(0, ref); - // } - // - // /* - // * Return the active part. Filter fast views. - // */ - // IWorkbenchPart getActive() { - // if (parts.isEmpty()) { - // return null; - // } - // return getActive(parts.size() - 1); - // } - // - // /* - // * Return the previously active part. Filter fast views. - // */ - // IWorkbenchPart getPreviouslyActive() { - // if (parts.size() < 2) { - // return null; - // } - // return getActive(parts.size() - 2); - // } - // - // private: IWorkbenchPart getActive(int start) { - // IWorkbenchPartReference ref = getActiveReference(start, false); - // - // if (ref == null) { - // return null; - // } - // - // return ref.getPart(true); - // } - // - // public: IWorkbenchPartReference getActiveReference(boolean editorsOnly) { - // return getActiveReference(parts.size() - 1, editorsOnly); - // } - // - // private: IWorkbenchPartReference getActiveReference(int start, boolean editorsOnly) { - // // First look for parts that aren't obscured by the current zoom state - // IWorkbenchPartReference nonObscured = getActiveReference(start, editorsOnly, true); - // - // if (nonObscured != null) { - // return nonObscured; - // } - // - // // Now try all the rest of the parts - // return getActiveReference(start, editorsOnly, false); - // } - // - // /* - // * Find a part in the list starting from the end and filter - // * and views from other perspectives. Will filter fast views - // * unless 'includeActiveFastViews' is true; - // */ - // private: IWorkbenchPartReference getActiveReference(int start, boolean editorsOnly, boolean skipPartsObscuredByZoom) { - // IWorkbenchPartReference[] views = getViewReferences(); - // for (int i = start; i >= 0; i--) { - // WorkbenchPartReference ref = (WorkbenchPartReference) parts - // .get(i); - // - // if (editorsOnly && !(ref instanceof IEditorReference)) { - // continue; - // } - // - // // Skip parts whose containers have disabled auto-focus - // PartPane pane = ref.getPane(); - // - // if (pane != null) { - // if (!pane.allowsAutoFocus()) { - // continue; - // } - // - // if (skipPartsObscuredByZoom) { - // if (pane.isObscuredByZoom()) { - // continue; - // } - // } - // } - // - // // Skip fastviews (unless overridden) - // if (ref instanceof IViewReference) { - // if (ref == getActiveFastView() || !((IViewReference) ref).isFastView()) { - // for (int j = 0; j < views.length; j++) { - // if (views[j] == ref) { - // return ref; - // } - // } - // } - // } else { - // return ref; - // } - // } - // return null; - // } - // - // /* - // * Retuns the index of the part within the activation list. The higher - // * the index, the more recently it was used. - // */ - // int indexOf(IWorkbenchPart part) { - // IWorkbenchPartReference ref = getReference(part); - // if (ref == null) { - // return -1; - // } - // return parts.indexOf(ref); - // } - // - // /* - // * Returns the index of the part reference within the activation list. - // * The higher the index, the more recent it was used. - // */ - // int indexOf(IWorkbenchPartReference ref) { - // return parts.indexOf(ref); - // } - // - // /* - // * Remove a part from the list - // */ - // boolean remove(IWorkbenchPartReference ref) { - // return parts.remove(ref); - // } - // - // /* - // * Returns the editors in activation order (oldest first). - // */ - // private: IEditorReference[] getEditors() { - // ArrayList editors = new ArrayList(parts.size()); - // for (Iterator i = parts.iterator(); i.hasNext();) { - // IWorkbenchPartReference part = (IWorkbenchPartReference) i - // .next(); - // if (part instanceof IEditorReference) { - // editors.add(part); - // } - // } - // return (IEditorReference[]) editors - // .toArray(new IEditorReference[editors.size()]); - // } - // - // /* - // * Return a list with all parts (editors and views). - // */ - // private: IWorkbenchPartReference[] getParts() { - // IWorkbenchPartReference[] views = getViewReferences(); - // ArrayList resultList = new ArrayList(parts.size()); - // for (Iterator iterator = parts.iterator(); iterator.hasNext();) { - // IWorkbenchPartReference ref = (IWorkbenchPartReference) iterator - // .next(); - // if (ref instanceof IViewReference) { - // //Filter views from other perspectives - // for (int i = 0; i < views.length; i++) { - // if (views[i] == ref) { - // resultList.add(ref); - // break; - // } - // } - // } else { - // resultList.add(ref); - // } - // } - // IWorkbenchPartReference[] result = new IWorkbenchPartReference[resultList - // .size()]; - // return (IWorkbenchPartReference[]) resultList.toArray(result); - // } - // - // /* - // * Returns the topmost editor on the stack, or null if none. - // */ - // IEditorPart getTopEditor() { - // IEditorReference editor = (IEditorReference)getActiveReference(parts.size() - 1, true); - // - // if (editor == null) { - // return null; - // } - // - // return editor.getEditor(true); - // } - // }; - - - // for dynamic UI -protected: - void AddPerspective(SmartPointer persp); - - /** - * Find the stack of view references stacked with this view part. - * - * @param part - * the part - * @return the stack of references - * @since 3.0 - */ -private: - QList GetViewReferenceStack( - IViewPart::Pointer part); - /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getViewStack(org.blueberry.ui.IViewPart) */ -public: QList GetViewStack(IViewPart::Pointer part); /** * Allow for programmatically resizing a part. *

* EXPERIMENTAL *

*

* Known limitations: *

    *
  • currently applies only to views
  • *
  • has no effect when view is zoomed
  • *
*/ -public: void ResizeView(IViewPart::Pointer part, int width, int height); + /** + * Sanity-checks the objects in this page. Throws an Assertation exception + * if an object's internal state is invalid. ONLY INTENDED FOR USE IN THE + * UI TEST SUITES. + */ + void TestInvariants(); + + IExtensionTracker* GetExtensionTracker() const; + + /* + * (non-Javadoc) + * + * @see org.blueberry.ui.IWorkbenchPage#getPerspectiveShortcuts() + */ + QList GetPerspectiveShortcuts(); + + /* + * (non-Javadoc) + * + * @see org.blueberry.ui.IWorkbenchPage#getShowViewShortcuts() + */ + QList GetShowViewShortcuts(); + + bool IsPartVisible(IWorkbenchPartReference::Pointer reference); + private: + QString GetId(IWorkbenchPart::Pointer part); + + QString GetId(IWorkbenchPartReference::Pointer ref); + + /** + * Sets the active part. + */ + void SetActivePart(IWorkbenchPart::Pointer newPart); + + /** + * Sets the layout of the page. Assumes the new perspective is not null. + * Keeps the active part if possible. Updates the window menubar and + * toolbar if necessary. + */ + void SetPerspective(SmartPointer newPersp); + + /* + * Update visibility state of all views. + */ + void UpdateVisibility(SmartPointer oldPersp, + SmartPointer newPersp); + + /** + * @param mode the mode to test + * @return whether the mode is recognized + */ + bool CertifyMode(int mode); + + /** + * Find the stack of view references stacked with this view part. + * + * @param part + * the part + * @return the stack of references + */ + QList GetViewReferenceStack( + IViewPart::Pointer part); + struct ActivationOrderPred : std::binary_function { ActivationOrderPred(ActivationList* partList); ActivationList* activationList; bool operator()(const IViewReference::Pointer o1, const IViewReference::Pointer o2) const; }; // provides sash information for the given pane struct SashInfo { SmartPointer right; SmartPointer left; SmartPointer top; SmartPointer bottom; SmartPointer rightNode; SmartPointer leftNode; SmartPointer topNode; SmartPointer bottomNode; }; void FindSashParts(SmartPointer tree, const PartPane::Sashes& sashes, SashInfo& info); +protected: + /** * Returns all parts that are owned by this page * * @return */ -protected: QList GetAllParts(); /** * Returns all open parts that are owned by this page (that is, all parts * for which a part opened event would have been sent -- these would be * activated parts whose controls have already been created. */ -protected: QList GetOpenParts(); - /** - * Sanity-checks the objects in this page. Throws an Assertation exception - * if an object's internal state is invalid. ONLY INTENDED FOR USE IN THE - * UI TEST SUITES. - */ -public: - void TestInvariants(); - - /* (non-Javadoc) - * @see org.blueberry.ui.IWorkbenchPage#getExtensionTracker() - */ - //public: IExtensionTracker GetExtensionTracker(); - - /* - * (non-Javadoc) - * - * @see org.blueberry.ui.IWorkbenchPage#getPerspectiveShortcuts() - */ -public: - QList GetPerspectiveShortcuts(); - - /* - * (non-Javadoc) - * - * @see org.blueberry.ui.IWorkbenchPage#getShowViewShortcuts() - */ -public: - QList GetShowViewShortcuts(); - - /** - * @since 3.1 - */ private: - void SuggestReset(); -public: - bool IsPartVisible(IWorkbenchPartReference::Pointer reference); + void SuggestReset(); }; } #endif /*BERRYWORKBENCHPAGE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPagePartList.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPagePartList.h index 1c0d198b00..f2ab95a6b9 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPagePartList.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPagePartList.h @@ -1,80 +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 BERRYWORKBENCHPAGEPARTLIST_H_ #define BERRYWORKBENCHPAGEPARTLIST_H_ #include #include "berryPartList.h" #include "berryPartService.h" #include "berryPageSelectionService.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * */ class WorkbenchPagePartList : public PartList { -public: - - berryObjectMacro(WorkbenchPagePartList) - private: PageSelectionService* selectionService; PartService partService; // = new PartService(UIListenerLogging.PAGE_PARTLISTENER_EVENTS, //UIListenerLogging.PAGE_PARTLISTENER2_EVENTS); protected: void FirePartOpened(IWorkbenchPartReference::Pointer part); void FirePartClosed(IWorkbenchPartReference::Pointer part); void FirePartAdded(IWorkbenchPartReference::Pointer part); void FirePartRemoved(IWorkbenchPartReference::Pointer part); void FireActiveEditorChanged(IWorkbenchPartReference::Pointer ref); void FireActivePartChanged(IWorkbenchPartReference::Pointer oldRef, IWorkbenchPartReference::Pointer newRef); void FirePartHidden(IWorkbenchPartReference::Pointer ref); void FirePartVisible(IWorkbenchPartReference::Pointer ref); void FirePartInputChanged(IWorkbenchPartReference::Pointer ref); public: WorkbenchPagePartList(PageSelectionService* selectionService); IPartService* GetPartService(); void FirePartBroughtToTop(IWorkbenchPartReference::Pointer ref); }; } #endif /*BERRYWORKBENCHPAGEPARTLIST_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp index 576ba5785b..d1dc4a79a4 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.cpp @@ -1,393 +1,471 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryWorkbenchPlugin.h" #include "berryWorkbenchRegistryConstants.h" #include "berryWorkbench.h" #include "berryPlatform.h" #include "intro/berryEditorIntroAdapterPart.h" #include "defaultpresentation/berryQtWorkbenchPresentationFactory.h" #include "berryQtStyleManager.h" +#include "berryExtensionFactory.h" #include "berryQtWorkbenchTweaklet.h" #include "berryQtWorkbenchPageTweaklet.h" #include "berryQtWidgetsTweaklet.h" +#include "dialogs/berryPerspectivesPreferencePage.h" #include "berryQtStylePreferencePage.h" #include "berryStatusUtil.h" #include "berryHandlerServiceFactory.h" #include "berryMenuServiceFactory.h" #include "berryCommandServiceFactory.h" #include "berryWorkbenchSourceProvider.h" #include "berryObjectString.h" #include "berryObjects.h" - -#include "berryShowViewHandler.h" +#include "berryPolicy.h" +#include "berryHandlerAuthority.h" + +#include "berryOpenPerspectivePropertyTester.h" +#include "berryPerspectiveParameterValues.h" + +#include "handlers/berryCloseAllPerspectivesHandler.h" +#include "handlers/berryClosePerspectiveHandler.h" +#include "handlers/berryDynamicHelpHandler.h" +#include "handlers/berryHelpContentsHandler.h" +#include "handlers/berryIntroHandler.h" +#include "handlers/berryOpenInNewWindowHandler.h" +#include "handlers/berryNewEditorHandler.h" +#include "handlers/berryQuitHandler.h" +#include "handlers/berryResetPerspectiveHandler.h" +#include "handlers/berrySavePerspectiveHandler.h" +#include "handlers/berryShowPerspectiveHandler.h" +#include "handlers/berryShowViewHandler.h" #include "berryIQtStyleManager.h" #include "berryIContributor.h" #include "berryILog.h" +#include "berryIElementFactory.h" #include "berryIExtension.h" #include namespace berry { bool WorkbenchPlugin::DEBUG = false; char WorkbenchPlugin::PREFERENCE_PAGE_CATEGORY_SEPARATOR = '/'; WorkbenchPlugin* WorkbenchPlugin::inst = 0; WorkbenchPlugin::WorkbenchPlugin() : AbstractUICTKPlugin() { inst = this; presentationFactory = 0; editorRegistry = 0; viewRegistry = 0; perspRegistry = 0; introRegistry = 0; } WorkbenchPlugin::~WorkbenchPlugin() { delete presentationFactory; delete editorRegistry; delete viewRegistry; delete perspRegistry; delete introRegistry; inst = 0; } bool WorkbenchPlugin::HasExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName) { if (!element->GetAttribute(extensionName).isNull()) return true; QString elementText = element->GetValue(); if (!elementText.isEmpty()) return true; QList children(element->GetChildren(extensionName)); if (children.size() == 1) { if (!(children[0]->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS).isNull())) return true; } return false; } bool WorkbenchPlugin::IsBundleLoadedForExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName) { QSharedPointer plugin = WorkbenchPlugin::GetBundleForExecutableExtension(element, extensionName); if (plugin.isNull()) return true; return plugin->getState() == ctkPlugin::ACTIVE; } QSharedPointer WorkbenchPlugin::GetBundleForExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName) { // this code is derived heavily from // ConfigurationElement.createExecutableExtension. QString prop; QString executable; QString contributorName; int i = 0; if (!extensionName.isNull()) prop = element->GetAttribute(extensionName); else { // property not specified, try as element value prop = element->GetValue(); if (!prop.isNull()) { prop = prop.trimmed(); if (prop.isEmpty()) prop = QString(); } } if (prop.isNull()) { // property not defined, try as a child element QList exec(element->GetChildren(extensionName)); if (!exec.isEmpty()) contributorName = exec[0]->GetAttribute("plugin"); } else { // simple property or element value, parse it into its components i = prop.indexOf(':'); if (i != -1) executable = prop.left(i).trimmed(); else executable = prop; i = executable.indexOf('/'); if (i != -1) contributorName = executable.left(i).trimmed(); } if (contributorName.isNull()) contributorName = element->GetContributor()->GetName(); return Platform::GetPlugin(contributorName); } WorkbenchPlugin* WorkbenchPlugin::GetDefault() { return inst; } std::size_t WorkbenchPlugin::GetBundleCount() { // TODO BundleContext GetBundles //return bundleContext->GetBundles().size(); return 0; } - -// ImageRegistry createImageRegistry() { -// return WorkbenchImages.getImageRegistry(); -// } - - -IPerspectiveRegistry* WorkbenchPlugin::GetPerspectiveRegistry() { - if (perspRegistry == 0) { +IPerspectiveRegistry* WorkbenchPlugin::GetPerspectiveRegistry() +{ + if (perspRegistry == 0) + { perspRegistry = new PerspectiveRegistry(); - // the load methods can touch on WorkbenchImages if an image is - // missing so we need to wrap the call in - // a startup block for the case where a custom descriptor exists on - // startup that does not have an image - // associated with it. See bug 196352. - //StartupThreading.runWithoutExceptions(new StartupRunnable() { - // public void runWithException() throws Throwable { - perspRegistry->Load(); - // } - //}); - + // the load methods can touch on WorkbenchImages if an image is + // missing so we need to wrap the call in + // a startup block for the case where a custom descriptor exists on + // startup that does not have an image + // associated with it. See bug 196352. + //StartupThreading.runWithoutExceptions(new StartupRunnable() { + // public void runWithException() throws Throwable { + perspRegistry->Load(); + // } + //}); } return perspRegistry; } - // PreferenceManager getPreferenceManager() { // if (preferenceManager == null) { // preferenceManager = new WorkbenchPreferenceManager( // PREFERENCE_PAGE_CATEGORY_SEPARATOR); // // //Get the pages from the registry // PreferencePageRegistryReader registryReader = new PreferencePageRegistryReader( // getWorkbench()); // registryReader // .loadFromRegistry(Platform.getExtensionRegistry()); // preferenceManager.addPages(registryReader.getTopLevelNodes()); // // } // return preferenceManager; // } - -// ISharedImages getSharedImages() { -// if (sharedImages == null) { -// sharedImages = new SharedImages(); -// } -// return sharedImages; -// } - IIntroRegistry* WorkbenchPlugin::GetIntroRegistry() { if (introRegistry == 0) { introRegistry = new IntroRegistry(); } return introRegistry; } IViewRegistry* WorkbenchPlugin::GetViewRegistry() { if (!viewRegistry) viewRegistry = new ViewRegistry(); return viewRegistry; } IEditorRegistry* WorkbenchPlugin::GetEditorRegistry() { if (!editorRegistry) editorRegistry = new EditorRegistry(); return editorRegistry; } +IElementFactory* WorkbenchPlugin::GetElementFactory(const QString& targetID) const +{ + // Get the extension point registry. + IExtensionPoint::Pointer extensionPoint = Platform::GetExtensionRegistry()->GetExtensionPoint( + PlatformUI::PLUGIN_ID(), + WorkbenchRegistryConstants::PL_ELEMENT_FACTORY); + + IElementFactory* factory = nullptr; + if (!extensionPoint) + { + WorkbenchPlugin::Log("Unable to find element factory. Extension point: " + + WorkbenchRegistryConstants::PL_ELEMENT_FACTORY + " not found"); + return factory; + } + + // Loop through the config elements. + IConfigurationElement::Pointer targetElement; + QList configElements = + extensionPoint->GetConfigurationElements(); + for (int j = 0; j < configElements.size(); j++) + { + QString strID = configElements[j]->GetAttribute("id"); + if (targetID == strID) + { + targetElement = configElements[j]; + break; + } + } + if (!targetElement) + { + // log it since we cannot safely display a dialog. + WorkbenchPlugin::Log("Unable to find element factory: " + targetID); + return factory; + } + + // Create the extension. + try + { + factory = targetElement->CreateExecutableExtension("class"); + } + catch (const CoreException& e) + { + // log it since we cannot safely display a dialog. + WorkbenchPlugin::Log("Unable to create element factory.", e.GetStatus()); + factory = nullptr; + } + return factory; +} + IPresentationFactory* WorkbenchPlugin::GetPresentationFactory() { if (presentationFactory != 0) return presentationFactory; QString targetID = Workbench::GetInstance()->GetPresentationId(); presentationFactory = this->CreateExtension( - WorkbenchRegistryConstants::PL_PRESENTATION_FACTORIES, - "factory", targetID); + WorkbenchRegistryConstants::PL_PRESENTATION_FACTORIES, + "factory", targetID); if (presentationFactory == 0) WorkbenchPlugin::Log("Error creating presentation factory: " + - targetID + " -- class is not an IPresentationFactory"); + targetID + " -- class is not an IPresentationFactory"); return presentationFactory; } void WorkbenchPlugin::Log(const QString& message) { BERRY_INFO << "LOG: " << message << std::endl; //inst->GetLog().log(message); } void WorkbenchPlugin::Log(const ctkException &exc) { QString str; QDebug dbg(&str); dbg << exc.printStackTrace(); BERRY_INFO << "LOG: " << str << std::endl; //inst->GetLog().log(exc); } void WorkbenchPlugin::Log(const QString& message, const ctkException &t) { PlatformException exc(message, t); WorkbenchPlugin::Log(exc); } void WorkbenchPlugin::Log(const QString& clazz, const QString& methodName, const ctkException &t) { QString msg = QString("Exception in ") + clazz + "." + methodName + ": " - + t.what(); + + t.what(); WorkbenchPlugin::Log(msg, t); } void WorkbenchPlugin::Log(const QString& message, const SmartPointer& status) { //1FTUHE0: ITPCORE:ALL - API - Status & logging - loss of semantic info if (!message.isEmpty()) { GetDefault()->GetLog()->Log(StatusUtil::NewStatus(IStatus::ERROR_TYPE, message, BERRY_STATUS_LOC)); } GetDefault()->GetLog()->Log(status); } void WorkbenchPlugin::Log(const SmartPointer& status) { GetDefault()->GetLog()->Log(status); } void WorkbenchPlugin::start(ctkPluginContext* context) { //context.addBundleListener(getBundleListener()); AbstractUICTKPlugin::start(context); bundleContext = context; + AbstractSourceProvider::DEBUG = Policy::DEBUG_SOURCES(); + + HandlerAuthority::DEBUG = Policy::DEBUG_HANDLERS(); + HandlerAuthority::DEBUG_PERFORMANCE = Policy::DEBUG_HANDLERS_PERFORMANCE(); + HandlerAuthority::DEBUG_VERBOSE = Policy::DEBUG_HANDLERS_VERBOSE(); + HandlerAuthority::DEBUG_VERBOSE_COMMAND_ID = Policy::DEBUG_HANDLERS_VERBOSE_COMMAND_ID(); + BERRY_REGISTER_EXTENSION_CLASS(EditorIntroAdapterPart, context) + BERRY_REGISTER_EXTENSION_CLASS(ExtensionFactory, context) + BERRY_REGISTER_EXTENSION_CLASS(QtWidgetsTweaklet, context) BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchTweaklet, context) BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchPageTweaklet, context) BERRY_REGISTER_EXTENSION_CLASS(QtWorkbenchPresentationFactory, context) + BERRY_REGISTER_EXTENSION_CLASS(PerspectivesPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QtStylePreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(HandlerServiceFactory, context) BERRY_REGISTER_EXTENSION_CLASS(MenuServiceFactory, context) BERRY_REGISTER_EXTENSION_CLASS(CommandServiceFactory, context) BERRY_REGISTER_EXTENSION_CLASS(WorkbenchSourceProvider, context) + BERRY_REGISTER_EXTENSION_CLASS(OpenPerspectivePropertyTester, context) + BERRY_REGISTER_EXTENSION_CLASS(PerspectiveParameterValues, context) + + BERRY_REGISTER_EXTENSION_CLASS(HelpContentsHandler, context) + BERRY_REGISTER_EXTENSION_CLASS(DynamicHelpHandler, context) + BERRY_REGISTER_EXTENSION_CLASS(IntroHandler, context) + BERRY_REGISTER_EXTENSION_CLASS(OpenInNewWindowHandler, context) + BERRY_REGISTER_EXTENSION_CLASS(NewEditorHandler, context) + BERRY_REGISTER_EXTENSION_CLASS(QuitHandler, context) + BERRY_REGISTER_EXTENSION_CLASS(ShowPerspectiveHandler, context) BERRY_REGISTER_EXTENSION_CLASS(ShowViewHandler, context) + BERRY_REGISTER_EXTENSION_CLASS(SavePerspectiveHandler, context) + BERRY_REGISTER_EXTENSION_CLASS(ClosePerspectiveHandler, context) + BERRY_REGISTER_EXTENSION_CLASS(CloseAllPerspectivesHandler, context) + BERRY_REGISTER_EXTENSION_CLASS(ResetPerspectiveHandler, context) styleManager.reset(new QtStyleManager()); context->registerService(styleManager.data()); // The UI plugin needs to be initialized so that it can install the callback in PrefUtil, // which needs to be done as early as possible, before the workbench // accesses any API preferences. // Bundle uiBundle = Platform.getBundle(PlatformUI.PLUGIN_ID); // try // { // // Attempt to load the activator of the ui bundle. This will force lazy start // // of the ui bundle. Using the bundle activator class here because it is a // // class that needs to be loaded anyway so it should not cause extra classes // // to be loaded. // if(uiBundle != null) // uiBundle.loadClass(UI_BUNDLE_ACTIVATOR); // } // catch (ClassNotFoundException e) // { // WorkbenchPlugin.log("Unable to load UI activator", e); //$NON-NLS-1$ // } /* * DO NOT RUN ANY OTHER CODE AFTER THIS LINE. If you do, then you are * likely to cause a deadlock in class loader code. Please see Bug 86450 * for more information. */ } //const QList WorkbenchPlugin::GetBundles() //{ // return bundleContext.IsNull() ? QList() : bundleContext->GetBundles(); //} ctkPluginContext* WorkbenchPlugin::GetPluginContext() { return bundleContext; } void WorkbenchPlugin::stop(ctkPluginContext* context) { AbstractUICTKPlugin::stop(context); styleManager.reset(); delete perspRegistry; // avoid possible crash, see bug #18399 perspRegistry = 0; } QString WorkbenchPlugin::GetDataLocation() const { QFileInfo fileInfo = bundleContext->getDataFile(""); if (!fileInfo.isWritable()) return QString(); return fileInfo.absoluteFilePath(); } } #if (QT_VERSION < QT_VERSION_CHECK(5,0,0)) Q_EXPORT_PLUGIN2(org_blueberry_ui_qt, berry::WorkbenchPlugin) #endif diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.h index b66951df5e..40b29e4bd8 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchPlugin.h @@ -1,498 +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. ===================================================================*/ #ifndef BERRYWORKBENCHPLUGIN_H_ #define BERRYWORKBENCHPLUGIN_H_ #include #include #include #include #include #include "berryAbstractUICTKPlugin.h" #include "berryPlatformUI.h" #include "presentations/berryIPresentationFactory.h" #include "berryViewRegistry.h" #include "berryEditorRegistry.h" #include "berryPerspectiveRegistry.h" #include "intro/berryIntroRegistry.h" namespace berry { class QtStyleManager; /** * \ingroup org_blueberry_ui_internal * * This class represents the TOP of the workbench UI world * A plugin class is effectively an application wrapper * for a plugin & its classes. This class should be thought * of as the workbench UI's application class. * * This class is responsible for tracking various registries * font, preference, graphics, dialog store. * * This class is explicitly referenced by the * workbench plugin's "plugin.xml" and places it * into the UI start extension point of the main * overall application harness * * When is this class started? * When the Application * calls createExecutableExtension to create an executable * instance of our workbench class. */ class WorkbenchPlugin : public AbstractUICTKPlugin { Q_OBJECT #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) Q_PLUGIN_METADATA(IID "org_blueberry_ui_qt") #endif Q_INTERFACES(ctkPluginActivator) private: //static const QString UI_BUNDLE_ACTIVATOR = "org.blueberry.ui.internal.UIPlugin"; //$NON-NLS-1$ // Default instance of the receiver static WorkbenchPlugin* inst; // The presentation factory IPresentationFactory* presentationFactory; // Manager that maps resources to descriptors of editors to use EditorRegistry* editorRegistry; // The context within which this plugin was started. ctkPluginContext* bundleContext; // Other data. //WorkbenchPreferenceManager preferenceManager; ViewRegistry* viewRegistry; PerspectiveRegistry* perspRegistry; IntroRegistry* introRegistry; //SharedImages sharedImages; QScopedPointer styleManager; public: /** * Global workbench ui plugin flag. Only workbench implementation is allowed to use this flag * All other plugins, examples, or test cases must *not* use this flag. */ static bool DEBUG; /** * The character used to separate preference page category ids */ static char PREFERENCE_PAGE_CATEGORY_SEPARATOR; /** * Create an instance of the WorkbenchPlugin. The workbench plugin is * effectively the "application" for the workbench UI. The entire UI * operates as a good plugin citizen. */ WorkbenchPlugin(); ~WorkbenchPlugin(); - /** + /* * Creates an extension. If the extension plugin has not * been loaded a busy cursor will be activated during the duration of * the load. * * @param element the config element defining the extension * @param classAttribute the name of the attribute carrying the class * @return the extension object * @throws CoreException if the extension cannot be created */ - // template // static E* CreateExtension(IConfigurationElement::ConstPointer element, // const QString& classAttribute) { // try { // // If plugin has been loaded create extension. // // Otherwise, show busy cursor then create extension. // if (BundleUtility.isActivated(element.getDeclaringExtension() // .getNamespace())) { // return element.createExecutableExtension(classAttribute); // } // final Object[] ret = new Object[1]; // final CoreException[] exc = new CoreException[1]; // BusyIndicator.showWhile(null, new Runnable() { // public void run() { // try { // ret[0] = element // .createExecutableExtension(classAttribute); // } catch (CoreException e) { // exc[0] = e; // } // } // }); // if (exc[0] != null) { // throw exc[0]; // } // return ret[0]; // // } catch (CoreException core) { // throw core; // } catch (Exception e) { // throw new CoreException(new Status(IStatus.ERR, PI_WORKBENCH, // IStatus.ERR, WorkbenchMessages.WorkbenchPlugin_extension,e)); // } // } /** * Answers whether the provided element either has an attribute with the * given name or a child element with the given name with an attribute * called class. * * @param element * the element to test * @param extensionName * the name of the extension to test for * @return whether or not the extension is declared */ static bool HasExecutableExtension(const IConfigurationElement::Pointer& element, const QString& extensionName); /** * Checks to see if the provided element has the syntax for an executable * extension with a given name that resides in a bundle that is already * active. Determining the bundle happens in one of two ways:
*
    *
  • The element has an attribute with the specified name or element text * in the form bundle.id/class.name[:optional attributes]
  • *
  • The element has a child element with the specified name that has a * plugin attribute
  • *
* * @param element * the element to test * @param extensionName * the name of the extension to test for * @return whether or not the bundle expressed by the above criteria is * active. If the bundle cannot be determined then the state of the * bundle that declared the element is returned. */ static bool IsBundleLoadedForExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName); /** * Returns the bundle that contains the class referenced by an executable * extension. Determining the bundle happens in one of two ways:
*
    *
  • The element has an attribute with the specified name or element text * in the form bundle.id/class.name[:optional attributes]
  • *
  • The element has a child element with the specified name that has a * plugin attribute
  • *
* * @param element * the element to test * @param extensionName * the name of the extension to test for * @return the bundle referenced by the extension. If that bundle cannot be * determined the bundle that declared the element is returned. Note * that this may be null. */ static QSharedPointer GetBundleForExecutableExtension( const IConfigurationElement::Pointer& element, const QString& extensionName); /** * Return the default instance of the receiver. This represents the runtime plugin. * @return WorkbenchPlugin * @see AbstractUICTKPlugin for the typical implementation pattern for plugin classes. */ static WorkbenchPlugin* GetDefault(); std::size_t GetBundleCount(); /** * Answer the manager that maps resource types to a the * description of the editor to use * @return IEditorRegistry the editor registry used * by this plug-in. */ IEditorRegistry* GetEditorRegistry(); + /** + * Answer the element factory for an id, or nullnull if not found. * @param targetID The id of the presentation factory to use. * @return IPresentationFactory or null * if not factory matches that id. */ IPresentationFactory* GetPresentationFactory(); -protected: - - /* - * Returns the image registry for this plugin. - * - * Where are the images? The images (typically gifs) are found in the same - * plugins directory. - * - * @see ImageRegistry - * - * Note: The workbench uses the standard JFace ImageRegistry to track its - * images. In addition the class WorkbenchGraphicResources provides - * convenience access to the graphics resources and fast field access for - * some of the commonly used graphical images. - */ - //ImageRegistry createImageRegistry(); - - - private: /** * Looks up the configuration element with the given id on the given extension point * and instantiates the class specified by the class attributes. * * @param extensionPointId the extension point id (simple id) * @param elementName the name of the configuration element, or null * to match any element * @param targetID the target id * @return the instantiated extension object, or null if not found */ template C* CreateExtension(const QString& extensionPointId, const QString& elementName, const QString& targetID) { IExtensionPoint::Pointer extensionPoint = Platform::GetExtensionRegistry() ->GetExtensionPoint(PlatformUI::PLUGIN_ID() + "." + extensionPointId); if (extensionPoint == 0) { WorkbenchPlugin::Log("Unable to find extension. Extension point: " + extensionPointId + " not found"); return 0; } // Loop through the config elements. IConfigurationElement::Pointer targetElement(0); QList elements( Platform::GetExtensionRegistry()->GetConfigurationElementsFor(PlatformUI::PLUGIN_ID() + "." + extensionPointId)); for (int j = 0; j < elements.size(); j++) { if (elementName == "" || elementName == elements[j]->GetName()) { QString strID = elements[j]->GetAttribute("id"); if (targetID == strID) { targetElement = elements[j]; break; } } } if (targetElement.IsNull()) { // log it since we cannot safely display a dialog. WorkbenchPlugin::Log("Unable to find extension: " + targetID + " in extension point: " + extensionPointId); return 0; } // Create the extension. try { return targetElement->CreateExecutableExtension("class"); } catch (const CoreException& /*e*/) { // log it since we cannot safely display a dialog. WorkbenchPlugin::Log("Unable to create extension: " + targetID + " in extension point: " + extensionPointId); } return 0; } public: /** * Return the perspective registry. * @return IPerspectiveRegistry. The registry for the receiver. */ IPerspectiveRegistry* GetPerspectiveRegistry(); /** * Returns the introduction registry. * * @return the introduction registry. */ IIntroRegistry* GetIntroRegistry(); /* * Get the preference manager. * @return PreferenceManager the preference manager for * the receiver. */ //PreferenceManager getPreferenceManager(); - /* - * Returns the shared images for the workbench. - * - * @return the shared image manager - */ - //ISharedImages getSharedImages(); - - - /** * Answer the view registry. * @return IViewRegistry the view registry for the * receiver. */ IViewRegistry* GetViewRegistry(); /** * Logs the given message to the platform log. * * If you have an exception in hand, call log(String, Throwable) instead. * * If you have a status object in hand call log(String, IStatus) instead. * * This convenience method is for internal use by the Workbench only and * must not be called outside the Workbench. * * @param message * A high level UI message describing when the problem happened. */ static void Log(const QString &message); /** * Log the throwable. * @param t */ static void Log(const ctkException& exc); /** * Logs the given message and throwable to the platform log. * * If you have a status object in hand call log(String, IStatus) instead. * * This convenience method is for internal use by the Workbench only and * must not be called outside the Workbench. * * @param message * A high level UI message describing when the problem happened. * @param t * The throwable from where the problem actually occurred. */ static void Log(const QString &message, const ctkException& t); /** * Logs the given throwable to the platform log, indicating the class and * method from where it is being logged (this is not necessarily where it * occurred). * * This convenience method is for internal use by the Workbench only and * must not be called outside the Workbench. * * @param clazz * The calling class. * @param methodName * The calling method name. * @param t * The throwable from where the problem actually occurred. */ static void Log(const QString &clazz, const QString &methodName, const ctkException& t); /** * Logs the given message and status to the platform log. * * This convenience method is for internal use by the Workbench only and * must not be called outside the Workbench. * * @param message * A high level UI message describing when the problem happened. * May be null. * @param status * The status describing the problem. Must not be null. */ static void Log(const QString& message, const SmartPointer& status); /** * Log the status to the default log. * @param status */ static void Log(const SmartPointer& status); /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */ void start(ctkPluginContext* context); /* * Return an array of all bundles contained in this workbench. * * @return an array of bundles in the workbench or an empty array if none */ //const QList GetBundles(); /** * Returns the bundle context associated with the workbench plug-in. * * @return the bundle context */ ctkPluginContext* GetPluginContext(); /* (non-Javadoc) * @see org.blueberry.ui.plugin.AbstractUICTKPlugin#stop(org.osgi.framework.BundleContext) */ void stop(ctkPluginContext* context); /** * FOR INTERNAL WORKBENCH USE ONLY. * * Returns the path to a location in the file system that can be used * to persist/restore state between workbench invocations. * If the location did not exist prior to this call it will be created. * Returns null if no such location is available. * * @return path to a location in the file system where this plug-in can * persist data between sessions, or null if no such * location is available. */ QString GetDataLocation() const; }; } #endif /*BERRYWORKBENCHPLUGIN_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchSourceProvider.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchSourceProvider.cpp index fe2b9078a6..cf58a5c672 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchSourceProvider.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchSourceProvider.cpp @@ -1,890 +1,890 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryWorkbenchSourceProvider.h" #include "berryIContextService.h" #include "berryIEditorSite.h" #include "berryIEvaluationContext.h" #include "berryIPartService.h" #include "berryISelectionService.h" #include "berryIShowInSource.h" #include "berryISources.h" #include "berryIWorkbench.h" #include "berryIWorkbenchLocationService.h" #include "berryIWorkbenchPartConstants.h" #include "berryDetachedWindow.h" #include "berryDisplay.h" #include "berryObjectString.h" #include "berryObjects.h" #include "berryShowInContext.h" #include "berryUiUtil.h" #include "berryWorkbench.h" #include "berryWorkbenchWindow.h" #include #include namespace berry { const QList WorkbenchSourceProvider::PROVIDED_SOURCE_NAMES = QList() << ISources::ACTIVE_CURRENT_SELECTION_NAME() << ISources::ACTIVE_EDITOR_ID_NAME() << ISources::ACTIVE_EDITOR_NAME() << ISources::ACTIVE_PART_ID_NAME() << ISources::ACTIVE_PART_NAME() << ISources::ACTIVE_SITE_NAME() << ISources::SHOW_IN_SELECTION() << ISources::SHOW_IN_INPUT() << ISources::ACTIVE_SHELL_NAME() << ISources::ACTIVE_WORKBENCH_WINDOW_NAME() << ISources::ACTIVE_WORKBENCH_WINDOW_SHELL_NAME() << ISources::ACTIVE_WORKBENCH_WINDOW_IS_TOOLBAR_VISIBLE_NAME() << ISources::ACTIVE_WORKBENCH_WINDOW_IS_PERSPECTIVEBAR_VISIBLE_NAME() << ISources::ACTIVE_WORKBENCH_WINDOW_IS_STATUS_LINE_VISIBLE_NAME() << ISources::ACTIVE_WORKBENCH_WINDOW_ACTIVE_PERSPECTIVE_NAME(); WorkbenchSourceProvider::WorkbenchSourceProvider() : workbench(NULL) , lastActiveEditor(NULL) , lastActivePart(NULL) , lastActivePartSite(NULL) , lastShowInInput(NULL) , lastEditorInput(NULL) , display(NULL) , lastActiveShell(NULL) , lastActiveWorkbenchWindowShell(NULL) { } void WorkbenchSourceProvider::Initialize(IServiceLocator* locator) { AbstractSourceProvider::Initialize(locator); // this.locator = locator; IWorkbenchLocationService* wls = locator->GetService(); workbench = wls->GetWorkbench(); workbench->AddWindowListener(this); lastWindow = workbench->GetActiveWorkbenchWindow(); display = workbench->GetDisplay(); qApp->installEventFilter(this); } WorkbenchSourceProvider::~WorkbenchSourceProvider() { if (!lastWindow.Expired()) { lastWindow.Lock()->GetSelectionService()->RemoveSelectionListener(this); } workbench->RemoveWindowListener(this); qApp->removeEventFilter(this); HookListener(const_cast(lastActiveWorkbenchWindow.Lock().GetPointer()), NULL); lastActiveWorkbenchWindow.Reset(); lastActiveWorkbenchWindowShell = NULL; lastActiveShell = NULL; lastWindow.Reset(); } QList WorkbenchSourceProvider::GetProvidedSourceNames() const { return PROVIDED_SOURCE_NAMES; } ISourceProvider::StateMapType WorkbenchSourceProvider::GetCurrentState() const { ISourceProvider::StateMapType currentState; UpdateActiveShell(currentState); UpdateActivePart(currentState); UpdateSelection(currentState); return currentState; } void WorkbenchSourceProvider::SelectionChanged(const SmartPointer& /*part*/, const SmartPointer& newSelection) { if (selection == newSelection) return; // we have already handled the change selection = newSelection; LogDebuggingInfo(QString("Selection changed to ") + (selection ? selection->ToString() : QString("NULL"))); FireSourceChanged(ISources::ACTIVE_CURRENT_SELECTION(), ISources::ACTIVE_CURRENT_SELECTION_NAME(), selection); } int WorkbenchSourceProvider::UpdateSelection(ISourceProvider::StateMapType& currentState) const { int sources = 0; currentState.insert(ISources::ACTIVE_CURRENT_SELECTION_NAME(), IEvaluationContext::UNDEFINED_VARIABLE); Object::ConstPointer object = currentState.value(ISources::ACTIVE_PART_NAME()); if (IWorkbenchPart::ConstPointer part = object.Cast()) { if (part->GetSite().IsNotNull() && part->GetSite()->GetSelectionProvider().IsNotNull()) { sources = ISources::ACTIVE_CURRENT_SELECTION(); ISelection::ConstPointer currentSelection = part->GetSite() ->GetSelectionProvider()->GetSelection(); currentState.insert(ISources::ACTIVE_CURRENT_SELECTION_NAME(), currentSelection); } } return sources; } void WorkbenchSourceProvider::UpdateWindows(IWorkbenchWindow* newWindow) { if (lastWindow == newWindow) { return; } ISelection::ConstPointer selection; if (!lastWindow.Expired()) { lastWindow.Lock()->GetSelectionService()->RemoveSelectionListener(this); } if (newWindow != NULL) { newWindow->GetSelectionService()->AddSelectionListener(this); selection = newWindow->GetSelectionService()->GetSelection(); } SelectionChanged(IWorkbenchPart::Pointer(0), selection); lastWindow = IWorkbenchWindow::Pointer(newWindow); } void WorkbenchSourceProvider::PartActivated(const SmartPointer& ) { CheckActivePart(); } void WorkbenchSourceProvider::PartBroughtToTop(const SmartPointer& ) { CheckActivePart(); } void WorkbenchSourceProvider::PartClosed(const SmartPointer& ) { CheckActivePart(); } void WorkbenchSourceProvider::PartDeactivated(const SmartPointer& ) { CheckActivePart(); } void WorkbenchSourceProvider::PartOpened(const SmartPointer& ) { CheckActivePart(); } void WorkbenchSourceProvider::WindowActivated(const SmartPointer& ) { CheckActivePart(); } void WorkbenchSourceProvider::WindowClosed(const SmartPointer& window) { if (window.IsNotNull()) { window->GetPartService()->RemovePartListener(this); } CheckActivePart(); } void WorkbenchSourceProvider::WindowDeactivated(const SmartPointer& ) { CheckActivePart(); } void WorkbenchSourceProvider::WindowOpened(const SmartPointer& window) { if (window.IsNotNull()) { window->GetPartService()->AddPartListener(this); } } void WorkbenchSourceProvider::HandleCheck(const SmartPointer& s) { if (s != lastActiveShell) { lastActiveShell = s.GetPointer(); CheckActivePart(); IWorkbenchWindow* window = NULL; if (s.IsNotNull()) { if (s->GetData().Cast()) { window = s->GetData().Cast().GetPointer(); } else if (DetachedWindow::Pointer dw = s->GetData().Cast()) { window = dw->GetWorkbenchPage()->GetWorkbenchWindow().GetPointer(); } } UpdateWindows(window); } } void WorkbenchSourceProvider::CheckActivePart() { CheckActivePart(false); } void WorkbenchSourceProvider::CheckActivePart(bool updateShowInSelection) { ISourceProvider::StateMapType currentState; UpdateActivePart(currentState, updateShowInSelection); int sources = 0; // Figure out what was changed. const Object::ConstPointer newActivePart = currentState.value(ISources::ACTIVE_PART_NAME()); if (newActivePart != lastActivePart) { sources |= ISources::ACTIVE_PART(); if (newActivePart != IEvaluationContext::UNDEFINED_VARIABLE) { lastActivePart = newActivePart.Cast().GetPointer(); } else { lastActivePart = NULL; } } const Object::ConstPointer newActivePartId = currentState.value(ISources::ACTIVE_PART_ID_NAME()); if (lastActivePartId != newActivePartId) { sources |= ISources::ACTIVE_PART_ID(); if (newActivePartId != IEvaluationContext::UNDEFINED_VARIABLE) { lastActivePartId = newActivePartId.Cast(); } else { lastActivePartId = NULL; } } const Object::ConstPointer newActivePartSite = currentState.value(ISources::ACTIVE_SITE_NAME()); if (newActivePartSite != lastActivePartSite) { sources |= ISources::ACTIVE_SITE(); if (newActivePartSite != IEvaluationContext::UNDEFINED_VARIABLE) { lastActivePartSite = newActivePartSite.Cast().GetPointer(); } else { lastActivePartSite = NULL; } } const Object::ConstPointer newShowInInput = currentState.value(ISources::SHOW_IN_INPUT()); if (newShowInInput != lastShowInInput) { sources |= ISources::ACTIVE_SITE(); lastShowInInput = newShowInInput.GetPointer(); } if (currentState.value(ISources::SHOW_IN_SELECTION()) != IEvaluationContext::UNDEFINED_VARIABLE) { sources |= ISources::ACTIVE_SITE(); } Object::ConstPointer newActiveEditor = currentState.value(ISources::ACTIVE_EDITOR_NAME()); if (newActiveEditor != lastActiveEditor) { sources |= ISources::ACTIVE_EDITOR(); newActiveEditor = (newActiveEditor == IEvaluationContext::UNDEFINED_VARIABLE ? Object::ConstPointer(0) : newActiveEditor); HookListener(const_cast(lastActiveEditor), const_cast(newActiveEditor.Cast().GetPointer())); lastActiveEditor = newActiveEditor.Cast().GetPointer(); } const Object::ConstPointer newEditorInput = currentState.value(ISources::ACTIVE_EDITOR_INPUT_NAME()); if (newEditorInput != lastEditorInput) { sources |= ISources::ACTIVE_EDITOR(); if (newEditorInput != IEvaluationContext::UNDEFINED_VARIABLE) { lastEditorInput = newEditorInput.Cast().GetPointer(); } else { lastEditorInput = NULL; } } const Object::ConstPointer newActiveEditorId = currentState.value(ISources::ACTIVE_EDITOR_ID_NAME()); if (newActiveEditorId != lastActiveEditorId) { sources |= ISources::ACTIVE_EDITOR_ID(); if (newActiveEditorId != IEvaluationContext::UNDEFINED_VARIABLE) { lastActiveEditorId = newActiveEditorId.Cast(); } else { lastActiveEditorId = NULL; } } // Fire the event, if something has changed. if (sources != 0) { if (DEBUG) { if ((sources & ISources::ACTIVE_PART()) != 0) { LogDebuggingInfo("Active part changed to " + (lastActivePart ? lastActivePart->ToString() : QString("NULL"))); } if ((sources & ISources::ACTIVE_PART_ID()) != 0) { LogDebuggingInfo("Active part id changed to " + (lastActivePartId ? lastActivePartId->ToString() : QString("NULL"))); } if ((sources & ISources::ACTIVE_SITE()) != 0) { LogDebuggingInfo("Active site changed to " + (lastActivePartSite ? lastActivePartSite->ToString() : QString("NULL"))); } if ((sources & ISources::ACTIVE_EDITOR()) != 0) { LogDebuggingInfo("Active editor changed to " + (lastActiveEditor ? lastActiveEditor->ToString() : QString("NULL"))); } if ((sources & ISources::ACTIVE_EDITOR_ID()) != 0) { LogDebuggingInfo("Active editor id changed to " + (lastActiveEditorId ? lastActiveEditorId->ToString() : QString("NULL"))); } } sources |= UpdateSelection(currentState); FireSourceChanged(sources, currentState); } } SmartPointer WorkbenchSourceProvider::GetShowInSource(const SmartPointer& sourcePart) const { IShowInSource::Pointer result(UiUtil::GetAdapter(sourcePart.GetPointer())); return result; } SmartPointer WorkbenchSourceProvider::GetContext(const SmartPointer& sourcePart) const { IShowInSource::Pointer source = GetShowInSource(sourcePart); if (source.IsNotNull()) { ShowInContext::Pointer context = source->GetShowInContext(); if (context.IsNotNull()) { return context; } } else if (IEditorPart::Pointer editorPart = sourcePart.Cast()) { Object::Pointer input = editorPart->GetEditorInput(); ISelectionProvider::Pointer sp = sourcePart->GetSite()->GetSelectionProvider(); ISelection::ConstPointer sel = sp.IsNull() ? ISelection::ConstPointer(0) : sp->GetSelection(); ShowInContext::Pointer context(new ShowInContext(input, sel)); return context; } return ShowInContext::Pointer(0); } IWorkbenchWindow* WorkbenchSourceProvider::GetActiveWindow() const { // IContextService* const contextService = workbench->GetService(); // if (contextService != NULL) // { // const int shellType = contextService->GetShellType(qApp->activeWindow()); // if (shellType != IContextService::TYPE_DIALOG) // { // return workbench->GetActiveWorkbenchWindow().GetPointer(); // } // } if (qApp->activeWindow() != qApp->activeModalWidget()) { return workbench->GetActiveWorkbenchWindow().GetPointer(); } return NULL; } void WorkbenchSourceProvider::UpdateActivePart(ISourceProvider::StateMapType& currentState) const { UpdateActivePart(currentState, false); } void WorkbenchSourceProvider::UpdateActivePart(ISourceProvider::StateMapType& currentState, bool updateShowInSelection) const { currentState.insert(ISources::ACTIVE_SITE_NAME(), IEvaluationContext::UNDEFINED_VARIABLE); currentState.insert(ISources::ACTIVE_PART_NAME(), IEvaluationContext::UNDEFINED_VARIABLE); currentState.insert(ISources::ACTIVE_PART_ID_NAME(), IEvaluationContext::UNDEFINED_VARIABLE); currentState.insert(ISources::ACTIVE_EDITOR_NAME(), IEvaluationContext::UNDEFINED_VARIABLE); currentState.insert(ISources::ACTIVE_EDITOR_ID_NAME(), IEvaluationContext::UNDEFINED_VARIABLE); currentState.insert(ISources::SHOW_IN_INPUT(), IEvaluationContext::UNDEFINED_VARIABLE); currentState.insert(ISources::SHOW_IN_SELECTION(), IEvaluationContext::UNDEFINED_VARIABLE); IWorkbenchWindow* const activeWorkbenchWindow = GetActiveWindow(); if (activeWorkbenchWindow != NULL) { const IWorkbenchPage::Pointer activeWorkbenchPage = activeWorkbenchWindow->GetActivePage(); if (activeWorkbenchPage.IsNotNull()) { // Check the active workbench part. const IWorkbenchPart::Pointer newActivePart = activeWorkbenchPage->GetActivePart(); currentState.insert(ISources::ACTIVE_PART_NAME(), newActivePart); if (newActivePart.IsNotNull()) { const IWorkbenchPartSite::Pointer activeWorkbenchPartSite = newActivePart->GetSite(); currentState.insert(ISources::ACTIVE_SITE_NAME(), activeWorkbenchPartSite); if (activeWorkbenchPartSite.IsNotNull()) { const Object::Pointer newActivePartId(new ObjectString(activeWorkbenchPartSite->GetId())); currentState.insert(ISources::ACTIVE_PART_ID_NAME(), newActivePartId); } ShowInContext::Pointer context = GetContext(newActivePart); if (context.IsNotNull()) { const Object::Pointer input = context->GetInput(); if (input.IsNotNull()) { currentState.insert(ISources::SHOW_IN_INPUT(), input); } if (updateShowInSelection) { const ISelection::ConstPointer selection = context->GetSelection(); if (selection.IsNotNull()) { currentState.insert(ISources::SHOW_IN_SELECTION(), selection); } } } } // Check the active editor part. const IEditorPart::Pointer newActiveEditor = activeWorkbenchPage->GetActiveEditor(); currentState.insert(ISources::ACTIVE_EDITOR_NAME(), newActiveEditor); if (newActiveEditor.IsNotNull()) { currentState.insert(ISources::ACTIVE_EDITOR_INPUT_NAME(), newActiveEditor->GetEditorInput()); const IEditorSite::Pointer activeEditorSite = newActiveEditor->GetEditorSite(); if (activeEditorSite.IsNotNull()) { const Object::Pointer newActiveEditorId(new ObjectString(activeEditorSite->GetId())); currentState.insert(ISources::ACTIVE_EDITOR_ID_NAME(), newActiveEditorId); } } } } } /** * The listener to individual window properties. */ void WorkbenchSourceProvider::PropertyChange(const SmartPointer& event) { if (WorkbenchWindow::PROP_TOOLBAR_VISIBLE == event->GetProperty()) { const Object::Pointer newValue = event->GetNewValue(); if (newValue.IsNull() || !(newValue.Cast())) return; if (lastToolbarVisibility != newValue) { FireSourceChanged( ISources::ACTIVE_WORKBENCH_WINDOW_SUBORDINATE(), ISources::ACTIVE_WORKBENCH_WINDOW_IS_TOOLBAR_VISIBLE_NAME(), newValue); lastToolbarVisibility = newValue.Cast(); } } else if (WorkbenchWindow::PROP_PERSPECTIVEBAR_VISIBLE == event->GetProperty()) { const Object::Pointer newValue = event->GetNewValue(); if (newValue.IsNull() || !(newValue.Cast())) return; if (lastPerspectiveBarVisibility != newValue) { FireSourceChanged( ISources::ACTIVE_WORKBENCH_WINDOW_SUBORDINATE(), ISources::ACTIVE_WORKBENCH_WINDOW_IS_PERSPECTIVEBAR_VISIBLE_NAME(), newValue); lastPerspectiveBarVisibility = newValue.Cast(); } } else if (WorkbenchWindow::PROP_STATUS_LINE_VISIBLE == event->GetProperty()) { const Object::Pointer newValue = event->GetNewValue(); if (newValue.IsNull() || !(newValue.Cast())) return; if (lastStatusLineVisibility != newValue) { FireSourceChanged( ISources::ACTIVE_WORKBENCH_WINDOW_SUBORDINATE(), ISources::ACTIVE_WORKBENCH_WINDOW_IS_STATUS_LINE_VISIBLE_NAME(), newValue); lastStatusLineVisibility = newValue.Cast(); } } else { IPropertyChangeListener::PropertyChange(event); } } void WorkbenchSourceProvider::PerspectiveActivated(const SmartPointer& /*page*/, const SmartPointer& perspective) { QString id = perspective.IsNull() ? QString() : perspective->GetId(); if (lastPerspectiveId.IsNotNull() && *lastPerspectiveId == id) { return; } Object::Pointer newValue(new ObjectString(id)); FireSourceChanged(ISources::ACTIVE_WORKBENCH_WINDOW_SUBORDINATE(), ISources::ACTIVE_WORKBENCH_WINDOW_ACTIVE_PERSPECTIVE_NAME(), newValue); lastPerspectiveId = new ObjectString(id); } void WorkbenchSourceProvider::PerspectiveChanged(const SmartPointer& /*page*/, const SmartPointer& /*perspective*/, const QString& /*changeId*/) { } void WorkbenchSourceProvider::PropertyChange(const Object::Pointer& source, int propId) { if (propId == IWorkbenchPartConstants::PROP_INPUT) { HandleInputChanged(source.Cast()); } } bool WorkbenchSourceProvider::eventFilter(QObject* /*obj*/, QEvent *event) { if (event->type() == QEvent::WindowActivate) HandleShellEvent(); return false; } void WorkbenchSourceProvider::HandleShellEvent() { // if (!(event.widget instanceof Shell)) // { // if (DEBUG) // { // logDebuggingInfo("WSP: passOnEvent: " + event.widget); //$NON-NLS-1$ // } // return; // } LogDebuggingInfo("\tWSP:lastActiveShell: " + - (lastActiveShell ? lastActiveShell->ToString() : QString("NULL"))); + (lastActiveShell ? lastActiveShell->GetControl()->objectName() : QString("NULL"))); LogDebuggingInfo("\tWSP:lastActiveWorkbenchWindowShell: " + - (lastActiveWorkbenchWindowShell ? lastActiveWorkbenchWindowShell->ToString() : QString("NULL"))); + (lastActiveWorkbenchWindowShell ? lastActiveWorkbenchWindowShell->GetControl()->objectName() : QString("NULL"))); const ISourceProvider::StateMapType currentState = GetCurrentState(); const Shell::ConstPointer newActiveShell = currentState.value(ISources::ACTIVE_SHELL_NAME()).Cast(); const WorkbenchWindow::ConstPointer newActiveWorkbenchWindow = currentState.value(ISources::ACTIVE_WORKBENCH_WINDOW_NAME()).Cast(); const Shell::ConstPointer newActiveWorkbenchWindowShell = currentState.value(ISources::ACTIVE_WORKBENCH_WINDOW_SHELL_NAME()).Cast(); // dont update the coolbar/perspective bar visibility unless we're // processing a workbench window change const ObjectBool::ConstPointer newToolbarVisibility( newActiveWorkbenchWindow.IsNull() ? lastToolbarVisibility.GetPointer() : (newActiveWorkbenchWindow->GetToolBarVisible() ? new ObjectBool(true) : new ObjectBool(false))); const ObjectBool::ConstPointer newPerspectiveBarVisibility( newActiveWorkbenchWindow.IsNull() ? lastPerspectiveBarVisibility.GetPointer() : (newActiveWorkbenchWindow->GetPerspectiveBarVisible() ? new ObjectBool(true) : new ObjectBool(false))); const ObjectBool::ConstPointer newStatusLineVis( newActiveWorkbenchWindow.IsNull() ? lastStatusLineVisibility.GetPointer() : (newActiveWorkbenchWindow->GetStatusLineVisible() ? new ObjectBool(true) : new ObjectBool(false))); ObjectString::ConstPointer perspectiveId = lastPerspectiveId; if (newActiveWorkbenchWindow.IsNotNull()) { IWorkbenchPage::Pointer activePage = newActiveWorkbenchWindow->GetActivePage(); if (activePage.IsNotNull()) { IPerspectiveDescriptor::Pointer perspective = activePage->GetPerspective(); if (perspective.IsNotNull()) { perspectiveId = new ObjectString(perspective->GetId()); } } } // Figure out which variables have changed. const bool shellChanged = newActiveShell != lastActiveShell; const bool windowChanged = newActiveWorkbenchWindowShell != lastActiveWorkbenchWindowShell; const bool toolbarChanged = newToolbarVisibility != lastToolbarVisibility; const bool statusLineChanged = newStatusLineVis != lastStatusLineVisibility; const bool perspectiveBarChanged = newPerspectiveBarVisibility != lastPerspectiveBarVisibility; const bool perspectiveIdChanged = lastPerspectiveId != perspectiveId; // Fire an event for those sources that have changed. if (shellChanged && windowChanged) { ISourceProvider::StateMapType sourceValuesByName; sourceValuesByName.insert(ISources::ACTIVE_SHELL_NAME(), newActiveShell); sourceValuesByName.insert(ISources::ACTIVE_WORKBENCH_WINDOW_NAME(), newActiveWorkbenchWindow); sourceValuesByName.insert(ISources::ACTIVE_WORKBENCH_WINDOW_SHELL_NAME(), newActiveWorkbenchWindowShell); int sourceFlags = ISources::ACTIVE_SHELL() | ISources::ACTIVE_WORKBENCH_WINDOW(); if (toolbarChanged) { sourceValuesByName.insert(ISources::ACTIVE_WORKBENCH_WINDOW_IS_TOOLBAR_VISIBLE_NAME(), newToolbarVisibility); sourceFlags |= ISources::ACTIVE_WORKBENCH_WINDOW_SUBORDINATE(); } if (statusLineChanged) { sourceValuesByName.insert(ISources::ACTIVE_WORKBENCH_WINDOW_IS_STATUS_LINE_VISIBLE_NAME(), newStatusLineVis); sourceFlags |= ISources::ACTIVE_WORKBENCH_WINDOW_SUBORDINATE(); } if (perspectiveBarChanged) { sourceValuesByName.insert(ISources::ACTIVE_WORKBENCH_WINDOW_IS_PERSPECTIVEBAR_VISIBLE_NAME(), newPerspectiveBarVisibility); sourceFlags |= ISources::ACTIVE_WORKBENCH_WINDOW_SUBORDINATE(); } if (perspectiveIdChanged) { sourceValuesByName.insert(ISources::ACTIVE_WORKBENCH_WINDOW_ACTIVE_PERSPECTIVE_NAME(), perspectiveId); sourceFlags |= ISources::ACTIVE_WORKBENCH_WINDOW_SUBORDINATE(); } if (DEBUG) { LogDebuggingInfo("Active shell changed to " + (newActiveShell ? newActiveShell->ToString() : QString("NULL"))); LogDebuggingInfo("Active workbench window changed to " + (newActiveWorkbenchWindow ? newActiveWorkbenchWindow->ToString() : QString("NULL"))); LogDebuggingInfo("Active workbench window shell changed to " + (newActiveWorkbenchWindowShell ? newActiveWorkbenchWindowShell->ToString() : QString("NULL"))); LogDebuggingInfo("Active workbench window coolbar visibility " + (newToolbarVisibility ? newToolbarVisibility->ToString() : QString("NULL"))); LogDebuggingInfo("Active workbench window perspective bar visibility " + (newPerspectiveBarVisibility ? newPerspectiveBarVisibility->ToString() : QString("NULL"))); LogDebuggingInfo("Active workbench window status line visibility " + (newStatusLineVis ? newStatusLineVis->ToString() : QString("NULL"))); } FireSourceChanged(sourceFlags, sourceValuesByName); HookListener(const_cast(lastActiveWorkbenchWindow.Lock().GetPointer()), const_cast(newActiveWorkbenchWindow.GetPointer())); } else if (shellChanged) { LogDebuggingInfo("Active shell changed to " + (newActiveShell ? newActiveShell->ToString() : QString("NULL"))); FireSourceChanged(ISources::ACTIVE_SHELL(), ISources::ACTIVE_SHELL_NAME(), newActiveShell); } else if (windowChanged) { ISourceProvider::StateMapType sourceValuesByName; sourceValuesByName.insert(ISources::ACTIVE_WORKBENCH_WINDOW_NAME(), newActiveWorkbenchWindow); sourceValuesByName.insert(ISources::ACTIVE_WORKBENCH_WINDOW_SHELL_NAME(), newActiveWorkbenchWindowShell); int sourceFlags = ISources::ACTIVE_SHELL() | ISources::ACTIVE_WORKBENCH_WINDOW(); if (toolbarChanged) { sourceValuesByName.insert(ISources::ACTIVE_WORKBENCH_WINDOW_IS_TOOLBAR_VISIBLE_NAME(), newToolbarVisibility); sourceFlags |= ISources::ACTIVE_WORKBENCH_WINDOW_SUBORDINATE(); } if (statusLineChanged) { sourceValuesByName.insert(ISources::ACTIVE_WORKBENCH_WINDOW_IS_STATUS_LINE_VISIBLE_NAME(), newStatusLineVis); sourceFlags |= ISources::ACTIVE_WORKBENCH_WINDOW_SUBORDINATE(); } if (perspectiveBarChanged) { sourceValuesByName.insert(ISources::ACTIVE_WORKBENCH_WINDOW_IS_PERSPECTIVEBAR_VISIBLE_NAME(), newPerspectiveBarVisibility); sourceFlags |= ISources::ACTIVE_WORKBENCH_WINDOW_SUBORDINATE(); } if (perspectiveIdChanged) { sourceValuesByName.insert(ISources::ACTIVE_WORKBENCH_WINDOW_ACTIVE_PERSPECTIVE_NAME(), perspectiveId); sourceFlags |= ISources::ACTIVE_WORKBENCH_WINDOW_SUBORDINATE(); } if (DEBUG) { LogDebuggingInfo("Active workbench window changed to " + (newActiveWorkbenchWindow ? newActiveWorkbenchWindow->ToString() : QString("NULL"))); LogDebuggingInfo("Active workbench window shell changed to " + (newActiveWorkbenchWindowShell ? newActiveWorkbenchWindowShell->ToString() : QString("NULL"))); LogDebuggingInfo("Active workbench window coolbar visibility " + (newToolbarVisibility ? newToolbarVisibility->ToString() : QString("NULL"))); LogDebuggingInfo("Active workbench window perspective bar visibility " + (newPerspectiveBarVisibility ? newPerspectiveBarVisibility->ToString() : QString("NULL"))); LogDebuggingInfo("Active workbench window status line visibility " + (newStatusLineVis ? newStatusLineVis->ToString() : QString("NULL"))); } FireSourceChanged(sourceFlags, sourceValuesByName); HookListener(const_cast(lastActiveWorkbenchWindow.Lock().GetPointer()), const_cast(newActiveWorkbenchWindow.GetPointer())); } if (shellChanged || windowChanged) { CheckOtherSources(newActiveShell); } // Update the member variables. lastActiveShell = newActiveShell.GetPointer(); lastActiveWorkbenchWindowShell = newActiveWorkbenchWindowShell.GetPointer(); lastActiveWorkbenchWindow = newActiveWorkbenchWindow; lastToolbarVisibility = newToolbarVisibility; lastStatusLineVisibility = newStatusLineVis; lastPerspectiveBarVisibility = newPerspectiveBarVisibility; lastPerspectiveId = perspectiveId; } void WorkbenchSourceProvider::CheckOtherSources(const SmartPointer& s) { HandleCheck(s); } void WorkbenchSourceProvider::HandleInputChanged(const SmartPointer& editor) { IEditorInput::Pointer newInput = editor->GetEditorInput(); if (newInput != lastEditorInput) { FireSourceChanged(ISources::ACTIVE_EDITOR(), ISources::ACTIVE_EDITOR_INPUT_NAME(), newInput.IsNull() ? IEvaluationContext::UNDEFINED_VARIABLE : Object::ConstPointer(newInput)); lastEditorInput = newInput.GetPointer(); } } void WorkbenchSourceProvider::HookListener(WorkbenchWindow* lastActiveWorkbenchWindow, WorkbenchWindow* newActiveWorkbenchWindow) { if (lastActiveWorkbenchWindow != NULL) { lastActiveWorkbenchWindow->RemovePropertyChangeListener(this); lastActiveWorkbenchWindow->RemovePerspectiveListener(this); } if (newActiveWorkbenchWindow != NULL) { newActiveWorkbenchWindow->AddPropertyChangeListener(this); newActiveWorkbenchWindow->AddPerspectiveListener(this); } } void WorkbenchSourceProvider::HookListener(IEditorPart* lastActiveEditor, IEditorPart* newActiveEditor) { if (lastActiveEditor != NULL) { lastActiveEditor->RemovePropertyListener(this); } if (newActiveEditor != NULL) { newActiveEditor->AddPropertyListener(this); } } void WorkbenchSourceProvider::UpdateActiveShell(ISourceProvider::StateMapType& currentState) const { QVariant windowShell; QWidget* activeWindow = qApp->activeWindow(); if (activeWindow) { windowShell = activeWindow->property("shell"); } Shell::Pointer newActiveShell(windowShell.isValid() ? windowShell.value() : NULL); currentState.insert(ISources::ACTIVE_SHELL_NAME(), newActiveShell); /* * We will fallback to the workbench window, but only if a dialog is not * open. */ // IContextService* const contextService = workbench->GetService(); // const int shellType = contextService->GetShellType(newActiveShell); // if (shellType == IContextService::TYPE_DIALOG) // return; if (activeWindow == qApp->activeModalWidget()) return; const WorkbenchWindow::ConstPointer newActiveWorkbenchWindow = workbench->GetActiveWorkbenchWindow().Cast(); Shell::Pointer newActiveWorkbenchWindowShell; if (newActiveWorkbenchWindow.IsNotNull()) { newActiveWorkbenchWindowShell = newActiveWorkbenchWindow->GetShell(); } currentState.insert(ISources::ACTIVE_WORKBENCH_WINDOW_NAME(), newActiveWorkbenchWindow); currentState.insert(ISources::ACTIVE_WORKBENCH_WINDOW_SHELL_NAME(), newActiveWorkbenchWindowShell); const ObjectBool::ConstPointer newToolbarVisibility( newActiveWorkbenchWindow.IsNull() ? lastToolbarVisibility.GetPointer() : (newActiveWorkbenchWindow->GetToolBarVisible() ? new ObjectBool(true) : new ObjectBool(false))); const ObjectBool::ConstPointer newPerspectiveBarVisibility( newActiveWorkbenchWindow.IsNull() ? lastPerspectiveBarVisibility.GetPointer() : (newActiveWorkbenchWindow->GetPerspectiveBarVisible() ? new ObjectBool(true) : new ObjectBool(false))); const ObjectBool::ConstPointer newStatusLineVis( newActiveWorkbenchWindow.IsNull() ? lastStatusLineVisibility.GetPointer() : (newActiveWorkbenchWindow->GetStatusLineVisible() ? new ObjectBool(true) : new ObjectBool(false))); ObjectString::ConstPointer perspectiveId = lastPerspectiveId; if (newActiveWorkbenchWindow.IsNotNull()) { const IWorkbenchPage::Pointer activePage = newActiveWorkbenchWindow->GetActivePage(); if (activePage.IsNotNull()) { const IPerspectiveDescriptor::Pointer perspective = activePage->GetPerspective(); if (perspective.IsNotNull()) { perspectiveId = new ObjectString(perspective->GetId()); } } } currentState.insert(ISources::ACTIVE_WORKBENCH_WINDOW_IS_TOOLBAR_VISIBLE_NAME(), newToolbarVisibility); currentState.insert(ISources::ACTIVE_WORKBENCH_WINDOW_IS_PERSPECTIVEBAR_VISIBLE_NAME(), newPerspectiveBarVisibility); currentState.insert(ISources::ACTIVE_WORKBENCH_WINDOW_IS_STATUS_LINE_VISIBLE_NAME(), newStatusLineVis); currentState.insert(ISources::ACTIVE_WORKBENCH_WINDOW_ACTIVE_PERSPECTIVE_NAME(), perspectiveId); } IPartListener::Events::Types WorkbenchSourceProvider::GetPartEventTypes() const { return IPartListener::Events::ACTIVATED | IPartListener::Events::BROUGHT_TO_TOP | IPartListener::Events::CLOSED | IPartListener::Events::DEACTIVATED | IPartListener::Events::OPENED; } IPerspectiveListener::Events::Types WorkbenchSourceProvider::GetPerspectiveEventTypes() const { return IPerspectiveListener::Events::ACTIVATED | IPerspectiveListener::Events::CHANGED; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.cpp index b1b38256ce..5d5bd39875 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.cpp @@ -1,1945 +1,1937 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "tweaklets/berryWorkbenchTweaklet.h" #include "berryWorkbenchWindow.h" #include "berryIWorkbenchPage.h" #include "berryIPerspectiveDescriptor.h" #include "berryIContextService.h" #include "berryUIException.h" #include "berryConstants.h" #include "berryIMenuService.h" #include "berryMenuUtil.h" #include "intro/berryIntroConstants.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchPage.h" #include "berryWorkbench.h" #include "berryWorkbenchConstants.h" #include "berryPartSite.h" #include "berryIServiceLocatorCreator.h" #include "berryMenuManager.h" +#include "berryQActionProperties.h" #include "berryQtControlWidget.h" #include "berryQtPerspectiveSwitcher.h" #include "berryWWinActionBars.h" #include "berryWorkbenchLocationService.h" #include "berryIServiceFactory.h" #include "berryIServiceScopes.h" #include "berryIEvaluationReference.h" #include "berryPlatformUI.h" #include "berryDebugUtil.h" #include #include #include #include #include namespace berry { const QString WorkbenchWindow::PROP_TOOLBAR_VISIBLE = "toolbarVisible"; const QString WorkbenchWindow::PROP_PERSPECTIVEBAR_VISIBLE = "perspectiveBarVisible"; const QString WorkbenchWindow::PROP_STATUS_LINE_VISIBLE = "statusLineVisible"; const ActionBarAdvisor::FillFlags WorkbenchWindow::FILL_ALL_ACTION_BARS = ActionBarAdvisor::FILL_MENU_BAR | ActionBarAdvisor::FILL_TOOL_BAR | ActionBarAdvisor::FILL_STATUS_LINE; WorkbenchWindow::WorkbenchWindow(int number) : Window(Shell::Pointer(0)) , pageComposite(0) , windowAdvisor(0) , actionBarAdvisor(0) , number(number) , largeUpdates(0) , closing(false) , shellActivated(false) , updateDisabled(true) , toolBarVisible(true) , perspectiveBarVisible(true) , statusLineVisible(true) , emptyWindowContentsCreated(false) , emptyWindowContents(0) , asMaximizedState(false) , partService(this) , serviceLocatorOwner(new ServiceLocatorOwner(this)) , resizeEventFilter(this) { this->Register(); // increase the reference count to avoid deleting // this object when temporary smart pointers // go out of scope // Make sure there is a workbench. This call will throw // an exception if workbench not created yet. IWorkbench* workbench = PlatformUI::GetWorkbench(); IServiceLocatorCreator* slc = workbench->GetService(); this->serviceLocator = slc->CreateServiceLocator( workbench, nullptr, IDisposable::WeakPtr(serviceLocatorOwner)).Cast(); InitializeDefaultServices(); // Add contribution managers that are exposed to other plugins. this->AddMenuBar(); //addCoolBar(SWT.NONE); // style is unused //addStatusLine(); this->FireWindowOpening(); // Fill the action bars this->FillActionBars(FILL_ALL_ACTION_BARS); this->UnRegister(false); // decrease reference count and avoid deleting // the window } WorkbenchWindow::~WorkbenchWindow() { - //BERRY_INFO << "WorkbenchWindow::~WorkbenchWindow()"; + // BERRY_INFO << "WorkbenchWindow::~WorkbenchWindow()"; } Object* WorkbenchWindow::GetService(const QString& key) { return serviceLocator->GetService(key); } bool WorkbenchWindow::HasService(const QString& key) const { return serviceLocator->HasService(key); } Shell::Pointer WorkbenchWindow::GetShell() const { return Window::GetShell(); } bool WorkbenchWindow::ClosePage(IWorkbenchPage::Pointer in, bool save) { // Validate the input. if (!pageList.Contains(in)) { return false; } WorkbenchPage::Pointer oldPage = in.Cast (); // Save old perspective. if (save && oldPage->IsSaveNeeded()) { if (!oldPage->SaveAllEditors(true)) { return false; } } // If old page is activate deactivate. bool oldIsActive = (oldPage == this->GetActivePage()); if (oldIsActive) { this->SetActivePage(IWorkbenchPage::Pointer(0)); } // Close old page. pageList.Remove(oldPage); partService.PageClosed(oldPage); //this->FirePageClosed(oldPage); //oldPage->Dispose(); // Activate new page. if (oldIsActive) { IWorkbenchPage::Pointer newPage = pageList.GetNextActive(); if (newPage != 0) { this->SetActivePage(newPage); } } if (!closing && pageList.IsEmpty()) { this->ShowEmptyWindowContents(); } return true; } void WorkbenchWindow::AddPerspectiveListener(IPerspectiveListener* l) { perspectiveEvents.AddListener(l); } void WorkbenchWindow::RemovePerspectiveListener(IPerspectiveListener* l) { perspectiveEvents.RemoveListener(l); } IPerspectiveListener::Events& WorkbenchWindow::GetPerspectiveEvents() { return perspectiveEvents; } void WorkbenchWindow::FireWindowOpening() { // let the application do further configuration this->GetWindowAdvisor()->PreWindowOpen(); } void WorkbenchWindow::FireWindowRestored() { //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { this->GetWindowAdvisor()->PostWindowRestore(); // } //}); } void WorkbenchWindow::FireWindowCreated() { this->GetWindowAdvisor()->PostWindowCreate(); } void WorkbenchWindow::FireWindowOpened() { this->GetWorkbenchImpl()->FireWindowOpened(IWorkbenchWindow::Pointer(this)); this->GetWindowAdvisor()->PostWindowOpen(); } bool WorkbenchWindow::FireWindowShellClosing() { return this->GetWindowAdvisor()->PreWindowShellClose(); } void WorkbenchWindow::FireWindowClosed() { // let the application do further deconfiguration this->GetWindowAdvisor()->PostWindowClose(); this->GetWorkbenchImpl()->FireWindowClosed(IWorkbenchWindow::Pointer(this)); } ///** // * Fires page activated // */ //void WorkbenchWindow::FirePageActivated(IWorkbenchPage::Pointer page) { //// String label = null; // debugging only //// if (UIStats.isDebugging(UIStats.NOTIFY_PAGE_LISTENERS)) { //// label = "activated " + page.getLabel(); //$NON-NLS-1$ //// } //// try { //// UIStats.start(UIStats.NOTIFY_PAGE_LISTENERS, label); //// UIListenerLogging.logPageEvent(this, page, //// UIListenerLogging.WPE_PAGE_ACTIVATED); // pageEvents.FirePageActivated(page); // partService.pageActivated(page); //// } finally { //// UIStats.end(UIStats.NOTIFY_PAGE_LISTENERS, page.getLabel(), label); //// } //} // ///** // * Fires page closed // */ //void WorkbenchWindow::FirePageClosed(IWorkbenchPage::Pointer page) { // String label = null; // debugging only // if (UIStats.isDebugging(UIStats.NOTIFY_PAGE_LISTENERS)) { // label = "closed " + page.getLabel(); //$NON-NLS-1$ // } // try { // UIStats.start(UIStats.NOTIFY_PAGE_LISTENERS, label); // UIListenerLogging.logPageEvent(this, page, // UIListenerLogging.WPE_PAGE_CLOSED); // pageListeners.firePageClosed(page); // partService.pageClosed(page); // } finally { // UIStats.end(UIStats.NOTIFY_PAGE_LISTENERS, page.getLabel(), label); // } // //} // ///** // * Fires page opened // */ //void WorkbenchWindow::FirePageOpened(IWorkbenchPage::Pointer page) { // String label = null; // debugging only // if (UIStats.isDebugging(UIStats.NOTIFY_PAGE_LISTENERS)) { // label = "opened " + page.getLabel(); //$NON-NLS-1$ // } // try { // UIStats.start(UIStats.NOTIFY_PAGE_LISTENERS, label); // UIListenerLogging.logPageEvent(this, page, // UIListenerLogging.WPE_PAGE_OPENED); // pageListeners.firePageOpened(page); // partService.pageOpened(page); // } finally { // UIStats.end(UIStats.NOTIFY_PAGE_LISTENERS, page.getLabel(), label); // } //} void WorkbenchWindow::FirePerspectiveActivated(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_ACTIVATED); perspectiveEvents.perspectiveActivated(page, perspective); } void WorkbenchWindow::FirePerspectivePreDeactivate( IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_PRE_DEACTIVATE); perspectiveEvents.perspectivePreDeactivate(page, perspective); } void WorkbenchWindow::FirePerspectiveDeactivated(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_DEACTIVATED); perspectiveEvents.perspectiveDeactivated(page, perspective); } void WorkbenchWindow::FirePerspectiveChanged(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective, const QString& changeId) { // Some callers call this even when there is no active perspective. // Just ignore this case. if (perspective != 0) { // UIListenerLogging.logPerspectiveChangedEvent(this, page, // perspective, null, changeId); perspectiveEvents.perspectiveChanged(page, perspective, changeId); } } void WorkbenchWindow::FirePerspectiveChanged(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective, IWorkbenchPartReference::Pointer partRef, const QString& changeId) { // Some callers call this even when there is no active perspective. // Just ignore this case. if (perspective != 0) { // UIListenerLogging.logPerspectiveChangedEvent(this, page, // perspective, partRef, changeId); perspectiveEvents.perspectivePartChanged(page, perspective, partRef, changeId); } } void WorkbenchWindow::FirePerspectiveClosed(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_CLOSED); perspectiveEvents.perspectiveClosed(page, perspective); } void WorkbenchWindow::FirePerspectiveOpened(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer perspective) { // UIListenerLogging.logPerspectiveEvent(this, page, perspective, // UIListenerLogging.PLE_PERSP_OPENED); perspectiveEvents.perspectiveOpened(page, perspective); } void WorkbenchWindow::FirePerspectiveSavedAs(IWorkbenchPage::Pointer page, IPerspectiveDescriptor::Pointer oldPerspective, IPerspectiveDescriptor::Pointer newPerspective) { // UIListenerLogging.logPerspectiveSavedAs(this, page, oldPerspective, // newPerspective); perspectiveEvents.perspectiveSavedAs(page, oldPerspective, newPerspective); } void WorkbenchWindow::FillActionBars(ActionBarAdvisor::FillFlags flags) { // Workbench workbench = getWorkbenchImpl(); // workbench.largeUpdateStart(); //try { this->GetActionBarAdvisor()->FillActionBars(flags); IMenuService* menuService = serviceLocator->GetService(); menuService->PopulateContributionManager(dynamic_cast(GetActionBars()->GetMenuManager()), MenuUtil::MAIN_MENU); // ICoolBarManager coolbar = getActionBars().getCoolBarManager(); // if (coolbar != null) // { // menuService.populateContributionManager( // (ContributionManager) coolbar, // MenuUtil.MAIN_TOOLBAR); // } // } finally { // workbench.largeUpdateEnd(); // } } QPoint WorkbenchWindow::GetInitialSize() { return this->GetWindowConfigurer()->GetInitialSize(); } bool WorkbenchWindow::Close() { //BERRY_INFO << "WorkbenchWindow::Close()"; bool ret = false; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { ret = this->BusyClose(); // } // }); return ret; } bool WorkbenchWindow::BusyClose() { // Whether the window was actually closed or not bool windowClosed = false; // Setup internal flags to indicate window is in // progress of closing and no update should be done. closing = true; updateDisabled = true; try { // Only do the check if it is OK to close if we are not closing // via the workbench as the workbench will check this itself. Workbench* workbench = this->GetWorkbenchImpl(); std::size_t count = workbench->GetWorkbenchWindowCount(); // also check for starting - if the first window dies on startup // then we'll need to open a default window. if (!workbench->IsStarting() && !workbench->IsClosing() && count <= 1 - && workbench->GetWorkbenchConfigurer() ->GetExitOnLastWindowClose()) + && workbench->GetWorkbenchConfigurer()->GetExitOnLastWindowClose()) { windowClosed = workbench->Close(); } else { if (this->OkToClose()) { windowClosed = this->HardClose(); } } } catch (std::exception& exc) { if (!windowClosed) { // Reset the internal flags if window was not closed. closing = false; updateDisabled = false; } throw exc; } // if (windowClosed && tracker != null) { // tracker.close(); // } return windowClosed; } void WorkbenchWindow::MakeVisible() { Shell::Pointer shell = GetShell(); if (shell) { // see bug 96700 and bug 4414 for a discussion on the use of open() // here shell->Open(); } } bool WorkbenchWindow::OkToClose() { // Save all of the editors. if (!this->GetWorkbenchImpl()->IsClosing()) { if (!this->SaveAllPages(true)) { return false; } } return true; } bool WorkbenchWindow::SaveAllPages(bool bConfirm) { bool bRet = true; PageList::iterator itr = pageList.Begin(); while (bRet && itr != pageList.End()) { bRet = (*itr)->SaveAllEditors(bConfirm); ++itr; } return bRet; } bool WorkbenchWindow::HardClose() { std::exception exc; bool exceptionOccured = false; try { // Clear the action sets, fix for bug 27416. //getActionPresentation().clearActionSets(); // Remove the handler submissions. Bug 64024. /* final IWorkbench workbench = getWorkbench(); final IHandlerService handlerService = (IHandlerService) workbench.getService(IHandlerService.class); handlerService.deactivateHandlers(handlerActivations); final Iterator activationItr = handlerActivations.iterator(); while (activationItr.hasNext()) { final IHandlerActivation activation = (IHandlerActivation) activationItr .next(); activation.getHandler().dispose(); } handlerActivations.clear(); globalActionHandlersByCommandId.clear(); */ // Remove the enabled submissions. Bug 64024. //IContextService* contextService = this->GetWorkbench()->GetService(); //contextService->UnregisterShell(this->GetShell()); this->CloseAllPages(); this->FireWindowClosed(); // time to wipe out our populate /* IMenuService menuService = (IMenuService) workbench .getService(IMenuService.class); menuService .releaseContributions(((ContributionManager) getActionBars() .getMenuManager())); ICoolBarManager coolbar = getActionBars().getCoolBarManager(); if (coolbar != null) { menuService .releaseContributions(((ContributionManager) coolbar)); } */ //getActionBarAdvisor().dispose(); //getWindowAdvisor().dispose(); //detachedWindowShells.dispose(); delete windowAdvisor; windowAdvisor = 0; // Null out the progress region. Bug 64024. //progressRegion = null; // Remove drop targets /* DragUtil.removeDragTarget(null, trimDropTarget); DragUtil.removeDragTarget(getShell(), trimDropTarget); trimDropTarget = null; if (trimMgr2 != null) { trimMgr2.dispose(); trimMgr2 = null; } if (trimContributionMgr != null) { trimContributionMgr.dispose(); trimContributionMgr = null; } */ } catch (std::exception& e) { exc = e; exceptionOccured = true; } bool result = Window::Close(); // Bring down all of the services ... after the window goes away serviceLocator->Dispose(); //menuRestrictions.clear(); if (exceptionOccured) throw exc; return result; } void WorkbenchWindow::CloseAllPages() { // Deactivate active page. this->SetActivePage(IWorkbenchPage::Pointer(0)); // Clone and deref all so that calls to getPages() returns // empty list (if called by pageClosed event handlers) PageList oldList = pageList; pageList.Clear(); // Close all. for (PageList::iterator itr = oldList.Begin(); itr != oldList.End(); ++itr) { partService.PageClosed(*itr); //(*itr)->FirePageClosed(page); //page.dispose(); } if (!closing) { this->ShowEmptyWindowContents(); } } WWinActionBars* WorkbenchWindow::GetActionBars() { if (actionBars.IsNull()) { actionBars = new WWinActionBars(this); } return actionBars.GetPointer(); } void WorkbenchWindow::SetPerspectiveExcludeList(const QStringList& v) { perspectiveExcludeList = v; } QStringList WorkbenchWindow::GetPerspectiveExcludeList() const { return perspectiveExcludeList; } void WorkbenchWindow::SetViewExcludeList(const QStringList& v) { viewExcludeList = v; } QStringList WorkbenchWindow::GetViewExcludeList() const { return viewExcludeList; } -IWorkbenchPage::Pointer WorkbenchWindow::GetPage(int i) const +QList WorkbenchWindow::GetPages() const { - QList pages = pageList.GetPages(); - int j = 0; - for (auto it = pages.begin(); it!=pages.end(); it++, j++) - { - if (j==i) - { - return *it; - } - } - return IWorkbenchPage::Pointer(); + return pageList.GetPages(); } IWorkbenchPage::Pointer WorkbenchWindow::GetActivePage() const { return pageList.GetActive(); } -IWorkbench* WorkbenchWindow::GetWorkbench() +IWorkbench* WorkbenchWindow::GetWorkbench() const { return PlatformUI::GetWorkbench(); } IPartService* WorkbenchWindow::GetPartService() { return &partService; } -ISelectionService* WorkbenchWindow::GetSelectionService() +ISelectionService* WorkbenchWindow::GetSelectionService() const { return partService.GetSelectionService(); } bool WorkbenchWindow::GetToolBarVisible() const { return GetWindowConfigurer()->GetShowToolBar() && toolBarVisible; } bool WorkbenchWindow::GetPerspectiveBarVisible() const { return GetWindowConfigurer()->GetShowPerspectiveBar() && perspectiveBarVisible; } bool WorkbenchWindow::GetStatusLineVisible() const { return GetWindowConfigurer()->GetShowStatusLine() && statusLineVisible; } void WorkbenchWindow::AddPropertyChangeListener(IPropertyChangeListener *listener) { genericPropertyListeners.AddListener(listener); } void WorkbenchWindow::RemovePropertyChangeListener(IPropertyChangeListener *listener) { genericPropertyListeners.RemoveListener(listener); } bool WorkbenchWindow::IsClosing() { return closing || this->GetWorkbenchImpl()->IsClosing(); } int WorkbenchWindow::Open() { if (pageList.IsEmpty()) { this->ShowEmptyWindowContents(); } this->FireWindowCreated(); this->GetWindowAdvisor()->OpenIntro(); int result = Window::Open(); // It's time for a layout ... to insure that if TrimLayout // is in play, it updates all of the trim it's responsible // for. We have to do this before updating in order to get // the PerspectiveBar management correct...see defect 137334 //getShell().layout(); this->FireWindowOpened(); // if (perspectiveSwitcher != null) { // perspectiveSwitcher.updatePerspectiveBar(); // perspectiveSwitcher.updateBarParent(); // } return result; } QWidget* WorkbenchWindow::GetPageComposite() { return pageComposite; } QWidget *WorkbenchWindow::CreatePageComposite(QWidget *parent) { QtControlWidget* pageArea = new QtControlWidget(parent, 0); pageArea->setObjectName("Page Composite"); new QHBoxLayout(pageArea); if (qobject_cast (parent) != 0) qobject_cast (parent)->setCentralWidget(pageArea); else parent->layout()->addWidget(pageArea); // we have to enable visibility to get a proper layout (see bug #1654) pageArea->setVisible(true); parent->setVisible(true); pageComposite = pageArea; return pageArea; } QWidget* WorkbenchWindow::CreateContents(Shell::Pointer parent) { // we know from Window.create that the parent is a Shell. this->GetWindowAdvisor()->CreateWindowContents(parent); // the page composite must be set by createWindowContents poco_assert(pageComposite != 0) ; // "createWindowContents must call configurer.createPageComposite"); //$NON-NLS-1$ return pageComposite; } void WorkbenchWindow::CreateDefaultContents(Shell::Pointer shell) { QMainWindow* mainWindow = qobject_cast(shell->GetControl()); if (GetWindowConfigurer()->GetShowMenuBar() && mainWindow) { QMenuBar* menuBar = GetMenuBarManager()->CreateMenuBar(mainWindow); mainWindow->setMenuBar(menuBar); } if (GetWindowConfigurer()->GetShowPerspectiveBar() && mainWindow) { mainWindow->addToolBar(new QtPerspectiveSwitcher(IWorkbenchWindow::Pointer(this))); } // Create the client composite area (where page content goes). CreatePageComposite(shell->GetControl()); } void WorkbenchWindow::CreateTrimWidgets(SmartPointer /*shell*/) { // do nothing -- trim widgets are created in CreateDefaultContents } bool WorkbenchWindow::UnableToRestorePage(IMemento::Pointer pageMem) { QString pageName; pageMem->GetString(WorkbenchConstants::TAG_LABEL, pageName); // return new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0, NLS.bind( // WorkbenchMessages.WorkbenchWindow_unableToRestorePerspective, // pageName), null); WorkbenchPlugin::Log("Unable to restore perspective: " + pageName); return false; } bool WorkbenchWindow::RestoreState(IMemento::Pointer memento, IPerspectiveDescriptor::Pointer activeDescriptor) { //TODO WorkbenchWindow restore state poco_assert(GetShell()); // final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.WorkbenchWindow_problemsRestoringWindow, null); bool result = true; // Restore the window advisor state. IMemento::Pointer windowAdvisorState = memento ->GetChild(WorkbenchConstants::TAG_WORKBENCH_WINDOW_ADVISOR); if (windowAdvisorState) { //result.add(getWindowAdvisor().restoreState(windowAdvisorState)); result &= GetWindowAdvisor()->RestoreState(windowAdvisorState); } // Restore actionbar advisor state. IMemento::Pointer actionBarAdvisorState = memento ->GetChild(WorkbenchConstants::TAG_ACTION_BAR_ADVISOR); if (actionBarAdvisorState) { // result.add(getActionBarAdvisor() // .restoreState(actionBarAdvisorState)); result &= GetActionBarAdvisor() ->RestoreState(actionBarAdvisorState); } // Read window's bounds and state. QRect displayBounds; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { displayBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetScreenSize(); //displayBounds = GetShell()->GetDisplay()->GetBounds(); // }}); // final IMemento fastViewMem = memento // .getChild(IWorkbenchConstants.TAG_FAST_VIEW_DATA); // if (fastViewMem != null) { // if (fastViewBar != null) { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // fastViewBar.restoreState(fastViewMem); // }}); // // } // } int x, y, w, h; memento->GetInteger(WorkbenchConstants::TAG_X, x); memento->GetInteger(WorkbenchConstants::TAG_Y, y); memento->GetInteger(WorkbenchConstants::TAG_WIDTH, w); memento->GetInteger(WorkbenchConstants::TAG_HEIGHT, h); QRect shellBounds(x, y, w, h); if (!shellBounds.isEmpty()) { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { if (!shellBounds.intersects(displayBounds)) { QRect clientArea(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetAvailableScreenSize()); shellBounds.setX(clientArea.x()); shellBounds.setY(clientArea.y()); } GetShell()->SetBounds(shellBounds); // }}); } QString maximized; memento->GetString(WorkbenchConstants::TAG_MAXIMIZED, maximized); if (maximized == "true") { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { GetShell()->SetMaximized(true); // }}); } QString minimized; memento->GetString(WorkbenchConstants::TAG_MINIMIZED, minimized); if (minimized == "true") { // getShell().setMinimized(true); } // // restore the width of the perspective bar // if (perspectiveSwitcher != null) { // perspectiveSwitcher.restoreState(memento); // } // // Restore the cool bar order by creating all the tool bar contribution // // items // // This needs to be done before pages are created to ensure proper // // canonical creation // // of cool items // final ICoolBarManager2 coolBarMgr = (ICoolBarManager2) getCoolBarManager2(); // if (coolBarMgr != null) { // IMemento coolBarMem = memento // .getChild(IWorkbenchConstants.TAG_COOLBAR_LAYOUT); // if (coolBarMem != null) { // // Check if the layout is locked // final Integer lockedInt = coolBarMem // .getInteger(IWorkbenchConstants.TAG_LOCKED); // StartupThreading.runWithoutExceptions(new StartupRunnable(){ // // public void runWithException() { // if ((lockedInt != null) && (lockedInt.intValue() == 1)) { // coolBarMgr.setLockLayout(true); // } else { // coolBarMgr.setLockLayout(false); // } // }}); // // // The new layout of the cool bar manager // ArrayList coolBarLayout = new ArrayList(); // // Traverse through all the cool item in the memento // IMemento contributionMems[] = coolBarMem // .getChildren(IWorkbenchConstants.TAG_COOLITEM); // for (int i = 0; i < contributionMems.length; i++) { // IMemento contributionMem = contributionMems[i]; // String type = contributionMem // .getString(IWorkbenchConstants.TAG_ITEM_TYPE); // if (type == null) { // // Do not recognize that type // continue; // } // String id = contributionMem // .getString(IWorkbenchConstants.TAG_ID); // // // Prevent duplicate items from being read back in. // IContributionItem existingItem = coolBarMgr.find(id); // if ((id != null) && (existingItem != null)) { // if (Policy.DEBUG_TOOLBAR_DISPOSAL) { // System.out // .println("Not loading duplicate cool bar item: " + id); //$NON-NLS-1$ // } // coolBarLayout.add(existingItem); // continue; // } // IContributionItem newItem = null; // if (type.equals(IWorkbenchConstants.TAG_TYPE_SEPARATOR)) { // if (id != null) { // newItem = new Separator(id); // } else { // newItem = new Separator(); // } // } else if (id != null) { // if (type // .equals(IWorkbenchConstants.TAG_TYPE_GROUPMARKER)) { // newItem = new GroupMarker(id); // // } else if (type // .equals(IWorkbenchConstants.TAG_TYPE_TOOLBARCONTRIBUTION) // || type // .equals(IWorkbenchConstants.TAG_TYPE_PLACEHOLDER)) { // // // Get Width and height // Integer width = contributionMem // .getInteger(IWorkbenchConstants.TAG_ITEM_X); // Integer height = contributionMem // .getInteger(IWorkbenchConstants.TAG_ITEM_Y); // // Look for the object in the current cool bar // // manager // IContributionItem oldItem = coolBarMgr.find(id); // // If a tool bar contribution item already exists // // for this id then use the old object // if (oldItem != null) { // newItem = oldItem; // } else { // IActionBarPresentationFactory actionBarPresentation = getActionBarPresentationFactory(); // newItem = actionBarPresentation.createToolBarContributionItem( // actionBarPresentation.createToolBarManager(), id); // if (type // .equals(IWorkbenchConstants.TAG_TYPE_PLACEHOLDER)) { // IToolBarContributionItem newToolBarItem = (IToolBarContributionItem) newItem; // if (height != null) { // newToolBarItem.setCurrentHeight(height // .intValue()); // } // if (width != null) { // newToolBarItem.setCurrentWidth(width // .intValue()); // } // newItem = new PlaceholderContributionItem( // newToolBarItem); // } // // make it invisible by default // newItem.setVisible(false); // // Need to add the item to the cool bar manager // // so that its canonical order can be preserved // IContributionItem refItem = findAlphabeticalOrder( // IWorkbenchActionConstants.MB_ADDITIONS, // id, coolBarMgr); // if (refItem != null) { // coolBarMgr.insertAfter(refItem.getId(), // newItem); // } else { // coolBarMgr.add(newItem); // } // } // // Set the current height and width // if ((width != null) // && (newItem instanceof IToolBarContributionItem)) { // ((IToolBarContributionItem) newItem) // .setCurrentWidth(width.intValue()); // } // if ((height != null) // && (newItem instanceof IToolBarContributionItem)) { // ((IToolBarContributionItem) newItem) // .setCurrentHeight(height.intValue()); // } // } // } // // Add new item into cool bar manager // if (newItem != null) { // coolBarLayout.add(newItem); // newItem.setParent(coolBarMgr); // coolBarMgr.markDirty(); // } // } // // // We need to check if we have everything we need in the layout. // boolean newlyAddedItems = false; // IContributionItem[] existingItems = coolBarMgr.getItems(); // for (int i = 0; i < existingItems.length && !newlyAddedItems; i++) { // IContributionItem existingItem = existingItems[i]; // // /* // * This line shouldn't be necessary, but is here for // * robustness. // */ // if (existingItem == null) { // continue; // } // // boolean found = false; // Iterator layoutItemItr = coolBarLayout.iterator(); // while (layoutItemItr.hasNext()) { // IContributionItem layoutItem = (IContributionItem) layoutItemItr // .next(); // if ((layoutItem != null) // && (layoutItem.equals(existingItem))) { // found = true; // break; // } // } // // if (!found) { // if (existingItem != null) { // newlyAddedItems = true; // } // } // } // // // Set the cool bar layout to the given layout. // if (!newlyAddedItems) { // final IContributionItem[] itemsToSet = new IContributionItem[coolBarLayout // .size()]; // coolBarLayout.toArray(itemsToSet); // StartupThreading // .runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // coolBarMgr.setItems(itemsToSet); // } // }); // } // // } else { // // For older workbenchs // coolBarMem = memento // .getChild(IWorkbenchConstants.TAG_TOOLBAR_LAYOUT); // if (coolBarMem != null) { // // Restore an older layout // restoreOldCoolBar(coolBarMem); // } // } // } // Recreate each page in the window. IWorkbenchPage::Pointer newActivePage; QList pageArray = memento ->GetChildren(WorkbenchConstants::TAG_PAGE); for (int i = 0; i < pageArray.size(); i++) { IMemento::Pointer pageMem = pageArray[i]; QString strFocus; pageMem->GetString(WorkbenchConstants::TAG_FOCUS, strFocus); if (strFocus.isEmpty()) { continue; } // Get the input factory. IAdaptable* input = 0; IMemento::Pointer inputMem = pageMem->GetChild(WorkbenchConstants::TAG_INPUT); if (inputMem) { QString factoryID; inputMem->GetString(WorkbenchConstants::TAG_FACTORY_ID, factoryID); if (factoryID.isEmpty()) { WorkbenchPlugin ::Log("Unable to restore page - no input factory ID."); //result.add(unableToRestorePage(pageMem)); result &= UnableToRestorePage(pageMem); continue; } // try { // UIStats.start(UIStats.RESTORE_WORKBENCH, // "WorkbenchPageFactory"); //$NON-NLS-1$ // StartupThreading // .runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { // IElementFactory factory = PlatformUI // .getWorkbench().getElementFactory( // factoryID); // if (factory == null) { // WorkbenchPlugin // .log("Unable to restore page - cannot instantiate input factory: " + factoryID); //$NON-NLS-1$ // result // .add(unableToRestorePage(pageMem)); // return; // } // // // Get the input element. // input[0] = factory.createElement(inputMem); // } // }); // // if (input[0] == null) { // WorkbenchPlugin // .log("Unable to restore page - cannot instantiate input element: " + factoryID); //$NON-NLS-1$ // result.add(unableToRestorePage(pageMem)); // continue; // } // } finally { // UIStats.end(UIStats.RESTORE_WORKBENCH, factoryID, // "WorkbenchPageFactory"); //$NON-NLS-1$ // } } // Open the perspective. IAdaptable* finalInput = input; WorkbenchPage::Pointer newPage; try { // StartupThreading.runWithWorkbenchExceptions(new StartupRunnable(){ // // public void runWithException() throws WorkbenchException { newPage = new WorkbenchPage(this, finalInput); // }}); //result.add(newPage[0].restoreState(pageMem, activeDescriptor)); result &= newPage->RestoreState(pageMem, activeDescriptor); pageList.Add(newPage); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { partService.PageOpened(newPage); // firePageOpened(newPage[0]); // }}); } catch (const WorkbenchException& e) { WorkbenchPlugin::Log( "Unable to restore perspective - constructor failed.", e); //$NON-NLS-1$ //result.add(e.getStatus()); continue; } if (!strFocus.isEmpty()) { newActivePage = newPage; } } // If there are no pages create a default. if (pageList.IsEmpty()) { try { const QString defPerspID = this->GetWorkbenchImpl()->GetPerspectiveRegistry() ->GetDefaultPerspective(); if (!defPerspID.isEmpty()) { WorkbenchPage::Pointer newPage; //StartupThreading.runWithWorkbenchExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { newPage = new WorkbenchPage(this, defPerspID, this->GetDefaultPageInput()); // }}); pageList.Add(newPage); //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { // firePageOpened(newPage[0]); partService.PageOpened(newPage); // }}); } } catch (WorkbenchException& e) { WorkbenchPlugin ::Log( "Unable to create default perspective - constructor failed.", e); result = false; //TODO set product name // String productName = WorkbenchPlugin.getDefault() // .getProductName(); // if (productName == null) { // productName = ""; //$NON-NLS-1$ // } // getShell().setText(productName); } } // Set active page. if (newActivePage.IsNull()) { newActivePage = pageList.GetNextActive().Cast(); } //StartupThreading.runWithoutExceptions(new StartupRunnable() { // public void runWithException() throws Throwable { this->SetActivePage(newActivePage); // }}); IMemento::Pointer introMem = memento->GetChild(WorkbenchConstants::TAG_INTRO); if (introMem) { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() throws Throwable { bool isStandby = false; introMem->GetBoolean(WorkbenchConstants::TAG_STANDBY, isStandby); GetWorkbench()->GetIntroManager()->ShowIntro( IWorkbenchWindow::Pointer(this), isStandby); // } // }); } // // // Only restore the trim state if we're using the default layout // if (defaultLayout != null) { // // Restore the trim state. We pass in the 'root' // // memento since we have to check for pre-3.2 // // state. // result.add(restoreTrimState(memento)); // } return result; } IAdaptable* WorkbenchWindow::GetDefaultPageInput() { return this->GetWorkbenchImpl()->GetDefaultPageInput(); } IWorkbenchPage::Pointer WorkbenchWindow::OpenPage( const QString& perspId, IAdaptable* input) { // Run op in busy cursor. IWorkbenchPage::Pointer result; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { result = this->BusyOpenPage(perspId, input); // } return result; } SmartPointer WorkbenchWindow::OpenPage(IAdaptable* input) { QString perspId = this->GetWorkbenchImpl()->GetDefaultPerspectiveId(); return this->OpenPage(perspId, input); } IWorkbenchPage::Pointer WorkbenchWindow::BusyOpenPage( const QString& perspID, IAdaptable* input) { IWorkbenchPage::Pointer newPage; if (pageList.IsEmpty()) { newPage = new WorkbenchPage(this, perspID, input); pageList.Add(newPage); //this->FirePageOpened(newPage); partService.PageOpened(newPage); this->SetActivePage(newPage); } else { IWorkbenchWindow::Pointer window = this->GetWorkbench()->OpenWorkbenchWindow(perspID, input); newPage = window->GetActivePage(); } return newPage; } int WorkbenchWindow::GetNumber() { return number; } void WorkbenchWindow::UpdateActionBars() { if (updateDisabled || UpdatesDeferred()) { return; } // updateAll required in order to enable accelerators on pull-down menus GetMenuBarManager()->Update(false); //GetToolBarManager()->Update(false); //GetStatusLineManager()->Update(false); } void WorkbenchWindow::LargeUpdateStart() { largeUpdates++; } void WorkbenchWindow::LargeUpdateEnd() { if (--largeUpdates == 0) { this->UpdateActionBars(); } } void WorkbenchWindow::SetActivePage(IWorkbenchPage::Pointer in) { if (this->GetActivePage() == in) { return; } // 1FVGTNR: ITPUI:WINNT - busy cursor for switching perspectives //BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { // public void run() { // Deactivate old persp. WorkbenchPage::Pointer currentPage = pageList.GetActive(); if (currentPage.IsNotNull()) { currentPage->OnDeactivate(); } // Activate new persp. if (in.IsNull() || pageList.Contains(in)) { pageList.SetActive(in); } WorkbenchPage::Pointer newPage = pageList.GetActive(); //Composite parent = getPageComposite(); //StackLayout layout = (StackLayout) parent.getLayout(); if (newPage.IsNotNull()) { //layout.topControl = newPage.getClientComposite(); //parent.layout(); this->HideEmptyWindowContents(); newPage->OnActivate(); //this->FirePageActivated(newPage); partService.PageActivated(newPage); //TODO perspective if (newPage->GetPerspective() != 0) { this->FirePerspectiveActivated(newPage, newPage->GetPerspective()); } } else { //layout.topControl = null; //parent.layout(); } //updateFastViewBar(); if (this->IsClosing()) { return; } updateDisabled = false; // Update action bars ( implicitly calls updateActionBars() ) //updateActionSets(); //submitGlobalActions(); //if (perspectiveSwitcher != null) { // perspectiveSwitcher.update(false); //} - //getMenuManager().update(IAction.TEXT); + GetMenuManager()->Update(QActionProperties::TEXT); // } //}); } MenuManager *WorkbenchWindow::GetMenuManager() const { return this->GetMenuBarManager(); } bool WorkbenchWindow::SaveState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.WorkbenchWindow_problemsSavingWindow, null); bool result = true; // Save the window's state and bounds. if (GetShell()->GetMaximized() || asMaximizedState) { memento->PutString(WorkbenchConstants::TAG_MAXIMIZED, "true"); } if (GetShell()->GetMinimized()) { memento->PutString(WorkbenchConstants::TAG_MINIMIZED, "true"); } if (normalBounds.isEmpty()) { normalBounds = GetShell()->GetBounds(); } // IMemento fastViewBarMem = memento // .createChild(IWorkbenchConstants.TAG_FAST_VIEW_DATA); // if (fastViewBar != null) { // fastViewBar.saveState(fastViewBarMem); // } memento->PutInteger(WorkbenchConstants::TAG_X, normalBounds.x()); memento->PutInteger(WorkbenchConstants::TAG_Y, normalBounds.y()); memento->PutInteger(WorkbenchConstants::TAG_WIDTH, normalBounds.width()); memento->PutInteger(WorkbenchConstants::TAG_HEIGHT, normalBounds.height()); IWorkbenchPage::Pointer activePage = GetActivePage(); if (activePage && activePage->FindView(IntroConstants::INTRO_VIEW_ID)) { IMemento::Pointer introMem = memento ->CreateChild(WorkbenchConstants::TAG_INTRO); bool isStandby = GetWorkbench()->GetIntroManager() ->IsIntroStandby(GetWorkbench()->GetIntroManager()->GetIntro()); introMem->PutBoolean(WorkbenchConstants::TAG_STANDBY, isStandby); } // // save the width of the perspective bar // IMemento persBarMem = memento // .createChild(IWorkbenchConstants.TAG_PERSPECTIVE_BAR); // if (perspectiveSwitcher != null) { // perspectiveSwitcher.saveState(persBarMem); // } // // / Save the order of the cool bar contribution items // ICoolBarManager2 coolBarMgr = (ICoolBarManager2) getCoolBarManager2(); // if (coolBarMgr != null) { // coolBarMgr.refresh(); // IMemento coolBarMem = memento // .createChild(IWorkbenchConstants.TAG_COOLBAR_LAYOUT); // if (coolBarMgr.getLockLayout() == true) { // coolBarMem.putInteger(IWorkbenchConstants.TAG_LOCKED, 1); // } else { // coolBarMem.putInteger(IWorkbenchConstants.TAG_LOCKED, 0); // } // IContributionItem[] items = coolBarMgr.getItems(); // for (int i = 0; i < items.length; i++) { // IMemento coolItemMem = coolBarMem // .createChild(IWorkbenchConstants.TAG_COOLITEM); // IContributionItem item = items[i]; // // The id of the contribution item // if (item.getId() != null) { // coolItemMem.putString(IWorkbenchConstants.TAG_ID, item // .getId()); // } // // Write out type and size if applicable // if (item.isSeparator()) { // coolItemMem.putString(IWorkbenchConstants.TAG_ITEM_TYPE, // IWorkbenchConstants.TAG_TYPE_SEPARATOR); // } else if (item.isGroupMarker() && !item.isSeparator()) { // coolItemMem.putString(IWorkbenchConstants.TAG_ITEM_TYPE, // IWorkbenchConstants.TAG_TYPE_GROUPMARKER); // } else { // if (item instanceof PlaceholderContributionItem) { // coolItemMem.putString( // IWorkbenchConstants.TAG_ITEM_TYPE, // IWorkbenchConstants.TAG_TYPE_PLACEHOLDER); // } else { // // Store the identifier. // coolItemMem // .putString( // IWorkbenchConstants.TAG_ITEM_TYPE, // IWorkbenchConstants.TAG_TYPE_TOOLBARCONTRIBUTION); // } // // /* // * Retrieve a reasonable approximation of the height and // * width, if possible. // */ // final int height; // final int width; // if (item instanceof IToolBarContributionItem) { // IToolBarContributionItem toolBarItem = (IToolBarContributionItem) item; // toolBarItem.saveWidgetState(); // height = toolBarItem.getCurrentHeight(); // width = toolBarItem.getCurrentWidth(); // } else if (item instanceof PlaceholderContributionItem) { // PlaceholderContributionItem placeholder = (PlaceholderContributionItem) item; // height = placeholder.getHeight(); // width = placeholder.getWidth(); // } else { // height = -1; // width = -1; // } // // // Store the height and width. // coolItemMem.putInteger(IWorkbenchConstants.TAG_ITEM_X, // width); // coolItemMem.putInteger(IWorkbenchConstants.TAG_ITEM_Y, // height); // } // } // } // Save each page. for (PageList::iterator itr = pageList.Begin(); itr != pageList.End(); ++itr) { WorkbenchPage::Pointer page = itr->Cast(); // Save perspective. IMemento::Pointer pageMem = memento ->CreateChild(WorkbenchConstants::TAG_PAGE); pageMem->PutString(WorkbenchConstants::TAG_LABEL, page->GetLabel()); //result.add(page.saveState(pageMem)); result &= page->SaveState(pageMem); if (page == GetActivePage().Cast()) { pageMem->PutString(WorkbenchConstants::TAG_FOCUS, "true"); } // // Get the input. // IAdaptable* input = page->GetInput(); // if (input != 0) { // IPersistableElement persistable = (IPersistableElement) Util.getAdapter(input, // IPersistableElement.class); // if (persistable == null) { // WorkbenchPlugin // .log("Unable to save page input: " //$NON-NLS-1$ // + input // + ", because it does not adapt to IPersistableElement"); //$NON-NLS-1$ // } else { // // Save input. // IMemento inputMem = pageMem // .createChild(IWorkbenchConstants.TAG_INPUT); // inputMem.putString(IWorkbenchConstants.TAG_FACTORY_ID, // persistable.getFactoryId()); // persistable.saveState(inputMem); // } // } } // Save window advisor state. IMemento::Pointer windowAdvisorState = memento ->CreateChild(WorkbenchConstants::TAG_WORKBENCH_WINDOW_ADVISOR); //result.add(getWindowAdvisor().saveState(windowAdvisorState)); result &= GetWindowAdvisor()->SaveState(windowAdvisorState); // Save actionbar advisor state. IMemento::Pointer actionBarAdvisorState = memento ->CreateChild(WorkbenchConstants::TAG_ACTION_BAR_ADVISOR); //result.add(getActionBarAdvisor().saveState(actionBarAdvisorState)); result &= GetActionBarAdvisor()->SaveState(actionBarAdvisorState); // // Only save the trim state if we're using the default layout // if (defaultLayout != null) { // IMemento trimState = memento.createChild(IWorkbenchConstants.TAG_TRIM); // result.add(saveTrimState(trimState)); // } return result; } WorkbenchWindowConfigurer::Pointer WorkbenchWindow::GetWindowConfigurer() const { if (windowConfigurer.IsNull()) { // lazy initialize windowConfigurer = new WorkbenchWindowConfigurer(WorkbenchWindow::Pointer(const_cast(this))); } return windowConfigurer; } bool WorkbenchWindow::CanHandleShellCloseEvent() { if (!Window::CanHandleShellCloseEvent()) { return false; } // let the advisor or other interested parties // veto the user's explicit request to close the window return FireWindowShellClosing(); } void WorkbenchWindow::ConfigureShell(Shell::Pointer shell) { Window::ConfigureShell(shell); detachedWindowShells = new ShellPool(shell, Constants::TITLE | Constants::MAX | Constants::CLOSE | Constants::RESIZE | Constants::BORDER ); QString title = this->GetWindowConfigurer()->BasicGetTitle(); if (!title.isEmpty()) { shell->SetText(title); } //IWorkbench* workbench = this->GetWorkbench(); // workbench.getHelpSystem().setHelp(shell, // IWorkbenchHelpContextIds.WORKBENCH_WINDOW); //IContextService* contextService = workbench->GetService(); //contextService->RegisterShell(shell, IContextService::TYPE_WINDOW); shell->GetControl()->installEventFilter(&resizeEventFilter); } ShellPool::Pointer WorkbenchWindow::GetDetachedWindowPool() { return detachedWindowShells; } WorkbenchAdvisor* WorkbenchWindow::GetAdvisor() { return this->GetWorkbenchImpl()->GetAdvisor(); } WorkbenchWindowAdvisor* WorkbenchWindow::GetWindowAdvisor() { if (windowAdvisor == 0) { windowAdvisor = this->GetAdvisor()->CreateWorkbenchWindowAdvisor(this->GetWindowConfigurer()); poco_check_ptr(windowAdvisor); } return windowAdvisor; } ActionBarAdvisor::Pointer WorkbenchWindow::GetActionBarAdvisor() { if (actionBarAdvisor.IsNull()) { actionBarAdvisor = this->GetWindowAdvisor()->CreateActionBarAdvisor(this->GetWindowConfigurer()->GetActionBarConfigurer()); poco_assert(actionBarAdvisor.IsNotNull()); } return actionBarAdvisor; } Workbench* WorkbenchWindow::GetWorkbenchImpl() { return dynamic_cast(this->GetWorkbench()); } void WorkbenchWindow::ShowEmptyWindowContents() { if (!emptyWindowContentsCreated) { QWidget* parent = this->GetPageComposite(); emptyWindowContents = this->GetWindowAdvisor()->CreateEmptyWindowContents( parent); emptyWindowContentsCreated = true; // // force the empty window composite to be layed out // ((StackLayout) parent.getLayout()).topControl = emptyWindowContents; // parent.layout(); } } void WorkbenchWindow::HideEmptyWindowContents() { if (emptyWindowContentsCreated) { if (emptyWindowContents != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->Dispose(emptyWindowContents); emptyWindowContents = 0; //this->GetPageComposite().layout(); } emptyWindowContentsCreated = false; } } WorkbenchWindow::ServiceLocatorOwner::ServiceLocatorOwner(WorkbenchWindow* wnd) : window(wnd) { } void WorkbenchWindow::ServiceLocatorOwner::Dispose() { Shell::Pointer shell = window->GetShell(); if (shell != 0) { window->Close(); } } bool WorkbenchWindow::PageList::Add(IWorkbenchPage::Pointer object) { pagesInCreationOrder.push_back(object); pagesInActivationOrder.push_front(object); // It will be moved to top only when activated. return true; } WorkbenchWindow::PageList::iterator WorkbenchWindow::PageList::Begin() { return pagesInCreationOrder.begin(); } WorkbenchWindow::PageList::iterator WorkbenchWindow::PageList::End() { return pagesInCreationOrder.end(); } bool WorkbenchWindow::PageList::Contains(IWorkbenchPage::Pointer object) { return std::find(pagesInCreationOrder.begin(), pagesInCreationOrder.end(), object) != pagesInCreationOrder.end(); } bool WorkbenchWindow::PageList::Remove(IWorkbenchPage::Pointer object) { if (active == object) { active = 0; } pagesInActivationOrder.removeAll(object); const int origSize = pagesInCreationOrder.size(); pagesInCreationOrder.removeAll(object); return origSize != pagesInCreationOrder.size(); } void WorkbenchWindow::PageList::Clear() { pagesInCreationOrder.clear(); pagesInActivationOrder.clear(); active = 0; } bool WorkbenchWindow::PageList::IsEmpty() { return pagesInCreationOrder.empty(); } QList WorkbenchWindow::PageList::GetPages() const { return pagesInCreationOrder; } void WorkbenchWindow::PageList::SetActive(IWorkbenchPage::Pointer page) { if (active == page) { return; } active = page; if (page.IsNotNull()) { pagesInActivationOrder.removeAll(page); pagesInActivationOrder.push_back(page); } } WorkbenchPage::Pointer WorkbenchWindow::PageList::GetActive() const { return active.Cast(); } WorkbenchPage::Pointer WorkbenchWindow::PageList::GetNextActive() { if (active.IsNull()) { if (pagesInActivationOrder.empty()) { return WorkbenchPage::Pointer(0); } return pagesInActivationOrder.back().Cast(); } if (pagesInActivationOrder.size() < 2) { return WorkbenchPage::Pointer(0); } return pagesInActivationOrder.at(pagesInActivationOrder.size()-2).Cast(); } bool WorkbenchWindow::UpdatesDeferred() const { return largeUpdates > 0; } void WorkbenchWindow::InitializeDefaultServices() { workbenchLocationService.reset( new WorkbenchLocationService(IServiceScopes::WINDOW_SCOPE, GetWorkbench(), this, NULL, 1)); workbenchLocationService->Register(); serviceLocator->RegisterService(workbenchLocationService.data()); //ActionCommandMappingService* mappingService = new ActionCommandMappingService(); //serviceLocator->RegisterService(IActionCommandMappingService, mappingService); } QSet > WorkbenchWindow::GetMenuRestrictions() const { return QSet >(); } void WorkbenchWindow::FirePropertyChanged(const QString& property, const Object::Pointer& oldValue, const Object::Pointer& newValue) { PropertyChangeEvent::Pointer event(new PropertyChangeEvent(Object::Pointer(this), property, oldValue, newValue)); genericPropertyListeners.propertyChange(event); } WorkbenchWindow::ShellEventFilter::ShellEventFilter(WorkbenchWindow* window) : window(window) { } bool WorkbenchWindow::ShellEventFilter::eventFilter(QObject* watched, QEvent* event) { QEvent::Type eventType = event->type(); if (eventType == QEvent::Move || eventType == QEvent::Resize) { QWidget* widget = static_cast(watched); QRect newBounds = widget->geometry(); if (eventType == QEvent::Move) { newBounds.setTopLeft(static_cast(event)->pos()); } else if(eventType == QEvent::Resize) { newBounds.setSize(static_cast(event)->size()); } this->SaveBounds(newBounds); } else if (eventType == QEvent::WindowActivate) { this->ShellActivated(); } else if (eventType == QEvent::WindowDeactivate) { this->ShellDeactivated(); } return false; } void WorkbenchWindow::ShellEventFilter::SaveBounds(const QRect& newBounds) { Shell::Pointer shell = window->GetShell(); if (shell == 0) { return; } // if (shell->IsDisposed()) // { // return; // } if (shell->GetMinimized()) { return; } if (shell->GetMaximized()) { window->asMaximizedState = true; return; } window->asMaximizedState = false; window->normalBounds = newBounds; } void WorkbenchWindow::ShellEventFilter::ShellActivated() { WorkbenchWindow::Pointer wnd(window); wnd->shellActivated = true; wnd->serviceLocator->Activate(); wnd->GetWorkbenchImpl()->SetActivatedWindow(wnd); WorkbenchPage::Pointer currentPage = wnd->GetActivePage().Cast(); if (currentPage != 0) { IWorkbenchPart::Pointer part = currentPage->GetActivePart(); if (part != 0) { PartSite::Pointer site = part->GetSite().Cast(); site->GetPane()->ShellActivated(); } IEditorPart::Pointer editor = currentPage->GetActiveEditor(); if (editor != 0) { PartSite::Pointer site = editor->GetSite().Cast(); site->GetPane()->ShellActivated(); } wnd->GetWorkbenchImpl()->FireWindowActivated(wnd); } //liftRestrictions(); } void WorkbenchWindow::ShellEventFilter::ShellDeactivated() { WorkbenchWindow::Pointer wnd(window); wnd->shellActivated = false; //imposeRestrictions(); wnd->serviceLocator->Deactivate(); WorkbenchPage::Pointer currentPage = wnd->GetActivePage().Cast(); if (currentPage != 0) { IWorkbenchPart::Pointer part = currentPage->GetActivePart(); if (part != 0) { PartSite::Pointer site = part->GetSite().Cast(); site->GetPane()->ShellDeactivated(); } IEditorPart::Pointer editor = currentPage->GetActiveEditor(); if (editor != 0) { PartSite::Pointer site = editor->GetSite().Cast(); site->GetPane()->ShellDeactivated(); } wnd->GetWorkbenchImpl()->FireWindowDeactivated(wnd); } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.h index 56e4959585..f0b85983ad 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryWorkbenchWindow.h @@ -1,713 +1,709 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYWORKBENCHWINDOW_H_ #define BERRYWORKBENCHWINDOW_H_ #include "berryIWorkbenchWindow.h" #include "berryIPerspectiveListener.h" #include "berryWindow.h" #include "berryWorkbenchWindowConfigurer.h" #include "berryShellPool.h" #include "berryServiceLocator.h" #include "berryWWinPartService.h" #include "application/berryWorkbenchAdvisor.h" #include "application/berryWorkbenchWindowAdvisor.h" #include "application/berryActionBarAdvisor.h" #include #include namespace berry { struct IEvaluationReference; struct IWorkbench; struct IWorkbenchPage; struct IPartService; struct ISelectionService; struct IPerspectiveDescriptor; struct IWorkbenchLocationService; class Workbench; class WorkbenchPage; class WWinActionBars; /** * \ingroup org_blueberry_ui_qt * */ class BERRY_UI_QT WorkbenchWindow: public Window, public IWorkbenchWindow { public: /** * Toolbar visibility change property. */ static const QString PROP_TOOLBAR_VISIBLE; // = "toolbarVisible"; /** * Perspective bar visibility change property. */ static const QString PROP_PERSPECTIVEBAR_VISIBLE; // = "perspectiveBarVisible"; /** * The status line visibility change property. for internal use only. */ static const QString PROP_STATUS_LINE_VISIBLE; // = "statusLineVisible"; public: - berryObjectMacro(WorkbenchWindow) + berryObjectMacro(WorkbenchWindow, Window, IWorkbenchWindow) WorkbenchWindow(int number); ~WorkbenchWindow(); Object* GetService(const QString& key); bool HasService(const QString& key) const; int Open(); bool Close(); Shell::Pointer GetShell() const; /** * @see org.blueberry.ui.IPageService */ void AddPerspectiveListener(IPerspectiveListener* l); /** * @see org.blueberry.ui.IPageService */ void RemovePerspectiveListener(IPerspectiveListener* l); /** * @see org.blueberry.ui.IPageService */ IPerspectiveListener::Events& GetPerspectiveEvents(); /** * Returns the action bars for this window. */ WWinActionBars* GetActionBars(); SmartPointer GetActivePage() const; - SmartPointer GetPage(int i) const; + QList > GetPages() const; void SetPerspectiveExcludeList(const QStringList& v); QStringList GetPerspectiveExcludeList() const; void SetViewExcludeList(const QStringList& v); QStringList GetViewExcludeList() const; /** * Sets the active page within the window. * * @param in * identifies the new active page, or null for no * active page */ void SetActivePage(SmartPointer in); /** * Answer the menu manager for this window. */ MenuManager* GetMenuManager() const; - IWorkbench* GetWorkbench(); + IWorkbench* GetWorkbench() const; IPartService* GetPartService(); - ISelectionService* GetSelectionService(); + ISelectionService* GetSelectionService() const; /** * @return whether the tool bar should be shown. This is only applicable if * the window configurer also wishes the cool bar to be visible. */ bool GetToolBarVisible() const; /** * @return whether the perspective bar should be shown. This is only * applicable if the window configurer also wishes the perspective * bar to be visible. */ bool GetPerspectiveBarVisible() const; /** * @return whether the status line should be shown. This is only applicable if * the window configurer also wishes status line to be visible. */ bool GetStatusLineVisible() const; /** * Add a generic property listener. * * @param listener the listener to add */ void AddPropertyChangeListener(IPropertyChangeListener* listener); /** * Removes a generic property listener. * * @param listener the listener to remove */ void RemovePropertyChangeListener(IPropertyChangeListener* listener); SmartPointer OpenPage(const QString& perspectiveId, IAdaptable* input); SmartPointer OpenPage(IAdaptable* input); //TODO menu manager //virtual QWidget* GetMenuManager() = 0; virtual bool SaveState(IMemento::Pointer memento); /** * Called when this window is about to be closed. * * Subclasses may overide to add code that returns false to * prevent closing under certain conditions. */ virtual bool OkToClose(); bool RestoreState(IMemento::Pointer memento, SmartPointer< IPerspectiveDescriptor> activeDescriptor); /** * Returns the number. This corresponds to a page number in a window or a * window number in the workbench. */ int GetNumber(); /** * update the action bars. */ void UpdateActionBars(); /** *

* Indicates the start of a large update within this window. This is used to * disable CPU-intensive, change-sensitive services that were temporarily * disabled in the midst of large changes. This method should always be * called in tandem with largeUpdateEnd, and the event loop * should not be allowed to spin before that method is called. *

*

* Important: always use with largeUpdateEnd! *

* * @since 3.1 */ void LargeUpdateStart(); /** *

* Indicates the end of a large update within this window. This is used to * re-enable services that were temporarily disabled in the midst of large * changes. This method should always be called in tandem with * largeUpdateStart, and the event loop should not be * allowed to spin before this method is called. *

*

* Important: always protect this call by using finally! *

* * @since 3.1 */ void LargeUpdateEnd(); QSet > GetMenuRestrictions() const; protected: friend class WorkbenchConfigurer; friend class WorkbenchWindowConfigurer; friend class WorkbenchWindowConfigurer::WindowActionBarConfigurer; friend class Workbench; friend class LayoutPartSash; friend class EditorSashContainer; friend class WorkbenchPage; friend class DetachedWindow; /** * Returns the GUI dependent page composite, under which the window's * pages create their controls. */ QWidget* GetPageComposite(); /** * Creates and remembers the client composite, under which workbench pages * create their controls. */ QWidget* CreatePageComposite(QWidget* parent); /** * Creates the contents of the workbench window, including trim controls and * the client composite. This MUST create the client composite via a call to * createClientComposite. * * @since 3.0 */ QWidget* CreateContents(Shell::Pointer parent); /** * Creates the default contents and layout of the shell. * * @param shell * the shell */ virtual void CreateDefaultContents(Shell::Pointer shell); void CreateTrimWidgets(SmartPointer shell); /** * Returns the unique object that applications use to configure this window. *

* IMPORTANT This method is declared package-private to prevent regular * plug-ins from downcasting IWorkbenchWindow to WorkbenchWindow and getting * hold of the workbench window configurer that would allow them to tamper * with the workbench window. The workbench window configurer is available * only to the application. *

*/ WorkbenchWindowConfigurer::Pointer GetWindowConfigurer() const; bool CanHandleShellCloseEvent(); /* * @see berry::Window#configureShell(Shell::Pointer) */ void ConfigureShell(Shell::Pointer shell); ShellPool::Pointer GetDetachedWindowPool(); /** * Fills the window's real action bars. * * @param flags * indicate which bars to fill */ void FillActionBars(ActionBarAdvisor::FillFlags flags); /** * The WorkbenchWindow implementation of this method * delegates to the window configurer. * * @since 3.0 */ QPoint GetInitialSize(); /** * Returns the default page input for workbench pages opened in this window. * * @return the default page input or null if none * @since 3.1 */ IAdaptable* GetDefaultPageInput(); bool IsClosing(); /** * Opens a new page. Assumes that busy cursor is 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.openPerspective APIs to * programmatically show a perspective. *

*/ SmartPointer BusyOpenPage(const QString& perspID, IAdaptable* input); bool ClosePage(SmartPointer in, bool save); /** * Makes the window visible and frontmost. */ void MakeVisible(); /** * The composite under which workbench pages create their controls. */ QWidget* pageComposite; private: /** * Constant indicating that all the actions bars should be filled. - * - * @since 3.0 */ static const ActionBarAdvisor::FillFlags FILL_ALL_ACTION_BARS; ShellPool::Pointer detachedWindowShells; /** * Object for configuring this workbench window. Lazily initialized to an * instance unique to this window. - * - * @since 3.0 */ mutable WorkbenchWindowConfigurer::Pointer windowConfigurer; WorkbenchWindowAdvisor* windowAdvisor; ActionBarAdvisor::Pointer actionBarAdvisor; SmartPointer actionBars; IPropertyChangeListener::Events genericPropertyListeners; int number; /** * The number of large updates that are currently going on. If this is * number is greater than zero, then UI updateActionBars is a no-op. */ int largeUpdates; bool closing; bool shellActivated; bool updateDisabled; bool toolBarVisible; bool perspectiveBarVisible; bool statusLineVisible; /** * The map of services maintained by the workbench window. These services * are initialized during workbench window during the * {@link #configureShell(Shell)}. */ ServiceLocator::Pointer serviceLocator; QScopedPointer workbenchLocationService; bool emptyWindowContentsCreated; QWidget* emptyWindowContents; QRect normalBounds; bool asMaximizedState; IPerspectiveListener::Events perspectiveEvents; WWinPartService partService; QStringList perspectiveExcludeList; QStringList viewExcludeList; struct ServiceLocatorOwner: public IDisposable { ServiceLocatorOwner(WorkbenchWindow* wnd); WorkbenchWindow* window; void Dispose(); }; IDisposable::Pointer serviceLocatorOwner; class PageList { private: // List of pages in the order they were created; QList > pagesInCreationOrder; // List of pages where the top is the last activated. QList > pagesInActivationOrder; // The page explicitly activated SmartPointer active; public: typedef QList >::iterator iterator; bool Add(SmartPointer object); iterator Begin(); iterator End(); void Clear(); bool Contains(SmartPointer object); bool Remove(SmartPointer object); bool IsEmpty(); QList > GetPages() const; void SetActive(SmartPointer page); SmartPointer GetActive() const; SmartPointer GetNextActive(); }; PageList pageList; /** * Notifies interested parties (namely the advisor) that the window is about * to be opened. * * @since 3.1 */ void FireWindowOpening(); /** * Notifies interested parties (namely the advisor) that the window has been * restored from a previously saved state. * * @throws WorkbenchException * passed through from the advisor * @since 3.1 */ void FireWindowRestored(); /** * Notifies interested parties (namely the advisor) that the window has been * created. * * @since 3.1 */ void FireWindowCreated(); /** * Notifies interested parties (namely the advisor and the window listeners) * that the window has been opened. * * @since 3.1 */ void FireWindowOpened(); /** * Notifies interested parties (namely the advisor) that the window's shell * is closing. Allows the close to be vetoed. * * @return true if the close should proceed, * false if it should be canceled * @since 3.1 */ bool FireWindowShellClosing(); /** * Notifies interested parties (namely the advisor and the window listeners) * that the window has been closed. * * @since 3.1 */ void FireWindowClosed(); // /** // * Fires page activated // */ // void FirePageActivated(IWorkbenchPage::Pointer page); // // /** // * Fires page closed // */ // void FirePageClosed(IWorkbenchPage::Pointer page); // // /** // * Fires page opened // */ // void FirePageOpened(IWorkbenchPage::Pointer page); /** * Fires perspective activated */ void FirePerspectiveActivated(SmartPointer page, IPerspectiveDescriptor::Pointer perspective); /** * Fires perspective deactivated. * * @since 3.2 */ void FirePerspectivePreDeactivate(SmartPointer page, IPerspectiveDescriptor::Pointer perspective); /** * Fires perspective deactivated. * * @since 3.1 */ void FirePerspectiveDeactivated(SmartPointer page, IPerspectiveDescriptor::Pointer perspective); /** * Fires perspective changed */ void FirePerspectiveChanged(SmartPointer , IPerspectiveDescriptor::Pointer perspective, const QString& changeId); /** * Fires perspective changed for an affected part */ void FirePerspectiveChanged(SmartPointer , IPerspectiveDescriptor::Pointer perspective, IWorkbenchPartReference::Pointer partRef, const QString& changeId); /** * Fires perspective closed */ void FirePerspectiveClosed(SmartPointer , IPerspectiveDescriptor::Pointer perspective); /** * Fires perspective opened */ void FirePerspectiveOpened(SmartPointer , IPerspectiveDescriptor::Pointer perspective); /** * Fires perspective saved as. * * @since 3.1 */ void FirePerspectiveSavedAs(SmartPointer , IPerspectiveDescriptor::Pointer oldPerspective, IPerspectiveDescriptor::Pointer newPerspective); /** * Returns the workbench advisor. Assumes the workbench has been created * already. *

* IMPORTANT This method is declared private to prevent regular plug-ins * from downcasting IWorkbenchWindow to WorkbenchWindow and getting hold of * the workbench advisor that would allow them to tamper with the workbench. * The workbench advisor is internal to the application. *

*/ /* private - DO NOT CHANGE */ WorkbenchAdvisor* GetAdvisor(); /** * Returns the window advisor, creating a new one for this window if needed. *

* IMPORTANT This method is declared private to prevent regular plug-ins * from downcasting IWorkbenchWindow to WorkbenchWindow and getting hold of * the window advisor that would allow them to tamper with the window. The * window advisor is internal to the application. *

*/ /* private - DO NOT CHANGE */ WorkbenchWindowAdvisor* GetWindowAdvisor(); /** * Returns the action bar advisor, creating a new one for this window if * needed. *

* IMPORTANT This method is declared private to prevent regular plug-ins * from downcasting IWorkbenchWindow to WorkbenchWindow and getting hold of * the action bar advisor that would allow them to tamper with the window's * action bars. The action bar advisor is internal to the application. *

*/ /* private - DO NOT CHANGE */ ActionBarAdvisor::Pointer GetActionBarAdvisor(); /* * Returns the IWorkbench implementation. */ Workbench* GetWorkbenchImpl(); bool UnableToRestorePage(IMemento::Pointer pageMem); /** * Close the window. * * Assumes that busy cursor is active. */ bool BusyClose(); /** * Unconditionally close this window. Assumes the proper flags have been set * correctly (e.i. closing and updateDisabled) */ bool HardClose(); /** * Close all of the pages. */ void CloseAllPages(); /** * Save all of the pages. Returns true if the operation succeeded. */ bool SaveAllPages(bool bConfirm); void ShowEmptyWindowContents(); void HideEmptyWindowContents(); struct ShellEventFilter : public QObject { ShellEventFilter(WorkbenchWindow* window); bool eventFilter(QObject* watched, QEvent* event); private: void SaveBounds(const QRect& newBounds); void ShellActivated(); void ShellDeactivated(); WorkbenchWindow* window; }; ShellEventFilter resizeEventFilter; /** * Hooks a listener to track the resize of the window's shell. Stores the * new bounds if in normal state - that is, not in minimized or maximized * state) */ void TrackShellResize(Shell::Pointer newShell); /** * Returns true iff we are currently deferring UI processing due to a large * update * * @return true iff we are deferring UI updates. */ bool UpdatesDeferred() const; /** * Initializes all of the default command-based services for the workbench * window. */ void InitializeDefaultServices(); void FirePropertyChanged(const QString& property, const Object::Pointer& oldValue, const Object::Pointer& newValue); }; } #endif /*BERRYWORKBENCHWINDOW_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQCTabBar.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQCTabBar.cpp index 2847bb8596..6ada3bcb0a 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQCTabBar.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQCTabBar.cpp @@ -1,110 +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 "berryQCTabBar.h" #include #include namespace berry { QCTabBar::QCTabBar(QWidget* parent) : QTabBar(parent) { } QCTabBar::~QCTabBar() { qDeleteAll(tabItemList); } void QCTabBar::tabRemoved(int index) { if (index >= 0 && index < tabItemList.size()) { delete tabItemList.takeAt(index); } } void QCTabBar::mousePressEvent(QMouseEvent* event) { if (event->button() == Qt::LeftButton) dragStartPosition = event->globalPos(); QTabBar::mousePressEvent(event); } void QCTabBar::mouseMoveEvent(QMouseEvent* event) { if (!(event->buttons() & Qt::LeftButton)) { QTabBar::mouseMoveEvent(event); return; } if ((event->globalPos() - dragStartPosition).manhattanLength() < QApplication::startDragDistance()) { QTabBar::mouseMoveEvent(event); return; } emit dragStarted(dragStartPosition); } AbstractTabItem* QCTabBar::getTab(int index) const { - if (index < 0 || ((unsigned int) index) >= tabItemList.size()) return 0; + if (index < 0 || index >= tabItemList.size()) return 0; return tabItemList[index]; } QList QCTabBar::getTabs() const { return tabItemList; } void QCTabBar::insertTab(int index, AbstractTabItem* item) { tabItemList.insert(index, item); QTabBar::insertTab(index, QString()); } void QCTabBar::moveAbstractTab(int from, int to) { AbstractTabItem* item = tabItemList[from]; - if ((unsigned int)to >= tabItemList.size()) --to; + if (to >= tabItemList.size()) --to; tabItemList.removeAt(from); tabItemList.insert(to, item); this->moveTab(from, to); } void QCTabBar::setCurrentTab(AbstractTabItem* item) { this->setCurrentIndex(tabItemList.indexOf(item)); } AbstractTabItem* QCTabBar::getCurrentTab() { int index = this->currentIndex(); return tabItemList[index]; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryMessageDialogWithToggle.cpp similarity index 61% copy from BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryMessageDialogWithToggle.cpp index 3b9d740123..11a5fbb4af 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryMessageDialogWithToggle.cpp @@ -1,25 +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 "berryIBerryPreferences.h" +#include "berryMessageDialogWithToggle.h" +#include "ui_berryMessageDialogWithToggle.h" -namespace berry { - -IBerryPreferences::~IBerryPreferences () +MessageDialogWithToggle::MessageDialogWithToggle(QWidget *parent) : + QDialog(parent), + ui(new Ui::MessageDialogWithToggle) { + ui->setupUi(this); } +MessageDialogWithToggle::~MessageDialogWithToggle() +{ + delete ui; } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryMessageDialogWithToggle.h similarity index 59% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryMessageDialogWithToggle.h index 1fd4128836..7f40247efb 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryMessageDialogWithToggle.h @@ -1,45 +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 BERRYMESSAGEDIALOGWITHTOGGLE_H +#define BERRYMESSAGEDIALOGWITHTOGGLE_H -#ifndef BERRYMMMENULISTENER_H -#define BERRYMMMENULISTENER_H +#include -#include - -namespace berry -{ - -class MenuManager; +namespace Ui { +class MessageDialogWithToggle; +} -class MMMenuListener : public QObject +class MessageDialogWithToggle : public QDialog { Q_OBJECT - berry::MenuManager* mm; - public: - - MMMenuListener(berry::MenuManager* mm); + explicit MessageDialogWithToggle(QWidget *parent = 0); + ~MessageDialogWithToggle(); private: - - Q_SLOT void HandleAboutToShow(); + Ui::MessageDialogWithToggle *ui; }; -} - -#endif // BERRYMMMENULISTENER_H +#endif // BERRYMESSAGEDIALOGWITHTOGGLE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryMessageDialogWithToggle.ui b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryMessageDialogWithToggle.ui new file mode 100644 index 0000000000..d22eee00e1 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryMessageDialogWithToggle.ui @@ -0,0 +1,89 @@ + + + MessageDialogWithToggle + + + + 0 + 0 + 400 + 300 + + + + Dialog + + + + + + + + TextLabel + + + + + + + TextLabel + + + + + + + + + CheckBox + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + buttonBox + accepted() + MessageDialogWithToggle + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + MessageDialogWithToggle + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp new file mode 100644 index 0000000000..bff6cdb97e --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.cpp @@ -0,0 +1,288 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY 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 "berryPerspectivesPreferencePage.h" +#include "ui_berryPerspectivesPreferencePage.h" + +#include +#include +#include + +#include "internal/berryPerspective.h" +#include "internal/berryPerspectiveRegistry.h" +#include "internal/berryPreferenceConstants.h" +#include "internal/berryWorkbenchPage.h" +#include "internal/berryWorkbenchPlugin.h" + +#include +#include + +namespace berry { + +bool PerspectiveComparator(const PerspectiveDescriptor::Pointer& p1, const PerspectiveDescriptor::Pointer& p2) +{ + return p1->GetLabel() < p2->GetLabel(); +} + +PerspectivesPreferencePage::PerspectivesPreferencePage() + : ui(nullptr) + , pageWidget(nullptr) + , workbench(nullptr) + , perspRegistry(nullptr) +{ +} + +PerspectivesPreferencePage::~PerspectivesPreferencePage() +{ + delete ui; +} + + +void PerspectivesPreferencePage::Init(berry::IWorkbench::Pointer workbench) +{ + ui = new Ui::PerspectivesPreferencePage; + + this->workbench = workbench.GetPointer(); + perspRegistry = dynamic_cast(workbench->GetPerspectiveRegistry()); +} + +void PerspectivesPreferencePage::CreateQtControl(QWidget* parent) +{ + pageWidget = new QWidget(parent); + ui->setupUi(pageWidget); + + ui->perspectivesListWidget->setSelectionMode(QAbstractItemView::SingleSelection); + ui->perspectivesListWidget->setIconSize(QSize(16, 16)); + + connect(ui->sameWindowButton, SIGNAL(clicked()), this, SLOT(OpenPerspInSameWindow())); + connect(ui->newWindowButton, SIGNAL(clicked()), this, SLOT(OpenPerspInNewWindow())); + connect(ui->perspectivesListWidget, SIGNAL(itemSelectionChanged()), this, SLOT(PerspectiveSelectionChanged())); + + connect(ui->revertButton, SIGNAL(clicked()), this, SLOT(RevertPerspective())); + connect(ui->makeDefaultButton, SIGNAL(clicked()), this, SLOT(MakeDefaultPerspective())); + connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(DeletePerspective())); + + this->Update(); +} + +QWidget* PerspectivesPreferencePage::GetQtControl() const +{ + return pageWidget; +} + +bool PerspectivesPreferencePage::PerformOk() +{ + // Set the default perspective + if (defaultPerspectiveId != perspRegistry->GetDefaultPerspective()) + { + perspRegistry->SetDefaultPerspective(defaultPerspectiveId); + } + + //Delete the perspective + if(perspectives.size() < perspRegistry->GetPerspectives().size()) + { + QList windows = workbench->GetWorkbenchWindows(); + + // close any perspectives that are about to be deleted + for (int i = 0; i < windows.size(); i++) + { + QList pages = windows[i]->GetPages(); + for (int j = 0; j < pages.size(); j++) + { + WorkbenchPage::Pointer page = pages[j].Cast(); + for (int k = 0; k < perspToDelete.size(); k++) + { + IPerspectiveDescriptor::Pointer desc(perspToDelete[k].GetPointer()); + if (page->FindPerspective(desc).IsNotNull()) + { + page->ClosePerspective(desc, true, true); + } + } + } + } + perspRegistry->DeletePerspectives(perspToDelete); + } + + // Revert the perspectives + perspRegistry->RevertPerspectives(perspToRevert); + + // store the open perspective mode setting + preferences->PutInt(PreferenceConstants::OPEN_PERSP_MODE, openPerspMode); + + return true; +} + +void PerspectivesPreferencePage::PerformCancel() +{ + +} + +void PerspectivesPreferencePage::Update() +{ + preferences = WorkbenchPlugin::GetDefault()->GetPreferences(); + + openPerspMode = preferences->GetInt(PreferenceConstants::OPEN_PERSP_MODE, PreferenceConstants::OPM_ACTIVE_PAGE); + + ui->sameWindowButton->setChecked(openPerspMode == PreferenceConstants::OPM_ACTIVE_PAGE); + ui->newWindowButton->setChecked(openPerspMode == PreferenceConstants::OPM_NEW_WINDOW); + + // Populate the perspectivesTable + perspectives.clear(); + perspToRevert.clear(); + perspToDelete.clear(); + QList persps = perspRegistry->GetPerspectives(); + for (int i = 0; i < persps.size(); i++) + { + perspectives.push_back(persps[i].Cast()); + } + qSort(perspectives.begin(), perspectives.end(), PerspectiveComparator); + defaultPerspectiveId = perspRegistry->GetDefaultPerspective(); + UpdatePerspectivesTable(); +} + +void PerspectivesPreferencePage::OpenPerspInSameWindow() +{ + openPerspMode = PreferenceConstants::OPM_ACTIVE_PAGE; +} + +void PerspectivesPreferencePage::OpenPerspInNewWindow() +{ + openPerspMode = PreferenceConstants::OPM_NEW_WINDOW; +} + +void PerspectivesPreferencePage::PerspectiveSelectionChanged() +{ + UpdateButtons(); +} + +void PerspectivesPreferencePage::RevertPerspective() +{ + PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); + if (desc.IsNotNull() && !perspToRevert.contains(desc)) + { + perspToRevert.push_back(desc); + } + UpdateButtons(); +} + +void PerspectivesPreferencePage::DeletePerspective() +{ + PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); + if (desc.IsNotNull() && !perspToDelete.contains(desc)) + { + if (!FindOpenInstance(desc)) + { + perspToDelete.push_back(desc); + perspToRevert.removeAll(desc); + perspectives.removeAll(desc); + UpdatePerspectivesTable(); + } + } + UpdateButtons(); +} + +void PerspectivesPreferencePage::MakeDefaultPerspective() +{ + PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); + if (desc.IsNotNull() && !perspToDelete.contains(desc)) + { + int row = perspectives.indexOf(desc); + defaultPerspectiveId = desc->GetId(); + UpdatePerspectivesTable(); + ui->perspectivesListWidget->item(row)->setSelected(true); + } + UpdateButtons(); +} + +void PerspectivesPreferencePage::UpdateButtons() +{ + PerspectiveDescriptor::Pointer desc = GetSelectedPerspective(); + if (desc) + { + ui->revertButton->setEnabled(desc->IsPredefined() && desc->HasCustomDefinition() && !perspToRevert.contains(desc)); + ui->deleteButton->setEnabled(!desc->IsPredefined()); + ui->makeDefaultButton->setEnabled(true); + } + else + { + ui->revertButton->setEnabled(false); + ui->deleteButton->setEnabled(false); + ui->makeDefaultButton->setEnabled(false); + } +} + +void PerspectivesPreferencePage::UpdatePerspectivesTable() +{ + ui->perspectivesListWidget->clear(); + for (PerspectiveDescriptor::Pointer desc : perspectives) + { + NewPerspectivesTableItem(desc); + } +} + +void PerspectivesPreferencePage::NewPerspectivesTableItem(const SmartPointer& desc) +{ + QString label = desc->GetLabel(); + if (desc->GetId() == defaultPerspectiveId) + { + label += " (default)"; + } + new QListWidgetItem(desc->GetImageDescriptor(), label, ui->perspectivesListWidget); +} + +bool PerspectivesPreferencePage::FindOpenInstance(const PerspectiveDescriptor::Pointer& desc) +{ + QList windows = workbench->GetWorkbenchWindows(); + + //find all active perspectives currently + for (int i = 0; i < windows.size(); i++) + { + QList pages = windows[i]->GetPages(); + for (int j = 0; j < pages.size(); j++) + { + WorkbenchPage::Pointer page = pages[j].Cast(); + if (page->FindPerspective(desc).IsNotNull()) + { + QMessageBox::StandardButton returnCode = + QMessageBox::question(workbench->GetActiveWorkbenchWindow()->GetShell()->GetControl(), + "Delete Perspective", + QString("Are you sure you want to delete the \"%1\" perspective? It has open instances.").arg(desc->GetLabel()), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); + return (returnCode != QMessageBox::Yes); + } + } + } + + return false; +} + +SmartPointer PerspectivesPreferencePage::GetSelectedPerspective() const +{ + PerspectiveDescriptor::Pointer desc; + + QList selection = ui->perspectivesListWidget->selectedItems(); + if (!selection.isEmpty()) + { + int row = ui->perspectivesListWidget->row(selection.back()); + if (row > -1) + { + desc = perspectives.at(row); + } + } + return desc; +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.h new file mode 100644 index 0000000000..4154bc2b1f --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.h @@ -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. + +===================================================================*/ + +#ifndef BERRYPERSPECTIVESPREFERENCEPAGE_H +#define BERRYPERSPECTIVESPREFERENCEPAGE_H + +#include + +namespace Ui { +class PerspectivesPreferencePage; +} + +namespace berry { + +class PerspectiveDescriptor; +class PerspectiveRegistry; + +class PerspectivesPreferencePage : public QObject, public IQtPreferencePage +{ + Q_OBJECT + Q_INTERFACES(berry::IPreferencePage) + +public: + + PerspectivesPreferencePage(); + ~PerspectivesPreferencePage(); + + void Init(IWorkbench::Pointer workbench) override; + + void CreateQtControl(QWidget* parent) override; + QWidget* GetQtControl() const override; + + bool PerformOk() override; + void PerformCancel() override; + void Update() override; + +private: + + Q_SLOT void OpenPerspInSameWindow(); + Q_SLOT void OpenPerspInNewWindow(); + + Q_SLOT void PerspectiveSelectionChanged(); + + Q_SLOT void RevertPerspective(); + Q_SLOT void DeletePerspective(); + Q_SLOT void MakeDefaultPerspective(); + + void UpdateButtons(); + void UpdatePerspectivesTable(); + void NewPerspectivesTableItem(const SmartPointer& desc); + bool FindOpenInstance(const SmartPointer& desc); + + SmartPointer GetSelectedPerspective() const; + + Ui::PerspectivesPreferencePage* ui; + QWidget* pageWidget; + + int openPerspMode; + SmartPointer preferences; + IWorkbench* workbench; + PerspectiveRegistry* perspRegistry; + + QString defaultPerspectiveId; + + QList > perspectives; + QList > perspToRevert; + QList > perspToDelete; +}; + +} + +#endif // BERRYPERSPECTIVESPREFERENCEPAGE_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.ui b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.ui new file mode 100644 index 0000000000..704c886beb --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berryPerspectivesPreferencePage.ui @@ -0,0 +1,139 @@ + + + PerspectivesPreferencePage + + + + 0 + 0 + 400 + 300 + + + + Form + + + + + + Open a new perspective + + + + + + In the same window + + + + + + + In a new window + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + Available perspectives: + + + + + + + + + + + + + + false + + + Make the Current Selection the Default Perspective + + + Make Default + + + + + + + false + + + messages.properties + +Reverts the Current Selection to its Original Value + + + Revert + + + + + + + false + + + Delete a User Defined Perspective + + + Delete + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + <html><head/><body><p><span style=" font-weight:600;">Note:</span> 'Revert' removes the customization from the selected perspective. This only applies to newly opened perspectives.</p></body></html> + + + true + + + + + + + + diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berrySavePerspectiveDialog.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berrySavePerspectiveDialog.cpp new file mode 100644 index 0000000000..539ffc9e34 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berrySavePerspectiveDialog.cpp @@ -0,0 +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. + +===================================================================*/ + +#include "berrySavePerspectiveDialog.h" +#include "berryPerspectiveListModel.h" +#include "internal/berryPerspectiveRegistry.h" + +#include "ui_berrySavePerspectiveDialog.h" + +#include +#include +#include +#include + +namespace berry { + +SavePerspectiveDialog::SavePerspectiveDialog(PerspectiveRegistry& perspReg, QWidget *parent) + : QDialog(parent) + , ui(new Ui::SavePerspectiveDialog) + , model(new PerspectiveListModel(perspReg, true, this)) + , perspReg(perspReg) +{ + ui->setupUi(this); + + QSortFilterProxyModel* proxyModel = new QSortFilterProxyModel(this); + proxyModel->setSourceModel(model); + proxyModel->sort(0); + ui->listView->setModel(proxyModel); + ui->listView->setSelectionMode(QAbstractItemView::SingleSelection); + ui->listView->setIconSize(QSize(16, 16)); + + connect(ui->lineEdit, SIGNAL(textChanged(QString)), this, SLOT(PerspectiveNameChanged(QString))); + connect(ui->listView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), + this, SLOT(PerspectiveSelected(QItemSelection,QItemSelection))); + + this->UpdateButtons(); + ui->lineEdit->setFocus(); +} + +SavePerspectiveDialog::~SavePerspectiveDialog() +{ + delete ui; +} + +void SavePerspectiveDialog::SetInitialSelection(const SmartPointer& initialSelection) +{ + if (initialSelection.IsNotNull() && + ui->listView->selectionModel()->selection().empty()) + { + QModelIndex index = this->model->index(initialSelection->GetId()); + if (index.isValid()) + { + ui->listView->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect); + } + } +} + +SmartPointer SavePerspectiveDialog::GetPersp() const +{ + return persp; +} + +QString SavePerspectiveDialog::GetPerspName() const +{ + return perspName; +} + +void SavePerspectiveDialog::accept() +{ + perspName = ui->lineEdit->text(); + persp = perspReg.FindPerspectiveWithLabel(perspName); + if (persp.IsNotNull()) + { + // Confirm ok to overwrite + QString msg = QString("A perspective with the name \"%1\" already exists. Do you want to overwrite?").arg(perspName); + int ret = QMessageBox::question(this, + "Overwrite Perspective", + msg, + QMessageBox::No | QMessageBox::Cancel | QMessageBox::Yes, + QMessageBox::No); + + switch (ret) + { + case QMessageBox::Yes: //yes + break; + case QMessageBox::No: //no + return; + case QMessageBox::Cancel: //cancel + this->reject(); + return; + default: + return; + } + } + + QDialog::accept(); +} + +void SavePerspectiveDialog::PerspectiveNameChanged(const QString& text) +{ + perspName = text; + persp = perspReg.FindPerspectiveWithLabel(perspName); + if (persp.IsNull()) + { + ui->listView->selectionModel()->clearSelection(); + } + else + { + QModelIndex selIndex = model->index(persp->GetId()); + ui->listView->selectionModel()->select(selIndex, QItemSelectionModel::ClearAndSelect); + } + + this->UpdateButtons(); +} + +void SavePerspectiveDialog::PerspectiveSelected(const QItemSelection& selected, const QItemSelection& /*deselected*/) +{ + persp = 0; + if (!selected.isEmpty()) + { + persp = model->perspectiveDescriptor(selected.indexes().front()); + } + + if (!persp.IsNull()) + { + perspName = persp->GetLabel(); + ui->lineEdit->setText(perspName); + } + + this->UpdateButtons(); +} + +void SavePerspectiveDialog::UpdateButtons() +{ + QString label = ui->lineEdit->text(); + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(perspReg.ValidateLabel(label)); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berrySavePerspectiveDialog.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berrySavePerspectiveDialog.h new file mode 100644 index 0000000000..30251da44c --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berrySavePerspectiveDialog.h @@ -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. + +===================================================================*/ + +#ifndef BERRYSAVEPERSPECTIVEDIALOG_H +#define BERRYSAVEPERSPECTIVEDIALOG_H + +#include + +#include + +class QItemSelection; + +namespace Ui { +class SavePerspectiveDialog; +} + +namespace berry { + +struct IPerspectiveDescriptor; +class PerspectiveRegistry; +class PerspectiveListModel; + +class SavePerspectiveDialog : public QDialog +{ + Q_OBJECT + +public: + + SavePerspectiveDialog(PerspectiveRegistry& perspReg, QWidget *parent = 0); + ~SavePerspectiveDialog(); + + void SetInitialSelection(const SmartPointer& initialSelection); + + SmartPointer GetPersp() const; + + QString GetPerspName() const; + +protected: + + virtual void accept(); + + Q_SLOT void PerspectiveNameChanged(const QString& name); + Q_SLOT void PerspectiveSelected(const QItemSelection& selected, const QItemSelection& deselected); + +private: + + void UpdateButtons(); + + Ui::SavePerspectiveDialog* ui; + PerspectiveListModel* model; + + PerspectiveRegistry& perspReg; + SmartPointer persp; + QString perspName; +}; + +} + +#endif // BERRYSAVEPERSPECTIVEDIALOG_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berrySavePerspectiveDialog.ui b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berrySavePerspectiveDialog.ui new file mode 100644 index 0000000000..b9171ddfa4 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/dialogs/berrySavePerspectiveDialog.ui @@ -0,0 +1,101 @@ + + + SavePerspectiveDialog + + + + 0 + 0 + 400 + 300 + + + + Save Perspective As... + + + + + + Enter or select a name to save the current perspective as. + + + + + + + 10 + + + 10 + + + + + Name: + + + + + + + + + + + + Existing Perspectives: + + + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + buttonBox + accepted() + SavePerspectiveDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + SavePerspectiveDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryCloseAllPerspectivesHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryCloseAllPerspectivesHandler.cpp new file mode 100644 index 0000000000..76b877991f --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryCloseAllPerspectivesHandler.cpp @@ -0,0 +1,39 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY 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 "berryCloseAllPerspectivesHandler.h" + +#include +#include +#include + +namespace berry { + +Object::Pointer CloseAllPerspectivesHandler::Execute(const SmartPointer& event) +{ + IWorkbenchWindow::Pointer window = HandlerUtil::GetActiveWorkbenchWindow(event); + if (window.IsNotNull()) + { + IWorkbenchPage::Pointer page = window->GetActivePage(); + if (page.IsNotNull()) + { + page->CloseAllPerspectives(true, true); + } + } + return Object::Pointer(); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryCloseAllPerspectivesHandler.h similarity index 58% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryCloseAllPerspectivesHandler.h index 1fd4128836..24abe9cc6b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryCloseAllPerspectivesHandler.h @@ -1,45 +1,39 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ +#ifndef BERRYCLOSEALLPERSPECTIVESHANDLER_H +#define BERRYCLOSEALLPERSPECTIVESHANDLER_H -#ifndef BERRYMMMENULISTENER_H -#define BERRYMMMENULISTENER_H +#include -#include +namespace berry { -namespace berry -{ - -class MenuManager; - -class MMMenuListener : public QObject +/** + * Closes all the perspectives. + */ +class CloseAllPerspectivesHandler : public AbstractHandler { Q_OBJECT - berry::MenuManager* mm; - public: - MMMenuListener(berry::MenuManager* mm); - -private: + Object::Pointer Execute(const SmartPointer& event); - Q_SLOT void HandleAboutToShow(); }; } -#endif // BERRYMMMENULISTENER_H +#endif // BERRYCLOSEALLPERSPECTIVESHANDLER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryClosePerspectiveHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryClosePerspectiveHandler.cpp new file mode 100644 index 0000000000..7eb0582294 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryClosePerspectiveHandler.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 "berryClosePerspectiveHandler.h" + +#include + +#include "internal/berryPerspective.h" +#include "internal/berryWorkbenchPage.h" + +#include +#include + +namespace berry { + +Object::Pointer ClosePerspectiveHandler::Execute(const SmartPointer& event) +{ + IWorkbenchWindow::Pointer activeWorkbenchWindow = HandlerUtil::GetActiveWorkbenchWindow(event); + if (activeWorkbenchWindow.IsNotNull()) + { + WorkbenchPage::Pointer page = activeWorkbenchWindow->GetActivePage().Cast(); + if (page.IsNotNull()) + { + const ExecutionEvent::ParameterMap& parameters = event->GetParameters(); + QString value = parameters[IWorkbenchCommandConstants::WINDOW_CLOSE_PERSPECTIVE_PARM_ID]; + if (value.isEmpty()) + { + page->ClosePerspective(page->GetPerspective(), true, true); + } + else + { + IPerspectiveDescriptor::Pointer perspective = activeWorkbenchWindow + ->GetWorkbench()->GetPerspectiveRegistry() + ->FindPerspectiveWithId(value); + if (perspective.IsNotNull()) + { + page->ClosePerspective(perspective, true, true); + } + } + } + } + return Object::Pointer(); +} + +void ClosePerspectiveHandler::ClosePerspective(const SmartPointer& page, const SmartPointer& persp) +{ + if (page != nullptr && persp != nullptr) + { + page->ClosePerspective(persp->GetDesc(), true, true); + } +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryClosePerspectiveHandler.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryClosePerspectiveHandler.h new file mode 100644 index 0000000000..9fd73ba5ff --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryClosePerspectiveHandler.h @@ -0,0 +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 BERRYCLOSEPERSPECTIVEHANDLER_H +#define BERRYCLOSEPERSPECTIVEHANDLER_H + +#include + +namespace berry { + +class WorkbenchPage; +class Perspective; + +class ClosePerspectiveHandler : public AbstractHandler +{ + Q_OBJECT + +public: + + Object::Pointer Execute(const SmartPointer& event); + + /** + * Closes the specified perspective. Nothing will happen if the given page + * or perspective are null. + * @param page + * a reference to the page + * @param persp + * the perspective to close + */ + static void ClosePerspective(const SmartPointer& page, + const SmartPointer& persp); +}; + +} +#endif // BERRYCLOSEPERSPECTIVEHANDLER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryDynamicHelpHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryDynamicHelpHandler.cpp new file mode 100644 index 0000000000..5cce251c14 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryDynamicHelpHandler.cpp @@ -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. + +===================================================================*/ + +#include "berryDynamicHelpHandler.h" + +#include "internal/berryWorkbenchPlugin.h" + +#include + +namespace berry { + +Object::Pointer DynamicHelpHandler::Execute(const SmartPointer& /*event*/) +{ + ctkPluginContext* context = WorkbenchPlugin::GetDefault()->GetPluginContext(); + if (context == 0) + { + BERRY_WARN << "Plugin context not set, unable to open context help"; + return Object::Pointer(); + } + + ctkServiceReference eventAdminRef = context->getServiceReference(); + ctkEventAdmin* eventAdmin = 0; + if (eventAdminRef) + { + eventAdmin = context->getService(eventAdminRef); + } + if (eventAdmin == 0) + { + BERRY_WARN << "ctkEventAdmin service not found. Unable to open context help"; + } + else + { + ctkEvent ev("org/blueberry/ui/help/CONTEXTHELP_REQUESTED"); + eventAdmin->postEvent(ev); + } + return Object::Pointer(); +} + +} + diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryDynamicHelpHandler.h similarity index 62% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryDynamicHelpHandler.h index 1fd4128836..0402fd6a9f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryDynamicHelpHandler.h @@ -1,45 +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 BERRYDYNAMICHELPHANDLER_H +#define BERRYDYNAMICHELPHANDLER_H -#ifndef BERRYMMMENULISTENER_H -#define BERRYMMMENULISTENER_H +#include -#include +namespace berry { -namespace berry -{ - -class MenuManager; - -class MMMenuListener : public QObject +class DynamicHelpHandler : public AbstractHandler { Q_OBJECT - berry::MenuManager* mm; - public: - MMMenuListener(berry::MenuManager* mm); - -private: + Object::Pointer Execute(const SmartPointer &event); - Q_SLOT void HandleAboutToShow(); }; } -#endif // BERRYMMMENULISTENER_H +#endif // BERRYDYNAMICHELPHANDLER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryHelpContentsHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryHelpContentsHandler.cpp new file mode 100644 index 0000000000..58ca2876e2 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryHelpContentsHandler.cpp @@ -0,0 +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 "berryHelpContentsHandler.h" + +#include +#include +#include +#include + + +namespace berry { + +Object::Pointer HelpContentsHandler::Execute(const SmartPointer& event) +{ + IWorkbenchWindow::Pointer window = HandlerUtil::GetActiveWorkbenchWindow(event); + PlatformUI::GetWorkbench()->ShowPerspective("org.blueberry.perspectives.help", + window); + return Object::Pointer(); +} + +bool HelpContentsHandler::IsEnabled() const +{ + return PlatformUI::GetWorkbench()->GetPerspectiveRegistry() + ->FindPerspectiveWithId("org.blueberry.perspectives.help").IsNotNull(); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryHelpContentsHandler.h similarity index 61% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryHelpContentsHandler.h index 1fd4128836..7a7ce0129e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryHelpContentsHandler.h @@ -1,45 +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 BERRYHELPCONTENTSHANDLER_H +#define BERRYHELPCONTENTSHANDLER_H -#ifndef BERRYMMMENULISTENER_H -#define BERRYMMMENULISTENER_H +#include -#include +namespace berry { -namespace berry -{ - -class MenuManager; - -class MMMenuListener : public QObject +class HelpContentsHandler : public AbstractHandler { Q_OBJECT - berry::MenuManager* mm; - public: - MMMenuListener(berry::MenuManager* mm); - -private: + Object::Pointer Execute(const SmartPointer& event); - Q_SLOT void HandleAboutToShow(); + bool IsEnabled() const; }; } -#endif // BERRYMMMENULISTENER_H +#endif // BERRYHELPCONTENTSHANDLER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryIntroHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryIntroHandler.cpp new file mode 100644 index 0000000000..456894ea27 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryIntroHandler.cpp @@ -0,0 +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. + +===================================================================*/ + +#include "berryIntroHandler.h" + +#include +#include + +#include "internal/berryWorkbench.h" +#include "internal/intro/berryIntroDescriptor.h" + +#include +#include + +namespace berry { + +IntroHandler::IntroHandler() +{ + workbench = dynamic_cast(PlatformUI::GetWorkbench()); + introDescriptor = workbench->GetIntroDescriptor(); +} + +IntroHandler::~IntroHandler() +{ +} + +SmartPointer IntroHandler::Execute(const SmartPointer &event) +{ + if (introDescriptor.IsNull()) + { + QMessageBox::warning(QApplication::activeWindow(), + "No Welcome Content Found", + "There is no welcome content suitable for display in this application."); + } + else + { + IWorkbenchWindow::Pointer window = HandlerUtil::GetActiveWorkbenchWindow(event); + workbench->GetIntroManager()->ShowIntro(window, false); + } + return Object::Pointer(); +} + +bool IntroHandler::IsEnabled() const +{ + + bool enabled = false; + IWorkbenchWindow::Pointer window = PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(); + if (window.IsNotNull()) + { + enabled = !window->GetPages().isEmpty(); + } + return enabled; +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryIntroHandler.h similarity index 54% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryIntroHandler.h index 90365ba2c1..6f32a67738 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtWorkbenchTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryIntroHandler.h @@ -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. ===================================================================*/ -#ifndef BERRYQTWORKBENCHTWEAKLET_H_ -#define BERRYQTWORKBENCHTWEAKLET_H_ +#ifndef BERRYINTROHANDLER_H +#define BERRYINTROHANDLER_H -#include - -#include +#include namespace berry { -class BERRY_UI_QT QtWorkbenchTweaklet : public QObject, public WorkbenchTweaklet +class IntroDescriptor; +class Workbench; + +class IntroHandler : public AbstractHandler { Q_OBJECT - Q_INTERFACES(berry::WorkbenchTweaklet) -public: +private: - berryObjectMacro(QtWorkbenchTweaklet) + Workbench* workbench; + SmartPointer introDescriptor; + +public: - QtWorkbenchTweaklet(); + IntroHandler(); + ~IntroHandler(); - Display* CreateDisplay(); + SmartPointer Execute(const SmartPointer& event); - bool IsRunning(); + bool IsEnabled() const; }; -} // namespace berry +} -#endif /*BERRYQTWORKBENCHTWEAKLET_H_*/ +#endif // BERRYINTROHANDLER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryNewEditorHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryNewEditorHandler.cpp new file mode 100644 index 0000000000..e6c2cab2ca --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryNewEditorHandler.cpp @@ -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. + +===================================================================*/ + +#include "berryNewEditorHandler.h" + +#include +#include + +#include "internal/berryWorkbenchConstants.h" +#include "internal/berryWorkbenchPage.h" + +#include +#include +#include + +#include +#include + +namespace berry { + +Object::Pointer NewEditorHandler::Execute(const SmartPointer &event) +{ + IWorkbenchWindow::Pointer activeWorkbenchWindow = HandlerUtil::GetActiveWorkbenchWindow(event); + IWorkbenchPage::Pointer page = activeWorkbenchWindow->GetActivePage(); + if (page.IsNull()) + { + return Object::Pointer(); + } + IEditorPart::Pointer editor = page->GetActiveEditor(); + if (editor.IsNull()) + { + return Object::Pointer(); + } + QString editorId = editor->GetSite()->GetId(); + if (editorId.isEmpty()) + { + return Object::Pointer(); + } + try + { + if (IPersistableEditor* persistableEditor = dynamic_cast(editor.GetPointer())) + { + IMemento::Pointer editorState(XMLMemento::CreateWriteRoot(WorkbenchConstants::TAG_EDITOR_STATE).GetPointer()); + persistableEditor->SaveState(editorState); + page.Cast()->OpenEditor(editor->GetEditorInput(), + editorId, true, + IWorkbenchPage::MATCH_NONE, editorState); + } + else + { + page->OpenEditor(editor->GetEditorInput(), editorId, true, + IWorkbenchPage::MATCH_NONE); + } + } + catch (const PartInitException& e) + { + QMessageBox::critical(QApplication::activeWindow(), "Error", e.message()); + } + return Object::Pointer(); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryNewEditorHandler.h similarity index 64% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.cpp copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryNewEditorHandler.h index ffd8e80060..14612f3746 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryNewEditorHandler.h @@ -1,37 +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 BERRYNEWEDITORHANDLER_H +#define BERRYNEWEDITORHANDLER_H -#include "berryMMMenuListener.h" - -#include +#include namespace berry { -MMMenuListener::MMMenuListener(berry::MenuManager* mm) - : QObject(), mm(mm) -{} - -void MMMenuListener::HandleAboutToShow() +class NewEditorHandler : public AbstractHandler { - if (mm->removeAllWhenShown) - { - mm->RemoveAll(); - } - mm->Update(false, false); -} + Q_OBJECT + +public: + + Object::Pointer Execute(const SmartPointer &event); + +}; } + +#endif // BERRYNEWEDITORHANDLER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryOpenInNewWindowHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryOpenInNewWindowHandler.cpp new file mode 100644 index 0000000000..f5d85dbac6 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryOpenInNewWindowHandler.cpp @@ -0,0 +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. + +===================================================================*/ + +#include "berryOpenInNewWindowHandler.h" + +#include + +#include +#include +#include +#include +#include + +#include + +#include "internal/berryWorkbench.h" + +#include +#include + +namespace berry { + +Object::Pointer OpenInNewWindowHandler::Execute(const SmartPointer &event) +{ + IWorkbenchWindow::Pointer activeWorkbenchWindow = HandlerUtil::GetActiveWorkbenchWindow(event); + if (activeWorkbenchWindow.IsNull()) + { + return Object::Pointer(); + } + + try + { + QString perspId; + + IWorkbenchPage::Pointer page = activeWorkbenchWindow->GetActivePage(); + IAdaptable* pageInput = dynamic_cast(activeWorkbenchWindow->GetWorkbench())->GetDefaultPageInput(); + if (page.IsNotNull() && page->GetPerspective().IsNotNull()) + { + perspId = page->GetPerspective()->GetId(); + pageInput = page->GetInput(); + } + else + { + perspId = activeWorkbenchWindow->GetWorkbench() + ->GetPerspectiveRegistry()->GetDefaultPerspective(); + } + + activeWorkbenchWindow->GetWorkbench()->OpenWorkbenchWindow(perspId, + pageInput); + } + catch (const WorkbenchException& e) + { +// StatusUtil.handleStatus(e.getStatus(), +// "Problems Opening New Window: " + e.message(), +// StatusManager::SHOW); + QMessageBox::critical(QApplication::activeWindow(), "Problems Opening New Window", e.message()); + } + return Object::Pointer(); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryOpenInNewWindowHandler.h similarity index 62% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryOpenInNewWindowHandler.h index 1fd4128836..c7b9945bcf 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryOpenInNewWindowHandler.h @@ -1,45 +1,35 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ +#ifndef BERRYOPENINNEWWINDOWHANDLER_H +#define BERRYOPENINNEWWINDOWHANDLER_H -#ifndef BERRYMMMENULISTENER_H -#define BERRYMMMENULISTENER_H +#include -#include +namespace berry { -namespace berry -{ - -class MenuManager; - -class MMMenuListener : public QObject +class OpenInNewWindowHandler : public AbstractHandler { Q_OBJECT - berry::MenuManager* mm; - public: - MMMenuListener(berry::MenuManager* mm); - -private: + Object::Pointer Execute(const SmartPointer& event); - Q_SLOT void HandleAboutToShow(); }; } - -#endif // BERRYMMMENULISTENER_H +#endif // BERRYOPENINNEWWINDOWHANDLER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryQuitHandler.cpp similarity index 53% rename from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.cpp rename to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryQuitHandler.cpp index ffd8e80060..9c15d9a455 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryQuitHandler.cpp @@ -1,37 +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 "berryQuitHandler.h" -#include "berryMMMenuListener.h" - -#include +#include +#include namespace berry { -MMMenuListener::MMMenuListener(berry::MenuManager* mm) - : QObject(), mm(mm) -{} - -void MMMenuListener::HandleAboutToShow() +Object::Pointer QuitHandler::Execute(const SmartPointer& event) { - if (mm->removeAllWhenShown) + IWorkbenchWindow::Pointer activeWorkbenchWindow = HandlerUtil::GetActiveWorkbenchWindow(event); + if (activeWorkbenchWindow.IsNull()) { - mm->RemoveAll(); + // action has been disposed + return Object::Pointer(); } - mm->Update(false, false); + + activeWorkbenchWindow->GetWorkbench()->Close(); + return Object::Pointer(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryQuitHandler.h similarity index 62% copy from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h copy to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryQuitHandler.h index 1fd4128836..8a39155ad0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryQuitHandler.h @@ -1,45 +1,39 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ +#ifndef BERRYQUITHANDLER_H +#define BERRYQUITHANDLER_H -#ifndef BERRYMMMENULISTENER_H -#define BERRYMMMENULISTENER_H +#include -#include +namespace berry { -namespace berry -{ - -class MenuManager; - -class MMMenuListener : public QObject +/** + * Quit (close the workbench). + */ +class QuitHandler : public AbstractHandler { Q_OBJECT - berry::MenuManager* mm; - public: - MMMenuListener(berry::MenuManager* mm); - -private: + Object::Pointer Execute(const SmartPointer& event); - Q_SLOT void HandleAboutToShow(); }; } -#endif // BERRYMMMENULISTENER_H +#endif // BERRYQUITHANDLER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryResetPerspectiveHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryResetPerspectiveHandler.cpp new file mode 100644 index 0000000000..6241e8d7f1 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryResetPerspectiveHandler.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 "berryResetPerspectiveHandler.h" + +#include +#include + +#include +#include + +#include + +namespace berry { + +Object::Pointer ResetPerspectiveHandler::Execute(const SmartPointer& event) +{ + + IWorkbenchWindow::Pointer activeWorkbenchWindow = HandlerUtil::GetActiveWorkbenchWindow(event); + if (activeWorkbenchWindow.IsNotNull()) + { + WorkbenchPage::Pointer page = activeWorkbenchWindow->GetActivePage().Cast(); + if (page.IsNotNull()) + { + IPerspectiveDescriptor::Pointer descriptor = page->GetPerspective(); + if (descriptor.IsNotNull()) + { + bool offerRevertToBase = false; + if (PerspectiveDescriptor::Pointer desc = descriptor.Cast()) + { + offerRevertToBase = desc->IsPredefined() && desc->HasCustomDefinition(); + } + + if (offerRevertToBase) + { + QString message = QString("Do you want to reset the current %1 perspective to its saved state?").arg( + descriptor->GetLabel()); +// bool toggleState = false; +// MessageDialogWithToggle dialog = MessageDialogWithToggle.open( +// MessageDialog.QUESTION, activeWorkbenchWindow.getShell(), +// WorkbenchMessages.RevertPerspective_title, message, +// WorkbenchMessages.RevertPerspective_option, +// toggleState, null, null, SWT.SHEET); +// if (dialog.getReturnCode() == IDialogConstants.YES_ID) { +// if (dialog.getToggleState()) { +// PerspectiveRegistry* reg = PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); +// reg->RevertPerspective(descriptor); +// } +// page->ResetPerspective(); +// } + qDebug() << "****** " << message; + } + else + { + QString message = QString("Do you want to reset the current %1 perspective to its defaults?").arg( + descriptor->GetLabel()); + if (QMessageBox::question(activeWorkbenchWindow->GetShell()->GetControl(), "Reset Perspective", + message, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == + QMessageBox::Yes) + { + page->ResetPerspective(); + } + } + } + } + } + + return Object::Pointer(); +} + + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryResetPerspectiveHandler.h similarity index 62% rename from BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h rename to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryResetPerspectiveHandler.h index 1fd4128836..e4ce37a315 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryMMMenuListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryResetPerspectiveHandler.h @@ -1,45 +1,35 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ +#ifndef BERRYRESETPERSPECTIVEHANDLER_H +#define BERRYRESETPERSPECTIVEHANDLER_H -#ifndef BERRYMMMENULISTENER_H -#define BERRYMMMENULISTENER_H +#include -#include +namespace berry { -namespace berry -{ - -class MenuManager; - -class MMMenuListener : public QObject +class ResetPerspectiveHandler : public AbstractHandler { Q_OBJECT - berry::MenuManager* mm; - public: - MMMenuListener(berry::MenuManager* mm); - -private: - - Q_SLOT void HandleAboutToShow(); + Object::Pointer Execute(const SmartPointer& event); }; } -#endif // BERRYMMMENULISTENER_H +#endif // BERRYRESETPERSPECTIVEHANDLER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berrySavePerspectiveHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berrySavePerspectiveHandler.cpp new file mode 100644 index 0000000000..3b63f9b8e6 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berrySavePerspectiveHandler.cpp @@ -0,0 +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 "berrySavePerspectiveHandler.h" + +#include "berryHandlerUtil.h" +#include "berryIWorkbenchWindow.h" +#include "berryIWorkbenchPage.h" + +#include "internal/berryPerspectiveDescriptor.h" +#include "internal/berryWorkbenchPlugin.h" +#include "internal/dialogs/berrySavePerspectiveDialog.h" + +#include + +#include + +namespace berry { + +Object::Pointer SavePerspectiveHandler::Execute(const SmartPointer& event) +{ + + IWorkbenchWindow::Pointer activeWorkbenchWindow = HandlerUtil::GetActiveWorkbenchWindow(event); + if (activeWorkbenchWindow.IsNotNull()) + { + IWorkbenchPage::Pointer page = activeWorkbenchWindow->GetActivePage(); + if (page.IsNotNull()) + { + PerspectiveDescriptor::Pointer descriptor(page->GetPerspective().Cast()); + if (descriptor.IsNotNull()) + { + if (descriptor->IsSingleton()) + { + SaveSingleton(page); + } + else + { + SaveNonSingleton(page, descriptor); + } + } + } + } + return Object::Pointer(); +} + +void SavePerspectiveHandler::SaveSingleton(const IWorkbenchPage::Pointer& page) +{ + QMessageBox::StandardButton btn = + QMessageBox::question(page->GetWorkbenchWindow()->GetShell()->GetControl(), + "Overwrite perspective", + "The current perspective can only be opened once and cannot be saved using a new name. " + "Do you want to overwrite?", + QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel); + if (btn == QMessageBox::Ok) + { + page->SavePerspective(); + } +} + +void SavePerspectiveHandler::SaveNonSingleton(const IWorkbenchPage::Pointer& page, + const PerspectiveDescriptor::Pointer& oldDesc) { + // Get reg. + PerspectiveRegistry* reg = static_cast( + berry::WorkbenchPlugin::GetDefault()->GetPerspectiveRegistry()); + assert(reg != nullptr); + + // Get persp name. + SavePerspectiveDialog dlg(*reg, page->GetWorkbenchWindow()->GetShell()->GetControl()); + // Look up the descriptor by id again to ensure it is still valid. + IPerspectiveDescriptor::Pointer description = reg->FindPerspectiveWithId(oldDesc->GetId()); + dlg.SetInitialSelection(description); + if (dlg.exec() != QDialog::Accepted) + { + return; + } + + // Create descriptor. + IPerspectiveDescriptor::Pointer newDesc = dlg.GetPersp(); + if (newDesc.IsNull()) + { + QString name = dlg.GetPerspName(); + newDesc = reg->CreatePerspective(name, description); + if (newDesc.IsNull()) + { + QMessageBox::critical(&dlg, + "Cannot Save Perspective", + "Invalid Perspective Descriptor"); + return; + } + } + + // Save state. + page->SavePerspectiveAs(newDesc); +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berrySavePerspectiveHandler.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berrySavePerspectiveHandler.h new file mode 100644 index 0000000000..584e956b01 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berrySavePerspectiveHandler.h @@ -0,0 +1,51 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#ifndef BERRYSAVEPERSPECTIVEHANDLER_H +#define BERRYSAVEPERSPECTIVEHANDLER_H + +#include + +namespace berry { + +struct IWorkbenchPage; +class PerspectiveDescriptor; + +class SavePerspectiveHandler : public AbstractHandler +{ + Q_OBJECT + +public: + + Object::Pointer Execute(const SmartPointer& event); + +private: + + /** + * Save a singleton over itself. + */ + void SaveSingleton(const SmartPointer& page); + + /** + * Save a singleton over the user selection. + */ + void SaveNonSingleton(const SmartPointer& page, const SmartPointer& oldDesc); + +}; + +} + +#endif // BERRYSAVEPERSPECTIVEHANDLER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryShowPerspectiveHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryShowPerspectiveHandler.cpp new file mode 100644 index 0000000000..4f703d466e --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryShowPerspectiveHandler.cpp @@ -0,0 +1,141 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY 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 "berryShowPerspectiveHandler.h" + +#include +#include +#include + +#include +#include + +#include "internal/berryPreferenceConstants.h" +#include "internal/berryQtShowPerspectiveDialog.h" +#include "internal/berryWorkbench.h" +#include "internal/berryWorkbenchPlugin.h" + +#include + +namespace berry +{ + +Object::Pointer ShowPerspectiveHandler::Execute(const ExecutionEvent::ConstPointer& event) +{ + IWorkbenchWindow::Pointer window = HandlerUtil::GetActiveWorkbenchWindowChecked(event); + + // Get the perspective identifier, if any. + const ExecutionEvent::ParameterMap& parameters = event->GetParameters(); + auto idParam = parameters.find(IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_ID); + auto newWindowParam = parameters.find(IWorkbenchCommandConstants::PERSPECTIVES_SHOW_PERSPECTIVE_PARM_NEWWINDOW); + + if (idParam == parameters.end() || idParam.value().isEmpty()) + { + OpenOther(window.GetPointer()); + } + else + { + if (newWindowParam == parameters.end() || newWindowParam.value().compare("false", Qt::CaseInsensitive) == 0) + { + OpenPerspective(idParam.value(), window.GetPointer()); + } + else + { + OpenNewWindowPerspective(idParam.value(), window.GetPointer()); + } + } + return Object::Pointer(); +} + +void ShowPerspectiveHandler::OpenNewWindowPerspective(const QString& perspectiveId, const IWorkbenchWindow* activeWorkbenchWindow) +{ + IWorkbench* workbench = activeWorkbenchWindow->GetWorkbench(); + try + { + IAdaptable* input = dynamic_cast(workbench)->GetDefaultPageInput(); + workbench->OpenWorkbenchWindow(perspectiveId, input); + } + catch (const WorkbenchException& e) + { + QMessageBox::critical(activeWorkbenchWindow->GetShell()->GetControl(), "Problems Changing Perspective", e.message()); +// ErrorDialog.openError(activeWorkbenchWindow.getShell(), +// WorkbenchMessages.ChangeToPerspectiveMenu_errorTitle, e +// .getMessage(), e.getStatus()); + } +} + +void ShowPerspectiveHandler::OpenOther(IWorkbenchWindow* activeWorkbenchWindow) +{ + QtShowPerspectiveDialog dialog(activeWorkbenchWindow->GetWorkbench()->GetPerspectiveRegistry(), + activeWorkbenchWindow->GetShell()->GetControl()); + + int returnCode = dialog.exec(); + if (returnCode == QDialog::Rejected) + { + return; + } + + QString perspectiveId = dialog.GetSelection(); + if (!perspectiveId.isEmpty()) + { + int openPerspMode = WorkbenchPlugin::GetDefault()->GetPreferences()->GetInt(PreferenceConstants::OPEN_PERSP_MODE, + PreferenceConstants::OPM_ACTIVE_PAGE); + IWorkbenchPage::Pointer page = activeWorkbenchWindow->GetActivePage(); + IPerspectiveDescriptor::Pointer persp = page == nullptr ? IPerspectiveDescriptor::Pointer() : page->GetPerspective(); + + // only open it in a new window if the preference is set and the + // current workbench page doesn't have an active perspective + if (PreferenceConstants::OPM_NEW_WINDOW == openPerspMode && persp.IsNotNull()) + { + OpenNewWindowPerspective(perspectiveId, activeWorkbenchWindow); + } + else + { + OpenPerspective(perspectiveId, activeWorkbenchWindow); + } + } +} + +void ShowPerspectiveHandler::OpenPerspective(const QString& perspectiveId, IWorkbenchWindow* activeWorkbenchWindow) +{ + IWorkbench* workbench = activeWorkbenchWindow->GetWorkbench(); + + IWorkbenchPage::Pointer activePage = activeWorkbenchWindow->GetActivePage(); + IPerspectiveDescriptor::Pointer desc = workbench->GetPerspectiveRegistry()->FindPerspectiveWithId(perspectiveId); + if (desc.IsNull()) + { + throw ExecutionException(QString("Perspective ") + perspectiveId + " cannot be found."); + } + + try + { + if (activePage.IsNotNull()) + { + activePage->SetPerspective(desc); + } + else + { + IAdaptable* input = dynamic_cast(workbench)->GetDefaultPageInput(); + activeWorkbenchWindow->OpenPage(perspectiveId, input); + } + } + catch (const WorkbenchException& e) + { + throw ExecutionException("Perspective could not be opened.", e); + } +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryShowPerspectiveHandler.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryShowPerspectiveHandler.h new file mode 100644 index 0000000000..54856c3b55 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryShowPerspectiveHandler.h @@ -0,0 +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 BERRYSHOWPERSPECTIVEHANDLER_H +#define BERRYSHOWPERSPECTIVEHANDLER_H + +#include +#include + +namespace berry { + +struct IWorkbenchWindow; + +/** + * Shows the given perspective. If no perspective is specified in the + * parameters, then this opens the perspective selection dialog. + */ +class ShowPerspectiveHandler : public AbstractHandler +{ + Q_OBJECT + +public: + + berryObjectMacro(ShowPerspectiveHandler) + + Object::Pointer Execute(const ExecutionEvent::ConstPointer& event); + +private: + + /** + * Opens the specified perspective in a new window. + * + * @param perspectiveId + * The perspective to open; must not be null + * @throws ExecutionException + * If the perspective could not be opened. + */ + void OpenNewWindowPerspective(const QString& perspectiveId, + const IWorkbenchWindow* activeWorkbenchWindow); + + /** + * Opens a view selection dialog, allowing the user to chose a view. + * + * @throws ExecutionException + * If the perspective could not be opened. + */ + void OpenOther(IWorkbenchWindow* activeWorkbenchWindow); + + /** + * Opens the perspective with the given identifier. + * + * @param perspectiveId + * The perspective to open; must not be null + * @throws ExecutionException + * If the perspective could not be opened. + */ + void OpenPerspective(const QString& perspectiveId, + IWorkbenchWindow* activeWorkbenchWindow); +}; + +} + +#endif // BERRYSHOWPERSPECTIVEHANDLER_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryShowViewHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp similarity index 84% rename from BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryShowViewHandler.cpp rename to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp index d0655120d9..5b50d966af 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryShowViewHandler.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.cpp @@ -1,117 +1,116 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryIWorkbenchCommandConstants.h" -#include "berryShowViewHandler.h" #include "berryHandlerUtil.h" #include "berryUIException.h" #include "berryIWorkbenchPage.h" #include "berryIViewDescriptor.h" #include "berryPlatformUI.h" #include "internal/berryWorkbenchPlugin.h" #include "internal/berryQtShowViewDialog.h" #include #include namespace berry { ShowViewHandler::ShowViewHandler() { } Object::Pointer ShowViewHandler::Execute(const ExecutionEvent::ConstPointer& event) { - IWorkbenchWindow::ConstPointer window = HandlerUtil::GetActiveWorkbenchWindowChecked(event); + IWorkbenchWindow::Pointer window = HandlerUtil::GetActiveWorkbenchWindowChecked(event); // Get the view identifier, if any. const ExecutionEvent::ParameterMap& parameters = event->GetParameters(); ExecutionEvent::ParameterMap::const_iterator result = parameters.find(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_PARM_ID); QString viewId = result != parameters.end() ? result.value() : QString::null; result = parameters.find(IWorkbenchCommandConstants::VIEWS_SHOW_VIEW_SECONDARY_ID); QString secondary = result != parameters.end() ? result.value() : QString::null; if (viewId.isEmpty()) { this->OpenOther(window); } else { try { this->OpenView(viewId, secondary, window); } catch (const PartInitException& e) { throw ExecutionException("Part could not be initialized", e); } } return Object::Pointer(0); } -void ShowViewHandler::OpenOther(IWorkbenchWindow::ConstPointer window) +void ShowViewHandler::OpenOther(IWorkbenchWindow::Pointer window) { const IWorkbenchPage::Pointer page = window->GetActivePage(); if (page.IsNull()) { return; } QtShowViewDialog dialog(window.GetPointer(), WorkbenchPlugin::GetDefault()->GetViewRegistry()); int returnCode = dialog.exec(); if (returnCode == QDialog::Rejected) { return; } - const QList descriptors = dialog.GetSelection(); - for (int i = 0; i < descriptors.size(); ++i) + const QList descriptors = dialog.GetSelection(); + for (QString id : descriptors) { try { - this->OpenView(descriptors[i]->GetId(), QString(), window); + this->OpenView(id, QString(), window); } catch (const PartInitException& e) { BERRY_WARN << e.what(); // StatusUtil.handleStatus(e.getStatus(), // WorkbenchMessages.ShowView_errorTitle // + ": " + e.getMessage(), //$NON-NLS-1$ // StatusManager.SHOW); } } } -void ShowViewHandler::OpenView(const QString& viewId, const QString& secondaryId, IWorkbenchWindow::ConstPointer activeWorkbenchWindow) +void ShowViewHandler::OpenView(const QString& viewId, const QString& secondaryId, IWorkbenchWindow::Pointer activeWorkbenchWindow) { const IWorkbenchPage::Pointer activePage = activeWorkbenchWindow->GetActivePage(); if (activePage.IsNull()) { return; } activePage->ShowView(viewId, secondaryId, IWorkbenchPage::VIEW_ACTIVATE); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryShowViewHandler.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.h similarity index 86% rename from BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryShowViewHandler.h rename to BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.h index a1ef9d0af3..72a7f27180 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/handlers/berryShowViewHandler.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/handlers/berryShowViewHandler.h @@ -1,75 +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 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 +class ShowViewHandler : public AbstractHandler { Q_OBJECT public: berryObjectMacro(ShowViewHandler) -public: - /** * Creates a new ShowViewHandler that will open the view in its default location. */ ShowViewHandler(); Object::Pointer Execute(const ExecutionEvent::ConstPointer& event); private: /** * Opens a view selection dialog, allowing the user to chose a view. */ - void OpenOther(IWorkbenchWindow::ConstPointer window); + void OpenOther(IWorkbenchWindow::Pointer window); /** * Opens the view with the given identifier. * * @param viewId * The view to open; must not be null * @param secondaryId * An optional secondary id; may be null * @throws PartInitException * If the part could not be initialized. */ - void OpenView(const QString& viewId, const QString& secondaryId, IWorkbenchWindow::ConstPointer activeWorkbenchWindow); + void OpenView(const QString& viewId, const QString& secondaryId, IWorkbenchWindow::Pointer activeWorkbenchWindow); }; } #endif /*BERRYSHOWVIEWHANDLER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIntroRegistry.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIntroRegistry.cpp index 23eb758b69..3765baca3f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIntroRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/intro/berryIntroRegistry.cpp @@ -1,172 +1,172 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berryIntroRegistry.h" #include #include #include "berryIntroDescriptor.h" #include "internal/berryRegistryReader.h" #include "internal/berryWorkbenchPlugin.h" namespace berry { const QString IntroRegistry::TAG_INTRO = "intro"; const QString IntroRegistry::TAG_INTROPRODUCTBINDING = "introProductBinding"; const QString IntroRegistry::ATT_INTROID = "introId"; const QString IntroRegistry::ATT_PRODUCTID = "productId"; QString IntroRegistry::GetIntroForProduct( const QString& targetProductId, const QList& extensions) const { for (int i = 0; i < extensions.size(); i++) { QList elements( extensions[i]->GetConfigurationElements()); for (int j = 0; j < elements.size(); j++) { if (elements[j]->GetName() == TAG_INTROPRODUCTBINDING) { QString introId = elements[j]->GetAttribute(ATT_INTROID); QString productId = elements[j]->GetAttribute(ATT_PRODUCTID); if (introId.isEmpty() || productId.isEmpty()) { //TODO IStatus /* IStatus status = new Status( IStatus.ERROR, elements[j].getDeclaringExtension() .getNamespace(), IStatus.ERROR, - "introId and productId must be defined.", new IllegalArgumentException()); //$NON-NLS-1$ - WorkbenchPlugin.log("Invalid intro binding", status); //$NON-NLS-1$ + "introId and productId must be defined.", new IllegalArgumentException()); + WorkbenchPlugin.log("Invalid intro binding", status); */ WorkbenchPlugin::Log( elements[j]->GetDeclaringExtension()->GetNamespaceIdentifier() + ": Invalid intro binding. introId and productId must be defined"); continue; } if (targetProductId == productId) { return introId; } } } } return ""; } int IntroRegistry::GetIntroCount() const { return static_cast (GetIntros().size()); } QList IntroRegistry::GetIntros() const { IExtensionPoint::Pointer point = Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID() + "." + WorkbenchRegistryConstants::PL_INTRO); if (!point) { return QList(); } QList extensions(point->GetExtensions()); extensions = RegistryReader::OrderExtensions(extensions); QList list; for (int i = 0; i < extensions.size(); i++) { QList elements( extensions[i]->GetConfigurationElements()); for (int j = 0; j < elements.size(); j++) { if (elements[j]->GetName() == TAG_INTRO) { try { IIntroDescriptor::Pointer descriptor(new IntroDescriptor(elements[j])); list.push_back(descriptor); } catch (const CoreException& e) { // log an error since its not safe to open a dialog here //TODO IStatus WorkbenchPlugin::Log("Unable to create intro descriptor", e); // e.getStatus()); } } } } return list; } IIntroDescriptor::Pointer IntroRegistry::GetIntroForProduct( const QString& targetProductId) const { IExtensionPoint::Pointer point = Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID() + "." + WorkbenchRegistryConstants::PL_INTRO); if (!point) { return IIntroDescriptor::Pointer(); } QList extensions(point->GetExtensions()); extensions = RegistryReader::OrderExtensions(extensions); QString targetIntroId = GetIntroForProduct(targetProductId, extensions); if (targetIntroId.isEmpty()) { return IIntroDescriptor::Pointer(); } IIntroDescriptor::Pointer descriptor; QList intros(GetIntros()); for (int i = 0; i < intros.size(); i++) { if (intros[i]->GetId() == targetIntroId) { descriptor = intros[i]; break; } } return descriptor; } IIntroDescriptor::Pointer IntroRegistry::GetIntro(const QString& id) const { QList intros(GetIntros()); for (int i = 0; i < intros.size(); i++) { IIntroDescriptor::Pointer desc = intros[i]; if (desc->GetId() == id) { return desc; } } return IIntroDescriptor::Pointer(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/model/berryPerspectiveListModel.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/model/berryPerspectiveListModel.cpp new file mode 100644 index 0000000000..10703a31ce --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/model/berryPerspectiveListModel.cpp @@ -0,0 +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. + +===================================================================*/ + + +#include "berryPerspectiveListModel.h" + +#include +#include + +#include + +namespace berry { + +struct PerspectiveListModel::Impl +{ + IPerspectiveRegistry& m_PerspReg; + QList m_Perspectives; + const bool m_MarkDefault; + + Impl(IPerspectiveRegistry& perspReg, bool markDefault) + : m_PerspReg(perspReg) + // TODO use activity filter for correct perspective list + , m_Perspectives(perspReg.GetPerspectives()) + , m_MarkDefault(markDefault) + { + } +}; + +PerspectiveListModel::PerspectiveListModel(IPerspectiveRegistry& perspReg, bool markDefault, QObject* parent) + : QAbstractListModel(parent) + , d(new Impl(perspReg, markDefault)) +{ +} + +PerspectiveListModel::~PerspectiveListModel() +{ +} + +int PerspectiveListModel::rowCount(const QModelIndex& /*parent*/) const +{ + return d->m_Perspectives.size(); +} + +QVariant PerspectiveListModel::data(const QModelIndex& index, int role) const +{ + if (index.row() < 0 || index.row() >= d->m_Perspectives.size() || + index.column() > 0) + { + return QVariant(); + } + + if (role == Qt::DisplayRole) + { + const IPerspectiveDescriptor::Pointer& desc = d->m_Perspectives.at(index.row()); + QString label = desc->GetLabel(); + if (d->m_MarkDefault) + { + QString def = d->m_PerspReg.GetDefaultPerspective(); + if (desc->GetId() == def) + { + label += " (default)"; + } + } + return label; + } + else if (role == Qt::DecorationRole) + { + const IPerspectiveDescriptor::Pointer& desc = d->m_Perspectives.at(index.row()); + return desc->GetImageDescriptor(); + } + else if (role == Id) + { + const IPerspectiveDescriptor::Pointer& desc = d->m_Perspectives.at(index.row()); + return desc->GetId(); + } + else if (role == Description) + { + const IPerspectiveDescriptor::Pointer& desc = d->m_Perspectives.at(index.row()); + return desc->GetDescription(); + } + return QVariant(); +} + +QVariant PerspectiveListModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const +{ + if (role == Qt::DisplayRole) + { + if (section == 0) + { + return QString("Perspective"); + } + } + return QVariant(); +} + +QString PerspectiveListModel::perspectiveName(const QModelIndex& index) const +{ + if (!index.isValid()) return QString::null; + + return d->m_Perspectives.at(index.row())->GetLabel(); +} + +IPerspectiveDescriptor::Pointer PerspectiveListModel::perspectiveDescriptor(const QModelIndex& index) const +{ + return d->m_Perspectives.at(index.row()); +} + +QModelIndex PerspectiveListModel::index(const QString& perspId) const +{ + int index = -1; + for(int i = 0; i < d->m_Perspectives.size(); ++i) + { + if (d->m_Perspectives.at(i)->GetId() == perspId) + { + index = i; + break; + } + } + + if (index > -1) + { + return this->createIndex(index, 0); + } + return QModelIndex(); +} + + + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/model/berryPerspectiveListModel.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/model/berryPerspectiveListModel.h new file mode 100644 index 0000000000..83939a1ba2 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/model/berryPerspectiveListModel.h @@ -0,0 +1,64 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#ifndef BERRYPERSPECTIVELISTMODEL_H +#define BERRYPERSPECTIVELISTMODEL_H + +#include + +#include + +#include +#include + +namespace berry { + +struct IPerspectiveDescriptor; +struct IPerspectiveRegistry; + +class BERRY_UI_QT PerspectiveListModel : public QAbstractListModel +{ + Q_OBJECT + +public: + + enum Role { + Id = Qt::UserRole, + Description + }; + + PerspectiveListModel(IPerspectiveRegistry& perspReg, bool markDefault = true, QObject* parent = nullptr); + ~PerspectiveListModel(); + + int rowCount(const QModelIndex &parent = QModelIndex()) const; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + + QString perspectiveName(const QModelIndex& index) const; + SmartPointer perspectiveDescriptor(const QModelIndex& index) const; + + using QAbstractListModel::index; + QModelIndex index(const QString& perspId) const; + +private: + + struct Impl; + QScopedPointer d; +}; + +} + +#endif // BERRYPERSPECTIVELISTMODEL_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp new file mode 100644 index 0000000000..1c69dd60c3 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/model/berryViewTreeModel.cpp @@ -0,0 +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 "berryViewTreeModel.h" + +#include "berryIViewRegistry.h" +#include "berryIViewCategory.h" +#include "berryIWorkbench.h" +#include "berryIWorkbenchWindow.h" +#include "berryIWorkbenchPage.h" + +#include "internal/intro/berryIntroConstants.h" +#include "internal/berryKeywordRegistry.h" + +#include +#include + +namespace berry { + +// --------------------------- Tree Item Classes --------------------------- + +struct ViewTreeItem; + +bool CompareViewTreeItem(ViewTreeItem* item1, ViewTreeItem* item2); + +struct ViewTreeItem +{ + ViewTreeItem(ViewTreeModel* model) + : m_parent(nullptr) + , m_model(model) + {} + + virtual ~ViewTreeItem() + { + QList children = m_children; + if (m_parent) m_parent->removeChild(this); + qDeleteAll(children); + } + + virtual QVariant data(int role) + { + if (role == ViewTreeModel::Keywords) + { + if (m_keywordCache.isEmpty()) + { + m_keywordCache = QStringList(keywordLabels().toList()); + } + return m_keywordCache; + } + return QVariant(); + } + + virtual Qt::ItemFlags flags() const + { + return Qt::ItemIsEnabled | Qt::ItemIsSelectable; + } + + virtual QSet keywordLabels() const + { + return QSet(); + } + + void appendChild(ViewTreeItem* child) + { + m_children.push_back(child); + child->m_parent = this; + qSort(m_children.begin(), m_children.end(), CompareViewTreeItem); + } + + void removeChild(ViewTreeItem* child) + { + m_children.removeAll(child); + } + + QList takeChildren() + { + QList children = m_children; + m_children.clear(); + return children; + } + + ViewTreeItem* childItem(int row) const + { + if (row < 0 || row >= m_children.size()) return nullptr; + return m_children.at(row); + } + + ViewTreeItem* parentItem() const + { + return m_parent; + } + + int childCount() const + { + return m_children.size(); + } + + int row() const + { + if (m_parent) return m_parent->rowIndex(this); + return 0; + } + + int rowIndex(const ViewTreeItem* child) const + { + return m_children.indexOf(const_cast(child)); + } + + QList m_children; + ViewTreeItem* m_parent; + ViewTreeModel* m_model; + +private: + + QStringList m_keywordCache; + +}; + +bool CompareViewTreeItem(ViewTreeItem* item1, ViewTreeItem* item2) +{ + return item1->data(Qt::DisplayRole).toString() < item2->data(Qt::DisplayRole).toString(); +} + +struct RootTreeItem : ViewTreeItem +{ + RootTreeItem(ViewTreeModel* model) : ViewTreeItem(model) {} + + QVariant data(int /*role*/) override { return QVariant(); } +}; + +struct DescriptorTreeItem : ViewTreeItem +{ + DescriptorTreeItem(ViewTreeModel* model, IViewDescriptor::Pointer descriptor, ViewTreeItem* parent = nullptr); + + QVariant data(int role) override; + +protected: + + QSet keywordLabels() const override; + + IViewDescriptor::Pointer m_descriptor; +}; + +struct CategoryTreeItem : ViewTreeItem +{ + CategoryTreeItem(ViewTreeModel* model, IViewCategory::Pointer category, ViewTreeItem* parent = nullptr); + + QVariant data(int role) override; + + Qt::ItemFlags flags() const override; + +protected: + + QSet keywordLabels() const; + + /** + * Removes the temporary intro view from the list so that it cannot be activated except through + * the introduction command. + */ + void RemoveIntroView(QList& list); + +private: + + void CreateChildren(); + + IViewCategory::Pointer m_category; + +}; + +// --------------------------- Tree Model Classes --------------------------- + +struct ViewTreeModel::Impl +{ + Impl(const IWorkbenchWindow* window) + : window(window) + , viewRegistry(*window->GetWorkbench()->GetViewRegistry()) + { + + } + + const IWorkbenchWindow* window; + IViewRegistry& viewRegistry; + + QScopedPointer rootItem; +}; + +ViewTreeModel::ViewTreeModel(const IWorkbenchWindow* window, QObject* parent) + : QAbstractItemModel(parent) + , d(new Impl(window)) +{ + d->rootItem.reset(new RootTreeItem(this)); + + QList categoryItems; + + QList categories = d->viewRegistry.GetCategories(); + for (auto category : categories) + { + if (category->GetViews().isEmpty()) continue; + CategoryTreeItem* categoryItem = new CategoryTreeItem(this, category); + if (categoryItem->childCount() == 0) + { + delete categoryItem; + } + else + { + categoryItems.push_back(categoryItem); + } + } + + + // if there is only one category, return it's children directly + if (categoryItems.size() == 1) + { + QList items = categoryItems.front()->takeChildren(); + for (auto item : items) + { + d->rootItem->appendChild(item); + } + qDeleteAll(categoryItems); + } + else + { + for (auto category : categoryItems) + { + d->rootItem->appendChild(category); + } + } +} + +ViewTreeModel::~ViewTreeModel() +{ + +} + +QVariant ViewTreeModel::data(const QModelIndex& index, int role) const +{ + if (!index.isValid()) return QVariant(); + + return static_cast(index.internalPointer())->data(role); +} + +Qt::ItemFlags ViewTreeModel::flags(const QModelIndex& index) const +{ + if (!index.isValid()) return 0; + + return static_cast(index.internalPointer())->flags(); +} + +QVariant ViewTreeModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const +{ + if (role == Qt::DisplayRole && section == 0) + { + return "View"; + } + return QVariant(); +} + +QModelIndex ViewTreeModel::index(int row, int column, const QModelIndex& parent) const +{ + if (!hasIndex(row, column, parent)) + { + return QModelIndex(); + } + + ViewTreeItem* parentItem = nullptr; + if (!parent.isValid()) + { + parentItem = d->rootItem.data(); + } + else + { + parentItem = static_cast(parent.internalPointer()); + } + + ViewTreeItem* childItem = parentItem->childItem(row); + if (childItem) + { + return createIndex(row, column, childItem); + } + return QModelIndex(); +} + +QModelIndex ViewTreeModel::parent(const QModelIndex& child) const +{ + if (!child.isValid()) + { + return QModelIndex(); + } + + ViewTreeItem* childItem = static_cast(child.internalPointer()); + ViewTreeItem* parentItem = childItem->parentItem(); + + if (parentItem == d->rootItem.data()) + { + return QModelIndex(); + } + return createIndex(parentItem->row(), 0, parentItem); +} + +int ViewTreeModel::rowCount(const QModelIndex& parent) const +{ + ViewTreeItem* parentItem = nullptr; + if (parent.column() > 0) return 0; + + if (!parent.isValid()) + { + parentItem = d->rootItem.data(); + } + else + { + parentItem = static_cast(parent.internalPointer()); + } + return parentItem->childCount(); +} + +int ViewTreeModel::columnCount(const QModelIndex& /*parent*/) const +{ + return 1; +} + +const IWorkbenchWindow*ViewTreeModel::GetWorkbenchWindow() const +{ + return d->window; +} + +// --------------------------- DescriptorTreeItem --------------------------- + +DescriptorTreeItem::DescriptorTreeItem(ViewTreeModel* model, IViewDescriptor::Pointer descriptor, ViewTreeItem* parent) + : ViewTreeItem(model) + , m_descriptor(descriptor) +{ + if (parent) parent->appendChild(this); +} + +QVariant DescriptorTreeItem::data(int role) +{ + if (role == Qt::DisplayRole) + { + return m_descriptor->GetLabel(); + } + else if (role == Qt::DecorationRole) + { + return m_descriptor->GetImageDescriptor(); + } + else if (role == Qt::ForegroundRole) + { + IWorkbenchPage::Pointer page = this->m_model->GetWorkbenchWindow()->GetActivePage(); + if (page.IsNotNull()) + { + if (page->FindViewReference(m_descriptor->GetId()).IsNotNull()) + { + return QBrush(QColor(Qt::gray)); + } + } + } + else if (role == ViewTreeModel::Description) + { + return m_descriptor->GetDescription(); + } + else if (role == ViewTreeModel::Id) + { + return m_descriptor->GetId(); + } + return ViewTreeItem::data(role); +} + +QSet DescriptorTreeItem::keywordLabels() const +{ + KeywordRegistry* registry = KeywordRegistry::GetInstance(); + QStringList ids = m_descriptor->GetKeywordReferences(); + QSet keywords; + keywords.insert(m_descriptor->GetLabel()); + for(auto id : ids) + { + QString label = registry->GetKeywordLabel(id); + for (auto keyword : label.split(' ', QString::SkipEmptyParts)) + { + keywords.insert(keyword); + } + } + return keywords; +} + +// --------------------------- CategoryTreeItem --------------------------- + +CategoryTreeItem::CategoryTreeItem(ViewTreeModel* model, IViewCategory::Pointer category, ViewTreeItem* parent) + : ViewTreeItem(model) + , m_category(category) +{ + if (parent) parent->appendChild(this); + this->CreateChildren(); +} + +QVariant CategoryTreeItem::data(int role) +{ + if (role == Qt::DisplayRole) + { + return m_category->GetLabel(); + } + else if (role == Qt::DecorationRole) + { + return QIcon::fromTheme("folder"); + } + else if (role == ViewTreeModel::Id) + { + return m_category->GetId(); + } + return ViewTreeItem::data(role); +} + +Qt::ItemFlags CategoryTreeItem::flags() const +{ + return Qt::ItemIsEnabled; +} + +QSet CategoryTreeItem::keywordLabels() const +{ + QSet keywords; + for(auto child : this->m_children) + { + for (auto keyword : child->data(ViewTreeModel::Keywords).toStringList()) + { + keywords.insert(keyword); + } + } + return keywords; +} + +void CategoryTreeItem::CreateChildren() +{ + auto viewDescriptors = m_category->GetViews(); + RemoveIntroView(viewDescriptors); + for(auto viewDescriptor : viewDescriptors) + { + new DescriptorTreeItem(this->m_model, viewDescriptor, this); + } +} + +void CategoryTreeItem::RemoveIntroView(QList& list) +{ + for (auto view = list.begin(); view != list.end();) + { + if ((*view)->GetId() == IntroConstants::INTRO_VIEW_ID) + { + view = list.erase(view); + } + else ++view; + } +} + +} diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/model/berryViewTreeModel.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/model/berryViewTreeModel.h new file mode 100644 index 0000000000..dfd9ec09b7 --- /dev/null +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/model/berryViewTreeModel.h @@ -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. + +===================================================================*/ + +#ifndef BERRYVIEWTREEMODEL_H +#define BERRYVIEWTREEMODEL_H + +#include + +#include + +#include + +namespace berry { + +struct IViewRegistry; +struct IWorkbenchWindow; + +class BERRY_UI_QT ViewTreeModel : public QAbstractItemModel +{ + Q_OBJECT + +public: + + ViewTreeModel(const IWorkbenchWindow* window, + QObject* parent = nullptr); + + ~ViewTreeModel(); + + enum Role { + Description = Qt::UserRole, + Keywords, + Id + }; + + QVariant data(const QModelIndex &index, int role) const override; + Qt::ItemFlags flags(const QModelIndex& index) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; + QModelIndex parent(const QModelIndex &child) const override; + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + int columnCount(const QModelIndex &parent = QModelIndex()) const override; + + const IWorkbenchWindow* GetWorkbenchWindow() const; + +private: + + struct Impl; + QScopedPointer d; +}; + +} + +#endif // BERRYVIEWTREEMODEL_H diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/services/berryIServiceLocator.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/services/berryIServiceLocator.h index a2f5f89a33..5957042b5a 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/services/berryIServiceLocator.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/services/berryIServiceLocator.h @@ -1,107 +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. ===================================================================*/ #ifndef BERRYISERVICELOCATOR_H_ #define BERRYISERVICELOCATOR_H_ #include #include #include #include #include #include namespace berry { /** *

* A component with which one or more services are registered. The services can * be retrieved from this locator using the service type. For example: *

* *
  * IHandlerService* service = workbenchWindow->GetService();
  * 
* *

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

*/ struct BERRY_UI_QT IServiceLocator : public virtual Object { - berryObjectMacro(berry::IServiceLocator) + berryObjectMacro(berry::IServiceLocator, Object) ~IServiceLocator(); /** * Retrieves the service corresponding to the given API. * * @tparam S * This is the interface that the service implements. Must not be * null. * @return The service, or null if no such service could be * found. */ template S* GetService() { const char* typeName = qobject_interface_iid(); if (typeName == NULL) { - BERRY_WARN << "Error getting service: Cannot get the interface id for type '" << Object::DemangleName(typeid(S).name()) + BERRY_WARN << "Error getting service: Cannot get the interface id for type '" << Reflection::GetClassName() << "'. It is probably missing a Q_DECLARE_INTERFACE macro in its header."; return NULL; } Object* obj = this->GetService(typeName); S* service = dynamic_cast(obj); if (obj != NULL && service == NULL) { BERRY_WARN << "Error getting service: Class '" << obj->GetClassName() << "' cannot be cast to service interface " - << "'" << Object::DemangleName(typeid(S).name()) << "'"; + << "'" << Reflection::GetClassName() << "'"; } return service; } /** * Whether this service exists within the scope of this service locator. * This does not include looking for the service within the scope of the * parents. This method can be used to determine whether a particular * service supports nesting in this scope. * * @tparam S * This is the interface that the service implements. Must not be * null. * @return true iff the service locator can find a service * for the given interface; false otherwise. */ template bool HasService() const { return this->HasService(qobject_interface_iid()); } virtual Object* GetService(const QString& api) = 0; virtual bool HasService(const QString& api) const = 0; }; } #endif /* BERRYISERVICELOCATOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/util/berrySafeRunnable.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/util/berrySafeRunnable.cpp index 70f7cd1e8c..03b253beb8 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/util/berrySafeRunnable.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/util/berrySafeRunnable.cpp @@ -1,135 +1,153 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "berrySafeRunnable.h" #include #include #include namespace berry { bool SafeRunnable::ignoreErrors = false; ISafeRunnableRunner::Pointer SafeRunnable::runner; class DefaultSafeRunnableRunner: public ISafeRunnableRunner { public: void Run(ISafeRunnable::Pointer code) { try { code->Run(); - } catch (const std::exception& e) + } + catch (const ctkException& e) + { + HandleException(code, e); + } + catch (const std::exception& e) { HandleException(code, e); - } catch (...) + } + catch (...) { HandleException(code); } } private: - void HandleException(ISafeRunnable::Pointer code, const std::exception& e = - std::exception()) + void HandleException(ISafeRunnable::Pointer code) + { + HandleException(code, ctkException("Unknown exception thrown")); + } + + void HandleException(ISafeRunnable::Pointer code, + const std::exception& e) + { + HandleException(code, ctkException(e.what())); + } + + void HandleException(ISafeRunnable::Pointer code, const ctkException& e) { try { static_cast(dynamic_cast (e)); } catch (const std::bad_cast&) { // TODO logging try { // Policy.getLog() // .log( // new Status(IStatus.ERROR, Policy.JFACE, // IStatus.ERROR, // "Exception occurred", e)); //$NON-NLS-1$ - } catch (...) + qDebug() << e.printStackTrace(); + } + catch (...) { //e.printStackTrace(); BERRY_ERROR << "Exception occurred" << std::endl; } } code->HandleException(e); } }; SmartPointer SafeRunnable::CreateDefaultRunner() { ISafeRunnableRunner::Pointer runner(new DefaultSafeRunnableRunner()); return runner; } SafeRunnable::SafeRunnable(const QString& message) : message(message) { } -void SafeRunnable::HandleException(const std::exception& /*e*/) +void SafeRunnable::HandleException(const ctkException& /*e*/) { // Workaround to avoid interactive error dialogs during // automated testing if (ignoreErrors) return; if (message.isEmpty()) message = "An error has occurred. See error log for more details."; // TODO status bar // Policy.getStatusHandler().show( // new Status(IStatus.ERROR, Policy.JFACE, message, e), // JFaceResources.getString("SafeRunnable.errorMessage")); //$NON-NLS-1$ BERRY_ERROR << message << std::endl; } bool SafeRunnable::GetIgnoreErrors() { return ignoreErrors; } void SafeRunnable::SetIgnoreErrors(bool flag) { ignoreErrors = flag; } SmartPointer SafeRunnable::GetRunner() { if (!runner) { runner = CreateDefaultRunner(); } return runner; } void SafeRunnable::SetRunner(SmartPointer runner) { SafeRunnable::runner = runner; } void SafeRunnable::Run(SmartPointer runnable) { GetRunner()->Run(runnable); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/util/berrySafeRunnable.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/util/berrySafeRunnable.h index dde7fb783f..761f64d6e6 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/util/berrySafeRunnable.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/util/berrySafeRunnable.h @@ -1,117 +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. ===================================================================*/ #ifndef BERRYSAFERUNNABLE_H_ #define BERRYSAFERUNNABLE_H_ #include #include "berryISafeRunnableRunner.h" namespace berry { /** * Implements a default implementation of ISafeRunnable. The default * implementation of HandleException opens a dialog to show any * errors as they accumulate. *

* This may be executed on any thread. */ class BERRY_UI_QT SafeRunnable : public ISafeRunnable { private: static bool ignoreErrors; static ISafeRunnableRunner::Pointer runner; QString message; /** * Creates the default safe runnable runner. * * @return the default safe runnable runner */ static ISafeRunnableRunner::Pointer CreateDefaultRunner(); public: using ISafeRunnable::Run; /** * Creates a new instance of SafeRunnable with the given error message. * * @param message * the error message to use */ SafeRunnable(const QString& message = ""); /* - * (non-Javadoc) - * - * @see ISafeRunnable#HandleException(const std::exception&) + * @see ISafeRunnable#HandleException(const ctkException&) */ - void HandleException(const std::exception& e); + void HandleException(const ctkException& e); /** * Flag to avoid interactive error dialogs during automated testing. * * @return true if errors should be ignored * */ static bool GetIgnoreErrors(); /** * Flag to avoid interactive error dialogs during automated testing. * * @param flag * set to true if errors should be ignored */ static void SetIgnoreErrors(bool flag); /** * Returns the safe runnable runner. * * @return the safe runnable runner * */ static ISafeRunnableRunner::Pointer GetRunner(); /** * Sets the safe runnable runner. * * @param runner * the runner to set, or null to reset to the * default runner */ static void SetRunner(ISafeRunnableRunner::Pointer runner); /** * Runs the given safe runnable using the safe runnable runner. This is a * convenience method, equivalent to: * SafeRunnable#GetRunner()->Run(runnable). * * @param runnable * the runnable to run */ static void Run(ISafeRunnable::Pointer runnable); }; } #endif /* BERRYSAFERUNNABLE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.h b/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.h index ea0030f974..9b60986401 100644 --- a/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.h +++ b/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.h @@ -1,212 +1,210 @@ /*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BERRYUITESTCASE_H_ #define BERRYUITESTCASE_H_ #include #include #include #include #include #include namespace berry { /** * UITestCase is a useful super class for most * UI tests cases. It contains methods to create new windows * and pages. It will also automatically close the test * windows when the tearDown method is called. */ class BERRY_UITEST_EXPORT UITestCase: public TestCase { public: /** * Returns the workbench page input to use for newly created windows. * * @return the page input to use for newly created windows * @since 3.1 */ static IAdaptable* GetPageInput(); UITestCase(const QString& testName); /** * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. * The default implementation does nothing. * Subclasses may extend. */ virtual void DoSetUp(); /** * Tears down the fixture, for example, close a network connection. * This method is called after a test is executed. * The default implementation closes all test windows, processing events both before * and after doing so. * Subclasses may extend. */ virtual void DoTearDown(); /** * Fails the test due to the given throwable. */ void failexc(const QString& message, const std::exception& e, long lineNumber = -1, const QString& fileName = "unknown"); /** * Open a test window with the empty perspective. */ IWorkbenchWindow::Pointer OpenTestWindow(); /** * Open a test window with the provided perspective. */ IWorkbenchWindow::Pointer OpenTestWindow(const QString& perspectiveId); /** * Close all test windows. */ void CloseAllTestWindows(); /** * Open a test page with the empty perspective in a window. */ IWorkbenchPage::Pointer OpenTestPage(const IWorkbenchWindow::Pointer& win); /** * Open "n" test pages with the empty perspective in a window. */ QList OpenTestPage( const IWorkbenchWindow::Pointer& win, int pageTotal); /** * Close all pages within a window. */ void CloseAllPages(const IWorkbenchWindow::Pointer& window); protected: /** * Outputs a trace message to the trace output device, if enabled. * By default, trace messages are sent to System.out. * * @param msg the trace message */ void Trace(const QString& msg); /** * Simple implementation of setUp. Subclasses are prevented * from overriding this method to maintain logging consistency. * DoSetUp() should be overriden instead. */ void setUp(); /** * Simple implementation of tearDown. Subclasses are prevented * from overriding this method to maintain logging consistency. * DoTearDown() should be overriden instead. */ void tearDown(); static void ProcessEvents(); /** * Set whether the window listener will manage opening and closing of created windows. */ void ManageWindows(bool manage); /** * Returns the workbench. * * @return the workbench * @since 3.1 */ IWorkbench* GetWorkbench(); class TestWindowListener: public IWindowListener { private: bool enabled; QList& testWindows; public: - berryObjectMacro(TestWindowListener) - TestWindowListener(QList& testWindows); void SetEnabled(bool enabled); void WindowActivated(const IWorkbenchWindow::Pointer& window); void WindowDeactivated(const IWorkbenchWindow::Pointer& window); void WindowClosed(const IWorkbenchWindow::Pointer& window); void WindowOpened(const IWorkbenchWindow::Pointer& window); }; IWorkbench* fWorkbench; private: QList testWindows; QScopedPointer windowListener; static void Indent(std::ostream& output, unsigned int indent); //static void Write(IStatus status, unsigned int indent); /** * Adds a window listener to the workbench to keep track of * opened test windows. */ void AddWindowListener(); /** * Removes the listener added by addWindowListener. */ void RemoveWindowListener(); /** * Try and process events until the new shell is the active shell. This may * never happen, so time out after a suitable period. * * @param shell * the shell to wait on * @since 3.2 */ void WaitOnShell(Shell::Pointer shell); }; #define failuimsg(msg, exc) \ (this->failexc(msg, exc, __LINE__, __FILE__)) } #endif /* BERRYUITESTCASE_H_ */ diff --git a/BlueBerry/Documentation/reference/extension-points/index.dox b/BlueBerry/Documentation/reference/extension-points/index.dox index 8b6e7c33fa..15a4f955fa 100644 --- a/BlueBerry/Documentation/reference/extension-points/index.dox +++ b/BlueBerry/Documentation/reference/extension-points/index.dox @@ -1,64 +1,95 @@ /** \page BlueBerryExtPointsIndex Extension-Point Reference

BlueBerry Platform Extension Points

The following extension points can be used to extend the capabilities of the platform infrastructure: -

Platform runtime

+

Platform Core Expressions

+
    +
  • \subpage xp_org_blueberry_core_expresions_definitions +
  • \subpage xp_org_blueberry_core_expresions_expressionLanguage +
  • \subpage xp_org_blueberry_core_expresions_propertyTesters +
+ + +

Platform Runtime

  • \subpage xp_org_blueberry_osgi_applications

Workbench

  • \subpage xp_org_blueberry_ui_editors +
  • \subpage xp_org_blueberry_ui_elementFactories +
  • \subpage xp_org_blueberry_ui_keywords +
  • \subpage xp_org_blueberry_ui_menus +
  • \subpage xp_org_blueberry_ui_perspectiveExtensions
  • \subpage xp_org_blueberry_ui_perspectives +
  • \subpage xp_org_blueberry_ui_preferencePages
  • \subpage xp_org_blueberry_ui_presentationFactories
  • \subpage xp_org_blueberry_ui_services -
  • \subpage xp_org_blueberry_ui_keywords -
  • \subpage xp_org_blueberry_ui_preferencePages
  • \subpage xp_org_blueberry_ui_tweaklets
  • \subpage xp_org_blueberry_ui_views

Other

  • \subpage xp_org_blueberry_tests
+\page xp_org_blueberry_core_expressions_definitions org.blueberry.core.expressions.definitions +\htmlinclude org_blueberry_core_expressions_definitions.html + +\page xp_org_blueberry_core_expressions_expressionLanguage org.blueberry.core.expressions.expressionLanguage +\htmlinclude org_blueberry_core_expressions_expressionLanguage.html + +\page xp_org_blueberry_core_expressions_propertyTesters org.blueberry.core.expressions.propertyTesters +\htmlinclude org_blueberry_core_expressions_propertyTesters.html + + \page xp_org_blueberry_osgi_applications org.blueberry.osgi.applications \htmlinclude org_blueberry_osgi_applications.html + +\page xp_org_blueberry_ui_elementFactories org.blueberry.ui.elementFactories +\htmlinclude org_blueberry_ui_elementFactories.html + +\page xp_org_blueberry_ui_menus org.blueberry.ui.menus +\htmlinclude org_blueberry_ui_menus.html + +\page xp_org_blueberry_ui_perspectiveExtensions org.blueberry.ui.perspectiveExtensions +\htmlinclude org_blueberry_ui_perspectiveExtensions.html + \page xp_org_blueberry_ui_editors org.blueberry.ui.editors \htmlinclude org_blueberry_ui_editors.html \page xp_org_blueberry_ui_perspectives org.blueberry.ui.perspectives \htmlinclude org_blueberry_ui_perspectives.html \page xp_org_blueberry_ui_presentationFactories org.blueberry.ui.presentationFactories \htmlinclude org_blueberry_ui_presentationFactories.html \page xp_org_blueberry_ui_services org.blueberry.ui.services \htmlinclude org_blueberry_ui_services.html \page xp_org_blueberry_ui_keywords org.blueberry.ui.keywords \htmlinclude org_blueberry_ui_keywords.html \page xp_org_blueberry_ui_preferencePages org.blueberry.ui.preferencePages \htmlinclude org_blueberry_ui_preferencePages.html \page xp_org_blueberry_ui_tweaklets org.blueberry.ui.tweaklets \htmlinclude org_blueberry_ui_tweaklets.html \page xp_org_blueberry_ui_views org.blueberry.ui.views \htmlinclude org_blueberry_ui_views.html \page xp_org_blueberry_tests org.blueberry.tests \htmlinclude org_blueberry_tests.html */ diff --git a/CMakeExternals/ITK.cmake b/CMakeExternals/ITK.cmake index cd49f4cad0..f0b5cde7ba 100644 --- a/CMakeExternals/ITK.cmake +++ b/CMakeExternals/ITK.cmake @@ -1,92 +1,92 @@ #----------------------------------------------------------------------------- # ITK #----------------------------------------------------------------------------- # Sanity checks if(DEFINED ITK_DIR AND NOT EXISTS ${ITK_DIR}) message(FATAL_ERROR "ITK_DIR variable is defined but corresponds to non-existing directory") endif() set(proj ITK) set(proj_DEPENDENCIES GDCM) if(MITK_USE_OpenCV) list(APPEND proj_DEPENDENCIES OpenCV) endif() if(MITK_USE_HDF5) list(APPEND proj_DEPENDENCIES HDF5) endif() set(ITK_DEPENDS ${proj}) if(NOT DEFINED ITK_DIR) set(additional_cmake_args ) if(MINGW) set(additional_cmake_args -DCMAKE_USE_WIN32_THREADS:BOOL=ON -DCMAKE_USE_PTHREADS:BOOL=OFF) endif() list(APPEND additional_cmake_args -DUSE_WRAP_ITK:BOOL=OFF ) if(MITK_USE_OpenCV) list(APPEND additional_cmake_args -DModule_ITKVideoBridgeOpenCV:BOOL=ON -DOpenCV_DIR:PATH=${OpenCV_DIR} ) endif() # Keep the behaviour of ITK 4.3 which by default turned on ITK Review # see MITK bug #17338 list(APPEND additional_cmake_args -DModule_ITKReview:BOOL=ON # for 4.7, the OpenJPEG is needed by review but the variable must be set -DModule_ITKOpenJPEG:BOOL=ON ) if(CTEST_USE_LAUNCHERS) list(APPEND additional_cmake_args "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" ) endif() set(vcl_constexpr_patch) - if(GCC_VERSION VERSION_LESS 4.7 AND GCC_VERSION VERSION_GREATER 4) + if(GCC_VERSION VERSION_LESS 4.8 AND GCC_VERSION VERSION_GREATER 4) set(vcl_constexpr_patch COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/ITK-4.7.1-gcc-4.6.patch ) endif() ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/InsightToolkit-4.7.1-20c0592.tar.gz URL_MD5 f778a5f0e297c06dc629c33ec45733dc # work with external GDCM PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/ITK-4.7.1.patch ${vcl_constexpr_patch} CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} ${additional_cmake_args} -DBUILD_EXAMPLES:BOOL=OFF -DITK_USE_SYSTEM_GDCM:BOOL=ON -DGDCM_DIR:PATH=${GDCM_DIR} CMAKE_CACHE_ARGS ${ep_common_cache_args} CMAKE_CACHE_DEFAULT_ARGS ${ep_common_cache_default_args} DEPENDS ${proj_DEPENDENCIES} ) set(ITK_DIR ${ep_prefix}) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() diff --git a/CMakeLists.txt b/CMakeLists.txt index fa8905dc5f..77a420128f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,1369 +1,1374 @@ set(MITK_CMAKE_MINIMUM_REQUIRED_VERSION 3.2) cmake_minimum_required(VERSION ${MITK_CMAKE_MINIMUM_REQUIRED_VERSION}) #----------------------------------------------------------------------------- -# See http://cmake.org/cmake/help/cmake-2-8-docs.html#section_Policies for details +# See http://www.cmake.org/cmake/help/v3.2/manual/cmake-policies.7.html for details #----------------------------------------------------------------------------- set(project_policies ) foreach(policy ${project_policies}) if(POLICY ${policy}) cmake_policy(SET ${policy} NEW) endif() endforeach() #----------------------------------------------------------------------------- # Superbuild Option - Enabled by default #----------------------------------------------------------------------------- option(MITK_USE_SUPERBUILD "Build MITK and the projects it depends on via SuperBuild.cmake." ON) if(MITK_USE_SUPERBUILD) project(MITK-superbuild) set(MITK_SOURCE_DIR ${PROJECT_SOURCE_DIR}) set(MITK_BINARY_DIR ${PROJECT_BINARY_DIR}) else() project(MITK VERSION 2014.10.99) endif() #----------------------------------------------------------------------------- # Update CMake module path #------------------------------------------------------------------------------ set(MITK_CMAKE_DIR ${MITK_SOURCE_DIR}/CMake) set(CMAKE_MODULE_PATH ${MITK_CMAKE_DIR} ${CMAKE_MODULE_PATH} ) #----------------------------------------------------------------------------- # CMake function(s) and macro(s) #----------------------------------------------------------------------------- # Standard CMake macros include(FeatureSummary) include(CTestUseLaunchers) include(CMakeParseArguments) include(FindPackageHandleStandardArgs) # MITK macros include(mitkFunctionGetGccVersion) include(mitkFunctionCheckCompilerFlags) include(mitkFunctionSuppressWarnings) # includes several functions include(mitkMacroEmptyExternalProject) include(mitkFunctionGenerateProjectXml) include(mitkFunctionEnableBuildConfiguration) include(mitkFunctionWhitelists) include(mitkFunctionAddExternalProject) SUPPRESS_VC_DEPRECATED_WARNINGS() #----------------------------------------------------------------------------- # Set a default build type if none was specified #----------------------------------------------------------------------------- if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) message(STATUS "Setting build type to 'Debug' as none was specified.") set(CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build." FORCE) # Set the possible values of build type for cmake-gui set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") endif() #----------------------------------------------------------------------------- # Check miminum Mac OS X version #----------------------------------------------------------------------------- # The minimum supported Mac OS X version is 10.9. If you use a version less than 10.9, there is no guarantee that the build still works. if(APPLE) exec_program(sw_vers ARGS -productVersion OUTPUT_VARIABLE osx_version) if (osx_version VERSION_LESS "10.9") message(WARNING "Detected OS X version \"${osx_version}\" is not supported anymore. Minimum required OS X version is 10.9 or greater.") endif() if (CMAKE_OSX_DEPLOYMENT_TARGET AND CMAKE_OSX_DEPLOYMENT_TARGET VERSION_LESS 10.9) message(WARNING "Detected OS X deployment target \"${CMAKE_OSX_DEPLOYMENT_TARGET}\" is not supported anymore. Minimum required OS X version is 10.9 or greater.") endif() endif() #----------------------------------------------------------------------------- # Check miminum compiler versions #----------------------------------------------------------------------------- if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") - # require at least gcc 4.6 as provided by Ubuntu 12.04 - if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.6) - message(FATAL_ERROR "GCC version must be at least 4.6") + # require at least gcc 4.7.3 as provided by ppa:ubuntu-toolchain-r/test for Ubuntu 12.04 + if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.7.3) + message(FATAL_ERROR "GCC version must be at least 4.7.3") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") - # require at least clang 3.2 for correct RTTI handling and C++11 support - if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.2) - message(FATAL_ERROR "Clang version must be at least 3.2") + # require at least clang 3.4 as provided by Ubuntu 12.04 + if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4) + message(FATAL_ERROR "Clang version must be at least 3.4") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang") # require at least clang 5.0 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0) message(FATAL_ERROR "Apple Clang version must be at least 5.0") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") - # require at least Visual Studio 2010 (msvc ...) - if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16) - message(FATAL_ERROR "Micorsoft Visual Studio 2010 or newer required (MSVC 16.0)") + # require at least Visual Studio 2012 + if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 17.0.61030.0) + message(FATAL_ERROR "Microsoft Visual Studio 2012 Update 4 or newer required (MSVC 17.0.61030.0)") endif() else() message(WARNING "You are using an unsupported compiler! Compilation has only been tested with Clang (Linux or Apple), GCC and MSVC.") endif() if(CMAKE_COMPILER_IS_GNUCXX) mitkFunctionGetGccVersion(${CMAKE_CXX_COMPILER} GCC_VERSION) else() set(GCC_VERSION 0) endif() set(MITK_CXX_STANDARD 11) set(CMAKE_CXX_EXTENSIONS 0) set(CMAKE_CXX_STANDARD ${MITK_CXX_STANDARD}) set(CMAKE_CXX_STANDARD_REQUIRED 1) # This is necessary to avoid problems with compile feature checks. # CMAKE_CXX_STANDARD seems to only set the -std=c++11 flag for targets. # However, compile flag checks also need to be done with -std=c++11. # The MITK_CXX11_FLAG variable is also used for external projects # build during the MITK super-build. mitkFunctionCheckCompilerFlags("-std=c++11" MITK_CXX11_FLAG) if(NOT MITK_CXX11_FLAG) # Older gcc compilers use -std=c++0x mitkFunctionCheckCompilerFlags("-std=c++0x" MITK_CXX11_FLAG) endif() #----------------------------------------------------------------------------- # Warn if source or build path is too long #----------------------------------------------------------------------------- if(WIN32) set(_src_dir_length_max 50) set(_bin_dir_length_max 50) if(MITK_USE_SUPERBUILD) set(_src_dir_length_max 43) # _src_dir_length_max - strlen(ITK-src) set(_bin_dir_length_max 40) # _bin_dir_length_max - strlen(MITK-build) endif() string(LENGTH "${MITK_SOURCE_DIR}" _src_n) string(LENGTH "${MITK_BINARY_DIR}" _bin_n) # The warnings should be converted to errors if(_src_n GREATER _src_dir_length_max) message(WARNING "MITK source code directory path length is too long (${_src_n} > ${_src_dir_length_max})." "Please move the MITK source code directory to a directory with a shorter path." ) endif() if(_bin_n GREATER _bin_dir_length_max) message(WARNING "MITK build directory path length is too long (${_bin_n} > ${_bin_dir_length_max})." "Please move the MITK build directory to a directory with a shorter path." ) endif() endif() #----------------------------------------------------------------------------- # Additional MITK Options (also shown during superbuild) #----------------------------------------------------------------------------- macro(env_option name doc value) set(_value $ENV{${name}}) if("${_value}" STREQUAL "") set(_value ${value}) endif() option(${name} "${doc}" ${_value}) endmacro() # ----------------------------------------- # General build options option(BUILD_SHARED_LIBS "Build MITK with shared libraries" ON) option(WITH_COVERAGE "Enable/Disable coverage" OFF) option(BUILD_TESTING "Test the project" ON) env_option(MITK_BUILD_ALL_APPS "Build all MITK applications" OFF) env_option(MITK_BUILD_EXAMPLES "Build the MITK Examples" OFF) option(MITK_ENABLE_PIC_READER "Enable support for reading the DKFZ pic file format." ON) mark_as_advanced(MITK_BUILD_ALL_APPS MITK_ENABLE_PIC_READER ) # ----------------------------------------- # Qt version related variables if(APPLE) set(DESIRED_QT_VERSION 4 CACHE STRING "Pick a version of Qt to use: 4 or 5") else() set(DESIRED_QT_VERSION 5 CACHE STRING "Pick a version of Qt to use: 4 or 5") endif() env_option(MITK_USE_QT "Use the Qt Company's Qt library" ON) set(MITK_DESIRED_QT_VERSION ${DESIRED_QT_VERSION}) if(MITK_USE_QT) # find the package at the very beginning, so that QT4_FOUND is available if(DESIRED_QT_VERSION MATCHES 4) set(MITK_QT4_MINIMUM_VERSION 4.7) find_package(Qt4 ${MITK_QT4_MINIMUM_VERSION} REQUIRED) set(MITK_USE_Qt4 TRUE) set(MITK_USE_Qt5 FALSE) endif() if(DESIRED_QT_VERSION MATCHES 5) set(MITK_QT5_MINIMUM_VERSION 5.0.0) set(MITK_USE_Qt4 FALSE) set(MITK_USE_Qt5 TRUE) set(CMAKE_PREFIX_PATH "${CMAKE_PREFIX_PATH}" CACHE PATH "") set(MITK_QT5_COMPONENTS Concurrent OpenGL PrintSupport Script Sql Svg WebKitWidgets Xml XmlPatterns UiTools) find_package(Qt5 ${MITK_QT5_MINIMUM_VERSION} COMPONENTS ${MITK_QT5_COMPONENTS} REQUIRED) if(Qt5_DIR) get_filename_component(_Qt5_DIR "${Qt5_DIR}/../../../" ABSOLUTE) list(FIND CMAKE_PREFIX_PATH "${_Qt5_DIR}" _result) if(_result LESS 0) set(CMAKE_PREFIX_PATH "${_Qt5_DIR};${CMAKE_PREFIX_PATH}" CACHE PATH "" FORCE) endif() endif() endif() else() set(MITK_USE_Qt4 FALSE) set(MITK_USE_Qt5 FALSE) endif() # ------------------------------------------------------------------------ # Register external projects which can be build with the MITK superbuild # system. Each mitkFunctionAddExternalProject() call registers an external # project for which a CMakeExternals/.cmake file must exist. The # call also creates a MITK_USE_ variable (appearing in the CMake # UI if the NO_CACHE option is *not* given). # ----------------------------------------- # Optional external projects with no # inter-dependencies set_property(GLOBAL PROPERTY MITK_EXTERNAL_PROJECTS "") mitkFunctionAddExternalProject(NAME Poco ON COMPONENTS Foundation Util XML Zip) mitkFunctionAddExternalProject(NAME Boost OFF DOC "Use the Boost C++ library") mitkFunctionAddExternalProject(NAME DCMTK ON DOC "EXPERIMENTAL, superbuild only: Use DCMTK in MITK") mitkFunctionAddExternalProject(NAME OpenIGTLink OFF) mitkFunctionAddExternalProject(NAME tinyxml ON ADVANCED) mitkFunctionAddExternalProject(NAME GDCM ON ADVANCED) mitkFunctionAddExternalProject(NAME GLUT OFF ADVANCED) mitkFunctionAddExternalProject(NAME Raptor2 OFF ADVANCED) mitkFunctionAddExternalProject(NAME Eigen ON ADVANCED DOC "Use the Eigen library") mitkFunctionAddExternalProject(NAME GLEW ON ADVANCED DOC "Use the GLEW library") mitkFunctionAddExternalProject(NAME ANN ON ADVANCED DOC "Use Approximate Nearest Neighbor Library") mitkFunctionAddExternalProject(NAME CppUnit ON ADVANCED DOC "Use CppUnit for unit tests") mitkFunctionAddExternalProject(NAME PCRE OFF ADVANCED NO_PACKAGE) mitkFunctionAddExternalProject(NAME ZLIB OFF ADVANCED NO_PACKAGE NO_CACHE) mitkFunctionAddExternalProject(NAME HDF5 OFF ADVANCED) # ----------------------------------------- # The following external projects must be # ordered according to their # inter-dependencies mitkFunctionAddExternalProject(NAME SWIG OFF ADVANCED NO_PACKAGE DEPENDS PCRE) mitkFunctionAddExternalProject(NAME Python OFF NO_PACKAGE DEPENDS SWIG DOC "Use Python wrapping in MITK") mitkFunctionAddExternalProject(NAME Numpy OFF ADVANCED NO_PACKAGE) mitkFunctionAddExternalProject(NAME OpenCV OFF) mitkFunctionAddExternalProject(NAME Vigra OFF DEPENDS HDF5) # These are "hard" dependencies and always set to ON mitkFunctionAddExternalProject(NAME ITK ON NO_CACHE) mitkFunctionAddExternalProject(NAME VTK ON NO_CACHE) mitkFunctionAddExternalProject(NAME SimpleITK OFF DEPENDS ITK GDCM SWIG) mitkFunctionAddExternalProject(NAME ACVD OFF DOC "Use Approximated Centroidal Voronoi Diagrams") mitkFunctionAddExternalProject(NAME CTK ON DEPENDS QT DCMTK DOC "Use CTK in MITK") mitkFunctionAddExternalProject(NAME Rasqal OFF DEPENDS Raptor2 PCRE ADVANCED) mitkFunctionAddExternalProject(NAME Redland OFF DEPENDS Rasqal DOC "Use the Redland RDF library") mitkFunctionAddExternalProject(NAME SOFA OFF DEPENDS GLUT Boost DOC "Use Simulation Open Framework Architecture") if(MITK_USE_QT) mitkFunctionAddExternalProject(NAME Qwt ON ADVANCED DEPENDS QT) endif() # ----------------------------------------- # Other MITK_USE_* options not related to # external projects build via the # MITK superbuild env_option(MITK_USE_BLUEBERRY "Build the BlueBerry platform" ON) env_option(MITK_USE_OpenCL "Use OpenCL GPU-Computing library" OFF) #----------------------------------------------------------------------------- # Build configurations #----------------------------------------------------------------------------- set(_buildConfigs "Custom") file(GLOB _buildConfigFiles CMake/BuildConfigurations/*.cmake) foreach(_buildConfigFile ${_buildConfigFiles}) get_filename_component(_buildConfigFile ${_buildConfigFile} NAME_WE) list(APPEND _buildConfigs ${_buildConfigFile}) endforeach() set(MITK_BUILD_CONFIGURATION "Custom" CACHE STRING "Use pre-defined MITK configurations") mark_as_advanced(MITK_BUILD_CONFIGURATION) set_property(CACHE MITK_BUILD_CONFIGURATION PROPERTY STRINGS ${_buildConfigs}) mitkFunctionEnableBuildConfiguration() mitkFunctionCreateWhitelistPaths(MITK) mitkFunctionFindWhitelists(MITK) # ----------------------------------------- # Custom dependency logic if(MITK_USE_Boost) option(MITK_USE_SYSTEM_Boost "Use the system Boost" OFF) set(MITK_USE_Boost_LIBRARIES "" CACHE STRING "A semi-colon separated list of required Boost libraries") endif() if(MITK_USE_SOFA) - # SOFA requires at least CMake 2.8.8 - set(SOFA_CMAKE_VERSION 2.8.8) - if(${CMAKE_VERSION} VERSION_LESS ${SOFA_CMAKE_VERSION}) - set(MITK_USE_SOFA OFF CACHE BOOL "" FORCE) - message(WARNING "Switched off MITK_USE_SOFA\n Minimum required CMake version: ${SOFA_CMAKE_VERSION}\n Installed CMake version: ${CMAKE_VERSION}") - endif() - # SOFA/ITK combination requires at least MSVC 2010 - if(MSVC_VERSION AND MSVC_VERSION LESS 1600) - set(MITK_USE_SOFA OFF CACHE BOOL "" FORCE) - message(WARNING "Switched off MITK_USE_SOFA\n MSVC versions less than 2010 are not supported.") - endif() # SOFA requires boost library if(MITK_USE_SOFA AND NOT MITK_USE_Boost) message("> Forcing MITK_USE_Boost to ON because of MITK_USE_SOFA") set(MITK_USE_Boost ON CACHE BOOL "" FORCE) endif() # SOFA requires boost system library list(FIND MITK_USE_Boost_LIBRARIES system _result) if(_result LESS 0) message("> Adding 'system' to MITK_USE_Boost_LIBRARIES.") list(APPEND MITK_USE_Boost_LIBRARIES system) endif() # SOFA requires boost thread library list(FIND MITK_USE_Boost_LIBRARIES thread _result) if(_result LESS 0) message("> Adding 'thread' to MITK_USE_Boost_LIBRARIES.") list(APPEND MITK_USE_Boost_LIBRARIES thread) endif() # Simulation plugin requires boost chrono library list(FIND MITK_USE_Boost_LIBRARIES chrono _result) if(_result LESS 0) message("> Adding 'chrono' to MITK_USE_Boost_LIBRARIES.") list(APPEND MITK_USE_Boost_LIBRARIES chrono) endif() set(MITK_USE_Boost_LIBRARIES ${MITK_USE_Boost_LIBRARIES} CACHE STRING "" FORCE) # Allow setting external SOFA plugins directory and SOFA plugins set(MITK_USE_SOFA_PLUGINS_DIR ${MITK_USE_SOFA_PLUGINS_DIR} CACHE PATH "External SOFA plugins directory" FORCE) set(MITK_USE_SOFA_PLUGINS ${MITK_USE_SOFA_PLUGINS} CACHE PATH "List of semicolon-separated plugin names" FORCE) endif() if(MITK_USE_Python AND NOT MITK_USE_SYSTEM_PYTHON) set(MITK_USE_ZLIB ON) if(NOT MITK_USE_Numpy) message("> Forcing MITK_USE_Numpy to ON because of MITK_USE_Python") set(MITK_USE_Numpy ON CACHE BOOL "Use Numpy" FORCE) endif() if(NOT MITK_USE_SimpleITK) message("> Forcing MITK_USE_SimpleITK to ON because of MITK_USE_Python") set(MITK_USE_Numpy ON CACHE BOOL "Use Numpy" FORCE) endif() if(APPLE) message(WARNING "Python wrapping is unsuported on mac OSX!") set(MITK_USE_Python OFF CACHE BOOL "Use Python wrapping in MITK" FORCE) else() option(MITK_USE_SYSTEM_PYTHON "Use the system python runtime" OFF) if(MITK_USE_SYSTEM_PYTHON) find_package(PythonLibs REQUIRED) find_package(PythonInterp REQUIRED) endif() endif() endif() if(BUILD_TESTING AND NOT MITK_USE_CppUnit) message("> Forcing MITK_USE_CppUnit to ON because BUILD_TESTING=ON") set(MITK_USE_CppUnit ON CACHE BOOL "Use CppUnit for unit tests" FORCE) endif() if(MITK_USE_BLUEBERRY) option(MITK_BUILD_ALL_PLUGINS "Build all MITK plugins" OFF) mark_as_advanced(MITK_BUILD_ALL_PLUGINS) if(NOT MITK_USE_CTK) message("> Forcing MITK_USE_CTK to ON because of MITK_USE_BLUEBERRY") set(MITK_USE_CTK ON CACHE BOOL "Use CTK in MITK" FORCE) endif() endif() #----------------------------------------------------------------------------- # Pixel type multiplexing #----------------------------------------------------------------------------- # Customize the default pixel types for multiplex macros set(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES "int, unsigned int, short, unsigned short, char, unsigned char" CACHE STRING "List of integral pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES "double, float" CACHE STRING "List of floating pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES "itk::RGBPixel, itk::RGBAPixel" CACHE STRING "List of composite pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_DIMENSIONS "2,3" CACHE STRING "List of dimensions used in AccessByItk and InstantiateAccessFunction macros") mark_as_advanced(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES MITK_ACCESSBYITK_DIMENSIONS ) # consistency checks if(NOT MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES) set(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES "int, unsigned int, short, unsigned short, char, unsigned char" CACHE STRING "List of integral pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES) set(MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES "double, float" CACHE STRING "List of floating pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES) set(MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES "itk::RGBPixel, itk::RGBAPixel" CACHE STRING "List of composite pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES) string(REPLACE "," ";" _integral_types ${MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES}) string(REPLACE "," ";" _floating_types ${MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES}) foreach(_scalar_type ${_integral_types} ${_floating_types}) set(MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}itk::VariableLengthVector<${_scalar_type}>,") endforeach() string(LENGTH "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}" _length) math(EXPR _length "${_length} - 1") string(SUBSTRING "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}" 0 ${_length} MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES) set(MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES ${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES} CACHE STRING "List of vector pixel types used in AccessByItk and InstantiateAccessFunction macros for itk::VectorImage types" FORCE) endif() if(NOT MITK_ACCESSBYITK_DIMENSIONS) set(MITK_ACCESSBYITK_DIMENSIONS "2,3" CACHE STRING "List of dimensions used in AccessByItk and InstantiateAccessFunction macros") endif() #----------------------------------------------------------------------------- # Project.xml #----------------------------------------------------------------------------- # A list of topologically ordered targets set(CTEST_PROJECT_SUBPROJECTS) if(MITK_USE_BLUEBERRY) list(APPEND CTEST_PROJECT_SUBPROJECTS BlueBerry) endif() list(APPEND CTEST_PROJECT_SUBPROJECTS MITK-Core MITK-CoreUI MITK-IGT MITK-ToF MITK-DTI MITK-Registration MITK-Modules # all modules not contained in a specific subproject MITK-Plugins # all plugins not contained in a specific subproject MITK-Examples Unlabeled # special "subproject" catching all unlabeled targets and tests ) # Configure CTestConfigSubProject.cmake that could be used by CTest scripts configure_file(${MITK_SOURCE_DIR}/CTestConfigSubProject.cmake.in ${MITK_BINARY_DIR}/CTestConfigSubProject.cmake) if(CTEST_PROJECT_ADDITIONAL_TARGETS) # those targets will be executed at the end of the ctest driver script # and they also get their own subproject label set(subproject_list "${CTEST_PROJECT_SUBPROJECTS};${CTEST_PROJECT_ADDITIONAL_TARGETS}") else() set(subproject_list "${CTEST_PROJECT_SUBPROJECTS}") endif() # Generate Project.xml file expected by the CTest driver script mitkFunctionGenerateProjectXml(${MITK_BINARY_DIR} MITK "${subproject_list}" ${MITK_USE_SUPERBUILD}) #----------------------------------------------------------------------------- # Superbuild script #----------------------------------------------------------------------------- if(MITK_USE_SUPERBUILD) include("${CMAKE_CURRENT_SOURCE_DIR}/SuperBuild.cmake") # Print configuration summary message("\n\n") feature_summary( DESCRIPTION "------- FEATURE SUMMARY FOR ${PROJECT_NAME} -------" WHAT ALL) return() endif() #***************************************************************************** #**************************** END OF SUPERBUILD **************************** #***************************************************************************** #----------------------------------------------------------------------------- # CMake function(s) and macro(s) #----------------------------------------------------------------------------- include(WriteBasicConfigVersionFile) include(CheckCXXSourceCompiles) include(GenerateExportHeader) include(mitkFunctionOrganizeSources) include(mitkFunctionGetVersion) include(mitkFunctionGetVersionDescription) include(mitkFunctionCreateWindowsBatchScript) include(mitkFunctionInstallProvisioningFiles) include(mitkFunctionInstallAutoLoadModules) include(mitkFunctionGetLibrarySearchPaths) include(mitkFunctionCompileSnippets) include(mitkFunctionUseModules) include(mitkFunctionCheckModuleDependencies) include(mitkFunctionCreateModule) include(mitkMacroCreateExecutable) include(mitkMacroCreateModuleTests) include(mitkFunctionAddCustomModuleTest) include(mitkMacroMultiplexPicType) include(mitkMacroInstall) include(mitkMacroInstallHelperApp) include(mitkMacroInstallTargets) include(mitkMacroGenerateToolsLibrary) include(mitkMacroGetLinuxDistribution) include(mitkMacroGetPMDPlatformString) include(mitkMacroConfigureItkPixelTypes) #----------------------------------------------------------------------------- # Global CMake variables #----------------------------------------------------------------------------- # Required and enabled C++11 features for all MITK code. # These are added as PUBLIC compile features to all MITK modules. -set(MITK_CXX_FEATURES cxx_auto_type cxx_nullptr cxx_override) +set(MITK_CXX_FEATURES + cxx_auto_type + cxx_decltype + cxx_enum_forward_declarations + cxx_extended_friend_declarations + cxx_extern_templates + cxx_final + cxx_lambdas + cxx_local_type_template_args + cxx_long_long_type + cxx_nullptr + cxx_override + cxx_range_for + cxx_right_angle_brackets + cxx_rvalue_references + cxx_static_assert + cxx_strong_enums + cxx_template_template_parameters + cxx_trailing_return_types + cxx_variadic_macros +) if(NOT DEFINED CMAKE_DEBUG_POSTFIX) # We can't do this yet because the CTK Plugin Framework # cannot cope with a postfix yet. #set(CMAKE_DEBUG_POSTFIX d) endif() #----------------------------------------------------------------------------- # Output directories. #----------------------------------------------------------------------------- set(_default_LIBRARY_output_dir lib) set(_default_RUNTIME_output_dir bin) set(_default_ARCHIVE_output_dir lib) foreach(type LIBRARY RUNTIME ARCHIVE) # Make sure the directory exists if(MITK_CMAKE_${type}_OUTPUT_DIRECTORY AND NOT EXISTS ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}) message("Creating directory MITK_CMAKE_${type}_OUTPUT_DIRECTORY: ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}") file(MAKE_DIRECTORY "${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}") endif() if(MITK_CMAKE_${type}_OUTPUT_DIRECTORY) set(CMAKE_${type}_OUTPUT_DIRECTORY ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}) else() set(CMAKE_${type}_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/${_default_${type}_output_dir}) set(MITK_CMAKE_${type}_OUTPUT_DIRECTORY ${CMAKE_${type}_OUTPUT_DIRECTORY}) endif() set(CMAKE_${type}_OUTPUT_DIRECTORY ${CMAKE_${type}_OUTPUT_DIRECTORY} CACHE INTERNAL "Output directory for ${type} files.") mark_as_advanced(CMAKE_${type}_OUTPUT_DIRECTORY) endforeach() #----------------------------------------------------------------------------- # Set MITK specific options and variables (NOT available during superbuild) #----------------------------------------------------------------------------- # ASK THE USER TO SHOW THE CONSOLE WINDOW FOR CoreApp and mitkWorkbench option(MITK_SHOW_CONSOLE_WINDOW "Use this to enable or disable the console window when starting MITK GUI Applications" ON) mark_as_advanced(MITK_SHOW_CONSOLE_WINDOW) # TODO: check if necessary option(USE_ITKZLIB "Use the ITK zlib for pic compression." ON) mark_as_advanced(USE_ITKZLIB) if(NOT MITK_FAST_TESTING) if(DEFINED MITK_CTEST_SCRIPT_MODE AND (MITK_CTEST_SCRIPT_MODE STREQUAL "continuous" OR MITK_CTEST_SCRIPT_MODE STREQUAL "experimental") ) set(MITK_FAST_TESTING 1) endif() endif() # MITK_VERSION set(MITK_VERSION_STRING "${MITK_VERSION_MAJOR}.${MITK_VERSION_MINOR}.${MITK_VERSION_PATCH}") if(MITK_VERSION_PATCH STREQUAL "99") set(MITK_VERSION_STRING "${MITK_VERSION_STRING}-${MITK_REVISION_SHORTID}") endif() # Needed early on for redirecting the BlueBerry documentation output dir set(MITK_DOXYGEN_OUTPUT_DIR ${PROJECT_BINARY_DIR}/Documentation/Doxygen CACHE PATH "Output directory for doxygen generated documentation." ) if(NOT UNIX AND NOT MINGW) set(MITK_WIN32_FORCE_STATIC "STATIC" CACHE INTERNAL "Use this variable to always build static libraries on non-unix platforms") endif() if(MITK_BUILD_ALL_PLUGINS) set(MITK_BUILD_ALL_PLUGINS_OPTION "FORCE_BUILD_ALL") endif() # Configure pixel types used for ITK image access multiplexing mitkMacroConfigureItkPixelTypes() # Configure module naming conventions set(MITK_MODULE_NAME_REGEX_MATCH "^[A-Z].*$") set(MITK_MODULE_NAME_REGEX_NOT_MATCH "^[Mm][Ii][Tt][Kk].*$") set(MITK_MODULE_NAME_PREFIX "Mitk") set(MITK_MODULE_NAME_DEFAULTS_TO_DIRECTORY_NAME 1) #----------------------------------------------------------------------------- # Get MITK version info #----------------------------------------------------------------------------- mitkFunctionGetVersion(${MITK_SOURCE_DIR} MITK) mitkFunctionGetVersionDescription(${MITK_SOURCE_DIR} MITK) #----------------------------------------------------------------------------- # Installation preparation # # These should be set before any MITK install macros are used #----------------------------------------------------------------------------- # on Mac OSX all BlueBerry plugins get copied into every # application bundle (.app directory) specified here if(MITK_USE_BLUEBERRY AND APPLE) include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/AppList.cmake") foreach(mitk_app ${MITK_APPS}) # extract option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 1 option_name) list(GET target_info_list 0 app_name) # check if the application is enabled if(${option_name} OR MITK_BUILD_ALL_APPS) set(MACOSX_BUNDLE_NAMES ${MACOSX_BUNDLE_NAMES} Mitk${app_name}) endif() endforeach() endif() #----------------------------------------------------------------------------- # Set coverage Flags #----------------------------------------------------------------------------- if(WITH_COVERAGE) if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") set(coverage_flags "-g -fprofile-arcs -ftest-coverage -O0 -DNDEBUG") set(COVERAGE_CXX_FLAGS ${coverage_flags}) set(COVERAGE_C_FLAGS ${coverage_flags}) endif() endif() #----------------------------------------------------------------------------- # MITK C/CXX Flags #----------------------------------------------------------------------------- set(MITK_C_FLAGS "${COVERAGE_C_FLAGS}") set(MITK_C_FLAGS_DEBUG ) set(MITK_C_FLAGS_RELEASE ) set(MITK_CXX_FLAGS "${COVERAGE_CXX_FLAGS} ${MITK_CXX11_FLAG}") set(MITK_CXX_FLAGS_DEBUG ) set(MITK_CXX_FLAGS_RELEASE ) set(MITK_EXE_LINKER_FLAGS ) set(MITK_SHARED_LINKER_FLAGS ) if(WIN32) set(MITK_CXX_FLAGS "${MITK_CXX_FLAGS} -D_WIN32_WINNT=0x0501 -DPOCO_NO_UNWINDOWS -DWIN32_LEAN_AND_MEAN -DNOMINMAX") mitkFunctionCheckCompilerFlags("/wd4005" MITK_CXX_FLAGS) # warning C4005: macro redefinition mitkFunctionCheckCompilerFlags("/wd4231" MITK_CXX_FLAGS) # warning C4231: nonstandard extension used : 'extern' before template explicit instantiation # the following line should be removed after fixing bug 17637 mitkFunctionCheckCompilerFlags("/wd4316" MITK_CXX_FLAGS) # warning C4316: object alignment on heap endif() if(NOT MSVC_VERSION) foreach(_flag -Wall -Wextra -Wpointer-arith -Winvalid-pch -Wcast-align -Wwrite-strings -Wno-error=gnu -Wno-error=unknown-pragmas # The strict-overflow warning is generated by ITK template code -Wno-error=strict-overflow -Woverloaded-virtual -Wstrict-null-sentinel #-Wold-style-cast #-Wsign-promo # the following two lines should be removed after ITK-3097 has # been resolved, see also MITK bug 15279 -Wno-unused-local-typedefs -Wno-array-bounds -fdiagnostics-show-option ) mitkFunctionCheckCAndCXXCompilerFlags(${_flag} MITK_C_FLAGS MITK_CXX_FLAGS) endforeach() endif() if(CMAKE_COMPILER_IS_GNUCXX AND NOT APPLE) mitkFunctionCheckCompilerFlags("-Wl,--no-undefined" MITK_SHARED_LINKER_FLAGS) mitkFunctionCheckCompilerFlags("-Wl,--as-needed" MITK_SHARED_LINKER_FLAGS) endif() if(CMAKE_COMPILER_IS_GNUCXX) - # With older version of gcc supporting the flag -fstack-protector-all, an extra dependency to libssp.so - # is introduced. If gcc is smaller than 4.4.0 and the build type is Release let's not include the flag. - # Doing so should allow to build package made for distribution using older linux distro. - if(${GCC_VERSION} VERSION_GREATER "4.4.0" OR (CMAKE_BUILD_TYPE STREQUAL "Debug" AND ${GCC_VERSION} VERSION_LESS "4.4.0")) - mitkFunctionCheckCAndCXXCompilerFlags("-fstack-protector-all" MITK_C_FLAGS MITK_CXX_FLAGS) - endif() + mitkFunctionCheckCAndCXXCompilerFlags("-fstack-protector-all" MITK_C_FLAGS MITK_CXX_FLAGS) + if(MINGW) # suppress warnings about auto imported symbols set(MITK_SHARED_LINKER_FLAGS "-Wl,--enable-auto-import ${MITK_SHARED_LINKER_FLAGS}") endif() set(MITK_CXX_FLAGS_RELEASE "-D_FORTIFY_SOURCE=2 ${MITK_CXX_FLAGS_RELEASE}") endif() set(MITK_MODULE_LINKER_FLAGS ${MITK_SHARED_LINKER_FLAGS}) set(MITK_EXE_LINKER_FLAGS ${MITK_SHARED_LINKER_FLAGS}) #----------------------------------------------------------------------------- # MITK Packages #----------------------------------------------------------------------------- set(MITK_MODULES_PACKAGE_DEPENDS_DIR ${MITK_SOURCE_DIR}/CMake/PackageDepends) set(MODULES_PACKAGE_DEPENDS_DIRS ${MITK_MODULES_PACKAGE_DEPENDS_DIR}) if(NOT MITK_USE_SYSTEM_Boost) set(Boost_NO_SYSTEM_PATHS 1) endif() set(Boost_USE_MULTITHREADED 1) set(Boost_USE_STATIC_LIBS 0) set(Boost_USE_STATIC_RUNTIME 0) # We need this later for a DCMTK workaround set(_dcmtk_dir_orig ${DCMTK_DIR}) # This property is populated at the top half of this file get_property(MITK_EXTERNAL_PROJECTS GLOBAL PROPERTY MITK_EXTERNAL_PROJECTS) foreach(ep ${MITK_EXTERNAL_PROJECTS}) get_property(_package GLOBAL PROPERTY MITK_${ep}_PACKAGE) get_property(_components GLOBAL PROPERTY MITK_${ep}_COMPONENTS) if(MITK_USE_${ep} AND _package) if(_components) find_package(${_package} COMPONENTS ${_components} REQUIRED CONFIG) else() # Prefer config mode first because it finds external # Config.cmake files pointed at by _DIR variables. # Otherwise, existing Find.cmake files could fail. # (e.g. in the case of GLEW and the FindGLEW.cmake file shipped # with CMake). find_package(${_package} QUIET CONFIG) string(TOUPPER "${_package}" _package_uc) if(NOT (${_package}_FOUND OR ${_package_uc}_FOUND)) find_package(${_package} REQUIRED) endif() endif() endif() endforeach() # Ensure that the MITK CMake module path comes first set(CMAKE_MODULE_PATH ${MITK_CMAKE_DIR} ${CMAKE_MODULE_PATH} ) if(MITK_USE_DCMTK) # Due to the preferred CONFIG mode in find_package calls above, # the DCMTKConfig.cmake file is read, which does not provide useful # package information. We explictly need MODULE mode to find DCMTK. if(${_dcmtk_dir_orig} MATCHES "${MITK_EXTERNAL_PROJECT_PREFIX}.*") # Help our FindDCMTK.cmake script find our super-build DCMTK set(DCMTK_DIR ${MITK_EXTERNAL_PROJECT_PREFIX}) else() # Use the original value set(DCMTK_DIR ${_dcmtk_dir_orig}) endif() find_package(DCMTK REQUIRED MODULE) endif() if(MITK_USE_Python) find_package(PythonLibs REQUIRED) find_package(PythonInterp REQUIRED) endif() if(MITK_USE_SOFA) # The SOFAConfig.cmake file does not provide exported targets or # libraries with absolute paths, hence we need to make the link # directories globally available until the SOFAConfig.cmake file # supports a proper mechanism for handling targets. # The same code is needed in MITKConfig.cmake. link_directories(${SOFA_LIBRARY_DIRS}) endif() if(MITK_USE_Boost) # Same as SOFA above link_directories(${Boost_LIBRARY_DIRS}) endif() if(MITK_USE_OpenIGTLink) # Same as SOFA above link_directories(${OpenIGTLink_LIBRARY_DIRS}) endif() if(MITK_USE_SimpleITK) link_directories(${SimpleITK_LIBRARY_DIRS}) endif() if(MITK_USE_OpenCL) find_package(OpenCL REQUIRED) endif() # Qt support if(MITK_USE_QT) if(DESIRED_QT_VERSION MATCHES 4) find_package(Qt4 ${MITK_QT4_MINIMUM_VERSION} REQUIRED) elseif(DESIRED_QT_VERSION MATCHES 5) find_package(Qt5Core ${MITK_QT5_MINIMUM_VERSION} REQUIRED) # at least Core required get_target_property(_qmake_exec Qt5::qmake LOCATION) execute_process(COMMAND ${_qmake_exec} -query QT_INSTALL_BINS RESULT_VARIABLE _result OUTPUT_VARIABLE QT_BINARY_DIR ERROR_VARIABLE _error ) string(STRIP "${QT_BINARY_DIR}" QT_BINARY_DIR) if(_result OR NOT EXISTS "${QT_BINARY_DIR}") message(FATAL_ERROR "Could not determine Qt binary directory: ${_result} ${QT_BINARY_DIR} ${_error}") endif() endif() endif() #----------------------------------------------------------------------------- # Testing #----------------------------------------------------------------------------- if(BUILD_TESTING) enable_testing() include(CTest) mark_as_advanced(TCL_TCLSH DART_ROOT) option(MITK_ENABLE_RENDERING_TESTING OFF "Enable the MITK rendering tests. Requires x-server in Linux.") #Rendering testing does not work for Linux nightlies, thus it is disabled per default #and activated for Mac and Windows. if(WIN32 OR APPLE) set(MITK_ENABLE_RENDERING_TESTING ON) endif() mark_as_advanced( MITK_ENABLE_RENDERING_TESTING ) # Setup file for setting custom ctest vars configure_file( CMake/CTestCustom.cmake.in ${MITK_BINARY_DIR}/CTestCustom.cmake @ONLY ) # Initial cache for ProjectTemplate and PluginGenerator tests configure_file( CMake/mitkTestInitialCache.txt.in ${MITK_BINARY_DIR}/mitkTestInitialCache.txt @ONLY ) # Configuration for the CMake-generated test driver set(CMAKE_TESTDRIVER_EXTRA_INCLUDES "#include ") set(CMAKE_TESTDRIVER_BEFORE_TESTMAIN " try {") set(CMAKE_TESTDRIVER_AFTER_TESTMAIN " } catch( std::exception & excp ) { fprintf(stderr,\"%s\\n\",excp.what()); return EXIT_FAILURE; } catch( ... ) { printf(\"Exception caught in the test driver\\n\"); return EXIT_FAILURE; } ") set(MITK_TEST_OUTPUT_DIR "${MITK_BINARY_DIR}/test_output") if(NOT EXISTS ${MITK_TEST_OUTPUT_DIR}) file(MAKE_DIRECTORY ${MITK_TEST_OUTPUT_DIR}) endif() # Test the external project template if(MITK_USE_BLUEBERRY) include(mitkTestProjectTemplate) endif() # Test the package target include(mitkPackageTest) endif() configure_file(mitkTestingConfig.h.in ${MITK_BINARY_DIR}/mitkTestingConfig.h) #----------------------------------------------------------------------------- # MITK_SUPERBUILD_BINARY_DIR #----------------------------------------------------------------------------- # If MITK_SUPERBUILD_BINARY_DIR isn't defined, it means MITK is *NOT* build using Superbuild. # In that specific case, MITK_SUPERBUILD_BINARY_DIR should default to MITK_BINARY_DIR if(NOT DEFINED MITK_SUPERBUILD_BINARY_DIR) set(MITK_SUPERBUILD_BINARY_DIR ${MITK_BINARY_DIR}) endif() #----------------------------------------------------------------------------- # Set C/CXX and linker flags for MITK code #----------------------------------------------------------------------------- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${MITK_CXX_FLAGS}") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${MITK_CXX_FLAGS_DEBUG}") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${MITK_CXX_FLAGS_RELEASE}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${MITK_C_FLAGS}") set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} ${MITK_C_FLAGS_DEBUG}") set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} ${MITK_C_FLAGS_RELEASE}") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${MITK_EXE_LINKER_FLAGS}") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${MITK_SHARED_LINKER_FLAGS}") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${MITK_MODULE_LINKER_FLAGS}") #----------------------------------------------------------------------------- # Compile Utilities and set-up MITK variables #----------------------------------------------------------------------------- add_subdirectory(Utilities) if(MITK_USE_BLUEBERRY) # We need to hack a little bit because MITK applications may need # to enable certain BlueBerry plug-ins. However, these plug-ins # are validated separately from the MITK plug-ins and know nothing # about potential MITK plug-in dependencies of the applications. Hence # we cannot pass the MITK application list to the BlueBerry # ctkMacroSetupPlugins call but need to extract the BlueBerry dependencies # from the applications and set them explicitly. include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/AppList.cmake") foreach(mitk_app ${MITK_APPS}) # extract target_dir and option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 0 target_dir) list(GET target_info_list 1 option_name) # check if the application is enabled and if target_libraries.cmake exists if((${option_name} OR MITK_BUILD_ALL_APPS) AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/Applications/${target_dir}/target_libraries.cmake") include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/${target_dir}/target_libraries.cmake") foreach(_target_dep ${target_libraries}) if(_target_dep MATCHES org_blueberry_) string(REPLACE _ . _app_bb_dep ${_target_dep}) # explicitly set the build option for the BlueBerry plug-in set(BLUEBERRY_BUILD_${_app_bb_dep} ON CACHE BOOL "Build the ${_app_bb_dep} plug-in") endif() endforeach() endif() endforeach() set(mbilog_DIR "${mbilog_BINARY_DIR}") if(MITK_BUILD_ALL_PLUGINS) set(BLUEBERRY_BUILD_ALL_PLUGINS ON) endif() set(BLUEBERRY_CXX_FLAGS "${MITK_CXX_FLAGS}") set(BLUEBERRY_CXX_FLAGS_RELEASE "${MITK_CXX_FLAGS_RELEASE}") set(BLUEBERRY_C_FLAGS "${MITK_C_FLAGS}") set(BLUEBERRY_XPDOC_OUTPUT_DIR ${MITK_DOXYGEN_OUTPUT_DIR}/html/extension-points/html/) add_subdirectory(BlueBerry) set(BlueBerry_DIR ${CMAKE_CURRENT_BINARY_DIR}/BlueBerry CACHE PATH "The directory containing a CMake configuration file for BlueBerry" FORCE) include(mitkMacroCreateCTKPlugin) endif() #----------------------------------------------------------------------------- # Add custom targets representing CDash subprojects #----------------------------------------------------------------------------- foreach(subproject ${CTEST_PROJECT_SUBPROJECTS}) if(NOT TARGET ${subproject} AND NOT subproject MATCHES "Unlabeled") add_custom_target(${subproject}) endif() endforeach() #----------------------------------------------------------------------------- # Add subdirectories #----------------------------------------------------------------------------- add_subdirectory(Modules) if(MITK_USE_BLUEBERRY) find_package(BlueBerry REQUIRED) set(MITK_DEFAULT_SUBPROJECTS MITK-Plugins) # Plug-in testing (needs some work to be enabled again) if(BUILD_TESTING) include(berryTestingHelpers) set(BLUEBERRY_UI_TEST_APP "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CoreApp") if(TARGET CoreApp) get_target_property(_is_macosx_bundle CoreApp MACOSX_BUNDLE) if(APPLE AND _is_macosx_bundle) set(BLUEBERRY_UI_TEST_APP "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CoreApp.app/Contents/MacOS/CoreApp") endif() endif() set(BLUEBERRY_TEST_APP_ID "org.mitk.qt.coreapplication") endif() include("${CMAKE_CURRENT_SOURCE_DIR}/Plugins/PluginList.cmake") mitkFunctionWhitelistPlugins(MITK MITK_EXT_PLUGINS) set(mitk_plugins_fullpath "") foreach(mitk_plugin ${MITK_EXT_PLUGINS}) list(APPEND mitk_plugins_fullpath Plugins/${mitk_plugin}) endforeach() if(EXISTS ${MITK_PRIVATE_MODULES}/PluginList.cmake) include(${MITK_PRIVATE_MODULES}/PluginList.cmake) foreach(mitk_plugin ${MITK_PRIVATE_PLUGINS}) list(APPEND mitk_plugins_fullpath ${MITK_PRIVATE_MODULES}/${mitk_plugin}) endforeach() endif() if(MITK_BUILD_EXAMPLES) include("${CMAKE_CURRENT_SOURCE_DIR}/Examples/Plugins/PluginList.cmake") set(mitk_example_plugins_fullpath ) foreach(mitk_example_plugin ${MITK_EXAMPLE_PLUGINS}) list(APPEND mitk_example_plugins_fullpath Examples/Plugins/${mitk_example_plugin}) list(APPEND mitk_plugins_fullpath Examples/Plugins/${mitk_example_plugin}) endforeach() endif() # Specify which plug-ins belong to this project macro(GetMyTargetLibraries all_target_libraries varname) set(re_ctkplugin_mitk "^org_mitk_[a-zA-Z0-9_]+$") set(re_ctkplugin_bb "^org_blueberry_[a-zA-Z0-9_]+$") set(_tmp_list) list(APPEND _tmp_list ${all_target_libraries}) ctkMacroListFilter(_tmp_list re_ctkplugin_mitk re_ctkplugin_bb OUTPUT_VARIABLE ${varname}) endmacro() # Get infos about application directories and build options include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/AppList.cmake") set(mitk_apps_fullpath ) foreach(mitk_app ${MITK_APPS}) string(FIND ${mitk_app} "MITK_BUILD_APP_" _index) string(SUBSTRING ${mitk_app} ${_index} -1 _var) if(${_var}) list(APPEND mitk_apps_fullpath "${CMAKE_CURRENT_SOURCE_DIR}/Applications/${mitk_app}") endif() endforeach() if (mitk_plugins_fullpath) ctkMacroSetupPlugins(${mitk_plugins_fullpath} BUILD_OPTION_PREFIX MITK_BUILD_ APPS ${mitk_apps_fullpath} BUILD_ALL ${MITK_BUILD_ALL_PLUGINS} COMPACT_OPTIONS) endif() set(MITK_PLUGIN_USE_FILE "${MITK_BINARY_DIR}/MitkPluginUseFile.cmake") if(${PROJECT_NAME}_PLUGIN_LIBRARIES) ctkFunctionGeneratePluginUseFile(${MITK_PLUGIN_USE_FILE}) else() file(REMOVE ${MITK_PLUGIN_USE_FILE}) set(MITK_PLUGIN_USE_FILE ) endif() endif() #----------------------------------------------------------------------------- # Documentation #----------------------------------------------------------------------------- add_subdirectory(Documentation) #----------------------------------------------------------------------------- # Installation #----------------------------------------------------------------------------- # set MITK cpack variables # These are the default variables, which can be overwritten ( see below ) include(mitkSetupCPack) set(use_default_config ON) # MITK_APPS is set in Applications/AppList.cmake (included somewhere above # if MITK_USE_BLUEBERRY is set to ON). if(MITK_APPS) set(activated_apps_no 0) list(LENGTH MITK_APPS app_count) # Check how many apps have been enabled # If more than one app has been activated, the we use the # default CPack configuration. Otherwise that apps configuration # will be used, if present. foreach(mitk_app ${MITK_APPS}) # extract option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 1 option_name) # check if the application is enabled if(${option_name} OR MITK_BUILD_ALL_APPS) MATH(EXPR activated_apps_no "${activated_apps_no} + 1") endif() endforeach() if(app_count EQUAL 1 AND (activated_apps_no EQUAL 1 OR MITK_BUILD_ALL_APPS)) # Corner case if there is only one app in total set(use_project_cpack ON) elseif(activated_apps_no EQUAL 1 AND NOT MITK_BUILD_ALL_APPS) # Only one app is enabled (no "build all" flag set) set(use_project_cpack ON) else() # Less or more then one app is enabled set(use_project_cpack OFF) endif() foreach(mitk_app ${MITK_APPS}) # extract target_dir and option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 0 target_dir) list(GET target_info_list 1 option_name) # check if the application is enabled if(${option_name} OR MITK_BUILD_ALL_APPS) # check whether application specific configuration files will be used if(use_project_cpack) # use files if they exist if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/Applications/${target_dir}/CPackOptions.cmake") include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/${target_dir}/CPackOptions.cmake") endif() if(EXISTS "${PROJECT_SOURCE_DIR}/Applications/${target_dir}/CPackConfig.cmake.in") set(CPACK_PROJECT_CONFIG_FILE "${PROJECT_BINARY_DIR}/Applications/${target_dir}/CPackConfig.cmake") configure_file(${PROJECT_SOURCE_DIR}/Applications/${target_dir}/CPackConfig.cmake.in ${CPACK_PROJECT_CONFIG_FILE} @ONLY) set(use_default_config OFF) endif() endif() # add link to the list list(APPEND CPACK_CREATE_DESKTOP_LINKS "${target_dir}") endif() endforeach() endif() # if no application specific configuration file was used, use default if(use_default_config) configure_file(${MITK_SOURCE_DIR}/MITKCPackOptions.cmake.in ${MITK_BINARY_DIR}/MITKCPackOptions.cmake @ONLY) set(CPACK_PROJECT_CONFIG_FILE "${MITK_BINARY_DIR}/MITKCPackOptions.cmake") endif() # include CPack model once all variables are set include(CPack) # Additional installation rules include(mitkInstallRules) #----------------------------------------------------------------------------- # Last configuration steps #----------------------------------------------------------------------------- # ---------------- Export targets ----------------- set(MITK_EXPORTS_FILE "${MITK_BINARY_DIR}/MitkExports.cmake") file(REMOVE ${MITK_EXPORTS_FILE}) set(targets_to_export) get_property(module_targets GLOBAL PROPERTY MITK_MODULE_TARGETS) if(module_targets) list(APPEND targets_to_export ${module_targets}) endif() if(MITK_USE_BLUEBERRY) if(MITK_PLUGIN_LIBRARIES) list(APPEND targets_to_export ${MITK_PLUGIN_LIBRARIES}) endif() endif() export(TARGETS ${targets_to_export} APPEND FILE ${MITK_EXPORTS_FILE}) set(MITK_EXPORTED_TARGET_PROPERTIES ) foreach(target_to_export ${targets_to_export}) get_target_property(autoload_targets ${target_to_export} MITK_AUTOLOAD_TARGETS) if(autoload_targets) set(MITK_EXPORTED_TARGET_PROPERTIES "${MITK_EXPORTED_TARGET_PROPERTIES} set_target_properties(${target_to_export} PROPERTIES MITK_AUTOLOAD_TARGETS \"${autoload_targets}\")") endif() get_target_property(autoload_dir ${target_to_export} MITK_AUTOLOAD_DIRECTORY) if(autoload_dir) set(MITK_EXPORTED_TARGET_PROPERTIES "${MITK_EXPORTED_TARGET_PROPERTIES} set_target_properties(${target_to_export} PROPERTIES MITK_AUTOLOAD_DIRECTORY \"${autoload_dir}\")") endif() get_target_property(deprecated_module ${target_to_export} MITK_MODULE_DEPRECATED_SINCE) if(deprecated_module) set(MITK_EXPORTED_TARGET_PROPERTIES "${MITK_EXPORTED_TARGET_PROPERTIES} set_target_properties(${target_to_export} PROPERTIES MITK_MODULE_DEPRECATED_SINCE \"${deprecated_module}\")") endif() endforeach() # ---------------- External projects ----------------- get_property(MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS_CONFIG GLOBAL PROPERTY MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS) set(MITK_CONFIG_EXTERNAL_PROJECTS ) #string(REPLACE "^^" ";" _mitk_external_projects ${MITK_EXTERNAL_PROJECTS}) foreach(ep ${MITK_EXTERNAL_PROJECTS}) get_property(_components GLOBAL PROPERTY MITK_${ep}_COMPONENTS) set(MITK_CONFIG_EXTERNAL_PROJECTS "${MITK_CONFIG_EXTERNAL_PROJECTS} set(MITK_USE_${ep} ${MITK_USE_${ep}}) set(MITK_${ep}_DIR \"${${ep}_DIR}\") set(MITK_${ep}_COMPONENTS ${_components}) ") endforeach() foreach(ep ${MITK_EXTERNAL_PROJECTS}) get_property(_package GLOBAL PROPERTY MITK_${ep}_PACKAGE) get_property(_components GLOBAL PROPERTY MITK_${ep}_COMPONENTS) if(_components) set(_components_arg COMPONENTS \${_components}) else() set(_components_arg) endif() if(_package) set(MITK_CONFIG_EXTERNAL_PROJECTS "${MITK_CONFIG_EXTERNAL_PROJECTS} if(MITK_USE_${ep}) set(${ep}_DIR \${MITK_${ep}_DIR}) if(MITK_${ep}_COMPONENTS) mitkMacroFindDependency(${_package} COMPONENTS \${MITK_${ep}_COMPONENTS}) else() mitkMacroFindDependency(${_package}) endif() endif()") endif() endforeach() # ---------------- Tools ----------------- configure_file(${MITK_SOURCE_DIR}/CMake/ToolExtensionITKFactory.cpp.in ${MITK_BINARY_DIR}/ToolExtensionITKFactory.cpp.in COPYONLY) configure_file(${MITK_SOURCE_DIR}/CMake/ToolExtensionITKFactoryLoader.cpp.in ${MITK_BINARY_DIR}/ToolExtensionITKFactoryLoader.cpp.in COPYONLY) configure_file(${MITK_SOURCE_DIR}/CMake/ToolGUIExtensionITKFactory.cpp.in ${MITK_BINARY_DIR}/ToolGUIExtensionITKFactory.cpp.in COPYONLY) # ---------------- Configure files ----------------- configure_file(mitkVersion.h.in ${MITK_BINARY_DIR}/mitkVersion.h) configure_file(mitkConfig.h.in ${MITK_BINARY_DIR}/mitkConfig.h) set(IPFUNC_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Utilities/ipFunc) set(UTILITIES_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Utilities) configure_file(mitkConfig.h.in ${MITK_BINARY_DIR}/mitkConfig.h) configure_file(MITKConfig.cmake.in ${MITK_BINARY_DIR}/MITKConfig.cmake @ONLY) write_basic_config_version_file(${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake VERSION ${MITK_VERSION_STRING} COMPATIBILITY AnyNewerVersion) # If we are under Windows, create two batch files which correctly # set up the environment for the application and for Visual Studio if(WIN32) include(mitkFunctionCreateWindowsBatchScript) set(VS_SOLUTION_FILE "${PROJECT_BINARY_DIR}/${PROJECT_NAME}.sln") if(MITK_USE_HDF5) list(APPEND MITK_LIBRARY_DIRS ${HDF5_DIR}/install/bin) message(STATUS "MITK-Runtime " ${MITK_RUNTIME_PATH}) endif(MITK_USE_HDF5) foreach(VS_BUILD_TYPE debug release) mitkFunctionCreateWindowsBatchScript("${MITK_SOURCE_DIR}/CMake/StartVS.bat.in" ${PROJECT_BINARY_DIR}/StartVS_${VS_BUILD_TYPE}.bat ${VS_BUILD_TYPE}) endforeach() endif(WIN32) #----------------------------------------------------------------------------- # MITK Applications #----------------------------------------------------------------------------- # This must come after MITKConfig.h was generated, since applications # might do a find_package(MITK REQUIRED). add_subdirectory(Applications) #----------------------------------------------------------------------------- # MITK Examples #----------------------------------------------------------------------------- if(MITK_BUILD_EXAMPLES) # This must come after MITKConfig.h was generated, since applications # might do a find_package(MITK REQUIRED). add_subdirectory(Examples) endif() #----------------------------------------------------------------------------- # Print configuration summary #----------------------------------------------------------------------------- message("\n\n") feature_summary( DESCRIPTION "------- FEATURE SUMMARY FOR ${PROJECT_NAME} -------" WHAT ALL ) diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewer.cpp b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewer.cpp index cf94111eee..a47e2edfd4 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewer.cpp +++ b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewer.cpp @@ -1,45 +1,45 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "CustomViewer.h" #include "CustomViewerWorkbenchAdvisor.h" #include CustomViewer::CustomViewer() { } CustomViewer::~CustomViewer() { } int CustomViewer::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); - wbAdvisor.reset(new CustomViewerWorkbenchAdvisor); - int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); + CustomViewerWorkbenchAdvisor* wbAdvisor = new CustomViewerWorkbenchAdvisor; + int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void CustomViewer::Stop() { } diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewer.h b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewer.h index 5acf740db0..12eea2c3e2 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewer.h +++ b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewer.h @@ -1,60 +1,55 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef CUSTOMVIEWER_H_ #define CUSTOMVIEWER_H_ #include /// Qt #include #include class CustomViewerWorkbenchAdvisor; /** Documentation * \ingroup org_mitk_example_gui_customviewer * * \brief A blueberry application class as an entry point for the custom viewer plug-in. * * This class acts as an entry point application class for the dedicated custom viewer plug-in. */ class CustomViewer : public QObject, public berry::IApplication { Q_OBJECT Q_INTERFACES(berry::IApplication) public: /** Standard constructor.*/ CustomViewer(); /** Standard destructor.*/ ~CustomViewer(); /** Starts the application.*/ int Start(); /** Exits the application.*/ void Stop(); - -private: - -/** The WorkbenchAdvisor for the CustomViewer application.*/ - QScopedPointer wbAdvisor; }; #endif /*CUSTOMVIEWER_H_*/ diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.cpp b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.cpp index fb3857a8e7..fcc8290a7e 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.cpp +++ b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.cpp @@ -1,59 +1,58 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "CustomViewerWorkbenchAdvisor.h" #include "CustomViewerWorkbenchWindowAdvisor.h" #include "berryIQtStyleManager.h" #include "org_mitk_example_gui_customviewer_Activator.h" const QString CustomViewerWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.viewerperspective"; // //! [WorkbenchAdvisorCreateWindowAdvisor] berry::WorkbenchWindowAdvisor* CustomViewerWorkbenchAdvisor::CreateWorkbenchWindowAdvisor(berry::IWorkbenchWindowConfigurer::Pointer configurer) { - wwAdvisor.reset(new CustomViewerWorkbenchWindowAdvisor(configurer)); - return wwAdvisor.data(); + return new CustomViewerWorkbenchWindowAdvisor(configurer); } // //! [WorkbenchAdvisorCreateWindowAdvisor] CustomViewerWorkbenchAdvisor::~CustomViewerWorkbenchAdvisor() { } // //! [WorkbenchAdvisorInit] void CustomViewerWorkbenchAdvisor::Initialize(berry::IWorkbenchConfigurer::Pointer configurer) { berry::QtWorkbenchAdvisor::Initialize(configurer); ctkPluginContext* pluginContext = org_mitk_example_gui_customviewer_Activator::GetPluginContext(); ctkServiceReference serviceReference = pluginContext->getServiceReference(); //always granted by org.blueberry.ui.qt Q_ASSERT(serviceReference); berry::IQtStyleManager* styleManager = pluginContext->getService(serviceReference); Q_ASSERT(styleManager); QString styleName = "CustomStyle"; styleManager->AddStyle(":/customstyle.qss", styleName); styleManager->SetStyle(":/customstyle.qss"); //styleManager->AddStyle("/home/me/customstyle.qss", styleName); //styleManager->SetStyle("/home/me/customstyle.qss"); } // //! [WorkbenchAdvisorInit] QString CustomViewerWorkbenchAdvisor::GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } diff --git a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.h b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.h index 86837c2c55..e3bc5323c0 100644 --- a/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.h +++ b/Examples/Plugins/org.mitk.example.gui.customviewer/src/internal/CustomViewerWorkbenchAdvisor.h @@ -1,55 +1,51 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 /** * \brief A WorkbenchAdvisor class for the custom viewer plug-in. * * This WorkbenchAdvisor class for the custom viewer plug-in adds and sets a Qt-Stylesheet * file to the berry::QtStyleManager during the initialization phase for customization purpose. */ // //! [WorkbenchAdvisorDecl] class CustomViewerWorkbenchAdvisor : public berry::QtWorkbenchAdvisor // //! [WorkbenchAdvisorDecl] { public: /** * Holds the ID-String of the initial window perspective. */ static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor(berry::IWorkbenchWindowConfigurer::Pointer); ~CustomViewerWorkbenchAdvisor(); /** * Gets the style manager (berry::IQtStyleManager), adds and initializes a Qt-Stylesheet-File (.qss). */ void Initialize(berry::IWorkbenchConfigurer::Pointer); /** * Returns the ID-String of the initial window perspective. */ QString GetInitialWindowPerspectiveId(); -private: - - QScopedPointer wwAdvisor; - }; diff --git a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinition.cpp b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinition.cpp index 50ccdc2372..4822100c8a 100644 --- a/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinition.cpp +++ b/Examples/Plugins/org.mitk.example.gui.extensionpointdefinition/src/internal/ExtensionPointDefinition.cpp @@ -1,83 +1,78 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "ExtensionPointDefinition.h" // berry Includes #include #include #include class MinimalWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // Set an individual initial size configurer->SetInitialSize(QPoint(600,400)); // Set an individual title configurer->SetTitle("Extension Points"); // Enable or disable the perspective bar configurer->SetShowPerspectiveBar(false); - wwAdvisor.reset(new berry::WorkbenchWindowAdvisor(configurer)); - return wwAdvisor.data(); + return new berry::WorkbenchWindowAdvisor(configurer); } QString GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } -private: - - QScopedPointer wwAdvisor; - }; const QString MinimalWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.minimalperspective"; ExtensionPointDefinition::ExtensionPointDefinition() { } ExtensionPointDefinition::~ExtensionPointDefinition() { } int ExtensionPointDefinition::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); wbAdvisor.reset(new MinimalWorkbenchAdvisor); int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void ExtensionPointDefinition::Stop() { //nothing to do } diff --git a/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MultiplePerspectives.cpp b/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MultiplePerspectives.cpp index 589e4846f9..b020a57a37 100644 --- a/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MultiplePerspectives.cpp +++ b/Examples/Plugins/org.mitk.example.gui.multipleperspectives/src/internal/MultiplePerspectives.cpp @@ -1,88 +1,83 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "MultiplePerspectives.h" // berry includes #include #include #include class MultiplePerspectivesWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { //! [initial window size] // Set an individual initial size configurer->SetInitialSize(QPoint(600,400)); //! [initial window size] // Set an individual title configurer->SetTitle("Multiple Perspectives"); //! [Visibility of perspective bar] // Enable or disable the perspective bar configurer->SetShowPerspectiveBar(true); //! [Visibility of perspective bar] - wwAdvisor.reset(new berry::WorkbenchWindowAdvisor(configurer)); - return wwAdvisor.data(); + return new berry::WorkbenchWindowAdvisor(configurer); } QString GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } -private: - - QScopedPointer wwAdvisor; - }; const QString MultiplePerspectivesWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.minimalperspective"; MultiplePerspectives::MultiplePerspectives() { } MultiplePerspectives::~MultiplePerspectives() { } int MultiplePerspectives::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); wbAdvisor.reset(new MultiplePerspectivesWorkbenchAdvisor); int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void MultiplePerspectives::Stop() { } diff --git a/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/SelectionServiceMitk.cpp b/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/SelectionServiceMitk.cpp index f9a1603e76..d1ad2f80a4 100644 --- a/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/SelectionServiceMitk.cpp +++ b/Examples/Plugins/org.mitk.example.gui.selectionservicemitk/src/internal/SelectionServiceMitk.cpp @@ -1,80 +1,75 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "SelectionServiceMitk.h" // berry includes #include #include #include class SelectionServiceMITKWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // Set an individual initial size configurer->SetInitialSize(QPoint(600,400)); // Set the window title configurer->SetTitle("MITK Selection Service"); - wwAdvisor.reset(new berry::WorkbenchWindowAdvisor(configurer)); - return wwAdvisor.data(); + return new berry::WorkbenchWindowAdvisor(configurer); } QString GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } -private: - - QScopedPointer wwAdvisor; - }; const QString SelectionServiceMITKWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.extendedperspective"; SelectionServiceMitk::SelectionServiceMitk() { } SelectionServiceMitk::~SelectionServiceMitk() { } int SelectionServiceMitk::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); wbAdvisor.reset(new SelectionServiceMITKWorkbenchAdvisor); int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void SelectionServiceMitk::Stop() { } diff --git a/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/SelectionServiceQt.cpp b/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/SelectionServiceQt.cpp index 396f553bd4..c3db95b06d 100644 --- a/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/SelectionServiceQt.cpp +++ b/Examples/Plugins/org.mitk.example.gui.selectionserviceqt/src/internal/SelectionServiceQt.cpp @@ -1,80 +1,75 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "SelectionServiceQt.h" // berry includes #include #include #include class SelectionServiceQtWorkbenchAdvisor : public berry::QtWorkbenchAdvisor { public: static const QString DEFAULT_PERSPECTIVE_ID; berry::WorkbenchWindowAdvisor* CreateWorkbenchWindowAdvisor( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // Set an individual initial size configurer->SetInitialSize(QPoint(600,400)); // Set the window title configurer->SetTitle("Qt Selection Service"); - wwAdvisor.reset(new berry::WorkbenchWindowAdvisor(configurer)); - return wwAdvisor.data(); + return new berry::WorkbenchWindowAdvisor(configurer); } QString GetInitialWindowPerspectiveId() { return DEFAULT_PERSPECTIVE_ID; } -private: - - QScopedPointer wwAdvisor; - }; const QString SelectionServiceQtWorkbenchAdvisor::DEFAULT_PERSPECTIVE_ID = "org.mitk.example.extendedperspective"; SelectionServiceQt::SelectionServiceQt() { } SelectionServiceQt::~SelectionServiceQt() { } int SelectionServiceQt::Start() { berry::Display* display = berry::PlatformUI::CreateDisplay(); wbAdvisor.reset(new SelectionServiceQtWorkbenchAdvisor); int code = berry::PlatformUI::CreateAndRunWorkbench(display, wbAdvisor.data()); // exit the application with an appropriate return code return code == berry::PlatformUI::RETURN_RESTART ? EXIT_RESTART : EXIT_OK; } void SelectionServiceQt::Stop() { } diff --git a/Modules/ContourModel/CMakeLists.txt b/Modules/ContourModel/CMakeLists.txt index fa639bee89..9866a3d387 100644 --- a/Modules/ContourModel/CMakeLists.txt +++ b/Modules/ContourModel/CMakeLists.txt @@ -1,9 +1,9 @@ MITK_CREATE_MODULE( INCLUDE_DIRS Algorithms DataManagement IO Rendering DEPENDS MitkCore MitkSceneSerializationBase MitkLegacyGL MitkOverlays PACKAGE_DEPENDS ITK|ITKReview - AUTOLOAD_WITH MitkCore + # AUTOLOAD_WITH MitkCore TODO: Create IO Submodule and autoload that one instead. WARNINGS_AS_ERRORS ) add_subdirectory(Testing) diff --git a/Modules/SurfaceInterpolation/Testing/mitkSurfaceInterpolationControllerTest.cpp b/Modules/SurfaceInterpolation/Testing/mitkSurfaceInterpolationControllerTest.cpp index 20f7865c7c..eca26013c5 100644 --- a/Modules/SurfaceInterpolation/Testing/mitkSurfaceInterpolationControllerTest.cpp +++ b/Modules/SurfaceInterpolation/Testing/mitkSurfaceInterpolationControllerTest.cpp @@ -1,764 +1,764 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 #include #include #include #include "mitkImageTimeSelector.h" #include "mitkImagePixelWriteAccessor.h" class mitkSurfaceInterpolationControllerTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkSurfaceInterpolationControllerTestSuite); MITK_TEST(TestSingleton); MITK_TEST(TestSetCurrentInterpolationSession); MITK_TEST(TestReplaceInterpolationSession); MITK_TEST(TestRemoveAllInterpolationSessions); MITK_TEST(TestRemoveInterpolationSession); MITK_TEST(TestOnSegmentationDeleted); MITK_TEST(TestSetCurrentInterpolationSession4D); MITK_TEST(TestReplaceInterpolationSession4D); MITK_TEST(TestRemoveAllInterpolationSessions4D); MITK_TEST(TestRemoveInterpolationSession4D); MITK_TEST(TestOnSegmentationDeleted4D); /// \todo Workaround for memory leak in TestAddNewContour. Bug 18096. vtkDebugLeaks::SetExitError(0); MITK_TEST(TestAddNewContour); MITK_TEST(TestRemoveContour); CPPUNIT_TEST_SUITE_END(); private: mitk::SurfaceInterpolationController::Pointer m_Controller; public: mitk::Image::Pointer createImage(unsigned int *dimensions) { mitk::Image::Pointer newImage = mitk::Image::New(); mitk::PixelType p_type = mitk::MakeScalarPixelType(); newImage->Initialize(p_type, 3, dimensions); return newImage; } mitk::Image::Pointer createImage4D(unsigned int *dimensions) { mitk::Image::Pointer newImage = mitk::Image::New(); mitk::PixelType p_type = mitk::MakeScalarPixelType(); newImage->Initialize(p_type, 4, dimensions); return newImage; } void setUp() { m_Controller = mitk::SurfaceInterpolationController::GetInstance(); m_Controller->SetCurrentTimeStep( 0 ); vtkSmartPointer polygonSource = vtkSmartPointer::New(); polygonSource->SetRadius(100); polygonSource->SetNumberOfSides(7); polygonSource->Update(); mitk::Surface::Pointer surface = mitk::Surface::New(); surface->SetVtkPolyData(polygonSource->GetOutput()); } void TestSingleton() { mitk::SurfaceInterpolationController::Pointer controller2 = mitk::SurfaceInterpolationController::GetInstance(); CPPUNIT_ASSERT_MESSAGE("SurfaceInterpolationController pointers are not equal!", m_Controller.GetPointer() == controller2.GetPointer()); } void TestSetCurrentInterpolationSession() { // Create image for testing unsigned int dimensions1[] = {10, 10, 10}; mitk::Image::Pointer segmentation_1 = createImage(dimensions1); unsigned int dimensions2[] = {20, 10, 30}; mitk::Image::Pointer segmentation_2 = createImage(dimensions2); // Test 1 m_Controller->SetCurrentInterpolationSession(segmentation_1); MITK_ASSERT_EQUAL(m_Controller->GetCurrentSegmentation(), segmentation_1->Clone(), "Segmentation images are not equal"); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().GetPointer() == segmentation_1.GetPointer()); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 1", m_Controller->GetNumberOfInterpolationSessions() == 1); // Test 2 m_Controller->SetCurrentInterpolationSession(segmentation_2); MITK_ASSERT_EQUAL(m_Controller->GetCurrentSegmentation(), segmentation_2->Clone(), "Segmentation images are not equal"); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().GetPointer() == segmentation_2.GetPointer()); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 2", m_Controller->GetNumberOfInterpolationSessions() == 2); // Test 3 m_Controller->SetCurrentInterpolationSession(segmentation_1); MITK_ASSERT_EQUAL(m_Controller->GetCurrentSegmentation(), segmentation_1->Clone(), "Segmentation images are not equal"); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().GetPointer() == segmentation_1.GetPointer()); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 2", m_Controller->GetNumberOfInterpolationSessions() == 2); // Test 4 m_Controller->SetCurrentInterpolationSession(segmentation_1); MITK_ASSERT_EQUAL(m_Controller->GetCurrentSegmentation(), segmentation_1->Clone(), "Segmentation images are not equal"); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().GetPointer() == segmentation_1.GetPointer()); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 2", m_Controller->GetNumberOfInterpolationSessions() == 2); // Test 5 m_Controller->SetCurrentInterpolationSession(0); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().IsNull()); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 2", m_Controller->GetNumberOfInterpolationSessions() == 2); } void TestReplaceInterpolationSession() { // Create segmentation image unsigned int dimensions1[] = {10, 10, 10}; mitk::Image::Pointer segmentation_1 = createImage(dimensions1); m_Controller->SetCurrentInterpolationSession(segmentation_1); // Create some contours double center_1[3] = {1.25f ,3.43f ,4.44f}; double normal_1[3] = {0.25f ,1.76f, 0.93f}; vtkSmartPointer p_source = vtkSmartPointer::New(); p_source->SetNumberOfSides(20); p_source->SetCenter(center_1); p_source->SetRadius(4); p_source->SetNormal(normal_1); p_source->Update(); vtkPolyData* poly_1 = p_source->GetOutput(); mitk::Surface::Pointer surf_1 = mitk::Surface::New(); surf_1->SetVtkPolyData(poly_1); double center_2[3] = {4.0f ,4.0f ,4.0f}; double normal_2[3] = {1.0f ,0.0f, 0.0f}; vtkSmartPointer p_source_2 = vtkSmartPointer::New(); p_source_2->SetNumberOfSides(80); p_source_2->SetCenter(center_2); p_source_2->SetRadius(4); p_source_2->SetNormal(normal_2); p_source_2->Update(); vtkPolyData* poly_2 = p_source_2->GetOutput(); mitk::Surface::Pointer surf_2 = mitk::Surface::New(); surf_2->SetVtkPolyData(poly_2); // Add contours m_Controller->AddNewContour(surf_1); m_Controller->AddNewContour(surf_2); // Check if all contours are there mitk::SurfaceInterpolationController::ContourPositionInformation contourInfo1; contourInfo1.contourNormal = normal_1; contourInfo1.contourPoint = center_1; mitk::SurfaceInterpolationController::ContourPositionInformation contourInfo2; contourInfo2.contourNormal = normal_2; contourInfo2.contourPoint = center_2; mitk::Image::Pointer segmentation_2 = createImage(dimensions1); bool success = m_Controller->ReplaceInterpolationSession(segmentation_1, segmentation_2); const mitk::Surface* contour_1 = m_Controller->GetContour(contourInfo1); const mitk::Surface* contour_2 = m_Controller->GetContour(contourInfo2); CPPUNIT_ASSERT_MESSAGE("Replace session failed!", success == true); CPPUNIT_ASSERT_MESSAGE("Wrong number of contours!", m_Controller->GetNumberOfContours() == 2); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_1->GetVtkPolyData()), *(contour_1->GetVtkPolyData()), 0.000001, true)); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_2->GetVtkPolyData()), *(contour_2->GetVtkPolyData()), 0.000001, true)); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 1", m_Controller->GetNumberOfInterpolationSessions() == 1); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().GetPointer() == segmentation_2.GetPointer()); unsigned int dimensions2[] = {10, 20, 10}; mitk::Image::Pointer segmentation_3 = createImage(dimensions2); success = m_Controller->ReplaceInterpolationSession(segmentation_2, segmentation_3); CPPUNIT_ASSERT_MESSAGE("Replace session failed!", success == false); CPPUNIT_ASSERT_MESSAGE("Wrong number of contours!", m_Controller->GetNumberOfContours() == 2); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 1", m_Controller->GetNumberOfInterpolationSessions() == 1); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().GetPointer() == segmentation_2.GetPointer()); } void TestRemoveAllInterpolationSessions() { // Create image for testing unsigned int dimensions1[] = {10, 10, 10}; mitk::Image::Pointer segmentation_1 = createImage(dimensions1); unsigned int dimensions2[] = {20, 10, 30}; mitk::Image::Pointer segmentation_2 = createImage(dimensions2); // Test 1 m_Controller->SetCurrentInterpolationSession(segmentation_1); m_Controller->SetCurrentInterpolationSession(segmentation_2); m_Controller->RemoveAllInterpolationSessions(); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 0", m_Controller->GetNumberOfInterpolationSessions() == 0); } void TestRemoveInterpolationSession() { // Create image for testing unsigned int dimensions1[] = {10, 10, 10}; mitk::Image::Pointer segmentation_1 = createImage(dimensions1); unsigned int dimensions2[] = {20, 10, 30}; mitk::Image::Pointer segmentation_2 = createImage(dimensions2); // Test 1 m_Controller->SetCurrentInterpolationSession(segmentation_1); m_Controller->SetCurrentInterpolationSession(segmentation_2); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 2", m_Controller->GetNumberOfInterpolationSessions() == 2); // Test current segmentation should not be null if another one was removed m_Controller->RemoveInterpolationSession(segmentation_1); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 1", m_Controller->GetNumberOfInterpolationSessions() == 1); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().GetPointer() == segmentation_2.GetPointer()); CPPUNIT_ASSERT_MESSAGE("Current segmentation is null after another one was removed", m_Controller->GetCurrentSegmentation().IsNotNull()); m_Controller->SetCurrentInterpolationSession(segmentation_1); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 2", m_Controller->GetNumberOfInterpolationSessions() == 2); // Test current segmentation should not be null if another one was removed m_Controller->RemoveInterpolationSession(segmentation_1); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 1", m_Controller->GetNumberOfInterpolationSessions() == 1); CPPUNIT_ASSERT_MESSAGE("Current segmentation is not null after session was removed", m_Controller->GetCurrentSegmentation().IsNull()); } void TestOnSegmentationDeleted() { { // Create image for testing unsigned int dimensions1[] = {10, 10, 10}; mitk::Image::Pointer segmentation_1 = createImage(dimensions1); m_Controller->SetCurrentInterpolationSession(segmentation_1); } CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 0", m_Controller->GetNumberOfInterpolationSessions() == 0); } void TestAddNewContour() { // Create segmentation image unsigned int dimensions1[] = {10, 10, 10}; mitk::Image::Pointer segmentation_1 = createImage(dimensions1); m_Controller->SetCurrentInterpolationSession(segmentation_1); // Create some contours double center_1[3] = {1.25f ,3.43f ,4.44f}; double normal_1[3] = {0.25f ,1.76f, 0.93f}; vtkSmartPointer p_source = vtkSmartPointer::New(); p_source->SetNumberOfSides(20); p_source->SetCenter(center_1); p_source->SetRadius(4); p_source->SetNormal(normal_1); p_source->Update(); vtkPolyData* poly_1 = p_source->GetOutput(); mitk::Surface::Pointer surf_1 = mitk::Surface::New(); surf_1->SetVtkPolyData(poly_1); double center_2[3] = {4.0f ,4.0f ,4.0f}; double normal_2[3] = {1.0f ,0.0f, 0.0f}; vtkSmartPointer p_source_2 = vtkSmartPointer::New(); p_source_2->SetNumberOfSides(80); p_source_2->SetCenter(center_2); p_source_2->SetRadius(4); p_source_2->SetNormal(normal_2); p_source_2->Update(); vtkPolyData* poly_2 = p_source_2->GetOutput(); mitk::Surface::Pointer surf_2 = mitk::Surface::New(); surf_2->SetVtkPolyData(poly_2); double center_3[3] = {4.0f ,4.0f ,3.0f}; double normal_3[3] = {0.0f ,0.0f, 1.0f}; vtkSmartPointer p_source_3 = vtkSmartPointer::New(); p_source_3->SetNumberOfSides(10); p_source_3->SetCenter(center_3); p_source_3->SetRadius(4); p_source_3->SetNormal(normal_3); p_source_3->Update(); vtkPolyData* poly_3 = p_source_3->GetOutput(); mitk::Surface::Pointer surf_3 = mitk::Surface::New(); surf_3->SetVtkPolyData(poly_3); // Add contours m_Controller->AddNewContour(surf_1); m_Controller->AddNewContour(surf_2); m_Controller->AddNewContour(surf_3); // Check if all contours are there mitk::SurfaceInterpolationController::ContourPositionInformation contourInfo1; contourInfo1.contourNormal = normal_1; contourInfo1.contourPoint = center_1; mitk::SurfaceInterpolationController::ContourPositionInformation contourInfo2; contourInfo2.contourNormal = normal_2; contourInfo2.contourPoint = center_2; mitk::SurfaceInterpolationController::ContourPositionInformation contourInfo3; contourInfo3.contourNormal = normal_3; contourInfo3.contourPoint = center_3; const mitk::Surface* contour_1 = m_Controller->GetContour(contourInfo1); const mitk::Surface* contour_2 = m_Controller->GetContour(contourInfo2); const mitk::Surface* contour_3 = m_Controller->GetContour(contourInfo3); CPPUNIT_ASSERT_MESSAGE("Wrong number of contours!", m_Controller->GetNumberOfContours() == 3); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_1->GetVtkPolyData()), *(contour_1->GetVtkPolyData()), 0.000001, true)); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_2->GetVtkPolyData()), *(contour_2->GetVtkPolyData()), 0.000001, true)); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_3->GetVtkPolyData()), *(contour_3->GetVtkPolyData()), 0.000001, true)); // Create another segmentation image unsigned int dimensions2[] = {20, 20, 20}; mitk::Image::Pointer segmentation_2 = createImage(dimensions2); m_Controller->SetCurrentInterpolationSession(segmentation_2); // Create some contours double center_4[3] = {10.0f ,10.0f ,10.0f}; double normal_4[3] = {0.0f ,1.0f, 0.0f}; vtkSmartPointer p_source_4 = vtkSmartPointer::New(); p_source_4->SetNumberOfSides(8); p_source_4->SetCenter(center_4); p_source_4->SetRadius(5); p_source_4->SetNormal(normal_4); p_source_4->Update(); vtkPolyData* poly_4 = p_source_4->GetOutput(); mitk::Surface::Pointer surf_4 = mitk::Surface::New(); surf_4->SetVtkPolyData(poly_4); double center_5[3] = {3.0f ,10.0f ,10.0f}; double normal_5[3] = {1.0f ,0.0f, 0.0f}; vtkSmartPointer p_source_5 = vtkSmartPointer::New(); p_source_5->SetNumberOfSides(16); p_source_5->SetCenter(center_5); p_source_5->SetRadius(8); p_source_5->SetNormal(normal_5); p_source_5->Update(); vtkPolyData* poly_5 = p_source_5->GetOutput(); mitk::Surface::Pointer surf_5 = mitk::Surface::New(); surf_5->SetVtkPolyData(poly_5); double center_6[3] = {10.0f ,10.0f ,3.0f}; double normal_6[3] = {0.0f ,0.0f, 1.0f}; vtkSmartPointer p_source_6 = vtkSmartPointer::New(); p_source_6->SetNumberOfSides(100); p_source_6->SetCenter(center_6); p_source_6->SetRadius(5); p_source_6->SetNormal(normal_6); p_source_6->Update(); vtkPolyData* poly_6 = p_source_6->GetOutput(); mitk::Surface::Pointer surf_6 = mitk::Surface::New(); surf_6->SetVtkPolyData(poly_6); mitk::SurfaceInterpolationController::ContourPositionInformation contourInfo4; contourInfo4.contourNormal = normal_4; contourInfo4.contourPoint = center_4; mitk::SurfaceInterpolationController::ContourPositionInformation contourInfo5; contourInfo5.contourNormal = normal_5; contourInfo5.contourPoint = center_5; mitk::SurfaceInterpolationController::ContourPositionInformation contourInfo6; contourInfo6.contourNormal = normal_6; contourInfo6.contourPoint = center_6; // Add contours m_Controller->AddNewContour(surf_4); m_Controller->AddNewContour(surf_5); m_Controller->AddNewContour(surf_6); // Check if all contours are there mitk::Surface* contour_4 = const_cast(m_Controller->GetContour(contourInfo4)); mitk::Surface* contour_5 = const_cast(m_Controller->GetContour(contourInfo5)); mitk::Surface* contour_6 = const_cast(m_Controller->GetContour(contourInfo6)); CPPUNIT_ASSERT_MESSAGE("Wrong number of contours!", m_Controller->GetNumberOfContours() == 3); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_4->GetVtkPolyData()), *(contour_4->GetVtkPolyData()), 0.000001, true)); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_5->GetVtkPolyData()), *(contour_5->GetVtkPolyData()), 0.000001, true)); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_6->GetVtkPolyData()), *(contour_6->GetVtkPolyData()), 0.000001, true)); // Modify some contours vtkSmartPointer p_source_7 = vtkSmartPointer::New(); p_source_7->SetNumberOfSides(200); p_source_7->SetCenter(3.0,10.0,10.0); p_source_7->SetRadius(5); p_source_7->SetNormal(1, 0, 0); p_source_7->Update(); vtkPolyData* poly_7 = p_source_7->GetOutput(); mitk::Surface::Pointer surf_7 = mitk::Surface::New(); surf_7->SetVtkPolyData(poly_7); m_Controller->AddNewContour(surf_7); mitk::Surface* contour_7 = const_cast(m_Controller->GetContour(contourInfo5)); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_7->GetVtkPolyData()), *(contour_7->GetVtkPolyData()), 0.000001, true)); // Change session and test if all contours are available m_Controller->SetCurrentInterpolationSession(segmentation_1); mitk::Surface* contour_8 = const_cast(m_Controller->GetContour(contourInfo1)); mitk::Surface* contour_9 = const_cast(m_Controller->GetContour(contourInfo2)); mitk::Surface* contour_10 = const_cast(m_Controller->GetContour(contourInfo3)); CPPUNIT_ASSERT_MESSAGE("Wrong number of contours!", m_Controller->GetNumberOfContours() == 3); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_1->GetVtkPolyData()), *(contour_8->GetVtkPolyData()), 0.000001, true)); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_2->GetVtkPolyData()), *(contour_9->GetVtkPolyData()), 0.000001, true)); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_3->GetVtkPolyData()), *(contour_10->GetVtkPolyData()), 0.000001, true)); } void TestRemoveContour() { // Create segmentation image unsigned int dimensions1[] = {10, 10, 10}; mitk::Image::Pointer segmentation_1 = createImage(dimensions1); m_Controller->SetCurrentInterpolationSession(segmentation_1); // Create some contours double center_1[3] = {4.0f ,4.0f ,4.0f}; double normal_1[3] = {0.0f ,1.0f, 0.0f}; vtkSmartPointer p_source = vtkSmartPointer::New(); p_source->SetNumberOfSides(20); p_source->SetCenter(center_1); p_source->SetRadius(4); p_source->SetNormal(normal_1); p_source->Update(); vtkPolyData* poly_1 = p_source->GetOutput(); mitk::Surface::Pointer surf_1 = mitk::Surface::New(); surf_1->SetVtkPolyData(poly_1); double center_2[3] = {4.0f ,4.0f ,4.0f}; double normal_2[3] = {1.0f ,0.0f, 0.0f}; vtkSmartPointer p_source_2 = vtkSmartPointer::New(); p_source_2->SetNumberOfSides(80); p_source_2->SetCenter(center_2); p_source_2->SetRadius(4); p_source_2->SetNormal(normal_2); p_source_2->Update(); vtkPolyData* poly_2 = p_source_2->GetOutput(); mitk::Surface::Pointer surf_2 = mitk::Surface::New(); surf_2->SetVtkPolyData(poly_2); // Add contours m_Controller->AddNewContour(surf_1); m_Controller->AddNewContour(surf_2); CPPUNIT_ASSERT_MESSAGE("Wrong number of contours!", m_Controller->GetNumberOfContours() == 2); mitk::SurfaceInterpolationController::ContourPositionInformation contourInfo3; contourInfo3.contour = surf_1->Clone(); contourInfo3.contourNormal = normal_1; contourInfo3.contourPoint = center_1; // Shift the new contour so that it is different contourInfo3.contourPoint += 0.5; bool success = m_Controller->RemoveContour(contourInfo3); CPPUNIT_ASSERT_MESSAGE("Remove failed - contour was unintentionally removed!", (m_Controller->GetNumberOfContours() == 2) && !success); mitk::SurfaceInterpolationController::ContourPositionInformation contourInfo2; contourInfo2.contourNormal = normal_2; contourInfo2.contourPoint = center_2; contourInfo2.contour = surf_2; success = m_Controller->RemoveContour(contourInfo2); CPPUNIT_ASSERT_MESSAGE("Remove failed - contour was not removed!", (m_Controller->GetNumberOfContours() == 1) && success); // Let's see if the other contour No. 1 is still there contourInfo3.contourPoint -= 0.5; const mitk::Surface* remainingContour = m_Controller->GetContour(contourInfo3); CPPUNIT_ASSERT_MESSAGE("Remove failed - contour was accidentally removed!", (m_Controller->GetNumberOfContours() == 1) && mitk::Equal(*(surf_1->GetVtkPolyData()), *(remainingContour->GetVtkPolyData()), 0.000001, true) &&success); } bool AssertImagesEqual4D( mitk::Image* img1, mitk::Image* img2 ) { mitk::ImageTimeSelector::Pointer selector1 = mitk::ImageTimeSelector::New(); selector1->SetInput( img1 ); selector1->SetChannelNr( 0 ); mitk::ImageTimeSelector::Pointer selector2= mitk::ImageTimeSelector::New(); selector2->SetInput( img2 ); selector2->SetChannelNr( 0 ); int numTs1 = img1->GetTimeSteps(); int numTs2 = img2->GetTimeSteps(); if ( numTs1 != numTs2 ) { return false; } /*mitk::ImagePixelWriteAccessor accessor( img1 ); itk::Index<4> ind; ind[0] = 5; ind[1] = 5; ind[2] = 5; ind[3] = 2; accessor.SetPixelByIndex( ind, 7 );*/ for ( int ts = 0; ts < numTs1; ++ts ) { selector1->SetTimeNr( ts ); selector2->SetTimeNr( ts ); selector1->Update(); selector2->Update(); mitk::Image::Pointer imgSel1 = selector1->GetOutput(); mitk::Image::Pointer imgSel2 = selector2->GetOutput(); MITK_ASSERT_EQUAL(imgSel1, imgSel2, "Segmentation images are not equal"); } return true; } void TestSetCurrentInterpolationSession4D() { /*unsigned int testDimensions[] = {10, 10, 10, 5}; mitk::Image::Pointer testSeg = createImage4D(testDimensions); mitk::Image::Pointer testSegClone = testSeg->Clone(); int testTs = testSeg->GetTimeSteps(); MITK_ASSERT_EQUAL(testSeg, testSegClone, "Segmentation images are not equal");*/ // Create image for testing unsigned int dimensions1[] = {10, 10, 10, 5}; mitk::Image::Pointer segmentation_1 = createImage4D(dimensions1); unsigned int dimensions2[] = {20, 10, 30, 4}; mitk::Image::Pointer segmentation_2 = createImage4D(dimensions2); // Test 1 m_Controller->SetCurrentInterpolationSession(segmentation_1); - bool equal = AssertImagesEqual4D( m_Controller->GetCurrentSegmentation(), segmentation_1->Clone() ); + AssertImagesEqual4D( m_Controller->GetCurrentSegmentation(), segmentation_1->Clone() ); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().GetPointer() == segmentation_1.GetPointer()); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 1", m_Controller->GetNumberOfInterpolationSessions() == 1); // Test 2 m_Controller->SetCurrentInterpolationSession(segmentation_2); //MITK_ASSERT_EQUAL(m_Controller->GetCurrentSegmentation(), segmentation_2->Clone(), "Segmentation images are not equal"); - equal = AssertImagesEqual4D( m_Controller->GetCurrentSegmentation(), segmentation_2->Clone() ); + AssertImagesEqual4D( m_Controller->GetCurrentSegmentation(), segmentation_2->Clone() ); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().GetPointer() == segmentation_2.GetPointer()); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 2", m_Controller->GetNumberOfInterpolationSessions() == 2); // Test 3 m_Controller->SetCurrentInterpolationSession(segmentation_1); //MITK_ASSERT_EQUAL(m_Controller->GetCurrentSegmentation(), segmentation_1->Clone(), "Segmentation images are not equal"); - equal = AssertImagesEqual4D( m_Controller->GetCurrentSegmentation(), segmentation_1->Clone() ); + AssertImagesEqual4D( m_Controller->GetCurrentSegmentation(), segmentation_1->Clone() ); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().GetPointer() == segmentation_1.GetPointer()); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 2", m_Controller->GetNumberOfInterpolationSessions() == 2); // Test 4 m_Controller->SetCurrentInterpolationSession(segmentation_1); //MITK_ASSERT_EQUAL(m_Controller->GetCurrentSegmentation(), segmentation_1->Clone(), "Segmentation images are not equal"); - equal = AssertImagesEqual4D( m_Controller->GetCurrentSegmentation(), segmentation_1->Clone() ); + AssertImagesEqual4D( m_Controller->GetCurrentSegmentation(), segmentation_1->Clone() ); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().GetPointer() == segmentation_1.GetPointer()); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 2", m_Controller->GetNumberOfInterpolationSessions() == 2); // Test 5 m_Controller->SetCurrentInterpolationSession(0); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().IsNull()); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 2", m_Controller->GetNumberOfInterpolationSessions() == 2); } void TestReplaceInterpolationSession4D() { // Create segmentation image unsigned int dimensions1[] = {10, 10, 10, 5}; mitk::Image::Pointer segmentation_1 = createImage4D(dimensions1); m_Controller->SetCurrentInterpolationSession(segmentation_1); // Create some contours double center_1[3] = {1.25f ,3.43f ,4.44f}; double normal_1[3] = {0.25f ,1.76f, 0.93f}; vtkSmartPointer p_source = vtkSmartPointer::New(); p_source->SetNumberOfSides(20); p_source->SetCenter(center_1); p_source->SetRadius(4); p_source->SetNormal(normal_1); p_source->Update(); vtkPolyData* poly_1 = p_source->GetOutput(); mitk::Surface::Pointer surf_1 = mitk::Surface::New(); surf_1->SetVtkPolyData(poly_1); double center_2[3] = {4.0f ,4.0f ,4.0f}; double normal_2[3] = {1.0f ,0.0f, 0.0f}; vtkSmartPointer p_source_2 = vtkSmartPointer::New(); p_source_2->SetNumberOfSides(80); p_source_2->SetCenter(center_2); p_source_2->SetRadius(4); p_source_2->SetNormal(normal_2); p_source_2->Update(); vtkPolyData* poly_2 = p_source_2->GetOutput(); mitk::Surface::Pointer surf_2 = mitk::Surface::New(); surf_2->SetVtkPolyData(poly_2); // Add contours m_Controller->AddNewContour(surf_1); m_Controller->AddNewContour(surf_2); // Add contours for another timestep m_Controller->SetCurrentTimeStep( 2 ); double center_3[3] = {1.3f ,3.5f ,4.6f}; double normal_3[3] = {0.20f ,1.6f, 0.8f}; vtkSmartPointer p_source_3 = vtkSmartPointer::New(); p_source_3->SetNumberOfSides(20); p_source_3->SetCenter(center_3); p_source_3->SetRadius(4); p_source_3->SetNormal(normal_3); p_source_3->Update(); vtkPolyData* poly_3 = p_source_3->GetOutput(); mitk::Surface::Pointer surf_3 = mitk::Surface::New(); surf_3->SetVtkPolyData(poly_3); double center_4[3] = {1.32f ,3.53f ,4.8f}; double normal_4[3] = {0.22f ,1.5f, 0.85f}; vtkSmartPointer p_source_4 = vtkSmartPointer::New(); p_source_4->SetNumberOfSides(20); p_source_4->SetCenter(center_4); p_source_4->SetRadius(4); p_source_4->SetNormal(normal_4); p_source_4->Update(); vtkPolyData* poly_4 = p_source_4->GetOutput(); mitk::Surface::Pointer surf_4 = mitk::Surface::New(); surf_4->SetVtkPolyData(poly_4); m_Controller->AddNewContour(surf_3); m_Controller->AddNewContour(surf_4); m_Controller->SetCurrentTimeStep( 0 ); // Check if all contours are there mitk::SurfaceInterpolationController::ContourPositionInformation contourInfo1; contourInfo1.contourNormal = normal_1; contourInfo1.contourPoint = center_1; mitk::SurfaceInterpolationController::ContourPositionInformation contourInfo2; contourInfo2.contourNormal = normal_2; contourInfo2.contourPoint = center_2; mitk::SurfaceInterpolationController::ContourPositionInformation contourInfo3; contourInfo3.contourNormal = normal_3; contourInfo3.contourPoint = center_3; mitk::SurfaceInterpolationController::ContourPositionInformation contourInfo4; contourInfo4.contourNormal = normal_4; contourInfo4.contourPoint = center_4; mitk::Image::Pointer segmentation_2 = createImage4D(dimensions1); bool success = m_Controller->ReplaceInterpolationSession(segmentation_1, segmentation_2); CPPUNIT_ASSERT_MESSAGE("Replace session failed!", success == true); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 1", m_Controller->GetNumberOfInterpolationSessions() == 1); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().GetPointer() == segmentation_2.GetPointer()); const mitk::Surface* contour_1 = m_Controller->GetContour(contourInfo1); const mitk::Surface* contour_2 = m_Controller->GetContour(contourInfo2); CPPUNIT_ASSERT_MESSAGE("Wrong number of contours!", m_Controller->GetNumberOfContours() == 2); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_1->GetVtkPolyData()), *(contour_1->GetVtkPolyData()), 0.000001, true)); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_2->GetVtkPolyData()), *(contour_2->GetVtkPolyData()), 0.000001, true)); m_Controller->SetCurrentTimeStep( 2 ); //CPPUNIT_ASSERT_MESSAGE("Contour accessed from outside of timestep!", m_Controller->GetNumberOfContours() == 0); contour_1 = m_Controller->GetContour(contourInfo1); contour_2 = m_Controller->GetContour(contourInfo2); CPPUNIT_ASSERT_MESSAGE("Contour accessed from outside of timestep!", contour_1 == 0 && contour_2 == 0); const mitk::Surface* contour_3 = m_Controller->GetContour(contourInfo3); const mitk::Surface* contour_4 = m_Controller->GetContour(contourInfo4); CPPUNIT_ASSERT_MESSAGE("Wrong number of contours!", m_Controller->GetNumberOfContours() == 2); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_3->GetVtkPolyData()), *(contour_3->GetVtkPolyData()), 0.000001, true)); CPPUNIT_ASSERT_MESSAGE("Contours not equal!", mitk::Equal(*(surf_4->GetVtkPolyData()), *(contour_4->GetVtkPolyData()), 0.000001, true)); unsigned int dimensions2[] = {10, 20, 10, 4}; mitk::Image::Pointer segmentation_3 = createImage4D(dimensions2); success = m_Controller->ReplaceInterpolationSession(segmentation_2, segmentation_3); CPPUNIT_ASSERT_MESSAGE("Replace session failed!", success == false); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 1", m_Controller->GetNumberOfInterpolationSessions() == 1); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().GetPointer() == segmentation_2.GetPointer()); m_Controller->SetCurrentTimeStep( 1 ); CPPUNIT_ASSERT_MESSAGE("Wrong number of contours!", m_Controller->GetNumberOfContours() == 0); m_Controller->SetCurrentTimeStep( 0 ); CPPUNIT_ASSERT_MESSAGE("Wrong number of contours!", m_Controller->GetNumberOfContours() == 2); m_Controller->SetCurrentTimeStep( 4 ); CPPUNIT_ASSERT_MESSAGE("Wrong number of contours!", m_Controller->GetNumberOfContours() == 0); m_Controller->SetCurrentTimeStep( 2 ); CPPUNIT_ASSERT_MESSAGE("Wrong number of contours!", m_Controller->GetNumberOfContours() == 2); } void TestRemoveAllInterpolationSessions4D() { // Create image for testing unsigned int dimensions1[] = {10, 10, 10, 4}; mitk::Image::Pointer segmentation_1 = createImage4D(dimensions1); unsigned int dimensions2[] = {20, 10, 30, 5}; mitk::Image::Pointer segmentation_2 = createImage4D(dimensions2); // Test 1 m_Controller->SetCurrentInterpolationSession(segmentation_1); m_Controller->SetCurrentInterpolationSession(segmentation_2); m_Controller->RemoveAllInterpolationSessions(); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 0", m_Controller->GetNumberOfInterpolationSessions() == 0); } void TestRemoveInterpolationSession4D() { // Create image for testing unsigned int dimensions1[] = {10, 10, 10, 3}; mitk::Image::Pointer segmentation_1 = createImage4D(dimensions1); unsigned int dimensions2[] = {20, 10, 30, 6}; mitk::Image::Pointer segmentation_2 = createImage4D(dimensions2); // Test 1 m_Controller->SetCurrentInterpolationSession(segmentation_1); m_Controller->SetCurrentInterpolationSession(segmentation_2); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 2", m_Controller->GetNumberOfInterpolationSessions() == 2); // Test current segmentation should not be null if another one was removed m_Controller->RemoveInterpolationSession(segmentation_1); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 1", m_Controller->GetNumberOfInterpolationSessions() == 1); CPPUNIT_ASSERT_MESSAGE("Segmentation images are not equal", m_Controller->GetCurrentSegmentation().GetPointer() == segmentation_2.GetPointer()); CPPUNIT_ASSERT_MESSAGE("Current segmentation is null after another one was removed", m_Controller->GetCurrentSegmentation().IsNotNull()); m_Controller->SetCurrentInterpolationSession(segmentation_1); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 2", m_Controller->GetNumberOfInterpolationSessions() == 2); // Test current segmentation should not be null if another one was removed m_Controller->RemoveInterpolationSession(segmentation_1); CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 1", m_Controller->GetNumberOfInterpolationSessions() == 1); CPPUNIT_ASSERT_MESSAGE("Current segmentation is not null after session was removed", m_Controller->GetCurrentSegmentation().IsNull()); } void TestOnSegmentationDeleted4D() { { // Create image for testing unsigned int dimensions1[] = {10, 10, 10, 7}; mitk::Image::Pointer segmentation_1 = createImage4D(dimensions1); m_Controller->SetCurrentInterpolationSession(segmentation_1); m_Controller->SetCurrentTimeStep( 3 ); } CPPUNIT_ASSERT_MESSAGE("Number of interpolation session not 0", m_Controller->GetNumberOfInterpolationSessions() == 0); } }; MITK_TEST_SUITE_REGISTRATION(mitkSurfaceInterpolationController) diff --git a/Plugins/org.mitk.gui.common/files.cmake b/Plugins/org.mitk.gui.common/files.cmake index 44a5d0d931..ced5665193 100644 --- a/Plugins/org.mitk.gui.common/files.cmake +++ b/Plugins/org.mitk.gui.common/files.cmake @@ -1,35 +1,36 @@ set(MOC_H_FILES src/internal/org_mitk_gui_common_Activator.h ) set(SRC_CPP_FILES mitkDataNodeObject.cpp mitkDataNodeSelection.cpp mitkDataStorageEditorInput.cpp mitkILifecycleAwarePart.h mitkILifecycleAwarePart.cpp mitkILinkedRenderWindowPart.h mitkILinkedRenderWindowPart.cpp mitkIRenderingManager.cpp mitkIRenderWindowPart.cpp mitkIRenderWindowPartListener.h mitkIRenderWindowPartListener.cpp mitkIZombieViewPart.h mitkIZombieViewPart.cpp + mitkWorkbenchCommandConstants.cpp mitkWorkbenchUtil.cpp ) set(INTERNAL_CPP_FILES org_mitk_gui_common_Activator.cpp ) #set(CPP_FILES manifest.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/Plugins/org.mitk.gui.common/src/internal/mitkDataStorageEditorInputFactory.cpp b/Plugins/org.mitk.gui.common/src/internal/mitkDataStorageEditorInputFactory.cpp new file mode 100644 index 0000000000..7fd446a933 --- /dev/null +++ b/Plugins/org.mitk.gui.common/src/internal/mitkDataStorageEditorInputFactory.cpp @@ -0,0 +1,58 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY 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 "mitkDataStorageEditorInputFactory.h" + +#include + +#include + +namespace mitk { + +static QString TAG_PATH = "path"; +static QString TAG_LABEL = "label"; +static QString ID_FACTORY = "org.mitk.ui.DataStorageEditorInputFactory"; + +berry::IAdaptable* DataStorageEditorInputFactory::CreateElement(const berry::IMemento::Pointer& memento) +{ + memento-> +} + +QString DataStorageEditorInputFactory::GetFactoryId() +{ + return ID_FACTORY; +} + +void DataStorageEditorInputFactory::SaveState(const berry::IMemento::Pointer& memento, const DataStorageEditorInput* input) +{ + IDataStorageReference::Pointer dataStorageRef = input->GetDataStorageReference(); + if (dataStorageRef) + { + QString label = dataStorageRef->GetLabel(); + DataStorage::Pointer dataStorage = dataStorageRef->GetDataStorage(); + if (dataStorage) + { + memento->PutString(TAG_LABEL, label); + auto nodes = dataStorage->GetAll(); + for(auto nodeIter = nodes.begin(); nodeIter != nodes.end(); ++nodeIter) + { + //(*nodeIter)->GetP + } + } + } +} + +} diff --git a/Plugins/org.mitk.gui.common/src/internal/mitkDataStorageEditorInputFactory.h b/Plugins/org.mitk.gui.common/src/internal/mitkDataStorageEditorInputFactory.h new file mode 100644 index 0000000000..025e819251 --- /dev/null +++ b/Plugins/org.mitk.gui.common/src/internal/mitkDataStorageEditorInputFactory.h @@ -0,0 +1,42 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#ifndef MITKDATASTORAGEEDITORINPUTFACTORY_H +#define MITKDATASTORAGEEDITORINPUTFACTORY_H + +#include + +namespace mitk { + +class DataStorageEditorInput; + +class DataStorageEditorInputFactory : public QObject, public berry::IElementFactory +{ + Q_OBJECT + Q_INTERFACES(berry::IElementFactory) + +public: + + berry::IAdaptable* CreateElement(const berry::IMemento::Pointer& memento); + + static QString GetFactoryId(); + + static void SaveState(const berry::IMemento::Pointer& memento, const DataStorageEditorInput* input); +}; + +} + +#endif // MITKDATASTORAGEEDITORINPUTFACTORY_H diff --git a/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.cpp b/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.cpp index 8dbb625c13..a47e5a14b0 100644 --- a/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.cpp +++ b/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.cpp @@ -1,75 +1,112 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkDataStorageEditorInput.h" #include +#include +#include + #include #include "internal/org_mitk_gui_common_Activator.h" +#include "internal/mitkDataStorageEditorInputFactory.h" + +#include namespace mitk { DataStorageEditorInput::DataStorageEditorInput() { } DataStorageEditorInput::DataStorageEditorInput(IDataStorageReference::Pointer ref) { m_DataStorageRef = ref; } bool DataStorageEditorInput::Exists() const { return true; } QString DataStorageEditorInput::GetName() const { return "DataStorage Scene"; } QString DataStorageEditorInput::GetToolTipText() const { return ""; } +QIcon DataStorageEditorInput::GetIcon() const +{ + return QIcon(); +} + +const berry::IPersistableElement*DataStorageEditorInput::GetPersistable() const +{ + //return this; + return nullptr; +} + +berry::Object* DataStorageEditorInput::GetAdapter(const QString& adapterType) const +{ + berry::IAdapterManager* adapterManager = berry::Platform::GetAdapterManager(); + if (adapterManager) + { + return adapterManager->GetAdapter(this, adapterType); + } + return nullptr; +} + +//QString DataStorageEditorInput::GetFactoryId() const +//{ +// return DataStorageEditorInputFactory::GetFactoryId(); +//} + +//void DataStorageEditorInput::SaveState(const berry::IMemento::Pointer& memento) const +//{ +// return DataStorageEditorInputFactory::SaveState(memento, this); +//} + bool DataStorageEditorInput::operator==(const berry::Object* o) const { if (const DataStorageEditorInput* input = dynamic_cast(o)) return this->m_DataStorageRef == input->m_DataStorageRef; return false; } IDataStorageReference::Pointer DataStorageEditorInput::GetDataStorageReference() { if (m_DataStorageRef.IsNull()) { ctkPluginContext* context = PluginActivator::GetContext(); ctkServiceReference serviceRef = context->getServiceReference(); if (!serviceRef) return IDataStorageReference::Pointer(0); IDataStorageService* dataService = context->getService(serviceRef); if (!dataService) return IDataStorageReference::Pointer(0); m_DataStorageRef = dataService->GetDefaultDataStorage(); } return m_DataStorageRef; } } diff --git a/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.h b/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.h index 53a4a6cfb9..aee42046d8 100644 --- a/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.h +++ b/Plugins/org.mitk.gui.common/src/mitkDataStorageEditorInput.h @@ -1,59 +1,68 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKDATASTORAGEEDITORINPUT_H_ #define MITKDATASTORAGEEDITORINPUT_H_ #include +#include + #include #include namespace mitk { /** * \ingroup org_mitk_gui_common * * \brief An editor input based on a mitk::DataStorage. * * This editor input is usually used in render window editors inheriting from * QmitkAbstractRenderEditor. */ -class MITK_GUI_COMMON_PLUGIN DataStorageEditorInput : public berry::IEditorInput +class MITK_GUI_COMMON_PLUGIN DataStorageEditorInput : public berry::IEditorInput //, private berry::IPersistableElement { public: - berryObjectMacro(DataStorageEditorInput); + berryObjectMacro(DataStorageEditorInput) DataStorageEditorInput(); DataStorageEditorInput(IDataStorageReference::Pointer ref); bool Exists() const; QString GetName() const; QString GetToolTipText() const; + QIcon GetIcon() const; + + const berry::IPersistableElement* GetPersistable() const; + Object* GetAdapter(const QString &adapterType) const; IDataStorageReference::Pointer GetDataStorageReference(); bool operator==(const berry::Object*) const; private: + //QString GetFactoryId() const; + //void SaveState(const berry::SmartPointer& memento) const; + IDataStorageReference::Pointer m_DataStorageRef; }; } #endif /*MITKDATASTORAGEEDITORINPUT_H_*/ diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkEditorPerspective.cpp b/Plugins/org.mitk.gui.common/src/mitkWorkbenchCommandConstants.cpp similarity index 68% copy from Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkEditorPerspective.cpp copy to Plugins/org.mitk.gui.common/src/mitkWorkbenchCommandConstants.cpp index 9e68a6b335..7b8f573448 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkEditorPerspective.cpp +++ b/Plugins/org.mitk.gui.common/src/mitkWorkbenchCommandConstants.cpp @@ -1,22 +1,24 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkEditorPerspective.h" +#include "mitkWorkbenchCommandConstants.h" + +namespace mitk { + +const QString WorkbenchCommandConstants::PROJECT_CLOSE = "org.mitk.ui.project.close"; +const QString WorkbenchCommandConstants::PROJECT_SAVE = "org.mitk.ui.project.save"; -void QmitkEditorPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) -{ - layout->GetEditorArea(); } diff --git a/Plugins/org.mitk.gui.common/src/mitkWorkbenchCommandConstants.h b/Plugins/org.mitk.gui.common/src/mitkWorkbenchCommandConstants.h new file mode 100644 index 0000000000..a44d2ab239 --- /dev/null +++ b/Plugins/org.mitk.gui.common/src/mitkWorkbenchCommandConstants.h @@ -0,0 +1,49 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#ifndef MITKWORKBENCHCOMMANDCONSTANTS_H +#define MITKWORKBENCHCOMMANDCONSTANTS_H + +#include + +#include + +namespace mitk { + +class MITK_GUI_COMMON_PLUGIN WorkbenchCommandConstants : public berry::IWorkbenchCommandConstants +{ +public: + + // Project Category + + /** + * Id for command "Close Project" in category "Project" + * (value is "org.mitk.ui.project.close"). + */ + static const QString PROJECT_CLOSE; // = "org.mitk.ui.project.close"; + + /** + * Id for command "Save Project" in category "Project" + * (value is "org.mitk.ui.project.save"). + */ + static const QString PROJECT_SAVE; // = "org.mitk.ui.project.save"; + +}; + +} + + +#endif // MITKWORKBENCHCOMMANDCONSTANTS_H diff --git a/Plugins/org.mitk.gui.qt.application/files.cmake b/Plugins/org.mitk.gui.qt.application/files.cmake index 6d3966687a..f5e224e391 100644 --- a/Plugins/org.mitk.gui.qt.application/files.cmake +++ b/Plugins/org.mitk.gui.qt.application/files.cmake @@ -1,49 +1,51 @@ set(SRC_CPP_FILES QmitkCloseProjectAction.cpp QmitkDefaultDropTargetListener.cpp QmitkFileExitAction.cpp QmitkFileOpenAction.cpp QmitkFileSaveAction.cpp QmitkPreferencesDialog.cpp QmitkStatusBar.cpp ) set(INTERNAL_CPP_FILES org_mitk_gui_qt_application_Activator.cpp QmitkEditorsPreferencePage.cpp QmitkGeneralPreferencePage.cpp + QmitkShowPreferencePageHandler.cpp ) set(MOC_H_FILES src/QmitkCloseProjectAction.h src/QmitkFileExitAction.h src/QmitkFileOpenAction.h src/QmitkFileSaveAction.h src/QmitkPreferencesDialog.h src/internal/org_mitk_gui_qt_application_Activator.h src/internal/QmitkEditorsPreferencePage.h src/internal/QmitkGeneralPreferencePage.h + src/internal/QmitkShowPreferencePageHandler.h ) set(UI_FILES src/QmitkPreferencesDialog.ui ) set(CACHED_RESOURCE_FILES plugin.xml ) set(QRC_FILES resources/resources.qrc ) 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/Plugins/org.mitk.gui.qt.application/plugin.xml b/Plugins/org.mitk.gui.qt.application/plugin.xml index eb6511c500..5c19286c7d 100644 --- a/Plugins/org.mitk.gui.qt.application/plugin.xml +++ b/Plugins/org.mitk.gui.qt.application/plugin.xml @@ -1,10 +1,16 @@ - + + + + + diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.cpp index d090c81b2b..3d7a67ea28 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.cpp @@ -1,127 +1,141 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkCloseProjectAction.h" #include "internal/org_mitk_gui_qt_application_Activator.h" #include #include #include #include #include #include #include +#include #include QmitkCloseProjectAction::QmitkCloseProjectAction(berry::IWorkbenchWindow::Pointer window) -: QAction(0) + : QAction(0) + , m_Window(nullptr) { - this->init(window); + this->init(window.GetPointer()); } QmitkCloseProjectAction::QmitkCloseProjectAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) -: QAction(0) + : QAction(0) + , m_Window(nullptr) +{ + this->setIcon(icon); + this->init(window.GetPointer()); +} + +QmitkCloseProjectAction::QmitkCloseProjectAction(berry::IWorkbenchWindow* window) + : QAction(0) + , m_Window(nullptr) +{ + this->init(window); +} + +QmitkCloseProjectAction::QmitkCloseProjectAction(const QIcon& icon, berry::IWorkbenchWindow* window) + : QAction(0) + , m_Window(nullptr) { this->setIcon(icon); this->init(window); } -void QmitkCloseProjectAction::init(berry::IWorkbenchWindow::Pointer window) +void QmitkCloseProjectAction::init(berry::IWorkbenchWindow* window) { m_Window = window; - this->setParent(static_cast(m_Window->GetShell()->GetControl())); this->setText("&Close Project..."); this->setToolTip("Close Project will remove all data objects from the application. This will free up the memory that is used by the data."); - m_Window = window; this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } void QmitkCloseProjectAction::Run() { - - try { ctkPluginContext* context = mitk::PluginActivator::GetContext(); mitk::IDataStorageService* dss = 0; ctkServiceReference dsRef = context->getServiceReference(); if (dsRef) { dss = context->getService(dsRef); } if (!dss) { MITK_WARN << "IDataStorageService service not available. Unable to close project."; context->ungetService(dsRef); return; } mitk::IDataStorageReference::Pointer dataStorageRef = dss->GetActiveDataStorage(); if (dataStorageRef.IsNull()) { // No active data storage set (i.e. not editor with a DataStorageEditorInput is active). dataStorageRef = dss->GetDefaultDataStorage(); } mitk::DataStorage::Pointer dataStorage = dataStorageRef->GetDataStorage(); if (dataStorage.IsNull()) { MITK_WARN << "No data storage available. Cannot close project."; return; } //check if we got the default datastorage and if there is anything else then helper object in the storage if(dataStorageRef->IsDefault() && dataStorage->GetSubset(mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object", mitk::BoolProperty::New(true))))->empty()) { return; } /* Ask, if the user is sure about that */ QString msg = "Are you sure that you want to close the current project (%1)?\nThis will remove all data objects."; if (QMessageBox::question(NULL, "Remove all data?", msg.arg(dataStorageRef->GetLabel()), QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) { return; } /* Remove everything */ mitk::DataStorage::SetOfObjects::ConstPointer nodesToRemove = dataStorage->GetAll(); dataStorage->Remove(nodesToRemove); // Remove the datastorage from the data storage service dss->RemoveDataStorageReference(dataStorageRef); // Close all editors with this data storage as input mitk::DataStorageEditorInput::Pointer dsInput(new mitk::DataStorageEditorInput(dataStorageRef)); QList dsEditors = m_Window->GetActivePage()->FindEditors(dsInput, QString(), berry::IWorkbenchPage::MATCH_INPUT); if (!dsEditors.empty()) { QList editorsToClose = dsEditors; m_Window->GetActivePage()->CloseEditors(editorsToClose, false); } } catch (std::exception& e) { MITK_ERROR << "Exception caught during closing project: " << e.what(); QMessageBox::warning(NULL, "Error", QString("An error occurred during Close Project: %1").arg(e.what())); } } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.h b/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.h index 21518d244b..110b154660 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.h +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkCloseProjectAction.h @@ -1,50 +1,56 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkCloseProjectAction_H_ #define QmitkCloseProjectAction_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 #include -#include +namespace berry { +struct IWorkbenchWindow; +} /** * \ingroup org_mitk_gui_qt_application */ class MITK_QT_APP QmitkCloseProjectAction : public QAction { Q_OBJECT public: - QmitkCloseProjectAction(berry::IWorkbenchWindow::Pointer window); - QmitkCloseProjectAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window); + QmitkCloseProjectAction(berry::SmartPointer window); + QmitkCloseProjectAction(berry::IWorkbenchWindow* window); + QmitkCloseProjectAction(const QIcon & icon, berry::SmartPointer window); + QmitkCloseProjectAction(const QIcon & icon, berry::IWorkbenchWindow* window); protected slots: void Run(); private: - void init(berry::IWorkbenchWindow::Pointer window); - berry::IWorkbenchWindow::Pointer m_Window; + void init(berry::IWorkbenchWindow* window); + berry::IWorkbenchWindow* m_Window; }; #endif /*QmitkCloseProjectAction_H_*/ diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp index 6eab0b1c51..9f17aa1a0d 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.cpp @@ -1,116 +1,123 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkFileOpenAction.h" #include "internal/org_mitk_gui_qt_application_Activator.h" #include #include #include #include class QmitkFileOpenActionPrivate { public: - void init ( berry::IWorkbenchWindow::Pointer window, QmitkFileOpenAction* action ) + void init ( berry::IWorkbenchWindow* window, QmitkFileOpenAction* action ) { m_Window = window; - action->setParent(static_cast(m_Window.Lock()->GetShell()->GetControl())); - action->setText("&Open..."); + action->setText("&Open File..."); action->setToolTip("Open data files (images, surfaces,...)"); QObject::connect(action, SIGNAL(triggered(bool)), action, SLOT(Run())); } berry::IPreferences::Pointer GetPreferences() const { berry::IPreferencesService* prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); if (prefService) { return prefService->GetSystemPreferences()->Node("/General"); } return berry::IPreferences::Pointer(0); } QString getLastFileOpenPath() const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { return prefs->Get("LastFileOpenPath", ""); } return QString(); } void setLastFileOpenPath(const QString& path) const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { prefs->Put("LastFileOpenPath", path); prefs->Flush(); } } bool GetOpenEditor() const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { return prefs->GetBool("OpenEditor", true); } return true; } - berry::IWorkbenchWindow::WeakPtr m_Window; + berry::IWorkbenchWindow* m_Window; }; QmitkFileOpenAction::QmitkFileOpenAction(berry::IWorkbenchWindow::Pointer window) : QAction(0), d(new QmitkFileOpenActionPrivate) { - d->init(window, this); + d->init(window.GetPointer(), this); } QmitkFileOpenAction::QmitkFileOpenAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(0), d(new QmitkFileOpenActionPrivate) +{ + d->init(window.GetPointer(), this); + this->setIcon(icon); +} + +QmitkFileOpenAction::QmitkFileOpenAction(const QIcon& icon, berry::IWorkbenchWindow* window) + : QAction(0), d(new QmitkFileOpenActionPrivate) { d->init(window, this); this->setIcon(icon); } QmitkFileOpenAction::~QmitkFileOpenAction() { } void QmitkFileOpenAction::Run() { // Ask the user for a list of files to open QStringList fileNames = QFileDialog::getOpenFileNames(NULL, "Open", d->getLastFileOpenPath(), QmitkIOUtil::GetFileOpenFilterString()); if (fileNames.empty()) return; d->setLastFileOpenPath(fileNames.front()); - mitk::WorkbenchUtil::LoadFiles(fileNames, d->m_Window.Lock(), d->GetOpenEditor()); + mitk::WorkbenchUtil::LoadFiles(fileNames, berry::IWorkbenchWindow::Pointer(d->m_Window), + d->GetOpenEditor()); } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.h b/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.h index 09079fc7fc..a6888ad471 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.h +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkFileOpenAction.h @@ -1,62 +1,63 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKFILEOPENACTION_H_ #define QMITKFILEOPENACTION_H_ #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 class QmitkFileOpenActionPrivate; /** * \ingroup org_mitk_gui_qt_application */ class MITK_QT_APP QmitkFileOpenAction : public QAction { Q_OBJECT public: QmitkFileOpenAction(berry::IWorkbenchWindow::Pointer window); QmitkFileOpenAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window); + QmitkFileOpenAction(const QIcon & icon, berry::IWorkbenchWindow* window); ~QmitkFileOpenAction(); protected slots: virtual void Run(); private: const QScopedPointer d; }; #endif /*QMITKFILEOPENACTION_H_*/ diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp index 504dff27a5..10db64cb10 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.cpp @@ -1,190 +1,196 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkFileSaveAction.h" #include "internal/org_mitk_gui_qt_application_Activator.h" #include #include #include #include #include #include #include #include class QmitkFileSaveActionPrivate { private: void HandleSelectionChanged(const berry::IWorkbenchPart::Pointer& /*part*/, const berry::ISelection::ConstPointer& selection) { this->setEnabled(selection); } QScopedPointer m_SelectionListener; public: QmitkFileSaveActionPrivate() : m_SelectionListener(new berry::NullSelectionChangedAdapter( this, &QmitkFileSaveActionPrivate::HandleSelectionChanged)) { } ~QmitkFileSaveActionPrivate() { if (!m_Window.Expired()) { m_Window.Lock()->GetSelectionService()->RemoveSelectionListener(m_SelectionListener.data()); } } - void init ( berry::IWorkbenchWindow::Pointer window, QmitkFileSaveAction* action ) + void init ( berry::IWorkbenchWindow* window, QmitkFileSaveAction* action ) { - m_Window = window; + m_Window = berry::IWorkbenchWindow::Pointer(window); m_Action = action; - action->setParent(static_cast(m_Window.Lock()->GetShell()->GetControl())); action->setText("&Save..."); action->setToolTip("Save data objects (images, surfaces,...)"); berry::ISelectionService* selectionService = m_Window.Lock()->GetSelectionService(); setEnabled(selectionService->GetSelection()); selectionService->AddSelectionListener(m_SelectionListener.data()); QObject::connect(action, SIGNAL(triggered(bool)), action, SLOT(Run())); } berry::IPreferences::Pointer GetPreferences() const { berry::IPreferencesService* prefService = mitk::PluginActivator::GetInstance()->GetPreferencesService(); if (prefService != nullptr) { return prefService->GetSystemPreferences()->Node("/General"); } return berry::IPreferences::Pointer(0); } QString getLastFileSavePath() const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { return prefs->Get("LastFileSavePath", ""); } return QString(); } void setLastFileSavePath(const QString& path) const { berry::IPreferences::Pointer prefs = GetPreferences(); if(prefs.IsNotNull()) { prefs->Put("LastFileSavePath", path); prefs->Flush(); } } void setEnabled(berry::ISelection::ConstPointer selection) { mitk::DataNodeSelection::ConstPointer nodeSelection = selection.Cast(); if (nodeSelection.IsNotNull() && !selection->IsEmpty()) { bool enable = false; std::list dataNodes = nodeSelection->GetSelectedDataNodes(); for (std::list::const_iterator nodeIter = dataNodes.begin(), nodeIterEnd = dataNodes.end(); nodeIter != nodeIterEnd; ++nodeIter) { if ((*nodeIter)->GetData() != NULL) { enable = true; break; } } m_Action->setEnabled(enable); } else { m_Action->setEnabled(false); } } berry::IWorkbenchWindow::WeakPtr m_Window; QAction* m_Action; }; QmitkFileSaveAction::QmitkFileSaveAction(berry::IWorkbenchWindow::Pointer window) : QAction(0), d(new QmitkFileSaveActionPrivate) { - d->init(window, this); + d->init(window.GetPointer(), this); } QmitkFileSaveAction::QmitkFileSaveAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window) : QAction(0), d(new QmitkFileSaveActionPrivate) +{ + d->init(window.GetPointer(), this); + this->setIcon(icon); +} + +QmitkFileSaveAction::QmitkFileSaveAction(const QIcon& icon, berry::IWorkbenchWindow* window) + : QAction(0), d(new QmitkFileSaveActionPrivate) { d->init(window, this); this->setIcon(icon); } QmitkFileSaveAction::~QmitkFileSaveAction() { } void QmitkFileSaveAction::Run() { // Get the list of selected base data objects mitk::DataNodeSelection::ConstPointer selection = d->m_Window.Lock()->GetSelectionService()->GetSelection().Cast(); if (selection.IsNull() || selection->IsEmpty()) { MITK_ERROR << "Assertion failed: data node selection is NULL or empty"; return; } std::list dataNodes = selection->GetSelectedDataNodes(); std::vector data; QStringList names; for (std::list::const_iterator nodeIter = dataNodes.begin(), nodeIterEnd = dataNodes.end(); nodeIter != nodeIterEnd; ++nodeIter) { data.push_back((*nodeIter)->GetData()); std::string name; (*nodeIter)->GetStringProperty("name", name); names.push_back(QString::fromStdString(name)); } try { QStringList fileNames = QmitkIOUtil::Save(data, names, d->getLastFileSavePath(), d->m_Action->parentWidget()); if (!fileNames.empty()) { d->setLastFileSavePath(QFileInfo(fileNames.back()).absolutePath()); } } catch (const mitk::Exception& e) { MITK_INFO << e; return; } } diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.h b/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.h index d80f54bf6c..197089584f 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.h +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkFileSaveAction.h @@ -1,55 +1,56 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKFILESAVEACTION_H_ #define QMITKFILESAVEACTION_H_ #include #include #include #include #include class QmitkFileSaveActionPrivate; /** * \ingroup org_mitk_gui_qt_application */ class MITK_QT_APP QmitkFileSaveAction : public QAction { Q_OBJECT public: QmitkFileSaveAction(berry::IWorkbenchWindow::Pointer window); QmitkFileSaveAction(const QIcon & icon, berry::IWorkbenchWindow::Pointer window); + QmitkFileSaveAction(const QIcon & icon, berry::IWorkbenchWindow* window); ~QmitkFileSaveAction(); protected slots: virtual void Run(); private: const QScopedPointer d; }; #endif /*QMITKFILESAVEACTION_H_*/ diff --git a/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.cpp b/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.cpp index 7418a0ded1..4930c45f4c 100644 --- a/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/QmitkPreferencesDialog.cpp @@ -1,411 +1,410 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkPreferencesDialog.h" #include "berryPlatform.h" +#include "berryPlatformUI.h" +#include "berryIWorkbench.h" #include "berryIConfigurationElement.h" #include "berryIExtensionRegistry.h" #include "berryIExtension.h" #include #include #include "internal/org_mitk_gui_qt_application_Activator.h" #include #include #include #include #include #include using namespace std; class QmitkPreferencesDialogPrivate : public Ui::QmitkPreferencesDialog { public: /// /// Just a stub class for holding information on prefpages (metadata) /// struct PrefPage { PrefPage(QString _id, QString _name, QString _category , QString _className, QString _keywords, berry::IConfigurationElement::Pointer _confElem) : id(_id), name(_name), category(_category), className(_className), keywords(_keywords), prefPage(0), confElem(_confElem), treeWidgetItem(0) {} bool operator==(const PrefPage& other) { return id == other.id; } bool operator<(const PrefPage& other) { return name < other.name; } QString id; QString name; QString category; QString className; QString keywords; berry::IQtPreferencePage* prefPage; berry::IConfigurationElement::Pointer confElem; QTreeWidgetItem* treeWidgetItem; }; QmitkPreferencesDialogPrivate() : m_CurrentPage(0) { berry::IExtensionRegistry* xpService = berry::Platform::GetExtensionRegistry(); // m_PrefPages QList prefPages(xpService->GetConfigurationElementsFor("org.blueberry.ui.preferencePages")); QList keywordExts(xpService->GetConfigurationElementsFor("org.blueberry.ui.keywords")); QList::iterator prefPagesIt; QList::iterator keywordRefsIt; - QString keywordLabels; - for (prefPagesIt = prefPages.begin(); prefPagesIt != prefPages.end(); ++prefPagesIt) { QString id = (*prefPagesIt)->GetAttribute("id"); QString name = (*prefPagesIt)->GetAttribute("name"); QString className = (*prefPagesIt)->GetAttribute("class"); if(!id.isEmpty() && !name.isEmpty() && !className.isEmpty()) { + QString keywordLabels; + QString category = (*prefPagesIt)->GetAttribute("category"); //# collect keywords QList keywordRefs = (*prefPagesIt)->GetChildren("keywordreference"); // get all keyword references for (keywordRefsIt = keywordRefs.begin() ; keywordRefsIt != keywordRefs.end(); ++keywordRefsIt) // iterate over all refs { QString keywordRefId = (*keywordRefsIt)->GetAttribute("id"); // get referenced id for (QList::iterator keywordExtsIt = keywordExts.begin(); keywordExtsIt != keywordExts.end(); ++keywordExtsIt) // iterate over all keywords { QString keywordId = (*keywordExtsIt)->GetAttribute("id"); // get keyword id if(keywordId == keywordRefId) // if referenced id is equals the current keyword id { //# collect all keywords from label attribute with a tokenizer QString currLabel = (*keywordExtsIt)->GetAttribute("label"); currLabel = currLabel.toLower(); if (!currLabel.isEmpty()) keywordLabels += QString(" ") + currLabel; //break; // break here; possibly search for other referenced keywords } } } // add information as PrefPage m_PrefPages.push_back(PrefPage(id, name, category, className, keywordLabels, berry::IConfigurationElement::Pointer(*prefPagesIt))); } } } /// /// Saves all treewidgetitems in a map, the key is the id of the preferencepage. /// QList m_PrefPages; int m_CurrentPage; }; QmitkPreferencesDialog::QmitkPreferencesDialog(QWidget * parent, Qt::WindowFlags f) : QDialog(parent, f), d(new QmitkPreferencesDialogPrivate) { d->setupUi(this); QObject::connect(d->m_Keyword, SIGNAL(editingFinished()), this, SLOT(OnKeywordEditingFinished())); QObject::connect(d->m_Keyword, SIGNAL(textChanged(QString)), this, SLOT(OnKeywordTextChanged(QString))); QObject::connect(d->m_PreferencesTree, SIGNAL(itemSelectionChanged()), this, SLOT(OnPreferencesTreeItemSelectionChanged())); QPushButton* importButton = d->buttonBox->addButton("Import...", QDialogButtonBox::ActionRole); QObject::connect(importButton, SIGNAL(clicked()), this, SLOT(OnImportButtonClicked())); QPushButton* exportButton = d->buttonBox->addButton("Export...", QDialogButtonBox::ActionRole); QObject::connect(exportButton, SIGNAL(clicked()), this, SLOT(OnExportButtonClicked())); QObject::connect(this, SIGNAL(accepted()), this, SLOT(OnDialogAccepted())); QObject::connect(this, SIGNAL(rejected()), this, SLOT(OnDialogRejected())); d->buttonBox->button(QDialogButtonBox::Cancel)->setDefault(true); this->UpdateTree(); } QmitkPreferencesDialog::~QmitkPreferencesDialog() { } void QmitkPreferencesDialog::SetSelectedPage(const QString& id) { for(QList::iterator it = d->m_PrefPages.begin(); it != d->m_PrefPages.end(); ++it) { if(it->id == id) { d->m_PreferencesTree->setCurrentItem(it->treeWidgetItem); break; } } } void QmitkPreferencesDialog::OnImportButtonClicked() { int answer = QMessageBox::question(this, "Importing Preferences" , "All existing preferences will be overwritten!\nAre you sure that you want to import other preferences?", QMessageBox::Yes | QMessageBox::No ); if(answer == QMessageBox::No) return; try { berry::IBerryPreferencesService* berryPrefService = dynamic_cast(berry::Platform::GetPreferencesService()); if(berryPrefService != 0) { static QString importDir = ""; QString fileName = QFileDialog::getOpenFileName(this, tr("Choose file to import preferences"), importDir, tr("XML files (*.xml)")); if(!fileName.isEmpty()) { importDir = QFileInfo(fileName).absoluteDir().path(); berryPrefService->ImportPreferences(fileName, ""); berry::IQtPreferencePage* prefPage = d->m_PrefPages[d->m_CurrentPage].prefPage; if(prefPage) prefPage->Update(); MITK_INFO("QmitkPreferencesDialog") << "Preferences successfully imported from " << fileName; } } } catch (Poco::Exception& pe) { QMessageBox::critical(this, "Error Importing", pe.message().c_str()); MITK_ERROR("QmitkPreferencesDialog") << pe.what(); } catch (std::exception& e) { QMessageBox::critical(this, "Error Importing", e.what()); MITK_ERROR("QmitkPreferencesDialog") << e.what(); } } void QmitkPreferencesDialog::OnExportButtonClicked() { try { berry::IBerryPreferencesService* berryPrefService = dynamic_cast(berry::Platform::GetPreferencesService()); if(berryPrefService != 0) { SavePreferences(); static QString exportDir = ""; QString fileName = QFileDialog::getSaveFileName(this, tr("Choose file to export preferences"), exportDir, tr("XML files (*.xml)")); if(!fileName.isEmpty()) { if(QFileInfo(fileName).suffix() != ".xml") { fileName += ".xml"; } exportDir = QFileInfo(fileName).absoluteDir().path(); berryPrefService->ExportPreferences(fileName, ""); MITK_INFO("QmitkPreferencesDialog") << "Preferences successfully exported to " << fileName; } } } catch (Poco::Exception& pe) { QMessageBox::critical(this, "Error Exporting", pe.message().c_str()); MITK_ERROR("QmitkPreferencesDialog") << pe.what(); } catch (std::exception& e) { QMessageBox::critical(this, "Error Exporting", e.what()); MITK_ERROR("QmitkPreferencesDialog") << e.what(); } } void QmitkPreferencesDialog::SavePreferences() { berry::IQtPreferencePage* prefPage = 0; for(QList::iterator it = d->m_PrefPages.begin(); it != d->m_PrefPages.end(); ++it) { prefPage = it->prefPage; if(prefPage) { prefPage->PerformOk(); } } /** * Every preference page has its own preferences, which should stay the same after a system restart.
* Therefore this method flushes all the preferences, every time a change in the preferences is
* performed and confirmed. * */ berry::Platform::GetPreferencesService()->GetSystemPreferences()->Flush(); } void QmitkPreferencesDialog::OnDialogAccepted() { this->SavePreferences(); } void QmitkPreferencesDialog::OnDialogRejected() { berry::IQtPreferencePage* prefPage = d->m_PrefPages[d->m_CurrentPage].prefPage; if(prefPage) prefPage->PerformCancel(); } void QmitkPreferencesDialog::OnKeywordTextChanged(const QString & /*s*/) { // search for text this->UpdateTree(); } void QmitkPreferencesDialog::OnKeywordEditingFinished() { } //bool QmitkPreferencesDialog::eventFilter( QObject *obj, QEvent *event ) //{ // if(obj == d->m_Keyword) // { // if(event->type() == QEvent::FocusIn && d->m_Keyword->text() == "search ...") // { // d->m_Keyword->setText(""); // d->m_Keyword->setStyleSheet("color: black;"); // } // else if(event->type() == QEvent::FocusOut && d->m_Keyword->text() == "") // { // d->m_Keyword->setText("search ..."); // d->m_Keyword->setStyleSheet("color: gray;"); // } // } // return true; //} void QmitkPreferencesDialog::OnPreferencesTreeItemSelectionChanged() { if(d->m_PreferencesTree == 0) return; // TODO: create page and show it QList selectedItems = d->m_PreferencesTree->selectedItems(); if(selectedItems.size()>0) { d->m_CurrentPage = 0; + berry::IWorkbench* workbench = berry::PlatformUI::GetWorkbench(); for(QList::iterator it = d->m_PrefPages.begin(); it != d->m_PrefPages.end(); ++it, ++d->m_CurrentPage) { if(it->treeWidgetItem == selectedItems.at(0)) { d->m_Headline->setText(it->name); if(it->prefPage == 0) { berry::IPreferencePage* page = it->confElem->CreateExecutableExtension("class"); - if (page == 0) - { - // support legacy BlueBerry extensions - page = it->confElem->CreateExecutableExtension("class"); - } it->prefPage = dynamic_cast(page); + it->prefPage->Init(berry::IWorkbench::Pointer(workbench)); it->prefPage->CreateQtControl(d->m_PreferencesPanel); d->m_PreferencesPanel->addWidget(it->prefPage->GetQtControl()); } d->m_PreferencesPanel->setCurrentWidget(it->prefPage->GetQtControl()); break; } } } } void QmitkPreferencesDialog::UpdateTree() { if(d->m_PreferencesTree == 0) return; //m_PreferencesTree->clear(); QString keyword = d->m_Keyword->text().toLower(); map items; for(QList::iterator it = d->m_PrefPages.begin(); it != d->m_PrefPages.end(); ++it) { if(it->treeWidgetItem == 0) { if(it->category.isEmpty()) { it->treeWidgetItem = new QTreeWidgetItem(d->m_PreferencesTree); } else { it->treeWidgetItem = new QTreeWidgetItem(items[it->category]); } it->treeWidgetItem->setText(0, it->name); items[it->id] = it->treeWidgetItem; } // hide treeWidgetItem if keyword not matches if(!keyword.isEmpty()) { if( it->keywords.indexOf(keyword) == -1 ) it->treeWidgetItem->setHidden(true); else { //#make the whole branch visible QTreeWidgetItem* treeWidgetParent = it->treeWidgetItem->parent(); while(treeWidgetParent!=0) { treeWidgetParent->setHidden(false); treeWidgetParent->setExpanded(true); treeWidgetParent = treeWidgetParent->parent(); } it->treeWidgetItem->setHidden(false); QFont f = it->treeWidgetItem->font(0); f.setBold(true); it->treeWidgetItem->setFont(0, f); } } else { QFont f = it->treeWidgetItem->font(0); f.setBold(false); it->treeWidgetItem->setFont(0, f); it->treeWidgetItem->setHidden(false); } } if(d->m_PrefPages.size()>0) { if(d->m_PrefPages.front().treeWidgetItem != 0) d->m_PrefPages.front().treeWidgetItem->setSelected(true); } } diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkShowPreferencePageHandler.cpp b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkShowPreferencePageHandler.cpp new file mode 100644 index 0000000000..82bdb03f30 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkShowPreferencePageHandler.cpp @@ -0,0 +1,37 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY 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 "QmitkShowPreferencePageHandler.h" + +#include + +#include + +#include + +#include + +berry::Object::Pointer QmitkShowPreferencePageHandler::Execute(const berry::ExecutionEvent::ConstPointer& event) +{ + const QString preferencePageId = event->GetParameter(berry::IWorkbenchCommandConstants::WINDOW_PREFERENCES_PARM_PAGEID); + + QmitkPreferencesDialog prefDialog(QApplication::activeWindow()); + prefDialog.SetSelectedPage(preferencePageId); + + prefDialog.exec(); + + return berry::Object::Pointer(); +} diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/QmitkShowPreferencePageHandler.h b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkShowPreferencePageHandler.h new file mode 100644 index 0000000000..be8cb0e850 --- /dev/null +++ b/Plugins/org.mitk.gui.qt.application/src/internal/QmitkShowPreferencePageHandler.h @@ -0,0 +1,37 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#ifndef QMITKSHOWPREFERENCEPAGEHANDLER_H +#define QMITKSHOWPREFERENCEPAGEHANDLER_H + +#include + +/** + * Shows the given preference page. If no preference page id is specified in the + * parameters, then this opens the preferences dialog to whatever page was + * active the last time the dialog was shown. + */ +class QmitkShowPreferencePageHandler : public berry::AbstractHandler +{ + Q_OBJECT + +public: + + berry::Object::Pointer Execute(const berry::SmartPointer &event); + +}; + +#endif // QMITKSHOWPREFERENCEPAGEHANDLER_H diff --git a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp index 6a2e403498..94d37671dd 100644 --- a/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp +++ b/Plugins/org.mitk.gui.qt.application/src/internal/org_mitk_gui_qt_application_Activator.cpp @@ -1,75 +1,78 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "org_mitk_gui_qt_application_Activator.h" #include "QmitkGeneralPreferencePage.h" #include "QmitkEditorsPreferencePage.h" #include +#include "QmitkShowPreferencePageHandler.h" + #include namespace mitk { org_mitk_gui_qt_application_Activator* org_mitk_gui_qt_application_Activator::m_Instance = 0; ctkPluginContext* org_mitk_gui_qt_application_Activator::m_Context = 0; void org_mitk_gui_qt_application_Activator::start(ctkPluginContext* context) { this->m_Instance = this; this->m_Context = context; BERRY_REGISTER_EXTENSION_CLASS(QmitkGeneralPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkEditorsPreferencePage, context) + BERRY_REGISTER_EXTENSION_CLASS(QmitkShowPreferencePageHandler, context) QmitkRegisterClasses(); this->m_PrefServiceTracker.reset(new ctkServiceTracker(context)); this->m_PrefServiceTracker->open(); } void org_mitk_gui_qt_application_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) this->m_PrefServiceTracker.reset(); this->m_Context = 0; this->m_Instance = 0; } ctkPluginContext* org_mitk_gui_qt_application_Activator::GetContext() { return m_Context; } org_mitk_gui_qt_application_Activator *org_mitk_gui_qt_application_Activator::GetInstance() { return m_Instance; } berry::IPreferencesService* org_mitk_gui_qt_application_Activator::GetPreferencesService() { return m_PrefServiceTracker->getService(); } } #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(org_mitk_gui_qt_application, mitk::org_mitk_gui_qt_application_Activator) #endif diff --git a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.h b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.h index c9d78c2398..f1018ae803 100644 --- a/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.h +++ b/Plugins/org.mitk.gui.qt.common/src/QmitkAbstractRenderEditor.h @@ -1,157 +1,159 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKABSTRACTRENDEREDITOR_H #define QMITKABSTRACTRENDEREDITOR_H #include #include #include "mitkIRenderWindowPart.h" #include #include #include class QmitkAbstractRenderEditorPrivate; /** * \ingroup org_mitk_gui_qt_common * * \brief A convenient base class for MITK render window BlueBerry Editors. * * QmitkAbstractRenderEditor provides several convenience methods that ease the introduction of * a new editor for rendering a MITK DataStorage: * *
    *
  1. Access to the DataStorage (~ the shared data repository) *
  2. Access to and update notification for the editor's preferences *
  3. Default implementation of some mitk::IRenderWindowPart methods *
* * When inheriting from QmitkAbstractRenderEditor, you must implement the following methods: *
    *
  • void CreateQtPartControl(QWidget* parent) *
  • void SetFocus() *
* * You may reimplement the following private virtual methods to be notified about certain changes: *
    *
  • void OnPreferencesChanged(const berry::IBerryPreferences*) *
* * \see IRenderWindowPart * \see ILinkedRenderWindowPart */ class MITK_QT_COMMON QmitkAbstractRenderEditor : public berry::QtEditorPart, public virtual mitk::IRenderWindowPart { Q_OBJECT Q_INTERFACES(mitk::IRenderWindowPart) public: + berryObjectMacro(QmitkAbstractRenderEditor, QtEditorPart, mitk::IRenderWindowPart) + QmitkAbstractRenderEditor(); ~QmitkAbstractRenderEditor(); protected: /** * Initializes this editor by checking for a valid mitk::DataStorageEditorInput as input. * * \see berry::IEditorPart::Init */ void Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input); /** * Get a reference to the DataStorage set by the editor input. */ virtual mitk::IDataStorageReference::Pointer GetDataStorageReference() const; /** * Get the DataStorage set by the editor input. */ virtual mitk::DataStorage::Pointer GetDataStorage() const; /** * Get the preferences for this editor. */ virtual berry::IPreferences::Pointer GetPreferences() const; /** * Get the RenderingManager used by this editor. This default implementation uses the * global MITK RenderingManager provided by mitk::RenderingManager::GetInstance(). * * \see mitk::IRenderWindowPart::GetRenderingManager */ mitk::IRenderingManager* GetRenderingManager() const; /** * Request an update of this editor's render windows. * This implementation calls mitk::IRenderingManager::RequestUpdate on the rendering * manager interface returned by GetRenderingManager(); * * \param requestType The type of render windows for which an update is requested. * * \see mitk::IRenderWindowPart::RequestUpdate */ void RequestUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL); /** * Force an immediate update of this editor's render windows. * This implementation calls mitk::IRenderingManager::ForceImmediateUpdate() on the rendering * manager interface returned by GetRenderingManager(); * * \param requestType The type of render windows for which an immedate update is forced. * * \see mitk::IRenderWindowPart::ForceImmediateUpdate */ void ForceImmediateUpdate(mitk::RenderingManager::RequestType requestType = mitk::RenderingManager::REQUEST_UPDATE_ALL); /** * Get the time navigation controller for this editor. * This implementation returns the SliceNavigationController returned by the mitk::IRenderingManager::GetTimeNavigationController() * method of the interface implementation returned by GetRenderingManager(). * * \see mitk::IRenderingManager::GetTimeNavigationController */ mitk::SliceNavigationController* GetTimeNavigationController() const; /** \see berry::IEditorPart::DoSave */ void DoSave(); /** \see berry::IEditorPart::DoSaveAs */ void DoSaveAs(); /** \see berry::IEditorPart::IsDirty */ bool IsDirty() const; /** \see berry::IEditorPart::IsSaveAsAllowed */ bool IsSaveAsAllowed() const; private: virtual void OnPreferencesChanged(const berry::IBerryPreferences*); private: QScopedPointer d; }; #endif // QMITKABSTRACTRENDEREDITOR_H diff --git a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.h b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.h index 9baaf1d3de..d9c846a036 100644 --- a/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.h +++ b/Plugins/org.mitk.gui.qt.common/src/internal/QmitkViewCoordinator.h @@ -1,124 +1,122 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkViewCoordinator_h #define QmitkViewCoordinator_h #include #include #include #include #include namespace mitk { struct IRenderWindowPart; struct IRenderWindowPartListener; struct IZombieViewPart; } class QmitkAbstractView; /** * A class which coordinates active QmitkAbstractView s, e.g. calling activated and hidden on them. */ class QmitkViewCoordinator : private berry::IPartListener, private berry::IWindowListener { public: - berryObjectMacro(QmitkViewCoordinator); - /** * Add listener */ QmitkViewCoordinator(); /** * Remove listener */ virtual ~QmitkViewCoordinator(); void Start(); void Stop(); //#IPartListener methods (these methods internally call Activated() or other similar methods) /** * \see IPartListener::GetPartEventTypes() */ berry::IPartListener::Events::Types GetPartEventTypes() const; /** * \see IPartListener::PartActivated() */ virtual void PartActivated (const berry::IWorkbenchPartReference::Pointer& partRef); /** * \see IPartListener::PartDeactivated() */ virtual void PartDeactivated(const berry::IWorkbenchPartReference::Pointer& /*partRef*/); /** * \see IPartListener::PartOpened() */ virtual void PartOpened(const berry::IWorkbenchPartReference::Pointer& partRef); /** * \see IPartListener::PartClosed() */ virtual void PartClosed (const berry::IWorkbenchPartReference::Pointer& partRef); /** * \see IPartListener::PartHidden() */ virtual void PartHidden(const berry::IWorkbenchPartReference::Pointer& partRef); /** * \see IPartListener::PartVisible() */ virtual void PartVisible(const berry::IWorkbenchPartReference::Pointer& partRef); /** * Notifies this listener that the given window has been closed. */ virtual void WindowClosed(const berry::IWorkbenchWindow::Pointer& window); /** * Notifies this listener that the given window has been opened. */ virtual void WindowOpened(const berry::IWorkbenchWindow::Pointer& /*window*/); private: void RenderWindowPartActivated(mitk::IRenderWindowPart* renderPart); void RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderPart); private: mitk::IZombieViewPart* m_ActiveZombieView; mitk::IRenderWindowPart* m_ActiveRenderWindowPart; mitk::IRenderWindowPart* m_VisibleRenderWindowPart; QSet m_RenderWindowListeners; }; #endif // QmitkViewCoordinator_h diff --git a/Plugins/org.mitk.gui.qt.ext/files.cmake b/Plugins/org.mitk.gui.qt.ext/files.cmake index 290cdf8b6a..0807b425f9 100644 --- a/Plugins/org.mitk.gui.qt.ext/files.cmake +++ b/Plugins/org.mitk.gui.qt.ext/files.cmake @@ -1,60 +1,61 @@ set(SRC_CPP_FILES QmitkExtActionBarAdvisor.cpp - QmitkExtActionConstants.cpp QmitkExtWorkbenchWindowAdvisor.cpp QmitkExtFileSaveProjectAction.cpp QmitkOpenDicomEditorAction.cpp QmitkOpenXnatEditorAction.cpp ) set(INTERNAL_CPP_FILES + QmitkAboutHandler.cpp QmitkAppInstancesPreferencePage.cpp QmitkExternalProgramsPreferencePage.cpp QmitkCommonExtPlugin.cpp QmitkInputDevicesPrefPage.cpp QmitkModuleView.cpp ) set(UI_FILES src/internal/QmitkAppInstancesPreferencePage.ui src/internal/QmitkExternalProgramsPreferencePage.ui ) set(MOC_H_FILES src/QmitkExtFileSaveProjectAction.h src/QmitkExtWorkbenchWindowAdvisor.h + src/internal/QmitkAboutHandler.h src/internal/QmitkAppInstancesPreferencePage.h src/internal/QmitkExternalProgramsPreferencePage.h src/internal/QmitkCommonExtPlugin.h src/internal/QmitkExtWorkbenchWindowAdvisorHack.h src/internal/QmitkInputDevicesPrefPage.h src/internal/QmitkModuleView.h src/QmitkOpenDicomEditorAction.h src/QmitkOpenXnatEditorAction.h ) set(CACHED_RESOURCE_FILES # list of resource files which can be used by the plug-in # system without loading the plug-ins shared library, # for example the icon used in the menu and tabs for the # plug-in views in the workbench plugin.xml resources/ModuleView.png ) set(QRC_FILES # uncomment the following line if you want to use Qt resources resources/org_mitk_gui_qt_ext.qrc resources/org_mitk_icons.qrc ) 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/Plugins/org.mitk.gui.qt.ext/plugin.xml b/Plugins/org.mitk.gui.qt.ext/plugin.xml index b9e718f264..dec112b1e5 100644 --- a/Plugins/org.mitk.gui.qt.ext/plugin.xml +++ b/Plugins/org.mitk.gui.qt.ext/plugin.xml @@ -1,34 +1,40 @@ + + + + diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.cpp index c75d15a9ce..3e36fbb157 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.cpp @@ -1,95 +1,278 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkExtActionBarAdvisor.h" -#include "QmitkExtActionConstants.h" +#include "QmitkFileOpenAction.h" +#include "QmitkFileSaveAction.h" +#include "QmitkExtFileSaveProjectAction.h" +#include "QmitkCloseProjectAction.h" + +#include #include #include #include +#include +#include #include +#include #include #include +#include + +#include +#include +#include QmitkExtActionBarAdvisor::QmitkExtActionBarAdvisor(berry::IActionBarConfigurer::Pointer configurer) : berry::ActionBarAdvisor(configurer) { window = configurer->GetWindowConfigurer()->GetWindow().GetPointer(); } +void QmitkExtActionBarAdvisor::MakeActions(berry::IWorkbenchWindow* window) +{ + QAction* fileOpenAction = new QmitkFileOpenAction( + QIcon::fromTheme("document-open", + QIcon(":/org_mitk_icons/icons/tango/scalable/actions/document-open.svg")), + window); + fileOpenAction->setShortcut(QKeySequence::Open); + this->Register(fileOpenAction, berry::IWorkbenchCommandConstants::FILE_OPEN); + + QAction* fileSaveAction = new QmitkFileSaveAction( + QIcon(":/org.mitk.gui.qt.ext/Save_48.png"), + window); + fileSaveAction->setShortcut(QKeySequence::Save); + this->Register(fileSaveAction, berry::IWorkbenchCommandConstants::FILE_SAVE); + + QAction* fileSaveProjectAction = new QmitkExtFileSaveProjectAction(window); + fileSaveProjectAction->setIcon(QIcon::fromTheme("document-save", + QIcon(":/org_mitk_icons/icons/tango/scalable/actions/document-save.svg"))); + this->Register(fileSaveProjectAction, mitk::WorkbenchCommandConstants::PROJECT_SAVE); + + QAction* closeProjectAction = new QmitkCloseProjectAction(window); + closeProjectAction->setIcon(QIcon::fromTheme("edit-delete", + QIcon(":/org_mitk_icons/icons/tango/scalable/actions/edit-delete.svg"))); + this->Register(closeProjectAction, mitk::WorkbenchCommandConstants::PROJECT_CLOSE); + +} + void QmitkExtActionBarAdvisor::FillMenuBar(berry::IMenuManager* menuBar) { - //menuBar.add(createFileMenu()); - //menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); + menuBar->Add(CreateFileMenu()); + menuBar->Add(CreateEditMenu()); + menuBar->Add(berry::IContributionItem::Pointer(new berry::GroupMarker(berry::WorkbenchActionConstants::MB_ADDITIONS))); menuBar->Add(CreateWindowMenu()); - //menuBar.add(createHelpMenu()); + menuBar->Add(CreateHelpMenu()); +} + +void QmitkExtActionBarAdvisor::FillToolBar(berry::IToolBarManager* /*toolBar*/) +{ +} + +berry::SmartPointer QmitkExtActionBarAdvisor::CreateFileMenu() +{ + berry::MenuManager::Pointer menu(new berry::MenuManager("&File", + berry::WorkbenchActionConstants::M_FILE)); + + menu->Add(berry::IContributionItem::Pointer(new berry::GroupMarker(berry::WorkbenchActionConstants::FILE_START))); + { + // create the New submenu, using the same id for it as the New action + QString newText = "&New"; + QString newId = "org.blueberry.ui.newWizard"; + berry::MenuManager::Pointer newMenu(new berry::MenuManager(newText, newId)); + newMenu->SetCommandId("org.blueberry.ui.file.newQuickMenu"); + newMenu->Add(berry::IContributionItem::Pointer(new berry::Separator(newId))); + //this.newWizardMenu = new NewWizardMenu(getWindow()); + //newMenu.add(this.newWizardMenu); + newMenu->Add(berry::IContributionItem::Pointer(new berry::Separator(berry::WorkbenchActionConstants::MB_ADDITIONS))); + menu->Add(newMenu); + } + + menu->Add(this->GetAction(berry::IWorkbenchCommandConstants::FILE_OPEN), + berry::IWorkbenchCommandConstants::FILE_OPEN); + + menu->Add(berry::IContributionItem::Pointer(new berry::GroupMarker(berry::WorkbenchActionConstants::NEW_EXT))); + menu->Add(berry::IContributionItem::Pointer(new berry::Separator())); + + //menu.add(closeAction); + //menu.add(closeAllAction); + // // menu.add(closeAllSavedAction); + + menu->Add(this->GetAction(mitk::WorkbenchCommandConstants::PROJECT_CLOSE), + mitk::WorkbenchCommandConstants::PROJECT_CLOSE); + menu->Add(berry::IContributionItem::Pointer(new berry::GroupMarker(berry::WorkbenchActionConstants::CLOSE_EXT))); + menu->Add(berry::IContributionItem::Pointer(new berry::Separator())); + + menu->Add(this->GetAction(berry::IWorkbenchCommandConstants::FILE_SAVE), + berry::IWorkbenchCommandConstants::FILE_SAVE); + menu->Add(this->GetAction(mitk::WorkbenchCommandConstants::PROJECT_SAVE), + mitk::WorkbenchCommandConstants::PROJECT_SAVE); + menu->Add(berry::IContributionItem::Pointer(new berry::GroupMarker(berry::WorkbenchActionConstants::SAVE_EXT))); + menu->Add(berry::IContributionItem::Pointer(new berry::Separator())); + menu->Add(berry::IContributionItem::Pointer(new berry::Separator(berry::WorkbenchActionConstants::MB_ADDITIONS))); + + menu->Add(berry::IContributionItem::Pointer(new berry::Separator())); + + menu->Add(berry::ContributionItemFactory::REOPEN_EDITORS->Create(window)); + menu->Add(berry::IContributionItem::Pointer(new berry::GroupMarker(berry::WorkbenchActionConstants::MRU))); + menu->Add(berry::IContributionItem::Pointer(new berry::Separator())); + + // If we're on OS X we shouldn't show this command in the File menu. It + // should be invisible to the user. However, we should not remove it - + // the carbon UI code will do a search through our menu structure + // looking for it when Cmd-Q is invoked (or Quit is chosen from the + // application menu. + //ActionContributionItem quitItem = new ActionContributionItem(quitAction); + //quitItem.setVisible(!Util.isMac()); + //menu.add(quitItem); + menu->Add(GetItem(berry::IWorkbenchCommandConstants::FILE_EXIT, "Exit")); + menu->Add(berry::IContributionItem::Pointer(new berry::GroupMarker(berry::WorkbenchActionConstants::FILE_END))); + + return menu; +} + +berry::SmartPointer QmitkExtActionBarAdvisor::CreateEditMenu() +{ + berry::MenuManager::Pointer menu(new berry::MenuManager("&Edit", + berry::WorkbenchActionConstants::M_EDIT)); + + menu->Add(berry::IContributionItem::Pointer(new berry::GroupMarker(berry::WorkbenchActionConstants::EDIT_START))); + + menu->Add(GetItem(berry::IWorkbenchCommandConstants::EDIT_UNDO, "&Undo")); + menu->Add(GetItem(berry::IWorkbenchCommandConstants::EDIT_REDO, "&Redo")); + menu->Add(berry::IContributionItem::Pointer(new berry::GroupMarker(berry::WorkbenchActionConstants::UNDO_EXT))); + menu->Add(berry::IContributionItem::Pointer(new berry::Separator())); +/* + menu.add(getCutItem()); + menu.add(getCopyItem()); + menu.add(getPasteItem()); + menu.add(new GroupMarker(IWorkbenchActionConstants.CUT_EXT)); + menu.add(new Separator()); + + menu.add(getDeleteItem()); + menu.add(getSelectAllItem()); + menu.add(new Separator()); + + menu.add(getFindItem()); + menu.add(new GroupMarker(IWorkbenchActionConstants.FIND_EXT)); + menu.add(new Separator()); + + menu.add(getBookmarkItem()); + menu.add(getTaskItem()); + menu.add(new GroupMarker(IWorkbenchActionConstants.ADD_EXT)); +*/ + menu->Add(berry::IContributionItem::Pointer(new berry::GroupMarker(berry::WorkbenchActionConstants::EDIT_END))); + menu->Add(berry::IContributionItem::Pointer(new berry::Separator(berry::WorkbenchActionConstants::MB_ADDITIONS))); + + return menu; +} + +berry::SmartPointer QmitkExtActionBarAdvisor::CreateHelpMenu() +{ + berry::MenuManager::Pointer menu(new berry::MenuManager("&Help", + berry::WorkbenchActionConstants::M_HELP)); + + menu->Add(berry::IContributionItem::Pointer(new berry::GroupMarker(berry::WorkbenchActionConstants::HELP_START))); + + menu->Add(berry::IContributionItem::Pointer(new berry::Separator("group.intro"))); + // See if a welcome or intro page is specified + if (window->GetWorkbench()->GetIntroManager()->HasIntro()) + { + menu->Add(GetItem(berry::IWorkbenchCommandConstants::HELP_WELCOME, "Welcome")); + } + menu->Add(berry::IContributionItem::Pointer(new berry::GroupMarker("group.intro.ext"))); + menu->Add(berry::IContributionItem::Pointer(new berry::Separator("group.main"))); + menu->Add(GetItem(berry::IWorkbenchCommandConstants::HELP_HELP_CONTENTS, "Help &Contents")); + //menu->Add(GetItem(berry::IWorkbenchCommandConstants::HELP_HELP_SEARCH, "Help Search")); + menu->Add(GetItem(berry::IWorkbenchCommandConstants::HELP_DYNAMIC_HELP, "Conte&xt Help")); + menu->Add(berry::IContributionItem::Pointer(new berry::GroupMarker(berry::WorkbenchActionConstants::HELP_END))); + menu->Add(berry::IContributionItem::Pointer(new berry::Separator(berry::WorkbenchActionConstants::MB_ADDITIONS))); + + // about should always be at the bottom + menu->Add(berry::IContributionItem::Pointer(new berry::Separator("group.about"))); + + menu->Add(GetItem(berry::IWorkbenchCommandConstants::HELP_ABOUT, "&About")); + menu->Add(berry::IContributionItem::Pointer(new berry::GroupMarker("group.about.ext"))); + + return menu; } berry::MenuManager::Pointer QmitkExtActionBarAdvisor::CreateWindowMenu() { berry::MenuManager::Pointer menu(new berry::MenuManager("&Window", - QmitkExtActionConstants::M_WINDOW)); - - //addMacWindowMenuItems(menu); + berry::WorkbenchActionConstants::M_WINDOW)); - //menu.add(newWindowAction); - //menu.add(newEditorAction); + menu->Add(GetItem(berry::IWorkbenchCommandConstants::WINDOW_NEW_WINDOW, "New Window")); + menu->Add(GetItem(berry::IWorkbenchCommandConstants::WINDOW_NEW_EDITOR, "New Editor")); - //menu.add(new Separator()); + menu->Add(berry::IContributionItem::Pointer(new berry::Separator())); AddPerspectiveActions(menu.GetPointer()); //menu.add(new Separator()); //AddKeyboardShortcuts(menu); - //Separator sep = new Separator(IWorkbenchActionConstants.MB_ADDITIONS); + berry::Separator::Pointer sep(new berry::Separator(berry::WorkbenchActionConstants::MB_ADDITIONS)); //sep.setVisible(!Util.isMac()); - //menu.add(sep); + menu->Add(berry::IContributionItem::Pointer(sep.GetPointer())); //if(Util.isCocoa()) // menu.add(arrangeWindowsItem); // See the comment for quit in createFileMenu - //ActionContributionItem openPreferencesItem = new ActionContributionItem(openPreferencesAction); + berry::IContributionItem::Pointer openPreferencesItem = + GetItem(berry::IWorkbenchCommandConstants::WINDOW_PREFERENCES, "Preferences"); //openPreferencesItem.setVisible(!Util.isMac()); - //menu.add(openPreferencesItem); + menu->Add(openPreferencesItem); - //menu.add(ContributionItemFactory.OPEN_WINDOWS.create(getWindow())); + menu->Add(berry::ContributionItemFactory::OPEN_WINDOWS->Create(window)); return menu; } void QmitkExtActionBarAdvisor::AddPerspectiveActions(berry::MenuManager* menu) { -// { -// QString openText = IDEWorkbenchMessages.Workbench_openPerspective; -// MenuManager changePerspMenuMgr = new MenuManager(openText, "openPerspective"); -// IContributionItem changePerspMenuItem = ContributionItemFactory.PERSPECTIVES_SHORTLIST -// .create(getWindow()); -// changePerspMenuMgr.add(changePerspMenuItem); -// menu.add(changePerspMenuMgr); -// } + { + berry::MenuManager::Pointer changePerspMenuMgr(new berry::MenuManager("Open Perspective", "openPerspective")); + berry::IContributionItem::Pointer changePerspMenuItem = + berry::ContributionItemFactory::PERSPECTIVES_SHORTLIST->Create(window); + changePerspMenuMgr->Add(changePerspMenuItem); + menu->Add(changePerspMenuMgr); + } { berry::MenuManager::Pointer showViewMenuMgr(new berry::MenuManager("Show &View", "showView")); berry::IContributionItem::Pointer showViewMenu = berry::ContributionItemFactory::VIEWS_SHORTLIST->Create(window); showViewMenuMgr->Add(showViewMenu); menu->Add(showViewMenuMgr); } - //menu.add(new Separator()); + menu->Add(berry::IContributionItem::Pointer(new berry::Separator())); //menu.add(editActionSetAction); - //menu.add(savePerspectiveAction); - //menu.add(resetPerspectiveAction); - //menu.add(closePerspAction); - //menu.add(closeAllPerspsAction); + menu->Add(GetItem(berry::IWorkbenchCommandConstants::WINDOW_SAVE_PERSPECTIVE_AS, "Save Serspective &As...")); + menu->Add(GetItem(berry::IWorkbenchCommandConstants::WINDOW_RESET_PERSPECTIVE, "&Reset Perspective...")); + menu->Add(GetItem(berry::IWorkbenchCommandConstants::WINDOW_CLOSE_PERSPECTIVE, "&Close Perspective")); + menu->Add(GetItem(berry::IWorkbenchCommandConstants::WINDOW_CLOSE_ALL_PERSPECTIVES, "Close All Perspectives")); +} + +berry::SmartPointer QmitkExtActionBarAdvisor::GetItem(const QString& commandId, const QString& label, + const QString& tooltip, const QIcon& icon) +{ + berry::CommandContributionItemParameter::Pointer param( + new berry::CommandContributionItemParameter(window, QString(), commandId, berry::CommandContributionItem::STYLE_PUSH)); + param->icon = icon; + param->label = label; + param->tooltip = tooltip; + berry::IContributionItem::Pointer item(new berry::CommandContributionItem(param)); + return item; } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.h index 416e09e8af..ded8432392 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.h +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionBarAdvisor.h @@ -1,57 +1,83 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKEXTACTIONBARADVISOR_H_ #define QMITKEXTACTIONBARADVISOR_H_ #include #include +#include + namespace berry { +struct IContributionItem; struct IWorkbenchWindow; class MenuManager; } class MITK_QT_COMMON_EXT_EXPORT QmitkExtActionBarAdvisor : public berry::ActionBarAdvisor { public: QmitkExtActionBarAdvisor(berry::SmartPointer configurer); protected: - void FillMenuBar(berry::IMenuManager* menuBar); + void MakeActions(berry::IWorkbenchWindow* window); + + void FillMenuBar(berry::IMenuManager* menuBar) override; + + void FillToolBar(berry::IToolBarManager* toolBar) override; private: + /** + * Creates and returns the File menu. + */ + berry::SmartPointer CreateFileMenu(); + + /** + * Creates and returns the Edit menu. + */ + berry::SmartPointer CreateEditMenu(); + /** * Creates and returns the Window menu. */ berry::SmartPointer CreateWindowMenu(); + /** + * Creates and returns the Help menu. + */ + berry::SmartPointer CreateHelpMenu(); + + /** * Adds the perspective actions to the specified menu. */ void AddPerspectiveActions(berry::MenuManager* menu); + berry::SmartPointer GetItem(const QString& commandId, const QString& label, + const QString& tooltip = QString(), const QIcon& icon = QIcon()); + berry::IWorkbenchWindow* window; }; #endif /*QMITKEXTACTIONBARADVISOR_H_*/ diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionConstants.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionConstants.h deleted file mode 100644 index 35729cc0df..0000000000 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionConstants.h +++ /dev/null @@ -1,145 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - - -#ifndef QMITKEXTACTIONCONSTANTS_H -#define QMITKEXTACTIONCONSTANTS_H - -#include - -#include - -/** - * Action ids for standard actions, groups in the workbench menu bar, and - * global actions. - *

- * This interface contains constants only; it is not intended to be implemented - * or extended. - *

- *

Standard menus

- *
    - *
  • File menu (M_FILE)
  • - *
  • Edit menu (M_EDIT)
  • - *
  • Window menu (M_WINDOW)
  • - *
  • Help menu (M_HELP)
  • - *
- *

Standard group for adding top level menus

- *
    - *
  • Extra top level menu group (MB_ADDITIONS)
  • - *
- *

Global actions

- *
    - *
  • Undo (UNDO)
  • - *
  • Redo (REDO)
  • - *
  • Cut (CUT)
  • - *
  • Copy (COPY)
  • - *
  • Paste (PASTE)
  • - *
  • Delete (DELETE)
  • - *
  • Find (FIND)
  • - *
  • Select All (SELECT_ALL)
  • - *
  • Add Bookmark (BOOKMARK)
  • - *
- *

Standard File menu actions

- *
    - *
  • Start group (FILE_START)
  • - *
  • End group (FILE_END)
  • - *
  • New action (NEW)
  • - *
  • Extra New-like action group (NEW_EXT)
  • - *
  • Close action (CLOSE)
  • - *
  • Close All action (CLOSE_ALL)
  • - *
  • Extra Close-like action group (CLOSE_EXT)
  • - *
  • Save action (SAVE)
  • - *
  • Save As action (SAVE_AS)
  • - *
  • Save All action (SAVE_ALL)
  • - *
  • Extra Save-like action group (SAVE_EXT)
  • - *
  • Import action (IMPORT)
  • - *
  • Export action (EXPORT)
  • - *
  • Extra Import-like action group (IMPORT_EXT)
  • - *
  • Quit action (QUIT)
  • - *
- *

Standard Edit menu actions

- *
    - *
  • Start group (EDIT_START)
  • - *
  • End group (EDIT_END)
  • - *
  • Undo global action (UNDO)
  • - *
  • Redo global action (REDO)
  • - *
  • Extra Undo-like action group (UNDO_EXT)
  • - *
  • Cut global action (CUT)
  • - *
  • Copy global action (COPY)
  • - *
  • Paste global action (PASTE)
  • - *
  • Extra Cut-like action group (CUT_EXT)
  • - *
  • Delete global action (DELETE)
  • - *
  • Find global action (FIND)
  • - *
  • Select All global action (SELECT_ALL)
  • - *
  • Bookmark global action (BOOKMARK)
  • - *
- *

Standard Perspective menu actions

- *
    - *
  • Extra Perspective-like action group (VIEW_EXT)
  • - *
- *

Standard Workbench menu actions

- *
    - *
  • Start group (WB_START)
  • - *
  • End group (WB_END)
  • - *
  • Extra Build-like action group (BUILD_EXT)
  • - *
  • Build action (BUILD)
  • - *
  • Rebuild All action (REBUILD_ALL)
  • - *
- *

Standard Window menu actions

- *
    - *
  • Extra Window-like action group (WINDOW_EXT)
  • - *
- *

Standard Help menu actions

- *
    - *
  • Start group (HELP_START)
  • - *
  • End group (HELP_END)
  • - *
  • About action (ABOUT)
  • - *
- *

Standard pop-up menu groups

- *
    - *
  • Managing group (GROUP_MANAGING)
  • - *
  • Reorganize group (GROUP_REORGANIZE)
  • - *
  • Add group (GROUP_ADD)
  • - *
  • File group (GROUP_FILE)
  • - *
- *

- * To hook a global action handler, a view should use the following code: - * - * IAction copyHandler = ...; - * view.getSite().getActionBars().setGlobalActionHandler( - * IWorkbenchActionConstants.COPY, - * copyHandler); - * - * For editors, this should be done in the IEditorActionBarContributor. - *

- * - * @see org.eclipse.ui.IActionBars#setGlobalActionHandler - * - * Note: many of the remaining non-deprecated constants here are IDE-specific - * and should be deprecated and moved to a constant pool at the IDE layer - * (e.g. IIDEActionConstants). - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -struct MITK_QT_COMMON_EXT_EXPORT QmitkExtActionConstants : public berry::WorkbenchActionConstants -{ - /** - * Name of standard Window menu (value "window"). - */ - static const QString M_WINDOW; // = "window" -}; - -#endif // QMITKEXTACTIONCONSTANTS_H diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.cpp index adaddbd4db..61691c5476 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.cpp @@ -1,167 +1,180 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkExtFileSaveProjectAction.h" #include "internal/QmitkCommonExtPlugin.h" #include #include #include #include #include #include #include #include #include #include #include #include #include +#include #include #include "berryPlatform.h" QmitkExtFileSaveProjectAction::QmitkExtFileSaveProjectAction(berry::IWorkbenchWindow::Pointer window) -: QAction(0) + : QAction(0) + , m_Window(nullptr) +{ + this->Init(window.GetPointer()); +} + +QmitkExtFileSaveProjectAction::QmitkExtFileSaveProjectAction(berry::IWorkbenchWindow* window) + : QAction(0) + , m_Window(nullptr) +{ + this->Init(window); +} + +void QmitkExtFileSaveProjectAction::Init(berry::IWorkbenchWindow* window) { m_Window = window; - this->setParent(static_cast(m_Window->GetShell()->GetControl())); this->setText("&Save Project..."); this->setToolTip("Save content of Data Manager as a .mitk project file"); - m_Window = window; this->connect(this, SIGNAL(triggered(bool)), this, SLOT(Run())); } + void QmitkExtFileSaveProjectAction::Run() { try { /** * @brief stores the last path of last saved file */ static QString m_LastPath; mitk::IDataStorageReference::Pointer dsRef; { ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); mitk::IDataStorageService* dss = 0; ctkServiceReference dsServiceRef = context->getServiceReference(); if (dsServiceRef) { dss = context->getService(dsServiceRef); } if (!dss) { QString msg = "IDataStorageService service not available. Unable to open files."; MITK_WARN << msg.toStdString(); QMessageBox::warning(QApplication::activeWindow(), "Unable to open files", msg); return; } // Get the active data storage (or the default one, if none is active) dsRef = dss->GetDataStorage(); context->ungetService(dsServiceRef); } mitk::DataStorage::Pointer storage = dsRef->GetDataStorage(); QString dialogTitle = "Save MITK Scene (%1)"; QString fileName = QFileDialog::getSaveFileName(NULL, dialogTitle.arg(dsRef->GetLabel()), m_LastPath, "MITK scene files (*.mitk)", NULL ); if (fileName.isEmpty() ) return; // remember the location m_LastPath = fileName; if ( fileName.right(5) != ".mitk" ) fileName += ".mitk"; mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New(); mitk::ProgressBar::GetInstance()->AddStepsToDo(2); /* Build list of nodes that should be saved */ mitk::NodePredicateNot::Pointer isNotHelperObject = mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object", mitk::BoolProperty::New(true))); mitk::DataStorage::SetOfObjects::ConstPointer nodesToBeSaved = storage->GetSubset(isNotHelperObject); if ( !sceneIO->SaveScene( nodesToBeSaved, storage, fileName.toStdString() ) ) { QMessageBox::information(NULL, "Scene saving", "Scene could not be written completely. Please check the log.", QMessageBox::Ok); } mitk::ProgressBar::GetInstance()->Progress(2); mitk::SceneIO::FailedBaseDataListType::ConstPointer failedNodes = sceneIO->GetFailedNodes(); if (!failedNodes->empty()) { std::stringstream ss; ss << "The following nodes could not be serialized:" << std::endl; for ( mitk::SceneIO::FailedBaseDataListType::const_iterator iter = failedNodes->begin(); iter != failedNodes->end(); ++iter ) { ss << " - "; if ( mitk::BaseData* data =(*iter)->GetData() ) { ss << data->GetNameOfClass(); } else { ss << "(NULL)"; } ss << " contained in node '" << (*iter)->GetName() << "'" << std::endl; } MITK_WARN << ss.str(); } mitk::PropertyList::ConstPointer failedProperties = sceneIO->GetFailedProperties(); if (!failedProperties->GetMap()->empty()) { std::stringstream ss; ss << "The following properties could not be serialized:" << std::endl; const mitk::PropertyList::PropertyMap* propmap = failedProperties->GetMap(); for ( mitk::PropertyList::PropertyMap::const_iterator iter = propmap->begin(); iter != propmap->end(); ++iter ) { ss << " - " << iter->second->GetNameOfClass() << " associated to key '" << iter->first << "'" << std::endl; } MITK_WARN << ss.str(); } } catch (std::exception& e) { MITK_ERROR << "Exception caught during scene saving: " << e.what(); } } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.h b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.h index a70e3ee443..0fc9ff2825 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.h +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtFileSaveProjectAction.h @@ -1,51 +1,58 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkExtFileSaveProjectAction_H_ #define QmitkExtFileSaveProjectAction_H_ #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 + +namespace berry { +struct IWorkbenchWindow; +} class MITK_QT_COMMON_EXT_EXPORT QmitkExtFileSaveProjectAction : public QAction { Q_OBJECT public: - QmitkExtFileSaveProjectAction(berry::IWorkbenchWindow::Pointer window); + QmitkExtFileSaveProjectAction(berry::SmartPointer window); + QmitkExtFileSaveProjectAction(berry::IWorkbenchWindow* window); protected slots: void Run(); private: - berry::IWorkbenchWindow::Pointer m_Window; + void Init(berry::IWorkbenchWindow* window); + + berry::IWorkbenchWindow* m_Window; }; #endif /*QmitkExtFileSaveProjectAction_H_*/ diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp index 4f40e01d40..2c611d04e3 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/QmitkExtWorkbenchWindowAdvisor.cpp @@ -1,1363 +1,1376 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkExtWorkbenchWindowAdvisor.h" #include "QmitkExtActionBarAdvisor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // UGLYYY #include "internal/QmitkExtWorkbenchWindowAdvisorHack.h" #include "internal/QmitkCommonExtPlugin.h" #include "mitkUndoController.h" #include "mitkVerboseLimitedLinearUndo.h" #include #include #include #include QmitkExtWorkbenchWindowAdvisorHack * QmitkExtWorkbenchWindowAdvisorHack::undohack = new QmitkExtWorkbenchWindowAdvisorHack(); QString QmitkExtWorkbenchWindowAdvisor::QT_SETTINGS_FILENAME = "QtSettings.ini"; +static bool USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS = false; + class PartListenerForTitle: public berry::IPartListener { public: PartListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPartEventTypes() const { return Events::ACTIVATED | Events::BROUGHT_TO_TOP | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartActivated(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref.Cast ()) { windowAdvisor->UpdateTitle(false); } } void PartBroughtToTop(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref.Cast ()) { windowAdvisor->UpdateTitle(false); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& /*ref*/) { windowAdvisor->UpdateTitle(false); } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) { if (!windowAdvisor->lastActiveEditor.Expired() && ref->GetPart(false) == windowAdvisor->lastActiveEditor.Lock()) { windowAdvisor->UpdateTitle(true); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) { if (!windowAdvisor->lastActiveEditor.Expired() && ref->GetPart(false) == windowAdvisor->lastActiveEditor.Lock()) { windowAdvisor->UpdateTitle(false); } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; }; class PartListenerForViewNavigator: public berry::IPartListener { public: PartListenerForViewNavigator(QAction* act) : viewNavigatorAction(act) { } Events::Types GetPartEventTypes() const { return Events::OPENED | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartOpened(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.viewnavigatorview") { viewNavigatorAction->setChecked(true); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.viewnavigatorview") { viewNavigatorAction->setChecked(false); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.viewnavigatorview") { viewNavigatorAction->setChecked(true); } } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.viewnavigatorview") { viewNavigatorAction->setChecked(false); } } private: QAction* viewNavigatorAction; }; class PartListenerForImageNavigator: public berry::IPartListener { public: PartListenerForImageNavigator(QAction* act) : imageNavigatorAction(act) { } Events::Types GetPartEventTypes() const { return Events::OPENED | Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartOpened(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartClosed(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(true); } } void PartHidden(const berry::IWorkbenchPartReference::Pointer& ref) { if (ref->GetId()=="org.mitk.views.imagenavigator") { imageNavigatorAction->setChecked(false); } } private: QAction* imageNavigatorAction; }; class PerspectiveListenerForTitle: public berry::IPerspectiveListener { public: PerspectiveListenerForTitle(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa), perspectivesClosed(false) { } Events::Types GetPerspectiveEventTypes() const { - return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED - // remove the following line when command framework is finished - | Events::CLOSED | Events::OPENED; + if (USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS) + { + return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED; + } + else + { + return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED + | Events::CLOSED | Events::OPENED; + } } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveSavedAs(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*oldPerspective*/, const berry::IPerspectiveDescriptor::Pointer& /*newPerspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { windowAdvisor->UpdateTitle(false); } void PerspectiveOpened(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { if (perspectivesClosed) { QListIterator i(windowAdvisor->viewActions); while (i.hasNext()) { i.next()->setEnabled(true); } //GetViewRegistry()->Find("org.mitk.views.imagenavigator"); if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) { windowAdvisor->openDicomEditorAction->setEnabled(true); } if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.xnat.browser")) { windowAdvisor->openXnatEditorAction->setEnabled(true); } windowAdvisor->fileSaveProjectAction->setEnabled(true); windowAdvisor->closeProjectAction->setEnabled(true); windowAdvisor->undoAction->setEnabled(true); windowAdvisor->redoAction->setEnabled(true); windowAdvisor->imageNavigatorAction->setEnabled(true); windowAdvisor->viewNavigatorAction->setEnabled(true); windowAdvisor->resetPerspAction->setEnabled(true); if( windowAdvisor->GetShowClosePerspectiveMenuItem() ) { windowAdvisor->closePerspAction->setEnabled(true); } } perspectivesClosed = false; } void PerspectiveClosed(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { berry::IWorkbenchWindow::Pointer wnd = windowAdvisor->GetWindowConfigurer()->GetWindow(); bool allClosed = true; if (wnd->GetActivePage()) { QList perspectives(wnd->GetActivePage()->GetOpenPerspectives()); allClosed = perspectives.empty(); } if (allClosed) { perspectivesClosed = true; QListIterator i(windowAdvisor->viewActions); while (i.hasNext()) { i.next()->setEnabled(false); } if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) { windowAdvisor->openDicomEditorAction->setEnabled(false); } if(windowAdvisor->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.xnat.browser")) { windowAdvisor->openXnatEditorAction->setEnabled(false); } windowAdvisor->fileSaveProjectAction->setEnabled(false); windowAdvisor->closeProjectAction->setEnabled(false); windowAdvisor->undoAction->setEnabled(false); windowAdvisor->redoAction->setEnabled(false); windowAdvisor->imageNavigatorAction->setEnabled(false); windowAdvisor->viewNavigatorAction->setEnabled(false); windowAdvisor->resetPerspAction->setEnabled(false); if( windowAdvisor->GetShowClosePerspectiveMenuItem() ) { windowAdvisor->closePerspAction->setEnabled(false); } } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; bool perspectivesClosed; }; class PerspectiveListenerForMenu: public berry::IPerspectiveListener { public: PerspectiveListenerForMenu(QmitkExtWorkbenchWindowAdvisor* wa) : windowAdvisor(wa) { } Events::Types GetPerspectiveEventTypes() const { return Events::ACTIVATED | Events::DEACTIVATED; } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& perspective) { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(true); } } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& perspective) { QAction* action = windowAdvisor->mapPerspIdToAction[perspective->GetId()]; if (action) { action->setChecked(false); } } private: QmitkExtWorkbenchWindowAdvisor* windowAdvisor; }; QmitkExtWorkbenchWindowAdvisor::QmitkExtWorkbenchWindowAdvisor(berry::WorkbenchAdvisor* wbAdvisor, berry::IWorkbenchWindowConfigurer::Pointer configurer) : berry::WorkbenchWindowAdvisor(configurer), lastInput(0), wbAdvisor(wbAdvisor), showViewToolbar(true), showPerspectiveToolbar(false), showVersionInfo(true), showMitkVersionInfo(true), showViewMenuItem(true), showNewWindowMenuItem(false), showClosePerspectiveMenuItem(true), viewNavigatorFound(false), showMemoryIndicator(true), dropTargetListener(new QmitkDefaultDropTargetListener) { productName = QCoreApplication::applicationName(); viewExcludeList.push_back("org.mitk.views.viewnavigatorview"); } QmitkExtWorkbenchWindowAdvisor::~QmitkExtWorkbenchWindowAdvisor() { } berry::ActionBarAdvisor::Pointer QmitkExtWorkbenchWindowAdvisor::CreateActionBarAdvisor( berry::IActionBarConfigurer::Pointer configurer) { - //berry::ActionBarAdvisor::Pointer actionBarAdvisor( - // new QmitkExtActionBarAdvisor(configurer)); - //return actionBarAdvisor; - return berry::WorkbenchWindowAdvisor::CreateActionBarAdvisor(configurer); + if (USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS) + { + berry::ActionBarAdvisor::Pointer actionBarAdvisor( + new QmitkExtActionBarAdvisor(configurer)); + return actionBarAdvisor; + } + else + { + return berry::WorkbenchWindowAdvisor::CreateActionBarAdvisor(configurer); + } } QWidget* QmitkExtWorkbenchWindowAdvisor::CreateEmptyWindowContents(QWidget* parent) { QWidget* parentWidget = static_cast(parent); QLabel* label = new QLabel(parentWidget); label->setText("No perspectives are open. Open a perspective in the Window->Open Perspective menu."); label->setContentsMargins(10,10,10,10); label->setAlignment(Qt::AlignTop); label->setEnabled(false); parentWidget->layout()->addWidget(label); return label; } void QmitkExtWorkbenchWindowAdvisor::ShowClosePerspectiveMenuItem(bool show) { showClosePerspectiveMenuItem = show; } bool QmitkExtWorkbenchWindowAdvisor::GetShowClosePerspectiveMenuItem() { return showClosePerspectiveMenuItem; } void QmitkExtWorkbenchWindowAdvisor::ShowMemoryIndicator(bool show) { showMemoryIndicator = show; } bool QmitkExtWorkbenchWindowAdvisor::GetShowMemoryIndicator() { return showMemoryIndicator; } void QmitkExtWorkbenchWindowAdvisor::ShowNewWindowMenuItem(bool show) { showNewWindowMenuItem = show; } void QmitkExtWorkbenchWindowAdvisor::ShowViewToolbar(bool show) { showViewToolbar = show; } void QmitkExtWorkbenchWindowAdvisor::ShowViewMenuItem(bool show) { showViewMenuItem = show; } void QmitkExtWorkbenchWindowAdvisor::ShowPerspectiveToolbar(bool show) { showPerspectiveToolbar = show; } void QmitkExtWorkbenchWindowAdvisor::ShowVersionInfo(bool show) { showVersionInfo = show; } void QmitkExtWorkbenchWindowAdvisor::ShowMitkVersionInfo(bool show) { showMitkVersionInfo = show; } void QmitkExtWorkbenchWindowAdvisor::SetProductName(const QString& product) { productName = product; } void QmitkExtWorkbenchWindowAdvisor::SetWindowIcon(const QString& wndIcon) { windowIcon = wndIcon; } void QmitkExtWorkbenchWindowAdvisor::PostWindowCreate() { - // very bad hack... - berry::IWorkbenchWindow::Pointer window = - this->GetWindowConfigurer()->GetWindow(); - QMainWindow* mainWindow = - qobject_cast (window->GetShell()->GetControl()); - - window->SetPerspectiveExcludeList(perspectiveExcludeList); - window->SetViewExcludeList(viewExcludeList); + // very bad hack... + berry::IWorkbenchWindow::Pointer window = + this->GetWindowConfigurer()->GetWindow(); + QMainWindow* mainWindow = + qobject_cast (window->GetShell()->GetControl()); - if (!windowIcon.isEmpty()) - { - mainWindow->setWindowIcon(QIcon(windowIcon)); - } - mainWindow->setContextMenuPolicy(Qt::PreventContextMenu); + if (!windowIcon.isEmpty()) + { + mainWindow->setWindowIcon(QIcon(windowIcon)); + } + mainWindow->setContextMenuPolicy(Qt::PreventContextMenu); - /*mainWindow->setStyleSheet("color: white;" + /*mainWindow->setStyleSheet("color: white;" "background-color: #808080;" "selection-color: #659EC7;" "selection-background-color: #808080;" " QMenuBar {" "background-color: #808080; }");*/ - // Load selected icon theme + // Load selected icon theme - QStringList searchPaths = QIcon::themeSearchPaths(); - searchPaths.push_front( QString(":/org_mitk_icons/icons/") ); - QIcon::setThemeSearchPaths( searchPaths ); + QStringList searchPaths = QIcon::themeSearchPaths(); + searchPaths.push_front( QString(":/org_mitk_icons/icons/") ); + QIcon::setThemeSearchPaths( searchPaths ); - berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); - berry::IPreferences::Pointer stylePref = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); - QString iconTheme = stylePref->Get(berry::QtPreferences::QT_ICON_THEME, "<>"); - if( iconTheme == QString( "<>" ) ) - { - iconTheme = QString( "tango" ); - } - QIcon::setThemeName( iconTheme ); + berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); + berry::IPreferences::Pointer stylePref = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); + QString iconTheme = stylePref->Get(berry::QtPreferences::QT_ICON_THEME, "<>"); + if( iconTheme == QString( "<>" ) ) + { + iconTheme = QString( "tango" ); + } + QIcon::setThemeName( iconTheme ); - // ==== Application menu ============================ + // ==== Application menu ============================ - QMenuBar* menuBar = mainWindow->menuBar(); - menuBar->setContextMenuPolicy(Qt::PreventContextMenu); + if (!USE_EXPERIMENTAL_COMMAND_CONTRIBUTIONS) + { + QMenuBar* menuBar = mainWindow->menuBar(); + menuBar->setContextMenuPolicy(Qt::PreventContextMenu); #ifdef __APPLE__ - menuBar->setNativeMenuBar(true); + menuBar->setNativeMenuBar(true); #else - menuBar->setNativeMenuBar(false); + menuBar->setNativeMenuBar(false); #endif - QMenu* fileMenu = menuBar->addMenu("&File"); - fileMenu->setObjectName("FileMenu"); + QMenu* fileMenu = menuBar->addMenu("&File"); + fileMenu->setObjectName("FileMenu"); QAction* fileOpenAction = new QmitkFileOpenAction(QIcon::fromTheme("document-open",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/document-open.svg")), window); fileOpenAction->setShortcut(QKeySequence::Open); - fileMenu->addAction(fileOpenAction); + fileMenu->addAction(fileOpenAction); QAction* fileSaveAction = new QmitkFileSaveAction(QIcon(":/org.mitk.gui.qt.ext/Save_48.png"), window); fileSaveAction->setShortcut(QKeySequence::Save); fileMenu->addAction(fileSaveAction); - fileSaveProjectAction = new QmitkExtFileSaveProjectAction(window); + fileSaveProjectAction = new QmitkExtFileSaveProjectAction(window); fileSaveProjectAction->setIcon(QIcon::fromTheme("document-save",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/document-save.svg"))); - fileMenu->addAction(fileSaveProjectAction); - closeProjectAction = new QmitkCloseProjectAction(window); + fileMenu->addAction(fileSaveProjectAction); + closeProjectAction = new QmitkCloseProjectAction(window); closeProjectAction->setIcon(QIcon::fromTheme("edit-delete",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/edit-delete.svg"))); - fileMenu->addAction(closeProjectAction); - fileMenu->addSeparator(); - QAction* fileExitAction = new QmitkFileExitAction(window); + fileMenu->addAction(closeProjectAction); + fileMenu->addSeparator(); + QAction* fileExitAction = new QmitkFileExitAction(window); fileExitAction->setIcon(QIcon::fromTheme("system-log-out",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/system-log-out.svg"))); fileExitAction->setShortcut(QKeySequence::Quit); - fileExitAction->setObjectName("QmitkFileExitAction"); - fileMenu->addAction(fileExitAction); + fileExitAction->setObjectName("QmitkFileExitAction"); + fileMenu->addAction(fileExitAction); -if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) -{ - openDicomEditorAction = new QmitkOpenDicomEditorAction(QIcon(":/org.mitk.gui.qt.ext/dcm-icon.png"),window); -} + if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) + { + openDicomEditorAction = new QmitkOpenDicomEditorAction(QIcon(":/org.mitk.gui.qt.ext/dcm-icon.png"),window); + } if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.xnat.browser")) { - openXnatEditorAction = new QmitkOpenXnatEditorAction(QIcon(":/org.mitk.gui.qt.ext/xnat-icon.png"),window); + openXnatEditorAction = new QmitkOpenXnatEditorAction(QIcon(":/org.mitk.gui.qt.ext/xnat-icon.png"),window); } - berry::IViewRegistry* viewRegistry = - berry::PlatformUI::GetWorkbench()->GetViewRegistry(); - const QList viewDescriptors = viewRegistry->GetViews(); + berry::IViewRegistry* viewRegistry = + berry::PlatformUI::GetWorkbench()->GetViewRegistry(); + const QList viewDescriptors = viewRegistry->GetViews(); - // another bad hack to get an edit/undo menu... - QMenu* editMenu = menuBar->addMenu("&Edit"); + // another bad hack to get an edit/undo menu... + QMenu* editMenu = menuBar->addMenu("&Edit"); undoAction = editMenu->addAction(QIcon::fromTheme("edit-undo",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/edit-undo.svg")), - "&Undo", - QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onUndo()), - QKeySequence("CTRL+Z")); - undoAction->setToolTip("Undo the last action (not supported by all modules)"); + "&Undo", + QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onUndo()), + QKeySequence("CTRL+Z")); + undoAction->setToolTip("Undo the last action (not supported by all modules)"); redoAction = editMenu->addAction(QIcon::fromTheme("edit-redo",QIcon(":/org_mitk_icons/icons/tango/scalable/actions/edit-redo.svg")) - , "&Redo", - QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onRedo()), - QKeySequence("CTRL+Y")); - redoAction->setToolTip("execute the last action that was undone again (not supported by all modules)"); - - imageNavigatorAction = new QAction(QIcon(":/org.mitk.gui.qt.ext/Slider.png"), "&Image Navigator", NULL); - bool imageNavigatorViewFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.imagenavigator"); - if (imageNavigatorViewFound) - { - QObject::connect(imageNavigatorAction, SIGNAL(triggered(bool)), QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onImageNavigator())); - imageNavigatorAction->setCheckable(true); - - // add part listener for image navigator - imageNavigatorPartListener.reset(new PartListenerForImageNavigator(imageNavigatorAction)); - window->GetPartService()->AddPartListener(imageNavigatorPartListener.data()); - berry::IViewPart::Pointer imageNavigatorView = - window->GetActivePage()->FindView("org.mitk.views.imagenavigator"); - imageNavigatorAction->setChecked(false); - if (imageNavigatorView) - { - bool isImageNavigatorVisible = window->GetActivePage()->IsPartVisible(imageNavigatorView); - if (isImageNavigatorVisible) - imageNavigatorAction->setChecked(true); - } - imageNavigatorAction->setToolTip("Toggle image navigator for navigating through image"); + , "&Redo", + QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onRedo()), + QKeySequence("CTRL+Y")); + redoAction->setToolTip("execute the last action that was undone again (not supported by all modules)"); + + imageNavigatorAction = new QAction(QIcon(":/org.mitk.gui.qt.ext/Slider.png"), "&Image Navigator", NULL); + bool imageNavigatorViewFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.imagenavigator"); + if (imageNavigatorViewFound) + { + QObject::connect(imageNavigatorAction, SIGNAL(triggered(bool)), QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onImageNavigator())); + imageNavigatorAction->setCheckable(true); + + // add part listener for image navigator + imageNavigatorPartListener.reset(new PartListenerForImageNavigator(imageNavigatorAction)); + window->GetPartService()->AddPartListener(imageNavigatorPartListener.data()); + berry::IViewPart::Pointer imageNavigatorView = + window->GetActivePage()->FindView("org.mitk.views.imagenavigator"); + imageNavigatorAction->setChecked(false); + if (imageNavigatorView) + { + bool isImageNavigatorVisible = window->GetActivePage()->IsPartVisible(imageNavigatorView); + if (isImageNavigatorVisible) + imageNavigatorAction->setChecked(true); + } + imageNavigatorAction->setToolTip("Toggle image navigator for navigating through image"); } viewNavigatorAction = new QAction(QIcon(":/org.mitk.gui.qt.ext/view-manager_48.png"),"&View Navigator", NULL); viewNavigatorFound = window->GetWorkbench()->GetViewRegistry()->Find("org.mitk.views.viewnavigatorview"); if (viewNavigatorFound) { - QObject::connect(viewNavigatorAction, SIGNAL(triggered(bool)), QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onViewNavigator())); - viewNavigatorAction->setCheckable(true); - - // add part listener for view navigator - viewNavigatorPartListener.reset(new PartListenerForViewNavigator(viewNavigatorAction)); - window->GetPartService()->AddPartListener(viewNavigatorPartListener.data()); - berry::IViewPart::Pointer viewnavigatorview = - window->GetActivePage()->FindView("org.mitk.views.viewnavigatorview"); - viewNavigatorAction->setChecked(false); - if (viewnavigatorview) - { - bool isViewNavigatorVisible = window->GetActivePage()->IsPartVisible(viewnavigatorview); - if (isViewNavigatorVisible) - viewNavigatorAction->setChecked(true); - } - viewNavigatorAction->setToolTip("Toggle View Navigator"); - } + QObject::connect(viewNavigatorAction, SIGNAL(triggered(bool)), QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onViewNavigator())); + viewNavigatorAction->setCheckable(true); + + // add part listener for view navigator + viewNavigatorPartListener.reset(new PartListenerForViewNavigator(viewNavigatorAction)); + window->GetPartService()->AddPartListener(viewNavigatorPartListener.data()); + berry::IViewPart::Pointer viewnavigatorview = + window->GetActivePage()->FindView("org.mitk.views.viewnavigatorview"); + viewNavigatorAction->setChecked(false); + if (viewnavigatorview) + { + bool isViewNavigatorVisible = window->GetActivePage()->IsPartVisible(viewnavigatorview); + if (isViewNavigatorVisible) + viewNavigatorAction->setChecked(true); + } + viewNavigatorAction->setToolTip("Toggle View Navigator"); + } - // toolbar for showing file open, undo, redo and other main actions - QToolBar* mainActionsToolBar = new QToolBar; + // toolbar for showing file open, undo, redo and other main actions + QToolBar* mainActionsToolBar = new QToolBar; mainActionsToolBar->setObjectName("mainActionsToolBar"); - mainActionsToolBar->setContextMenuPolicy(Qt::PreventContextMenu); + mainActionsToolBar->setContextMenuPolicy(Qt::PreventContextMenu); #ifdef __APPLE__ - mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon ); + mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon ); #else - mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon ); + mainActionsToolBar->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon ); #endif - mainActionsToolBar->addAction(fileOpenAction); - mainActionsToolBar->addAction(fileSaveProjectAction); - mainActionsToolBar->addAction(closeProjectAction); - mainActionsToolBar->addAction(undoAction); - mainActionsToolBar->addAction(redoAction); -if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) -{ - mainActionsToolBar->addAction(openDicomEditorAction); -} + mainActionsToolBar->addAction(fileOpenAction); + mainActionsToolBar->addAction(fileSaveProjectAction); + mainActionsToolBar->addAction(closeProjectAction); + mainActionsToolBar->addAction(undoAction); + mainActionsToolBar->addAction(redoAction); + if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.dicomeditor")) + { + mainActionsToolBar->addAction(openDicomEditorAction); + } if(this->GetWindowConfigurer()->GetWindow()->GetWorkbench()->GetEditorRegistry()->FindEditor("org.mitk.editors.xnat.browser")) { - mainActionsToolBar->addAction(openXnatEditorAction); + mainActionsToolBar->addAction(openXnatEditorAction); + } + if (imageNavigatorViewFound) + { + mainActionsToolBar->addAction(imageNavigatorAction); } - if (imageNavigatorViewFound) - { - mainActionsToolBar->addAction(imageNavigatorAction); - } if (viewNavigatorFound) - mainActionsToolBar->addAction(viewNavigatorAction); - mainWindow->addToolBar(mainActionsToolBar); + mainActionsToolBar->addAction(viewNavigatorAction); + mainWindow->addToolBar(mainActionsToolBar); #ifdef __APPLE__ #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) - mainWindow->setUnifiedTitleAndToolBarOnMac(true); + mainWindow->setUnifiedTitleAndToolBarOnMac(true); // default is false #endif #endif - // ==== Window Menu ========================== - QMenu* windowMenu = menuBar->addMenu("Window"); - if (showNewWindowMenuItem) - { - windowMenu->addAction("&New Window", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onNewWindow())); - windowMenu->addSeparator(); - } + // ==== Window Menu ========================== + QMenu* windowMenu = menuBar->addMenu("Window"); + if (showNewWindowMenuItem) + { + windowMenu->addAction("&New Window", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onNewWindow())); + windowMenu->addSeparator(); + } - QMenu* perspMenu = windowMenu->addMenu("&Open Perspective"); + QMenu* perspMenu = windowMenu->addMenu("&Open Perspective"); - QMenu* viewMenu; - if (showViewMenuItem) - { - viewMenu = windowMenu->addMenu("Show &View"); - viewMenu->setObjectName("Show View"); - } - windowMenu->addSeparator(); - resetPerspAction = windowMenu->addAction("&Reset Perspective", - QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onResetPerspective())); + QMenu* viewMenu; + if (showViewMenuItem) + { + viewMenu = windowMenu->addMenu("Show &View"); + viewMenu->setObjectName("Show View"); + } + windowMenu->addSeparator(); + resetPerspAction = windowMenu->addAction("&Reset Perspective", + QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onResetPerspective())); - if(showClosePerspectiveMenuItem) - closePerspAction = windowMenu->addAction("&Close Perspective", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onClosePerspective())); + if(showClosePerspectiveMenuItem) + closePerspAction = windowMenu->addAction("&Close Perspective", QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onClosePerspective())); - windowMenu->addSeparator(); - windowMenu->addAction("&Preferences...", - QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onEditPreferences()), - QKeySequence("CTRL+P")); + windowMenu->addSeparator(); + windowMenu->addAction("&Preferences...", + QmitkExtWorkbenchWindowAdvisorHack::undohack, SLOT(onEditPreferences()), + QKeySequence("CTRL+P")); - // fill perspective menu - berry::IPerspectiveRegistry* perspRegistry = - window->GetWorkbench()->GetPerspectiveRegistry(); - QActionGroup* perspGroup = new QActionGroup(menuBar); + // fill perspective menu + berry::IPerspectiveRegistry* perspRegistry = + window->GetWorkbench()->GetPerspectiveRegistry(); + QActionGroup* perspGroup = new QActionGroup(menuBar); - QList perspectives( - perspRegistry->GetPerspectives()); + QList perspectives( + perspRegistry->GetPerspectives()); bool skip = false; for (QList::iterator perspIt = - perspectives.begin(); perspIt != perspectives.end(); ++perspIt) + perspectives.begin(); perspIt != perspectives.end(); ++perspIt) { // if perspectiveExcludeList is set, it contains the id-strings of perspectives, which // should not appear as an menu-entry in the perspective menu if (perspectiveExcludeList.size() > 0) { for (int i=0; iGetId()) { skip = true; break; } } if (skip) { skip = false; continue; } } QAction* perspAction = new berry::QtOpenPerspectiveAction(window, - *perspIt, perspGroup); + *perspIt, perspGroup); mapPerspIdToAction.insert((*perspIt)->GetId(), perspAction); } - perspMenu->addActions(perspGroup->actions()); + perspMenu->addActions(perspGroup->actions()); - // sort elements (converting vector to map...) - QList::const_iterator iter; - std::map VDMap; + // sort elements (converting vector to map...) + QList::const_iterator iter; + std::map VDMap; - skip = false; - for (iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter) - { + skip = false; + for (iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter) + { - // if viewExcludeList is set, it contains the id-strings of view, which - // should not appear as an menu-entry in the menu - if (viewExcludeList.size() > 0) - { - for (int i=0; iGetId()) - { - skip = true; - break; - } - } - if (skip) - { - skip = false; - continue; - } - } + // if viewExcludeList is set, it contains the id-strings of view, which + // should not appear as an menu-entry in the menu + if (viewExcludeList.size() > 0) + { + for (int i=0; iGetId()) + { + skip = true; + break; + } + } + if (skip) + { + skip = false; + continue; + } + } - if ((*iter)->GetId() == "org.blueberry.ui.internal.introview") - continue; - if ((*iter)->GetId() == "org.mitk.views.imagenavigator") - continue; - if ((*iter)->GetId() == "org.mitk.views.viewnavigatorview") - continue; + if ((*iter)->GetId() == "org.blueberry.ui.internal.introview") + continue; + if ((*iter)->GetId() == "org.mitk.views.imagenavigator") + continue; + if ((*iter)->GetId() == "org.mitk.views.viewnavigatorview") + continue; - std::pair p( - (*iter)->GetLabel(), (*iter)); - VDMap.insert(p); - } + std::pair p( + (*iter)->GetLabel(), (*iter)); + VDMap.insert(p); + } - // ==== Perspective Toolbar ================================== - QToolBar* qPerspectiveToolbar = new QToolBar; + // ==== Perspective Toolbar ================================== + QToolBar* qPerspectiveToolbar = new QToolBar; qPerspectiveToolbar->setObjectName("perspectiveToolBar"); - if (showPerspectiveToolbar) - { - qPerspectiveToolbar->addActions(perspGroup->actions()); - mainWindow->addToolBar(qPerspectiveToolbar); - } - else - delete qPerspectiveToolbar; + if (showPerspectiveToolbar) + { + qPerspectiveToolbar->addActions(perspGroup->actions()); + mainWindow->addToolBar(qPerspectiveToolbar); + } + else + delete qPerspectiveToolbar; - // ==== View Toolbar ================================== - QToolBar* qToolbar = new QToolBar; + // ==== View Toolbar ================================== + QToolBar* qToolbar = new QToolBar; qToolbar->setObjectName("viewToolBar"); - std::map::const_iterator - MapIter; - for (MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter) - { - berry::QtShowViewAction* viewAction = new berry::QtShowViewAction(window, - (*MapIter).second); - viewActions.push_back(viewAction); - if(showViewMenuItem) - viewMenu->addAction(viewAction); - if (showViewToolbar) - { - qToolbar->addAction(viewAction); - } - } + std::map::const_iterator + MapIter; + for (MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter) + { + berry::QtShowViewAction* viewAction = new berry::QtShowViewAction(window, + (*MapIter).second); + viewActions.push_back(viewAction); + if(showViewMenuItem) + viewMenu->addAction(viewAction); + if (showViewToolbar) + { + qToolbar->addAction(viewAction); + } + } - if (showViewToolbar) - { - mainWindow->addToolBar(qToolbar); - } - else - delete qToolbar; + if (showViewToolbar) + { + mainWindow->addToolBar(qToolbar); + } + else + delete qToolbar; - QSettings settings(GetQSettingsFile(), QSettings::IniFormat); - mainWindow->restoreState(settings.value("ToolbarPosition").toByteArray()); + QSettings settings(GetQSettingsFile(), QSettings::IniFormat); + mainWindow->restoreState(settings.value("ToolbarPosition").toByteArray()); - // ===== Help menu ==================================== - QMenu* helpMenu = menuBar->addMenu("&Help"); - helpMenu->addAction("&Welcome",this, SLOT(onIntro())); - helpMenu->addAction("&Open Help Perspective", this, SLOT(onHelpOpenHelpPerspective())); - helpMenu->addAction("&Context Help",this, SLOT(onHelp()), QKeySequence("F1")); - helpMenu->addAction("&About",this, SLOT(onAbout())); - // ===================================================== + // ===== Help menu ==================================== + QMenu* helpMenu = menuBar->addMenu("&Help"); + helpMenu->addAction("&Welcome",this, SLOT(onIntro())); + helpMenu->addAction("&Open Help Perspective", this, SLOT(onHelpOpenHelpPerspective())); + helpMenu->addAction("&Context Help",this, SLOT(onHelp()), QKeySequence("F1")); + helpMenu->addAction("&About",this, SLOT(onAbout())); + // ===================================================== - QStatusBar* qStatusBar = new QStatusBar(); + QStatusBar* qStatusBar = new QStatusBar(); - //creating a QmitkStatusBar for Output on the QStatusBar and connecting it with the MainStatusBar - QmitkStatusBar *statusBar = new QmitkStatusBar(qStatusBar); - //disabling the SizeGrip in the lower right corner - statusBar->SetSizeGripEnabled(false); + //creating a QmitkStatusBar for Output on the QStatusBar and connecting it with the MainStatusBar + QmitkStatusBar *statusBar = new QmitkStatusBar(qStatusBar); + //disabling the SizeGrip in the lower right corner + statusBar->SetSizeGripEnabled(false); - QmitkProgressBar *progBar = new QmitkProgressBar(); + QmitkProgressBar *progBar = new QmitkProgressBar(); - qStatusBar->addPermanentWidget(progBar, 0); - progBar->hide(); -// progBar->AddStepsToDo(2); -// progBar->Progress(1); + qStatusBar->addPermanentWidget(progBar, 0); + progBar->hide(); + // progBar->AddStepsToDo(2); + // progBar->Progress(1); - mainWindow->setStatusBar(qStatusBar); + mainWindow->setStatusBar(qStatusBar); if (showMemoryIndicator) { - QmitkMemoryUsageIndicatorView* memoryIndicator = new QmitkMemoryUsageIndicatorView(); - qStatusBar->addPermanentWidget(memoryIndicator, 0); + QmitkMemoryUsageIndicatorView* memoryIndicator = new QmitkMemoryUsageIndicatorView(); + qStatusBar->addPermanentWidget(memoryIndicator, 0); } - + } } void QmitkExtWorkbenchWindowAdvisor::PreWindowOpen() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); // show the shortcut bar and progress indicator, which are hidden by // default //configurer->SetShowPerspectiveBar(true); //configurer->SetShowFastViewBars(true); //configurer->SetShowProgressIndicator(true); // // add the drag and drop support for the editor area // configurer.addEditorAreaTransfer(EditorInputTransfer.getInstance()); // configurer.addEditorAreaTransfer(ResourceTransfer.getInstance()); // configurer.addEditorAreaTransfer(FileTransfer.getInstance()); // configurer.addEditorAreaTransfer(MarkerTransfer.getInstance()); // configurer.configureEditorAreaDropListener(new EditorAreaDropAdapter( // configurer.getWindow())); this->HookTitleUpdateListeners(configurer); menuPerspectiveListener.reset(new PerspectiveListenerForMenu(this)); configurer->GetWindow()->AddPerspectiveListener(menuPerspectiveListener.data()); configurer->AddEditorAreaTransfer(QStringList("text/uri-list")); configurer->ConfigureEditorAreaDropListener(dropTargetListener.data()); } void QmitkExtWorkbenchWindowAdvisor::PostWindowOpen() { berry::WorkbenchWindowAdvisor::PostWindowOpen(); // Force Rendering Window Creation on startup. berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); ctkServiceReference serviceRef = context->getServiceReference(); if (serviceRef) { mitk::IDataStorageService *dsService = context->getService(serviceRef); if (dsService) { mitk::IDataStorageReference::Pointer dsRef = dsService->GetDataStorage(); mitk::DataStorageEditorInput::Pointer dsInput(new mitk::DataStorageEditorInput(dsRef)); mitk::WorkbenchUtil::OpenEditor(configurer->GetWindow()->GetActivePage(),dsInput); } } } void QmitkExtWorkbenchWindowAdvisor::onIntro() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onIntro(); } void QmitkExtWorkbenchWindowAdvisor::onHelp() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onHelp(); } void QmitkExtWorkbenchWindowAdvisor::onHelpOpenHelpPerspective() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onHelpOpenHelpPerspective(); } void QmitkExtWorkbenchWindowAdvisor::onAbout() { QmitkExtWorkbenchWindowAdvisorHack::undohack->onAbout(); } //-------------------------------------------------------------------------------- // Ugly hack from here on. Feel free to delete when command framework // and undo buttons are done. //-------------------------------------------------------------------------------- QmitkExtWorkbenchWindowAdvisorHack::QmitkExtWorkbenchWindowAdvisorHack() : QObject() { } QmitkExtWorkbenchWindowAdvisorHack::~QmitkExtWorkbenchWindowAdvisorHack() { } void QmitkExtWorkbenchWindowAdvisorHack::onUndo() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast( model )) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetUndoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Undo " << descriptions.front().second; } } model->Undo(); } else { MITK_ERROR << "No undo model instantiated"; } } void QmitkExtWorkbenchWindowAdvisorHack::onRedo() { mitk::UndoModel* model = mitk::UndoController::GetCurrentUndoModel(); if (model) { if (mitk::VerboseLimitedLinearUndo* verboseundo = dynamic_cast( model )) { mitk::VerboseLimitedLinearUndo::StackDescription descriptions = verboseundo->GetRedoDescriptions(); if (descriptions.size() >= 1) { MITK_INFO << "Redo " << descriptions.front().second; } } model->Redo(); } else { MITK_ERROR << "No undo model instantiated"; } } void QmitkExtWorkbenchWindowAdvisorHack::onImageNavigator() { // get ImageNavigatorView berry::IViewPart::Pointer imageNavigatorView = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.imagenavigator"); if (imageNavigatorView) { bool isImageNavigatorVisible = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->IsPartVisible(imageNavigatorView); if (isImageNavigatorVisible) { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->HideView(imageNavigatorView); return; } } berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ShowView("org.mitk.views.imagenavigator"); //berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkExtWorkbenchWindowAdvisorHack::onViewNavigator() { // get viewnavigatorView berry::IViewPart::Pointer viewnavigatorView = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->FindView("org.mitk.views.viewnavigatorview"); if (viewnavigatorView) { bool isviewnavigatorVisible = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->IsPartVisible(viewnavigatorView); if (isviewnavigatorVisible) { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->HideView(viewnavigatorView); return; } } berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ShowView("org.mitk.views.viewnavigatorview"); //berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkExtWorkbenchWindowAdvisorHack::onEditPreferences() { QmitkPreferencesDialog _PreferencesDialog(QApplication::activeWindow()); _PreferencesDialog.exec(); } void QmitkExtWorkbenchWindowAdvisorHack::onQuit() { berry::PlatformUI::GetWorkbench()->Close(); } void QmitkExtWorkbenchWindowAdvisorHack::onResetPerspective() { berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } void QmitkExtWorkbenchWindowAdvisorHack::onClosePerspective() { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); page->ClosePerspective(page->GetPerspective(), true, true); } void QmitkExtWorkbenchWindowAdvisorHack::onNewWindow() { berry::PlatformUI::GetWorkbench()->OpenWorkbenchWindow(0); } void QmitkExtWorkbenchWindowAdvisorHack::onIntro() { bool hasIntro = berry::PlatformUI::GetWorkbench()->GetIntroManager()->HasIntro(); if (!hasIntro) { QRegExp reg("(.*)(\\n)*"); QRegExp reg2("(\\n)*(.*)"); QFile file(":/org.mitk.gui.qt.ext/index.html"); file.open(QIODevice::ReadOnly | QIODevice::Text); //text file only for reading QString text = QString(file.readAll()); file.close(); QString title = text; title.replace(reg, ""); title.replace(reg2, ""); std::cout << title.toStdString() << std::endl; QMessageBox::information(NULL, title, text, "Close"); } else { berry::PlatformUI::GetWorkbench()->GetIntroManager()->ShowIntro( berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), false); } } void QmitkExtWorkbenchWindowAdvisorHack::onHelp() { ctkPluginContext* context = QmitkCommonExtPlugin::getContext(); if (context == 0) { MITK_WARN << "Plugin context not set, unable to open context help"; return; } // Check if the org.blueberry.ui.qt.help plug-in is installed and started QList > plugins = context->getPlugins(); foreach(QSharedPointer p, plugins) { if (p->getSymbolicName() == "org.blueberry.ui.qt.help") { if (p->getState() != ctkPlugin::ACTIVE) { // try to activate the plug-in explicitly try { p->start(ctkPlugin::START_TRANSIENT); } catch (const ctkPluginException& pe) { MITK_ERROR << "Activating org.blueberry.ui.qt.help failed: " << pe.what(); return; } } } } ctkServiceReference eventAdminRef = context->getServiceReference(); ctkEventAdmin* eventAdmin = 0; if (eventAdminRef) { eventAdmin = context->getService(eventAdminRef); } if (eventAdmin == 0) { MITK_WARN << "ctkEventAdmin service not found. Unable to open context help"; } else { ctkEvent ev("org/blueberry/ui/help/CONTEXTHELP_REQUESTED"); eventAdmin->postEvent(ev); } } void QmitkExtWorkbenchWindowAdvisorHack::onHelpOpenHelpPerspective() { berry::PlatformUI::GetWorkbench()->ShowPerspective("org.blueberry.perspectives.help", berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()); } void QmitkExtWorkbenchWindowAdvisorHack::onAbout() { QmitkAboutDialog* aboutDialog = new QmitkAboutDialog(QApplication::activeWindow(),NULL); aboutDialog->open(); } void QmitkExtWorkbenchWindowAdvisor::HookTitleUpdateListeners( berry::IWorkbenchWindowConfigurer::Pointer configurer) { // hook up the listeners to update the window title titlePartListener.reset(new PartListenerForTitle(this)); - //titlePerspectiveListener = new PerspectiveListenerForTitle(this); + titlePerspectiveListener.reset(new PerspectiveListenerForTitle(this)); editorPropertyListener.reset(new berry::PropertyChangeIntAdapter< - QmitkExtWorkbenchWindowAdvisor>(this, - &QmitkExtWorkbenchWindowAdvisor::PropertyChange)); + QmitkExtWorkbenchWindowAdvisor>(this, + &QmitkExtWorkbenchWindowAdvisor::PropertyChange)); // configurer.getWindow().addPageListener(new IPageListener() { // public void pageActivated(IWorkbenchPage page) { // updateTitle(false); // } // // public void pageClosed(IWorkbenchPage page) { // updateTitle(false); // } // // public void pageOpened(IWorkbenchPage page) { // // do nothing // } // }); - //configurer->GetWindow()->AddPerspectiveListener(titlePerspectiveListener); + configurer->GetWindow()->AddPerspectiveListener(titlePerspectiveListener.data()); configurer->GetWindow()->GetPartService()->AddPartListener(titlePartListener.data()); } QString QmitkExtWorkbenchWindowAdvisor::ComputeTitle() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); berry::IWorkbenchPage::Pointer currentPage = configurer->GetWindow()->GetActivePage(); berry::IEditorPart::Pointer activeEditor; if (currentPage) { activeEditor = lastActiveEditor.Lock(); } QString title; //TODO Product // IProduct product = Platform.getProduct(); // if (product != null) { // title = product.getName(); // } // instead of the product name, we use a custom variable for now title = productName; if(showMitkVersionInfo) { title += QString(" ") + MITK_VERSION_STRING; } if (showVersionInfo) { // add version informatioin QString versions = QString(" (ITK %1.%2.%3 VTK %4.%5.%6 Qt %7 MITK %8)") .arg(ITK_VERSION_MAJOR).arg(ITK_VERSION_MINOR).arg(ITK_VERSION_PATCH) .arg(VTK_MAJOR_VERSION).arg(VTK_MINOR_VERSION).arg(VTK_BUILD_VERSION) .arg(QT_VERSION_STR) .arg(MITK_VERSION_STRING); title += versions; } if (currentPage) { if (activeEditor) { lastEditorTitle = activeEditor->GetTitleToolTip(); if (!lastEditorTitle.isEmpty()) title = lastEditorTitle + " - " + title; } berry::IPerspectiveDescriptor::Pointer persp = currentPage->GetPerspective(); QString label = ""; if (persp) { label = persp->GetLabel(); } berry::IAdaptable* input = currentPage->GetInput(); if (input && input != wbAdvisor->GetDefaultPageInput()) { label = currentPage->GetLabel(); } if (!label.isEmpty()) { title = label + " - " + title; } } title += " (Not for use in diagnosis or treatment of patients)"; return title; } void QmitkExtWorkbenchWindowAdvisor::RecomputeTitle() { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); QString oldTitle = configurer->GetTitle(); QString newTitle = ComputeTitle(); if (newTitle != oldTitle) { configurer->SetTitle(newTitle); } } void QmitkExtWorkbenchWindowAdvisor::UpdateTitle(bool editorHidden) { berry::IWorkbenchWindowConfigurer::Pointer configurer = GetWindowConfigurer(); berry::IWorkbenchWindow::Pointer window = configurer->GetWindow(); berry::IEditorPart::Pointer activeEditor; berry::IWorkbenchPage::Pointer currentPage = window->GetActivePage(); berry::IPerspectiveDescriptor::Pointer persp; berry::IAdaptable* input = 0; if (currentPage) { activeEditor = currentPage->GetActiveEditor(); persp = currentPage->GetPerspective(); input = currentPage->GetInput(); } if (editorHidden) { activeEditor = 0; } // Nothing to do if the editor hasn't changed if (activeEditor == lastActiveEditor.Lock() && currentPage == lastActivePage.Lock() && persp == lastPerspective.Lock() && input == lastInput) { return; } if (!lastActiveEditor.Expired()) { lastActiveEditor.Lock()->RemovePropertyListener(editorPropertyListener.data()); } lastActiveEditor = activeEditor; lastActivePage = currentPage; lastPerspective = persp; lastInput = input; if (activeEditor) { activeEditor->AddPropertyListener(editorPropertyListener.data()); } RecomputeTitle(); } void QmitkExtWorkbenchWindowAdvisor::PropertyChange(const berry::Object::Pointer& /*source*/, int propId) { if (propId == berry::IWorkbenchPartConstants::PROP_TITLE) { if (!lastActiveEditor.Expired()) { QString newTitle = lastActiveEditor.Lock()->GetPartName(); if (lastEditorTitle != newTitle) { RecomputeTitle(); } } } } void QmitkExtWorkbenchWindowAdvisor::SetPerspectiveExcludeList(const QList& v) { this->perspectiveExcludeList = v; } QList QmitkExtWorkbenchWindowAdvisor::GetPerspectiveExcludeList() { return this->perspectiveExcludeList; } void QmitkExtWorkbenchWindowAdvisor::SetViewExcludeList(const QList& v) { this->viewExcludeList = v; } QList QmitkExtWorkbenchWindowAdvisor::GetViewExcludeList() { return this->viewExcludeList; } void QmitkExtWorkbenchWindowAdvisor::PostWindowClose() { berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = static_cast (window->GetShell()->GetControl()); QSettings settings(GetQSettingsFile(), QSettings::IniFormat); settings.setValue("ToolbarPosition", mainWindow->saveState()); } QString QmitkExtWorkbenchWindowAdvisor::GetQSettingsFile() const { QFileInfo settingsInfo = QmitkCommonExtPlugin::getContext()->getDataFile(QT_SETTINGS_FILENAME); return settingsInfo.canonicalFilePath(); } diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkEditorPerspective.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAboutHandler.cpp similarity index 60% copy from Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkEditorPerspective.cpp copy to Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAboutHandler.cpp index 9e68a6b335..2a33e6c507 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkEditorPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAboutHandler.cpp @@ -1,22 +1,26 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkEditorPerspective.h" +#include "QmitkAboutHandler.h" -void QmitkEditorPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) +#include + +berry::Object::Pointer QmitkAboutHandler::Execute(const berry::SmartPointer& /*event*/) { - layout->GetEditorArea(); + QmitkAboutDialog* aboutDialog = new QmitkAboutDialog(QApplication::activeWindow(), NULL); + aboutDialog->open(); + return berry::Object::Pointer(); } diff --git a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionConstants.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAboutHandler.h similarity index 63% rename from Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionConstants.cpp rename to Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAboutHandler.h index 4c9481b513..76ce10eaee 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/QmitkExtActionConstants.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkAboutHandler.h @@ -1,21 +1,31 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ +#ifndef QMITKABOUTHANDLER_H +#define QMITKABOUTHANDLER_H -#include "QmitkExtActionConstants.h" +#include -const QString QmitkExtActionConstants::M_WINDOW = "window"; +class QmitkAboutHandler : public berry::AbstractHandler +{ + Q_OBJECT +public: + + Object::Pointer Execute(const berry::SmartPointer& event); +}; + +#endif // QMITKABOUTHANDLER_H diff --git a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp index 95ac671667..c5573f35a8 100644 --- a/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp +++ b/Plugins/org.mitk.gui.qt.ext/src/internal/QmitkCommonExtPlugin.cpp @@ -1,240 +1,242 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkCommonExtPlugin.h" #include +#include "QmitkAboutHandler.h" #include "QmitkAppInstancesPreferencePage.h" #include "QmitkExternalProgramsPreferencePage.h" #include "QmitkInputDevicesPrefPage.h" #include "QmitkModuleView.h" #include #include #include #include #include #include #include #include #include #include #include #include ctkPluginContext* QmitkCommonExtPlugin::_context = 0; void QmitkCommonExtPlugin::start(ctkPluginContext* context) { this->_context = context; QtWidgetsExtRegisterClasses(); + BERRY_REGISTER_EXTENSION_CLASS(QmitkAboutHandler, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkAppInstancesPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkExternalProgramsPreferencePage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkInputDevicesPrefPage, context) BERRY_REGISTER_EXTENSION_CLASS(QmitkModuleView, context) if (qApp->metaObject()->indexOfSignal("messageReceived(QByteArray)") > -1) { connect(qApp, SIGNAL(messageReceived(QByteArray)), this, SLOT(handleIPCMessage(QByteArray))); } // This is a potentially long running operation. loadDataFromDisk(berry::Platform::GetApplicationArgs(), true); } void QmitkCommonExtPlugin::stop(ctkPluginContext* context) { Q_UNUSED(context) this->_context = 0; } ctkPluginContext* QmitkCommonExtPlugin::getContext() { return _context; } void QmitkCommonExtPlugin::loadDataFromDisk(const QStringList &arguments, bool globalReinit) { if (!arguments.empty()) { ctkServiceReference serviceRef = _context->getServiceReference(); if (serviceRef) { mitk::IDataStorageService* dataStorageService = _context->getService(serviceRef); mitk::DataStorage::Pointer dataStorage = dataStorageService->GetDefaultDataStorage()->GetDataStorage(); int argumentsAdded = 0; for (int i = 0; i < arguments.size(); ++i) { if (arguments[i].right(5) == ".mitk") { mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New(); bool clearDataStorageFirst(false); mitk::ProgressBar::GetInstance()->AddStepsToDo(2); dataStorage = sceneIO->LoadScene( arguments[i].toLocal8Bit().constData(), dataStorage, clearDataStorageFirst ); mitk::ProgressBar::GetInstance()->Progress(2); argumentsAdded++; } else { try { const std::string path(arguments[i].toStdString()); mitk::IOUtil::Load(path, *dataStorage); argumentsAdded++; } catch(...) { MITK_WARN << "Failed to load command line argument: " << arguments[i].toStdString(); } } } // end for each command line argument if (argumentsAdded > 0 && globalReinit) { // calculate bounding geometry mitk::RenderingManager::GetInstance()->InitializeViews(dataStorage->ComputeBoundingGeometry3D()); } } else { MITK_ERROR << "A service reference for mitk::IDataStorageService does not exist"; } } } void QmitkCommonExtPlugin::startNewInstance(const QStringList &args, const QStringList& files) { QStringList newArgs(args); #ifdef Q_OS_UNIX newArgs << QString("--") +berry::Platform::ARG_NEWINSTANCE; #else newArgs << QString("/") + berry::Platform::ARG_NEWINSTANCE; #endif newArgs << files; QProcess::startDetached(qApp->applicationFilePath(), newArgs); } void QmitkCommonExtPlugin::handleIPCMessage(const QByteArray& msg) { QDataStream ds(msg); QString msgType; ds >> msgType; // we only handle messages containing command line arguments if (msgType != "$cmdLineArgs") return; // activate the current workbench window berry::IWorkbenchWindow::Pointer window = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(); QMainWindow* mainWindow = static_cast (window->GetShell()->GetControl()); mainWindow->setWindowState(mainWindow->windowState() & ~Qt::WindowMinimized); mainWindow->raise(); mainWindow->activateWindow(); // Get the preferences for the instantiation behavior berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); berry::IPreferences::Pointer prefs = prefService->GetSystemPreferences()->Node("/General"); bool newInstanceAlways = prefs->GetBool("newInstance.always", false); bool newInstanceScene = prefs->GetBool("newInstance.scene", true); QStringList args; ds >> args; QStringList fileArgs; QStringList sceneArgs; Poco::Util::OptionSet os; berry::Platform::GetOptionSet(os); Poco::Util::OptionProcessor processor(os); #if !defined(POCO_OS_FAMILY_UNIX) processor.setUnixStyle(false); #endif args.pop_front(); QStringList::Iterator it = args.begin(); while (it != args.end()) { std::string name; std::string value; if (processor.process(it->toStdString(), name, value)) { ++it; } else { if (it->endsWith(".mitk")) { sceneArgs << *it; } else { fileArgs << *it; } it = args.erase(it); } } if (newInstanceAlways) { if (newInstanceScene) { startNewInstance(args, fileArgs); foreach(QString sceneFile, sceneArgs) { startNewInstance(args, QStringList(sceneFile)); } } else { fileArgs.append(sceneArgs); startNewInstance(args, fileArgs); } } else { loadDataFromDisk(fileArgs, false); if (newInstanceScene) { foreach(QString sceneFile, sceneArgs) { startNewInstance(args, QStringList(sceneFile)); } } else { loadDataFromDisk(sceneArgs, false); } } } #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(org_mitk_gui_qt_ext, QmitkCommonExtPlugin) #endif diff --git a/Plugins/org.mitk.gui.qt.extapplication/plugin.xml b/Plugins/org.mitk.gui.qt.extapplication/plugin.xml index b83147ebd2..82b9bb07a4 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/plugin.xml +++ b/Plugins/org.mitk.gui.qt.extapplication/plugin.xml @@ -1,39 +1,56 @@ - + - + - - - \ No newline at end of file + + + + + + + + + + diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkEditorPerspective.cpp b/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkEditorPerspective.cpp index 9e68a6b335..e2d5e4fb23 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkEditorPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkEditorPerspective.cpp @@ -1,22 +1,25 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkEditorPerspective.h" void QmitkEditorPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { layout->GetEditorArea(); + + layout->AddPerspectiveShortcut("org.mitk.extapp.defaultperspective"); + layout->AddPerspectiveShortcut("org.mitk.mitkworkbench.perspectives.visualization"); } diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkExtDefaultPerspective.cpp b/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkExtDefaultPerspective.cpp index a9af67c34d..54eba4bd8e 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkExtDefaultPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkExtDefaultPerspective.cpp @@ -1,39 +1,42 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkExtDefaultPerspective.h" #include "berryIViewLayout.h" QmitkExtDefaultPerspective::QmitkExtDefaultPerspective() { } void QmitkExtDefaultPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { QString editorArea = layout->GetEditorArea(); layout->AddView("org.mitk.views.datamanager", berry::IPageLayout::LEFT, 0.3f, editorArea); berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.datamanager"); lo->SetCloseable(false); layout->AddView("org.mitk.views.imagenavigator", berry::IPageLayout::BOTTOM, 0.5f, "org.mitk.views.datamanager"); berry::IPlaceholderFolderLayout::Pointer bottomFolder = layout->CreatePlaceholderFolder("bottom", berry::IPageLayout::BOTTOM, 0.7f, editorArea); bottomFolder->AddPlaceholder("org.blueberry.views.logview"); bottomFolder->AddPlaceholder("org.mitk.views.modules"); + + layout->AddPerspectiveShortcut("org.mitk.mitkworkbench.perspectives.editor"); + layout->AddPerspectiveShortcut("org.mitk.mitkworkbench.perspectives.visualization"); } diff --git a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkVisualizationPerspective.cpp b/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkVisualizationPerspective.cpp index abb0201720..851c3d1c5e 100644 --- a/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkVisualizationPerspective.cpp +++ b/Plugins/org.mitk.gui.qt.extapplication/src/internal/perspectives/QmitkVisualizationPerspective.cpp @@ -1,53 +1,47 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkVisualizationPerspective.h" #include "berryIViewLayout.h" void QmitkVisualizationPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout) { ///////////////////////////////////////////////////// // all di-app perspectives should have the following: ///////////////////////////////////////////////////// QString editorArea = layout->GetEditorArea(); layout->AddStandaloneView("org.mitk.views.datamanager", false, berry::IPageLayout::LEFT, 0.3f, editorArea); berry::IFolderLayout::Pointer left = layout->CreateFolder("org.mitk.extapplication.leftcontrols", berry::IPageLayout::BOTTOM, 0.1f, "org.mitk.views.datamanager"); layout->AddStandaloneViewPlaceholder("org.mitk.views.imagenavigator", berry::IPageLayout::BOTTOM, .4f, "org.mitk.extapplication.leftcontrols", true); ///////////////////////////////////////////// // here goes the perspective specific stuff ///////////////////////////////////////////// - left->AddView("org.mitk.views.volumevisualization"); - berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.volumevisualization"); - lo->SetCloseable(true); + // Adding the entry for the image navigator to the Windows->"Show View" menu + layout->AddShowViewShortcut("org.mitk.views.imagenavigator"); - left->AddView("org.mitk.views.screenshotmaker"); - lo = layout->GetViewLayout("org.mitk.views.screenshotmaker"); - lo->SetCloseable(true); - - left->AddView("org.mitk.views.moviemaker"); - lo = layout->GetViewLayout("org.mitk.views.moviemaker"); - lo->SetCloseable(true); + layout->AddPerspectiveShortcut("org.mitk.extapp.defaultperspective"); + layout->AddPerspectiveShortcut("org.mitk.mitkworkbench.perspectives.editor"); } diff --git a/Plugins/org.mitk.gui.qt.imagenavigator/plugin.xml b/Plugins/org.mitk.gui.qt.imagenavigator/plugin.xml index 0abe6b9d63..6f1c57454f 100644 --- a/Plugins/org.mitk.gui.qt.imagenavigator/plugin.xml +++ b/Plugins/org.mitk.gui.qt.imagenavigator/plugin.xml @@ -1,12 +1,28 @@ - + + + + + + + + + + + diff --git a/Plugins/org.mitk.gui.qt.moviemaker/plugin.xml b/Plugins/org.mitk.gui.qt.moviemaker/plugin.xml index 10feb03244..21dfa996c7 100644 --- a/Plugins/org.mitk.gui.qt.moviemaker/plugin.xml +++ b/Plugins/org.mitk.gui.qt.moviemaker/plugin.xml @@ -1,39 +1,46 @@ Take movies of your data Take screenshots of your data - + + + + + + - - - - - - - - - - + + + + + - + + + + + + + diff --git a/Plugins/org.mitk.gui.qt.properties/plugin.xml b/Plugins/org.mitk.gui.qt.properties/plugin.xml index fd81f8223f..3054a28697 100644 --- a/Plugins/org.mitk.gui.qt.properties/plugin.xml +++ b/Plugins/org.mitk.gui.qt.properties/plugin.xml @@ -1,21 +1,18 @@ View, Set, and Change properties of DataNodes - - - - + diff --git a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyItemModel.cpp b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyItemModel.cpp index d792bfea83..6455084045 100644 --- a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyItemModel.cpp +++ b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyItemModel.cpp @@ -1,521 +1,521 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkGetPropertyService.h" #include "QmitkPropertiesPreferencePage.h" #include "QmitkPropertyItem.h" #include "QmitkPropertyItemModel.h" #include #include #include #include #include #include #include #include static QColor MitkToQt(const mitk::Color &color) { return QColor(color.GetRed() * 255, color.GetGreen() * 255, color.GetBlue() * 255); } static mitk::BaseProperty* GetBaseProperty(const QVariant& data) { return data.isValid() ? reinterpret_cast(data.value()) : NULL; } static mitk::Color QtToMitk(const QColor &color) { mitk::Color mitkColor; mitkColor.SetRed(color.red() / 255.0f); mitkColor.SetGreen(color.green() / 255.0f); mitkColor.SetBlue(color.blue() / 255.0f); return mitkColor; } class PropertyEqualTo { public: PropertyEqualTo(const mitk::BaseProperty* property) : m_Property(property) { } bool operator()(const mitk::PropertyList::PropertyMapElementType& pair) const { return pair.second.GetPointer() == m_Property; } private: const mitk::BaseProperty* m_Property; }; QmitkPropertyItemModel::QmitkPropertyItemModel(QObject* parent) : QAbstractItemModel(parent), m_PropertyAliases(NULL), m_PropertyFilters(NULL) { this->CreateRootItem(); } QmitkPropertyItemModel::~QmitkPropertyItemModel() { this->SetNewPropertyList(NULL); } int QmitkPropertyItemModel::columnCount(const QModelIndex& parent) const { if (parent.isValid()) return static_cast(parent.internalPointer())->GetColumnCount(); else return m_RootItem->GetColumnCount(); } void QmitkPropertyItemModel::CreateRootItem() { QList rootData; rootData << "Property" << "Value"; m_RootItem.reset(new QmitkPropertyItem(rootData)); this->beginResetModel(); this->endResetModel(); } QVariant QmitkPropertyItemModel::data(const QModelIndex& index, int role) const { if(!index.isValid()) return QVariant(); mitk::BaseProperty* property = index.column() == 1 ? GetBaseProperty(static_cast(index.internalPointer())->GetData(1)) : NULL; if (role == Qt::DisplayRole) { if (index.column() == 0) { return static_cast(index.internalPointer())->GetData(0); } else if (index.column() == 1 && property != NULL) { if (mitk::ColorProperty* colorProperty = dynamic_cast(property)) return MitkToQt(colorProperty->GetValue()); else if (dynamic_cast(property) == NULL) return QString::fromStdString(property->GetValueAsString()); } } else if (index.column() == 1 && property != NULL) { if (role == Qt::CheckStateRole) { if (mitk::BoolProperty* boolProperty = dynamic_cast(property)) return boolProperty->GetValue() ? Qt::Checked : Qt::Unchecked; } else if (role == Qt::EditRole) { if (dynamic_cast(property) != NULL) { return QString::fromStdString(property->GetValueAsString()); } else if (mitk::IntProperty* intProperty = dynamic_cast(property)) { return intProperty->GetValue(); } else if (mitk::FloatProperty* floatProperty = dynamic_cast(property)) { return floatProperty->GetValue(); } else if (mitk::DoubleProperty* doubleProperty = dynamic_cast(property)) { return doubleProperty->GetValue(); } else if (mitk::EnumerationProperty* enumProperty = dynamic_cast(property)) { QStringList values; for (mitk::EnumerationProperty::EnumConstIterator it = enumProperty->Begin(); it != enumProperty->End(); it++) values << QString::fromStdString(it->second); return values; } else if (mitk::ColorProperty* colorProperty = dynamic_cast(property)) { return MitkToQt(colorProperty->GetValue()); } } else if (role == mitk::PropertyRole) { return QVariant::fromValue(property); } } return QVariant(); } QModelIndex QmitkPropertyItemModel::FindProperty(const mitk::BaseProperty* property) { if (property == NULL) return QModelIndex(); typedef mitk::PropertyList::PropertyMap PropertyMap; const PropertyMap* propertyMap = m_PropertyList->GetMap(); PropertyMap::const_iterator it = std::find_if(propertyMap->begin(), propertyMap->end(), PropertyEqualTo(property)); if (it == propertyMap->end()) return QModelIndex(); QString name = QString::fromStdString(it->first); if (!name.contains('.')) { QModelIndexList item = this->match(index(0, 0), Qt::DisplayRole, name, 1, Qt::MatchExactly); if (!item.empty()) return item[0]; } else { QStringList names = name.split('.'); QModelIndexList items = this->match(index(0, 0), Qt::DisplayRole, names.last(), -1, Qt::MatchRecursive | Qt::MatchExactly); foreach(QModelIndex item, items) { QModelIndex candidate = item; for (int i = names.length() - 1; i != 0; --i) { QModelIndex parent = item.parent(); if (parent.parent() == QModelIndex()) { if (parent.data() != names.first()) break; return candidate; } if (parent.data() != names[i - 1]) break; item = parent; } } } return QModelIndex(); } Qt::ItemFlags QmitkPropertyItemModel::flags(const QModelIndex& index) const { Qt::ItemFlags flags = QAbstractItemModel::flags(index); if (index.column() == 1) { if (index.data(Qt::EditRole).isValid()) flags |= Qt::ItemIsEditable; if (index.data(Qt::CheckStateRole).isValid()) flags |= Qt::ItemIsUserCheckable; } return flags; } mitk::PropertyList* QmitkPropertyItemModel::GetPropertyList() const { return m_PropertyList.GetPointer(); } QVariant QmitkPropertyItemModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) return m_RootItem->GetData(section); return QVariant(); } QModelIndex QmitkPropertyItemModel::index(int row, int column, const QModelIndex& parent) const { if (!this->hasIndex(row, column, parent)) return QModelIndex(); QmitkPropertyItem* parentItem = parent.isValid() ? static_cast(parent.internalPointer()) : m_RootItem.get(); QmitkPropertyItem* childItem = parentItem->GetChild(row); return childItem != NULL ? this->createIndex(row, column, childItem) : QModelIndex(); } void QmitkPropertyItemModel::OnPreferencesChanged(const berry::IBerryPreferences* preferences) { bool showAliases = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_ALIASES, true); bool filterProperties = preferences->GetBool(QmitkPropertiesPreferencePage::FILTER_PROPERTIES, true); bool updateAliases = showAliases != (m_PropertyAliases != NULL); bool updateFilters = filterProperties != (m_PropertyFilters != NULL); bool resetPropertyList = false; if (updateAliases) { m_PropertyAliases = showAliases ? mitk::GetPropertyService() : NULL; resetPropertyList = m_PropertyList.IsNotNull(); } if (updateFilters) { m_PropertyFilters = filterProperties ? mitk::GetPropertyService() : NULL; if (!resetPropertyList) resetPropertyList = m_PropertyList.IsNotNull(); } if (resetPropertyList) this->SetNewPropertyList(m_PropertyList.GetPointer()); } -void QmitkPropertyItemModel::OnPropertyDeleted(const itk::Object* property, const itk::EventObject&) +void QmitkPropertyItemModel::OnPropertyDeleted(const itk::Object* /*property*/, const itk::EventObject&) { /*QModelIndex index = this->FindProperty(static_cast(property)); if (index != QModelIndex()) this->reset();*/ } void QmitkPropertyItemModel::OnPropertyListDeleted(const itk::Object*) { this->CreateRootItem(); } void QmitkPropertyItemModel::OnPropertyModified(const itk::Object* property, const itk::EventObject&) { QModelIndex index = this->FindProperty(static_cast(property)); if (index != QModelIndex()) emit dataChanged(index, index); } QModelIndex QmitkPropertyItemModel::parent(const QModelIndex& child) const { if (!child.isValid()) return QModelIndex(); QmitkPropertyItem* parentItem = static_cast(child.internalPointer())->GetParent(); if (parentItem == m_RootItem.get()) return QModelIndex(); return this->createIndex(parentItem->GetRow(), 0, parentItem); } int QmitkPropertyItemModel::rowCount(const QModelIndex& parent) const { if (parent.column() > 0) return 0; QmitkPropertyItem *parentItem = parent.isValid() ? static_cast(parent.internalPointer()) : m_RootItem.get(); return parentItem->GetChildCount(); } bool QmitkPropertyItemModel::setData(const QModelIndex& index, const QVariant& value, int role) { if (!index.isValid() || index.column() != 1 || (role != Qt::EditRole && role != Qt::CheckStateRole)) return false; mitk::BaseProperty* property = GetBaseProperty(static_cast(index.internalPointer())->GetData(1)); if (property == NULL) return false; if (mitk::BoolProperty* boolProperty = dynamic_cast(property)) { boolProperty->SetValue(value.toInt() == Qt::Checked ? true : false); } else if (mitk::StringProperty* stringProperty = dynamic_cast(property)) { stringProperty->SetValue(value.toString().toStdString()); } else if (mitk::IntProperty* intProperty = dynamic_cast(property)) { intProperty->SetValue(value.toInt()); } else if (mitk::FloatProperty* floatProperty = dynamic_cast(property)) { floatProperty->SetValue(value.toFloat()); } else if (mitk::DoubleProperty* doubleProperty = dynamic_cast(property)) { doubleProperty->SetValue(value.toDouble()); } else if (mitk::EnumerationProperty* enumProperty = dynamic_cast(property)) { std::string selection = value.toString().toStdString(); if (selection != enumProperty->GetValueAsString() && enumProperty->IsValidEnumerationValue(selection)) enumProperty->SetValue(selection); } else if (mitk::ColorProperty* colorProperty = dynamic_cast(property)) { colorProperty->SetValue(QtToMitk(value.value())); } m_PropertyList->InvokeEvent(itk::ModifiedEvent()); m_PropertyList->Modified(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); return true; } void QmitkPropertyItemModel::SetNewPropertyList(mitk::PropertyList* propertyList) { typedef mitk::PropertyList::PropertyMap PropertyMap; this->beginResetModel(); if (m_PropertyList.IsNotNull()) { mitk::MessageDelegate1 delegate(this, &QmitkPropertyItemModel::OnPropertyListDeleted); m_PropertyList.ObjectDelete.RemoveListener(delegate); const PropertyMap* propertyMap = m_PropertyList->GetMap(); for (PropertyMap::const_iterator propertyIt = propertyMap->begin(); propertyIt != propertyMap->end(); ++propertyIt) { std::map::const_iterator tagIt = m_PropertyModifiedTags.find(propertyIt->first); if (tagIt != m_PropertyModifiedTags.end()) propertyIt->second->RemoveObserver(tagIt->second); tagIt = m_PropertyDeletedTags.find(propertyIt->first); if (tagIt != m_PropertyDeletedTags.end()) propertyIt->second->RemoveObserver(tagIt->second); } m_PropertyModifiedTags.clear(); } m_PropertyList = propertyList; if (m_PropertyList.IsNotNull()) { mitk::MessageDelegate1 delegate(this, &QmitkPropertyItemModel::OnPropertyListDeleted); m_PropertyList.ObjectDelete.AddListener(delegate); mitk::MessageDelegate2 propertyDelegate(this, &QmitkPropertyItemModel::OnPropertyModified); itk::MemberCommand::Pointer modifiedCommand = itk::MemberCommand::New(); modifiedCommand->SetCallbackFunction(this, &QmitkPropertyItemModel::OnPropertyModified); const PropertyMap* propertyMap = m_PropertyList->GetMap(); for (PropertyMap::const_iterator it = propertyMap->begin(); it != propertyMap->end(); ++it) m_PropertyModifiedTags.insert(std::make_pair(it->first, it->second->AddObserver(itk::ModifiedEvent(), modifiedCommand))); itk::MemberCommand::Pointer deletedCommand = itk::MemberCommand::New(); deletedCommand->SetCallbackFunction(this, &QmitkPropertyItemModel::OnPropertyDeleted); for (PropertyMap::const_iterator it = propertyMap->begin(); it != propertyMap->end(); ++it) m_PropertyDeletedTags.insert(std::make_pair(it->first, it->second->AddObserver(itk::DeleteEvent(), deletedCommand))); } this->CreateRootItem(); if (m_PropertyList != NULL && !m_PropertyList->IsEmpty()) { mitk::PropertyList::PropertyMap filteredProperties; bool filterProperties = false; if (m_PropertyFilters != NULL && (m_PropertyFilters->HasFilter() || m_PropertyFilters->HasFilter(m_ClassName.toStdString()))) { filteredProperties = m_PropertyFilters->ApplyFilter(*m_PropertyList->GetMap(), m_ClassName.toStdString()); filterProperties = true; } const mitk::PropertyList::PropertyMap* propertyMap = !filterProperties ? m_PropertyList->GetMap() : &filteredProperties; mitk::PropertyList::PropertyMap::const_iterator end = propertyMap->end(); for (mitk::PropertyList::PropertyMap::const_iterator iter = propertyMap->begin(); iter != end; ++iter) { std::vector aliases; if (m_PropertyAliases != NULL) { aliases = m_PropertyAliases->GetAliases(iter->first, m_ClassName.toStdString()); if (aliases.empty() && !m_ClassName.isEmpty()) aliases = m_PropertyAliases->GetAliases(iter->first); } if (aliases.empty()) { QList data; data << QString::fromStdString(iter->first) << QVariant::fromValue((reinterpret_cast(iter->second.GetPointer()))); m_RootItem->AppendChild(new QmitkPropertyItem(data)); } else { std::vector::const_iterator end = aliases.end(); for (std::vector::const_iterator aliasIter = aliases.begin(); aliasIter != end; ++aliasIter) { QList data; data << QString::fromStdString(*aliasIter) << QVariant::fromValue((reinterpret_cast(iter->second.GetPointer()))); m_RootItem->AppendChild(new QmitkPropertyItem(data)); } } } } this->endResetModel(); } void QmitkPropertyItemModel::SetPropertyList(mitk::PropertyList* propertyList, const QString& className) { if (m_PropertyList.GetPointer() != propertyList) { m_ClassName = className; this->SetNewPropertyList(propertyList); } } void QmitkPropertyItemModel::Update() { this->SetNewPropertyList(m_PropertyList); } diff --git a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp index ef2c796a3d..cff91af97b 100644 --- a/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp +++ b/Plugins/org.mitk.gui.qt.properties/src/internal/QmitkPropertyTreeView.cpp @@ -1,412 +1,412 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkGetPropertyService.h" #include "QmitkAddNewPropertyDialog.h" #include "QmitkPropertiesPreferencePage.h" #include "QmitkPropertyItemDelegate.h" #include "QmitkPropertyItemModel.h" #include "QmitkPropertyItemSortFilterProxyModel.h" #include "QmitkPropertyTreeView.h" #include #include #include #include #include #include const std::string QmitkPropertyTreeView::VIEW_ID = "org.mitk.views.properties"; QmitkPropertyTreeView::QmitkPropertyTreeView() : m_Parent(NULL), m_PropertyNameChangedTag(0), m_PropertyAliases(NULL), m_PropertyDescriptions(NULL), m_ShowAliasesInDescription(true), m_DeveloperMode(false), m_ProxyModel(NULL), m_Model(NULL), m_Delegate(NULL), m_Renderer(NULL) { } QmitkPropertyTreeView::~QmitkPropertyTreeView() { } void QmitkPropertyTreeView::CreateQtPartControl(QWidget* parent) { m_Parent = parent; m_Controls.setupUi(parent); m_Controls.propertyListComboBox->addItem("Data node: common"); mitk::IRenderWindowPart* renderWindowPart = this->GetRenderWindowPart(); if (renderWindowPart != NULL) { QHash renderWindows = renderWindowPart->GetQmitkRenderWindows(); Q_FOREACH(QString renderWindow, renderWindows.keys()) { m_Controls.propertyListComboBox->addItem(QString("Data node: ") + renderWindow); } } m_Controls.propertyListComboBox->addItem("Base data"); m_Controls.newButton->setEnabled(false); m_Controls.description->hide(); m_Controls.propertyListLabel->hide(); m_Controls.propertyListComboBox->hide(); m_Controls.newButton->hide(); m_ProxyModel = new QmitkPropertyItemSortFilterProxyModel(m_Controls.treeView); m_Model = new QmitkPropertyItemModel(m_ProxyModel); m_ProxyModel->setSourceModel(m_Model); m_ProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_ProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); m_ProxyModel->setDynamicSortFilter(true); m_Delegate = new QmitkPropertyItemDelegate(m_Controls.treeView); m_Controls.treeView->setItemDelegateForColumn(1, m_Delegate); m_Controls.treeView->setModel(m_ProxyModel); m_Controls.treeView->setColumnWidth(0, 160); m_Controls.treeView->sortByColumn(0, Qt::AscendingOrder); m_Controls.treeView->setSelectionBehavior(QAbstractItemView::SelectRows); m_Controls.treeView->setSelectionMode(QAbstractItemView::SingleSelection); m_Controls.treeView->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::DoubleClicked); connect(m_Controls.filterLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(OnFilterTextChanged(const QString&))); connect(m_Controls.propertyListComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(OnPropertyListChanged(int))); connect(m_Controls.newButton, SIGNAL(clicked()), this, SLOT(OnAddNewProperty())); connect(m_Controls.treeView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(OnCurrentRowChanged(const QModelIndex&, const QModelIndex&))); connect(m_Model, SIGNAL(modelReset()), this, SLOT(OnModelReset())); } QString QmitkPropertyTreeView::GetPropertyNameOrAlias(const QModelIndex& index) { QString propertyName; if (index.isValid()) { QModelIndex current = index; while (current.isValid()) { QString name = m_ProxyModel->data(m_ProxyModel->index(current.row(), 0, current.parent())).toString(); propertyName.prepend(propertyName.isEmpty() ? name : name.append('.')); current = current.parent(); } } return propertyName; } void QmitkPropertyTreeView::OnCurrentRowChanged(const QModelIndex& current, const QModelIndex&) { if (m_PropertyDescriptions != NULL && current.isValid()) { QString name = this->GetPropertyNameOrAlias(current); if (!name.isEmpty()) { QString alias; bool isTrueName = true; if (m_PropertyAliases != NULL) { std::string trueName = m_PropertyAliases->GetPropertyName(name.toStdString()); if (trueName.empty() && !m_SelectionClassName.empty()) trueName = m_PropertyAliases->GetPropertyName(name.toStdString(), m_SelectionClassName); if (!trueName.empty()) { alias = name; name = QString::fromStdString(trueName); isTrueName = false; } } QString description = QString::fromStdString(m_PropertyDescriptions->GetDescription(name.toStdString())); std::vector aliases; if (!isTrueName && m_PropertyAliases != NULL) { aliases = m_PropertyAliases->GetAliases(name.toStdString(), m_SelectionClassName); if (aliases.empty() && !m_SelectionClassName.empty()) aliases = m_PropertyAliases->GetAliases(name.toStdString()); } if (!description.isEmpty() || !aliases.empty()) { QString customizedDescription; if (m_ShowAliasesInDescription && !aliases.empty()) { customizedDescription = "

" + name + "

"; std::size_t numAliases = aliases.size(); std::size_t lastAlias = numAliases - 1; for (std::size_t i = 0; i < numAliases; ++i) { customizedDescription += i != lastAlias ? "
" : "
"; customizedDescription += QString::fromStdString(aliases[i]) + "
"; } } else { customizedDescription = "

" + name + "

"; } if (!description.isEmpty()) customizedDescription += description; m_Controls.description->setText(customizedDescription); m_Controls.description->show(); return; } } } m_Controls.description->hide(); } void QmitkPropertyTreeView::OnFilterTextChanged(const QString& filter) { m_ProxyModel->setFilterWildcard(filter); if (filter.isEmpty()) m_Controls.treeView->collapseAll(); else m_Controls.treeView->expandAll(); } void QmitkPropertyTreeView::OnModelReset() { m_Controls.description->hide(); } void QmitkPropertyTreeView::OnPreferencesChanged(const berry::IBerryPreferences* preferences) { bool showAliases = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_ALIASES, true); bool showDescriptions = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_DESCRIPTIONS, true); bool showAliasesInDescription = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_ALIASES_IN_DESCRIPTION, true); bool developerMode = preferences->GetBool(QmitkPropertiesPreferencePage::DEVELOPER_MODE, false); bool updateAliases = showAliases != (m_PropertyAliases != NULL); bool updateDescriptions = showDescriptions != (m_PropertyDescriptions != NULL); bool updateAliasesInDescription = showAliasesInDescription != m_ShowAliasesInDescription; bool updateDeveloperMode = developerMode != m_DeveloperMode; if (updateAliases) m_PropertyAliases = showAliases ? mitk::GetPropertyService() : NULL; if (updateDescriptions) m_PropertyDescriptions = showDescriptions ? mitk::GetPropertyService() : NULL; if (updateAliasesInDescription) m_ShowAliasesInDescription = showAliasesInDescription; if (updateDescriptions || updateAliasesInDescription) { QModelIndexList selection = m_Controls.treeView->selectionModel()->selectedRows(); if (!selection.isEmpty()) this->OnCurrentRowChanged(selection[0], selection[0]); } if (updateDeveloperMode) { m_DeveloperMode = developerMode; if (!developerMode) m_Controls.propertyListComboBox->setCurrentIndex(0); m_Controls.propertyListLabel->setVisible(developerMode); m_Controls.propertyListComboBox->setVisible(developerMode); m_Controls.newButton->setVisible(developerMode); } m_Model->OnPreferencesChanged(preferences); } void QmitkPropertyTreeView::OnPropertyNameChanged(const itk::EventObject&) { mitk::PropertyList* propertyList = m_Model->GetPropertyList(); if (propertyList != NULL) { mitk::BaseProperty* nameProperty = propertyList->GetProperty("name"); if (nameProperty != NULL) { QString partName = "Properties ("; partName.append(QString::fromStdString(nameProperty->GetValueAsString())).append(')'); this->SetPartName(partName); } } } void QmitkPropertyTreeView::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList& nodes) { mitk::PropertyList* propertyList = m_Model->GetPropertyList(); if (propertyList != NULL) { mitk::BaseProperty* nameProperty = propertyList->GetProperty("name"); if (nameProperty != NULL) nameProperty->RemoveObserver(m_PropertyNameChangedTag); m_PropertyNameChangedTag = 0; } if (nodes.empty() || nodes.front().IsNull()) { m_SelectedNode = NULL; this->SetPartName("Properties"); m_Model->SetPropertyList(NULL); m_Delegate->SetPropertyList(NULL); m_Controls.newButton->setEnabled(false); } else { m_SelectedNode = nodes.front(); QString selectionClassName = m_SelectedNode->GetData() != NULL ? m_SelectedNode->GetData()->GetNameOfClass() : ""; m_SelectionClassName = selectionClassName.toStdString(); mitk::PropertyList::Pointer propertyList; if (m_Renderer == NULL && m_Controls.propertyListComboBox->currentText() == "Base data") { propertyList = m_SelectedNode->GetData() != NULL ? m_SelectedNode->GetData()->GetPropertyList() : NULL; } else { propertyList = m_SelectedNode->GetPropertyList(m_Renderer); } m_Model->SetPropertyList(propertyList, selectionClassName); m_Delegate->SetPropertyList(propertyList); OnPropertyNameChanged(itk::ModifiedEvent()); mitk::BaseProperty* nameProperty = m_SelectedNode->GetProperty("name"); if (nameProperty != NULL) { itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New(); command->SetCallbackFunction(this, &QmitkPropertyTreeView::OnPropertyNameChanged); m_PropertyNameChangedTag = nameProperty->AddObserver(itk::ModifiedEvent(), command); } m_Controls.newButton->setEnabled(true); } if (!m_ProxyModel->filterRegExp().isEmpty()) m_Controls.treeView->expandAll(); } void QmitkPropertyTreeView::SetFocus() { m_Controls.filterLineEdit->setFocus(); } -void QmitkPropertyTreeView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) +void QmitkPropertyTreeView::RenderWindowPartActivated(mitk::IRenderWindowPart* /*renderWindowPart*/) { if (m_Controls.propertyListComboBox->count() == 2) { QHash renderWindows = this->GetRenderWindowPart()->GetQmitkRenderWindows(); Q_FOREACH(QString renderWindow, renderWindows.keys()) { m_Controls.propertyListComboBox->insertItem(m_Controls.propertyListComboBox->count() - 1, QString("Data node: ") + renderWindow); } } } void QmitkPropertyTreeView::RenderWindowPartDeactivated(mitk::IRenderWindowPart*) { if (m_Controls.propertyListComboBox->count() > 2) { m_Controls.propertyListComboBox->clear(); m_Controls.propertyListComboBox->addItem("Data node: common"); m_Controls.propertyListComboBox->addItem("Base data"); } } void QmitkPropertyTreeView::OnPropertyListChanged(int index) { if (index == -1) return; QString renderer = m_Controls.propertyListComboBox->itemText(index); if (renderer.startsWith("Data node: ")) renderer = QString::fromStdString(renderer.toStdString().substr(11)); m_Renderer = renderer != "common" && renderer != "Base data" ? this->GetRenderWindowPart()->GetQmitkRenderWindow(renderer)->GetRenderer() : NULL; QList nodes; if (m_SelectedNode.IsNotNull()) nodes << m_SelectedNode; berry::IWorkbenchPart::Pointer workbenchPart; this->OnSelectionChanged(workbenchPart, nodes); } void QmitkPropertyTreeView::OnAddNewProperty() { std::unique_ptr dialog(m_Controls.propertyListComboBox->currentText() != "Base data" ? new QmitkAddNewPropertyDialog(m_SelectedNode, m_Renderer, m_Parent) : new QmitkAddNewPropertyDialog(m_SelectedNode->GetData())); if (dialog->exec() == QDialog::Accepted) this->m_Model->Update(); } diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h index 111f398b8d..59a4eb922a 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/QmitkSegmentationPreferencePage.h @@ -1,85 +1,85 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkSegmentationPreferencePage_h_included #define QmitkSegmentationPreferencePage_h_included -#include "berryIQtPreferencePage.h" #include "org_mitk_gui_qt_segmentation_Export.h" #include +#include "berryIQtPreferencePage.h" class QWidget; class QCheckBox; class QRadioButton; class QDoubleSpinBox; class MITK_QT_SEGMENTATION QmitkSegmentationPreferencePage : public QObject, public berry::IQtPreferencePage { Q_OBJECT Q_INTERFACES(berry::IPreferencePage) public: QmitkSegmentationPreferencePage(); ~QmitkSegmentationPreferencePage(); void Init(berry::IWorkbench::Pointer workbench); void CreateQtControl(QWidget* widget); QWidget* GetQtControl() const; /// /// \see IPreferencePage::PerformOk() /// virtual bool PerformOk(); /// /// \see IPreferencePage::PerformCancel() /// virtual void PerformCancel(); /// /// \see IPreferencePage::Update() /// virtual void Update(); protected slots: void OnVolumeRenderingCheckboxChecked(int); void OnSmoothingCheckboxChecked(int); protected: QWidget* m_MainControl; QCheckBox* m_SlimViewCheckBox; QRadioButton* m_RadioOutline; QRadioButton* m_RadioOverlay; QCheckBox* m_VolumeRenderingCheckBox; QCheckBox* m_SmoothingCheckBox; QDoubleSpinBox* m_SmoothingSpinBox; QDoubleSpinBox* m_DecimationSpinBox; QDoubleSpinBox* m_ClosingSpinBox; QCheckBox* m_SelectionModeCheckBox; bool m_Initializing; berry::IPreferences::Pointer m_SegmentationPreferencesNode; }; #endif /* QMITKDATAMANAGERPREFERENCEPAGE_H_ */ diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkDeformableClippingPlaneView.h b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkDeformableClippingPlaneView.h index 8db2fcb2c8..cbd0f40258 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkDeformableClippingPlaneView.h +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkDeformableClippingPlaneView.h @@ -1,102 +1,99 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _QMITKDEFORMABLECLIPPINGPLANEVIEW_H_INCLUDED #define _QMITKDEFORMABLECLIPPINGPLANEVIEW_H_INCLUDED #include "ui_QmitkDeformableClippingPlaneViewControls.h" - -#include - - #include "mitkImage.h" +#include typedef itk::RGBPixel< float > Color; /*! * \ingroup org_mitk_gui_qt_deformableSurface * * \brief QmitkDeformableClippingPlaneView * * Document your class here. * * \sa QmitkFunctionality */ class QmitkDeformableClippingPlaneView : public QmitkFunctionality { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkDeformableClippingPlaneView(); virtual ~QmitkDeformableClippingPlaneView(); virtual void CreateQtPartControl(QWidget *parent); /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// \brief Called when the functionality is activated virtual void Activated(); /// \brief Called when the functionality is deactivated virtual void Deactivated(); virtual void StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget); virtual void StdMultiWidgetNotAvailable(); protected slots: /// \brief Called when the user clicks the GUI button/makes a selection void OnComboBoxSelectionChanged(const mitk::DataNode* node); void OnCreateNewClippingPlane(); void OnCalculateClippingVolume(); void OnTranslationMode(bool check); void OnRotationMode(bool check); void OnDeformationMode(bool check); protected: /*! \brief Invoked when the DataManager selection changed */ virtual void OnSelectionChanged(mitk::DataNode* node); virtual void OnSelectionChanged(std::vector nodes); virtual void NodeRemoved(const mitk::DataNode* node); virtual void NodeChanged(const mitk::DataNode* node); void UpdateView(); QmitkStdMultiWidget* m_MultiWidget; Ui::QmitkDeformableClippingPlaneViewControls m_Controls; private: mitk::DataStorage::SetOfObjects::ConstPointer GetAllClippingPlanes(); mitk::Color GetLabelColor(int label); void DeactivateInteractionButtons(); mitk::DataNode::Pointer m_ReferenceNode; mitk::DataNode::Pointer m_WorkingNode; }; #endif // _QMITKDEFORMABLECLIPPINGPLANEVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp index 0f514e1f47..bf693e6f50 100644 --- a/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp +++ b/Plugins/org.mitk.gui.qt.segmentation/src/internal/QmitkSegmentationView.cpp @@ -1,1247 +1,1247 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "mitkProperties.h" #include "mitkSegTool2D.h" #include "mitkStatusBar.h" #include "QmitkStdMultiWidget.h" #include "QmitkNewSegmentationDialog.h" #include #include #include "QmitkSegmentationView.h" #include "QmitkSegmentationOrganNamesHandling.cpp" #include #include "mitkVtkResliceInterpolationProperty.h" #include "mitkApplicationCursor.h" #include "mitkSegmentationObjectFactory.h" #include "mitkPluginActivator.h" #include "usModuleResource.h" #include "usModuleResourceStream.h" //micro service to get the ToolManager instance #include "mitkToolManagerProvider.h" const std::string QmitkSegmentationView::VIEW_ID = "org.mitk.views.segmentation"; // public methods QmitkSegmentationView::QmitkSegmentationView() - :m_Parent(NULL) + :m_MouseCursorSet(false) + ,m_Parent(NULL) ,m_Controls(NULL) ,m_MultiWidget(NULL) ,m_DataSelectionChanged(false) - ,m_MouseCursorSet(false) { mitk::NodePredicateDataType::Pointer isDwi = mitk::NodePredicateDataType::New("DiffusionImage"); mitk::NodePredicateDataType::Pointer isDti = mitk::NodePredicateDataType::New("TensorImage"); mitk::NodePredicateDataType::Pointer isQbi = mitk::NodePredicateDataType::New("QBallImage"); mitk::NodePredicateOr::Pointer isDiffusionImage = mitk::NodePredicateOr::New(isDwi, isDti); isDiffusionImage = mitk::NodePredicateOr::New(isDiffusionImage, isQbi); m_IsOfTypeImagePredicate = mitk::NodePredicateOr::New(isDiffusionImage, mitk::TNodePredicateDataType::New()); m_IsBinaryPredicate = mitk::NodePredicateProperty::New("binary", mitk::BoolProperty::New(true)); m_IsNotBinaryPredicate = mitk::NodePredicateNot::New( m_IsBinaryPredicate ); m_IsNotABinaryImagePredicate = mitk::NodePredicateAnd::New( m_IsOfTypeImagePredicate, m_IsNotBinaryPredicate ); m_IsABinaryImagePredicate = mitk::NodePredicateAnd::New( m_IsOfTypeImagePredicate, m_IsBinaryPredicate); } QmitkSegmentationView::~QmitkSegmentationView() { delete m_Controls; } void QmitkSegmentationView::NewNodesGenerated() { MITK_WARN<<"Use of deprecated function: NewNodesGenerated!! This function is empty and will be removed in the next time!"; } void QmitkSegmentationView::NewNodeObjectsGenerated(mitk::ToolManager::DataVectorType* nodes) { if (!nodes) return; mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); if (!toolManager) return; for (mitk::ToolManager::DataVectorType::iterator iter = nodes->begin(); iter != nodes->end(); ++iter) { this->FireNodeSelected( *iter ); // only last iteration meaningful, multiple generated objects are not taken into account here } } void QmitkSegmentationView::Visible() { if (m_DataSelectionChanged) { this->OnSelectionChanged(this->GetDataManagerSelection()); } } void QmitkSegmentationView::Activated() { // should be moved to ::BecomesVisible() or similar if( m_Controls ) { m_Controls->m_ManualToolSelectionBox2D->setEnabled( true ); m_Controls->m_ManualToolSelectionBox3D->setEnabled( true ); // m_Controls->m_OrganToolSelectionBox->setEnabled( true ); // m_Controls->m_LesionToolSelectionBox->setEnabled( true ); // m_Controls->m_SlicesInterpolator->Enable3DInterpolation( m_Controls->widgetStack->currentWidget() == m_Controls->pageManual ); mitk::DataStorage::SetOfObjects::ConstPointer segmentations = this->GetDefaultDataStorage()->GetSubset( m_IsABinaryImagePredicate ); mitk::DataStorage::SetOfObjects::ConstPointer image = this->GetDefaultDataStorage()->GetSubset( m_IsNotABinaryImagePredicate ); if (!image->empty()) { OnSelectionChanged(*image->begin()); } for ( mitk::DataStorage::SetOfObjects::const_iterator iter = segmentations->begin(); iter != segmentations->end(); ++iter) { mitk::DataNode* node = *iter; itk::SimpleMemberCommand::Pointer command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationView::OnWorkingNodeVisibilityChanged); m_WorkingDataObserverTags.insert( std::pair( node, node->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command ) ) ); itk::SimpleMemberCommand::Pointer command2 = itk::SimpleMemberCommand::New(); command2->SetCallbackFunction(this, &QmitkSegmentationView::OnBinaryPropertyChanged); m_BinaryPropertyObserverTags.insert( std::pair( node, node->GetProperty("binary")->AddObserver( itk::ModifiedEvent(), command2 ) ) ); } } itk::SimpleMemberCommand::Pointer command3 = itk::SimpleMemberCommand::New(); command3->SetCallbackFunction( this, &QmitkSegmentationView::RenderingManagerReinitialized ); m_RenderingManagerObserverTag = mitk::RenderingManager::GetInstance()->AddObserver( mitk::RenderingManagerViewsInitializedEvent(), command3 ); this->SetToolManagerSelection(m_Controls->patImageSelector->GetSelectedNode(), m_Controls->segImageSelector->GetSelectedNode()); } void QmitkSegmentationView::Deactivated() { if( m_Controls ) { this->SetToolSelectionBoxesEnabled( false ); //deactivate all tools mitk::ToolManagerProvider::GetInstance()->GetToolManager()->ActivateTool(-1); //Removing all observers for ( NodeTagMapType::iterator dataIter = m_WorkingDataObserverTags.begin(); dataIter != m_WorkingDataObserverTags.end(); ++dataIter ) { (*dataIter).first->GetProperty("visible")->RemoveObserver( (*dataIter).second ); } m_WorkingDataObserverTags.clear(); for ( NodeTagMapType::iterator dataIter = m_BinaryPropertyObserverTags.begin(); dataIter != m_BinaryPropertyObserverTags.end(); ++dataIter ) { (*dataIter).first->GetProperty("binary")->RemoveObserver( (*dataIter).second ); } m_BinaryPropertyObserverTags.clear(); mitk::RenderingManager::GetInstance()->RemoveObserver(m_RenderingManagerObserverTag); ctkPluginContext* context = mitk::PluginActivator::getContext(); ctkServiceReference ppmRef = context->getServiceReference(); mitk::PlanePositionManagerService* service = context->getService(ppmRef); service->RemoveAllPlanePositions(); context->ungetService(ppmRef); this->SetToolManagerSelection(0,0); } } void QmitkSegmentationView::StdMultiWidgetAvailable( QmitkStdMultiWidget& stdMultiWidget ) { SetMultiWidget(&stdMultiWidget); } void QmitkSegmentationView::StdMultiWidgetNotAvailable() { SetMultiWidget(NULL); } void QmitkSegmentationView::StdMultiWidgetClosed( QmitkStdMultiWidget& /*stdMultiWidget*/ ) { SetMultiWidget(NULL); } void QmitkSegmentationView::SetMultiWidget(QmitkStdMultiWidget* multiWidget) { // save the current multiwidget as the working widget m_MultiWidget = multiWidget; if (m_Parent) { m_Parent->setEnabled(m_MultiWidget); } // tell the interpolation about toolmanager and multiwidget (and data storage) if (m_Controls && m_MultiWidget) { mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); m_Controls->m_SlicesInterpolator->SetDataStorage( this->GetDefaultDataStorage()); QList controllers; controllers.push_back(m_MultiWidget->GetRenderWindow1()->GetSliceNavigationController()); controllers.push_back(m_MultiWidget->GetRenderWindow2()->GetSliceNavigationController()); controllers.push_back(m_MultiWidget->GetRenderWindow3()->GetSliceNavigationController()); m_Controls->m_SlicesInterpolator->Initialize( toolManager, controllers ); } } void QmitkSegmentationView::OnPreferencesChanged(const berry::IBerryPreferences* prefs) { if (m_Controls != NULL) { bool slimView = prefs->GetBool("slim view", false); m_Controls->m_ManualToolSelectionBox2D->SetShowNames(!slimView); m_Controls->m_ManualToolSelectionBox3D->SetShowNames(!slimView); } m_AutoSelectionEnabled = prefs->GetBool("auto selection", false); this->ForceDisplayPreferencesUponAllImages(); } void QmitkSegmentationView::CreateNewSegmentation() { mitk::DataNode::Pointer node = mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetReferenceData(0); if (node.IsNotNull()) { mitk::Image::Pointer image = dynamic_cast( node->GetData() ); if (image.IsNotNull()) { if (image->GetDimension()>1) { // ask about the name and organ type of the new segmentation QmitkNewSegmentationDialog* dialog = new QmitkNewSegmentationDialog( m_Parent ); // needs a QWidget as parent, "this" is not QWidget QString storedList = this->GetPreferences()->Get("Organ-Color-List",""); QStringList organColors; if (storedList.isEmpty()) { organColors = GetDefaultOrganColorString(); } else { /* a couple of examples of how organ names are stored: a simple item is built up like 'name#AABBCC' where #AABBCC is the hexadecimal notation of a color as known from HTML items are stored separated by ';' this makes it necessary to escape occurrences of ';' in name. otherwise the string "hugo;ypsilon#AABBCC;eugen#AABBCC" could not be parsed as two organs but we would get "hugo" and "ypsilon#AABBCC" and "eugen#AABBCC" so the organ name "hugo;ypsilon" is stored as "hugo\;ypsilon" and must be unescaped after loading the following lines could be one split with Perl's negative lookbehind */ // recover string list from BlueBerry view's preferences QString storedString = this->GetPreferences()->Get("Organ-Color-List",""); MITK_DEBUG << "storedString: " << storedString.toStdString(); // match a string consisting of any number of repetitions of either "anything but ;" or "\;". This matches everything until the next unescaped ';' QRegExp onePart("(?:[^;]|\\\\;)*"); MITK_DEBUG << "matching " << onePart.pattern().toStdString(); int count = 0; int pos = 0; while( (pos = onePart.indexIn( storedString, pos )) != -1 ) { ++count; int length = onePart.matchedLength(); if (length == 0) break; QString matchedString = storedString.mid(pos, length); MITK_DEBUG << " Captured length " << length << ": " << matchedString.toStdString(); pos += length + 1; // skip separating ';' // unescape possible occurrences of '\;' in the string matchedString.replace("\\;", ";"); // add matched string part to output list organColors << matchedString; } MITK_DEBUG << "Captured " << count << " organ name/colors"; } dialog->SetSuggestionList( organColors ); int dialogReturnValue = dialog->exec(); if ( dialogReturnValue == QDialog::Rejected ) return; // user clicked cancel or pressed Esc or something similar // ask the user about an organ type and name, add this information to the image's (!) propertylist // create a new image of the same dimensions and smallest possible pixel type mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); mitk::Tool* firstTool = toolManager->GetToolById(0); if (firstTool) { try { std::string newNodeName = dialog->GetSegmentationName().toStdString(); if(newNodeName.empty()) newNodeName = "no_name"; mitk::DataNode::Pointer emptySegmentation = firstTool->CreateEmptySegmentationNode( image, newNodeName, dialog->GetColor() ); // initialize showVolume to false to prevent recalculating the volume while working on the segmentation emptySegmentation->SetProperty( "showVolume", mitk::BoolProperty::New( false ) ); if (!emptySegmentation) return; // could be aborted by user UpdateOrganList( organColors, dialog->GetSegmentationName(), dialog->GetColor() ); /* escape ';' here (replace by '\;'), see longer comment above */ QString stringForStorage = organColors.replaceInStrings(";","\\;").join(";"); MITK_DEBUG << "Will store: " << stringForStorage; this->GetPreferences()->Put("Organ-Color-List", stringForStorage); this->GetPreferences()->Flush(); if(mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetWorkingData(0)) { mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetWorkingData(0)->SetSelected(false); } emptySegmentation->SetSelected(true); this->GetDefaultDataStorage()->Add( emptySegmentation, node ); // add as a child, because the segmentation "derives" from the original this->ApplyDisplayOptions( emptySegmentation ); this->FireNodeSelected( emptySegmentation ); this->OnSelectionChanged( emptySegmentation ); m_Controls->segImageSelector->SetSelectedNode(emptySegmentation); mitk::RenderingManager::GetInstance()->InitializeViews(emptySegmentation->GetData()->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true ); } catch (std::bad_alloc) { QMessageBox::warning(NULL,"Create new segmentation","Could not allocate memory for new segmentation"); } } } else { QMessageBox::information(NULL,"Segmentation","Segmentation is currently not supported for 2D images"); } } } else { MITK_ERROR << "'Create new segmentation' button should never be clickable unless a patient image is selected..."; } } void QmitkSegmentationView::OnWorkingNodeVisibilityChanged() { mitk::DataNode* selectedNode = m_Controls->segImageSelector->GetSelectedNode(); if ( !selectedNode ) { this->SetToolSelectionBoxesEnabled(false); return; } bool selectedNodeIsVisible = selectedNode->IsVisible(mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1"))); if (!selectedNodeIsVisible) { this->SetToolSelectionBoxesEnabled(false); this->UpdateWarningLabel("The selected segmentation is currently not visible!"); } else { this->SetToolSelectionBoxesEnabled(true); this->UpdateWarningLabel(""); } } void QmitkSegmentationView::OnBinaryPropertyChanged() { mitk::DataStorage::SetOfObjects::ConstPointer patImages = m_Controls->patImageSelector->GetNodes(); bool isBinary(false); for (mitk::DataStorage::SetOfObjects::ConstIterator it = patImages->Begin(); it != patImages->End(); ++it) { const mitk::DataNode* node = it->Value(); node->GetBoolProperty("binary", isBinary); if(isBinary) { m_Controls->patImageSelector->RemoveNode(node); m_Controls->segImageSelector->AddNode(node); this->SetToolManagerSelection(NULL,NULL); return; } } mitk::DataStorage::SetOfObjects::ConstPointer segImages = m_Controls->segImageSelector->GetNodes(); isBinary = true; for (mitk::DataStorage::SetOfObjects::ConstIterator it = segImages->Begin(); it != segImages->End(); ++it) { const mitk::DataNode* node = it->Value(); node->GetBoolProperty("binary", isBinary); if(!isBinary) { m_Controls->segImageSelector->RemoveNode(node); m_Controls->patImageSelector->AddNode(node); if (mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetWorkingData(0) == node) mitk::ToolManagerProvider::GetInstance()->GetToolManager()->SetWorkingData(NULL); return; } } } void QmitkSegmentationView::NodeAdded(const mitk::DataNode *node) { bool isBinary (false); bool isHelperObject (false); node->GetBoolProperty("binary", isBinary); node->GetBoolProperty("helper object", isHelperObject); if (m_AutoSelectionEnabled) { if (!isBinary && dynamic_cast(node->GetData())) { FireNodeSelected(const_cast(node)); } } if (isBinary && !isHelperObject) { itk::SimpleMemberCommand::Pointer command = itk::SimpleMemberCommand::New(); command->SetCallbackFunction(this, &QmitkSegmentationView::OnWorkingNodeVisibilityChanged); m_WorkingDataObserverTags.insert( std::pair( const_cast(node), node->GetProperty("visible")->AddObserver( itk::ModifiedEvent(), command ) ) ); itk::SimpleMemberCommand::Pointer command2 = itk::SimpleMemberCommand::New(); command2->SetCallbackFunction(this, &QmitkSegmentationView::OnBinaryPropertyChanged); m_BinaryPropertyObserverTags.insert( std::pair( const_cast(node), node->GetProperty("binary")->AddObserver( itk::ModifiedEvent(), command2 ) ) ); this->ApplyDisplayOptions( const_cast(node) ); m_Controls->segImageSelector->setCurrentIndex( m_Controls->segImageSelector->Find(node) ); } } void QmitkSegmentationView::NodeRemoved(const mitk::DataNode* node) { bool isSeg(false); bool isHelperObject(false); node->GetBoolProperty("helper object", isHelperObject); node->GetBoolProperty("binary", isSeg); mitk::Image* image = dynamic_cast(node->GetData()); if(isSeg && !isHelperObject && image) { //First of all remove all possible contour markers of the segmentation mitk::DataStorage::SetOfObjects::ConstPointer allContourMarkers = this->GetDataStorage()->GetDerivations(node, mitk::NodePredicateProperty::New("isContourMarker" , mitk::BoolProperty::New(true))); ctkPluginContext* context = mitk::PluginActivator::getContext(); ctkServiceReference ppmRef = context->getServiceReference(); mitk::PlanePositionManagerService* service = context->getService(ppmRef); for (mitk::DataStorage::SetOfObjects::ConstIterator it = allContourMarkers->Begin(); it != allContourMarkers->End(); ++it) { std::string nodeName = node->GetName(); unsigned int t = nodeName.find_last_of(" "); unsigned int id = atof(nodeName.substr(t+1).c_str())-1; service->RemovePlanePosition(id); this->GetDataStorage()->Remove(it->Value()); } context->ungetService(ppmRef); service = NULL; if ((mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetWorkingData(0) == node) && m_Controls->patImageSelector->GetSelectedNode().IsNotNull()) { this->SetToolManagerSelection(mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetReferenceData(0), NULL); this->UpdateWarningLabel("Select or create a segmentation"); } mitk::SurfaceInterpolationController::GetInstance()->RemoveInterpolationSession(image); } mitk::DataNode* tempNode = const_cast(node); //Since the binary property could be changed during runtime by the user if (image && !isHelperObject) { node->GetProperty("visible")->RemoveObserver( m_WorkingDataObserverTags[tempNode] ); m_WorkingDataObserverTags.erase(tempNode); node->GetProperty("binary")->RemoveObserver( m_BinaryPropertyObserverTags[tempNode] ); m_BinaryPropertyObserverTags.erase(tempNode); } if((mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetReferenceData(0) == node)) { //as we don't know which node was actually removed e.g. our reference node, disable 'New Segmentation' button. //consider the case that there is no more image in the datastorage this->SetToolManagerSelection(NULL, NULL); this->SetToolSelectionBoxesEnabled( false ); } } //void QmitkSegmentationView::CreateSegmentationFromSurface() //{ // mitk::DataNode::Pointer surfaceNode = // m_Controls->MaskSurfaces->GetSelectedNode(); // mitk::Surface::Pointer surface(0); // if(surfaceNode.IsNotNull()) // surface = dynamic_cast ( surfaceNode->GetData() ); // if(surface.IsNull()) // { // this->HandleException( "No surface selected.", m_Parent, true); // return; // } // mitk::DataNode::Pointer imageNode // = mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetReferenceData(0); // mitk::Image::Pointer image(0); // if (imageNode.IsNotNull()) // image = dynamic_cast( imageNode->GetData() ); // if(image.IsNull()) // { // this->HandleException( "No image selected.", m_Parent, true); // return; // } // mitk::SurfaceToImageFilter::Pointer s2iFilter // = mitk::SurfaceToImageFilter::New(); // s2iFilter->MakeOutputBinaryOn(); // s2iFilter->SetInput(surface); // s2iFilter->SetImage(image); // s2iFilter->Update(); // mitk::DataNode::Pointer resultNode = mitk::DataNode::New(); // std::string nameOfResultImage = imageNode->GetName(); // nameOfResultImage.append(surfaceNode->GetName()); // resultNode->SetProperty("name", mitk::StringProperty::New(nameOfResultImage) ); // resultNode->SetProperty("binary", mitk::BoolProperty::New(true) ); // resultNode->SetData( s2iFilter->GetOutput() ); // this->GetDataStorage()->Add(resultNode, imageNode); //} //void QmitkSegmentationView::ToolboxStackPageChanged(int id) //{ // // interpolation only with manual tools visible // m_Controls->m_SlicesInterpolator->EnableInterpolation( id == 0 ); // if( id == 0 ) // { // mitk::DataNode::Pointer workingData = mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetWorkingData(0); // if( workingData.IsNotNull() ) // { // m_Controls->segImageSelector->setCurrentIndex( m_Controls->segImageSelector->Find(workingData) ); // } // } // // this is just a workaround, should be removed when all tools support 3D+t // if (id==2) // lesions // { // mitk::DataNode::Pointer node = mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetReferenceData(0); // if (node.IsNotNull()) // { // mitk::Image::Pointer image = dynamic_cast( node->GetData() ); // if (image.IsNotNull()) // { // if (image->GetDimension()>3) // { // m_Controls->widgetStack->setCurrentIndex(0); // QMessageBox::information(NULL,"Segmentation","Lesion segmentation is currently not supported for 4D images"); // } // } // } // } //} // protected void QmitkSegmentationView::OnPatientComboBoxSelectionChanged( const mitk::DataNode* node ) { //mitk::DataNode* selectedNode = const_cast(node); if( node != NULL ) { this->UpdateWarningLabel(""); mitk::DataNode* segNode = m_Controls->segImageSelector->GetSelectedNode(); if (segNode) { mitk::DataStorage::SetOfObjects::ConstPointer possibleParents = this->GetDefaultDataStorage()->GetSources( segNode, m_IsNotABinaryImagePredicate ); bool isSourceNode(false); for (mitk::DataStorage::SetOfObjects::ConstIterator it = possibleParents->Begin(); it != possibleParents->End(); it++) { if (it.Value() == node) isSourceNode = true; } if ( !isSourceNode && (!this->CheckForSameGeometry(segNode, node) || possibleParents->Size() > 0 )) { this->SetToolManagerSelection(node, NULL); this->SetToolSelectionBoxesEnabled( false ); this->UpdateWarningLabel("The selected patient image does not match with the selected segmentation!"); } else if ((!isSourceNode && this->CheckForSameGeometry(segNode, node)) || isSourceNode ) { this->SetToolManagerSelection(node, segNode); //Doing this we can assure that the segmenation is always visible if the segmentation and the patient image are //loaded separately int layer(10); node->GetIntProperty("layer", layer); layer++; segNode->SetProperty("layer", mitk::IntProperty::New(layer)); //this->UpdateWarningLabel(""); RenderingManagerReinitialized(); } } else { this->SetToolManagerSelection(node, NULL); this->SetToolSelectionBoxesEnabled( false ); this->UpdateWarningLabel("Select or create a segmentation"); } } else { this->UpdateWarningLabel("Please load an image!"); this->SetToolSelectionBoxesEnabled( false ); } } void QmitkSegmentationView::OnSegmentationComboBoxSelectionChanged(const mitk::DataNode *node) { if (node == NULL) { this->UpdateWarningLabel("Select or create a segmentation"); this->SetToolSelectionBoxesEnabled( false ); return; } mitk::DataNode* refNode = m_Controls->patImageSelector->GetSelectedNode(); RenderingManagerReinitialized(); if ( m_Controls->lblSegmentationWarnings->isVisible()) // "RenderingManagerReinitialized()" caused a warning. we do not need to go any further return; if (m_AutoSelectionEnabled) { this->OnSelectionChanged(const_cast(node)); } else { mitk::DataStorage::SetOfObjects::ConstPointer possibleParents = this->GetDefaultDataStorage()->GetSources( node, m_IsNotABinaryImagePredicate ); if ( possibleParents->Size() == 1 ) { mitk::DataNode* parentNode = possibleParents->ElementAt(0); if (parentNode != refNode) { this->UpdateWarningLabel("The selected segmentation does not match with the selected patient image!"); this->SetToolSelectionBoxesEnabled( false ); this->SetToolManagerSelection(NULL, node); } else { this->UpdateWarningLabel(""); this->SetToolManagerSelection(refNode, node); } } else if (refNode && this->CheckForSameGeometry(node, refNode)) { this->UpdateWarningLabel(""); this->SetToolManagerSelection(refNode, node); } else if (!refNode || !this->CheckForSameGeometry(node, refNode)) { this->UpdateWarningLabel("Please select or load the according patient image!"); } } if (!node->IsVisible(mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1")))) { this->UpdateWarningLabel("The selected segmentation is currently not visible!"); this->SetToolSelectionBoxesEnabled( false ); } } void QmitkSegmentationView::OnShowMarkerNodes (bool state) { mitk::SegTool2D::Pointer manualSegmentationTool; unsigned int numberOfExistingTools = mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetTools().size(); for(unsigned int i = 0; i < numberOfExistingTools; i++) { manualSegmentationTool = dynamic_cast(mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetToolById(i)); if (manualSegmentationTool) { if(state == true) { manualSegmentationTool->SetShowMarkerNodes( true ); } else { manualSegmentationTool->SetShowMarkerNodes( false ); } } } } void QmitkSegmentationView::OnSelectionChanged(mitk::DataNode* node) { std::vector nodes; nodes.push_back( node ); this->OnSelectionChanged( nodes ); } void QmitkSegmentationView::OnSelectionChanged(std::vector nodes) { if (nodes.size() != 0) { std::string markerName = "Position"; unsigned int numberOfNodes = nodes.size(); std::string nodeName = nodes.at( 0 )->GetName(); if ( ( numberOfNodes == 1 ) && ( nodeName.find( markerName ) == 0) ) { this->OnContourMarkerSelected( nodes.at( 0 ) ); return; } } if (m_AutoSelectionEnabled && this->IsActivated()) { if (nodes.size() == 0 && m_Controls->patImageSelector->GetSelectedNode().IsNull()) { SetToolManagerSelection(NULL,NULL); } else if (nodes.size() == 1) { mitk::DataNode::Pointer selectedNode = nodes.at(0); if(selectedNode.IsNull()) { return; } mitk::Image::Pointer selectedImage = dynamic_cast(selectedNode->GetData()); if (selectedImage.IsNull()) { SetToolManagerSelection(NULL,NULL); return; } else { bool isASegmentation(false); selectedNode->GetBoolProperty("binary", isASegmentation); if (isASegmentation) { //If a segmentation is selected find a possible reference image: mitk::DataStorage::SetOfObjects::ConstPointer sources = this->GetDataStorage()->GetSources(selectedNode, m_IsNotABinaryImagePredicate); mitk::DataNode::Pointer refNode; if (sources->Size() != 0) { refNode = sources->ElementAt(0); refNode->SetVisibility(true); selectedNode->SetVisibility(true); SetToolManagerSelection(refNode,selectedNode); mitk::DataStorage::SetOfObjects::ConstPointer otherSegmentations = this->GetDataStorage()->GetSubset(m_IsABinaryImagePredicate); for(mitk::DataStorage::SetOfObjects::const_iterator iter = otherSegmentations->begin(); iter != otherSegmentations->end(); ++iter) { mitk::DataNode* node = *iter; if (dynamic_cast(node->GetData()) != selectedImage.GetPointer()) node->SetVisibility(false); } mitk::DataStorage::SetOfObjects::ConstPointer otherPatientImages = this->GetDataStorage()->GetSubset(m_IsNotABinaryImagePredicate); for(mitk::DataStorage::SetOfObjects::const_iterator iter = otherPatientImages->begin(); iter != otherPatientImages->end(); ++iter) { mitk::DataNode* node = *iter; if (dynamic_cast(node->GetData()) != dynamic_cast(refNode->GetData())) node->SetVisibility(false); } } else { mitk::DataStorage::SetOfObjects::ConstPointer possiblePatientImages = this->GetDataStorage()->GetSubset(m_IsNotABinaryImagePredicate); for (mitk::DataStorage::SetOfObjects::ConstIterator it = possiblePatientImages->Begin(); it != possiblePatientImages->End(); it++) { refNode = it->Value(); if (this->CheckForSameGeometry(selectedNode, it->Value())) { refNode->SetVisibility(true); selectedNode->SetVisibility(true); mitk::DataStorage::SetOfObjects::ConstPointer otherSegmentations = this->GetDataStorage()->GetSubset(m_IsABinaryImagePredicate); for(mitk::DataStorage::SetOfObjects::const_iterator iter = otherSegmentations->begin(); iter != otherSegmentations->end(); ++iter) { mitk::DataNode* node = *iter; if (dynamic_cast(node->GetData()) != selectedImage.GetPointer()) node->SetVisibility(false); } mitk::DataStorage::SetOfObjects::ConstPointer otherPatientImages = this->GetDataStorage()->GetSubset(m_IsNotABinaryImagePredicate); for(mitk::DataStorage::SetOfObjects::const_iterator iter = otherPatientImages->begin(); iter != otherPatientImages->end(); ++iter) { mitk::DataNode* node = *iter; if (dynamic_cast(node->GetData()) != dynamic_cast(refNode->GetData())) node->SetVisibility(false); } this->SetToolManagerSelection(refNode, selectedNode); //Doing this we can assure that the segmenation is always visible if the segmentation and the patient image are at the //same level in the datamanager int layer(10); refNode->GetIntProperty("layer", layer); layer++; selectedNode->SetProperty("layer", mitk::IntProperty::New(layer)); return; } } this->SetToolManagerSelection(NULL, selectedNode); } } else { if (mitk::ToolManagerProvider::GetInstance()->GetToolManager()->GetReferenceData(0) != selectedNode) { SetToolManagerSelection(selectedNode, NULL); //May be a bug in the selection services. A node which is deselected will be passed as selected node to the OnSelectionChanged function if (!selectedNode->IsVisible(mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1")))) selectedNode->SetVisibility(true); this->UpdateWarningLabel("The selected patient image does not\nmatchwith the selected segmentation!"); this->SetToolSelectionBoxesEnabled( false ); } } } } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); if ( m_Controls->lblSegmentationWarnings->isVisible()) // "RenderingManagerReinitialized()" caused a warning. we do not need to go any further return; RenderingManagerReinitialized(); } } void QmitkSegmentationView::OnContourMarkerSelected(const mitk::DataNode *node) { QmitkRenderWindow* selectedRenderWindow = 0; QmitkRenderWindow* RenderWindow1 = this->GetActiveStdMultiWidget()->GetRenderWindow1(); QmitkRenderWindow* RenderWindow2 = this->GetActiveStdMultiWidget()->GetRenderWindow2(); QmitkRenderWindow* RenderWindow3 = this->GetActiveStdMultiWidget()->GetRenderWindow3(); QmitkRenderWindow* RenderWindow4 = this->GetActiveStdMultiWidget()->GetRenderWindow4(); bool PlanarFigureInitializedWindow = false; // find initialized renderwindow if (node->GetBoolProperty("PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow1->GetRenderer())) { selectedRenderWindow = RenderWindow1; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow2->GetRenderer())) { selectedRenderWindow = RenderWindow2; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow3->GetRenderer())) { selectedRenderWindow = RenderWindow3; } if (!selectedRenderWindow && node->GetBoolProperty( "PlanarFigureInitializedWindow", PlanarFigureInitializedWindow, RenderWindow4->GetRenderer())) { selectedRenderWindow = RenderWindow4; } // make node visible if (selectedRenderWindow) { std::string nodeName = node->GetName(); unsigned int t = nodeName.find_last_of(" "); unsigned int id = atof(nodeName.substr(t+1).c_str())-1; { ctkPluginContext* context = mitk::PluginActivator::getContext(); ctkServiceReference ppmRef = context->getServiceReference(); mitk::PlanePositionManagerService* service = context->getService(ppmRef); selectedRenderWindow->GetSliceNavigationController()->ExecuteOperation(service->GetPlanePosition(id)); context->ungetService(ppmRef); } selectedRenderWindow->GetRenderer()->GetDisplayGeometry()->Fit(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkSegmentationView::OnTabWidgetChanged(int id) { //always disable tools on tab changed mitk::ToolManagerProvider::GetInstance()->GetToolManager()->ActivateTool(-1); //2D Tab ID = 0 //3D Tab ID = 1 if (id == 0) { //Hide 3D selection box, show 2D selection box m_Controls->m_ManualToolSelectionBox3D->hide(); m_Controls->m_ManualToolSelectionBox2D->show(); //Deactivate possible active tool //TODO Remove possible visible interpolations -> Maybe changes in SlicesInterpolator } else { //Hide 3D selection box, show 2D selection box m_Controls->m_ManualToolSelectionBox2D->hide(); m_Controls->m_ManualToolSelectionBox3D->show(); //Deactivate possible active tool } } void QmitkSegmentationView::SetToolManagerSelection(const mitk::DataNode* referenceData, const mitk::DataNode* workingData) { // called as a result of new BlueBerry selections // tells the ToolManager for manual segmentation about new selections // updates GUI information about what the user should select mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); toolManager->SetReferenceData(const_cast(referenceData)); toolManager->SetWorkingData( const_cast(workingData)); // check original image m_Controls->btnNewSegmentation->setEnabled(referenceData != NULL); if (referenceData) { this->UpdateWarningLabel(""); disconnect( m_Controls->patImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnPatientComboBoxSelectionChanged( const mitk::DataNode* ) ) ); m_Controls->patImageSelector->setCurrentIndex( m_Controls->patImageSelector->Find(referenceData) ); connect( m_Controls->patImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnPatientComboBoxSelectionChanged( const mitk::DataNode* ) ) ); } // check segmentation if (referenceData) { if (workingData) { this->FireNodeSelected(const_cast(workingData)); // if( m_Controls->widgetStack->currentIndex() == 0 ) // { disconnect( m_Controls->segImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnSegmentationComboBoxSelectionChanged( const mitk::DataNode* ) ) ); m_Controls->segImageSelector->setCurrentIndex(m_Controls->segImageSelector->Find(workingData)); connect( m_Controls->segImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnSegmentationComboBoxSelectionChanged(const mitk::DataNode*)) ); // } } } } void QmitkSegmentationView::ForceDisplayPreferencesUponAllImages() { if (!m_Parent || !m_Parent->isVisible()) return; // check all images and segmentations in DataStorage: // (items in brackets are implicitly done by previous steps) // 1. // if a reference image is selected, // show the reference image // and hide all other images (orignal and segmentation), // (and hide all segmentations of the other original images) // and show all the reference's segmentations // if no reference image is selected, do do nothing // // 2. // if a segmentation is selected, // show it // (and hide all all its siblings (childs of the same parent, incl, NULL parent)) // if no segmentation is selected, do nothing if (!m_Controls) return; // might happen on initialization (preferences loaded) mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); mitk::DataNode::Pointer referenceData = toolManager->GetReferenceData(0); mitk::DataNode::Pointer workingData = toolManager->GetWorkingData(0); // 1. if (referenceData.IsNotNull()) { // iterate all images mitk::DataStorage::SetOfObjects::ConstPointer allImages = this->GetDefaultDataStorage()->GetSubset( m_IsABinaryImagePredicate ); for ( mitk::DataStorage::SetOfObjects::const_iterator iter = allImages->begin(); iter != allImages->end(); ++iter) { mitk::DataNode* node = *iter; // apply display preferences ApplyDisplayOptions(node); // set visibility node->SetVisibility(node == referenceData); } } // 2. if (workingData.IsNotNull()) workingData->SetVisibility(true); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkSegmentationView::ApplyDisplayOptions(mitk::DataNode* node) { if (!node) return; bool isBinary(false); node->GetPropertyValue("binary", isBinary); if (isBinary) { node->SetProperty( "outline binary", mitk::BoolProperty::New( this->GetPreferences()->GetBool("draw outline", true)) ); node->SetProperty( "outline width", mitk::FloatProperty::New( 2.0 ) ); node->SetProperty( "opacity", mitk::FloatProperty::New( this->GetPreferences()->GetBool("draw outline", true) ? 1.0 : 0.3 ) ); node->SetProperty( "volumerendering", mitk::BoolProperty::New( this->GetPreferences()->GetBool("volume rendering", false) ) ); } } void QmitkSegmentationView::RenderingManagerReinitialized() { if ( ! m_MultiWidget ) { return; } /* * Here we check whether the geometry of the selected segmentation image if aligned with the worldgeometry * At the moment it is not supported to use a geometry different from the selected image for reslicing. * For further information see Bug 16063 */ mitk::DataNode* workingNode = m_Controls->segImageSelector->GetSelectedNode(); const mitk::BaseGeometry* worldGeo = m_MultiWidget->GetRenderWindow4()->GetSliceNavigationController()->GetCurrentGeometry3D(); if (workingNode && worldGeo) { const mitk::BaseGeometry* workingNodeGeo = workingNode->GetData()->GetGeometry(); const mitk::BaseGeometry* worldGeo = m_MultiWidget->GetRenderWindow4()->GetSliceNavigationController()->GetCurrentGeometry3D(); if (mitk::Equal(*workingNodeGeo->GetBoundingBox(), *worldGeo->GetBoundingBox(), mitk::eps, true)) { this->SetToolManagerSelection(m_Controls->patImageSelector->GetSelectedNode(), workingNode); this->SetToolSelectionBoxesEnabled(true); this->UpdateWarningLabel(""); } else { this->SetToolManagerSelection(m_Controls->patImageSelector->GetSelectedNode(), NULL); this->SetToolSelectionBoxesEnabled(false); this->UpdateWarningLabel("Please perform a reinit on the segmentation image!"); } } } bool QmitkSegmentationView::CheckForSameGeometry(const mitk::DataNode *node1, const mitk::DataNode *node2) const { bool isSameGeometry(true); mitk::Image* image1 = dynamic_cast(node1->GetData()); mitk::Image* image2 = dynamic_cast(node2->GetData()); if (image1 && image2) { mitk::BaseGeometry* geo1 = image1->GetGeometry(); mitk::BaseGeometry* geo2 = image2->GetGeometry(); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetOrigin(), geo2->GetOrigin()); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetExtent(0), geo2->GetExtent(0)); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetExtent(1), geo2->GetExtent(1)); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetExtent(2), geo2->GetExtent(2)); isSameGeometry = isSameGeometry && mitk::Equal(geo1->GetSpacing(), geo2->GetSpacing()); isSameGeometry = isSameGeometry && mitk::MatrixEqualElementWise(geo1->GetIndexToWorldTransform()->GetMatrix(), geo2->GetIndexToWorldTransform()->GetMatrix()); return isSameGeometry; } else { return false; } } void QmitkSegmentationView::UpdateWarningLabel(QString text) { if (text.size() == 0) m_Controls->lblSegmentationWarnings->hide(); else m_Controls->lblSegmentationWarnings->show(); m_Controls->lblSegmentationWarnings->setText(text); } void QmitkSegmentationView::CreateQtPartControl(QWidget* parent) { // setup the basic GUI of this view m_Parent = parent; m_Controls = new Ui::QmitkSegmentationControls; m_Controls->setupUi(parent); m_Controls->patImageSelector->SetDataStorage(this->GetDefaultDataStorage()); m_Controls->patImageSelector->SetPredicate(mitk::NodePredicateAnd::New(m_IsNotABinaryImagePredicate, mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))).GetPointer()); this->UpdateWarningLabel("Please load an image"); if( m_Controls->patImageSelector->GetSelectedNode().IsNotNull() ) this->UpdateWarningLabel("Select or create a new segmentation"); m_Controls->segImageSelector->SetDataStorage(this->GetDefaultDataStorage()); m_Controls->segImageSelector->SetPredicate(mitk::NodePredicateAnd::New(m_IsABinaryImagePredicate, mitk::NodePredicateNot::New(mitk::NodePredicateProperty::New("helper object"))).GetPointer()); if( m_Controls->segImageSelector->GetSelectedNode().IsNotNull() ) this->UpdateWarningLabel(""); mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); assert ( toolManager ); toolManager->SetDataStorage( *(this->GetDefaultDataStorage()) ); toolManager->InitializeTools(); // all part of open source MITK m_Controls->m_ManualToolSelectionBox2D->SetGenerateAccelerators(true); m_Controls->m_ManualToolSelectionBox2D->SetToolGUIArea( m_Controls->m_ManualToolGUIContainer2D ); m_Controls->m_ManualToolSelectionBox2D->SetDisplayedToolGroups("Add Subtract Correction Paint Wipe 'Region Growing' Fill Erase 'Live Wire' '2D Fast Marching'"); m_Controls->m_ManualToolSelectionBox2D->SetLayoutColumns(3); m_Controls->m_ManualToolSelectionBox2D->SetEnabledMode( QmitkToolSelectionBox::EnabledWithReferenceAndWorkingDataVisible ); connect( m_Controls->m_ManualToolSelectionBox2D, SIGNAL(ToolSelected(int)), this, SLOT(OnManualTool2DSelected(int)) ); //setup 3D Tools m_Controls->m_ManualToolSelectionBox3D->SetGenerateAccelerators(true); m_Controls->m_ManualToolSelectionBox3D->SetToolGUIArea( m_Controls->m_ManualToolGUIContainer3D ); //specify tools to be added to 3D Tool area m_Controls->m_ManualToolSelectionBox3D->SetDisplayedToolGroups("Threshold 'UL Threshold' Otsu 'Fast Marching 3D' 'Region Growing 3D' Watershed Picking"); m_Controls->m_ManualToolSelectionBox3D->SetLayoutColumns(3); m_Controls->m_ManualToolSelectionBox3D->SetEnabledMode( QmitkToolSelectionBox::EnabledWithReferenceAndWorkingDataVisible ); //Hide 3D selection box, show 2D selection box m_Controls->m_ManualToolSelectionBox3D->hide(); m_Controls->m_ManualToolSelectionBox2D->show(); toolManager->NewNodesGenerated += mitk::MessageDelegate( this, &QmitkSegmentationView::NewNodesGenerated ); // update the list of segmentations toolManager->NewNodeObjectsGenerated += mitk::MessageDelegate1( this, &QmitkSegmentationView::NewNodeObjectsGenerated ); // update the list of segmentations // create signal/slot connections connect( m_Controls->patImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnPatientComboBoxSelectionChanged( const mitk::DataNode* ) ) ); connect( m_Controls->segImageSelector, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), this, SLOT( OnSegmentationComboBoxSelectionChanged( const mitk::DataNode* ) ) ); connect( m_Controls->btnNewSegmentation, SIGNAL(clicked()), this, SLOT(CreateNewSegmentation()) ); // connect( m_Controls->CreateSegmentationFromSurface, SIGNAL(clicked()), this, SLOT(CreateSegmentationFromSurface()) ); // connect( m_Controls->widgetStack, SIGNAL(currentChanged(int)), this, SLOT(ToolboxStackPageChanged(int)) ); connect( m_Controls->tabWidgetSegmentationTools, SIGNAL(currentChanged(int)), this, SLOT(OnTabWidgetChanged(int))); // connect(m_Controls->MaskSurfaces, SIGNAL( OnSelectionChanged( const mitk::DataNode* ) ), // this, SLOT( OnSurfaceSelectionChanged( ) ) ); connect(m_Controls->m_SlicesInterpolator, SIGNAL(SignalShowMarkerNodes(bool)), this, SLOT(OnShowMarkerNodes(bool))); // m_Controls->MaskSurfaces->SetDataStorage(this->GetDefaultDataStorage()); // m_Controls->MaskSurfaces->SetPredicate(mitk::NodePredicateDataType::New("Surface")); } void QmitkSegmentationView::OnManualTool2DSelected(int id) { if (id >= 0) { std::string text = "Active Tool: \""; mitk::ToolManager* toolManager = mitk::ToolManagerProvider::GetInstance()->GetToolManager(); text += toolManager->GetToolById(id)->GetName(); text += "\""; mitk::StatusBar::GetInstance()->DisplayText(text.c_str()); us::ModuleResource resource = toolManager->GetToolById(id)->GetCursorIconResource(); this->SetMouseCursor(resource, 0, 0); } else { this->ResetMouseCursor(); mitk::StatusBar::GetInstance()->DisplayText(""); } } void QmitkSegmentationView::ResetMouseCursor() { if ( m_MouseCursorSet ) { mitk::ApplicationCursor::GetInstance()->PopCursor(); m_MouseCursorSet = false; } } void QmitkSegmentationView::SetMouseCursor( const us::ModuleResource& resource, int hotspotX, int hotspotY ) { if (!resource) return; // Remove previously set mouse cursor if ( m_MouseCursorSet ) { mitk::ApplicationCursor::GetInstance()->PopCursor(); } us::ModuleResourceStream cursor(resource, std::ios::binary); mitk::ApplicationCursor::GetInstance()->PushCursor( cursor, hotspotX, hotspotY ); m_MouseCursorSet = true; } void QmitkSegmentationView::SetToolSelectionBoxesEnabled(bool status) { if (status) { m_Controls->m_ManualToolSelectionBox2D->RecreateButtons(); m_Controls->m_ManualToolSelectionBox3D->RecreateButtons(); } m_Controls->m_ManualToolSelectionBox2D->setEnabled(status); m_Controls->m_ManualToolSelectionBox3D->setEnabled(status); m_Controls->m_SlicesInterpolator->setEnabled(status); } // ATTENTION some methods for handling the known list of (organ names, colors) are defined in QmitkSegmentationOrganNamesHandling.cpp diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/files.cmake b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/files.cmake index b8f7c67c31..8971845b1e 100755 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/files.cmake +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/files.cmake @@ -1,36 +1,37 @@ set(SRC_CPP_FILES QmitkStdMultiWidgetEditor.cpp ) set(INTERNAL_CPP_FILES org_mitk_gui_qt_stdmultiwidgeteditor_Activator.cpp QmitkStdMultiWidgetEditorPreferencePage.cpp ) set(MOC_H_FILES src/QmitkStdMultiWidgetEditor.h src/internal/org_mitk_gui_qt_stdmultiwidgeteditor_Activator.h src/internal/QmitkStdMultiWidgetEditorPreferencePage.h ) set(UI_FILES src/internal/QmitkStdMultiWidgetEditorPreferencePage.ui ) set(CACHED_RESOURCE_FILES plugin.xml + resources/StdMultiWidgetEditor.png ) set(QRC_FILES ) 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/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/plugin.xml b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/plugin.xml index 754a1a2286..e781ecce68 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/plugin.xml +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/plugin.xml @@ -1,28 +1,29 @@ diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/resources/StdMultiWidgetEditor.png b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/resources/StdMultiWidgetEditor.png new file mode 100644 index 0000000000..00cf383e5b Binary files /dev/null and b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/resources/StdMultiWidgetEditor.png differ diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp index 01088e2ff1..bfc9e1ade2 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.cpp @@ -1,558 +1,556 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkStdMultiWidgetEditor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include class QmitkStdMultiWidgetEditorPrivate { public: QmitkStdMultiWidgetEditorPrivate(); ~QmitkStdMultiWidgetEditorPrivate(); QmitkStdMultiWidget* m_StdMultiWidget; QmitkMouseModeSwitcher* m_MouseModeToolbar; /** * @brief Members for the MultiWidget decorations. */ QString m_WidgetBackgroundColor1[4]; QString m_WidgetBackgroundColor2[4]; QString m_WidgetDecorationColor[4]; QString m_WidgetAnnotation[4]; bool m_MenuWidgetsEnabled; QScopedPointer m_PartListener; QHash m_RenderWindows; }; struct QmitkStdMultiWidgetPartListener : public berry::IPartListener { - berryObjectMacro(QmitkStdMultiWidgetPartListener) - QmitkStdMultiWidgetPartListener(QmitkStdMultiWidgetEditorPrivate* dd) : d(dd) {} Events::Types GetPartEventTypes() const { return Events::CLOSED | Events::HIDDEN | Events::VISIBLE; } void PartClosed(const berry::IWorkbenchPartReference::Pointer& partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast(); if (d->m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { d->m_StdMultiWidget->RemovePlanesFromDataStorage(); stdMultiWidgetEditor->RequestActivateMenuWidget(false); } } } void PartHidden(const berry::IWorkbenchPartReference::Pointer& partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast(); if (d->m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { d->m_StdMultiWidget->RemovePlanesFromDataStorage(); stdMultiWidgetEditor->RequestActivateMenuWidget(false); } } } void PartVisible(const berry::IWorkbenchPartReference::Pointer& partRef) { if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast(); if (d->m_StdMultiWidget == stdMultiWidgetEditor->GetStdMultiWidget()) { d->m_StdMultiWidget->AddPlanesToDataStorage(); stdMultiWidgetEditor->RequestActivateMenuWidget(true); } } } private: QmitkStdMultiWidgetEditorPrivate* const d; }; QmitkStdMultiWidgetEditorPrivate::QmitkStdMultiWidgetEditorPrivate() : m_StdMultiWidget(0), m_MouseModeToolbar(0) , m_MenuWidgetsEnabled(false) , m_PartListener(new QmitkStdMultiWidgetPartListener(this)) {} QmitkStdMultiWidgetEditorPrivate::~QmitkStdMultiWidgetEditorPrivate() { } const QString QmitkStdMultiWidgetEditor::EDITOR_ID = "org.mitk.editors.stdmultiwidget"; QmitkStdMultiWidgetEditor::QmitkStdMultiWidgetEditor() : d(new QmitkStdMultiWidgetEditorPrivate) { } QmitkStdMultiWidgetEditor::~QmitkStdMultiWidgetEditor() { this->GetSite()->GetPage()->RemovePartListener(d->m_PartListener.data()); } QmitkStdMultiWidget* QmitkStdMultiWidgetEditor::GetStdMultiWidget() { return d->m_StdMultiWidget; } QmitkRenderWindow *QmitkStdMultiWidgetEditor::GetActiveQmitkRenderWindow() const { if (d->m_StdMultiWidget) return d->m_StdMultiWidget->GetRenderWindow1(); return 0; } QHash QmitkStdMultiWidgetEditor::GetQmitkRenderWindows() const { return d->m_RenderWindows; } QmitkRenderWindow *QmitkStdMultiWidgetEditor::GetQmitkRenderWindow(const QString &id) const { if (d->m_RenderWindows.contains(id)) return d->m_RenderWindows[id]; return 0; } mitk::Point3D QmitkStdMultiWidgetEditor::GetSelectedPosition(const QString & /*id*/) const { return d->m_StdMultiWidget->GetCrossPosition(); } void QmitkStdMultiWidgetEditor::SetSelectedPosition(const mitk::Point3D &pos, const QString &/*id*/) { d->m_StdMultiWidget->MoveCrossToPosition(pos); } void QmitkStdMultiWidgetEditor::EnableDecorations(bool enable, const QStringList &decorations) { if (decorations.isEmpty() || decorations.contains(DECORATION_BORDER)) { enable ? d->m_StdMultiWidget->EnableColoredRectangles() : d->m_StdMultiWidget->DisableColoredRectangles(); } if (decorations.isEmpty() || decorations.contains(DECORATION_LOGO)) { enable ? d->m_StdMultiWidget->EnableDepartmentLogo() : d->m_StdMultiWidget->DisableDepartmentLogo(); } if (decorations.isEmpty() || decorations.contains(DECORATION_MENU)) { d->m_StdMultiWidget->ActivateMenuWidget(enable); } if (decorations.isEmpty() || decorations.contains(DECORATION_BACKGROUND)) { enable ? d->m_StdMultiWidget->EnableGradientBackground() : d->m_StdMultiWidget->DisableGradientBackground(); } } bool QmitkStdMultiWidgetEditor::IsDecorationEnabled(const QString &decoration) const { if (decoration == DECORATION_BORDER) { return d->m_StdMultiWidget->IsColoredRectanglesEnabled(); } else if (decoration == DECORATION_LOGO) { return d->m_StdMultiWidget->IsColoredRectanglesEnabled(); } else if (decoration == DECORATION_MENU) { return d->m_StdMultiWidget->IsMenuWidgetEnabled(); } else if (decoration == DECORATION_BACKGROUND) { return d->m_StdMultiWidget->GetGradientBackgroundFlag(); } return false; } QStringList QmitkStdMultiWidgetEditor::GetDecorations() const { QStringList decorations; decorations << DECORATION_BORDER << DECORATION_LOGO << DECORATION_MENU << DECORATION_BACKGROUND; return decorations; } mitk::SlicesRotator* QmitkStdMultiWidgetEditor::GetSlicesRotator() const { return d->m_StdMultiWidget->GetSlicesRotator(); } mitk::SlicesSwiveller* QmitkStdMultiWidgetEditor::GetSlicesSwiveller() const { return d->m_StdMultiWidget->GetSlicesSwiveller(); } void QmitkStdMultiWidgetEditor::EnableSlicingPlanes(bool enable) { d->m_StdMultiWidget->SetWidgetPlanesVisibility(enable); } bool QmitkStdMultiWidgetEditor::IsSlicingPlanesEnabled() const { mitk::DataNode::Pointer node = this->d->m_StdMultiWidget->GetWidgetPlane1(); if (node.IsNotNull()) { bool visible = false; node->GetVisibility(visible, 0); return visible; } else { return false; } } void QmitkStdMultiWidgetEditor::EnableLinkedNavigation(bool enable) { enable ? d->m_StdMultiWidget->EnableNavigationControllerEventListening() : d->m_StdMultiWidget->DisableNavigationControllerEventListening(); } bool QmitkStdMultiWidgetEditor::IsLinkedNavigationEnabled() const { return d->m_StdMultiWidget->IsCrosshairNavigationEnabled(); } void QmitkStdMultiWidgetEditor::CreateQtPartControl(QWidget* parent) { if (d->m_StdMultiWidget == 0) { QHBoxLayout* layout = new QHBoxLayout(parent); layout->setContentsMargins(0,0,0,0); if (d->m_MouseModeToolbar == NULL) { d->m_MouseModeToolbar = new QmitkMouseModeSwitcher(parent); // delete by Qt via parent layout->addWidget(d->m_MouseModeToolbar); } berry::IPreferences::Pointer prefs = this->GetPreferences(); mitk::BaseRenderer::RenderingMode::Type renderingMode = static_cast(prefs->GetInt( "Rendering Mode" , 0 )); d->m_StdMultiWidget = new QmitkStdMultiWidget(parent,0,0,renderingMode); d->m_RenderWindows.insert("axial", d->m_StdMultiWidget->GetRenderWindow1()); d->m_RenderWindows.insert("sagittal", d->m_StdMultiWidget->GetRenderWindow2()); d->m_RenderWindows.insert("coronal", d->m_StdMultiWidget->GetRenderWindow3()); d->m_RenderWindows.insert("3d", d->m_StdMultiWidget->GetRenderWindow4()); d->m_MouseModeToolbar->setMouseModeSwitcher( d->m_StdMultiWidget->GetMouseModeSwitcher() ); connect( d->m_MouseModeToolbar, SIGNAL( MouseModeSelected(mitk::MouseModeSwitcher::MouseMode) ), d->m_StdMultiWidget, SLOT( MouseModeSelected(mitk::MouseModeSwitcher::MouseMode) ) ); layout->addWidget(d->m_StdMultiWidget); mitk::DataStorage::Pointer ds = this->GetDataStorage(); // Tell the multiWidget which (part of) the tree to render d->m_StdMultiWidget->SetDataStorage(ds); // Initialize views as axial, sagittal, coronar to all data objects in DataStorage // (from top-left to bottom) mitk::TimeGeometry::Pointer geo = ds->ComputeBoundingGeometry3D(ds->GetAll()); mitk::RenderingManager::GetInstance()->InitializeViews(geo); // Initialize bottom-right view as 3D view d->m_StdMultiWidget->GetRenderWindow4()->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D ); // Enable standard handler for levelwindow-slider d->m_StdMultiWidget->EnableStandardLevelWindow(); // Add the displayed views to the tree to see their positions // in 2D and 3D d->m_StdMultiWidget->AddDisplayPlaneSubTree(); d->m_StdMultiWidget->EnableNavigationControllerEventListening(); // Store the initial visibility status of the menu widget. d->m_MenuWidgetsEnabled = d->m_StdMultiWidget->IsMenuWidgetEnabled(); this->GetSite()->GetPage()->AddPartListener(d->m_PartListener.data()); berry::IBerryPreferences* berryprefs = dynamic_cast(prefs.GetPointer()); InitializePreferences(berryprefs); this->OnPreferencesChanged(berryprefs); this->RequestUpdate(); } } void QmitkStdMultiWidgetEditor::OnPreferencesChanged(const berry::IBerryPreferences* prefs) { // Enable change of logo. If no DepartmentLogo was set explicitly, MBILogo is used. // Set new department logo by prefs->Set("DepartmentLogo", "PathToImage"); // If no logo was set for this plug-in specifically, walk the parent preference nodes // and lookup a logo value there. const berry::IPreferences* currentNode = prefs; while(currentNode) { bool logoFound = false; foreach (const QString& key, prefs->Keys()) { if( key == "DepartmentLogo") { QString departmentLogoLocation = prefs->Get("DepartmentLogo", ""); if (departmentLogoLocation.isEmpty()) { d->m_StdMultiWidget->DisableDepartmentLogo(); } else { // we need to disable the logo first, otherwise setting a new logo will have // no effect due to how mitkManufacturerLogo works... d->m_StdMultiWidget->DisableDepartmentLogo(); d->m_StdMultiWidget->SetDepartmentLogoPath(qPrintable(departmentLogoLocation)); d->m_StdMultiWidget->EnableDepartmentLogo(); } logoFound = true; break; } } if (logoFound) break; currentNode = currentNode->Parent().GetPointer(); } //Update internal members this->FillMembersWithCurrentDecorations(); this->GetPreferenceDecorations(prefs); //Now the members can be used to modify the stdmultiwidget mitk::Color upper = HexColorToMitkColor(d->m_WidgetBackgroundColor1[0]); mitk::Color lower = HexColorToMitkColor(d->m_WidgetBackgroundColor2[0]); d->m_StdMultiWidget->SetGradientBackgroundColorForRenderWindow(upper, lower, 0); upper = HexColorToMitkColor(d->m_WidgetBackgroundColor1[1]); lower = HexColorToMitkColor(d->m_WidgetBackgroundColor2[1]); d->m_StdMultiWidget->SetGradientBackgroundColorForRenderWindow(upper, lower, 1); upper = HexColorToMitkColor(d->m_WidgetBackgroundColor1[2]); lower = HexColorToMitkColor(d->m_WidgetBackgroundColor2[2]); d->m_StdMultiWidget->SetGradientBackgroundColorForRenderWindow(upper, lower, 2); upper = HexColorToMitkColor(d->m_WidgetBackgroundColor1[3]); lower = HexColorToMitkColor(d->m_WidgetBackgroundColor2[3]); d->m_StdMultiWidget->SetGradientBackgroundColorForRenderWindow(upper, lower, 3); d->m_StdMultiWidget->EnableGradientBackground(); // preferences for renderWindows mitk::Color colorDecorationWidget1 = HexColorToMitkColor(d->m_WidgetDecorationColor[0]); mitk::Color colorDecorationWidget2 = HexColorToMitkColor(d->m_WidgetDecorationColor[1]); mitk::Color colorDecorationWidget3 = HexColorToMitkColor(d->m_WidgetDecorationColor[2]); mitk::Color colorDecorationWidget4 = HexColorToMitkColor(d->m_WidgetDecorationColor[3]); d->m_StdMultiWidget->SetDecorationColor(0, colorDecorationWidget1); d->m_StdMultiWidget->SetDecorationColor(1, colorDecorationWidget2); d->m_StdMultiWidget->SetDecorationColor(2, colorDecorationWidget3); d->m_StdMultiWidget->SetDecorationColor(3, colorDecorationWidget4); for(unsigned int i = 0; i < 4; ++i) { d->m_StdMultiWidget->SetCornerAnnotation(d->m_WidgetAnnotation[i].toStdString(), HexColorToMitkColor(d->m_WidgetDecorationColor[i]), i); } //The crosshair gap int crosshairgapsize = prefs->GetInt("crosshair gap size", 32); d->m_StdMultiWidget->GetWidgetPlane1()->SetIntProperty("Crosshair.Gap Size", crosshairgapsize); d->m_StdMultiWidget->GetWidgetPlane2()->SetIntProperty("Crosshair.Gap Size", crosshairgapsize); d->m_StdMultiWidget->GetWidgetPlane3()->SetIntProperty("Crosshair.Gap Size", crosshairgapsize); //refresh colors of rectangles d->m_StdMultiWidget->EnableColoredRectangles(); // Set preferences respecting zooming and padding bool constrainedZooming = prefs->GetBool("Use constrained zooming and padding", false); mitk::RenderingManager::GetInstance()->SetConstrainedPaddingZooming(constrainedZooming); mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage()); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); // level window setting bool showLevelWindowWidget = prefs->GetBool("Show level/window widget", true); if (showLevelWindowWidget) { d->m_StdMultiWidget->EnableStandardLevelWindow(); } else { d->m_StdMultiWidget->DisableStandardLevelWindow(); } // mouse modes toolbar bool newMode = prefs->GetBool("PACS like mouse interaction", false); d->m_MouseModeToolbar->setVisible( newMode ); d->m_StdMultiWidget->GetMouseModeSwitcher()->SetInteractionScheme( newMode ? mitk::MouseModeSwitcher::PACS : mitk::MouseModeSwitcher::MITK ); } mitk::Color QmitkStdMultiWidgetEditor::HexColorToMitkColor(const QString& widgetColorInHex) { QColor qColor(widgetColorInHex); mitk::Color returnColor; float colorMax = 255.0f; if (widgetColorInHex.isEmpty()) // default value { returnColor[0] = 1.0; returnColor[1] = 1.0; returnColor[2] = 1.0; MITK_ERROR << "Using default color for unknown widget " << qPrintable(widgetColorInHex); } else { returnColor[0] = qColor.red() / colorMax; returnColor[1] = qColor.green() / colorMax; returnColor[2] = qColor.blue() / colorMax; } return returnColor; } QString QmitkStdMultiWidgetEditor::MitkColorToHex(const mitk::Color& color) { QColor returnColor; float colorMax = 255.0f; returnColor.setRed(static_cast(color[0]* colorMax + 0.5)); returnColor.setGreen(static_cast(color[1]* colorMax + 0.5)); returnColor.setBlue(static_cast(color[2]* colorMax + 0.5)); return returnColor.name(); } void QmitkStdMultiWidgetEditor::FillMembersWithCurrentDecorations() { //fill members with current values (or default values) from the std multi widget for(unsigned int i = 0; i < 4; ++i) { d->m_WidgetDecorationColor[i] = MitkColorToHex(d->m_StdMultiWidget->GetDecorationColor(i)); d->m_WidgetBackgroundColor1[i] = MitkColorToHex(d->m_StdMultiWidget->GetGradientColors(i).first); d->m_WidgetBackgroundColor2[i] = MitkColorToHex(d->m_StdMultiWidget->GetGradientColors(i).second); d->m_WidgetAnnotation[i] = QString::fromStdString(d->m_StdMultiWidget->GetCornerAnnotationText(i)); } } void QmitkStdMultiWidgetEditor::GetPreferenceDecorations(const berry::IBerryPreferences * preferences) { //overwrite members with values from the preferences, if they the prefrence is defined d->m_WidgetBackgroundColor1[0] = preferences->Get("widget1 first background color", d->m_WidgetBackgroundColor1[0]); d->m_WidgetBackgroundColor2[0] = preferences->Get("widget1 second background color", d->m_WidgetBackgroundColor2[0]); d->m_WidgetBackgroundColor1[1] = preferences->Get("widget2 first background color", d->m_WidgetBackgroundColor1[1]); d->m_WidgetBackgroundColor2[1] = preferences->Get("widget2 second background color", d->m_WidgetBackgroundColor2[1]); d->m_WidgetBackgroundColor1[2] = preferences->Get("widget3 first background color", d->m_WidgetBackgroundColor1[2]); d->m_WidgetBackgroundColor2[2] = preferences->Get("widget3 second background color", d->m_WidgetBackgroundColor2[2]); d->m_WidgetBackgroundColor1[3] = preferences->Get("widget4 first background color", d->m_WidgetBackgroundColor1[3]); d->m_WidgetBackgroundColor2[3] = preferences->Get("widget4 second background color", d->m_WidgetBackgroundColor2[3]); d->m_WidgetDecorationColor[0] = preferences->Get("widget1 decoration color", d->m_WidgetDecorationColor[0]); d->m_WidgetDecorationColor[1] = preferences->Get("widget2 decoration color", d->m_WidgetDecorationColor[1]); d->m_WidgetDecorationColor[2] = preferences->Get("widget3 decoration color", d->m_WidgetDecorationColor[2]); d->m_WidgetDecorationColor[3] = preferences->Get("widget4 decoration color", d->m_WidgetDecorationColor[3]); d->m_WidgetAnnotation[0] = preferences->Get("widget1 corner annotation", d->m_WidgetAnnotation[0]); d->m_WidgetAnnotation[1] = preferences->Get("widget2 corner annotation", d->m_WidgetAnnotation[1]); d->m_WidgetAnnotation[2] = preferences->Get("widget3 corner annotation", d->m_WidgetAnnotation[2]); d->m_WidgetAnnotation[3] = preferences->Get("widget4 corner annotation", d->m_WidgetAnnotation[3]); } void QmitkStdMultiWidgetEditor::InitializePreferences(berry::IBerryPreferences * preferences) { this->FillMembersWithCurrentDecorations(); //fill members this->GetPreferenceDecorations(preferences); //overwrite if preferences are defined //create new preferences preferences->Put("widget1 corner annotation", d->m_WidgetAnnotation[0]); preferences->Put("widget2 corner annotation", d->m_WidgetAnnotation[1]); preferences->Put("widget3 corner annotation", d->m_WidgetAnnotation[2]); preferences->Put("widget4 corner annotation", d->m_WidgetAnnotation[3]); preferences->Put("widget1 decoration color", d->m_WidgetDecorationColor[0]); preferences->Put("widget2 decoration color", d->m_WidgetDecorationColor[1]); preferences->Put("widget3 decoration color", d->m_WidgetDecorationColor[2]); preferences->Put("widget4 decoration color", d->m_WidgetDecorationColor[3]); preferences->Put("widget1 first background color", d->m_WidgetBackgroundColor1[0]); preferences->Put("widget2 first background color", d->m_WidgetBackgroundColor1[1]); preferences->Put("widget3 first background color", d->m_WidgetBackgroundColor1[2]); preferences->Put("widget4 first background color", d->m_WidgetBackgroundColor1[3]); preferences->Put("widget1 second background color", d->m_WidgetBackgroundColor2[0]); preferences->Put("widget2 second background color", d->m_WidgetBackgroundColor2[1]); preferences->Put("widget3 second background color", d->m_WidgetBackgroundColor2[2]); preferences->Put("widget4 second background color", d->m_WidgetBackgroundColor2[3]); } void QmitkStdMultiWidgetEditor::SetFocus() { if (d->m_StdMultiWidget != 0) d->m_StdMultiWidget->setFocus(); } void QmitkStdMultiWidgetEditor::RequestActivateMenuWidget(bool on) { if (d->m_StdMultiWidget) { if (on) { d->m_StdMultiWidget->ActivateMenuWidget(d->m_MenuWidgetsEnabled); } else { d->m_MenuWidgetsEnabled = d->m_StdMultiWidget->IsMenuWidgetEnabled(); d->m_StdMultiWidget->ActivateMenuWidget(false); } } } diff --git a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h index 7045b9fb0b..132dfaa18d 100644 --- a/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h +++ b/Plugins/org.mitk.gui.qt.stdmultiwidgeteditor/src/QmitkStdMultiWidgetEditor.h @@ -1,154 +1,154 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkStdMultiWidgetEditor_h #define QmitkStdMultiWidgetEditor_h #include #include #include class QmitkStdMultiWidget; class QmitkMouseModeSwitcher; class QmitkStdMultiWidgetEditorPrivate; /** * \ingroup org_mitk_gui_qt_stdmultiwidgeteditor */ class ORG_MITK_GUI_QT_STDMULTIWIDGETEDITOR QmitkStdMultiWidgetEditor : public QmitkAbstractRenderEditor, public mitk::ILinkedRenderWindowPart { Q_OBJECT public: - berryObjectMacro(QmitkStdMultiWidgetEditor); + berryObjectMacro(QmitkStdMultiWidgetEditor) static const QString EDITOR_ID; QmitkStdMultiWidgetEditor(); ~QmitkStdMultiWidgetEditor(); QmitkStdMultiWidget* GetStdMultiWidget(); /// \brief If on=true will request the QmitkStdMultiWidget set the Menu widget to /// whatever was the last known enabled state, and if on=false will turn the Menu widget off. void RequestActivateMenuWidget(bool on); // ------------------- mitk::IRenderWindowPart ---------------------- /** * \see mitk::IRenderWindowPart::GetActiveQmitkRenderWindow() */ QmitkRenderWindow* GetActiveQmitkRenderWindow() const; /** * \see mitk::IRenderWindowPart::GetQmitkRenderWindows() */ QHash GetQmitkRenderWindows() const; /** * \see mitk::IRenderWindowPart::GetQmitkRenderWindow(QString) */ QmitkRenderWindow* GetQmitkRenderWindow(const QString& id) const; /** * \see mitk::IRenderWindowPart::GetSelectionPosition() */ mitk::Point3D GetSelectedPosition(const QString& id = QString()) const; /** * \see mitk::IRenderWindowPart::SetSelectedPosition() */ void SetSelectedPosition(const mitk::Point3D& pos, const QString& id = QString()); /** * \see mitk::IRenderWindowPart::EnableDecorations() */ void EnableDecorations(bool enable, const QStringList& decorations = QStringList()); /** * \see mitk::IRenderWindowPart::IsDecorationEnabled() */ bool IsDecorationEnabled(const QString& decoration) const; /** * \see mitk::IRenderWindowPart::GetDecorations() */ QStringList GetDecorations() const; // ------------------- mitk::ILinkedRenderWindowPart ---------------------- mitk::SlicesRotator* GetSlicesRotator() const; mitk::SlicesSwiveller* GetSlicesSwiveller() const; void EnableSlicingPlanes(bool enable); bool IsSlicingPlanesEnabled() const; void EnableLinkedNavigation(bool enable); bool IsLinkedNavigationEnabled() const; protected: /** * @brief FillMembersWithCurrentDecorations Helper method to fill internal members with * current values of the std multi widget. */ void FillMembersWithCurrentDecorations(); /** * @brief GetPreferenceDecorations Getter to fill internal members with values of preferences. * @param preferences The berry preferences. * * If a preference is set, the value will overwrite the current value. If it does not exist, * the value will not change. */ void GetPreferenceDecorations(const berry::IBerryPreferences *preferences); void SetFocus(); void OnPreferencesChanged(const berry::IBerryPreferences*); void CreateQtPartControl(QWidget* parent); /** * @brief GetColorForWidget helper method to convert a saved color string to mitk::Color. * @param widgetColorInHex color in hex format (#12356) where each diget is in the form (0-F). * @return the color in mitk format. */ mitk::Color HexColorToMitkColor(const QString& widgetColorInHex); /** * @brief MitkColorToHex Convert an mitk::Color to hex string. * @param color mitk format. * @return String in hex (#RRGGBB). */ QString MitkColorToHex(const mitk::Color& color); /** * @brief InitializePreferences Internal helper method to set default preferences. * This method is used to show the current preferences in the first call of * the preference page (the GUI). * * @param preferences berry preferences. */ void InitializePreferences(berry::IBerryPreferences *preferences); private: const QScopedPointer d; }; #endif /*QmitkStdMultiWidgetEditor_h*/ diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/files.cmake b/Plugins/org.mitk.gui.qt.viewnavigator/files.cmake index 74b6c45511..0e4f1270fb 100644 --- a/Plugins/org.mitk.gui.qt.viewnavigator/files.cmake +++ b/Plugins/org.mitk.gui.qt.viewnavigator/files.cmake @@ -1,50 +1,47 @@ set(SRC_CPP_FILES QmitkViewNavigatorWidget.cpp - QmitkNewPerspectiveDialog.cpp # mitkQtPerspectiveItem.h # mitkQtViewItem.h ) set(INTERNAL_CPP_FILES org_mitk_gui_qt_viewnavigator_Activator.cpp ViewNavigatorView.cpp ) set(UI_FILES - src/internal/ViewNavigatorViewControls.ui src/QmitkViewNavigatorWidgetControls.ui ) set(MOC_H_FILES src/internal/org_mitk_gui_qt_viewnavigator_Activator.h src/internal/ViewNavigatorView.h src/QmitkViewNavigatorWidget.h - src/QmitkNewPerspectiveDialog.h ) # list of resource files which can be used by the plug-in # system without loading the plug-ins shared library, # for example the icon used in the menu and tabs for the # plug-in views in the workbench set(CACHED_RESOURCE_FILES resources/view-manager_48.png plugin.xml ) # list of Qt .qrc files which contain additional resources # specific to this plugin set(QRC_FILES ) 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/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkNewPerspectiveDialog.cpp b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkNewPerspectiveDialog.cpp deleted file mode 100644 index f177ba6361..0000000000 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkNewPerspectiveDialog.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY 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 "QmitkNewPerspectiveDialog.h" - -#include "mitkOrganTypeProperty.h" - -#include - -#include -#include -#include -#include -#include -#include -#include - -QmitkNewPerspectiveDialog::QmitkNewPerspectiveDialog(QWidget* parent) - :QDialog(parent) -{ - QGridLayout* formGridLayout = new QGridLayout( this ); - - QLabel* label = new QLabel( "Perspective name:", this ); - - m_PerspectiveNameLineEdit = new QLineEdit( "", this ); - m_PerspectiveNameLineEdit->setFocus(); - - m_AcceptNameButton = new QPushButton( tr("Ok"), this ); - m_AcceptNameButton->setDefault(true); - m_AcceptNameButton->setEnabled(false); - - QPushButton* rejectNameButton = new QPushButton( tr("Cancel"), this ); - - formGridLayout->addWidget(label, 0, 0); - formGridLayout->addWidget(m_PerspectiveNameLineEdit, 0, 1); - formGridLayout->addWidget(m_AcceptNameButton, 1, 0); - formGridLayout->addWidget(rejectNameButton, 1, 1); - setLayout(formGridLayout); - - // create connections - connect( rejectNameButton, SIGNAL(clicked()), this, SLOT(reject()) ); - connect( m_AcceptNameButton, SIGNAL(clicked()), this, SLOT(OnAcceptClicked()) ); - connect( m_PerspectiveNameLineEdit, SIGNAL(textEdited(const QString&)), this, SLOT(OnPerspectiveNameChanged(const QString&)) ); -} - -QmitkNewPerspectiveDialog::~QmitkNewPerspectiveDialog() -{ -} - -void QmitkNewPerspectiveDialog::SetPerspectiveName(QString name) -{ - m_PerspectiveNameLineEdit->setText(name); - OnPerspectiveNameChanged(name); -} - -void QmitkNewPerspectiveDialog::OnAcceptClicked() -{ - m_PerspectiveName = m_PerspectiveNameLineEdit->text(); - this->accept(); -} - -const QString QmitkNewPerspectiveDialog::GetPerspectiveName() -{ - return m_PerspectiveName; -} - -void QmitkNewPerspectiveDialog::OnPerspectiveNameChanged(const QString& newText) -{ - if (!newText.isEmpty()) - m_AcceptNameButton->setEnabled(true); - else - m_AcceptNameButton->setEnabled(false); -} diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkNewPerspectiveDialog.h b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkNewPerspectiveDialog.h deleted file mode 100644 index 5c07105962..0000000000 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkNewPerspectiveDialog.h +++ /dev/null @@ -1,70 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef QmitkNewPerspectiveDialog_h_Included -#define QmitkNewPerspectiveDialog_h_Included - -#include "mitkColorProperty.h" - -#include -#include - -class QLabel; -class QLineEdit; -class Q3ListBox; -class QPushButton; - -#include - -/** - \brief Dialog for QmitkInteractiveSegmentation. - - \ingroup ToolManagerEtAl - \ingroup Widgets - - This dialog is used to ask a user about the type of a newly created segmentation and a name for it. - - \warning Will not create a new organ type in the OrganTypeProperty. Client has to do that. - - Last contribution by $Author: maleike $. -*/ -class QmitkNewPerspectiveDialog : public QDialog -{ - Q_OBJECT - -public: - - QmitkNewPerspectiveDialog(QWidget* parent = 0); - virtual ~QmitkNewPerspectiveDialog(); - - const QString GetPerspectiveName(); - void SetPerspectiveName(QString name); - -signals: - -protected slots: - - void OnAcceptClicked(); - void OnPerspectiveNameChanged(const QString&); - -protected: - - QLineEdit* m_PerspectiveNameLineEdit; - QPushButton* m_AcceptNameButton; - QString m_PerspectiveName; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp index e593e36dd1..7986aa64ed 100644 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp +++ b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.cpp @@ -1,785 +1,693 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //Qmitk headers #include "QmitkViewNavigatorWidget.h" // Blueberry #include #include #include #include #include #include #include +#include +#include +#include + +// MITK +#include // Qt #include #include #include #include #include class KeywordRegistry { public: KeywordRegistry() { berry::IExtensionRegistry* extensionPointService = berry::Platform::GetExtensionRegistry(); auto keywordExts = extensionPointService->GetConfigurationElementsFor("org.blueberry.ui.keywords"); for (auto keywordExtsIt = keywordExts.begin(); keywordExtsIt != keywordExts.end(); ++keywordExtsIt) { QString keywordId = (*keywordExtsIt)->GetAttribute("id"); QString keywordLabels = (*keywordExtsIt)->GetAttribute("label"); m_Keywords[keywordId].push_back(keywordLabels); } } QStringList GetKeywords(const QString& id) { return m_Keywords[id]; } QStringList GetKeywords(const QStringList& ids) { QStringList result; for (int i = 0; i < ids.size(); ++i) { result.append(this->GetKeywords(ids[i])); } return result; } private: QHash m_Keywords; }; class ClassFilterProxyModel : public QSortFilterProxyModel { private : bool hasToBeDisplayed(const QModelIndex index) const; bool displayElement(const QModelIndex index) const; public: ClassFilterProxyModel(QObject *parent = NULL); bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; }; ClassFilterProxyModel::ClassFilterProxyModel(QObject *parent): QSortFilterProxyModel(parent) { } bool ClassFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); return hasToBeDisplayed(index); } bool ClassFilterProxyModel::displayElement(const QModelIndex index) const { bool result = false; QString type = sourceModel()->data(index, Qt::DisplayRole).toString(); QStandardItem * item = dynamic_cast(sourceModel())->itemFromIndex(index); if (type.contains(filterRegExp())) { return true; } { mitk::QtViewItem* viewItem = dynamic_cast(item); if (viewItem) { for (int i = 0; i < viewItem->m_Tags.size(); ++i) { if (viewItem->m_Tags[i].contains(filterRegExp())) { return true; } } if (viewItem->m_Description.contains(filterRegExp())) { return true; } } } { mitk::QtPerspectiveItem* viewItem = dynamic_cast(item); if (viewItem) { for (int i = 0; i < viewItem->m_Tags.size(); ++i) { if (viewItem->m_Tags[i].contains(filterRegExp())) { return true; } } if (viewItem->m_Description.contains(filterRegExp())) { return true; } } } return result; } bool ClassFilterProxyModel::hasToBeDisplayed(const QModelIndex index) const { bool result = false; if ( sourceModel()->rowCount(index) > 0 ) { for( int ii = 0; ii < sourceModel()->rowCount(index); ii++) { QModelIndex childIndex = sourceModel()->index(ii,0,index); if ( ! childIndex.isValid() ) break; result = hasToBeDisplayed(childIndex); result |= displayElement(index); if (result) { break; } } } else { result = displayElement(index); } return result; } class ViewNavigatorPerspectiveListener: public berry::IPerspectiveListener { public: ViewNavigatorPerspectiveListener(QmitkViewNavigatorWidget* p) : parentWidget(p) { } Events::Types GetPerspectiveEventTypes() const { return Events::ACTIVATED | Events::SAVED_AS | Events::DEACTIVATED // remove the following line when command framework is finished | Events::CLOSED | Events::OPENED | Events::PART_CHANGED; } void PerspectiveActivated(const berry::IWorkbenchPage::Pointer& /*page*/, - const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) + const berry::IPerspectiveDescriptor::Pointer& perspective) { + parentWidget->m_ActivePerspective = perspective; parentWidget->UpdateTreeList(); } void PerspectiveSavedAs(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*oldPerspective*/, - const berry::IPerspectiveDescriptor::Pointer& /*newPerspective*/) + const berry::IPerspectiveDescriptor::Pointer& newPerspective) { - + parentWidget->m_ActivePerspective = newPerspective; + parentWidget->UpdateTreeList(); } void PerspectiveDeactivated(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { - parentWidget->UpdateTreeList(); + parentWidget->m_ActivePerspective = 0; + parentWidget->UpdateTreeList(); } void PerspectiveOpened(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { parentWidget->UpdateTreeList(); } void PerspectiveClosed(const berry::IWorkbenchPage::Pointer& /*page*/, const berry::IPerspectiveDescriptor::Pointer& /*perspective*/) { - parentWidget->UpdateTreeList(); + parentWidget->m_ActivePerspective = 0; + parentWidget->UpdateTreeList(); } using IPerspectiveListener::PerspectiveChanged; void PerspectiveChanged(const berry::IWorkbenchPage::Pointer&, const berry::IPerspectiveDescriptor::Pointer&, const berry::IWorkbenchPartReference::Pointer& partRef, const std::string& changeId) { if (changeId=="viewHide" && partRef->GetId()=="org.mitk.views.viewnavigatorview") berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->RemovePerspectiveListener(parentWidget->m_PerspectiveListener.data()); else parentWidget->UpdateTreeList(NULL, partRef.GetPointer(), changeId); } private: QmitkViewNavigatorWidget* parentWidget; }; -struct ViewNavigatorWindowListener : public berry::IWindowListener -{ - ViewNavigatorWindowListener(QmitkViewNavigatorWidget* switcher) - : switcher(switcher) - , m_Done(false) - {} - - virtual void WindowOpened(const berry::IWorkbenchWindow::Pointer& window) - { - if (m_Done) - return; - if ( switcher->FillTreeList() ) - { - m_Done = true; - switcher->m_PerspectiveListener.reset(new ViewNavigatorPerspectiveListener(switcher)); - window->AddPerspectiveListener(switcher->m_PerspectiveListener.data()); - } - } - - virtual void WindowActivated(const berry::IWorkbenchWindow::Pointer& window) - { - if (m_Done) - return; - if ( switcher->FillTreeList() ) - { - m_Done = true; - switcher->m_PerspectiveListener.reset(new ViewNavigatorPerspectiveListener(switcher)); - window->AddPerspectiveListener(switcher->m_PerspectiveListener.data()); - } - } - -private: - QmitkViewNavigatorWidget* switcher; - bool m_Done; -}; - bool compareViews(const berry::IViewDescriptor::Pointer& a, const berry::IViewDescriptor::Pointer& b) { if (a.IsNull() || b.IsNull()) return false; return a->GetLabel().compare(b->GetLabel()) < 0; } bool comparePerspectives(const berry::IPerspectiveDescriptor::Pointer& a, const berry::IPerspectiveDescriptor::Pointer& b) { if (a.IsNull() || b.IsNull()) return false; return a->GetLabel().compare(b->GetLabel()) < 0; } bool compareQStandardItems(const QStandardItem* a, const QStandardItem* b) { if (a==NULL || b==NULL) return false; return a->text().compare(b->text()) < 0; } -QmitkViewNavigatorWidget::QmitkViewNavigatorWidget( QWidget * parent, Qt::WindowFlags ) +QmitkViewNavigatorWidget::QmitkViewNavigatorWidget(berry::IWorkbenchWindow::Pointer window, + QWidget * parent, Qt::WindowFlags ) : QWidget(parent) + , m_Window(window) { m_Generated = false; this->CreateQtPartControl(this); } QmitkViewNavigatorWidget::~QmitkViewNavigatorWidget() { - + m_Window->RemovePerspectiveListener(m_PerspectiveListener.data()); } void QmitkViewNavigatorWidget::setFocus() { m_Controls.lineEdit->setFocus(); } void QmitkViewNavigatorWidget::CreateQtPartControl( QWidget *parent ) { // create GUI widgets from the Qt Designer's .ui file - if (berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow().IsNotNull()) - { - m_PerspectiveListener.reset(new ViewNavigatorPerspectiveListener(this)); - berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->AddPerspectiveListener(m_PerspectiveListener.data()); - } - else - { - m_WindowListener.reset(new ViewNavigatorWindowListener(this)); - berry::PlatformUI::GetWorkbench()->AddWindowListener(m_WindowListener.data()); - } + m_PerspectiveListener.reset(new ViewNavigatorPerspectiveListener(this)); + m_Window->AddPerspectiveListener(m_PerspectiveListener.data()); m_Parent = parent; m_Controls.setupUi( parent ); connect( m_Controls.m_PluginTreeView, SIGNAL(customContextMenuRequested(QPoint)), SLOT(CustomMenuRequested(QPoint))); connect( m_Controls.m_PluginTreeView, SIGNAL(doubleClicked(const QModelIndex&)), SLOT(ItemClicked(const QModelIndex&))); connect( m_Controls.lineEdit, SIGNAL(textChanged(QString)), SLOT(FilterChanged())); m_ContextMenu = new QMenu(m_Controls.m_PluginTreeView); m_Controls.m_PluginTreeView->setContextMenuPolicy(Qt::CustomContextMenu); // Create a new TreeModel for the data m_TreeModel = new QStandardItemModel(); m_FilterProxyModel = new ClassFilterProxyModel(this); m_FilterProxyModel->setSourceModel(m_TreeModel); //proxyModel->setFilterFixedString("Diff"); m_Controls.m_PluginTreeView->setModel(m_FilterProxyModel); + + this->UpdateTreeList(); } void QmitkViewNavigatorWidget::UpdateTreeList(QStandardItem* root, berry::IWorkbenchPartReference *partRef, const std::string &changeId) { - berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); + berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage(); if (page.IsNull()) return; if( !m_Generated ) { m_Generated = FillTreeList(); } if (root==NULL) root = m_TreeModel->invisibleRootItem(); for (int i=0; irowCount(); i++) { QStandardItem* item = root->child(i); QFont font; if (dynamic_cast(item)) { mitk::QtPerspectiveItem* pItem = dynamic_cast(item); berry::IPerspectiveDescriptor::Pointer currentPersp = page->GetPerspective(); if (currentPersp.IsNotNull() && currentPersp->GetId()==pItem->m_Perspective->GetId()) font.setBold(true); pItem->setFont(font); } mitk::QtViewItem* vItem = dynamic_cast(item); if (vItem) { QList viewParts(page->GetViews()); for (int i=0; iGetPartName()==vItem->m_View->GetLabel()) { font.setBold(true); break; } if( partRef!=NULL && partRef->GetId()==vItem->m_View->GetId() && changeId=="viewHide") font.setBold(false); vItem->setFont(font); } UpdateTreeList(item, partRef, changeId); } } bool QmitkViewNavigatorWidget::FillTreeList() { // active workbench window available? - if (berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow().IsNull()) + if (m_Window.IsNull()) return false; // active page available? - berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); + berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage(); if (page.IsNull()) return false; // everything is fine and we can remove the window listener if (m_WindowListener != nullptr) berry::PlatformUI::GetWorkbench()->RemoveWindowListener(m_WindowListener.data()); // initialize tree model m_TreeModel->clear(); QStandardItem *treeRootItem = m_TreeModel->invisibleRootItem(); // get all available perspectives berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); QList perspectiveDescriptors(perspRegistry->GetPerspectives()); qSort(perspectiveDescriptors.begin(), perspectiveDescriptors.end(), comparePerspectives); // get all Keywords KeywordRegistry keywordRegistry; berry::IPerspectiveDescriptor::Pointer currentPersp = page->GetPerspective(); - QStringList perspectiveExcludeList = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetPerspectiveExcludeList(); + //QStringList perspectiveExcludeList = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetPerspectiveExcludeList(); std::vector< QStandardItem* > categoryItems; QStandardItem *perspectiveRootItem = new QStandardItem("Workflows"); perspectiveRootItem->setEditable(false); perspectiveRootItem->setFont(QFont("", 12, QFont::Normal)); treeRootItem->appendRow(perspectiveRootItem); for (int i=0; iGetId()) { skipPerspective = true; break; } if (skipPerspective) continue; - +*/ //QIcon* pIcon = static_cast(p->GetImageDescriptor()->CreateImage()); mitk::QtPerspectiveItem* pItem = new mitk::QtPerspectiveItem(p->GetLabel()); pItem->m_Perspective = p; pItem->m_Description = p->GetDescription(); QStringList keylist = p->GetKeywordReferences(); pItem->m_Tags = keywordRegistry.GetKeywords(keylist); pItem->setEditable(false); QFont font; font.setBold(true); if (currentPersp.IsNotNull() && currentPersp->GetId()==p->GetId()) pItem->setFont(font); QStringList catPath = p->GetCategoryPath(); if (catPath.isEmpty()) { perspectiveRootItem->appendRow(pItem); } else { QStandardItem* categoryItem = NULL; for (unsigned int c=0; ctext() == catPath.front()) { categoryItem = categoryItems.at(c); break; } } if (categoryItem==NULL) { categoryItem = new QStandardItem(QIcon(),catPath.front()); categoryItems.push_back(categoryItem); } categoryItem->setEditable(false); categoryItem->appendRow(pItem); categoryItem->setFont(QFont("", 12, QFont::Normal)); } } std::sort(categoryItems.begin(), categoryItems.end(), compareQStandardItems); for (unsigned int i=0; iappendRow(categoryItems.at(i)); // get all available views berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); QList viewDescriptors(viewRegistry->GetViews()); QList viewParts(page->GetViews()); qSort(viewDescriptors.begin(), viewDescriptors.end(), compareViews); QStandardItem* emptyItem = new QStandardItem(); emptyItem->setFlags(Qt::ItemIsEnabled); treeRootItem->appendRow(emptyItem); - QStringList viewExcludeList = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetViewExcludeList(); + //QStringList viewExcludeList = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetViewExcludeList(); QStandardItem* viewRootItem = new QStandardItem(QIcon(),"Views"); viewRootItem->setFont(QFont("", 12, QFont::Normal)); viewRootItem->setEditable(false); treeRootItem->appendRow(viewRootItem); categoryItems.clear(); QStandardItem* noCategoryItem = new QStandardItem(QIcon(),"Miscellaneous"); noCategoryItem->setEditable(false); noCategoryItem->setFont(QFont("", 12, QFont::Normal)); for (int i = 0; i < viewDescriptors.size(); ++i) { berry::IViewDescriptor::Pointer v = viewDescriptors[i]; + /* bool skipView = false; for(int e=0; eGetId()) { skipView = true; break; } if (skipView) continue; - +*/ QStringList catPath = v->GetCategoryPath(); QIcon icon = v->GetImageDescriptor(); mitk::QtViewItem* vItem = new mitk::QtViewItem(icon, v->GetLabel()); vItem->m_View = v; vItem->setToolTip(v->GetDescription()); vItem->m_Description = v->GetDescription(); QStringList keylist = v->GetKeywordReferences(); vItem->m_Tags = keywordRegistry.GetKeywords(keylist); vItem->setEditable(false); for (int i=0; iGetPartName()==v->GetLabel()) { QFont font; font.setBold(true); vItem->setFont(font); break; } if (catPath.empty()) noCategoryItem->appendRow(vItem); else { QStandardItem* categoryItem = NULL; for (unsigned int c=0; ctext() == catPath.front()) { categoryItem = categoryItems.at(c); break; } if (categoryItem==NULL) { categoryItem = new QStandardItem(QIcon(),catPath.front()); categoryItems.push_back(categoryItem); } categoryItem->setEditable(false); categoryItem->appendRow(vItem); categoryItem->setFont(QFont("", 12, QFont::Normal)); } } std::sort(categoryItems.begin(), categoryItems.end(), compareQStandardItems); for (unsigned int i=0; iappendRow(categoryItems.at(i)); if (noCategoryItem->hasChildren()) viewRootItem->appendRow(noCategoryItem); m_Controls.m_PluginTreeView->expandAll(); return true; } void QmitkViewNavigatorWidget::FilterChanged() { QString filterString = m_Controls.lineEdit->text(); // if (filterString.size() > 0 ) m_Controls.m_PluginTreeView->expandAll(); // else // m_Controls.m_PluginTreeView->collapseAll(); // QRegExp::PatternSyntax syntax = QRegExp::RegExp; Qt::CaseSensitivity caseSensitivity = Qt::CaseInsensitive; QString strPattern = "^*" + filterString; QRegExp regExp(strPattern, caseSensitivity); m_FilterProxyModel->setFilterRegExp(regExp); } void QmitkViewNavigatorWidget::ItemClicked(const QModelIndex &index) { QStandardItem* item = m_TreeModel->itemFromIndex(m_FilterProxyModel->mapToSource(index)); if ( dynamic_cast< mitk::QtPerspectiveItem* >(item) ) { try { mitk::QtPerspectiveItem* pItem = dynamic_cast< mitk::QtPerspectiveItem* >(item); berry::PlatformUI::GetWorkbench()->ShowPerspective( pItem->m_Perspective->GetId(), berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow() ); } catch (...) { QMessageBox::critical(0, "Opening Perspective Failed", QString("The requested perspective could not be opened.\nSee the log for details.")); } } else if ( dynamic_cast< mitk::QtViewItem* >(item) ) { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); if (page.IsNotNull()) { try { mitk::QtViewItem* vItem = dynamic_cast< mitk::QtViewItem* >(item); page->ShowView(vItem->m_View->GetId()); } catch (berry::PartInitException e) { BERRY_ERROR << "Error: " << e.what() << std::endl; } } } } -void QmitkViewNavigatorWidget::AddPerspective() +void QmitkViewNavigatorWidget::SaveCurrentPerspectiveAs() { - QmitkNewPerspectiveDialog* dialog = new QmitkNewPerspectiveDialog( m_Parent ); - - int dialogReturnValue = dialog->exec(); - if ( dialogReturnValue == QDialog::Rejected ) - return; - - berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); - try - { - berry::IPerspectiveDescriptor::Pointer perspDesc; - perspDesc = perspRegistry->CreatePerspective(dialog->GetPerspectiveName(), perspRegistry->FindPerspectiveWithId(perspRegistry->GetDefaultPerspective())); - berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->SetPerspective(perspDesc); - } - catch(...) - { - QMessageBox::warning(m_Parent, "Error", "Duplication of selected perspective failed. Please make sure the specified perspective name is not already in use!"); - } + berry::IHandlerService* handlerService = m_Window->GetService(); + try + { + handlerService->ExecuteCommand(berry::IWorkbenchCommandConstants::WINDOW_SAVE_PERSPECTIVE_AS, + berry::UIElement::Pointer()); FillTreeList(); + } + catch(const berry::NotHandledException) + {} + catch(const berry::CommandException& e) + { + MITK_ERROR << e.what(); + } } -void QmitkViewNavigatorWidget::ClonePerspective() -{ - if (m_RegisteredPerspective.IsNotNull()) - { - QmitkNewPerspectiveDialog* dialog = new QmitkNewPerspectiveDialog( m_Parent ); - QString defaultName = m_RegisteredPerspective->GetLabel(); - defaultName.append(" Copy"); - dialog->SetPerspectiveName(defaultName); - - int dialogReturnValue = dialog->exec(); - if ( dialogReturnValue == QDialog::Rejected ) - return; - - berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); - try - { - berry::IPerspectiveDescriptor::Pointer perspDesc = perspRegistry->ClonePerspective(dialog->GetPerspectiveName(), dialog->GetPerspectiveName(), m_RegisteredPerspective); - berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->SetPerspective(perspDesc); - } - catch(...) - { - QMessageBox::warning(m_Parent, "Error", "Duplication of selected perspective failed. Please make sure the specified perspective name is not already in use!"); - } - FillTreeList(); - } -} - -void QmitkViewNavigatorWidget::ResetPerspective() +void QmitkViewNavigatorWidget::ResetCurrentPerspective() { if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", "Do you really want to reset the current perspective?", QMessageBox::Yes|QMessageBox::No).exec()) berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->ResetPerspective(); } -void QmitkViewNavigatorWidget::DeletePerspective() -{ - if (m_RegisteredPerspective.IsNotNull()) - { - QString question = "Do you really want to remove the perspective '"; - question.append(m_RegisteredPerspective->GetLabel()); - question.append("'?"); - if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", question, QMessageBox::Yes|QMessageBox::No).exec()) - { - if( m_RegisteredPerspective == berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->GetPerspective() ) - { - berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->CloseCurrentPerspective(true, true); - } - berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); - perspRegistry->DeletePerspective(m_RegisteredPerspective); - berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->RemovePerspective(m_RegisteredPerspective); - FillTreeList(); - if (! berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->GetPerspective()) - { - berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage()->Close(); - } - } - } -} - void QmitkViewNavigatorWidget::ClosePerspective() { if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", "Do you really want to close the current perspective?", QMessageBox::Yes|QMessageBox::No).exec()) { - berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); - page->CloseCurrentPerspective(true, true); + berry::IWorkbenchPage::Pointer page = m_Window->GetActivePage(); + page->ClosePerspective(page->GetPerspective(), true, true); // if ( page->GetPerspective().IsNull() ) // { // berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); // berry::PlatformUI::GetWorkbench()->ShowPerspective( perspRegistry->GetDefaultPerspective(), berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow() ); // } } } void QmitkViewNavigatorWidget::CloseAllPerspectives() { if (QMessageBox::Yes == QMessageBox(QMessageBox::Question, "Please confirm", "Do you really want to close all perspectives?", QMessageBox::Yes|QMessageBox::No).exec()) { berry::IWorkbenchPage::Pointer page = berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow()->GetActivePage(); page->CloseAllPerspectives(true, true); // berry::IPerspectiveRegistry* perspRegistry = berry::PlatformUI::GetWorkbench()->GetPerspectiveRegistry(); // berry::PlatformUI::GetWorkbench()->ShowPerspective( perspRegistry->GetDefaultPerspective(), berry::PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow() ); } } void QmitkViewNavigatorWidget::ExpandAll() { m_Controls.m_PluginTreeView->expandAll(); } void QmitkViewNavigatorWidget::CollapseAll() { m_Controls.m_PluginTreeView->collapseAll(); } void QmitkViewNavigatorWidget::CustomMenuRequested(QPoint pos) { QModelIndex index = m_Controls.m_PluginTreeView->indexAt(pos); QStandardItem* item = m_TreeModel->itemFromIndex(m_FilterProxyModel->mapToSource(index)); if (m_ContextMenu==NULL) return; m_ContextMenu->clear(); - m_RegisteredPerspective = NULL; QAction* expandAction = new QAction("Expand tree", this); m_ContextMenu->addAction(expandAction); connect(expandAction, SIGNAL(triggered()), SLOT(ExpandAll())); QAction* collapseAction = new QAction("Collapse tree", this); m_ContextMenu->addAction(collapseAction); connect(collapseAction, SIGNAL(triggered()), SLOT(CollapseAll())); m_ContextMenu->addSeparator(); + if ( item!=NULL && dynamic_cast< mitk::QtPerspectiveItem* >(item) ) { - m_RegisteredPerspective = dynamic_cast< mitk::QtPerspectiveItem* >(item)->m_Perspective; - - //m_ContextMenu->addSeparator(); - - QAction* cloneAction = new QAction("Duplicate perspective", this); - m_ContextMenu->addAction(cloneAction); - connect(cloneAction, SIGNAL(triggered()), SLOT(ClonePerspective())); - - if (!m_RegisteredPerspective->IsPredefined()) + berry::IPerspectiveDescriptor::Pointer persp = dynamic_cast< mitk::QtPerspectiveItem* >(item)->m_Perspective; + if (this->m_ActivePerspective.IsNotNull() && this->m_ActivePerspective == persp) { - QAction* deleteAction = new QAction("Remove perspective", this); - m_ContextMenu->addAction(deleteAction); - connect(deleteAction, SIGNAL(triggered()), SLOT(DeletePerspective())); - } + //m_ContextMenu->addSeparator(); - m_ContextMenu->addSeparator(); + QAction* saveAsAction = new QAction("Save As...", this); + m_ContextMenu->addAction(saveAsAction); + connect(saveAsAction, SIGNAL(triggered()), SLOT(SaveCurrentPerspectiveAs())); + m_ContextMenu->addSeparator(); + } } QAction* resetAction = new QAction("Reset current perspective", this); m_ContextMenu->addAction(resetAction); - connect(resetAction, SIGNAL(triggered()), SLOT(ResetPerspective())); + connect(resetAction, SIGNAL(triggered()), SLOT(ResetCurrentPerspective())); - QAction* closeAction = new QAction("Close current perspective", this); + QAction* closeAction = new QAction("Close perspective", this); m_ContextMenu->addAction(closeAction); connect(closeAction, SIGNAL(triggered()), SLOT(ClosePerspective())); m_ContextMenu->addSeparator(); QAction* closeAllAction = new QAction("Close all perspectives", this); m_ContextMenu->addAction(closeAllAction); connect(closeAllAction, SIGNAL(triggered()), SLOT(CloseAllPerspectives())); m_ContextMenu->popup(m_Controls.m_PluginTreeView->viewport()->mapToGlobal(pos)); } diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.h b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.h index 42415d6ae6..e3e8714431 100644 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.h +++ b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidget.h @@ -1,91 +1,92 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _QMITKViewNavigatorWidget_H_INCLUDED #define _QMITKViewNavigatorWidget_H_INCLUDED //QT headers #include #include #include #include "ui_QmitkViewNavigatorWidgetControls.h" #include #include #include #include #include #include #include #include -#include #include #include class ClassFilterProxyModel; /** @brief */ class QmitkViewNavigatorWidget : public QWidget { //this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: - QmitkViewNavigatorWidget (QWidget* parent = 0, Qt::WindowFlags f = 0); + QmitkViewNavigatorWidget (berry::IWorkbenchWindow::Pointer window, + QWidget* parent = 0, Qt::WindowFlags f = 0); virtual ~QmitkViewNavigatorWidget(); virtual void CreateQtPartControl(QWidget *parent); void setFocus(); bool FillTreeList(); void UpdateTreeList(QStandardItem* item = NULL, berry::IWorkbenchPartReference* partRef=NULL, const std::string& changeId=""); QScopedPointer m_PerspectiveListener; QScopedPointer m_WindowListener; public slots: void CustomMenuRequested(QPoint pos); void ItemClicked(const QModelIndex &index); - void AddPerspective(); - void ClonePerspective(); - void ResetPerspective(); - void DeletePerspective(); + void SaveCurrentPerspectiveAs(); + void ResetCurrentPerspective(); void CloseAllPerspectives(); void ClosePerspective(); void ExpandAll(); void CollapseAll(); void FilterChanged(); protected: + friend class ViewNavigatorPerspectiveListener; + // member variables Ui::QmitkViewNavigatorWidgetControls m_Controls; QWidget* m_Parent; QStandardItemModel* m_TreeModel; ClassFilterProxyModel* m_FilterProxyModel; QMenu* m_ContextMenu; - berry::IPerspectiveDescriptor::Pointer m_RegisteredPerspective; + berry::IPerspectiveDescriptor::Pointer m_ActivePerspective; bool m_Generated; private: + berry::IWorkbenchWindow::Pointer m_Window; }; #endif // _QMITKViewNavigatorWidget_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidgetControls.ui b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidgetControls.ui index 7073a4bf1e..464c881007 100644 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidgetControls.ui +++ b/Plugins/org.mitk.gui.qt.viewnavigator/src/QmitkViewNavigatorWidgetControls.ui @@ -1,52 +1,64 @@ QmitkViewNavigatorWidgetControls 0 0 752 974 0 0 QmitkTemplate + + 0 + + + 0 + + + 0 + + + 0 + Filter... true false ctkSearchBox QLineEdit
ctkSearchBox.h
diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/internal/ViewNavigatorView.cpp b/Plugins/org.mitk.gui.qt.viewnavigator/src/internal/ViewNavigatorView.cpp index f2255bdfbc..455aaf799e 100644 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/internal/ViewNavigatorView.cpp +++ b/Plugins/org.mitk.gui.qt.viewnavigator/src/internal/ViewNavigatorView.cpp @@ -1,49 +1,40 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ -// Blueberry -#include -#include - -// Qmitk #include "ViewNavigatorView.h" -// Qt -#include +#include "QmitkViewNavigatorWidget.h" + +// BlueBerry +#include -//mitk image -#include +#include const std::string ViewNavigatorView::VIEW_ID = "org.mitk.views.viewnavigatorview"; void ViewNavigatorView::SetFocus() { - m_Controls.widget->setFocus(); + m_ViewNavigatorWidget->setFocus(); } void ViewNavigatorView::CreateQtPartControl( QWidget *parent ) { - // create GUI widgets from the Qt Designer's .ui file - m_Controls.setupUi( parent ); - -} - -void ViewNavigatorView::OnSelectionChanged( berry::IWorkbenchPart::Pointer /*source*/, - const QList& nodes ) -{ - + parent->setLayout(new QVBoxLayout); + parent->layout()->setContentsMargins(0, 0, 0, 0); + m_ViewNavigatorWidget = new QmitkViewNavigatorWidget(this->GetSite()->GetWorkbenchWindow(), parent); + parent->layout()->addWidget(m_ViewNavigatorWidget); } diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/internal/ViewNavigatorView.h b/Plugins/org.mitk.gui.qt.viewnavigator/src/internal/ViewNavigatorView.h index 6e860b9038..1a362d4a9c 100644 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/internal/ViewNavigatorView.h +++ b/Plugins/org.mitk.gui.qt.viewnavigator/src/internal/ViewNavigatorView.h @@ -1,64 +1,54 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef ViewNavigatorView_h #define ViewNavigatorView_h -#include #include -#include - -#include "ui_ViewNavigatorViewControls.h" +class QmitkViewNavigatorWidget; /** \brief ViewNavigatorView \warning This class is not yet documented. Use "git blame" and ask the author to provide basic documentation. \sa QmitkAbstractView \ingroup ${plugin_target}_internal */ class ViewNavigatorView : public QmitkAbstractView { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT - public: - - static const std::string VIEW_ID; - - protected slots: - - /// \brief Called when the user clicks the GUI button +public: - protected: + static const std::string VIEW_ID; - virtual void CreateQtPartControl(QWidget *parent); +protected: - virtual void SetFocus(); + virtual void CreateQtPartControl(QWidget *parent); - /// \brief called by QmitkFunctionality when DataManager's selection has changed - virtual void OnSelectionChanged( berry::IWorkbenchPart::Pointer source, - const QList& nodes ); + virtual void SetFocus(); - Ui::ViewNavigatorViewControls m_Controls; +private: + QmitkViewNavigatorWidget* m_ViewNavigatorWidget; }; #endif // ViewNavigatorView_h diff --git a/Plugins/org.mitk.gui.qt.viewnavigator/src/internal/ViewNavigatorViewControls.ui b/Plugins/org.mitk.gui.qt.viewnavigator/src/internal/ViewNavigatorViewControls.ui deleted file mode 100644 index 090827ba27..0000000000 --- a/Plugins/org.mitk.gui.qt.viewnavigator/src/internal/ViewNavigatorViewControls.ui +++ /dev/null @@ -1,54 +0,0 @@ - - - ViewNavigatorViewControls - - - - 0 - 0 - 222 - 161 - - - - - 0 - 0 - - - - QmitkTemplate - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - - - - QmitkViewNavigatorWidget - QWidget -
QmitkViewNavigatorWidget.h
- 1 -
-
- - -
diff --git a/Plugins/org.mitk.gui.qt.volumevisualization/plugin.xml b/Plugins/org.mitk.gui.qt.volumevisualization/plugin.xml index 4ab6b1c346..cd07a6e472 100755 --- a/Plugins/org.mitk.gui.qt.volumevisualization/plugin.xml +++ b/Plugins/org.mitk.gui.qt.volumevisualization/plugin.xml @@ -1,26 +1,40 @@ Configure the 3D-Visualization of images. + + + + + + + + diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.cpp b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.cpp index 3ca9e92bca..855702f4d1 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.cpp +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.cpp @@ -1,63 +1,81 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "QmitkXnatObjectEditorInput.h" +#include + QmitkXnatObjectEditorInput::QmitkXnatObjectEditorInput(ctkXnatObject* object) : m_Object(object) { } QmitkXnatObjectEditorInput::~QmitkXnatObjectEditorInput() { } ctkXnatObject* QmitkXnatObjectEditorInput::GetXnatObject() const { return m_Object; } bool QmitkXnatObjectEditorInput::Exists() const { return m_Object->exists(); } QString QmitkXnatObjectEditorInput::GetName() const { return m_Object->id(); } QString QmitkXnatObjectEditorInput::GetToolTipText() const { return m_Object->description(); } bool QmitkXnatObjectEditorInput::operator==(const berry::Object* o) const { if ( const QmitkXnatObjectEditorInput* other = dynamic_cast(o) ) { if ( other->GetXnatObject()->parent() ) { return (other->GetName() == this->GetName()) && (other->GetXnatObject()->parent()->id() == this->GetXnatObject()->parent()->id()); } else { return (other->GetName() == this->GetName()); } } return false; } + + +QIcon QmitkXnatObjectEditorInput::GetIcon() const +{ + return QIcon(); +} + +const berry::IPersistableElement* QmitkXnatObjectEditorInput::GetPersistable() const +{ + return nullptr; +} + +berry::Object* QmitkXnatObjectEditorInput::GetAdapter(const QString& /*adapterType*/) const +{ + return nullptr; +} diff --git a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.h b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.h index a21eaa697d..7c94873b59 100644 --- a/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.h +++ b/Plugins/org.mitk.gui.qt.xnat/src/internal/QmitkXnatObjectEditorInput.h @@ -1,44 +1,48 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKXNATOBJECTEDITORINPUT_H_ #define QMITKXNATOBJECTEDITORINPUT_H_ #include "berryIEditorInput.h" #include "ctkXnatObject.h" class QmitkXnatObjectEditorInput : public berry::IEditorInput { public: berryObjectMacro(QmitkXnatObjectEditorInput); QmitkXnatObjectEditorInput(ctkXnatObject* object); ~QmitkXnatObjectEditorInput(); /// \brief Returns the kept ctkXnatObject. ctkXnatObject* GetXnatObject() const; virtual bool Exists() const; virtual QString GetName() const; virtual QString GetToolTipText() const; + QIcon GetIcon() const; + const berry::IPersistableElement* GetPersistable() const; + berry::Object* GetAdapter(const QString& adapterType) const; + virtual bool operator==(const berry::Object* o) const; private: ctkXnatObject* m_Object; }; #endif /*QMITKXNATOBJECTEDITORINPUT_H_*/ diff --git a/Plugins/org.mitk.simulation/src/internal/org_mitk_simulation_Activator.cpp b/Plugins/org.mitk.simulation/src/internal/org_mitk_simulation_Activator.cpp index b035cec4ff..fec81c3eee 100644 --- a/Plugins/org.mitk.simulation/src/internal/org_mitk_simulation_Activator.cpp +++ b/Plugins/org.mitk.simulation/src/internal/org_mitk_simulation_Activator.cpp @@ -1,111 +1,111 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY 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 "org_mitk_simulation_Activator.h" +#include #include #include #include #include #include #include -#include #include #include #include #include static void RegisterSofaClasses() { int MeshMitkLoaderClass = sofa::core::RegisterObject("").add(); boost::ignore_unused(MeshMitkLoaderClass); } static void LoadSofaPlugins() { berry::IPreferences::Pointer preferences = mitk::GetSimulationPreferences(); if (preferences.IsNull()) return; QString plugins = preferences->Get("plugins", ""); if (plugins.isEmpty()) return; QStringList pluginList = plugins.split(';', QString::SkipEmptyParts); QStringListIterator it(pluginList); typedef sofa::helper::system::PluginManager PluginManager; PluginManager& pluginManager = PluginManager::getInstance(); while (it.hasNext()) { std::string plugin = it.next().toStdString(); std::ostringstream errlog; pluginManager.loadPlugin(plugin, &errlog); if (errlog.str().empty()) pluginManager.getPluginMap()[plugin].initExternalModule(); } } static void AddPropertyFilters() { mitk::IPropertyFilters* filters = mitk::org_mitk_simulation_Activator::GetService(); if (filters == NULL) return; mitk::PropertyFilter filter; filter.AddEntry("layer", mitk::PropertyFilter::Blacklist); filter.AddEntry("name", mitk::PropertyFilter::Blacklist); filter.AddEntry("path", mitk::PropertyFilter::Blacklist); filter.AddEntry("selected", mitk::PropertyFilter::Blacklist); filter.AddEntry("visible", mitk::PropertyFilter::Blacklist); filters->AddFilter(filter, "Simulation"); } ctkPluginContext* mitk::org_mitk_simulation_Activator::Context = NULL; void mitk::org_mitk_simulation_Activator::start(ctkPluginContext* context) { Context = context; RegisterSimulationObjectFactory(); RegisterSofaClasses(); LoadSofaPlugins(); AddPropertyFilters(); QmitkNodeDescriptorManager* nodeDescriptorManager = QmitkNodeDescriptorManager::GetInstance(); if (nodeDescriptorManager != NULL) { mitk::NodePredicateDataType::Pointer simulationPredicate = mitk::NodePredicateDataType::New("Simulation"); nodeDescriptorManager->AddDescriptor(new QmitkNodeDescriptor("Simulation", ":/Simulation/SOFAIcon.png", simulationPredicate, nodeDescriptorManager)); } } void mitk::org_mitk_simulation_Activator::stop(ctkPluginContext*) { Context = NULL; } #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) Q_EXPORT_PLUGIN2(org_mitk_simulation, mitk::org_mitk_simulation_Activator) #endif