diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryAdaptExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryAdaptExpression.h index 9eaf77ff39..b1bc9f638d 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryAdaptExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryAdaptExpression.h @@ -1,82 +1,82 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYADAPTEXPRESSION_H_ #define BERRYADAPTEXPRESSION_H_ #include "berryCompositeExpression.h" -#include "../berryEvaluationContext.h" -#include "../berryEvaluationResult.h" -#include "../berryExpressionInfo.h" +#include "berryEvaluationContext.h" +#include "berryEvaluationResult.h" +#include "berryExpressionInfo.h" #include "service/berryIConfigurationElement.h" #include "Poco/DOM/Node.h" #include namespace berry { class AdaptExpression : public CompositeExpression { private: static const std::string ATT_TYPE; /** * The seed for the hash code for all adapt expressions. */ static const std::size_t HASH_INITIAL; std::string fTypeName; public: AdaptExpression(SmartPointer configElement); AdaptExpression(Poco::XML::Node* element); AdaptExpression(const std::string& typeName); // bool equals(final Object object) { // if (!(object instanceof AdaptExpression)) // return false; // // final AdaptExpression that= (AdaptExpression)object; // return this.fTypeName.equals(that.fTypeName) // && equals(this.fExpressions, that.fExpressions); // } /* (non-Javadoc) * @see Expression#evaluate(IVariablePool) */ EvaluationResult Evaluate(IEvaluationContext* context); void CollectExpressionInfo(ExpressionInfo* info); protected: std::size_t ComputeHashCode(); }; } // namespace berry #endif /*BERRYADAPTEXPRESSION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.h index 787911b95a..e8ec00e6d2 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCompositeExpression.h @@ -1,64 +1,64 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYCOMPOSITEEXPRESSION_H_ #define BERRYCOMPOSITEEXPRESSION_H_ -#include "../berryExpression.h" -#include "../berryExpressionInfo.h" -#include "../berryEvaluationResult.h" -#include "../berryIEvaluationContext.h" +#include "berryExpression.h" +#include "berryExpressionInfo.h" +#include "berryEvaluationResult.h" +#include "berryIEvaluationContext.h" #include namespace berry { class CompositeExpression : public Expression { public: berryObjectMacro(CompositeExpression) private: /** * The seed for the hash code for all composite expressions. */ static const std::size_t HASH_INITIAL; protected: std::vector fExpressions; virtual EvaluationResult EvaluateAnd(IEvaluationContext* scope); virtual EvaluationResult EvaluateOr(IEvaluationContext* scope); virtual std::size_t ComputeHashCode(); public: virtual void Add(Expression::Pointer expression); virtual void GetChildren(std::vector& children); virtual void CollectExpressionInfo(ExpressionInfo* info); }; } // namespace berry #endif /*BERRYCOMPOSITEEXPRESSION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCountExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCountExpression.h index 55a3a46957..ac754ac9ac 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCountExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryCountExpression.h @@ -1,75 +1,75 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __BERRY_COUNT_EXPRESSION_H__ #define __BERRY_COUNT_EXPRESSION_H__ -#include "../berryExpression.h" -#include "../berryIEvaluationContext.h" -#include "../berryExpressionInfo.h" +#include "berryExpression.h" +#include "berryIEvaluationContext.h" +#include "berryExpressionInfo.h" #include "service/berryIConfigurationElement.h" #include "Poco/DOM/Element.h" #include namespace berry { class CountExpression : public Expression { private: static const int ANY_NUMBER; static const int EXACT; static const int ONE_OR_MORE; static const int NONE_OR_ONE; static const int NONE; static const int UNKNOWN; /** * The seed for the hash code for all count expressions. */ static const std::size_t HASH_INITIAL; int fMode; int fSize; void InitializeSize(std::string size); public: CountExpression(SmartPointer configElement); CountExpression(Poco::XML::Element* element); CountExpression(const std::string& size); EvaluationResult Evaluate(IEvaluationContext* context); void CollectExpressionInfo(ExpressionInfo* info); bool operator==(Expression& object); protected: std::size_t ComputeHashCode(); }; } // namespace berry #endif // __BERRY_COUNT_EXPRESSION_H__ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefaultVariable.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefaultVariable.h index 32c529cc36..c5e27ad899 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefaultVariable.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefaultVariable.h @@ -1,94 +1,94 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYDEFAULTVARIABLE_H_ #define BERRYDEFAULTVARIABLE_H_ -#include "../berryIEvaluationContext.h" +#include "berryIEvaluationContext.h" #include namespace berry { class DefaultVariable : public IEvaluationContext { private: Object::Pointer fDefaultVariable; IEvaluationContext* fParent; IEvaluationContext* fManagedPool; public: /** * Constructs a new variable pool for a single default variable. * * @param parent the parent context for the default variable. Must not * be null. * @param defaultVariable the default variable */ DefaultVariable(IEvaluationContext* parent, Object::Pointer defaultVariable); /** * {@inheritDoc} */ IEvaluationContext* GetParent() const; /** * {@inheritDoc} */ IEvaluationContext* GetRoot(); /** * {@inheritDoc} */ Object::Pointer GetDefaultVariable() const; /** * {@inheritDoc} */ void SetAllowPluginActivation(bool value); /** * {@inheritDoc} */ bool GetAllowPluginActivation() const; /** * {@inheritDoc} */ void AddVariable(const std::string& name, Object::Pointer value); /** * {@inheritDoc} */ Object::Pointer RemoveVariable(const std::string& name); /** * {@inheritDoc} */ Object::Pointer GetVariable(const std::string& name) const; /** * {@inheritDoc} */ Object::Pointer ResolveVariable(const std::string& name, std::vector& args); }; } // namespace berry #endif /*BERRYDEFAULTVARIABLE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefinitionRegistry.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefinitionRegistry.cpp index d074d0f969..1e127c1f84 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefinitionRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefinitionRegistry.cpp @@ -1,91 +1,91 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryDefinitionRegistry.h" -#include "../berryExpressionConverter.h" +#include "berryExpressionConverter.h" #include "berryPlatform.h" #include "berryPlatformException.h" #include "service/berryIExtensionPointService.h" namespace berry { std::map& DefinitionRegistry::GetCache() { return cache; } DefinitionRegistry::DefinitionRegistry() { //Platform.getExtensionRegistry().addRegistryChangeListener(this, "org.blueberry.core.expressions"); //$NON-NLS-1$ } Expression::Pointer DefinitionRegistry::GetExpression(const std::string& id) { Expression::Pointer cachedExpression= this->GetCache()[id]; if (!cachedExpression.IsNull()) { return cachedExpression; } IExtensionPointService::Pointer service = Platform::GetExtensionPointService(); IConfigurationElement::vector ces( service->GetConfigurationElementsFor("org.blueberry.core.expressions.definitions")); Expression::Pointer foundExpression; for (IConfigurationElement::vector::iterator i= ces.begin(); i != ces.end(); ++i) { std::string cid; if ((*i)->GetAttribute("id", cid)) { if (cid == id) { try { foundExpression= this->GetExpression(id, *i); break; } catch (InvalidServiceObjectException e) { throw CoreException("Missing expression", id); } } } } if (foundExpression.IsNull()) { throw CoreException("Missing expression", id); } return foundExpression; } Expression::Pointer DefinitionRegistry::GetExpression(const std::string& id, IConfigurationElement::Pointer element) { IConfigurationElement::vector children(element->GetChildren()); Expression::Pointer expr= ExpressionConverter::GetDefault()->Perform(children[0]); if (!expr.IsNull()) { this->GetCache()[id] = expr; } return expr; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefinitionRegistry.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefinitionRegistry.h index f69b69fdd7..a6f5cd4430 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefinitionRegistry.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryDefinitionRegistry.h @@ -1,62 +1,62 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYDEFINITIONREGISTRY_H_ #define BERRYDEFINITIONREGISTRY_H_ -#include "../berryExpression.h" +#include "berryExpression.h" #include "service/berryIConfigurationElement.h" #include namespace berry { /** * This manages the extension point that allows core expression reuse. */ class DefinitionRegistry { //implements IRegistryChangeListener { private: std::map cache; std::map& GetCache(); public: DefinitionRegistry(); /** * Get the expression with the id defined by an extension. This class will * cache the expressions when appropriate, so it's OK to always ask the * registry. * * @param id The unique ID of the expression definition * @return the expression * @throws CoreException If the expression cannot be found. */ Expression::Pointer GetExpression(const std::string& id); private: Expression::Pointer GetExpression(const std::string& id, SmartPointer element); }; } // namespace berry #endif /*BERRYDEFINITIONREGISTRY_H_*/ 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 fa06265891..a6455b4ad8 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryEqualsExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryEqualsExpression.h @@ -1,62 +1,62 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __BERRY_EQUALS_EXPRESSION_H__ #define __BERRY_EQUALS_EXPRESSION_H__ -#include "../berryExpression.h" -#include "../berryExpressionInfo.h" -#include "../berryIEvaluationContext.h" +#include "berryExpression.h" +#include "berryExpressionInfo.h" +#include "berryIEvaluationContext.h" #include "service/berryIConfigurationElement.h" #include "Poco/DOM/Element.h" namespace berry { class EqualsExpression : public Expression { /** * The seed for the hash code for all equals expressions. */ private: static const std::size_t HASH_INITIAL; Object::Pointer fExpectedValue; public: EqualsExpression(const Object::Pointer expectedValue); EqualsExpression(SmartPointer element); EqualsExpression(Poco::XML::Element* element); EvaluationResult Evaluate(IEvaluationContext* context); void CollectExpressionInfo(ExpressionInfo* info); bool operator==(Expression& object); protected: std::size_t ComputeHashCode(); }; } // namespace berry #endif // __BERRY_EQUALS_EXPRESSION_H__ 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 0aa23be708..70e39a9c73 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressions.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryExpressions.h @@ -1,104 +1,104 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYEXPRESSIONS_H_ #define BERRYEXPRESSIONS_H_ #include "Poco/Any.h" #include "Poco/DOM/Element.h" #include "service/berryIConfigurationElement.h" -#include "../berryExpression.h" -#include "../berryIIterable.h" -#include "../berryICountable.h" +#include "berryExpression.h" +#include "berryIIterable.h" +#include "berryICountable.h" #include #include #include namespace berry { class Expressions { private: Expressions(); static int FindNextComma(const std::string& str, int start); public: /* debugging flag to enable tracing */ static const bool TRACING; static bool IsInstanceOf(Object::ConstPointer element, const std::string& type); static void CheckAttribute(const std::string& name, bool value); static void CheckAttribute(const std::string& name, bool result, const std::string& value, std::vector& validValues); static void CheckCollection(Object::ConstPointer var, Expression::Pointer expression); /** * Converts the given variable into an IIterable. If a corresponding adapter can't be found an * exception is thrown. If the corresponding adapter isn't loaded yet, null is returned. * * @param var the variable to turn into an IIterable * @param expression the expression referring to the variable * * @return the IIterable or null if a corresponding adapter isn't loaded yet * * @throws CoreException if the var can't be adapted to an IIterable */ static IIterable::Pointer GetAsIIterable(Object::Pointer var, Expression::Pointer expression); /** * Converts the given variable into an ICountable. If a corresponding adapter can't be found an * exception is thrown. If the corresponding adapter isn't loaded yet, null is returned. * * @param var the variable to turn into an ICountable * @param expression the expression referring to the variable * * @return the ICountable or null if a corresponding adapter isn't loaded yet * * @throws CoreException if the var can't be adapted to an ICountable */ static ICountable::Pointer GetAsICountable(Object::Pointer var, Expression::Pointer expression); static bool GetOptionalBooleanAttribute(SmartPointer element, const std::string& attributeName); static bool GetOptionalBooleanAttribute(Poco::XML::Element* element, const std::string& attributeName); //---- Argument parsing -------------------------------------------- static void GetArguments(std::vector& args, SmartPointer element, const std::string& attributeName); static void GetArguments(std::vector& args, Poco::XML::Element* element, const std::string& attributeName); static void ParseArguments(std::vector&, const std::string& args); static Object::Pointer ConvertArgument(const std::string& arg, bool result = true); static std::string UnEscapeString(const std::string& str); }; } #endif /*BERRYEXPRESSIONS_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryInstanceofExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryInstanceofExpression.h index 0b2bca4420..3df5c13d70 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryInstanceofExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryInstanceofExpression.h @@ -1,74 +1,74 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __BERRY_INSTANCEOF_EXPRESSION_H__ #define __BERRY_INSTANCEOF_EXPRESSION_H__ -#include "../berryExpression.h" +#include "berryExpression.h" #include "service/berryIConfigurationElement.h" #include "Poco/DOM/Element.h" namespace berry { struct InstanceofExpression : public Expression { private: /** * The seed for the hash code for all instance of expressions. */ static const std::size_t HASH_INITIAL; std::string fTypeName; public: InstanceofExpression(SmartPointer element); InstanceofExpression(Poco::XML::Element* element); InstanceofExpression(const std::string& typeName); /* (non-Javadoc) * @see org.blueberry.jdt.internal.corext.refactoring.participants.Expression#evaluate(java.lang.Object) */ EvaluationResult Evaluate(IEvaluationContext* context); void CollectExpressionInfo(ExpressionInfo* info); bool operator==(Expression& object); //---- Debugging --------------------------------------------------- /* (non-Javadoc) * @see java.lang.Object#toString() */ std::string ToString(); protected: std::size_t ComputeHashCode(); }; } // namespace berry #endif // __BERRY_INSTANCEOF_EXPRESSION_H__ 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 1b916e9506..451a0cba2f 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryNotExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryNotExpression.h @@ -1,54 +1,54 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __BERRY_NOT_EXPRESSION_H__ #define __BERRY_NOT_EXPRESSION_H__ -#include "../berryExpression.h" +#include "berryExpression.h" namespace berry { class NotExpression : public Expression { private: /** * The seed for the hash code for all not expressions. */ static const std::size_t HASH_INITIAL; Expression::Pointer fExpression; public: NotExpression(Expression::Pointer expression); EvaluationResult Evaluate(IEvaluationContext* context); void CollectExpressionInfo(ExpressionInfo* info); bool operator==(Expression& object); protected: std::size_t ComputeHashCode(); }; } // namespace berry #endif // __BERRY_NOT_EXPRESSION_H__ 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 db3fd0bd30..17e3fb46c9 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryProperty.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryProperty.h @@ -1,71 +1,71 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPROPERTY_H_ #define BERRYPROPERTY_H_ -#include "../berryIPropertyTester.h" +#include "berryIPropertyTester.h" #include "berryObject.h" #include "Poco/SharedPtr.h" #include "Poco/Any.h" #include #include namespace berry { class Property { public: typedef Property Self; typedef Poco::SharedPtr Pointer; typedef Poco::SharedPtr ConstPointer; private: Object::Pointer fType; std::string fNamespace; std::string fName; IPropertyTester::Pointer fTester; friend class TypeExtensionManager; /* package */ Property(Object::Pointer type, const std::string& namespaze, const std::string& name); /* package */ void SetPropertyTester(IPropertyTester::Pointer tester); public: bool IsInstantiated(); bool IsDeclaringPluginActive(); bool IsValidCacheEntry(bool forcePluginActivation); bool Test(Object::Pointer receiver, std::vector& args, Object::Pointer expectedValue); bool operator==(Property& obj); bool operator==(Property* obj); int HashCode(); }; } // namespace berry #endif /*BERRYPROPERTY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyTesterDescriptor.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyTesterDescriptor.h index b3b97c3767..a8db794830 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyTesterDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryPropertyTesterDescriptor.h @@ -1,72 +1,72 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPROPERTYTESTERDESCRIPTOR_H_ #define BERRYPROPERTYTESTERDESCRIPTOR_H_ #include "service/berryIConfigurationElement.h" -#include "../berryIPropertyTester.h" +#include "berryIPropertyTester.h" #include "Poco/Any.h" #include #include namespace berry { class PropertyTesterDescriptor : public IPropertyTester { public: berryObjectMacro(PropertyTesterDescriptor) private: IConfigurationElement::Pointer fConfigElement; std::string fNamespace; std::string fProperties; static const std::string PROPERTIES; static const std::string NAMESPACE; static const std::string CLASS; public: PropertyTesterDescriptor(IConfigurationElement::Pointer element); PropertyTesterDescriptor(IConfigurationElement::Pointer element, const std::string& namespaze, const std::string& properties); const std::string& GetProperties(); const std::string& GetNamespace(); IConfigurationElement::Pointer GetExtensionElement(); bool Handles(const std::string& namespaze, const std::string& property); bool IsInstantiated(); bool IsDeclaringPluginActive(); IPropertyTester* Instantiate(); bool Test(Object::Pointer receiver, const std::string& method, std::vector& args, Object::Pointer expectedValue); }; } // namespace berry #endif /*BERRYPROPERTYTESTERDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryResolveExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryResolveExpression.cpp index 9ed7402f12..ea2c189276 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryResolveExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryResolveExpression.cpp @@ -1,99 +1,99 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryResolveExpression.h" #include "berryExpressions.h" -#include "../berryEvaluationContext.h" +#include "berryEvaluationContext.h" #include "Poco/Hash.h" namespace berry { const std::string ResolveExpression::ATT_VARIABLE= "variable"; const std::string ResolveExpression::ATT_ARGS= "args"; const std::size_t ResolveExpression::HASH_INITIAL = Poco::Hash()("berry::ResolveExpression"); ResolveExpression::ResolveExpression(IConfigurationElement::Pointer configElement) { bool result = configElement->GetAttribute(ATT_VARIABLE, fVariable); Expressions::CheckAttribute(ATT_VARIABLE, result); Expressions::GetArguments(fArgs, configElement, ATT_ARGS); } ResolveExpression::ResolveExpression(Poco::XML::Element* element) { fVariable = element->getAttribute(ATT_VARIABLE); Expressions::CheckAttribute(ATT_VARIABLE, fVariable.size()> 0); Expressions::GetArguments(fArgs, element, ATT_ARGS); } ResolveExpression::ResolveExpression(const std::string& variable, std::vector& args) : fVariable(variable), fArgs(args) { } EvaluationResult ResolveExpression::Evaluate(IEvaluationContext* context) { Object::Pointer variable= context->ResolveVariable(fVariable, fArgs); if (variable.IsNull()) { throw CoreException("Variable not defined", fVariable); } EvaluationContext evalContext(context, variable); return this->EvaluateAnd(&evalContext); } void ResolveExpression::CollectExpressionInfo(ExpressionInfo* info) { ExpressionInfo other; this->CompositeExpression::CollectExpressionInfo(&other); if (other.HasDefaultVariableAccess()) { info->AddVariableNameAccess(fVariable); } info->MergeExceptDefaultVariable(&other); } bool ResolveExpression::operator==(Expression& object) { try { ResolveExpression& that = dynamic_cast(object); return this->fVariable == that.fVariable && this->Equals(this->fArgs, that.fArgs) && this->Equals(this->fExpressions, that.fExpressions); } catch (std::bad_cast) { return false; } } std::size_t ResolveExpression::ComputeHashCode() { return HASH_INITIAL * HASH_FACTOR + this->HashCode(fExpressions) * HASH_FACTOR + this->HashCode(fArgs) * HASH_FACTOR + Poco::Hash()(fVariable); } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryStandardElementHandler.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryStandardElementHandler.cpp index 688a538b1c..b7ac22b624 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryStandardElementHandler.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryStandardElementHandler.cpp @@ -1,161 +1,161 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryStandardElementHandler.h" -#include "../berryExpressionTagNames.h" +#include "berryExpressionTagNames.h" #include "berryInstanceofExpression.h" #include "berryTestExpression.h" #include "berryOrExpression.h" #include "berryAndExpression.h" #include "berryNotExpression.h" #include "berryWithExpression.h" #include "berryAdaptExpression.h" #include "berryIterateExpression.h" #include "berryCountExpression.h" #include "berrySystemTestExpression.h" #include "berryResolveExpression.h" #include "berryEnablementExpression.h" #include "berryEqualsExpression.h" #include "berryReferenceExpression.h" namespace berry { Expression::Pointer StandardElementHandler::Create(ExpressionConverter* converter, IConfigurationElement::Pointer element) { std::string name = element->GetName(); if (ExpressionTagNames::INSTANCEOF == name) { Expression::Pointer result(new InstanceofExpression(element)); return result; } else if (ExpressionTagNames::TEST == name) { Expression::Pointer result(new TestExpression(element)); return result; } else if (ExpressionTagNames::OR == name) { CompositeExpression::Pointer result(new OrExpression()); this->ProcessChildren(converter, element, result); return result; } else if (ExpressionTagNames::AND == name) { CompositeExpression::Pointer result(new AndExpression()); this->ProcessChildren(converter, element, result); return result; } else if (ExpressionTagNames::NOT == name) { IConfigurationElement::vector children(element->GetChildren()); Expression::Pointer result(new NotExpression(converter->Perform(children[0]))); return result; } else if (ExpressionTagNames::WITH == name) { CompositeExpression::Pointer result(new WithExpression(element)); this->ProcessChildren(converter, element, result); return result; } else if (ExpressionTagNames::ADAPT == name) { CompositeExpression::Pointer result(new AdaptExpression(element)); this->ProcessChildren(converter, element, result); return result; } else if (ExpressionTagNames::ITERATE == name) { CompositeExpression::Pointer result(new IterateExpression(element)); this->ProcessChildren(converter, element, result); return result; } else if (ExpressionTagNames::COUNT == name) { Expression::Pointer result(new CountExpression(element)); return result; } else if (ExpressionTagNames::SYSTEM_TEST == name) { Expression::Pointer result(new SystemTestExpression(element)); return result; } else if (ExpressionTagNames::RESOLVE == name) { CompositeExpression::Pointer result(new ResolveExpression(element)); this->ProcessChildren(converter, element, result); return result; } else if (ExpressionTagNames::ENABLEMENT == name) { CompositeExpression::Pointer result(new EnablementExpression(element)); this->ProcessChildren(converter, element, result); return result; } else if (ExpressionTagNames::EQUALS == name) { Expression::Pointer result(new EqualsExpression(element)); return result; } else if (ExpressionTagNames::REFERENCE == name) { Expression::Pointer result(new ReferenceExpression(element)); return result; } return Expression::Pointer(); } Expression::Pointer StandardElementHandler::Create(ExpressionConverter* converter, Poco::XML::Element* element) { std::string name= element->nodeName(); if (ExpressionTagNames::INSTANCEOF == name) { Expression::Pointer result(new InstanceofExpression(element)); return result; } else if (ExpressionTagNames::TEST == name) { Expression::Pointer result(new TestExpression(element)); return result; } else if (ExpressionTagNames::OR == name) { CompositeExpression::Pointer result(new OrExpression()); this->ProcessChildren(converter, element, result); return result; } else if (ExpressionTagNames::AND == name) { CompositeExpression::Pointer result(new AndExpression()); this->ProcessChildren(converter, element, result); return result; } else if (ExpressionTagNames::NOT == name) { Poco::XML::Node* child = element->firstChild(); while (child != 0) { if (child->nodeType() == Poco::XML::Node::ELEMENT_NODE) { Expression::Pointer result(new NotExpression(converter->Perform(static_cast(child)))); return result; } child = child->nextSibling(); } } else if (ExpressionTagNames::WITH == name) { CompositeExpression::Pointer result(new WithExpression(element)); this->ProcessChildren(converter, element, result); return result; } else if (ExpressionTagNames::ADAPT == name) { CompositeExpression::Pointer result(new AdaptExpression(element)); this->ProcessChildren(converter, element, result); return result; } else if (ExpressionTagNames::ITERATE == name) { CompositeExpression::Pointer result(new IterateExpression(element)); this->ProcessChildren(converter, element, result); return result; } else if (ExpressionTagNames::COUNT == name) { Expression::Pointer result(new CountExpression(element)); return result; } else if (ExpressionTagNames::SYSTEM_TEST == name) { Expression::Pointer result(new SystemTestExpression(element)); return result; } else if (ExpressionTagNames::RESOLVE == name) { CompositeExpression::Pointer result(new ResolveExpression(element)); this->ProcessChildren(converter, element, result); return result; } else if (ExpressionTagNames::ENABLEMENT == name) { CompositeExpression::Pointer result(new EnablementExpression(element)); this->ProcessChildren(converter, element, result); return result; } else if (ExpressionTagNames::EQUALS == name) { Expression::Pointer result(new EqualsExpression(element)); return result; } else if (ExpressionTagNames::REFERENCE == name) { Expression::Pointer result(new ReferenceExpression(element)); return result; } return Expression::Pointer(); } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryStandardElementHandler.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryStandardElementHandler.h index 8e7023a489..de516f8425 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryStandardElementHandler.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryStandardElementHandler.h @@ -1,41 +1,41 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYSTANDARDELEMENTHANDLER_H_ #define BERRYSTANDARDELEMENTHANDLER_H_ #include "service/berryIConfigurationElement.h" -#include "../berryExpression.h" -#include "../berryElementHandler.h" -#include "../berryExpressionConverter.h" +#include "berryExpression.h" +#include "berryElementHandler.h" +#include "berryExpressionConverter.h" namespace berry { class StandardElementHandler : public ElementHandler { public: Expression::Pointer Create(ExpressionConverter* converter, SmartPointer element); Expression::Pointer Create(ExpressionConverter* converter, Poco::XML::Element* element); }; } // namespace berry #endif /*BERRYSTANDARDELEMENTHANDLER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berrySystemTestExpression.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berrySystemTestExpression.h index 2aa4613797..5e34672c75 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berrySystemTestExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berrySystemTestExpression.h @@ -1,71 +1,71 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __BERRY_SYSTEM_TEXT_EXPRESSION_H__ #define __BERRY_SYSTEM_TEXT_EXPRESSION_H__ -#include "../berryExpression.h" +#include "berryExpression.h" #include "service/berryIConfigurationElement.h" #include "Poco/DOM/Element.h" namespace berry { class SystemTestExpression : public Expression { private: std::string fProperty; std::string fExpectedValue; static const std::string ATT_PROPERTY; /** * The seed for the hash code for all system test expressions. */ static const std::size_t HASH_INITIAL; public: SystemTestExpression(SmartPointer element); SystemTestExpression(Poco::XML::Element* element); SystemTestExpression(const std::string& property, const std::string& expectedValue); EvaluationResult Evaluate(IEvaluationContext* context); void CollectExpressionInfo(ExpressionInfo* info); bool operator==(Expression& object); protected: std::size_t ComputeHashCode(); // ---- Debugging --------------------------------------------------- /* (non-Javadoc) * @see java.lang.Object#toString() */ public: std::string ToString(); }; } // namespace berry #endif // __BERRY_SYSTEM_TEXT_EXPRESSION_H__ 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 14ccd195cf..bed1f912f9 100755 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTestExpression.h @@ -1,92 +1,92 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __BERRY_TEST_EXPRESSION_H__ #define __BERRY_TEST_EXPRESSION_H__ -#include "../berryExpression.h" +#include "berryExpression.h" #include "berryTypeExtensionManager.h" #include "service/berryIConfigurationElement.h" #include "berryObject.h" #include "Poco/DOM/Element.h" namespace berry { class TestExpression : public Expression { private: std::string fNamespace; std::string fProperty; std::vector fArgs; Object::Pointer fExpectedValue; bool fForcePluginActivation; static const char PROP_SEP; static const std::string ATT_PROPERTY; static const std::string ATT_ARGS; static const std::string ATT_FORCE_PLUGIN_ACTIVATION; /** * The seed for the hash code for all test expressions. */ static const std::size_t HASH_INITIAL; static TypeExtensionManager fgTypeExtensionManager; public: TestExpression(SmartPointer element); TestExpression(Poco::XML::Element* element); TestExpression(const std::string& namespaze, const std::string& property, std::vector& args, Object::Pointer expectedValue); TestExpression(const std::string& namespaze, const std::string& property, std::vector& args, Object::Pointer expectedValue, bool forcePluginActivation); EvaluationResult Evaluate(IEvaluationContext* context); void CollectExpressionInfo(ExpressionInfo* info); bool operator==(Expression& object); protected: std::size_t ComputeHashCode(); //---- Debugging --------------------------------------------------- /* (non-Javadoc) * @see java.lang.Object#toString() */ public: std::string ToString(); //---- 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 689ac7c071..459202df44 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtension.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtension.cpp @@ -1,105 +1,105 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryTypeExtension.h" #include "berryTypeExtensionManager.h" #include "berryPropertyTesterDescriptor.h" -#include "../berryPropertyTester.h" +#include "berryPropertyTester.h" namespace berry { TypeExtension::TypeExtension(const std::string& typeInfo) : fTypeInfo(typeInfo), fExtendersLoaded(false), fExtendsLoaded(false) { } IPropertyTester::Pointer TypeExtension::FindTypeExtender(TypeExtensionManager& manager, const std::string& namespaze, const std::string& method, bool staticMethod, bool forcePluginActivation) { if (!fExtendersLoaded) { manager.LoadTesters(fExtenders, fTypeInfo); fExtendersLoaded = true; } IPropertyTester::Pointer result; // handle extenders associated with this type extender for (unsigned 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 (CoreException e) { fExtenders[i] = IPropertyTester::Pointer(); throw e; } } else { fExtenders[i]= IPropertyTester::Pointer(); throw CoreException("Type extender has incorrect type"); } } else { return extender; } } } // there is no inheritance for static methods if (staticMethod) return CONTINUE_::Pointer(new CONTINUE_()); // handle inheritance chain // TODO Reflection // if (!fExtendsLoaded) { // fExtends.clear(); // Object::ExtTypeInfo types(fTypeInfo); // while (!types.m_TypeNames.empty()) { // types.m_TypeNames.pop_back(); // types.m_TypeInfos.pop_back(); // fExtends.push_back(manager.Get(types)); // } // fExtendsLoaded = true; // } // for (unsigned int i= 0; i < fExtends.size(); i++) { // result = fExtends[i]->FindTypeExtender(manager, namespaze, method, staticMethod, forcePluginActivation); // if (result.Cast().IsNull()) // return result; // } return CONTINUE_::Pointer(new CONTINUE_()); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtension.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtension.h index 4a627e3ff0..ebe0975526 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtension.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtension.h @@ -1,111 +1,111 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYTYPEEXTENSION_H_ #define BERRYTYPEEXTENSION_H_ #include #include -#include "../berryIPropertyTester.h" +#include "berryIPropertyTester.h" #include namespace berry { class TypeExtensionManager; class END_POINT_; class TypeExtension : public Object { public: berryObjectMacro(TypeExtension); private: /* the type this extension is extending */ std::string fTypeInfo; /* the list of associated extenders */ std::vector fExtenders; bool fExtendersLoaded; /* the extensions associated with fType's super classes */ std::vector fExtends; bool fExtendsLoaded; TypeExtension() : fExtendersLoaded(false), fExtendsLoaded(false) { // special constructor to create the CONTINUE instance } protected: friend class TypeExtensionManager; /* a special property tester instance that is used to signal that method searching has to continue */ /* package */ class CONTINUE_ : public IPropertyTester { public: berryObjectMacro(CONTINUE_) bool Handles(const std::string& /*namespaze*/, const std::string& /*method*/) { return false; } bool IsInstantiated() { return true; } bool IsDeclaringPluginActive() { return true; } IPropertyTester* Instantiate() { return this; } bool Test(Object::Pointer /*receiver*/, const std::string& /*method*/, std::vector& /*args*/, Object::Pointer /*expectedValue*/) { return false; } }; static const CONTINUE_ CONTINUE; static const END_POINT_ END_POINT; /* package */ TypeExtension(const std::string& typeInfo); /* package */ IPropertyTester::Pointer FindTypeExtender(TypeExtensionManager& manager, const std::string& namespaze, const std::string& 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 std::string& /*namespaze*/, const std::string& /*name*/, bool /*staticMethod*/, bool /*forcePluginActivation*/) { return CONTINUE_::Pointer(new CONTINUE_()); } }; } // namespace berry #endif /*BERRYTYPEEXTENSION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtensionManager.h b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtensionManager.h index 60291ad3ed..6cd431ad20 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtensionManager.h +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryTypeExtensionManager.h @@ -1,127 +1,127 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYTYPEEXTENSIONMANAGER_H_ #define BERRYTYPEEXTENSIONMANAGER_H_ -#include "../berryIPropertyTester.h" +#include "berryIPropertyTester.h" #include "berryTypeExtension.h" #include "berryPropertyCache.h" #include "berryProperty.h" #include #include #include #include namespace berry { class TypeExtensionManager { // implements IRegistryChangeListener { private: std::string fExtensionPoint; static const std::string TYPE; class NULL_PROPERTY_TESTER_ : public IPropertyTester { public: bool Handles(const std::string& /*namespaze*/, const std::string& /*property*/) { return false; } bool IsInstantiated() { return true; } bool IsDeclaringPluginActive() { return true; } IPropertyTester* Instantiate() { return this; } bool Test(Object::Pointer, const std::string& /*property*/, std::vector& /*args*/, Object::Pointer /*expectedValue*/) { return false; } }; static const NULL_PROPERTY_TESTER_ NULL_PROPERTY_TESTER; /* * Map containing all already created type extension object. */ std::map fTypeExtensionMap; /* * Table containing mapping of class name to configuration element */ std::map >* fConfigurationElementMap; /* * A cache to give fast access to the last 1000 method invocations. */ PropertyCache* fPropertyCache; public: TypeExtensionManager(const std::string& extensionPoint); ~TypeExtensionManager(); Property::Pointer GetProperty(Object::Pointer receiver, const std::string& namespaze, const std::string& method); /*synchronized*/Property::Pointer GetProperty(Object::Pointer receiver, const std::string& namespaze, const std::string& 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 std::string& type); /* * This method doesn't need to be synchronized since it is called * from withing the getProperty method which is synchronized */ /* package */void LoadTesters(std::vector& result, const std::string& typeName); // public void registryChanged(IRegistryChangeEvent event) { // IExtensionDelta[] deltas= event.getExtensionDeltas(ExpressionPlugin.getPluginId(), fExtensionPoint); // if (deltas.length > 0) { // initializeCaches(); // } // } private: /*synchronized*/void InitializeCaches(); }; } #endif /*BERRYTYPEEXTENSIONMANAGER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryWithExpression.cpp b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryWithExpression.cpp index 3e534243d1..0dddfb80a2 100644 --- a/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryWithExpression.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.expressions/src/internal/berryWithExpression.cpp @@ -1,94 +1,94 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWithExpression.h" #include "berryExpressions.h" -#include "../berryEvaluationContext.h" +#include "berryEvaluationContext.h" #include namespace berry { const std::string WithExpression::ATT_VARIABLE= "variable"; const std::size_t WithExpression::HASH_INITIAL= Poco::hash("berry::WithExpression"); WithExpression::WithExpression(IConfigurationElement::Pointer configElement) { bool result = configElement->GetAttribute(ATT_VARIABLE, fVariable); Expressions::CheckAttribute(ATT_VARIABLE, result); } WithExpression::WithExpression(Poco::XML::Element* element) { fVariable = element->getAttribute(ATT_VARIABLE); Expressions::CheckAttribute(ATT_VARIABLE, fVariable.length()> 0); } WithExpression::WithExpression(const std::string& variable) : fVariable(variable) { } bool WithExpression::operator==(Expression& object) { try { WithExpression& that = dynamic_cast(object); return this->fVariable == that.fVariable && this->Equals(this->fExpressions, that.fExpressions); } catch (std::bad_cast) { return false; } } EvaluationResult WithExpression::Evaluate(IEvaluationContext* context) { Object::Pointer variable(context->GetVariable(fVariable)); if (variable.IsNull()) { throw CoreException("Variable not defined", fVariable); } return this->EvaluateAnd(new EvaluationContext(context, variable)); } void WithExpression::CollectExpressionInfo(ExpressionInfo* info) { ExpressionInfo* other = new ExpressionInfo(); CompositeExpression::CollectExpressionInfo(other); if (other->HasDefaultVariableAccess()) { info->AddVariableNameAccess(fVariable); } info->MergeExceptDefaultVariable(other); } std::size_t WithExpression::ComputeHashCode() { return HASH_INITIAL * HASH_FACTOR + this->HashCode(fExpressions) * HASH_FACTOR + Poco::hash(fVariable); } } diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryInternalJob.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryInternalJob.h index 44eae72fdf..fc46721c9a 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryInternalJob.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryInternalJob.h @@ -1,468 +1,468 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRY_INTERNALJOB_H #define BERRY_INTERNALJOB_H #include #include #include #include -#include "../berryJobExceptions.h" -#include "../berryISchedulingRule.h" -#include "../berryIProgressMonitor.h" -#include "../berryIJobChangeListener.h" +#include "berryJobExceptions.h" +#include "berryISchedulingRule.h" +#include "berryIProgressMonitor.h" +#include "berryIJobChangeListener.h" #include #include #include #include #include #include namespace berry { struct JobManager; /** * Internal implementation class for jobs. Clients must not implement this class * directly. All jobs must be subclasses of the API org.blueberry_core_jobs.Job class. */ // struct BERRY_JOBS InternalJob: public Object, public Comparable struct BERRY_JOBS InternalJob : public Object { friend struct JobQueue; friend struct JobManager; berryObjectMacro(InternalJob) bool operator==(const Object* otherJob) const; /** * Adds an entry at the end of the list of which this item is the head. */ void AddLast(InternalJob::Pointer entry); /* * Returns the job listeners that are only listening to this job. */ const IJobChangeListener::Events& GetListeners() const; /** * Returns the job's progress monitor, or null if it is not running. */ IProgressMonitor::Pointer GetProgressMonitor() const; /** * Returns the time that this job should be started, awakened, or * rescheduled, depending on the current state. * @return time in milliseconds */ Poco::Timestamp GetStartTime() const; /** * Returns the raw job state, including internal states no exposed as API. */ int InternalGetState() const; /* * @see Job#GetState() */ int GetState() const; /** * @see Job#GetName() */ std::string GetName() const; /* * @see Job#setRule(ISchedulingRule::Pointer) */ void InternalSetRule(ISchedulingRule::Pointer rule); /** * Must be called from JobManager#setPriority */ void InternalSetPriority(int newPriority); /** * Must be called from JobManager#ChangeState */ void InternalSetState(int i); /** * Returns whether this job was canceled when it was about to run */ bool IsAboutToRunCanceled() const; /** * Returns whether this job was canceled when it was running. */ bool IsRunCanceled() const ; /** * Returns true if this job conflicts with the given job, and false otherwise. */ bool IsConflicting(InternalJob::Pointer otherJob) const; /** * Returns the next entry (ahead of this one) in the list, or null if there is no next entry */ InternalJob::Pointer Next() const; /** * Returns the previous entry (behind this one) in the list, or null if there is no previous entry */ InternalJob::Pointer Previous() const; /** * Removes this entry from any list it belongs to. Returns the receiver. */ InternalJob::Pointer Remove(); /* * @see Job#run(IProgressMonitor) */ virtual IStatus::Pointer Run(IProgressMonitor::Pointer myProgressMonitor) = 0 ; /** * Sets whether this job was canceled when it was about to run */ void SetAboutToRunCanceled(bool value) throw (JobRuntimeException); /** * Sets the next entry in this linked list of jobs. * @param entry */ /** * Sets whether this job was canceled when it was running */ void SetRunCanceled(bool value) ; void SetNext(InternalJob::Pointer entry); /** * Sets the previous entry in this linked list of jobs. * @param entry */ void SetPrevious(InternalJob::Pointer entry); /** * Sets the progress monitor to use for the next execution of this job, * or for clearing the monitor when a job completes. * @param monitor a progress monitor */ void SetProgressMonitor(IProgressMonitor::Pointer monitor); /** * Sets or clears the result of an execution of this job. * @param result a result status, or null */ void SetResult(IStatus::Pointer result) ; /** * Sets a time to start, wake up, or schedule this job, * depending on the current state * @param time a time in milliseconds */ void SetStartTime(Poco::Timestamp::TimeDiff time); void SetStartTime(const Poco::Timestamp& newtime); /* * @see Job.SetThread */ void SetThread(Poco::Thread* thread); /* * @see Job.GetThread */ Poco::Thread* GetThread() const; /* * Prints a string-based representation of this job instance. * For debugging purposes only. */ std::string ToString(); /** * @param waitQueueStamp The waitQueueStamp to set. */ void SetWaitQueueStamp(Poco::Timestamp waitQueueStamp); /** * @return Returns the waitQueueStamp. */ Poco::Timestamp GetWaitQueueStamp(); protected: InternalJob(std::string name); /* * @see Job#AddJobListener(IJobChangeListener::Pointer) */ void AddJobChangeListener(IJobChangeListener::Pointer listener); /* * @see Job#BelongsTo(Object) */ virtual bool BelongsTo(Object::Pointer family); /* * @see Job#Cancel() */ bool Cancel(); /* * @see Job#Canceling() */ virtual void Canceling(); /* * * @see Job#Done(IStatus:.Pointer) */ void Done(IStatus::Pointer endResult); /* * @see Job#GetPriority() */ int GetPriority() const; /* * @see Job#GetProperty */ /// Object GetProperty(QualifiedName key) ; /* * @see Job#GetResult */ IStatus::Pointer GetResult() const ; /* * @see Job#GetRule */ ISchedulingRule::Pointer GetRule() const; /* * @see Job.IsSystem() */ bool IsSystem() const; /* * @see Job.IsUser() */ bool IsUser() const; /* * @see Job#Join() */ /// void Join() throws InterruptedException ; /* * @see Job#RemoveJobListener(IJobChangeListener) */ void RemoveJobChangeListener(IJobChangeListener::Pointer listener); /* * @see Job#Schedule(long) */ void Schedule(Poco::Timestamp::TimeDiff delay); /* * @see Job#SetName(std::string) */ void SetName(const std::string& name); /* * @see Job#SetPriority(int) */ void SetPriority(int newPriority); /* * @see Job#SetProgressGroup(IProgressMonitor::Pointer, int ticks) */ void SetProgressGroup(IProgressMonitor::Pointer group, int ticks); /* * @see Job#SetProperty(QualifiedName,Object) */ /// void SetProperty(QualifiedName key, Object value) ; /* internalSetRule * @see Job#SetRule(ISchedulingRule::Pointer) */ void SetRule(ISchedulingRule::Pointer rule); /* * @see Job.SetSystem */ void SetSystem(bool value); /* * @see Job.SetUser */ void SetUser(bool value); /* * @see Job#ShouldSchedule */ virtual bool ShouldSchedule(); /* * @see Job#Sleep() */ bool Sleep(); /* * @see Job#WakeUp(long) */ void WakeUp(long delay); public: /** * Flag on a job indicating that it was canceled when running. This flag * is used to ensure that #canceling is only ever called once on a job in * case of recursive cancellation attempts. */ static const int M_RUN_CANCELED = 0x0800; /** * Job state code (value 16) indicating that a job has been removed from * the wait queue and is about to start running. From an API point of view, * this is the same as RUNNING. */ static const int ABOUT_TO_RUN = 0x10; /** * Job state code (value 32) indicating that a job has passed scheduling * precondition checks and is about to be added to the wait queue. From an API point of view, * this is the same as WAITING. */ static const int ABOUT_TO_SCHEDULE = 0x20; /** * Job state code (value 8) indicating that a job is blocked by another currently * running job. From an API point of view, this is the same as WAITING. */ static const int BLOCKED = 0x08; /** * Start time constant indicating a job should be started at * a time in the infinite future, causing it to sleep forever. */ static const Poco::Timestamp::TimeDiff T_INFINITE; /** * Start time constant indicating that the job has no start time. */ static const Poco::Timestamp::TimeDiff T_NONE; private: //flag mask bits static const int M_STATE = 0xFF; static const int M_SYSTEM = 0x0100; static const int M_USER = 0x0200; /** * flag on a job indicating that it was about to run, but has been canceled */ static const int M_ABOUT_TO_RUN_CANCELED = 0x0400; static int nextJobNumber; int jobNumber; volatile int flags; /// ListenerList listeners ; std::string name; /** * The job ahead of me in a queue or list. */ InternalJob::Pointer next; /** * The job behind me in a queue or list. */ InternalJob* previous; int priority; /** * Arbitrary properties (key,value) pairs, attached * to a job instance by a third party. */ //std::map properties ; IStatus::Pointer m_result; // Pointer to the ISchedulingRule belonging to the particular job ISchedulingRule::Pointer sptr_schedulingRule; IProgressMonitor::Pointer sptr_monitor; /** * If the job is waiting, this represents the time the job should start by. * If this job is sleeping, this represents the time the job should wake up. * If this job is running, this represents the delay automatic rescheduling, * or -1 if the job should not be rescheduled. */ Poco::Timestamp m_startTime; /** * Stamp added when a job is added to the wait queue. Used to ensure * jobs in the wait queue maintain their insertion order even if they are * removed from the wait queue temporarily while blocked */ Poco::Timestamp waitQueueStamp; /* * The that is currently running this job */ Poco::Thread* ptr_thread; InternalJob(const Self&); protected: static JobManager* const ptr_manager; IJobChangeListener::Events jobEvents; /* * @see Job#isBlocking() */ bool IsBlocking(); }; } #endif /* BERRY_INTERNALJOB_H */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobChangeEvent.cpp b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobChangeEvent.cpp index 915db9a18f..f4f4e277e3 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobChangeEvent.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobChangeEvent.cpp @@ -1,44 +1,44 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryJobChangeEvent.h" -#include "../berryJob.h" +#include "berryJob.h" namespace berry { JobChangeEvent::JobChangeEvent() : delay(-1), reschedule(false) { } Poco::Timestamp::TimeDiff JobChangeEvent::GetDelay() const { return delay; } Job::Pointer JobChangeEvent::GetJob() const { return job; } IStatus::Pointer JobChangeEvent::GetResult() const { return result; } } diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobChangeEvent.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobChangeEvent.h index 3d402c0379..2b69c019fa 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobChangeEvent.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobChangeEvent.h @@ -1,80 +1,80 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYJOBCHANGEEVENT_H_ #define BERRYJOBCHANGEEVENT_H_ -#include "../berryIJobChangeEvent.h" +#include "berryIJobChangeEvent.h" namespace berry { class JobChangeEvent : public IJobChangeEvent { private: friend class JobListeners; /** * The job on which this event occurred. */ SmartPointer job; /** * The result returned by the job's run method, or null if * not applicable. */ IStatus::Pointer result; /** * The amount of time to wait after scheduling the job before it should be run, * or -1 if not applicable for this type of event. */ Poco::Timestamp::TimeDiff delay; /** * Whether this job is being immediately rescheduled. */ bool reschedule; public: berryObjectMacro(JobChangeEvent) JobChangeEvent(); /* * Method declared on IJobChangeEvent */ Poco::Timestamp::TimeDiff GetDelay() const; /* * Method declared on IJobChangeEvent */ SmartPointer GetJob() const; /* ( * Method declared on IJobChangeEvent */ IStatus::Pointer GetResult() const; }; } #endif /* BERRYJOBCHANGEEVENT_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 703b580d83..2d7e18bbdd 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.cpp +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.cpp @@ -1,160 +1,160 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryJobListeners.h" #include "berryJobManager.h" -#include "../berryJob.h" +#include "berryJob.h" #include #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 { dynamic_cast (e); return; } catch (const std::bad_cast&) { // TODO get bundle id (find a C++ way) //std::string pluginId = JobOSGiUtils.getDefault().getBundleId(listener); std::string pluginId; if (pluginId.empty()) pluginId = JobManager::PI_JOBS(); std::string message = "Problems occurred when invoking code from plug-in: " + pluginId; std::cerr << message << std::endl; // TODO Logging // RuntimeLog.log(new Status(IStatus.ERROR, pluginId, JobManager.PLUGIN_ERROR, // message, e)); } } } diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.h index 98be4c5624..d52a435fc9 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobListeners.h @@ -1,134 +1,134 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYJOBLISTENERS_H_ #define BERRYJOBLISTENERS_H_ #include "berryJobChangeEvent.h" -#include "../berryIJobChangeListener.h" +#include "berryIJobChangeListener.h" namespace berry { /** * Responsible for notifying all job listeners about job lifecycle events. Uses a * specialized iterator to ensure the complex iteration logic is contained in one place. */ class JobListeners { public: struct IListenerDoit { virtual void Notify(const IJobChangeListener::Events& listener, const IJobChangeEvent::ConstPointer event) const = 0; virtual ~IListenerDoit() {} }; private: friend struct JobManager; const IListenerDoit* aboutToRun; const IListenerDoit* awake; const IListenerDoit* done; const IListenerDoit* running; const IListenerDoit* scheduled; const IListenerDoit* sleeping; /** * The global job listeners. */ IJobChangeListener::Events global; /** * TODO Could use an instance pool to re-use old event objects */ static JobChangeEvent::Pointer NewEvent(SmartPointer job); static JobChangeEvent::Pointer NewEvent(SmartPointer job, IStatus::Pointer result); static JobChangeEvent::Pointer NewEvent(SmartPointer job, Poco::Timestamp::TimeDiff delay); /** * Process the given doit for all global listeners and all local listeners * on the given job. */ void DoNotify(const IListenerDoit* doit, const IJobChangeEvent::ConstPointer event); public: JobListeners(); ~JobListeners(); void HandleException(const std::exception& e); void Add(IJobChangeListener::Pointer listener) { global.AddListener(listener); } void Remove(IJobChangeListener::Pointer listener) { global.RemoveListener(listener); } void AboutToRun(SmartPointer job) { DoNotify(aboutToRun, NewEvent(job)); } void Awake(SmartPointer job) { DoNotify(awake, NewEvent(job)); } void Done(SmartPointer job, IStatus::Pointer result, bool reschedule) { JobChangeEvent::Pointer event = NewEvent(job, result); event->reschedule = reschedule; DoNotify(done, event); } void Running(SmartPointer job) { DoNotify(running, NewEvent(job)); } void Scheduled(SmartPointer job, Poco::Timestamp::TimeDiff delay, bool reschedule) { JobChangeEvent::Pointer event = NewEvent(job, delay); event->reschedule = reschedule; DoNotify(scheduled, event); } void Sleeping(SmartPointer job) { DoNotify(sleeping, NewEvent(job)); } }; } #endif /* BERRYJOBLISTENERS_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobManager.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobManager.h index 5a00dbf42d..a03dfa8c82 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobManager.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobManager.h @@ -1,435 +1,435 @@ //*========================================================================= // // Program: BlueBerry Platform // Language: C++ // Date: $Date$ // Version: $Revision$ // // Copyright (c) German Cancer Research Center, Division of Medical and // Biological Informatics. All rights reserved. // See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notices for more information. // // =========================================================================*/ // // #ifndef _BERRY_JOBMANAGER_H #define _BERRY_JOBMANAGER_H #include "berryInternalJob.h" #include "berryJobQueue.h" #include "berryWorkerPool.h" #include "berryJobListeners.h" -#include "../berryJob.h" -#include "../berryIProgressMonitorWithBlocking.h" -#include "../berryIJobManager.h" -#include "../berryISchedulingRule.h" +#include "berryJob.h" +#include "berryIProgressMonitorWithBlocking.h" +#include "berryIJobManager.h" +#include "berryISchedulingRule.h" #include #include #include #include #include #include #include #include #include namespace berry { /** * Implementation of API type IJobManager * * Implementation note: all the data structures of this class are protected * by a single lock object held as a private field in this class. The JobManager * instance itself is not used because this class is publicly reachable, and third * party clients may try to synchronize on it. * * The WorkerPool class uses its own monitor for synchronizing its data * structures. To avoid deadlock between the two classes, the JobManager * must NEVER call the worker pool while its own monitor is held. */ struct BERRY_JOBS JobManager: public IJobManager { public: friend class WorkerPool; friend struct InternalJob; friend struct NullRule; berryObjectMacro(JobManager) /** * The unique identifier constant of this plug-in. */ static const std::string& PI_JOBS(); static bool DEBUG; static bool DEBUG_BEGIN_END; static bool DEBUG_DEADLOCK; static bool DEBUG_LOCKS; static bool DEBUG_TIMING; static bool DEBUG_SHUTDOWN; /** * Status code constant indicating an error occurred while running a plug-in. * For backward compatibility with Platform.PLUGIN_ERROR left at (value = 2). */ static const int PLUGIN_ERROR; /// const ImplicitJobs iImplicitJobs = new ImplicitJobs(this); /** * The singleton job manager instance. It must be a singleton because * all job instances maintain a reference (as an optimization) and have no way * of updating it. */ static JobManager* GetInstance(); /** * For debugging purposes only */ static std::string PrintState(int state); /** * Note that although this method is not API, clients have historically used * it to force jobs shutdown in cases where OSGi shutdown does not occur. * For this reason, this method should be considered near-API and should not * be changed if at all possible. */ static void Shutdown(); // void Cancel(Object family) ; IProgressMonitor::Pointer CreateProgressGroup(); Job* CurrentJob(); // void EndRule(ISchedulingRule rule) ; // Job[] Find(Object family) ; // LockManager GetLockManager() { // return lockManager; // } bool IsIdle(); bool IsSuspended(); // void Join(final Object family, IProgressMonitor monitor) throws InterruptedException, OperationCanceledException ); // ILock NewLock() ; /** * @see IJobManager#RemoveChangeListener(IJobChangeListener::Pointer) */ void RemoveJobChangeListener(IJobChangeListener::Pointer listener); // /** //* report to the progress monitor that this thread is blocked, supplying //* an information message, and if possible the job that is causing the blockage. //* important: an invocation of this method must be followed eventually be //* an invocation of ReportUnblocked. //* @param monitor the monitor to report blocking to //* @param BlockingJob the job that is blocking this thread, or null //* @see #Reportunblocked //*/ void ReportBlocked( IProgressMonitor::Pointer monitor, InternalJob::Pointer blockingjob) const ; /** * Reports that this thread was blocked, but is no longer blocked and is able * to proceed. * @param monitor The monitor to report unblocking to. * @see #ReportBlocked */ void ReportUnblocked(IProgressMonitor::Pointer monitor) const ; /** * @have a look at IJobManager Resume */ void Resume(); // /** // * @have a look at IJobManager Resume // */ // void Resume(ISchedulingRule::Pointer rule)const ; /** * @have a look at IJobManager SetProgressProvider */ void SetProgressProvider(ProgressProvider::Pointer provider); void SetRule(InternalJob::Pointer job, ISchedulingRule::Pointer rule); // /* // * @see IJobManager#sleep(std::string) // */ // void Sleep(Object family) ; void Suspend(); /* * @see schedule(long) */ void Schedule(InternalJob::Pointer job, Poco::Timestamp::TimeDiff delay, bool reschedule); // void Suspend(ISchedulingRule::Pointer rule, IProgressMonitor::Pointer monitor)const ; // void TransferRule(ISchedulingRule rule, Thread destinationThread) ; // void SetLockListener(LockListener listener) ; // /** // * Puts a job to sleep. Returns true if the job was successfully put to sleep. // */ // void WakeUp(Object family) ; void AddJobChangeListener(IJobChangeListener::Pointer listener); // void beginRule(ISchedulingRule rule, IProgressMonitor monitor) ; protected: /** * Cancels a job */ bool Cancel(InternalJob::Pointer job); /** * Returns a new progress monitor for this job, belonging to the given * progress group. Returns null if it is not a valid time to set the job's group. */ IProgressMonitor::Pointer CreateMonitor(InternalJob::Pointer job, IProgressMonitor::Pointer group, int ticks); /** * Indicates that a job was running, and has now finished. Note that this method * can be called under OutOfMemoryError conditions and thus must be paranoid * about allocating objects. */ /// optional Extension IStatus for implementation help have a look at the Java JobAPI void EndJob(InternalJob::Pointer job,IStatus::Pointer result, bool notify); /** * Returns a running or blocked job whose scheduling rule conflicts with the * scheduling rule of the given waiting job. Returns null if there are no * conflicting jobs. A job can only run if there are no running jobs and no blocked * jobs whose scheduling rule conflicts with its rule. */ InternalJob::Pointer FindBlockingJob(InternalJob::Pointer waitingJob); /** * Returns whether the job manager is active (has not been shutdown). */ bool IsActive(); /** * Returns true if the given job is blocking the execution of a non-system * job. */ bool IsBlocking(InternalJob::Pointer runningJob); // void Join(InternalJob job) ; /** * Attempts to immediately start a given job. Returns true if the job was * successfully started, and false if it could not be started immediately * due to a currently running job with a conflicting rule. Listeners will never * be notified of jobs that are run in this way. */ bool RunNow(InternalJob::Pointer sptr_job); /** * Puts a job to sleep. Returns true if the job was successfully put to sleep. */ bool Sleep(InternalJob::Pointer job); /** * Changes a job priority. */ void SetPriority(InternalJob::Pointer job, int newPriority); /** * Returns the estimated time in milliseconds before the next job is scheduled * to wake up. The result may be negative. Returns InternalJob.T_INFINITE if * there are no sleeping or waiting jobs. */ Poco::Timespan::TimeDiff SleepHint(); /** * Returns the next job to be run, or null if no jobs are waiting to run. * The worker must call endJob when the job is finished running. */ Job::Pointer StartJob(); /* * @see Job#WakeUp(long) */ void WakeUp(InternalJob::Pointer job, Poco::Timestamp::TimeDiff delay); private: JobManager(); /* Poco Mutex for synchronizing purposes */ Poco::Mutex m_mutex; // Dummy Null rule to validate SchedulingRules implemented by clients SmartPointer sptr_testRule; // //ToDO static const ISchedulingRule nullRule = new ISchedulingRule() { // public bool Contains(ISchedulingRule rule) ; // public boolean IsConflicting(ISchedulingRule rule) ; /** * True if this manager is active, and false otherwise. A job manager * starts out active, and becomes inactive if it has been shutdown * and not restarted. */ volatile bool m_active; JobListeners m_JobListeners; // // /** // * The lock for synchronizing all activity in the job manager. To avoid deadlock, // * this lock must never be held for extended periods, and must never be // * held while third party code is being called. // */ // // private final Object lock = new Object(); // static const Object lock ; // // //private LockManager lockManager = new LockManager(); // static const LockManger lockManager; /** * The pool of worker threads. */ WorkerPool::Pointer m_Pool; ProgressProvider::Pointer m_sptr_progressProvider; /** * Jobs that are currently running. Should only be modified from changeState */ Poco::HashSet m_running; /** * Jobs that are sleeping. Some sleeping jobs are scheduled to wake * up at a given start time, while others will sleep indefinitely until woken. * Should only be modified from changeState */ JobQueue m_JobQueueSleeping; /** * jobs that are waiting to be run. Should only be modified from changeState */ JobQueue m_JobQueueWaiting; /** * True if this manager has been suspended, and false otherwise. A job manager * starts out not suspended, and becomes suspended when suspend * is invoked. Once suspended, no jobs will start running until resume * is cancelled. */ bool m_suspended; /** * Counter to record wait queue insertion order. */ long long m_waitQueueCounter; // /** // * For debugging purposes only // */ // const std::string PrintJobName(Job job); /** * Atomically updates the state of a job, adding or removing from the * necessary queues or sets. */ void ChangeState(InternalJob::Pointer job, int newState); /** * Returns a new progress monitor for this job. Never returns null. */ IProgressMonitor::Pointer CreateMonitor(Job::Pointer sptr_jobToMonitor); /** * Returns the delay in milliseconds that a job with a given priority can * tolerate waiting. */ Poco::Timestamp::TimeDiff DelayFor(int priority); /** * Performs the scheduling of a job. Does not perform any notifications. */ void DoSchedule(InternalJob::Pointer job, Poco::Timestamp::TimeDiff delay); /** * Shuts down the job manager. Currently running jobs will be told * to stop, but worker threads may still continue processing. * (note: This implemented IJobManager.Shutdown which was removed * due to problems caused by premature shutdown) */ void DoShutdown(); // void InitDebugOptions() ; /** * Removes and returns the first waiting job in the queue. Returns null if there * are no items waiting in the queue. If an item is removed from the queue, * it is moved to the running jobs list. */ Job::Pointer NextJob(); /** * Returns a non-null progress monitor instance. If the monitor is null, * returns the default monitor supplied by the progress provider, or a * NullProgressMonitor if no default monitor is available. */ IProgressMonitor::Pointer MonitorFor(IProgressMonitor::Pointer monitor); // /** // * Adds all family members in the list of jobs to the collection // */ // void Select(List members, Object family, InternalJob firstJob, int stateMask) ; // // /** // * Returns a list of all jobs known to the job manager that belong to the given family. // */ // List Select(Object family) ; // // /** // * Returns a list of all jobs known to the job manager that belong to the given // * family and are in one of the provided states. // */ // List Select(Object family, int stateMask) ; /** * Validates that the given scheduling rule obeys the constraints of * scheduling rules as described in the ISchedulingRule */ void ValidateRule(ISchedulingRule::Pointer rule); }; } #endif /* _BERRY_TEMPLATE_H */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobQueue.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobQueue.h index 7013fa3444..333e6cc510 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobQueue.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryJobQueue.h @@ -1,107 +1,107 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _BERRY_JOBQUEUE_H #define _BERRY_JOBQUEUE_H #include "berryInternalJob.h" -#include "../berryJob.h" +#include "berryJob.h" #include #include namespace berry { /** * A linked list based priority queue. Either the elements in the queue must * implement Comparable, or a Comparator must be provided. */ struct BERRY_JOBS JobQueue: public Object { private: /** * The dummy entry sits between the head and the tail of the queue. * dummy.previous() is the head, and dummy.next() is the tail. */ InternalJob::Pointer dummy; /** * If true, conflicting jobs will be allowed to overtake others in the * queue that have lower priority. If false, higher priority jumps can only * move up the queue by overtaking jobs that they don't conflict with. */ bool m_allowConflictOvertaking; /** * Returns whether the new entry to overtake the existing queue entry. * @param newEntry The entry to be added to the queue * @param queueEntry The existing queue entry */ bool CanOvertake(InternalJob::Pointer newEntry, InternalJob::Pointer queueEntry); public: /** * Create a new job queue. */ JobQueue(bool m_allowConflictOvertaking); /** * remove all elements */ void Clear(); /** * Return and remove the element with highest priority, or null if empty. */ InternalJob::Pointer Dequeue(); /** * Adds an item to the queue */ void Enqueue(InternalJob::Pointer newEntry); /** * Removes the given element from the queue. */ void Remove(InternalJob::Pointer jobToRemove); /** * The given object has changed priority. Reshuffle the heap until it is * valid. */ void Resort(InternalJob::Pointer entry); /** * Returns true if the queue is empty, and false otherwise. */ bool IsEmpty(); /** * Return greatest element without removing it, or null if empty */ InternalJob::Pointer Peek(); }; } #endif /* _BERRY_JOBQUEUE_H */ diff --git a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorkerPool.h b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorkerPool.h index ee23a38d09..918336eaa3 100644 --- a/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorkerPool.h +++ b/BlueBerry/Bundles/org.blueberry.core.jobs/src/internal/berryWorkerPool.h @@ -1,147 +1,147 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _BERRY_WORKERPOOL_H #define _BERRY_WORKERPOOL_H #include #include "berryWorker.h" #include "berryInternalJob.h" -#include "../berryJobExceptions.h" +#include "berryJobExceptions.h" #include #include #include #include namespace berry { struct JobManager; class BERRY_JOBS WorkerPool: public Object, public Poco::SynchronizedObject { friend struct JobManager; public: berryObjectMacro(WorkerPool) WorkerPool(JobManager* myManager); /** * Signals the death of a worker thread. Note that this method can be called under * OutOfMemoryError conditions and thus must be paranoid about allocating objects. */ void EndWorker(Worker::Pointer sptr_worker); /** * Signals the end of a job. Note that this method can be called under * OutOfMemoryError conditions and thus must be paranoid about allocating objects. */ void EndJob(InternalJob::Pointer job, IStatus::Pointer result) ; /** * Returns a new job to run. Returns null if the thread should die. */ InternalJob::Pointer StartJob(Worker* worker); protected: /** * Notification that a job has been added to the queue. Wake a worker, * creating a new worker if necessary. The provided job may be null. */ void JobQueued(); void Shutdown(); private: void Add(Worker::Pointer worker); /** impossible to have less than zero busy threads */ void DecrementBusyThreads(); /** impossible to have more busy threads than there are threads */ void IncrementBusyThreads(); /** * Remove a worker thread from our list. * @return true if a worker was removed, and false otherwise. */ bool Remove(Worker::Pointer worker); /** * Sleep for the given duration or until woken. */ void Sleep(long duration); static const long BEST_BEFORE; /** * There will always be at least MIN_THREADS workers in the pool. */ static const int MIN_THREADS; /** * Mutex (mutual exclusion) is a synchronization mechanism used to control access to a shared resource in * a concurrent (multithreaded) scenario. */ Poco::Mutex m_mutexOne; // // /** // * Records whether new worker threads should be daemon threads. // */ // // bool m_isDaemon; // JobManager* m_ptrManager; // int m_numThreads; /** * The number of threads that are currently sleeping */ int m_sleepingThreads; /** * The living set of workers in this pool. */ std::vector m_threads; /** * The number of workers in the threads array */ int m_busyThreads; /** * The default context class loader to use when creating worker threads. */ // const ClassLoader defaultContextLoader; }; } #endif /* _BERRY_WORKERPOOL_H */ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryAbstractPreferencesStorage.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryAbstractPreferencesStorage.h index d9dd4ad2b6..a348b6345f 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryAbstractPreferencesStorage.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryAbstractPreferencesStorage.h @@ -1,64 +1,64 @@ #ifndef BERRYABSTRACTPREFERENCESSTORAGE_H_ #define BERRYABSTRACTPREFERENCESSTORAGE_H_ #include -#include "../berryIPreferences.h" +#include "berryIPreferences.h" #include "Poco/File.h" namespace berry { /// /// Interface to flush Preferences. /// class BERRY_RUNTIME AbstractPreferencesStorage : public Object { public: berryObjectMacro(berry::AbstractPreferencesStorage) /// /// Saves the path, sets the root initially to 0. /// In subclasses try to read data from file here. /// AbstractPreferencesStorage(const Poco::File& _File); /// /// Pure virtual (abstract class) /// virtual ~AbstractPreferencesStorage(); /// /// Flushes the given (or all) prefs persistently /// virtual void Flush(IPreferences* prefs) throw(Poco::Exception, BackingStoreException) = 0; /// /// Returns the root prefs /// virtual IPreferences::Pointer GetRoot() const; /// /// Returns the path of the file /// virtual const Poco::File& GetFile() const; /// /// Sets the file /// virtual void SetFile(const Poco::File& f); protected: /// /// Path to the file where the data is stored /// Poco::File m_File; /// /// Pointer to the root Preferences /// IPreferences::Pointer m_Root; }; } #endif /* BERRYABSTRACTPREFERENCESSTORAGE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryAdapterService.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryAdapterService.h index 4f150142a7..3566161db4 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryAdapterService.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryAdapterService.h @@ -1,234 +1,234 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYADAPTERMANAGER_H_ #define BERRYADAPTERMANAGER_H_ #include -#include "../berryIAdapterManager.h" -#include "../berryIAdapterFactory.h" +#include "berryIAdapterManager.h" +#include "berryIAdapterFactory.h" #include #include #include #include #include namespace berry { /** * This class is the standard implementation of IAdapterManager. It provides * fast lookup of property values with the following semantics: *
    *
  • At most one factory will be invoked per property lookup *
  • If multiple installed factories provide the same adapter, only the first found in * the search order will be invoked. *
  • The search order from a class with the definition
    * class X extends Y implements A, B
    is as follows: *
  • the target's class: X *
  • X's superclasses in order to Object *
  • a breadth-first traversal of the target class's interfaces in the order returned by * getInterfaces (in the example, A and its superinterfaces then B and its * superinterfaces) *
* * @see IAdapterFactory * @see IAdapterManager */ class AdapterService : public Service, public IAdapterManager { /** * Cache of adapters for a given adaptable class. Maps String -> Map * (adaptable class name -> (adapter class name -> factory instance)) * Thread safety note: The outer map is synchronized using a synchronized * map wrapper class. The inner map is not synchronized, but it is immutable * so synchronization is not necessary. */ private: std::map > adapterLookup; /** * Cache of classes for a given type name. Avoids too many loadClass calls. * (factory -> (type name -> Class)). * Thread safety note: Since this structure is a nested hash map, and both * the inner and outer maps are mutable, access to this entire structure is * controlled by the classLookupLock field. Note the field can still be * nulled concurrently without holding the lock. */ std::map > classLookup; /** * The lock object controlling access to the classLookup data structure. */ //const Object classLookupLock = new Object(); /** * Cache of class lookup order (Class -> Class[]). This avoids having to compute often, and * provides clients with quick lookup for instanceOf checks based on type name. * Thread safety note: The map is synchronized using a synchronized * map wrapper class. The arrays within the map are immutable. */ //std::map<> classSearchOrderLookup; /** * Map of factories, keyed by String, fully qualified class name of * the adaptable class that the factory provides adapters for. Value is a List * of IAdapterFactory. */ Poco::HashMap factories; std::list lazyFactoryProviders; public: bool IsA(const std::type_info& type) const; public: const std::type_info& GetType() const; public: static AdapterManager GetDefault(); /** * Private constructor to block instance creation. */ private: AdapterManager(); /** * Given a type name, add all of the factories that respond to those types into * the given table. Each entry will be keyed by the adapter class name (supplied in * IAdapterFactory.getAdapterList). */ private: void AddFactoriesFor(const std::string& typeName, std::map& table); private: void CacheClassLookup(IAdapterFactory* factory, const std::type_info& clazz); private: void* /*Class*/ CachedClassForName(IAdapterFactory* factory, const std::string& typeName); /** * Returns the class with the given fully qualified name, or null * if that class does not exist or belongs to a plug-in that has not * yet been loaded. */ private: void* /*Class*/ ClassForName(IAdapterFactory* factory, const std::string& typeName); /* (non-Javadoc) * @see org.blueberry.core.runtime.IAdapterManager#getAdapterTypes(java.lang.Class) */ public: void ComputeAdapterTypes(std::vector& types, const std::type_info& adaptable); /** * Computes the adapters that the provided class can adapt to, along * with the factory object that can perform that transformation. Returns * a table of adapter class name to factory object. * @param adaptable */ private: void GetFactories(std::map table, const std::type_info& adaptable); //public: Class[] computeClassOrder(Class adaptable); /** * Builds and returns a table of adapters for the given adaptable type. * The table is keyed by adapter class name. The * value is the sole factory that defines that adapter. Note that * if multiple adapters technically define the same property, only the * first found in the search order is considered. * * Note that it is important to maintain a consistent class and interface * lookup order. See the class comment for more details. */ //private: void computeClassOrder(Class adaptable, Collection classes); //private: void computeInterfaceOrder(Class[] interfaces, Collection classes, Set seen); /** * Flushes the cache of adapter search paths. This is generally required whenever an * adapter is added or removed. *

* It is likely easier to just toss the whole cache rather than trying to be smart * and remove only those entries affected. *

*/ public: void FlushLookup(); /* (non-Javadoc) * @see org.blueberry.core.runtime.IAdapterManager#getAdapter(java.lang.Object, java.lang.Class) */ public: ExpressionVariable::Ptr GetAdapter(ExpressionVariable::Ptr adaptable, const std::type_info& adapterType); /* (non-Javadoc) * @see org.blueberry.core.runtime.IAdapterManager#getAdapter(java.lang.Object, java.lang.Class) */ public: ExpressionVariable::Ptr GetAdapter(ExpressionVariable::Ptr adaptable, const std::string& adapterType); /** * Returns an adapter of the given type for the provided adapter. * @param adaptable the object to adapt * @param adapterType the type to adapt the object to * @param force true if the plug-in providing the * factory should be activated if necessary. false * if no plugin activations are desired. */ private: ExpressionVariable::Ptr GetAdapter(ExpressionVariable::Ptr adaptable, const std::string& adapterType, bool force); public: bool HasAdapter(ExpressionVariable::Ptr adaptable, const std::string& adapterTypeName); /* (non-Javadoc) * @see org.blueberry.core.runtime.IAdapterManager#queryAdapter(java.lang.Object, java.lang.String) */ public: int QueryAdapter(ExpressionVariable::Ptr adaptable, const std::string& adapterTypeName); /* (non-Javadoc) * @see org.blueberry.core.runtime.IAdapterManager#loadAdapter(java.lang.Object, java.lang.String) */ public: ExpressionVariable::Ptr LoadAdapter(ExpressionVariable::Ptr adaptable, const std::string& adapterTypeName); /* * @see IAdapterManager#registerAdapters */ public: void RegisterAdapters(IAdapterFactory* factory, const std::type_info& adaptable); /* * @see IAdapterManager#registerAdapters */ public: void RegisterFactory(IAdapterFactory* factory, const std::string& adaptableType); /* * @see IAdapterManager#unregisterAdapters */ public: void UnregisterAdapters(IAdapterFactory* factory); /* * @see IAdapterManager#unregisterAdapters */ public: void UnregisterAdapters(IAdapterFactory* factory, const std::type_info& adaptable); /* * Shuts down the adapter manager by removing all factories * and removing the registry change listener. Should only be * invoked during platform shutdown. */ public: void UnregisterAllAdapters(); public: void RegisterLazyFactoryProvider(IAdapterManagerProvider* factoryProvider); public: bool UnregisterLazyFactoryProvider(IAdapterManagerProvider* factoryProvider); public: Poco::HashMap<>& GetFactories(); }; } // namespace berry #endif /*BERRYADAPTERMANAGER_H_*/ 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 fd52f762c9..cd2daa9f80 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferences.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferences.h @@ -1,327 +1,327 @@ #ifndef BERRYPREFERENCES_H_ #define BERRYPREFERENCES_H_ #include -#include "../berryIBerryPreferences.h" +#include "berryIBerryPreferences.h" #include #include #include #include #include "Poco/Mutex.h" namespace berry { class AbstractPreferencesStorage; /// /// Implementation of the OSGI Preferences Interface. /// Wraps a DOMNode. /// class BERRY_RUNTIME Preferences: public IBerryPreferences { public: /// /// For use with berry::SmartPtr /// berryObjectMacro(berry::Preferences) /// /// Maps a string key to a string value /// typedef std::map PropertyMap; /// /// The list of Child nodes /// typedef std::vector 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 std::string& _Name , Preferences* _Parent , AbstractPreferencesStorage* _Storage); /// /// Nothing to do here /// virtual ~Preferences(); /// /// Prints out the absolute path of the preference node. /// std::string ToString() const; /// /// Returns if this node and his silblings have to be rewritten persistently /// bool IsDirty() const; /// /// Returns if this node is removed /// bool IsRemoved() const; /// /// Returns if this node has property with a specific key /// bool Has(std::string key) const; /// /// Returns true if the absolute paths are the same /// bool Equals(const Preferences* rhs) const; /// /// 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 /// ChildrenList GetChildren() const; //# Begin of IPreferences methods /// /// \see IPreferences::AbsolutePath() /// virtual std::string AbsolutePath() const; /// /// \see IPreferences::ChildrenNames() /// virtual std::vector ChildrenNames() const throw(Poco::Exception, BackingStoreException); /// /// \see IPreferences::ChildrenNames() /// virtual AbstractPreferencesStorage* GetStorage() const; /// /// \see IPreferences::Clear() /// virtual void Clear() throw(Poco::Exception, BackingStoreException); /// /// \see IPreferences::Flush() /// virtual void Flush() throw(Poco::Exception, BackingStoreException); /// /// \see IPreferences::Get() /// virtual std::string Get(std::string key, std::string def) const; /// /// \see IPreferences::GetBool() /// virtual bool GetBool(std::string key, bool def) const; /// /// \see IPreferences::GetByteArray() /// virtual std::string GetByteArray(std::string key, std::string def) const; /// /// \see IPreferences::GetDouble() /// virtual double GetDouble(std::string key, double def) const; /// /// \see IPreferences::GetFloat() /// virtual float GetFloat(std::string key, float def) const; /// /// \see IPreferences::GetInt() /// virtual int GetInt(std::string key, int def) const; /// /// \see IPreferences::GetLong() /// virtual long GetLong(std::string key, long def) const; /// /// \see IPreferences::Keys() /// std::vector Keys() const throw(Poco::Exception, BackingStoreException); /// /// \see IPreferences::Name() /// virtual std::string Name() const; /// /// \see IPreferences::Node() /// virtual IPreferences::Pointer Node(std::string pathName); /// /// \see IPreferences::NodeExists() /// virtual bool NodeExists(std::string pathName) const throw(Poco::Exception, BackingStoreException); /// /// \see IPreferences::Parent() /// virtual IPreferences::Pointer Parent() const; /// /// \see IPreferences::Put() /// virtual void Put(std::string key, std::string value); /// /// \see IPreferences::PutByteArray() /// virtual void PutByteArray(std::string key, std::string value); /// /// \see IPreferences::PutBool() /// virtual void PutBool(std::string key, bool value); /// /// \see IPreferences::PutDouble() /// virtual void PutDouble(std::string key, double value); /// /// \see IPreferences::Sync() /// virtual void PutFloat(std::string key, float value); /// /// \see IPreferences::PutInt() /// virtual void PutInt(std::string key, int value); /// /// \see IPreferences::PutLong() /// virtual void PutLong(std::string key, long value); /// /// \see IPreferences::Remove() /// virtual void Remove(std::string key); /// /// \see IPreferences::RemoveNode() /// virtual void RemoveNode() throw(Poco::Exception, BackingStoreException); /// /// \see IPreferences::Sync() /// virtual void Sync() throw(Poco::Exception, BackingStoreException); //# End of IPreferences methods protected: /// /// Checks if this node is about to be removed. /// \throws IllegalStateException /// void AssertValid() const; /// /// Checks a path value for validity. /// \throws invalid_argument /// static void AssertPath(std::string pathName); /// /// Converts any value to a string (using stream operator "<<") /// template static std::string 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(); } /// /// Sets the dirty flag recursively on all child nodes. /// void SetDirty(bool _Dirty); /// /// Sets the removed flag recursively on all child nodes. /// void SetRemoved(bool _Removed); protected: /// /// Holds all Key/Value Pairs. /// std::map m_Properties; /// /// Holds all child nodes (explicit ownership). /// std::vector m_Children; /// /// Saves the absolute path of this node (calculated in the constructor) /// std::string m_Path; /// /// Saves the name of this node (set when read from backend) /// std::string m_Name; /// /// Saves the parent of this node /// Preferences* m_Parent; /// /// Saves the root of this tree /// Preferences* m_Root; /// /// 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). /// bool m_Removed; /// /// A storage to call the flush method. /// AbstractPreferencesStorage* m_Storage; /// /// A mutex to avoid concurrency crashes. Mutable because we need to use Mutex::lock() in const functions /// mutable Poco::Mutex m_Mutex; }; } namespace Base64 { /// /// Encode string to base64 (needed for writing byte arrays) /// std::string encode(const std::string &sString); /// /// Decode base64 to string (needed for reading byte arrays) /// std::string decode(const std::string &sString); }; /// /// Uses Preferences::ToString to print node information /// std::ostream& operator<<(std::ostream& os,const berry::Preferences& m); /// /// Uses Preferences::ToString to print node information /// std::ostream& operator<<(std::ostream& os,const berry::Preferences* m); #endif /* BERRYPREFERENCES_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferencesService.h b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferencesService.h index 3735ea24bb..f6618ce5b8 100644 --- a/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferencesService.h +++ b/BlueBerry/Bundles/org.blueberry.core.runtime/src/internal/berryPreferencesService.h @@ -1,103 +1,103 @@ #ifndef BERRYPREFERENCESSERVICE_H_ #define BERRYPREFERENCESSERVICE_H_ #include -#include "../berryIBerryPreferencesService.h" +#include "berryIBerryPreferencesService.h" #include "berryAbstractPreferencesStorage.h" #include #include #include namespace berry { /** * Implementation of the IPreferencesService Interface */ class BERRY_RUNTIME PreferencesService : public QObject, public IBerryPreferencesService { Q_OBJECT Q_INTERFACES(berry::IPreferencesService) public: berryObjectMacro(PreferencesService) //# From berry::Service virtual bool IsA(const std::type_info& type) const; virtual const std::type_info& GetType() const; /// /// Returns the default name for the preferences data file /// static std::string GetDefaultPreferencesFileName(); /// /// Returns the path to the directory where all preference data is stored. /// static std::string GetDefaultPreferencesDirPath(); /// /// Reads in all users for which preferences exist. /// PreferencesService(std::string _PreferencesDir=""); /// /// Nothing to do here so far. /// virtual ~PreferencesService(); /** * If no system preference file exists create a new AbstractPreferencesStorage. * \see IPreferencesService::GetSystemPreferences() */ virtual IPreferences::Pointer GetSystemPreferences(); /** * If no user preference file exists create a new AbstractPreferencesStorage. * \see IPreferencesService::GetUserPreferences() */ virtual IPreferences::Pointer GetUserPreferences(std::string name); /** * \see IPreferencesService::GetUsers() */ virtual std::vector GetUsers() const; /// /// \see IPreferencesService::ImportPreferences() /// virtual void ImportPreferences(Poco::File f, std::string name=""); /// /// \see IPreferencesService::ExportPreferences() /// virtual void ExportPreferences(Poco::File f, std::string name=""); /// /// flushes all preferences /// virtual void ShutDown(); protected: /// /// Helper func for ImportPreferences(). Imports all nodes of an IPreferences tree recursively /// void ImportNode( IPreferences::Pointer nodeToImport , IPreferences::Pointer rootOfOldPrefs ); /// /// Holds the directory where the preferences files will be stored /// std::string m_PreferencesDir; /// /// Maps all user names to their preference storage. /// std::map m_PreferencesStorages; /// /// A mutex to avoid concurrency crashes. Mutable because we need to use Mutex::lock() in const functions /// mutable Poco::Mutex m_Mutex; }; } // namespace berry #endif /*BERRYPREFERENCESSERVICE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/application/berryIApplication.h b/BlueBerry/Bundles/org.blueberry.osgi/src/application/berryIApplication.h index 1f8083b40b..2ccb11addb 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/application/berryIApplication.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/application/berryIApplication.h @@ -1,103 +1,103 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYIAPPLICATION_H_ #define BERRYIAPPLICATION_H_ #include -#include "../berryMacros.h" +#include "berryMacros.h" #include namespace berry { /** * Bootstrap type for an application. An IApplication represent executable * entry points into an application. An IApplication can be configured into * the Platform's org.blueberry.osgi.applications extension-point. * *

* Clients may implement this interface. *

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

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

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

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

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

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

*/ virtual void Stop() = 0; }; } Q_DECLARE_INTERFACE(berry::IApplication, "org.blueberry.IApplication") #endif /*BERRYIAPPLICATION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/application/berryStarter.cpp b/BlueBerry/Bundles/org.blueberry.osgi/src/application/berryStarter.cpp index 838b716a52..691211a2ee 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/application/berryStarter.cpp +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/application/berryStarter.cpp @@ -1,176 +1,176 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryLog.h" #include "berryStarter.h" -#include "../berryPlatform.h" +#include "berryPlatform.h" -#include "../internal/berryInternalPlatform.h" -#include "../service/berryIExtensionPointService.h" -#include "../service/berryIConfigurationElement.h" +#include "internal/berryInternalPlatform.h" +#include "service/berryIExtensionPointService.h" +#include "service/berryIConfigurationElement.h" #include "berryIApplication.h" #include #include namespace berry { const std::string Starter::XP_APPLICATIONS = "org.blueberry.osgi.applications"; int Starter::Run(int& argc, char** argv, Poco::Util::AbstractConfiguration* config) { // The CTK PluginFramework needs a QCoreApplication if (!qApp) { BERRY_FATAL << "No QCoreApplication instance found. You need to create one prior to calling Starter::Run()"; } InternalPlatform* platform = InternalPlatform::GetInstance(); int returnCode = 0; // startup the internal platform platform->Initialize(argc, argv, config); platform->Launch(); bool consoleLog = platform->ConsoleLog(); // run the application IExtensionPointService::Pointer service = platform->GetExtensionPointService(); if (service == 0) { platform->GetLogger()->log( Poco::Message( "Starter", "The extension point service could not be retrieved. This usually indicates that the BlueBerry OSGi plug-in could not be loaded.", Poco::Message::PRIO_FATAL)); std::unexpected(); returnCode = 1; } else { IConfigurationElement::vector extensions( service->GetConfigurationElementsFor(Starter::XP_APPLICATIONS)); IConfigurationElement::vector::iterator iter; for (iter = extensions.begin(); iter != extensions.end();) { if ((*iter)->GetName() != "application") iter = extensions.erase(iter); else ++iter; } std::string argApplication = Platform::GetConfiguration().getString( Platform::ARG_APPLICATION, ""); IApplication* app = 0; if (extensions.size() == 0) { BERRY_FATAL << "No extensions configured into extension-point '" << Starter::XP_APPLICATIONS << "' found. Aborting.\n"; returnCode = 0; } else if (extensions.size() == 1) { if (!argApplication.empty()) BERRY_INFO(consoleLog) << "One '" << Starter::XP_APPLICATIONS << "' extension found, ignoring " << Platform::ARG_APPLICATION << " argument.\n"; std::vector runs( extensions[0]->GetChildren("run")); app = runs.front()->CreateExecutableExtension ("class"); if (app == 0) { // support legacy BlueBerry extensions app = runs.front()->CreateExecutableExtension ("class", IApplication::GetManifestName()); } } else { if (argApplication.empty()) { BERRY_WARN << "You must provide an application id via \"" << Platform::ARG_APPLICATION << "=\""; BERRY_INFO << "Possible application ids are:"; for (iter = extensions.begin(); iter != extensions.end(); ++iter) { std::string appid; if ((*iter)->GetAttribute("id", appid) && !appid.empty()) { BERRY_INFO << appid; } } returnCode = 0; } else { for (iter = extensions.begin(); iter != extensions.end(); ++iter) { BERRY_INFO(consoleLog) << "Checking applications extension from: " << (*iter)->GetContributor() << std::endl; std::string appid; if ((*iter)->GetAttribute("id", appid)) { BERRY_INFO(consoleLog) << "Found id: " << appid << std::endl; if (appid.size() > 0 && appid == argApplication) { std::vector runs( (*iter)->GetChildren("run")); app = runs.front()->CreateExecutableExtension ("class"); if (app == 0) { // try legacy BlueBerry extensions app = runs.front()->CreateExecutableExtension ( "class", IApplication::GetManifestName()); } break; } } else throw CoreException("missing attribute", "id"); } } } if (app == 0) { BERRY_ERROR << "Could not create executable application extension for id: " << argApplication << std::endl; returnCode = 1; } else { returnCode = app->Start(); } } platform->Shutdown(); return returnCode; } } diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/application/berryStarter.h b/BlueBerry/Bundles/org.blueberry.osgi/src/application/berryStarter.h index 519cb8f3d1..839552401d 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/application/berryStarter.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/application/berryStarter.h @@ -1,41 +1,41 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYSTARTER_H_ #define BERRYSTARTER_H_ #include -#include "../berryPlatform.h" +#include "berryPlatform.h" #include namespace berry { class BERRY_OSGI Starter { public: static const std::string XP_APPLICATIONS; static int Run(int& argc, char** argv, Poco::Util::AbstractConfiguration* config = 0); }; } #endif /*BERRYSTARTER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryBundleEvent.cpp b/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryBundleEvent.cpp index 1ded7ed193..b3131f4278 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryBundleEvent.cpp +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryBundleEvent.cpp @@ -1,66 +1,66 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryBundleEvent.h" -#include "../berryIBundle.h" +#include "berryIBundle.h" namespace berry { BundleEvent::BundleEvent(IBundle::Pointer bundle, EventKind what) : m_Bundle(bundle), m_What(what) { } BundleEvent::BundleEvent(IBundle* bundle, EventKind what) : m_Bundle(bundle), m_What(what) { } BundleEvent::BundleEvent(const BundleEvent& event) : m_Bundle(event.GetBundle()), m_What(event.What()) { } BundleEvent::~BundleEvent() { } BundleEvent& BundleEvent::operator= (const BundleEvent& event) { m_Bundle = event.GetBundle(); m_What = event.What(); return *this; } IBundle::ConstPointer BundleEvent::GetBundle() const { return m_Bundle; } BundleEvent::EventKind BundleEvent::What() const { return m_What; } } diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryBundleEvent.h b/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryBundleEvent.h index e662eac89a..75195cee00 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryBundleEvent.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryBundleEvent.h @@ -1,57 +1,57 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYBUNDLEEVENT_H_ #define BERRYBUNDLEEVENT_H_ #include -#include "../berrySmartPointer.h" +#include "berrySmartPointer.h" namespace berry { struct IBundle; class BERRY_OSGI BundleEvent { public: enum EventKind { EV_BUNDLE_INSTALLED, EV_BUNDLE_LOADED, EV_BUNDLE_RESOLVING, EV_BUNDLE_RESOLVED, EV_BUNDLE_STARTING, EV_BUNDLE_STARTED, EV_BUNDLE_STOPPING, EV_BUNDLE_STOPPED, EV_BUNDLE_UNINSTALLING, EV_BUNDLE_UNINSTALLED, EV_BUNDLE_UNLOADED }; BundleEvent(SmartPointer bundle, EventKind what); BundleEvent(IBundle* bundle, EventKind what); BundleEvent(const BundleEvent& event); virtual ~BundleEvent(); BundleEvent& operator= (const BundleEvent& event); SmartPointer GetBundle() const; EventKind What() const; private: SmartPointer m_Bundle; EventKind m_What; }; } // namespace berry #endif /*BERRYBUNDLEEVENT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryBundleEvents.h b/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryBundleEvents.h index 400ac5f89a..f15077bbac 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryBundleEvents.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryBundleEvents.h @@ -1,46 +1,46 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYBUNDLEEVENTS_H_ #define BERRYBUNDLEEVENTS_H_ #include -#include "../berryMessage.h" +#include "berryMessage.h" #include "berryBundleEvent.h" namespace berry { struct BERRY_OSGI BundleEvents { Message1 bundleInstalled; Message1 bundleLoaded; Message1 bundleResolved; Message1 bundleResolving; Message1 bundleStarted; Message1 bundleStarting; Message1 bundleStopped; Message1 bundleStopping; Message1 bundleUninstalled; Message1 bundleUninstalling; Message1 bundleUnloaded; }; } // namespace berry #endif /*BERRYBUNDLEEVENTS_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryPlatformEvent.h b/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryPlatformEvent.h index f3f3b0c7e7..e2b89bc4d9 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryPlatformEvent.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryPlatformEvent.h @@ -1,62 +1,62 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPLATFORMEVENT_H_ #define BERRYPLATFORMEVENT_H_ #include -#include "../berryIBundle.h" +#include "berryIBundle.h" #include "Poco/Any.h" #include namespace berry { class BERRY_OSGI PlatformEvent { public: enum EventKind { EV_PLATFORM_STARTED, EV_PLATFORM_ERROR, EV_PLATFORM_WARNING, EV_LOGGED}; PlatformEvent(EventKind what); PlatformEvent(EventKind what, IBundle::Pointer bundle); PlatformEvent(EventKind what, IBundle::Pointer bundle, std::exception exc); EventKind What() const; const std::exception* GetException() const; IBundle::Pointer GetBundle(); void SetData(Poco::Any* data); Poco::Any* GetData(); const Poco::Any* GetData() const; private: IBundle::Pointer m_Bundle; std::exception m_Exception; EventKind m_What; bool m_HasException; Poco::Any* m_Data; }; } #endif /*BERRYPLATFORMEVENT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryPlatformEvents.h b/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryPlatformEvents.h index 4103a7671a..bb835be888 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryPlatformEvents.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/event/berryPlatformEvents.h @@ -1,42 +1,42 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPLATFORMEVENTS_H_ #define BERRYPLATFORMEVENTS_H_ #include -#include "../berryMessage.h" +#include "berryMessage.h" #include "berryPlatformEvent.h" namespace berry { struct BERRY_OSGI PlatformEvents { typedef Message1 EventType; EventType platformStarted; EventType platformError; EventType platformWarning; EventType logged; }; } #endif /*BERRYPLATFORMEVENTS_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundle.cpp b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundle.cpp index 41f4b08f05..539b6ee400 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundle.cpp +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundle.cpp @@ -1,319 +1,319 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryLog.h" #include "Poco/Exception.h" #include "berryBundle.h" #include "berryInternalPlatform.h" -#include "../berryBundleLoader.h" +#include "berryBundleLoader.h" #include "berryBundleManifest.h" -#include "../berryIBundleActivator.h" -#include "../berryIBundleContext.h" -#include "../berryPlatformException.h" +#include "berryIBundleActivator.h" +#include "berryIBundleContext.h" +#include "berryPlatformException.h" #include #include namespace berry { Bundle::Bundle(BundleLoader& loader, IBundleStorage::Pointer storage, bool initialize) : m_BundleLoader(loader) { { Poco::Mutex::ScopedLock lock(m_Mutex); m_Storage = storage; } if (initialize) { init(); } } void Bundle::init() { Poco::Mutex::ScopedLock lock(m_Mutex); try { this->LoadManifest(); m_State = BUNDLE_INSTALLED; } catch (Poco::FileException& exc) { BERRY_ERROR << "Exception: " << exc.displayText() << std::endl; m_State = BUNDLE_UNINSTALLED; } } Bundle::~Bundle() { } bool Bundle::operator==(const Object* o) const { if (const IBundle* bundle = dynamic_cast(o)) return this->GetSymbolicName() == bundle->GetSymbolicName(); return false; } IBundleActivator* Bundle::GetActivator() const { Poco::Mutex::ScopedLock lock(m_Mutex); if (m_State == BUNDLE_ACTIVE) return m_Activator; return 0; } const std::string& Bundle::GetActivatorClass() const { return m_Manifest->GetActivatorClass(); } const std::string& Bundle::GetActivatorLibrary() const { return m_Manifest->GetActivatorLibrary(); } const std::string& Bundle::GetCopyright() const { return m_Manifest->GetCopyright(); } const std::string& Bundle::GetVendor() const { return m_Manifest->GetVendor(); } IBundleManifest::ActivationPolicy Bundle::GetActivationPolicy() const { return m_Manifest->GetActivationPolicy(); } std::istream* Bundle::GetLocalizedResource(const std::string& name) const { return m_Storage->GetResource(name); } std::istream* Bundle::GetResource(const std::string& name) const { return m_Storage->GetResource(name); } bool Bundle::IsActive() const { return m_State == BUNDLE_ACTIVE; } bool Bundle::IsResolved() const { return m_State == BUNDLE_RESOLVED || m_State == BUNDLE_STARTING || m_State == BUNDLE_ACTIVE || m_State == BUNDLE_STOPPING; } bool Bundle::IsStarted() const { return m_State == BUNDLE_STARTING || m_State == BUNDLE_ACTIVE || m_State == BUNDLE_STOPPING; } bool Bundle::IsSystemBundle() const { return m_Manifest->IsSystemBundle(); } const IBundleManifest& Bundle::GetManifest() const { return *m_Manifest; } const std::string& Bundle::GetName() const { return m_Manifest->GetName(); } const Poco::Path Bundle::GetPath() const { return m_Storage->GetPath(); } IBundleStorage& Bundle::GetStorage() { return *m_Storage; } // const Version& GetVersion() const; const IBundleManifest::Dependencies& Bundle::GetRequiredBundles() const { return m_Manifest->GetRequiredBundles(); } void Bundle::Resolve() { if (m_State == BUNDLE_INSTALLED) { ctkPluginContext* context = InternalPlatform::GetInstance()->GetCTKPluginFrameworkContext(); //const BundleManifest::Dependencies& dependencies =; IBundleManifest::Dependencies::const_iterator iter; for (iter = this->GetRequiredBundles().begin(); iter != this->GetRequiredBundles().end(); ++iter) { //BERRY_INFO << "Checking dependency:" << iter->symbolicName << ";\n"; IBundle::Pointer bundle = m_BundleLoader.FindBundle(iter->symbolicName); if (bundle.IsNull()) { // Check if we have a CTK Plugin dependency bool resolved = false; if (context) { QString symbolicName = QString::fromStdString(iter->symbolicName); foreach (QSharedPointer plugin, context->getPlugins()) { if (plugin->getSymbolicName() == symbolicName) { resolved = true; break; } } } if (!resolved) { throw BundleResolveException("The bundle " + this->GetSymbolicName() + " depends on missing bundle:", iter->symbolicName); } } else if (!bundle->IsResolved()) { bundle->Resolve(); } } m_State = BUNDLE_RESOLVED; } } void Bundle::Start() { if (m_State == BUNDLE_RESOLVED) { Poco::Mutex::ScopedLock lock(m_Mutex); m_State = BUNDLE_STARTING; // BundleEvent starting(this, BundleEvent::EV_BUNDLE_STARTING); // this->GetEvents().bundleStarting(this, starting); BERRY_INFO(InternalPlatform::GetInstance()->ConsoleLog()) << "Bundle " << this->GetSymbolicName() << " is starting"; m_Activator->Start(m_BundleLoader.GetContextForBundle(IBundle::Pointer(this))); m_State = BUNDLE_ACTIVE; // BundleEvent started(this, BundleEvent::EV_BUNDLE_STARTED); // this->GetEvents().bundleStarted(this, started); // BERRY_INFO << "Bundle " << this->GetSymbolicName() << " is active"; } else { throw BundleStateException("Bundle " + this->GetSymbolicName() + " could not be started, because it is not in state RESOLVED."); } } void Bundle::Stop() { throw Poco::NotImplementedException("Bundle::Stop() not implemented yet"); } Bundle::State Bundle::GetState() const { return m_State; } std::string Bundle::GetStateString() const { switch (this->GetState()) { case BUNDLE_INSTALLED: return "Installed"; case BUNDLE_UNINSTALLED: return "Uninstalled"; case BUNDLE_RESOLVED: return "Resolved"; case BUNDLE_STARTING: return "Starting"; case BUNDLE_ACTIVE: return "Active"; case BUNDLE_STOPPING: return "Stopping"; default: throw BundleStateException("The bundle is not in a valid state"); } } BundleEvents& Bundle::GetEvents() { return m_BundleLoader.GetEvents(); } const std::string& Bundle::GetSymbolicName() const { return m_Manifest->GetSymbolicName(); } void Bundle::LoadManifest() { std::istream* istr = m_Storage->GetResource("META-INF/MANIFEST.MF"); if (!istr) throw Poco::FileNotFoundException("Could not load META-INF/MANIFEST.MF from " + m_Storage->GetPath().toString()); m_Manifest = new BundleManifest(istr); delete istr; } void Bundle::SetActivator(IBundleActivator* activator) { Poco::Mutex::ScopedLock lock(m_Mutex); m_Activator = activator; } } diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundle.h b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundle.h index a9c3ee0f5c..74bf84078d 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundle.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundle.h @@ -1,99 +1,99 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYBUNDLE_H_ #define BERRYBUNDLE_H_ #include "Poco/Path.h" #include "Poco/Mutex.h" -#include "../berryIBundle.h" -#include "../berryIBundleStorage.h" +#include "berryIBundle.h" +#include "berryIBundleStorage.h" namespace berry { class BundleLoader; class Bundle : public IBundle { public: berryObjectMacro(Bundle); Bundle(BundleLoader& loader, IBundleStorage::Pointer storage, bool init = true); ~Bundle(); void init(); IBundleActivator* GetActivator() const; const std::string& GetActivatorClass() const; const std::string& GetActivatorLibrary() const; const std::string& GetCopyright() const; const std::string& GetVendor() const; IBundleManifest::ActivationPolicy GetActivationPolicy() const; std::istream* GetLocalizedResource(const std::string& name) const; std::istream* GetResource(const std::string& name) const; bool IsActive() const; bool IsResolved() const; bool IsStarted() const; bool IsSystemBundle() const; const IBundleManifest& GetManifest() const; const std::string& GetName() const; const Poco::Path GetPath() const; IBundleStorage& GetStorage(); // const Version& GetVersion() const; const IBundleManifest::Dependencies& GetRequiredBundles() const; void Resolve(); void Start(); void Stop(); State GetState() const; std::string GetStateString() const; BundleEvents& GetEvents(); const std::string& GetSymbolicName() const; virtual void LoadManifest(); void SetActivator(IBundleActivator* activator); bool operator==(const Object* o) const; protected: IBundleManifest::Pointer m_Manifest; IBundleStorage::Pointer m_Storage; BundleLoader& m_BundleLoader; IBundleActivator* m_Activator; State m_State; mutable Poco::Mutex m_Mutex; }; } // namespace berry #endif /*BERRYBUNDLE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleContext.cpp b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleContext.cpp index c0b00f580f..97265faa87 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleContext.cpp +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleContext.cpp @@ -1,111 +1,111 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryBundleContext.h" #include "berryBundle.h" -#include "../berryBundleLoader.h" +#include "berryBundleLoader.h" namespace berry { BundleContext::BundleContext(BundleLoader& loader, IBundle::Pointer bundle, const Poco::Path& persistencyDir) : m_BundleLoader(loader),m_Bundle(bundle), m_PersistencyDir(persistencyDir) { } BundleContext::~BundleContext() { } bool BundleContext::operator==(const Object* o) const { if (const IBundleContext* context = dynamic_cast(o)) return this->GetThisBundle() == context->GetThisBundle(); return false; } void BundleContext::RegisterService(const std::string& id, Service::Pointer service) const { Platform::GetServiceRegistry().RegisterService(id, service); } IBundleContext::Pointer BundleContext::GetContextForBundle(IBundle::ConstPointer bundle) const { return m_BundleLoader.GetContextForBundle(bundle); } BundleEvents& BundleContext::GetEvents() const { return m_BundleLoader.GetEvents(); } IBundle::ConstPointer BundleContext::FindBundle(const std::string& name) const { return m_BundleLoader.FindBundle(name); } void BundleContext::ListBundles(std::vector& bundles) const { for (BundleLoader::BundleMap::const_iterator i = m_BundleLoader.m_BundleMap.begin(); i != m_BundleLoader.m_BundleMap.end(); ++i) { if (i->second.m_Bundle) { bundles.push_back(i->second.m_Bundle); } } } Poco::Logger& BundleContext::GetLogger() const { return m_BundleLoader.GetLogger(); } Poco::Path BundleContext::GetPathForLibrary(const std::string& libraryName) const { return m_BundleLoader.GetPathForLibrary(libraryName); } Poco::Path BundleContext::GetPersistentDirectory() const { return m_PersistencyDir; } IBundle::Pointer BundleContext::GetThisBundle() const { return m_Bundle; } void BundleContext::InitPersistency(const std::string& /*persistencyPath*/) { } } diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleContext.h b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleContext.h index d5a286c85d..4004a3424c 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleContext.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleContext.h @@ -1,72 +1,72 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYBUNDLECONTEXT_H_ #define BERRYBUNDLECONTEXT_H_ -#include "../berryIBundleContext.h" -#include "../berryBundleLoader.h" +#include "berryIBundleContext.h" +#include "berryBundleLoader.h" namespace berry { class BundleContext : public IBundleContext { public: berryObjectMacro(BundleContext); BundleContext(BundleLoader& loader, SmartPointer bundle, const Poco::Path& persistencyDir); ~BundleContext(); IBundleContext::Pointer GetContextForBundle(SmartPointer bundle) const; BundleEvents& GetEvents() const; SmartPointer FindBundle(const std::string& name) const; void ListBundles(std::vector >& bundles) const; Poco::Logger& GetLogger() const; // Logger& GetLogger() const; Poco::Path GetPathForLibrary(const std::string& libraryName) const; Poco::Path GetPersistentDirectory() const; void RegisterService(const std::string& id, Service::Pointer service) const; SmartPointer GetThisBundle() const; void InitPersistency(const std::string& persistencyPath); //static std::string GetLoggerName(const Bundle* bundle); bool operator==(const Object* o) const; private: BundleLoader& m_BundleLoader; SmartPointer m_Bundle; const Poco::Path m_PersistencyDir; }; } // namespace berry #endif /*BERRYBUNDLECONTEXT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleDirectory.h b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleDirectory.h index 6994fee8ca..71f72e1010 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleDirectory.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleDirectory.h @@ -1,55 +1,55 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYBUNDLEDIRECTORY_H_ #define BERRYBUNDLEDIRECTORY_H_ #include -#include "../berryIBundleStorage.h" +#include "berryIBundleStorage.h" namespace berry { using namespace Poco; class BundleDirectory : public IBundleStorage { private: Path m_RootPath; public: berryObjectMacro(BundleDirectory); BundleDirectory(const Path& path); virtual ~BundleDirectory(); std::istream* GetResource(const std::string& path) const; void List(const std::string& path, std::vector& files, bool quiet = true) const; bool IsDirectory(const std::string& path) const; Path GetPath() const; Path BuildPath(const std::string& path) const; bool operator==(const Object* o) const; }; } // namespace berry #endif /*BERRYBUNDLEDIRECTORY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleManifest.h b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleManifest.h index f46a0c6421..accf77f8aa 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleManifest.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryBundleManifest.h @@ -1,75 +1,75 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYBUNDLEMANIFEST_H_ #define BERRYBUNDLEMANIFEST_H_ -#include "../berryIBundleManifest.h" +#include "berryIBundleManifest.h" namespace berry { class BundleManifest : public IBundleManifest { public: berryObjectMacro(BundleManifest); BundleManifest(std::istream* istr); ~BundleManifest(); const std::string& GetActivatorClass() const; const std::string& GetActivatorLibrary() const; const std::string& GetCopyright() const; ActivationPolicy GetActivationPolicy() const; bool IsSystemBundle() const; const std::string& GetName() const; const IBundleManifest::Dependencies& GetRequiredBundles() const; const std::string& GetSymbolicName() const; const std::string& GetVendor() const; //const Version& GetVersion() const; bool operator==(const Object* o) const; private: const std::string POLICY_EAGER; const std::string POLICY_LAZY; void ParseActivator(const std::string& activator); void ParseManifest(std::istream* istr); void ParseRequiredBundles(const std::string& requiredBundles); IBundleManifest::Dependencies m_Dependencies; std::string m_ActivatorLibrary; std::string m_Activator; std::string m_Copyright; ActivationPolicy m_ActivationPolicy; std::string m_Name; std::string m_SymbolicName; std::string m_Vendor; std::string m_Version; std::string m_ManifestVersion; bool m_SystemBundle; std::string m_RequireBundle; }; } // namespace berry #endif /*BERRYBUNDLEMANIFEST_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryConfigurationElement.cpp b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryConfigurationElement.cpp index e2de3d55f9..c609d80ec5 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryConfigurationElement.cpp +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryConfigurationElement.cpp @@ -1,148 +1,148 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryConfigurationElement.h" #include "berryExtension.h" -#include "../berryBundleLoader.h" +#include "berryBundleLoader.h" #include #include #include namespace berry { ConfigurationElement::ConfigurationElement(BundleLoader* loader, Poco::XML::Node* config, std::string contributor, Extension::Pointer extension, const ConfigurationElement* parent) : m_ConfigurationNode(config), m_Parent(parent), m_Extension(extension) { IConfigurationElement::m_ClassLoader = loader; IConfigurationElement::m_Contributor = contributor; } bool ConfigurationElement::GetAttribute(const std::string& name, std::string& value) const { if (m_ConfigurationNode->hasAttributes()) { Poco::XML::NamedNodeMap* attributes = m_ConfigurationNode->attributes(); Poco::XML::Node* attr = attributes->getNamedItem(name); if (attr == 0) return false; value = attr->nodeValue(); attributes->release(); return true; } return false; } bool ConfigurationElement::GetBoolAttribute(const std::string& name, bool& value) const { std::string val; if (this->GetAttribute(name, val)) { Poco::toUpperInPlace(val); if (val == "1" || val == "TRUE") value = true; else value = false; return true; } return false; } const std::vector ConfigurationElement ::GetChildren() const { std::vector children; if (m_ConfigurationNode->hasChildNodes()) { Poco::XML::NodeList* ch = m_ConfigurationNode->childNodes(); for (unsigned long i = 0; i < ch->length(); ++i) { IConfigurationElement::Pointer xelem(new ConfigurationElement(IConfigurationElement::m_ClassLoader, ch->item(i), m_Contributor, m_Extension, this)); children.push_back(xelem); } ch->release(); } return children; } const std::vector ConfigurationElement ::GetChildren(const std::string& name) const { std::vector children; if (m_ConfigurationNode->hasChildNodes()) { Poco::XML::NodeList* ch = m_ConfigurationNode->childNodes(); for (unsigned long i = 0; i < ch->length(); ++i) { if (ch->item(i)->nodeName() == name) { IConfigurationElement::Pointer xelem(new ConfigurationElement(IConfigurationElement::m_ClassLoader, ch->item(i), m_Contributor, m_Extension, this)); children.push_back(xelem); } } ch->release(); } return children; } std::string ConfigurationElement::GetValue() const { return m_ConfigurationNode->nodeValue(); } std::string ConfigurationElement::GetName() const { return m_ConfigurationNode->nodeName(); } const IConfigurationElement* ConfigurationElement::GetParent() const { return m_Parent; } const std::string& ConfigurationElement::GetContributor() const { return m_Contributor; } const IExtension* ConfigurationElement::GetDeclaringExtension() const { return m_Extension.GetPointer(); } ConfigurationElement::~ConfigurationElement() { } } diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryConfigurationElement.h b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryConfigurationElement.h index ce91124d01..fdb536cf5a 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryConfigurationElement.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryConfigurationElement.h @@ -1,72 +1,72 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYEXTENSIONELEMENT_H_ #define BERRYEXTENSIONELEMENT_H_ -#include "../berryMacros.h" +#include "berryMacros.h" -#include "../berryBundleLoader.h" +#include "berryBundleLoader.h" #include "Poco/DOM/Node.h" -#include "../service/berryIConfigurationElement.h" +#include "service/berryIConfigurationElement.h" namespace berry { class Extension; class ConfigurationElement : public IConfigurationElement { public: berryObjectMacro(ConfigurationElement); ConfigurationElement(BundleLoader* loader, Poco::XML::Node* config, std::string contributor, SmartPointer extension, const ConfigurationElement* parent = 0); bool GetAttribute(const std::string& name, std::string& value) const; bool GetBoolAttribute(const std::string& name, bool& value) const; const std::vector GetChildren() const; const std::vector GetChildren(const std::string& name) const; std::string GetValue() const; std::string GetName() const; const IConfigurationElement* GetParent() const; const std::string& GetContributor() const; const IExtension* GetDeclaringExtension() const; ~ConfigurationElement(); private: Poco::XML::Node* m_ConfigurationNode; const ConfigurationElement* m_Parent; SmartPointer m_Extension; }; } // namespace berry #endif /*BERRYEXTENSIONELEMENT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryDefaultActivator.h b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryDefaultActivator.h index be4104e3cf..596b5f527a 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryDefaultActivator.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryDefaultActivator.h @@ -1,34 +1,34 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYDEFAULTACTIVATOR_H_ #define BERRYDEFAULTACTIVATOR_H_ -#include "../berryIBundleActivator.h" -#include "../berryIBundleContext.h" +#include "berryIBundleActivator.h" +#include "berryIBundleContext.h" namespace berry { class DefaultActivator : public IBundleActivator { void Start(IBundleContext::Pointer context); void Stop(IBundleContext::Pointer context); }; } #endif /*BERRYDEFAULTACTIVATOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtension.h b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtension.h index 6ae6ed3ef5..cf47362565 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtension.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtension.h @@ -1,124 +1,124 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYEXTENSION_H_ #define BERRYEXTENSION_H_ -#include "../service/berryIExtension.h" +#include "service/berryIExtension.h" #include "berryConfigurationElement.h" namespace berry { /** * An object which represents the user-defined extension in a * plug-in manifest. *

* This class may be instantiated, or further subclassed. *

*/ class Extension : public IExtension, public Object { private: // DTD properties (included in plug-in manifest) std::string extensionPoint; std::string id; std::string label; std::string namespaze; std::vector elements; public: berryObjectMacro(Extension); Extension(const std::string& namespaze); /** * Two Extensions are equal if they have the same Id * and target the same extension point. */ bool operator==(const Object* em) const; /** * Returns the extension point with which this extension is associated. * * @return the extension point with which this extension is associated * or null */ std::string GetExtensionPointIdentifier() const; std::string GetNamespace() const; /** * Returns the simple identifier of this extension, or null * if this extension does not have an identifier. * This identifier is specified in the plug-in manifest as a non-empty * string containing no period characters ('.') and * must be unique within the defining plug-in. * * @return the simple identifier of the extension (e.g. "main") * or null */ std::string GetSimpleIdentifier() const; std::string GetUniqueIdentifier() const; const std::vector GetConfigurationElements() const; std::string GetLabel() const; /** * Set the extension point with which this extension is associated. * This object must not be read-only. * * @return the extension point with which this extension is associated. * May be null. */ void SetExtensionPointIdentifier(const std::string& value); /** * Sets the simple identifier of this extension, or null * if this extension does not have an identifier. * This identifier is specified in the plug-in manifest as a non-empty * string containing no period characters ('.') and * must be unique within the defining plug-in. * This object must not be read-only. * * @param value the simple identifier of the extension (e.g. "main"). * May be null. */ void SetSimpleIdentifier(const std::string& value); /** * Sets the configuration element children of this extension. * * @param value the configuration elements in this extension. * May be null. */ void SetSubElements(const std::vector& value); void SetLabel(const std::string& l); bool operator<(const IExtension* e2) const; }; } #endif /*BERRYEXTENSION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtensionPoint.cpp b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtensionPoint.cpp index b177f8ede7..7dba08176b 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtensionPoint.cpp +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtensionPoint.cpp @@ -1,139 +1,139 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryExtensionPoint.h" -#include "../service/berryIConfigurationElement.h" +#include "service/berryIConfigurationElement.h" -#include "../berryPlatformException.h" +#include "berryPlatformException.h" namespace berry { ExtensionPoint::ExtensionPoint(const std::string& contributor) : m_Contributor(contributor), m_Label(""), m_SimpleId("") { m_UniqueId = contributor + "." + m_SimpleId; } std::string ExtensionPoint::GetContributor() const { return m_Contributor; } const std::vector ExtensionPoint::GetConfigurationElements() const { std::vector result; const std::vector extensions = this->GetExtensions(); for (std::vector::const_iterator itr = extensions.begin(); itr != extensions.end(); ++itr) { const std::vector configs = (*itr)->GetConfigurationElements(); result.insert(result.end(), configs.begin(), configs.end()); } return result; } const IExtension* ExtensionPoint::GetExtension(const std::string& extensionId) const { std::map::const_iterator iter = m_Extensions.find(extensionId); if (iter == m_Extensions.end()) return 0; return iter->second.GetPointer(); } const std::vector ExtensionPoint::GetExtensions() const { std::vector extensions; for (std::map::const_iterator iter = m_Extensions.begin(); iter != m_Extensions.end(); ++iter) { extensions.push_back(iter->second.GetPointer()); } for (std::vector::const_iterator iter = m_UnnamedExtensions.begin(); iter != m_UnnamedExtensions.end(); ++iter) { extensions.push_back(iter->GetPointer()); } //extensions.insert(extensions.end(), m_UnnamedExtensions.begin(), m_UnnamedExtensions.end()); return extensions; } std::string ExtensionPoint::GetLabel() const { return m_Label; } std::string ExtensionPoint::GetSimpleIdentifier() const { return m_SimpleId; } std::string ExtensionPoint::GetUniqueIdentifier() const { return m_UniqueId; } void ExtensionPoint::SetLabel(const std::string& label) { m_Label = label; } void ExtensionPoint::SetSimpleId(const std::string& id) { m_SimpleId = id; } void ExtensionPoint::SetParentId(const std::string& id) { m_UniqueId = id + "." + m_SimpleId; } void ExtensionPoint::AddExtension(Extension::Pointer extension) { if (extension->GetUniqueIdentifier() == "") { m_UnnamedExtensions.push_back(extension); return; } if (m_Extensions.find(extension->GetUniqueIdentifier()) != m_Extensions.end()) { throw PlatformException("Duplicate extension id \"" + extension->GetUniqueIdentifier() + "\" found for extension point \"" + this->GetUniqueIdentifier() + "\" from plugin \"" + this->GetContributor() + "\""); } m_Extensions[extension->GetUniqueIdentifier()] = extension; } } diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtensionPoint.h b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtensionPoint.h index 8963381b0c..aa346fd8ae 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtensionPoint.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtensionPoint.h @@ -1,73 +1,73 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYEXTENSIONPOINT_H_ #define BERRYEXTENSIONPOINT_H_ -#include "../berryMacros.h" +#include "berryMacros.h" -#include "../service/berryIExtensionPoint.h" -#include "../service/berryIExtension.h" +#include "service/berryIExtensionPoint.h" +#include "service/berryIExtension.h" #include "berryExtension.h" #include namespace berry { struct IConfigurationElement; class ExtensionPoint : public IExtensionPoint, public Object { public: berryObjectMacro(ExtensionPoint); ExtensionPoint(const std::string& contributor); std::string GetContributor() const; const std::vector GetConfigurationElements() const; const IExtension* GetExtension(const std::string& extensionId) const; const std::vector GetExtensions() const; std::string GetLabel() const; std::string GetSimpleIdentifier() const; std::string GetUniqueIdentifier() const; void AddExtension(Extension::Pointer extension); void SetLabel(const std::string& label); void SetSimpleId(const std::string& id); void SetParentId(const std::string& id); private: std::string m_Contributor; std::string m_Label; std::string m_SimpleId; std::string m_UniqueId; std::map m_Extensions; std::vector m_UnnamedExtensions; }; } #endif /*BERRYEXTENSIONPOINT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtensionPointService.h b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtensionPointService.h index 147b051996..0305f0c65a 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtensionPointService.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryExtensionPointService.h @@ -1,83 +1,83 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYEXTENSIONPOINTSERVICE_H_ #define BERRYEXTENSIONPOINTSERVICE_H_ -#include "../berryMacros.h" +#include "berryMacros.h" #include "Poco/SAX/InputSource.h" #include "Poco/DOM/DOMParser.h" -#include "../service/berryIConfigurationElement.h" +#include "service/berryIConfigurationElement.h" #include "berryExtensionPoint.h" -#include "../service/berryIExtensionPointService.h" +#include "service/berryIExtensionPointService.h" #include #include namespace berry { class Bundle; class BundleLoader; class ExtensionPointService : public QObject, public IExtensionPointService { Q_OBJECT Q_INTERFACES(berry::IExtensionPointService) public: berryObjectMacro(ExtensionPointService); bool IsA(const std::type_info& type); const std::type_info& GetType() const; ExtensionPointService(BundleLoader* loader); void AddContribution(std::istream& istr, const std::string& contributor); const std::vector GetConfigurationElementsFor(const std::string& extensionPointId) const; const IExtension* GetExtension(const std::string& extensionPointId, const std::string& extensionId) const; const IExtensionPoint* GetExtensionPoint(const std::string& id) const; const std::vector GetExtensions(const std::string& contributor) const; const std::vector GetExtensionPoints() const; const std::vector GetExtensionPoints(const std::string& contributor) const; bool HasContributionFrom(const std::string& name) const; private: typedef std::map ExtensionPointMap; std::set m_Contributors; BundleLoader* m_BundleLoader; ExtensionPointMap m_ExtensionPointMap; Poco::XML::DOMParser m_DOMParser; Poco::XML::InputSource m_XMLInputSource; bool m_ConsoleLog; }; } // namespace berry #endif /*BERRYEXTENSIONPOINTSERVICE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryInternalPlatform.cpp b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryInternalPlatform.cpp index 0bacc11472..39921b35b6 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryInternalPlatform.cpp +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryInternalPlatform.cpp @@ -1,603 +1,603 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryInternalPlatform.h" #include "berryLog.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include -#include "../berryPlatform.h" -#include "../berryPlatformException.h" -#include "../berryDebugUtil.h" -#include "../event/berryPlatformEvents.h" +#include "berryPlatform.h" +#include "berryPlatformException.h" +#include "berryDebugUtil.h" +#include "event/berryPlatformEvents.h" #include "berryPlatformLogChannel.h" -#include "../berryIBundle.h" +#include "berryIBundle.h" #include "berryCodeCache.h" -#include "../berryBundleLoader.h" +#include "berryBundleLoader.h" #include "berrySystemBundle.h" #include "berryBundleDirectory.h" #include "berryProvisioningInfo.h" #include #include #include namespace berry { Poco::Mutex InternalPlatform::m_Mutex; InternalPlatform::InternalPlatform() : m_Initialized(false), m_Running(false), m_ConsoleLog(false), m_ServiceRegistry(0), m_CodeCache(0), m_BundleLoader(0), m_SystemBundle(0), m_PlatformLogger(0), m_ctkPluginFrameworkFactory(0), m_EventStarted(PlatformEvent::EV_PLATFORM_STARTED) { } InternalPlatform::~InternalPlatform() { } InternalPlatform* InternalPlatform::GetInstance() { Poco::Mutex::ScopedLock lock(m_Mutex); static InternalPlatform instance; return &instance; } bool InternalPlatform::ConsoleLog() const { return m_ConsoleLog; } ctkPluginContext* InternalPlatform::GetCTKPluginFrameworkContext() const { if (m_ctkPluginFrameworkFactory) { return m_ctkPluginFrameworkFactory->getFramework()->getPluginContext(); } return 0; } ServiceRegistry& InternalPlatform::GetServiceRegistry() { AssertInitialized(); return *m_ServiceRegistry; } 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_ServiceRegistry = new ServiceRegistry(); m_ConsoleLog = this->GetConfiguration().hasProperty(Platform::ARG_CONSOLELOG); m_ConfigPath.assign(this->GetConfiguration().getString("application.configDir")); m_InstancePath.assign(this->GetConfiguration().getString("application.dir")); try { m_InstallPath.assign(this->GetConfiguration().getString(Platform::ARG_HOME)); } catch (Poco::NotFoundException& ) { m_InstallPath.assign(m_InstancePath); } if (this->GetConfiguration().hasProperty(Platform::ARG_STORAGE_DIR)) { std::string dataLocation = this->GetConfiguration().getString(Platform::ARG_STORAGE_DIR, ""); if (dataLocation.at(dataLocation.size()-1) != '/') { dataLocation += '/'; } m_UserPath.assign(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. QString dataLocation = QDesktopServices::storageLocation(QDesktopServices::DataLocation) + '_'; dataLocation += QString::number(qHash(QCoreApplication::applicationDirPath())) + "/"; m_UserPath.assign(dataLocation.toStdString()); } BERRY_INFO(m_ConsoleLog) << "Framework storage dir: " << m_UserPath.toString(); Poco::File userFile(m_UserPath); try { userFile.createDirectories(); userFile.canWrite(); } catch(const Poco::IOException& e) { BERRY_WARN << e.displayText(); m_UserPath.assign(Poco::Path::temp()); m_UserPath.pushDirectory("." + this->commandName()); userFile = m_UserPath; } // Initialize the CTK Plugin Framework ctkProperties fwProps; fwProps.insert(ctkPluginConstants::FRAMEWORK_STORAGE, QString::fromStdString(userFile.path())); if (this->GetConfiguration().hasProperty(Platform::ARG_CLEAN)) { fwProps.insert(ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN, ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); } if (this->GetConfiguration().hasProperty(Platform::ARG_CONSOLELOG)) { 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)) { QString preloadLibs = QString::fromStdString(this->GetConfiguration().getString(Platform::ARG_PRELOAD_LIBRARY)); 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(); std::string provisioningFile = this->GetConfiguration().getString(Platform::ARG_PROVISIONING); if (!provisioningFile.empty()) { BERRY_INFO(m_ConsoleLog) << "Using provisioning file: " << provisioningFile; ProvisioningInfo provInfo(QString::fromStdString(provisioningFile)); foreach(QString pluginPath, provInfo.getPluginDirs()) { ctkPluginFrameworkLauncher::addSearchPath(pluginPath); } bool forcePluginOverwrite = this->GetConfiguration().hasOption(Platform::ARG_FORCE_PLUGIN_INSTALL); 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) { BERRY_ERROR << "Failed to install: " << pluginUrl.toString().toStdString() << ",\n" << e.what(); } } } else { BERRY_INFO << "No provisioning file set."; } m_BaseStatePath = m_UserPath; m_BaseStatePath.pushDirectory("bb-metadata"); m_BaseStatePath.pushDirectory("bb-plugins"); Poco::Path logPath(m_UserPath); logPath.setFileName(this->commandName() + ".log"); m_PlatformLogChannel = new PlatformLogChannel(logPath.toString()); m_PlatformLogger = &Poco::Logger::create("PlatformLogger", m_PlatformLogChannel, Poco::Message::PRIO_TRACE); try { m_CodeCache = new CodeCache(this->GetConfiguration().getString(Platform::ARG_PLUGIN_CACHE)); } catch (Poco::NotFoundException&) { Poco::Path cachePath(m_UserPath); cachePath.pushDirectory("bb-plugin_cache"); m_CodeCache = new CodeCache(cachePath.toString()); } m_BundleLoader = new BundleLoader(m_CodeCache, *m_PlatformLogger); // tell the BundleLoader about the installed CTK plug-ins QStringList installedCTKPlugins; foreach(QSharedPointer plugin, pfwContext->getPlugins()) { installedCTKPlugins << plugin->getSymbolicName(); } m_BundleLoader->SetCTKPlugins(installedCTKPlugins); m_Initialized = true; // Clear the CodeCache if (this->GetConfiguration().hasProperty(Platform::ARG_CLEAN)) m_CodeCache->Clear(); try { // assemble a list of base plugin-directories (which contain // the real plugins as directories) std::vector pluginBaseDirs; Poco::StringTokenizer tokenizer(this->GetConfiguration().getString(Platform::ARG_PLUGIN_DIRS, ""), ";", Poco::StringTokenizer::TOK_IGNORE_EMPTY | Poco::StringTokenizer::TOK_TRIM); for (Poco::StringTokenizer::Iterator token = tokenizer.begin(); token != tokenizer.end(); ++token) { pluginBaseDirs.push_back(*token); } std::vector pluginPaths; for (std::vector::iterator pluginBaseDir = pluginBaseDirs.begin(); pluginBaseDir != pluginBaseDirs.end(); ++pluginBaseDir) { BERRY_INFO(m_ConsoleLog) << "Plugin base directory: " << *pluginBaseDir; Poco::File pluginDir(*pluginBaseDir); if (!pluginDir.exists() || !pluginDir.isDirectory()) { BERRY_WARN(m_ConsoleLog) << *pluginBaseDir << " is not a direcotry or does not exist. SKIPPED.\n"; continue; } std::vector pluginList; pluginDir.list(pluginList); std::vector::iterator iter; for (iter = pluginList.begin(); iter != pluginList.end(); iter++) { Poco::Path pluginPath = Poco::Path::forDirectory(*pluginBaseDir); pluginPath.pushDirectory(*iter); Poco::File file(pluginPath); if (file.exists() && file.isDirectory()) { pluginPaths.push_back(pluginPath); } } } std::vector::iterator pathIter; for (pathIter = pluginPaths.begin(); pathIter != pluginPaths.end(); pathIter++) { try { Bundle::Pointer bundle = m_BundleLoader->LoadBundle(*pathIter); if (bundle) { BERRY_INFO(m_ConsoleLog) << "Bundle state (" << pathIter->toString() << "): " << bundle->GetStateString() << std::endl; } } catch (const BundleStateException& exc) { BERRY_WARN << exc.displayText() << std::endl; } } // resolve plugins m_BundleLoader->ResolveAllBundles(); } catch (Poco::Exception& exc) { this->logger().log(exc); } #ifdef BLUEBERRY_DEBUG_SMARTPOINTER DebugUtil::RestoreState(); #endif } void InternalPlatform::uninstallPugin(const QUrl& pluginUrl, ctkPluginContext* pfwContext) { QFileInfo libInfo(pluginUrl.toLocalFile()); QString libName = libInfo.baseName(); if (libName.startsWith("lib")) { libName = libName.mid(3); } QString symbolicName = libName.replace('_', '.'); foreach(QSharedPointer plugin, pfwContext->getPlugins()) { if (plugin->getSymbolicName() == symbolicName && plugin->getLocation() != pluginUrl.toString()) { BERRY_WARN << "A plug-in with the symbolic name " << symbolicName.toStdString() << " but different location is already installed. Trying to uninstall " << plugin->getLocation().toStdString(); plugin->uninstall(); return; } } } void InternalPlatform::Launch() { AssertInitialized(); if (m_Running) return; m_Running = true; this->run(); } void InternalPlatform::Shutdown() { QSharedPointer ctkPluginFW; { Poco::Mutex::ScopedLock lock(m_Mutex); AssertInitialized(); DebugUtil::SaveState(); ctkPluginFW = m_ctkPluginFrameworkFactory->getFramework(); m_Initialized = false; } ctkPluginFW->stop(); this->uninitialize(); // wait 10 seconds for the CTK plugin framework to stop ctkPluginFW->waitForStop(10000); { Poco::Mutex::ScopedLock lock(m_Mutex); delete m_ServiceRegistry; delete m_BundleLoader; delete m_CodeCache; } } void InternalPlatform::AssertInitialized() { if (!m_Initialized) throw Poco::SystemException("The Platform has not been initialized yet!"); } IExtensionPointService::Pointer InternalPlatform::GetExtensionPointService() { Poco::Mutex::ScopedLock lock(m_Mutex); this->AssertInitialized(); return m_ServiceRegistry->GetServiceById(IExtensionPointService::SERVICE_ID); } const Poco::Path& InternalPlatform::GetConfigurationPath() { return m_ConfigPath; } const Poco::Path& InternalPlatform::GetInstallPath() { return m_InstallPath; } const Poco::Path& InternalPlatform::GetInstancePath() { return m_InstancePath; } bool InternalPlatform::GetStatePath(Poco::Path& statePath, IBundle::Pointer bundle, bool create) { statePath = m_BaseStatePath; statePath.pushDirectory(bundle->GetSymbolicName()); try { Poco::File stateFile(statePath); if (!stateFile.exists() && create) stateFile.createDirectories(); } catch (Poco::FileException&) { return false; } return true; } PlatformEvents& InternalPlatform::GetEvents() { return m_Events; } const Poco::Path& InternalPlatform::GetUserPath() { return m_UserPath; } bool InternalPlatform::IsRunning() const { Poco::Mutex::ScopedLock lock(m_Mutex); return (m_Initialized && m_Running); } IBundle::Pointer InternalPlatform::GetBundle(const std::string& id) { Poco::Mutex::ScopedLock lock(m_Mutex); AssertInitialized(); return m_BundleLoader->FindBundle(id); } std::vector InternalPlatform::GetBundles() const { return m_BundleLoader->GetBundles(); } Poco::Logger* InternalPlatform::GetLogger() { return m_PlatformLogger; } Poco::Util::LayeredConfiguration& InternalPlatform::GetConfiguration() const { return this->config(); } std::vector 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, "", "forces a new instance of this application"); newInstanceOption.binding(Platform::ARG_NEWINSTANCE); options.addOption(newInstanceOption); Poco::Util::Option cleanOption(Platform::ARG_CLEAN, "", "cleans the plugin cache"); cleanOption.binding(Platform::ARG_CLEAN); options.addOption(cleanOption); Poco::Util::Option appOption(Platform::ARG_APPLICATION, "", "the id of the application extension to be executed"); appOption.argument("").binding(Platform::ARG_APPLICATION); options.addOption(appOption); Poco::Util::Option storageDirOption(Platform::ARG_STORAGE_DIR, "", "the location for storing persistent application data"); storageDirOption.argument("").binding(Platform::ARG_STORAGE_DIR); options.addOption(storageDirOption); Poco::Util::Option consoleLogOption(Platform::ARG_CONSOLELOG, "", "log messages to the console"); consoleLogOption.binding(Platform::ARG_CONSOLELOG); options.addOption(consoleLogOption); Poco::Util::Option forcePluginOption(Platform::ARG_FORCE_PLUGIN_INSTALL, "", "force installing plug-ins with same symbolic name"); forcePluginOption.binding(Platform::ARG_FORCE_PLUGIN_INSTALL); options.addOption(forcePluginOption); Poco::Util::Option preloadLibsOption(Platform::ARG_PRELOAD_LIBRARY, "", "preload a library"); preloadLibsOption.argument("").repeatable(true).callback(Poco::Util::OptionCallback(this, &InternalPlatform::handlePreloadLibraryOption)); options.addOption(preloadLibsOption); Poco::Util::Option testPluginOption(Platform::ARG_TESTPLUGIN, "", "the plug-in to be tested"); testPluginOption.argument("").binding(Platform::ARG_TESTPLUGIN); options.addOption(testPluginOption); Poco::Util::Option testAppOption(Platform::ARG_TESTAPPLICATION, "", "the application to be tested"); testAppOption.argument("").binding(Platform::ARG_TESTAPPLICATION); options.addOption(testAppOption); Poco::Util::Option xargsOption(Platform::ARG_XARGS, "", "Extended argument list"); xargsOption.argument("").binding(Platform::ARG_XARGS); 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)) { oldVal = this->config().getString(Platform::ARG_PRELOAD_LIBRARY); } this->config().setString(Platform::ARG_PRELOAD_LIBRARY, oldVal + "," + value); } int InternalPlatform::main(const std::vector& args) { m_FilteredArgs = args; //m_FilteredArgs.insert(m_FilteredArgs.begin(), this->config().getString("application.argv[0]")); ctkPluginContext* context = GetCTKPluginFrameworkContext(); QFileInfo storageDir = context->getDataFile(""); BundleDirectory::Pointer bundleStorage(new BundleDirectory(Poco::Path(storageDir.absolutePath().toStdString()))); SystemBundle::Pointer systemBundle(new SystemBundle(*m_BundleLoader, bundleStorage)); if (systemBundle == 0) throw PlatformException("Could not find the system bundle"); m_BundleLoader->m_SystemBundle = systemBundle; m_BundleLoader->LoadBundle(systemBundle); 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); } m_BundleLoader->StartSystemBundle(systemBundle); systemBundle->Resume(); 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.osgi/src/internal/berryInternalPlatform.h b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryInternalPlatform.h index 9a71764f2d..ec0f7bcbef 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryInternalPlatform.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryInternalPlatform.h @@ -1,151 +1,151 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYINTERNALPLATFORM_H_ #define BERRYINTERNALPLATFORM_H_ #include #include #include #include #include -#include "../event/berryPlatformEvents.h" -#include "../service/berryServiceRegistry.h" +#include "event/berryPlatformEvents.h" +#include "service/berryServiceRegistry.h" #include "berryExtensionPointService.h" #include class ctkPluginFrameworkFactory; class ctkPluginContext; namespace berry { struct IBundle; class CodeCache; class BundleLoader; class PlatformLogChannel; class SystemBundle; class BERRY_OSGI InternalPlatform : private Poco::Util::Application { private: static Poco::Mutex m_Mutex; bool m_Initialized; bool m_Running; bool m_ConsoleLog; ServiceRegistry* m_ServiceRegistry; Poco::Path m_BaseStatePath; Poco::Path m_InstallPath; Poco::Path m_InstancePath; Poco::Path m_UserPath; Poco::Path m_ConfigPath; std::vector m_FilteredArgs; CodeCache* m_CodeCache; BundleLoader* m_BundleLoader; SystemBundle* m_SystemBundle; Poco::AutoPtr m_PlatformLogChannel; Poco::Logger* m_PlatformLogger; 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(); void handlePreloadLibraryOption(const std::string &name, const std::string &value); int main(const std::vector& args); void uninstallPugin(const QUrl& pluginUrl, ctkPluginContext* pfwContext); public: 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(); ctkPluginContext* GetCTKPluginFrameworkContext() const; /// Returns a ServiceRegistry object for registering /// and accessing services from different plugins ServiceRegistry& GetServiceRegistry(); /// Convenience method to quickly get the extension /// point service, which is automatically started /// by the platform IExtensionPointService::Pointer GetExtensionPointService(); bool ConsoleLog() const; const Poco::Path& GetConfigurationPath(); const Poco::Path& GetInstallPath(); const Poco::Path& GetInstancePath(); bool GetStatePath(Poco::Path& statePath, SmartPointer bundle, bool create = true); const Poco::Path& GetUserPath(); PlatformEvents& GetEvents(); bool IsRunning() const; Poco::Util::LayeredConfiguration& GetConfiguration() const; std::vector GetApplicationArgs() const; int& GetRawApplicationArgs(char**& argv); IBundle::Pointer GetBundle(const std::string& id); std::vector GetBundles() const; Poco::Logger* GetLogger(); }; } // namespace berry #endif /*BERRYINTERNALPLATFORM_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryPlatformLogChannel.cpp b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryPlatformLogChannel.cpp index c1cf815765..a2ad62cb1f 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryPlatformLogChannel.cpp +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berryPlatformLogChannel.cpp @@ -1,45 +1,45 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryPlatformLogChannel.h" -#include "../berryPlatform.h" -#include "../event/berryPlatformEvent.h" +#include "berryPlatform.h" +#include "event/berryPlatformEvent.h" #include "Poco/Any.h" namespace berry { PlatformLogChannel::PlatformLogChannel(const std::string& path) : Poco::SimpleFileChannel(path) { } void PlatformLogChannel::log(const Poco::Message& msg) { Poco::SimpleFileChannel::log(msg); PlatformEvent event(PlatformEvent::EV_LOGGED); Poco::Any data(msg); event.SetData(&data); Platform::GetEvents().logged(event); } } diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundle.cpp b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundle.cpp index 39cdcd9703..c9883bbcb6 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundle.cpp +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundle.cpp @@ -1,77 +1,77 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryLog.h" #include "berrySystemBundle.h" #include "berrySystemBundleManifest.h" #include "Poco/Exception.h" -#include "../berryBundleLoader.h" +#include "berryBundleLoader.h" namespace berry { SystemBundle::SystemBundle(BundleLoader& loader, IBundleStorage::Pointer storage) : Bundle(loader, storage, false) { this->init(); m_State = BUNDLE_RESOLVED; } void SystemBundle::Start() { } void SystemBundle::Resume() { m_State = BUNDLE_ACTIVE; // read the plugin.xml file from the resolved plugins try { m_BundleLoader.ReadAllContributions(); } catch (Poco::Exception exc) { BERRY_ERROR << exc.displayText() << std::endl; } // start all plugins with lazy-start: false try { m_BundleLoader.StartAllBundles(); } catch (Poco::Exception exc) { BERRY_ERROR << exc.displayText() << std::endl; } } BundleLoader& SystemBundle::GetBundleLoader() { return m_BundleLoader; } void SystemBundle::LoadManifest() { m_Manifest = new SystemBundleManifest(); } } diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundleActivator.cpp b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundleActivator.cpp index 026243dbc8..818ec06a9a 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundleActivator.cpp +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundleActivator.cpp @@ -1,41 +1,41 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryLog.h" #include "berrySystemBundleActivator.h" -#include "../berryIBundleContext.h" -#include "../berryPlatform.h" -#include "../service/berryServiceRegistry.h" +#include "berryIBundleContext.h" +#include "berryPlatform.h" +#include "service/berryServiceRegistry.h" #include "berrySystemBundle.h" #include "berryExtensionPointService.h" namespace berry { void SystemBundleActivator::Start(IBundleContext::Pointer context) { } void SystemBundleActivator::Stop(IBundleContext::Pointer /*context*/) { } } diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundleActivator.h b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundleActivator.h index 96919cbc93..a6cc9d385c 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundleActivator.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundleActivator.h @@ -1,35 +1,35 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYSYSTEMBUNDLEACTIVATOR_H_ #define BERRYSYSTEMBUNDLEACTIVATOR_H_ -#include "../berryIBundleActivator.h" +#include "berryIBundleActivator.h" namespace berry { class SystemBundleActivator : public IBundleActivator { public: void Start(SmartPointer context); void Stop(SmartPointer context); }; } #endif /*BERRYSYSTEMBUNDLEACTIVATOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundleManifest.h b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundleManifest.h index 0345c5dac6..1e2c89e1da 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundleManifest.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/internal/berrySystemBundleManifest.h @@ -1,58 +1,58 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYSYSTEMBUNDLEMANIFEST_H #define BERRYSYSTEMBUNDLEMANIFEST_H -#include "../berryIBundleManifest.h" +#include "berryIBundleManifest.h" #include namespace berry { class SystemBundleManifest : public IBundleManifest { public: SystemBundleManifest(); virtual const std::string& GetActivatorClass() const; virtual const std::string& GetActivatorLibrary() const; virtual const std::string& GetCopyright() const; virtual ActivationPolicy GetActivationPolicy() const; virtual bool IsSystemBundle() const; virtual const std::string& GetName() const; virtual const Dependencies& GetRequiredBundles() const; virtual const std::string& GetSymbolicName() const; virtual const std::string& GetVendor() const; private: Dependencies dependencies; QHash manifestHeaders; std::string activatorClass; std::string activatorLib; std::string copyright; std::string name; std::string symbolicName; std::string vendor; }; } #endif // BERRYSYSTEMBUNDLEMANIFEST_H diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/service/berryIConfigurationElement.h b/BlueBerry/Bundles/org.blueberry.osgi/src/service/berryIConfigurationElement.h index c4efee5222..86be865f52 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/service/berryIConfigurationElement.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/service/berryIConfigurationElement.h @@ -1,157 +1,157 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYIEXTENSIONELEMENT_H_ #define BERRYIEXTENSIONELEMENT_H_ #include "berryLog.h" #include -#include "../berryBundleLoader.h" -#include "../berryPlatformException.h" +#include "berryBundleLoader.h" +#include "berryPlatformException.h" #include "berryExtensionType.h" #include "berryIExecutableExtension.h" #include "berryIExtension.h" #include #include namespace berry { struct IExtension; struct BERRY_OSGI IConfigurationElement : public Object { berryObjectMacro(IConfigurationElement); public: typedef std::vector vector; template C* CreateExecutableExtension(const std::string& propertyName, const std::string& manifestName) { std::string className; if (this->GetAttribute(propertyName, className)) { try { C* cl = m_ClassLoader->LoadClass(m_Contributor, className, manifestName); // check if we have extension adapter and initialize if (dynamic_cast(cl) != 0) { // make the call even if the initialization string is null dynamic_cast(cl)->SetInitializationData(Pointer(this), propertyName, Object::Pointer(0)); } if (cl == 0) { BERRY_WARN << "Could not load executable extension " << className << " from " << GetContributor(); } return cl; } catch (Poco::Exception& e) { BERRY_ERROR << "Error loading class: " << e.displayText() << std::endl; throw e; } } throw CoreException("Missing attribute", propertyName); } template C* CreateExecutableExtension(const std::string& propertyName) { std::string className; if (this->GetAttribute(propertyName, className)) { std::string contributor = this->GetContributor(); QSharedPointer plugin = Platform::GetCTKPlugin(QString::fromStdString(contributor)); if (!plugin.isNull()) { // immediately start the plugin but do not change the plugins autostart setting plugin->start(ctkPlugin::START_TRANSIENT); QString typeName = plugin->getSymbolicName() + "_" + QString::fromStdString(className); int extensionTypeId = ExtensionType::type(typeName.toAscii().data()); if (extensionTypeId == 0) { BERRY_WARN << "The class " << className << " was not registered as an Extension Type using BERRY_REGISTER_EXTENSION_CLASS(type, pluginContext) or you forgot to run Qt's moc on the header file. " "Legacy BlueBerry bundles should use CreateExecutableExtension(propertyName, C::GetManifestName()) instead."; } else { QObject* obj = ExtensionType::construct(extensionTypeId); // check if we have extension adapter and initialize if (IExecutableExtension* execExt = qobject_cast(obj)) { // make the call even if the initialization string is null execExt->SetInitializationData(Pointer(this), propertyName, Object::Pointer(0)); } C* interface = qobject_cast(obj); if (interface == 0) { BERRY_WARN << "The QObject subclass " << className << " does not seem to implement the required interface class, or you forgot the Q_INTERFACES macro."; } return interface; } } else { BERRY_WARN << "Trying to create an executable extension (from " << this->GetDeclaringExtension()->GetExtensionPointIdentifier() << " in " << contributor << ") from a non-CTK plug-in. " "Use the CreateExecutableExtension(propertyName, manifestName) method instead."; } } return 0; } virtual bool GetAttribute(const std::string& name, std::string& value) const = 0; virtual bool GetBoolAttribute(const std::string& name, bool& value) const = 0; virtual const std::vector GetChildren() const = 0; virtual const std::vector GetChildren(const std::string& name) const = 0; virtual std::string GetValue() const = 0; virtual std::string GetName() const = 0; virtual const IConfigurationElement* GetParent() const = 0; virtual const std::string& GetContributor() const = 0; virtual const IExtension* GetDeclaringExtension() const = 0; virtual ~IConfigurationElement() {}; protected: BundleLoader* m_ClassLoader; std::string m_Contributor; }; } // namespace berry #endif /*BERRYIEXTENSIONELEMENT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/service/berryIExecutableExtension.h b/BlueBerry/Bundles/org.blueberry.osgi/src/service/berryIExecutableExtension.h index 81eb2fb411..dfd849b9b5 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/service/berryIExecutableExtension.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/service/berryIExecutableExtension.h @@ -1,128 +1,128 @@ #ifndef BERRYIEXECUTABLEEXTENSION_H_ #define BERRYIEXECUTABLEEXTENSION_H_ -#include "../berryObject.h" -#include "../berrySmartPointer.h" +#include "berryObject.h" +#include "berrySmartPointer.h" #include namespace berry { struct IConfigurationElement; /** * Interface for executable extension classes that require access to * their configuration element, or implement an extension adapter. *

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

*

* Clients may implement this interface. *

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

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

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

*

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

*

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

*

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

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

*

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

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

*

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

*

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

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

* * @param config the configuration element used to trigger this execution. * It can be queried by the executable extension for specific * configuration properties * @param propertyName the name of an attribute of the configuration element * used on the createExecutableExtension(String) call. This * argument can be used in the cases where a single configuration element * is used to define multiple executable extensions. * @param data adapter data in the form of a String, * a Hashtable, or null. * @exception CoreException if error(s) detected during initialization processing * @see IConfigurationElement#createExecutableExtension */ virtual void SetInitializationData(SmartPointer config, const std::string& propertyName, Object::Pointer data) = 0; virtual ~IExecutableExtension() {}; }; } Q_DECLARE_INTERFACE(berry::IExecutableExtension, "org.blueberry.IExecutableExtension") #endif /*BERRYIEXECUTABLEEXTENSION_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.osgi/src/service/berryService.h b/BlueBerry/Bundles/org.blueberry.osgi/src/service/berryService.h index be73d0b181..c71d3cfb74 100644 --- a/BlueBerry/Bundles/org.blueberry.osgi/src/service/berryService.h +++ b/BlueBerry/Bundles/org.blueberry.osgi/src/service/berryService.h @@ -1,44 +1,44 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYSERVICE_H_ #define BERRYSERVICE_H_ #include -#include "../berryMacros.h" -#include "../berryObject.h" +#include "berryMacros.h" +#include "berryObject.h" #include namespace berry { class BERRY_OSGI Service : public Object { public: berryObjectMacro(Service); virtual ~Service(); virtual bool IsA(const std::type_info& type) const; virtual const std::type_info& GetType() const; }; } // namespace berry #endif /*BERRYSERVICE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryPluginActivator.cpp b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryPluginActivator.cpp index 4a2a278649..3f62514247 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryPluginActivator.cpp +++ b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryPluginActivator.cpp @@ -1,44 +1,44 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryPluginActivator.h" -#include "../berryCoreTestApplication.h" +#include "berryCoreTestApplication.h" #include namespace berry { org_blueberry_test_Activator::org_blueberry_test_Activator() { } void org_blueberry_test_Activator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(CoreTestApplication, context) } void org_blueberry_test_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } Q_EXPORT_PLUGIN2(org_blueberry_test, berry::org_blueberry_test_Activator) diff --git a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestDescriptor.h b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestDescriptor.h index 7abb02106b..ba55bc23e1 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestDescriptor.h @@ -1,50 +1,50 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYTESTDESCRIPTOR_H_ #define BERRYTESTDESCRIPTOR_H_ -#include "../berryITestDescriptor.h" +#include "berryITestDescriptor.h" #include namespace berry { class TestDescriptor : public ITestDescriptor { public: berryObjectMacro(TestDescriptor) TestDescriptor(IConfigurationElement::Pointer elem); CppUnit::Test* CreateTest(); std::string GetId() const; std::string GetContributor() const; std::string GetDescription() const; bool IsUITest() const; private: IConfigurationElement::Pointer configElem; }; } #endif /* BERRYTESTDESCRIPTOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestRegistry.h b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestRegistry.h index 71774bc80a..5d3bb62bab 100644 --- a/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestRegistry.h +++ b/BlueBerry/Bundles/org.blueberry.test/src/internal/berryTestRegistry.h @@ -1,58 +1,58 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYTESTREGISTRY_H_ #define BERRYTESTREGISTRY_H_ #include -#include "../berryITestDescriptor.h" +#include "berryITestDescriptor.h" #include #include namespace berry { class TestRegistry { public: static const std::string TAG_TEST; // = "test" static const std::string ATT_ID; // = "id" static const std::string ATT_CLASS; // = "class" static const std::string ATT_DESCRIPTION; // = "description" static const std::string ATT_UITEST; // = "uitest" static const std::string TEST_MANIFEST; // = "CppUnitTest" TestRegistry(); const std::vector& GetTestsForId(const std::string& pluginid); protected: void ReadTest(IConfigurationElement::Pointer testElem); private: Poco::HashMap > mapIdToTests; }; } #endif /* BERRYTESTREGISTRY_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryLogView.h b/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryLogView.h index 86e9424210..c3da6cc11d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryLogView.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt.log/src/internal/berryLogView.h @@ -1,46 +1,46 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYLOGVIEW_H_ #define BERRYLOGVIEW_H_ #include -#include "../berryQtViewPart.h" +#include "berryQtViewPart.h" namespace berry { class LogView : public QtViewPart { Q_OBJECT public: LogView(); LogView(const LogView& other); void SetFocus(); protected: void CreateQtPartControl(QWidget* parent); }; } // namespace berry #endif /*BERRYLOGVIEW_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp index 54fe14e513..5311e642f4 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/application/berryQtWorkbenchAdvisor.cpp @@ -1,60 +1,60 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryQtWorkbenchAdvisor.h" -#include "../internal/berryQtGlobalEventFilter.h" -#include "../berryQtPreferences.h" +#include "internal/berryQtGlobalEventFilter.h" +#include "berryQtPreferences.h" #include #include #include #include #include #include #include #include #include namespace berry { void QtWorkbenchAdvisor::Initialize(IWorkbenchConfigurer::Pointer configurer) { WorkbenchAdvisor::Initialize(configurer); IPreferencesService::Pointer prefService = Platform::GetServiceRegistry().GetServiceById( IPreferencesService::ID); IPreferences::Pointer prefs = prefService->GetSystemPreferences()->Node(QtPreferences::QT_STYLES_NODE); QString styleName = QString::fromStdString(prefs->Get(QtPreferences::QT_STYLE_NAME, "")); IQtStyleManager::Pointer styleManager = Platform::GetServiceRegistry().GetServiceById(IQtStyleManager::ID); styleManager->SetStyle(styleName); QObject* eventFilter = new QtGlobalEventFilter(qApp); qApp->installEventFilter(eventFilter); // character strings should be interpreted as UTF-8 encoded strings // e.g. plugin.xml files are UTF-8 encoded QTextCodec* utf8Codec = QTextCodec::codecForName("UTF-8"); QTextCodec::setCodecForCStrings(utf8Codec); QTextCodec::setCodecForTr(utf8Codec); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQCHPluginListener.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQCHPluginListener.cpp index b3ce77035e..bfdfcaf512 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQCHPluginListener.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/berryQCHPluginListener.cpp @@ -1,157 +1,157 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryQCHPluginListener.h" #include #include #include -#include "../berryQtAssistantUtil.h" +#include "berryQtAssistantUtil.h" namespace berry { QCHPluginListener::QCHPluginListener(ctkPluginContext* context) : delayRegistration(true), context(context) { } void QCHPluginListener::processPlugins() { if (QtAssistantUtil::GetHelpCollectionFile().isEmpty()) { return; } foreach (QSharedPointer plugin, context->getPlugins()) { if (isPluginResolved(plugin)) addPlugin(plugin); else removePlugin(plugin); } delayRegistration = false; } void QCHPluginListener::pluginChanged(const ctkPluginEvent& event) { if (delayRegistration) { this->processPlugins(); 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; } } 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 qch files QtAssistantUtil::UnregisterQCHFiles(qchFiles); // 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(); } } QtAssistantUtil::RegisterQCHFiles(localQCHFiles); } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtGlobalEventFilter.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtGlobalEventFilter.cpp index 1f4a65f775..35b18556b4 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtGlobalEventFilter.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtGlobalEventFilter.cpp @@ -1,61 +1,61 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryQtGlobalEventFilter.h" -#include "../internal/berryQtControlWidget.h" +#include "internal/berryQtControlWidget.h" #include #include #include #include #include namespace berry { QtGlobalEventFilter::QtGlobalEventFilter(QObject* parent) : QObject(parent) { } bool QtGlobalEventFilter::eventFilter(QObject* /*obj*/, QEvent* event) { if (event->type() == QEvent::MouseButtonPress) { QMouseEvent* mouseEvent = static_cast(event); QWidget* widget = QApplication::widgetAt(mouseEvent->globalPos()); if (widget) { QObject* parent = widget; while (parent) { if (parent->objectName() == "PartPaneControl") { (dynamic_cast(parent))->FireActivateEvent(); break; } parent = parent->parent(); } } } return false; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStyleManager.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStyleManager.cpp index c6a035acaf..2a28e9c6ff 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStyleManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStyleManager.cpp @@ -1,315 +1,315 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryQtStyleManager.h" #include #include #include #include #include #include #include #include #include #include #include -#include "../berryQtPreferences.h" +#include "berryQtPreferences.h" namespace berry { bool QtStyleManager::IsA(const std::type_info& type) const { std::string name(GetType().name()); return name == type.name() || Service::IsA(type); } const std::type_info& QtStyleManager::GetType() const { return typeid(berry::IQtStyleManager); } QtStyleManager::QtStyleManager() { AddDefaultStyle(); ReadPreferences(); } void QtStyleManager::ReadPreferences() { IPreferencesService::Pointer prefService = Platform::GetServiceRegistry() .GetServiceById(IPreferencesService::ID); IPreferences::Pointer stylePref = prefService->GetSystemPreferences()->Node(QtPreferences::QT_STYLES_NODE); QString paths = QString::fromStdString(stylePref->Get(QtPreferences::QT_STYLE_SEARCHPATHS, "")); QStringList pathList = paths.split(";", QString::SkipEmptyParts); QStringListIterator it(pathList); while (it.hasNext()) { AddStyles(it.next()); } QString styleName = QString::fromStdString(stylePref->Get(QtPreferences::QT_STYLE_NAME, "")); // if a style is contributed via the Qt resource mechanism, it may not be // registered yet. if (Contains(styleName)) // do not update the style in the QApplication instance, // since it might not be created yet SetStyle(styleName, false); else SetDefaultStyle(false); } QtStyleManager::~QtStyleManager() { for (FileNameToStyleMap::const_iterator i = styles.begin(); i != styles.end(); ++i) { delete i.value(); } } void QtStyleManager::AddDefaultStyle() { #ifndef _APPLE_ AddStyle(":/org.blueberry.ui.qt/defaultstyle.qss", "Default"); defaultStyle = styles[":/org.blueberry.ui.qt/defaultstyle.qss"]; #endif } void QtStyleManager::ClearStyles() { for (FileNameToStyleMap::iterator i = styles.begin(); i != styles.end(); ) { if (!i.value()->fileName.startsWith(':')) { delete i.value(); i = styles.erase(i); } else ++i; } SetDefaultStyle(); } QtStyleManager::Style QtStyleManager::GetStyle() const { return Style(currentStyle->name, currentStyle->fileName); } QString QtStyleManager::GetStylesheet() const { return currentStyle->stylesheet; } QString QtStyleManager::GetActiveTabStylesheet() const { return currentStyle->activeTabStylesheet; } QString QtStyleManager::GetTabStylesheet() const { return currentStyle->tabStylesheet; } void QtStyleManager::AddStyle(const QString& styleFileName, const QString& styleName) { ExtStyle* newStyle = new ExtStyle(); if (styleName.isEmpty()) { QFileInfo info(styleFileName); newStyle->name = info.completeBaseName(); } else { newStyle->name = styleName; } newStyle->fileName = styleFileName; styles.insert(newStyle->fileName, newStyle); } void QtStyleManager::AddStyles(const QString& path) { QDirIterator dirIt(path); while (dirIt.hasNext()) { QString current = dirIt.next(); QFileInfo info = dirIt.fileInfo(); if (info.isFile() && info.isReadable()) { QString fileName = info.fileName(); if (fileName.endsWith("-tab.qss") || fileName.endsWith("-activetab.qss")) continue; if (fileName.endsWith(".qss")) AddStyle(current); } } } void QtStyleManager::ReadStyleData(ExtStyle* style) { QString tabStyleFileName(style->fileName); QString activeTabStyleFileName(style->fileName); int index = style->fileName.lastIndexOf(".qss"); tabStyleFileName.replace(index, 4, "-tab.qss"); activeTabStyleFileName.replace(index, 4, "-activetab.qss"); QFile styleFile(style->fileName); if (styleFile.open(QIODevice::ReadOnly)) { QTextStream in(&styleFile); style->stylesheet = in.readAll(); } else { BERRY_WARN << "Could not read " << style->fileName.toStdString(); } QFile tabStyleFile(tabStyleFileName); if (tabStyleFile.open(QIODevice::ReadOnly)) { QTextStream in(&tabStyleFile); style->tabStylesheet = in.readAll(); } else { BERRY_WARN << "Could not read " << tabStyleFileName.toStdString(); } QFile activeTabStyleFile(activeTabStyleFileName); if (activeTabStyleFile.open(QIODevice::ReadOnly)) { QTextStream in(&activeTabStyleFile); style->activeTabStylesheet = in.readAll(); } else { BERRY_WARN << "Could not read " << activeTabStyleFileName.toStdString(); } } void QtStyleManager::RemoveStyle(const QString& styleFileName) { if (currentStyle->fileName == styleFileName) { SetDefaultStyle(); } delete styles.take(styleFileName); } void QtStyleManager::RemoveStyles(const QString& repo) { if (repo.isEmpty()) { ClearStyles(); return; } for (FileNameToStyleMap::iterator i = styles.begin(); i != styles.end();) { ExtStyle* style = i.value(); QFileInfo info(style->fileName); if (info.absolutePath() == repo) { if (style->name == currentStyle->name) { SetDefaultStyle(); } i = styles.erase(i); delete style; } else { ++i; } } } void QtStyleManager::GetStyles(StyleList& styleNames) const { for (FileNameToStyleMap::const_iterator i = styles.begin(); i != styles.end(); ++i) styleNames.push_back(Style(i.value()->name, i.value()->fileName)); } void QtStyleManager::SetStyle(const QString& fileName) { SetStyle(fileName, true); } void QtStyleManager::SetStyle(const QString& fileName, bool update) { if (fileName.isEmpty()) { SetDefaultStyle(); return; } FileNameToStyleMap::const_iterator i = styles.find(fileName); ExtStyle* style = 0; if (i == styles.end()) { BERRY_WARN << "Style " + fileName.toStdString() << " does not exist"; style = defaultStyle; } else { style = i.value(); } currentStyle = style; ReadStyleData(style); if (update) { qApp->setStyleSheet(currentStyle->stylesheet); PlatformUI::GetWorkbench()->UpdateTheme(); } } QtStyleManager::Style QtStyleManager::GetDefaultStyle() const { return Style(defaultStyle->name, defaultStyle->fileName); } void QtStyleManager::SetDefaultStyle() { SetDefaultStyle(true); } void QtStyleManager::SetDefaultStyle(bool update) { SetStyle(defaultStyle->fileName, update); } bool QtStyleManager::Contains(const QString& fileName) const { return styles.contains(fileName); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStyleManager.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStyleManager.h index 902d6c58d0..333aeb94bb 100644 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStyleManager.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/berryQtStyleManager.h @@ -1,86 +1,86 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYQTSTYLEMANAGER_H_ #define BERRYQTSTYLEMANAGER_H_ -#include "../berryIQtStyleManager.h" +#include "berryIQtStyleManager.h" #include namespace berry { class QtStyleManager : public QObject, public IQtStyleManager { Q_OBJECT Q_INTERFACES(berry::IQtStyleManager) public: QtStyleManager(); ~QtStyleManager(); Style GetStyle() const; QString GetStylesheet() const; QString GetActiveTabStylesheet() const; QString GetTabStylesheet() const; void AddStyle(const QString& styleFileName, const QString& styleName = QString()); void AddStyles(const QString& path); void RemoveStyle(const QString& styleFileName); void RemoveStyles(const QString& path = QString()); void GetStyles(StyleList& styles) const; void SetStyle(const QString& fileName); Style GetDefaultStyle() const; void SetDefaultStyle(); bool Contains(const QString& fileName) const; bool IsA( const std::type_info& type ) const; const std::type_info& GetType() const; private: void AddDefaultStyle(); void ClearStyles(); void ReadPreferences(); void SetStyle(const QString& fileName, bool update); void SetDefaultStyle(bool update); struct ExtStyle : public Style { QString stylesheet; QString tabStylesheet; QString activeTabStylesheet; }; void ReadStyleData(ExtStyle* style); typedef QHash FileNameToStyleMap; FileNameToStyleMap styles; ExtStyle const* currentStyle; ExtStyle* defaultStyle; }; } #endif /* BERRYQTSTYLEMANAGER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryEmptyTabFolder.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryEmptyTabFolder.h index 6a3035114f..b3a1026274 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryEmptyTabFolder.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryEmptyTabFolder.h @@ -1,123 +1,123 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYEMPTYTABFOLDER_H_ #define BERRYEMPTYTABFOLDER_H_ -#include "../util/berryAbstractTabFolder.h" +#include "internal/util/berryAbstractTabFolder.h" namespace berry { /** * Implements the AbstractTabFolder interface, however this object only displays * the content of the currently selected part. There are no tabs, no title, no toolbar, * etc. There is no means to select a different part, unless it is done programmatically. * * @since 3.1 */ class EmptyTabFolder: public AbstractTabFolder { private: QWidget* control; QWidget* childControl; //QColor borderColor; public: EmptyTabFolder(QWidget* parent, bool showborder); /* (non-Javadoc) * @see org.blueberry.ui.internal.presentations.util.AbstractTabFolder#computeSize(int, int) */ QSize ComputeSize(int widthHint, int heightHint); /* (non-Javadoc) * @see org.blueberry.ui.internal.presentations.util.AbstractTabFolder#add(int, int) */ AbstractTabItem* Add(int index, int flags); /* (non-Javadoc) * @see org.blueberry.ui.internal.presentations.util.AbstractTabFolder#move(int, int) */ void Move(int from, int to); /* (non-Javadoc) * @see org.blueberry.ui.internal.presentations.util.AbstractTabFolder#getContentParent() */ QWidget* GetContentParent(); /* (non-Javadoc) * @see org.blueberry.ui.internal.presentations.util.AbstractTabFolder#setContent(org.blueberry.swt.widgets.Control) */ void SetContent(QWidget* newContent); /* (non-Javadoc) * @see org.blueberry.ui.internal.presentations.util.AbstractTabFolder#getItems() */ std::vector GetItems(); /* (non-Javadoc) * @see org.blueberry.ui.internal.presentations.util.AbstractTabFolder#getSelection() */ AbstractTabItem* GetSelection(); /* (non-Javadoc) * @see org.blueberry.ui.internal.presentations.util.AbstractTabFolder#setSelection(org.blueberry.ui.internal.presentations.util.AbstractTabItem) */ void SetSelection(AbstractTabItem* toSelect); // void SetToolbar(Control toolbar) { // if (toolbar != null) { // toolbar.setVisible(false); // } // } void Layout(bool flushCache); /* (non-Javadoc) * @see org.blueberry.ui.internal.presentations.util.AbstractTabFolder#setSelectedInfo(org.blueberry.ui.internal.presentations.util.PartInfo) */ void SetSelectedInfo(const PartInfo& info); /* (non-Javadoc) * @see org.blueberry.ui.internal.presentations.util.AbstractTabFolder#enablePaneMenu(boolean) */ void EnablePaneMenu(bool enabled); // /* (non-Javadoc) // * @see org.blueberry.ui.internal.presentations.util.AbstractTabFolder#getToolbarParent() // */ // Composite getToolbarParent() { // return control; // } /* (non-Javadoc) * @see org.blueberry.ui.internal.presentations.util.AbstractTabFolder#getControl() */ QWidget* GetControl(); /* (non-Javadoc) * @see org.blueberry.ui.internal.presentations.util.AbstractTabFolder#getTabArea() */ QRect GetTabArea(); }; } #endif /* BERRYEMPTYTABFOLDER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryEmptyTabItem.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryEmptyTabItem.h index 53854bb43e..f3ca3d8340 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryEmptyTabItem.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryEmptyTabItem.h @@ -1,56 +1,56 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYEMPTYTABITEM_H_ #define BERRYEMPTYTABITEM_H_ -#include "../util/berryAbstractTabItem.h" +#include "internal/util/berryAbstractTabItem.h" namespace berry { struct EmptyTabItem : public AbstractTabItem { /* (non-Javadoc) * @see AbstractTabItem#getBounds() */ QRect GetBounds(); /* (non-Javadoc) * @see AbstractTabItem#setInfo(org.blueberry.ui.internal.presentations.util.PartInfo) */ void SetInfo(const PartInfo& info); /* (non-Javadoc) * @see AbstractTabItem#Dispose() */ void Dispose(); /* (non-Javadoc) * @see org.blueberry.ui.internal.presentations.util.AbstractTabItem#getData() */ Object::Pointer GetData(); /* (non-Javadoc) * @see org.blueberry.ui.internal.presentations.util.AbstractTabItem#setData(java.lang.Object) */ void SetData(Object::Pointer data); }; } #endif /* BERRYEMPTYTABITEM_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabItem.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabItem.h index 52205d062c..c536546657 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabItem.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryNativeTabItem.h @@ -1,83 +1,83 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYNATIVETABITEM_H_ #define BERRYNATIVETABITEM_H_ -#include "../util/berryAbstractTabItem.h" +#include "internal/util/berryAbstractTabItem.h" #include class QToolButton; namespace berry { class NativeTabFolder; class NativeTabItem: public QObject, public AbstractTabItem { Q_OBJECT private: Object::Pointer data; NativeTabFolder* parent; const int style; bool showClose; QToolButton* closeButton; private slots: void CloseButtonClicked(); public: NativeTabItem(NativeTabFolder* parent, int index, int style); /* (non-Javadoc) * @see AbstractTabItem#getBounds() */ QRect GetBounds(); void SetInfo(const PartInfo& info); bool GetShowClose() const; void SetShowClose(bool close); QWidget* GetCloseButton(); void Dispose(); /* (non-Javadoc) * @see AbstractTabItem#getData() */ Object::Pointer GetData(); /* (non-Javadoc) * @see AbstractTabItem#setData(java.lang.Object) */ void SetData(Object::Pointer d); }; } #endif /* BERRYNATIVETABITEM_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQCTabBar.h b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQCTabBar.h index 5fa172ca0b..1703a4a95a 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQCTabBar.h +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQCTabBar.h @@ -1,73 +1,73 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYQCTABBAR_H_ #define BERRYQCTABBAR_H_ #include #include -#include "../util/berryAbstractTabItem.h" +#include "internal/util/berryAbstractTabItem.h" namespace berry { class QCTabBar : public QTabBar { Q_OBJECT private: // maps the index in the tabbar to the AbstractTabItem std::deque tabItemList; QPoint dragStartPosition; protected: void tabRemoved(int index); void mousePressEvent(QMouseEvent* event); void mouseMoveEvent(QMouseEvent* event); public: QCTabBar(QWidget* parent = 0); ~QCTabBar(); AbstractTabItem* getTab(int index) const; std::vector getTabs() const; /** * Inserts a new tab at the specified index. The TabBar takes * ownership of the AbstractTabItem. */ void insertTab(int index, AbstractTabItem* item); void moveAbstractTab(int from, int to); void setCurrentTab(AbstractTabItem* item); AbstractTabItem* getCurrentTab(); signals: void dragStarted(const QPoint& location); }; } #endif /* BERRYQCTABBAR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.cpp index 90b0df926d..a3f3981a54 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/defaultpresentation/berryQtWorkbenchPresentationFactory.cpp @@ -1,168 +1,168 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryQtWorkbenchPresentationFactory.h" #include "berryNativeTabFolder.h" #include "berryEmptyTabFolder.h" -#include "../util/berryPresentablePartFolder.h" -#include "../util/berryTabbedStackPresentation.h" +#include "internal/util/berryPresentablePartFolder.h" +#include "internal/util/berryTabbedStackPresentation.h" -#include "../berryQtSash.h" +#include "internal/berryQtSash.h" #include #include namespace berry { QtWorkbenchPresentationFactory::QtWorkbenchPresentationFactory() {} QtWorkbenchPresentationFactory::QtWorkbenchPresentationFactory( const QtWorkbenchPresentationFactory& other) { } StackPresentation::Pointer QtWorkbenchPresentationFactory::CreateEditorPresentation( void* parent, IStackPresentationSite::Pointer site) { NativeTabFolder* folder = new NativeTabFolder(static_cast (parent)); // /* // * Set the minimum characters to display, if the preference is something // * other than the default. This is mainly intended for RCP applications // * or for expert users (i.e., via the plug-in customization file). // * // * Bug 32789. // */ // final IPreferenceStore store = PlatformUI.getPreferenceStore(); // if (store // .contains(IWorkbenchPreferenceConstants.EDITOR_MINIMUM_CHARACTERS)) { // final int minimumCharacters = store // .getInt(IWorkbenchPreferenceConstants.EDITOR_MINIMUM_CHARACTERS); // if (minimumCharacters >= 0) { // folder.setMinimumCharacters(minimumCharacters); // } // } PresentablePartFolder* partFolder = new PresentablePartFolder(folder); StackPresentation::Pointer result(new TabbedStackPresentation(site, partFolder)); //, new StandardEditorSystemMenu(site)); // DefaultThemeListener themeListener = // new DefaultThemeListener(folder, result.getTheme()); // result.getTheme().addListener(themeListener); // // new DefaultMultiTabListener(result.getApiPreferences(), IWorkbenchPreferenceConstants.SHOW_MULTIPLE_EDITOR_TABS, folder); // // new DefaultSimpleTabListener(result.getApiPreferences(), IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS, folder); return result; } StackPresentation::Pointer QtWorkbenchPresentationFactory::CreateViewPresentation( void* parent, IStackPresentationSite::Pointer site) { NativeTabFolder* folder = new NativeTabFolder(static_cast (parent)); // final IPreferenceStore store = PlatformUI.getPreferenceStore(); // final int minimumCharacters = store // .getInt(IWorkbenchPreferenceConstants.VIEW_MINIMUM_CHARACTERS); // if (minimumCharacters >= 0) { // folder.setMinimumCharacters(minimumCharacters); // } PresentablePartFolder* partFolder = new PresentablePartFolder(folder); //folder->SetUnselectedCloseVisible(false); //folder->SetUnselectedImageVisible(true); StackPresentation::Pointer result(new TabbedStackPresentation(site, partFolder)); //, new StandardViewSystemMenu(site)); // DefaultThemeListener themeListener = // new DefaultThemeListener(folder, result.getTheme()); // result.getTheme().addListener(themeListener); // // new DefaultSimpleTabListener(result.getApiPreferences(), IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS, folder); return result; } StackPresentation::Pointer QtWorkbenchPresentationFactory::CreateStandaloneViewPresentation( void* parent, IStackPresentationSite::Pointer site, bool showTitle) { if (showTitle) { return this->CreateViewPresentation(parent, site); } EmptyTabFolder* folder = new EmptyTabFolder(static_cast (parent), true); StackPresentation::Pointer presentation(new TabbedStackPresentation(site, folder)); //, new StandardViewSystemMenu(site)); return presentation; } std::string QtWorkbenchPresentationFactory::GetId() { return "berryQtWorkbenchPresentationFactory"; } void* QtWorkbenchPresentationFactory::CreateSash(void* parent, int style) { Qt::Orientation orientation = style & SASHORIENTATION_HORIZONTAL ? Qt::Horizontal : Qt::Vertical; QWidget* sash = new QtSash(orientation, static_cast (parent)); sash->setObjectName("Sash widget"); if (orientation == Qt::Horizontal) sash->setFixedHeight(this->GetSashSize(style)); else sash->setFixedWidth(this->GetSashSize(style)); return sash; } int QtWorkbenchPresentationFactory::GetSashSize(int /*style*/) { return 3; } void QtWorkbenchPresentationFactory::UpdateTheme() { QWidgetList topLevels = QApplication::topLevelWidgets(); QListIterator topIt(topLevels); while (topIt.hasNext()) { QWidget* topWidget = topIt.next(); QList folders = topWidget->findChildren (); QListIterator i(folders); while (i.hasNext()) { i.next()->UpdateColors(); } } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPresentablePartFolder.cpp b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPresentablePartFolder.cpp index 187df577c4..104cbbd3d8 100755 --- a/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPresentablePartFolder.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui.qt/src/internal/util/berryPresentablePartFolder.cpp @@ -1,436 +1,436 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryPresentablePartFolder.h" #include "berryAbstractTabItem.h" -#include "../berryQtWidgetsTweaklet.h" +#include "internal/berryQtWidgetsTweaklet.h" #include #include #include namespace berry { PresentablePartFolder::ContentProxyListener::ContentProxyListener( PresentablePartFolder* folder) : folder(folder) { } GuiTk::IControlListener::Events::Types PresentablePartFolder::ContentProxyListener::GetEventTypes() const { return Events::MOVED & Events::RESIZED; } void PresentablePartFolder::ContentProxyListener::ControlMoved( GuiTk::ControlEvent::Pointer /*e*/) { folder->LayoutContent(); } void PresentablePartFolder::ContentProxyListener::ControlResized( GuiTk::ControlEvent::Pointer /*e*/) { } PresentablePartFolder::ShellListener::ShellListener(AbstractTabFolder* _folder) : folder(_folder) { } void PresentablePartFolder::ShellListener::ShellActivated(ShellEvent::Pointer /*e*/) { folder->ShellActive(true); } void PresentablePartFolder::ShellListener::ShellDeactivated( ShellEvent::Pointer /*e*/) { folder->ShellActive(false); } PresentablePartFolder::ChildPropertyChangeListener::ChildPropertyChangeListener( PresentablePartFolder* folder) : presentablePartFolder(folder) { } void PresentablePartFolder::ChildPropertyChangeListener::PropertyChange( Object::Pointer source, int property) { if (source.Cast () != 0) { IPresentablePart::Pointer part = source.Cast (); presentablePartFolder->ChildPropertyChanged(part, property); } } PartInfo PresentablePartFolder::tempPartInfo = PartInfo(); void PresentablePartFolder::LayoutContent() { if (current != 0) { Rectangle clientArea = DragUtil::GetDisplayBounds(contentProxy); Rectangle bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl( folder->GetControl()->parentWidget(), clientArea); current->SetBounds(bounds); } } void PresentablePartFolder::InternalRemove(IPresentablePart::Pointer toRemove) { AbstractTabItem* item = this->GetTab(toRemove); if (item != 0) { item->Dispose(); } // do not use item anymore! if (std::find(partList.begin(), partList.end(), toRemove) != partList.end()) { toRemove->RemovePropertyListener(childPropertyChangeListener); partList.remove(toRemove); } } void PresentablePartFolder::ChildPropertyChanged( IPresentablePart::Pointer part, int property) { AbstractTabItem* tab = this->GetTab(part); if (property == IPresentablePart::PROP_HIGHLIGHT_IF_BACK) { if (tab != 0 && this->GetCurrent() != part) {//Set bold if it doesn't currently have focus tab->SetBold(true); this->InitTab(tab, part); } } // else if (property == IPresentablePart::PROP_TOOLBAR) // { // if (tab != 0 && this->GetCurrent() == part) // { // folder->FlushToolbarSize(); // } // if (tab != 0) // { // this->InitTab(tab, part); // if (this->GetCurrent() == part) // { // this->Layout(true); // } // } else if (property == IPresentablePart::PROP_CONTENT_DESCRIPTION || property == IPresentablePart::PROP_PANE_MENU || property == IPresentablePart::PROP_TITLE) { if (tab != 0) { this->InitTab(tab, part); if (this->GetCurrent() == part) { this->Layout(true); } } } else if (property == IPresentablePart::PROP_PREFERRED_SIZE) { TabFolderEvent::Pointer event( new TabFolderEvent(TabFolderEvent::EVENT_PREFERRED_SIZE, tab, 0, 0)); folder->FireEvent(event); } else { if (tab != 0) this->InitTab(tab, part); } } PresentablePartFolder::~PresentablePartFolder() { Tweaklets::Get(QtWidgetsTweaklet::KEY)->GetShell(folder->GetControl())->RemoveShellListener( shellListener); for (std::list::iterator iter = partList.begin(); iter != partList.end(); ++iter) { (*iter)->RemovePropertyListener(childPropertyChangeListener); } for (QWidget* currentWidget = contentProxy; currentWidget != 0 && currentWidget != folder->GetControl()->parentWidget(); currentWidget = currentWidget->parentWidget()) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(currentWidget, contentListener); } BERRY_DEBUG << "DELETING PresentablePartFolder and contentProxy\n"; delete folder; } void PresentablePartFolder::InitTab(AbstractTabItem* item, IPresentablePart::Pointer part) { tempPartInfo.Set(part); item->SetInfo(tempPartInfo); item->SetBusy(part->IsBusy()); if (part == this->GetCurrent()) { folder->SetSelectedInfo(tempPartInfo); //TODO Pane menu //folder->EnablePaneMenu(part->GetMenu() != 0); //setToolbar(part.getToolBar()); } } PresentablePartFolder::PresentablePartFolder(AbstractTabFolder* _folder) : folder(_folder), isVisible(true), shellListener(new ShellListener(folder)), childPropertyChangeListener(new ChildPropertyChangeListener(this)) { Shell::Pointer controlShell = Tweaklets::Get(QtWidgetsTweaklet::KEY)->GetShell(folder->GetControl()); controlShell->AddShellListener(shellListener); folder->ShellActive(Tweaklets::Get(QtWidgetsTweaklet::KEY)->GetActiveShell() == controlShell); //folder.getControl().addDisposeListener(tabDisposeListener); //toolbarProxy = new ProxyControl(folder.getToolbarParent()); // NOTE: if the shape of contentProxy changes, the fix for bug 85899 in EmptyTabFolder.computeSize may need adjustment. contentListener = new ContentProxyListener(this); contentProxy = new QtControlWidget(folder->GetContentParent(), 0); contentProxy->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); //contentProxy->setVisible(false); for (QWidget* currentWidget = contentProxy; currentWidget != 0 && currentWidget != folder->GetControl()->parentWidget(); currentWidget = currentWidget->parentWidget()) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(currentWidget, contentListener); } folder->SetContent(contentProxy); } std::vector PresentablePartFolder::GetPartList() { std::vector items = folder->GetItems(); std::vector result; for (unsigned int i = 0; i < items.size(); i++) { result.push_back(this->GetPartForTab(items[i])); } return result; } void PresentablePartFolder::Insert(IPresentablePart::Pointer part, int idx) { poco_assert(folder->GetControl() != 0); if (this->GetTab(part) != 0) { if (this->IndexOf(part) != idx) this->Move(part, idx); return; } idx = std::min(idx, static_cast(folder->GetItemCount())); AbstractTabItem* item = 0; int style = 0; if (part->IsCloseable()) { style |= Constants::CLOSE; } item = folder->Add(idx, style); item->SetData(part); this->InitTab(item, part); part->AddPropertyListener(childPropertyChangeListener); partList.push_back(part); } void PresentablePartFolder::Remove(IPresentablePart::Pointer toRemove) { if (toRemove == current) { this->Select(IPresentablePart::Pointer(0)); } this->InternalRemove(toRemove); } void PresentablePartFolder::Move(IPresentablePart::Pointer part, int newIndex) { int currentIndex = this->IndexOf(part); if (currentIndex == newIndex) { return; } folder->Move(currentIndex, newIndex); //this->InternalRemove(part); //this->Insert(part, newIndex); //if (current == part) //{ // folder->SetSelection(this->GetTab(part)); //} } std::size_t PresentablePartFolder::Size() { return folder->GetItemCount(); } void PresentablePartFolder::SetBounds(const QRect& bounds) { QSize minSize = folder->ComputeSize(bounds.width(), Constants::DEFAULT); QRect newBounds(bounds); if (folder->GetState() == IStackPresentationSite::STATE_MINIMIZED && minSize.height() < bounds.height()) { newBounds.setHeight(minSize.height()); } // Set the tab folder's bounds folder->GetControl()->setGeometry(newBounds); this->Layout(false); } void PresentablePartFolder::Select(IPresentablePart::Pointer toSelect) { if (toSelect == current) { return; } if (toSelect != 0) { toSelect->SetVisible(true); } if (current != 0) { current->SetVisible(false); //setToolbar(null); } current = toSelect; AbstractTabItem* selectedItem = this->GetTab(toSelect); folder->SetSelection(selectedItem); if (selectedItem != 0) { // Determine if we need to un-bold this tab selectedItem->SetBold(false); this->InitTab(selectedItem, toSelect); } // else // { // setToolbar(null); // } this->Layout(true); } IPresentablePart::Pointer PresentablePartFolder::GetPartForTab( AbstractTabItem* tab) { if (tab == 0) { return IPresentablePart::Pointer(0); } IPresentablePart::Pointer part = tab->GetData().Cast (); return part; } AbstractTabItem* PresentablePartFolder::GetTab(IPresentablePart::Pointer part) { return folder->FindItem(part); } int PresentablePartFolder::IndexOf(IPresentablePart::Pointer part) { AbstractTabItem* item = this->GetTab(part); if (item == 0) { return -1; } return folder->IndexOf(item); } AbstractTabFolder* PresentablePartFolder::GetTabFolder() { return folder; } void PresentablePartFolder::SetVisible(bool isVisible) { this->isVisible = isVisible; this->GetTabFolder()->SetVisible(isVisible); if (isVisible) { this->Layout(true); } } void PresentablePartFolder::Layout(bool changed) { if (!isVisible) { // Don't bother with layout if we're not visible return; } // Lay out the tab folder and compute the client area folder->Layout(changed); //toolbarProxy.layout(); this->LayoutContent(); } IPresentablePart::Pointer PresentablePartFolder::GetCurrent() { return current; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/application/berryActionBarAdvisor.h b/BlueBerry/Bundles/org.blueberry.ui/src/application/berryActionBarAdvisor.h index cb0eebd99b..78f32388fe 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/application/berryActionBarAdvisor.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/application/berryActionBarAdvisor.h @@ -1,261 +1,261 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYACTIONBARADVISOR_H_ #define BERRYACTIONBARADVISOR_H_ -#include "../berryIMemento.h" -#include "../berryIWorkbenchWindow.h" +#include "berryIMemento.h" +#include "berryIWorkbenchWindow.h" #include "berryIActionBarConfigurer.h" namespace berry { /** * 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) * * @since 3.1 */ class BERRY_UI ActionBarAdvisor : public Object { public: berryObjectMacro(ActionBarAdvisor); /** * 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). */ public: static const int FILL_PROXY; /** * Bit flag for {@link #fillActionBars fillActionBars} indicating that the * operation is supposed to fill (or describe) the workbench window's menu * bar. */ public: static const int FILL_MENU_BAR; /** * Bit flag for {@link #fillActionBars fillActionBars} indicating that the * operation is supposed to fill (or describe) the workbench window's cool * bar. */ public: static const int FILL_COOL_BAR; /** * Bit flag for {@link #fillActionBars fillActionBars} indicating that the * operation is supposed to fill (or describe) the workbench window's status * line. */ public: static const int FILL_STATUS_LINE; private: IActionBarConfigurer::Pointer actionBarConfigurer; //private: Map actions = new HashMap(); /** * 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 */ public: ActionBarAdvisor(IActionBarConfigurer::Pointer configurer); /** * Returns the action bar configurer. * * @return the action bar configurer */ protected: virtual IActionBarConfigurer::Pointer GetActionBarConfigurer(); /** * 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), * 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. *

*

* 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 * 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_STATUS_LINE FILL_STATUS_LINE}, * and {@link #FILL_PROXY FILL_PROXY} */ public: virtual void FillActionBars(int flags); /** * 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. * * @param window the window containing the action bars */ protected: virtual void MakeActions(IWorkbenchWindow::Pointer 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. *

* * @param action the action to register, this cannot be null * * @see IAction#setActionDefinitionId(String) * @see #disposeAction(IAction) */ // 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); // } /** * 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 std::string& id) { // return (IAction) actions.get(id); // } /** * 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 */ protected: virtual void FillMenuBar(void* menuBar); /** * Fills the cool bar with the main toolbars for the window. *

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

* * @param coolBar the cool bar manager */ // protected: virtual void FillCoolBar(ICoolBarManager coolBar) { // // do nothing // } /** * 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 */ // protected: virtual void FillStatusLine(IStatusLineManager statusLine) { // // do nothing // } /** * 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 * @since 3.1 */ public: virtual bool SaveState(IMemento::Pointer 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 * @since 3.1 */ public: virtual bool RestoreState(IMemento::Pointer memento); }; } #endif /*BERRYACTIONBARADVISOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/application/berryIWorkbenchConfigurer.h b/BlueBerry/Bundles/org.blueberry.ui/src/application/berryIWorkbenchConfigurer.h index 7951c7e951..243ab09c71 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/application/berryIWorkbenchConfigurer.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/application/berryIWorkbenchConfigurer.h @@ -1,259 +1,259 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYIWORKBENCHCONFIGURER_H_ #define BERRYIWORKBENCHCONFIGURER_H_ #include #include -#include "../berryIWorkbench.h" +#include "berryIWorkbench.h" #include "berryIWorkbenchWindowConfigurer.h" namespace berry { /** * Interface providing special access for configuring the workbench. *

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

*

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

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

* The initial value is false. *

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

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

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

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

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

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

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

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

*

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

*

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

*

* The initial value is true. *

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

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

* * @param enabled * true if the workbench should exit when the last * window is closed, false if the window should * just be closed */ virtual void SetExitOnLastWindowClose(bool enabled) = 0; }; } #endif /*BERRYIWORKBENCHCONFIGURER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/application/berryIWorkbenchWindowConfigurer.h b/BlueBerry/Bundles/org.blueberry.ui/src/application/berryIWorkbenchWindowConfigurer.h index b088b2c567..c5234defeb 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/application/berryIWorkbenchWindowConfigurer.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/application/berryIWorkbenchWindowConfigurer.h @@ -1,375 +1,375 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYIWORKBENCHWINDOWCONFIGURER_H_ #define BERRYIWORKBENCHWINDOWCONFIGURER_H_ #include #include -#include "../berryShell.h" -#include "../berryIMemento.h" -#include "../berryPoint.h" -#include "../berryIDropTargetListener.h" +#include "berryShell.h" +#include "berryIMemento.h" +#include "berryPoint.h" +#include "berryIDropTargetListener.h" namespace berry { struct IWorkbenchConfigurer; struct IWorkbenchWindow; /** * Interface providing special access for configuring workbench windows. *

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

*

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

*

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

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

* The initial value is true. *

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

* The initial value is true. *

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

* The initial value is true. *

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

* The initial value is false. *

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

* The initial value is false. *

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

* For more details on the applicable shell style bits, see the * documentation for Shell. *

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

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

*

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

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

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

*

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

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

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

* * @return the menu bar, suitable for setting in the shell */ //virtual Menu createMenuBar(); /* * Creates the cool bar control. *

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

* * @param parent the parent composite * @return the cool bar control, suitable for laying out in the parent */ //virtual Control createCoolBarControl(Composite parent); /* * Creates the status line control. *

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

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

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

* * @param parent the parent composite * @return the page composite, suitable for laying out in the parent */ virtual void* CreatePageComposite(void* parent) = 0; /** * Saves the current state of the window using the specified memento. * * @param memento the memento in which to save the window's state * @return a status object indicating whether the save was successful * @see IWorkbenchConfigurer#RestoreWorkbenchWindow(IMemento::Pointer) */ virtual bool SaveState(IMemento::Pointer memento) = 0; }; } #endif /*BERRYIWORKBENCHWINDOWCONFIGURER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/application/berryWorkbenchAdvisor.h b/BlueBerry/Bundles/org.blueberry.ui/src/application/berryWorkbenchAdvisor.h index ef13eef5a0..453575d39e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/application/berryWorkbenchAdvisor.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/application/berryWorkbenchAdvisor.h @@ -1,412 +1,412 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWORKBENCHADVISOR_H_ #define BERRYWORKBENCHADVISOR_H_ #include -#include "../berryIMemento.h" +#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 WorkbenchAdvisor { /** * The workbench configurer. */ private: IWorkbenchConfigurer::Pointer workbenchConfigurer; /* * The workbench error handler. */ //private: AbstractStatusHandler workbenchErrorHandler; 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 std::string 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 std::string 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 std::string&) */ // public: ContributionComparator getComparatorFor(String contributionType) { // return new ContributionComparator(); // } }; } #endif /*BERRYWORKBENCHADVISOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/application/berryWorkbenchWindowAdvisor.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/application/berryWorkbenchWindowAdvisor.cpp index fcd5135b1e..d17ea59e97 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/application/berryWorkbenchWindowAdvisor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/application/berryWorkbenchWindowAdvisor.cpp @@ -1,142 +1,142 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWorkbenchWindowAdvisor.h" #include #include #include #include -#include "../internal/berryWorkbenchWindowConfigurer.h" -#include "../internal/berryWorkbenchPlugin.h" +#include "internal/berryWorkbenchWindowConfigurer.h" +#include "internal/berryWorkbenchPlugin.h" namespace berry { IWorkbenchWindowConfigurer::Pointer WorkbenchWindowAdvisor::GetWindowConfigurer() { return windowConfigurer; } WorkbenchWindowAdvisor::WorkbenchWindowAdvisor( IWorkbenchWindowConfigurer::Pointer configurer) { poco_assert(configurer.IsNotNull()); this->windowConfigurer = configurer; } WorkbenchWindowAdvisor::~WorkbenchWindowAdvisor() { } void WorkbenchWindowAdvisor::PreWindowOpen() { // do nothing } ActionBarAdvisor::Pointer WorkbenchWindowAdvisor::CreateActionBarAdvisor( IActionBarConfigurer::Pointer configurer) { ActionBarAdvisor::Pointer actionBarAdvisor(new ActionBarAdvisor(configurer)); return actionBarAdvisor; } void WorkbenchWindowAdvisor::PostWindowRestore() { // do nothing } void WorkbenchWindowAdvisor::OpenIntro() { // TODO: Refactor this into an IIntroManager.openIntro(IWorkbenchWindow) call // introOpened flag needs to be global IWorkbenchConfigurer::Pointer wbConfig = GetWindowConfigurer()->GetWorkbenchConfigurer(); std::string key = "introOpened"; //$NON-NLS-1$ ObjectBool::Pointer introOpened = wbConfig->GetData(key).Cast(); if (introOpened && introOpened->GetValue()) { return; } wbConfig->SetData(key, ObjectBool::Pointer(new ObjectBool(true))); IPreferences::Pointer workbenchPrefs = WorkbenchPlugin::GetDefault()->GetPreferencesService()->GetSystemPreferences(); bool showIntro = workbenchPrefs->GetBool(WorkbenchPreferenceConstants::SHOW_INTRO, true); IIntroManager* introManager = wbConfig->GetWorkbench()->GetIntroManager(); bool hasIntro = introManager->HasIntro(); bool isNewIntroContentAvailable = introManager->IsNewContentAvailable(); if (hasIntro && (showIntro || isNewIntroContentAvailable)) { introManager ->ShowIntro(GetWindowConfigurer()->GetWindow(), false); workbenchPrefs->PutBool(WorkbenchPreferenceConstants::SHOW_INTRO, false); workbenchPrefs->Flush(); } } void WorkbenchWindowAdvisor::PostWindowCreate() { // do nothing } void WorkbenchWindowAdvisor::PostWindowOpen() { // do nothing } bool WorkbenchWindowAdvisor::PreWindowShellClose() { // do nothing, but allow the close() to proceed return true; } void WorkbenchWindowAdvisor::PostWindowClose() { // do nothing } void WorkbenchWindowAdvisor::CreateWindowContents(Shell::Pointer shell) { this->GetWindowConfigurer().Cast()->CreateDefaultContents(shell); } void* WorkbenchWindowAdvisor::CreateEmptyWindowContents(void* /*parent*/) { return 0; } bool WorkbenchWindowAdvisor::SaveState(IMemento::Pointer /*memento*/) { // do nothing return true; } bool WorkbenchWindowAdvisor::RestoreState(IMemento::Pointer /*memento*/) { // do nothing return true; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/application/berryWorkbenchWindowAdvisor.h b/BlueBerry/Bundles/org.blueberry.ui/src/application/berryWorkbenchWindowAdvisor.h index 6db8bdb82f..06d944292e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/application/berryWorkbenchWindowAdvisor.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/application/berryWorkbenchWindowAdvisor.h @@ -1,262 +1,262 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWORKBENCHWINDOWADVISOR_H_ #define BERRYWORKBENCHWINDOWADVISOR_H_ -#include "../berryIMemento.h" -#include "../berryShell.h" +#include "berryIMemento.h" +#include "berryShell.h" #include "berryActionBarAdvisor.h" #include "berryIActionBarConfigurer.h" namespace berry { /** * Public base class for configuring a workbench window. *

* The workbench window advisor object is created in response to a workbench * window being created (one per window), and is used to configure the window. *

*

* An application should declare a subclass of WorkbenchWindowAdvisor * and override methods to configure workbench windows to suit the needs of the * particular application. *

*

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

    *
  • PreWindowOpen() - called as the window is being opened; * use to configure aspects of the window other than actions bars
  • *
  • PostWindowRestore() - called after the window has been * recreated from a previously saved state; use to adjust the restored * window
  • *
  • PostWindowCreate() - called after the window has been created, * either from an initial state or from a restored state; used to adjust the * window
  • *
  • OpenIntro() - called immediately before the window is opened in * order to create the introduction component, if any.
  • *
  • PostWindowOpen() - called after the window has been * opened; use to hook window listeners, etc.
  • *
  • PreWindowShellClose() - called when the window's shell * is closed by the user; use to pre-screen window closings
  • *
*

* */ class BERRY_UI WorkbenchWindowAdvisor { private: IWorkbenchWindowConfigurer::Pointer windowConfigurer; protected: /** * Returns the workbench window configurer. * * @return the workbench window configurer */ IWorkbenchWindowConfigurer::Pointer GetWindowConfigurer(); public: /** * Creates a new workbench window advisor for configuring a workbench * window via the given workbench window configurer. * * @param configurer an object for configuring the workbench window */ WorkbenchWindowAdvisor(IWorkbenchWindowConfigurer::Pointer configurer); virtual ~WorkbenchWindowAdvisor(); /** * Performs arbitrary actions before the window is opened. *

* This method is called before the window's controls have been created. * 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 window configurer to tweak the * workbench window in an application-specific way; however, filling the * window's menu bar, tool bar, and status line must be done in * ActionBarAdvisor#FillActionBars(), which is called immediately * after this method is called. *

*/ virtual void PreWindowOpen(); /** * Creates a new action bar advisor to configure the action bars of the window * via the given action bar configurer. * The default implementation returns a new instance of ActionBarAdvisor. * * @param configurer the action bar configurer for the window * @return the action bar advisor for the window */ virtual ActionBarAdvisor::Pointer CreateActionBarAdvisor( IActionBarConfigurer::Pointer configurer); /** * Performs arbitrary actions after the window has been restored, * but before it is opened. *

* This method is called after a previously-saved window has been * recreated. This method is not called when a new window is created from * scratch. This method is never called when a workbench is started for the * very first time, or when workbench state is not saved or restored. * 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. *

* * @exception WorkbenchException thrown if there are any errors to report * from post-restoration of the window */ virtual void PostWindowRestore(); /** * Opens the introduction componenet. *

* Clients must not call this method directly (although super calls are okay). * The default implementation opens the intro in the first window provided * if the preference WorkbenchPreferenceConstants#SHOW_INTRO is true. If * an intro is shown then this preference will be set to false. * Subsequently, and intro will be shown only if * WorkbenchConfigurer#GetSaveAndRestore() returns * true and the introduction was visible on last shutdown. * Subclasses may override. *

*/ virtual void OpenIntro(); /** * Performs arbitrary actions after the window has been created (possibly * after being restored), but has not yet been opened. *

* This method is called after the window has been created from scratch, * or when it has been restored from a previously-saved window. In the latter case, * this method is called after PostWindowRestore(). * Clients must not call this method directly (although super calls are okay). * The default implementation does nothing. Subclasses may override. *

*/ virtual void PostWindowCreate(); /** * Performs arbitrary actions after the window has been opened (possibly * after being restored). *

* This method is called after the window has been opened. This method is * called after the window has been created from scratch, or when * it has been restored from a previously-saved window. * Clients must not call this method directly (although super calls are okay). * The default implementation does nothing. Subclasses may override. *

*/ virtual void PostWindowOpen(); /** * Performs arbitrary actions as the window's shell is being closed * directly, and possibly veto the close. *

* This method is called from a IShellListener associated with the window, * for example when the user clicks the window's close button. It is not * called when the window is being closed for other reasons, such as if the * user exits the workbench via the ActionFactory#QUIT action. * Clients must not call this method directly (although super calls are * okay). If this method returns false, then the user's * request to close the shell is ignored. This gives the workbench advisor * an opportunity to query the user and/or veto the closing of a window * under some circumstances. *

* * @return true to allow the window to close, and * false to prevent the window from closing * @see IWorkbenchWindow#Close() * @see WorkbenchAdvisor#PreShutdown() */ virtual bool PreWindowShellClose(); /** * Performs arbitrary actions after the window is closed. *

* This method is called after the window's controls have been disposed. * Clients must not call this method directly (although super calls are * okay). The default implementation does nothing. Subclasses may override. *

*/ virtual void PostWindowClose(); /** * Creates the contents of the window. *

* The default implementation adds a menu bar, a cool bar, a status line, * a perspective bar, and a fast view bar. The visibility of these controls * can be configured using the SetShow* methods on * IWorkbenchWindowConfigurer. *

*

* Subclasses may override to define custom window contents and layout, * but must call IWorkbenchWindowConfigurer#CreatePageComposite(). *

* * @param shell the window's shell * @see IWorkbenchWindowConfigurer#CreateMenuBar() * @see IWorkbenchWindowConfigurer#CreateCoolBarControl() * @see IWorkbenchWindowConfigurer#CreateStatusLineControl() * @see IWorkbenchWindowConfigurer#CreatePageComposite() */ virtual void CreateWindowContents(Shell::Pointer shell); /** * Creates and returns the control to be shown when the window has no open pages. * If null is returned, the default window background is shown. *

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

* * @param parent the parent composite * @return the control or null */ virtual void* CreateEmptyWindowContents(void* parent); /** * Saves arbitrary application specific state information. * * @param memento the storage area for object's state * @return a status object indicating whether the save was successful */ virtual bool SaveState(IMemento::Pointer memento); /** * Restores arbitrary application specific state information. * * @param memento the storage area for object's state * @return a status object indicating whether the restore was successful */ virtual bool RestoreState(IMemento::Pointer memento); }; } #endif /*BERRYWORKBENCHWINDOWADVISOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryIShowViewDialog.h b/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryIShowViewDialog.h index 98e1d4f21a..bf53b659c8 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryIShowViewDialog.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryIShowViewDialog.h @@ -1,43 +1,43 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYISHOWVIEWDIALOG_H_ #define BERRYISHOWVIEWDIALOG_H_ #include "berryIDialog.h" #include -#include "../berryIViewDescriptor.h" +#include "berryIViewDescriptor.h" namespace berry { /** * \ingroup org_blueberry_ui * */ struct BERRY_UI IShowViewDialog : public IDialog { berryInterfaceMacro(IShowViewDialog, berry); virtual std::vector GetSelection() = 0; }; } #endif /*BERRYISHOWVIEWDIALOG_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryMessageDialog.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryMessageDialog.cpp index 2d8e08e7ae..42c93d72f8 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryMessageDialog.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryMessageDialog.cpp @@ -1,68 +1,68 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#include "../tweaklets/berryMessageDialogTweaklet.h" +#include "tweaklets/berryMessageDialogTweaklet.h" #include "berryMessageDialog.h" namespace berry { bool MessageDialog::OpenConfirm(Shell::Pointer parent, const std::string& title, const std::string& message) { return Tweaklets::Get(MessageDialogTweaklet::KEY)->OpenConfirm(parent, title, message); } void MessageDialog::OpenError(Shell::Pointer parent, const std::string& title, const std::string& message) { Tweaklets::Get(MessageDialogTweaklet::KEY)->OpenError(parent, title, message); } void MessageDialog::OpenInformation(Shell::Pointer parent, const std::string& title, const std::string& message) { Tweaklets::Get(MessageDialogTweaklet::KEY)->OpenInformation(parent, title, message); } bool MessageDialog::OpenQuestion(Shell::Pointer parent, const std::string& title, const std::string& message) { return Tweaklets::Get(MessageDialogTweaklet::KEY)->OpenQuestion(parent, title, message); } void MessageDialog::OpenWarning(Shell::Pointer parent, const std::string& title, const std::string& message) { Tweaklets::Get(MessageDialogTweaklet::KEY)->OpenWarning(parent, title, message); } IDialog::Pointer MessageDialog::CreateMessageDialog(Shell::Pointer parentShell, const std::string& dialogTitle, void* dialogTitleImage, const std::string& dialogMessage, int dialogImageType, const std::vector& dialogButtonLabels, int defaultIndex) { return Tweaklets::Get(MessageDialogTweaklet::KEY)->MessageDialog(parentShell, dialogTitle, dialogTitleImage, dialogMessage, dialogImageType, dialogButtonLabels, defaultIndex); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryMessageDialog.h b/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryMessageDialog.h index b89cae5455..d1e92b49f0 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryMessageDialog.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/dialogs/berryMessageDialog.h @@ -1,148 +1,148 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYMESSAGEDIALOG_H_ #define BERRYMESSAGEDIALOG_H_ #include "berryIDialog.h" -#include "../berryShell.h" +#include "berryShell.h" #include #include namespace berry { struct MessageDialog { /** * Convenience method to open a simple confirm (OK/Cancel) dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message * @return true if the user presses the OK button, * false otherwise */ static bool OpenConfirm(Shell::Pointer parent, const std::string& title, const std::string& message); /** * Convenience method to open a standard error dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message */ static void OpenError(Shell::Pointer parent, const std::string& title, const std::string& message); /** * Convenience method to open a standard information dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message */ static void OpenInformation(Shell::Pointer parent, const std::string& title, const std::string& message); /** * Convenience method to open a simple Yes/No question dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message * @return true if the user presses the OK button, * false otherwise */ static bool OpenQuestion(Shell::Pointer parent, const std::string& title, const std::string& message); /** * Convenience method to open a standard warning dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message */ static void OpenWarning(Shell::Pointer parent, const std::string& title, const std::string& message); /** * Create a message dialog. Note that the dialog will have no visual * representation (no widgets) until it is told to open. *

* The labels of the buttons to appear in the button bar are supplied in * this constructor as an array. The open method will return * the index of the label in this array corresponding to the button that was * pressed to close the dialog. If the dialog was dismissed without pressing * a button (ESC, etc.) then -1 is returned. Note that the open * method blocks. *

* * @param parentShell * the parent shell * @param dialogTitle * the dialog title, or null if none * @param dialogTitleImage * the dialog title image, or null if none * @param dialogMessage * the dialog message * @param dialogImageType * one of the following values: *
    *
  • IDialog::NONE for a dialog with no * image
  • *
  • IDialog::ERR for a dialog with an * error image
  • *
  • IDialog::INFORMATION for a dialog * with an information image
  • *
  • IDialog::QUESTION for a dialog with a * question image
  • *
  • IDialog::WARNING for a dialog with a * warning image
  • *
* @param dialogButtonLabels * an array of labels for the buttons in the button bar * @param defaultIndex * the index in the button label array of the default button */ static IDialog::Pointer CreateMessageDialog(Shell::Pointer parentShell, const std::string& dialogTitle, void* dialogTitleImage, const std::string& dialogMessage, int dialogImageType, const std::vector& dialogButtonLabels, int defaultIndex); }; } #endif /* BERRYMESSAGEDIALOG_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryHandlerUtil.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryHandlerUtil.cpp index 8605b050f4..ab809923f3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryHandlerUtil.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryHandlerUtil.cpp @@ -1,349 +1,349 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryHandlerUtil.h" #include #include -#include "../berryISources.h" +#include "berryISources.h" namespace berry { void HandlerUtil::NoVariableFound(ExecutionEvent::Pointer event, const std::string& name) { throw ExecutionException("No " + name //$NON-NLS-1$ + " found while executing " + event->GetCommand()->GetId()); //$NON-NLS-1$ } void HandlerUtil::IncorrectTypeFound(ExecutionEvent::Pointer event, const std::string& name, const std::string& expectedType, const std::string& wrongType) { throw ExecutionException("Incorrect type for " //$NON-NLS-1$ + name + " found while executing " //$NON-NLS-1$ + event->GetCommand()->GetId() + ", expected " + expectedType //$NON-NLS-1$ + " found " + wrongType); //$NON-NLS-1$ } Object::Pointer HandlerUtil::GetVariable( ExecutionEvent::Pointer event, const std::string& name) { return event->GetApplicationContext().Cast()->GetVariable(name); } Object::Pointer HandlerUtil::GetVariableChecked( ExecutionEvent::Pointer event, const std::string& name) { Object::Pointer o(HandlerUtil::GetVariable(event, name)); if (o.IsNull()) { HandlerUtil::NoVariableFound(event, name); } return o; } Object::Pointer HandlerUtil::GetVariable( Object::Pointer context, const std::string& name) { IEvaluationContext::Pointer eval(context.Cast()); if (eval.IsNotNull()) { return eval->GetVariable(name); } return Object::Pointer(0); } HandlerUtil::StringVectorType::Pointer HandlerUtil::GetActiveContexts( ExecutionEvent::Pointer event) { Object::Pointer o(HandlerUtil::GetVariable(event, ISources::ACTIVE_CONTEXT_NAME())); return o.Cast(); } HandlerUtil::StringVectorType::Pointer HandlerUtil::GetActiveContextsChecked( ExecutionEvent::Pointer event) { Object::Pointer 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(ExecutionEvent::Pointer event) //{ // Object::Pointer o(HandlerUtil::GetVariable(event, // ISources::ACTIVE_EDITOR_NAME)); // return o.Cast(); //} //IEditorPart::Pointer HandlerUtil::GetActiveEditorChecked( // ExecutionEvent::Pointer event) //{ // Object::Pointer o = HandlerUtil::GetVariableChecked(event, // ISources::ACTIVE_EDITOR_NAME); // if (o.Cast().IsNull()) // { // HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_EDITOR_NAME, // "IEditorPart", o->GetClassName()); // } // return (IEditorPart) o; //} ObjectString::Pointer HandlerUtil::GetActiveEditorId(ExecutionEvent::Pointer event) { Object::Pointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_EDITOR_ID_NAME()); return o.Cast(); } ObjectString::Pointer HandlerUtil::GetActiveEditorIdChecked( ExecutionEvent::Pointer event) { Object::Pointer o = HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_EDITOR_ID_NAME()); if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_EDITOR_ID_NAME(), "std::string", o->GetClassName()); } return o.Cast(); } IWorkbenchPart::Pointer HandlerUtil::GetActivePart(ExecutionEvent::Pointer event) { Object::Pointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_PART_NAME()); return o.Cast(); } IWorkbenchPart::Pointer HandlerUtil::GetActivePartChecked( ExecutionEvent::Pointer event) { Object::Pointer 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(); } ObjectString::Pointer HandlerUtil::GetActivePartId(ExecutionEvent::Pointer event) { Object::Pointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_PART_ID_NAME()); return o.Cast(); } ObjectString::Pointer HandlerUtil::GetActivePartIdChecked( ExecutionEvent::Pointer event) { Object::Pointer o = HandlerUtil::GetVariableChecked(event, ISources::ACTIVE_PART_ID_NAME()); if (o.Cast().IsNull()) { HandlerUtil::IncorrectTypeFound(event, ISources::ACTIVE_PART_ID_NAME(), "std::string", o->GetClassName()); } return o.Cast(); } IWorkbenchPartSite::Pointer HandlerUtil::GetActiveSite( ExecutionEvent::Pointer event) { Object::Pointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_SITE_NAME()); return o.Cast(); } IWorkbenchPartSite::Pointer HandlerUtil::GetActiveSiteChecked( ExecutionEvent::Pointer event) { Object::Pointer 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(); } ISelection::Pointer HandlerUtil::GetCurrentSelection( ExecutionEvent::Pointer event) { Object::Pointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_CURRENT_SELECTION_NAME()); return o.Cast(); } ISelection::Pointer HandlerUtil::GetCurrentSelectionChecked( ExecutionEvent::Pointer event) { Object::Pointer 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::Pointer HandlerUtil::GetActiveMenus( ExecutionEvent::Pointer event) { Object::Pointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_MENU_NAME()); return o.Cast(); } HandlerUtil::StringVectorType::Pointer HandlerUtil::GetActiveMenusChecked( ExecutionEvent::Pointer event) { Object::Pointer 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::Pointer HandlerUtil::GetActiveMenuSelection( ExecutionEvent::Pointer event) { Object::Pointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_MENU_SELECTION_NAME()); return o.Cast(); } ISelection::Pointer HandlerUtil::GetActiveMenuSelectionChecked( ExecutionEvent::Pointer event) { Object::Pointer 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::Pointer HandlerUtil::GetActiveWorkbenchWindow( ExecutionEvent::Pointer event) { Object::Pointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_WORKBENCH_WINDOW_NAME()); return o.Cast(); } IWorkbenchWindow::Pointer HandlerUtil::GetActiveWorkbenchWindowChecked( ExecutionEvent::Pointer event) { Object::Pointer 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(); } ISelection::Pointer HandlerUtil::GetActiveMenuEditorInput( ExecutionEvent::Pointer event) { Object::Pointer o = HandlerUtil::GetVariable(event, ISources::ACTIVE_MENU_EDITOR_INPUT_NAME()); return o.Cast(); } ISelection::Pointer HandlerUtil::GetActiveMenuEditorInputChecked( ExecutionEvent::Pointer event) { Object::Pointer 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::Pointer HandlerUtil::GetShowInSelection( ExecutionEvent::Pointer event) { Object::Pointer o = HandlerUtil::GetVariable(event, ISources::SHOW_IN_SELECTION()); return o.Cast(); } ISelection::Pointer HandlerUtil::GetShowInSelectionChecked( ExecutionEvent::Pointer event) { Object::Pointer 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::Pointer HandlerUtil::GetShowInInput( ExecutionEvent::Pointer event) { Object::Pointer var = HandlerUtil::GetVariable(event, ISources::SHOW_IN_INPUT()); // if (var == IEvaluationContext.UNDEFINED_VARIABLE) { // return null; // } return var; } Object::Pointer HandlerUtil::GetShowInInputChecked( ExecutionEvent::Pointer event) { Object::Pointer 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; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryHandlerUtil.h b/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryHandlerUtil.h index 7cd0bd2fee..00ac94261c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryHandlerUtil.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryHandlerUtil.h @@ -1,411 +1,411 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYHANDLERUTIL_H_ #define BERRYHANDLERUTIL_H_ #include #include #include #include -#include "../berryIWorkbenchPart.h" -#include "../berryIWorkbenchPartSite.h" -#include "../berryISelection.h" -#include "../berryIWorkbenchWindow.h" +#include "berryIWorkbenchPart.h" +#include "berryIWorkbenchPartSite.h" +#include "berryISelection.h" +#include "berryIWorkbenchWindow.h" -#include "../berryISources.h" +#include "berryISources.h" namespace berry { /** * \ingroup org_blueberry_ui * * 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 HandlerUtil { private: static void NoVariableFound(ExecutionEvent::Pointer event, const std::string& name); static void IncorrectTypeFound(ExecutionEvent::Pointer event, const std::string& name, const std::string& expectedType, const std::string& wrongType); public: typedef ObjectVector StringVectorType; /** * Extract the variable. * * @param event * The execution event that contains the application context * @param name * The variable name to extract. * @return The object from the application context, or null * if it could not be found. */ static Object::Pointer GetVariable(ExecutionEvent::Pointer event, const std::string& name); /** * Extract the variable. * * @param event * The execution event that contains the application context * @param name * The variable name to extract. * @return The object from the application context. Will not return * null. * @throws ExecutionException * if the variable is not found. */ static Object::Pointer GetVariableChecked(ExecutionEvent::Pointer event, const std::string& 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. * @since 3.4 */ static Object::Pointer GetVariable(Object::Pointer context, const std::string& name); /** * Return the active contexts. * * @param event * The execution event that contains the application context * @return a collection of String contextIds, or null. */ static StringVectorType::Pointer GetActiveContexts(ExecutionEvent::Pointer event); /** * Return the active contexts. * * @param event * The execution event that contains the application context * @return a collection of String contextIds. Will not return * null. * @throws ExecutionException * If the context variable is not found. */ static StringVectorType::Pointer GetActiveContextsChecked(ExecutionEvent::Pointer event); /** * Return the active shell. Is not necessarily the active workbench window * shell. * * @param event * The execution event that contains the application context * @return the active shell, or null. */ // static Shell GetActiveShell(ExecutionEvent::Pointer event) { // Object::Pointer o = getVariable(event, ISources.ACTIVE_SHELL_NAME); // if (o instanceof Shell) { // return (Shell) o; // } // return null; // } /** * Return the active shell. Is not necessarily the active workbench window * shell. * * @param event * The execution event that contains the application context * @return the active shell. Will not return null. * @throws ExecutionException * If the active shell variable is not found. */ // static Shell GetActiveShellChecked(ExecutionEvent::Pointer event) // { // Object::Pointer o = getVariableChecked(event, ISources.ACTIVE_SHELL_NAME); // if (!(o instanceof Shell)) { // incorrectTypeFound(event, ISources.ACTIVE_SHELL_NAME, Shell.class, // o.getClass()); // } // return (Shell) o; // } /** * Return the active workbench window. * * @param event * The execution event that contains the application context * @return the active workbench window, or null. */ static IWorkbenchWindow::Pointer GetActiveWorkbenchWindow(ExecutionEvent::Pointer event); /** * Return the active workbench window. * * @param event * The execution event that contains the application context * @return the active workbench window. Will not return null. * @throws ExecutionException * If the active workbench window variable is not found. */ static IWorkbenchWindow::Pointer GetActiveWorkbenchWindowChecked( ExecutionEvent::Pointer event); /** * Return the active editor. * * @param event * The execution event that contains the application context * @return the active editor, or null. */ //static IEditorPart::Pointer GetActiveEditor(ExecutionEvent::Pointer event); /** * Return the active editor. * * @param event * The execution event that contains the application context * @return the active editor. Will not return null. * @throws ExecutionException * If the active editor variable is not found. */ //static IEditorPart::Pointer GetActiveEditorChecked(ExecutionEvent::Pointer event); /** * Return the part id of the active editor. * * @param event * The execution event that contains the application context * @return the part id of the active editor, or null. */ static ObjectString::Pointer GetActiveEditorId(ExecutionEvent::Pointer event); /** * Return the part id of the active editor. * * @param event * The execution event that contains the application context * @return the part id of the active editor. Will not return * null. * @throws ExecutionException * If the active editor id variable is not found. */ static ObjectString::Pointer GetActiveEditorIdChecked(ExecutionEvent::Pointer event); /** * Return the active part. * * @param event * The execution event that contains the application context * @return the active part, or null. */ static IWorkbenchPart::Pointer GetActivePart(ExecutionEvent::Pointer event); /** * Return the active part. * * @param event * The execution event that contains the application context * @return the active part. Will not return null. * @throws ExecutionException * If the active part variable is not found. */ static IWorkbenchPart::Pointer GetActivePartChecked(ExecutionEvent::Pointer event); /** * Return the part id of the active part. * * @param event * The execution event that contains the application context * @return the part id of the active part, or null. */ static ObjectString::Pointer GetActivePartId(ExecutionEvent::Pointer event); /** * Return the part id of the active part. * * @param event * The execution event that contains the application context * @return the part id of the active part. Will not return null. * @throws ExecutionException * If the active part id variable is not found. */ static ObjectString::Pointer GetActivePartIdChecked(ExecutionEvent::Pointer event); /** * Return the active part site. * * @param event * The execution event that contains the application context * @return the active part site, or null. */ static IWorkbenchPartSite::Pointer GetActiveSite(ExecutionEvent::Pointer event); /** * Return the active part site. * * @param event * The execution event that contains the application context * @return the active part site. Will not return null. * @throws ExecutionException * If the active part site variable is not found. */ static IWorkbenchPartSite::Pointer GetActiveSiteChecked(ExecutionEvent::Pointer event); /** * Return the current selection. * * @param event * The execution event that contains the application context * @return the current selection, or null. */ static ISelection::Pointer GetCurrentSelection(ExecutionEvent::Pointer event); /** * Return the current selection. * * @param event * The execution event that contains the application context * @return the current selection. Will not return null. * @throws ExecutionException * If the current selection variable is not found. */ static ISelection::Pointer GetCurrentSelectionChecked(ExecutionEvent::Pointer event); /** * Return the menu IDs that were applied to the registered context menu. For * example, #CompilationUnitEditorContext. * * @param event * The execution event that contains the application context * @return the menu IDs, or null. */ static StringVectorType::Pointer GetActiveMenus(ExecutionEvent::Pointer event); /** * Return the menu IDs that were applied to the registered context menu. For * example, #CompilationUnitEditorContext. * * @param event * The execution event that contains the application context * @return the menu IDs. Will not return null. * @throws ExecutionException * If the active menus variable is not found. */ static StringVectorType::Pointer GetActiveMenusChecked(ExecutionEvent::Pointer event); /** * Return the active menu selection. The active menu is a registered context * menu. * * @param event * The execution event that contains the application context * @return the active menu selection, or null. */ static ISelection::Pointer GetActiveMenuSelection(ExecutionEvent::Pointer event); /** * Return the active menu selection. The active menu is a registered context * menu. * * @param event * The execution event that contains the application context * @return the active menu selection. Will not return null. * @throws ExecutionException * If the active menu selection variable is not found. */ static ISelection::Pointer GetActiveMenuSelectionChecked(ExecutionEvent::Pointer event); /** * Return the active menu editor input, if available. The active menu is a * registered context menu. * * @param event * The execution event that contains the application context * @return the active menu editor, or null. */ static ISelection::Pointer GetActiveMenuEditorInput(ExecutionEvent::Pointer event); /** * Return the active menu editor input. The active menu is a registered * context menu. Some context menus do not include the editor input which * will throw an exception. * * @param event * The execution event that contains the application context * @return the active menu editor input. Will not return null. * @throws ExecutionException * If the active menu editor input variable is not found. */ static ISelection::Pointer GetActiveMenuEditorInputChecked( ExecutionEvent::Pointer event); /** * Return the ShowInContext selection. * * @param event * The execution event that contains the application context * @return the show in selection, or null. * @since 3.4 */ static ISelection::Pointer GetShowInSelection(ExecutionEvent::Pointer 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. * @since 3.4 */ static ISelection::Pointer GetShowInSelectionChecked(ExecutionEvent::Pointer event); /** * Return the ShowInContext input. * * @param event * The execution event that contains the application context * @return the show in input, or null. * @since 3.4 */ static Object::Pointer GetShowInInput(ExecutionEvent::Pointer 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. * @since 3.4 */ static Object::Pointer GetShowInInputChecked(ExecutionEvent::Pointer event); }; } #endif /*BERRYHANDLERUTIL_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryIHandlerActivation.h b/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryIHandlerActivation.h index eb26011428..9f61e9a4e0 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryIHandlerActivation.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryIHandlerActivation.h @@ -1,121 +1,121 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYIHANDLERACTIVATION_H_ #define BERRYIHANDLERACTIVATION_H_ -#include "../internal/berryIEvaluationResultCache.h" +#include "internal/berryIEvaluationResultCache.h" #include namespace berry { struct IHandler; struct IHandlerService; /** *

* A token representing the activation of a handler. This token can later be * used to cancel that activation. Without this token, then handler will only * become inactive if the component in which the handler was activated is * destroyed. *

*

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

* * @since 3.1 * @see org.eclipse.ui.ISources * @see org.eclipse.ui.ISourceProvider */ struct BERRY_UI IHandlerActivation : public IEvaluationResultCache { berryInterfaceMacro(IHandlerActivation, berry) /** * The depth at which the root exists. * * @since 3.2 */ static const int ROOT_DEPTH; // = 1; /** * Clears the cached computation of the isActive method, if * any. This method is only intended for internal use. It provides a * mechanism by which ISourceProvider events can invalidate * state on a IHandlerActivation instance. * * @deprecated Use {@link IEvaluationResultCache#clearResult()} instead. */ virtual void ClearActive() = 0; /** * Returns the identifier of the command whose handler is being activated. * * @return The command identifier; never null. */ virtual std::string GetCommandId() const = 0; /** * Returns the depth at which this activation was created within the * services hierarchy. The root of the hierarchy is at a depth of * 1. This is used as the final tie-breaker in the event * that no other method can be used to determine a winner. * * @return The depth at which the handler was inserted into the services * hierarchy; should be a positive integer. * @since 3.2 */ virtual int GetDepth() const = 0; /** * Returns the handler that should be activated. * * @return The handler; may be null. */ virtual SmartPointer GetHandler() const = 0; /** * Returns the handler service from which this activation was requested. * This is used to ensure that an activation can only be retracted from the * same service which issued it. * * @return The handler service; never null. */ virtual SmartPointer GetHandlerService() const = 0; /** * Returns whether this handler activation is currently active -- given the * current state of the workbench. This method should cache its computation. * The cache will be cleared by a call to clearActive. * * @param context * The context in which this state should be evaluated; must not * be null. * @return true if the activation is currently active; * false otherwise. * @deprecated Use * {@link IEvaluationResultCache#evaluate(IEvaluationContext)} * instead. */ virtual bool IsActive(SmartPointer context) const = 0; }; } #endif /* BERRYIHANDLERACTIVATION_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryIHandlerService.h b/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryIHandlerService.h index 0c9b795a9e..b2f260b3d8 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryIHandlerService.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryIHandlerService.h @@ -1,432 +1,432 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYIHANDLERSERVICE_H_ #define BERRYIHANDLERSERVICE_H_ -#include "../services/berryIServiceWithSources.h" +#include "services/berryIServiceWithSources.h" -#include "../common/berryCommandExceptions.h" +#include "common/berryCommandExceptions.h" namespace berry { class Command; class ExecutionEvent; class ParameterizedCommand; class Expression; class UIElement; struct IHandler; struct IHandlerActivation; /** *

* Provides services related to activating and deactivating handlers within the * workbench. *

*

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

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

* @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. * * @since 3.1 */ struct BERRY_UI IHandlerService : public IServiceWithSources { berryInterfaceMacro(IHandlerService, berry) /** *

* Activates the given handler from a child service. This is used by slave * and nested services to promote handler activations up to the root. By * using this method, it is possible for handlers coming from a more nested * component to override the nested component. *

* * @param activation * The activation that is local to the child service; must not be * null. * @return A token which can be used to later cancel the activation. Only * someone with access to this token can cancel the activation. The * activation will automatically be cancelled if the service locator * context from which this service was retrieved is destroyed. This * activation is local to this service (i.e., it is not the * activation that is passed as a parameter). * @since 3.2 */ virtual SmartPointer ActivateHandler(SmartPointer activation) = 0; /** *

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

*

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

* * @param commandId * The identifier for the command which this handler handles; * must not be null. * @param handler * The handler to activate; must not be null. * @return A token which can be used to later cancel the activation. Only * someone with access to this token can cancel the activation. The * activation will automatically be cancelled if the context from * which this service was retrieved is destroyed. */ virtual SmartPointer ActivateHandler( const std::string& commandId, SmartPointer handler) = 0; /** *

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

*

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

* * @param commandId * The identifier for the command which this handler handles; * must not be null. * @param handler * The handler to activate; must not be null. * @param expression * This expression must evaluate to true before * this handler will really become active. The expression may be * null if the handler should always be active. * @return A token which can be used to later cancel the activation. Only * someone with access to this token can cancel the activation. The * activation will automatically be cancelled if the context from * which this service was retrieved is destroyed. * * @see org.eclipse.ui.ISources * @since 3.2 */ virtual SmartPointer ActivateHandler( const std::string& commandId, SmartPointer handler, SmartPointer expression) = 0; /** *

* Activates the given handler within the context of this service. The * handler becomes active when expression evaluates to * true. if global==false, then this * handler service must also be the active service to active the handler. * For example, the handler service on a part is active when that part is * active. *

*

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

* * @param commandId * The identifier for the command which this handler handles; * must not be null. * @param handler * The handler to activate; must not be null. * @param expression * This expression must evaluate to true before * this handler will really become active. The expression may be * null if the handler should always be active. * @param global * Indicates that the handler should be activated irrespectively * of whether the corresponding workbench component (e.g., * window, part, etc.) is active. * @return A token which can be used to later cancel the activation. Only * someone with access to this token can cancel the activation. The * activation will automatically be cancelled if the context from * which this service was retrieved is destroyed. * * @see org.eclipse.ui.ISources * @since 3.2 */ virtual SmartPointer ActivateHandler(const std::string& commandId, SmartPointer handler, SmartPointer expression, bool global) = 0; /** *

* Activates the given handler within the context of this service. The * handler becomes active when expression evaluates to * true. *

*

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

* * @param commandId * The identifier for the command which this handler handles; * must not be null. * @param handler * The handler to activate; must not be null. * @param expression * This expression must evaluate to true before * this handler will really become active. The expression may be * null if the handler should always be active. * @param sourcePriorities * The source priorities for the expression. * @return A token which can be used to later cancel the activation. Only * someone with access to this token can cancel the activation. The * activation will automatically be cancelled if the context from * which this service was retrieved is destroyed. * * @see org.eclipse.ui.ISources * @deprecated Use * {@link IHandlerService#activateHandler(String, IHandler, Expression)} * instead. */ virtual SmartPointer ActivateHandler(const std::string& commandId, SmartPointer handler, SmartPointer expression, int sourcePriorities) = 0; /** * Creates an execution event based on an SWT event. This execution event * can then be passed to a command for execution. * * @param command * The command for which an execution event should be created; * must not be null. * @param event * The SWT event triggering the command execution; may be * null. * @return An execution event suitable for calling * {@link Command#executeWithChecks(ExecutionEvent)}. * @since 3.2 * @see Command#executeWithChecks(ExecutionEvent) */ virtual SmartPointer CreateExecutionEvent( SmartPointer command, SmartPointer uielement) = 0; /** * Creates a parameterized execution event based on an SWT event and a * parameterized command. This execution event can then be passed to a * command for execution. * * @param command * The parameterized command for which an execution event should * be created; must not be null. * @param event * The SWT event triggering the command execution; may be * null. * @return An execution event suitable for calling * {@link Command#executeWithChecks(ExecutionEvent)}. * @since 3.2 * @see ParameterizedCommand#getCommand() * @see Command#executeWithChecks(ExecutionEvent) */ virtual SmartPointer CreateExecutionEvent( SmartPointer command, SmartPointer uielement) = 0; /** * Deactivates the given handler within the context of this service. If the * handler was activated with a different service, then it must be * deactivated from that service instead. It is only possible to retract a * handler activation with this method. That is, you must have the same * IHandlerActivation used to activate the handler. * * @param activation * The token that was returned from a call to * activateHandler; must not be null. */ virtual void DeactivateHandler(SmartPointer activation) = 0; /** * Deactivates the given handlers within the context of this service. If the * handler was activated with a different service, then it must be * deactivated from that service instead. It is only possible to retract a * handler activation with this method. That is, you must have the same * IHandlerActivation used to activate the handler. * * @param activations * The tokens that were returned from a call to * activateHandler. This collection must only * contain instances of IHandlerActivation. The * collection must not be null. */ virtual void DeactivateHandlers( const std::vector >& activations) = 0; /** * Executes the command with the given identifier and no parameters. * * @param commandId * The identifier of the command to execute; must not be * null. * @param event * The SWT event triggering the command execution; may be * null. * @return The return value from the execution; may be null. * @throws ExecutionException * If the handler has problems executing this command. * @throws NotDefinedException * If the command you are trying to execute is not defined. * @throws NotEnabledException * If the command you are trying to execute is not enabled. * @throws NotHandledException * If there is no handler. * @since 3.2 * @see Command#executeWithChecks(ExecutionEvent) */ virtual Object::Pointer ExecuteCommand(const std::string& commandId, SmartPointer uielement) throw(ExecutionException, NotDefinedException, NotEnabledException, NotHandledException) = 0; /** * Executes the given parameterized command. * * @param command * The parameterized command to be executed; must not be * null. * @param event * The SWT event triggering the command execution; may be * null. * @return The return value from the execution; may be null. * @throws ExecutionException * If the handler has problems executing this command. * @throws NotDefinedException * If the command you are trying to execute is not defined. * @throws NotEnabledException * If the command you are trying to execute is not enabled. * @throws NotHandledException * If there is no handler. * @since 3.2 * @see Command#executeWithChecks(ExecutionEvent) */ virtual Object::Pointer ExecuteCommand( SmartPointer command, SmartPointer uielement) throw(ExecutionException, NotDefinedException, NotEnabledException, NotHandledException) = 0; /** * Executes the given parameterized command in the provided context. It * takes care of finding the correct active handler given the context, calls * {@link IHandler2#setEnabled(Object)} to update the enabled state if * supported, and executes with that handler. * * @param command * The parameterized command to be executed; must not be * null. * @param event * The SWT event triggering the command execution; may be * null. * @param context * the evaluation context to run against. Must not be * null * @return The return value from the execution; may be null. * @throws ExecutionException * If the handler has problems executing this command. * @throws NotDefinedException * If the command you are trying to execute is not defined. * @throws NotEnabledException * If the command you are trying to execute is not enabled. * @throws NotHandledException * If there is no handler. * @since 3.4 * @see Command#executeWithChecks(ExecutionEvent) * @see #createContextSnapshot(boolean) */ virtual Object::Pointer ExecuteCommandInContext( SmartPointer command, SmartPointer uielement, SmartPointer context) throw(ExecutionException, NotDefinedException, NotEnabledException, NotHandledException) = 0; /** * This method creates a copy of the application context returned by * {@link #getCurrentState()}. * * @param includeSelection * if true, include the default variable and * selection variables * @return an context filled with the current set of variables. If selection * is not included, the default variable is an empty collection * @since 3.4 */ virtual SmartPointer CreateContextSnapshot(bool includeSelection) = 0; /** * Returns an evaluation context representing the current state of the * world. This is equivalent to the application context required by * {@link ExecutionEvent}. * * @return the current state of the application; never null. * @see ParameterizedCommand#executeWithChecks(Object, Object) * @see ExecutionEvent#ExecutionEvent(Command, java.util.Map, Object, * Object) * @see org.eclipse.ui.services.IEvaluationService */ virtual SmartPointer GetCurrentState() const = 0; /** *

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

*/ virtual void ReadRegistry() = 0; /** * Sets the help context identifier to associate with a particular handler. * * @param handler * The handler with which to register a help context identifier; * must not be null. * @param helpContextId * The help context identifier to register; may be * null if the help context identifier should be * removed. * @since 3.2 */ virtual void SetHelpContextId(SmartPointer handler, const std::string& helpContextId) = 0; }; } #endif /* BERRYIHANDLERSERVICE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryShowViewHandler.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryShowViewHandler.cpp index 78895a1045..7a7b689565 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryShowViewHandler.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryShowViewHandler.cpp @@ -1,118 +1,118 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryShowViewHandler.h" #include "berryHandlerUtil.h" -#include "../tweaklets/berryWorkbenchTweaklet.h" -#include "../dialogs/berryIShowViewDialog.h" +#include "tweaklets/berryWorkbenchTweaklet.h" +#include "dialogs/berryIShowViewDialog.h" -#include "../berryUIException.h" -#include "../berryIWorkbenchPage.h" -#include "../berryIViewDescriptor.h" -#include "../berryPlatformUI.h" +#include "berryUIException.h" +#include "berryIWorkbenchPage.h" +#include "berryIViewDescriptor.h" +#include "berryPlatformUI.h" #include #include namespace berry { const std::string ShowViewHandler::PARAMETER_NAME_VIEW_ID = "org.blueberry.ui.showView.viewId"; //$NON-NLS-1$ ShowViewHandler::ShowViewHandler() { } Object::Pointer ShowViewHandler::Execute( const ExecutionEvent::Pointer 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(PARAMETER_NAME_VIEW_ID); std::string value; if (result != parameters.end()) value = result->second; if (value == "") { this->OpenOther(window); } else { try { this->OpenView(value, window); } catch (PartInitException e) { throw ExecutionException("Part could not be initialized", e); //$NON-NLS-1$ } } return Object::Pointer(0); } void ShowViewHandler::OpenOther(IWorkbenchWindow::Pointer window) { const IWorkbenchPage::Pointer page = window->GetActivePage(); if (page.IsNull()) { return; } IShowViewDialog::Pointer dialog = Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateStandardDialog(WorkbenchTweaklet::DIALOG_ID_SHOW_VIEW).Cast(); if (dialog.IsNull()) return; int returnCode = dialog->Open(); if (returnCode == IDialog::CANCEL) { return; } const std::vector descriptors = dialog->GetSelection(); for (unsigned int i = 0; i < descriptors.size(); ++i) { try { this->OpenView(descriptors[i]->GetId(), window); } catch (PartInitException e) { // StatusUtil.handleStatus(e.getStatus(), // WorkbenchMessages.ShowView_errorTitle // + ": " + e.getMessage(), //$NON-NLS-1$ // StatusManager.SHOW); } } } void ShowViewHandler::OpenView(const std::string& viewId, IWorkbenchWindow::Pointer activeWorkbenchWindow) { const IWorkbenchPage::Pointer activePage = activeWorkbenchWindow->GetActivePage(); if (activePage.IsNull()) { return; } activePage->ShowView(viewId); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryShowViewHandler.h b/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryShowViewHandler.h index 8105868f5c..c512227557 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryShowViewHandler.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/handlers/berryShowViewHandler.h @@ -1,81 +1,81 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYSHOWVIEWHANDLER_H_ #define BERRYSHOWVIEWHANDLER_H_ #include #include -#include "../berryIWorkbenchWindow.h" +#include "berryIWorkbenchWindow.h" #include namespace berry { /** * \ingroup org_blueberry_ui * * 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 ShowViewHandler : public AbstractHandler { public: berryObjectMacro(ShowViewHandler) private: /** * The name of the parameter providing the view identifier. */ static const std::string PARAMETER_NAME_VIEW_ID; public: /** * Creates a new ShowViewHandler that will open the view in its default location. */ ShowViewHandler(); Object::Pointer Execute( const ExecutionEvent::Pointer event); private: /** * Opens a view selection dialog, allowing the user to chose a view. */ void OpenOther(IWorkbenchWindow::Pointer window); /** * Opens the view with the given identifier. * * @param viewId * The view to open; must not be null * @throws PartInitException * If the part could not be initialized. */ void OpenView(const std::string& viewId, IWorkbenchWindow::Pointer activeWorkbenchWindow); }; } #endif /*BERRYSHOWVIEWHANDLER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractPartSelectionTracker.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractPartSelectionTracker.cpp index 441dc251d2..df37b4b1a6 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractPartSelectionTracker.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractPartSelectionTracker.cpp @@ -1,131 +1,131 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryAbstractPartSelectionTracker.h" -#include "../berryIPostSelectionProvider.h" -#include "../berryINullSelectionListener.h" +#include "berryIPostSelectionProvider.h" +#include "berryINullSelectionListener.h" -#include "../util/berrySafeRunnable.h" +#include "util/berrySafeRunnable.h" #include namespace berry { class SafeSelectionRunnable : public SafeRunnable { public: berryObjectMacro(SafeSelectionRunnable) ISelectionListener::Pointer l; SafeSelectionRunnable(IWorkbenchPart::Pointer part, ISelection::ConstPointer sel) : p(part), s(sel) {} void Run() { l->SelectionChanged(p, s); } private: IWorkbenchPart::Pointer p; ISelection::ConstPointer s; }; AbstractPartSelectionTracker::AbstractPartSelectionTracker( const std::string& partId) { this->SetPartId(partId); } void AbstractPartSelectionTracker::AddSelectionListener( ISelectionListener::Pointer listener) { fListeners.push_back(listener); } void AbstractPartSelectionTracker::AddPostSelectionListener( ISelectionListener::Pointer listener) { fPostListeners.push_back(listener); } void AbstractPartSelectionTracker::RemoveSelectionListener( ISelectionListener::Pointer listener) { fListeners.remove(listener); } void AbstractPartSelectionTracker::RemovePostSelectionListener( ISelectionListener::Pointer listener) { fPostListeners.remove(listener); } AbstractPartSelectionTracker::~AbstractPartSelectionTracker() { } void AbstractPartSelectionTracker::FireSelection(IWorkbenchPart::Pointer part, ISelection::ConstPointer sel) { SafeSelectionRunnable::Pointer runnable(new SafeSelectionRunnable(part, sel)); for (std::list::iterator i = fListeners.begin(); i != fListeners.end(); ++i) { ISelectionListener::Pointer l = *i; if ((part && sel) || l.Cast()) { runnable->l = l; SafeRunner::Run(runnable); } } } void AbstractPartSelectionTracker::FirePostSelection(IWorkbenchPart::Pointer part, ISelection::ConstPointer sel) { SafeSelectionRunnable::Pointer runnable(new SafeSelectionRunnable(part, sel)); for (std::list::iterator i = fPostListeners.begin(); i != fPostListeners.end(); ++i) { ISelectionListener::Pointer l = *i; if ((part && sel) || l.Cast()) { runnable->l = l; SafeRunner::Run(runnable); } } } std::string AbstractPartSelectionTracker::GetPartId() { return fPartId; } void AbstractPartSelectionTracker::SetPartId(const std::string& partId) { fPartId = partId; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractPartSelectionTracker.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractPartSelectionTracker.h index e5ab69a919..3434b92767 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractPartSelectionTracker.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractPartSelectionTracker.h @@ -1,145 +1,145 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYABSTRACTPARTSELECTIONTRACKER_H_ #define BERRYABSTRACTPARTSELECTIONTRACKER_H_ #include #include -#include "../berryISelectionService.h" -#include "../berryISelectionListener.h" -#include "../berryIWorkbenchPart.h" +#include "berryISelectionService.h" +#include "berryISelectionListener.h" +#include "berryIWorkbenchPart.h" #include namespace berry { class AbstractPartSelectionTracker : public virtual Object { public: berryObjectMacro(AbstractPartSelectionTracker); private: /** * List of selection listeners for this tracker */ std::list fListeners; /** * List of post selection listeners for this tracker */ std::list fPostListeners; /** * The id of the part this tracker tracks */ std::string fPartId; public: /** * Constructs a part selection tracker for the part with the given id. * * @param id part identifier */ AbstractPartSelectionTracker(const std::string& partId); /** * Adds a selection listener to this tracker * * @param listener the listener to add */ void AddSelectionListener(ISelectionListener::Pointer listener); /** * Adds a post selection listener to this tracker * * @param listener the listener to add */ void AddPostSelectionListener(ISelectionListener::Pointer listener); /** * Returns the selection from the part being tracked, * or null if the part is closed or has no selection. */ virtual ISelection::ConstPointer GetSelection() = 0; /** * Removes a selection listener from this tracker. * * @param listener the listener to remove */ void RemoveSelectionListener(ISelectionListener::Pointer listener); /** * Removes a post selection listener from this tracker. * * @param listener the listener to remove */ void RemovePostSelectionListener(ISelectionListener::Pointer listener); /** * Disposes this selection tracker. This removes all listeners currently registered. */ ~AbstractPartSelectionTracker(); protected: /** * Fires a selection event to the listeners. * * @param part the part or null if no active part * @param sel the selection or null if no active selection * @param listeners the list of listeners to notify */ void FireSelection(IWorkbenchPart::Pointer part, ISelection::ConstPointer sel); /** * Fires a post selection event to the listeners. * * @param part the part or null if no active part * @param sel the selection or null if no active selection * @param listeners the list of listeners to notify */ void FirePostSelection(IWorkbenchPart::Pointer part, ISelection::ConstPointer sel); /** * Returns the id of the part that this tracks. * * @return part identifier */ std::string GetPartId(); private: /** * Sets the id of the part that this tracks. * * @param id view identifier */ void SetPartId(const std::string& partId); }; } #endif /* BERRYABSTRACTPARTSELECTIONTRACKER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractSelectionService.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractSelectionService.cpp index 48608786df..3e17d98e0b 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractSelectionService.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractSelectionService.cpp @@ -1,265 +1,265 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryAbstractSelectionService.h" #include "berryWorkbenchPlugin.h" -#include "../berryIPostSelectionProvider.h" -#include "../berryINullSelectionListener.h" +#include "berryIPostSelectionProvider.h" +#include "berryINullSelectionListener.h" namespace berry { //ISelectionService::SelectionEvents& AbstractSelectionService::GetSelectionEvents(const std::string& partId) //{ // if (partId.empty()) // { // return selectionEvents; // } // // return this->GetPerPartTracker(partId)->GetSelectionEvents(); //} AbstractSelectionService::AbstractSelectionService() { selListener = new SelectionListener(this); postSelListener = new PostSelectionListener(this); } AbstractSelectionService::SelectionListener::SelectionListener(AbstractSelectionService* service) : m_SelectionService(service) { } void AbstractSelectionService::SelectionListener::SelectionChanged(SelectionChangedEvent::Pointer event) { m_SelectionService->FireSelection(m_SelectionService->activePart, event->GetSelection()); } AbstractSelectionService::PostSelectionListener::PostSelectionListener(AbstractSelectionService* service) : m_SelectionService(service) { } void AbstractSelectionService::PostSelectionListener::SelectionChanged( SelectionChangedEvent::Pointer event) { m_SelectionService->FirePostSelection(m_SelectionService->activePart, event->GetSelection()); } void AbstractSelectionService::AddSelectionListener(ISelectionListener::Pointer l) { fListeners.push_back(l); } void AbstractSelectionService::AddSelectionListener(const std::string& partId, ISelectionListener::Pointer listener) { this->GetPerPartTracker(partId)->AddSelectionListener(listener); } void AbstractSelectionService::AddPostSelectionListener( ISelectionListener::Pointer l) { fPostListeners.push_back(l); } void AbstractSelectionService::AddPostSelectionListener(const std::string& partId, ISelectionListener::Pointer listener) { this->GetPerPartTracker(partId)->AddPostSelectionListener(listener); } void AbstractSelectionService::RemoveSelectionListener(ISelectionListener::Pointer l) { fListeners.remove(l); } void AbstractSelectionService::RemovePostSelectionListener( const std::string& partId, ISelectionListener::Pointer listener) { this->GetPerPartTracker(partId)->RemovePostSelectionListener(listener); } void AbstractSelectionService::RemovePostSelectionListener( ISelectionListener::Pointer l) { fPostListeners.remove(l); } void AbstractSelectionService::RemoveSelectionListener(const std::string& partId, ISelectionListener::Pointer listener) { this->GetPerPartTracker(partId)->RemoveSelectionListener(listener); } void AbstractSelectionService::FireSelection(IWorkbenchPart::Pointer part, ISelection::ConstPointer sel) { for (std::list::iterator i = fListeners.begin(); i != fListeners.end(); ++i) { ISelectionListener::Pointer l = *i; if ((part && sel) || l.Cast()) { try { l->SelectionChanged(part, sel); } catch (const Poco::RuntimeException& rte) { WorkbenchPlugin::Log(rte); } catch (const std::exception& e) { WorkbenchPlugin::Log(e.what()); } } } } void AbstractSelectionService::FirePostSelection(IWorkbenchPart::Pointer part, ISelection::ConstPointer sel) { for (std::list::iterator i = fPostListeners.begin(); i != fPostListeners.end(); ++i) { ISelectionListener::Pointer l = *i; if ((part && sel) || l.Cast()) { try { l->SelectionChanged(part, sel); } catch (const Poco::RuntimeException& rte) { WorkbenchPlugin::Log(rte); } catch (const std::exception& e) { WorkbenchPlugin::Log(e.what()); } } } } AbstractPartSelectionTracker::Pointer AbstractSelectionService::GetPerPartTracker( const std::string& partId) { AbstractPartSelectionTracker::Pointer tracker; std::map::const_iterator res = perPartTrackers.find(partId); if (res == perPartTrackers.end()) { tracker = this->CreatePartTracker(partId); perPartTrackers[partId] = tracker; } else { tracker = res->second; } return tracker; } ISelection::ConstPointer AbstractSelectionService::GetSelection() const { if (activeProvider.IsNotNull()) { return activeProvider->GetSelection(); } else { return ISelection::ConstPointer(0); } } ISelection::ConstPointer AbstractSelectionService::GetSelection(const std::string& partId) { return this->GetPerPartTracker(partId)->GetSelection(); } void AbstractSelectionService::SetActivePart(IWorkbenchPart::Pointer newPart) { // Optimize. if (newPart == activePart) { return; } ISelectionProvider::Pointer selectionProvider; if (newPart.IsNotNull()) { selectionProvider = newPart->GetSite()->GetSelectionProvider(); if (selectionProvider.IsNull()) { newPart = 0; } } if (newPart == activePart) { return; } if (activePart.IsNotNull()) { if (activeProvider.IsNotNull()) { activeProvider->RemoveSelectionChangedListener(selListener); if (activeProvider.Cast().IsNotNull()) { activeProvider.Cast() ->RemovePostSelectionChangedListener(postSelListener); } else { activeProvider ->RemoveSelectionChangedListener(postSelListener); } activeProvider = 0; } activePart = 0; } activePart = newPart; if (newPart.IsNotNull()) { activeProvider = selectionProvider; // Fire an event if there's an active provider activeProvider->AddSelectionChangedListener(selListener); ISelection::ConstPointer sel = activeProvider->GetSelection(); this->FireSelection(newPart, sel); if (activeProvider.Cast().IsNotNull()) { activeProvider.Cast() ->AddPostSelectionChangedListener(postSelListener); } else { activeProvider->AddSelectionChangedListener(postSelListener); } this->FirePostSelection(newPart, sel); } else { this->FireSelection(IWorkbenchPart::Pointer(0), ISelection::ConstPointer(0)); this->FirePostSelection(IWorkbenchPart::Pointer(0), ISelection::ConstPointer(0)); } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractSelectionService.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractSelectionService.h index 9e1c14027a..c9c8bc9bb8 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractSelectionService.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryAbstractSelectionService.h @@ -1,321 +1,321 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYABSTRACTSELECTIONSERVICE_H_ #define BERRYABSTRACTSELECTIONSERVICE_H_ -#include "../berryISelectionService.h" -#include "../berryIWorkbenchPage.h" -#include "../berryISelectionChangedListener.h" -#include "../berryISelectionProvider.h" +#include "berryISelectionService.h" +#include "berryIWorkbenchPage.h" +#include "berryISelectionChangedListener.h" +#include "berryISelectionProvider.h" #include "berryAbstractPartSelectionTracker.h" #include namespace berry { /** * \ingroup org_blueberry_ui_internal * * The selection service for a page */ class AbstractSelectionService : public ISelectionService { private: IWorkbenchPage* page; /** * The list of selection listeners (not per-part). */ std::list fListeners; /** * The list of post selection listeners (not per-part). */ std::list fPostListeners; /** * The currently active part. */ IWorkbenchPart::Pointer activePart; /** * The active part's selection provider, remembered in case the part * replaces its selection provider after we hooked a listener. */ ISelectionProvider::Pointer activeProvider; /** * Map from part id (String) to per-part tracker (AbstractPartSelectionTracker). */ std::map perPartTrackers; struct SelectionListener : public ISelectionChangedListener { SelectionListener(AbstractSelectionService* tracker); void SelectionChanged(SelectionChangedEvent::Pointer event); AbstractSelectionService* m_SelectionService; }; friend class PostSelectionListener; struct PostSelectionListener : public ISelectionChangedListener { PostSelectionListener(AbstractSelectionService* tracker); void SelectionChanged(SelectionChangedEvent::Pointer event); AbstractSelectionService* m_SelectionService; }; friend struct PostSelectionListener; /** * The JFace selection listener to hook on the active part's selection provider. */ ISelectionChangedListener::Pointer selListener; /** * The JFace post selection listener to hook on the active part's selection provider. */ ISelectionChangedListener::Pointer postSelListener; public: //SelectionEvents& GetSelectionEvents(const std::string& partId = ""); /* (non-Javadoc) * Method declared on ISelectionService. */ void AddSelectionListener(ISelectionListener::Pointer l); /* (non-Javadoc) * Method declared on ISelectionService. */ void AddSelectionListener(const std::string& partId, ISelectionListener::Pointer listener); /* (non-Javadoc) * Method declared on ISelectionService. */ void AddPostSelectionListener(ISelectionListener::Pointer l); /* (non-Javadoc) * Method declared on ISelectionService. */ void AddPostSelectionListener(const std::string& partId, ISelectionListener::Pointer listener); /* (non-Javadoc) * Method declared on ISelectionService. */ void RemoveSelectionListener(ISelectionListener::Pointer l); /* * (non-Javadoc) * Method declared on ISelectionListener. */ void RemovePostSelectionListener(const std::string& partId, ISelectionListener::Pointer listener); /* (non-Javadoc) * Method declared on ISelectionService. */ void RemovePostSelectionListener(ISelectionListener::Pointer l); /* * (non-Javadoc) * Method declared on ISelectionListener. */ void RemoveSelectionListener(const std::string& partId, ISelectionListener::Pointer listener); protected: AbstractSelectionService(); /** * Fires a selection event to the given listeners. * * @param part the part or null if no active part * @param sel the selection or null if no active selection */ void FireSelection(IWorkbenchPart::Pointer part, ISelection::ConstPointer sel); /** * Fires a selection event to the given listeners. * * @param part the part or null if no active part * @param sel the selection or null if no active selection */ void FirePostSelection(IWorkbenchPart::Pointer part, ISelection::ConstPointer sel); /** * Returns the per-part selection tracker for the given part id. * * @param partId part identifier * @return per-part selection tracker */ AbstractPartSelectionTracker::Pointer GetPerPartTracker(const std::string& partId); /** * Creates a new per-part selection tracker for the given part id. * * @param partId part identifier * @return per-part selection tracker */ virtual AbstractPartSelectionTracker::Pointer CreatePartTracker( const std::string& partId) const = 0; public: /** * Returns the selection. */ ISelection::ConstPointer GetSelection() const; /* * @see ISelectionService#getSelection(String) */ ISelection::ConstPointer GetSelection(const std::string& partId); /** * Sets the current-active part (or null if none) * * @since 3.1 * * @param newPart the new active part (or null if none) */ void SetActivePart(IWorkbenchPart::Pointer newPart); // /** // * Notifies the listener that a part has been activated. // */ // public void partActivated(IWorkbenchPart newPart) { // // Optimize. // if (newPart == activePart) // return; // // // Unhook selection from the old part. // reset(); // // // Update active part. // activePart = newPart; // // // Hook selection on the new part. // if (activePart != null) { // activeProvider = activePart.getSite().getSelectionProvider(); // if (activeProvider != null) { // // Fire an event if there's an active provider // activeProvider.addSelectionChangedListener(selListener); // ISelection sel = activeProvider.getSelection(); // fireSelection(newPart, sel); // if (activeProvider instanceof IPostSelectionProvider) // ((IPostSelectionProvider) activeProvider) // .addPostSelectionChangedListener(postSelListener); // else // activeProvider.addSelectionChangedListener(postSelListener); // firePostSelection(newPart, sel); // } else { // //Reset active part. activeProvider may not be null next time this method is called. // activePart = null; // } // } // // No need to fire an event if no active provider, since this was done in reset() // } // // /** // * Notifies the listener that a part has been brought to the front. // */ // public void partBroughtToTop(IWorkbenchPart newPart) { // // do nothing, the active part has not changed, // // so the selection is unaffected // } // // /** // * Notifies the listener that a part has been closed // */ // public void partClosed(IWorkbenchPart part) { // // Unhook selection from the part. // if (part == activePart) { // reset(); // } // } // // /** // * Notifies the listener that a part has been deactivated. // */ // public void partDeactivated(IWorkbenchPart part) { // // Unhook selection from the part. // if (part == activePart) { // reset(); // } // } // // /** // * Notifies the listener that a part has been opened. // */ // public void partOpened(IWorkbenchPart part) { // // Wait for activation. // } // // /** // * Notifies the listener that a part has been opened. // */ // public void partInputChanged(IWorkbenchPart part) { // // 36501 - only process if part is active // if (activePart == part) { // reset(); // partActivated(part); // } // } // // /** // * Resets the service. The active part and selection provider are // * dereferenced. // */ // public void reset() { // if (activePart != null) { // fireSelection(null, null); // firePostSelection(null, null); // if (activeProvider != null) { // activeProvider.removeSelectionChangedListener(selListener); // if (activeProvider instanceof IPostSelectionProvider) // ((IPostSelectionProvider) activeProvider) // .removePostSelectionChangedListener(postSelListener); // else // activeProvider // .removeSelectionChangedListener(postSelListener); // activeProvider = null; // } // activePart = null; // } // } }; } #endif /*BERRYABSTRACTSELECTIONSERVICE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDefaultSaveable.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDefaultSaveable.cpp index 8b0e0c6eaf..3390ab9b15 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDefaultSaveable.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDefaultSaveable.cpp @@ -1,117 +1,117 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryDefaultSaveable.h" -#include "../berryIWorkbenchPart.h" -#include "../berryIWorkbenchPage.h" -#include "../berryUIException.h" -#include "../berryImageDescriptor.h" +#include "berryIWorkbenchPart.h" +#include "berryIWorkbenchPage.h" +#include "berryUIException.h" +#include "berryImageDescriptor.h" namespace berry { DefaultSaveable::DefaultSaveable(IWorkbenchPart::Pointer _part) : part(_part) { } void DefaultSaveable::DoSave(/*IProgressMonitor monitor*/) { IWorkbenchPart::Pointer _part(part); if (_part.Cast () != 0) { _part.Cast ()->DoSave(/*monitor*/); } } std::string DefaultSaveable::GetName() const { return part.Lock()->GetPartName(); } ImageDescriptor::Pointer DefaultSaveable::GetImageDescriptor() const { //TODO DefaultSaveable GetImageDescriptor // Image image = part.getTitleImage(); // if (image == null) // { // return null; // } // return ImageDescriptor.createFromImage(image); return ImageDescriptor::Pointer(0); } std::string DefaultSaveable::GetToolTipText() const { return part.Lock()->GetTitleToolTip(); } bool DefaultSaveable::IsDirty() const { IWorkbenchPart::Pointer _part(part); if (_part.Cast () != 0) { return _part.Cast ()->IsDirty(); } return false; } bool DefaultSaveable::operator<(const Saveable* obj) const { if (this == obj) return false; if (obj == 0) return true; const DefaultSaveable* other = dynamic_cast (obj); if (part.Expired()) { return !other->part.Expired(); } else return part < other->part; } bool DefaultSaveable::Show(IWorkbenchPage::Pointer page) { IWorkbenchPart::Pointer _part(part); IWorkbenchPartReference::Pointer reference = page->GetReference(_part); if (reference != 0) { page->Activate(_part); return true; } if (_part.Cast () != 0) { IViewPart::Pointer viewPart = _part.Cast (); try { page->ShowView(viewPart->GetViewSite()->GetId(), viewPart ->GetViewSite()->GetSecondaryId(), IWorkbenchPage::VIEW_ACTIVATE); } catch (PartInitException& /*e*/) { return false; } return true; } return false; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDefaultSaveable.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDefaultSaveable.h index ed5b51e13a..ab5193289b 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDefaultSaveable.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDefaultSaveable.h @@ -1,98 +1,98 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYDEFAULTSAVEABLE_H_ #define BERRYDEFAULTSAVEABLE_H_ -#include "../berrySaveable.h" +#include "berrySaveable.h" namespace berry { /** * A default {@link Saveable} implementation that wrappers a regular * workbench part (one that does not itself adapt to Saveable). * * @since 3.2 */ class DefaultSaveable : public Saveable { private: WeakPointer part; public: /** * Creates a new DefaultSaveable. * * @param part * the part represented by this model */ DefaultSaveable(SmartPointer part); /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#doSave(org.blueberry.core.runtime.IProgressMonitor) */ void DoSave(/*IProgressMonitor monitor*/); /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#getName() */ std::string GetName() const; /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#getImageDescriptor() */ SmartPointer GetImageDescriptor() const; /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#getToolTipText() */ std::string GetToolTipText() const; /* * (non-Javadoc) * * @see org.blueberry.ui.Saveable#isDirty() */ bool IsDirty() const; /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ bool operator<(const Saveable* obj) const; /* (non-Javadoc) * @see org.blueberry.ui.Saveable#show(org.blueberry.ui.IWorkbenchPage) */ bool Show(SmartPointer page); }; } #endif /* BERRYDEFAULTSAVEABLE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDefaultStackPresentationSite.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDefaultStackPresentationSite.h index 63c53b24df..eaa028a823 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDefaultStackPresentationSite.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDefaultStackPresentationSite.h @@ -1,100 +1,100 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYDEFAULTSTACKPRESENTATIONSITE_H_ #define BERRYDEFAULTSTACKPRESENTATIONSITE_H_ -#include "../presentations/berryIStackPresentationSite.h" -#include "../presentations/berryStackPresentation.h" +#include "presentations/berryIStackPresentationSite.h" +#include "presentations/berryStackPresentation.h" namespace berry { class DefaultStackPresentationSite: public IStackPresentationSite { private: StackPresentation::Pointer presentation; int state; int activeState; public: berryObjectMacro(DefaultStackPresentationSite); DefaultStackPresentationSite(); void SetPresentation(StackPresentation::Pointer newPresentation); StackPresentation::Pointer GetPresentation(); int GetState(); void SetActive(int activeState); int GetActive(); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IStackPresentationSite#selectPart(org.blueberry.ui.internal.skins.IPresentablePart) */ void SelectPart(IPresentablePart::Pointer toSelect); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#setState(int) */ void SetState(int newState); void SetPresentationState(int newState); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentablePart#isClosable() */ bool IsCloseable(IPresentablePart::Pointer part); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#dragStart(org.blueberry.ui.internal.skins.IPresentablePart, boolean) */ void DragStart(IPresentablePart::Pointer beingDragged, Point& initialPosition, bool keyboard); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#close(org.blueberry.ui.internal.skins.IPresentablePart) */ void Close(IPresentablePart::Pointer toClose); /* (non-Javadoc) * @see org.blueberry.ui.internal.skins.IPresentationSite#dragStart(boolean) */ void DragStart(Point& initialPosition, bool keyboard); /* (non-Javadoc) * @see org.blueberry.ui.presentations.IStackPresentationSite#supportsState(int) */ bool SupportsState(int state); // void AddSystemActions(IMenuManager menuManager) { // // } }; } #endif /* BERRYDEFAULTSTACKPRESENTATIONSITE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDetachedPlaceHolder.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDetachedPlaceHolder.h index 43ba70f55e..ac374e6a82 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDetachedPlaceHolder.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDetachedPlaceHolder.h @@ -1,104 +1,104 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYDETACHEDPLACEHOLDER_H_ #define BERRYDETACHEDPLACEHOLDER_H_ #include "berryContainerPlaceholder.h" -#include "../berryIMemento.h" -#include "../berryRectangle.h" +#include "berryIMemento.h" +#include "berryRectangle.h" #include namespace berry { /** * DetachedPlaceHolder is the placeholder for detached views. * */ class DetachedPlaceHolder : public ContainerPlaceholder { private: std::list children; Rectangle bounds; public: berryObjectMacro(DetachedPlaceHolder); /** * DetachedPlaceHolder constructor comment. * @param id java.lang.String * @param bounds the size of the placeholder */ DetachedPlaceHolder(const std::string& id, const Rectangle& b); /** * Add a child to the container. */ void Add(StackablePart::Pointer newPart); /** * Return true if the container allows its * parts to show a border if they choose to, * else false if the container does not want * its parts to show a border. * @return boolean */ bool AllowsBorder(); Rectangle GetBounds(); /** * Returns a list of layout children. */ std::list GetChildren(); /** * Remove a child from the container. */ void Remove(StackablePart::Pointer part); /** * Replace one child with another */ void Replace(StackablePart::Pointer oldPart, StackablePart::Pointer newPart); /** * Restore the state from the memento. * @param memento */ void RestoreState(IMemento::Pointer memento); /** * Save state to the memento. * @param memento */ void SaveState(IMemento::Pointer memento); void FindSashes(LayoutPart::Pointer part, PartPane::Sashes& sashes); }; } #endif /* BERRYDETACHEDPLACEHOLDER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDetachedWindow.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDetachedWindow.cpp index de3fa9d22d..b7f3efe004 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDetachedWindow.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDetachedWindow.cpp @@ -1,545 +1,545 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryDetachedWindow.h" -#include "../berryIWorkbenchPartConstants.h" -#include "../berryISaveablePart.h" +#include "berryIWorkbenchPartConstants.h" +#include "berryISaveablePart.h" #include "berryWorkbenchWindow.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" +#include "tweaklets/berryGuiWidgetsTweaklet.h" #include "berryWorkbenchConstants.h" #include "berryEditorManager.h" #include "berryDragUtil.h" namespace berry { DetachedWindow::ShellListener::ShellListener(DetachedWindow* wnd) : window(wnd) { } void DetachedWindow::ShellListener::ShellClosed(ShellEvent::Pointer e) { // hold on to a reference of the DetachedWindow instance // (otherwise, wnd->HandleClose() woulde delete the DetachedWindow // instance too early, trying to write to members afterwards) DetachedWindow::Pointer wnd(window); // only continue to close if the handleClose // wasn't canceled e->doit = wnd->HandleClose(); } DetachedWindow::ShellControlListener::ShellControlListener(DetachedWindow* wnd) : window(wnd) { } GuiTk::IControlListener::Events::Types DetachedWindow::ShellControlListener::GetEventTypes() const { return Events::RESIZED; } void DetachedWindow::ShellControlListener::ControlResized( GuiTk::ControlEvent::Pointer e) { window->folder->SetBounds( Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(e->item)); } DetachedWindow::DetachedWindow(WorkbenchPage* workbenchPage) { shellListener = new ShellListener(this); resizeListener = new ShellControlListener(this); this->page = workbenchPage; hideViewsOnClose = true; folder = new PartStack(page, false); } void DetachedWindow::PropertyChange(Object::Pointer /*source*/, int propId) { if (propId == IWorkbenchPartConstants::PROP_TITLE) { this->UpdateTitle(); } else if (propId == PartStack::PROP_SELECTION) { this->ActivePartChanged(this->GetPartReference(folder->GetSelection())); } } Shell::Pointer DetachedWindow::GetShell() { return windowShell; } void DetachedWindow::Create() { folder->AddListener(IPropertyChangeListener::Pointer(this)); windowShell = page->GetWorkbenchWindow().Cast () ->GetDetachedWindowPool()->AllocateShell( shellListener); windowShell->SetData(Object::Pointer(this)); windowShell->SetText(""); //$NON-NLS-1$ DragUtil::AddDragTarget(windowShell->GetControl(), IDragOverListener::Pointer(this)); hideViewsOnClose = true; if (bounds.IsEmpty()) { Rectangle windowRect = page->GetWorkbenchWindow()->GetShell()->GetBounds(); Point center(windowRect.x + windowRect.width / 2, windowRect.y - windowRect.height / 2); bounds = Rectangle(center.x - 150, center.y + 100, 300, 200); } // Force the rect into the current display Rectangle dispBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetAvailableScreenSize(); if (bounds.width > dispBounds.width) bounds.width = dispBounds.width; if (bounds.height > dispBounds.height) bounds.height = dispBounds.height; if (bounds.x + bounds.width > dispBounds.width) bounds.x = dispBounds.width - bounds.width; if (bounds.y + bounds.height > dispBounds.height) bounds.y = dispBounds.height - bounds.height; this->GetShell()->SetBounds(bounds); this->ConfigureShell(windowShell); this->CreateContents(windowShell->GetControl()); //windowShell->Layout(true); //folder->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(windowShell->GetControl())); } void DetachedWindow::Add(StackablePart::Pointer part) { Shell::Pointer shell = this->GetShell(); if (shell != 0) { part->Reparent(shell->GetControl()); } folder->Add(part); this->UpdateMinimumSize(); } bool DetachedWindow::BelongsToWorkbenchPage( IWorkbenchPage::Pointer workbenchPage) { return (workbenchPage == this->page); } bool DetachedWindow::Close() { hideViewsOnClose = false; Shell::Pointer shell = this->GetShell(); if (shell != 0) { shell->Close(); } return true; } IDropTarget::Pointer DetachedWindow::Drag(void* /*currentControl*/, Object::Pointer draggedObject, const Point& position, const Rectangle& /*dragRectangle*/) { if (draggedObject.Cast () == 0) { return IDropTarget::Pointer(0); } PartPane::Pointer sourcePart = draggedObject.Cast (); if (sourcePart->GetWorkbenchWindow() != page->GetWorkbenchWindow()) { return IDropTarget::Pointer(0); } // Only handle the event if the source part is acceptable to the particular PartStack IDropTarget::Pointer target; if (folder->AllowsDrop(sourcePart)) { target = folder->GetDropTarget(draggedObject, position); if (target == 0) { Rectangle displayBounds = DragUtil::GetDisplayBounds(folder->GetControl()); if (displayBounds.Contains(position)) { StackDropResult::Pointer stackDropResult(new StackDropResult( displayBounds, Object::Pointer(0))); target = folder->CreateDropTarget(sourcePart, stackDropResult); } else { return IDropTarget::Pointer(0); } } } return target; } IStackableContainer::ChildrenType DetachedWindow::GetChildren() const { return folder->GetChildren(); } WorkbenchPage::Pointer DetachedWindow::GetWorkbenchPage() { return WorkbenchPage::Pointer(this->page); } void DetachedWindow::RestoreState(IMemento::Pointer memento) { // Read the bounds. int x = 0; memento->GetInteger(WorkbenchConstants::TAG_X, x); int y = 0; memento->GetInteger(WorkbenchConstants::TAG_Y, y); int width = 0; memento->GetInteger(WorkbenchConstants::TAG_WIDTH, width); int height = 0; memento->GetInteger(WorkbenchConstants::TAG_HEIGHT, height); // memento->GetInteger(WorkbenchConstants::TAG_FLOAT); // Set the bounds. bounds = Rectangle(x, y, width, height); if (GetShell()) { GetShell()->SetBounds(bounds); } // Create the folder. IMemento::Pointer childMem = memento->GetChild(WorkbenchConstants::TAG_FOLDER); if (childMem) { folder->RestoreState(childMem); } } void DetachedWindow::SaveState(IMemento::Pointer memento) { if (GetShell()) { bounds = GetShell()->GetBounds(); } // Save the bounds. memento->PutInteger(WorkbenchConstants::TAG_X, bounds.x); memento->PutInteger(WorkbenchConstants::TAG_Y, bounds.y); memento->PutInteger(WorkbenchConstants::TAG_WIDTH, bounds.width); memento->PutInteger(WorkbenchConstants::TAG_HEIGHT, bounds.height); // Save the views. IMemento::Pointer childMem = memento->CreateChild( WorkbenchConstants::TAG_FOLDER); folder->SaveState(childMem); } void* DetachedWindow::GetControl() { return folder->GetControl(); } int DetachedWindow::Open() { if (this->GetShell() == 0) { this->Create(); } Rectangle bounds = this->GetShell()->GetBounds(); if (!(bounds == this->GetShell()->GetBounds())) { this->GetShell()->SetBounds(bounds); } this->GetShell()->SetVisible(true); folder->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea(this->GetShell()->GetControl())); return 0; } void DetachedWindow::ActivePartChanged( IWorkbenchPartReference::Pointer partReference) { if (activePart == partReference) { return; } if (activePart != 0) { activePart->RemovePropertyListener(IPropertyChangeListener::Pointer(this)); } activePart = partReference; if (partReference != 0) { partReference->AddPropertyListener(IPropertyChangeListener::Pointer(this)); } this->UpdateTitle(); } void DetachedWindow::ConfigureShell(Shell::Pointer shell) { this->UpdateTitle(); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener( shell->GetControl(), resizeListener); //shell.addListener(SWT.Activate, activationListener); //shell.addListener(SWT.Deactivate, activationListener); //TODO DetachedWindow key bindings // // Register this detached view as a window (for key bindings). // IContextService contextService = (IContextService) getWorkbenchPage() // .getWorkbenchWindow().getWorkbench().getService(IContextService.class); // contextService.registerShell(shell, IContextService.TYPE_WINDOW); // // page.getWorkbenchWindow().getWorkbench().getHelpSystem().setHelp(shell, // IWorkbenchHelpContextIds.DETACHED_WINDOW); } void* DetachedWindow::CreateContents(void* parent) { // Create the tab folder. folder->CreateControl(parent); // Reparent each view in the tab folder. std::list detachedChildren; this->CollectViewPanes(detachedChildren, this->GetChildren()); for (std::list::iterator itr = detachedChildren.begin(); itr != detachedChildren.end(); ++itr) { PartPane::Pointer part = *itr; part->Reparent(parent); } //TODO DetachedWindow listen to folder events (update size?) // if (folder->GetPresentation() // instanceof TabbedStackPresentation) // { // TabbedStackPresentation stack = (TabbedStackPresentation) folder.getPresentation(); // AbstractTabFolder tabFolder = stack.getTabFolder(); // tabFolder.addListener(new TabFolderListener() // { // public void handleEvent(TabFolderEvent e) // { // switch (e.type) // { // case TabFolderEvent.EVENT_CLOSE: // { // updateMinimumSize(); // break; // } // case TabFolderEvent.EVENT_PREFERRED_SIZE: // { // updateMinimumSize(); // break; // } // } // } // }); // } // Return tab folder control. return folder->GetControl(); } void DetachedWindow::UpdateTitle() { if (activePart != 0) { // Uncomment to set the shell title to match the title of the active part // String text = activePart.getTitle(); // // if (!text.equals(s.getText())) { // s.setText(text); // } } } void DetachedWindow::UpdateMinimumSize() { // // We can only do this for 'Tabbed' stacked presentations. // if (folder.getPresentation().Cast() != 0) // { // TabbedStackPresentation stack = (TabbedStackPresentation) folder.getPresentation(); // // if (stack->GetPartList().size() == 1) // { // // Get the minimum space required for the part // int width = stack->ComputePreferredSize(true, Constants::INF, Constants::INF, 0); // int height = stack->ComputePreferredSize(false, Constants::INF, Constants::INF, 0); // // // Take the current shell 'trim' into account // int shellHeight = windowShell->GetBounds().height - windowShell->GetClientArea().height; // int shellWidth = windowShell->GetBounds().width - windowShell->GetClientArea().width; // // windowShell->SetMinimumSize(width + shellWidth, height + shellHeight); // } // } } IWorkbenchPartReference::Pointer DetachedWindow::GetPartReference( StackablePart::Pointer pane) { if (pane == 0 || pane.Cast () == 0) { return IWorkbenchPartReference::Pointer(0); } return pane.Cast ()->GetPartReference(); } bool DetachedWindow::HandleClose() { if (hideViewsOnClose) { std::list views; this->CollectViewPanes(views, this->GetChildren()); // Save any dirty views if (!this->HandleSaves(views)) { return false; // User canceled the save } // OK, go on with the closing for (std::list::iterator itr = views.begin(); itr != views.end(); ++itr) { PartPane::Pointer child = *itr; // Only close if closable... if (child->IsCloseable()) { page->HideView(child->GetPartReference().Cast ()); // Was the close cancelled? if (child->GetContainer() != 0) return false; } else { page->AttachView(child->GetPartReference().Cast ()); } } } if (folder != 0) { folder->Dispose(); } if (windowShell != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener( windowShell->GetControl(), resizeListener); // windowShell.removeListener(SWT.Activate, activationListener); // windowShell.removeListener(SWT.Deactivate, activationListener); DragUtil::RemoveDragTarget(windowShell->GetControl(), IDragOverListener::Pointer(this)); bounds = windowShell->GetBounds(); //TODO DetachedWindow unregister key bindings // // Unregister this detached view as a window (for key bindings). // final IContextService contextService = (IContextService) getWorkbenchPage().getWorkbenchWindow().getWorkbench().getService(IContextService.class); // contextService.unregisterShell(windowShell); windowShell->SetData(Object::Pointer(0)); windowShell = 0; } return true; } bool DetachedWindow::HandleSaves(std::list views) { std::vector dirtyViews; for (std::list::iterator iterator = views.begin(); iterator != views.end(); ++iterator) { PartPane::Pointer pane = *iterator; IViewReference::Pointer ref = pane->GetPartReference().Cast (); IViewPart::Pointer part = ref->GetView(false); if (part.Cast () != 0) { ISaveablePart::Pointer saveable = part.Cast (); if (saveable->IsDirty() && saveable->IsSaveOnCloseNeeded()) { dirtyViews.push_back(part); } } } // If there are any prompt to save -before- any closing happens // FIXME: This code will result in a double prompt if the user // decides not to save a particular view at this stage they'll // get a second one from the 'hideView' call... if (dirtyViews.size() > 0) { IWorkbenchWindow::Pointer window = page->GetWorkbenchWindow(); bool success = EditorManager::SaveAll(dirtyViews, true, true, false, window); if (!success) { return false; // the user canceled. } } return true; } void DetachedWindow::CollectViewPanes(std::list& result, const std::list& parts) { for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { StackablePart::Pointer part = *iter; if (part.Cast () != 0) { result.push_back(part.Cast ()); } } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDetachedWindow.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDetachedWindow.h index 442ed44a0d..15eff10c2d 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDetachedWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDetachedWindow.h @@ -1,199 +1,199 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYDETACHEDWINDOW_H_ #define BERRYDETACHEDWINDOW_H_ #include "berryPartStack.h" #include "berryWorkbenchPage.h" #include "berryLayoutPart.h" #include "berryIDragOverListener.h" -#include "../berryIShellListener.h" -#include "../guitk/berryGuiTkIControlListener.h" +#include "berryIShellListener.h" +#include "guitk/berryGuiTkIControlListener.h" -#include "../berryRectangle.h" -#include "../berryShell.h" +#include "berryRectangle.h" +#include "berryShell.h" namespace berry { /** * TODO: Drag from detached to fast view bar back to detached causes NPE * * @since 3.1 */ class DetachedWindow: public IPropertyChangeListener, public IDragOverListener { public: berryObjectMacro(DetachedWindow); private: PartStack::Pointer folder; WorkbenchPage* page; Rectangle bounds; Shell::Pointer windowShell; bool hideViewsOnClose; struct ShellListener: public IShellListener { ShellListener(DetachedWindow* wnd); void ShellClosed(ShellEvent::Pointer e); private: DetachedWindow* window; }; IShellListener::Pointer shellListener; struct ShellControlListener: public GuiTk::IControlListener { ShellControlListener(DetachedWindow* wnd); Events::Types GetEventTypes() const; void ControlResized(GuiTk::ControlEvent::Pointer e); private: DetachedWindow* window; }; GuiTk::IControlListener::Pointer resizeListener; // Listener activationListener = new Listener() { // public void handleEvent(Event event) { // switch (event.type) { // case SWT.Activate: // page.window.liftRestrictions(); // break; // case SWT.Deactivate: // page.window.imposeRestrictions(); // break; // } // } // }; IWorkbenchPartReference::Pointer activePart; public: /** * Create a new FloatingWindow. */ DetachedWindow(WorkbenchPage* workbenchPage); void PropertyChange(Object::Pointer source, int propId); Shell::Pointer GetShell(); void Create(); /** * Adds a visual part to this window. * Supports reparenting. */ void Add(StackablePart::Pointer part); bool BelongsToWorkbenchPage(IWorkbenchPage::Pointer workbenchPage); bool Close(); /* * @see org.blueberry.ui.internal.IDragOverListener#Drag(void*, Object::Pointer, const Point&, const Rectangle& ) */ IDropTarget::Pointer Drag(void* currentControl, Object::Pointer draggedObject, const Point& position, const Rectangle& dragRectangle); IStackableContainer::ChildrenType GetChildren() const; WorkbenchPage::Pointer GetWorkbenchPage(); /** * @see IPersistablePart */ void RestoreState(IMemento::Pointer memento); /** * @see IPersistablePart */ void SaveState(IMemento::Pointer memento); void* GetControl(); /** * Opens the detached window. */ int Open(); protected: void ActivePartChanged(IWorkbenchPartReference::Pointer partReference); /** * This method will be called to initialize the given Shell's layout */ void ConfigureShell(Shell::Pointer shell); /** * Override this method to create the widget tree that is used as the window's contents. */ void* CreateContents(void* parent); private: void UpdateTitle(); /** * Ensure that the shell's minimum size is equal to the minimum size * of the first part added to the shell. */ void UpdateMinimumSize(); static IWorkbenchPartReference::Pointer GetPartReference( StackablePart::Pointer pane); /** * Closes this window and disposes its shell. */ bool HandleClose(); /** * Prompts for and handles the saving of dirty, saveable views * @param views The list of ViewPanes * @return true unless the user cancels the save(s) */ bool HandleSaves(std::list views); /** * Answer a list of the view panes. */ void CollectViewPanes(std::list& result, const std::list& parts); }; } #endif /* BERRYDETACHEDWINDOW_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDragUtil.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDragUtil.cpp index 35ceffccdb..1d6f73302a 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDragUtil.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDragUtil.cpp @@ -1,363 +1,363 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryDragUtil.h" -#include "../berryGeometry.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" -#include "../tweaklets/berryDnDTweaklet.h" -#include "../tweaklets/berryITracker.h" +#include "berryGeometry.h" +#include "tweaklets/berryGuiWidgetsTweaklet.h" +#include "tweaklets/berryDnDTweaklet.h" +#include "tweaklets/berryITracker.h" namespace berry { const std::string DragUtil::DROP_TARGET_ID = "org.blueberry.ui.internal.dropTarget"; TestDropLocation::Pointer DragUtil::forcedDropTarget(0); std::list DragUtil::defaultTargets = std::list< IDragOverListener::Pointer>(); DragUtil::TrackerMoveListener::TrackerMoveListener(Object::Pointer draggedItem, const Rectangle& sourceBounds, const Point& initialLocation, bool allowSnapping) : allowSnapping(allowSnapping), draggedItem(draggedItem), sourceBounds( sourceBounds), initialLocation(initialLocation) { } GuiTk::IControlListener::Events::Types DragUtil::TrackerMoveListener::GetEventTypes() const { return Events::MOVED; } void DragUtil::TrackerMoveListener::ControlMoved( GuiTk::ControlEvent::Pointer event) { // Get the curslor location as a point Point location(event->x, event->y); // Select a drop target; use the global one by default IDropTarget::Pointer target; void* targetControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorControl(); // Get the ITracker which fired the event ITracker* tracker = static_cast (event->item); // Get the drop target for this location target = DragUtil::GetDropTarget(targetControl, draggedItem, location, tracker->GetRectangle()); // Set up the tracker feedback based on the target Rectangle snapTarget; if (target != 0) { snapTarget = target->GetSnapRectangle(); tracker->SetCursor(target->GetCursor()); } else { tracker->SetCursor(DnDTweaklet::CURSOR_INVALID); } // If snapping then reset the tracker's rectangle based on the current drop target if (allowSnapping) { if (snapTarget.width == 0 || snapTarget.height == 0) { snapTarget = Rectangle(sourceBounds.x + location.x - initialLocation.x, sourceBounds.y + location.y - initialLocation.y, sourceBounds.width, sourceBounds.height); } // Try to prevent flicker: don't change the rectangles if they're already in // the right location Rectangle currentRectangle = tracker->GetRectangle(); if (!(currentRectangle == snapTarget)) { tracker->SetRectangle(snapTarget); } } } DragUtil::TargetListType::Pointer DragUtil::GetTargetList(void* control) { Object::Pointer data = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetData( control, DROP_TARGET_ID); TargetListType::Pointer list = data.Cast (); return list; } IDropTarget::Pointer DragUtil::GetDropTarget(const std::list< IDragOverListener::Pointer>& toSearch, void* mostSpecificControl, Object::Pointer draggedObject, const Point& position, const Rectangle& dragRectangle) { for (std::list::const_iterator iter = toSearch.begin(); iter != toSearch.end(); ++iter) { IDragOverListener::Pointer next = *iter; IDropTarget::Pointer dropTarget = next->Drag(mostSpecificControl, draggedObject, position, dragRectangle); if (dropTarget != 0) { return dropTarget; } } return IDropTarget::Pointer(0); } void DragUtil::AddDragTarget(void* control, IDragOverListener::Pointer target) { if (control == 0) { defaultTargets.push_back(target); } else { TargetListType::Pointer targetList = GetTargetList(control); if (targetList == 0) { targetList = new TargetListType(); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetData(control, DROP_TARGET_ID, targetList); } targetList->push_back(target); } } void DragUtil::RemoveDragTarget(void* control, IDragOverListener::Pointer target) { if (control == 0) { defaultTargets.remove(target); } else { TargetListType::Pointer targetList = GetTargetList(control); if (targetList != 0) { targetList->remove(target); if (targetList->empty()) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetData(control, DROP_TARGET_ID, Object::Pointer(0)); } } } } Rectangle DragUtil::GetDisplayBounds(void* boundsControl) { void* parent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent( boundsControl); if (parent == 0) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(boundsControl); } Rectangle rect = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds( boundsControl); return Geometry::ToDisplay(parent, rect); } bool DragUtil::PerformDrag(Object::Pointer draggedItem, const Rectangle& sourceBounds, const Point& initialLocation, bool allowSnapping) { IDropTarget::Pointer target = DragToTarget(draggedItem, sourceBounds, initialLocation, allowSnapping); if (target == 0) { return false; } target->Drop(); target->DragFinished(true); return true; } void DragUtil::ForceDropLocation(TestDropLocation::Pointer forcedLocation) { forcedDropTarget = forcedLocation; } IDropTarget::Pointer DragUtil::DragToTarget(Object::Pointer draggedItem, const Rectangle& sourceBounds, const Point& initialLocation, bool allowSnapping) { //final Display display = Display.getCurrent(); // Testing...immediately 'drop' onto the test target if (forcedDropTarget != 0) { Point location = forcedDropTarget->GetLocation(); void* currentControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->FindControl( forcedDropTarget->GetShells(), location); return GetDropTarget(currentControl, draggedItem, location, sourceBounds); } // Create a tracker. This is just an XOR rect on the screen. // As it moves we notify the drag listeners. ITracker* tracker = Tweaklets::Get(DnDTweaklet::KEY)->CreateTracker(); //tracker.setStippled(true); GuiTk::IControlListener::Pointer trackerListener(new TrackerMoveListener( draggedItem, sourceBounds, initialLocation, allowSnapping)); tracker->AddControlListener(trackerListener); // Setup...when the drag starts we might already be over a valid target, check this... // If there is a 'global' target then skip the check IDropTarget::Pointer target; void* startControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorControl(); if (startControl != 0 && allowSnapping) { target = GetDropTarget(startControl, draggedItem, initialLocation, sourceBounds); } // Set up an initial tracker rectangle Rectangle startRect = sourceBounds; if (target != 0) { Rectangle rect = target->GetSnapRectangle(); if (rect.width != 0 && rect.height != 0) { startRect = rect; } tracker->SetCursor(target->GetCursor()); } if (startRect.width != 0 && startRect.height != 0) { tracker->SetRectangle(startRect); } // Tracking Loop...tracking is preformed on the 'SWT.Move' listener registered // against the tracker. // // HACK: // // Some control needs to capture the mouse during the drag or other // // controls will interfere with the cursor // Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); // if (shell != null) // { // shell.setCapture(true); // } // Run tracker until mouse up occurs or escape key pressed. bool trackingOk = tracker->Open(); // // HACK: // // Release the mouse now // if (shell != null) // { // shell.setCapture(false); // } // Done tracking... // Get the current drop target IDropTarget::Pointer dropTarget; Point finalLocation = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorLocation(); void* targetControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetCursorControl(); dropTarget = GetDropTarget(targetControl, draggedItem, finalLocation, tracker->GetRectangle()); // Cleanup... delete tracker; // if we're going to perform a 'drop' then delay the issuing of the 'finished' // callback until after it's done... if (trackingOk) { return dropTarget; } else if (dropTarget != 0) { // If the target can handle a 'finished' notification then send one dropTarget->DragFinished(false); } return IDropTarget::Pointer(0); } IDropTarget::Pointer DragUtil::GetDropTarget(void* toSearch, Object::Pointer draggedObject, const Point& position, const Rectangle& dragRectangle) { // Search for a listener by walking the control's parent hierarchy for (void* current = toSearch; current != 0; current = Tweaklets::Get( GuiWidgetsTweaklet::KEY)->GetParent(current)) { TargetListType::Pointer targetList = GetTargetList(current); std::list targets; if (targetList != 0) targets.assign(targetList->begin(), targetList->end()); IDropTarget::Pointer dropTarget = GetDropTarget(targets, toSearch, draggedObject, position, dragRectangle); if (dropTarget != 0) { return dropTarget; } // // Don't look to parent shells for drop targets // if (current instanceof Shell) { // break; // } } // No controls could handle this event -- check for default targets return GetDropTarget(defaultTargets, toSearch, draggedObject, position, dragRectangle); } //Point DragUtil::GetEventLoc(GuiTk::ControlEvent::Pointer event) //{ // Control ctrl = (Control) event.widget; // return ctrl.toDisplay(new Point(event.x, event.y)); //} } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDragUtil.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDragUtil.h index 34b3e889d4..77b592062b 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDragUtil.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryDragUtil.h @@ -1,215 +1,215 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYDRAGUTIL_H_ #define BERRYDRAGUTIL_H_ #include -#include "../berryRectangle.h" -#include "../guitk/berryGuiTkIControlListener.h" +#include "berryRectangle.h" +#include "guitk/berryGuiTkIControlListener.h" #include "berryTestDropLocation.h" #include "berryIDragOverListener.h" #include "berryIDropTarget.h" #include #include namespace berry { /** * Provides the methods for attaching drag-and-drop listeners to SWT controls. */ class BERRY_UI DragUtil { public: typedef ObjectList TargetListType; private: static const std::string DROP_TARGET_ID; //$NON-NLS-1$ /** * The location where all drags will end. If this is non-null, then * all user input is ignored in drag/drop. If null, we use user input * to determine where objects should be dropped. */ static TestDropLocation::Pointer forcedDropTarget; /** * List of IDragOverListener */ static std::list defaultTargets; /** * Return the list of 'IDragOverListener' elements associated with * the given control. If there's a 'global' listener then always * return it. * * @param control * @return */ static TargetListType::Pointer GetTargetList(void* control); /** * Given a list of IDragOverListeners and a description of what is being dragged, it returns * a IDropTarget for the current drop. * * @param toSearch * @param mostSpecificControl * @param draggedObject * @param position * @param dragRectangle * @return */ static IDropTarget::Pointer GetDropTarget(const std::list& toSearch, void* mostSpecificControl, Object::Pointer draggedObject, const Point &position, const Rectangle& dragRectangle); struct TrackerMoveListener : public GuiTk::IControlListener { TrackerMoveListener(Object::Pointer draggedItem, const Rectangle& sourceBounds, const Point& initialLocation, bool allowSnapping); Events::Types GetEventTypes() const; void ControlMoved(GuiTk::ControlEvent::Pointer event); private: bool allowSnapping; Object::Pointer draggedItem; Rectangle sourceBounds; Point initialLocation; }; public: /** * Sets the drop target for the given control. It is possible to add one or more * targets for a "null" control. This becomes a default target that is used if no * other targets are found (for example, when dragging objects off the application * window). * * @param control the control that should be treated as a drag target, or null * to indicate the default target * @param target the drag target to handle the given control */ static void AddDragTarget(void* control, IDragOverListener::Pointer target); /** * Removes a drop target from the given control. * * @param control * @param target */ static void RemoveDragTarget(void* control, IDragOverListener::Pointer target); /** * Shorthand method. Returns the bounding rectangle for the given control, in * display coordinates. * * @param draggedItem * @param boundsControl * @return */ static Rectangle GetDisplayBounds(void* boundsControl); static bool PerformDrag(Object::Pointer draggedItem, const Rectangle& sourceBounds, const Point& initialLocation, bool allowSnapping); // /** // * Drags the given item to the given location (in display coordinates). This // * method is intended for use by test suites. // * // * @param draggedItem object being dragged // * @param finalLocation location being dragged to // * @return true iff the drop was accepted // */ // static bool DragTo(Display display, Object draggedItem, // Point finalLocation, Rectangle dragRectangle) { // Control currentControl = SwtUtil.findControl(display, finalLocation); // // IDropTarget target = getDropTarget(currentControl, draggedItem, // finalLocation, dragRectangle); // // if (target == null) { // return false; // } // // target.drop(); // // return true; // } /** * Forces all drags to end at the given position (display coordinates). Intended * for use by test suites. If this method is called, then all subsequent calls * to performDrag will terminate immediately and behave as though the object were * dragged to the given location. Calling this method with null cancels this * behavior and causes performDrag to behave normally. * * @param forcedLocation location where objects will be dropped (or null to * cause drag/drop to behave normally). */ static void ForceDropLocation(TestDropLocation::Pointer forcedLocation); /** * Drags the given item, given an initial bounding rectangle in display coordinates. * Due to a quirk in the Tracker class, changing the tracking rectangle when using the * keyboard will also cause the mouse cursor to move. Since "snapping" causes the tracking * rectangle to change based on the position of the mouse cursor, it is impossible to do * drag-and-drop with the keyboard when snapping is enabled. * * @param draggedItem object being dragged * @param sourceBounds initial bounding rectangle for the dragged item * @param initialLocation initial position of the mouse cursor * @param allowSnapping true iff the rectangle should snap to the drop location. This must * be false if the user might be doing drag-and-drop using the keyboard. * * @return */ static IDropTarget::Pointer DragToTarget(Object::Pointer draggedItem, const Rectangle& sourceBounds, const Point& initialLocation, bool allowSnapping); /** * Returns the drag target for the given control or null if none. * * @param toSearch * @param e * @return */ static IDropTarget::Pointer GetDropTarget(void* toSearch, Object::Pointer draggedObject, const Point& position, const Rectangle& dragRectangle); /** * Returns the location of the given event, in display coordinates * @return */ //static Point GetEventLoc(GuiTk::ControlEvent::Pointer event); }; } #endif /* BERRYDRAGUTIL_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorAreaHelper.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorAreaHelper.cpp index b56bef1c34..8ebf123ae2 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorAreaHelper.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorAreaHelper.cpp @@ -1,268 +1,268 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryEditorAreaHelper.h" #include "berryEditorSashContainer.h" #include "berryPartSite.h" -#include "../berryIPageLayout.h" +#include "berryIPageLayout.h" #include "berryPartPane.h" namespace berry { void EditorAreaHelper::CloseEditor(PartPane::Pointer pane) { if (pane != 0) { editorArea->RemoveEditor(pane); } } void EditorAreaHelper::AddToLayout(PartPane::Pointer pane, PartStack::Pointer stack) { //EditorStack stack = editorArea.getActiveWorkbook(); pane->SetContainer(stack); editorArea->AddEditor(pane, stack); } EditorAreaHelper::EditorAreaHelper(WorkbenchPage* page) { this->editorArea = new EditorSashContainer(IPageLayout::ID_EDITOR_AREA, page, page->GetClientComposite()); this->editorArea->CreateControl(page->GetClientComposite()); this->editorArea->SetActive(true); } void EditorAreaHelper::DisplayEditorList() { PartStack::Pointer activeWorkbook = editorArea->GetActiveWorkbook(); if (activeWorkbook != 0) { activeWorkbook->ShowPartList(); } } void EditorAreaHelper::CloseEditor(IEditorReference::Pointer ref) { PartPane::Pointer pane = ref.Cast()->GetPane(); this->CloseEditor(pane); } void EditorAreaHelper::CloseEditor(IEditorPart::Pointer part) { PartPane::Pointer pane = part->GetSite().Cast()->GetPane(); this->CloseEditor(pane); } void EditorAreaHelper::DerefPart(StackablePart::Pointer part) { // Get vital part stats before reparenting. IStackableContainer::Pointer oldContainer = part->GetContainer(); // Reparent the part back to the main window //part.reparent(editorArea.getParent()); // Update container. if (oldContainer == 0) { return; } oldContainer->Remove(part); std::list children = oldContainer->GetChildren(); if (children.empty()) { // There are no more children in this container, so get rid of it if (oldContainer.Cast()) { LayoutPart::Pointer parent = oldContainer.Cast(); ILayoutContainer::Pointer parentContainer = parent->GetContainer(); if (parentContainer != 0) { parentContainer->Remove(parent); parent->Dispose(); } } } } EditorAreaHelper::~EditorAreaHelper() { if (editorArea != 0) { editorArea->SetActive(false); editorArea->Dispose(); } } std::string EditorAreaHelper::GetActiveEditorWorkbookID() { return editorArea->GetActiveWorkbookID(); } PartStack::Pointer EditorAreaHelper::GetActiveWorkbook() { return editorArea->GetActiveWorkbook(); } LayoutPart::Pointer EditorAreaHelper::GetLayoutPart() { LayoutPart::Pointer layoutPart = editorArea.Cast(); return layoutPart; } IEditorReference::Pointer EditorAreaHelper::GetVisibleEditor() { PartStack::Pointer activeWorkbook = editorArea->GetActiveWorkbook(); PartPane::Pointer pane = activeWorkbook->GetSelection().Cast(); if (pane != 0) { IEditorReference::Pointer result = pane->GetPartReference().Cast(); return result; } return IEditorReference::Pointer(0); } void EditorAreaHelper::MoveEditor(IEditorPart::Pointer /*part*/, int /*position*/) { ///*EditorPane pane = (EditorPane)*/((EditorSite) part.getSite()).getPane(); //TODO commented this out during presentations works //pane.getWorkbook().reorderTab(pane, position); } void EditorAreaHelper::AddEditor(EditorReference::Pointer ref, const std::string& workbookId) { std::list refs = editorArea->GetPage()->GetEditorReferences(); for (std::list::iterator iter = refs.begin(); iter != refs.end(); ++iter) { if (ref == (*iter)) { return; } } PartStack::Pointer stack = this->GetWorkbookFromID(workbookId); if (stack == 0) { stack = this->GetActiveWorkbook(); } this->AddToLayout(ref->GetPane(), stack); editorArea->GetPage()->PartAdded(ref); } bool EditorAreaHelper::RestoreState(IMemento::Pointer memento) { // Restore the editor area workbooks layout/relationship return editorArea->RestoreState(memento); } bool EditorAreaHelper::RestorePresentationState(IMemento::Pointer areaMem) { return editorArea->RestorePresentationState(areaMem); } bool EditorAreaHelper::SaveState(IMemento::Pointer memento) { // Save the editor area workbooks layout/relationship return editorArea->SaveState(memento); } void EditorAreaHelper::SetActiveEditorWorkbookFromID(const std::string& id) { editorArea->SetActiveWorkbookFromID(id); } void EditorAreaHelper::SetActiveWorkbook(PartStack::Pointer workbook, bool hasFocus) { editorArea->SetActiveWorkbook(workbook, hasFocus); } bool EditorAreaHelper::SetVisibleEditor(IEditorReference::Pointer ref, bool setFocus) { IEditorReference::Pointer visibleEditor = this->GetVisibleEditor(); if (ref != visibleEditor) { IWorkbenchPart::Pointer part = ref->GetPart(true); PartPane::Pointer pane; if (part != 0) { pane = part->GetSite().Cast()->GetPane(); } if (pane != 0) { pane->GetContainer().Cast()->SetSelection(pane); if (setFocus) { part->SetFocus(); } return true; } } return false; } std::list EditorAreaHelper::GetWorkbooks() { return editorArea->GetEditorWorkbooks(); } std::list EditorAreaHelper::GetEditors() { std::list result; std::list workbooks = editorArea->GetEditorWorkbooks(); for (std::list::iterator iter = workbooks.begin(); iter != workbooks.end(); ++iter) { PartStack::Pointer stack = *iter; std::list children = stack->GetChildren(); for (std::list::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { StackablePart::Pointer part = *childIter; result.push_back(part.Cast()->GetPartReference().Cast()); } } return result; } PartStack::Pointer EditorAreaHelper::GetWorkbookFromID(const std::string& workbookId) { return editorArea->GetWorkbookFromID(workbookId); } void EditorAreaHelper::UpdateStackButtons() { editorArea->UpdateStackButtons(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorDescriptor.cpp index 75ffeaebd1..ae036e273a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorDescriptor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorDescriptor.cpp @@ -1,450 +1,450 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryEditorDescriptor.h" #include "berryWorkbenchRegistryConstants.h" #include "berryWorkbenchPlugin.h" -#include "../berryEditorPart.h" +#include "berryEditorPart.h" #include "berryImageDescriptor.h" namespace berry { const int EditorDescriptor::OPEN_INTERNAL = 0x01; const int EditorDescriptor::OPEN_INPLACE = 0x02; const int EditorDescriptor::OPEN_EXTERNAL = 0x04; EditorDescriptor::EditorDescriptor(const std::string& id2, IConfigurationElement::Pointer element) : testImage(true), matchingStrategyChecked(false), openMode(0) { this->SetID(id2); this->SetConfigurationElement(element); } EditorDescriptor::EditorDescriptor() : testImage(true), matchingStrategyChecked(false), openMode(0) { } //IEditorActionBarContributor::Pointer EditorDescriptor::CreateActionBarContributor() //{ // // Handle case for predefined editor descriptors, like the // // one for IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID, which // // don't have a configuration element. // if (configurationElement.IsNull()) // { // return IEditorActionBarContributor::Pointer(); // } // // // Get the contributor class name. // std::string className; // if (!configurationElement->GetAttribute(IWorkbenchRegistryConstants::ATT_CONTRIBUTOR_CLASS, className)) // { // return IEditorActionBarContributor::Pointer(); // } // // // Create the contributor object. // IEditorActionBarContributor contributor; // try // { // contributor = configurationElement->CreateExecutableExtension( // IWorkbenchRegistryConstants::ATT_CONTRIBUTOR_CLASS); // } // catch (CoreException e) // { // WorkbenchPlugin::Log("Unable to create editor contributor: " + //$NON-NLS-1$ // id, e); // } // return contributor; //} std::string EditorDescriptor::GetEditorClassName() const { if (configurationElement.IsNull()) { return className; } return RegistryReader::GetClassValue(configurationElement, WorkbenchRegistryConstants::ATT_CLASS); } IConfigurationElement::Pointer EditorDescriptor::GetConfigurationElement() const { return configurationElement; } IEditorPart::Pointer EditorDescriptor::CreateEditor() { IEditorPart::Pointer extension( configurationElement->CreateExecutableExtension ( WorkbenchRegistryConstants::ATT_CLASS)); if (extension.IsNull()) { // support legacy BlueBerry extensions extension = configurationElement->CreateExecutableExtension ( WorkbenchRegistryConstants::ATT_CLASS, IEditorPart::GetManifestName()); } return extension; } std::string EditorDescriptor::GetFileName() const { //if (program == null) //{ if (configurationElement.IsNull()) { return fileName; } std::string val; configurationElement->GetAttribute(WorkbenchRegistryConstants::ATT_COMMAND, val); return val; //} //return program.getName(); } std::string EditorDescriptor::GetId() const { //if (program == null) //{ if (configurationElement.IsNull()) { return id; } std::string val; configurationElement->GetAttribute(WorkbenchRegistryConstants::ATT_ID, val); return val; //} //return Util.safeString(program.getName()); } SmartPointer EditorDescriptor::GetImageDescriptor() const { if (testImage) { testImage = false; if (!imageDesc) { std::string imageFileName(this->GetImageFilename()); std::string command(this->GetFileName()); if (!imageFileName.empty() && configurationElement) { imageDesc = AbstractUICTKPlugin::ImageDescriptorFromPlugin( configurationElement->GetContributor(), imageFileName); } else if (!command.empty()) { //imageDesc = WorkbenchImages.getImageDescriptorFromProgram( // command, 0); } } this->VerifyImage(); } return imageDesc; } void EditorDescriptor::VerifyImage() const { //TODO Editor verify image // if (!imageDesc) { // imageDesc = WorkbenchImages // .getImageDescriptor(ISharedImages.IMG_OBJ_FILE); // } // else { // Image img = imageDesc.createImage(false); // if (img == null) { // // @issue what should be the default image? // imageDesc = WorkbenchImages // .getImageDescriptor(ISharedImages.IMG_OBJ_FILE); // } else { // img.dispose(); // } // } } std::string EditorDescriptor::GetImageFilename() const { if (!configurationElement) { return imageFilename; } std::string filename; configurationElement->GetAttribute(WorkbenchRegistryConstants::ATT_ICON, filename); return filename; } std::string EditorDescriptor::GetLabel() const { //if (program == null) //{ if (configurationElement.IsNull()) { return editorName; } std::string val; configurationElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME, val); return val; //} //return program.getName(); } std::string EditorDescriptor::GetLauncher() const { if (configurationElement.IsNull()) { return launcherName; } std::string val; configurationElement->GetAttribute(WorkbenchRegistryConstants::ATT_LAUNCHER, val); return val; } std::string EditorDescriptor::GetPluginID() const { if (!configurationElement.IsNull()) { return configurationElement->GetContributor(); } return pluginIdentifier; } bool EditorDescriptor::IsInternal() const { return this->GetOpenMode() == OPEN_INTERNAL; } bool EditorDescriptor::IsOpenInPlace() const { return this->GetOpenMode() == OPEN_INPLACE; } bool EditorDescriptor::IsOpenExternal() const { return this->GetOpenMode() == OPEN_EXTERNAL; } bool EditorDescriptor::LoadValues(IMemento::Pointer /*memento*/) { // editorName = memento.getString(IWorkbenchConstants.TAG_LABEL); // imageFilename = memento.getString(IWorkbenchConstants.TAG_IMAGE); // className = memento.getString(IWorkbenchConstants.TAG_CLASS); // launcherName = memento.getString(IWorkbenchConstants.TAG_LAUNCHER); // fileName = memento.getString(IWorkbenchConstants.TAG_FILE); // id = Util.safeString(memento.getString(IWorkbenchConstants.TAG_ID)); // pluginIdentifier = memento.getString(IWorkbenchConstants.TAG_PLUGIN); // // Integer openModeInt = memento // .getInteger(IWorkbenchConstants.TAG_OPEN_MODE); // if (openModeInt != null) // { // openMode = openModeInt.intValue(); // } // else // { // // legacy: handle the older attribute names, needed to allow reading of pre-3.0-RCP workspaces // boolean internal = new Boolean(memento // .getString(IWorkbenchConstants.TAG_INTERNAL)) // .booleanValue(); // boolean openInPlace = new Boolean(memento // .getString(IWorkbenchConstants.TAG_OPEN_IN_PLACE)) // .booleanValue(); // if (internal) // { // openMode = OPEN_INTERNAL; // } // else // { // if (openInPlace) // { // openMode = OPEN_INPLACE; // } // else // { // openMode = OPEN_EXTERNAL; // } // } // } // if (openMode != OPEN_EXTERNAL && openMode != OPEN_INTERNAL && openMode // != OPEN_INPLACE) // { // WorkbenchPlugin // .log("Ignoring editor descriptor with invalid openMode: " + this); //$NON-NLS-1$ // return false; // } // // String programName = memento // .getString(IWorkbenchConstants.TAG_PROGRAM_NAME); // if (programName != null) // { // this.program = findProgram(programName); // } return true; } void EditorDescriptor::SaveValues(IMemento::Pointer /*memento*/) { // memento.putString(IWorkbenchConstants.TAG_LABEL, getLabel()); // memento.putString(IWorkbenchConstants.TAG_IMAGE, getImageFilename()); // memento.putString(IWorkbenchConstants.TAG_CLASS, getEditorClassName()); // memento.putString(IWorkbenchConstants.TAG_LAUNCHER, getLauncher()); // memento.putString(IWorkbenchConstants.TAG_FILE, getFileName()); // memento.putString(IWorkbenchConstants.TAG_ID, getId()); // memento.putString(IWorkbenchConstants.TAG_PLUGIN, getPluginId()); // // memento.putInteger(IWorkbenchConstants.TAG_OPEN_MODE, getOpenMode()); // // legacy: handle the older attribute names, needed to allow reading of workspace by pre-3.0-RCP // memento.putString(IWorkbenchConstants.TAG_INTERNAL, String // .valueOf(isInternal())); // memento.putString(IWorkbenchConstants.TAG_OPEN_IN_PLACE, String // .valueOf(isOpenInPlace())); // // if (this.program != null) // { // memento.putString(IWorkbenchConstants.TAG_PROGRAM_NAME, // this.program.getName()); // } } int EditorDescriptor::GetOpenMode() const { if (configurationElement.IsNull()) { // if we've been serialized, return our serialized value return openMode; } else if (this->GetLauncher() != "") { // open using a launcer return EditorDescriptor::OPEN_EXTERNAL; } else if (this->GetFileName() != "") { // open using an external editor return EditorDescriptor::OPEN_EXTERNAL; } else if (this->GetPluginId() != "") { // open using an internal editor return EditorDescriptor::OPEN_INTERNAL; } else { return 0; // default for system editor } } void EditorDescriptor::SetClassName(const std::string& newClassName) { className = newClassName; } void EditorDescriptor::SetConfigurationElement( IConfigurationElement::Pointer newConfigurationElement) { configurationElement = newConfigurationElement; } void EditorDescriptor::SetFileName(const std::string& aFileName) { fileName = aFileName; } void EditorDescriptor::SetID(const std::string& anID) { id = anID; } void EditorDescriptor::SetLauncher(const std::string& newLauncher) { launcherName = newLauncher; } void EditorDescriptor::SetName(const std::string& newName) { editorName = newName; } void EditorDescriptor::SetOpenMode(int mode) { openMode = mode; } void EditorDescriptor::SetPluginIdentifier(const std::string& anID) { pluginIdentifier = anID; } std::string EditorDescriptor::ToString() const { return "EditorDescriptor(id=" + this->GetId() + ", label=" + this->GetLabel() + ")"; //$NON-NLS-2$ //$NON-NLS-3$//$NON-NLS-1$ } std::string EditorDescriptor::GetLocalId() const { return this->GetId(); } std::string EditorDescriptor::GetPluginId() const { return this->GetPluginID(); } IEditorMatchingStrategy::Pointer EditorDescriptor::GetEditorMatchingStrategy() { if (matchingStrategy.IsNull() && !matchingStrategyChecked) { matchingStrategyChecked = true; if (/*program == null &&*/!configurationElement.IsNull()) { std::string strategy; if (configurationElement->GetAttribute( WorkbenchRegistryConstants::ATT_MATCHING_STRATEGY, strategy)) { try { matchingStrategy = configurationElement->CreateExecutableExtension< IEditorMatchingStrategy> ( WorkbenchRegistryConstants::ATT_MATCHING_STRATEGY); if (matchingStrategy.IsNull()) { // support legacy BlueBerry extensions matchingStrategy = configurationElement->CreateExecutableExtension< IEditorMatchingStrategy> ( WorkbenchRegistryConstants::ATT_MATCHING_STRATEGY, IEditorMatchingStrategy::GetManifestName()); } } catch (CoreException e) { WorkbenchPlugin::Log( "Error creating editor management policy for editor id " + this->GetId(), e); //$NON-NLS-1$ } } } } return matchingStrategy; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorDescriptor.h index c976499fe7..ab4de44c58 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorDescriptor.h @@ -1,391 +1,391 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYEDITORDESCRIPTOR_H_ #define BERRYEDITORDESCRIPTOR_H_ -#include "../berryIEditorDescriptor.h" -#include "../berryIMemento.h" +#include "berryIEditorDescriptor.h" +#include "berryIMemento.h" #include namespace berry { struct IEditorPart; /** * \ingroup org_blueberry_ui_internal * * @see IEditorDescriptor */ class BERRY_UI EditorDescriptor : public IEditorDescriptor { //, Serializable, IPluginContribution { public: berryObjectMacro(EditorDescriptor) // @issue the following constants need not be public; see bug 47600 /** * Open internal constant. Value 0x01. */ static const int OPEN_INTERNAL; // = 0x01; /** * Open in place constant. Value 0x02. */ static const int OPEN_INPLACE; // = 0x02; /** * Open external constant. Value 0x04. */ static const int OPEN_EXTERNAL; // = 0x04; private: std::string editorName; std::string imageFilename; mutable SmartPointer imageDesc; mutable bool testImage; std::string className; std::string launcherName; std::string fileName; std::string id; bool matchingStrategyChecked; IEditorMatchingStrategy::Pointer matchingStrategy; //Program program; //The id of the plugin which contributed this editor, null for external editors std::string pluginIdentifier; int openMode; IConfigurationElement::Pointer configurationElement; /** * Create a new instance of an editor descriptor. Limited * to internal framework calls. * @param element * @param id2 */ /* package */ public: EditorDescriptor(const std::string& id2, IConfigurationElement::Pointer element); /** * Create a new instance of an editor descriptor. Limited * to internal framework calls. */ /* package */ public: EditorDescriptor(); /** * Creates a descriptor for an external program. * * @param filename the external editor full path and filename * @return the editor descriptor */ //public: static EditorDescriptor::Pointer CreateForProgram(const std::string& filename) { // if (filename == null) { // throw new IllegalArgumentException(); // } // EditorDescriptor editor = new EditorDescriptor(); // // editor.setFileName(filename); // editor.setID(filename); // editor.setOpenMode(OPEN_EXTERNAL); // // //Isolate the program name (no directory or extension) // int start = filename.lastIndexOf(File.separator); // String name; // if (start != -1) { // name = filename.substring(start + 1); // } else { // name = filename; // } // int end = name.lastIndexOf('.'); // if (end != -1) { // name = name.substring(0, end); // } // editor.setName(name); // // // get the program icon without storing it in the registry // ImageDescriptor imageDescriptor = new ProgramImageDescriptor(filename, // 0); // editor.setImageDescriptor(imageDescriptor); // // return editor; // } /** * Return the program called programName. Return null if it is not found. * @return org.blueberry.swt.program.Program */ //private: static Program FindProgram(const std::string& programName) { // // Program[] programs = Program.getPrograms(); // for (int i = 0; i < programs.length; i++) { // if (programs[i].getName().equals(programName)) { // return programs[i]; // } // } // // return null; // } /** * Create the editor action bar contributor for editors of this type. * * @return the action bar contributor, or null */ //public: IEditorActionBarContributor::Pointer CreateActionBarContributor(); /** * Return the editor class name. * * @return the class name */ public: std::string GetEditorClassName() const; /** * Return the configuration element used to define this editor, or null. * * @return the element or null */ public: IConfigurationElement::Pointer GetConfigurationElement() const; /** * Create an editor part based on this descriptor. * * @return the editor part * @throws CoreException thrown if there is an issue creating the editor */ public: SmartPointer CreateEditor(); /** * Return the file name of the command to execute for this editor. * * @return the file name to execute */ public: std::string GetFileName() const; /** * Return the id for this editor. * * @return the id */ public: std::string GetId() const; /** * Return the image descriptor describing this editor. * * @return the image descriptor */ public: SmartPointer GetImageDescriptor() const; /** * Verifies that the image descriptor generates an image. If not, the * descriptor is replaced with the default image. * * @since 3.1 */ private: void VerifyImage() const; /** * The name of the image describing this editor. * * @return the image file name */ public: std::string GetImageFilename() const; /** * Return the user printable label for this editor. * * @return the label */ public: std::string GetLabel() const; /** * Returns the class name of the launcher. * * @return the launcher class name */ public: std::string GetLauncher() const; /** * Return the contributing plugin id. * * @return the contributing plugin id */ public: std::string GetPluginID() const; /** * Get the program for the receiver if there is one. * @return Program */ //public: Program GetProgram() { // return this.program; // } /* (non-Javadoc) * @see org.blueberry.ui.IEditorDescriptor#isInternal */ public: bool IsInternal() const; /* (non-Javadoc) * @see org.blueberry.ui.IEditorDescriptor#isOpenInPlace */ public: bool IsOpenInPlace() const; /* (non-Javadoc) * @see org.blueberry.ui.IEditorDescriptor#isOpenExternal */ public: bool IsOpenExternal() const; /** * Load the object properties from a memento. * * @return true if the values are valid, false otherwise */ protected: bool LoadValues(IMemento::Pointer memento); /** * Save the object values in a IMemento */ protected: void SaveValues(IMemento::Pointer memento); /** * Return the open mode of this editor. * * @return the open mode of this editor * @since 3.1 */ private: int GetOpenMode() const; /** * Set the class name of an internal editor. */ /* package */public: void SetClassName(const std::string& newClassName); /** * Set the configuration element which contributed this editor. */ /* package */public: void SetConfigurationElement( IConfigurationElement::Pointer newConfigurationElement); /** * Set the filename of an external editor. */ /* package */public: void SetFileName(const std::string& aFileName); /** * Set the id of the editor. * For internal editors this is the id as provided in the extension point * For external editors it is path and filename of the editor */ /* package */public: void SetID(const std::string& anID); /** * The Image to use to repesent this editor */ /* package */ // public : void SetImageDescriptor(ImageDescriptor desc) { // imageDesc = desc; // testImage = true; // } /** * The name of the image to use for this editor. */ /* package */ // public: void SetImageFilename(const std::string& aFileName) { // imageFilename = aFileName; // } /** * Sets the new launcher class name * * @param newLauncher the new launcher */ /* package */public: void SetLauncher(const std::string& newLauncher); /** * The label to show for this editor. */ /* package */public: void SetName(const std::string& newName); /** * Sets the open mode of this editor descriptor. * * @param mode the open mode * * @issue this method is public as a temporary fix for bug 47600 */ public: void SetOpenMode(int mode); /** * The id of the plugin which contributed this editor, null for external editors. */ /* package */public: void SetPluginIdentifier(const std::string& anID); /** * Set the receivers program. * @param newProgram */ /* package */ // public: void SetProgram(Program newProgram) { // // this.program = newProgram; // if (editorName == null) { // setName(newProgram.getName()); // } // } /** * For debugging purposes only. */ public: std::string ToString() const; /* (non-Javadoc) * @see org.blueberry.ui.activities.support.IPluginContribution#getLocalId() */ public: std::string GetLocalId() const; /* (non-Javadoc) * @see org.blueberry.ui.activities.support.IPluginContribution#getPluginId() */ public: std::string GetPluginId() const; /* (non-Javadoc) * @see org.blueberry.ui.IEditorDescriptor#getEditorManagementPolicy() */ public: IEditorMatchingStrategy::Pointer GetEditorMatchingStrategy(); }; } #endif /*BERRYEDITORDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorManager.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorManager.cpp index 63be5410dc..051964ba92 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorManager.cpp @@ -1,1296 +1,1296 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryEditorManager.h" -#include "../berryIWorkbenchPart.h" -#include "../berryIWorkbenchWindow.h" -#include "../berryIEditorRegistry.h" -#include "../berryUIException.h" +#include "berryIWorkbenchPart.h" +#include "berryIWorkbenchWindow.h" +#include "berryIEditorRegistry.h" +#include "berryUIException.h" #include "berryWorkbenchWindow.h" #include "berryWorkbenchPage.h" #include "berryEditorSite.h" #include "berryEditorReference.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include "berryNullEditorInput.h" #include "berryEditorAreaHelper.h" #include "berryPartStack.h" #include namespace berry { const std::string EditorManager::PIN_EDITOR_KEY = "PIN_EDITOR"; const std::string EditorManager::RESOURCES_TO_SAVE_MESSAGE = "Select resources to save:"; const std::string EditorManager::SAVE_RESOURCES_TITLE = "Save Resources"; EditorManager::EditorManager(WorkbenchWindow::Pointer wind, WorkbenchPage::Pointer workbenchPage, EditorAreaHelper* pres) : editorPresentation(pres), window(wind.GetPointer()), page(workbenchPage.GetPointer()) { poco_check_ptr(editorPresentation); poco_assert(window != 0); poco_assert(page != 0); //page.getExtensionTracker().registerHandler(this, null); } void EditorManager::CheckDeleteEditorResources() { // // get the current number of editors // IEditorReference[] editors = page.getEditorReferences(); // // If there are no editors // if (editors.length == 0) // { // if (editorPropChangeListnener != null) // { // // remove property change listener for editors // IPreferenceStore prefStore = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // prefStore // .removePropertyChangeListener(editorPropChangeListnener); // editorPropChangeListnener = null; // } // if (pinEditorHandlerActivation != null) // { // // remove pin editor keyboard shortcut handler // final IHandlerService handlerService = (IHandlerService) window.getWorkbench().getService(IHandlerService.class); // handlerService.deactivateHandler(pinEditorHandlerActivation); // pinEditorHandlerActivation = null; // } // } } //void EditorManager::CheckCreateEditorPropListener() //{ // if (editorPropChangeListnener == null) // { // // Add a property change listener for closing editors automatically // // preference // // Add or remove the pin icon accordingly // editorPropChangeListnener = new IPropertyChangeListener() // { // public void propertyChange(PropertyChangeEvent event) // { // if (event.getProperty().equals( // IPreferenceConstants.REUSE_EDITORS_BOOLEAN)) // { // IEditorReference[] editors = getEditors(); // for (int i = 0; i < editors.length; i++) // { // ((EditorReference) editors[i]).pinStatusUpdated(); // } // } // } // }; // WorkbenchPlugin.getDefault().getPreferenceStore() // .addPropertyChangeListener(editorPropChangeListnener); // } //} //void EditorManager::CheckCreatePinEditorShortcutKeyHandler() //{ // if (pinEditorHandlerActivation == null) // { // final Shell shell = window.getShell(); // final IHandler pinEditorHandler = new AbstractHandler() // { // public final Object execute(final ExecutionEvent event) // { // // check if the "Close editors automatically" preference is // // set // IPreferenceStore store = WorkbenchPlugin.getDefault().getPreferenceStore(); // if (store // .getBoolean(IPreferenceConstants.REUSE_EDITORS_BOOLEAN) // || ((TabBehaviour)Tweaklets.get(TabBehaviour.KEY)).alwaysShowPinAction()) // { // // IWorkbenchPartReference ref = editorPresentation // .getVisibleEditor(); // if (ref instanceof WorkbenchPartReference) // { // WorkbenchPartReference concreteRef = (WorkbenchPartReference) ref; // // concreteRef.setPinned(concreteRef.isPinned()); // } // } // return null; // } // }; // // // Assign the handler for the pin editor keyboard shortcut. // final IHandlerService handlerService = (IHandlerService) window.getWorkbench().getService(IHandlerService.class); // pinEditorHandlerActivation = handlerService.activateHandler( // "org.blueberry.ui.window.pinEditor", pinEditorHandler, //$NON-NLS-1$ // new ActiveShellExpression(shell)); // } //} std::vector EditorManager::CollectDirtyEditors() { std::vector result; std::list editors(page->GetEditorReferences()); for (std::list::iterator i = editors.begin(); i != editors.end(); ++i) { IEditorPart::Pointer part = (*i)->GetPart(false).Cast(); if (part.IsNotNull() && part->IsDirty()) { result.push_back(part); } } return result; } bool EditorManager::ContainsEditor(IEditorReference::Pointer ref) { std::list editors(page->GetEditorReferences()); return std::find(editors.begin(), editors.end(), ref) != editors.end(); } //EditorActionBars* EditorManager::CreateEditorActionBars( // EditorDescriptor::Pointer desc, IEditorSite::Pointer site) //{ // // Get the editor type. // String type = desc.getId(); // // // If an action bar already exists for this editor type return it. // EditorActionBars actionBars = (EditorActionBars) actionCache.get(type); // if (actionBars != null) // { // actionBars.addRef(); // return actionBars; // } // // // Create a new action bar set. // actionBars = new EditorActionBars(page, site.getWorkbenchWindow(), type); // actionBars.addRef(); // actionCache.put(type, actionBars); // // // Read base contributor. // IEditorActionBarContributor contr = desc.createActionBarContributor(); // if (contr != null) // { // actionBars.setEditorContributor(contr); // contr.init(actionBars, page); // } // // // Read action extensions. // EditorActionBuilder builder = new EditorActionBuilder(); // contr = builder.readActionExtensions(desc); // if (contr != null) // { // actionBars.setExtensionContributor(contr); // contr.init(actionBars, page); // } // // // Return action bars. // return actionBars; //} //EditorActionBars* EditorManager::CreateEmptyEditorActionBars( // IEditorSite::Pointer site) //{ // // Get the editor type. // String type = String.valueOf(System.currentTimeMillis()); // // // Create a new action bar set. // // Note: It is an empty set. // EditorActionBars actionBars = new EditorActionBars(page, site.getWorkbenchWindow(), type); // actionBars.addRef(); // actionCache.put(type, actionBars); // // // Return action bars. // return actionBars; //} //void EditorManager::DisposeEditorActionBars(EditorActionBars* actionBars) //{ // actionBars.removeRef(); // if (actionBars.getRef() <= 0) // { // String type = actionBars.getEditorType(); // actionCache.remove(type); // // refresh the cool bar manager before disposing of a cool item // ICoolBarManager2 coolBar = (ICoolBarManager2) window.getCoolBarManager2(); // if (coolBar != null) // { // coolBar.refresh(); // } // actionBars.dispose(); // } //} IEditorPart::Pointer EditorManager::FindEditor(IEditorInput::Pointer input) { return this->FindEditor("", input, IWorkbenchPage::MATCH_INPUT); } IEditorPart::Pointer EditorManager::FindEditor(const std::string& editorId, IEditorInput::Pointer input, int matchFlags) { std::vector refs(this->FindEditors(input, editorId, matchFlags)); if (refs.size() == 0) { return IEditorPart::Pointer(); } return refs[0]->GetEditor(true); } std::vector EditorManager::FindEditors( IEditorInput::Pointer input, const std::string& editorId, int matchFlags) { if (matchFlags == IWorkbenchPage::MATCH_NONE) { return std::vector(); } std::vector result; std::list othersList(page->GetEditorReferences()); if (!othersList.empty()) { IEditorReference::Pointer active = page->GetActiveEditorReference(); if (active.IsNotNull()) { othersList.remove(active); std::list activeList; activeList.push_back(active); this->FindEditors(activeList, input, editorId, matchFlags, result); } this->FindEditors(othersList, input, editorId, matchFlags, result); } return result; } void EditorManager::FindEditors( std::list& editorList, IEditorInput::Pointer input, const std::string& editorId, int matchFlags, std::vector& result) { if (matchFlags == IWorkbenchPage::MATCH_NONE) { return; } // Phase 0: Remove editors whose ids don't match (if matching by id) if (((matchFlags & IWorkbenchPage::MATCH_ID) != 0) && !editorId.empty()) { for (std::list::iterator i = editorList.begin(); i != editorList.end();) { if (editorId != (*i)->GetId()) { i = editorList.erase(i); continue; } ++i; } } // If not matching on editor input, just return the remaining editors. // In practice, this case is never used. if ((matchFlags & IWorkbenchPage::MATCH_INPUT) == 0) { result.insert(result.end(), editorList.begin(), editorList.end()); return; } // Phase 1: check editors that have their own matching strategy for (std::list::iterator i = editorList.begin(); i != editorList.end();) { EditorReference::Pointer editor = i->Cast(); IEditorDescriptor::Pointer desc = editor->GetDescriptor(); if (desc.IsNotNull()) { IEditorMatchingStrategy::Pointer matchingStrategy = desc ->GetEditorMatchingStrategy(); if (matchingStrategy.IsNotNull()) { i = editorList.erase(i); // We're handling this one here, so remove it // from the list. if (matchingStrategy->Matches(editor, input)) { result.push_back(editor); } continue; } } ++i; } // Phase 2: check materialized editors (without their own matching // strategy) for (std::list::iterator i = editorList.begin(); i != editorList.end();) { EditorReference::Pointer editor = i->Cast(); IEditorPart::Pointer part = editor->GetPart(false).Cast(); if (part.IsNotNull()) { i = editorList.erase(i); // We're handling this one here, so remove it from // the list. if (part->GetEditorInput().IsNotNull() && part->GetEditorInput() == input) { result.push_back(editor); } } else ++i; } // Phase 3: check unmaterialized editors for input equality, // delaying plug-in activation further by only restoring the editor // input // if the editor reference's factory id and name match. // std::string name = input->GetName(); // IPersistableElement persistable = input.getPersistable(); // if (name == null || persistable == null) // { // return; // } // String id = persistable.getFactoryId(); // if (id == null) // { // return; // } // for (Iterator i = editorList.iterator(); i.hasNext();) // { // EditorReference editor = (EditorReference) i.next(); // if (name.equals(editor.getName()) && id.equals(editor.getFactoryId())) // { // IEditorInput restoredInput; // try // { // restoredInput = editor.getEditorInput(); // if (Util.equals(restoredInput, input)) // { // result.add(editor); // } // } // catch (PartInitException e1) // { // WorkbenchPlugin.log(e1); // } // } // } } std::size_t EditorManager::GetEditorCount() { return page->GetEditorReferences().size(); } IEditorRegistry* EditorManager::GetEditorRegistry() { return WorkbenchPlugin::GetDefault()->GetEditorRegistry(); } std::vector EditorManager::GetDirtyEditors() { return this->CollectDirtyEditors(); } std::list EditorManager::GetEditors() { return page->GetEditorReferences(); } IEditorPart::Pointer EditorManager::GetVisibleEditor() { IEditorReference::Pointer ref = editorPresentation->GetVisibleEditor(); if (ref.IsNull()) { return IEditorPart::Pointer(0); } return ref->GetPart(true).Cast(); } bool EditorManager::IsSaveAllNeeded() { std::list editors(page->GetEditorReferences()); for (std::list::iterator i = editors.begin(); i != editors.end(); ++i) { if ((*i)->IsDirty()) { return true; } } return false; } IEditorReference::Pointer EditorManager::FindReusableEditor( EditorDescriptor::Pointer /*desc*/) { //return ((TabBehaviour)Tweaklets.get(TabBehaviour.KEY)).findReusableEditor(page); return IEditorReference::Pointer(0); } IEditorReference::Pointer EditorManager::OpenEditor( const std::string& editorId, IEditorInput::Pointer input, bool /*setVisible*/, IMemento::Pointer editorState) { if (input.IsNull()) { throw Poco::InvalidArgumentException(); } IEditorRegistry* reg = this->GetEditorRegistry(); EditorDescriptor::Pointer desc = reg->FindEditor(editorId).Cast(); if (desc.IsNull()) { throw PartInitException("Unable to open editor, unknown editor id", editorId); } return this->OpenEditorFromDescriptor(desc, input, editorState); } IEditorReference::Pointer EditorManager::OpenEditorFromDescriptor( EditorDescriptor::Pointer desc, IEditorInput::Pointer input, IMemento::Pointer editorState) { IEditorReference::Pointer result; if (desc->IsInternal()) { result = this->ReuseInternalEditor(desc, input); if (result.IsNull()) { result = new EditorReference(this, input, desc, editorState); } } // else if (desc->GetId() == IEditorRegistry::SYSTEM_INPLACE_EDITOR_ID) // { // if (ComponentSupport.inPlaceEditorSupported()) // { // result = new EditorReference(this, input, desc); // } // } // else if (desc->GetId() == IEditorRegistry::SYSTEM_EXTERNAL_EDITOR_ID) // { // IPathEditorInput pathInput = getPathEditorInput(input); // if (pathInput != null) // { // result = openSystemExternalEditor(pathInput.getPath()); // } // else // { // throw new PartInitException( // WorkbenchMessages.EditorManager_systemEditorError); // } // } // else if (desc->IsOpenExternal()) // { // result = openExternalEditor(desc, input); // } else { // this should never happen throw PartInitException("Invalid editor descriptor for id", desc->GetId()); } if (result.IsNotNull()) { this->CreateEditorTab(result.Cast(), ""); //$NON-NLS-1$ } // Workbench wb = (Workbench) window.getWorkbench(); // wb.getEditorHistory().add(input, desc); return result; } //IEditorReference::Pointer EditorManager::OpenExternalEditor( // EditorDescriptor::Pointer desc, IEditorInput::Pointer input) //{ // final CoreException ex[] = new CoreException[1]; // // final IPathEditorInput pathInput = getPathEditorInput(input); // if (pathInput != null && pathInput.getPath() != null) // { // BusyIndicator.showWhile(getDisplay(), new Runnable() // { // public void run() // { // try // { // if (desc.getLauncher() != null) // { // // open using launcher // Object launcher = WorkbenchPlugin.createExtension( // desc.getConfigurationElement(), "launcher"); //$NON-NLS-1$ // ((IEditorLauncher) launcher).open(pathInput // .getPath()); // } // else // { // // open using command // ExternalEditor oEditor = new ExternalEditor( // pathInput.getPath(), desc); // oEditor.open(); // } // } // catch (CoreException e) // { // ex[0] = e; // } // } // } // ); // } // else // { // throw new PartInitException(NLS.bind( // WorkbenchMessages.EditorManager_errorOpeningExternalEditor, // desc.getFileName(), desc.getId())); // } // // if (ex[0] != null) // { // throw new PartInitException(NLS.bind( // WorkbenchMessages.EditorManager_errorOpeningExternalEditor, // desc.getFileName(), desc.getId()), ex[0]); // } // // // we do not have an editor part for external editors // return null; //} void EditorManager::CreateEditorTab(EditorReference::Pointer ref, const std::string& workbookId) { editorPresentation->AddEditor(ref, workbookId); } EditorSite::Pointer EditorManager::CreateSite(IEditorReference::Pointer ref, IEditorPart::Pointer part, EditorDescriptor::Pointer desc, IEditorInput::Pointer input) const { EditorSite::Pointer site(new EditorSite(ref, part, page, desc)); if (desc.IsNotNull()) { //site.setActionBars(createEditorActionBars(desc, site)); } else { //site.setActionBars(createEmptyEditorActionBars(site)); } const std::string label = part->GetPartName(); // debugging only try { part->Init(site, input); // Sanity-check the site if (!(part->GetSite() == site) || !(part->GetEditorSite() == site)) { throw PartInitException("Editor initialization failed: " + desc->GetId() + ". Site is incorrect."); } } catch (PartInitException e) { throw e; } catch (std::exception e) { throw PartInitException("An exception was thrown during initialization", e.what()); } return site; } IEditorReference::Pointer EditorManager::ReuseInternalEditor( EditorDescriptor::Pointer /*desc*/, IEditorInput::Pointer /*input*/) { // poco_assert(desc.IsNotNull()); // "descriptor must not be null"); //$NON-NLS-1$ // poco_assert(input.IsNotNull()); // "input must not be null"); //$NON-NLS-1$ // // IEditorReference::Pointer reusableEditorRef = this->FindReusableEditor(desc); // if (reusableEditorRef.IsNotNull()) // { // return this->ReuseInternalEditor(page, this, editorPresentation, desc, input, // reusableEditorRef); // } return IEditorReference::Pointer(0); } IEditorPart::Pointer EditorManager::CreatePart(EditorDescriptor::Pointer desc) const { // try // { IEditorPart::Pointer result = desc->CreateEditor(); // IConfigurationElement element = desc.getConfigurationElement(); // if (element != null) // { // page.getExtensionTracker().registerObject( // element.getDeclaringExtension(), result, // IExtensionTracker.REF_WEAK); // } return result; // } // catch (CoreException e) // { // throw PartInitException(StatusUtil.newStatus( // desc.getPluginID(), // WorkbenchMessages.EditorManager_instantiationError, e)); // } } //IEditorReference::Pointer EditorManager::OpenSystemExternalEditor( // Poco::Path location) //{ // if (location == null) // { // throw new IllegalArgumentException(); // } // // final boolean result[] = // { false}; // BusyIndicator.showWhile(getDisplay(), new Runnable() // { // public void run() // { // if (location != null) // { // result[0] = Program.launch(location.toOSString()); // } // } // } // ); // // if (!result[0]) // { // throw new PartInitException(NLS.bind( // WorkbenchMessages.EditorManager_unableToOpenExternalEditor, // location)); // } // // // We do not have an editor part for external editors // return null; // } // ImageDescriptor EditorManager::FindImage(EditorDescriptor::Pointer desc, // Poco::Path path) // { // if (desc == null) // { // // @issue what should be the default image? // return ImageDescriptor.getMissingImageDescriptor(); // } // // if (desc.isOpenExternal() && path != null) // { // return PlatformUI.getWorkbench().getEditorRegistry() // .getImageDescriptor(path.toOSString()); // } // // return desc.getImageDescriptor(); // } bool EditorManager::RestoreState(IMemento::Pointer memento) { // Restore the editor area workbooks layout/relationship // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.EditorManager_problemsRestoringEditors, null); bool result = true; std::string activeWorkbookID; std::vector visibleEditors; std::vector activeEditor; IMemento::Pointer areaMem = memento->GetChild(WorkbenchConstants::TAG_AREA); if (areaMem) { //result.add(editorPresentation.restoreState(areaMem)); editorPresentation->RestoreState(areaMem); areaMem->GetString(WorkbenchConstants::TAG_ACTIVE_WORKBOOK, activeWorkbookID); } // Loop through the editors. std::vector editorMems(memento->GetChildren(WorkbenchConstants::TAG_EDITOR)); for (std::size_t x = 0; x < editorMems.size(); x++) { // for dynamic UI - call restoreEditorState to replace code which is // commented out RestoreEditorState(editorMems[x], visibleEditors, activeEditor); //, result); } // restore the presentation if (areaMem) { //result.add(editorPresentation.restorePresentationState(areaMem)); result &= editorPresentation->RestorePresentationState(areaMem); } try { // StartupThreading.runWithThrowable(new StartupRunnable() // { // // public void runWithException() throws Throwable // { // Update each workbook with its visible editor. for (std::size_t i = 0; i < visibleEditors.size(); i++) { SetVisibleEditor(visibleEditors[i], false); } // Update the active workbook if (!activeWorkbookID.empty()) { editorPresentation->SetActiveEditorWorkbookFromID(activeWorkbookID); } if (!activeEditor.empty() && activeEditor[0]) { IWorkbenchPart::Pointer editor = activeEditor[0]->GetPart(true); if (editor) { page->Activate(editor); } } // }}); } catch (...) { // The exception is already logged. // result // .add(new Status( // IStatus.ERR, // PlatformUI.PLUGIN_ID, // 0, // WorkbenchMessages.EditorManager_exceptionRestoringEditor, // t)); result &= false; } return result; } bool EditorManager::SaveAll(bool confirm, bool closing, bool addNonPartSources) { // Get the list of dirty editors and views. If it is // empty just return. std::vector parts(page->GetDirtyParts()); if (parts.empty()) { return true; } std::vector wbParts; for (std::vector::const_iterator i = parts.begin(); i != parts.end(); ++i) { if (IWorkbenchPart::Pointer part = i->Cast()) { wbParts.push_back(part); } } // If confirmation is required .. return this->SaveAll(wbParts, confirm, closing, addNonPartSources, IWorkbenchWindow::Pointer(window)); } bool EditorManager::SaveAll( const std::vector& /*dirtyParts*/, bool /*confirm*/, bool /*closing*/, bool /*addNonPartSources*/, SmartPointer /*window*/) { // // clone the input list // dirtyParts = new ArrayList(dirtyParts); // List modelsToSave; // if (confirm) { // boolean saveable2Processed = false; // // Process all parts that implement ISaveablePart2. // // These parts are removed from the list after saving // // them. We then need to restore the workbench to // // its previous state, for now this is just last // // active perspective. // // Note that the given parts may come from multiple // // windows, pages and perspectives. // ListIterator listIterator = dirtyParts.listIterator(); // // WorkbenchPage currentPage = null; // Perspective currentPageOriginalPerspective = null; // while (listIterator.hasNext()) { // IWorkbenchPart part = (IWorkbenchPart) listIterator.next(); // if (part instanceof ISaveablePart2) { // WorkbenchPage page = (WorkbenchPage) part.getSite() // .getPage(); // if (!Util.equals(currentPage, page)) { // if (currentPage != null // && currentPageOriginalPerspective != null) { // if (!currentPageOriginalPerspective // .equals(currentPage.getActivePerspective())) { // currentPage // .setPerspective(currentPageOriginalPerspective // .getDesc()); // } // } // currentPage = page; // currentPageOriginalPerspective = page // .getActivePerspective(); // } // if (confirm) { // if (part instanceof IViewPart) { // Perspective perspective = page // .getFirstPerspectiveWithView((IViewPart) part); // if (perspective != null) { // page.setPerspective(perspective.getDesc()); // } // } // // show the window containing the page? // IWorkbenchWindow partsWindow = page // .getWorkbenchWindow(); // if (partsWindow != partsWindow.getWorkbench() // .getActiveWorkbenchWindow()) { // Shell shell = partsWindow.getShell(); // if (shell.getMinimized()) { // shell.setMinimized(false); // } // shell.setActive(); // } // page.bringToTop(part); // } // // try to save the part // int choice = SaveableHelper.savePart((ISaveablePart2) part, // page.getWorkbenchWindow(), confirm); // if (choice == ISaveablePart2.CANCEL) { // // If the user cancels, don't restore the previous // // workbench state, as that will // // be an unexpected switch from the current state. // return false; // } else if (choice != ISaveablePart2.DEFAULT) { // saveable2Processed = true; // listIterator.remove(); // } // } // } // // // try to restore the workbench to its previous state // if (currentPage != null && currentPageOriginalPerspective != null) { // if (!currentPageOriginalPerspective.equals(currentPage // .getActivePerspective())) { // currentPage.setPerspective(currentPageOriginalPerspective // .getDesc()); // } // } // // // if processing a ISaveablePart2 caused other parts to be // // saved, remove them from the list presented to the user. // if (saveable2Processed) { // listIterator = dirtyParts.listIterator(); // while (listIterator.hasNext()) { // ISaveablePart part = (ISaveablePart) listIterator.next(); // if (!part.isDirty()) { // listIterator.remove(); // } // } // } // // modelsToSave = convertToSaveables(dirtyParts, closing, addNonPartSources); // // // If nothing to save, return. // if (modelsToSave.isEmpty()) { // return true; // } // boolean canceled = SaveableHelper.waitForBackgroundSaveJobs(modelsToSave); // if (canceled) { // return false; // } // // Use a simpler dialog if there's only one // if (modelsToSave.size() == 1) { // Saveable model = (Saveable) modelsToSave.get(0); // String message = NLS.bind(WorkbenchMessages.EditorManager_saveChangesQuestion, model.getName()); // // Show a dialog. // String[] buttons = new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }; // MessageDialog d = new MessageDialog( // shellProvider.getShell(), WorkbenchMessages.Save_Resource, // null, message, MessageDialog.QUESTION, buttons, 0); // // int choice = SaveableHelper.testGetAutomatedResponse(); // if (SaveableHelper.testGetAutomatedResponse() == SaveableHelper.USER_RESPONSE) { // choice = d.open(); // } // // // Branch on the user choice. // // The choice id is based on the order of button labels // // above. // switch (choice) { // case ISaveablePart2.YES: // yes // break; // case ISaveablePart2.NO: // no // return true; // default: // case ISaveablePart2.CANCEL: // cancel // return false; // } // } // else { // ListSelectionDialog dlg = new ListSelectionDialog( // shellProvider.getShell(), modelsToSave, // new ArrayContentProvider(), // new WorkbenchPartLabelProvider(), RESOURCES_TO_SAVE_MESSAGE); // dlg.setInitialSelections(modelsToSave.toArray()); // dlg.setTitle(SAVE_RESOURCES_TITLE); // // // this "if" statement aids in testing. // if (SaveableHelper.testGetAutomatedResponse()==SaveableHelper.USER_RESPONSE) { // int result = dlg.open(); // //Just return false to prevent the operation continuing // if (result == IDialogConstants.CANCEL_ID) { // return false; // } // // modelsToSave = Arrays.asList(dlg.getResult()); // } // } // } // else { // modelsToSave = convertToSaveables(dirtyParts, closing, addNonPartSources); // } // // // If the editor list is empty return. // if (modelsToSave.isEmpty()) { // return true; // } // // // Create save block. // final List finalModels = modelsToSave; // IRunnableWithProgress progressOp = new IRunnableWithProgress() { // public void run(IProgressMonitor monitor) { // IProgressMonitor monitorWrap = new EventLoopProgressMonitor( // monitor); // monitorWrap.beginTask("", finalModels.size()); //$NON-NLS-1$ // for (Iterator i = finalModels.iterator(); i.hasNext();) { // Saveable model = (Saveable) i.next(); // // handle case where this model got saved as a result of saving another // if (!model.isDirty()) { // monitor.worked(1); // continue; // } // SaveableHelper.doSaveModel(model, new SubProgressMonitor(monitorWrap, 1), shellProvider, closing || confirm); // if (monitorWrap.isCanceled()) { // break; // } // } // monitorWrap.done(); // } // }; // // // Do the save. // return SaveableHelper.runProgressMonitorOperation( // WorkbenchMessages.Save_All, progressOp, runnableContext, shellProvider); return true; } bool EditorManager::SavePart(ISaveablePart::Pointer /*saveable*/, IWorkbenchPart::Pointer /*part*/, bool /*confirm*/) { //TODO EditorManager save part (SaveableHelper) //return SaveableHelper.savePart(saveable, part, window, confirm); return true; } bool EditorManager::SaveState(const IMemento::Pointer memento) { // final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.EditorManager_problemsSavingEditors, null); bool result = true; // Save the editor area workbooks layout/relationship IMemento::Pointer editorAreaMem = memento->CreateChild(WorkbenchConstants::TAG_AREA); //result.add(editorPresentation.saveState(editorAreaMem)); result &= editorPresentation->SaveState(editorAreaMem); // Save the active workbook id editorAreaMem->PutString(WorkbenchConstants::TAG_ACTIVE_WORKBOOK, editorPresentation->GetActiveEditorWorkbookID()); // Get each workbook std::list workbooks(editorPresentation->GetWorkbooks()); for (std::list::iterator iter = workbooks.begin(); iter != workbooks.end(); ++iter) { PartStack::Pointer workbook = *iter; // Use the list of editors found in EditorStack; fix for 24091 std::list editorPanes(workbook->GetChildren()); for (std::list::iterator i = editorPanes.begin(); i != editorPanes.end(); ++i) { // Save each open editor. EditorReference::Pointer editorReference = i->Cast()->GetPartReference().Cast(); IEditorPart::Pointer editor = editorReference->GetEditor(false); if (!editor) { if (editorReference->GetMemento()) { IMemento::Pointer editorMem = memento ->CreateChild(WorkbenchConstants::TAG_EDITOR); editorMem->PutMemento(editorReference->GetMemento()); } continue; } // for dynamic UI - add the next line to replace the subsequent // code which is commented out SaveEditorState(memento, editorReference); //, result); } } return result; } bool EditorManager::SetVisibleEditor(IEditorReference::Pointer newEd, bool setFocus) { return editorPresentation->SetVisibleEditor(newEd, setFocus); } IPathEditorInput::Pointer EditorManager::GetPathEditorInput( IEditorInput::Pointer input) { if (input.Cast().IsNotNull()) { return input.Cast(); } // return (IPathEditorInput) // Util.getAdapter(input, IPathEditorInput.class); return IPathEditorInput::Pointer(0); } void EditorManager::RestoreEditorState(IMemento::Pointer /*editorMem*/, std::vector& /*visibleEditors*/, std::vector& /*activeEditor*/) { // MultiStatus result) { //TODO Restore editor state // String strFocus = editorMem.getString(IWorkbenchConstants.TAG_FOCUS); // boolean visibleEditor = "true".equals(strFocus); //$NON-NLS-1$ // EditorReference::Pointer e = new EditorReference(this, editorMem); // // try // { // StartupThreading.runWithPartInitExceptions(new StartupRunnable () // { // // public void runWithException() throws Throwable // { // createEditorTab(e, workbookID); // }}); // // } // catch (PartInitException ex) // { // result.add(ex.getStatus()); // } // // String strActivePart = editorMem // .getString(IWorkbenchConstants.TAG_ACTIVE_PART); // if ("true".equals(strActivePart)) // { //$NON-NLS-1$ // activeEditor[0] = e; // } // // String strFocus = editorMem.getString(IWorkbenchConstants.TAG_FOCUS); // boolean visibleEditor = "true".equals(strFocus); //$NON-NLS-1$ // if (visibleEditor) // { // visibleEditors.add(e); // } } void EditorManager::SaveEditorState(IMemento::Pointer /*mem*/, IEditorReference::Pointer /*ed*/) { //TODO Save editor state // final EditorReference editorRef = (EditorReference) ed; // final IEditorPart editor = ed.getEditor(false); // final IMemento memento = mem; // final MultiStatus result = res; // if (!(editor.getEditorSite() instanceof EditorSite)) // { // return; // } // final EditorSite site = (EditorSite) editor.getEditorSite(); // if (site.getPane() instanceof MultiEditorInnerPane) // { // return; // } // // SafeRunner.run(new SafeRunnable() // { // public void run() // { // // Get the input. // IEditorInput input = editor.getEditorInput(); // if (!input.exists()) // { // return; // } // IPersistableElement persistable = input.getPersistable(); // if (persistable == null) // { // return; // } // // // Save editor. // IMemento editorMem = memento // .createChild(IWorkbenchConstants.TAG_EDITOR); // editorMem.putString(IWorkbenchConstants.TAG_TITLE, editorRef // .getTitle()); // editorMem.putString(IWorkbenchConstants.TAG_NAME, editorRef // .getName()); // editorMem.putString(IWorkbenchConstants.TAG_ID, editorRef // .getId()); // editorMem.putString(IWorkbenchConstants.TAG_TOOLTIP, editorRef // .getTitleToolTip()); // // editorMem.putString(IWorkbenchConstants.TAG_PART_NAME, // editorRef.getPartName()); // // if (editor instanceof IWorkbenchPart3) // { // Map properties = ((IWorkbenchPart3) editor) // .getPartProperties(); // if (!properties.isEmpty()) // { // IMemento propBag = editorMem // .createChild(IWorkbenchConstants.TAG_PROPERTIES); // Iterator i = properties.entrySet().iterator(); // while (i.hasNext()) // { // Map.Entry entry = (Map.Entry) i.next(); // IMemento p = propBag.createChild( // IWorkbenchConstants.TAG_PROPERTY, // (String) entry.getKey()); // p.putTextData((String) entry.getValue()); // } // } // } // // if (editorRef.isPinned()) // { // editorMem.putString(IWorkbenchConstants.TAG_PINNED, "true"); //$NON-NLS-1$ // } // // EditorPane editorPane = (EditorPane) ((EditorSite) editor // .getEditorSite()).getPane(); // editorMem.putString(IWorkbenchConstants.TAG_WORKBOOK, // editorPane.getWorkbook().getID()); // // if (editor == page.getActivePart()) // { // editorMem.putString(IWorkbenchConstants.TAG_ACTIVE_PART, // "true"); //$NON-NLS-1$ // } // // if (editorPane == editorPane.getWorkbook().getSelection()) // { // editorMem.putString(IWorkbenchConstants.TAG_FOCUS, "true"); //$NON-NLS-1$ // } // // if (input instanceof IPathEditorInput) // { // IPath path = ((IPathEditorInput) input).getPath(); // if (path != null) // { // editorMem.putString(IWorkbenchConstants.TAG_PATH, path // .toString()); // } // } // // // Save input. // IMemento inputMem = editorMem // .createChild(IWorkbenchConstants.TAG_INPUT); // inputMem.putString(IWorkbenchConstants.TAG_FACTORY_ID, // persistable.getFactoryId()); // persistable.saveState(inputMem); // // // any editors that want to persist state // if (editor instanceof IPersistableEditor) // { // IMemento editorState = editorMem // .createChild(IWorkbenchConstants.TAG_EDITOR_STATE); // ((IPersistableEditor) editor).saveState(editorState); // } // } // // public void handleException(Throwable e) // { // result // .add(new Status( // IStatus.ERR, // PlatformUI.PLUGIN_ID, // 0, // NLS // .bind( // WorkbenchMessages.EditorManager_unableToSaveEditor, // editorRef.getTitle()), e)); // } // } // ); } IMemento::Pointer EditorManager::GetMemento(IEditorReference::Pointer e) { if (e.Cast().IsNotNull()) { return e.Cast()->GetMemento(); } return IMemento::Pointer(0); } IEditorReference::Pointer EditorManager::OpenEmptyTab() { IEditorInput::Pointer input(new NullEditorInput()); EditorDescriptor::Pointer desc = (dynamic_cast(this->GetEditorRegistry())) ->FindEditor(EditorRegistry::EMPTY_EDITOR_ID).Cast(); EditorReference::Pointer result(new EditorReference(this, input, desc)); try { this->CreateEditorTab(result, ""); //$NON-NLS-1$ return result; } catch (PartInitException e) { // StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, e)); BERRY_ERROR << e.displayText() << std::endl; } return IEditorReference::Pointer(0); } bool EditorManager::UseIPersistableEditor() { // IPreferenceStore store = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // return store.getBoolean(IPreferenceConstants.USE_IPERSISTABLE_EDITORS); return false; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorManager.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorManager.h index 6374813c6a..29d42774b3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorManager.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorManager.h @@ -1,433 +1,433 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYEDITORMANAGER_H_ #define BERRYEDITORMANAGER_H_ #include -#include "../berryIEditorPart.h" -#include "../berryIEditorReference.h" -#include "../berryIPathEditorInput.h" -#include "../berryIMemento.h" +#include "berryIEditorPart.h" +#include "berryIEditorReference.h" +#include "berryIPathEditorInput.h" +#include "berryIMemento.h" #include "berryEditorDescriptor.h" #include #include namespace berry { struct IWorkbenchPart; struct IWorkbenchWindow; class WorkbenchWindow; class WorkbenchPage; class EditorSite; class EditorReference; struct IEditorRegistry; class EditorAreaHelper; /** * \ingroup org_blueberry_ui_internal * * Manage a group of element editors. Prevent the creation of two editors on the * same element. * * 06/12/00 - DS - Given the ambiguous editor input type, the manager delegates * a number of responsibilities to the editor itself. * *
    *
  1. The editor should determine its own title.
  2. *
  3. The editor should listen to resource deltas and close itself if the * input is deleted. It may also choose to stay open if the editor has dirty * state.
  4. *
  5. The editor should persist its own state plus editor input.
  6. *
*/ class EditorManager { // implements IExtensionChangeHandler { friend class EditorReference; EditorAreaHelper* editorPresentation; WorkbenchWindow* window; WorkbenchPage* page; //std::map actionCache = new HashMap(); static const std::string PIN_EDITOR_KEY; // = "PIN_EDITOR"; //$NON-NLS-1$ //static const std::string PIN_EDITOR = "ovr16/pinned_ovr.gif"; //$NON-NLS-1$ // When the user removes or adds the close editors automatically preference // the icon should be removed or added accordingly //IPropertyChangeListener editorPropChangeListnener = null; // Handler for the pin editor keyboard shortcut //IHandlerActivation pinEditorHandlerActivation = null; static const std::string RESOURCES_TO_SAVE_MESSAGE; // = "Select resources to save:"; static const std::string SAVE_RESOURCES_TITLE; // = "Save Resources"; public: /** * EditorManager constructor comment. */ EditorManager(SmartPointer window, SmartPointer workbenchPage, EditorAreaHelper* pres); protected: /** * Check to determine if the editor resources are no longer needed removes * property change listener for editors removes pin editor keyboard shortcut * handler disposes cached images and clears the cached images hash table */ void CheckDeleteEditorResources(); /** * Check to determine if the property change listener for editors should be * created */ //void CheckCreateEditorPropListener(); /** * Check to determine if the handler for the pin editor keyboard shortcut * should be created. */ //void CheckCreatePinEditorShortcutKeyHandler(); /** * Method to create the editor's pin ImageDescriptor * * @return the single image descriptor for the editor's pin icon */ // ImageDescriptor GetEditorPinImageDesc() { // ImageRegistry registry = JFaceResources.getImageRegistry(); // ImageDescriptor pinDesc = registry.getDescriptor(PIN_EDITOR_KEY); // // Avoid registering twice // if (pinDesc == null) { // pinDesc = WorkbenchImages.getWorkbenchImageDescriptor(PIN_EDITOR); // registry.put(PIN_EDITOR_KEY, pinDesc); // // } // return pinDesc; // } private: /** * Answer a list of dirty editors. */ std::vector CollectDirtyEditors(); /** * Returns whether the manager contains an editor. */ public: bool ContainsEditor(IEditorReference::Pointer ref); /* * Creates the action bars for an editor. Editors of the same type should * share a single editor action bar, so this implementation may return an * existing action bar vector. */ private: //EditorActionBars* CreateEditorActionBars(EditorDescriptor::Pointer desc, // IEditorSite::Pointer site); /* * Creates the action bars for an editor. */ private: //EditorActionBars* CreateEmptyEditorActionBars(IEditorSite::Pointer site); /* * Dispose */ protected: //void DisposeEditorActionBars(EditorActionBars* actionBars); /** * Returns an open editor matching the given editor input. If none match, * returns null. * * @param input * the editor input * @return the matching editor, or null if no match fond */ public: IEditorPart::Pointer FindEditor(IEditorInput::Pointer input); /** * Returns an open editor matching the given editor input and/or editor id, * as specified by matchFlags. If none match, returns null. * * @param editorId * the editor id * @param input * the editor input * @param matchFlags * flags specifying which aspects to match * @return the matching editor, or null if no match fond * @since 3.1 */ public: IEditorPart::Pointer FindEditor(const std::string& editorId, IEditorInput::Pointer input, int matchFlags); /** * Returns the open editor references matching the given editor input and/or * editor id, as specified by matchFlags. If none match, returns an empty * array. * * @param editorId * the editor id * @param input * the editor input * @param matchFlags * flags specifying which aspects to match * @return the matching editor, or null if no match fond * @since 3.1 */ public: std::vector FindEditors( IEditorInput::Pointer input, const std::string& editorId, int matchFlags); /** * Returns an open editor matching the given editor id and/or editor input. * Returns null if none match. * * @param editorId * the editor id * @param input * the editor input * @param editorList * a mutable list containing the references for the editors to * check (warning: items may be removed) * @param result * the list to which matching editor references should be added * @since 3.1 */ private: void FindEditors(std::list >& editorList, IEditorInput::Pointer input, const std::string& editorId, int matchFlags, std::vector& result); /** * Answer the number of editors. */ public: std::size_t GetEditorCount(); /* * Answer the editor registry. */ private: IEditorRegistry* GetEditorRegistry(); /* * See IWorkbenchPage. */ public: std::vector GetDirtyEditors(); /* * See IWorkbenchPage. */ public: std::list GetEditors(); /* * See IWorkbenchPage#getFocusEditor */ public: IEditorPart::Pointer GetVisibleEditor(); /** * Answer true if save is needed in any one of the editors. */ public: bool IsSaveAllNeeded(); /* * Prompt the user to save the reusable editor. Return false if a new editor * should be opened. */ private: IEditorReference::Pointer FindReusableEditor(EditorDescriptor::Pointer desc); /** * @param editorId * the editor part id * @param input * the input * @param setVisible * if this is to be created visible ... not used * @param editorState * an {@link IMemento} <editorState> for persistable * editors. Can be null. * @return a created editor reference * @throws PartInitException */ public: IEditorReference::Pointer OpenEditor(const std::string& editorId, IEditorInput::Pointer input, bool setVisible, IMemento::Pointer editorState); /* * Open a new editor */ public: IEditorReference::Pointer OpenEditorFromDescriptor( EditorDescriptor::Pointer desc, IEditorInput::Pointer input, IMemento::Pointer editorState); /** * Open a specific external editor on an file based on the descriptor. */ //private: // IEditorReference::Pointer OpenExternalEditor(EditorDescriptor::Pointer desc, // IEditorInput::Pointer input); /* * Opens an editor part. */ private: void CreateEditorTab(SmartPointer ref, const std::string& workbookId); /* * Create the site and initialize it with its action bars. */ protected: SmartPointer CreateSite(IEditorReference::Pointer ref, IEditorPart::Pointer part, EditorDescriptor::Pointer desc, IEditorInput::Pointer input) const; /* * See IWorkbenchPage. */ private: IEditorReference::Pointer ReuseInternalEditor(EditorDescriptor::Pointer desc, IEditorInput::Pointer input); protected: IEditorPart::Pointer CreatePart(EditorDescriptor::Pointer desc) const; /** * Open a system external editor on the input path. */ //private: // IEditorReference::Pointer OpenSystemExternalEditor(Poco::Path location); protected: //ImageDescriptor FindImage(EditorDescriptor::Pointer desc, Poco::Path path); /** * @see org.blueberry.ui.IPersistable */ public: /*IStatus*/bool RestoreState(IMemento::Pointer memento); /** * Save all of the editors in the workbench. Return true if successful. * Return false if the user has canceled the command. * @param confirm true if the user should be prompted before the save * @param closing true if the page is being closed * @param addNonPartSources true if saveables from non-part sources should be saved too. * @return false if the user canceled or an error occurred while saving */ public: bool SaveAll(bool confirm, bool closing, bool addNonPartSources); /** * Saves the given dirty editors and views, optionally prompting the user. * * @param dirtyParts * the dirty views and editors * @param confirm * true to prompt whether to save, false * to save without prompting * @param closing * true if the parts are being closed, * false if just being saved without closing * @param addNonPartSources true if non-part sources should be saved too * @param window * the window to use as the parent for the dialog that prompts to * save multiple dirty editors and views * @return true on success, false if the user * canceled the save or an error occurred while saving */ public: static bool SaveAll(const std::vector& dirtyParts, bool confirm, bool closing, bool addNonPartSources, SmartPointer); /* * Saves the workbench part. */ public: bool SavePart(ISaveablePart::Pointer saveable, IWorkbenchPart::Pointer part, bool confirm); /** * @see IPersistablePart */ public: /*IStatus*/bool SaveState(const IMemento::Pointer memento); /** * Shows an editor. If setFocus == true then give it focus, * too. * * @return true if the active editor was changed, false if not. */ public: bool SetVisibleEditor(IEditorReference::Pointer newEd, bool setFocus); private: IPathEditorInput::Pointer GetPathEditorInput(IEditorInput::Pointer input); /* * Made public for Mylar in 3.3 - see bug 138666. Can be made private once * we have real API for this. */ private: void RestoreEditorState(IMemento::Pointer editorMem, std::vector& visibleEditors, std::vector& activeEditor); // for dynamic UI protected: void SaveEditorState(IMemento::Pointer mem, IEditorReference::Pointer ed/*, MultiStatus res*/); // for dynamic UI public: IMemento::Pointer GetMemento(IEditorReference::Pointer e); IEditorReference::Pointer OpenEmptyTab(); public: static bool UseIPersistableEditor(); }; } #endif /*BERRYEDITORMANAGER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorReference.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorReference.cpp index e1f2804563..dbd8f4c5d1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorReference.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorReference.cpp @@ -1,575 +1,575 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryEditorReference.h" -#include "../tweaklets/berryWorkbenchPageTweaklet.h" +#include "tweaklets/berryWorkbenchPageTweaklet.h" #include "berryEditorManager.h" #include "berryEditorDescriptor.h" #include "berryEditorRegistry.h" #include "berryEditorSite.h" #include "berryEditorAreaHelper.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchPage.h" #include "berryNullEditorInput.h" #include "berryPartTester.h" -#include "../berryImageDescriptor.h" -#include "../berryPlatformUI.h" -#include "../berryIWorkbenchPartConstants.h" +#include "berryImageDescriptor.h" +#include "berryPlatformUI.h" +#include "berryIWorkbenchPartConstants.h" namespace berry { EditorReference::EditorReference(EditorManager* man, IEditorInput::Pointer input, EditorDescriptor::Pointer desc, IMemento::Pointer editorState) : manager(man), expectingInputChange(false), reportedMalfunctioningEditor(false) { this->InitListenersAndHandlers(); restoredInput = input; this->editorState = editorState; this->Init(desc->GetId(), "", desc->GetImageDescriptor(), desc->GetLabel(), ""); } EditorReference::EditorReference(EditorManager* man, IMemento::Pointer memento) : manager(man), expectingInputChange(false), reportedMalfunctioningEditor(false) { this->InitListenersAndHandlers(); this->editorMemento = memento; if (manager->UseIPersistableEditor()) { //editorState = editorMemento->GetChild(WorkbenchConstants::TAG_EDITOR_STATE); } else { editorState = 0; } // String id = memento.getString(IWorkbenchConstants.TAG_ID); // String title = memento.getString(IWorkbenchConstants.TAG_TITLE); // String tooltip = Util.safeString(memento // .getString(IWorkbenchConstants.TAG_TOOLTIP)); // String partName = memento // .getString(IWorkbenchConstants.TAG_PART_NAME); // // IMemento propBag = memento.getChild(IWorkbenchConstants.TAG_PROPERTIES); // if (propBag != null) // { // IMemento[] props = propBag // .getChildren(IWorkbenchConstants.TAG_PROPERTY); // for (int i = 0; i < props.length; i++) // { // propertyCache.put(props[i].getID(), props[i].getTextData()); // } // } // For compatibility set the part name to the title if not found // if (partName.empty()) // { // partName = title; // } // Get the editor descriptor. // EditorDescriptor::Pointer desc; // if (id != null) // { // desc = getDescriptor(id); // } // // desc may be null if id is null or desc is not found, but findImage below handles this // String location = memento.getString(IWorkbenchConstants.TAG_PATH); // IPath path = location == null ? null : new Path(location); // ImageDescriptor iDesc = this.manager.findImage(desc, path); // // this.name = memento.getString(IWorkbenchConstants.TAG_NAME); // if (this.name == null) // { // this.name = title; // } // setPinned("true".equals(memento.getString(IWorkbenchConstants.TAG_PINNED))); //$NON-NLS-1$ // // IMemento inputMem = memento.getChild(IWorkbenchConstants.TAG_INPUT); // if (inputMem != null) // { // this.factoryId = inputMem // .getString(IWorkbenchConstants.TAG_FACTORY_ID); // } // // init(id, title, tooltip, iDesc, partName, ""); //$NON-NLS-1$ } EditorDescriptor::Pointer EditorReference::GetDescriptor() { return this->GetDescriptor(this->GetId()); } EditorDescriptor::Pointer EditorReference::GetDescriptor(const std::string& id) { EditorDescriptor::Pointer desc; IEditorRegistry* reg = WorkbenchPlugin::GetDefault()->GetEditorRegistry(); desc = reg->FindEditor(id).Cast (); return desc; } void EditorReference::InitListenersAndHandlers() { // Create a property change listener to track the "close editors automatically" // preference and show/remove the pin icon on editors // Only 1 listener will be created in the EditorManager when necessary //this->manager->CheckCreateEditorPropListener(); // Create a keyboard shortcut handler for pinning editors // Only 1 handler will be created in the EditorManager when necessary //this->manager->CheckCreatePinEditorShortcutKeyHandler(); } PartPane::Pointer EditorReference::CreatePane() { PartPane::Pointer pane( new PartPane(IWorkbenchPartReference::Pointer(this), this->manager->page)); return pane; //return Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateEditorPane(this, // this->manager->page); } void EditorReference::PinStatusUpdated() { //firePropertyChange(IWorkbenchPart.PROP_TITLE); } std::string EditorReference::GetFactoryId() { // IEditorPart editor = getEditor(false); // if (editor != null) // { // IPersistableElement persistable = editor.getEditorInput() // .getPersistable(); // if (persistable != null) // { // return persistable.getFactoryId(); // } // return null; // } // return factoryId; return ""; } std::string EditorReference::ComputePartName() { return WorkbenchPartReference::ComputePartName(); } std::string EditorReference::GetName() { if (part.IsNotNull()) { return this->GetEditor(false)->GetEditorInput()->GetName(); } return name; } IEditorPart::Pointer EditorReference::GetEditor(bool restore) { return this->GetPart(restore).Cast (); } void EditorReference::SetName(const std::string& name) { this->name = name; } IMemento::Pointer EditorReference::GetMemento() { return editorMemento; } IWorkbenchPage::Pointer EditorReference::GetPage() const { return IWorkbenchPage::Pointer(this->manager->page); } IEditorInput::Pointer EditorReference::GetEditorInput() { IEditorPart::Pointer part = this->GetEditor(false); if (part.IsNotNull()) { return part->GetEditorInput(); } return this->GetRestoredInput(); } IEditorInput::Pointer EditorReference::GetRestoredInput() { if (restoredInput.IsNotNull()) { return restoredInput; } // Get the input factory. // IMemento::Pointer editorMem = this->GetMemento(); // if (editorMem == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_no_persisted_state, getId(), getName())); // } // IMemento inputMem = editorMem // .getChild(IWorkbenchConstants.TAG_INPUT); // String factoryID = null; // if (inputMem != null) // { // factoryID = inputMem // .getString(IWorkbenchConstants.TAG_FACTORY_ID); // } // if (factoryID == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_no_input_factory_ID, getId(), getName())); // } // IAdaptable input = null; // String label = null; // debugging only // if (UIStats.isDebugging(UIStats.CREATE_PART_INPUT)) // { // label = getName() != null ? getName() : factoryID; // } // try // { // UIStats.start(UIStats.CREATE_PART_INPUT, label); // IElementFactory factory = PlatformUI.getWorkbench() // .getElementFactory(factoryID); // if (factory == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_bad_element_factory, new Object[] // { factoryID, getId(), getName()})); // } // // // Get the input element. // input = factory.createElement(inputMem); // if (input == null) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_create_element_returned_null, new Object[] // { factoryID, getId(), getName()})); // } // }finally // { // UIStats.end(UIStats.CREATE_PART_INPUT, input, label); // } // if (!(input instanceof IEditorInput)) // { // throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_wrong_createElement_result, new Object[] // { factoryID, getId(), getName()})); // } // restoredInput = (IEditorInput) input; return restoredInput; } IWorkbenchPart::Pointer EditorReference::CreatePart() { if (EditorRegistry::EMPTY_EDITOR_ID == this->GetId()) { return this->GetEmptyEditor(this->GetDescriptor()); } IWorkbenchPart::Pointer result; // Try to restore the editor -- this does the real work of restoring the editor // try { result = this->CreatePartHelper().Cast (); } catch (PartInitException e) { // If unable to create the part, create an error part instead // and pass the error to the status handling facility // IStatus originalStatus = exception.getStatus(); // IStatus logStatus = StatusUtil.newStatus(originalStatus, // NLS.bind("Unable to create editor ID {0}: {1}", //$NON-NLS-1$ // getId(), originalStatus.getMessage())); // IStatus displayStatus = StatusUtil.newStatus(originalStatus, // NLS.bind(WorkbenchMessages.EditorManager_unableToCreateEditor, // originalStatus.getMessage())); WorkbenchPlugin::Log("Unable to create editor ID " + this->GetId() + ": " + e.displayText()); // Pass the error to the status handling facility //StatusManager.getManager().handle(logStatus); EditorDescriptor::Pointer descr = this->GetDescriptor(); std::string label = this->GetId(); if (descr.IsNotNull()) label = descr->GetLabel(); IEditorPart::Pointer part = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreateErrorEditorPart(label, e.displayText()); if (part.IsNotNull()) { IEditorInput::Pointer input; try { input = this->GetEditorInput(); } catch (PartInitException e1) { input = new NullEditorInput(EditorReference::Pointer(this)); } PartPane::Pointer pane = this->GetPane(); pane->CreateControl( manager->page->GetEditorPresentation()->GetLayoutPart()->GetControl()); EditorSite::Pointer site( new EditorSite(IEditorReference::Pointer(this), part, manager->page, descr)); //site.setActionBars(new EditorActionBars(manager.page, site.getWorkbenchWindow(), getId())); part->Init(site, input); try { part->CreatePartControl(pane->GetControl()); } catch (...) { //content.dispose(); //StatusUtil.handleStatus(e, StatusManager.SHOW // | StatusManager.LOG); WorkbenchPlugin::Log("Error creating editor"); return IWorkbenchPart::Pointer(0); } result = part.Cast (); } } return result; } void EditorReference::PropertyChanged(Object::Pointer source, int propId) { // Detect badly behaved editors that don't fire PROP_INPUT events // when they're supposed to. This branch is only needed to handle // malfunctioning editors. if (propId == IWorkbenchPartConstants::PROP_INPUT) { expectingInputChange = false; } WorkbenchPartReference::PropertyChanged(source, propId); } bool EditorReference::SetInput(IEditorInput::Pointer input) { if (part.IsNotNull()) { if (part.Cast ().IsNotNull()) { IReusableEditor::Pointer editor = part.Cast (); expectingInputChange = true; editor->SetInput(input); // If the editor never fired a PROP_INPUT event, log the fact that we've discovered // a buggy editor and fire the event for free. Firing the event for free isn't required // and cannot be relied on (it only works if the input change was triggered by this // method, and there are definitely other cases where events will still be lost), // but older versions of the workbench did this so we fire it here in the spirit // of playing nice. if (expectingInputChange) { // Log the fact that this editor is broken this->ReportMalfunction( "Editor is not firing a PROP_INPUT event in response to IReusableEditor.setInput(...)"); //$NON-NLS-1$ // Fire the property for free (can't be relied on since there are other ways the input // can change, but we do it here to be consistent with older versions of the workbench) FirePropertyChange(IWorkbenchPartConstants::PROP_INPUT); } return editor->GetEditorInput() == input; } // Can't change the input if the editor already exists and isn't an IReusableEditor return false; } // Changing the input is trivial and always succeeds if the editor doesn't exist yet if (input != restoredInput) { restoredInput = input; //firePropertyChange(IWorkbenchPartConstants.PROP_INPUT); } return true; } void EditorReference::ReportMalfunction(const std::string& string) { if (!reportedMalfunctioningEditor) { reportedMalfunctioningEditor = true; std::string errorMessage = "Problem detected with part " + this->GetId(); //$NON-NLS-1$ if (part.IsNotNull()) { errorMessage.append("(class = ").append(part->GetClassName()).append( ")"); //$NON-NLS-1$ //$NON-NLS-2$ } errorMessage += ": " + string; //$NON-NLS-1$ //StatusManager.getManager().handle(StatusUtil.newStatus(getDescriptor().getPluginId(), errorMessage, null)); BERRY_ERROR << errorMessage << std::endl; } } IEditorPart::Pointer EditorReference::CreatePartHelper() { EditorSite::Pointer site; IEditorPart::Pointer part; try { IEditorInput::Pointer editorInput = this->GetEditorInput(); // Get the editor descriptor. std::string editorID = this->GetId(); EditorDescriptor::Pointer desc = this->GetDescriptor(); if (desc.IsNull()) { throw PartInitException("No editor descriptor for id " + editorID); } if (desc->IsInternal()) { // Create an editor instance. part = manager->CreatePart(desc); this->CreatePartProperties(part); } // else if (desc->GetId() == IEditorRegistry.SYSTEM_INPLACE_EDITOR_ID) // { // // part = ComponentSupport.getSystemInPlaceEditor(); // // if (part == null) // { // throw new PartInitException(WorkbenchMessages.EditorManager_no_in_place_support); // } // } else { throw PartInitException("Invalid editor descriptor for id " + editorID); } // Create a pane for this part PartPane::Pointer pane = this->GetPane(); pane->CreateControl(manager->page->GetEditorPresentation()->GetLayoutPart()->GetControl()); // Link everything up to the part reference (the part reference itself should not have // been modified until this point) site = manager->CreateSite(IEditorReference::Pointer(this), part, desc, editorInput); // if there is saved state that's appropriate, pass it on if (/*part instanceof IPersistableEditor &&*/editorState.IsNotNull()) { //part->RestoreState(editorState); } // Remember the site and the action bars (now that we've created them, we'll need to dispose // them if an exception occurs) //actionBars = (EditorActionBars) site.getActionBars(); part->CreatePartControl(pane->GetControl()); // The editor should now be fully created. Exercise its public interface, and sanity-check // it wherever possible. If it's going to throw exceptions or behave badly, it's much better // that it does so now while we can still cancel creation of the part. PartTester::TestEditor(part); return part; } catch (std::exception e) { throw PartInitException(e.what()); } } IEditorPart::Pointer EditorReference::GetEmptyEditor( EditorDescriptor::Pointer descr) { IEditorPart::Pointer part = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreateErrorEditorPart("(Empty)", ""); IEditorInput::Pointer input; try { input = this->GetEditorInput(); } catch (PartInitException e1) { input = new NullEditorInput(EditorReference::Pointer(this)); } PartPane::Pointer pane = this->GetPane(); pane->CreateControl( manager->page->GetEditorPresentation()->GetLayoutPart()->GetControl()); EditorSite::Pointer site(new EditorSite(IEditorReference::Pointer(this), part, manager->page, descr)); //site.setActionBars(new EditorActionBars(manager.page, site.getWorkbenchWindow(), getId())); part->Init(site, input); try { part->CreatePartControl(pane->GetControl()); } catch (std::exception e) { //StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, e)); BERRY_ERROR << e.what() << std::endl; return IEditorPart::Pointer(0); } this->part = part.Cast (); // Add a dispose listener to the part. This dispose listener does nothing but log an exception // if the part's widgets get disposed unexpectedly. The workbench part reference is the only // object that should dispose this control, and it will remove the listener before it does so. this->RefreshFromPart(); //this->ReleaseReferences(); if (this->GetPage().Cast ()->GetActiveEditorReference() != this) { //fireInternalPropertyChange(INTERNAL_PROPERTY_OPENED); } return part; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorReference.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorReference.h index 9ada64b0d8..3f89bc2693 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorReference.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorReference.h @@ -1,243 +1,243 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYEDITORREFERENCE_H_ #define BERRYEDITORREFERENCE_H_ #include "berryWorkbenchPartReference.h" -#include "../berryIEditorReference.h" -#include "../berryIEditorInput.h" -#include "../berryIMemento.h" -#include "../berryIWorkbenchPart.h" -#include "../berryIEditorPart.h" +#include "berryIEditorReference.h" +#include "berryIEditorInput.h" +#include "berryIMemento.h" +#include "berryIWorkbenchPart.h" +#include "berryIEditorPart.h" namespace berry { class EditorManager; class EditorDescriptor; class PartPane; struct IWorkbenchPage; /** * \ingroup org_blueberry_ui_internal * */ class EditorReference : public WorkbenchPartReference, public IEditorReference { private: const EditorManager* manager; private: IMemento::Pointer editorMemento; private: IMemento::Pointer editorState; /** * Flag that lets us detect malfunctioning editors that don't fire PROP_INPUT events. * It is never needed for a correctly-functioning */ private: bool expectingInputChange; /** * Flag that determines whether we've already reported that this editor is malfunctioning. * This prevents us from spamming the event log if we repeatedly detect the same error in * a particular editor. If we ever detect an editor is violating its public contract in * a way we can recover from (such as a missing property change event), we report the error * once and then silently ignore errors from the same editor. */ private: bool reportedMalfunctioningEditor; /** * User-readable name of the editor's input */ std::string name; std::string factoryId; IEditorInput::Pointer restoredInput; /** * @param manager * The editor manager for this reference * @param input * our input * @param desc * the descriptor from the declaration * @param editorState * propogate state from another editor. Can be null. */ public: berryObjectMacro(EditorReference) EditorReference(EditorManager* manager, IEditorInput::Pointer input, SmartPointer desc, IMemento::Pointer editorState = IMemento::Pointer(0)); /** * Constructs a new editor reference for use by editors being restored from * a memento. */ EditorReference(EditorManager* manager, IMemento::Pointer memento); public: SmartPointer GetDescriptor(); /** * @since 3.1 * * @param id the id * @return the editor descriptor */ private: SmartPointer GetDescriptor(const std::string& id); /** * Initializes the necessary editor listeners and handlers */ private: void InitListenersAndHandlers(); protected: SmartPointer CreatePane(); /** * This method is called when there should be a change in the editor pin * status (added or removed) so that it will ask its presentable part * to fire a PROP_TITLE event in order for the presentation to request * the new icon for this editor */ public: void PinStatusUpdated(); public: std::string GetFactoryId(); protected: std::string ComputePartName(); public: std::string GetName(); public: IEditorPart::Pointer GetEditor(bool restore); public: void SetName(const std::string& name); public: IMemento::Pointer GetMemento(); public: SmartPointer GetPage() const; public: IEditorInput::Pointer GetEditorInput(); private: IEditorInput::Pointer GetRestoredInput(); /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartReference#getTitleImage() * This method will append a pin to the icon of the editor * if the "automatically close editors" option in the * preferences is enabled and the editor has been pinned. */ //public: ImageDescriptor computeImageDescriptor() { // ImageDescriptor descriptor = super.computeImageDescriptor(); // if (!isPinned()) { // return descriptor; // } // // // Check if the pinned preference is set // IPreferenceStore prefStore = WorkbenchPlugin.getDefault() // .getPreferenceStore(); // boolean bUsePin = prefStore // .getBoolean(IPreferenceConstants.REUSE_EDITORS_BOOLEAN) // || ((TabBehaviour)Tweaklets.get(TabBehaviour.KEY)).alwaysShowPinAction(); // // if (!bUsePin) { // return descriptor; // } // // ImageDescriptor pinDesc = this.manager.getEditorPinImageDesc(); // if (pinDesc == null) { // return descriptor; // } // // return new OverlayIcon(descriptor, pinDesc, new Point(16, 16)); // } protected: /** * Wrapper for restoring the editor. First, this delegates to busyRestoreEditorHelper * to do the real work of restoring the view. If unable to restore the editor, this * method tries to substitute an error part and return success. * * @return the created part */ IWorkbenchPart::Pointer CreatePart(); void PropertyChanged(Object::Pointer source, int propId); /** * Attempts to set the input of the editor to the given input. Note that the input * can't always be changed for an editor. Editors that don't implement IReusableEditor * can't have their input changed once they've been materialized. * * @since 3.1 * * @param input new input * @return true iff the input was actually changed */ public: bool SetInput(IEditorInput::Pointer input); /** * Reports a recoverable malfunction in the system log. A recoverable malfunction would be * something like failure to fire an expected property change. Only the first malfunction is * recorded to avoid spamming the system log with repeated failures in the same editor. * * @since 3.1 * * @param string */ private: void ReportMalfunction(const std::string& string); private: IEditorPart::Pointer CreatePartHelper(); /** * Creates and returns an empty editor (ErrorEditorPart). * * @param descr the editor descriptor * @return the empty editor part or null in case of an exception */ public: IEditorPart::Pointer GetEmptyEditor(SmartPointer descr); }; } // namespace berry #endif /*BERRYEDITORREFERENCE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorRegistry.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorRegistry.h index c38f66a56e..8dd56421cb 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorRegistry.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorRegistry.h @@ -1,772 +1,772 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYEDITORREGISTRY_H_ #define BERRYEDITORREGISTRY_H_ #include -#include "../berryIEditorRegistry.h" -#include "../berryIFileEditorMapping.h" +#include "berryIEditorRegistry.h" +#include "berryIFileEditorMapping.h" #include "berryEditorDescriptor.h" #include "berryFileEditorMapping.h" #include #include #include #include #include #include namespace berry { /** * \ingroup org_blueberry_ui_internal * * Provides access to the collection of defined editors for resource types. */ class EditorRegistry : public IEditorRegistry { class RelatedRegistry { public: RelatedRegistry(EditorRegistry* editorRegistry); /** * Return the objects related to the type. * * @param type * @return the objects related to the type */ // public: std::vector GetRelatedObjects(IContentType type) { // IEditorDescriptor[] relatedObjects = (IEditorDescriptor[]) contentTypeToEditorMappings.get(type); // if (relatedObjects == null) { // return EMPTY; // } // return (IEditorDescriptor[]) WorkbenchActivityHelper.restrictArray(relatedObjects); // } /** * Return the objects related to the filename * @param fileName * @return the objects related to the filename */ public: std::list GetRelatedObjects( const std::string& fileName); private: EditorRegistry* editorRegistry; }; friend class RelatedRegistry; /** * Map of FileEditorMapping (extension to FileEditorMapping) Uses two * java.util.HashMap: one keeps the default which are set by the plugins and * the other keeps the changes made by the user through the preference page. */ class EditorMap { static std::map defaultMap; static std::map map; public: void Clear(); /** * Put a default mapping into the editor map. * * @param key the key to set * @param value the value to associate */ public: static void PutDefault(const std::string& key, FileEditorMapping::Pointer value); /** * Put a mapping into the user editor map. * * @param key the key to set * @param value the value to associate */ public: void Put(const std::string& key, FileEditorMapping::Pointer value); /** * Return the mapping associated to the key. First searches user * map, and then falls back to the default map if there is no match. May * return null * * @param key * the key to search for * @return the mapping associated to the key or null */ public: FileEditorMapping::Pointer Get(const std::string& key); /** * Return all mappings. This will return default mappings overlayed with * user mappings. * * @return the mappings */ public: std::vector AllMappings(); /** * Return all user mappings. * * @return the mappings */ public: std::vector UserMappings(); }; struct CmpFileEditorMapping : public std::binary_function { bool operator()(const FileEditorMapping::Pointer& x, const FileEditorMapping::Pointer& y) const { return x->GetLabel() < y->GetLabel(); } }; struct CmpIEditorDescriptor : public std::binary_function { bool operator()(const IEditorDescriptor::Pointer& x, const IEditorDescriptor::Pointer& y) const { return x->GetLabel() < y->GetLabel(); } }; struct CmpEditorDescriptor : public std::binary_function { bool operator()(const EditorDescriptor::Pointer& x, const EditorDescriptor::Pointer& y) const { return x->GetLabel() < y->GetLabel(); } }; //private: Map contentTypeToEditorMappings = new HashMap(); /* * Cached images - these include images from registered editors (via * plugins) and others hence this table is not one to one with the mappings * table. It is in fact a superset of the keys one would find in * typeEditorMappings */ //private: Map extensionImages = new HashMap(); /** * Vector of EditorDescriptor - all the editors loaded from plugin files. * The list is kept in order to be able to show in the editor selection * dialog of the resource associations page. This list is sorted based on the * human readable label of the editor descriptor. * * @see #comparer */ private: std::list sortedEditorsFromPlugins; // Map of EditorDescriptor - map editor id to editor. private: std::map mapIDtoEditor; // Map of FileEditorMapping (extension to FileEditorMapping) private: EditorMap typeEditorMappings; /* * Compares the labels from two IEditorDescriptor objects */ //private: // static final Comparator comparer = new Comparator() // { // private Collator collator = Collator.getInstance(); // // public int compare(Object arg0, Object arg1) // { // String s1 = ((IEditorDescriptor) arg0).getLabel(); // String s2 = ((IEditorDescriptor) arg1).getLabel(); // return collator.compare(s1, s2); // } // }; private: RelatedRegistry relatedRegistry; public: static const std::string EMPTY_EDITOR_ID; // = "org.blueberry.ui.internal.emptyEditorTab"; //$NON-NLS-1$ /** * Return an instance of the receiver. Adds listeners into the extension * registry for dynamic UI purposes. */ public: EditorRegistry(); /** * Add an editor for the given extensions with the specified (possibly null) * extended type. The editor is being registered from a plugin * * @param editor * The description of the editor (as obtained from the plugin * file and built by the registry reader) * @param extensions * Collection of file extensions the editor applies to * @param filenames * Collection of filenames the editor applies to * @param contentTypeVector * @param bDefault * Indicates whether the editor should be made the default editor * and hence appear first inside a FileEditorMapping * * This method is not API and should not be called outside the workbench * code. */ public: void AddEditorFromPlugin(EditorDescriptor::Pointer editor, const std::vector& extensions, const std::vector& filenames, const std::vector& contentTypeVector, bool bDefault); /** * Add external editors to the editor mapping. */ private: void AddExternalEditorsToEditorMap(); /* * (non-Javadoc) Method declared on IEditorRegistry. */ //public: void AddPropertyListener(IPropertyListener l) { // addListenerObject(l); // } /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: IEditorDescriptor::Pointer FindEditor(const std::string& id); /** * Fires a property changed event to all registered listeners. * * @param type the type of event * @see IEditorRegistry#PROP_CONTENTS */ // private: void FirePropertyChange(final int type) { // Object[] array = getListeners(); // for (int nX = 0; nX < array.length; nX++) { // final IPropertyListener l = (IPropertyListener) array[nX]; // Platform.run(new SafeRunnable() { // public: void run() { // l.propertyChanged(EditorRegistry.this, type); // } // }); // } // } /* * (non-Javadoc) Method declared on IEditorRegistry. * * @deprecated */ public: IEditorDescriptor::Pointer GetDefaultEditor(); /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: IEditorDescriptor::Pointer GetDefaultEditor(const std::string& filename); /** * Return the (approximated) content type for a file with the given name. * * @param filename the filename * @return the content type or null if it could not be determined * @since 3.1 */ // private: IContentType::Pointer GuessAtContentType(const std::string& filename) { // return Platform.getContentTypeManager().findContentTypeFor(filename); // } /** * Returns the default file image descriptor. * * @return the image descriptor */ // private: ImageDescriptor GetDefaultImage() { // // @issue what should be the default image? // return WorkbenchImages.getImageDescriptor(ISharedImages.IMG_OBJ_FILE); // } /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: std::list GetEditors(const std::string& filename); /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: std::vector GetFileEditorMappings(); /* * (non-Javadoc) Method declared on IEditorRegistry. */ // public: ImageDescriptor GetImageDescriptor(String filename) { // return getImageDescriptor(filename, guessAtContentType(filename)); // } /** * Find the file editor mapping for the file extension. Returns * null if not found. * * @param ext * the file extension * @return the mapping, or null */ private: FileEditorMapping::Pointer GetMappingFor(const std::string& ext); /** * Find the file editor mappings for the given filename. *

* Return an array of two FileEditorMapping items, where the first mapping * is for the entire filename, and the second mapping is for the filename's * extension only. These items can be null if no mapping exist on the * filename and/or filename's extension.

* * @param filename the filename * @return the mappings */ private: std::vector GetMappingForFilename(const std::string& filename); /** * Return the editor descriptors pulled from the OS. *

* WARNING! The image described by each editor descriptor is *not* known by * the workbench's graphic registry. Therefore clients must take care to * ensure that if they access any of the images held by these editors that * they also dispose them *

* @return the editor descriptors */ //public: std::vector GetSortedEditorsFromOS(); /** * Return the editors loaded from plugins. * * @return the sorted array of editors declared in plugins * @see #comparer */ public: std::list GetSortedEditorsFromPlugins(); /** * Answer an intial id to editor map. This will create a new map and * populate it with the default system editors. * * @param initialSize * the initial size of the map * @return the new map */ private: void InitialIdToEditorMap(std::map& map); /** * Add the system editors to the provided map. This will always add an * editor with an id of {@link #SYSTEM_EXTERNAL_EDITOR_ID} and may also add * an editor with id of {@link #SYSTEM_INPLACE_EDITOR_ID} if the system * configuration supports it. * * @param map the map to augment */ private: void AddSystemEditors(std::map& map); /** * Initialize the registry state from plugin declarations and preference * overrides. */ private: void InitializeFromStorage(); /** * Set the default editors according to the preference store which can be * overwritten in the file properties.ini. In the form: *

* ext1:id1;ext2:id2;... *

* * @param defaultEditors the default editors to set */ private: void SetProductDefaults(const std::string& defaultEditors); /** * Read the editors defined in the preferences store. * * @param editorTable * Editor table to store the editor definitions. * @return true if the table is built succesfully. */ private: bool ReadEditors(std::map& editorTable); /** * Read the file types and associate them to their defined editor(s). * * @param editorTable * The editor table containing the defined editors. * @param reader * Reader containing the preferences content for the resources. * * @throws WorkbenchException */ public: void ReadResources(std::map& editorTable, std::ostream& reader); /** * Determine if the editors list contains the editor descriptor. * * @param editorsArray * The list of editors * @param editorDescriptor * The editor descriptor * @return true if the editors list contains the editor descriptor */ private: bool Contains(const std::vector& editorsArray, IEditorDescriptor::Pointer editorDescriptor); /** * Creates the reader for the resources preferences defined in the * preference store. * * @param editorTable * The editor table containing the defined editors. * @return true if the resources are read succesfully. */ private: bool ReadResources(std::map& editorTable); /** * Load the serialized resource associations Return true if the operation * was successful, false otherwise */ private: bool LoadAssociations(); /** * Return a friendly version of the given key suitable for use in the editor * map. */ private: std::string MappingKeyFor(const std::string& type); /** * Return a key that combines the file's name and extension of the given * mapping * * @param mapping the mapping to generate a key for */ private: std::string MappingKeyFor(FileEditorMapping::Pointer mapping); /** * Rebuild the editor map */ private: void RebuildEditorMap(); /** * Rebuild the internal editor mapping. */ private: void RebuildInternalEditorMap(); /* * (non-Javadoc) Method declared on IEditorRegistry. */ // public: void RemovePropertyListener(IPropertyListener l) { // removeListenerObject(l); // } /** * Save the registry to the filesystem by serializing the current resource * associations. */ public: void SaveAssociations(); /** * Set the collection of FileEditorMappings. The given collection is * converted into the internal hash table for faster lookup Each mapping * goes from an extension to the collection of editors that work on it. This * operation will rebuild the internal editor mappings. * * @param newResourceTypes * te new file editor mappings. */ public: void SetFileEditorMappings(const std::vector& newResourceTypes); /* * (non-Javadoc) Method declared on IEditorRegistry. */ public: void SetDefaultEditor(const std::string& fileName, const std::string& editorId); /** * Alphabetically sort the internal editors. * * @see #comparer */ private: std::vector SortEditors(const std::vector& unsortedList); /** * Alphabetically sort the internal editors. * * @see #comparer */ private: void SortInternalEditors(); /* * (non-Javadoc) * * @see org.blueberry.ui.IEditorRegistry#isSystemInPlaceEditorAvailable(String) */ public: bool IsSystemInPlaceEditorAvailable(const std::string& filename); /* * (non-Javadoc) * * @see org.blueberry.ui.IEditorRegistry#isSystemExternalEditorAvailable(String) */ public: bool IsSystemExternalEditorAvailable(const std::string& filename); /* * (non-Javadoc) * * @see org.blueberry.ui.IEditorRegistry#getSystemExternalEditorImageDescriptor(java.lang.String) */ // public: ImageDescriptor GetSystemExternalEditorImageDescriptor( // const std::string& filename) { // Program externalProgram = null; // int extensionIndex = filename.lastIndexOf('.'); // if (extensionIndex >= 0) { // externalProgram = Program.findProgram(filename // .substring(extensionIndex)); // } // if (externalProgram == null) { // return null; // } // // return new ExternalProgramImageDescriptor(externalProgram); // } /** * Removes the entry with the value of the editor descriptor from the given * map. If the descriptor is the last descriptor in a given * FileEditorMapping then the mapping is removed from the map. * * @param map * the map to search * @param desc * the descriptor value to remove */ private: void RemoveEditorFromMapping(std::map& map, IEditorDescriptor::Pointer desc); private: const IExtensionPoint* GetExtensionPointFilter(); /* (non-Javadoc) * @see org.blueberry.ui.IEditorRegistry#getDefaultEditor(java.lang.String, org.blueberry.core.runtime.content.IContentType) */ // public: IEditorDescriptor::Pointer GetDefaultEditor(const std::string& fileName, IContentType contentType) { // return getEditorForContentType(fileName, contentType); // } /** * Return the editor for a file with a given content type. * * @param filename the file name * @param contentType the content type * @return the editor for a file with a given content type * @since 3.1 */ private: IEditorDescriptor::Pointer GetEditorForContentType(const std::string& filename /*IContentType contentType*/); /* (non-Javadoc) * @see org.blueberry.ui.IEditorRegistry#getEditors(java.lang.String, org.blueberry.core.runtime.content.IContentType) */ // public: std::vector GetEditors(const std::string& fileName, IContentType contentType) { // return findRelatedObjects(contentType, fileName, relatedRegistry); // } /* (non-Javadoc) * @see org.blueberry.ui.IEditorRegistry#getImageDescriptor(java.lang.String, org.blueberry.core.runtime.content.IContentType) */ // public: ImageDescriptor GetImageDescriptor(const std::string filename, IContentType contentType) { // if (filename == null) { // return getDefaultImage(); // } // // if (contentType != null) { // IEditorDescriptor desc = getEditorForContentType(filename, contentType); // if (desc != null) { // ImageDescriptor anImage = (ImageDescriptor) extensionImages.get(desc); // if (anImage != null) { // return anImage; // } // anImage = desc.getImageDescriptor(); // extensionImages.put(desc, anImage); // return anImage; // } // } // // Lookup in the cache first... // String key = mappingKeyFor(filename); // ImageDescriptor anImage = (ImageDescriptor) extensionImages.get(key); // if (anImage != null) { // return anImage; // } // // // See if we have a mapping for the filename or extension // FileEditorMapping[] mapping = getMappingForFilename(filename); // for (int i = 0; i < 2; i++) { // if (mapping[i] != null) { // // Lookup in the cache first... // String mappingKey = mappingKeyFor(mapping[i]); // ImageDescriptor mappingImage = (ImageDescriptor) extensionImages // .get(key); // if (mappingImage != null) { // return mappingImage; // } // // Create it and cache it // IEditorDescriptor editor = mapping[i].getDefaultEditor(); // if (editor != null) { // mappingImage = editor.getImageDescriptor(); // extensionImages.put(mappingKey, mappingImage); // return mappingImage; // } // } // } // // // Nothing - time to look externally for the icon // anImage = getSystemExternalEditorImageDescriptor(filename); // if (anImage == null) { // anImage = getDefaultImage(); // } // // for dynamic UI - comment out the next line // //extensionImages.put(key, anImage); // return anImage; // // } /** * Find objects related to the content type. * * This method is temporary and exists only to back us off of the * soon-to-be-removed IContentTypeManager.IRelatedRegistry API. * * @param type * @param fileName * @param registry * @return the related objects */ private: std::list FindRelatedObjects(/*IContentType type,*/ const std::string& fileName, RelatedRegistry& registry); /** * Return the editors bound to this content type, either directly or indirectly. * * @param type the content type to check * @return the editors * @since 3.1 * * TODO: this should be rolled in with the above findRelatedObjects code */ // public: std::vector GetEditorsForContentType(IContentType type) { // ArrayList allRelated = new ArrayList(); // if (type == null) { // return new IEditorDescriptor [0]; // } // // Object [] related = relatedRegistry.getRelatedObjects(type); // for (int i = 0; i < related.length; i++) { // // we don't want to return duplicates // if (!allRelated.contains(related[i])) { // // if it's not filtered, add it to the list // if (!WorkbenchActivityHelper.filterItem(related[i])) { // allRelated.add(related[i]); // } // // } // } // // // now add any indirectly related objects, walking up the content type hierarchy // while ((type = type.getBaseType()) != null) { // related = relatedRegistry.getRelatedObjects(type); // for (int i = 0; i < related.length; i++) { // // we don't want to return duplicates // if (!allRelated.contains(related[i])) { // // if it's not filtered, add it to the list // if (!WorkbenchActivityHelper.filterItem(related[i])) { // allRelated.add(related[i]); // } // } // } // } // // return (IEditorDescriptor[]) allRelated.toArray(new IEditorDescriptor[allRelated.size()]); // } /** * Get filemappings for all defined filetypes, including those defined by content type. * * @return the filetypes * @since 3.1 */ public: std::vector GetUnifiedMappings(); }; class MockMapping : public IFileEditorMapping { //private: IContentType contentType; private: std::string extension; private: std::string filename; MockMapping(/*IContentType type,*/const std::string& name, const std::string& ext); public: IEditorDescriptor::Pointer GetDefaultEditor(); public: std::list GetEditors() const; public: std::list GetDeletedEditors() const; public: std::string GetExtension(); // public: ImageDescriptor GetImageDescriptor() { // IEditorDescriptor editor = getDefaultEditor(); // if (editor == null) { // return WorkbenchImages // .getImageDescriptor(ISharedImages.IMG_OBJ_FILE); // } // // return editor.getImageDescriptor(); // } public: std::string GetLabel(); public: std::string GetName(); /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public: bool operator==(const Object* obj) const; }; } #endif /*BERRYEDITORREGISTRY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorRegistryReader.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorRegistryReader.cpp index f272386485..3282ca0f84 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorRegistryReader.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorRegistryReader.cpp @@ -1,127 +1,127 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryEditorRegistryReader.h" #include "berryEditorRegistry.h" #include "berryEditorDescriptor.h" #include "berryWorkbenchRegistryConstants.h" -#include "../berryPlatformUI.h" +#include "berryPlatformUI.h" #include #include namespace berry { void EditorRegistryReader::AddEditors(EditorRegistry* registry) { this->editorRegistry = registry; this->ReadRegistry(PlatformUI::PLUGIN_ID, WorkbenchRegistryConstants::PL_EDITOR); } bool EditorRegistryReader::ReadElement(IConfigurationElement::Pointer element) { if (element->GetName() != WorkbenchRegistryConstants::TAG_EDITOR) { return false; } std::string id; if (!element->GetAttribute(WorkbenchRegistryConstants::ATT_ID, id)) { this->LogMissingAttribute(element, WorkbenchRegistryConstants::ATT_ID); return true; } EditorDescriptor::Pointer editor(new EditorDescriptor(id, element)); std::vector extensionsVector; std::vector filenamesVector; std::vector contentTypeVector; bool defaultEditor = false; std::string value; // Get editor name (required field). if (!element->GetAttribute(WorkbenchRegistryConstants::ATT_NAME, value)) { this->LogMissingAttribute(element, WorkbenchRegistryConstants::ATT_NAME); return true; } // Get target extensions (optional field) std::string extensionsString; if (element->GetAttribute(WorkbenchRegistryConstants::ATT_EXTENSIONS, extensionsString)) { Poco::StringTokenizer tokenizer(extensionsString, ",", Poco::StringTokenizer::TOK_IGNORE_EMPTY | Poco::StringTokenizer::TOK_TRIM);//$NON-NLS-1$ Poco::StringTokenizer::Iterator token = tokenizer.begin(); while (token != tokenizer.end()) { extensionsVector.push_back(*token); ++token; } } std::string filenamesString; if (element->GetAttribute(WorkbenchRegistryConstants::ATT_FILENAMES, filenamesString)) { Poco::StringTokenizer tokenizer(filenamesString, ",", Poco::StringTokenizer::TOK_IGNORE_EMPTY | Poco::StringTokenizer::TOK_TRIM);//$NON-NLS-1$ Poco::StringTokenizer::Iterator token = tokenizer.begin(); while (token != tokenizer.end()) { filenamesVector.push_back(*token); ++token; } } IConfigurationElement::vector bindings = element->GetChildren( WorkbenchRegistryConstants::TAG_CONTENT_TYPE_BINDING); for (unsigned int i = 0; i < bindings.size(); ++i) { std::string contentTypeId; if (!bindings[i]->GetAttribute( WorkbenchRegistryConstants::ATT_CONTENT_TYPE_ID, contentTypeId)) { continue; } contentTypeVector.push_back(contentTypeId); } // Is this the default editor? element->GetBoolAttribute(WorkbenchRegistryConstants::ATT_DEFAULT, defaultEditor); // Add the editor to the manager. editorRegistry->AddEditorFromPlugin(editor, extensionsVector, filenamesVector, contentTypeVector, defaultEditor); return true; } void EditorRegistryReader::ReadElement(EditorRegistry* editorRegistry, IConfigurationElement::Pointer element) { this->editorRegistry = editorRegistry; this->ReadElement(element); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorSashContainer.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorSashContainer.cpp index 3ef751e5de..5b99c77e18 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorSashContainer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorSashContainer.cpp @@ -1,610 +1,610 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryEditorSashContainer.h" #include "berryPresentationSerializer.h" #include "berryWorkbenchConstants.h" #include "berryWorkbenchPlugin.h" #include "berryLayoutTree.h" #include "berryWorkbenchWindowConfigurer.h" #include "berryWorkbenchWindow.h" #include "berryQtDnDControlWidget.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" +#include "tweaklets/berryGuiWidgetsTweaklet.h" #include #include namespace berry { const std::string EditorSashContainer::DEFAULT_WORKBOOK_ID = "DefaultEditorWorkbook"; void EditorSashContainer::AddChild(const RelationshipInfo& info) { PartSashContainer::AddChild(info); this->UpdateStackButtons(); } void EditorSashContainer::ChildAdded(LayoutPart::Pointer child) { PartSashContainer::ChildAdded(child); if (child.Cast () != 0) { editorWorkbooks.push_back(child.Cast ()); } } void EditorSashContainer::ChildRemoved(LayoutPart::Pointer child) { PartSashContainer::ChildRemoved(child); if (child.Cast () != 0) { editorWorkbooks.remove(child.Cast()); if (activeEditorWorkbook == child) { this->SetActiveWorkbook(PartStack::Pointer(0), false); } this->UpdateStackButtons(); } } PartStack::Pointer EditorSashContainer::CreateDefaultWorkbook() { PartStack::Pointer newWorkbook = this->NewEditorWorkbook(); newWorkbook->SetID(DEFAULT_WORKBOOK_ID); this->Add(newWorkbook); return newWorkbook; } void EditorSashContainer::AddDropSupport() { WorkbenchWindowConfigurer::Pointer winConfigurer = page->GetWorkbenchWindow().Cast()->GetWindowConfigurer(); QtDnDControlWidget* dropWidget = static_cast(GetParent()); dropWidget->SetTransferTypes(winConfigurer->GetTransfers()); dropWidget->AddDropListener(winConfigurer->GetDropTargetListener().GetPointer()); } PartStack::Pointer EditorSashContainer::NewEditorWorkbook() { PartStack::Pointer newWorkbook(new PartStack(page, true, PresentationFactoryUtil::ROLE_EDITOR)); std::stringstream buf; buf << newWorkbook->GetClassName() << newWorkbook.GetPointer(); newWorkbook->SetID(buf.str()); return newWorkbook; } void* EditorSashContainer::CreateParent(void* parentWidget) { //return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->CreateComposite(parentWidget); return new QtDnDControlWidget(static_cast(parentWidget)); } void EditorSashContainer::DisposeParent() { this->parent = 0; } bool EditorSashContainer::IsActiveWorkbook(PartStack::Pointer workbook) { return activeEditorWorkbook == workbook; } PartStack::Pointer EditorSashContainer::CreateStack() { return this->NewEditorWorkbook(); } void EditorSashContainer::SetVisiblePart( IStackableContainer::Pointer container, PartPane::Pointer visiblePart) { PartStack::Pointer stack = container.Cast(); if (stack == 0) return; stack->GetContainer().Cast()->SetActiveWorkbook(stack, true); stack->SetSelection(visiblePart); } StackablePart::Pointer EditorSashContainer::GetVisiblePart( IStackableContainer::Pointer container) { PartStack::Pointer refPart = container.Cast(); return refPart->GetSelection(); } EditorSashContainer::EditorSashContainer(const std::string& editorId, WorkbenchPage* page, void* parent) : PartSashContainer(editorId, page, parent) { this->CreateDefaultWorkbook(); } bool EditorSashContainer::AllowsAdd(LayoutPart::Pointer layoutPart) { return LayoutPart::AllowsAdd(layoutPart); } void EditorSashContainer::AddEditor(PartPane::Pointer pane, PartStack::Pointer stack) { //EditorStack workbook = getActiveWorkbook(); stack->Add(pane); } void EditorSashContainer::UpdateStackButtons() { // // This is applicable only when the new // // min/max behaviour is being used // Perspective persp = getPage().getActivePerspective(); // if (!Perspective.useNewMinMax(persp)) // return; // // // Find the upper Right editor stack // LayoutPart[] stacks = getChildren(); // EditorStack winner = getUpperRightEditorStack(stacks); // // // Now hide the buttons for all but the upper right stack // for (int i = 0; i < stacks.length; i++) // { // if (!(stacks[i] instanceof EditorStack) // ) // continue; // ((EditorStack) stacks[i]).showMinMax(stacks[i] == winner); // } // // // Force the stack's presentation state to match its perspective // persp.refreshEditorAreaVisibility(); } PartStack::Pointer EditorSashContainer::GetUpperRightEditorStack() { return this->GetUpperRightEditorStack(this->GetChildren()); } PartStack::Pointer EditorSashContainer::GetUpperRightEditorStack( const ILayoutContainer::ChildrenType& stacks) { // Find the upper Right editor stack PartStack::Pointer winner; Rectangle winnerRect; for (ILayoutContainer::ChildrenType::const_iterator iter = stacks.begin(); iter != stacks.end(); ++iter) { LayoutPart::Pointer part = *iter; if (part.Cast() == 0) continue; PartStack::Pointer stack = part.Cast(); Rectangle bb = stack->GetBounds(); if (iter == stacks.begin() || bb.y < winnerRect.y || (bb.y == winnerRect.y && bb.x > winnerRect.x)) { winner = stack; winnerRect = bb; } } return winner; } PartStack::Pointer EditorSashContainer::GetActiveWorkbook() { if (activeEditorWorkbook == 0) { if (editorWorkbooks.size() < 1) { this->SetActiveWorkbook(this->CreateDefaultWorkbook(), false); } else { this->SetActiveWorkbook(editorWorkbooks.front(), false); } } return activeEditorWorkbook; } std::string EditorSashContainer::GetActiveWorkbookID() { return this->GetActiveWorkbook()->GetID(); } std::list EditorSashContainer::GetEditorWorkbooks() { return editorWorkbooks; } std::size_t EditorSashContainer::GetEditorWorkbookCount() { return editorWorkbooks.size(); } void EditorSashContainer::FindSashes(LayoutPart::Pointer pane, PartPane::Sashes& sashes) { //Find the sashes around the current editor and //then the sashes around the editor area. PartSashContainer::FindSashes(pane, sashes); ILayoutContainer::Pointer container = this->GetContainer(); if (container != 0) { container->FindSashes(LayoutPart::Pointer(this), sashes); } } void EditorSashContainer::RemoveAllEditors() { PartStack::Pointer currentWorkbook = this->GetActiveWorkbook(); // Iterate over a copy so the original can be modified. std::list workbooks(editorWorkbooks); for (std::list::iterator iter = workbooks.begin(); iter != workbooks.end(); ++iter) { PartStack::Pointer workbook = *iter; std::list children = workbook->GetChildren(); for (std::list::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { workbook->Remove(*childIter); } if (workbook != currentWorkbook) { this->Remove(workbook); workbook->Dispose(); } } } void EditorSashContainer::RemoveEditor(PartPane::Pointer pane) { PartStack::Pointer workbook = pane->GetContainer().Cast(); if (workbook == 0) { return; } workbook->Remove(pane); // remove the editor workbook if empty if (workbook->GetItemCount() < 1 /* && editorWorkbooks.size() > 1*/) { // // If the user closes the last editor and the editor area // // is maximized, restore it // Perspective persp = getPage().getActivePerspective(); // if (Perspective.useNewMinMax(persp)) // { // if (persp.getPresentation().getMaximizedStack() instanceof EditorStack) // persp.getPresentation().getMaximizedStack(). // setState(IStackPresentationSite.STATE_RESTORED); // } this->Remove(workbook); workbook->Dispose(); } } bool EditorSashContainer::RestoreState(IMemento::Pointer memento) { //TODO EditorSashContainer restore state // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.RootLayoutContainer_problemsRestoringPerspective, 0); bool result = true; // Remove the default editor workbook that is // initialy created with the editor area. // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void runWithException() throws Throwable // { PartStack::Pointer defaultWorkbook; for (ILayoutContainer::ChildrenType::iterator i = children.begin(); i != children.end(); ++i) { LayoutPart::Pointer child = *i; if (child->GetID() == DEFAULT_WORKBOOK_ID) { defaultWorkbook = child.Cast(); if (defaultWorkbook->GetItemCount() > 0) { defaultWorkbook = 0; } } } if (defaultWorkbook) { Remove(defaultWorkbook); } // }} // ); // Restore the relationship/layout std::vector infos(memento->GetChildren(WorkbenchConstants::TAG_INFO)); Poco::HashMap mapIDtoPart(infos.size()); for (std::size_t i = 0; i < infos.size(); i++) { // Get the info details. IMemento::Pointer childMem = infos[i]; std::string partID; childMem->GetString(WorkbenchConstants::TAG_PART, partID); std::string relativeID; childMem->GetString(WorkbenchConstants::TAG_RELATIVE, relativeID); int relationship = 0; int left = 0, right = 0; if (!relativeID.empty()) { childMem->GetInteger(WorkbenchConstants::TAG_RELATIONSHIP, relationship); childMem->GetInteger(WorkbenchConstants::TAG_RATIO_LEFT, left); childMem->GetInteger(WorkbenchConstants::TAG_RATIO_RIGHT, right); } PartStack::Pointer workbook; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void runWithException() throws Throwable // { // Create the part. workbook = NewEditorWorkbook(); workbook->SetID(partID); // 1FUN70C: ITPUI:WIN - Shouldn't set Container when not active workbook->SetContainer(ILayoutContainer::Pointer(this)); // }} // ); IMemento::Pointer workbookMemento = childMem->GetChild( WorkbenchConstants::TAG_FOLDER); if (workbookMemento) { //result.add(workbook[0].restoreState(workbookMemento)); result &= workbook->RestoreState(workbookMemento); } const int myLeft = left, myRight = right, myRelationship = relationship; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void runWithException() throws Throwable // { // Add the part to the layout if (relativeID.empty()) { Add(workbook); } else { LayoutPart::Pointer refPart = mapIDtoPart[relativeID]; if (refPart) { Add(workbook, myRelationship, myLeft, myRight, refPart); } else { WorkbenchPlugin::Log("Unable to find part for ID: " + relativeID); } } // }} // ); mapIDtoPart[partID] = workbook; } return result; } bool EditorSashContainer::SaveState(IMemento::Pointer memento) { std::vector relationships(ComputeRelation()); // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.RootLayoutContainer_problemsSavingPerspective, 0); bool result = true; for (std::size_t i = 0; i < relationships.size(); i++) { // Save the relationship info .. // private LayoutPart part; // private int relationship; // private float ratio; // private LayoutPart relative; const RelationshipInfo& info = relationships[i]; IMemento::Pointer childMem = memento->CreateChild( WorkbenchConstants::TAG_INFO); childMem->PutString(WorkbenchConstants::TAG_PART, info.part->GetID()); PartStack::Pointer stack = info.part.Cast(); if (stack) { IMemento::Pointer folderMem = childMem->CreateChild( WorkbenchConstants::TAG_FOLDER); //result.add(stack.saveState(folderMem)); result &= stack->SaveState(folderMem); } if (info.relative != 0) { childMem->PutString(WorkbenchConstants::TAG_RELATIVE, info.relative->GetID()); childMem->PutInteger(WorkbenchConstants::TAG_RELATIONSHIP, info.relationship); childMem->PutInteger(WorkbenchConstants::TAG_RATIO_LEFT, info.left); childMem->PutInteger(WorkbenchConstants::TAG_RATIO_RIGHT, info.right); } } return result; } void EditorSashContainer::SetActiveWorkbook(PartStack::Pointer newWorkbook, bool hasFocus) { if (newWorkbook != 0) { if (std::find(editorWorkbooks.begin(), editorWorkbooks.end(), newWorkbook) == editorWorkbooks.end()) { return; } } PartStack::Pointer oldWorkbook = activeEditorWorkbook; activeEditorWorkbook = newWorkbook; if (oldWorkbook != 0 && oldWorkbook != newWorkbook) { oldWorkbook->SetActive(StackPresentation::AS_INACTIVE); } if (newWorkbook != 0) { if (hasFocus) { newWorkbook->SetActive(StackPresentation::AS_ACTIVE_FOCUS); } else { newWorkbook->SetActive(StackPresentation::AS_ACTIVE_NOFOCUS); } } this->UpdateTabList(); } void EditorSashContainer::SetActiveWorkbookFromID(const std::string& id) { for (std::list::iterator iter = editorWorkbooks.begin(); iter != editorWorkbooks.end(); ++iter) { PartStack::Pointer workbook = *iter; if (workbook->GetID() == id) { this->SetActiveWorkbook(workbook, false); } } } PartStack::Pointer EditorSashContainer::GetWorkbookFromID(const std::string& id) { for (std::list::iterator iter = editorWorkbooks.begin(); iter != editorWorkbooks.end(); ++iter) { PartStack::Pointer workbook = *iter; if (workbook->GetID() == id) { return workbook; } } return PartStack::Pointer(0); } void EditorSashContainer::UpdateTabList() { void* parent = this->GetParent(); if (parent != 0) { // parent may be 0 on startup PartStack::Pointer wb(this->GetActiveWorkbook()); //TODO EditorSashContainer update tab list // if (wb == 0) // { // parent.setTabList(new Control[0]); // } // else // { // parent.setTabList(wb.getTabList()); // } } } void EditorSashContainer::CreateControl(void* parent) { PartSashContainer::CreateControl(parent); ///let the user drop files/editor input on the editor area this->AddDropSupport(); } bool EditorSashContainer::IsCompressible() { //Added for bug 19524 return true; } bool EditorSashContainer::IsStackType(IStackableContainer::Pointer toTest) { if (toTest.Cast() == 0) return false; return (toTest.Cast ()->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR); } bool EditorSashContainer::IsPaneType(StackablePart::Pointer toTest) { if (toTest.Cast() == 0) return false; return (toTest.Cast ()->GetPartReference().Cast () != 0); } bool EditorSashContainer::RestorePresentationState(IMemento::Pointer /*areaMem*/) { std::list workbooks = this->GetEditorWorkbooks(); for (std::list::iterator iter = workbooks.begin(); iter != workbooks.end(); ++iter) { PartStack::Pointer workbook = *iter; IMemento::Pointer memento = workbook->GetSavedPresentationState(); if (memento == 0) { continue; } std::list listParts = workbook->GetPresentableParts(); std::vector parts(listParts.begin(), listParts.end()); PresentationSerializer serializer(parts); //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // public void runWithException() throws Throwable // { workbook->GetPresentation()->RestoreState(&serializer, memento); // }} // ); } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", 0); //$NON-NLS-1$ return true; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorSite.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorSite.h index c8a05790b6..8e5af4f277 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorSite.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryEditorSite.h @@ -1,155 +1,155 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYEDITORSITE_H_ #define BERRYEDITORSITE_H_ #include "berryPartSite.h" #include "berryEditorDescriptor.h" -#include "../berryIEditorPart.h" +#include "berryIEditorPart.h" #include "berryWorkbenchPage.h" -#include "../berryIEditorSite.h" -#include "../berryIEditorReference.h" +#include "berryIEditorSite.h" +#include "berryIEditorReference.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * * An editor container manages the services for an editor. */ class EditorSite : public PartSite, public IEditorSite { /* package */ //static final int PROP_REUSE_EDITOR = -0x101; private: EditorDescriptor::Pointer desc; //ListenerList propChangeListeners = new ListenerList(1); // SubActionBars ab = null; /** * Initialize the local services. */ // void InitializeDefaultServices() { // // Register an implementation of the service appropriate for the // // EditorSite. // final IDragAndDropService editorDTService = new EditorSiteDragAndDropServiceImpl(); // serviceLocator.registerService(IDragAndDropService.class, editorDTService); // } protected: std::string GetInitialScopeId(); public: berryObjectMacro(EditorSite) /** * Constructs an EditorSite for an editor. */ EditorSite(IEditorReference::Pointer ref, IEditorPart::Pointer editor, WorkbenchPage* page, EditorDescriptor::Pointer desc); // void SetActionBars(SubActionBars bars) { // super.setActionBars(bars); // // if (bars instanceof IActionBars2) { // ab = new SubActionBars2((IActionBars2)bars, this); // } else { // ab = new SubActionBars(bars, this); // } // } // void ActivateActionBars(bool forceVisibility) { // if (ab != null) { // ab.activate(forceVisibility); // } // super.activateActionBars(forceVisibility); // } // void DeactivateActionBars(bool forceHide) { // if (ab != null) { // ab.deactivate(forceHide); // } // super.deactivateActionBars(forceHide); // } /** * Returns the editor action bar contributor for this editor. *

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

* * @return the editor action bar contributor */ // IEditorActionBarContributor::Pointer GetActionBarContributor() { // EditorActionBars bars = (EditorActionBars) getActionBars(); // if (bars != null) { // return bars.getEditorContributor(); // } // // return null; // } /** * Returns the extension editor action bar contributor for this editor. */ // IEditorActionBarContributor::Pointer GetExtensionActionBarContributor() { // EditorActionBars bars = (EditorActionBars) getActionBars(); // if (bars != null) { // return bars.getExtensionContributor(); // } // // return null; // } /** * Returns the editor */ IEditorPart::Pointer GetEditorPart(); EditorDescriptor::Pointer GetEditorDescriptor(); // void registerContextMenu(final MenuManager menuManager, // final ISelectionProvider selectionProvider, // final boolean includeEditorInput) { // registerContextMenu(getId(), menuManager, selectionProvider, // includeEditorInput); // } // // void registerContextMenu(final String menuId, // final MenuManager menuManager, // final ISelectionProvider selectionProvider, // final boolean includeEditorInput) { // if (menuExtenders == null) { // menuExtenders = new ArrayList(1); // } // // PartSite.registerContextMenu(menuId, menuManager, selectionProvider, // includeEditorInput, getPart(), menuExtenders); // } }; } #endif /*BERRYEDITORSITE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryErrorViewPart.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryErrorViewPart.h index a7b82385a6..54b5e196e7 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryErrorViewPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryErrorViewPart.h @@ -1,83 +1,83 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYERRORVIEWPART_H_ #define BERRYERRORVIEWPART_H_ -#include "../tweaklets/berryWorkbenchPageTweaklet.h" +#include "tweaklets/berryWorkbenchPageTweaklet.h" -#include "../berryViewPart.h" +#include "berryViewPart.h" namespace berry { /** * This part is shown instead the views with errors. * * @since 3.3 */ class ErrorViewPart : public ViewPart { public: berryObjectMacro(ErrorViewPart) /** * Creates instance of the class */ ErrorViewPart(); /** * Creates instance of the class * * @param error the status */ ErrorViewPart(const std::string& title, const std::string& error); /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ void CreatePartControl(void* parent); /* * (non-Javadoc) * * @see org.eclipse.ui.part.ViewPart#setPartName(java.lang.String) */ void SetPartName(const std::string& newName); /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ void SetFocus(); private: //IStatus error; std::string title; std::string error; Object::Pointer statusPart; }; } #endif /* BERRYERRORVIEWPART_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryFileEditorMapping.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryFileEditorMapping.h index f3d5eecd6b..35906d3f5d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryFileEditorMapping.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryFileEditorMapping.h @@ -1,228 +1,228 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYFILEEDITORMAPPING_H_ #define BERRYFILEEDITORMAPPING_H_ -#include "../berryIFileEditorMapping.h" +#include "berryIFileEditorMapping.h" #include "berryEditorDescriptor.h" #include #include namespace berry { /** * \ingroup org_blueberry_ui_internal * * Implementation of IFileEditorMapping. * */ class FileEditorMapping : public IFileEditorMapping { public: berryObjectMacro(FileEditorMapping) private: static const std::string STAR; // = "*"; //$NON-NLS-1$ static const std::string DOT; // = "."; //$NON-NLS-1$ std::string name; std::string extension; // Collection of EditorDescriptor, where the first one // is considered the default one. std::list editors; std::list deletedEditors; std::list declaredDefaultEditors; /** * Compare the editor ids from both lists and return true if they * are equals. */ bool CompareList(const std::list& l1, const std::list& l2) const; public: /** * Create an instance of this class. * * @param name java.lang.std::string * @param extension java.lang.std::string */ FileEditorMapping(const std::string& extension, const std::string& name = STAR); /** * Add the given editor to the list of editors registered. * * @param editor the editor to add */ void AddEditor(EditorDescriptor::Pointer editor); /** * Clone the receiver. */ // Object clone() { // try { // FileEditorMapping clone = (FileEditorMapping) super.clone(); // clone.editors = (List) ((ArrayList) editors).clone(); // return clone; // } catch (CloneNotSupportedException e) { // return null; // } // } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ bool operator==(const Object* obj) const; /* (non-Javadoc) * Method declared on IFileEditorMapping. */ IEditorDescriptor::Pointer GetDefaultEditor(); /* (non-Javadoc) * Method declared on IFileEditorMapping. */ std::list GetEditors() const; /* (non-Javadoc) * Method declared on IFileEditorMapping. */ std::list GetDeletedEditors() const; /* (non-Javadoc) * Method declared on IFileEditorMapping. */ std::string GetExtension() const; /* (non-Javadoc) * Method declared on IFileEditorMapping. */ // ImageDescriptor getImageDescriptor() { // IEditorDescriptor editor = getDefaultEditor(); // if (editor == null) { // return WorkbenchImages // .getImageDescriptor(ISharedImages.IMG_OBJ_FILE); // } // return editor.getImageDescriptor(); // } /* (non-Javadoc) * Method declared on IFileEditorMapping. */ std::string GetLabel() const; /* (non-Javadoc) * Method declared on IFileEditorMapping. */ std::string GetName() const; /** * Remove the given editor from the set of editors registered. * * @param editor the editor to remove */ void RemoveEditor(EditorDescriptor::Pointer editor); /** * Set the default editor registered for file type * described by this mapping. * * @param editor the editor to be set as default */ void SetDefaultEditor(EditorDescriptor::Pointer editor); /** * Set the collection of all editors (EditorDescriptor) * registered for the file type described by this mapping. * Typically an editor is registered either through a plugin or explicitly by * the user modifying the associations in the preference pages. * This modifies the internal list to share the passed list. * (hence the clear indication of list in the method name) * * @param newEditors the new list of associated editors */ void SetEditorsList(const std::list& newEditors); /** * Set the collection of all editors (EditorDescriptor) * formally registered for the file type described by this mapping * which have been deleted by the user. * This modifies the internal list to share the passed list. * (hence the clear indication of list in the method name) * * @param newDeletedEditors the new list of associated (but deleted) editors */ void SetDeletedEditorsList( const std::list& newDeletedEditors); /** * Set the file's extension. * * @param extension the file extension for this mapping */ void SetExtension(const std::string& extension); /** * Set the file's name. * * @param name the file name for this mapping */ void SetName(const std::string& name); /** * Get the editors that have been declared as default. This may be via plugin * declarations or the preference page. * * @return the editors the default editors * @since 3.1 */ std::list GetDeclaredDefaultEditors(); /** * Return whether the editor is declared default. * If this is EditorDescriptor fails the ExpressionsCheck it will always * return false, even if it's the original default editor. * * @param editor the editor to test * @return whether the editor is declared default * @since 3.1 */ bool IsDeclaredDefaultEditor(IEditorDescriptor::Pointer editor); /** * Set the default editors for this mapping. * * @param defaultEditors the editors * @since 3.1 */ void SetDefaultEditors( const std::list& defaultEditors); }; } #endif /*BERRYFILEEDITORMAPPING_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryFolderLayout.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryFolderLayout.cpp index 27025cf5b5..13e4744b24 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryFolderLayout.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryFolderLayout.cpp @@ -1,98 +1,98 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryFolderLayout.h" #include "berryPartPlaceholder.h" #include "berryWorkbenchPlugin.h" #include "berryPageLayout.h" #include "berryLayoutHelper.h" -#include "../berryUIException.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 std::string& viewId) { if (!pageLayout->CheckValidPlaceholderId(viewId)) { return; } // Create the placeholder. StackablePart::Pointer newPart(new PartPlaceholder(viewId)); this->LinkPartToPageLayout(viewId, newPart); // Add it to the folder layout. folder->Add(newPart); } void FolderLayout::AddView(const std::string& 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); //$NON-NLS-1$ } PartPane::Pointer newPart = LayoutHelper::CreateView(pageLayout->GetViewFactory(), viewId); this->LinkPartToPageLayout(viewId, newPart); folder->Add(newPart); } catch (PartInitException& e) { // cannot safely open the dialog so log the problem WorkbenchPlugin::Log(this->GetClassName(), "AddView(const std::string&)", e); //$NON-NLS-1$ } } std::string FolderLayout::GetProperty(const std::string& id) { return folder->GetProperty(id); } void FolderLayout::SetProperty(const std::string& id, const std::string& value) { folder->SetProperty(id, value); } void FolderLayout::LinkPartToPageLayout(const std::string& viewId, StackablePart::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/src/internal/berryFolderLayout.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryFolderLayout.h index c31c2cdd8d..231b98ec8a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryFolderLayout.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryFolderLayout.h @@ -1,97 +1,97 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYFOLDERLAYOUT_H_ #define BERRYFOLDERLAYOUT_H_ -#include "../berryIFolderLayout.h" +#include "berryIFolderLayout.h" #include "berryPartStack.h" #include "berryViewFactory.h" namespace berry { class PageLayout; /** * \ingroup org_blueberry_ui_internal * * This layout is used to define the initial set of views and placeholders * in a folder. *

* Views are added to the folder by ID. This id is used to identify * a view descriptor in the view registry, and this descriptor is used to * instantiate the IViewPart. *

*/ class FolderLayout : public IFolderLayout { public: berryObjectMacro(FolderLayout) private: PartStack::Pointer folder; SmartPointer pageLayout; ViewFactory* viewFactory; public: /** * Create an instance of a FolderLayout belonging to a * PageLayout. */ FolderLayout(SmartPointer pageLayout, PartStack::Pointer folder, ViewFactory* viewFactory); /* (non-Javadoc) * @see org.blueberry.ui.IPlaceholderFolderLayout#addPlaceholder(java.lang.String) */ void AddPlaceholder(const std::string& viewId); /* (non-Javadoc) * @see org.blueberry.ui.IFolderLayout#addView(java.lang.String) */ void AddView(const std::string& viewId); /* (non-Javadoc) * @see org.blueberry.ui.IPlaceholderFolderLayout#getProperty(java.lang.String) */ std::string GetProperty(const std::string& id); /* (non-Javadoc) * @see org.blueberry.ui.IPlaceholderFolderLayout#setProperty(java.lang.String, java.lang.String) */ void SetProperty(const std::string& id, const std::string& value); private: /** * Inform the page layout of the new part created * and the folder the part belongs to. */ void LinkPartToPageLayout(const std::string& viewId, StackablePart::Pointer newPart); }; } #endif /*BERRYFOLDERLAYOUT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryIDragOverListener.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryIDragOverListener.h index f037a915b7..92d15f8f2b 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryIDragOverListener.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryIDragOverListener.h @@ -1,68 +1,68 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYIDRAGOVERLISTENER_H_ #define BERRYIDRAGOVERLISTENER_H_ #include #include -#include "../berryPoint.h" -#include "../berryRectangle.h" +#include "berryPoint.h" +#include "berryRectangle.h" #include "berryIDropTarget.h" namespace berry { /** * Implementers of this interface will receive notifications when objects are dragged over * a particular control. */ struct IDragOverListener : public virtual Object { berryObjectMacro(IDragOverListener); struct Events { typedef Message4 DragEventType; typedef MessageDelegate4 DragDelegate; DragEventType drag; void AddListener(IDragOverListener::Pointer listener); void RemoveListener(IDragOverListener::Pointer listener); }; /** * Notifies the receiver that the given object has been dragged over * the given position. Returns a drop target if the object may be * dropped in this position. Returns null otherwise. * * @param draggedObject object being dragged over this location * @param position location of the cursor * @param dragRectangle current drag rectangle (may be an empty rectangle if none) * @return a valid drop target or null if none */ virtual IDropTarget::Pointer Drag(void* currentControl, Object::Pointer draggedObject, const Point& position, const Rectangle& dragRectangle) = 0; }; } #endif /* BERRYIDRAGOVERLISTENER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryIDropTarget.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryIDropTarget.h index 91b49c40e5..0b661a5dc5 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryIDropTarget.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryIDropTarget.h @@ -1,70 +1,70 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYIDROPTARGET_H_ #define BERRYIDROPTARGET_H_ #include -#include "../berryRectangle.h" -#include "../tweaklets/berryDnDTweaklet.h" +#include "berryRectangle.h" +#include "tweaklets/berryDnDTweaklet.h" namespace berry { /** * This interface is used to drop objects. It knows how to drop a particular object * in a particular location. IDropTargets are typically created by IDragOverListeners, and * it is the job of the IDragOverListener to supply the drop target with information about * the object currently being dragged. * * @see IDragOverListener */ struct IDropTarget : public Object { berryObjectMacro(IDropTarget); /** * Drops the object in this position */ virtual void Drop() = 0; /** * Returns a cursor id describing this drop operation * * @return a cursor id describing this drop operation */ virtual DnDTweaklet::CursorType GetCursor() = 0; /** * Returns a rectangle (screen coordinates) describing the target location * for this drop operation. * * @return a snap rectangle or null if this drop target does not have a specific snap * location. */ virtual Rectangle GetSnapRectangle() = 0; /** * This is called whenever a drag operation is cancelled */ virtual void DragFinished(bool dropPerformed) = 0; }; } #endif /* BERRYIDROPTARGET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPart.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPart.cpp index e8cfd72bb1..fe601a8da8 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPart.cpp @@ -1,338 +1,338 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryLayoutPart.h" #include "berryILayoutContainer.h" #include "berryDetachedWindow.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" -#include "../berryIWorkbenchWindow.h" -#include "../berryConstants.h" +#include "tweaklets/berryGuiWidgetsTweaklet.h" +#include "berryIWorkbenchWindow.h" +#include "berryConstants.h" namespace berry { const std::string LayoutPart::PROP_VISIBILITY = "PROP_VISIBILITY"; //$NON-NLS-1$ LayoutPart::LayoutPart(const std::string& id_) : id(id_), deferCount(0) { } LayoutPart::~LayoutPart() { } bool LayoutPart::AllowsAutoFocus() { if (container != 0) { return container->AllowsAutoFocus(); } return true; } void LayoutPart::Dispose() { } Rectangle LayoutPart::GetBounds() { if (this->GetControl() == 0) return Rectangle(); return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetControl()); } ILayoutContainer::Pointer LayoutPart::GetContainer() { return container; } std::string LayoutPart::GetID() const { return id; } bool LayoutPart::IsCompressible() { return false; } Point LayoutPart::GetSize() { Rectangle r = this->GetBounds(); Point ptSize(r.width, r.height); return ptSize; } int LayoutPart::GetSizeFlags(bool /*horizontal*/) { return Constants::MIN; } int LayoutPart::ComputePreferredSize(bool /*width*/, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredParallel) { return preferredParallel; } IDropTarget::Pointer LayoutPart::GetDropTarget(Object::Pointer /*draggedObject*/, const Point& /*displayCoordinates*/) { return IDropTarget::Pointer(0); } bool LayoutPart::IsDocked() { Shell::Pointer s = this->GetShell(); if (s == 0) { return false; } return s->GetData().Cast() != 0; } Shell::Pointer LayoutPart::GetShell() { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(ctrl); } return Shell::Pointer(0); } IWorkbenchWindow::Pointer LayoutPart::GetWorkbenchWindow() { Shell::Pointer s = this->GetShell(); if (s == 0) { return IWorkbenchWindow::Pointer(0); } Object::Pointer data = s->GetData(); if (data.Cast() != 0) { return data.Cast(); } else if (data.Cast() != 0) { return data.Cast()->GetWorkbenchPage()->GetWorkbenchWindow(); } return IWorkbenchWindow::Pointer(0); } void LayoutPart::MoveAbove(void* /*refControl*/) { } void LayoutPart::Reparent(void* newParent) { void* control = this->GetControl(); GuiWidgetsTweaklet* guiTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if ((control == 0) || (guiTweaklet->GetParent(control) == newParent)) { return; } if (guiTweaklet->IsReparentable(control)) { // make control small in case it is not resized with other controls //control.setBounds(0, 0, 0, 0); // By setting the control to disabled before moving it, // we ensure that the focus goes away from the control and its children // and moves somewhere else bool enabled = guiTweaklet->GetEnabled(control); guiTweaklet->SetEnabled(control, false); guiTweaklet->SetParent(control, newParent); guiTweaklet->SetEnabled(control, enabled); guiTweaklet->MoveAbove(control, 0); } } bool LayoutPart::GetVisible() { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(ctrl); } return false; } bool LayoutPart::IsVisible() { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsVisible(ctrl); } return false; } void LayoutPart::SetVisible(bool makeVisible) { void* ctrl = this->GetControl(); if (ctrl != 0) { if (makeVisible == Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(ctrl)) { return; } // if (!makeVisible && this->IsFocusAncestor(ctrl)) // { // // Workaround for Bug 60970 [EditorMgmt] setActive() called on an editor when it does not have focus. // // Force focus on the shell so that when ctrl is hidden, // // SWT does not try to send focus elsewhere, which may cause // // some other part to be activated, which affects the part // // activation order and can cause flicker. // ctrl.getShell().forceFocus(); // } Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(ctrl, makeVisible); } } bool LayoutPart::IsFocusAncestor(void* /*ctrl*/) { // Control f = ctrl.getDisplay().getFocusControl(); // while (f != null && f != ctrl) // { // f = f.getParent(); // } // return f == ctrl; return false; } void LayoutPart::SetBounds(const Rectangle& r) { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(ctrl, r); } } void LayoutPart::SetContainer(ILayoutContainer::Pointer container) { this->container = container; //TODO Zoom // if (container != 0) // { // setZoomed(container.childIsZoomed(this)); // } } void LayoutPart::SetID(const std::string& str) { id = str; } LayoutPart::Pointer LayoutPart::GetPart() { return LayoutPart::Pointer(this); } void LayoutPart::DeferUpdates(bool shouldDefer) { if (shouldDefer) { if (deferCount == 0) { this->StartDeferringEvents(); } deferCount++; } else { if (deferCount> 0) { deferCount--; if (deferCount == 0) { this->HandleDeferredEvents(); } } } } void LayoutPart::StartDeferringEvents() { } void LayoutPart::HandleDeferredEvents() { } bool LayoutPart::IsDeferred() { return deferCount> 0; } void LayoutPart::DescribeLayout(std::string& /*buf*/) const { } std::string LayoutPart::GetPlaceHolderId() { return this->GetID(); } void LayoutPart::ResizeChild(LayoutPart::Pointer /*childThatChanged*/) { } void LayoutPart::FlushLayout() { ILayoutContainer::Pointer container = this->GetContainer(); if (container != 0) { container->ResizeChild(LayoutPart::Pointer(this)); } } bool LayoutPart::AllowsAdd(LayoutPart::Pointer /*toAdd*/) { return false; } std::string LayoutPart::ToString() { return ""; } void LayoutPart::TestInvariants() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPart.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPart.h index dfcc3d2121..1afa5f6d48 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPart.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPart.h @@ -1,298 +1,298 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYLAYOUTPART_H_ #define BERRYLAYOUTPART_H_ #include #include "berryIDropTarget.h" -#include "../berryISizeProvider.h" -#include "../berryRectangle.h" -#include "../berryPoint.h" -#include "../berryShell.h" +#include "berryISizeProvider.h" +#include "berryRectangle.h" +#include "berryPoint.h" +#include "berryShell.h" namespace berry { struct ILayoutContainer; struct IWorkbenchWindow; /** * \ingroup org_blueberry_ui_internal * * A presentation part is used to build the presentation for the * workbench. Common subclasses are pane and folder. */ class LayoutPart : virtual public Object { //, public ISizeProvider { public: berryObjectMacro(LayoutPart); protected: SmartPointer container; protected: std::string id; public: static const std::string PROP_VISIBILITY;// = "PROP_VISIBILITY"; //$NON-NLS-1$ /** * Number of times deferUpdates(true) has been called without a corresponding * deferUpdates(false) */ private: int deferCount; /** * PresentationPart constructor comment. */ public: LayoutPart(const std::string& id); public: virtual ~LayoutPart(); /** * When a layout part closes, focus will return to a previously active part. * This method determines whether this part should be considered for activation * when another part closes. If a group of parts are all closing at the same time, * they will all return false from this method while closing to ensure that the * parent does not activate a part that is in the process of closing. Parts will * also return false from this method if they are minimized, closed fast views, * obscured by zoom, etc. * * @return true iff the parts in this container may be given focus when the active * part is closed */ public: virtual bool AllowsAutoFocus(); /** * Creates the GUI control */ public: virtual void CreateControl(void* parent) = 0; /** * Disposes the GUI control * * This can be used to execute cleanup code or notify listeners * when a LayoutPart is no longer used, but is still referenced * by a SmartPointer (instead of putting the code in the LayoutPart * destructor). */ public: virtual void Dispose(); /** * Gets the presentation bounds. */ public: Rectangle GetBounds(); /** * Gets the parent for this part. *

* In general, this is non-null if the object has been added to a container and the * container's widgetry exists. The exception to this rule is PartPlaceholders * created when restoring a ViewStack using restoreState, which point to the * ViewStack even if its widgetry doesn't exist yet. Returns null in the remaining * cases. *

*

* TODO: change the semantics of this method to always point to the parent container, * regardless of whether its widgetry exists. Locate and refactor code that is currently * depending on the special cases. *

*/ public: virtual SmartPointer GetContainer(); /** * Get the part control. This method may return null. */ public: virtual void* GetControl() = 0; /** * Gets the ID for this part. */ public: virtual std::string GetID() const; public: virtual bool IsCompressible(); /** * Gets the presentation size. */ public: virtual Point GetSize(); /** * @see org.blueberry.ui.presentations.StackPresentation#getSizeFlags(boolean) * * @since 3.1 */ public: virtual int GetSizeFlags(bool horizontal); /** * @see org.blueberry.ui.presentations.StackPresentation#computePreferredSize(boolean, int, int, int) * * @since 3.1 */ public: virtual int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); public: virtual IDropTarget::Pointer GetDropTarget(Object::Pointer draggedObject, const Point& displayCoordinates); public: bool IsDocked(); public: virtual Shell::Pointer GetShell(); /** * Returns the workbench window window for a part. * * @return the workbench window, or null if there's no window * associated with this part. */ public: virtual SmartPointer GetWorkbenchWindow(); /** * Move the control over another one. */ public: virtual void MoveAbove(void* refControl); /** * Reparent a part. */ public: virtual void Reparent(void* newParent); /** * Returns true if this part was set visible. This returns whatever was last passed into * setVisible, but does not necessarily indicate that the part can be seen (ie: one of its * ancestors may be invisible) */ public: virtual bool GetVisible(); /** * Returns true if this part can be seen. Returns false if the part or any of its ancestors * are invisible. */ public: virtual bool IsVisible(); /** * Shows the receiver if visible is true otherwise hide it. */ public: virtual void SetVisible(bool makeVisible); /** * Returns true if the given control or any of its descendents has focus. */ private: virtual bool IsFocusAncestor(void* ctrl); /** * Sets the presentation bounds. */ public: virtual void SetBounds(const Rectangle& r); /** * Sets the parent for this part. */ public: virtual void SetContainer(SmartPointer container); /** * Sets the part ID. */ public: virtual void SetID(const std::string& str); /* (non-Javadoc) * @see org.blueberry.ui.internal.IWorkbenchDragDropPart#getPart() */ public: virtual LayoutPart::Pointer GetPart(); /** * deferUpdates(true) disables widget updates until a corresponding call to * deferUpdates(false). Exactly what gets deferred is the decision * of each LayoutPart, however the part may only defer operations in a manner * that does not affect the final result. * That is, the state of the receiver after the final call to deferUpdates(false) * must be exactly the same as it would have been if nothing had been deferred. * * @param shouldDefer true iff events should be deferred */ public: void DeferUpdates(bool shouldDefer); /** * This is called when deferUpdates(true) causes UI events for this * part to be deferred. Subclasses can overload to initialize any data * structures that they will use to collect deferred events. */ protected: virtual void StartDeferringEvents(); /** * Immediately processes all UI events which were deferred due to a call to * deferUpdates(true). This is called when the last call is made to * deferUpdates(false). Subclasses should overload this method if they * defer some or all UI processing during deferUpdates. */ protected: virtual void HandleDeferredEvents(); /** * Subclasses can call this method to determine whether UI updates should * be deferred. Returns true iff there have been any calls to deferUpdates(true) * without a corresponding call to deferUpdates(false). Any operation which is * deferred based on the result of this method should be performed later within * handleDeferredEvents(). * * @return true iff updates should be deferred. */ protected: bool IsDeferred(); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they do not need to be translated. * * @param buf */ public: virtual void DescribeLayout(std::string& buf) const; /** * Returns an id representing this part, suitable for use in a placeholder. * * @since 3.0 */ public: virtual std::string GetPlaceHolderId(); public: virtual void ResizeChild(LayoutPart::Pointer childThatChanged); public: void FlushLayout(); /** * Returns true iff the given part can be added to this ILayoutContainer * @param toAdd * @return * @since 3.1 */ public: virtual bool AllowsAdd(LayoutPart::Pointer toAdd); /** * Tests the integrity of this object. Throws an exception if the object's state * is not internally consistent. For use in test suites. */ public: virtual void TestInvariants(); public: virtual std::string ToString(); }; } #endif /*BERRYLAYOUTPART_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPartSash.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPartSash.cpp index 2fc28239d0..8257708f6c 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPartSash.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPartSash.cpp @@ -1,306 +1,306 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryLayoutPartSash.h" #include "berryLayoutTree.h" #include "berryLayoutTreeNode.h" #include "berryWorkbenchPlugin.h" -#include "../berryConstants.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" +#include "berryConstants.h" +#include "tweaklets/berryGuiWidgetsTweaklet.h" namespace berry { LayoutPartSash::SelectionListener::SelectionListener(LayoutPartSash* lp) : layoutPartSash(lp) { } void LayoutPartSash::SelectionListener::WidgetSelected(GuiTk::SelectionEvent::Pointer e) { layoutPartSash->CheckDragLimit(e); if (e->detail != Constants::DRAG) { layoutPartSash->WidgetSelected(e->x, e->y, e->width, e->height); } } LayoutPartSash::LayoutPartSash(PartSashContainer* rootContainer, int style) : LayoutPart(""), sash(0), enabled(false), rootContainer(rootContainer), style(style), left(300), right(300), presFactory(0), isVisible(false) { selectionListener = new SelectionListener(this); } LayoutPartSash::~LayoutPartSash() { this->Dispose(); } void LayoutPartSash::CheckDragLimit(GuiTk::SelectionEvent::Pointer event) { LayoutTree::Pointer root = rootContainer->GetLayoutTree(); LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); Rectangle nodeBounds = node->GetBounds(); Rectangle eventRect(event->x, event->y, event->width, event->height); bool vertical = (style == Constants::VERTICAL); // If a horizontal sash, flip the coordinate system so that we // can handle horizontal and vertical sashes without special cases if (!vertical) { nodeBounds.FlipXY(); eventRect.FlipXY(); } int eventX = eventRect.x; int left = std::max(0, eventX - nodeBounds.x); left = std::min(left, nodeBounds.width - this->GetSashSize()); int right = nodeBounds.width - left - this->GetSashSize(); LayoutTreeNode::ChildSizes sizes = node->ComputeChildSizes(nodeBounds.width, nodeBounds.height, left, right, nodeBounds.width); eventRect.x = nodeBounds.x + sizes.left; // If it's a horizontal sash, restore eventRect to its original coordinate system if (!vertical) { eventRect.FlipXY(); } event->x = eventRect.x; event->y = eventRect.y; } void LayoutPartSash::CreateControl(void* /*parent*/) { // Defer creation of the control until it becomes visible if (isVisible) { this->DoCreateControl(); } } void LayoutPartSash::DoCreateControl() { if (sash == 0) { // ask the presentation factory to create the sash IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory(); int sashStyle = IPresentationFactory::SASHTYPE_NORMAL | style; sash = factory->CreateSash(this->rootContainer->GetParent(), sashStyle); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddSelectionListener(sash, selectionListener); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(sash, enabled); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(sash, bounds); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(sash, isVisible); } } void LayoutPartSash::SetBounds(const Rectangle& r) { LayoutPart::SetBounds(r); bounds = r; } void LayoutPartSash::SetVisible(bool visible) { if (visible == isVisible) { return; } if (visible) { this->DoCreateControl(); } else { this->Dispose(); } LayoutPart::SetVisible(visible); isVisible = visible; } bool LayoutPartSash::IsVisible() { return isVisible; } void LayoutPartSash::Dispose() { if (sash != 0) { bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(sash); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->Dispose(sash); } sash = 0; } Rectangle LayoutPartSash::GetBounds() { if (sash == 0) { return bounds; } return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(sash); } void* LayoutPartSash::GetControl() { return sash; } std::string LayoutPartSash::GetID() { return ""; } LayoutPartSash::Pointer LayoutPartSash::GetPostLimit() { return postLimit; } LayoutPartSash::Pointer LayoutPartSash::GetPreLimit() { return preLimit; } int LayoutPartSash::GetLeft() { return left; } int LayoutPartSash::GetRight() { return right; } bool LayoutPartSash::IsHorizontal() { return ((style & Constants::HORIZONTAL) == Constants::HORIZONTAL); } bool LayoutPartSash::IsVertical() { return ((style & Constants::VERTICAL) == Constants::VERTICAL); } void LayoutPartSash::SetPostLimit(LayoutPartSash::Pointer newPostLimit) { postLimit = newPostLimit; } void LayoutPartSash::SetPreLimit(LayoutPartSash::Pointer newPreLimit) { preLimit = newPreLimit; } void LayoutPartSash::SetRatio(float newRatio) { int total = left + right; int newLeft = (int) (total * newRatio); this->SetSizes(newLeft, total - newLeft); } void LayoutPartSash::SetSizes(int left, int right) { if (left < 0 || right < 0) { return; } if (left == this->left && right == this->right) { return; } this->left = left; this->right = right; this->FlushCache(); } void LayoutPartSash::FlushCache() { LayoutTree::Pointer root = rootContainer->GetLayoutTree(); if (root != 0) { LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); if (node != 0) { node->FlushCache(); } } } void LayoutPartSash::WidgetSelected(int x, int y, int /*width*/, int /*height*/) { if (!enabled) { return; } LayoutTree::Pointer root = rootContainer->GetLayoutTree(); LayoutTreeNode::Pointer node = root->FindSash(LayoutPartSash::Pointer(this)); Rectangle nodeBounds = node->GetBounds(); //Recompute ratio x -= nodeBounds.x; y -= nodeBounds.y; if (style == Constants::VERTICAL) { this->SetSizes(x, nodeBounds.width - x - this->GetSashSize()); } else { this->SetSizes(y, nodeBounds.height - y - this->GetSashSize()); } node->SetBounds(nodeBounds); } void LayoutPartSash::SetEnabled(bool resizable) { this->enabled = resizable; if (sash != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(sash, enabled); } } int LayoutPartSash::GetSashSize() const { IPresentationFactory* factory = WorkbenchPlugin::GetDefault()->GetPresentationFactory(); int sashStyle = IPresentationFactory::SASHTYPE_NORMAL | style; int size = factory->GetSashSize(sashStyle); return size; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPartSash.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPartSash.h index ce39ce9af6..70b8920b5a 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPartSash.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutPartSash.h @@ -1,183 +1,183 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYLAYOUTPARTSASH_H_ #define BERRYLAYOUTPARTSASH_H_ #include "berryLayoutPart.h" #include "berryPartSashContainer.h" -#include "../guitk/berryGuiTkISelectionListener.h" -#include "../presentations/berryIPresentationFactory.h" +#include "guitk/berryGuiTkISelectionListener.h" +#include "presentations/berryIPresentationFactory.h" namespace berry { class LayoutPartSash: public LayoutPart { friend class WorkbenchPage; friend class PartSashContainer; friend class LayoutTreeNode; public: berryObjectMacro(LayoutPartSash); LayoutPartSash(PartSashContainer* rootContainer, int style); ~LayoutPartSash(); private: void* sash; bool enabled; PartSashContainer* rootContainer; int style; LayoutPartSash::Pointer preLimit; LayoutPartSash::Pointer postLimit; int left; int right; Rectangle bounds; IPresentationFactory* presFactory; /** * Stores whether or not the sash is visible. (This is expected to have a meaningful * value even if the underlying control doesn't exist). */ bool isVisible; struct SelectionListener : public GuiTk::ISelectionListener { SelectionListener(LayoutPartSash* layoutPartSash); void WidgetSelected(GuiTk::SelectionEvent::Pointer e); private: LayoutPartSash* layoutPartSash; }; GuiTk::ISelectionListener::Pointer selectionListener; // checkDragLimit contains changes by cagatayk@acm.org void CheckDragLimit(GuiTk::SelectionEvent::Pointer event); /** * Creates the control. As an optimization, creation of the control is deferred if * the control is invisible. */ public: void CreateControl(void* parent); /** * Creates the underlying SWT control. * * @since 3.1 */ private: void DoCreateControl(); public: void SetBounds(const Rectangle& r); /** * Makes the sash visible or invisible. Note: as an optimization, the actual widget is destroyed when the * sash is invisible. */ public: void SetVisible(bool visible); public: bool IsVisible(); /** * See LayoutPart#dispose */ public: void Dispose(); /** * Gets the presentation bounds. */ public: Rectangle GetBounds(); /** * Returns the part control. */ public: void* GetControl(); /** * */ public: std::string GetID(); protected: LayoutPartSash::Pointer GetPostLimit(); LayoutPartSash::Pointer GetPreLimit(); int GetLeft(); int GetRight(); bool IsHorizontal(); bool IsVertical(); void SetPostLimit(LayoutPartSash::Pointer newPostLimit); void SetPreLimit(LayoutPartSash::Pointer newPreLimit); void SetRatio(float newRatio); void SetSizes(int left, int right); private: void FlushCache(); private: void WidgetSelected(int x, int y, int width, int height); /** * @param resizable * @since 3.1 */ public: void SetEnabled(bool resizable); protected: /* package */int GetSashSize() const; }; } #endif /* BERRYLAYOUTPARTSASH_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutTree.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutTree.cpp index 1de8acfed6..ae6ce734fd 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutTree.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutTree.cpp @@ -1,482 +1,482 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryLayoutTree.h" #include "berryLayoutTreeNode.h" #include "berryLayoutPartSash.h" #include "berryContainerPlaceholder.h" -#include "../berryConstants.h" +#include "berryConstants.h" namespace berry { int LayoutTree::minCacheHits = 0; int LayoutTree::minCacheMisses = 0; int LayoutTree::maxCacheHits = 0; int LayoutTree::maxCacheMisses = 0; LayoutTree::LayoutTree(LayoutPart::Pointer part) : parent(0), cachedMinimumWidthHint(Constants::DEFAULT), cachedMinimumWidth(Constants::DEFAULT), cachedMinimumHeightHint(Constants::DEFAULT), cachedMinimumHeight(Constants::DEFAULT), cachedMaximumWidthHint(Constants::DEFAULT), cachedMaximumWidth(Constants::DEFAULT), cachedMaximumHeightHint(Constants::DEFAULT), cachedMaximumHeight(Constants::DEFAULT), forceLayout(true), sizeFlagsDirty(true), widthSizeFlags(0), heightSizeFlags(0) { this->part = part; } LayoutPart::Pointer LayoutTree::ComputeRelation( std::list& /*relations*/) { return part; } LayoutPart::Pointer LayoutTree::FindPart(const Point& /*toFind*/) { return part; } void LayoutTree::DisposeSashes() { } LayoutTree::Pointer LayoutTree::Find(LayoutPart::Pointer child) { if (part != child) { return LayoutTree::Pointer(0); } return LayoutTree::Pointer(this); } void LayoutTree::FindSashes(PartPane::Sashes sashes) { if (this->GetParent() == 0) { return; } this->GetParent()->FindSashes(LayoutTree::Pointer(this), sashes); } LayoutPart::Pointer LayoutTree::FindBottomRight() { return part; } LayoutTreeNode::Pointer LayoutTree::FindSash(LayoutPartSash::Pointer /*sash*/) { return LayoutTreeNode::Pointer(0); } Rectangle LayoutTree::GetBounds() { return currentBounds; } int LayoutTree::Subtract(int a, int b) { poco_assert(b >= 0 && b < INF); return Add(a, -b); } int LayoutTree::Add(int a, int b) { if (a == INF || b == INF) { return INF; } return a + b; } void LayoutTree::AssertValidSize(int toCheck) { poco_assert(toCheck >= 0 && (toCheck == INF || toCheck < INF / 2)); } int LayoutTree::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { this->AssertValidSize(availableParallel); this->AssertValidSize(availablePerpendicular); this->AssertValidSize(preferredParallel); if (!this->IsVisible()) { return 0; } if (availableParallel == 0) { return 0; } if (preferredParallel == 0) { return std::min(availableParallel, this->ComputeMinimumSize(width, availablePerpendicular)); } else if (preferredParallel == INF && availableParallel == INF) { return this->ComputeMaximumSize(width, availablePerpendicular); } // Optimization: if this subtree doesn't have any size preferences beyond its minimum and maximum // size, simply return the preferred size if (!this->HasSizeFlag(width, Constants::FILL)) { return preferredParallel; } int result = this->DoComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); return result; } int LayoutTree::DoGetSizeFlags(bool width) { return part->GetSizeFlags(width); } int LayoutTree::DoComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { int result = std::min(availableParallel, part->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel)); this->AssertValidSize(result); return result; } int LayoutTree::ComputeMinimumSize(bool width, int availablePerpendicular) { this->AssertValidSize(availablePerpendicular); // Optimization: if this subtree has no minimum size, then always return 0 as its // minimum size. if (!this->HasSizeFlag(width, Constants::MIN)) { return 0; } // If this subtree doesn't contain any wrapping controls (ie: they don't care // about their perpendicular size) then force the perpendicular // size to be INF. This ensures that we will get a cache hit // every time for non-wrapping controls. if (!this->HasSizeFlag(width, Constants::WRAP)) { availablePerpendicular = INF; } if (width) { // Check if we have a cached width measurement (we can only return a cached // value if we computed it for the same height) if (cachedMinimumWidthHint == availablePerpendicular) { minCacheHits++; return cachedMinimumWidth; } // Recompute the minimum width and store it in the cache minCacheMisses++; int result = this->DoComputeMinimumSize(width, availablePerpendicular); cachedMinimumWidth = result; cachedMinimumWidthHint = availablePerpendicular; return result; } else { // Check if we have a cached height measurement (we can only return a cached // value if we computed it for the same width) if (cachedMinimumHeightHint == availablePerpendicular) { minCacheHits++; return cachedMinimumHeight; } // Recompute the minimum width and store it in the cache minCacheMisses++; int result = this->DoComputeMinimumSize(width, availablePerpendicular); cachedMinimumHeight = result; cachedMinimumHeightHint = availablePerpendicular; return result; } } void LayoutTree::PrintCacheStatistics() { BERRY_INFO << "minimize cache " << minCacheHits << " / " << (minCacheHits + minCacheMisses) << " hits " << (minCacheHits * 100 / (minCacheHits + minCacheMisses)) << "%\n"; BERRY_INFO << "maximize cache " << maxCacheHits << " / " << (maxCacheHits + maxCacheMisses) << " hits" << (maxCacheHits * 100 / (maxCacheHits + maxCacheMisses)) << "%\n"; } int LayoutTree::DoComputeMinimumSize(bool width, int availablePerpendicular) { int result = this->DoComputePreferredSize(width, INF, availablePerpendicular, 0); this->AssertValidSize(result); return result; } int LayoutTree::ComputeMaximumSize(bool width, int availablePerpendicular) { this->AssertValidSize(availablePerpendicular); // Optimization: if this subtree has no maximum size, then always return INF as its // maximum size. if (!this->HasSizeFlag(width, Constants::MAX)) { return INF; } // If this subtree doesn't contain any wrapping controls (ie: they don't care // about their perpendicular size) then force the perpendicular // size to be INF. This ensures that we will get a cache hit // every time. if (!this->HasSizeFlag(width, Constants::WRAP)) { availablePerpendicular = INF; } if (width) { // Check if we have a cached width measurement (we can only return a cached // value if we computed it for the same height) if (cachedMaximumWidthHint == availablePerpendicular) { maxCacheHits++; return cachedMaximumWidth; } maxCacheMisses++; // Recompute the maximum width and store it in the cache int result = this->DoComputeMaximumSize(width, availablePerpendicular); cachedMaximumWidth = result; cachedMaximumWidthHint = availablePerpendicular; return result; } else { // Check if we have a cached height measurement if (cachedMaximumHeightHint == availablePerpendicular) { maxCacheHits++; return cachedMaximumHeight; } maxCacheMisses++; // Recompute the maximum height and store it in the cache int result = this->DoComputeMaximumSize(width, availablePerpendicular); cachedMaximumHeight = result; cachedMaximumHeightHint = availablePerpendicular; return result; } } int LayoutTree::DoComputeMaximumSize(bool width, int availablePerpendicular) { return this->DoComputePreferredSize(width, INF, availablePerpendicular, INF); } void LayoutTree::FlushNode() { // Clear cached sizes cachedMinimumWidthHint = Constants::DEFAULT; cachedMinimumWidth = Constants::DEFAULT; cachedMinimumHeightHint = Constants::DEFAULT; cachedMinimumHeight = Constants::DEFAULT; cachedMaximumWidthHint = Constants::DEFAULT; cachedMaximumWidth = Constants::DEFAULT; cachedMaximumHeightHint = Constants::DEFAULT; cachedMaximumHeight = Constants::DEFAULT; // Flags may have changed. Ensure that they are recomputed the next time around sizeFlagsDirty = true; // The next setBounds call should trigger a layout even if set to the same bounds since // one of the children has changed. forceLayout = true; } void LayoutTree::FlushChildren() { this->FlushNode(); } void LayoutTree::FlushCache() { this->FlushNode(); if (parent != 0) { parent->FlushCache(); } } int LayoutTree::GetSizeFlags(bool width) { if (sizeFlagsDirty) { widthSizeFlags = this->DoGetSizeFlags(true); heightSizeFlags = this->DoGetSizeFlags(false); sizeFlagsDirty = false; } return width ? widthSizeFlags : heightSizeFlags; } LayoutTreeNode* LayoutTree::GetParent() const { return parent; } LayoutTree::Pointer LayoutTree::Insert(LayoutPart::Pointer child, bool left, LayoutPartSash::Pointer sash, LayoutPart::Pointer relative) { LayoutTree::Pointer relativeChild = this->Find(relative); LayoutTreeNode::Pointer node(new LayoutTreeNode(sash)); if (relativeChild == 0) { //Did not find the relative part. Insert beside the root. node->SetChild(left, child); node->SetChild(!left, LayoutTree::Pointer(this)); return node; } else { LayoutTreeNode* oldParent = relativeChild->GetParent(); node->SetChild(left, child); node->SetChild(!left, relativeChild); if (oldParent == 0) { //It was the root. Return a new root. return node; } oldParent->ReplaceChild(relativeChild, node); return LayoutTree::Pointer(this); } } bool LayoutTree::IsCompressible() { //Added for bug 19524 return part->IsCompressible(); } bool LayoutTree::IsVisible() { return part.Cast().IsNull(); } void LayoutTree::RecomputeRatio() { } LayoutTree::Pointer LayoutTree::Remove(LayoutPart::Pointer child) { LayoutTree::Pointer tree = this->Find(child); if (tree == 0) { return LayoutTree::Pointer(this); } LayoutTreeNode::Pointer oldParent(tree->GetParent()); if (oldParent == 0) { //It was the root and the only child of this tree return LayoutTree::Pointer(0); } if (oldParent->GetParent() == 0) { return oldParent->Remove(tree); } oldParent->Remove(tree); return LayoutTree::Pointer(this); } void LayoutTree::SetBounds(const Rectangle& bounds) { if (!(bounds == currentBounds) || forceLayout) { currentBounds = bounds; this->DoSetBounds(currentBounds); forceLayout = false; } } void LayoutTree::DoSetBounds(const Rectangle& bounds) { part->SetBounds(bounds); } void LayoutTree::SetParent(LayoutTreeNode* parent) { this->parent = parent; } void LayoutTree::SetPart(LayoutPart::Pointer part) { this->part = part; this->FlushCache(); } std::string LayoutTree::ToString() { return "(" + part->ToString() + ")";//$NON-NLS-2$//$NON-NLS-1$ } void LayoutTree::CreateControl(void* /*parent*/) { } void LayoutTree::DescribeLayout(std::string& buf) const { part->DescribeLayout(buf); } bool LayoutTree::HasSizeFlag(bool width, int flag) { return (this->GetSizeFlags(width) & flag) != 0; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutTree.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutTree.h index 59f862eba4..f83e1e2481 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutTree.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutTree.h @@ -1,374 +1,374 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYLAYOUTTREE_H_ #define BERRYLAYOUTTREE_H_ -#include "../berryISizeProvider.h" -#include "../berryRectangle.h" -#include "../berryPoint.h" +#include "berryISizeProvider.h" +#include "berryRectangle.h" +#include "berryPoint.h" #include "berryPartSashContainer.h" #include namespace berry { class LayoutTreeNode; class LayoutPartSash; /** * \ingroup org_blueberry_ui_internal * * Implementation of a tree where the node is allways a sash * and it allways has two chidren. If a children is removed * the sash, ie the node, is removed as well and its other children * placed on its parent. */ class LayoutTree : public Object, public ISizeProvider { //implements ISizeProvider { public: berryObjectMacro(LayoutTree); /* The parent of this tree or null if it is the root */ LayoutTreeNode* parent; /* Any LayoutPart if this is a leaf or a LayoutSashPart if it is a node */ LayoutPart::Pointer part; private: // Cached information int cachedMinimumWidthHint; int cachedMinimumWidth; int cachedMinimumHeightHint; int cachedMinimumHeight; int cachedMaximumWidthHint; int cachedMaximumWidth; int cachedMaximumHeightHint; int cachedMaximumHeight; bool forceLayout; Rectangle currentBounds; // Cached size flags bool sizeFlagsDirty; int widthSizeFlags; int heightSizeFlags; public: // Cache statistics. For use in benchmarks and test suites only! static int minCacheHits; static int minCacheMisses; static int maxCacheHits; static int maxCacheMisses; /** * Initialize this tree with its part. */ LayoutTree(LayoutPart::Pointer part); /** * Add the relation ship between the children in the list * and returns the left children. */ virtual LayoutPart::Pointer ComputeRelation( std::list& relations); /** * Locates the part that intersects the given point * * @param toFind * @return */ virtual LayoutPart::Pointer FindPart(const Point& toFind); /** * Dispose all Sashs in this tree */ virtual void DisposeSashes(); /** * Find a LayoutPart in the tree and return its sub-tree. Returns * null if the child is not found. */ virtual SmartPointer Find(LayoutPart::Pointer child); /** * Find the Left,Right,Top and Bottom * sashes around this tree and set them * in sashes */ virtual void FindSashes(PartPane::Sashes sashes); /** * Find the part that is in the bottom right position. */ virtual LayoutPart::Pointer FindBottomRight(); /** * Find a sash in the tree and return its sub-tree. Returns * null if the sash is not found. */ virtual SmartPointer FindSash(SmartPointer sash); /** * Return the bounds of this tree which is the rectangle that * contains all Controls in this tree. */ Rectangle GetBounds(); /** * Subtracts two integers. If a is INF, this is treated as * positive infinity. * * @param a a positive integer or INF indicating positive infinity * @param b a positive integer (may not be INF) * @return a - b, or INF if a == INF * @since 3.1 */ static int Subtract(int a, int b); /** * Adds two positive integers. Treates INF as positive infinity. * * @param a a positive integer * @param b a positive integer * @return a + b, or INF if a or b are positive infinity * @since 3.1 */ static int Add(int a, int b); /** * Asserts that toCheck is a positive integer less than INF / 2 or equal * to INF. Many of the methods of this class use positive integers as sizes, * with INF indicating positive infinity. This picks up accidental addition or * subtraction from infinity. * * @param toCheck integer to validate * @since 3.1 */ static void AssertValidSize(int toCheck); /** * Computes the preferred size for this object. The interpretation of the result depends on the flags returned * by getSizeFlags(). If the caller is looking for a maximum or minimum size, this delegates to computeMinimumSize * or computeMaximumSize in order to benefit from caching optimizations. Otherwise, it delegates to * doComputePreferredSize. Subclasses should overload one of doComputeMinimumSize, doComputeMaximumSize, or * doComputePreferredSize to specialize the return value. * * @see LayoutPart#computePreferredSize(boolean, int, int, int) */ int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); protected: /** * Returns the size flags for this tree. * * @see org.blueberry.ui.presentations.StackPresentation#getSizeFlags(boolean) * * @param b indicates whether the caller wants the flags for computing widths (=true) or heights (=false) * @return a bitwise combiniation of flags with the same meaning as StackPresentation.getSizeFlags(boolean) */ virtual int DoGetSizeFlags(bool width); /** * Subclasses should overload this method instead of computePreferredSize(boolean, int, int, int) * * @see org.blueberry.ui.presentations.StackPresentation#computePreferredSize(boolean, int, int, int) * * @since 3.1 */ virtual int DoComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); public: /** * Returns the minimum size for this subtree. Equivalent to calling * computePreferredSize(width, INF, availablePerpendicular, 0). * Returns a cached value if possible or defers to doComputeMinimumSize otherwise. * Subclasses should overload doComputeMinimumSize if they want to specialize the * return value. * * @param width true iff computing the minimum width, false iff computing the minimum height * @param availablePerpendicular available space (pixels) perpendicular to the dimension * being computed. This is a height when computing a width, or a width when computing a height. * * @see LayoutPart#computePreferredSize(boolean, int, int, int) */ int ComputeMinimumSize(bool width, int availablePerpendicular); /** * For use in benchmarks and test suites only. Displays cache utilization statistics for all * LayoutTree instances. * * @since 3.1 */ static void PrintCacheStatistics(); virtual int DoComputeMinimumSize(bool width, int availablePerpendicular); int ComputeMaximumSize(bool width, int availablePerpendicular); protected: virtual int DoComputeMaximumSize(bool width, int availablePerpendicular); public: /** * Called to flush any cached information in this tree and its parents. */ virtual void FlushNode(); /** * Flushes all cached information about this node and all of its children. * This should be called if something may have caused all children to become * out of synch with their cached information (for example, if a lot of changes * may have happened without calling flushCache after each change) * * @since 3.1 */ virtual void FlushChildren(); /** * Flushes all cached information about this node and all of its ancestors. * This should be called when a single child changes. * * @since 3.1 */ void FlushCache(); int GetSizeFlags(bool width); /** * Returns the parent of this tree or null if it is the root. */ virtual LayoutTreeNode* GetParent() const; /** * Inserts a new child on the tree. The child will be placed beside * the relative child. Returns the new root of the tree. */ virtual SmartPointer Insert(LayoutPart::Pointer child, bool left, SmartPointer sash, SmartPointer relative); /** * Returns true if this tree can be compressed and expanded. * @return true if springy */ virtual bool IsCompressible(); /** * Returns true if this tree has visible parts otherwise returns false. */ virtual bool IsVisible(); /** * Recompute the ratios in this tree. */ virtual void RecomputeRatio(); /** * Find a child in the tree and remove it and its parent. * The other child of its parent is placed on the parent's parent. * Returns the new root of the tree. */ virtual SmartPointer Remove(LayoutPart::Pointer child); /** * Sets the bounds of this node. If the bounds have changed or any children have * changed then the children will be recursively layed out. This implementation * filters out redundant calls and delegates to doSetBounds to layout the children. * Subclasses should overload doSetBounds to lay out their children. * * @param bounds new bounds of the tree */ void SetBounds(const Rectangle& bounds); protected: /** * Resize the parts on this tree to fit in bounds. */ virtual void DoSetBounds(const Rectangle& bounds); public: /** * Set the parent of this tree. */ virtual void SetParent(LayoutTreeNode* parent); /** * Set the part of this leaf */ virtual void SetPart(LayoutPart::Pointer part); /** * Returns a string representation of this object. */ virtual std::string ToString(); /** * Creates SWT controls owned by the LayoutTree (ie: the sashes). Does not affect the * LayoutParts that are being arranged by the LayoutTree. * * @param parent * @since 3.1 */ virtual void CreateControl(void* parent); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they should not be translated or equality tests will fail. *

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

* * @param buf */ virtual void DescribeLayout(std::string& buf) const; /** * This is a shorthand method that checks if the tree contains the * given size flag. For example, hasSizeFlag(false, SWT.MIN) returns * true iff the receiver enforces a minimum height, or * hasSizeFlag(true, SWT.WRAP) returns true iff the receiver needs to * know its height when computing its preferred width. * * @param vertical * @return * @since 3.1 */ bool HasSizeFlag(bool width, int flag); }; } #endif /*BERRYLAYOUTTREE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutTreeNode.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutTreeNode.cpp index be563caa13..0ea77a6649 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutTreeNode.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryLayoutTreeNode.cpp @@ -1,718 +1,718 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryLayoutTreeNode.h" -#include "../berryConstants.h" -#include "../berryIPageLayout.h" +#include "berryConstants.h" +#include "berryIPageLayout.h" #include namespace berry { LayoutTreeNode::ChildSizes::ChildSizes (int l, int r, bool resize) { left = l; right = r; resizable = resize; } LayoutTreeNode::LayoutTreeNode(LayoutPartSash::Pointer sash) : LayoutTree(sash) { children[0] = 0; children[1] = 0; } LayoutTreeNode::~LayoutTreeNode() { } void LayoutTreeNode::FlushChildren() { LayoutTree::FlushChildren(); children[0]->FlushChildren(); children[1]->FlushChildren(); } LayoutPart::Pointer LayoutTreeNode::FindPart(const Point& toFind) { if (!children[0]->IsVisible()) { if (!children[1]->IsVisible()) { return LayoutPart::Pointer(0); } return children[1]->FindPart(toFind); } else { if (!children[1]->IsVisible()) { return children[0]->FindPart(toFind); } } LayoutPartSash::Pointer sash = this->GetSash(); Rectangle bounds = sash->GetBounds(); if (sash->IsVertical()) { if (toFind.x < bounds.x + (bounds.width / 2)) { return children[0]->FindPart(toFind); } return children[1]->FindPart(toFind); } else { if (toFind.y < bounds.y + (bounds.height / 2)) { return children[0]->FindPart(toFind); } return children[1]->FindPart(toFind); } } LayoutPart::Pointer LayoutTreeNode::ComputeRelation( std::list& relations) { PartSashContainer::RelationshipInfo r = PartSashContainer::RelationshipInfo(); r.relative = children[0]->ComputeRelation(relations); r.part = children[1]->ComputeRelation(relations); r.left = this->GetSash()->GetLeft(); r.right = this->GetSash()->GetRight(); r.relationship = this->GetSash()->IsVertical() ? IPageLayout::RIGHT : IPageLayout::BOTTOM; relations.push_front(r); return r.relative; } void LayoutTreeNode::DisposeSashes() { children[0]->DisposeSashes(); children[1]->DisposeSashes(); this->GetSash()->Dispose(); } LayoutTree::Pointer LayoutTreeNode::Find(LayoutPart::Pointer child) { LayoutTree::Pointer node = children[0]->Find(child); if (node != 0) { return node; } node = children[1]->Find(child); return node; } LayoutPart::Pointer LayoutTreeNode::FindBottomRight() { if (children[1]->IsVisible()) { return children[1]->FindBottomRight(); } return children[0]->FindBottomRight(); } LayoutTreeNode* LayoutTreeNode::FindCommonParent(LayoutPart::Pointer child1, LayoutPart::Pointer child2, bool foundChild1, bool foundChild2) { if (!foundChild1) { foundChild1 = this->Find(child1) != 0; } if (!foundChild2) { foundChild2 = this->Find(child2) != 0; } if (foundChild1 && foundChild2) { return this; } if (parent == 0) { return 0; } return parent ->FindCommonParent(child1, child2, foundChild1, foundChild2); } LayoutTreeNode::Pointer LayoutTreeNode::FindSash(LayoutPartSash::Pointer sash) { if (this->GetSash() == sash) { return LayoutTreeNode::Pointer(this); } LayoutTreeNode::Pointer node = children[0]->FindSash(sash); if (node != 0) { return node; } node = children[1]->FindSash(sash); if (node != 0) { return node; } return LayoutTreeNode::Pointer(0); } void LayoutTreeNode::FindSashes(LayoutTree::Pointer child, PartPane::Sashes sashes) { void* sash = this->GetSash()->GetControl(); bool leftOrTop = children[0] == child; if (sash != 0) { LayoutPartSash::Pointer partSash = this->GetSash(); //If the child is in the left, the sash //is in the rigth and so on. if (leftOrTop) { if (partSash->IsVertical()) { if (sashes.right == 0) { sashes.right = sash; } } else { if (sashes.bottom == 0) { sashes.bottom = sash; } } } else { if (partSash->IsVertical()) { if (sashes.left == 0) { sashes.left = sash; } } else { if (sashes.top == 0) { sashes.top = sash; } } } } if (this->GetParent() != 0) { this->GetParent()->FindSashes(LayoutTree::Pointer(this), sashes); } } LayoutPartSash::Pointer LayoutTreeNode::GetSash() const { return part.Cast(); } int LayoutTreeNode::GetSashSize() const { return this->GetSash()->GetSashSize(); } bool LayoutTreeNode::IsVisible() { return children[0]->IsVisible() || children[1]->IsVisible(); } LayoutTree::Pointer LayoutTreeNode::Remove(LayoutTree::Pointer child) { this->GetSash()->Dispose(); if (parent == 0) { //This is the root. Return the other child to be the new root. if (children[0] == child) { children[1]->SetParent(0); return children[1]; } children[0]->SetParent(0); return children[0]; } LayoutTreeNode::Pointer oldParent(parent); if (children[0] == child) { oldParent->ReplaceChild(LayoutTree::Pointer(this), children[1]); } else { oldParent->ReplaceChild(LayoutTree::Pointer(this), children[0]); } return oldParent; } void LayoutTreeNode::ReplaceChild(LayoutTree::Pointer oldChild, LayoutTree::Pointer newChild) { if (children[0] == oldChild) { children[0] = newChild; } else if (children[1] == oldChild) { children[1] = newChild; } newChild->SetParent(this); if (!children[0]->IsVisible() || !children[0]->IsVisible()) { this->GetSash()->Dispose(); } this->FlushCache(); } bool LayoutTreeNode::SameDirection(bool isVertical, LayoutTreeNode::Pointer subTree) { bool treeVertical = this->GetSash()->IsVertical(); if (treeVertical != isVertical) { return false; } while (subTree != 0) { if (this == subTree.GetPointer()) { return true; } if (subTree->children[0]->IsVisible() && subTree->children[1]->IsVisible()) { if (subTree->GetSash()->IsVertical() != isVertical) { return false; } } subTree = subTree->GetParent(); } return true; } int LayoutTreeNode::DoComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { this->AssertValidSize(availablePerpendicular); this->AssertValidSize(availableParallel); this->AssertValidSize(preferredParallel); // If one child is invisible, defer to the other child if (!children[0]->IsVisible()) { return children[1]->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } if (!children[1]->IsVisible()) { return children[0]->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } if (availableParallel == 0) { return 0; } // If computing the dimension perpendicular to our sash if (width == this->GetSash()->IsVertical()) { // Compute the child sizes ChildSizes sizes = this->ComputeChildSizes(availableParallel, availablePerpendicular, GetSash()->GetLeft(), GetSash()->GetRight(), preferredParallel); // Return the sum of the child sizes plus the sash size return this->Add(sizes.left, this->Add(sizes.right, this->GetSashSize())); } else { // Computing the dimension parallel to the sash. We will compute and return the preferred size // of whichever child is closest to the ideal size. // First compute the dimension of the child sizes perpendicular to the sash ChildSizes sizes = this->ComputeChildSizes(availablePerpendicular, availableParallel, GetSash()->GetLeft(), GetSash()->GetRight(), availablePerpendicular); // Use this information to compute the dimension of the child sizes parallel to the sash. // Return the preferred size of whichever child is largest int leftSize = children[0]->ComputePreferredSize(width, availableParallel, sizes.left, preferredParallel); // Compute the preferred size of the right child int rightSize = children[1]->ComputePreferredSize(width, availableParallel, sizes.right, preferredParallel); // Return leftSize or rightSize: whichever one is largest int result = rightSize; if (leftSize > rightSize) { result = leftSize; } this->AssertValidSize(result); return result; } } LayoutTreeNode::ChildSizes LayoutTreeNode::ComputeChildSizes(int width, int height, int left, int right, int preferredWidth) { poco_assert(children[0]->IsVisible()); poco_assert(children[1]->IsVisible()); this->AssertValidSize(width); this->AssertValidSize(height); this->AssertValidSize(preferredWidth); poco_assert(left >= 0); poco_assert(right >= 0); poco_assert(preferredWidth >= 0); poco_assert(preferredWidth <= width); bool vertical = this->GetSash()->IsVertical(); if (width <= this->GetSashSize()) { return ChildSizes(0,0, false); } if (width == INF) { if (preferredWidth == INF) { return ChildSizes(children[0]->ComputeMaximumSize(vertical, height), children[1]->ComputeMaximumSize(vertical, height), false); } if (preferredWidth == 0) { return ChildSizes(children[0]->ComputeMinimumSize(vertical, height), children[1]->ComputeMinimumSize(vertical, height), false); } } int total = left + right; // Use all-or-none weighting double wLeft = left, wRight = right; switch (this->GetCompressionBias()) { case -1: wLeft = 0.0; break; case 1: wRight = 0.0; break; default: break; } double wTotal = wLeft + wRight; // Subtract the SASH_WIDTH from preferredWidth and width. From here on, we'll deal with the // width available to the controls and neglect the space used by the sash. preferredWidth = std::max(0, this->Subtract(preferredWidth, this->GetSashSize())); width = std::max(0, this->Subtract(width, this->GetSashSize())); int redistribute = this->Subtract(preferredWidth, total); // Compute the minimum and maximum sizes for each child int leftMinimum = children[0]->ComputeMinimumSize(vertical, height); int rightMinimum = children[1]->ComputeMinimumSize(vertical, height); int leftMaximum = children[0]->ComputeMaximumSize(vertical, height); int rightMaximum = children[1]->ComputeMaximumSize(vertical, height); int idealLeft = 0; int idealRight = 0; if (PartSashContainer::leftToRight) { // Keep track of the available space for each child, given the minimum size of the other child int leftAvailable = std::min(leftMaximum, std::max(0, this->Subtract(width, rightMinimum))); int rightAvailable = std::min(rightMaximum, std::max(0, this->Subtract(width, leftMinimum))); // Figure out the ideal size of the left child idealLeft = std::max(leftMinimum, std::min(preferredWidth, left + (int)(redistribute * wLeft / wTotal))); // If the right child can't use all its available space, let the left child fill it in idealLeft = std::max(idealLeft, preferredWidth - rightAvailable); // Ensure the left child doesn't get larger than its available space idealLeft = std::min(idealLeft, leftAvailable); // Check if the left child would prefer to be a different size idealLeft = children[0]->ComputePreferredSize(vertical, leftAvailable, height, idealLeft); // Ensure that the left child is larger than its minimum size idealLeft = std::max(idealLeft, leftMinimum); idealLeft = std::min(idealLeft, leftAvailable); // Compute the right child width idealRight = std::max(rightMinimum, preferredWidth - idealLeft); rightAvailable = std::max(0, std::min(rightAvailable, this->Subtract(width, idealLeft))); idealRight = std::min(idealRight, rightAvailable); idealRight = children[1]->ComputePreferredSize(vertical, rightAvailable, height, idealRight); idealRight = std::max(idealRight, rightMinimum); } else { // Keep track of the available space for each child, given the minimum size of the other child int rightAvailable = std::min(rightMaximum, std::max(0, this->Subtract(width, leftMinimum))); int leftAvailable = std::min(leftMaximum, std::max(0, this->Subtract(width, rightMinimum))); // Figure out the ideal size of the right child idealRight = std::max(rightMinimum, std::min(preferredWidth, right + (int)(redistribute * wRight / wTotal))); // If the left child can't use all its available space, let the right child fill it in idealRight = std::max(idealRight, preferredWidth - leftAvailable); // Ensure the right child doesn't get larger than its available space idealRight = std::min(idealRight, rightAvailable); // Check if the right child would prefer to be a different size idealRight = children[1]->ComputePreferredSize(vertical, rightAvailable, height, idealRight); // Ensure that the right child is larger than its minimum size idealRight = std::max(idealRight, rightMinimum); idealRight = std::min(idealRight, rightAvailable); // Compute the left child width idealLeft = std::max(leftMinimum, preferredWidth - idealRight); leftAvailable = std::max(0, std::min(leftAvailable, this->Subtract(width, idealRight))); idealLeft = std::min(idealLeft, leftAvailable); idealLeft = children[0]->ComputePreferredSize(vertical, leftAvailable, height, idealLeft); idealLeft = std::max(idealLeft, leftMinimum); } return ChildSizes(idealLeft, idealRight, leftMaximum> leftMinimum && rightMaximum> rightMinimum && leftMinimum + rightMinimum < width); } int LayoutTreeNode::DoGetSizeFlags(bool width) { if (!children[0]->IsVisible()) { return children[1]->GetSizeFlags(width); } if (!children[1]->IsVisible()) { return children[0]->GetSizeFlags(width); } int leftFlags = children[0]->GetSizeFlags(width); int rightFlags = children[1]->GetSizeFlags(width); return ((leftFlags | rightFlags) & ~Constants::MAX) | (leftFlags & rightFlags & Constants::MAX); } void LayoutTreeNode::DoSetBounds(const Rectangle& b) { if (!children[0]->IsVisible()) { children[1]->SetBounds(b); this->GetSash()->SetVisible(false); return; } if (!children[1]->IsVisible()) { children[0]->SetBounds(b); this->GetSash()->SetVisible(false); return; } Rectangle bounds = b; bool vertical = this->GetSash()->IsVertical(); // If this is a horizontal sash, flip coordinate systems so // that we can eliminate special cases if (!vertical) { bounds.FlipXY(); } ChildSizes childSizes = this->ComputeChildSizes(bounds.width, bounds.height, this->GetSash()->GetLeft(), this->GetSash()->GetRight(), bounds.width); this->GetSash()->SetVisible(true); this->GetSash()->SetEnabled(childSizes.resizable); Rectangle leftBounds = Rectangle(bounds.x, bounds.y, childSizes.left, bounds.height); Rectangle sashBounds = Rectangle(leftBounds.x + leftBounds.width, bounds.y, this->GetSashSize(), bounds.height); Rectangle rightBounds = Rectangle(sashBounds.x + sashBounds.width, bounds.y, childSizes.right, bounds.height); if (!vertical) { leftBounds.FlipXY(); sashBounds.FlipXY(); rightBounds.FlipXY(); } this->GetSash()->SetBounds(sashBounds); children[0]->SetBounds(leftBounds); children[1]->SetBounds(rightBounds); } void LayoutTreeNode::CreateControl(void* parent) { children[0]->CreateControl(parent); children[1]->CreateControl(parent); this->GetSash()->CreateControl(parent); LayoutTree::CreateControl(parent); } bool LayoutTreeNode::IsCompressible() { return children[0]->IsCompressible() || children[1]->IsCompressible(); } int LayoutTreeNode::GetCompressionBias() { bool left = children[0]->IsCompressible(); bool right = children[1]->IsCompressible(); if (left == right) { return 0; } if (right) { return -1; } return 1; } bool LayoutTreeNode::IsLeftChild(LayoutTree::ConstPointer toTest) { return children[0] == toTest; } LayoutTree::Pointer LayoutTreeNode::GetChild(bool left) { int index = left ? 0 : 1; return (children[index]); } void LayoutTreeNode::SetChild(bool left, LayoutPart::Pointer part) { LayoutTree::Pointer child(new LayoutTree(part)); this->SetChild(left, child); this->FlushCache(); } void LayoutTreeNode::SetChild(bool left, LayoutTree::Pointer child) { int index = left ? 0 : 1; children[index] = child; child->SetParent(this); this->FlushCache(); } std::string LayoutTreeNode::ToString() { std::stringstream s; s << "\n"; if (part->GetControl() != 0) { s << "<@" << part->GetControl() << ">\n";//$NON-NLS-2$//$NON-NLS-1$ } std::stringstream result; result << "["; //$NON-NLS-1$ if (children[0]->GetParent() != this) { result << result.str() << "{" << children[0] << "}" << s.str();//$NON-NLS-2$//$NON-NLS-1$ } else { result << result.str() << children[0] << s.str(); } if (children[1]->GetParent() != this) { result << result.str() << "{" << children[1] << "}]";//$NON-NLS-2$//$NON-NLS-1$ } else { result << result.str() << children[1] << "]";//$NON-NLS-1$ } return result.str(); } //void LayoutTreeNode::UpdateSashes(void* parent) { // if (parent == 0) // return; // children[0]->UpdateSashes(parent); // children[1]->UpdateSashes(parent); // if (children[0]->IsVisible() && children[1]->IsVisible()) // this->GetSash()->CreateControl(parent); // else // this->GetSash()->Dispose(); // } void LayoutTreeNode::DescribeLayout(std::string& buf) const { if (!(children[0]->IsVisible())) { if (!children[1]->IsVisible()) { return; } children[1]->DescribeLayout(buf); return; } if (!children[1]->IsVisible()) { children[0]->DescribeLayout(buf); return; } buf.append("("); //$NON-NLS-1$ children[0]->DescribeLayout(buf); buf.append(this->GetSash()->IsVertical() ? "|" : "-"); //$NON-NLS-1$ //$NON-NLS-2$ children[1]->DescribeLayout(buf); buf.append(")"); //$NON-NLS-1$ } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryNullEditorInput.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryNullEditorInput.h index e83e09abd7..9bfa3cf44e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryNullEditorInput.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryNullEditorInput.h @@ -1,77 +1,77 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYNULLEDITORINPUT_H_ #define BERRYNULLEDITORINPUT_H_ -#include "../berryIEditorInput.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) 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() */ std::string GetName() const; /* (non-Javadoc) * @see org.blueberry.ui.IEditorInput#getToolTipText() */ std::string GetToolTipText() const; bool operator==(const Object* o) const; }; } #endif /*BERRYNULLEDITORINPUT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPageLayout.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPageLayout.cpp index d972ba2d96..4ff775e72d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPageLayout.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPageLayout.cpp @@ -1,690 +1,690 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #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" +#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. // StackablePart::Pointer newPart = this->CreateView(ID_EDITOR_AREA); // if (newPart == 0) // { // // this should never happen as long as newID is the editor ID. // return; // } // // this->SetFolderPart(ID_EDITOR_AREA, editorFolder.Cast()); // Add it to the layout. rootLayoutContainer->Add(editorFolder); } catch (PartInitException& e) { WorkbenchPlugin::Log(this->GetClassName(), "AddEditorArea()", e); //$NON-NLS-1$ } } ViewLayoutRec::Pointer PageLayout::GetViewLayoutRec(const std::string& 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::AddStack(IStackableContainer::Pointer newPart, const std::string& partId, int relationship, float ratio, const std::string& refId) { //this->SetRefPart(partId, newPart); this->SetFolderPart(partId, newPart); // If the referenced part is inside a folder, // then use the folder as the reference part. IStackableContainer::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.Cast(), this->GetPartSashConst(relationship), ratio, refPart.Cast()); } else if (refId == ID_EDITOR_AREA) { ratio = this->NormalizeRatio(ratio); rootLayoutContainer->Add(newPart.Cast(), this->GetPartSashConst(relationship), ratio, this->editorFolder.Cast()); } else { WorkbenchPlugin::Log("Reference part does not exist yet: " + refId); rootLayoutContainer->Add(newPart.Cast()); } } void PageLayout::AddPerspectiveShortcut(const std::string& id) { if (std::find(perspectiveShortcuts.begin(), perspectiveShortcuts.end(), id) == perspectiveShortcuts.end()) { perspectiveShortcuts.push_back(id); } } void PageLayout::AddPlaceholder(const std::string& viewId, int relationship, float ratio, const std::string& refId) { if (!this->CheckValidPlaceholderId(viewId)) { return; } // Create a folder. ContainerPlaceholder::Pointer folder(new ContainerPlaceholder(viewId)); folder->SetContainer(rootLayoutContainer); folder->SetRealContainer(PartStack::Pointer(new PartStack(rootLayoutContainer->page))); //folder->SetId(folderId); // Create the placeholder. PartPlaceholder::Pointer newPart(new PartPlaceholder(viewId)); folder->Add(newPart); this->AddStack(folder, viewId, relationship, ratio, refId); // force creation of the view layout rec this->GetViewLayoutRec(viewId, true); } bool PageLayout::CheckValidPlaceholderId(const std::string& 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 std::string 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 std::string& id) { if (std::find(showInPartIds.begin(), showInPartIds.end(), id) == showInPartIds.end()) { showInPartIds.push_back(id); } } void PageLayout::AddShowViewShortcut(const std::string& id) { if (std::find(showViewShortcuts.begin(), showViewShortcuts.end(), id) == showInPartIds.end()) { showViewShortcuts.push_back(id); } } void PageLayout::AddView(const std::string& viewId, int relationship, float ratio, const std::string& refId) { this->AddView(viewId, relationship, ratio, refId, false, false, true); } void PageLayout::AddView(const std::string& viewId, int relationship, float ratio, const std::string& refId, bool minimized) { this->AddView(viewId, relationship, ratio, refId, minimized, false, true); } void PageLayout::AddView(const std::string& viewId, int relationship, float ratio, const std::string& refId, bool /*minimized*/, bool standalone, bool showTitle) { if (this->CheckPartInLayout(viewId)) { return; } try { // Create the part. StackablePart::Pointer newPart = this->CreateView(viewId); if (newPart == 0) { this->AddPlaceholder(viewId, relationship, ratio, refId); //TODO ViewActivator for IIdentifier //LayoutHelper::AddViewActivator(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->AddStack(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 std::string& 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 std::string& folderId, int relationship, float ratio, const std::string& refId) { if (this->CheckPartInLayout(folderId)) { IStackableContainer::Pointer folder = this->GetFolderPart(folderId); return mapFolderToFolderLayout[folder].Cast(); } // Create the folder. PartStack::Pointer folder(new PartStack(rootLayoutContainer->page)); folder->SetID(folderId); this->AddStack(folder, folderId, relationship, ratio, refId); // Create a wrapper. FolderLayout::Pointer layout(new FolderLayout(PageLayout::Pointer(this), folder, viewFactory)); mapFolderToFolderLayout.insert(std::make_pair(folder, layout)); return layout; } IPlaceholderFolderLayout::Pointer PageLayout::CreatePlaceholderFolder( const std::string& folderId, int relationship, float ratio, const std::string& 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(IStackableContainer::Pointer(new PartStack(rootLayoutContainer->page))); folder->SetID(folderId); this->AddStack(folder, folderId, relationship, ratio, refId); // Create a wrapper. IPlaceholderFolderLayout::Pointer layout(new PlaceholderFolderLayout(PageLayout::Pointer(this), folder)); mapFolderToFolderLayout.insert(std::make_pair(folder, layout)); return layout; } StackablePart::Pointer PageLayout::CreateView(const std::string& 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; } std::string PageLayout::GetEditorArea() { return ID_EDITOR_AREA; } IStackableContainer::Pointer PageLayout::GetFolderPart(const std::string& viewId) { return mapIDtoFolder[viewId]; } int PageLayout::GetPartSashConst(int nRelationship) { return nRelationship; } std::vector PageLayout::GetPerspectiveShortcuts() { return perspectiveShortcuts; } StackablePart::Pointer PageLayout::GetRefPart(const std::string& partID) { return mapIDtoPart[partID]; } PartSashContainer::Pointer PageLayout::GetRootLayoutContainer() { return rootLayoutContainer; } std::vector PageLayout::GetShowInPartIds() { return showInPartIds; } std::vector 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 std::string& viewId, ContainerPlaceholder::Pointer container) { IStackableContainer::Pointer tabFolder = container->GetRealContainer(); mapIDtoFolder[viewId] = tabFolder; } void PageLayout::SetFolderPart(const std::string& viewId, PartStack::Pointer folder) { mapIDtoFolder[viewId] = folder.Cast(); } void PageLayout::SetFolderPart(const std::string& viewId, IStackableContainer::Pointer folder) { mapIDtoFolder[viewId] = folder; } void PageLayout::SetRefPart(const std::string& partID, StackablePart::Pointer part) { mapIDtoPart[partID] = part; } void PageLayout::StackPart(StackablePart::Pointer newPart, const std::string& viewId, const std::string& 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. // StackablePart::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 std::string& viewId, const std::string& refId) { if (this->CheckPartInLayout(viewId)) { return; } // Create the placeholder. PartPlaceholder::Pointer newPart(new PartPlaceholder(viewId)); StackablePart::Pointer refPart = this->GetRefPart(refId); if (refPart != 0) { newPart->SetContainer(refPart->GetContainer()); } this->StackPart(newPart, viewId, refId); } void PageLayout::StackView(const std::string& viewId, const std::string& refId) { if (this->CheckPartInLayout(viewId)) { return; } // Create the new part. try { StackablePart::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 std::string& viewId, bool showTitle, int relationship, float ratio, const std::string& 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 std::string& viewId, int relationship, float ratio, const std::string& refId, bool showTitle) { std::string 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(IStackableContainer::Pointer(new PartStack(rootLayoutContainer->page, true, appearance, 0))); folder->SetID(stackId); this->AddStack(folder, stackId, relationship, ratio, refId); // Create a wrapper. PlaceholderFolderLayout::Pointer placeHolder(new PlaceholderFolderLayout(PageLayout::Pointer(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 std::string& viewId) { ViewLayoutRec::Pointer rec = this->GetViewLayoutRec(viewId, true); if (rec == 0) { return IViewLayout::Pointer(0); } return IViewLayout::Pointer(new ViewLayout(PageLayout::Pointer(this), rec)); } std::map PageLayout::GetIDtoViewLayoutRecMap() { return mapIDtoViewLayoutRec; } void PageLayout::RemovePlaceholder(const std::string& id) { StackablePart::Pointer part = this->GetRefPart(id); if (part->IsPlaceHolder()) { IStackableContainer::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.erase(id); mapIDtoFolder.erase(id); mapIDtoViewLayoutRec.erase(id); } } IPlaceholderFolderLayout::Pointer PageLayout::GetFolderForView( const std::string& viewId) { if (mapIDtoFolder[viewId] == 0) return IPlaceholderFolderLayout::Pointer(0); IStackableContainer::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/src/internal/berryPageLayout.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPageLayout.h index f49908f878..f69b3c8224 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPageLayout.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPageLayout.h @@ -1,587 +1,587 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPAGELAYOUT_H_ #define BERRYPAGELAYOUT_H_ -#include "../berryIPageLayout.h" +#include "berryIPageLayout.h" #include "berryViewLayoutRec.h" #include "berryContainerPlaceholder.h" #include "berryViewSashContainer.h" #include "berryPartStack.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * * This factory is used to define the initial layout of a part sash container. *

* Design notes: The design of IPageLayout is a reflection of * three requirements: *

    *
  1. A mechanism is required to define the initial layout for a page.
  2. *
  3. The views and editors within a page will be persisted between * sessions.
  4. *
  5. The view and editor lifecycle for (1) and (2) should be identical.
  6. *
*

*

* In reflection of these requirements, the following strategy has been * implemented for layout definition. *

    *
  1. A view extension is added to the workbench registry for the view. * This extension defines the extension id and extension class.
  2. *
  3. A view is added to a page by invoking one of the add methods * in IPageLayout. The type of view is passed as an * extension id, rather than a handle. The page layout will map * the extension id to a view class, create an instance of the class, * and then add the view to the page.
  4. *
*

*/ class PageLayout : public IPageLayout { public: berryObjectMacro(PageLayout); private: //ArrayList actionSets = new ArrayList(3); IPerspectiveDescriptor::Pointer descriptor; LayoutPart::Pointer editorFolder; bool editorVisible; bool fixed; typedef std::map IDToFolderMap; IDToFolderMap mapIDtoFolder; typedef std::map IDToPartMap; IDToPartMap mapIDtoPart; typedef std::map IDToViewLayoutRecMap; IDToViewLayoutRecMap mapIDtoViewLayoutRec; typedef std::map FolderToFolderLayoutMap; FolderToFolderLayoutMap mapFolderToFolderLayout; std::vector perspectiveShortcuts; ViewSashContainer::Pointer rootLayoutContainer; std::vector showInPartIds; std::vector showViewShortcuts; ViewFactory* viewFactory; /** * Constructs a new PageLayout for other purposes. */ public: PageLayout(); /** * Constructs a new PageLayout for the normal case of creating a new * perspective. */ public: PageLayout(ViewSashContainer::Pointer container, ViewFactory* viewFactory, LayoutPart::Pointer editorFolder, IPerspectiveDescriptor::Pointer descriptor); /** * Adds the editor to a layout. */ private: void AddEditorArea(); /** * Adds an action set to the page. * * @param actionSetID Identifies the action set extension to use. It must * exist within the workbench registry. */ // public: void addActionSet(String actionSetID) { // if (!actionSets.contains(actionSetID)) { // actionSets.add(actionSetID); // } // } /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#addFastView(java.lang.String) */ // public: void addFastView(String id) { // addFastView(id, INVALID_RATIO); // } /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#addFastView(java.lang.String, float) */ // public: void addFastView(String id, float ratio) { // if (checkPartInLayout(id)) { // return; // } // if (id != null) { // try { // IViewDescriptor viewDescriptor = viewFactory.getViewRegistry() // .find(ViewFactory.extractPrimaryId(id)); // if (!WorkbenchActivityHelper.filterItem(viewDescriptor)) { // IViewReference ref = viewFactory.createView(ViewFactory // .extractPrimaryId(id), ViewFactory // .extractSecondaryId(id)); // fastViews.add(ref); // // // force creation of the view layout rec // ViewLayoutRec rec = getViewLayoutRec(id, true); // // // remember the ratio, if valid // if (ratio >= IPageLayout.RATIO_MIN // && ratio <= IPageLayout.RATIO_MAX) { // rec.fastViewWidthRatio = ratio; // } // } // } catch (PartInitException e) { // WorkbenchPlugin.log(getClass(), "addFastView", e); //$NON-NLS-1$ // } // } // } /** * Check to see if the partId represents a fast view's id. * * @param partId * The part's id. * @return true if the partId is a fast view id. */ // private: boolean isFastViewId(String partId) { // for (int i = 0; i < fastViews.size(); i++) { // IViewReference ref = (IViewReference) fastViews.get(i); // String secondaryId = ref.getSecondaryId(); // String refId = (secondaryId == null ? ref.getId() : ref.getId() // + ":" + secondaryId); //$NON-NLS-1$ // if (refId.equals(partId)) { // return true; // } // } // return false; // } /** * Returns the view layout record for the given view id, or null if not * found. If create is true, the record is created if it doesn't already * exist. * * @since 3.0 */ public: ViewLayoutRec::Pointer GetViewLayoutRec(const std::string& id, bool create); /** * Adds a creation wizard to the File New menu. * The id must name a new wizard extension contributed to the * workbench's extension point (named "org.blueberry.ui.newWizards"). * * @param id the wizard id */ // public: void addNewWizardShortcut(String id) { // if (!newWizardShortcuts.contains(id)) { // newWizardShortcuts.add(id); // } // } /** * Add the layout part to the page's layout */ private: void AddStack(IStackableContainer::Pointer newPart, const std::string& partId, int relationship, float ratio, const std::string& refId); /** * Adds a perspective shortcut to the Perspective menu. * The id must name a perspective extension contributed to the * workbench's extension point (named "org.blueberry.ui.perspectives"). * * @param id the perspective id */ public: void AddPerspectiveShortcut(const std::string& id); /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#addPlaceholder(java.lang.String, int, float, java.lang.String) */ public: void AddPlaceholder(const std::string& viewId, int relationship, float ratio, const std::string& refId); /** * Checks whether the given id is a valid placeholder id. * A placeholder id may be simple or compound, and can optionally contain a wildcard. * * @param id the placeholder id * @return true if the given id is a valid placeholder id, false otherwise */ bool CheckValidPlaceholderId(const std::string& id); /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#addShowInPart(java.lang.String) */ public: void AddShowInPart(const std::string& id); /** * Adds a view to the Show View menu. The id must name a view extension * contributed to the workbench's extension point (named "org.blueberry.ui.views"). * * @param id the view id */ public: void AddShowViewShortcut(const std::string& id); /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#addView(java.lang.String, int, float, java.lang.String) */ public: void AddView(const std::string& viewId, int relationship, float ratio, const std::string& refId); /** * Convenience method to allow setting the initial minimized * state if a new stack is created. Used by the 'perspectiveExtension' * reader. * * @since 3.3 */ public: void AddView(const std::string& viewId, int relationship, float ratio, const std::string& refId, bool minimized); /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#addView(java.lang.String, int, float, java.lang.String) */ private: void AddView(const std::string& viewId, int relationship, float ratio, const std::string& refId, bool minimized, bool standalone, bool showTitle); // public: List getMinimizedStacks() { // return minimizedStacks; // } /** * Verify that the part is already present in the layout * and cannot be added again. Log a warning message. */ public: bool CheckPartInLayout(const std::string& partId); /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#createFolder(java.lang.String, int, float, java.lang.String) */ public: IFolderLayout::Pointer CreateFolder(const std::string& folderId, int relationship, float ratio, const std::string& refId); /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#createPlaceholderFolder(java.lang.String, int, float, java.lang.String) */ public: IPlaceholderFolderLayout::Pointer CreatePlaceholderFolder( const std::string& folderId, int relationship, float ratio, const std::string& refId); /** * Create a new LayoutPart. * * @param partID the id of the part to create. * @return the LayoutPart, or null if it should not be * created because of activity filtering. * @throws PartInitException thrown if there is a problem creating the part. */ private: StackablePart::Pointer CreateView(const std::string& partID); /** * @return the action set list for the page. This is List of * Strings. */ // public: ArrayList getActionSets() { // return actionSets; // } /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#getDescriptor() */ public: IPerspectiveDescriptor::Pointer GetDescriptor(); /** * @return an identifier for the editor area. The editor area is * automatically added to each layout before any other part. It should be * used as a reference part for other views. */ public: std::string GetEditorArea(); /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#getEditorReuseThreshold() */ // public: int getEditorReuseThreshold() { // return -1; // } /** * @return ArrayList */ // public: ArrayList getFastViews() { // return fastViews; // } /** * @return the folder part containing the given view ID or null * if none (i.e. part of the page layout instead of a folder layout). */ private: IStackableContainer::Pointer GetFolderPart(const std::string& viewId); /** * @return the new wizard shortcuts associated with the page. This is a List of * Strings. */ // public: ArrayList getNewWizardShortcuts() { // return newWizardShortcuts; // } /** * @return the part sash container const for a layout value. */ private: int GetPartSashConst(int nRelationship); /** * @return the perspective shortcuts associated with the page. This is a List of * Strings. */ public: std::vector GetPerspectiveShortcuts(); /** * @return the part for a given ID. */ /*package*/ StackablePart::Pointer GetRefPart(const std::string& partID); /** * @return the top level layout container. */ public: PartSashContainer::Pointer GetRootLayoutContainer(); /** * @return the ids of the parts to list in the Show In... prompter. This is * a List of Strings. */ public: std::vector GetShowInPartIds(); /** * @return the show view shortcuts associated with the page. This is a List of * Strings. */ public: std::vector GetShowViewShortcuts(); /** * @return the ViewFactory for this PageLayout. * @since 3.0 */ /* package */ ViewFactory* GetViewFactory(); /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#isEditorAreaVisible() */ public: bool IsEditorAreaVisible(); /** * Trim the ratio so that direct manipulation of parts is easy. * * @param in the initial ratio. * @return the normalized ratio. */ private: float NormalizeRatio(float in); /** * Prefill the layout with required parts. */ private: void Prefill(); /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#setEditorAreaVisible(boolean) */ public: void SetEditorAreaVisible(bool showEditorArea); /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#setEditorReuseThreshold(int) */ // public: void setEditorReuseThreshold(int openEditors) { // //no-op // } /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#setFixed(boolean) */ public: void SetFixed(bool fixed); /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#getFixed() */ public: bool IsFixed(); /** * Map the folder part containing the given view ID. * * @param viewId the part ID. * @param container the ContainerPlaceholder. */ /*package*/ void SetFolderPart(const std::string& viewId, ContainerPlaceholder::Pointer container); /** * Map the folder part containing the given view ID. * * @param viewId the part ID. * @param folder the ViewStack. */ /*package*/ void SetFolderPart(const std::string& viewId, PartStack::Pointer folder); void SetFolderPart(const std::string& viewId, IStackableContainer::Pointer folder); /** * Map an ID to a part. * * @param partId the part ID. * @param part the LayoutPart. */ /*package*/ void SetRefPart(const std::string& partID, StackablePart::Pointer part); /** * Stack a part on top of another. * * @param newPart the new part. * @param viewId the view ID. * @param refId the reference ID. */ private: void StackPart(StackablePart::Pointer newPart, const std::string& viewId, const std::string& refId); /** * Stack a placeholder on top of another. * * @param viewId the view ID. * @param refId the reference ID. */ public: void StackPlaceholder(const std::string& viewId, const std::string& refId); // stackView(String, String) modified by dan_rubel@instantiations.com /** * Stack one view on top of another. * * @param viewId the view ID. * @param refId the reference ID. */ public: void StackView(const std::string& viewId, const std::string& refId); /** * Converts common position constants into layout position constants. * * @param one of Constants::TOP, Constants::BOTTOM, Constants::LEFT, or Constants::RIGHT * @return one of IPageLayout::TOP, IPageLayout::BOTTOM, IPageLayout::LEFT, IPageLayout::RIGHT, or -1 indicating an * invalid input * * @since 3.0 */ public: static int ConstantToLayoutPosition(int constant); /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#addStandaloneView(java.lang.String, boolean, int, float, java.lang.String) * @since 3.0 */ public: void AddStandaloneView(const std::string& viewId, bool showTitle, int relationship, float ratio, const std::string& refId); /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#addStandaloneViewPlaceholder(java.lang.String, int, float, java.lang.String, boolean) */ public: void AddStandaloneViewPlaceholder(const std::string& viewId, int relationship, float ratio, const std::string& refId, bool showTitle); /* * (non-Javadoc) * * @see org.blueberry.ui.IPageLayout#getViewLayout(java.lang.String) * @since 3.0 */ public: IViewLayout::Pointer GetViewLayout(const std::string& viewId); /** * @since 3.0 */ public: std::map GetIDtoViewLayoutRecMap(); /** * Removes any existing placeholder with the given id. * * @param id the id for the placeholder * @since 3.1 */ public: void RemovePlaceholder(const std::string& id); /* (non-Javadoc) * @see org.blueberry.ui.IPageLayout#getFolderForView(java.lang.String) */ public: IPlaceholderFolderLayout::Pointer GetFolderForView(const std::string& viewId); }; } #endif /*BERRYPAGELAYOUT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPagePartSelectionTracker.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPagePartSelectionTracker.cpp index 2fcd0a1888..6cabcfb248 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPagePartSelectionTracker.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPagePartSelectionTracker.cpp @@ -1,276 +1,276 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryPagePartSelectionTracker.h" -#include "../berryIPostSelectionProvider.h" +#include "berryIPostSelectionProvider.h" namespace berry { class SelTrackerPartListener: public IPartListener { public: SelTrackerPartListener(PagePartSelectionTracker* tracker) : tracker(tracker) {} Events::Types GetPartEventTypes() const { return Events::CLOSED | Events::OPENED; } void PartClosed(IWorkbenchPartReference::Pointer partRef) { if (tracker->GetPartId(partRef->GetPart(false)) == tracker->AbstractPartSelectionTracker::GetPartId()) { tracker->SetPart(IWorkbenchPart::Pointer(0), true); } } void PartOpened(IWorkbenchPartReference::Pointer partRef) { if (tracker->GetPartId(partRef->GetPart(false)) == tracker->AbstractPartSelectionTracker::GetPartId()) { tracker->SetPart(partRef->GetPart(false), true); } } private: PagePartSelectionTracker* tracker; }; class SelTrackerPerspectiveListener: public IPerspectiveListener { public: SelTrackerPerspectiveListener(PagePartSelectionTracker* tracker) : tracker(tracker) {} IPerspectiveListener::Events::Types GetPerspectiveEventTypes() const { return IPerspectiveListener::Events::PART_CHANGED; } void PerspectiveChanged(IWorkbenchPage::Pointer, IPerspectiveDescriptor::Pointer, IWorkbenchPartReference::Pointer partRef, const std::string& changeId) { if (!partRef) return; IWorkbenchPart::Pointer part = partRef->GetPart(false); if (!part) return; if (IWorkbenchPage::CHANGE_VIEW_SHOW == changeId) { if (tracker->GetPart()) // quick check first, plus avoids double setting return; if (tracker->GetPartId(part) == tracker->AbstractPartSelectionTracker::GetPartId()) tracker->SetPart(part, true); } } private: PagePartSelectionTracker* tracker; }; class SelTrackerSelectionChangedListener: public ISelectionChangedListener { public: SelTrackerSelectionChangedListener(PagePartSelectionTracker* tracker) : tracker(tracker) {} void SelectionChanged(SelectionChangedEvent::Pointer event) { tracker->FireSelection(tracker->GetPart(), event->GetSelection()); } private: PagePartSelectionTracker* tracker; }; PagePartSelectionTracker::PostSelectionListener::PostSelectionListener( PagePartSelectionTracker* tracker) : m_Tracker(tracker) { } void PagePartSelectionTracker::PostSelectionListener::SelectionChanged( SelectionChangedEvent::Pointer event) { m_Tracker->FirePostSelection(m_Tracker->GetPart(), event->GetSelection()); } PagePartSelectionTracker::PagePartSelectionTracker( IWorkbenchPage* page, const std::string& partId) : AbstractPartSelectionTracker(partId) { postSelectionListener = new PostSelectionListener(this); perspListener = new SelTrackerPerspectiveListener(this); selChangedListener = new SelTrackerSelectionChangedListener(this); partListener = new SelTrackerPartListener(this); this->SetPage(page); page->AddPartListener(partListener); page->GetWorkbenchWindow()->AddPerspectiveListener( perspListener); std::string secondaryId; std::string primaryId = partId; std::string::size_type indexOfColon; if ((indexOfColon = partId.find_first_of(':')) != std::string::npos) { secondaryId = partId.substr(indexOfColon + 1); primaryId = partId.substr(0, indexOfColon); } IViewReference::Pointer part = page->FindViewReference(primaryId, secondaryId); if (part.IsNotNull() && part->GetView(false).IsNotNull()) { this->SetPart(part->GetView(false), false); } } ISelection::ConstPointer PagePartSelectionTracker::GetSelection() { IWorkbenchPart::Pointer part = this->GetPart(); if (part.IsNotNull()) { ISelectionProvider::Pointer sp = part->GetSite()->GetSelectionProvider(); if (sp.IsNotNull()) { return sp->GetSelection(); } } return ISelection::Pointer(0); } PagePartSelectionTracker::~PagePartSelectionTracker() { IWorkbenchPage::Pointer page = GetPage(); page->GetWorkbenchWindow()->RemovePerspectiveListener( perspListener); page->RemovePartListener(partListener); this->SetPart(IWorkbenchPart::Pointer(0), false); this->SetPage(0); } IWorkbenchPart::Pointer PagePartSelectionTracker::GetPart() { return fPart; } IWorkbenchPage::Pointer PagePartSelectionTracker::GetPage() { return IWorkbenchPage::Pointer(fPage); } ISelectionProvider::Pointer PagePartSelectionTracker::GetSelectionProvider() { IWorkbenchPart::Pointer part = this->GetPart(); if (part.IsNotNull()) { return part->GetSite()->GetSelectionProvider(); } return ISelectionProvider::Pointer(0); } std::string PagePartSelectionTracker::GetPartId(IWorkbenchPart::Pointer part) { std::string id = part->GetSite()->GetId(); if (part.Cast ().IsNotNull()) { std::string secondaryId = part.Cast ()->GetViewSite() ->GetSecondaryId(); if (secondaryId != "") { id = id + ':' + secondaryId; } } return id; } void PagePartSelectionTracker::SetPage(IWorkbenchPage* page) { fPage = page; } void PagePartSelectionTracker::SetPart(IWorkbenchPart::Pointer part, bool notify) { if (fPart.IsNotNull()) { // remove myself as a listener from the existing part ISelectionProvider::Pointer sp = fPart->GetSite()->GetSelectionProvider(); if (sp.IsNotNull()) { sp->RemoveSelectionChangedListener(selChangedListener); if (sp.Cast ().IsNotNull()) { sp.Cast () ->RemovePostSelectionChangedListener( postSelectionListener); } else { sp->RemoveSelectionChangedListener(postSelectionListener); } } } fPart = part; ISelection::ConstPointer sel; if (part.IsNotNull()) { ISelectionProvider::Pointer sp = part->GetSite()->GetSelectionProvider(); if (sp.IsNotNull()) { sp->AddSelectionChangedListener(selChangedListener); if (sp.Cast ().IsNotNull()) { sp.Cast () ->AddPostSelectionChangedListener( postSelectionListener); } else { sp->AddSelectionChangedListener(postSelectionListener); } if (notify) { // get the selection to send below sel = sp->GetSelection(); } } } if (notify) { this->FireSelection(part, sel); this->FirePostSelection(part, sel); } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPagePartSelectionTracker.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPagePartSelectionTracker.h index 75a9777469..04820bc646 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPagePartSelectionTracker.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPagePartSelectionTracker.h @@ -1,144 +1,144 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPAGEPARTSELECTIONTRACKER_H_ #define BERRYPAGEPARTSELECTIONTRACKER_H_ -#include "../berryIPartListener.h" -#include "../berryISelectionChangedListener.h" -#include "../berryISelectionService.h" -#include "../berryISelectionProvider.h" -#include "../berrySelectionChangedEvent.h" -#include "../berryIWorkbenchPage.h" +#include "berryIPartListener.h" +#include "berryISelectionChangedListener.h" +#include "berryISelectionService.h" +#include "berryISelectionProvider.h" +#include "berrySelectionChangedEvent.h" +#include "berryIWorkbenchPage.h" #include "berryAbstractPartSelectionTracker.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * * Provides per-part selection tracking for the selection service. */ class PagePartSelectionTracker : public AbstractPartSelectionTracker { public: berryObjectMacro(PagePartSelectionTracker); private: /** * The workbench page for which this is tracking selection. */ IWorkbenchPage* fPage; /** * The part in this tracker's page, or null if one is not open. */ IWorkbenchPart::Pointer fPart; struct PostSelectionListener : public ISelectionChangedListener { PostSelectionListener(PagePartSelectionTracker* tracker); void SelectionChanged(SelectionChangedEvent::Pointer event); PagePartSelectionTracker* m_Tracker; }; friend struct PostSelectionListener; friend class SelTrackerPartListener; friend class SelTrackerPerspectiveListener; friend class SelTrackerSelectionChangedListener; ISelectionChangedListener::Pointer postSelectionListener; IPerspectiveListener::Pointer perspListener; ISelectionChangedListener::Pointer selChangedListener; IPartListener::Pointer partListener; public: /** * Constructs a part selection tracker for the part with the given id. * * @param id part identifier */ PagePartSelectionTracker(IWorkbenchPage* page, const std::string& partId); /** * Returns the selection from the part being tracked, * or null if the part is closed or has no selection. */ ISelection::ConstPointer GetSelection(); /** * Disposes this selection tracker. This removes all listeners currently registered. */ ~PagePartSelectionTracker(); protected: /** * Returns the part this is tracking, * or null if it is not open * * @return part., or null */ IWorkbenchPart::Pointer GetPart(); /** * Returns the page this selection provider works for * * @return workbench page */ IWorkbenchPage::Pointer GetPage(); ISelectionProvider::Pointer GetSelectionProvider(); private: /** * Returns the id for the given part, taking into account * multi-view instances which may have a secondary id. * */ std::string GetPartId(IWorkbenchPart::Pointer part); /** * Sets the page this selection provider works for * * @param page workbench page */ void SetPage(IWorkbenchPage* page); /** * Sets the part for this selection tracker. * * @param part the part * @param notify whether to send notification that the selection has changed. */ void SetPart(IWorkbenchPart::Pointer part, bool notify); }; } #endif /*BERRYPAGEPARTSELECTIONTRACKER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPageSelectionService.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPageSelectionService.cpp index 1d877e083e..989c4095e7 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPageSelectionService.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPageSelectionService.cpp @@ -1,48 +1,48 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryPageSelectionService.h" #include "berryPagePartSelectionTracker.h" -#include "../berryIWorkbenchPage.h" +#include "berryIWorkbenchPage.h" namespace berry { void PageSelectionService::SetPage(IWorkbenchPage* page) { this->page = page; } PageSelectionService::PageSelectionService(IWorkbenchPage* page) { SetPage(page); } IWorkbenchPage* PageSelectionService::GetPage() const { return page; } AbstractPartSelectionTracker::Pointer PageSelectionService::CreatePartTracker( const std::string& partId) const { AbstractPartSelectionTracker::Pointer tracker(new PagePartSelectionTracker(GetPage(), partId)); return tracker; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartList.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartList.cpp index 95730f9509..58f4a48d07 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartList.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartList.cpp @@ -1,352 +1,352 @@ #include "berryPartList.h" #include "berrySaveablesList.h" #include "berryPartPane.h" -#include "../berryIWorkbenchPartConstants.h" -#include "../berryIWorkbenchPartSite.h" +#include "berryIWorkbenchPartConstants.h" +#include "berryIWorkbenchPartSite.h" #include namespace berry { void PartList::PropertyChange(Object::Pointer source, int propId) { WorkbenchPartReference::Pointer ref = source.Cast< WorkbenchPartReference> (); if (propId == IWorkbenchPartConstants::PROP_OPENED) { this->PartOpened(ref); } else if (propId == IWorkbenchPartConstants::PROP_CLOSED) { this->PartClosed(ref); } else if (propId == IWorkbenchPartConstants::PROP_VISIBLE) { if (ref->GetVisible()) { this->PartVisible(ref); } else { this->PartHidden(ref); } } else if (propId == IWorkbenchPartConstants::PROP_INPUT) { this->PartInputChanged(ref); } } IWorkbenchPartReference::Pointer PartList::GetActivePartReference() { return activePartReference.Lock(); } IEditorReference::Pointer PartList::GetActiveEditorReference() { return activeEditorReference.Lock(); } IEditorPart::Pointer PartList::GetActiveEditor() { return activeEditorReference.Expired() ? IEditorPart::Pointer(0) : activeEditorReference.Lock()->GetEditor( false); } IWorkbenchPart::Pointer PartList::GetActivePart() { return activePartReference.Expired() ? IWorkbenchPart::Pointer(0) : activePartReference.Lock()->GetPart(false); } //std::vector PartList::GetEditors() //{ // std::vector result; // for (std::deque::iterator iter = // parts.begin(); iter != parts.end(); ++iter) // { // if (iter->Cast () != 0) // result.push_back(iter->Cast ()); // } // // return result; //} void PartList::AddPart(WorkbenchPartReference::Pointer ref) { poco_assert(ref.IsNotNull()); ref->AddPropertyListener(IPropertyChangeListener::Pointer(this)); // if (!this->Contains(ref)) // { // parts.push_back(ref); // } // parts.add(ref); this->FirePartAdded(ref); // If this part is already open, fire the "part opened" event // immediately if (ref->GetPart(false).IsNotNull()) { this->PartOpened(ref); } // If this part is already visible, fire the visibility event // immediately if (ref->GetVisible()) { this->PartVisible(ref); } } void PartList::SetActivePart(IWorkbenchPartReference::Pointer ref) { if (activePartReference.Lock() == ref) { return; } IWorkbenchPartReference::Pointer oldPart = activePartReference.Lock(); // A part can't be activated until it is added //poco_assert(ref == 0 || this->Contains(ref)); //std::remove(parts.begin(), parts.end(), ref); //parts.push_front(ref); activePartReference = ref; this->FireActivePartChanged(oldPart, ref); } void PartList::SetActiveEditor(IEditorReference::Pointer ref) { if (activeEditorReference.Lock() == ref) { return; } // A part can't be activated until it is added //poco_assert(ref == 0 || this->Contains(ref)); activeEditorReference = ref; //std::remove(parts.begin(), parts.end(), ref); //parts.push_front(ref); this->FireActiveEditorChanged(ref); } void PartList::RemovePart(WorkbenchPartReference::Pointer ref) { poco_assert(ref.IsNotNull()); // It is an error to remove a part that isn't in the list //poco_assert(this->Contains(ref)); // We're not allowed to remove the active part. We must deactivate it // first. poco_assert(activePartReference.Lock() != ref); // We're not allowed to remove the active editor. We must deactivate it // first. if (ref.Cast()) { poco_assert(activeEditorReference.Lock() != ref.Cast()); } if (ref->GetVisible()) { ref->SetVisible(false); } // If this part is currently open, fire the "part closed" event before // removal if (ref->GetPart(false).IsNotNull()) { this->PartClosed(ref); } //std::remove(parts.begin(), parts.end(), ref); ref->RemovePropertyListener(IPropertyChangeListener::Pointer(this)); this->FirePartRemoved(ref); } //int PartList::IndexOf(const IWorkbenchPartReference::Pointer ref) const //{ // std::deque::const_iterator result = std::find(parts.begin(), parts.end(), ref); // if (result == parts.end()) return -1; // else return result - parts.begin(); //} //void PartList::BringToTop(IWorkbenchPartReference::Pointer ref) //{ // IStackableContainer::Pointer targetContainer; // if (ref != 0) // { // PartPane::Pointer pane = ref.Cast()->GetPane(); // if (pane != 0) // { // targetContainer = pane->GetContainer(); // } // } // // std::deque::iterator newIndex = this->LastIndexOfContainer(targetContainer); // // // //New index can be -1 if there is no last index // // if (newIndex >= 0 && ref == parts.get(newIndex)) // // return; // // std::remove(parts.begin(), parts.end(), ref); // if(newIndex != parts.end()) // { // parts.insert(newIndex, ref); // } // else // parts.push_front(ref); //} //std::vector //PartList::GetParts(const std::vector& views) //{ // std::vector resultList; // for (std::deque::iterator partIter = parts.begin(); // partIter != parts.end(); ++partIter) // { // IWorkbenchPartReference::Pointer ref = *partIter; // if (ref.Cast() != 0) // { // //Filter views from other perspectives // for (unsigned int i = 0; i < views.size(); i++) // { // if (ref == views[i]) // { // resultList.push_back(ref); // break; // } // } // } // else // { // resultList.push_back(ref); // } // } // return resultList; //} //std::deque::iterator //PartList::LastIndexOfContainer(IStackableContainer::Pointer container) //{ // for (std::deque::iterator iter = parts.begin(); // iter != parts.end(); ++iter) // { // IWorkbenchPartReference::Pointer ref = *iter; // // IStackableContainer::Pointer cnt; // PartPane::Pointer pane = ref.Cast()->GetPane(); // if (pane != 0) // { // cnt = pane->GetContainer(); // } // if (cnt == container) // { // return iter; // } // } // // return parts.end(); //} //bool PartList::Contains(IWorkbenchPartReference::Pointer ref) //{ // return std::find(parts.begin(), parts.end(), ref) != parts.end(); //} void PartList::PartInputChanged(WorkbenchPartReference::Pointer ref) { this->FirePartInputChanged(ref); } void PartList::PartHidden(WorkbenchPartReference::Pointer ref) { // Part should not be null poco_assert(ref.IsNotNull()); // This event should only be fired if the part is actually visible poco_assert(!ref->GetVisible()); // We shouldn't be receiving events from parts until they are in the // list //poco_assert(this->Contains(ref)); this->FirePartHidden(ref); } void PartList::PartOpened(WorkbenchPartReference::Pointer ref) { poco_assert(ref.IsNotNull()); IWorkbenchPart::Pointer actualPart = ref->GetPart(false); // We're firing the event that says "the part was just created"... so // there better be a part there. poco_assert(actualPart.IsNotNull()); // Must be called after the part is inserted into the part list //poco_assert(this->Contains(ref)); // The active part must be opened before it is activated, so we should // never get an open event for a part that is already active. // (This either indicates that a redundant // open event was fired or that a closed part was somehow activated) poco_assert(activePartReference.Lock() != ref); // The active editor must be opened before it is activated, so we should // never get an open event for an editor that is already active. // (This either indicates that a redundant // open event was fired or that a closed editor was somehow activated) poco_assert((void*)activeEditorReference.Lock().GetPointer() != (void*)ref.GetPointer()); SaveablesList::Pointer modelManager = actualPart ->GetSite()->GetService(ISaveablesLifecycleListener::GetManifestName()).Cast(); modelManager->PostOpen(actualPart); // Fire the "part opened" event this->FirePartOpened(ref); } void PartList::PartClosed(WorkbenchPartReference::Pointer ref) { poco_assert(ref.IsNotNull()); IWorkbenchPart::Pointer actualPart = ref->GetPart(false); // Called before the part is disposed, so the part should still be // there. poco_assert(actualPart.IsNotNull()); // Must be called before the part is actually removed from the part list // poco_assert(this->Contains(ref)); // Not allowed to close the active part. The part must be deactivated // before it may be closed. poco_assert(activePartReference.Lock() != ref); // Not allowed to close the active editor. The editor must be // deactivated before it may be closed. if (ref.Cast()) { poco_assert(activeEditorReference.Lock() != ref.Cast()); } this->FirePartClosed(ref); } void PartList::PartVisible(WorkbenchPartReference::Pointer ref) { // Part should not be null poco_assert(ref.IsNotNull()); // This event should only be fired if the part is actually visible poco_assert(ref->GetVisible()); // We shouldn't be receiving events from parts until they are in the // list //poco_assert(this->Contains(ref)); // Part must be open before it can be made visible poco_assert(ref->GetPart(false).IsNotNull()); this->FirePartVisible(ref); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartList.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartList.h index b77cdb3d8e..3dd9ab2a9f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartList.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartList.h @@ -1,174 +1,174 @@ #ifndef BERRYPARTLIST_H_ #define BERRYPARTLIST_H_ #include "berryWorkbenchPartReference.h" #include "berryIStackableContainer.h" -#include "../berryIEditorReference.h" -#include "../berryIViewReference.h" +#include "berryIEditorReference.h" +#include "berryIViewReference.h" #include namespace berry { class PartList : public IPropertyChangeListener { private: // list of parts in the activation order (oldest last) //std::deque parts; IWorkbenchPartReference::WeakPtr activePartReference; IEditorReference::WeakPtr activeEditorReference; public: void PropertyChange(Object::Pointer source, int propId); IWorkbenchPartReference::Pointer GetActivePartReference(); IEditorReference::Pointer GetActiveEditorReference(); IEditorPart::Pointer GetActiveEditor(); IWorkbenchPart::Pointer GetActivePart(); //std::vector GetEditors(); void AddPart(WorkbenchPartReference::Pointer ref); /** * Sets the active part. * * @param ref */ void SetActivePart(IWorkbenchPartReference::Pointer ref); void SetActiveEditor(IEditorReference::Pointer ref); /** * In order to remove a part, it must first be deactivated. */ void RemovePart(WorkbenchPartReference::Pointer ref); //int IndexOf(const IWorkbenchPartReference::Pointer ref) const; /* * Ensures that the given part appears AFTER any other part in the same * container. */ //void BringToTop(IWorkbenchPartReference::Pointer ref); /* * Return a list with all parts (editors and views). */ //std::vector GetParts(const std::vector& views); private: /* * Returns the last (most recent) index of the given container in the activation list, or returns * -1 if the given container does not appear in the activation list. */ //std::deque::iterator // LastIndexOfContainer(IStackableContainer::Pointer container); void PartInputChanged(WorkbenchPartReference::Pointer ref); void PartHidden(WorkbenchPartReference::Pointer ref); void PartOpened(WorkbenchPartReference::Pointer ref); /** * Called when a concrete part is about to be destroyed. This is called * BEFORE disposal happens, so the part should still be accessable from the * part reference. * * @param ref */ void PartClosed(WorkbenchPartReference::Pointer ref); void PartVisible(WorkbenchPartReference::Pointer ref); //bool Contains(IWorkbenchPartReference::Pointer ref); protected: /** * Fire the event indicating that a part reference was just realized. That * is, the concrete IWorkbenchPart has been attached to the part reference. * * @param part * the reference that was create */ virtual void FirePartOpened(IWorkbenchPartReference::Pointer part) = 0; /** * Fire the event indicating that a part reference was just realized. That * is, the concrete IWorkbenchPart has been attached to the part reference. * * @param part * the reference that was create */ virtual void FirePartClosed(IWorkbenchPartReference::Pointer part) = 0; /** * Indicates that a new part reference was added to the list. * * @param part */ virtual void FirePartAdded(IWorkbenchPartReference::Pointer part) = 0; /** * Indicates that a part reference was removed from the list * * @param part */ virtual void FirePartRemoved(IWorkbenchPartReference::Pointer part) = 0; /** * Indicates that the active editor changed * * @param part * active part reference or null if none */ virtual void FireActiveEditorChanged(IWorkbenchPartReference::Pointer ref) = 0; /** * Indicates that the active part has changed * * @param part * active part reference or null if none */ virtual void FireActivePartChanged( IWorkbenchPartReference::Pointer oldPart, IWorkbenchPartReference::Pointer newPart) = 0; /** * Indicates that the part has been made visible * * @param ref */ virtual void FirePartVisible(IWorkbenchPartReference::Pointer ref) = 0; /** * Indicates that the part has been hidden * * @param ref */ virtual void FirePartHidden(IWorkbenchPartReference::Pointer ref) = 0; /** * Indicates that the part input has changed * * @param ref */ virtual void FirePartInputChanged(IWorkbenchPartReference::Pointer ref) = 0; virtual void FirePartBroughtToTop(IWorkbenchPartReference::Pointer ref) = 0; }; } #endif /*BERRYPARTLIST_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartPane.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartPane.cpp index 8fb22a4a87..37de43f690 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartPane.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartPane.cpp @@ -1,467 +1,467 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryPartPane.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" -#include "../tweaklets/berryWorkbenchPageTweaklet.h" +#include "tweaklets/berryGuiWidgetsTweaklet.h" +#include "tweaklets/berryWorkbenchPageTweaklet.h" #include "berryWorkbenchPage.h" #include "berryPartStack.h" #include "berryEditorAreaHelper.h" #include "berryPerspective.h" #include "berryPartStack.h" #include "berryDragUtil.h" namespace berry { PartPane::Sashes::Sashes() : left(0), right(0), top(0), bottom(0) { } PartPane::PartPane(IWorkbenchPartReference::Pointer partReference, WorkbenchPage* workbenchPage) : StackablePart(partReference->GetId()), control(0), inLayout(true), busy(false), hasFocus(false) { //super(partReference.getId()); this->partReference = partReference; this->page = workbenchPage; } void PartPane::CreateControl(void* parent) { if (this->GetControl() != 0) { return; } partReference.Lock()->AddPropertyListener(IPropertyChangeListener::Pointer(this)); // Create view form. control = Tweaklets::Get(WorkbenchPageTweaklet::KEY)->CreatePaneControl(parent); // the part should never be visible by default. It will be made visible // by activation. This allows us to have views appear in tabs without // becoming active by default. Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(control, false); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->MoveAbove(control, 0); // Create a title bar. //this->CreateTitleBar(); // When the pane or any child gains focus, notify the workbench. Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(control, GuiTk::IControlListener::Pointer(this)); //control.addTraverseListener(traverseListener); } bool PartPane::IsPlaceHolder() { return false; } PartPane::~PartPane() { // super.dispose(); // this->Register(); if (control != 0) { BERRY_DEBUG << "Deleting PartPane control"; Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(control, GuiTk::IControlListener::Pointer(this)); // control.removeTraverseListener(traverseListener); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->Dispose(control); control = 0; } // if ((paneMenuManager != null)) // { // paneMenuManager.dispose(); // paneMenuManager = null; // } // if (!partReference.Expired()) { partReference.Lock()->RemovePropertyListener(IPropertyChangeListener::Pointer(this)); } // partReference.removePartPropertyListener(this); this->UnRegister(false); } void PartPane::DoHide() { if (partReference.Lock().Cast() != 0) { this->GetPage()->HideView(partReference.Lock().Cast()); } else if (partReference.Lock().Cast() != 0) { this->GetPage()->CloseEditor(partReference.Lock().Cast(), true); } } Rectangle PartPane::GetParentBounds() { void* ctrl = this->GetControl(); if (this->GetContainer() != 0 && this->GetContainer().Cast() != 0) { LayoutPart::Pointer part = this->GetContainer().Cast(); if (part->GetControl() != 0) { ctrl = part->GetControl(); } } return DragUtil::GetDisplayBounds(ctrl); } void* PartPane::GetControl() { return control; } IWorkbenchPartReference::Pointer PartPane::GetPartReference() const { return partReference.Lock(); } void PartPane::ControlActivated(GuiTk::ControlEvent::Pointer /*e*/) { if (inLayout) { this->RequestActivation(); } } GuiTk::IControlListener::Events::Types PartPane::GetEventTypes() const { return GuiTk::IControlListener::Events::ACTIVATED; } void PartPane::MoveAbove(void* refControl) { if (this->GetControl() != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->MoveAbove(this->GetControl(), refControl); } } void PartPane::RequestActivation() { IWorkbenchPart::Pointer part = partReference.Lock()->GetPart(true); this->page->RequestActivation(part); } //PartStack::Pointer PartPane::GetStack() //{ // return partStack; //} PartPane::Sashes PartPane::FindSashes() { Sashes result; IStackableContainer::Pointer container = this->GetContainer(); if (container == 0) { return result; } container->FindSashes(result); return result; } WorkbenchPage::Pointer PartPane::GetPage() { return WorkbenchPage::Pointer(page); } void PartPane::SetContainer(IStackableContainer::Pointer container) { if (hasFocus) { IStackableContainer::Pointer oldContainer = this->GetContainer(); if (PartStack::Pointer oldStack = oldContainer.Cast()) { oldStack->SetActive(StackPresentation::AS_INACTIVE); } if (PartStack::Pointer newContainer = container.Cast()) { newContainer->SetActive(StackPresentation::AS_ACTIVE_FOCUS); } } void* containerControl = container == 0 ? 0 : container.Cast()->GetControl(); if (containerControl != 0) { void* control = this->GetControl(); void* newParent = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(containerControl); if (control != 0 && newParent != Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(control)) { this->Reparent(newParent); } } StackablePart::SetContainer(container); } void PartPane::Reparent(void* newParent) { void* control = this->GetControl(); GuiWidgetsTweaklet* guiTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if ((control == 0) || (guiTweaklet->GetParent(control) == newParent)) { return; } if (guiTweaklet->IsReparentable(control)) { // make control small in case it is not resized with other controls //control.setBounds(0, 0, 0, 0); // By setting the control to disabled before moving it, // we ensure that the focus goes away from the control and its children // and moves somewhere else bool enabled = guiTweaklet->GetEnabled(control); guiTweaklet->SetEnabled(control, false); guiTweaklet->SetParent(control, newParent); guiTweaklet->SetEnabled(control, enabled); guiTweaklet->MoveAbove(control, 0); } } void PartPane::ShowFocus(bool inFocus) { if (partReference.Lock().Cast() != 0) { hasFocus = inFocus; } if (PartStack::Pointer stack = this->GetContainer().Cast()) { if (partReference.Lock().Cast() != 0) { stack->SetActive(inFocus ? StackPresentation::AS_ACTIVE_FOCUS : StackPresentation::AS_INACTIVE); } else if (partReference.Lock().Cast() != 0) { if (inFocus) { page->GetEditorPresentation()->SetActiveWorkbook(stack, true); } else { stack->SetActive(page->GetEditorPresentation()->GetActiveWorkbook() == stack ? StackPresentation::AS_ACTIVE_NOFOCUS : StackPresentation::AS_INACTIVE); } } } } PartStack::Pointer PartPane::GetStack() { IStackableContainer::Pointer container = this->GetContainer(); return container.Cast(); } void PartPane::SetVisible(bool makeVisible) { // Avoid redundant visibility changes if (makeVisible == this->GetVisible()) { return; } if (makeVisible) { partReference.Lock()->GetPart(true); } if (this->GetControl() != 0) Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetVisible(this->GetControl(), makeVisible); partReference.Lock().Cast()->FireVisibilityChange(); } bool PartPane::GetVisible() { if (this->GetControl() != 0) return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(this->GetControl()); return false; } void PartPane::SetFocus() { this->RequestActivation(); IWorkbenchPart::Pointer part = partReference.Lock()->GetPart(true); if (part.IsNotNull()) { // Control control = getControl(); // if (!SwtUtil.isFocusAncestor(control)) // { // First try to call part.setFocus part->SetFocus(); //} } } void PartPane::SetWorkbenchPage(WorkbenchPage::Pointer workbenchPage) { this->page = workbenchPage.GetPointer(); } void PartPane::DoDock() { // do nothing } void PartPane::SetBusy(bool isBusy) { if (isBusy != busy) { busy = isBusy; //firePropertyChange(IPresentablePart.PROP_BUSY); } } void PartPane::ShowHighlight() { //No nothing by default } void* PartPane::GetToolBar() { return 0; } bool PartPane::HasViewMenu() { return false; } bool PartPane::IsBusy() { return busy; } void PartPane::DescribeLayout(std::string& buf) const { IWorkbenchPartReference::Pointer part = this->GetPartReference(); if (part.IsNotNull()) { buf.append(part->GetPartName()); return; } } bool PartPane::IsCloseable() { if (partReference.Lock().Cast() != 0) { Perspective::Pointer perspective = page->GetActivePerspective(); if (perspective == 0) { // Shouldn't happen -- can't have a ViewStack without a // perspective return true; } return perspective->IsCloseable(partReference.Lock().Cast()); } return true; } void PartPane::SetInLayout(bool inLayout) { this->inLayout = inLayout; } bool PartPane::GetInLayout() { return inLayout; } bool PartPane::AllowsAutoFocus() { if (!inLayout) { return false; } //return super.allowsAutoFocus(); return true; } void PartPane::RemoveContributions() { } void PartPane::AddPropertyListener(IPropertyChangeListener::Pointer listener) { propertyChangeEvents.AddListener(listener); } void PartPane::RemovePropertyListener(IPropertyChangeListener::Pointer listener) { propertyChangeEvents.RemoveListener(listener); } void PartPane::FirePropertyChange(PropertyChangeEvent::Pointer event) { propertyChangeEvents.propertyChange(event); } void PartPane::PropertyChange(PropertyChangeEvent::Pointer event) { this->FirePropertyChange(event); } int PartPane::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { return partReference.Lock().Cast()->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } int PartPane::GetSizeFlags(bool horizontal) { return partReference.Lock().Cast()->GetSizeFlags(horizontal); } void PartPane::ShellActivated() { } void PartPane::ShellDeactivated() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartPane.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartPane.h index 5872eb225d..f339f6ea24 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartPane.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartPane.h @@ -1,437 +1,437 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPARTPANE_H_ #define BERRYPARTPANE_H_ #include "berryWorkbenchPartReference.h" #include "berryStackablePart.h" -#include "../berryRectangle.h" -#include "../berryIPropertyChangeListener.h" +#include "berryRectangle.h" +#include "berryIPropertyChangeListener.h" -#include "../guitk/berryGuiTkIControlListener.h" +#include "guitk/berryGuiTkIControlListener.h" namespace berry { class WorkbenchPage; class PartStack; struct IStackableContainer; /** * Provides the common behavior for both views * and editor panes. * */ class PartPane : public StackablePart, public IPropertyChangeListener, public GuiTk::IControlListener { public: berryObjectMacro(PartPane); friend class PartSashContainer; friend class EditorSashContainer; friend class WorkbenchPage; friend struct IStackableContainer; friend struct ILayoutContainer; friend class PartStack; friend class ContainerPlaceholder; friend class LayoutTree; friend class LayoutTreeNode; friend class DetachedPlaceHolder; friend class PerspectiveHelper; // private: MenuManager paneMenuManager; // private: ListenerList listeners = new ListenerList(); // private: ListenerList partListeners = new ListenerList(); private: IPropertyChangeListener::Events propertyChangeEvents; protected: IWorkbenchPartReference::WeakPtr partReference; protected: WorkbenchPage* page; protected: void* control; private: bool inLayout; // private: TraverseListener traverseListener = new TraverseListener() { // /* (non-Javadoc) // * @see org.blueberry.swt.events.TraverseListener#keyTraversed(org.blueberry.swt.events.TraverseEvent) // */ // public: void keyTraversed(TraverseEvent e) { // // Hack: Currently, SWT sets focus whenever we call Control.traverse. This doesn't // // cause too much of a problem for ctrl-pgup and ctrl-pgdn, but it is seriously unexpected // // for other traversal events. When (and if) it becomes possible to call traverse() without // // forcing a focus change, this if statement should be removed and ALL events should be // // forwarded to the container. // if (e.detail == SWT.TRAVERSE_PAGE_NEXT // || e.detail == SWT.TRAVERSE_PAGE_PREVIOUS) { // ILayoutContainer container = getContainer(); // if (container != null && container instanceof LayoutPart) { // LayoutPart parent = (LayoutPart) container; // Control parentControl = parent.getControl(); // if (parentControl != null && !parentControl.isDisposed()) { // e.doit = parentControl.traverse(e.detail); // if (e.doit) { // e.detail = SWT.TRAVERSE_NONE; // } // } // } // } // } // // }; private: bool busy; private: bool hasFocus; //private: SmartPointer partStack; protected: /*static*/ class Sashes { public: Sashes(); /*Sash*/ void* left; /*Sash*/ void* right; /*Sash*/ void* top; /*Sash*/ void* bottom; }; /** * Construct a pane for a part. */ public: PartPane(IWorkbenchPartReference::Pointer partReference, WorkbenchPage* workbenchPage); // public: void addSizeMenuItem(Menu menu, int index) { // //Add size menu // MenuItem item = new MenuItem(menu, SWT.CASCADE, index); // item.setText(WorkbenchMessages.PartPane_size); // Menu sizeMenu = new Menu(menu); // item.setMenu(sizeMenu); // addSizeItems(sizeMenu); // } /** * * Creates the GUI-dependent container control * for the part widgets. This is passed to * IWorkbenchPart::CreatePartControl(void*) */ public: virtual void CreateControl(void* parent); //public: virtual void SetControlEnabled(bool enabled) = 0; /** * Create a title bar for the pane if required. */ // protected: virtual void CreateTitleBar() = 0; public: bool IsPlaceHolder(); /** * @private: */ public: virtual ~PartPane(); /** * User has requested to close the pane. * Take appropriate action depending on type. */ public: void DoHide(); protected: Rectangle GetParentBounds(); /** * Get the control. */ public: void* GetControl(); /** * Answer the part child. */ public: IWorkbenchPartReference::Pointer GetPartReference() const; /** * @see GuiTk::IControlListener */ public: void ControlActivated(GuiTk::ControlEvent::Pointer e); /** * @see GuiTk::IControlListener */ public: GuiTk::IControlListener::Events::Types GetEventTypes() const; /** * Move the control over another one. */ public: void MoveAbove(void* refControl); /** * Notify the workbook page that the part pane has * been activated by the user. */ public: void RequestActivation(); /** * Shows the receiver if visible is true otherwise hide it. */ public: void SetVisible(bool makeVisible); public: virtual bool GetVisible(); /** * Sets focus to this part. */ public: void SetFocus(); /** * Sets the workbench page of the view. */ public: void SetWorkbenchPage(SmartPointer workbenchPage); public: void Reparent(void* newParent); /** * Indicate focus in part. */ public: void ShowFocus(bool inFocus); /** * @see IPartDropTarget::targetPartFor */ // public: LayoutPart targetPartFor(LayoutPart dragSource) { // return this; // } /** * Returns the PartStack that contains this PartPane, or null if none. * * @return */ public: SmartPointer GetStack(); public: void SetContainer(SmartPointer stack); /** * Show a title label menu for this pane. */ // public: void ShowPaneMenu() { // PartStack folder = getStack(); // // if (folder != null) { // folder.showPaneMenu(); // } // } /** * Show the context menu for this part. */ // public: void showSystemMenu() { // PartStack folder = getStack(); // // if (folder != null) { // folder.showSystemMenu(); // } // } /** * Finds and return the sashes around this part. */ protected: Sashes FindSashes(); /** * Enable the user to resize this part using * the keyboard to move the specified sash */ // protected: void moveSash(final Sash sash) { // moveSash(sash, this); // } // public: static void moveSash(final Sash sash, // final LayoutPart toGetFocusWhenDone) { // final KeyListener listener = new KeyAdapter() { // public: void keyPressed(KeyEvent e) { // if (e.character == SWT.ESC || e.character == '\r') { // if (toGetFocusWhenDone != null) { // toGetFocusWhenDone.setFocus(); // } // } // } // }; // sash.addFocusListener(new FocusAdapter() { // public: void focusGained(FocusEvent e) { // sash.setBackground(sash.getDisplay().getSystemColor( // SWT.COLOR_LIST_SELECTION)); // sash.addKeyListener(listener); // } // // public: void focusLost(FocusEvent e) { // sash.setBackground(null); // sash.removeKeyListener(listener); // } // }); // sash.setFocus(); // // } /** * Add a menu item to the Size Menu */ // protected: void addSizeItem(Menu sizeMenu, String labelMessage, // final Sash sash) { // MenuItem item = new MenuItem(sizeMenu, SWT.NONE); // item.setText(labelMessage); // item.addSelectionListener(new SelectionAdapter() { // public: void widgetSelected(SelectionEvent e) { // moveSash(sash); // } // }); // item.setEnabled(!isZoomed() && sash != null); // } /** * Returns the workbench page of this pane. */ public: SmartPointer GetPage(); /** * Add the Left,Right,Up,Botton menu items to the Size menu. */ // protected: void addSizeItems(Menu sizeMenu) { // Sashes sashes = findSashes(); // addSizeItem(sizeMenu, // WorkbenchMessages.PartPane_sizeLeft, sashes.left); // addSizeItem(sizeMenu, // WorkbenchMessages.PartPane_sizeRight, sashes.right); // addSizeItem(sizeMenu, // WorkbenchMessages.PartPane_sizeTop, sashes.top); // addSizeItem(sizeMenu, WorkbenchMessages.PartPane_sizeBottom, sashes.bottom); // } /** * Pin this part. */ protected: virtual void DoDock(); /** * Set the busy state of the pane. */ public: virtual void SetBusy(bool isBusy); /** * Show a highlight for the receiver if it is * not currently the part in the front of its * presentation. * */ public: virtual void ShowHighlight(); /** * @return */ public: virtual void* GetToolBar(); /** * @return */ public: bool HasViewMenu(); /** * @param location */ // public: void ShowViewMenu(Point location) { // // } public: bool IsBusy(); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they do not need to be translated. * * @param buf */ public: void DescribeLayout(std::string& buf) const; /** * @return * @since 3.1 */ public: bool IsCloseable(); public: void SetInLayout(bool inLayout); public: bool GetInLayout(); public: bool AllowsAutoFocus(); /** * Clears all contribution items from the contribution managers (this is done separately * from dispose() since it is done after the part is disposed). This is a bit of a hack. * Really, the contribution managers should be part of the site, not the PartPane. If these * were moved elsewhere, then disposal of the PartPane would be atomic and this method could * be removed. */ public: virtual void RemoveContributions(); public: void AddPropertyListener(IPropertyChangeListener::Pointer listener); public: void RemovePropertyListener(IPropertyChangeListener::Pointer listener); public: void FirePropertyChange(PropertyChangeEvent::Pointer event); /* (non-Javadoc) * @see IPropertyChangeListener#PropertyChange(PropertyChangeEvent::Pointer) */ public: void PropertyChange(PropertyChangeEvent::Pointer event); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#computePreferredSize(boolean, int, int, int) */ public: int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#getSizeFlags(boolean) */ public: int GetSizeFlags(bool horizontal); /** * Informs the pane that it's window shell has * been activated. */ public: virtual void ShellActivated(); /** * Informs the pane that it's window shell has * been deactivated. */ public: virtual void ShellDeactivated(); }; } #endif /*BERRYPARTPANE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSashContainer.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSashContainer.cpp index cf2cbf99c7..ff4f44be03 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSashContainer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSashContainer.cpp @@ -1,1283 +1,1283 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryPartSashContainer.h" #include "berryLayoutTree.h" #include "berryLayoutTreeNode.h" #include "berryPartStack.h" #include "berryPageLayout.h" #include "berryPerspective.h" #include "berryPerspectiveHelper.h" #include "berryDragUtil.h" #include "berryWorkbenchPlugin.h" -#include "../berryWorkbenchPreferenceConstants.h" -#include "../berryGeometry.h" +#include "berryWorkbenchPreferenceConstants.h" +#include "berryGeometry.h" #include "berryPartPane.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" -#include "../berryConstants.h" +#include "tweaklets/berryGuiWidgetsTweaklet.h" +#include "berryConstants.h" namespace berry { bool PartSashContainer::leftToRight = true; PartSashContainer::ControlListener::ControlListener( PartSashContainer* container) : partSashContainer(container) { } GuiTk::IControlListener::Events::Types PartSashContainer::ControlListener::GetEventTypes() const { return Events::RESIZED; } void PartSashContainer::ControlListener::ControlResized( GuiTk::ControlEvent::Pointer /*e*/) { partSashContainer->ResizeSashes(); } PartSashContainer::SashContainerDropTarget::SashContainerDropTarget( PartSashContainer* partSashContainer, Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) : partSashContainer(partSashContainer) { this->SetTarget(sourcePart, side, cursor, targetPart); } void PartSashContainer::SashContainerDropTarget::SetTarget( Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) { this->side = side; this->targetPart = targetPart; this->sourcePart = sourcePart; this->cursor = cursor; } void PartSashContainer::SashContainerDropTarget::Drop() { if (side != Constants::NONE) { StackablePart::Pointer visiblePart = sourcePart.Cast (); if (sourcePart.Cast () != 0) { visiblePart = partSashContainer->GetVisiblePart(sourcePart.Cast< IStackableContainer> ()); } partSashContainer->DropObject( partSashContainer->GetVisibleParts(sourcePart), visiblePart, targetPart, side); } } void PartSashContainer::DropObject(const std::vector& toDrop, StackablePart::Pointer visiblePart, Object::Pointer targetPart, int side) { //getControl().setRedraw(false); // Targetpart is null if there isn't a part under the cursor (all the parts are // hidden or the container is empty). In this case, the actual side doesn't really // since we'll be the only visible container and will fill the entire space. However, // we can't leave it as Constants::CENTER since we can't stack if we don't have something // to stack on. In this case, we pick Constants::BOTTOM -- this will insert the new pane // below any currently-hidden parts. if (targetPart == 0 && side == Constants::CENTER) { side = Constants::BOTTOM; } PartStack::Pointer targetStack = targetPart.Cast (); if (targetStack == 0 && targetPart.Cast() != 0) { targetStack = targetPart.Cast ()->GetStack(); } LayoutPart::Pointer targetLayoutPart = targetStack; // if targetLayoutPart == 0 then we normally got a EditorSashContainer if (targetLayoutPart == 0) targetLayoutPart = targetPart.Cast(); if (side == Constants::CENTER) { if (this->IsStackType(targetStack)) { for (unsigned int idx = 0; idx < toDrop.size(); idx++) { StackablePart::Pointer next = toDrop[idx]; this->Stack(next, targetStack); } } } else { PartStack::Pointer newPart = this->CreateStack(); // if the toDrop array has 1 item propagate the stack // appearance if (toDrop.size() == 1 && toDrop[0]->GetStack() != 0) { toDrop[0]->GetStack()->CopyAppearanceProperties(newPart); } for (unsigned int idx = 0; idx < toDrop.size(); idx++) { StackablePart::Pointer next = toDrop[idx]; this->Stack(next, newPart); } this->AddEnhanced(newPart, side, this->GetDockingRatio(newPart, targetStack), targetLayoutPart); } if (visiblePart != 0) { this->SetVisiblePart(visiblePart->GetContainer(), visiblePart.Cast ()); } //getControl().setRedraw(true); if (visiblePart != 0) { visiblePart->SetFocus(); } } DnDTweaklet::CursorType PartSashContainer::SashContainerDropTarget::GetCursor() { return DnDTweaklet::PositionToCursorType(cursor); } Rectangle PartSashContainer::SashContainerDropTarget::GetSnapRectangle() { Rectangle targetBounds; if (targetPart.Cast () != 0) { targetBounds = DragUtil::GetDisplayBounds( targetPart.Cast ()->GetControl()); } else if (targetPart.Cast () != 0) { targetBounds = DragUtil::GetDisplayBounds( targetPart.Cast ()->GetControl()); } else { targetBounds = DragUtil::GetDisplayBounds(partSashContainer->GetParent()); } if (side == Constants::CENTER || side == Constants::NONE) { return targetBounds; } int distance = Geometry::GetDimension(targetBounds, !Geometry::IsHorizontal( side)); IStackableContainer::Pointer stack = targetPart.Cast (); if (stack == 0 && targetPart.Cast () != 0) { stack = targetPart.Cast ()->GetContainer(); } return Geometry::GetExtrudedEdge(targetBounds, (int) (distance * partSashContainer->GetDockingRatio(sourcePart, stack)), side); } PartSashContainer::PartSashContainer(const std::string& id, WorkbenchPage* _page, void* _parentWidget) : LayoutPart(id), parentWidget(_parentWidget), parent(0), page(_page), active( false), layoutDirty(false) { resizeListener = new ControlListener(this); std::string layout = WorkbenchPlugin::GetDefault()->GetPreferencesService()-> GetSystemPreferences()->Get(WorkbenchPreferenceConstants::PREFERRED_SASH_LAYOUT, WorkbenchPreferenceConstants::LEFT); if (layout == WorkbenchPreferenceConstants::RIGHT) { leftToRight = false; } } std::vector PartSashContainer::GetVisibleParts( Object::Pointer pane) { std::vector parts; if (pane.Cast ().IsNotNull()) { parts.push_back(pane.Cast ()); } else if (pane.Cast ().IsNotNull()) { PartStack::Pointer stack = pane.Cast (); std::list children = stack->GetChildren(); for (std::list::iterator iter = children.begin(); iter != children.end(); ++iter) { if (iter->Cast () != 0) { parts.push_back(iter->Cast ()); } } } return parts; } PartSashContainer::~PartSashContainer() { } void PartSashContainer::FindSashes(LayoutPart::Pointer pane, PartPane::Sashes& sashes) { if (root == 0) { return; } LayoutTree::Pointer part = root->Find(pane); if (part == 0) { return; } part->FindSashes(sashes); } void PartSashContainer::Add(LayoutPart::Pointer child) { if (child.IsNull()) { return; } this->AddEnhanced(child, Constants::RIGHT, 0.5f, this->FindBottomRight()); } void PartSashContainer::AddPart(StackablePart::Pointer child) { if (child.IsNull()) { return; } PartStack::Pointer newFolder = this->CreateStack(); newFolder->Add(child); this->AddEnhanced(newFolder, Constants::RIGHT, 0.5f, this->FindBottomRight()); } void PartSashContainer::AddEnhanced(LayoutPart::Pointer child, int directionConstant, float ratioForNewPart, LayoutPart::Pointer relative) { int relativePosition = PageLayout::ConstantToLayoutPosition(directionConstant); float ratioForUpperLeftPart; if (relativePosition == IPageLayout::RIGHT || relativePosition == IPageLayout::BOTTOM) { ratioForUpperLeftPart = 1.0f - ratioForNewPart; } else { ratioForUpperLeftPart = ratioForNewPart; } this->Add(child, relativePosition, ratioForUpperLeftPart, relative); } void PartSashContainer::Add(LayoutPart::Pointer child, int relationship, float ratio, LayoutPart::Pointer relative) { bool isHorizontal = (relationship == IPageLayout::LEFT || relationship == IPageLayout::RIGHT); LayoutTree::Pointer node; if (root != 0 && relative != 0) { node = root->Find(relative); } Rectangle bounds; if (this->GetParent() == 0) { void* control = this->GetPage()->GetClientComposite(); if (control != 0) { bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(control); } else { bounds = Rectangle(0, 0, 800, 600); } bounds.x = 0; bounds.y = 0; } else { bounds = this->GetBounds(); } int totalSize = this->MeasureTree(bounds, node, isHorizontal); int left = (int) (totalSize * ratio); int right = totalSize - left; this->Add(child, relationship, left, right, relative); } int PartSashContainer::MeasureTree(const Rectangle& outerBounds, LayoutTree::ConstPointer toMeasure, bool horizontal) { if (toMeasure == 0) { return outerBounds.GetDimension(horizontal); } LayoutTreeNode* parent = toMeasure->GetParent(); if (parent == 0) { return outerBounds.GetDimension(horizontal); } if (parent->GetSash()->IsHorizontal() == horizontal) { return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal); } bool isLeft = parent->IsLeftChild(toMeasure); LayoutTree::Pointer otherChild = parent->GetChild(!isLeft); if (otherChild->IsVisible()) { int left = parent->GetSash()->GetLeft(); int right = parent->GetSash()->GetRight(); int childSize = isLeft ? left : right; int bias = parent->GetCompressionBias(); // Normalize bias: 1 = we're fixed, -1 = other child is fixed if (isLeft) { bias = -bias; } if (bias == 1) { // If we're fixed, return the fixed size return childSize; } else if (bias == -1) { // If the other child is fixed, return the size of the parent minus the fixed size of the // other child return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal) - (left + right - childSize); } // Else return the size of the parent, scaled appropriately return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal) * childSize / (left + right); } return MeasureTree(outerBounds, LayoutTree::ConstPointer(parent), horizontal); } void PartSashContainer::AddChild(const RelationshipInfo& info) { LayoutPart::Pointer child = info.part; children.push_back(child); if (root == 0) { root = new LayoutTree(child); } else { //Add the part to the tree. int vertical = (info.relationship == IPageLayout::LEFT || info.relationship == IPageLayout::RIGHT) ? Constants::VERTICAL : Constants::HORIZONTAL; bool left = info.relationship == IPageLayout::LEFT || info.relationship == IPageLayout::TOP; LayoutPartSash::Pointer sash(new LayoutPartSash(this, vertical)); sash->SetSizes(info.left, info.right); if ((parent != 0) && child.Cast ().IsNull()) { sash->CreateControl(parent); } LayoutTree::Pointer newroot = root->Insert(child, left, sash, info.relative); root = newroot; } this->ChildAdded(child); if (active) { child->CreateControl(parent); child->SetVisible(true); child->SetContainer(ILayoutContainer::Pointer(this)); this->ResizeChild(child); } } void PartSashContainer::AddChildForPlaceholder(LayoutPart::Pointer child, LayoutPart::Pointer placeholder) { RelationshipInfo newRelationshipInfo; newRelationshipInfo.part = child; if (root != 0) { newRelationshipInfo.relationship = IPageLayout::RIGHT; newRelationshipInfo.relative = root->FindBottomRight(); newRelationshipInfo.left = 200; newRelationshipInfo.right = 200; } // find the relationship info for the placeholder std::vector relationships = this->ComputeRelation(); for (unsigned int i = 0; i < relationships.size(); i++) { RelationshipInfo info = relationships[i]; if (info.part == placeholder) { newRelationshipInfo.left = info.left; newRelationshipInfo.right = info.right; newRelationshipInfo.relationship = info.relationship; newRelationshipInfo.relative = info.relative; } } this->AddChild(newRelationshipInfo); this->FlushLayout(); } bool PartSashContainer::AllowsBorder() { return true; } void PartSashContainer::ChildAdded(LayoutPart::Pointer child) { if (this->IsDeferred()) { child->DeferUpdates(true); } } void PartSashContainer::ChildRemoved(LayoutPart::Pointer child) { if (this->IsDeferred()) { child->DeferUpdates(false); } } std::vector PartSashContainer::ComputeRelation() { LayoutTree::Pointer treeRoot = root; std::list list; if (treeRoot == 0) { return std::vector(); } RelationshipInfo r; r.part = treeRoot->ComputeRelation(list); list.push_front(r); std::vector result(list.begin(), list.end()); return result; } void PartSashContainer::SetActive(bool isActive) { if (isActive == active) { return; } active = isActive; ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { if (childIter->Cast ().IsNotNull()) { PartStack::Pointer stack = childIter->Cast (); stack->SetActive(isActive); } } if (isActive) { this->CreateControl(parentWidget); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(parent, resizeListener); DragUtil::AddDragTarget(parent, IDragOverListener::Pointer(this)); DragUtil::AddDragTarget(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parent)->GetControl(), IDragOverListener::Pointer(this)); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { LayoutPart::Pointer child = *childIter; child->SetContainer(ILayoutContainer::Pointer(this)); child->SetVisible(true); //zoomedPart == null || child == zoomedPart); if (child.Cast ().IsNull()) { if (root != 0) { LayoutTree::Pointer node = root->Find(child); if (node != 0) { node->FlushCache(); } } } } if (root != 0) { //root.flushChildren(); //if (!isZoomed()) { root->CreateControl(parent); } } this->ResizeSashes(); } else { DragUtil::RemoveDragTarget(parent, IDragOverListener::Pointer(this)); DragUtil::RemoveDragTarget(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parent)->GetControl(), IDragOverListener::Pointer(this)); // remove all Listeners if (resizeListener != 0 && parent != 0) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(parent, resizeListener); } for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { LayoutPart::Pointer child = *iter; child->SetContainer(ILayoutContainer::Pointer(0)); if (child.Cast ().IsNotNull()) { child->SetVisible(false); } } this->DisposeSashes(); //dispose(); } } void PartSashContainer::CreateControl(void* parentWidget) { if (this->parent != 0) { return; } parent = this->CreateParent(parentWidget); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { (*childIter)->CreateControl(parent); } } void PartSashContainer::Dispose() { if (parent == 0) { return; } for (ILayoutContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { // In PartSashContainer dispose really means deactivate, so we // only dispose PartTabFolders. if (iter->Cast() != 0) { (*iter)->Dispose(); } } this->DisposeParent(); this->parent = 0; } void PartSashContainer::DisposeSashes() { if (root != 0) { root->DisposeSashes(); } } void PartSashContainer::SetVisible(bool makeVisible) { if (makeVisible == this->GetVisible()) { return; } //if (!SwtUtil.isDisposed(this.parent)) //{ Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(this->parent, makeVisible); //} LayoutPart::SetVisible(makeVisible); ILayoutContainer::ChildrenType children = this->children; for (ILayoutContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { (*childIter)->SetVisible(makeVisible); // && (zoomedPart == null || child == zoomedPart)); } } LayoutPart::Pointer PartSashContainer::FindBottomRight() { if (root == 0) { return LayoutPart::Pointer(0); } return root->FindBottomRight(); } Rectangle PartSashContainer::GetBounds() { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->parent); } ILayoutContainer::ChildrenType PartSashContainer::GetChildren() { return children; } void* PartSashContainer::GetControl() { return this->parent; } LayoutTree::Pointer PartSashContainer::GetLayoutTree() { return root; } WorkbenchPage::Pointer PartSashContainer::GetPage() { return WorkbenchPage::Pointer(page); } void* PartSashContainer::GetParent() { return parent; } bool PartSashContainer::IsChild(LayoutPart::Pointer part) { return std::find(children.begin(), children.end(), part) != children.end(); } void PartSashContainer::ResizeChild(LayoutPart::Pointer childThatChanged) { if (root != 0) { LayoutTree::Pointer tree = root->Find(childThatChanged); if (tree != 0) { tree->FlushCache(); } } this->FlushLayout(); } void PartSashContainer::Remove(LayoutPart::Pointer child) { // if (child == getZoomedPart()) // { // childRequestZoomOut(); // } if (!this->IsChild(child)) { return; } children.remove(child); if (root != 0) { root = root->Remove(child); } this->ChildRemoved(child); if (active) { child->SetVisible(false); child->SetContainer(ILayoutContainer::Pointer(0)); this->FlushLayout(); } } void PartSashContainer::FlushLayout() { layoutDirty = true; LayoutPart::FlushLayout(); if (layoutDirty) { this->ResizeSashes(); } } void PartSashContainer::Replace(LayoutPart::Pointer oldChild, LayoutPart::Pointer newChild) { if (!this->IsChild(oldChild)) { return; } // if (oldChild == getZoomedPart()) // { // if (newChild.Cast ().IsNotNull()) // { // childRequestZoomOut(); // } // else // { // zoomedPart.setZoomed(false); // zoomedPart = newChild; // zoomedPart.setZoomed(true); // } // } children.erase(std::find(children.begin(), children.end(), oldChild)); children.push_back(newChild); this->ChildAdded(newChild); if (root != 0) { LayoutTree::Pointer leaf; leaf = root->Find(oldChild); if (leaf != 0) { leaf->SetPart(newChild); } } this->ChildRemoved(oldChild); if (active) { oldChild->SetVisible(false); oldChild->SetContainer(ILayoutContainer::Pointer(0)); newChild->CreateControl(parent); newChild->SetContainer(ILayoutContainer::Pointer(this)); newChild->SetVisible(true); //zoomedPart == null || zoomedPart == newChild); this->ResizeChild(newChild); } } void PartSashContainer::ResizeSashes() { layoutDirty = false; if (!active) { return; } // if (isZoomed()) // { // getZoomedPart().setBounds(parent.getClientArea()); // } // else { if (root != 0) { root->SetBounds(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetClientArea( parent)); } } } int PartSashContainer::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { // if (isZoomed()) // { // return getZoomedPart().computePreferredSize(width, availableParallel, // availablePerpendicular, preferredParallel); // } if (root != 0) { return root->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } return preferredParallel; } int PartSashContainer::GetSizeFlags(bool width) { // if (isZoomed()) // { // return getZoomedPart().getSizeFlags(width); // } if (root != 0) { return root->GetSizeFlags(width); } return 0; } void PartSashContainer::SetBounds(const Rectangle& r) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(this->parent, r); } IDropTarget::Pointer PartSashContainer::Drag(void* /*currentControl*/, Object::Pointer draggedObject, const Point& position, const Rectangle& /*dragRectangle*/) { if (!(draggedObject.Cast () != 0 || draggedObject.Cast () != 0)) { return IDropTarget::Pointer(0); } PartPane::Pointer sourcePart = draggedObject.Cast (); PartStack::Pointer sourceContainer = draggedObject.Cast (); if (sourceContainer == 0) { sourceContainer = sourcePart->GetStack(); } if (!this->IsStackType(sourceContainer) && !this->IsPaneType(sourcePart)) { return IDropTarget::Pointer(0); } IWorkbenchWindow::Pointer window = sourcePart ? sourcePart->GetWorkbenchWindow() : sourceContainer->GetWorkbenchWindow(); bool differentWindows = window != this->GetWorkbenchWindow(); bool editorDropOK = ((sourceContainer->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) && window->GetWorkbench() == this->GetWorkbenchWindow()->GetWorkbench()); if (differentWindows && !editorDropOK) { return IDropTarget::Pointer(0); } Rectangle containerBounds = DragUtil::GetDisplayBounds(parent); LayoutPart::Pointer targetPart; // If this container has no visible children if (this->GetVisibleChildrenCount(ILayoutContainer::Pointer(this)) == 0) { return this->CreateDropTarget(draggedObject, Constants::CENTER, Constants::CENTER, Object::Pointer(0)); } if (containerBounds.Contains(position)) { if (root != 0) { targetPart = root->FindPart( Tweaklets::Get(GuiWidgetsTweaklet::KEY)->ToControl(parent, position)); } if (targetPart != 0) { void* targetControl = targetPart->GetControl(); Rectangle targetBounds = DragUtil::GetDisplayBounds(targetControl); int side = Geometry::GetClosestSide(targetBounds, position); int distance = Geometry::GetDistanceFromEdge(targetBounds, position, side); // is the source coming from a standalone part bool standalone = (this->IsStackType(sourceContainer) && sourceContainer->IsStandalone()) || (this->IsPaneType(sourcePart) && sourcePart->GetStack()->IsStandalone()); // Only allow dropping onto an existing stack from different windows if (differentWindows && targetPart.Cast () != 0 && targetPart.Cast ()->GetAppearance() == PresentationFactoryUtil::ROLE_EDITOR) { IDropTarget::Pointer target = targetPart->GetDropTarget(draggedObject, position); return target; } // Reserve the 5 pixels around the edge of the part for the drop-on-edge cursor if (distance >= 5 && !standalone) { // Otherwise, ask the part if it has any special meaning for this drop location IDropTarget::Pointer target = targetPart->GetDropTarget(draggedObject, position); if (target != 0) { return target; } } if (distance > 30 && this->IsStackType(targetPart.Cast ()) && !standalone) { PartStack::Pointer targetContainer = targetPart.Cast (); if (targetContainer->AllowsAdd(sourcePart)) { side = Constants::CENTER; } } // If the part doesn't want to override this drop location then drop on the edge // A "pointless drop" would be one that will put the dragged object back where it started. // Note that it should be perfectly valid to drag an object back to where it came from -- however, // the drop should be ignored. bool pointlessDrop = false; // = isZoomed(); if (!sourcePart && sourceContainer == targetPart) { pointlessDrop = true; } if ((sourceContainer != 0) && (sourceContainer == targetPart) && this->GetVisibleChildrenCount(sourceContainer.Cast()) <= 1) { pointlessDrop = true; } if (side == Constants::CENTER && sourceContainer == targetPart) { pointlessDrop = true; } int cursor = side; if (pointlessDrop) { side = Constants::NONE; cursor = Constants::CENTER; } if (sourcePart) return this->CreateDropTarget(sourcePart, side, cursor, targetPart); else return this->CreateDropTarget(sourceContainer, side, cursor, targetPart); } } else { // We only allow dropping into a stack, not creating one if (differentWindows) return IDropTarget::Pointer(0); int side = Geometry::GetClosestSide(containerBounds, position); bool pointlessDrop = false; // = isZoomed(); if (/*(this->IsStackType(sourceContainer) && sourceContainer == this) ||*/ (this->IsPaneType(sourcePart) && this->GetVisibleChildrenCount( sourceContainer.Cast()) <= 1) && sourceContainer->GetContainer() == this) { if (root == 0 || this->GetVisibleChildrenCount(ILayoutContainer::Pointer(this)) <= 1) { pointlessDrop = true; } } int cursor = Geometry::GetOppositeSide(side); if (pointlessDrop) { side = Constants::NONE; } if (sourcePart) return this->CreateDropTarget(sourcePart, side, cursor, Object::Pointer(0)); else return this->CreateDropTarget(sourceContainer, side, cursor, Object::Pointer(0)); } return IDropTarget::Pointer(0); } PartSashContainer::SashContainerDropTarget::Pointer PartSashContainer::CreateDropTarget( Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart) { if (dropTarget == 0) { dropTarget = new SashContainerDropTarget(this, sourcePart, side, cursor, targetPart); } else { dropTarget->SetTarget(sourcePart, side, cursor, targetPart); } return dropTarget; } void PartSashContainer::Stack(StackablePart::Pointer newPart, IStackableContainer::Pointer container) { //this->GetControl().setRedraw(false); // Only deref the part if it is being referenced in -this- perspective Perspective::Pointer persp = page->GetActivePerspective(); PerspectiveHelper* pres = (persp != 0) ? persp->GetPresentation() : 0; if (pres != 0 && container.Cast()->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) { IWorkbenchPartReference::Pointer newPartRef = newPart.Cast ()->GetPartReference(); IViewReference::Pointer vRef = newPartRef.Cast (); if (vRef != 0) { StackablePart::Pointer fpp = pres->FindPart(vRef->GetId(), vRef->GetSecondaryId()); if (fpp != 0) { // Remove the part from old container. this->DerefPart(newPart); } } } else { // Remove the part from old container. this->DerefPart(newPart); } // Reparent part and add it to the workbook newPart->Reparent(this->GetParent()); container->Add(newPart); //getControl().setRedraw(true); } void PartSashContainer::DerefPart(StackablePart::Pointer sourcePart) { IStackableContainer::Pointer container = sourcePart->GetContainer(); if (container != 0) { container->Remove(sourcePart); if (this->IsStackType(container) && container.Cast () != 0) { if (container->GetChildren().size() == 0) { LayoutPart::Pointer stack = container.Cast (); this->Remove(stack); stack->Dispose(); } } } } std::size_t PartSashContainer::GetVisibleChildrenCount( IStackableContainer::Pointer container) { // Treat null as an empty container if (container == 0) { return 0; } IStackableContainer::ChildrenType children = container->GetChildren(); std::size_t count = 0; for (IStackableContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if (!(*iter)->IsPlaceHolder()) { count++; } } return count; } std::size_t PartSashContainer::GetVisibleChildrenCount( ILayoutContainer::Pointer container) { // Treat null as an empty container if (container == 0) { return 0; } return container->GetChildren().size(); } float PartSashContainer::GetDockingRatio(Object::Pointer /*dragged*/, IStackableContainer::Pointer /*target*/) { return 0.5f; } void PartSashContainer::DescribeLayout(std::string& buf) const { if (root == 0) { return; } // if (isZoomed()) // { // buf.append("zoomed "); //$NON-NLS-1$ // root.describeLayout(buf); // } // else { buf.append("layout "); //$NON-NLS-1$ root->DescribeLayout(buf); } } void PartSashContainer::Add(LayoutPart::Pointer child, int relationship, int left, int right, LayoutPart::Pointer relative) { if (child == 0) { return; } if (relative != 0 && !this->IsChild(relative)) { return; } if (relationship < IPageLayout::LEFT || relationship > IPageLayout::BOTTOM) { relationship = IPageLayout::LEFT; } // store info about relative positions RelationshipInfo info; info.part = child; info.relationship = relationship; info.left = left; info.right = right; info.relative = relative; this->AddChild(info); } bool PartSashContainer::AllowsAutoFocus() { return true; } void PartSashContainer::StartDeferringEvents() { LayoutPart::StartDeferringEvents(); ILayoutContainer::ChildrenType deferredChildren = children; for (ILayoutContainer::ChildrenType::iterator iter = deferredChildren.begin(); iter != deferredChildren.end(); ++iter) { (*iter)->DeferUpdates(true); } } void PartSashContainer::HandleDeferredEvents() { LayoutPart::HandleDeferredEvents(); ILayoutContainer::ChildrenType deferredChildren = children; for (ILayoutContainer::ChildrenType::iterator iter = deferredChildren.begin(); iter != deferredChildren.end(); ++iter) { (*iter)->DeferUpdates(false); } } void PartSashContainer::TestInvariants() { LayoutPart::TestInvariants(); // If we have a parent container, ensure that we are displaying the zoomed appearance iff // our parent is zoomed in on us // if (this->GetContainer() != 0) // { // Assert.isTrue((getZoomedPart() != null) == (getContainer().childIsZoomed( // this))); // } ILayoutContainer::ChildrenType childArray = this->GetChildren(); for (ILayoutContainer::ChildrenType::iterator iter = childArray.begin(); iter != childArray.end(); ++iter) { (*iter)->TestInvariants(); } // If we're zoomed, ensure that we're actually zoomed into one of our children // if (isZoomed()) // { // Assert.isTrue(children.contains(zoomedPart)); // } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSashContainer.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSashContainer.h index a2ada0f8b4..13e065f941 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSashContainer.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSashContainer.h @@ -1,704 +1,704 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPARTSASHCONTAINER_H_ #define BERRYPARTSASHCONTAINER_H_ #include "berryLayoutPart.h" #include "berryILayoutContainer.h" #include "berryIStackableContainer.h" #include "berryIDragOverListener.h" #include "berryAbstractDropTarget.h" -#include "../tweaklets/berryDnDTweaklet.h" -#include "../berryRectangle.h" +#include "tweaklets/berryDnDTweaklet.h" +#include "berryRectangle.h" -#include "../guitk/berryGuiTkIControlListener.h" +#include "guitk/berryGuiTkIControlListener.h" namespace berry { class WorkbenchPage; class PartPane; class LayoutTree; class PartStack; /** * \ingroup org_blueberry_ui_internal * * Abstract container that groups various layout * parts (possibly other containers) together as * a unit. Manages the placement and size of these * layout parts based on the location of sashes within * the container. * * GUI specializations must override the following methods * (read their documentation for implementation details): * *
    *
  • PartSashContainer */ class PartSashContainer: public LayoutPart, public ILayoutContainer, public IDragOverListener { public: berryObjectMacro(PartSashContainer); friend class LayoutTree; friend class LayoutTreeNode; friend class PageLayout; private: void* parentWidget; //LayoutPart::Pointer zoomedPart; /* Indicates if the children of a sash container should be aligned from left to right * or the other way around. This is important if one child does * not occupy all of the available space. Then the empty space * is either on the left, or on the right side. */ bool static leftToRight; protected: struct ControlListener : public GuiTk::IControlListener { ControlListener(PartSashContainer* partSashContainer); Events::Types GetEventTypes() const; void ControlResized(GuiTk::ControlEvent::Pointer e); private: PartSashContainer* partSashContainer; }; void* parent; GuiTk::IControlListener::Pointer resizeListener; SmartPointer root; WorkbenchPage* page; bool active; bool layoutDirty; /* Array of LayoutPart */ ILayoutContainer::ChildrenType children; protected: struct RelationshipInfo { LayoutPart::Pointer part; LayoutPart::Pointer relative; int relationship; /** * Preferred size for the left child (this would be the size, in pixels of the child * at the time the sash was last moved) */ int left; /** * Preferred size for the right child (this would be the size, in pixels of the child * at the time the sash was last moved) */ int right; }; private: class SashContainerDropTarget : public AbstractDropTarget { private: int side; int cursor; // This is a IStackablePart or IStackableContainer Object::Pointer targetPart; // This is a IStackablePart or IStackableContainer Object::Pointer sourcePart; PartSashContainer* partSashContainer; public: berryObjectMacro(SashContainerDropTarget); SashContainerDropTarget(PartSashContainer* partSashContainer, Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart); void SetTarget(Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart); void Drop(); DnDTweaklet::CursorType GetCursor(); Rectangle GetSnapRectangle(); }; SashContainerDropTarget::Pointer dropTarget; public: /** * Constructs a PartSashContainer with the given id under the given page * and parentWidget. * * GUI specializations must hook */ PartSashContainer(const std::string& id, WorkbenchPage* page, void* parentWidget); ~PartSashContainer(); /* (non-Javadoc) * @see org.blueberry.ui.internal.ILayoutContainer#obscuredByZoom(org.blueberry.ui.internal.LayoutPart) */ // public: bool childObscuredByZoom(LayoutPart toTest) { // LayoutPart zoomPart = getZoomedPart(); // // if (zoomPart != null && toTest != zoomPart) { // return true; // } // return isObscuredByZoom(); // } /** * Given an object associated with a drag (a PartPane or PartStack), this returns * the actual PartPanes being dragged. * * @param pane * @return */ private: std::vector > GetVisibleParts(Object::Pointer pane); /** * Find the sashs around the specified part. */ public: void FindSashes(LayoutPart::Pointer pane, PartPane::Sashes& sashes); public: /** * Add a part. */ virtual void Add(LayoutPart::Pointer child); virtual void AddPart(StackablePart::Pointer child); /** * Add a part relative to another. For compatibility only. New code should use * addEnhanced, above. * * @param child the new part to add * @param relationship one of PageLayout.TOP, PageLayout.BOTTOM, PageLayout.LEFT, or PageLayout.RIGHT * @param ratio a value between 0.0 and 1.0, indicating how much space will be allocated to the UPPER-LEFT pane * @param relative part where the new part will be attached */ virtual void Add(LayoutPart::Pointer child, int relationship, float ratio, LayoutPart::Pointer relative); protected: virtual void DropObject(const std::vector& toDrop, StackablePart::Pointer visiblePart, Object::Pointer targetPart, int side); /** * Add a new part relative to another. This should be used in place of add. * It differs as follows: *
      *
    • relationships are specified using SWT direction constants
    • *
    • the ratio applies to the newly added child -- not the upper-left child
    • *
    * * @param child new part to add to the layout * @param swtDirectionConstant one of SWT.TOP, SWT.BOTTOM, SWT.LEFT, or SWT.RIGHT * @param ratioForNewPart a value between 0.0 and 1.0 specifying how much space will be allocated for the newly added part * @param relative existing part indicating where the new child should be attached * @since 3.0 */ protected: virtual void AddEnhanced(LayoutPart::Pointer child, int swtDirectionConstant, float ratioForNewPart, LayoutPart::Pointer relative); protected: static int MeasureTree(const Rectangle& outerBounds, SmartPointer toMeasure, bool horizontal); protected: virtual void AddChild(const RelationshipInfo& info); /** * Adds the child using ratio and position attributes * from the specified placeholder without replacing * the placeholder * * FIXME: I believe there is a bug in computeRelation() * when a part is positioned relative to the editorarea. * We end up with a null relative and 0.0 for a ratio. */ protected: virtual void AddChildForPlaceholder(LayoutPart::Pointer child, LayoutPart::Pointer placeholder); /** * See ILayoutContainer#allowBorder */ public: virtual bool AllowsBorder(); /** * Notification that a child layout part has been * added to the container. Subclasses may override * this method to perform any container specific * work. */ protected: virtual void ChildAdded(LayoutPart::Pointer child); /** * Notification that a child layout part has been * removed from the container. Subclasses may override * this method to perform any container specific * work. */ protected: virtual void ChildRemoved(LayoutPart::Pointer child); /** * Returns an array with all the relation ship between the * parts. */ public: virtual std::vector ComputeRelation(); public: virtual void SetActive(bool isActive); /** * @see LayoutPart#getControl */ public: void CreateControl(void* parentWidget); /** * Subclasses override this method to specify * the composite to use to parent all children * layout parts it contains. */ protected: virtual void* CreateParent(void* parentWidget) = 0; /** * @see LayoutPart#dispose */ public: virtual void Dispose(); /** * Subclasses override this method to dispose * of any swt resources created during createParent. */ protected: virtual void DisposeParent() = 0; /** * Dispose all sashs used in this perspective. */ public: virtual void DisposeSashes(); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#setVisible(boolean) */ public: void SetVisible(bool makeVisible); /** * Return the most bottom right part or null if none. */ public: virtual LayoutPart::Pointer FindBottomRight(); /** * @see LayoutPart#getBounds */ public: Rectangle GetBounds(); /** * @see ILayoutContainer#getChildren */ public: ChildrenType GetChildren(); /** * @see LayoutPart#getControl */ public: void* GetControl(); public: virtual SmartPointer GetLayoutTree(); /** * For themes. * * @return the current WorkbenchPage. */ public: virtual SmartPointer GetPage(); /** * Returns the composite used to parent all the * layout parts contained within. */ public: virtual void* GetParent(); protected: virtual bool IsChild(LayoutPart::Pointer part); /** * Returns whether this container is zoomed. */ // public: bool IsZoomed() { // return (zoomedPart != null); // } /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#forceLayout(org.blueberry.ui.internal.LayoutPart) */ public: void ResizeChild(LayoutPart::Pointer childThatChanged); /** * Remove a part. */ public: void Remove(LayoutPart::Pointer child); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#forceLayout() */ public: void FlushLayout(); /** * Replace one part with another. */ public: void Replace(LayoutPart::Pointer oldChild, LayoutPart::Pointer newChild); private: void ResizeSashes(); /** * Returns the maximum size that can be utilized by this part if the given width and * height are available. Parts can overload this if they have a quantized set of preferred * sizes. * * @param width available horizontal space (pixels) * @return returns a new point where point.x is <= availableWidth and point.y is <= availableHeight */ public: virtual int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); public: int GetSizeFlags(bool width); /** * @see LayoutPart#setBounds */ public: void SetBounds(const Rectangle& r); /** * Zoom in on a particular layout part. * * The implementation of zoom is quite simple. When zoom occurs we create * a zoom root which only contains the zoom part. We store the old * root in unzoomRoot and then active the zoom root. When unzoom occurs * we restore the unzoomRoot and dispose the zoom root. * * Note: Method assumes we are active. */ // private: void zoomIn(LayoutPart part) { // // Sanity check. // if (isZoomed()) { // return; // } // // // Hide the sashes // root.disposeSashes(); // // // Make all parts invisible except for the zoomed part // LayoutPart[] children = getChildren(); // for (int i = 0; i < children.length; i++) { // LayoutPart child = children[i]; // child.setVisible(child == part); // } // // zoomedPart = part; // // // Notify the part that it has been zoomed // part.setZoomed(true); // // // Remember that we need to trigger a layout // layoutDirty = true; // } /** * Returns the currently zoomed part or null if none * * @return the currently zoomed part or null if none * @since 3.1 */ // public: LayoutPart getZoomedPart() { // return zoomedPart; // } // public: void childRequestZoomIn(LayoutPart toZoom) { // if (!SwtUtil.isDisposed(this.parent)) { // this.parent.setRedraw(false); // } // try { // zoomIn(toZoom); // // requestZoomIn(); // // if (layoutDirty) { // resizeSashes(); // } // } finally { // if (!SwtUtil.isDisposed(this.parent)) { // this.parent.setRedraw(true); // } // } // } // public: void childRequestZoomOut() { // if (!SwtUtil.isDisposed(this.parent)) { // this.parent.setRedraw(false); // } // try { // zoomOut(); // // requestZoomOut(); // // if (layoutDirty) { // resizeSashes(); // } // } finally { // if (!SwtUtil.isDisposed(this.parent)) { // this.parent.setRedraw(true); // } // } // } /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#setZoomed(boolean) */ // public: void setZoomed(boolean isZoomed) { // if (!isZoomed) { // zoomOut(); // } else { // if (!isZoomed()) { // LayoutPart toZoom = pickPartToZoom(); // // if (toZoom != null) { // zoomIn(toZoom); // } // } // } // super.setZoomed(isZoomed); // } // public: LayoutPart pickPartToZoom() { // return findBottomRight(); // } /** * Zoom out. * * See zoomIn for implementation details. * * Note: Method assumes we are active. */ // private: void zoomOut() { // // Sanity check. // if (!isZoomed()) { // return; // } // // LayoutPart zoomedPart = this.zoomedPart; // this.zoomedPart = null; // // Inform the part that it is no longer zoomed // zoomedPart.setZoomed(false); // // // Make all children visible // LayoutPart[] children = getChildren(); // for (int i = 0; i < children.length; i++) { // LayoutPart child = children[i]; // // child.setVisible(true); // } // // // Recreate the sashes // root.createControl(getParent()); // // // Ensure that the part being un-zoomed will have its size refreshed. // LayoutTree node = root.find(zoomedPart); // node.flushCache(); // // layoutDirty = true; // } /* (non-Javadoc) * @see org.blueberry.ui.internal.dnd.IDragOverListener#drag(org.blueberry.swt.widgets.Control, java.lang.Object, org.blueberry.swt.graphics.Point, org.blueberry.swt.graphics.Rectangle) */ public: IDropTarget::Pointer Drag(void* currentControl, Object::Pointer draggedObject, const Point& position, const Rectangle& dragRectangle); /** * @param sourcePart * @param targetPart * @param side * @param cursor * @return * @since 3.1 */ private: SashContainerDropTarget::Pointer CreateDropTarget(Object::Pointer sourcePart, int side, int cursor, Object::Pointer targetPart); /** * Returns true iff this PartSashContainer allows its parts to be stacked onto the given * container. * * @param container * @return */ public: virtual bool IsStackType(IStackableContainer::Pointer toTest) = 0; public: virtual bool IsPaneType(StackablePart::Pointer toTest) = 0; protected: virtual SmartPointer CreateStack() = 0; public: virtual void Stack(StackablePart::Pointer newPart, SmartPointer container); /** * @param container * @param visiblePart */ protected: virtual void SetVisiblePart(IStackableContainer::Pointer container, SmartPointer visiblePart) = 0; /** * @param container * @return */ protected: virtual StackablePart::Pointer GetVisiblePart( IStackableContainer::Pointer container) = 0; /** * @param sourcePart */ protected: virtual void DerefPart(StackablePart::Pointer sourcePart); protected: virtual std::size_t GetVisibleChildrenCount(IStackableContainer::Pointer container); virtual std::size_t GetVisibleChildrenCount(ILayoutContainer::Pointer container); protected: virtual float GetDockingRatio(Object::Pointer dragged, IStackableContainer::Pointer target); /** * Writes a description of the layout to the given string buffer. * This is used for drag-drop test suites to determine if two layouts are the * same. Like a hash code, the description should compare as equal iff the * layouts are the same. However, it should be user-readable in order to * help debug failed tests. Although these are english readable strings, * they should not be translated or equality tests will fail. * * @param buf */ public: void DescribeLayout(std::string& buf) const; /** * Adds a new child to the container relative to some part * * @param child * @param relationship * @param left preferred pixel size of the left/top child * @param right preferred pixel size of the right/bottom child * @param relative relative part */ protected: virtual void Add(LayoutPart::Pointer child, int relationship, int left, int right, LayoutPart::Pointer relative); /* (non-Javadoc) * @see org.blueberry.ui.internal.ILayoutContainer#isZoomed(org.blueberry.ui.internal.LayoutPart) */ // public: bool childIsZoomed(LayoutPart toTest) { // return toTest == getZoomedPart(); // } /* (non-Javadoc) * @see org.blueberry.ui.internal.ILayoutContainer#allowsAutoFocus() */ public: bool AllowsAutoFocus(); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#startDeferringEvents() */ protected: void StartDeferringEvents(); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#handleDeferredEvents() */ protected: void HandleDeferredEvents(); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#testInvariants() */ public: void TestInvariants(); }; } #endif /*BERRYPARTSASHCONTAINER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartService.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartService.h index 650b9bd9ca..083d12292f 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartService.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartService.h @@ -1,82 +1,82 @@ #ifndef BERRYPARTSERVICE_H_ #define BERRYPARTSERVICE_H_ -#include "../berryIPartService.h" +#include "berryIPartService.h" #include namespace berry { class PartService : public IPartService { private: //PartListenerList listeners = new PartListenerList(); IPartListener::Events partEvents; IWorkbenchPartReference::WeakPtr activePart; std::string debugListenersKey; std::string debugListeners2Key; /** * @param ref */ void FirePartActivated(IWorkbenchPartReference::Pointer ref); /** * @param ref */ void FirePartDeactivated(IWorkbenchPartReference::Pointer ref); public: PartService(const std::string& debugListenersKey, const std::string& debugListeners2Key); /* * (non-Javadoc) * Method declared on IPartService */ void AddPartListener(IPartListener::Pointer l); /* * (non-Javadoc) * Method declared on IPartService */ void RemovePartListener(IPartListener::Pointer l); /** * @param ref */ void FirePartBroughtToTop(IWorkbenchPartReference::Pointer ref); /** * @param ref */ void FirePartClosed(IWorkbenchPartReference::Pointer ref); void FirePartVisible(IWorkbenchPartReference::Pointer ref); void FirePartHidden(IWorkbenchPartReference::Pointer ref); void FirePartInputChanged(IWorkbenchPartReference::Pointer ref); /** * @param ref */ void FirePartOpened(IWorkbenchPartReference::Pointer ref); IWorkbenchPart::Pointer GetActivePart(); IWorkbenchPartReference::Pointer GetActivePartReference(); void SetActivePart(IWorkbenchPartReference::Pointer ref); }; } #endif /*BERRYPARTSERVICE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSite.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSite.cpp index cfba2ab7c7..de40405e4c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSite.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSite.cpp @@ -1,361 +1,361 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryPartSite.h" -#include "../berryIWorkbenchPart.h" -#include "../berryIWorkbenchPage.h" -#include "../berryIWorkbenchWindow.h" +#include "berryIWorkbenchPart.h" +#include "berryIWorkbenchPage.h" +#include "berryIWorkbenchWindow.h" #include "berryPartPane.h" -#include "../services/berryIServiceFactory.h" +#include "services/berryIServiceFactory.h" #include "berryIServiceLocatorCreator.h" #include "berryWorkbenchPartReference.h" namespace berry { //void //PartSite::RegisterContextMenu(const std::string& menuId, // const MenuManager menuManager, // const ISelectionProvider selectionProvider, // bool includeEditorInput, IWorkbenchPart::ConstPointer part, // const Collection menuExtenders) { // /* // * Check to see if the same menu manager and selection provider have // * already been used. If they have, then we can just add another menu // * identifier to the existing PopupMenuExtender. // */ // final Iterator extenderItr = menuExtenders.iterator(); // boolean foundMatch = false; // while (extenderItr.hasNext()) { // final PopupMenuExtender existingExtender = (PopupMenuExtender) extenderItr // .next(); // if (existingExtender.matches(menuManager, selectionProvider, part)) { // existingExtender.addMenuId(menuId); // foundMatch = true; // break; // } // } // // if (!foundMatch) { // menuExtenders.add(new PopupMenuExtender(menuId, menuManager, // selectionProvider, part, includeEditorInput)); // } // } PartSite::PartSite(IWorkbenchPartReference::Pointer ref, IWorkbenchPart::Pointer _part, IWorkbenchPage* _page) : partReference(ref), part(_part), page(_page), serviceLocatorOwner(new ServiceLocatorOwner(this)) { extensionID = "org.blueberry.ui.UnknownID"; //$NON-NLS-1$ extensionName = "Unknown Name"; //$NON-NLS-1$ // Initialize the service locator. IServiceLocator::Pointer parentServiceLocator(page->GetWorkbenchWindow()); IServiceLocatorCreator::Pointer slc(parentServiceLocator ->GetService(IServiceLocatorCreator::GetManifestName()).Cast()); this->serviceLocator = slc->CreateServiceLocator(IServiceLocator::WeakPtr(parentServiceLocator), IServiceFactory::Pointer(0), IDisposable::WeakPtr(serviceLocatorOwner)).Cast(); //initializeDefaultServices(); } PartSite::~PartSite() { } PartSite::ServiceLocatorOwner::ServiceLocatorOwner(PartSite* s) : site(s) { } void PartSite::ServiceLocatorOwner::Dispose() { void* control = site->GetPane()->GetControl(); if (control != 0) { site->GetPane()->DoHide(); } } void PartSite::InitializeDefaultServices() { // serviceLocator.registerService(IWorkbenchPartSite.class, this); // final Expression defaultExpression = new ActivePartExpression(part); // // final IContextService parentContextService = (IContextService) serviceLocator // .getService(IContextService.class); // final IContextService contextService = new SlaveContextService( // parentContextService, defaultExpression); // serviceLocator.registerService(IContextService.class, contextService); // // final ICommandService parentCommandService = (ICommandService) serviceLocator // .getService(ICommandService.class); // final ICommandService commandService = new SlaveCommandService( // parentCommandService, IServiceScopes.PARTSITE_SCOPE, // this); // serviceLocator.registerService(ICommandService.class, commandService); } //IActionBars //PartSite::GetActionBars() { // return actionBars; // } std::string PartSite::GetId() { return extensionID; } IWorkbenchPage::Pointer PartSite::GetPage() { return IWorkbenchPage::Pointer(page); } PartPane::Pointer PartSite::GetPane() { return partReference.Lock().Cast()->GetPane(); } IWorkbenchPart::Pointer PartSite::GetPart() { return IWorkbenchPart::Pointer(part); } IWorkbenchPartReference::Pointer PartSite::GetPartReference() { return partReference.Lock(); } std::string PartSite::GetPluginId() { return pluginID; } std::string PartSite::GetRegisteredName() { return extensionName; } ISelectionProvider::Pointer PartSite::GetSelectionProvider() { return selectionProvider; } Shell::Pointer PartSite::GetShell() { PartPane::Pointer pane = GetPane(); if (!pane) return GetWorkbenchWindow()->GetShell(); return pane->GetShell(); } IWorkbenchWindow::Pointer PartSite::GetWorkbenchWindow() { return page->GetWorkbenchWindow(); } // void // PartSite::RegisterContextMenu(const std::string& menuID, // MenuManager menuMgr, // ISelectionProvider selProvider) { // if (menuExtenders == null) { // menuExtenders = new ArrayList(1); // } // // registerContextMenu(menuID, menuMgr, selProvider, true, getPart(), // menuExtenders); // } //void //PartSite::RegisterContextMenu(MenuManager menuMgr, // ISelectionProvider selProvider) { // registerContextMenu(getId(), menuMgr, selProvider); // } //void //PartSite::GetContextMenuIds(std::vector& menuIds) { // if (menuExtenders == null) { // return new String[0]; // } // ArrayList menuIds = new ArrayList(menuExtenders.size()); // for (Iterator iter = menuExtenders.iterator(); iter.hasNext();) { // final PopupMenuExtender extender = (PopupMenuExtender) iter.next(); // menuIds.addAll(extender.getMenuIds()); // } // return (String[]) menuIds.toArray(new String[menuIds.size()]); // } //void //PartSite::SetActionBars(SubActionBars bars) { // actionBars = bars; // } void PartSite::SetConfigurationElement( IConfigurationElement::Pointer configElement) { // Get extension ID. configElement->GetAttribute("id", extensionID); //$NON-NLS-1$ // Get plugin ID. pluginID = configElement->GetContributor(); // Get extension name. std::string name; configElement->GetAttribute("name", name); //$NON-NLS-1$ if (name != "") { extensionName = name; } } void PartSite::SetPluginId(const std::string& pluginId) { this->pluginID = pluginId; } void PartSite::SetId(const std::string& id) { extensionID = id; } void PartSite::SetPart(IWorkbenchPart::Pointer newPart) { part = newPart; } void PartSite::SetRegisteredName(const std::string& name) { extensionName = name; } void PartSite::SetSelectionProvider(ISelectionProvider::Pointer provider) { selectionProvider = provider; } /* * @see IWorkbenchPartSite#getKeyBindingService() * * TODO deprecated: use IHandlerService instead */ //IKeyBindingService //PartSite::GetKeyBindingService() { // if (keyBindingService == null) { // keyBindingService = new KeyBindingService(this); // // // TODO why is this here? and it should be using HandlerSubmissions // // directly.. // if (this instanceof EditorSite) { // EditorActionBuilder.ExternalContributor contributor = (EditorActionBuilder.ExternalContributor) ((EditorSite) this) // .getExtensionActionBarContributor(); // // if (contributor != null) { // ActionDescriptor[] actionDescriptors = contributor // .getExtendedActions(); // // if (actionDescriptors != null) { // for (int i = 0; i < actionDescriptors.length; i++) { // ActionDescriptor actionDescriptor = actionDescriptors[i]; // // if (actionDescriptor != null) { // IAction action = actionDescriptors[i] // .getAction(); // // if (action != null // && action.getActionDefinitionId() != null) { // keyBindingService.registerAction(action); // } // } // } // } // } // } // } // // return keyBindingService; // } std::string PartSite::GetInitialScopeId() { return ""; } void* PartSite::GetAdapterImpl(const std::type_info& /*adapter*/) const { // if (IWorkbenchSiteProgressService.class == adapter) { // return getSiteProgressService(); // } // // if (IWorkbenchPartTestable.class == adapter) { // return new WorkbenchPartTestable(this); // } // // return Platform.getAdapterManager().getAdapter(this, adapter); return 0; } //void //PartSite::ActivateActionBars(bool forceVisibility) { // if (actionBars != null) { // actionBars.activate(forceVisibility); // } // } //void //PartSite::DeactivateActionBars(bool forceHide) { // if (actionBars != null) { // actionBars.deactivate(forceHide); // } // } //WorkbenchSiteProgressService //PartSite::GetSiteProgressService() { // if (progressService == null) { // progressService = new WorkbenchSiteProgressService(this); // } // return progressService; // } Object::Pointer PartSite::GetService(const std::string& api) { return serviceLocator->GetService(api); } bool PartSite::HasService(const std::string& api) const { return serviceLocator->HasService(api); } std::string PartSite::ToString() { std::string buffer = "PartSite(id=" + this->GetId() + ",pluginId=" + this->GetPluginId() + ",registeredName=" + this->GetRegisteredName() + ")"; return buffer; } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSite.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSite.h index e7546481ea..0797f3260d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSite.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartSite.h @@ -1,311 +1,311 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPARTSITE_H_ #define BERRYPARTSITE_H_ #include #include "berryServiceLocator.h" -#include "../berryIWorkbenchPartSite.h" -#include "../berryIWorkbenchPartReference.h" -#include "../berryISelectionProvider.h" +#include "berryIWorkbenchPartSite.h" +#include "berryIWorkbenchPartReference.h" +#include "berryISelectionProvider.h" namespace berry { struct IWorkbenchPart; struct IWorkbenchPage; struct IWorkbenchWindow; 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); /** * 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 std::string& menuId, // const MenuManager menuManager, // const ISelectionProvider selectionProvider, // bool includeEditorInput, IWorkbenchPart::ConstPointer part, // const Collection menuExtenders); private: IWorkbenchPartReference::WeakPtr partReference; WeakPointer part; IWorkbenchPage* page; std::string extensionID; std::string pluginID; std::string 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; 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 std::string GetId(); /** * 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 std::string GetPluginId(); /** * Returns the registered name for this part. */ public: virtual std::string GetRegisteredName(); /** * 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 std::string& 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(std::vector& 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 std::string& pluginId); /** * Sets the part registry extension ID. * * @param id * the registry extension ID */ protected: virtual void SetId(const std::string& 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 std::string& 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 std::string 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::Pointer GetService(const std::string& api); public: bool HasService(const std::string& 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 std::string ToString(); }; } // namespace berry #endif /*BERRYPARTSITE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartStack.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartStack.cpp index bb1dd25b63..1e035671c3 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartStack.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartStack.cpp @@ -1,1608 +1,1608 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryPartStack.h" #include "berryPerspective.h" #include "berryPresentationFactoryUtil.h" #include "berryWorkbenchPlugin.h" #include "berryPresentationSerializer.h" #include "berryDragUtil.h" #include "berryEditorAreaHelper.h" #include "berryPerspectiveHelper.h" #include "berryWorkbenchConstants.h" -#include "../berryXMLMemento.h" +#include "berryXMLMemento.h" -#include "../berryIWorkbenchPartConstants.h" -#include "../berryGeometry.h" +#include "berryIWorkbenchPartConstants.h" +#include "berryGeometry.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" +#include "tweaklets/berryGuiWidgetsTweaklet.h" #include #include namespace berry { const int PartStack::PROP_SELECTION = 0x42; PartStack::PartStackDropResult::Pointer PartStack::dropResult( new PartStack::PartStackDropResult()); void PartStack::PartStackDropResult::SetTarget(PartStack::Pointer stack, PartPane::Pointer pane, StackDropResult::Pointer result) { this->pane = pane; this->dropResult = result; this->stack = stack; } void PartStack::PartStackDropResult::Drop() { // If we're dragging a pane over itself do nothing //if (dropResult.getInsertionPoint() == pane.getPresentablePart()) { return; }; Object::Pointer cookie; if (dropResult != 0) { cookie = dropResult->GetCookie(); } PartPane::Pointer pane(this->pane); PartStack::Pointer stack(this->stack); // Handle cross window drops by opening a new editor if (pane->GetPartReference().Cast () != 0) { IEditorReference::Pointer editorRef = pane->GetPartReference().Cast< IEditorReference> (); if (pane->GetWorkbenchWindow() != stack->GetWorkbenchWindow()) { try { IEditorInput::Pointer input = editorRef->GetEditorInput(); // Close the old editor and capture the actual closed state incase of a 'cancel' bool editorClosed = pane->GetPage()->CloseEditor(editorRef, true); // Only open open the new editor if the old one closed if (editorClosed) stack->GetPage()->OpenEditor(input, editorRef->GetId()); return; } catch (PartInitException& e) { //e.printStackTrace(); BERRY_ERROR << e.displayText(); } } } if (pane->GetContainer() != stack) { // Moving from another stack stack->DerefPart(pane); pane->Reparent(stack->GetParent()); stack->Add(pane, cookie); stack->SetSelection(pane); pane->SetFocus(); } else if (cookie != 0) { // Rearranging within this stack stack->GetPresentation()->MovePart(stack->GetPresentablePart(pane), cookie); } } DnDTweaklet::CursorType PartStack::PartStackDropResult::GetCursor() { return DnDTweaklet::CURSOR_CENTER; } Rectangle PartStack::PartStackDropResult::GetSnapRectangle() { if (dropResult == 0) { return DragUtil::GetDisplayBounds(stack.Lock()->GetControl()); } return dropResult->GetSnapRectangle(); } PartStack::MyStackPresentationSite::MyStackPresentationSite(PartStack* stack) : partStack(stack) { } void PartStack::MyStackPresentationSite::Close(IPresentablePart::Pointer part) { partStack->Close(part); } void PartStack::MyStackPresentationSite::Close(const std::vector< IPresentablePart::Pointer>& parts) { partStack->Close(parts); } void PartStack::MyStackPresentationSite::DragStart( IPresentablePart::Pointer beingDragged, Point& initialLocation, bool keyboard) { partStack->DragStart(beingDragged, initialLocation, keyboard); } void PartStack::MyStackPresentationSite::DragStart(Point& initialLocation, bool keyboard) { partStack->DragStart(IPresentablePart::Pointer(0), initialLocation, keyboard); } bool PartStack::MyStackPresentationSite::IsPartMoveable( IPresentablePart::Pointer part) { return partStack->IsMoveable(part); } void PartStack::MyStackPresentationSite::SelectPart( IPresentablePart::Pointer toSelect) { partStack->PresentationSelectionChanged(toSelect); } bool PartStack::MyStackPresentationSite::SupportsState(int state) { return partStack->SupportsState(state); } void PartStack::MyStackPresentationSite::SetState(int newState) { partStack->SetState(newState); } IPresentablePart::Pointer PartStack::MyStackPresentationSite::GetSelectedPart() { return partStack->GetSelectedPart(); } // void AddSystemActions(IMenuManager menuManager) { // PartStack.this.addSystemActions(menuManager); // } bool PartStack::MyStackPresentationSite::IsStackMoveable() { return partStack->CanMoveFolder(); } void PartStack::MyStackPresentationSite::FlushLayout() { partStack->FlushLayout(); } PartStack::PresentableVector PartStack::MyStackPresentationSite::GetPartList() { return partStack->GetPresentableParts(); } std::string PartStack::MyStackPresentationSite::GetProperty( const std::string& id) { return partStack->GetProperty(id); } PartStack::PartStack(WorkbenchPage* p, bool allowsStateChanges, int appear, IPresentationFactory* fac) : LayoutPart("PartStack"), page(p), isActive(true), allowStateChanges( allowsStateChanges), appearance(appear), ignoreSelectionChanges(false), factory(fac) { std::stringstream buf; buf << "PartStack@" << this; this->SetID(buf.str()); presentationSite = new MyStackPresentationSite(this); } bool PartStack::IsMoveable(IPresentablePart::Pointer part) { PartPane::Pointer pane = this->GetPaneFor(part); Perspective::Pointer perspective = this->GetPage()->GetActivePerspective(); if (perspective == 0) { // Shouldn't happen -- can't have a ViewStack without a // perspective return true; } IWorkbenchPartReference::Pointer partRef = pane->GetPartReference(); if (partRef.Cast () != 0) return perspective->IsMoveable(partRef.Cast ()); return true; } bool PartStack::SupportsState(int /*newState*/) { if (page->IsFixedLayout()) { return false; } return allowStateChanges; } bool PartStack::CanMoveFolder() { if (appearance == PresentationFactoryUtil::ROLE_EDITOR) return true; Perspective::Pointer perspective = this->GetPage()->GetActivePerspective(); if (perspective == 0) { // Shouldn't happen -- can't have a ViewStack without a // perspective return false; } // We need to search if one of the presentations is not moveable // if that's the case the whole folder should not be moveable IStackPresentationSite::Pointer presenationSite; if ((presenationSite = this->GetPresentationSite()) != 0) { std::list parts = presenationSite->GetPartList(); for (std::list::iterator iter = parts.begin(); iter != parts.end(); ++iter) { if (!presenationSite->IsPartMoveable(*iter)) { return false; } } } return !perspective->IsFixedLayout(); } void PartStack::DerefPart(StackablePart::Pointer toDeref) { if (appearance == PresentationFactoryUtil::ROLE_EDITOR) EditorAreaHelper::DerefPart(toDeref); else this->GetPage()->GetActivePerspective()->GetPresentation()->DerefPart( toDeref); } bool PartStack::AllowsDrop(PartPane::Pointer part) { PartStack::Pointer stack = part->GetContainer().Cast (); if (stack != 0) { if (stack->appearance == this->appearance) return true; } return false; } void PartStack::AddListener(IPropertyChangeListener::Pointer listener) { propEvents.AddListener(listener); } void PartStack::RemoveListener(IPropertyChangeListener::Pointer listener) { propEvents.RemoveListener(listener); } int PartStack::GetAppearance() const { return appearance; } std::string PartStack::GetID() const { return LayoutPart::GetID(); } bool PartStack::IsStandalone() { return (appearance == PresentationFactoryUtil::ROLE_STANDALONE || appearance == PresentationFactoryUtil::ROLE_STANDALONE_NOTITLE); } IPresentablePart::Pointer PartStack::GetSelectedPart() { return presentationCurrent.Cast (); } IStackPresentationSite::Pointer PartStack::GetPresentationSite() { return presentationSite; } void PartStack::TestInvariants() { void* focusControl = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetFocusControl(); bool currentFound = false; ChildVector children = this->GetChildren(); for (ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { StackablePart::Pointer child = *iter; // No 0 children allowed poco_assert(child != 0) ; // "0 children are not allowed in PartStack" // Ensure that all the PartPanes have an associated presentable part IPresentablePart::Pointer part = this->GetPresentablePart(child); if (!child->IsPlaceHolder()) { poco_assert(part != 0); // "All PartPanes must have a non-0 IPresentablePart" } // Ensure that the child's backpointer points to this stack IStackableContainer::Pointer childContainer = child->GetContainer(); // Disable tests for placeholders -- PartPlaceholder backpointers don't // obey the usual rules -- they sometimes point to a container placeholder // for this stack instead of the real stack. if (!child->IsPlaceHolder()) { // If the widgetry exists, the child's backpointer must point to us poco_assert(childContainer.GetPointer() == this); // "PartStack has a child that thinks it has a different parent" // If this child has focus, then ensure that it is selected and that we have // the active appearance. if (focusControl && Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsChild(child->GetControl(), focusControl)) { poco_assert(child == current); // "The part with focus is not the selected part" // focus check commented out since it fails when focus workaround in LayoutPart.setVisible is not present // Assert.isTrue(getActive() == StackPresentation.AS_ACTIVE_FOCUS); } } // Ensure that "current" points to a valid child if (child == current) { currentFound = true; } // Test the child's internal state child->TestInvariants(); } // If we have at least one child, ensure that the "current" pointer points to one of them if (this->GetPresentableParts().size()> 0) { poco_assert(currentFound); StackPresentation::Pointer presentation = this->GetPresentation(); // If the presentation controls have focus, ensure that we have the active appearance if (focusControl && Tweaklets::Get(GuiWidgetsTweaklet::KEY)->IsChild(presentation->GetControl(), focusControl)) { poco_assert(this->GetActive() == StackPresentation::AS_ACTIVE_FOCUS); // "The presentation has focus but does not have the active appearance" } } // Check to that we're displaying the zoomed icon iff we're actually maximized //poco_assert((this->GetState() == IStackPresentationSite::STATE_MAXIMIZED) // == (this->GetContainer() != 0 && this->GetContainer()->ChildIsZoomed(this))); } void PartStack::DescribeLayout(std::string& buf) const { int activeState = this->GetActive(); if (activeState == StackPresentation::AS_ACTIVE_FOCUS) { buf.append("active "); //$NON-NLS-1$ } else if (activeState == StackPresentation::AS_ACTIVE_NOFOCUS) { buf.append("active_nofocus "); //$NON-NLS-1$ } buf.append("("); //$NON-NLS-1$ ChildVector children = this->GetChildren(); int visibleChildren = 0; for (ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { StackablePart::Pointer next = *iter; if (!next->IsPlaceHolder()) { if (iter != children.begin()) { buf.append(", "); //$NON-NLS-1$ } if (next == requestedCurrent) { buf.append("*"); //$NON-NLS-1$ } next->DescribeLayout(buf); visibleChildren++; } } buf.append(")"); //$NON-NLS-1$ } void PartStack::Add(StackablePart::Pointer child) { this->Add(child, Object::Pointer(0)); } void PartStack::Add(StackablePart::Pointer newChild, Object::Pointer cookie) { children.push_back(newChild); // Fix for bug 78470: if(newChild->GetContainer().Cast() == 0) { newChild->SetContainer(IStackableContainer::Pointer(this)); } this->ShowPart(newChild, cookie); } bool PartStack::AllowsAdd(StackablePart::Pointer /*toAdd*/) { return !this->IsStandalone(); } bool PartStack::AllowsAutoFocus() { if (presentationSite->GetState() == IStackPresentationSite::STATE_MINIMIZED) { return false; } return LayoutPart::AllowsAutoFocus(); } void PartStack::Close(const std::vector& parts) { for (unsigned int idx = 0; idx < parts.size(); idx++) { IPresentablePart::Pointer part = parts[idx]; this->Close(part); } } void PartStack::Close(IPresentablePart::Pointer part) { if (!presentationSite->IsCloseable(part)) { return; } PartPane::Pointer pane = this->GetPaneFor(part); if (pane != 0) { pane->DoHide(); } } IPresentationFactory* PartStack::GetFactory() { if (factory != 0) { return factory; } return WorkbenchPlugin::GetDefault()->GetPresentationFactory(); } void PartStack::CreateControl(void* parent) { if (this->GetPresentation() != 0) { return; } IPresentationFactory* factory = this->GetFactory(); PresentableVector partList = this->GetPresentableParts(); std::vector partVec(partList.begin(), partList.end()); PresentationSerializer serializer(partVec); StackPresentation::Pointer presentation = PresentationFactoryUtil ::CreatePresentation(factory, appearance, parent, presentationSite, &serializer, savedPresentationState); this->CreateControl(parent, presentation); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->MoveBelow(this->GetControl(), 0); } IDropTarget::Pointer PartStack::GetDropTarget(Object::Pointer draggedObject, const Point& position) { if (draggedObject.Cast() == 0) { return IDropTarget::Pointer(0); } PartPane::Pointer pane = draggedObject.Cast(); if (this->IsStandalone() || !this->AllowsDrop(pane)) { return IDropTarget::Pointer(0); } // Don't allow views to be dragged between windows bool differentWindows = pane->GetWorkbenchWindow() != this->GetWorkbenchWindow(); bool editorDropOK = ((pane->GetPartReference().Cast() != 0) && pane->GetWorkbenchWindow()->GetWorkbench() == this->GetWorkbenchWindow()->GetWorkbench()); if (differentWindows && !editorDropOK) { return IDropTarget::Pointer(0); } StackDropResult::Pointer dropResult = this->GetPresentation()->DragOver( this->GetControl(), position); if (dropResult == 0) { return IDropTarget::Pointer(0); } return this->CreateDropTarget(pane, dropResult); } void PartStack::SetBounds(const Rectangle& r) { if (this->GetPresentation() != 0) { this->GetPresentation()->SetBounds(r); } } IDropTarget::Pointer PartStack::CreateDropTarget(PartPane::Pointer pane, StackDropResult::Pointer result) { dropResult->SetTarget(PartStack::Pointer(this), pane, result); return dropResult; } void PartStack::SetActive(bool isActive) { this->isActive = isActive; // Add all visible children to the presentation for(ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { (*iter)->SetContainer(isActive ? IStackableContainer::Pointer(this) : IStackableContainer::Pointer(0)); } for (PresentableVector::iterator iter = presentableParts.begin(); iter != presentableParts.end(); ++iter) { PresentablePart::Pointer next = iter->Cast(); next->EnableInputs(isActive); next->EnableOutputs(isActive); } } void PartStack::CreateControl(void* /*parent*/, StackPresentation::Pointer presentation) { poco_assert(this->GetPresentation() == 0); if (presentationSite->GetPresentation() != 0) { return; } presentationSite->SetPresentation(presentation); // Add all visible children to the presentation // Use a copy of the current set of children to avoid a ConcurrentModificationException // if a part is added to the same stack while iterating over the children (bug 78470) ChildVector childParts(children); for (ChildVector::iterator iter = childParts.begin(); iter != childParts.end(); ++iter) { this->ShowPart(*iter, Object::Pointer(0)); } if (savedPresentationState != 0) { PresentableVector partList = this->GetPresentableParts(); std::vector partVec(partList.begin(), partList.end()); PresentationSerializer serializer(partVec); presentation->RestoreState(&serializer, savedPresentationState); } //void* ctrl = this->GetPresentation()->GetControl(); //TODO control setData ? //ctrl.setData(this); // We should not have a placeholder selected once we've created the widgetry if (requestedCurrent != 0 && requestedCurrent->IsPlaceHolder()) { requestedCurrent = 0; this->UpdateContainerVisibleTab(); } this->RefreshPresentationSelection(); } void PartStack::SavePresentationState() { if (this->GetPresentation() == 0) { return; } {// Save the presentation's state before disposing it XMLMemento::Pointer memento = XMLMemento ::CreateWriteRoot(WorkbenchConstants::TAG_PRESENTATION); memento->PutString(WorkbenchConstants::TAG_ID, this->GetFactory()->GetId()); std::list parts(this->GetPresentableParts()); PresentationSerializer serializer(std::vector(parts.begin(), parts.end())); this->GetPresentation()->SaveState(&serializer, memento); // Store the memento in savedPresentationState savedPresentationState = memento; } } PartStack::~PartStack() { //BERRY_INFO << "DELETING PARTSTACK"; } void PartStack::Dispose() { if (this->GetPresentation() == 0) { return; } this->SavePresentationState(); // for (PresentableVector::iterator iter = presentableParts.begin(); // iter != presentableParts.end(); ++iter) // { // iter->Cast()->Dispose(); // } presentableParts.clear(); presentationCurrent = 0; current = 0; this->FireInternalPropertyChange(PROP_SELECTION); } void PartStack::FindSashes(PartPane::Sashes& sashes) { ILayoutContainer::Pointer container = this->GetContainer(); if (container != 0) { container->FindSashes(LayoutPart::Pointer(this), sashes); } } Rectangle PartStack::GetBounds() { if (this->GetPresentation() == 0) { return Rectangle(0, 0, 0, 0); } return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl()); } std::list PartStack::GetChildren() const { return children; } void* PartStack::GetControl() { StackPresentation::Pointer presentation = this->GetPresentation(); if (presentation == 0) { return 0; } return presentation->GetControl(); } /** * Answer the number of children. */ PartStack::ChildVector::size_type PartStack::GetItemCount() { if (this->GetPresentation() == 0) { return children.size(); } return this->GetPresentableParts().size(); } PartPane::Pointer PartStack::GetPaneFor(IPresentablePart::Pointer part) { if (part == 0 || part.Cast() == 0) { return PartPane::Pointer(0); } return part.Cast()->GetPane(); } void* PartStack::GetParent() { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(this->GetControl()); } PartStack::PresentableVector PartStack::GetPresentableParts() { return presentableParts; } PresentablePart::Pointer PartStack::GetPresentablePart(StackablePart::Pointer pane) { for (PresentableVector::iterator iter = presentableParts.begin(); iter != presentableParts.end(); ++iter) { PresentablePart::Pointer part = iter->Cast(); if (part->GetPane() == pane) { return part; } } return PresentablePart::Pointer(0); } StackPresentation::Pointer PartStack::GetPresentation() { return presentationSite->GetPresentation(); } StackablePart::Pointer PartStack::GetSelection() { return current; } void PartStack::PresentationSelectionChanged(IPresentablePart::Pointer newSelection) { // Ignore selection changes that occur as a result of removing a part if (ignoreSelectionChanges) { return; } PartPane::Pointer newPart = this->GetPaneFor(newSelection); // This method should only be called on objects that are already in the layout poco_assert(newPart != 0); if (newPart == requestedCurrent) { return; } this->SetSelection(newPart); if (newPart != 0) { newPart->SetFocus(); } } void PartStack::Remove(StackablePart::Pointer child) { IPresentablePart::Pointer presentablePart = this->GetPresentablePart(child); // Need to remove it from the list of children before notifying the presentation // since it may setVisible(false) on the part, leading to a partHidden notification, // during which findView must not find the view being removed. See bug 60039. children.remove(child); StackPresentation::Pointer presentation = this->GetPresentation(); if (presentablePart != 0 && presentation != 0) { ignoreSelectionChanges = true; presentableParts.remove(presentablePart); presentation->RemovePart(presentablePart); presentablePart = 0; ignoreSelectionChanges = false; } if (this->GetPresentation() != 0) { child->SetContainer(IStackableContainer::Pointer(0)); } if (child == requestedCurrent) { this->UpdateContainerVisibleTab(); } } void PartStack::Reparent(void* newParent) { void* control = this->GetControl(); GuiWidgetsTweaklet* tweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if ((control == 0) || (tweaklet->GetParent(control) == newParent) || !tweaklet->IsReparentable(control)) { return; } LayoutPart::Reparent(newParent); for(ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { (*iter)->Reparent(newParent); } } void PartStack::Replace(StackablePart::Pointer oldChild, StackablePart::Pointer newChild) { ChildVector::iterator loc = std::find(children.begin(), children.end(), oldChild); int idx = 0; int numPlaceholders = 0; //subtract the number of placeholders still existing in the list //before this one - they wont have parts. for (ChildVector::iterator iter = children.begin(); iter != loc; ++iter, ++idx) { if ((*iter)->IsPlaceHolder()) { numPlaceholders++; } } ObjectInt::Pointer cookie(new ObjectInt(idx - numPlaceholders)); children.insert(loc, newChild); this->ShowPart(newChild, cookie); if (oldChild == requestedCurrent && newChild.Cast() != 0) { this->SetSelection(newChild.Cast()); } this->Remove(oldChild); } int PartStack::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel) { return this->GetPresentation()->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredParallel); } int PartStack::GetSizeFlags(bool horizontal) { StackPresentation::Pointer presentation = this->GetPresentation(); if (presentation != 0) { return presentation->GetSizeFlags(horizontal); } return 0; } bool PartStack::RestoreState(IMemento::Pointer memento) { // Read the active tab. std::string activeTabID; memento->GetString(WorkbenchConstants::TAG_ACTIVE_PAGE_ID, activeTabID); // Read the page elements. std::vector children = memento->GetChildren(WorkbenchConstants::TAG_PAGE); // Loop through the page elements. for (std::size_t i = 0; i < children.size(); i++) { // Get the info details. IMemento::Pointer childMem = children[i]; std::string partID; childMem->GetString(WorkbenchConstants::TAG_CONTENT, partID); // Create the part. StackablePart::Pointer part(new PartPlaceholder(partID)); part->SetContainer(IStackableContainer::Pointer(this)); this->Add(part); //1FUN70C: ITPUI:WIN - Shouldn't set Container when not active //part.setContainer(this); if (partID == activeTabID) { this->SetSelection(part); // Mark this as the active part. //current = part; } } //IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); //boolean useNewMinMax = preferenceStore.getBoolean(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); int expanded; if (memento->GetInteger(WorkbenchConstants::TAG_EXPANDED, expanded)) { //StartupThreading.runWithoutExceptions(new StartupRunnable() // { // void runWithException() throws Throwable // { SetState(expanded != IStackPresentationSite::STATE_MINIMIZED ? IStackPresentationSite::STATE_RESTORED : IStackPresentationSite::STATE_MINIMIZED); // } // }); } else { SetState(IStackPresentationSite::STATE_RESTORED); } int appearance; if (memento->GetInteger(WorkbenchConstants::TAG_APPEARANCE, appearance)) { this->appearance = appearance; } // Determine if the presentation has saved any info here savedPresentationState = 0; std::vector presentationMementos(memento ->GetChildren(WorkbenchConstants::TAG_PRESENTATION)); for (std::size_t idx = 0; idx < presentationMementos.size(); idx++) { IMemento::Pointer child = presentationMementos[idx]; std::string id; child->GetString(WorkbenchConstants::TAG_ID, id); if (id == GetFactory()->GetId()) { savedPresentationState = child; break; } } IMemento::Pointer propertiesState = memento->GetChild(WorkbenchConstants::TAG_PROPERTIES); if (propertiesState) { std::vector props(propertiesState->GetChildren(WorkbenchConstants::TAG_PROPERTY)); for (std::size_t i = 0; i < props.size(); i++) { std::string id = props[i]->GetID(); properties.insert(std::make_pair(id, props[i]->GetTextData())); } } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", 0); //$NON-NLS-1$ return true; } void PartStack::SetVisible(bool makeVisible) { void* ctrl = this->GetControl(); bool useShortcut = makeVisible || !isActive; if (ctrl != 0 && useShortcut) { if (makeVisible == Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetVisible(ctrl)) { return; } } if (makeVisible) { for (PresentableVector::iterator iter = presentableParts.begin(); iter != presentableParts.end(); ++iter) { PresentablePart::Pointer next = iter->Cast(); next->EnableInputs(isActive); next->EnableOutputs(isActive); } } LayoutPart::SetVisible(makeVisible); StackPresentation::Pointer presentation = this->GetPresentation(); if (presentation != 0) { presentation->SetVisible(makeVisible); } if (!makeVisible) { for (PresentableVector::iterator iter = presentableParts.begin(); iter != presentableParts.end(); ++iter) { PresentablePart::Pointer next = iter->Cast(); next->EnableInputs(false); } } } bool PartStack::SaveState(IMemento::Pointer memento) { if (GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) { // Save the active tab. if (requestedCurrent) { memento->PutString(WorkbenchConstants::TAG_ACTIVE_PAGE_ID, requestedCurrent ->GetCompoundId()); } // Write out the presentable parts (in order) Poco::HashSet cachedIds; PartStack::PresentableVector pparts(GetPresentableParts()); for (PartStack::PresentableVector::iterator ppIter = pparts.begin(); ppIter != pparts.end(); ++ppIter) { PresentablePart::Pointer presPart = ppIter->Cast(); IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_PAGE); PartPane::Pointer part = presPart->GetPane(); std::string tabText = part->GetPartReference()->GetPartName(); childMem->PutString(WorkbenchConstants::TAG_LABEL, tabText); childMem->PutString(WorkbenchConstants::TAG_CONTENT, presPart->GetPane()->GetPlaceHolderId()); // Cache the id so we don't write it out later cachedIds.insert(presPart->GetPane()->GetPlaceHolderId()); } for (ChildVector::iterator iter = children.begin(); iter != children.end(); ++iter) { StackablePart::Pointer next = *iter; PartPane::Pointer part; if (part = next.Cast()) { // Have we already written it out? if (cachedIds.find(part->GetPlaceHolderId()) != cachedIds.end()) continue; } IMemento::Pointer childMem = memento ->CreateChild(WorkbenchConstants::TAG_PAGE); std::string tabText = "LabelNotFound"; if (part) { tabText = part->GetPartReference()->GetPartName(); } childMem->PutString(WorkbenchConstants::TAG_LABEL, tabText); childMem->PutString(WorkbenchConstants::TAG_CONTENT, next->GetId()); } } // IPreferenceStore preferenceStore = PrefUtil.getAPIPreferenceStore(); // boolean useNewMinMax = preferenceStore.getBoolean(IWorkbenchPreferenceConstants.ENABLE_NEW_MIN_MAX); // if (useNewMinMax) // { memento->PutInteger(WorkbenchConstants::TAG_EXPANDED, presentationSite->GetState()); // } // else // { // memento // .putInteger( // IWorkbenchConstants.TAG_EXPANDED, // (presentationSite.getState() == IStackPresentationSite.STATE_MINIMIZED) ? IStackPresentationSite.STATE_MINIMIZED // : IStackPresentationSite.STATE_RESTORED); // } memento->PutInteger(WorkbenchConstants::TAG_APPEARANCE, appearance); this->SavePresentationState(); if (savedPresentationState) { IMemento::Pointer presentationState = memento ->CreateChild(WorkbenchConstants::TAG_PRESENTATION); presentationState->PutMemento(savedPresentationState); } if (!properties.empty()) { IMemento::Pointer propertiesState = memento->CreateChild(WorkbenchConstants::TAG_PROPERTIES); for (std::map::iterator iterator = properties.begin(); iterator != properties.end(); ++iterator) { if (iterator->second.empty()) continue; IMemento::Pointer prop = propertiesState->CreateChild(WorkbenchConstants::TAG_PROPERTY, iterator->first); prop->PutTextData(iterator->second); } } //return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, 0, "", 0); return true; } WorkbenchPage::Pointer PartStack::GetPage() { // WorkbenchWindow::Pointer window = this->GetWorkbenchWindow().Cast(); // // if (window == 0) // { // return 0; // } // // return window->GetActivePage().Cast(); return WorkbenchPage::Pointer(page); } void PartStack::SetActive(int activeState) { // if (activeState == StackPresentation::AS_ACTIVE_FOCUS && isMinimized) // { // setMinimized(false); // } presentationSite->SetActive(activeState); } int PartStack::GetActive() const { return presentationSite->GetActive(); } void PartStack::SetSelection(StackablePart::Pointer part) { if (part == requestedCurrent) { return; } requestedCurrent = part; this->RefreshPresentationSelection(); } void PartStack::UpdateActions(PresentablePart::Pointer /*current*/) { } void PartStack::HandleDeferredEvents() { LayoutPart::HandleDeferredEvents(); this->RefreshPresentationSelection(); } void PartStack::RefreshPresentationSelection() { // If deferring UI updates, exit. if (this->IsDeferred()) { return; } // If the presentation is already displaying the desired part, then there's nothing // to do. if (current == requestedCurrent) { return; } StackPresentation::Pointer presentation = this->GetPresentation(); if (presentation != 0) { presentationCurrent = this->GetPresentablePart(requestedCurrent); // this->UupdateActions(presentationCurrent); if (presentationCurrent != 0 && presentation != 0) { requestedCurrent->CreateControl(this->GetParent()); GuiWidgetsTweaklet* tweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if (tweaklet->GetParent(requestedCurrent->GetControl()) != tweaklet->GetParent(this->GetControl())) { requestedCurrent->Reparent(tweaklet->GetParent(this->GetControl())); } presentation->SelectPart(presentationCurrent); } // Update the return value of getVisiblePart current = requestedCurrent; this->FireInternalPropertyChange(PROP_SELECTION); } } int PartStack::GetState() { return presentationSite->GetState(); } void PartStack::SetState(const int newState) { int oldState = presentationSite->GetState(); if (!this->SupportsState(newState) || newState == oldState) { return; } // WorkbenchWindow::Pointer wbw = this->GetPage()->GetWorkbenchWindow().Cast(); // if (wbw == 0 || wbw->GetShell() == 0 || wbw->GetActivePage() == 0) // return; // // WorkbenchPage::Pointer page = wbw->GetActivePage(); // // bool useNewMinMax = Perspective::UseNewMinMax(page->GetActivePerspective()); // // // we have to fiddle with the zoom behavior to satisfy Intro req's // // by usning the old zoom behavior for its stack // if (newState == IStackPresentationSite::STATE_MAXIMIZED) // useNewMinMax = useNewMinMax; // && !this->IsIntroInStack(); // else if (newState == IStackPresentationSite::STATE_RESTORED) // { // PartStack::Pointer maxStack = page->GetActivePerspective()->GetPresentation()->GetMaximizedStack(); // useNewMinMax = useNewMinMax && maxStack == this; // } // // if (useNewMinMax) // { // //StartupThreading.runWithoutExceptions(new StartupRunnable() // // { // // void runWithException() throws Throwable // // { // wbw->GetPageComposite()->SetRedraw(false); // try // { // if (newState == IStackPresentationSite::STATE_MAXIMIZED) // { // smartZoom(); // } // else if (oldState == IStackPresentationSite::STATE_MAXIMIZED) // { // smartUnzoom(); // } // // if (newState == IStackPresentationSite::STATE_MINIMIZED) // { // setMinimized(true); // } // // wbw.getPageComposite().setRedraw(true); // // // Force a redraw (fixes Mac refresh) // wbw.getShell().redraw(); // // } // catch (...) // { // wbw.getPageComposite().setRedraw(true); // // // Force a redraw (fixes Mac refresh) // wbw.getShell().redraw(); // } // // this->SetPresentationState(newState); // // } // // }); // } // else // { //// bool minimized = (newState == IStackPresentationSite::STATE_MINIMIZED); //// this->SetMinimized(minimized); //// //// if (newState == IStackPresentationSite::STATE_MAXIMIZED) //// { //// requestZoomIn(); //// } //// else if (oldState == IStackPresentationSite::STATE_MAXIMIZED) //// { //// requestZoomOut(); //// //// if (newState == IStackPresentationSite::STATE_MINIMIZED) //// setMinimized(true); //// } // } } void PartStack::ShowPart(StackablePart::Pointer part, Object::Pointer cookie) { if (this->GetPresentation() == 0) { return; } if (part->IsPlaceHolder()) { part->SetContainer(IStackableContainer::Pointer(this)); return; } if (part.Cast() == 0) { WorkbenchPlugin::Log("Incorrect part " + part->GetId() + "contained in a part stack"); return; } PartPane::Pointer pane = part.Cast(); PresentablePart::Pointer presentablePart(new PresentablePart(pane, Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetParent(this->GetControl()))); presentableParts.push_back(presentablePart); if (isActive) { part->SetContainer(IStackableContainer::Pointer(this)); // The active part should always be enabled if (part->GetControl() != 0) Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetEnabled(part->GetControl(), true); } presentationSite->GetPresentation()->AddPart(presentablePart, cookie); if (requestedCurrent == 0) { this->SetSelection(pane); } // if (childObscuredByZoom(part)) // { // presentablePart.enableInputs(false); // } } void PartStack::UpdateContainerVisibleTab() { ChildVector parts = this->GetChildren(); if (parts.size() < 1) { this->SetSelection(StackablePart::Pointer(0)); return; } PartPane::Pointer selPart; int topIndex = 0; WorkbenchPage::Pointer page = this->GetPage(); if (page != 0) { std::vector sortedParts = page->GetSortedParts(); for (ChildVector::iterator partIter = parts.begin(); partIter != parts.end(); ++partIter) { if (partIter->Cast() != 0) { IWorkbenchPartReference::Pointer part = partIter->Cast() ->GetPartReference(); int index = static_cast(std::find(sortedParts.begin(), sortedParts.end(), part) - sortedParts.begin()); if (index >= topIndex) { topIndex = index; selPart = partIter->Cast(); } } } } if (selPart == 0) { PresentableVector presentableParts = this->GetPresentableParts(); if (presentableParts.size() != 0) { IPresentablePart::Pointer part = presentableParts.front(); selPart = this->GetPaneFor(part); } } this->SetSelection(selPart); } void PartStack::ShowSystemMenu() { //this->GetPresentation()->ShowSystemMenu(); } void PartStack::ShowPaneMenu() { //this->GetPresentation()->ShowPaneMenu(); } void PartStack::ShowPartList() { this->GetPresentation()->ShowPartList(); } std::vector PartStack::GetTabList(StackablePart::Pointer part) { if (part != 0) { IPresentablePart::Pointer presentablePart = this->GetPresentablePart(part); StackPresentation::Pointer presentation = this->GetPresentation(); if (presentablePart != 0 && presentation != 0) { return presentation->GetTabList(presentablePart); } } return std::vector(); } void PartStack::DragStart(IPresentablePart::Pointer beingDragged, Point& initialLocation, bool keyboard) { if (beingDragged == 0) { this->PaneDragStart(PartPane::Pointer(0), initialLocation, keyboard); } else { if (presentationSite->IsPartMoveable(beingDragged)) { PartPane::Pointer pane = this->GetPaneFor(beingDragged); if (pane != 0) { this->PaneDragStart(pane, initialLocation, keyboard); } } } } void PartStack::PaneDragStart(PartPane::Pointer pane, Point& initialLocation, bool keyboard) { if (pane == 0) { if (this->CanMoveFolder()) { if (presentationSite->GetState() == IStackPresentationSite::STATE_MAXIMIZED) { // Calculate where the initial location was BEFORE the 'restore'...as a percentage Rectangle bounds = Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())); float xpct = (initialLocation.x - bounds.x) / (float)(bounds.width); float ypct = (initialLocation.y - bounds.y) / (float)(bounds.height); // Only restore if we're dragging views/view stacks if (this->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) this->SetState(IStackPresentationSite::STATE_RESTORED); // Now, adjust the initial location to be within the bounds of the restored rect bounds = Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())); initialLocation.x = (int) (bounds.x + (xpct * bounds.width)); initialLocation.y = (int) (bounds.y + (ypct * bounds.height)); } DragUtil::PerformDrag(Object::Pointer(this), Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())), initialLocation, !keyboard); } } else { if (presentationSite->GetState() == IStackPresentationSite::STATE_MAXIMIZED) { // Calculate where the initial location was BEFORE the 'restore'...as a percentage Rectangle bounds = Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())); float xpct = (initialLocation.x - bounds.x) / (float)(bounds.width); float ypct = (initialLocation.y - bounds.y) / (float)(bounds.height); // Only restore if we're dragging views/view stacks if (this->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) this->SetState(IStackPresentationSite::STATE_RESTORED); // Now, adjust the initial location to be within the bounds of the restored rect // See bug 100908 bounds = Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())); initialLocation.x = (int) (bounds.x + (xpct * bounds.width)); initialLocation.y = (int) (bounds.y + (ypct * bounds.height)); } DragUtil::PerformDrag(pane, Geometry::ToDisplay(this->GetParent(), Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetBounds(this->GetPresentation()->GetControl())), initialLocation, !keyboard); } } IMemento::Pointer PartStack::GetSavedPresentationState() { return savedPresentationState; } void PartStack::FireInternalPropertyChange(int id) { ObjectInt::Pointer val(new ObjectInt(id)); Object::Pointer source(this); PropertyChangeEvent::Pointer event(new PropertyChangeEvent(source, IWorkbenchPartConstants::INTEGER_PROPERTY, val, val)); propEvents.propertyChange(event); } std::string PartStack::GetProperty(const std::string& id) { return properties[id]; } void PartStack::SetProperty(const std::string& id, const std::string& value) { if (value == "") { properties.erase(id); } else { properties.insert(std::make_pair(id, value)); } } void PartStack::CopyAppearanceProperties(PartStack::Pointer copyTo) { copyTo->appearance = this->appearance; if (!properties.empty()) { for (std::map::iterator iter = properties.begin(); iter != properties.end(); ++iter) { copyTo->SetProperty(iter->first, iter->second); } } } void PartStack::ResizeChild(StackablePart::Pointer /*childThatChanged*/) { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartStack.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartStack.h index 6c751cb107..d349922366 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartStack.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartStack.h @@ -1,763 +1,763 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPARTSTACK_H_ #define BERRYPARTSTACK_H_ #include "berryLayoutPart.h" #include "berryIStackableContainer.h" #include "berryWorkbenchPage.h" #include "berryPresentablePart.h" #include "berryPartPlaceholder.h" #include "berryDefaultStackPresentationSite.h" #include "berryPresentationFactoryUtil.h" #include "berryAbstractDropTarget.h" #include "berryPartPane.h" -#include "../berryIMemento.h" +#include "berryIMemento.h" -#include "../presentations/berryIPresentationFactory.h" +#include "presentations/berryIPresentationFactory.h" #include #include #include namespace berry { /** * \ingroup org_blueberry_ui_internal * * Implements the common behavior for stacks of Panes (ie: EditorStack and ViewStack) * This layout container has PartPanes as children and belongs to a PartSashContainer. * * @since 3.0 */ class PartStack : public LayoutPart, public IStackableContainer { friend class EditorSashContainer; friend class PartSashContainer; friend class DetachedWindow; public: berryObjectMacro(PartStack); public: static const int PROP_SELECTION; // = 0x42; private: typedef std::list ChildVector; private: ChildVector children; private: WorkbenchPage* page; private: bool isActive; private: bool allowStateChanges; private: typedef std::list PresentableVector; private: PresentableVector presentableParts; private: std::map properties; protected: int appearance; /** * Stores the last value passed to setSelection. If UI updates are being deferred, * this may be significantly different from the other current pointers. Once UI updates * are re-enabled, the stack will update the presentation selection to match the requested * current pointer. */ private: StackablePart::Pointer requestedCurrent; /** * Stores the current part for the stack. Whenever the outside world asks a PartStack * for the current part, this is what gets returned. This pointer is only updated after * the presentation selection has been restored and the stack has finished updating its * internal state. If the stack is still in the process of updating the presentation, * it will still point to the previous part until the presentation is up-to-date. */ private: StackablePart::Pointer current; /** * Stores the presentable part sent to the presentation. Whenever the presentation * asks for the current part, this is what gets returned. This is updated before sending * the part to the presentation, and it is not updated while UI updates are disabled. * When UI updates are enabled, the stack first makes presentationCurrent match * requestedCurrent. Once the presentation is displaying the correct part, the "current" * pointer on PartStack is updated. */ private: PresentablePart::Pointer presentationCurrent; private: bool ignoreSelectionChanges; protected: IMemento::Pointer savedPresentationState; protected: class MyStackPresentationSite : public DefaultStackPresentationSite { private: PartStack* partStack; public: MyStackPresentationSite(PartStack* stack); void Close(IPresentablePart::Pointer part); void Close(const std::vector& parts); void DragStart(IPresentablePart::Pointer beingDragged, Point& initialLocation, bool keyboard); void DragStart(Point& initialLocation, bool keyboard); bool IsPartMoveable(IPresentablePart::Pointer part); void SelectPart(IPresentablePart::Pointer toSelect); bool SupportsState(int state); void SetState(int newState); IPresentablePart::Pointer GetSelectedPart(); // void AddSystemActions(IMenuManager menuManager) { // PartStack.this.addSystemActions(menuManager); // } bool IsStackMoveable(); void FlushLayout(); PresentableVector GetPartList(); std::string GetProperty(const std::string& id); }; DefaultStackPresentationSite::Pointer presentationSite; private: class PartStackDropResult : public AbstractDropTarget { private: PartPane::WeakPtr pane; // Result of the presentation's dragOver method or null if we are stacking over the // client area of the pane. StackDropResult::Pointer dropResult; PartStack::WeakPtr stack; public: berryObjectMacro(PartStackDropResult); /** * Resets the target of this drop result (allows the same drop result object to be * reused) * * @param stack * @param pane * @param result result of the presentation's dragOver method, or null if we are * simply stacking anywhere. * @since 3.1 */ void SetTarget(PartStack::Pointer stack, PartPane::Pointer pane, StackDropResult::Pointer result); void Drop(); DnDTweaklet::CursorType GetCursor(); Rectangle GetSnapRectangle(); }; private: static PartStackDropResult::Pointer dropResult; // protected: bool isMinimized; private: IPropertyChangeListener::Events propEvents; /** * Custom presentation factory to use for this stack, or null to * use the default */ private: IPresentationFactory* factory; // private: boolean smartZoomed = false; // private: boolean doingUnzoom = false; protected: virtual bool IsMoveable(IPresentablePart::Pointer part); // protected: abstract void addSystemActions(IMenuManager menuManager); protected: virtual bool SupportsState(int newState); protected: virtual bool CanMoveFolder(); protected: virtual void DerefPart(StackablePart::Pointer toDeref); protected: virtual bool AllowsDrop(PartPane::Pointer part); // protected: static void appendToGroupIfPossible(IMenuManager m, // String groupId, ContributionItem item) { // try { // m.appendToGroup(groupId, item); // } catch (IllegalArgumentException e) { // m.add(item); // } // } /** * Creates a new part stack that uses the given custom presentation factory * @param appearance * @param factory custom factory to use (or null to use the default) */ public: PartStack(WorkbenchPage* page, bool allowsStateChanges = true, int appearance = PresentationFactoryUtil::ROLE_VIEW, IPresentationFactory* factory = 0); /** * Adds a property listener to this stack. The listener will receive a PROP_SELECTION * event whenever the result of getSelection changes * * @param listener */ public: void AddListener(IPropertyChangeListener::Pointer listener); public: void RemoveListener(IPropertyChangeListener::Pointer listener); public: int GetAppearance() const; public: std::string GetID() const; protected: bool IsStandalone(); /** * Returns the currently selected IPresentablePart, or null if none * * @return */ protected: IPresentablePart::Pointer GetSelectedPart(); protected: IStackPresentationSite::Pointer GetPresentationSite(); /** * Tests the integrity of this object. Throws an exception if the object's state * is invalid. For use in test suites. */ public: void TestInvariants(); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#describeLayout(java.lang.StringBuffer) */ public: void DescribeLayout(std::string& buf) const; /** * See IVisualContainer#add */ public: void Add(StackablePart::Pointer child); /** * Add a part at a particular position */ protected: void Add(StackablePart::Pointer newChild, Object::Pointer cookie); public: bool AllowsAdd(StackablePart::Pointer toAdd); /* * (non-Javadoc) * * @see org.blueberry.ui.internal.ILayoutContainer#allowsAutoFocus() */ public: bool AllowsAutoFocus(); /** * @param parts */ protected: void Close(const std::vector& parts); /** * @param part */ protected: void Close(IPresentablePart::Pointer part); protected: IPresentationFactory* GetFactory(); public: void CreateControl(void* parent); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#getDropTarget(java.lang.Object, org.blueberry.swt.graphics.Point) */ public: IDropTarget::Pointer GetDropTarget(Object::Pointer draggedObject, const Point& position); public: void SetActive(bool isActive); public: IDropTarget::Pointer CreateDropTarget(PartPane::Pointer pane, StackDropResult::Pointer result); /** * Saves the current state of the presentation to savedPresentationState, if the * presentation exists. */ protected: void SavePresentationState(); public: ~PartStack(); /** * See LayoutPart#Dispose */ public: void Dispose(); public: void FindSashes(PartPane::Sashes& sashes); /** * Gets the presentation bounds. */ public: Rectangle GetBounds(); /** * See IVisualContainer#getChildren */ public: ChildVector GetChildren() const; public: void* GetControl(); /** * Answer the number of children. */ public: ChildVector::size_type GetItemCount(); /** * Returns the LayoutPart for the given IPresentablePart, or null if the given * IPresentablePart is not in this stack. Returns null if given a null argument. * * @param part to locate or null * @return */ protected: PartPane::Pointer GetPaneFor(IPresentablePart::Pointer part); /** * Get the parent control. */ public: void* GetParent(); /** * Returns a list of IPresentablePart * * @return */ public: PresentableVector GetPresentableParts(); private: PresentablePart::Pointer GetPresentablePart(StackablePart::Pointer pane); protected: StackPresentation::Pointer GetPresentation(); /** * Returns the visible child. * @return the currently visible part, or null if none */ public: StackablePart::Pointer GetSelection(); private: void PresentationSelectionChanged(IPresentablePart::Pointer newSelection); /** * See IVisualContainer#remove */ public: void Remove(StackablePart::Pointer child); /** * Reparent a part. Also reparent visible children... */ public: void Reparent(void* newParent); /** * See IVisualContainer#replace */ public: void Replace(StackablePart::Pointer oldChild, StackablePart::Pointer newChild); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#computePreferredSize(boolean, int, int, int) */ public: int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredParallel); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#getSizeFlags(boolean) */ public: int GetSizeFlags(bool horizontal); /** * @see IPersistable */ public: bool RestoreState(IMemento::Pointer memento); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#setVisible(boolean) */ public: void SetVisible(bool makeVisible); /** * @see IPersistable */ public: bool SaveState(IMemento::Pointer memento); protected: WorkbenchPage::Pointer GetPage(); /** * Set the active appearence on the tab folder. * * @param active */ public: void SetActive(int activeState); public: int GetActive() const; public: void CreateControl(void* parent, StackPresentation::Pointer presentation); /** * Sets the presentation bounds. */ public: void SetBounds(const Rectangle& r); public: void SetSelection(StackablePart::Pointer part); /** * Updates the enablement state of actions */ protected: virtual void UpdateActions(PresentablePart::Pointer current); /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#handleDeferredEvents() */ protected: void HandleDeferredEvents(); private: void RefreshPresentationSelection(); public: int GetState(); /** * Sets the minimized state for this stack. The part may call this method to * minimize or restore itself. The minimized state only affects the view * when unzoomed in the 3.0 presentation (in 3.3 it's handled by the * ViewStack directly and works as expected). */ // public: void setMinimized(boolean minimized) { // if (minimized != isMinimized) { // isMinimized = minimized; // // refreshPresentationState(); // } // } /* (non-Javadoc) * @see org.blueberry.ui.internal.ILayoutContainer#obscuredByZoom(org.blueberry.ui.internal.LayoutPart) */ // public: boolean childObscuredByZoom(LayoutPart toTest) { // return isObscuredByZoom(); // } /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#requestZoom(org.blueberry.ui.internal.LayoutPart) */ // public: void childRequestZoomIn(LayoutPart toZoom) { // super.childRequestZoomIn(toZoom); // // requestZoomIn(); // } /* (non-Javadoc) * @see org.blueberry.ui.internal.LayoutPart#requestZoomOut() */ // public: void childRequestZoomOut() { // super.childRequestZoomOut(); // // requestZoomOut(); // } /* (non-Javadoc) * @see org.blueberry.ui.internal.ILayoutContainer#isZoomed(org.blueberry.ui.internal.LayoutPart) */ // public: boolean childIsZoomed(LayoutPart toTest) { // return isZoomed(); // } /** * This is a hack that allows us to preserve the old * min/max behavior for the stack containing the IntroPart. * This is required to have the initial Intro (Welcome) * pane to show correctly but will induce strange * effects should a user re-locate the part to * stacks other that its initial one... * * @return true if the stack contains the intro * as a ViewPane (not if it's only a placeholder) */ // private: boolean isIntroInStack() { // LayoutPart[] kids = getChildren(); // for (int i = 0; i < kids.length; i++) { // if (kids[i] instanceof ViewPane) { // ViewPane vp = (ViewPane) kids[i]; // if (vp.getID().equals(IIntroConstants.INTRO_VIEW_ID)) // return true; // } // } // return false; // } // private: void smartZoom() { // WorkbenchWindow wbw = (WorkbenchWindow) getPage().getWorkbenchWindow(); // if (wbw == null || wbw.getShell() == null) // return; // // Perspective perspective = getPage().getActivePerspective(); // FastViewManager fvm = perspective.getFastViewManager(); // // fvm.deferUpdates(true); // // // Cache the layout bounds // perspective.getPresentation().updateBoundsMap(); // // LayoutPart[] children = perspective.getPresentation().getLayout().getChildren(); // for (int i = 0; i < children.length; i++) { // if (children[i] != this) { // if (children[i] instanceof ViewStack) { // ((ViewStack) children[i]).setMinimized(true); // ViewStackTrimToolBar vstb = fvm // .getViewStackTrimToolbar(children[i] // .getID()); // vstb.setRestoreOnUnzoom(true); // } // else if (children[i] instanceof EditorSashContainer && !(this instanceof EditorStack)) { // perspective.setEditorAreaState(IStackPresentationSite.STATE_MINIMIZED); // perspective.setEditorAreaRestoreOnUnzoom(true); // } // } // } // // // If the editor area has changed state tell the perspective // if (this instanceof EditorStack) // perspective.setEditorAreaState(IStackPresentationSite.STATE_MAXIMIZED); // // // Clear the boundsMap // perspective.getPresentation().resetBoundsMap(); // // // We're done batching... // fvm.deferUpdates(false); // // perspective.getPresentation().setMaximizedStack(this); // smartZoomed = true; // } // protected: void smartUnzoom() { // // Prevent recursion through 'setMinimized' // if (doingUnzoom) // return; // doingUnzoom = true; // // WorkbenchWindow wbw = (WorkbenchWindow) getPage().getWorkbenchWindow(); // if (wbw == null || wbw.getShell() == null) // return; // // ITrimManager tbm = wbw.getTrimManager(); // Perspective perspective = getPage().getActivePerspective(); // FastViewManager fvm = perspective.getFastViewManager(); // // ILayoutContainer root = getContainer(); // // // We go up one more level when maximizing an editor stack // // so that we 'zoom' the editor area // boolean restoringEditorArea = false; // if (root instanceof EditorSashContainer) { // root = ((EditorSashContainer) root).getContainer(); // restoringEditorArea = true; // } // // // This is a compound operation // fvm.deferUpdates(true); // // LayoutPart[] children = root.getChildren(); // for (int i = 0; i < children.length; i++) { // if (children[i] != this) { // IWindowTrim trim = tbm.getTrim(children[i].getID()); // if (trim == null) // continue; // // if (trim instanceof ViewStackTrimToolBar) { // ViewStackTrimToolBar vstb = (ViewStackTrimToolBar) trim; // if (vstb.restoreOnUnzoom() // && children[i] instanceof ContainerPlaceholder) { // // In the current presentation its a // // container placeholder // ViewStack realStack = (ViewStack) ((ContainerPlaceholder) children[i]) // .getRealContainer(); // realStack.setMinimized(false); // // vstb.setRestoreOnUnzoom(false); // } // } else if (trim instanceof EditorAreaTrimToolBar) { // if (perspective.getEditorAreaRestoreOnUnzoom()) // perspective.setEditorAreaState(IStackPresentationSite.STATE_RESTORED); // } // } // } // // // If the editor area has changed state tell the perspective // if (restoringEditorArea) // perspective.setEditorAreaState(IStackPresentationSite.STATE_RESTORED); // // perspective.getPresentation().setMaximizedStack(null); // // fvm.deferUpdates(false); // smartZoomed = false; // // doingUnzoom = false; // } protected: void SetState(const int newState); /** * Called by the workbench page to notify this part that it has been zoomed or unzoomed. * The PartStack should not call this method itself -- it must request zoom changes by * talking to the WorkbenchPage. */ // public: void setZoomed(boolean isZoomed) { // // super.setZoomed(isZoomed); // // LayoutPart[] children = getChildren(); // // for (int i = 0; i < children.length; i++) { // LayoutPart next = children[i]; // // next.setZoomed(isZoomed); // } // // refreshPresentationState(); // } // public: boolean isZoomed() { // ILayoutContainer container = getContainer(); // // if (container != null) { // return container.childIsZoomed(this); // } // // return false; // } // protected: void refreshPresentationState() { // if (isZoomed() || smartZoomed) { // presentationSite.setPresentationState(IStackPresentationSite.STATE_MAXIMIZED); // } else { // // boolean wasMinimized = (presentationSite.getState() == IStackPresentationSite.STATE_MINIMIZED); // // if (isMinimized) { // presentationSite.setPresentationState(IStackPresentationSite.STATE_MINIMIZED); // } else { // presentationSite.setPresentationState(IStackPresentationSite.STATE_RESTORED); // } // // if (isMinimized != wasMinimized) { // flushLayout(); // // if (isMinimized) { // WorkbenchPage page = getPage(); // // if (page != null) { // page.refreshActiveView(); // } // } // } // } // } /** * Makes the given part visible in the presentation. * @param part the part to add to the stack * @param cookie other information */ private: void ShowPart(StackablePart::Pointer part, Object::Pointer cookie); /** * Update the container to show the correct visible tab based on the * activation list. */ private: void UpdateContainerVisibleTab(); /** * */ public: void ShowSystemMenu(); public: void ShowPaneMenu(); public: void ShowPartList(); public: std::vector GetTabList(StackablePart::Pointer part); /** * * @param beingDragged * @param initialLocation * @param keyboard */ private: void DragStart(IPresentablePart::Pointer beingDragged, Point& initialLocation, bool keyboard); public: void PaneDragStart(PartPane::Pointer pane, Point& initialLocation, bool keyboard); /** * @return Returns the savedPresentationState. */ public: IMemento::Pointer GetSavedPresentationState(); private: void FireInternalPropertyChange(int id); // TrimStack Support /** * Explicitly sets the presentation state. This is used by the * new min/max code to force the CTabFolder to show the proper * state without going through the 'setState' code (which causes * nasty side-effects. * @param newState The state to set the presentation to */ // public: void setPresentationState(int newState) { // presentationSite.setPresentationState(newState); // } // // Support for passing perspective layout properties to the presentation public: std::string GetProperty(const std::string& id); public: void SetProperty(const std::string& id, const std::string& value); /** * Copies all appearance related data from this stack to the given stack. */ public: void CopyAppearanceProperties(PartStack::Pointer copyTo); public: void ResizeChild(StackablePart::Pointer childThatChanged); }; } #endif /*BERRYPARTSTACK_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartTester.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartTester.cpp index d9d92d4361..87a46017a0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartTester.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartTester.cpp @@ -1,111 +1,111 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryPartTester.h" #include #include -#include "../berryIEditorSite.h" -#include "../berryIViewSite.h" +#include "berryIEditorSite.h" +#include "berryIViewSite.h" namespace berry { void PartTester::TestEditor(IEditorPart::Pointer part) { TestWorkbenchPart(part); if (!(part->GetSite() == part->GetEditorSite().GetPointer())) throw Poco::AssertionViolationException("The part's editor site must be the same as the part's site"); //$NON-NLS-1$ IEditorInput::Pointer input = part->GetEditorInput(); if (input.IsNull()) throw Poco::AssertionViolationException("The editor input must be non-null"); //$NON-NLS-1$ TestEditorInput(input); part->IsDirty(); part->IsSaveAsAllowed(); part->IsSaveOnCloseNeeded(); } void PartTester::TestEditorInput(IEditorInput::Pointer /*input*/) { //input.getAdapter(Object.class); // Don't test input.getImageDescriptor() -- the workbench never uses that // method and most editor inputs would fail the test. It should really be // deprecated. // Persistable element may be null // IPersistableElement persistableElement = input.getPersistable(); // if (persistableElement != null) { // Assert // .isNotNull(persistableElement.getFactoryId(), // "The persistable element for the editor input must have a non-null factory id"); //$NON-NLS-1$ // } } void PartTester::TestWorkbenchPart(IWorkbenchPart::Pointer part) { // IPropertyListener testListener = new IPropertyListener() { // public void propertyChanged(Object source, int propId) { // // } // }; // Test addPropertyListener //part.addPropertyListener(testListener); // Test removePropertyListener //part.removePropertyListener(testListener); // Test equals if (part != part) throw Poco::AssertionViolationException("A part must be equal to itself"); //$NON-NLS-1$ Object::Pointer obj(new ObjectString("jo")); if (part == obj) throw Poco::AssertionViolationException("A part must have a meaningful operator== method"); //$NON-NLS-1$ // Test getAdapter //Object partAdapter = part.getAdapter(part.getClass()); //Assert.isTrue(partAdapter == null || partAdapter == part, //"A part must adapter to itself or return null"); //$NON-NLS-1$ // Test getTitleImage //Assert.isNotNull(part.getTitleImage(), // "A part's title image must be non-null"); //$NON-NLS-1$ // Compute hashCode //part.hashCode(); } void PartTester::TestView(IViewPart::Pointer part) { if (!(part->GetSite() == part->GetViewSite().GetPointer())) throw Poco::AssertionViolationException( "A part's site must be the same as a part's view site"); //$NON-NLS-1$ TestWorkbenchPart(part); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartTester.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartTester.h index d932504d79..1b6660711c 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartTester.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPartTester.h @@ -1,74 +1,74 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPARTTESTER_H_ #define BERRYPARTTESTER_H_ -#include "../berryIEditorPart.h" -#include "../berryIEditorInput.h" -#include "../berryIViewPart.h" +#include "berryIEditorPart.h" +#include "berryIEditorInput.h" +#include "berryIViewPart.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * */ class PartTester { private: PartTester() { } /** * Sanity-check the public interface of the editor. This is called on every editor after it * is fully initiallized, but before it is actually connected to the editor reference or the * layout. Calls as much of the editor's public interface as possible to test for exceptions, * and tests the return values for glaring faults. This does not need to be an exhaustive conformance * test, as it is called every time an editor is opened and it needs to be efficient. * The part should be unmodified when the method exits. * * @param part */ public: static void TestEditor(IEditorPart::Pointer part); public: static void TestEditorInput(IEditorInput::Pointer input); /** * Sanity-checks a workbench part. Excercises the public interface and tests for any * obviously bogus return values. The part should be unmodified when the method exits. * * @param part * @throws Exception */ private: static void TestWorkbenchPart(IWorkbenchPart::Pointer part); /** * Sanity-check the public interface of a view. This is called on every view after it * is fully initiallized, but before it is actually connected to the part reference or the * layout. Calls as much of the part's public interface as possible without modifying the part * to test for exceptions and check the return values for glaring faults. This does not need * to be an exhaustive conformance test, as it is called every time an editor is opened and * it needs to be efficient. * * @param part */ public: static void TestView(IViewPart::Pointer part); }; } #endif /*BERRYPARTTESTER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspective.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspective.cpp index 9f12ed0d71..2cba0acaa9 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspective.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspective.cpp @@ -1,1765 +1,1765 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#include "../tweaklets/berryGuiWidgetsTweaklet.h" +#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 "../dialogs/berryMessageDialog.h" +#include "dialogs/berryMessageDialog.h" #include "berryWorkbenchWindow.h" -#include "../presentations/berryIStackPresentationSite.h" +#include "presentations/berryIStackPresentationSite.h" namespace berry { const std::string Perspective::VERSION_STRING = "0.016"; Perspective::Perspective(PerspectiveDescriptor::Pointer desc, WorkbenchPage::Pointer page) : descriptor(desc) { this->Init(page); if (desc.IsNotNull()) { this->CreatePresentation(desc); } } 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)); } 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. std::vector refs(this->GetViewReferences()); for (std::vector::size_type i = 0, length = refs.size(); i < length; i++) { this->GetViewFactory()->ReleaseView(refs[i]); } mapIDtoViewLayoutRec.clear(); } void Perspective::DisposeViewRefs() { if (!memento) { return; } std::vector views(memento->GetChildren(WorkbenchConstants::TAG_VIEW)); for (std::size_t x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; std::string id; childMem->GetString(WorkbenchConstants::TAG_ID, id); // skip creation of the intro reference - it's handled elsewhere. if (id == IntroConstants::INTRO_VIEW_ID) { continue; } std::string secondaryId = ViewFactory::ExtractSecondaryId(id); if (!secondaryId.empty()) { id = ViewFactory::ExtractPrimaryId(id); } std::string 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 std::string& viewId) { return this->FindView(viewId, ""); } IViewReference::Pointer Perspective::FindView(const std::string& id, const std::string& secondaryId) { std::vector refs(this->GetViewReferences()); for (unsigned 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); } void* Perspective::GetClientComposite() { return page->GetClientComposite(); } IPerspectiveDescriptor::Pointer Perspective::GetDesc() { return descriptor; } PartPane::Pointer Perspective::GetPane(IViewReference::Pointer ref) { return ref.Cast()->GetPane(); } std::vector Perspective::GetPerspectiveShortcuts() { return perspectiveShortcuts; } PerspectiveHelper* Perspective::GetPresentation() const { return presentation; } std::vector Perspective::GetShowViewShortcuts() { return showViewShortcuts; } ViewFactory* Perspective::GetViewFactory() { return viewFactory; } std::vector Perspective::GetViewReferences() { // Get normal views. if (presentation == 0) { return std::vector(); } std::vector panes; presentation->CollectViewPanes(panes); std::vector 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 (std::vector::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 ContainerPlaceholder(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 std::string& 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 (WorkbenchException& e) { this->UnableToOpenPerspective(persp, e.displayText()); } } void Perspective::UnableToOpenPerspective(PerspectiveDescriptor::Pointer persp, const std::string& 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(); std::string title = "Restoring problems"; std::string msg = "Unable to read workbench state."; if (status == "") { MessageDialog::OpenError(Shell::Pointer(0), title, msg); } else { //TODO error dialog //ErrorDialog.openError((Shell) 0, title, msg, status); MessageDialog::OpenError(Shell::Pointer(0), 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; std::vector descs(WorkbenchPlugin::GetDefault() ->GetViewRegistry()->GetStickyViews()); for (std::size_t i = 0; i < descs.size(); i++) { IStickyViewDescriptor::Pointer stickyViewDescriptor = descs[i]; std::string 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); // Retrieve view layout info stored in the page layout. std::map layoutInfo = layout->GetIDtoViewLayoutRecMap(); mapIDtoViewLayoutRec.insert(layoutInfo.begin(), layoutInfo.end()); //TODO Perspective action sets // Create action sets. //List temp = new ArrayList(); //this->CreateInitialActionSets(temp, layout.getActionSets()); // IContextService service = 0; // if (page != 0) // { // service = (IContextService) page.getWorkbenchWindow().getService( // IContextService.class); // } // try // { // if (service!=0) // { // service.activateContext(ContextAuthority.DEFER_EVENTS); // } // 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(); // // // 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(); // Create presentation. presentation = new PerspectiveHelper(page, container, Perspective::Pointer(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); } layout = 0; } 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 std::string& /*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; } this->memento = memento; // Add the visible views. std::vector 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 std::vector& views) { // MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, // WorkbenchMessages.Perspective_problemsRestoringViews, 0); bool result = true; for (std::size_t x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; std::string id; childMem->GetString(WorkbenchConstants::TAG_ID, id); // skip creation of the intro reference - it's handled elsewhere. if (id == IntroConstants::INTRO_VIEW_ID) { continue; } std::string secondaryId(ViewFactory::ExtractSecondaryId(id)); if (!secondaryId.empty()) { id = ViewFactory::ExtractPrimaryId(id); } // Create and open the view. try { std::string 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.displayText(), 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) { Rectangle r(0, 0, 0, 0); boundsMem->GetInteger(WorkbenchConstants::TAG_X, r.x); boundsMem->GetInteger(WorkbenchConstants::TAG_Y, r.y); boundsMem->GetInteger(WorkbenchConstants::TAG_HEIGHT, r.height); boundsMem->GetInteger(WorkbenchConstants::TAG_WIDTH, r.width); //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, Perspective::Pointer(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. std::vector views(memento->GetChildren(WorkbenchConstants::TAG_VIEW)); for (std::size_t x = 0; x < views.size(); x++) { // Get the view details. IMemento::Pointer childMem = views[x]; std::string id; childMem->GetString(WorkbenchConstants::TAG_ID, id); std::string secondaryId(ViewFactory::ExtractSecondaryId(id)); if (!secondaryId.empty()) { 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) { std::string 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().Cast()); } } // // Load the fast views // if (fastViewManager != 0) // fastViewManager.restoreState(memento, result); // Load the view layout recs std::vector recMementos(memento ->GetChildren(WorkbenchConstants::TAG_VIEW_LAYOUT_REC)); for (std::size_t i = 0; i < recMementos.size(); i++) { IMemento::Pointer recMemento = recMementos[i]; std::string compoundId; if (recMemento->GetString(WorkbenchConstants::TAG_ID, compoundId)) { ViewLayoutRec::Pointer rec = GetViewLayoutRec(compoundId, true); std::string closeablestr; recMemento->GetString(WorkbenchConstants::TAG_CLOSEABLE, closeablestr); if (WorkbenchConstants::FALSE_VAL == closeablestr) { rec->isCloseable = false; } std::string moveablestr; recMemento->GetString(WorkbenchConstants::TAG_MOVEABLE, moveablestr); if (WorkbenchConstants::FALSE_VAL == moveablestr) { rec->isMoveable = false; } std::string standalonestr; recMemento->GetString(WorkbenchConstants::TAG_STANDALONE, standalonestr); if (WorkbenchConstants::TRUE_VAL == standalonestr) { rec->isStandalone = true; std::string 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. std::vector 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 (std::size_t x = 0; x < actions.size(); x++) { std::string 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 (std::size_t x = 0; x < actions.size(); x++) { std::string 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; } std::vector Perspective::GetShowInIdsFromRegistry() { PerspectiveExtensionReader reader; std::vector tags; tags.push_back(WorkbenchRegistryConstants::TAG_SHOW_IN_PART); reader.SetIncludeOnlyTags(tags); PageLayout::Pointer layout(new PageLayout()); reader.ExtendLayout(descriptor->GetOriginalId(), layout); return layout->GetShowInPartIds(); } void Perspective::SaveDesc() { this->SaveDescAs(descriptor); } 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) // { // ErrorDialog.openError((Shell) 0, WorkbenchMessages.Perspective_problemSavingTitle, // WorkbenchMessages.Perspective_problemSavingMessage, // 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 Perspective::SaveState(IMemento::Pointer memento) { // MultiStatus result = new MultiStatus( // PlatformUI.PLUGIN_ID, // IStatus.OK, // WorkbenchMessages.Perspective_problemsSavingPerspective, 0); // // 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); 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) { Rectangle 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 (std::vector::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 (std::vector::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. std::vector viewPanes; presentation->CollectViewPanes(viewPanes); // Save the views. for (std::vector::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 (std::map::iterator i = mapIDtoViewLayoutRec.begin(); i != mapIDtoViewLayoutRec.end(); ++i) { std::string compoundId(i->first); ViewLayoutRec::Pointer rec(i->second); 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 &= 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 std::vector& list) { perspectiveShortcuts = list; } void Perspective::SetShowInPartIds(const std::vector& list) { showInPartIds = list; } void Perspective::SetShowViewActionIds(const std::vector& 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 std::string& viewId, const std::string& 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 std::string& viewId, const std::string& 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 std::string 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(std::string& buf) const { // std::vector 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/src/internal/berryPerspective.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspective.h index a4d7928e6c..aab0e265d5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspective.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspective.h @@ -1,629 +1,629 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #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 "berryIWorkbenchPartReference.h" +#include "berryIViewReference.h" +#include "berryIViewPart.h" #include #include #include namespace berry { class ViewFactory; class PerspectiveHelper; /** * \ingroup org_blueberry_ui_internal * */ class Perspective : public Object { public: berryObjectMacro(Perspective); friend class WorkbenchPage; private: ViewFactory* viewFactory; std::map mapIDtoViewLayoutRec; static const std::string VERSION_STRING; // = "0.016";//$NON-NLS-1$ /** * 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; ContainerPlaceholder::Pointer editorHolder; bool editorHidden; int editorAreaState; //ArrayList alwaysOnActionSets; //ArrayList alwaysOffActionSets; std::vector showViewShortcuts; std::vector perspectiveShortcuts; bool fixed; std::vector 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 std::string& 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 std::string& id, const std::string& secondaryId); /** * Returns the window's client composite widget * which views and editor area will be parented. */ public: void* 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: std::vector GetPerspectiveShortcuts(); /** * Returns the presentation. */ public: PerspectiveHelper* GetPresentation() const; /** * Returns the show view shortcuts associated with this perspective. * * @return an array of view identifiers */ public: std::vector GetShowViewShortcuts(); /** * Returns the view factory. */ public: ViewFactory* GetViewFactory(); /** * See IWorkbenchPage. */ public: std::vector 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 std::string& 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 std::string& 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(); /** * 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 std::string& 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 std::vector& 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: std::vector 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); /** * Save the layout. */ 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 std::vector& list); /** * Sets the ids of the parts to list in the Show In... prompter. * This is a List of Strings. */ public: void SetShowInPartIds(const std::vector& list); /** * Sets the ids of the views to list in the Show View shortcuts. * This is a List of Strings. */ public: void SetShowViewActionIds(const std::vector& 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 std::string& viewId, const std::string& secondaryId); /** * Shows the view with the given id and secondary id. */ public: IViewPart::Pointer ShowView(const std::string& viewId, const std::string& 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(std::string& 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/src/internal/berryPerspectiveDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveDescriptor.h index b599ce3a5c..2c5faa5d89 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveDescriptor.h @@ -1,234 +1,234 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPERSPECTIVEDESCRIPTOR_H_ #define BERRYPERSPECTIVEDESCRIPTOR_H_ #include -#include "../berryIPerspectiveDescriptor.h" -#include "../berryIPerspectiveFactory.h" -#include "../berryIMemento.h" +#include "berryIPerspectiveDescriptor.h" +#include "berryIPerspectiveFactory.h" +#include "berryIMemento.h" #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 { public: berryObjectMacro(PerspectiveDescriptor) private: std::string id; std::string pluginId; std::string originalId; std::string label; std::string className; std::string description; bool singleton; bool fixed; mutable ImageDescriptor::Pointer imageDescriptor; IConfigurationElement::Pointer configElement; /** * 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 std::string& id, const std::string& 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 std::string& 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(); /** * Deletes the custom definition for a perspective.. */ public: void DeleteCustomDefinition(); /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveDescriptor#getDescription() */ public: std::string GetDescription() const; /** * Returns whether or not this perspective is fixed. * * @return whether or not this perspective is fixed */ public: bool GetFixed() const; /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveDescriptor#getId() */ public: std::string GetId() const; public: std::string GetPluginId() const; /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveDescriptor#getImageDescriptor() */ public: ImageDescriptor::Pointer GetImageDescriptor() const; /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveDescriptor#getLabel() */ public: std::string GetLabel() const; /** * Return the original id of this descriptor. * * @return the original id of this descriptor */ public: std::string GetOriginalId() const; /** * Returns true if this perspective has a custom definition. * * @return whether this perspective has a custom definition */ public: bool HasCustomDefinition() const; /** * Returns true if this perspective wants to be default. * * @return whether this perspective wants to be default */ public: 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; /** * Returns true if this perspective is a singleton. * * @return whether this perspective is a singleton */ public: 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); /** * Revert to the predefined extension template. Does nothing if this * descriptor is user defined. */ public: 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); /** * 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; /** * Returns the factory class name for this descriptor. * * @return the factory class name for this descriptor * @since 3.1 */ public: std::string GetFactoryClassName() const; }; } #endif /*BERRYPERSPECTIVEDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveHelper.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveHelper.cpp index 65115057d9..510a11a25d 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveHelper.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveHelper.cpp @@ -1,1674 +1,1674 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ -#include "../tweaklets/berryGuiWidgetsTweaklet.h" +#include "tweaklets/berryGuiWidgetsTweaklet.h" #include "berryPerspectiveHelper.h" #include "berryLayoutTree.h" #include "berryEditorSashContainer.h" #include "berryDragUtil.h" #include "berryPresentationFactoryUtil.h" #include "berryWorkbenchConstants.h" #include #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( void* /*currentControl*/, Object::Pointer draggedObject, const Point& /*position*/, const Rectangle& 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 Rectangle& dragRectangle) { this->stack = 0; this->part = part; this->dragRectangle = dragRectangle; } void PerspectiveHelper::ActualDropTarget::SetTarget(PartStack::Pointer stack, const Rectangle& dragRectangle) { this->stack = stack; this->part = 0; this->dragRectangle = dragRectangle; } PerspectiveHelper::ActualDropTarget::ActualDropTarget(PerspectiveHelper* perspHelper, PartPane::Pointer part, const Rectangle& dragRectangle) : AbstractDropTarget(), perspHelper(perspHelper) { this->SetTarget(part, dragRectangle); } PerspectiveHelper::ActualDropTarget::ActualDropTarget(PerspectiveHelper* perspHelper, PartStack::Pointer stack, const Rectangle& 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 IStackableContainer::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); } } DnDTweaklet::CursorType PerspectiveHelper::ActualDropTarget::GetCursor() { return DnDTweaklet::CURSOR_OFFSCREEN; } PerspectiveHelper::MatchingPart::MatchingPart(const std::string& pid, const std::string& sid, StackablePart::Pointer part) { this->pid = pid; this->sid = sid; this->part = part; this->len = pid.size() + sid.size(); this->hasWildcard = (pid.find_first_of(PartPlaceholder::WILD_CARD) != std::string::npos) || (sid.find_first_of(PartPlaceholder::WILD_CARD) != std::string::npos); } 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::Pointer 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 = 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. void* 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(void* parent) { if (active) { return; } parentWidget = parent; // Activate main layout // make sure all the views have been properly parented std::vector children; this->CollectViewPanes(children, mainLayout->GetChildren()); for (std::vector::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(StackablePart::Pointer part) { // Look for a placeholder. PartPlaceholder::Pointer placeholder; StackablePart::Pointer testPart; std::string primaryId = part->GetId(); std::string 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) { IStackableContainer::Pointer stack = relative.Cast (); if (stack->AllowsAdd(part)) { mainLayout->Stack(part, stack); } else { mainLayout->AddPart(part); } } else { mainLayout->AddPart(part); } } else { IStackableContainer::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.remove(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); std::list otherChildren = holder->GetChildren(); for (std::list::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(); container = containerPlaceholder->GetRealContainer(); if (container.Cast () != 0) { parentContainer->Replace(containerPlaceholder, container.Cast()); } containerPlaceholder->SetRealContainer(IStackableContainer::Pointer(0)); } // reparent part. //if (!(container instanceof ViewStack)) // { // 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 (container instanceof PartSashContainer) // { // ((PartSashContainer) container) .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(StackablePart::Pointer part) { IStackableContainer::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) { StackablePart::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; } IStackableContainer::Pointer container = foundPart->GetContainer(); if (container.Cast () != 0) { return false; } if (container.Cast () != 0) { PartStack::Pointer folder = container.Cast(); StackablePart::Pointer visiblePart = folder->GetSelection(); if (visiblePart == 0) { return false; } return partRef == visiblePart.Cast()->GetPartReference(); } return true; } bool PerspectiveHelper::WillPartBeVisible(const std::string& partId) { return this->WillPartBeVisible(partId, 0); } bool PerspectiveHelper::WillPartBeVisible(const std::string& partId, const std::string& secondaryId) { StackablePart::Pointer part = this->FindPart(partId, secondaryId); if (part == 0) { return false; } IStackableContainer::Pointer container = part->GetContainer(); if (container != 0 && container.Cast () != 0) { container = container.Cast()->GetRealContainer(); } if (container != 0 && container.Cast () != 0) { PartStack::Pointer folder = container.Cast(); if (folder->GetSelection() == 0) { return false; } return part->GetCompoundId() == folder->GetSelection().Cast()->GetCompoundId(); } return true; } std::vector PerspectiveHelper::CollectPlaceholders() { // Scan the main window. std::vector 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; std::list moreResults = win->GetChildren(); if (moreResults.size()> 0) { for (std::list::iterator iter = moreResults.begin(); iter != moreResults.end(); ++iter) { if (iter->Cast() != 0) results.push_back(iter->Cast()); } } } } return results; } std::vector PerspectiveHelper::CollectPlaceholders( const std::list& parts) { std::vector result; for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (part.Cast () != 0) { // iterate through sub containers to find sub-parts std::vector newParts = this->CollectPlaceholders( part.Cast()->GetChildren()); result.insert(result.end(), newParts.begin(), newParts.end()); } else if (part.Cast () != 0) { std::list children = part.Cast()->GetChildren(); for (std::list::iterator partIter = children.begin(); partIter != children.end(); ++partIter) { if (partIter->Cast() != 0) result.push_back(partIter->Cast()); } } } return result; } std::vector PerspectiveHelper::CollectContainerPlaceholders() { // Scan the main window. std::vector results(this->CollectContainerPlaceholders( mainLayout->GetChildren())); // // Scan each detached window. // if (detachable) // { // for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); // winIter != detachedWindowList.end(); ++winIter) // { // DetachedWindow::Pointer win = *winIter; // std::list moreResults = win->GetChildren(); // if (moreResults.size()> 0) // { // for (std::list::iterator iter = moreResults.begin(); // iter != moreResults.end(); ++iter) // { // if (iter->Cast() != 0) // results.push_back(iter->Cast()); // } // } // } // } return results; } std::vector PerspectiveHelper::CollectContainerPlaceholders( const std::list& parts) { std::vector result; for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (part.Cast () != 0) { // iterate through sub containers to find sub-parts std::vector newParts = this->CollectContainerPlaceholders( part.Cast()->GetChildren()); result.insert(result.end(), newParts.begin(), newParts.end()); } else if (part.Cast () != 0) { result.push_back(part.Cast()); } } return result; } void PerspectiveHelper::CollectViewPanes(std::vector& 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; std::list moreResults = win->GetChildren(); for (std::list::iterator iter = moreResults.begin(); iter != moreResults.end(); ++iter) { if (iter->Cast() != 0) result.push_back(iter->Cast()); } } } } void PerspectiveHelper::CollectViewPanes(std::vector& result, const std::list& parts) { for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (part.Cast () != 0 && part.Cast()->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR) { std::list children = part.Cast()->GetChildren(); for (std::list::iterator partIter = children.begin(); partIter != children.end(); ++partIter) { if (partIter->Cast() != 0) result.push_back(partIter->Cast()); } } else if (part.Cast () != 0) { this->CollectViewPanes(result, part.Cast()->GetChildren()); } } } void PerspectiveHelper::Deactivate() { if (!active) { return; } this->DisableAllDrag(); // Reparent all views to the main window void* parent = mainLayout->GetParent(); std::vector children; this->CollectViewPanes(children, mainLayout->GetChildren()); for (DetachedWindowsType::iterator winIter = detachedWindowList.begin(); winIter != detachedWindowList.end(); ++winIter) { DetachedWindow::Pointer window = *winIter; std::list moreResults = window->GetChildren(); for (std::list::iterator iter = moreResults.begin(); iter != moreResults.end(); ++iter) { if (iter->Cast() != 0) children.push_back(iter->Cast()); } } // *** Do we even need to do this if detached windows not supported? for (std::vector::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(std::string& 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; std::list children = window->GetChildren(); unsigned int j = 0; if (children.size() != 0) { buf.append("dWindow ("); //$NON-NLS-1$ for (std::list::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(StackablePart::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(); // std::vector 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. IStackableContainer::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); IStackableContainer::ChildrenType children = oldContainer->GetChildren(); if (wasDocked) { bool hasChildren = (children.size()> 0); if (hasChildren) { // make sure one is at least visible int childVisible = 0; for (IStackableContainer::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(std::cout); 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.remove(w); } else { // There are children. If none are visible hide detached // window. bool allInvisible = true; for (IStackableContainer::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 (IStackableContainer::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.remove(w); } } } } void PerspectiveHelper::Detach(LayoutPart::Pointer part, int x, int y) { // Detaching is disabled on some platforms .. if (!detachable) { return; } // Calculate detached window size. Point size = part->GetSize(); if (size.x == 0 || size.y == 0) { ILayoutContainer::Pointer container = part->GetContainer(); if (container.Cast () != 0) { size = container.Cast()->GetSize(); } } int width = std::max(size.x, MIN_DETACH_WIDTH); int height = std::max(size.y, 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(); StackablePart::Pointer visiblePart = stack->GetSelection(); IStackableContainer::ChildrenType children = stack->GetChildren(); for (IStackableContainer::ChildrenType::iterator iter = children.begin(); iter != children.end(); ++iter) { if (!(*iter)->IsPlaceHolder()) { // 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(StackablePart::Pointer part, int x, int y) { // Detaching is disabled on some platforms .. if (!detachable) { return; } // Calculate detached window size. Point size = part->GetSize(); if (size.x == 0 || size.y == 0) { IStackableContainer::Pointer container = part->GetContainer(); if (container.Cast () != 0) { size = container.Cast()->GetSize(); } } int width = std::max(size.x, MIN_DETACH_WIDTH); int height = std::max(size.y, 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); Rectangle bounds = pane->GetParentBounds(); this->DetachPart(pane, bounds.x, bounds.y); } } void PerspectiveHelper::AddDetachedPart(StackablePart::Pointer part) { // Calculate detached window size. Rectangle bounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(parentWidget)->GetBounds(); bounds.x = bounds.x + (bounds.width - 300) / 2; bounds.y = bounds.y + (bounds.height - 300) / 2; this->AddDetachedPart(part, bounds); } void PerspectiveHelper::AddDetachedPart(StackablePart::Pointer part, const Rectangle& 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); } void PerspectiveHelper::EnableAllDrag() { DragUtil::AddDragTarget(0, dragTarget); } StackablePart::Pointer PerspectiveHelper::FindPart(const std::string& id) { return this->FindPart(id, ""); } StackablePart::Pointer PerspectiveHelper::FindPart(const std::string& primaryId, const std::string& secondaryId) { //BERRY_INFO << "Looking for part: " << primaryId << ":" << secondaryId << std::endl; // check main window. std::vector matchingParts; StackablePart::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 StackablePart::Pointer(0); } StackablePart::Pointer PerspectiveHelper::FindPart(const std::string& id, const std::list& parts, std::vector& matchingParts) { //BERRY_INFO << "Looking for part " << id << " in a list of layout parts with size " << parts.size() << std::endl; for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; if (part.Cast () != 0) { StackablePart::Pointer result = this->FindPart(id, part.Cast()->GetChildren(), matchingParts); if (result != 0) return result; } else if (part.Cast() != 0) { StackablePart::Pointer result = this->FindPart(id, part.Cast()->GetChildren(), matchingParts); if (result != 0) return result; } } //BERRY_INFO << "Returning 0\n"; return StackablePart::Pointer(0); } LayoutPart::Pointer PerspectiveHelper::FindLayoutPart(const std::string& id, const std::list& parts, std::vector& matchingParts) { for (std::list::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) { return part; } else if (part.Cast() != 0) { // Skip. } else if (part.Cast () != 0) { part = this->FindLayoutPart(id, part.Cast()->GetChildren(), matchingParts); return part; } } return LayoutPart::Pointer(0); } StackablePart::Pointer PerspectiveHelper::FindPart(const std::string& id, const std::list& parts, std::vector& matchingParts) { //BERRY_INFO << "Looking for part " << id << " in a list of stackable parts with size " << parts.size() << std::endl; for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { StackablePart::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.Cast() != 0 && part.Cast()->HasWildCard()) { Poco::RegularExpression re(id, Poco::RegularExpression::RE_CASELESS); if (re.match(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)); // } } } //BERRY_INFO << "Returning 0\n"; return StackablePart::Pointer(0); } StackablePart::Pointer PerspectiveHelper::FindPart(const std::string& primaryId, const std::string& secondaryId, const std::list& parts, std::vector& matchingParts) { for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { LayoutPart::Pointer part = *iter; // check containers first if (part.Cast() != 0) { // skip } else if (part.Cast () != 0) { StackablePart::Pointer testPart = this->FindPart(primaryId, secondaryId, part.Cast()->GetChildren(), matchingParts); if (testPart != 0) { return testPart; } } } return StackablePart::Pointer(0); } StackablePart::Pointer PerspectiveHelper::FindPart(const std::string& primaryId, const std::string& secondaryId, const std::list& parts, std::vector& matchingParts) { for (std::list::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { StackablePart::Pointer part = *iter; // 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) { std::string id = part->GetId(); // optimization: don't bother parsing id if it has no separator -- it can't match std::string 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; } std::string phPrimaryId = ViewFactory::ExtractPrimaryId(id); // perfect matching pair if (phPrimaryId == primaryId && phSecondaryId == secondaryId) { return part; } // check for partial matching pair Poco::RegularExpression pre(phPrimaryId, Poco::RegularExpression::RE_CASELESS); if (pre.match(primaryId)) { Poco::RegularExpression sre(phSecondaryId, Poco::RegularExpression::RE_CASELESS); if (sre.match(secondaryId)) { matchingParts.push_back(MatchingPart(phPrimaryId, phSecondaryId, part)); } } } } return StackablePart::Pointer(0); } bool PerspectiveHelper::HasPlaceholder(const std::string& id) { return this->HasPlaceholder(id, 0); } bool PerspectiveHelper::HasPlaceholder(const std::string& primaryId, const std::string& secondaryId) { StackablePart::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(StackablePart::Pointer source, LayoutPart::Pointer target) { if ((source.Cast () != 0 || source.Cast () != 0) && target.Cast () != 0) { return 0.25f; } return 0.5f; } void PerspectiveHelper::RemovePart(StackablePart::Pointer part) { // Reparent the part back to the main window void* parent = mainLayout->GetParent(); part->Reparent(parent); // Replace part with a placeholder IStackableContainer::Pointer container = part->GetContainer(); if (container != 0) { std::string placeHolderId = part->GetPlaceHolderId(); container->Replace(part, StackablePart::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. std::list children = container->GetChildren(); bool allInvisible = true; for (std::list::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 (std::list::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.remove(w); } } } } void PerspectiveHelper::ReplacePlaceholderWithPart(StackablePart::Pointer part) { // Look for a PartPlaceholder that will tell us how to position this // object std::vector placeholders = this->CollectPlaceholders(); for (unsigned int i = 0; i < placeholders.size(); i++) { if (placeholders[i]->GetCompoundId() == part->GetCompoundId()) { // found a matching placeholder which we can replace with the // new View IStackableContainer::Pointer container = placeholders[i]->GetContainer(); if (container != 0) { if (container.Cast () != 0) { // One of the children is now visible so replace the // ContainerPlaceholder with the real container ContainerPlaceholder::Pointer containerPlaceholder = container.Cast(); ILayoutContainer::Pointer parentContainer = containerPlaceholder->GetContainer(); container = containerPlaceholder->GetRealContainer(); if (container.Cast () != 0) { parentContainer->Replace(containerPlaceholder, container.Cast()); } containerPlaceholder->SetRealContainer(IStackableContainer::Pointer(0)); } container->Replace(placeholders[i], part); return; } } } } void PerspectiveHelper::ReplacePlaceholderWithPart(LayoutPart::Pointer part) { // Look for a ContainerPlaceholder that will tell us how to position this // object std::vector placeholders(this->CollectContainerPlaceholders()); for (std::size_t i = 0; i < placeholders.size(); i++) { if (placeholders[i]->GetID() == part->GetID()) { // found a matching placeholder which we can replace with the // new container ILayoutContainer::Pointer container = placeholders[i]->GetContainer(); if (container != 0) { // if (container.Cast () != 0) // { // // One of the children is now visible so replace the // // ContainerPlaceholder with the real container // ContainerPlaceholder::Pointer containerPlaceholder = // container.Cast(); // ILayoutContainer::Pointer parentContainer = // containerPlaceholder->GetContainer(); // container // = containerPlaceholder->GetRealContainer(); // if (container.Cast () != 0) // { // parentContainer->Replace(containerPlaceholder, // container.Cast()); // } // containerPlaceholder->SetRealContainer(IStackableContainer::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) { std::vector detachedWindows(memento->GetChildren( WorkbenchConstants::TAG_DETACHED_WINDOW)); for (std::vector::iterator iter = detachedWindows.begin(); iter != detachedWindows.end(); ++iter) { DetachedWindow::Pointer win(new DetachedWindow(page)); detachedWindowList.push_back(win); win->RestoreState(*iter); } std::vector childrenMem(memento->GetChildren( WorkbenchConstants::TAG_HIDDEN_WINDOW)); for (std::vector::iterator iter = childrenMem.begin(); iter != childrenMem.end(); ++iter) { DetachedPlaceHolder::Pointer holder( new DetachedPlaceHolder("", Rectangle(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 std::list kids = mainLayout->GetChildren(); for (std::list::iterator iter = kids.begin(); iter != kids.end(); ++iter) { if (iter->Cast () != 0) { PartStack::Pointer vs = iter->Cast(); boundsMap.insert(std::make_pair(vs->GetID(), vs->GetBounds())); } else if (iter->Cast () != 0) { EditorSashContainer::Pointer esc = iter->Cast(); boundsMap.insert(std::make_pair(esc->GetID(), esc->GetBounds())); } } } void PerspectiveHelper::ResetBoundsMap() { boundsMap.clear(); } Rectangle PerspectiveHelper::GetCachedBoundsFor(const std::string& id) { return boundsMap[id]; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveRegistry.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveRegistry.h index 54282a3496..b5f4e2e474 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveRegistry.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveRegistry.h @@ -1,310 +1,310 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPERSPECTIVEREGISTRY_H_ #define BERRYPERSPECTIVEREGISTRY_H_ -#include "../berryIPerspectiveRegistry.h" +#include "berryIPerspectiveRegistry.h" #include "berryPerspectiveDescriptor.h" #include namespace berry { /** * Perspective registry. */ class PerspectiveRegistry : public IPerspectiveRegistry { // IExtensionChangeHandler { friend class PerspectiveDescriptor; private: std::string defaultPerspID; static const std::string EXT; // = "_persp.xml"; static const std::string ID_DEF_PERSP; // = "PerspectiveRegistry.DEFAULT_PERSP"; static const std::string PERSP; // = "_persp"; static const char SPACE_DELIMITER; // = ' '; std::list perspectives; // keep track of the perspectives the user has selected to remove or revert std::list perspToRemove; //IPropertyChangeListener::Pointer preferenceListener; 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. */ PerspectiveDescriptor::Pointer CreatePerspective(const std::string& label, PerspectiveDescriptor::Pointer originalDescriptor); /** * Reverts a list of perspectives back to the plugin definition * * @param perspToRevert */ void RevertPerspectives(const std::list& perspToRevert); /** * Deletes a list of perspectives * * @param perspToDelete */ void DeletePerspectives(const std::list& 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.std::string) */ IPerspectiveDescriptor::Pointer FindPerspectiveWithId(const std::string& id); /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveRegistry#findPerspectiveWithLabel(java.lang.std::string) */ IPerspectiveDescriptor::Pointer FindPerspectiveWithLabel(const std::string& label); /** * @see IPerspectiveRegistry#getDefaultPerspective() */ std::string GetDefaultPerspective(); /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveRegistry#getPerspectives() */ std::vector 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 std::string& id); /** * @see IPerspectiveRegistry#setDefaultPerspective(std::string) */ void SetDefaultPerspective(const std::string& 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 std::string& label); /* * (non-Javadoc) * * @see org.blueberry.ui.IPerspectiveRegistry#clonePerspective(java.lang.std::string, * java.lang.std::string, org.blueberry.ui.IPerspectiveDescriptor) */ IPerspectiveDescriptor::Pointer ClonePerspective(const std::string& id, const std::string& 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]); // } // } 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; 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 std::string& 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/src/internal/berryPerspectiveRegistryReader.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveRegistryReader.cpp index 7173893dbd..f7226b0e02 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveRegistryReader.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPerspectiveRegistryReader.cpp @@ -1,63 +1,63 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryPerspectiveRegistryReader.h" #include "berryPerspectiveRegistry.h" #include "berryWorkbenchPlugin.h" -#include "../berryPlatformUI.h" +#include "berryPlatformUI.h" #include "berryWorkbenchRegistryConstants.h" namespace berry { PerspectiveRegistryReader::PerspectiveRegistryReader() { } void PerspectiveRegistryReader::ReadPerspectives(PerspectiveRegistry* out) { registry = out; this->ReadRegistry(PlatformUI::PLUGIN_ID, WorkbenchRegistryConstants::PL_PERSPECTIVES); } bool PerspectiveRegistryReader::ReadElement(IConfigurationElement::Pointer element) { if (element->GetName() == WorkbenchRegistryConstants::TAG_PERSPECTIVE) { try { std::string id; element->GetAttribute(WorkbenchRegistryConstants::ATT_ID, id); PerspectiveDescriptor::Pointer desc( new PerspectiveDescriptor(id, element)); registry->AddPerspective(desc); } catch (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/src/internal/berryPlaceholderFolderLayout.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPlaceholderFolderLayout.h index 53406e81d4..14c0b42431 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPlaceholderFolderLayout.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPlaceholderFolderLayout.h @@ -1,85 +1,85 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPLACEHOLDERFOLDERLAYOUT_H_ #define BERRYPLACEHOLDERFOLDERLAYOUT_H_ -#include "../berryIPlaceholderFolderLayout.h" +#include "berryIPlaceholderFolderLayout.h" #include "berryStackablePart.h" #include "berryPageLayout.h" namespace berry { /** * \ingroup org_blueberry_ui_internal * * This layout is used to define the initial set of placeholders * in a placeholder. *

    * Views are added to the placeholder by ID. This id is used to identify * a view descriptor in the view registry, and this descriptor is used to * instantiate the IViewPart. *

    */ class PlaceholderFolderLayout : public IPlaceholderFolderLayout { public: berryObjectMacro(PlaceholderFolderLayout) private: PageLayout::Pointer pageLayout; ContainerPlaceholder::Pointer placeholder; public: PlaceholderFolderLayout(PageLayout::Pointer pageLayout, ContainerPlaceholder::Pointer folder); /** * @see IPlaceholderFolderLayout */ void AddPlaceholder(const std::string& viewId); /* (non-Javadoc) * @see org.blueberry.ui.IPlaceholderFolderLayout#getProperty(java.lang.String) */ std::string GetProperty(const std::string& id); /* (non-Javadoc) * @see org.blueberry.ui.IPlaceholderFolderLayout#setProperty(java.lang.String, java.lang.String) */ void SetProperty(const std::string& id, const std::string& value); private: /** * Inform the page layout of the new part created * and the placeholder the part belongs to. */ void LinkPartToPageLayout(const std::string& viewId, StackablePart::Pointer newPart); }; } #endif /*BERRYPLACEHOLDERFOLDERLAYOUT_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentablePart.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentablePart.cpp index dc5791339e..4cc08acf74 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentablePart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentablePart.cpp @@ -1,318 +1,318 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryPresentablePart.h" -#include "../berryIWorkbenchPartConstants.h" +#include "berryIWorkbenchPartConstants.h" #include "berryPartPane.h" #include "berryWorkbenchPage.h" #include namespace berry { PresentablePart:: PropertyListenerProxy::PropertyListenerProxy(PresentablePart* p) : part(p) { } void PresentablePart:: PropertyListenerProxy::PropertyChange(PropertyChangeEvent::Pointer e) { if (e->GetProperty() == IWorkbenchPartConstants::INTEGER_PROPERTY) { // these are "part" events PropertyChangeEvent::Pointer event(new PropertyChangeEvent(Object::Pointer(part), e->GetProperty(), e->GetOldValue(), e->GetNewValue())); part->FirePropertyChange(event); } else { part->FirePropertyChange(e); } } IPropertyChangeListener::Pointer PresentablePart::GetPropertyListenerProxy() { if (lazyPropertyListenerProxy == 0) { lazyPropertyListenerProxy = new PropertyListenerProxy(this); } return lazyPropertyListenerProxy; } WorkbenchPartReference::Pointer PresentablePart::GetPartReference() const { return part->GetPartReference().Cast(); } void PresentablePart::FirePropertyChange(PropertyChangeEvent::Pointer event) { partPropertyChangeEvents.propertyChange(event); } void PresentablePart::FirePropertyChange(int propId) { ObjectInt::Pointer val(new ObjectInt(propId)); Object::Pointer source(this); PropertyChangeEvent::Pointer event(new PropertyChangeEvent(source, IWorkbenchPartConstants::INTEGER_PROPERTY, val, val)); this->FirePropertyChange(event); } PresentablePart::PresentablePart(PartPane::Pointer part, void* /*parent*/) { enableInputs = true; enableOutputs = true; isVisible = false; isDirty = false; isBusy = false; hasViewMenu = false; this->part = part; this->GetPane()->AddPropertyListener(this->GetPropertyListenerProxy()); } PartPane::Pointer PresentablePart::GetPane() const { return part; } PresentablePart::~PresentablePart() { // Ensure that the property listener is detached (necessary to prevent leaks) this->GetPane()->RemovePropertyListener(this->GetPropertyListenerProxy()); } void PresentablePart::AddPropertyListener(IPropertyChangeListener::Pointer listener) { partPropertyChangeEvents.AddListener(listener); } void PresentablePart::RemovePropertyListener( IPropertyChangeListener::Pointer listener) { partPropertyChangeEvents.RemoveListener(listener); } void PresentablePart::SetBounds(const Rectangle& bounds) { savedBounds = bounds; if (enableInputs && part != 0) { part->SetBounds(bounds); } } void PresentablePart::SetVisible(bool isVisible) { this->isVisible = isVisible; if (enableInputs) { part->SetVisible(isVisible); } } void PresentablePart::SetFocus() { if (part != 0) { if (part->GetPage()->GetActivePart() == part->GetPartReference()->GetPart(false)) { part->SetFocus(); } else { part->RequestActivation(); } } } std::string PresentablePart::GetName() const { if (enableOutputs) { return this->GetPartReference()->GetPartName(); } return name; } std::string PresentablePart::GetTitle() const { return this->GetPartReference()->GetPartName(); } std::string PresentablePart::GetTitleStatus() const { if (enableOutputs) { return this->GetPartReference()->GetContentDescription(); } return titleStatus; } void* PresentablePart::GetTitleImage() { if (enableOutputs) { return this->GetPartReference()->GetTitleImage(); } // return PlatformUI.getWorkbench().getSharedImages().getImage( // ISharedImages.IMG_DEF_VIEW); return 0; } std::string PresentablePart::GetTitleToolTip() const { return this->GetPartReference()->GetTitleToolTip(); } bool PresentablePart::IsDirty() const { if (enableOutputs) { return this->GetPartReference()->IsDirty(); } return isDirty; } bool PresentablePart::IsBusy() const { if (enableOutputs) { return part->IsBusy(); } return isBusy; } void* PresentablePart::GetToolBar() { if (enableOutputs) { return this->GetPane()->GetToolBar(); } return 0; } bool PresentablePart::IsCloseable() const { return part->IsCloseable(); } void* PresentablePart::GetControl() { return part->GetControl(); } void PresentablePart::EnableOutputs(bool isActive) { if (isActive == this->enableOutputs) { return; } this->enableOutputs = isActive; if (isActive) { if (isBusy != this->GetPane()->IsBusy()) { this->FirePropertyChange(PROP_BUSY); } if (isDirty != this->IsDirty()) { this->FirePropertyChange(PROP_DIRTY); } if (name != this->GetName()) { this->FirePropertyChange(PROP_PART_NAME); } if (titleStatus != this->GetTitleStatus()) { this->FirePropertyChange(PROP_CONTENT_DESCRIPTION); } if (hasViewMenu != this->GetPane()->HasViewMenu()) { this->FirePropertyChange(PROP_PANE_MENU); } // Always assume that the toolbar and title has changed (keeping track of this for real // would be too expensive) this->FirePropertyChange(PROP_TOOLBAR); this->FirePropertyChange(PROP_TITLE); this->GetPane()->AddPropertyListener(this->GetPropertyListenerProxy()); } else { this->GetPane()->RemovePropertyListener(this->GetPropertyListenerProxy()); WorkbenchPartReference::Pointer ref = this->GetPartReference(); isBusy = this->GetPane()->IsBusy(); isDirty = ref->IsDirty(); name = ref->GetPartName(); titleStatus = ref->GetContentDescription(); hasViewMenu = this->GetPane()->HasViewMenu(); this->FirePropertyChange(PROP_TITLE); this->FirePropertyChange(PROP_TOOLBAR); } } void PresentablePart::EnableInputs(bool isActive) { if (isActive == this->enableInputs) { return; } this->enableInputs = isActive; if (isActive) { if (isActive && part != 0) { part->SetBounds(savedBounds); } part->SetVisible(isVisible); } } std::string PresentablePart::GetPartProperty(const std::string& key) const { return this->GetPartReference()->GetPartProperty(key); } int PresentablePart::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredResult) { return this->GetPane()->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredResult); } int PresentablePart::GetSizeFlags(bool width) { return this->GetPane()->GetSizeFlags(width); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentablePart.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentablePart.h index 762463a0b4..084ab734eb 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentablePart.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentablePart.h @@ -1,266 +1,266 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPRESENTABLEPART_H_ #define BERRYPRESENTABLEPART_H_ -#include "../presentations/berryIPresentablePart.h" +#include "presentations/berryIPresentablePart.h" #include "berryWorkbenchPartReference.h" namespace berry { class PartPane; /** * This is a lightweight adapter that allows PartPanes to be used by a StackPresentation. All methods * either redirect directly to PartPane or do trivial type conversions. All listeners registered by * the presentation are kept here rather than registering them directly on the PartPane. This allows * us to remove all listeners registered by a presentation that has been disposed, offering some * protection against memory leaks. */ class PresentablePart: public IPresentablePart { public: berryObjectMacro(PresentablePart); private: SmartPointer part; /** * Local listener list -- we use this rather than registering listeners directly on the part * in order to protect against memory leaks in badly behaved presentations. */ //List listeners = new ArrayList(); // Lazily initialized. Use getPropertyListenerProxy() to access. IPropertyChangeListener::Pointer lazyPropertyListenerProxy; //ListenerList partPropertyChangeListeners = new ListenerList(); IPropertyChangeListener::Events partPropertyChangeEvents; //IPropertyChangeListener::Pointer lazyPartPropertyChangeListener; // Lazily initialized. Use getMenu() to access //IPartMenu viewMenu; // True iff the "set" methods on this object are talking to the real part (disabled // if the part is currently being managed by another presentation stack) bool enableInputs; // True iff the "get" methods are returning up-to-date info from the real part (disabled // for efficiency if the presentation is invisible) bool enableOutputs; Rectangle savedBounds; bool isVisible; // Saved state (only used when the part is inactive) std::string name; std::string titleStatus; bool isDirty; bool isBusy; bool hasViewMenu; struct PropertyListenerProxy: public IPropertyChangeListener { PropertyListenerProxy(PresentablePart* part); void PropertyChange(PropertyChangeEvent::Pointer e); private: PresentablePart* part; }; friend struct PropertyListenerProxy; IPropertyChangeListener::Pointer GetPropertyListenerProxy(); WorkbenchPartReference::Pointer GetPartReference() const; protected: void FirePropertyChange(int propId); void FirePropertyChange(PropertyChangeEvent::Pointer event); public: /** * Constructor * * @param part */ PresentablePart(SmartPointer part, void* parent); SmartPointer GetPane() const; /** * Detach this PresentablePart from the real part. No further methods should * be invoked on this object. */ ~PresentablePart(); // void firePropertyChange(int propertyId) { // for (int i = 0; i < listeners.size(); i++) { // ((IPropertyListener) listeners.get(i)).propertyChanged(this, propertyId); // } // } void AddPropertyListener(IPropertyChangeListener::Pointer listener); void RemovePropertyListener(IPropertyChangeListener::Pointer listener); // void addPartPropertyListener(IPropertyChangeListener listener) { // partPropertyChangeListeners.add(listener); // } // // void removePartPropertyListener(IPropertyChangeListener listener) { // partPropertyChangeListeners.remove(listener); // } /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#setBounds(org.blueberry.swt.graphics.Rectangle) */ void SetBounds(const Rectangle& bounds); /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#setVisible(boolean) */ void SetVisible(bool isVisible); /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#setFocus() */ void SetFocus(); /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#getName() */ std::string GetName() const; /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#getTitle() */ std::string GetTitle() const; /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#getTitleStatus() */ std::string GetTitleStatus() const; /* * (non-Javadoc) * * @see org.blueberry.ui.presentations.IPresentablePart#getTitleImage() */ void* GetTitleImage(); /* * (non-Javadoc) * * @see org.blueberry.ui.presentations.IPresentablePart#getTitleToolTip() */ std::string GetTitleToolTip() const; /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#isDirty() */ bool IsDirty() const; /* * (non-Javadoc) * * @see org.blueberry.ui.presentations.IPresentablePart#isBusy() */ bool IsBusy() const; /* * (non-Javadoc) * * @see org.blueberry.ui.presentations.IPresentablePart#getToolBar() */ void* GetToolBar(); /* * (non-Javadoc) * * @see org.blueberry.ui.presentations.IPresentablePart#getMenu() */ // IPartMenu getMenu() { // boolean hasMenu; // // if (enableOutputs) { // hasMenu = part.hasViewMenu(); // } else { // hasMenu = this.hasViewMenu; // } // // if (!hasMenu) { // return null; // } // // if (viewMenu == null) { // viewMenu = new IPartMenu() { // public void showMenu(Point location) { // part.showViewMenu(location); // } // }; // } // // return viewMenu; // } /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#isCloseable() */ bool IsCloseable() const; /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#getControl() */ void* GetControl(); void EnableOutputs(bool isActive); void EnableInputs(bool isActive); /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentablePart#getPartProperty(java.lang.String) */ std::string GetPartProperty(const std::string& key) const; /* (non-Javadoc) * @see org.blueberry.ui.ISizeProvider#computePreferredSize(boolean, int, int, int) */ int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredResult); /* (non-Javadoc) * @see org.blueberry.ui.ISizeProvider#getSizeFlags(boolean) */ int GetSizeFlags(bool width); }; } #endif /* BERRYPRESENTABLEPART_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentationFactoryUtil.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentationFactoryUtil.h index f58dcc69f6..b9d1ef2c39 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentationFactoryUtil.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentationFactoryUtil.h @@ -1,54 +1,54 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPRESENTATIONFACTORYUTIL_H_ #define BERRYPRESENTATIONFACTORYUTIL_H_ -#include "../presentations/berryIPresentationFactory.h" -#include "../presentations/berryIStackPresentationSite.h" -#include "../presentations/berryIPresentationSerializer.h" +#include "presentations/berryIPresentationFactory.h" +#include "presentations/berryIStackPresentationSite.h" +#include "presentations/berryIPresentationSerializer.h" namespace berry { class PresentationFactoryUtil { public: static const int ROLE_EDITOR; // = 0x01; static const int ROLE_VIEW; // = 0x02; static const int ROLE_STANDALONE; // = 0x03; static const int ROLE_STANDALONE_NOTITLE; // = 0x04; static StackPresentation::Pointer CreatePresentation( IPresentationFactory* factory, int role, void* parent, IStackPresentationSite::Pointer site, IPresentationSerializer* serializer, IMemento::Pointer memento); private: PresentationFactoryUtil(); }; } #endif /* BERRYPRESENTATIONFACTORYUTIL_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentationSerializer.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentationSerializer.h index 56b525dccd..b2082fe205 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentationSerializer.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryPresentationSerializer.h @@ -1,58 +1,58 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYPRESENTATIONSERIALIZER_H_ #define BERRYPRESENTATIONSERIALIZER_H_ -#include "../presentations/berryIPresentationSerializer.h" -#include "../presentations/berryIPresentablePart.h" +#include "presentations/berryIPresentationSerializer.h" +#include "presentations/berryIPresentablePart.h" #include namespace berry { /** * This class is used to map IPresentableParts onto string IDs */ class PresentationSerializer: public IPresentationSerializer { private: std::vector parts; public: PresentationSerializer( const std::vector& presentableParts); /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentationSerializer#getId(org.blueberry.ui.presentations.IPresentablePart) */ std::string GetId(IPresentablePart::Pointer part); /* (non-Javadoc) * @see org.blueberry.ui.presentations.IPresentationSerializer#getPart(java.lang.String) */ IPresentablePart::Pointer GetPart(const std::string& id); }; } #endif /* BERRYPRESENTATIONSERIALIZER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryQtDnDControlWidget.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryQtDnDControlWidget.h index 74f29e723b..4df85d818d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryQtDnDControlWidget.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryQtDnDControlWidget.h @@ -1,55 +1,55 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYQTDNDCONTROLWIDGET_H #define BERRYQTDNDCONTROLWIDGET_H #include "berryQtControlWidget.h" -#include "../berryIDropTargetListener.h" +#include "berryIDropTargetListener.h" #include namespace berry { class QtDnDControlWidget : public QtControlWidget { public: QtDnDControlWidget(QWidget *parent = 0); void SetTransferTypes(const QStringList& types); void AddDropListener(IDropTargetListener* listener); void RemoveDropListener(IDropTargetListener* listener); protected: void dragEnterEvent(QDragEnterEvent* event); void dragMoveEvent(QDragMoveEvent* event); void dragLeaveEvent(QDragLeaveEvent* event); void dropEvent(QDropEvent* event); private: IDropTargetListener::Events dndEvents; QStringList transferTypes; }; } #endif // BERRYQTDNDCONTROLWIDGET_H diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryRegistryReader.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryRegistryReader.cpp index 55b4c8f6ca..254ab6b221 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryRegistryReader.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryRegistryReader.cpp @@ -1,152 +1,152 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include #include "berryRegistryReader.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchRegistryConstants.h" -#include "../berryImageDescriptor.h" +#include "berryImageDescriptor.h" namespace berry { RegistryReader::RegistryReader() { } RegistryReader::~RegistryReader() { } void RegistryReader::LogError(IConfigurationElement::Pointer element, const std::string& text) { const IExtension* extension = element->GetDeclaringExtension(); std::string buf = "Plugin " + extension->GetNamespace() + ", extension " + extension->GetExtensionPointIdentifier(); // look for an ID if available - this should help debugging std::string id; if (element->GetAttribute("id", id)) { buf.append(", id "); buf.append(id); } buf.append(": " + text); WorkbenchPlugin::Log(buf); } void RegistryReader::LogMissingAttribute( IConfigurationElement::Pointer element, const std::string& attributeName) { RegistryReader::LogError(element, "Required attribute '" + attributeName + "' not defined");//$NON-NLS-2$//$NON-NLS-1$ } void RegistryReader::LogMissingElement( IConfigurationElement::Pointer element, const std::string& elementName) { RegistryReader::LogError(element, "Required sub element '" + elementName + "' not defined");//$NON-NLS-2$//$NON-NLS-1$ } void RegistryReader::LogUnknownElement( IConfigurationElement::Pointer element) { RegistryReader::LogError(element, "Unknown extension tag found: " + element->GetName());//$NON-NLS-1$ } const std::vector RegistryReader::OrderExtensions( const std::vector& 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. std::vector sortedExtension(extensions); std::stable_sort(sortedExtension.begin(), sortedExtension.end()); return sortedExtension; } void RegistryReader::ReadElementChildren( IConfigurationElement::Pointer element) { this->ReadElements(element->GetChildren()); } void RegistryReader::ReadElements( const std::vector& elements) { for (unsigned int i = 0; i < elements.size(); i++) { if (!this->ReadElement(elements[i])) { RegistryReader::LogUnknownElement(elements[i]); } } } void RegistryReader::ReadExtension(const IExtension* extension) { this->ReadElements(extension->GetConfigurationElements()); } void RegistryReader::ReadRegistry( const std::string& pluginId, const std::string& extensionPoint) { const IExtensionPoint* point = Platform::GetExtensionPointService()->GetExtensionPoint(pluginId + "." + extensionPoint); if (point == 0) { return; } std::vector extensions(point->GetExtensions()); extensions = this->OrderExtensions(extensions); for (unsigned int i = 0; i < extensions.size(); i++) { this->ReadExtension(extensions[i]); } } std::string RegistryReader::GetDescription(IConfigurationElement::Pointer configElement) { IConfigurationElement::vector children(configElement->GetChildren(WorkbenchRegistryConstants::TAG_DESCRIPTION)); if (children.size() >= 1) { return children[0]->GetValue(); } return "";//$NON-NLS-1$ } std::string RegistryReader::GetClassValue( IConfigurationElement::Pointer configElement, const std::string& classAttributeName) { std::string className; if (configElement->GetAttribute(classAttributeName, className)) { return className; } IConfigurationElement::vector candidateChildren(configElement->GetChildren(classAttributeName)); if (candidateChildren.size() == 0) { return ""; } candidateChildren[0]->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS, className); return className; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berrySaveablesList.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berrySaveablesList.cpp index 9122c9751e..9570ed1f4a 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berrySaveablesList.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berrySaveablesList.cpp @@ -1,638 +1,638 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berrySaveablesList.h" #include "berryWorkbenchPlugin.h" #include "berryDefaultSaveable.h" -#include "../berryImageDescriptor.h" +#include "berryImageDescriptor.h" -#include "../berryWorkbenchPart.h" +#include "berryWorkbenchPart.h" namespace berry { bool SaveablesList::AddModel(Object::Pointer source, Saveable::Pointer model) { if (model == 0) { this->LogWarning("Ignored attempt to add invalid saveable", source, model); //$NON-NLS-1$ return false; } bool result = false; Saveable::Set& modelsForSource = modelMap[source.GetPointer()]; if (modelsForSource.find(model) == modelsForSource.end()) { modelsForSource.insert(model); result = this->IncrementRefCount(modelRefCounts, model); } else { this->LogWarning("Ignored attempt to add saveable that was already registered", source, model); //$NON-NLS-1$ } return result; } bool SaveablesList::IncrementRefCount( std::map& referenceMap, Saveable::Pointer key) { bool result = false; int& refCount = referenceMap[key]; if (refCount == 0) { result = true; } refCount++; return result; } bool SaveablesList::DecrementRefCount( std::map& referenceMap, Saveable::Pointer key) { bool result = false; int& refCount = referenceMap[key]; poco_assert(refCount != 0); if (refCount == 1) { referenceMap.erase(key); result = true; } else { --refCount; } return result; } bool SaveablesList::RemoveModel(Object::Pointer source, Saveable::Pointer model) { bool result = false; std::map::iterator it = modelMap.find(source.GetPointer()); if (it == modelMap.end()) { this->LogWarning( "Ignored attempt to remove a saveable when no saveables were known", source, model); //$NON-NLS-1$ } else { Saveable::Set& modelsForSource = it->second; if (modelsForSource.erase(model) != 0) { result = this->DecrementRefCount(modelRefCounts, model); if (modelsForSource.empty()) { modelMap.erase(source.GetPointer()); } } else { this->LogWarning( "Ignored attempt to remove a saveable that was not registered", source, model); //$NON-NLS-1$ } } return result; } void SaveablesList::LogWarning(const std::string& message, Object::Pointer source, Saveable::Pointer model) { // create a new exception std::string text = message + "; " + "unknown saveable: " + model->GetName() + " from part: " + source->GetClassName(); // record the current stack trace to help with debugging //assertionFailedException.fillInStackTrace(); WorkbenchPlugin::Log(text); } void SaveablesList::UpdateNonPartSource(ISaveablesSource::Pointer source) { std::vector saveables = source->GetSaveables(); if (saveables.empty()) { nonPartSources.erase(source); } else { nonPartSources.insert(source); } } void SaveablesList::RemoveModels(Object::Pointer source, const std::vector& modelArray) { std::vector removed; for (unsigned int i = 0; i < modelArray.size(); i++) { Saveable::Pointer model = modelArray[i]; if (this->RemoveModel(source, model)) { removed.push_back(model); } } if (removed.size() > 0) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source, SaveablesLifecycleEvent::POST_OPEN, removed, false)); this->FireModelLifecycleEvent(event); } } void SaveablesList::AddModels(Object::Pointer source, const std::vector& modelArray) { std::vector added; for (unsigned int i = 0; i < modelArray.size(); i++) { Saveable::Pointer model = modelArray[i]; if (this->AddModel(source, model)) { added.push_back(model); } } if (added.size() > 0) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source, SaveablesLifecycleEvent::POST_OPEN, added, false)); this->FireModelLifecycleEvent(event); } } void SaveablesList::FireModelLifecycleEvent( SaveablesLifecycleEvent::Pointer event) { events.lifecycleChange(event); } bool SaveablesList::PromptForSavingIfNecessary( IWorkbenchWindow::Pointer /*window*/, const Saveable::Set& /*modelsClosing*/, const std::map& /*modelsDecrementing*/, bool /*canCancel*/) { // List modelsToOptionallySave = new ArrayList(); // for (Iterator it = modelsDecrementing.keySet().iterator(); it.hasNext();) // { // Saveable modelDecrementing = (Saveable) it.next(); // if (modelDecrementing.isDirty() && !modelsClosing.contains( // modelDecrementing)) // { // modelsToOptionallySave.add(modelDecrementing); // } // } // // boolean shouldCancel = // modelsToOptionallySave.isEmpty() ? false : promptForSaving( // modelsToOptionallySave, window, window, canCancel, true); // // if (shouldCancel) // { // return true; // } // // List modelsToSave = new ArrayList(); // for (Iterator it = modelsClosing.iterator(); it.hasNext();) // { // Saveable modelClosing = (Saveable) it.next(); // if (modelClosing.isDirty()) // { // modelsToSave.add(modelClosing); // } // } // return modelsToSave.isEmpty() ? false : promptForSaving(modelsToSave, window, // window, canCancel, false); return false; } void SaveablesList::FillModelsClosing(Saveable::Set& modelsClosing, const std::map& modelsDecrementing) { for (std::map::const_iterator it = modelsDecrementing.begin(); it != modelsDecrementing.end(); ++it) { Saveable::Pointer model = it->first; if (it->second == modelRefCounts[model]) { modelsClosing.insert(model); } } } std::vector SaveablesList::GetSaveables( IWorkbenchPart::Pointer part) { if (part.Cast () != 0) { ISaveablesSource::Pointer source = part.Cast(); return source->GetSaveables(); } else if (part.Cast () != 0) { std::vector result; Saveable::Pointer defaultSaveable(new DefaultSaveable(part)); result.push_back(defaultSaveable); return result; } else { return std::vector(); } } Saveable::Set SaveablesList::GetOpenModels() { Saveable::Set allDistinctModels; for (std::map::iterator it = modelMap.begin(); it != modelMap.end(); ++it) allDistinctModels.insert(it->second.begin(), it->second.end()); return allDistinctModels; } void SaveablesList::HandleLifecycleEvent(SaveablesLifecycleEvent::Pointer event) { if (event->GetSource().Cast () == 0) { // just update the set of non-part sources. No prompting necessary. // See bug 139004. this->UpdateNonPartSource(event->GetSource().Cast()); return; } std::vector modelArray = event->GetSaveables(); int eventType = event->GetEventType(); if (eventType == SaveablesLifecycleEvent::POST_OPEN) { this->AddModels(event->GetSource(), modelArray); } else if (eventType == SaveablesLifecycleEvent::PRE_CLOSE) { std::vector models = event->GetSaveables(); std::map modelsDecrementing; Saveable::Set modelsClosing; for (unsigned int i = 0; i < models.size(); i++) { this->IncrementRefCount(modelsDecrementing, models[i]); } this->FillModelsClosing(modelsClosing, modelsDecrementing); bool canceled = this->PromptForSavingIfNecessary( PlatformUI::GetWorkbench()->GetActiveWorkbenchWindow(), modelsClosing, modelsDecrementing, !event->IsForce()); if (canceled) { event->SetVeto(true); } } else if (eventType == SaveablesLifecycleEvent::POST_CLOSE) { this->RemoveModels(event->GetSource(), modelArray); } else if (eventType == SaveablesLifecycleEvent::DIRTY_CHANGED) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer event( new SaveablesLifecycleEvent(source, event->GetEventType(), event->GetSaveables(), false)); this->FireModelLifecycleEvent(event); } } void SaveablesList::AddModelLifecycleListener( ISaveablesLifecycleListener::Pointer listener) { events.AddListener(listener); } void SaveablesList::RemoveModelLifecycleListener( ISaveablesLifecycleListener::Pointer listener) { events.RemoveListener(listener); } SaveablesList::PostCloseInfo::Pointer SaveablesList::PreCloseParts( const std::list& partsToClose, bool save, IWorkbenchWindow::Pointer window) { // reference count (how many occurrences of a model will go away?) PostCloseInfo::Pointer postCloseInfo(new PostCloseInfo()); for (std::list::const_iterator it = partsToClose.begin(); it != partsToClose.end(); ++it) { WorkbenchPart::Pointer part = it->Cast(); postCloseInfo->partsClosing.push_back(part); if (part.Cast () != 0) { ISaveablePart::Pointer saveablePart = part.Cast(); if (save && !saveablePart->IsSaveOnCloseNeeded()) { // pretend for now that this part is not closing continue; } } // if (save && part.Cast () != 0) // { // ISaveablePart2 saveablePart2 = (ISaveablePart2) part; // // TODO show saveablePart2 before prompting, see // // EditorManager.saveAll // int response = SaveableHelper.savePart(saveablePart2, window, true); // if (response == ISaveablePart2.CANCEL) // { // // user canceled // return 0; // } // else if (response != ISaveablePart2.DEFAULT) // { // // only include this part in the following logic if it returned // // DEFAULT // continue; // } // } std::vector modelsFromSource = this->GetSaveables(part); for (unsigned int i = 0; i < modelsFromSource.size(); i++) { this->IncrementRefCount(postCloseInfo->modelsDecrementing, modelsFromSource[i]); } } this->FillModelsClosing(postCloseInfo->modelsClosing, postCloseInfo->modelsDecrementing); if (save) { bool canceled = this->PromptForSavingIfNecessary(window, postCloseInfo->modelsClosing, postCloseInfo->modelsDecrementing, true); if (canceled) { return PostCloseInfo::Pointer(0); } } return postCloseInfo; } bool SaveablesList::PromptForSaving( const std::list& /*modelsToSave*/, /*final IShellProvider shellProvider, IRunnableContext runnableContext,*/ bool /*canCancel*/, bool /*stillOpenElsewhere*/) { // // Save parts, exit the method if cancel is pressed. // if (modelsToSave.size() > 0) { // boolean canceled = SaveableHelper.waitForBackgroundSaveJobs(modelsToSave); // if (canceled) { // return true; // } // // IPreferenceStore apiPreferenceStore = PrefUtil.getAPIPreferenceStore(); // boolean dontPrompt = stillOpenElsewhere && !apiPreferenceStore.getBoolean(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN); // // if (dontPrompt) { // modelsToSave.clear(); // return false; // } else if (modelsToSave.size() == 1) { // Saveable model = (Saveable) modelsToSave.get(0); // // Show a dialog. // std::vector buttons; // if(canCancel) { // buttons.push_back(IDialogConstants.YES_LABEL); // buttons.push_back(IDialogConstants.NO_LABEL); // buttons.push_back(IDialogConstants.CANCEL_LABEL); // } else { // buttons.push_back(IDialogConstants.YES_LABEL); // buttons.push_back(IDialogConstants.NO_LABEL); // } // // // don't save if we don't prompt // int choice = ISaveablePart2.NO; // // MessageDialog dialog; // if (stillOpenElsewhere) { // String message = NLS // .bind( // WorkbenchMessages.EditorManager_saveChangesOptionallyQuestion, // model.getName()); // MessageDialogWithToggle dialogWithToggle = new MessageDialogWithToggle(shellProvider.getShell(), // WorkbenchMessages.Save_Resource, 0, message, // MessageDialog.QUESTION, buttons, 0, WorkbenchMessages.EditorManager_closeWithoutPromptingOption, false) { // protected int getShellStyle() { // return (canCancel ? SWT.CLOSE : SWT.NONE) // | SWT.TITLE | SWT.BORDER // | SWT.APPLICATION_MODAL // | getDefaultOrientation(); // } // }; // dialog = dialogWithToggle; // } else { // String message = NLS // .bind( // WorkbenchMessages.EditorManager_saveChangesQuestion, // model.getName()); // dialog = new MessageDialog(shellProvider.getShell(), // WorkbenchMessages.Save_Resource, 0, message, // MessageDialog.QUESTION, buttons, 0) { // protected int getShellStyle() { // return (canCancel ? SWT.CLOSE : SWT.NONE) // | SWT.TITLE | SWT.BORDER // | SWT.APPLICATION_MODAL // | getDefaultOrientation(); // } // }; // } // // choice = SaveableHelper.testGetAutomatedResponse(); // if (SaveableHelper.testGetAutomatedResponse() == SaveableHelper.USER_RESPONSE) { // choice = dialog.open(); // // if(stillOpenElsewhere) { // // map value of choice back to ISaveablePart2 values // switch (choice) { // case IDialogConstants.YES_ID: // choice = ISaveablePart2.YES; // break; // case IDialogConstants.NO_ID: // choice = ISaveablePart2.NO; // break; // case IDialogConstants.CANCEL_ID: // choice = ISaveablePart2.CANCEL; // break; // default: // break; // } // MessageDialogWithToggle dialogWithToggle = (MessageDialogWithToggle) dialog; // if (choice != ISaveablePart2.CANCEL && dialogWithToggle.getToggleState()) { // apiPreferenceStore.setValue(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN, false); // } // } // } // // // Branch on the user choice. // // The choice id is based on the order of button labels // // above. // switch (choice) { // case ISaveablePart2.YES: // yes // break; // case ISaveablePart2.NO: // no // modelsToSave.clear(); // break; // default: // case ISaveablePart2.CANCEL: // cancel // return true; // } // } else { // MyListSelectionDialog dlg = new MyListSelectionDialog( // shellProvider.getShell(), // modelsToSave, // new ArrayContentProvider(), // new WorkbenchPartLabelProvider(), // stillOpenElsewhere ? WorkbenchMessages.EditorManager_saveResourcesOptionallyMessage // : WorkbenchMessages.EditorManager_saveResourcesMessage, // canCancel, stillOpenElsewhere); // dlg.setInitialSelections(modelsToSave.toArray()); // dlg.setTitle(EditorManager.SAVE_RESOURCES_TITLE); // // // this "if" statement aids in testing. // if (SaveableHelper.testGetAutomatedResponse() == SaveableHelper.USER_RESPONSE) { // int result = dlg.open(); // // Just return 0 to prevent the operation continuing // if (result == IDialogConstants.CANCEL_ID) // return true; // // if (dlg.getDontPromptSelection()) { // apiPreferenceStore.setValue(IWorkbenchPreferenceConstants.PROMPT_WHEN_SAVEABLE_STILL_OPEN, false); // } // // modelsToSave = Arrays.asList(dlg.getResult()); // } // } // } // // Create save block. // return saveModels(modelsToSave, shellProvider, runnableContext); return true; } bool SaveablesList::SaveModels(const std::list& /*finalModels*/ /*final IShellProvider shellProvider, IRunnableContext runnableContext*/) { // IRunnableWithProgress progressOp = new IRunnableWithProgress() { // public void run(IProgressMonitor monitor) { // IProgressMonitor monitorWrap = new EventLoopProgressMonitor( // monitor); // monitorWrap.beginTask("", finalModels.size()); //$NON-NLS-1$ // for (Iterator i = finalModels.iterator(); i.hasNext();) { // Saveable model = (Saveable) i.next(); // // handle case where this model got saved as a result of // // saving another // if (!model.isDirty()) { // monitor.worked(1); // continue; // } // SaveableHelper.doSaveModel(model, new SubProgressMonitor(monitorWrap, 1), shellProvider, true); // if (monitorWrap.isCanceled()) // break; // } // monitorWrap.done(); // } // }; // // // Do the save. // return !SaveableHelper.runProgressMonitorOperation( // WorkbenchMessages.Save_All, progressOp, runnableContext, // shellProvider); return true; } void SaveablesList::PostClose(PostCloseInfo::Pointer postCloseInfo) { std::vector removed; for (std::list::const_iterator it = postCloseInfo->partsClosing.begin(); it != postCloseInfo->partsClosing.end(); ++it) { IWorkbenchPart::Pointer part = *it; std::map::iterator it2 = modelMap.find(part.GetPointer()); if (it2 != modelMap.end()) { // make a copy to avoid a ConcurrentModificationException - we // will remove from the original set as we iterate Saveable::Set saveables(it2->second); for (Saveable::Set::const_iterator it3 = saveables.begin(); it3 != saveables.end(); ++it3) { if (RemoveModel(part, *it3)) { removed.push_back(*it3); } } } } if (!removed.empty()) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source, SaveablesLifecycleEvent::POST_CLOSE, removed, false)); this->FireModelLifecycleEvent(event); } } void SaveablesList::PostOpen(IWorkbenchPart::Pointer part) { this->AddModels(part, this->GetSaveables(part)); } void SaveablesList::DirtyChanged(IWorkbenchPart::Pointer part) { std::vector saveables = this->GetSaveables(part); if (saveables.size() > 0) { Object::Pointer source(this); SaveablesLifecycleEvent::Pointer event(new SaveablesLifecycleEvent(source, SaveablesLifecycleEvent::DIRTY_CHANGED, saveables, false)); this->FireModelLifecycleEvent(event); } } std::vector SaveablesList::TestGetSourcesForModel( Saveable::Pointer /*model*/) { std::vector result; // for (Iterator it = modelMap.entrySet().iterator(); it.hasNext();) { // Map.Entry entry = (Map.Entry) it.next(); // Set values = (Set) entry.getValue(); // if (values.contains(model)) { // result.add(entry.getKey()); // } // } return result; } std::vector SaveablesList::GetNonPartSources() { std::vector result(nonPartSources.begin(), nonPartSources.end()); return result; } std::vector SaveablesList::GetPartsForSaveable( Saveable::Pointer model) { std::vector result; for (std::map::iterator it = modelMap.begin(); it != modelMap.end(); ++it) { Saveable::Set& values = it->second; IWorkbenchPart::Pointer part(dynamic_cast(it->first)); if (values.find(model) != values.end() && part) { result.push_back(part); } } return result; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berrySaveablesList.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berrySaveablesList.h index 8df86cfe40..dd23809d84 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berrySaveablesList.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berrySaveablesList.h @@ -1,363 +1,363 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYSAVEABLESLIST_H_ #define BERRYSAVEABLESLIST_H_ -#include "../berryISaveablesLifecycleListener.h" +#include "berryISaveablesLifecycleListener.h" -#include "../berryISaveablesSource.h" -#include "../berryIWorkbenchWindow.h" -#include "../berryIWorkbenchPart.h" +#include "berryISaveablesSource.h" +#include "berryIWorkbenchWindow.h" +#include "berryIWorkbenchPart.h" -#include "../berryWorkbenchPart.h" +#include "berryWorkbenchPart.h" #include #include #include #include namespace berry { /** * The model manager maintains a list of open saveable models. * * @see Saveable * @see ISaveablesSource * * @since 3.2 */ class SaveablesList: public ISaveablesLifecycleListener { public: berryObjectMacro(SaveablesList); private: ISaveablesLifecycleListener::Events events; // event source (mostly ISaveablesSource) -> Set of Saveable std::map modelMap; // reference counting map, Saveable -> Integer std::map modelRefCounts; std::set nonPartSources; // returns true if this model has not yet been in getModels() bool AddModel(Object::Pointer source, Saveable::Pointer model); /** * returns true if the given key was added for the first time * * @param referenceMap * @param key * @return true if the ref count of the given key is now 1 */ bool IncrementRefCount(std::map& referenceMap, Saveable::Pointer key); /** * returns true if the given key has been removed * * @param referenceMap * @param key * @return true if the ref count of the given key was 1 */ bool DecrementRefCount(std::map& referenceMap, Saveable::Pointer key); // returns true if this model was removed from getModels(); bool RemoveModel(Object::Pointer source, Saveable::Pointer model); void LogWarning(const std::string& message, Object::Pointer source, Saveable::Pointer model); /** * Updates the set of non-part saveables sources. * @param source */ void UpdateNonPartSource(ISaveablesSource::Pointer source); /** * @param source * @param modelArray */ void RemoveModels(Object::Pointer source, const std::vector& modelArray); /** * @param source * @param modelArray */ void AddModels(Object::Pointer source, const std::vector& modelArray); /** * @param event */ void FireModelLifecycleEvent(SaveablesLifecycleEvent::Pointer event); /** * @param window * @param modelsClosing * @param canCancel * @return true if the user canceled */ bool PromptForSavingIfNecessary(IWorkbenchWindow::Pointer window, const Saveable::Set& modelsClosing, const std::map& modelsDecrementing, bool canCancel); /** * @param modelsClosing * @param modelsDecrementing */ void FillModelsClosing(Saveable::Set& modelsClosing, const std::map& modelsDecrementing); /** * Returns the saveable models provided by the given part. If the part does * not provide any models, a default model is returned representing the * part. * * @param part * the workbench part * @return the saveable models */ std::vector GetSaveables(IWorkbenchPart::Pointer part); //TODO SaveablesList ListSelectionDialog // class MyListSelectionDialog extends // ListSelectionDialog { // private final boolean canCancel; // private Button checkbox; // private boolean dontPromptSelection; // private boolean stillOpenElsewhere; // // private MyListSelectionDialog(Shell shell, Object input, // IStructuredContentProvider contentprovider, // ILabelProvider labelProvider, String message, boolean canCancel, boolean stillOpenElsewhere) { // super(shell, input, contentprovider, labelProvider, message); // this.canCancel = canCancel; // this.stillOpenElsewhere = stillOpenElsewhere; // if (!canCancel) { // int shellStyle = getShellStyle(); // shellStyle &= ~SWT.CLOSE; // setShellStyle(shellStyle); // } // } // // /** // * @return // */ // public boolean getDontPromptSelection() { // return dontPromptSelection; // } // // protected void createButtonsForButtonBar(Composite parent) { // createButton(parent, IDialogConstants.OK_ID, // IDialogConstants.OK_LABEL, true); // if (canCancel) { // createButton(parent, IDialogConstants.CANCEL_ID, // IDialogConstants.CANCEL_LABEL, false); // } // } // // protected Control createDialogArea(Composite parent) { // Composite dialogAreaComposite = (Composite) super.createDialogArea(parent); // // if (stillOpenElsewhere) { // Composite checkboxComposite = new Composite(dialogAreaComposite, SWT.NONE); // checkboxComposite.setLayout(new GridLayout(2, false)); // // checkbox = new Button(checkboxComposite, SWT.CHECK); // checkbox.addSelectionListener(new SelectionAdapter() { // public void widgetSelected(SelectionEvent e) { // dontPromptSelection = checkbox.getSelection(); // } // }); // GridData gd = new GridData(); // gd.horizontalAlignment = SWT.BEGINNING; // checkbox.setLayoutData(gd); // // Label label = new Label(checkboxComposite, SWT.NONE); // label.setText(WorkbenchMessages.EditorManager_closeWithoutPromptingOption); // gd = new GridData(); // gd.grabExcessHorizontalSpace = true; // gd.horizontalAlignment = SWT.BEGINNING; // } // // return dialogAreaComposite; // } // } public: struct PostCloseInfo : public Object { berryObjectMacro(PostCloseInfo); std::list > partsClosing; std::map modelsDecrementing; Saveable::Set modelsClosing; private: PostCloseInfo() {} friend class SaveablesList; }; /** * Returns the list of open models managed by this model manager. * * @return a list of models */ Saveable::Set GetOpenModels(); /** * This implementation of handleModelLifecycleEvent must be called by * implementers of ISaveablesSource whenever the list of models of the model * source changes, or when the dirty state of models changes. The * ISaveablesSource instance must be passed as the source of the event * object. *

    * This method may also be called by objects that hold on to models but are * not workbench parts. In this case, the event source must be set to an * object that is not an instanceof IWorkbenchPart. *

    *

    * Corresponding open and close events must originate from the same * (identical) event source. *

    *

    * This method must be called on the UI thread. *

    */ void HandleLifecycleEvent(SaveablesLifecycleEvent::Pointer event); /** * Adds the given listener to the list of listeners. Has no effect if the * same (identical) listener has already been added. The listener will be * notified about changes to the models managed by this model manager. Event * types include:
    * POST_OPEN when models were added to the list of models
    * POST_CLOSE when models were removed from the list of models
    * DIRTY_CHANGED when the dirty state of models changed *

    * Listeners should ignore all other event types, including PRE_CLOSE. There * is no guarantee that listeners are notified before models are closed. * * @param listener */ void AddModelLifecycleListener(ISaveablesLifecycleListener::Pointer listener); /** * Removes the given listener from the list of listeners. Has no effect if * the given listener is not contained in the list. * * @param listener */ void RemoveModelLifecycleListener( ISaveablesLifecycleListener::Pointer listener); /** * @param partsToClose * @param save * @param window * @return the post close info to be passed to postClose */ PostCloseInfo::Pointer PreCloseParts( const std::list >& partsToClose, bool save, IWorkbenchWindow::Pointer window); /** * Prompt the user to save the given saveables. * @param modelsToSave the saveables to be saved * @param shellProvider the provider used to obtain a shell in prompting is * required. Clients can use a workbench window for this. * @param runnableContext a runnable context that will be used to provide a * progress monitor while the save is taking place. Clients can * use a workbench window for this. * @param canCancel whether the operation can be canceled * @param stillOpenElsewhere whether the models are referenced by open parts * @return true if the user canceled */ bool PromptForSaving(const std::list& modelsToSave, /*final IShellProvider shellProvider, IRunnableContext runnableContext,*/ bool canCancel, bool stillOpenElsewhere); /** * Save the given models. * @param finalModels the list of models to be saved * @param shellProvider the provider used to obtain a shell in prompting is * required. Clients can use a workbench window for this. * @param runnableContext a runnable context that will be used to provide a * progress monitor while the save is taking place. Clients can * use a workbench window for this. * @return true if the operation was canceled */ bool SaveModels(const std::list& finalModels /*final IShellProvider shellProvider, IRunnableContext runnableContext*/); /** * @param postCloseInfoObject */ void PostClose(PostCloseInfo::Pointer postCloseInfoObject); /** * @param actualPart */ void PostOpen(IWorkbenchPart::Pointer part); /** * @param actualPart */ void DirtyChanged(IWorkbenchPart::Pointer part); /** * For testing purposes. Not to be called by clients. * * @param model * @return */ std::vector TestGetSourcesForModel(Saveable::Pointer model); /** * @return a list of ISaveablesSource objects registered with this saveables * list which are not workbench parts. */ std::vector GetNonPartSources(); /** * @param model */ std::vector GetPartsForSaveable( Saveable::Pointer model); }; } #endif /* BERRYSAVEABLESLIST_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryServiceLocator.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryServiceLocator.cpp index bd77332692..203ee4139c 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryServiceLocator.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryServiceLocator.cpp @@ -1,234 +1,234 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryServiceLocator.h" #include "berryWorkbenchServiceRegistry.h" -#include "../services/berryIServiceFactory.h" -#include "../services/berryINestable.h" +#include "services/berryIServiceFactory.h" +#include "services/berryINestable.h" #include namespace berry { ServiceLocator::ParentLocator::ParentLocator(const IServiceLocator::WeakPtr parent, const std::string& serviceInterface) : locator(parent), key(serviceInterface) { } Object::Pointer ServiceLocator::ParentLocator::GetService( const std::string& api) { if (key == api) { try { return locator.Lock()->GetService(key); } catch (const BadWeakPointerException& /*e*/) { } } return Object::Pointer(0); } bool ServiceLocator::ParentLocator::HasService(const std::string& api) const { if (key == api) { return true; } return false; } ServiceLocator::ServiceLocator() : activated(false), disposed(false) { } ServiceLocator::ServiceLocator(const IServiceLocator::WeakPtr _parent, const IServiceFactory::ConstPointer _factory, IDisposable::WeakPtr _owner) : activated(false), factory(_factory), parent(_parent), disposed(false), owner(_owner) { } void ServiceLocator::Activate() { activated = true; for (KeyToServiceMapType::iterator serviceItr = services.begin(); serviceItr != services.end(); ++serviceItr) { Object::Pointer service = serviceItr->second; if (INestable::Pointer nestableService = service.Cast()) { nestableService->Activate(); } } } void ServiceLocator::Deactivate() { activated = false; for (KeyToServiceMapType::iterator serviceItr = services.begin(); serviceItr != services.end(); ++serviceItr) { Object::Pointer service = serviceItr->second; if (INestable::Pointer nestableService = service.Cast()) { nestableService->Deactivate(); } } } void ServiceLocator::Dispose() { for (KeyToServiceMapType::iterator serviceItr = services.begin(); serviceItr != services.end(); ++serviceItr) { Object::Pointer object = serviceItr->second; if (IDisposable::Pointer service = object.Cast()) { service->Dispose(); } } services.clear(); parent.Reset(); disposed = true; } Object::Pointer ServiceLocator::GetService(const std::string& key) { if (disposed) { return Object::Pointer(0); } KeyToServiceMapType::const_iterator iter = services.find(key); Object::Pointer service; if (iter != services.end()) { service = iter->second; } else { // if we don't have a service in our cache then: // 1. check our local factory // 2. go to the registry // or 3. use the parent service IServiceLocator::Pointer factoryParent(WorkbenchServiceRegistry::GLOBAL_PARENT); if (!parent.Expired()) { factoryParent = new ParentLocator(parent, key); } if (factory) { service = factory->Create(key, factoryParent, IServiceLocator::Pointer(this)); } if (!service) { service = WorkbenchServiceRegistry::GetRegistry()->GetService(key, factoryParent, ServiceLocator::Pointer(this)); } if (!service) { service = factoryParent->GetService(key); } else { this->RegisterService(key, service); } } return service; } bool ServiceLocator::HasService(const std::string& key) const { if (disposed) { return false; } if (services.find(key) != services.end()) { return true; } return false; } void ServiceLocator::RegisterService(const std::string& api, Object::Pointer service) const { if (api.empty()) { throw Poco::InvalidArgumentException("The service key cannot be empty"); //$NON-NLS-1$ } // if (!api.isInstance(service)) // { // throw new IllegalArgumentException("The service does not implement the given interface"); //$NON-NLS-1$ // } if (services.find(api) != services.end()) { Object::Pointer currentService = services[api]; services.erase(api); if (IDisposable::Pointer disposable = currentService.Cast()) { disposable->Dispose(); } } if (service) { services.insert(std::make_pair(api, service)); if (INestable::Pointer nestable = service.Cast()) { if (activated) { nestable->Activate(); } } } } bool ServiceLocator::IsDisposed() const { return disposed; } void ServiceLocator::UnregisterServices(const std::vector& /*serviceNames*/) { IDisposable::Pointer d(owner); if (d) { d->Dispose(); } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryServiceLocator.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryServiceLocator.h index 819d2b122d..1f896b9a3f 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryServiceLocator.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryServiceLocator.h @@ -1,152 +1,152 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYSERVICELOCATOR_H_ #define BERRYSERVICELOCATOR_H_ -#include "../services/berryIServiceLocator.h" -#include "../services/berryINestable.h" -#include "../services/berryIDisposable.h" +#include "services/berryIServiceLocator.h" +#include "services/berryINestable.h" +#include "services/berryIDisposable.h" #include #include #include #include namespace berry { struct IServiceFactory; class ServiceLocator: public IDisposable, public INestable, public IServiceLocator { private: bool activated; class ParentLocator: public IServiceLocator { const IServiceLocator::WeakPtr locator; const std::string& key; public: ParentLocator(const IServiceLocator::WeakPtr parent, const std::string& serviceInterface); /* * (non-Javadoc) * * @see org.blueberry.ui.services.IServiceLocator#getService(java.lang.Class) */ Object::Pointer GetService(const std::string& api); /* * (non-Javadoc) * * @see org.blueberry.ui.services.IServiceLocator#hasService(java.lang.Class) */ bool HasService(const std::string& api) const; }; const SmartPointer factory; /** * The parent for this service locator. If a service can't be found in this * locator, then the parent is asked. This value may be null * if there is no parent. */ IServiceLocator::WeakPtr parent; /** * The map of services This value is null until a service is * registered. */ typedef std::map KeyToServiceMapType; mutable KeyToServiceMapType services; bool disposed; IDisposable::WeakPtr owner; public: berryObjectMacro(ServiceLocator) /** * Constructs a service locator with no parent. */ ServiceLocator(); /** * Constructs a service locator with the given parent. * * @param parent * The parent for this service locator; this value may be * null. * @param factory * a local factory that can provide services at this level * @param owner */ ServiceLocator(const IServiceLocator::WeakPtr parent, const SmartPointer factory, IDisposable::WeakPtr owner); void Activate(); void Deactivate(); void Dispose(); Object::Pointer GetService(const std::string& key); bool HasService(const std::string& key) const; /** * Registers a service with this locator. If there is an existing service * matching the same api and it implements * {@link IDisposable}, it will be disposed. * * @param api * This is the interface that the service implements. Must not be * null. * @param service * The service to register. This must be some implementation of * api. This value must not be null. */ void RegisterService(const std::string& api, Object::Pointer service) const; /** * @return */ bool IsDisposed() const; /** * Some services that were contributed to this locator are no longer available * (because the plug-in containing the AbstractServiceFactory is no longer * available). Notify the owner of the locator about this. */ void UnregisterServices(const std::vector& serviceNames); }; } #endif // BERRYSERVICELOCATOR_H_ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryServiceLocatorCreator.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryServiceLocatorCreator.cpp index 3ccde67db9..3d3f7d0f89 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryServiceLocatorCreator.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryServiceLocatorCreator.cpp @@ -1,37 +1,37 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryServiceLocatorCreator.h" #include "berryServiceLocator.h" -#include "../services/berryIServiceFactory.h" -#include "../services/berryIDisposable.h" +#include "services/berryIServiceFactory.h" +#include "services/berryIDisposable.h" namespace berry { SmartPointer ServiceLocatorCreator::CreateServiceLocator( const WeakPointer parent, const SmartPointer factory, WeakPointer owner) { IServiceLocator::WeakPtr weakParent(parent); IServiceLocator::Pointer locator(new ServiceLocator(weakParent, factory, owner)); return locator; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryShellPool.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryShellPool.cpp index f62651ec32..90d301326a 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryShellPool.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryShellPool.cpp @@ -1,84 +1,84 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryShellPool.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" +#include "tweaklets/berryGuiWidgetsTweaklet.h" namespace berry { const std::string ShellPool::CLOSE_LISTENER = "close listener"; //$NON-NLS-1$ void ShellPool::ShellClosed(ShellEvent::Pointer e) { if (e->doit) { Shell::Pointer s = e->GetSource(); IShellListener::Pointer l = s->GetData(CLOSE_LISTENER).Cast (); if (l != 0) { s->SetData(Object::Pointer(0), CLOSE_LISTENER); l->ShellClosed(e); // The shell can 'cancel' the close by setting // the 'doit' to false...if so, do nothing if (e->doit) { availableShells.push_back(s); s->SetVisible(false); } else { // Restore the listener s->SetData(l, CLOSE_LISTENER); } } } e->doit = false; } ShellPool::ShellPool(Shell::Pointer parentShell, int childFlags) : flags(childFlags), parentShell(parentShell) { } Shell::Pointer ShellPool::AllocateShell(IShellListener::Pointer closeListener) { Shell::Pointer result; if (!availableShells.empty()) { result = availableShells.front(); availableShells.pop_front(); } else { result = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->CreateShell(parentShell.Lock(), flags); result->AddShellListener(IShellListener::Pointer(this)); //result.addDisposeListener(disposeListener); } result->SetData(closeListener, CLOSE_LISTENER); return result; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryShellPool.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryShellPool.h index eb89b726a9..e8639e1626 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryShellPool.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryShellPool.h @@ -1,88 +1,88 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYSHELLPOOL_H_ #define BERRYSHELLPOOL_H_ -#include "../berryShell.h" +#include "berryShell.h" #include namespace berry { /** * Manages a pool of shells. This can be used instead of creating and destroying * shells. By reusing shells, they will never be disposed until the pool goes away. * This is useful in situations where client code may have cached pointers to the * shells to use as a parent for dialogs. It also works around bug 86226 (SWT menus * cannot be reparented). * * @since 3.1 */ class ShellPool: public IShellListener { int flags; /** * Parent shell (or null if none) * * The parentShell is owned by the WorkbenchWindow, which also owns a ShellPool instance */ Shell::WeakPtr parentShell; std::list availableShells; static const std::string CLOSE_LISTENER; // = "close listener"; // DisposeListener disposeListener = new DisposeListener() { // public void widgetDisposed(DisposeEvent e) { // WorkbenchPlugin.log(new RuntimeException("Widget disposed too early!")); //$NON-NLS-1$ // } // }; friend class WorkbenchWindow; public: berryObjectMacro(ShellPool); void ShellClosed(ShellEvent::Pointer e); /** * Creates a shell pool that allocates shells that are children of the * given parent and are created with the given flags. * * @param parentShell parent shell (may be null, indicating that this pool creates * top-level shells) * @param childFlags flags for all child shells */ ShellPool(Shell::Pointer parentShell, int childFlags); /** * Returns a new shell. The shell must not be disposed directly, but it may be closed. * Once the shell is closed, it will be returned to the shell pool. Note: callers must * remove all listeners from the shell before closing it. */ Shell::Pointer AllocateShell(IShellListener::Pointer closeListener); }; } #endif /* BERRYSHELLPOOL_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berrySourcePriorityNameMapping.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berrySourcePriorityNameMapping.h index 5345e95be1..c6f3b226c8 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berrySourcePriorityNameMapping.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berrySourcePriorityNameMapping.h @@ -1,147 +1,147 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYSOURCEPRIORITYNAMEMAPPING_H_ #define BERRYSOURCEPRIORITYNAMEMAPPING_H_ -#include "../berryISources.h" +#include "berryISources.h" #include #include #include namespace berry { /** *

    * A static class linking the names of variables in an IEvaluationContext to the * priority they should be given when doing conflict resolution. *

    *

    * In the future, it will possible to define a new variable (i.e., piece of * application state) that you want to use inside of the * org.blueberry.ui.contexts, org.blueberry.ui.handlers * or org.blueberry.ui.menus extension points. As it stands right * now, it is not possible to run code soon enough for the * IHandlerService, IMenuService or * IContextService to become aware of the new variables. This * will likely be fixed with a new extension point. *

    *

    * TODO Move to "org.blueberry.ui" and resolve the above issue. *

    * * @since 3.2 * @see org.blueberry.ui.ISources * @see org.blueberry.ui.contexts.IContextService * @see org.blueberry.ui.handlers.IHandlerService * @see org.blueberry.ui.menus.IMenuService */ class SourcePriorityNameMapping : public ISources { private: /** * The map of source priorities indexed by name. This value is never * null. */ static std::map sourcePrioritiesByName; /** * This class should not be instantiated. */ SourcePriorityNameMapping(); public: /** * The variable name to use when boosting priority on an activation. */ static const std::string LEGACY_LEGACY_NAME(); // = "LEGACY"; //$NON-NLS-1$ /** * The value returned if there is source priority for the given name * * @see SourcePriorityNameMapping#getMapping(String) */ static int NO_SOURCE_PRIORITY(); // = 0; private: struct Initializer { Initializer(); }; static Initializer initializer; public: /** * Adds a mapping between a source name and a source priority. This method * also cleans up any existing mappings using the same name or priority. * There is a one-to-one relationship between name and priority. * * @param sourceName * The name of the variable as it would appear in an XML * expression; must not be null. * @param sourcePriority * The priority of the source with respect to other sources. A * higher value means that expressions including this priority * will win ties more often. It is recommended that this value is * simply a single bit shifted to a particular place. * @see ISources */ static void AddMapping(const std::string& sourceName, int sourcePriority); /** * Computes the source priority for the given expression. The source * priority is a bit mask of all of the variables references by the * expression. The default variable is considered to be * {@link ISources#ACTIVE_CURRENT_SELECTION}. The source priority is used * to minimize recomputations of the expression, and it can also be used for * conflict resolution. * * @param expression * The expression for which the source priority should be * computed; may be null. * @return The bit mask of all the sources required for this expression; * 0 if none. */ static int ComputeSourcePriority(Expression::ConstPointer expression); /** * Gets the priority for the source with the given name. * * @param sourceName * The name of the variable as it would appear in an XML * expression; should not be null. * @return The source priority that matches, if any; * NO_SOURCE_PRIORITY if none is found. */ static int GetMapping(const std::string& sourceName); }; } #endif /* BERRYSOURCEPRIORITYNAMEMAPPING_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStackablePart.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStackablePart.cpp index 02433d51e6..38952831e6 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStackablePart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStackablePart.cpp @@ -1,172 +1,172 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryStackablePart.h" #include "berryIStackableContainer.h" #include "berryDetachedWindow.h" -#include "../berryIWorkbenchWindow.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" -#include "../berryImageDescriptor.h" +#include "berryIWorkbenchWindow.h" +#include "tweaklets/berryGuiWidgetsTweaklet.h" +#include "berryImageDescriptor.h" namespace berry { StackablePart::StackablePart(std::string id_) : id(id_) { } IStackableContainer::Pointer StackablePart::GetContainer() const { return container; } void StackablePart::SetContainer(IStackableContainer::Pointer container) { this->container = container; } void StackablePart::Reparent(void* newParent) { void* control = this->GetControl(); GuiWidgetsTweaklet* guiTweaklet = Tweaklets::Get(GuiWidgetsTweaklet::KEY); if ((control == 0) || (guiTweaklet->GetParent(control) == newParent)) { return; } if (guiTweaklet->IsReparentable(control)) { // make control small in case it is not resized with other controls //control.setBounds(0, 0, 0, 0); // By setting the control to disabled before moving it, // we ensure that the focus goes away from the control and its children // and moves somewhere else bool enabled = guiTweaklet->GetEnabled(control); guiTweaklet->SetEnabled(control, false); guiTweaklet->SetParent(control, newParent); guiTweaklet->SetEnabled(control, enabled); guiTweaklet->MoveAbove(control, 0); } } void StackablePart::DescribeLayout(std::string& /*description*/) const { } std::string StackablePart::GetPlaceHolderId() const { return this->GetId(); } std::string StackablePart::GetId() const { return id; } void StackablePart::SetId(const std::string& id) { this->id = id; } void StackablePart::SetFocus() { } void StackablePart::SetBounds(const Rectangle& r) { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->SetBounds(ctrl, r); } } Rectangle StackablePart::GetBounds() { return Rectangle(); } Point StackablePart::GetSize() { Rectangle r = this->GetBounds(); Point ptSize(r.width, r.height); return ptSize; } bool StackablePart::IsDocked() { Shell::Pointer s = this->GetShell(); if (s == 0) { return false; } return s->GetData().Cast() != 0; } Shell::Pointer StackablePart::GetShell() { void* ctrl = this->GetControl(); if (ctrl) { return Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetShell(ctrl); } return Shell::Pointer(0); } IWorkbenchWindow::Pointer StackablePart::GetWorkbenchWindow() { Shell::Pointer s = this->GetShell(); if (s == 0) { return IWorkbenchWindow::Pointer(0); } Object::Pointer data = s->GetData(); if (data.Cast() != 0) { return data.Cast(); } else if (data.Cast() != 0) { return data.Cast()->GetWorkbenchPage()->GetWorkbenchWindow(); } return IWorkbenchWindow::Pointer(0); } std::string StackablePart::GetCompoundId() { return this->GetId(); } bool StackablePart::IsPlaceHolder() const { return false; } void StackablePart::TestInvariants() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStackablePart.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStackablePart.h index 7caf67cbbe..1991925e5e 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStackablePart.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStackablePart.h @@ -1,98 +1,98 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYSTACKABLEPART_H_ #define BERRYSTACKABLEPART_H_ #include -#include "../berryShell.h" +#include "berryShell.h" -#include "../berryPoint.h" -#include "../berryRectangle.h" +#include "berryPoint.h" +#include "berryRectangle.h" #include namespace berry { struct IStackableContainer; struct IWorkbenchWindow; class StackablePart : public virtual Object { public: berryObjectMacro(StackablePart); StackablePart(std::string id); virtual void CreateControl(void* parent) = 0; virtual void* GetControl() = 0; virtual SmartPointer GetContainer() const; virtual void SetContainer(SmartPointer container); virtual void Reparent(void* newParent); virtual void DescribeLayout(std::string& description) const; virtual std::string GetPlaceHolderId() const; virtual std::string GetId() const; virtual void SetId(const std::string& id); /** * Sets focus to this part. */ virtual void SetFocus(); virtual void SetBounds(const Rectangle& bounds); virtual Rectangle GetBounds(); virtual Point GetSize(); virtual bool IsDocked(); virtual Shell::Pointer GetShell(); SmartPointer GetWorkbenchWindow(); /** * Returns the compound ID for this part. * The compound ID is of the form: primaryId [':' + secondaryId] * * @return the compound ID for this part. */ virtual std::string GetCompoundId(); virtual bool IsPlaceHolder() const; virtual void TestInvariants(); private: std::string id; SmartPointer container; }; } #endif /* BERRYSTACKABLEPART_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStickyViewDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStickyViewDescriptor.h index 44aee5179e..702843b2a1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStickyViewDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryStickyViewDescriptor.h @@ -1,98 +1,98 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYSTICKYVIEWDESCRIPTOR_H_ #define BERRYSTICKYVIEWDESCRIPTOR_H_ -#include "../berryIStickyViewDescriptor.h" +#include "berryIStickyViewDescriptor.h" #include namespace berry { class StickyViewDescriptor: public IStickyViewDescriptor { private: IConfigurationElement::Pointer configurationElement; std::string id; public: berryObjectMacro(StickyViewDescriptor) /** * Folder constant for right sticky views. */ static const std::string STICKY_FOLDER_RIGHT; // = "stickyFolderRight"; //$NON-NLS-1$ /** * Folder constant for left sticky views. */ static const std::string STICKY_FOLDER_LEFT; // = "stickyFolderLeft"; //$NON-NLS-1$ /** * Folder constant for top sticky views. */ static const std::string STICKY_FOLDER_TOP; // = "stickyFolderTop"; //$NON-NLS-1$ /** * Folder constant for bottom sticky views. */ static const std::string STICKY_FOLDER_BOTTOM; // = "stickyFolderBottom"; //$NON-NLS-1$ /** * @param element * @throws CoreException */ StickyViewDescriptor(IConfigurationElement::Pointer element) throw (CoreException); /** * Return the configuration element. * * @return the configuration element */ IConfigurationElement::Pointer GetConfigurationElement() const; /* * @see IStickyViewDescriptor#GetLocation() */ int GetLocation() const; /* * @see IStickyViewDescriptor#GetId() */ std::string GetId() const; /* * @see IStickyViewDescriptor#IsFixed() */ bool IsCloseable() const; /* * @see IStickyViewDescriptor#IsMoveable() */ bool IsMoveable() const; }; } #endif /* BERRYSTICKYVIEWDESCRIPTOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryTestDropLocation.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryTestDropLocation.h index e6a79ee86b..bbbeeab306 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryTestDropLocation.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryTestDropLocation.h @@ -1,59 +1,59 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYTESTDROPLOCATION_H_ #define BERRYTESTDROPLOCATION_H_ #include -#include "../berryPoint.h" -#include "../berryShell.h" +#include "berryPoint.h" +#include "berryShell.h" #include namespace berry { /** * This is an interface intended for use in test suites. Objects can implement * this interface to force any dragged object to be dropped at a particular * location. * * @since 3.0 */ struct TestDropLocation : public Object { berryObjectMacro(TestDropLocation); /** * Location where the object should be dropped, in display coordinates * * @return a location in display coordinates */ virtual Point GetLocation() = 0; /** * The drop code will pretend that only the given shells are open, * and that they have the specified Z-order. * * @return the shells to check for drop targets, from bottom to top. */ virtual std::vector GetShells() = 0; }; } #endif /* BERRYTESTDROPLOCATION_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewDescriptor.cpp index 812541c67a..27fc7bdb28 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewDescriptor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewDescriptor.cpp @@ -1,214 +1,214 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryViewDescriptor.h" #include "service/berryIConfigurationElement.h" #include "berryPlatformException.h" #include "berryRegistryReader.h" #include "berryWorkbenchRegistryConstants.h" -#include "../berryImageDescriptor.h" -#include "../berryAbstractUIPlugin.h" -#include "../berryAbstractUICTKPlugin.h" -#include "../berryImageDescriptor.h" -#include "../handlers/berryIHandlerActivation.h" +#include "berryImageDescriptor.h" +#include "berryAbstractUIPlugin.h" +#include "berryAbstractUICTKPlugin.h" +#include "berryImageDescriptor.h" +#include "handlers/berryIHandlerActivation.h" #include #include namespace berry { ViewDescriptor::ViewDescriptor(IConfigurationElement::Pointer e) : configElement(e) { this->LoadFromExtension(); } IViewPart::Pointer ViewDescriptor::CreateView() { IViewPart::Pointer part(configElement->CreateExecutableExtension ( WorkbenchRegistryConstants::ATT_CLASS)); if (part.IsNull()) { // support legacy BlueBerry extensions part = configElement->CreateExecutableExtension ( WorkbenchRegistryConstants::ATT_CLASS, IViewPart::GetManifestName()); } return part; } const std::vector& ViewDescriptor::GetCategoryPath() const { return categoryPath; } IConfigurationElement::Pointer ViewDescriptor::GetConfigurationElement() const { return configElement; } std::string ViewDescriptor::GetDescription() const { return RegistryReader::GetDescription(configElement); } std::string 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; } ImageDescriptor::Pointer ViewDescriptor::GetImageDescriptor() const { if (imageDescriptor) { return imageDescriptor; } std::string iconName; configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ICON, iconName); // If the icon attribute was omitted, use the default one if (iconName.empty()) { //TODO default image descriptor //return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_DEF_VIEW); return ImageDescriptor::GetMissingImageDescriptor(); } const IExtension* extension(configElement->GetDeclaringExtension()); const std::string extendingPluginId(extension->GetNamespace()); imageDescriptor = AbstractUICTKPlugin::ImageDescriptorFromPlugin( extendingPluginId, iconName); if (!imageDescriptor) { // Try legacy BlueBerry method imageDescriptor = AbstractUIPlugin::ImageDescriptorFromPlugin( extendingPluginId, iconName); } // If the icon attribute was invalid, use the error icon if (!imageDescriptor) { imageDescriptor = ImageDescriptor::GetMissingImageDescriptor(); } return imageDescriptor; } std::string ViewDescriptor::GetLabel() const { std::string label; configElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME, label); return label; } std::string ViewDescriptor::GetAccelerator() const { std::string accel; configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ACCELERATOR, accel); return accel; } bool ViewDescriptor::GetAllowMultiple() const { bool allow = false; configElement->GetBoolAttribute(WorkbenchRegistryConstants::ATT_ALLOW_MULTIPLE, allow); return allow; } bool ViewDescriptor::IsRestorable() const { std::string string; if (configElement->GetAttribute(WorkbenchRegistryConstants::ATT_RESTORABLE, string)) { return Poco::icompare(string, "true") == 0; } else { return true; } } Poco::Any ViewDescriptor::GetAdapter(const std::string& adapter) { if (adapter == IConfigurationElement::GetStaticClassName()) { return Poco::Any(GetConfigurationElement()); } return Poco::Any(); } 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; // } } void ViewDescriptor::LoadFromExtension() { configElement->GetAttribute(WorkbenchRegistryConstants::ATT_ID, id); // Sanity check. std::string name; if ((configElement->GetAttribute(WorkbenchRegistryConstants::ATT_NAME, name) == false) || (RegistryReader::GetClassValue(configElement, WorkbenchRegistryConstants::ATT_CLASS) == "")) { throw CoreException( "Invalid extension (missing label or class name)", id); } std::string category; if (configElement->GetAttribute(WorkbenchRegistryConstants::TAG_CATEGORY, category)) { Poco::StringTokenizer stok(category, "/", Poco::StringTokenizer::TOK_IGNORE_EMPTY | Poco::StringTokenizer::TOK_TRIM); // Parse the path tokens and store them for (Poco::StringTokenizer::Iterator iter = stok.begin(); iter != stok.end(); ++iter) { categoryPath.push_back(*iter); } } } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewDescriptor.h index ec16dce944..c56cf5dd01 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewDescriptor.h @@ -1,153 +1,153 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYVIEWDESCRIPTOR_H_ #define BERRYVIEWDESCRIPTOR_H_ -#include "../berryIViewPart.h" -#include "../berryIViewDescriptor.h" +#include "berryIViewPart.h" +#include "berryIViewDescriptor.h" #include "service/berryIConfigurationElement.h" #include #include namespace berry { struct IHandlerActivation; /** * \ingroup org_blueberry_ui_internal * */ class ViewDescriptor : public IViewDescriptor { private: std::string id; mutable SmartPointer imageDescriptor; IConfigurationElement::Pointer configElement; std::vector 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(IConfigurationElement::Pointer e); /* (non-Javadoc) * @see org.blueberry.ui.internal.registry.IViewDescriptor#createView() */ IViewPart::Pointer CreateView(); /* (non-Javadoc) * @see org.blueberry.ui.internal.registry.IViewDescriptor#getCategoryPath() */ const std::vector& 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() */ std::string GetDescription() const; /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartDescriptor#getId() */ std::string GetId() const; /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartDescriptor#getImageDescriptor() */ SmartPointer GetImageDescriptor() const; /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartDescriptor#getLabel() */ std::string GetLabel() const; /** * Return the accelerator attribute. * * @return the accelerator attribute */ std::string 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(); protected: /* (non-Javadoc) * @see IAdaptable#GetAdapterImpl(const std::type_info&) */ Poco::Any GetAdapter(const std::string& adapter); private: /** * load a view descriptor from the registry. */ void LoadFromExtension(); }; } #endif /*BERRYVIEWDESCRIPTOR_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewFactory.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewFactory.cpp index 343eae6838..2b3c9a2391 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewFactory.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewFactory.cpp @@ -1,325 +1,325 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryViewFactory.h" -#include "../berryUIException.h" -#include "../berryIViewRegistry.h" -#include "../berryImageDescriptor.h" +#include "berryUIException.h" +#include "berryIViewRegistry.h" +#include "berryImageDescriptor.h" #include "berryViewReference.h" #include "berryViewDescriptor.h" #include "berryWorkbenchPage.h" #include "berryWorkbenchConstants.h" -#include "../util/berrySafeRunnable.h" +#include "util/berrySafeRunnable.h" #include namespace berry { const std::string ViewFactory::ID_SEP = ":"; //$NON-NLS-1$ std::string ViewFactory::GetKey(const std::string& id, const std::string& secondaryId) { return secondaryId.empty() ? id : id + ID_SEP + secondaryId; } std::string ViewFactory::GetKey(IViewReference::Pointer viewRef) { return GetKey(viewRef->GetId(), viewRef->GetSecondaryId()); } std::string ViewFactory::ExtractPrimaryId(const std::string& compoundId) { std::string::size_type i = compoundId.find_last_of(ID_SEP); if (i == std::string::npos) { return compoundId; } return compoundId.substr(0, i); } std::string ViewFactory::ExtractSecondaryId(const std::string& compoundId) { std::string::size_type i = compoundId.find_last_of(ID_SEP); if (i == std::string::npos) { return ""; } return compoundId.substr(i + 1); } bool ViewFactory::HasWildcard(const std::string& viewId) { return viewId.find_first_of('*') != std::string::npos; } ViewFactory::ViewFactory(WorkbenchPage* p, IViewRegistry* reg) : page(p), viewReg(reg) { //page.getExtensionTracker().registerHandler(this, null); } IViewReference::Pointer ViewFactory::CreateView(const std::string& id, const std::string& secondaryId) { IViewDescriptor::Pointer desc = viewReg->Find(id); // ensure that the view id is valid if (desc.IsNull()) { throw PartInitException("Could not create view", id); } // ensure that multiple instances are allowed if a secondary id is given if (secondaryId != "") { if (!desc->GetAllowMultiple()) { throw PartInitException("View does not allow multiple instances", id); } } std::string 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.erase(key); counter.Put(key, ref); this->GetWorkbenchPage()->PartAdded(ref.Cast ()); } else { counter.AddRef(key); } return ref; } std::vector ViewFactory::GetViewReferences() { std::vector values(counter.Values()); return values; } IViewReference::Pointer ViewFactory::GetView(const std::string& id) { return this->GetView(id, ""); } IViewReference::Pointer ViewFactory::GetView(const std::string& id, const std::string& secondaryId) { std::string key = this->GetKey(id, secondaryId); return counter.Get(key); } const IViewRegistry* ViewFactory::GetViewRegistry() const { return viewReg; } std::vector ViewFactory::GetViews() { std::vector values(counter.Values()); return values; } WorkbenchPage* ViewFactory::GetWorkbenchPage() const { return page; } int ViewFactory::GetReferenceCount(IViewReference::Pointer viewRef) { std::string key = this->GetKey(viewRef); IViewReference::Pointer ref = counter.Get(key); return ref.IsNull() ? 0 : counter.GetRef(key); } void ViewFactory::ReleaseView(IViewReference::Pointer viewRef) { std::string 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) { std::vector mem(memento->GetChildren( WorkbenchConstants::TAG_VIEW)); for (std::size_t 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; std::vector refs(GetViews()); for (std::size_t 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 std::map& properties = view->GetPartProperties(); if (!properties.empty()) { IMemento::Pointer propBag = viewMemento ->CreateChild( WorkbenchConstants::TAG_PROPERTIES); for (std::map::const_iterator i = properties.begin(); i != properties.end(); ++i) { IMemento::Pointer p = propBag->CreateChild( WorkbenchConstants::TAG_PROPERTY, i->first); p->PutTextData(i->second); } } view->SaveState(viewMemento ->CreateChild( WorkbenchConstants::TAG_VIEW_STATE)); } void HandleException(const std::exception& /*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) { std::string compoundId; memento->GetString(WorkbenchConstants::TAG_ID, compoundId); mementoTable.insert(std::make_pair(compoundId, memento)); } IMemento::Pointer ViewFactory::GetViewState(const std::string& 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/src/internal/berryViewFactory.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewFactory.h index b827c9dada..2ea22319b4 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewFactory.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewFactory.h @@ -1,195 +1,195 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYVIEWFACTORY_H_ #define BERRYVIEWFACTORY_H_ #include -#include "../berryIMemento.h" -#include "../berryIViewReference.h" +#include "berryIMemento.h" +#include "berryIViewReference.h" #include "berryReferenceCounter.h" #include #include namespace berry { class WorkbenchPage; struct IViewRegistry; /** * \ingroup org_blueberry_ui_internal * * The ViewFactory is used to control the creation and disposal of views. * It implements a reference counting strategy so that one view can be shared * by more than one client. */ class ViewFactory { // implements IExtensionChangeHandler { private: std::map mementoTable; ReferenceCounter counter; WorkbenchPage* page; IViewRegistry* viewReg; public: /** * Separates a view's primary id from its secondary id in view key strings. */ static const std::string ID_SEP; // = ":"; //$NON-NLS-1$ /** * Returns a string representing a view with the given id and (optional) secondary id, * suitable for use as a key in a map. * * @param id primary id of the view * @param secondaryId secondary id of the view or null * @return the key */ static std::string GetKey(const std::string& id, const std::string& secondaryId); /** * Returns a string representing the given view reference, suitable for use as a key in a map. * * @param viewRef the view reference * @return the key */ static std::string GetKey(IViewReference::Pointer viewRef); /** * Extracts ths primary id portion of a compound id. * @param compoundId a compound id of the form: primaryId [':' secondaryId] * @return the primary id */ static std::string ExtractPrimaryId(const std::string& compoundId); /** * Extracts ths secondary id portion of a compound id. * @param compoundId a compound id of the form: primaryId [':' secondaryId] * @return the secondary id, or null if none */ static std::string ExtractSecondaryId(const std::string& compoundId); /** * Returns whether the given view id contains a wildcard. Wildcards cannot * be used in regular view ids, only placeholders. * * @param viewId the view id * @return true if the given view id contains a wildcard, * false otherwise * * @since 3.1 */ static bool HasWildcard(const std::string& viewId); /** * Constructs a new view factory. */ ViewFactory(WorkbenchPage* page, IViewRegistry* reg); /** * Creates an instance of a view defined by id and secondary id. * * This factory implements reference counting. The first call to this * method will return a new view. Subsequent calls will return the * first view with an additional reference count. The view is * disposed when releaseView is called an equal number of times * to createView. */ IViewReference::Pointer CreateView(const std::string& id, const std::string& secondaryId = ""); /** * Returns the set of views being managed by this factory * * @return the set of views being managed by this factory */ std::vector GetViewReferences(); /** * Returns the view with the given id, or null if not found. */ IViewReference::Pointer GetView(const std::string& id); /** * Returns the view with the given id and secondary id, or null if not found. */ IViewReference::Pointer GetView(const std::string& id, const std::string& secondaryId); /** * @return the IViewRegistry used by this factory. * @since 3.0 */ const IViewRegistry* GetViewRegistry() const; /** * Returns a list of views which are open. */ std::vector GetViews(); /** * @return the WorkbenchPage used by this factory. * @since 3.0 */ WorkbenchPage* GetWorkbenchPage() const; int GetReferenceCount(IViewReference::Pointer viewRef); /** * Releases an instance of a view. * * This factory does reference counting. For more info see * getView. */ void ReleaseView(IViewReference::Pointer viewRef); /** * Restore view states. * * @param memento the IMemento to restore from. * @return IStatus */ /*IStatus*/bool RestoreState(IMemento::Pointer memento); /** * Save view states. * * @param memento the IMemento to save to. * @return IStatus */ /*IStatus*/bool SaveState(IMemento::Pointer memento); // for dynamic UI IMemento::Pointer SaveViewState(IMemento::Pointer memento, IViewReference::Pointer ref, bool& res); // for dynamic UI void RestoreViewState(IMemento::Pointer memento); IMemento::Pointer GetViewState(const std::string& key); }; } #endif /*BERRYVIEWFACTORY_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewLayout.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewLayout.cpp index 33dcae96b2..14736d6ec9 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewLayout.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewLayout.cpp @@ -1,62 +1,62 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryViewLayout.h" -#include "../berryImageDescriptor.h" +#include "berryImageDescriptor.h" namespace berry { ViewLayout::ViewLayout(PageLayout::Pointer pageLayout, ViewLayoutRec::Pointer r) : rec(r) { poco_assert(pageLayout != 0); poco_assert(rec != 0); } bool ViewLayout::GetShowTitle() { return rec->showTitle; } bool ViewLayout::IsCloseable() { return rec->isCloseable; } bool ViewLayout::IsMoveable() { return rec->isMoveable; } bool ViewLayout::IsStandalone() { return rec->isStandalone; } void ViewLayout::SetCloseable(bool closeable) { rec->isCloseable = closeable; } void ViewLayout::SetMoveable(bool moveable) { rec->isMoveable = moveable; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewReference.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewReference.cpp index 68aba6afc9..7a410e10d4 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewReference.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewReference.cpp @@ -1,439 +1,439 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryViewReference.h" #include -#include "../berryUIException.h" -#include "../tweaklets/berryWorkbenchPageTweaklet.h" -#include "../berryPlatformUI.h" -#include "../berryImageDescriptor.h" +#include "berryUIException.h" +#include "tweaklets/berryWorkbenchPageTweaklet.h" +#include "berryPlatformUI.h" +#include "berryImageDescriptor.h" #include "berryWorkbenchPage.h" #include "berryWorkbenchConstants.h" #include "berryViewDescriptor.h" #include "berryViewFactory.h" #include "berryViewRegistry.h" #include "berryViewSite.h" #include "berryPartTester.h" #include "berryWorkbenchPlugin.h" #include "berryErrorViewPart.h" namespace berry { ViewReference::ViewReference(ViewFactory* fac, const std::string& id, const std::string& secId, IMemento::Pointer m) : factory(fac), secondaryId(secId), memento(m) { ViewDescriptor::Pointer desc = this->factory->GetViewRegistry()->Find(id).Cast (); ImageDescriptor::Pointer iDesc; std::string title; if (!desc.IsNull()) { iDesc = desc->GetImageDescriptor(); title = desc->GetLabel(); } std::string name; if (!memento.IsNull()) { // name = memento.getString(IWorkbenchConstants.TAG_PART_NAME); // IMemento propBag = memento.getChild(IWorkbenchConstants.TAG_PROPERTIES); // if (propBag != null) { // IMemento[] props = propBag // .getChildren(IWorkbenchConstants.TAG_PROPERTY); // for (int i = 0; i < props.length; i++) { // propertyCache.put(props[i].getID(), props[i].getTextData()); // } // } } if (name.empty()) { name = title; } this->Init(id, "", iDesc, name, ""); //$NON-NLS-1$//$NON-NLS-2$ } void ViewReference::DoDisposePart() { IViewPart::Pointer view = part.Cast (); //WorkbenchPartReference::DoDisposePart(); if (!view.IsNull()) { // Free action bars, pane, etc. //PartSite site = (PartSite) view.getSite(); //ViewActionBars actionBars = (ViewActionBars) site.getActionBars(); // // 3.3 start // //IMenuService menuService = (IMenuService) site // .getService(IMenuService.class); //menuService.releaseContributions((ContributionManager) site.getActionBars() // .getMenuManager()); //menuService.releaseContributions((ContributionManager) site.getActionBars() // .getToolBarManager()); // 3.3 end //actionBars.dispose(); // and now dispose the delegates since the // PluginActionContributionItem // can no longer do that // if (actionBuilder != null) { // actionBuilder.dispose(); // actionBuilder = null; // } // Free the site. //site.dispose(); } } IWorkbenchPage::Pointer ViewReference::GetPage() const { return IWorkbenchPage::Pointer(this->factory->GetWorkbenchPage()); } std::string ViewReference::GetRegisteredName() { if (!part.IsNull() && !part->GetSite().IsNull()) { return part->GetSite()->GetRegisteredName(); } const IViewRegistry* reg = this->factory->GetViewRegistry(); IViewDescriptor::Pointer desc = reg->Find(this->GetId()); if (!desc.IsNull()) { return desc->GetLabel(); } return this->GetPartName(); } std::string ViewReference::GetSecondaryId() { return secondaryId; } IViewPart::Pointer ViewReference::GetView(bool restore) { return this->GetPart(restore).Cast (); } IWorkbenchPart::Pointer ViewReference::CreatePart() { // Check the status of this part IWorkbenchPart::Pointer result; PartInitException exception; bool error = false; // Try to restore the view -- this does the real work of restoring the // view // try { result = this->CreatePartHelper(); } catch (PartInitException e) { exception = e; error = true; } // If unable to create the part, create an error part instead // and pass the error to the status handling facility if (error) { // IStatus partStatus = exception.getStatus(); // IStatus displayStatus = StatusUtil.newStatus(partStatus, // NLS.bind(WorkbenchMessages.ViewFactory_initException, partStatus.getMessage())); // IStatus logStatus = StatusUtil // .newStatus( // partStatus, // NLS // .bind( // "Unable to create view ID {0}: {1}", getId(), partStatus.getMessage())); //$NON-NLS-1$ // Pass the error to the status handling facility // StatusManager.getManager().handle(logStatus); std::string errorTitle = "Unable to create view ID " + this->GetId(); WorkbenchPlugin::Log(errorTitle + ": " + exception.displayText()); IViewDescriptor::Pointer desc = factory->GetViewRegistry()->Find( this->GetId()); std::string label = this->GetId(); if (!desc.IsNull()) { label = desc->GetLabel(); } std::string errorMsg = exception.displayText(); errorMsg += "
    • Check your shared library for unresolved symbols
    • " "
    • Check your class attribute in your plugin.xml file
    • " "
    • Check your manifest.cpp file
    " "
    For a comprehensive check-list, see http://www.mitk.org/wiki/How_to_fix_your_plug-in_DLL"; ErrorViewPart::Pointer part(new ErrorViewPart(errorTitle, errorMsg)); //PartPane pane = getPane(); IViewReference::Pointer viewRef(this); ViewSite::Pointer site(new ViewSite(viewRef, part, factory->GetWorkbenchPage(), GetId(), PlatformUI::PLUGIN_ID, label)); //site.setActionBars(new ViewActionBars(factory.page.getActionBars(), // site, (ViewPane) pane)); try { part->Init(site); } catch (PartInitException e) { BERRY_ERROR << e.displayText(); //StatusUtil.handleStatus(e, StatusManager.SHOW // | StatusManager.LOG); return IWorkbenchPart::Pointer(0); } part->SetPartName(label); void* parent = pane->GetControl(); try { part->CreatePartControl(parent); } catch (std::exception e) { BERRY_ERROR << "Error creating view: " << e.what() << std::endl; // StatusUtil.handleStatus(e, StatusManager.SHOW // | StatusManager.LOG); return IWorkbenchPart::Pointer(0); } result = part.Cast (); } return result; } PartPane::Pointer ViewReference::CreatePane() { IWorkbenchPartReference::Pointer partRef(this); PartPane::Pointer pane(new PartPane(partRef, this->factory->GetWorkbenchPage())); return pane; //return Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateViewPane(this, this->factory->GetWorkbenchPage()); } IWorkbenchPart::Pointer ViewReference::CreatePartHelper() { IWorkbenchPart::Pointer result; IMemento::Pointer stateMem; if (!memento.IsNull()) { stateMem = memento->GetChild(WorkbenchConstants::TAG_VIEW_STATE); } IViewDescriptor::Pointer desc = factory->GetViewRegistry()->Find(GetId()); if (desc.IsNull()) { throw PartInitException("Could not create view", this->GetId()); } // Create the part pane PartPane::Pointer pane = this->GetPane(); // Create the pane's top-level control pane->CreateControl(factory->GetWorkbenchPage()->GetClientComposite()); std::string label = desc->GetLabel(); // debugging only // Things that will need to be disposed if an exception occurs (they are // listed here // in the order they should be disposed) //Composite content = null; IViewPart::Pointer initializedView; ViewSite::Pointer site; //ViewActionBars actionBars = null; // End of things that need to be explicitly disposed from the try block try { IViewPart::Pointer view; view = desc->CreateView(); this->CreatePartProperties(view); // Create site IViewReference::Pointer viewRef(this); site = new ViewSite(viewRef, view, factory->GetWorkbenchPage(), desc); //actionBars = new ViewActionBars(factory.page.getActionBars(), site, // (ViewPane) pane); //site.setActionBars(actionBars); view->Init(site, stateMem); // Once we've called init, we MUST dispose the view. Remember // the fact that // we've initialized the view in case an exception is thrown. initializedView = view; if (view->GetSite() != site) { throw PartInitException("View initialization failed. Site is incorrect."); } // Create the top-level composite { void* parent = pane->GetControl(); view->CreatePartControl(parent); } // Install the part's tools and menu { // // 3.3 start // // IMenuService menuService = (IMenuService) site // .getService(IMenuService.class); // menuService.populateContributionManager( // (ContributionManager) site.getActionBars() // .getMenuManager(), "menu:" //$NON-NLS-1$ // + site.getId()); // menuService // .populateContributionManager((ContributionManager) site // .getActionBars().getToolBarManager(), // "toolbar:" + site.getId()); //$NON-NLS-1$ // 3.3 end // actionBuilder = new ViewActionBuilder(); // actionBuilder.readActionExtensions(view); // ActionDescriptor[] actionDescriptors = actionBuilder // .getExtendedActions(); // IKeyBindingService keyBindingService = view.getSite() // .getKeyBindingService(); // // if (actionDescriptors != null) { // for (int i = 0; i < actionDescriptors.length; i++) { // ActionDescriptor actionDescriptor = actionDescriptors[i]; // // if (actionDescriptor != null) { // IAction action = actionDescriptors[i].getAction(); // // if (action != null // && action.getActionDefinitionId() != null) { // keyBindingService.registerAction(action); // } // } // } // } // // site.getActionBars().updateActionBars(); } // The part should now be fully created. Exercise its public // interface, and sanity-check // it wherever possible. If it's going to throw exceptions or behave // badly, it's much better // that it does so now while we can still cancel creation of the // part. PartTester::TestView(view); result = view.Cast (); // IConfigurationElement::Pointer element = desc->GetConfigurationElement(); // if (!element.IsNull()) { // factory.page.getExtensionTracker().registerObject( // element.getDeclaringExtension(), view, // IExtensionTracker.REF_WEAK); // } } catch (const Poco::Exception& e) { // if ((e instanceof Error) && !(e instanceof LinkageError)) { // throw (Error) e; // } // An exception occurred. First deallocate anything we've allocated // in the try block (see the top // of the try block for a list of objects that need to be explicitly // disposed) // if (content != null) { // try { // content.dispose(); // } catch (RuntimeException re) { // StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, // re)); // } // } // // if (initializedView != null) { // try { // initializedView.dispose(); // } catch (RuntimeException re) { // StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, // re)); // } // } // // if (site != null) { // try { // site.dispose(); // } catch (RuntimeException re) { // StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, // re)); // } // } // // if (actionBars != null) { // try { // actionBars.dispose(); // } catch (RuntimeException re) { // StatusManager.getManager().handle( // StatusUtil.newStatus(WorkbenchPlugin.PI_WORKBENCH, // re)); // } // } throw PartInitException(e.message(), e, e.code()); } catch (const std::exception& e) { throw PartInitException(e.what()); } return result; } IMemento::Pointer ViewReference::GetMemento() { return memento; } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewReference.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewReference.h index fbaa72d819..5d7a92d17b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewReference.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewReference.h @@ -1,113 +1,113 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYVIEWREFERENCE_H_ #define BERRYVIEWREFERENCE_H_ -#include "../berryIMemento.h" +#include "berryIMemento.h" #include "berryWorkbenchPartReference.h" -#include "../berryIViewReference.h" +#include "berryIViewReference.h" #include "berryPartPane.h" namespace berry { class ViewFactory; struct IWorkbenchPage; /** * \ingroup org_blueberry_ui_internal * */ class ViewReference : public WorkbenchPartReference, public IViewReference { public: berryObjectMacro(ViewReference); private: const ViewFactory* factory; public: std::string secondaryId; private: IMemento::Pointer memento; //private: ViewActionBuilder actionBuilder; public: ViewReference(ViewFactory* factory, const std::string& id, const std::string& secondaryId, IMemento::Pointer memento); /* * (non-Javadoc) * * @see org.blueberry.ui.internal.WorkbenchPartReference#dispose() */ protected: virtual void DoDisposePart(); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPartReference#getPage() */ public: virtual SmartPointer GetPage() const; /* * (non-Javadoc) * * @see org.blueberry.ui.internal.WorkbenchPartReference#getRegisteredName() */ public: virtual std::string GetRegisteredName(); /* * (non-Javadoc) * * @see org.blueberry.ui.IViewReference */ public: virtual std::string GetSecondaryId(); /* * (non-Javadoc) * * @see org.blueberry.ui.IViewReference#getView(boolean) */ public: virtual IViewPart::Pointer GetView(bool restore); /** * Wrapper for restoring the view. First, this delegates to * busyRestoreViewHelper to do the real work of restoring the view. If * unable to restore the view, this method tries to substitute an error part * and return success. * * @return the created part */ protected: IWorkbenchPart::Pointer CreatePart(); protected: PartPane::Pointer CreatePane(); private: IWorkbenchPart::Pointer CreatePartHelper(); /** * The memento is that last view state saved by the workbench. * * @return the last state that was saved by the workbench. It can return * null. * @since 3.1.1 */ public: virtual IMemento::Pointer GetMemento(); }; } // namespace berry #endif /*BERRYVIEWREFERENCE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewRegistry.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewRegistry.cpp index b0bbace27f..34d03f9727 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewRegistry.cpp @@ -1,282 +1,282 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include #include "berryViewRegistry.h" -#include "../berryPlatformUI.h" -#include "../berryImageDescriptor.h" +#include "berryPlatformUI.h" +#include "berryImageDescriptor.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchRegistryConstants.h" #include "berryPlatform.h" namespace berry { ViewRegistry::ViewCategoryProxy::ViewCategoryProxy( IViewDescriptorCategoryPtr rawCategory) : rawCategory(rawCategory) { } const std::vector& ViewRegistry::ViewCategoryProxy::GetViews() const { return rawCategory->GetElements(); } const std::string& ViewRegistry::ViewCategoryProxy::GetId() const { return rawCategory->GetId(); } std::vector ViewRegistry::ViewCategoryProxy::GetPath() const { std::vector path; std::string rawParentPath = rawCategory->GetRawParentPath(); // nested categories are not supported yet // assume an empty raw parent path path.push_back(rawParentPath); return path; } std::string ViewRegistry::ViewCategoryProxy::GetLabel() const { return rawCategory->GetLabel(); } bool ViewRegistry::ViewCategoryProxy::operator==(const Object* o) const { if (const IViewCategory* other = dynamic_cast(o)) return this->GetId() == other->GetId(); return false; } int ViewRegistry::ViewCategoryProxy::HashCode() { //return GetId().hashCode(); return 0; } std::string ViewRegistry::EXTENSIONPOINT_UNIQUE_ID = "org.blueberry.ui.views"; // PlatformUI::PLUGIN_ID + "." + WorkbenchRegistryConstants::PL_VIEWS; Category::Pointer ViewRegistry::InternalFindCategory(const std::string& id) { for (std::vector::iterator itr = categories.begin(); itr != categories.end(); ++itr) { if (id == (*itr)->GetRootPath()) { return *itr; } } return IViewDescriptorCategoryPtr(0); } const IExtensionPoint* ViewRegistry::GetExtensionPointFilter() { return Platform::GetExtensionPointService()->GetExtensionPoint(EXTENSIONPOINT_UNIQUE_ID); } const std::string 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); } 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 (std::vector::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 std::string& id) const { for (std::vector::const_iterator itr = views.begin(); itr != views.end(); ++itr) { if (id == (*itr)->GetId()) { return *itr; } } return IViewDescriptor::Pointer(0); } IViewCategory::Pointer ViewRegistry::FindCategory(const std::string& id) { this->MapViewsToCategories(); IViewDescriptorCategoryPtr category(this->InternalFindCategory(id)); if (category.IsNull()) { return IViewCategory::Pointer(0); } IViewCategory::Pointer cat(new ViewCategoryProxy(category)); return cat; } std::vector ViewRegistry::GetCategories() { this->MapViewsToCategories(); std::vector retArray; for (std::vector::iterator itr = categories.begin(); itr != categories.end(); ++itr) { retArray.push_back(IViewCategory::Pointer(new ViewCategoryProxy(*itr))); } return retArray; } std::vector ViewRegistry::GetStickyViews() const { return sticky; } Category::Pointer ViewRegistry::GetMiscCategory() const { return miscCategory; } const std::vector& ViewRegistry::GetViews() const { return views; } void ViewRegistry::MapViewsToCategories() { if (dirtyViewCategoryMappings) { dirtyViewCategoryMappings = false; // clear all category mappings for (std::vector::iterator i = categories.begin(); i != categories.end(); ++i) { (*i)->Clear(); // this is bad } miscCategory->Clear(); for (std::vector::iterator i = views.begin(); i != views.end(); ++i) { IViewDescriptor::Pointer desc(*i); IViewDescriptorCategoryPtr cat(0); const std::vector& 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. std::string fmt(Poco::Logger::format( "Category $0 not found for view $1. This view added to ''$2'' category.", catPath[0], desc->GetId(), miscCategory->GetLabel())); WorkbenchPlugin::Log(fmt); } 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/src/internal/berryViewRegistry.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewRegistry.h index fffa87588c..4825e78155 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewRegistry.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewRegistry.h @@ -1,225 +1,225 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYVIEWREGISTRY_H_ #define BERRYVIEWREGISTRY_H_ -#include "../berryIViewRegistry.h" -#include "../berryIViewCategory.h" -#include "../berryIViewDescriptor.h" +#include "berryIViewRegistry.h" +#include "berryIViewCategory.h" +#include "berryIViewDescriptor.h" #include "berryCategory.h" #include "berryViewDescriptor.h" #include "berryViewRegistryReader.h" #include "berryStickyViewDescriptor.h" #include "service/berryIExtensionPoint.h" #include #include #include 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 { 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() */ const std::vector& GetViews() const; /* (non-Javadoc) * @see org.blueberry.ui.views.IViewCategory#getId() */ const std::string& GetId() const; /* (non-Javadoc) * @see org.blueberry.ui.views.IViewCategory#getPath() */ std::vector GetPath() const; /* (non-Javadoc) * @see org.blueberry.ui.views.IViewCategory#getLabel() */ std::string GetLabel() const; /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ bool operator==(const Object* o) const; /* (non-Javadoc) * @see java.lang.Object#hashCode() */ int HashCode(); }; private: static std::string EXTENSIONPOINT_UNIQUE_ID; /** * A set that will only ever contain ViewDescriptors. */ std::vector 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); // }}); std::vector sticky; std::vector 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 std::string& id); const IExtensionPoint* GetExtensionPointFilter(); protected: static const std::string 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 std::string& 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 std::string& id); /** * Get the list of view categories. */ std::vector GetCategories(); /** * Get the list of sticky views minus the sticky views which failed the * Expressions check. */ std::vector 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. */ const std::vector& 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/src/internal/berryViewRegistryReader.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewRegistryReader.cpp index 00055bf28e..bbbfae38c5 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewRegistryReader.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewRegistryReader.cpp @@ -1,115 +1,115 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryViewRegistryReader.h" #include "berryViewRegistry.h" #include "berryWorkbenchRegistryConstants.h" #include "berryWorkbenchPlugin.h" -#include "../berryImageDescriptor.h" -#include "../berryPlatformUI.h" +#include "berryImageDescriptor.h" +#include "berryPlatformUI.h" namespace berry { std::string ViewRegistryReader::GENERAL_VIEW_ID = "org.blueberry.ui"; ViewRegistryReader::ViewRegistryReader() : RegistryReader() { } void ViewRegistryReader::ReadViews(ViewRegistry* out) { // this does not seem to really ever be throwing an the exception viewRegistry = out; this->ReadRegistry(PlatformUI::PLUGIN_ID, WorkbenchRegistryConstants::PL_VIEWS); } void ViewRegistryReader::ReadCategory(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$ } } bool ViewRegistryReader::ReadElement(IConfigurationElement::Pointer element) { std::string 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(IConfigurationElement::Pointer 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(IConfigurationElement::Pointer 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/src/internal/berryViewSashContainer.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewSashContainer.cpp index 63ffc58761..c73f98fa0a 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewSashContainer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewSashContainer.cpp @@ -1,299 +1,299 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryViewSashContainer.h" #include "berryPerspective.h" #include "berryPerspectiveHelper.h" #include "berryLayoutTree.h" #include "berryWorkbenchConstants.h" #include "berryWorkbenchPlugin.h" -#include "../berryImageDescriptor.h" +#include "berryImageDescriptor.h" #include namespace berry { ViewSashContainer::ViewSashContainer(WorkbenchPage* page, void* parent) : PartSashContainer("root layout container", page, parent) { } ViewSashContainer::Pointer ViewSashContainer::GetRootContainer() { return ViewSashContainer::Pointer(this); } void* ViewSashContainer::GetControl() { return this->parent; } bool ViewSashContainer::RestoreState(IMemento::Pointer memento) { //TODO ViewSashContainer restore state // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.RootLayoutContainer_problemsRestoringPerspective, null); // bool result = true; // Read the info elements. std::vector children(memento->GetChildren(WorkbenchConstants::TAG_INFO)); // Create a part ID to part hashtable. Poco::HashMap mapIDtoPart(children.size()); // Loop through the info elements. for (std::size_t i = 0; i < children.size(); i++) { // Get the info details. IMemento::Pointer childMem = children[i]; std::string partID; childMem->GetString(WorkbenchConstants::TAG_PART, partID); std::string relativeID; childMem->GetString(WorkbenchConstants::TAG_RELATIVE, relativeID); int relationship = 0; int left = 0, right = 0; if (!relativeID.empty()) { childMem->GetInteger(WorkbenchConstants::TAG_RELATIONSHIP, relationship); childMem->GetInteger(WorkbenchConstants::TAG_RATIO_LEFT, left); childMem->GetInteger(WorkbenchConstants::TAG_RATIO_RIGHT, right); } std::string strFolder; childMem->GetString(WorkbenchConstants::TAG_FOLDER, strFolder); // Create the part. LayoutPart::Pointer part; if (strFolder.empty()) { // this is the editor area ContainerPlaceholder::Pointer placeholder(new ContainerPlaceholder(partID)); part = placeholder; } else { PartStack::Pointer folder(new PartStack(page)); folder->SetID(partID); //result.add(folder->RestoreState(childMem->GetChild(WorkbenchConstants::TAG_FOLDER))); result &= folder->RestoreState(childMem->GetChild(WorkbenchConstants::TAG_FOLDER)); ContainerPlaceholder::Pointer placeholder(new ContainerPlaceholder(partID)); placeholder->SetRealContainer(folder); part = placeholder; } // 1FUN70C: ITPUI:WIN - Shouldn't set Container when not active part->SetContainer(ILayoutContainer::Pointer(this)); const int myLeft = left, myRight = right, myRelationship = relationship; LayoutPart::Pointer myPart = part; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void runWithException() throws Throwable // { // Add the part to the layout if (relativeID.empty()) { this->Add(myPart); } else { LayoutPart::Pointer refPart = mapIDtoPart[relativeID]; if (refPart) { this->Add(myPart, myRelationship, myLeft, myRight, refPart); } else { WorkbenchPlugin::Log("Unable to find part for ID: " + relativeID); } } // }} // ); mapIDtoPart[partID] = part; } return result; } bool ViewSashContainer::SaveState(IMemento::Pointer memento) { std::vector relationships = this->ComputeRelation(); bool result = true; // MultiStatus // result = // new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK, WorkbenchMessages.RootLayoutContainer_problemsSavingPerspective, null); // Loop through the relationship array. for (std::size_t i = 0; i < relationships.size(); ++i) { // Save the relationship info .. // private LayoutPart part; // private int relationship; // private float ratio; // private LayoutPart relative; RelationshipInfo& info = relationships[i]; IMemento::Pointer childMem = memento->CreateChild(WorkbenchConstants::TAG_INFO); childMem->PutString(WorkbenchConstants::TAG_PART, info.part->GetID()); if (info.relative) { childMem->PutString(WorkbenchConstants::TAG_RELATIVE, info.relative->GetID()); childMem->PutInteger(WorkbenchConstants::TAG_RELATIONSHIP, info.relationship); childMem->PutInteger(WorkbenchConstants::TAG_RATIO_LEFT, info.left); childMem->PutInteger(WorkbenchConstants::TAG_RATIO_RIGHT, info.right); } // Is this part a folder or a placeholder for one? PartStack::Pointer folder(info.part.Cast()); if (!folder && info.part.Cast()) { IStackableContainer::Pointer part = info.part.Cast()->GetRealContainer(); folder = part.Cast(); } // If this is a folder (PartStack) save the contents. if (folder) { childMem->PutString(WorkbenchConstants::TAG_FOLDER, "true"); IMemento::Pointer folderMem(childMem->CreateChild(WorkbenchConstants::TAG_FOLDER)); //result.add(folder.saveState(folderMem)); result = folder->SaveState(folderMem); } } return result; } bool ViewSashContainer::IsStackType(IStackableContainer::Pointer toTest) { if (toTest.Cast () == 0) return false; return (toTest.Cast ()->GetAppearance() != PresentationFactoryUtil::ROLE_EDITOR); } bool ViewSashContainer::IsPaneType(StackablePart::Pointer toTest) { if (toTest.Cast () == 0) return false; return (toTest.Cast ()->GetPartReference().Cast () != 0); } bool ViewSashContainer::AllowsAdd(LayoutPart::Pointer layoutPart) { return LayoutPart::AllowsAdd(layoutPart); } // void ViewSashContainer::Replace(StackablePart::Pointer oldChild, // StackablePart::Pointer newChild) // { // if (!this->IsChild(oldChild)) // { // return; // } // // // Nasty hack: ensure that all views end up inside a tab folder. // // Since the view title is provided by the tab folder, this ensures // // that views don't get created without a title tab. // if (newChild instanceof ViewPane) // { // ViewStack folder = new ViewStack(page); // folder.add(newChild); // newChild = folder; // } // // super.replace(oldChild, newChild); // } void* ViewSashContainer::CreateParent(void* parentWidget) { return parentWidget; } void ViewSashContainer::DisposeParent() { // do nothing } float ViewSashContainer::GetDockingRatio(Object::Pointer dragged, IStackableContainer::Pointer target) { if (this->IsStackType(target)) { return PartSashContainer::GetDockingRatio(dragged, target); } else { return 0.25f; } } PartStack::Pointer ViewSashContainer::CreateStack() { PartStack::Pointer result(new PartStack(page)); return result; } void ViewSashContainer::SetVisiblePart(IStackableContainer::Pointer container, PartPane::Pointer visiblePart) { if (container.Cast () != 0) { PartStack::Pointer tabFolder = container.Cast (); tabFolder->SetSelection(visiblePart); } } StackablePart::Pointer ViewSashContainer::GetVisiblePart( IStackableContainer::Pointer container) { return container.Cast ()->GetSelection(); } void ViewSashContainer::DerefPart(StackablePart::Pointer sourcePart) { page->GetActivePerspective()->GetPresentation()->DerefPart(sourcePart); } // void ViewSashContainer::AddChild(const RelationshipInfo& info) // { // LayoutPart child = info.part; // // // Nasty hack: ensure that all views end up inside a tab folder. // // Since the view title is provided by the tab folder, this ensures // // that views don't get created without a title tab. // if (child instanceof ViewPane) // { // ViewStack folder = new ViewStack(page); // folder.add(child); // info.part = folder; // } // // super.addChild(info); // } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewSite.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewSite.cpp index 8b99f919da..99c09d85c1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewSite.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewSite.cpp @@ -1,57 +1,57 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryViewSite.h" -#include "../berryIViewReference.h" -#include "../berryIViewPart.h" +#include "berryIViewReference.h" +#include "berryIViewPart.h" #include "berryPartPane.h" -#include "../berryImageDescriptor.h" +#include "berryImageDescriptor.h" #include "berryViewDescriptor.h" #include "berryWorkbenchPage.h" namespace berry { ViewSite::ViewSite(IViewReference::Pointer ref, IViewPart::Pointer view, WorkbenchPage* page, const std::string& id, const std::string& pluginId, const std::string& registeredName) : PartSite(ref, view, page) { SetId(id); SetRegisteredName(registeredName); SetPluginId(pluginId); } ViewSite::ViewSite(IViewReference::Pointer ref, IViewPart::Pointer view, WorkbenchPage* page, IViewDescriptor::Pointer desc) : PartSite(ref, view, page) { SetConfigurationElement(desc.Cast()->GetConfigurationElement()); } std::string ViewSite::GetSecondaryId() { return GetPartReference().Cast()->GetSecondaryId(); } IViewPart::Pointer ViewSite::GetViewPart() { return GetPart().Cast(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewSite.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewSite.h index 713e240591..0c7d75627e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewSite.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryViewSite.h @@ -1,66 +1,66 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYVIEWSITE_H_ #define BERRYVIEWSITE_H_ #include "berryPartSite.h" -#include "../berryIViewSite.h" +#include "berryIViewSite.h" namespace berry { class WorkbenchPage; struct IViewReference; struct IViewPart; struct IViewDescriptor; /** * \ingroup org_blueberry_ui_internal * * A view container manages the services for a view. */ class ViewSite : public PartSite, public IViewSite { public: berryObjectMacro(ViewSite) ViewSite(SmartPointer ref, SmartPointer view, WorkbenchPage* page, const std::string& id, const std::string& pluginId, const std::string& registeredName); /** * Creates a new ViewSite. */ ViewSite(SmartPointer ref, SmartPointer view, WorkbenchPage* page, SmartPointer desc); /** * Returns the secondary id or null. */ std::string GetSecondaryId(); /** * Returns the view. */ SmartPointer GetViewPart(); }; } #endif /*BERRYVIEWSITE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWWinPartService.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWWinPartService.cpp index f874b88068..87042c7b69 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWWinPartService.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWWinPartService.cpp @@ -1,232 +1,232 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWWinPartService.h" -#include "../berryIWorkbenchWindow.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(IWorkbenchPartReference::Pointer /*ref*/) { wwps->UpdateActivePart(); } void PartBroughtToTop(IWorkbenchPartReference::Pointer ref) { wwps->partService.FirePartBroughtToTop(ref); } void PartClosed(IWorkbenchPartReference::Pointer ref) { wwps->partService.FirePartClosed(ref); } void PartDeactivated(IWorkbenchPartReference::Pointer /*ref*/) { wwps->UpdateActivePart(); } void PartOpened(IWorkbenchPartReference::Pointer ref) { wwps->partService.FirePartOpened(ref); } void PartHidden(IWorkbenchPartReference::Pointer ref) { wwps->partService.FirePartHidden(ref); } void PartVisible(IWorkbenchPartReference::Pointer ref) { wwps->partService.FirePartVisible(ref); } void PartInputChanged(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::Pointer l) { partService.AddPartListener(l); } void WWinPartService::RemovePartListener(IPartListener::Pointer 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() { return &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) { std::vector refs(newPage.Cast< WorkbenchPage> ()->GetOpenParts()); for (std::size_t 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); } } 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); std::vector refs(page->GetOpenParts()); for (std::size_t i = 0; i < refs.size(); i++) { IWorkbenchPartReference::Pointer reference = refs[i]; if (page->IsPartVisible(reference)) { partService.FirePartHidden(reference); } partService.FirePartClosed(reference); } tempPage->RemovePartListener(partListener); } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWWinPartService.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWWinPartService.h index 14fa464269..d4b3b69f1d 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWWinPartService.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWWinPartService.h @@ -1,112 +1,112 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWWINPARTSERVICE_H_ #define BERRYWWINPARTSERVICE_H_ -#include "../berryIPartService.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; IPartListener::Pointer 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::Pointer l); /* * (non-Javadoc) * Method declared on IPartService */ void RemovePartListener(IPartListener::Pointer 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(); /* * 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/src/internal/berryWindowManager.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWindowManager.cpp index cd500ad2bc..66a4b4d475 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWindowManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWindowManager.cpp @@ -1,104 +1,104 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWindowManager.h" -#include "../berryWindow.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() { std::vector t = windows; // make iteration robust for (std::vector::iterator iter = t.begin(); iter != t.end(); ++iter) { bool closed = (*iter)->Close(); if (!closed) { return false; } } if (!subManagers.empty()) { for (std::list::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() { return windows.size(); } std::vector WindowManager::GetWindows() { return windows; } void WindowManager::Remove(Window::Pointer window) { std::vector::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/src/internal/berryWindowPartSelectionTracker.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWindowPartSelectionTracker.cpp index 4c5e0c949e..c6f14f43bb 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWindowPartSelectionTracker.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWindowPartSelectionTracker.cpp @@ -1,81 +1,81 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWindowPartSelectionTracker.h" -#include "../berryIWorkbenchWindow.h" -#include "../berryIWorkbenchPage.h" +#include "berryIWorkbenchWindow.h" +#include "berryIWorkbenchPage.h" namespace berry { void WindowPartSelectionTracker::SetWindow( IWorkbenchWindow* window) { fWindow = window; } WindowPartSelectionTracker::WindowPartSelectionTracker(IWorkbenchWindow* window, const std::string& partId) : AbstractPartSelectionTracker(partId), selListener( new NullSelectionChangedAdapter (this, &WindowPartSelectionTracker::FireSelection)), postSelListener( new NullSelectionChangedAdapter (this, &WindowPartSelectionTracker::FirePostSelection)) { SetWindow(window); //window.addPageListener(this); IWorkbenchPage::Pointer page = window->GetActivePage(); if (page) { PageOpened(page); } } void WindowPartSelectionTracker::PageActivated( SmartPointer /*page*/) { } void WindowPartSelectionTracker::PageClosed(SmartPointer page) { page->RemoveSelectionListener(GetPartId(), selListener); page->RemovePostSelectionListener(GetPartId(), postSelListener); } void WindowPartSelectionTracker::PageOpened(SmartPointer page) { page->AddSelectionListener(GetPartId(), selListener); page->AddPostSelectionListener(GetPartId(), postSelListener); } ISelection::ConstPointer WindowPartSelectionTracker::GetSelection() { IWorkbenchPage::Pointer page = GetWindow()->GetActivePage(); if (page) { return page->GetSelection(GetPartId()); } return ISelection::ConstPointer(0); } SmartPointer WindowPartSelectionTracker::GetWindow() { return IWorkbenchWindow::Pointer(fWindow); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWindowPartSelectionTracker.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWindowPartSelectionTracker.h index 388b65b803..feef04779e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWindowPartSelectionTracker.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWindowPartSelectionTracker.h @@ -1,108 +1,108 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWINDOWPARTSELECTIONTRACKER_H_ #define BERRYWINDOWPARTSELECTIONTRACKER_H_ #include "berryAbstractPartSelectionTracker.h" -#include "../berryINullSelectionListener.h" +#include "berryINullSelectionListener.h" namespace berry { struct IWorkbenchWindow; struct IWorkbenchPage; /** * Provides part selection tracking for a part with a specific id * in all pages of a specific workbench window. This tracker shields * clients from a part opening and closing, and still provides selection * notification/information even when the part is not active. */ class WindowPartSelectionTracker : public AbstractPartSelectionTracker { // implements IPageListener { private: /** * The window this selection tracker is working in */ IWorkbenchWindow* fWindow; /** * Part selection listener. */ INullSelectionListener::Pointer selListener; /** * Part post selection listener */ INullSelectionListener::Pointer postSelListener; /** * Sets the window this tracker is working in. * * @param window workbench window */ void SetWindow(IWorkbenchWindow* window); public: /** * Constructs a new selection tracker for the given window and part id. * * @param window workbench window * @param partId part identifier */ WindowPartSelectionTracker(IWorkbenchWindow* window, const std::string& partId); /* * @see IPageListener#pageActivated(IWorkbenchPage) */ void PageActivated(SmartPointer page); /* * @see IPageListener#pageClosed(IWorkbenchPage) */ void PageClosed(SmartPointer page); /* * @see IPageListener#pageOpened(IWorkbenchPage) */ void PageOpened(SmartPointer page); /* * @see AbstractPartSelectionTracker#getSelection() */ ISelection::ConstPointer GetSelection(); protected: /** * Returns the window this tracker is working in. * * @return workbench window */ SmartPointer GetWindow(); }; } #endif /* BERRYWINDOWPARTSELECTIONTRACKER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWindowSelectionService.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWindowSelectionService.cpp index 02d9047b4b..143a0cd5ff 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWindowSelectionService.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWindowSelectionService.cpp @@ -1,50 +1,50 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWindowSelectionService.h" #include "berryWindowPartSelectionTracker.h" -#include "../berryIWorkbenchWindow.h" +#include "berryIWorkbenchWindow.h" namespace berry { void WindowSelectionService::SetWindow(IWorkbenchWindow* window) { this->window = window; } IWorkbenchWindow* WindowSelectionService::GetWindow() const { return window; } AbstractPartSelectionTracker::Pointer WindowSelectionService::CreatePartTracker( const std::string& partId) const { AbstractPartSelectionTracker::Pointer tracker(new WindowPartSelectionTracker( GetWindow(), partId)); return tracker; } WindowSelectionService::WindowSelectionService( IWorkbenchWindow* window) { SetWindow(window); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbench.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbench.cpp index f4268f1606..9168bb9b7b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbench.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbench.cpp @@ -1,1779 +1,1779 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryLog.h" -#include "../tweaklets/berryWorkbenchTweaklet.h" +#include "tweaklets/berryWorkbenchTweaklet.h" #include "berryWorkbench.h" #include #include "berrySaveablesList.h" #include "berryViewRegistry.h" #include "berryEditorRegistry.h" #include "berryServiceLocatorCreator.h" #include "berryWorkbenchPage.h" #include "berryPerspective.h" #include "berryPreferenceConstants.h" -#include "../dialogs/berryMessageDialog.h" +#include "dialogs/berryMessageDialog.h" #include "berryWorkbenchWindow.h" -#include "../berryImageDescriptor.h" -#include "../berryDisplay.h" -#include "../services/berryIServiceFactory.h" -#include "../util/berrySafeRunnable.h" +#include "berryImageDescriptor.h" +#include "berryDisplay.h" +#include "services/berryIServiceFactory.h" +#include "util/berrySafeRunnable.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchConstants.h" #include #include #include namespace berry { Workbench* Workbench::instance = 0; WorkbenchTestable::Pointer Workbench::testableObject; const unsigned int Workbench::VERSION_STRING_COUNT = 1; const std::string Workbench::VERSION_STRING[Workbench::VERSION_STRING_COUNT] = { "1.0" }; const std::string Workbench::DEFAULT_WORKBENCH_STATE_FILENAME = "workbench.xml"; class RestoreStateRunnable: public SafeRunnable { private: Workbench* workbench; Poco::File stateFile; bool& result; public: RestoreStateRunnable(Workbench* workbench, const Poco::File& stateFile, bool& result) : SafeRunnable( "Unable to read workbench state. Workbench UI layout will be reset."), workbench(workbench), stateFile(stateFile), result(result) { } void Run() { Poco::FileInputStream input(stateFile.path()); IMemento::Pointer memento = XMLMemento::CreateReadRoot(input); // Validate known version format std::string 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(); std::string msg = "Invalid workbench state version. workbench.xml will be deleted"; MessageDialog::OpenError(Shell::Pointer(0), "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(); // std::string 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."; // std::vector 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) { //StartupThreading.runWithoutExceptions(new StartupRunnable() { //public void runWithException() { Handle(e); // std::string 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) { 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() { MessageDialog::OpenInformation( Shell::Pointer(0), "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) : progressCount(-1), serviceLocatorOwner(new ServiceLocatorOwner(this)), largeUpdates(0), introManager(0), isStarting(true), isClosing(false) { 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; IServiceLocatorCreator::Pointer slc(new ServiceLocatorCreator()); this->serviceLocator = slc->CreateServiceLocator(IServiceLocator::WeakPtr(), IServiceFactory::ConstPointer(0), IDisposable::WeakPtr(serviceLocatorOwner)).Cast(); serviceLocator->RegisterService(IServiceLocatorCreator::GetManifestName(), slc); returnCode = PlatformUI::RETURN_UNSTARTABLE; } Display* Workbench::GetDisplay() { return display; } Workbench* Workbench::GetInstance() { return instance; } WorkbenchTestable::Pointer Workbench::GetWorkbenchTestable() { if (!testableObject) { testableObject = new WorkbenchTestable(); } return testableObject; } Workbench::~Workbench() { this->UnRegister(false); } Object::Pointer Workbench::GetService(const std::string& key) { return serviceLocator->GetService(key); } bool Workbench::HasService(const std::string& key) const { return serviceLocator->HasService(key); } bool Workbench::Init() { 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 //final EvaluationService restrictionService = new EvaluationService(); //final EvaluationService evaluationService = new EvaluationService(); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // serviceLocator.registerService(IRestrictionService.class, // restrictionService); // serviceLocator.registerService(IEvaluationService.class, // evaluationService); // } // }); // 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()); // 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()) { // std::string 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. Poco::File stateFile; // If there is no state file cause one to open. if (!GetWorkbenchStateFile(stateFile) || !stateFile.exists()) { // std::string 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) { std::string 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. std::vector children = memento ->GetChildren(WorkbenchConstants::TAG_WINDOW); createdWindows.clear(); // Read the workbench windows. for (std::size_t 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 (std::size_t 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 // final IEvaluationService evaluationService = // (IEvaluationService) serviceLocator.getService(IEvaluationService.class); // // // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { Object::Pointer service(new SaveablesList()); serviceLocator->RegisterService(ISaveablesLifecycleListener::GetManifestName(), service); // }}); // // /* // * 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; // commandManager = new CommandManager(); // }}); // // final CommandService [] commandService = new CommandService[1]; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // commandService[0] = new CommandService(commandManager); // commandService[0].readRegistry(); // serviceLocator.registerService(ICommandService.class, commandService[0]); // // }}); // // 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); // // final WorkbenchMenuService menuService = new WorkbenchMenuService(serviceLocator); // // serviceLocator.registerService(IMenuService.class, menuService); // // 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() { // menuService.readRegistry(); // }}); // // /* // * Phase 2 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. // */ // final SourceProviderService sourceProviderService = new SourceProviderService(serviceLocator); // serviceLocator.registerService(ISourceProviderService.class, // sourceProviderService); // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // // this currently instantiates all players ... sigh // sourceProviderService.readRegistry(); // ISourceProvider[] sp = sourceProviderService.getSourceProviders(); // for (int i = 0; i < sp.length; i++) { // evaluationService.addSourceProvider(sp[i]); // if (!(sp[i] instanceof ActiveContextSourceProvider)) { // contextService.addSourceProvider(sp[i]); // } // } // }}); // // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // // 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); // }}); // // /* // * Phase 3 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. // */ // final IHandlerService[] handlerService = new IHandlerService[1]; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { // handlerService[0] = (IHandlerService) serviceLocator // .getService(IHandlerService.class); // } // }); // workbenchContextSupport = new WorkbenchContextSupport(this, // contextManager); // workbenchCommandSupport = new WorkbenchCommandSupport(bindingManager, // commandManager, contextManager, handlerService[0]); // initializeCommandResolver(); // // addWindowListener(windowListener); // 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(); } std::string Workbench::GetDefaultPerspectiveId() { return this->GetAdvisor()->GetInitialWindowPerspectiveId(); } IAdaptable* Workbench::GetDefaultPageInput() { return this->GetAdvisor()->GetDefaultPageInput(); } std::string Workbench::GetPresentationId() { 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; } 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); std::vector windows = this->GetWorkbenchWindows(); for (unsigned 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. std::vector windows = this->GetWorkbenchWindows(); for (unsigned int i = 0; i < windows.size(); i++) { IWorkbenchWindow::Pointer window = windows[i]; if (window.Cast() != 0) { window.Cast()->LargeUpdateEnd(); } } } } 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.displayText() << std::endl; } } WorkbenchConfigurer::Pointer Workbench::GetWorkbenchConfigurer() { if (workbenchConfigurer.IsNull()) { workbenchConfigurer = new WorkbenchConfigurer(); } return workbenchConfigurer; } WorkbenchAdvisor* Workbench::GetAdvisor() { return advisor; } IViewRegistry* Workbench::GetViewRegistry() { return WorkbenchPlugin::GetDefault()->GetViewRegistry(); } IEditorRegistry* Workbench::GetEditorRegistry() { return WorkbenchPlugin::GetDefault()->GetEditorRegistry(); } IPerspectiveRegistry* Workbench::GetPerspectiveRegistry() { 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() { std::vector windows = this->GetWorkbenchWindows(); for (unsigned 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 Poco::Exception& e) { // public void handleException(Throwable e) { std::string message; if (e.message().empty()) { message = "An error has occurred. See error log for more details. Do you want to exit?"; } else { message = "An error has occurred: " + e.message() + ". See error log for more details. Do you want to exit?"; } if (!MessageDialog::OpenQuestion(Shell::Pointer(0), "Error", message)) { 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; } bool Workbench::GetWorkbenchStateFile(Poco::File& file) { Poco::Path path; if (!WorkbenchPlugin::GetDefault()->GetDataPath(path)) { return false; } path.append(DEFAULT_WORKBENCH_STATE_FILENAME); file = path; return true; } /* * 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. Poco::File stateFile; if (!GetWorkbenchStateFile(stateFile)) { return false; } //BERRY_INFO << "Saving state to: " << stateFile.path() << std::endl; try { Poco::FileOutputStream stream(stateFile.path()); memento->Save(stream); } catch (const Poco::IOException& /*e*/) { stateFile.remove(); MessageDialog::OpenError(Shell::Pointer(0), "Saving Problems", "Unable to store workbench state."); return false; } // Success ! return true; } IWorkbenchWindow::Pointer Workbench::GetActiveWorkbenchWindow() { // Look for the window that was last known being // the active one WorkbenchWindow::Pointer win = this->GetActivatedWindow(); return win; } std::size_t Workbench::GetWorkbenchWindowCount() { return windowManager.GetWindowCount(); } std::vector Workbench::GetWorkbenchWindows() { std::vector windows = windowManager.GetWindows(); std::vector result; for (std::vector::iterator iter = windows.begin(); iter != windows.end(); ++iter) { result.push_back(iter->Cast()); } return result; } IWorkbenchWindow::Pointer Workbench::OpenWorkbenchWindow( const std::string& 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 std::string& 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) { std::vector perspectives(page ->GetOpenPerspectives()); for (std::size_t 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(); std::vector windows(GetWorkbenchWindows()); for (std::size_t 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::Pointer 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 std::string& /*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() { return GetWorkbenchIntroManager(); } WorkbenchIntroManager* Workbench::GetWorkbenchIntroManager() { if (introManager == 0) { introManager = new WorkbenchIntroManager(this); } return introManager; } 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() { return Tweaklets::Get(WorkbenchTweaklet::KEY)->IsRunning(); } bool Workbench::IsStarting() { return isStarting; } bool Workbench::IsClosing() { return isClosing; } WorkbenchWindow::Pointer Workbench::GetActivatedWindow() { 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 = Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateWorkbenchWindow(this->GetNewWindowNumber()); //wbw->Init(); return wbw; } int Workbench::GetNewWindowNumber() { // Get window list. std::vector 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 std::string& 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. std::vector windows(GetWorkbenchWindows()); for (std::size_t 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::Pointer listener) { workbenchEvents.AddListener(listener); } void Workbench::RemoveWorkbenchListener(IWorkbenchListener::Pointer listener) { workbenchEvents.RemoveListener(listener); } IWorkbenchListener::Events& Workbench::GetWorkbenchEvents() { return workbenchEvents; } void Workbench::AddWindowListener(IWindowListener::Pointer l) { windowEvents.AddListener(l); } void Workbench::RemoveWindowListener(IWindowListener::Pointer 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(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbench.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbench.h index 9f6c38caf2..6e59827753 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbench.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbench.h @@ -1,602 +1,602 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWORKBENCH_H_ #define BERRYWORKBENCH_H_ -#include "../berryIViewPart.h" -#include "../berryIWorkbench.h" +#include "berryIViewPart.h" +#include "berryIWorkbench.h" #include "berryWorkbenchWindow.h" -#include "../berryIWorkbenchPage.h" -#include "../berryIWorkbenchPartReference.h" -#include "../berryXMLMemento.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 "application/berryWorkbenchAdvisor.h" #include "berryWorkbenchTestable.h" #include "intro/berryIntroDescriptor.h" #include "intro/berryWorkbenchIntroManager.h" #include "berryIStackableContainer.h" #include "berryServiceLocator.h" #include #include namespace berry { class ViewRegistry; class EditorRegistry; class WorkbenchWindowConfigurer; /** * \ingroup org_blueberry_ui * * 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 Workbench : public IWorkbench { 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::Pointer GetService(const std::string& key); /* * (non-Javadoc) * * @see org.blueberry.ui.services.IServiceLocator#hasService(java.lang.Object) */ bool HasService(const std::string& 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::Pointer listener); /* * Method declared on IWorkbench. */ void RemoveWorkbenchListener(IWorkbenchListener::Pointer listener); /* * Method declared on IWorkbench. */ IWorkbenchListener::Events& GetWorkbenchEvents(); /* * Method declared on IWorkbench. */ void AddWindowListener(IWindowListener::Pointer l); /* * Method declared on IWorkbench. */ void RemoveWindowListener(IWindowListener::Pointer l); /* * Method declared on IWorkbench. */ IWindowListener::Events& GetWindowEvents(); IWorkbenchWindow::Pointer GetActiveWorkbenchWindow(); IViewRegistry* GetViewRegistry(); IEditorRegistry* GetEditorRegistry(); IPerspectiveRegistry* GetPerspectiveRegistry(); std::size_t GetWorkbenchWindowCount(); std::vector GetWorkbenchWindows(); IWorkbenchWindow::Pointer OpenWorkbenchWindow(const std::string& perspectiveId, IAdaptable* input); IWorkbenchWindow::Pointer OpenWorkbenchWindow(IAdaptable* input); IWorkbenchPage::Pointer ShowPerspective(const std::string& perspectiveId, IWorkbenchWindow::Pointer window); IWorkbenchPage::Pointer ShowPerspective(const std::string& perspectiveId, IWorkbenchWindow::Pointer window, IAdaptable* input); bool SaveAllEditors(bool confirm); IIntroManager* GetIntroManager(); /** * @return the workbench intro manager */ WorkbenchIntroManager* GetWorkbenchIntroManager(); /** * @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(); /** * 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 IsClosing(); /** * Returns the default perspective id, which may be null. * * @return the default perspective id, or null */ std::string GetDefaultPerspectiveId(); /** * Returns the default workbench window page input. * * @return the default window page input or null if none */ IAdaptable* GetDefaultPageInput(); /** * Return the presentation ID specified by the preference or the default ID * if undefined. * * @return the presentation ID * @see IWorkbenchPreferenceConstants#PRESENTATION_FACTORY_ID */ std::string GetPresentationId(); 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(); protected: friend class PlatformUI; friend class WorkbenchConfigurer; friend class WorkbenchWindowConfigurer; friend class WorkbenchWindow; friend struct WorkbenchWindow::ShellActivationListener; 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(); /* * Returns the workbench window which was last known being the active one, * or null . */ SmartPointer GetActivatedWindow(); /* * 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 std::string VERSION_STRING[1]; static const std::string 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; /** * 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. */ std::vector createdWindows; struct ServiceLocatorOwner : public IDisposable { ServiceLocatorOwner(Workbench* workbench); void Dispose(); private: Workbench* workbench; }; friend struct ServiceLocatorOwner; IDisposable::Pointer serviceLocatorOwner; /** * 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; WorkbenchIntroManager* 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; std::string factoryID; /** * 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(); /* * 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. */ bool GetWorkbenchStateFile(Poco::File& file); /* * 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 std::string& perspID, IAdaptable* input); }; } // namespace berry #endif /*BERRYWORKBENCH_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchConfigurer.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchConfigurer.cpp index cec2a87a1f..0db9378055 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchConfigurer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchConfigurer.cpp @@ -1,133 +1,133 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWorkbenchConfigurer.h" -#include "../berryPlatformUI.h" +#include "berryPlatformUI.h" #include "berryWorkbenchWindow.h" -#include "../berryImageDescriptor.h" +#include "berryImageDescriptor.h" #include "berryWorkbench.h" namespace berry { WorkbenchConfigurer::WorkbenchConfigurer() : saveAndRestore(false), isEmergencyClosing(false), exitOnLastWindowClose(true) { } IWorkbench* WorkbenchConfigurer::GetWorkbench() { return PlatformUI::GetWorkbench(); } IWorkbenchWindowConfigurer::Pointer WorkbenchConfigurer::GetWindowConfigurer( IWorkbenchWindow::Pointer window) { if (window.IsNull()) { throw Poco::InvalidArgumentException(); } return window.Cast ()->GetWindowConfigurer(); } bool WorkbenchConfigurer::GetSaveAndRestore() { return saveAndRestore; } void WorkbenchConfigurer::SetSaveAndRestore(bool enabled) { saveAndRestore = enabled; } Object::Pointer WorkbenchConfigurer::GetData(const std::string& key) const { if (key.empty()) { throw Poco::InvalidArgumentException(); } Poco::HashMap::ConstIterator i = extraData.find(key); if (i != extraData.end()) return i->second; return Object::Pointer(0); } void WorkbenchConfigurer::SetData(const std::string& key, Object::Pointer data) { if (key.empty()) { throw Poco::InvalidArgumentException(); } if (data) { extraData.insert(std::make_pair(key, data)); } else { extraData.erase(key); } } void WorkbenchConfigurer::EmergencyClose() { if (!isEmergencyClosing) { isEmergencyClosing = true; if (Workbench::GetInstance() != 0 && !Workbench::GetInstance()->IsClosing()) { Workbench::GetInstance()->Close(PlatformUI::RETURN_EMERGENCY_CLOSE, true); } } } bool WorkbenchConfigurer::EmergencyClosing() { return isEmergencyClosing; } bool WorkbenchConfigurer::RestoreState() { return dynamic_cast (GetWorkbench())->RestoreState(); } void WorkbenchConfigurer::OpenFirstTimeWindow() { dynamic_cast (this->GetWorkbench())->OpenFirstTimeWindow(); } IWorkbenchWindowConfigurer::Pointer WorkbenchConfigurer::RestoreWorkbenchWindow( IMemento::Pointer memento) { return this->GetWindowConfigurer( dynamic_cast (this->GetWorkbench())->RestoreWorkbenchWindow( memento)); } bool WorkbenchConfigurer::GetExitOnLastWindowClose() { return exitOnLastWindowClose; } void WorkbenchConfigurer::SetExitOnLastWindowClose(bool enabled) { exitOnLastWindowClose = enabled; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchConfigurer.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchConfigurer.h index 3bed747aca..e1809db957 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchConfigurer.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchConfigurer.h @@ -1,167 +1,167 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWORKBENCHCONFIGURER_H_ #define BERRYWORKBENCHCONFIGURER_H_ -#include "../application/berryIWorkbenchConfigurer.h" +#include "application/berryIWorkbenchConfigurer.h" #include namespace berry { /** * Internal class providing special access for configuring the workbench. *

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

    *

    * This class is not intended to be instantiated or subclassed by clients. *

    * * @since 3.0 */ class WorkbenchConfigurer : public IWorkbenchConfigurer { public: berryObjectMacro(WorkbenchConfigurer); private: /** * Table to hold arbitrary key-data settings. * @see #SetData */ Poco::HashMap extraData; /** * Indicates whether workbench state should be saved on close and * restored on subsequent open. */ bool saveAndRestore; /** * Indicates whether the workbench is being forced to close. During * an emergency close, no interaction with the user should be done. */ bool isEmergencyClosing; /** * Indicates the behaviour when the last window is closed. * If true, the workbench will exit (saving the last window's state, * if configured to do so). * If false the window will be closed, leaving the workbench running. * * @since 3.1 */ bool exitOnLastWindowClose; public: /** * Creates a new workbench configurer. *

    * This method is declared package-private. Clients are passed an instance * only via {@link WorkbenchAdvisor#initialize WorkbenchAdvisor.initialize} *

    */ WorkbenchConfigurer(); /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchConfigurer#getWorkbench */ IWorkbench* GetWorkbench(); /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchConfigurer#declareImage */ // void declareImage(String symbolicName, ImageDescriptor descriptor, // boolean shared) { // if (symbolicName == null || descriptor == null) { // throw new IllegalArgumentException(); // } // WorkbenchImages.declareImage(symbolicName, descriptor, shared); // } /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchConfigurer#getWindowConfigurer */ IWorkbenchWindowConfigurer::Pointer GetWindowConfigurer(IWorkbenchWindow::Pointer window); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchConfigurer#getSaveAndRestore() */ bool GetSaveAndRestore(); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchConfigurer#setSaveAndRestore(boolean) */ void SetSaveAndRestore(bool enabled); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchConfigurer#getData */ Object::Pointer GetData(const std::string& key) const; /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchConfigurer#setData(String, Object) */ void SetData(const std::string& key, Object::Pointer data); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchConfigurer#emergencyClose() */ void EmergencyClose(); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchConfigurer#emergencyClosing() */ bool EmergencyClosing(); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchConfigurer#restoreState() */ bool RestoreState(); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchConfigurer#openFirstTimeWindow() */ void OpenFirstTimeWindow(); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchConfigurer#restoreWorkbenchWindow(org.blueberry.ui.IMemento) */ IWorkbenchWindowConfigurer::Pointer RestoreWorkbenchWindow(IMemento::Pointer memento); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchConfigurer#getExitOnLastWindowClose() */ bool GetExitOnLastWindowClose(); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchConfigurer#setExitOnLastWindowClose(boolean) */ void SetExitOnLastWindowClose(bool enabled); }; } #endif /*BERRYWORKBENCHCONFIGURER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchConstants.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchConstants.cpp index cd1d6dc6f0..5f375eb8ea 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchConstants.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchConstants.cpp @@ -1,350 +1,350 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWorkbenchConstants.h" -#include "../berryPlatformUI.h" +#include "berryPlatformUI.h" namespace berry { const std::string WorkbenchConstants::DEFAULT_PRESENTATION_ID = "org.blueberry.ui.presentations.default"; //$NON-NLS-1$ const std::string WorkbenchConstants::RESOURCE_TYPE_FILE_NAME = "resourcetypes.xml"; //$NON-NLS-1$ // Filename containing the workbench's preferences const std::string WorkbenchConstants::PREFERENCE_BUNDLE_FILE_NAME = "workbench.ini"; //$NON-NLS-1$ // Identifier for visible view parts. const std::string WorkbenchConstants::WORKBENCH_VISIBLE_VIEW_ID = "Workbench.visibleViewID"; //$NON-NLS-1$ // Identifier of workbench info properties page //const std::string WorkbenchConstants::WORKBENCH_PROPERTIES_PAGE_INFO = // PlatformUI::PLUGIN_ID + ".propertypages.info.file"; //$NON-NLS-1$ // Various editor. //const std::string WorkbenchConstants::OLE_EDITOR_ID = PlatformUI::PLUGIN_ID // + ".OleEditor"; //$NON-NLS-1$ // Default view category. const std::string WorkbenchConstants::DEFAULT_CATEGORY_ID = "org.blueberry.ui"; //PlatformUI::PLUGIN_ID; // Persistance tags. const std::string WorkbenchConstants::TRUE_VAL = "true"; //$NON-NLS-1$ const std::string WorkbenchConstants::FALSE_VAL = "false"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_WORKBENCH_ADVISOR = "workbenchAdvisor"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_WORKBENCH_WINDOW_ADVISOR = "workbenchWindowAdvisor"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ACTION_BAR_ADVISOR = "actionBarAdvisor"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ID = "id"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FOCUS = "focus"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_EDITOR = "editor"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_DEFAULT_EDITOR = "defaultEditor"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_DELETED_EDITOR = "deletedEditor"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_EDITORS = "editors"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_WORKBOOK = "workbook"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ACTIVE_WORKBOOK = "activeWorkbook"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_AREA = "editorArea"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_AREA_VISIBLE = "editorAreaVisible"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_AREA_HIDDEN = "editorAreaHidden"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_AREA_TRIM_STATE = "editorAreaTrimState"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_INPUT = "input"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FACTORY_ID = "factoryID"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_EDITOR_STATE = "editorState"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_TITLE = "title"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_X = "x"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_Y = "y"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FLOAT = "float"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ITEM_WRAP_INDEX = "wrapIndex"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_TOOLBAR_LAYOUT = "toolbarLayout"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_WIDTH = "width"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_HEIGHT = "height"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_MINIMIZED = "minimized"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_MAXIMIZED = "maximized"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FOLDER = "folder"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_INFO = "info"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PART = "part"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PART_NAME = "partName"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PROPERTIES = "properties"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PROPERTY = "property"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_RELATIVE = "relative"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_RELATIONSHIP = "relationship"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_RATIO = "ratio"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_RATIO_LEFT = "ratioLeft"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_RATIO_RIGHT = "ratioRight"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ACTIVE_PAGE_ID = "activePageID"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_EXPANDED = "expanded"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PAGE = "page"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_INTRO = "intro"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_STANDBY = "standby"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_LABEL = "label"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_CONTENT = "content"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_CLASS = "class"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FILE = "file"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_DESCRIPTOR = "descriptor"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_MAIN_WINDOW = "mainWindow"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_DETACHED_WINDOW = "detachedWindow"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_HIDDEN_WINDOW = "hiddenWindow"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_WORKBENCH = "workbench"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_WINDOW = "window"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_VERSION = "version"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PROGRESS_COUNT = "progressCount"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PERSPECTIVES = "perspectives"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PERSPECTIVE = "perspective"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ACTIVE_PERSPECTIVE = "activePerspective"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ACTIVE_PART = "activePart"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ACTION_SET = "actionSet"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ALWAYS_ON_ACTION_SET = "alwaysOnActionSet"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ALWAYS_OFF_ACTION_SET = "alwaysOffActionSet"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_SHOW_VIEW_ACTION = "show_view_action"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_SHOW_IN_TIME = "show_in_time"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_TIME = "time"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_NEW_WIZARD_ACTION = "new_wizard_action"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PERSPECTIVE_ACTION = "perspective_action"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_VIEW = "view"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_LAYOUT = "layout"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_EXTENSION = "extension"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_NAME = "name"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_IMAGE = "image"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_LAUNCHER = "launcher"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PLUGIN = "plugin"; //$NON-NLS-1$ /** deprecated - use TAG_OPEN_MODE */ const std::string WorkbenchConstants::TAG_INTERNAL = "internal"; //$NON-NLS-1$ /** deprecated - use TAG_OPEN_MODE */ const std::string WorkbenchConstants::TAG_OPEN_IN_PLACE = "open_in_place"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PROGRAM_NAME = "program_name"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FAST_VIEWS = "fastViews"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FAST_VIEW_BAR = "fastViewBar"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FAST_VIEW_BARS = "fastViewBars"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_GLOBAL_FAST_VIEWS = "globalFastViews"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FAST_GROUPS = "fastGroups"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FIXED = "fixed";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_CLOSEABLE = "closeable";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_MOVEABLE = "moveable";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_APPEARANCE = "appearance"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PRESENTATION = "presentation"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_STANDALONE = "standalone";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_SHOW_TITLE = "showTitle";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_VIEW_STATE = "viewState"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_SINGLETON = "singleton"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_EDITOR_REUSE_THRESHOLD = "editorReuseThreshold"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PERSISTABLE = "persistable"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_MRU_LIST = "mruList"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PERSPECTIVE_HISTORY = "perspHistory"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_WORKING_SET_MANAGER = "workingSetManager"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_WORKING_SETS = "workingSets"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_WORKING_SET = "workingSet"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ITEM = "item"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_EDIT_PAGE_ID = "editPageId"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_COOLBAR_LAYOUT = "coolbarLayout"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ITEM_SIZE = "itemSize"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ITEM_X = "x"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ITEM_Y = "y"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ITEM_TYPE = "itemType"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_TYPE_SEPARATOR = "typeSeparator"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_TYPE_GROUPMARKER = "typeGroupMarker"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_TYPE_TOOLBARCONTRIBUTION = "typeToolBarContribution"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_TYPE_PLACEHOLDER = "typePlaceholder"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_COOLITEM = "coolItem"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_INDEX = "index"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PINNED = "pinned"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PATH = "path";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_TOOLTIP = "tooltip";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_VIEWS = "views";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_POSITION = "position";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_NAVIGATION_HISTORY = "navigationHistory";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_STICKY_STATE = "stickyState"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_ACTIVE = "active";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_REMOVED = "removed";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_HISTORY_LABEL = "historyLabel";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_LOCKED = "locked";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_OPEN_MODE = "openMode"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_STARTUP = "startup"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FAST_VIEW_SIDE = "fastViewLocation"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FAST_VIEW_DATA = "fastViewData"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FAST_VIEW_ORIENTATION = "orientation"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FAST_VIEW_SEL_ID = "selectedTabId"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_FAST_VIEW_STYLE = "style"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_THEME = "theme";//$NON-NLS-1$ const std::string WorkbenchConstants::TAG_VIEW_LAYOUT_REC = "viewLayoutRec"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_PERSPECTIVE_BAR = "perspectiveBar"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_TRIM = "trimLayout"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_TRIM_AREA = "trimArea"; //$NON-NLS-1$ const std::string WorkbenchConstants::TAG_TRIM_ITEM = "trimItem"; //$NON-NLS-1$ //Fonts const std::string WorkbenchConstants::SMALL_FONT = "org.blueberry.ui.smallFont"; //$NON-NLS-1$ //Colors const std::string WorkbenchConstants::COLOR_HIGHLIGHT_ = "org.blueberry.ui.highlight"; //$NON-NLS-1$ } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPage.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPage.cpp index aad8d7ac4b..79c55f1e52 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPage.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPage.cpp @@ -1,4112 +1,4112 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryLog.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" -#include "../tweaklets/berryWorkbenchPageTweaklet.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 "intro/berryIntroConstants.h" #include "intro/berryViewIntroAdapterPart.h" -#include "../dialogs/berryMessageDialog.h" +#include "dialogs/berryMessageDialog.h" #include "berryWorkbenchWindow.h" -#include "../berryUIException.h" -#include "../berryPlatformUI.h" +#include "berryUIException.h" +#include "berryPlatformUI.h" #include "berryPartPane.h" -#include "../berryImageDescriptor.h" +#include "berryImageDescriptor.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.remove(perspective); PerspectiveListType::size_type origSize = openedList.size(); openedList.remove(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.rbegin()); } } } 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.remove(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) { IStackableContainer::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); IStackableContainer::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*/) { std::vector 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 (unsigned int j = 0; j < views.size(); j++) { if (views[j] == viewRef) { return viewRef.Cast (); } } //} } else { return ref.Cast (); } ++i; } return IWorkbenchPartReference::Pointer(0); } std::vector > WorkbenchPage::ActivationList::GetEditors() { std::vector editors; for (PartListIter i = parts.begin(); i != parts.end(); ++i) { if (IEditorReference::Pointer part = i->Cast()) { editors.push_back(part); } } return editors; } std::vector > WorkbenchPage::ActivationList::GetParts() { std::vector views(page->GetViewReferences()); std::vector resultList; for (PartListIter iterator = parts.begin(); iterator != parts.end(); ++iterator) { if (IViewReference::Pointer ref = iterator->Cast()) { //Filter views from other perspectives for (unsigned int i = 0; i < views.size(); i++) { if (ref == views[i]) { resultList.push_back(ref); break; } } } else { resultList.push_back(*iterator); } } return resultList; } 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) { std::string oldId; if (_topEditor) { oldId = _topEditor->GetSite()->GetId(); } std::string 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(); // } 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; } std::string oldId; if (!topEditor.Expired()) { oldId = topEditor.Lock()->GetSite()->GetId(); } std::string 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(); // } 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); } const IExtensionPoint* WorkbenchPage::GetPerspectiveExtensionPoint() { return Platform::GetExtensionPointService()->GetExtensionPoint( PlatformUI::PLUGIN_ID + "." + WorkbenchRegistryConstants::PL_PERSPECTIVE_EXTENSIONS); } WorkbenchPage::WorkbenchPage(WorkbenchWindow* w, const std::string& layoutID, IAdaptable* input) { 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) { 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::Pointer l) { partList->GetPartService()->AddPartListener(l); } void WorkbenchPage::AddSelectionListener(ISelectionListener::Pointer listener) { selectionService->AddSelectionListener(listener); } void WorkbenchPage::AddSelectionListener(const std::string& partId, ISelectionListener::Pointer listener) { selectionService->AddSelectionListener(partId, listener); } void WorkbenchPage::AddPostSelectionListener( ISelectionListener::Pointer listener) { selectionService->AddPostSelectionListener(listener); } void WorkbenchPage::AddPostSelectionListener(const std::string& partId, ISelectionListener::Pointer listener) { selectionService->AddPostSelectionListener(partId, listener); } IStackableContainer::Pointer WorkbenchPage::GetContainer( IWorkbenchPart::Pointer part) { PartPane::Pointer pane = this->GetPane(part); if (pane == 0) { return IStackableContainer::Pointer(0); } return pane->GetContainer(); } IStackableContainer::Pointer WorkbenchPage::GetContainer( IWorkbenchPartReference::Pointer part) { PartPane::Pointer pane = this->GetPane(part); if (pane == 0) { return IStackableContainer::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()) { IStackableContainer::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; // } // std::string 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); IStackableContainer::Pointer activeEditorContainer = this->GetContainer( this->GetActiveEditor().Cast ()); IStackableContainer::Pointer activePartContainer = this->GetContainer( this->GetActivePart()); IStackableContainer::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::BusySetPerspective(IPerspectiveDescriptor::Pointer desc) { // Create new layout. std::string 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 std::string& viewID, const std::string& 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::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 (); std::vector viewStack = this->GetViewReferenceStack(part); for (unsigned 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 std::list editors = this->GetEditorReferences(); std::list savedEditors; for (std::list::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 std::list& 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 std::vector editorRefs; for (std::list::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) { Poco::RuntimeException re( "WARNING: Blocked recursive attempt to close part " //$NON-NLS-1$ + 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 std::list partsToClose; for (unsigned 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 = this->GetWorkbenchWindow()->GetService( ISaveablesLifecycleListener::GetManifestName()).Cast (); // 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 (unsigned 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 (unsigned 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(); std::vector disposals = pendingDisposals; pendingDisposals.clear(); for (unsigned 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) { std::list 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()) { std::list list; list.push_back(ref.Cast ()); return this->CloseEditors(list, save); } return false; } 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(); // } std::vector partsToSave; std::list viewsToClose; // collect views that will go away and views that are dirty std::vector viewReferences = persp->GetViewReferences(); for (unsigned 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 std::list editorReferences = this->GetEditorReferences(); for (std::list::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 = this->GetWorkbenchWindow()->GetWorkbench()->GetService( ISaveablesLifecycleListener::GetManifestName()).Cast< SaveablesList> (); // 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() { void* 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) { std::string 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()) { MessageDialog::OpenError(window->GetShell(), "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. std::vector partsToClose = this->GetOpenParts(); std::list dirtyParts; for (unsigned 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 = this->GetWorkbenchWindow()->GetWorkbench()->GetService( ISaveablesLifecycleListener::GetManifestName()).Cast< SaveablesList> (); 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(); // Capture views. std::vector refs = viewFactory->GetViews(); // if (refs.size() > 0) // { // // Dispose views. // for (unsigned int i = 0; i < refs.size(); i++) // { // WorkbenchPartReference::Pointer ref = refs[i].Cast(); // //partList.RemovePart(ref); // //this->FirePartClosed(refs[i]); // // Platform.run(new SafeRunnable() { // // public void run() { // // // WorkbenchPlugin.log(new Status(IStatus.WARNING, WorkbenchPlugin.PI_WORKBENCH, // // // Status.OK, "WorkbenchPage leaked a refcount for view " + ref.getId(), 0)); //$NON-NLS-1$//$NON-NLS-2$ // // ref.dispose(); // // } // // // public void handleException(Throwable e) { // // } // // }); // } // } // 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 = 0; } // 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 std::string& id) { IViewReference::Pointer ref = this->FindViewReference(id); if (ref == 0) { return IViewPart::Pointer(0); } return ref->GetView(true); } IViewReference::Pointer WorkbenchPage::FindViewReference( const std::string& viewId) { return this->FindViewReference(viewId, ""); } IViewReference::Pointer WorkbenchPage::FindViewReference( const std::string& viewId, const std::string& 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(); } void* WorkbenchPage::GetClientComposite() { return composite; } EditorManager* WorkbenchPage::GetEditorManager() { return editorMgr; } PerspectiveHelper* WorkbenchPage::GetPerspectivePresentation() { if (this->GetActivePerspective() != 0) { return this->GetActivePerspective()->GetPresentation(); } return 0; } /** * Answer the editor presentation. */ EditorAreaHelper* WorkbenchPage::GetEditorPresentation() { return editorPresentation; } std::vector WorkbenchPage::GetEditors() { std::list refs = this->GetEditorReferences(); std::vector result; //Display d = getWorkbenchWindow().getShell().getDisplay(); //Must be backward compatible. // d.syncExec(new Runnable() // { // public void WorkbenchPage::run() // { for (std::list::iterator iter = refs.begin(); iter != refs.end(); ++iter) { IEditorPart::Pointer part = (*iter)->GetEditor(true); if (part != 0) { result.push_back(part); } } // } // }); return result; } std::vector WorkbenchPage::GetDirtyEditors() { return this->GetEditorManager()->GetDirtyEditors(); } std::vector WorkbenchPage::GetDirtyParts() { std::vector result; std::vector allParts = this->GetAllParts(); for (unsigned 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); } std::vector WorkbenchPage::FindEditors( IEditorInput::Pointer input, const std::string& editorId, int matchFlags) { return this->GetEditorManager()->FindEditors(input, editorId, matchFlags); } std::list WorkbenchPage::GetEditorReferences() { return editorPresentation->GetEditors(); } IAdaptable* WorkbenchPage::GetInput() { return input; } std::string WorkbenchPage::GetLabel() { std::string 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 std::string& partId) { return selectionService->GetSelection(partId); } //ISelectionService::SelectionEvents& WorkbenchPage::GetSelectionEvents(const std::string& partId) //{ // return selectionService->GetSelectionEvents(partId); //} ViewFactory* WorkbenchPage::GetViewFactory() { if (viewFactory == 0) { viewFactory = new ViewFactory(this, WorkbenchPlugin::GetDefault()->GetViewRegistry()); } return viewFactory; } std::vector WorkbenchPage::GetViewReferences() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp != 0) { return persp->GetViewReferences(); } else { return std::vector(); } } std::vector WorkbenchPage::GetViews() { return this->GetViews(Perspective::Pointer(0), true); } std::vector WorkbenchPage::GetViews( Perspective::Pointer persp, bool restore) { if (persp == 0) { persp = this->GetActivePerspective(); } std::vector parts; if (persp != 0) { std::vector refs = persp->GetViewReferences(); for (unsigned 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() { 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(); std::vector 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::Pointer saveablesList; SaveablesList::PostCloseInfo::Pointer postCloseInfo; if (refCount == 1) { IWorkbenchPart::Pointer actualPart = ref->GetPart(false); if (actualPart != 0) { saveablesList = actualPart->GetSite()->GetService( ISaveablesLifecycleListener::GetManifestName()).Cast< SaveablesList> (); std::list 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 std::string& 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 = 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())); } void WorkbenchPage::OpenPerspectiveExtras() { //TODO WorkbenchPage perspectice extras std::string extras = ""; //PrefUtil.getAPIPreferenceStore().getString( // IWorkbenchPreferenceConstants.PERSPECTIVE_BAR_EXTRAS); Poco::StringTokenizer tok(extras, ", ", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY); //$NON-NLS-1$ std::vector descs; for (Poco::StringTokenizer::Iterator itr = tok.begin(); itr != tok.end(); ++itr) { std::string id = *itr; 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 std::string& editorID) { return this->OpenEditor(input, editorID, true, MATCH_INPUT); } IEditorPart::Pointer WorkbenchPage::OpenEditor(IEditorInput::Pointer input, const std::string& editorID, bool activate) { return this->OpenEditor(input, editorID, activate, MATCH_INPUT); } IEditorPart::Pointer WorkbenchPage::OpenEditor( const IEditorInput::Pointer input, const std::string& editorID, bool activate, int matchFlags) { return this->OpenEditor(input, editorID, activate, matchFlags, IMemento::Pointer(0)); } IEditorPart::Pointer WorkbenchPage::OpenEditor( const IEditorInput::Pointer input, const std::string& 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 std::string& 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 std::string& 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()) { std::vector dlgLabels; dlgLabels.push_back("Yes"); dlgLabels.push_back("No"); dlgLabels.push_back("Cancel"); IDialog::Pointer dialog = MessageDialog::CreateMessageDialog( this->GetWorkbenchWindow()->GetShell(), "Save", (void*) 0, // accept the default window icon "\"" + input->GetName() + "\" is opened and has unsaved changes. Do you want to save it?", IDialog::QUESTION, dlgLabels, 0); int saveFile = dialog->Open(); if (saveFile == 0) { // 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 == 2) { 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::Pointer 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::Pointer listener) { selectionService->RemoveSelectionListener(listener); } void WorkbenchPage::RemoveSelectionListener(const std::string& partId, ISelectionListener::Pointer listener) { selectionService->RemoveSelectionListener(partId, listener); } void WorkbenchPage::RemovePostSelectionListener( ISelectionListener::Pointer listener) { selectionService->RemovePostSelectionListener(listener); } void WorkbenchPage::RemovePostSelectionListener(const std::string& partId, ISelectionListener::Pointer 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 std::string 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) // { // std::vector 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); std::string activePartID; childMem->GetString(WorkbenchConstants::TAG_ACTIVE_PART, activePartID); std::string activePartSecondaryID; if (!activePartID.empty()) { activePartSecondaryID = ViewFactory::ExtractSecondaryId(activePartID); if (!activePartSecondaryID.empty()) { activePartID = ViewFactory::ExtractPrimaryId(activePartID); } } std::string activePerspectiveID; childMem->GetString(WorkbenchConstants::TAG_ACTIVE_PERSPECTIVE, activePerspectiveID); // Restore perspectives. std::vector perspMems(childMem->GetChildren( WorkbenchConstants::TAG_PERSPECTIVE)); Perspective::Pointer activePerspective; for (std::size_t 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 == activeDescriptor) { activePerspective = persp; } else if ((activePerspective == 0) && desc->GetId() == activePerspectiveID) { activePerspective = persp; } perspList.Add(persp); 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; std::string myActivePartId = activePartID; std::string mySecondaryId = activePartSecondaryID; // StartupThreading.runWithoutExceptions(new StartupRunnable() // { // // public void WorkbenchPage::runWithException() throws Throwable // { window->FirePerspectiveActivated(WorkbenchPage::Pointer(this), myPerspective->GetDesc()); // Restore active part. if (!myActivePartId.empty()) { 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); // std::string 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 (...) { // std::string 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; } std::string WorkbenchPage::GetId(IWorkbenchPart::Pointer part) { return this->GetId(this->GetReference(part)); } std::string 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(Poco::RuntimeException( "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) { std::string title = "Restoring problems"; std::string msg = "Unable to read workbench state."; MessageDialog::OpenError(this->GetWorkbenchWindow()->GetShell(), 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 std::vector oldRefs; if (oldPersp != 0) { oldRefs = oldPersp->GetViewReferences(); for (unsigned 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(); std::vector newRefs = newPersp->GetViewReferences(); for (unsigned 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 (unsigned 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 std::string& viewID) { return this->ShowView(viewID, "", VIEW_ACTIVATE); } IViewPart::Pointer WorkbenchPage::ShowView(const std::string& viewID, const std::string& secondaryID, int mode) { if (secondaryID != "") { if (secondaryID.size() == 0 || secondaryID.find_first_of( ViewFactory::ID_SEP) != std::string::npos) { throw Poco::InvalidArgumentException( "Illegal secondary id (cannot be empty or contain a colon)"); } } if (!this->CertifyMode(mode)) { throw Poco::InvalidArgumentException("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; } std::vector WorkbenchPage::GetSortedEditors() { return activationList->GetEditors(); } std::vector WorkbenchPage::GetOpenPerspectives() { std::list opened = perspList.GetOpenedPerspectives(); std::vector result; for (std::list::iterator iter = opened.begin(); iter != opened.end(); ++iter) { result.push_back((*iter)->GetDesc()); } return result; } std::list WorkbenchPage::GetOpenInternalPerspectives() { return perspList.GetOpenedPerspectives(); } Perspective::Pointer WorkbenchPage::GetFirstPerspectiveWithView( IViewPart::Pointer part) { std::list perspectives = perspList.GetSortedPerspectives(); for (std::list::reverse_iterator iter = perspectives.rbegin(); iter != perspectives.rend(); ++iter) { if ((*iter)->ContainsView(part)) { return *iter; } } // we should never get here return Perspective::Pointer(0); } std::vector WorkbenchPage::GetSortedPerspectives() { std::list sortedArray = perspList.GetSortedPerspectives(); std::vector result; for (std::list::iterator iter = sortedArray.begin(); iter != sortedArray.end(); ++iter) { result.push_back((*iter)->GetDesc()); } return result; } std::vector 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()); } std::vector WorkbenchPage::GetViewReferenceStack( IViewPart::Pointer part) { // Sanity check. Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0 || !this->CertifyPart(part)) { return std::vector(); } IStackableContainer::Pointer container = part->GetSite().Cast ()->GetPane()->GetContainer(); if (container.Cast () != 0) { PartStack::Pointer folder = container.Cast (); std::vector list; IStackableContainer::ChildrenType children = folder->GetChildren(); for (IStackableContainer::ChildrenType::iterator childIter = children.begin(); childIter != children.end(); ++childIter) { StackablePart::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; } std::vector result; result.push_back(this->GetReference(part).Cast ()); return result; } std::vector WorkbenchPage::GetViewStack( IViewPart::Pointer part) { std::vector refStack = this->GetViewReferenceStack( part); std::vector result; for (unsigned 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(); IStackableContainer::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) { Rectangle 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) { Rectangle 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) { Rectangle 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) { Rectangle 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 void* 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); } std::vector WorkbenchPage::GetAllParts() { std::vector views = viewFactory->GetViews(); std::list editors = this->GetEditorReferences(); std::vector result; for (unsigned int i = 0; i < views.size(); i++) { result.push_back(views[i]); } for (std::list::iterator iter = editors.begin(); iter != editors.end(); ++iter) { result.push_back(*iter); } return result; } std::vector WorkbenchPage::GetOpenParts() { std::vector refs = this->GetAllParts(); std::vector result; for (unsigned 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; // } /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getPerspectiveShortcuts() */ std::vector WorkbenchPage::GetPerspectiveShortcuts() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return std::vector(); } return persp->GetPerspectiveShortcuts(); } std::vector WorkbenchPage::GetShowViewShortcuts() { Perspective::Pointer persp = this->GetActivePerspective(); if (persp == 0) { return std::vector(); } 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 (MessageDialog::OpenQuestion(parentShell, "Reset Perspective?", "Changes to installed plug-ins have affected this perspective. Would you like to reset this perspective to accept these changes?")) { 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/src/internal/berryWorkbenchPage.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPage.h index 6427afd18f..0e4b3b48cb 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPage.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPage.h @@ -1,1787 +1,1787 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWORKBENCHPAGE_H_ #define BERRYWORKBENCHPAGE_H_ #include #include -#include "../berryIWorkbenchPage.h" -#include "../berryIWorkbenchPartReference.h" -#include "../berryIReusableEditor.h" +#include "berryIWorkbenchPage.h" +#include "berryIWorkbenchPartReference.h" +#include "berryIReusableEditor.h" #include "berryIStackableContainer.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 { //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 WorkbenchPage: public IWorkbenchPage { public: 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; IEditorPart::WeakPtr topEditor; /** * 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); /** * 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); }; 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). */ std::vector > GetEditors(); /* * Return a list with all parts (editors and views). */ std::vector > 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 std::list > 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; void* composite; //Could be delete. This information is in the active part list; ActivationList* activationList; EditorManager* editorMgr; EditorAreaHelper* editorPresentation; //ListenerList propertyChangeListeners = new ListenerList(); PageSelectionService* selectionService; WorkbenchPagePartList::Pointer partList; // = new WorkbenchPagePartList(selectionService); //IActionBars actionBars; ViewFactory* viewFactory; PerspectiveList perspList; SmartPointer deferredActivePersp; //NavigationHistory navigationHistory = new NavigationHistory(this); IStickyViewManager::Pointer stickyViewMan; /** * 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; // Deferral count... delays disposing parts and sending certain events if nonzero int deferCount; // Parts waiting to be disposed std::vector pendingDisposals; const IExtensionPoint* 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 std::string& 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::Pointer l); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void AddSelectionListener(ISelectionListener::Pointer listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void AddSelectionListener(const std::string& partId, ISelectionListener::Pointer listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void AddPostSelectionListener(ISelectionListener::Pointer listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void AddPostSelectionListener(const std::string& partId, ISelectionListener::Pointer listener); private: IStackableContainer::Pointer GetContainer(IWorkbenchPart::Pointer part); private: IStackableContainer::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); /** * Shows a view. * * Assumes that a busy cursor is active. */ protected: IViewPart::Pointer BusyShowView(const std::string& viewID, const std::string& secondaryID, int mode); /* * Performs showing of the view in the given mode. */ private: void BusyShowView(IViewPart::Pointer part, int mode); /** * Returns whether a part exists in the current page. */ private: bool CertifyPart(IWorkbenchPart::Pointer part); /** * Closes the perspective. */ public: bool Close(); /** * See IWorkbenchPage */ public: bool CloseAllSavedEditors(); /** * See IWorkbenchPage */ public: bool CloseAllEditors(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 std::list& 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(); /** * See IWorkbenchPage#closeEditor */ public: bool CloseEditor(IEditorReference::Pointer editorRef, bool save); /** * See IWorkbenchPage#closeEditor */ public: bool CloseEditor(IEditorPart::Pointer editor, bool save); /** * @see IWorkbenchPage#closePerspective(IPerspectiveDescriptor, boolean, boolean) */ public: void ClosePerspective(IPerspectiveDescriptor::Pointer desc, bool saveParts, bool closePage); /** * 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) */ public: void CloseAllPerspectives(bool saveEditors, bool closePage); /** * Creates the client composite. */ private: 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. */ public: void DetachView(IViewReference::Pointer ref); /** * Removes a detachedwindow. */ public: void AttachView(IViewReference::Pointer ref); /** * Dispose a perspective. * * @param persp the perspective descriptor * @param notify whether to fire a perspective closed event */ private: void DisposePerspective(SmartPointer persp, bool notify); /** * Returns the first view manager with given ID. */ public: SmartPointer FindPerspective(IPerspectiveDescriptor::Pointer desc); /** * See IWorkbenchPage@findView. */ public: IViewPart::Pointer FindView(const std::string& id); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage */ public: IViewReference::Pointer FindViewReference(const std::string& viewId); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage */ public: IViewReference::Pointer FindViewReference(const std::string& viewId, const std::string& 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: void* 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(); /** * See IWorkbenchPage. */ public: std::vector GetEditors(); public: std::vector GetDirtyEditors(); public: std::vector GetDirtyParts(); /** * See IWorkbenchPage. */ public: IEditorPart::Pointer FindEditor(IEditorInput::Pointer input); /** * See IWorkbenchPage. */ public: std::vector FindEditors( IEditorInput::Pointer input, const std::string& editorId, int matchFlags); /** * See IWorkbenchPage. */ public: std::list GetEditorReferences(); /** * @see IWorkbenchPage */ public: IAdaptable* GetInput(); /** * Returns the page label. This is a combination of the page input and * active perspective. */ public: std::string 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 std::string& partId); //public: // SelectionEvents& GetSelectionEvents(const std::string& partId = ""); /* * Returns the view factory. */ public: ViewFactory* GetViewFactory(); /** * See IWorkbenchPage. */ public: std::vector GetViewReferences(); /** * See IWorkbenchPage. */ public: std::vector GetViews(); /** * Returns all view parts in the specified perspective * * @param persp the perspective * @return an array of view parts * @since 3.1 */ /*package*/ protected: std::vector GetViews(SmartPointer persp, bool restore); /** * See IWorkbenchPage. */ public: IWorkbenchWindow::Pointer GetWorkbenchWindow(); /* * (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); /** * 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 std::string& 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(); /** * 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(); /** * See IWorkbenchPage. */ public: void ReuseEditor(IReusableEditor::Pointer editor, IEditorInput::Pointer input); /** * See IWorkbenchPage. */ public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const std::string& editorID); /** * See IWorkbenchPage. */ public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const std::string& editorID, bool activate); /** * See IWorkbenchPage. */ public: IEditorPart::Pointer OpenEditor(IEditorInput::Pointer input, const std::string& 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 std::string& 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); /** * @see #openEditor(IEditorInput, String, boolean, int) */ private: IEditorPart::Pointer BusyOpenEditor(IEditorInput::Pointer input, const std::string& 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 std::string& 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); /** * See IWorkbenchPage. */ public: bool IsEditorPinned(IEditorPart::Pointer editor); /** * Removes an IPartListener from the part service. */ public: void RemovePartListener(IPartListener::Pointer l); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void RemoveSelectionListener(ISelectionListener::Pointer listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void RemoveSelectionListener(const std::string& partId, ISelectionListener::Pointer listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void RemovePostSelectionListener(ISelectionListener::Pointer listener); /* * (non-Javadoc) Method declared on ISelectionListener. */ public: void RemovePostSelectionListener(const std::string& partId, ISelectionListener::Pointer 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: std::string GetId(IWorkbenchPart::Pointer part); private: std::string 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 std::string& viewID); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#showView(java.lang.String, * java.lang.String, int) */ public: IViewPart::Pointer ShowView(const std::string& viewID, const std::string& 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: std::vector GetSortedEditors(); /** * @see IWorkbenchPage#getOpenPerspectives() */ public: std::vector GetOpenPerspectives(); /** * Return all open Perspective objects. * * @return all open Perspective objects * @since 3.1 */ /*package*/ protected: std::list > 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); /** * Returns the perspectives in activation order (oldest first). */ public: std::vector GetSortedPerspectives(); /* * Returns the parts in activation order (oldest first). */ public: std::vector 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: std::vector GetViewReferenceStack( IViewPart::Pointer part); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getViewStack(org.blueberry.ui.IViewPart) */ public: std::vector 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); private: 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); /** * Returns all parts that are owned by this page * * @return */ protected: std::vector 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: std::vector 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: std::vector GetPerspectiveShortcuts(); /* * (non-Javadoc) * * @see org.blueberry.ui.IWorkbenchPage#getShowViewShortcuts() */ public: std::vector GetShowViewShortcuts(); /** * @since 3.1 */ private: void SuggestReset(); public: bool IsPartVisible(IWorkbenchPartReference::Pointer reference); }; } #endif /*BERRYWORKBENCHPAGE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPagePartList.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPagePartList.cpp index 74fd00d0d2..fcef2b429a 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPagePartList.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPagePartList.cpp @@ -1,98 +1,98 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWorkbenchPagePartList.h" #include "berryPartPane.h" -#include "../berryImageDescriptor.h" +#include "berryImageDescriptor.h" namespace berry { void WorkbenchPagePartList::FirePartOpened(IWorkbenchPartReference::Pointer part) { partService.FirePartOpened(part); } void WorkbenchPagePartList::FirePartClosed(IWorkbenchPartReference::Pointer part) { partService.FirePartClosed(part); } void WorkbenchPagePartList::FirePartAdded(IWorkbenchPartReference::Pointer /*part*/) { // TODO: There is no listener for workbench page additions yet } void WorkbenchPagePartList::FirePartRemoved( IWorkbenchPartReference::Pointer /*part*/) { // TODO: There is no listener for workbench page removals yet } void WorkbenchPagePartList::FireActiveEditorChanged( IWorkbenchPartReference::Pointer ref) { if (ref.IsNotNull()) { this->FirePartBroughtToTop(ref); } } void WorkbenchPagePartList::FireActivePartChanged( IWorkbenchPartReference::Pointer /*oldRef*/, IWorkbenchPartReference::Pointer newRef) { partService.SetActivePart(newRef); IWorkbenchPart::Pointer realPart = newRef == 0 ? IWorkbenchPart::Pointer(0) : newRef->GetPart(false); selectionService->SetActivePart(realPart); } void WorkbenchPagePartList::FirePartHidden(IWorkbenchPartReference::Pointer ref) { partService.FirePartHidden(ref); } void WorkbenchPagePartList::FirePartVisible(IWorkbenchPartReference::Pointer ref) { partService.FirePartVisible(ref); } void WorkbenchPagePartList::FirePartInputChanged( IWorkbenchPartReference::Pointer ref) { partService.FirePartInputChanged(ref); } WorkbenchPagePartList::WorkbenchPagePartList(PageSelectionService* selService) : selectionService(selService), partService("", "") { } IPartService* WorkbenchPagePartList::GetPartService() { return &partService; } void WorkbenchPagePartList::FirePartBroughtToTop( IWorkbenchPartReference::Pointer ref) { partService.FirePartBroughtToTop(ref); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPartReference.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPartReference.cpp index 00ff120527..e16d495f76 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPartReference.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPartReference.cpp @@ -1,717 +1,717 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWorkbenchPartReference.h" #include #include #include "berryWorkbenchPlugin.h" #include "berryUtil.h" #include "berryPartPane.h" -#include "../berryIWorkbenchPartSite.h" -#include "../berryIEditorPart.h" -#include "../berryIWorkbenchPartConstants.h" -#include "../berryImageDescriptor.h" +#include "berryIWorkbenchPartSite.h" +#include "berryIEditorPart.h" +#include "berryIWorkbenchPartConstants.h" +#include "berryImageDescriptor.h" namespace berry { int WorkbenchPartReference::STATE_LAZY = 0; int WorkbenchPartReference::STATE_CREATION_IN_PROGRESS = 1; int WorkbenchPartReference::STATE_CREATED = 2; int WorkbenchPartReference::STATE_DISPOSED = 3; WorkbenchPartReference::PropertyChangeListener::PropertyChangeListener( WorkbenchPartReference* ref) : partRef(ref) { } void WorkbenchPartReference::PropertyChangeListener::PropertyChange( PropertyChangeEvent::Pointer event) { if (event->GetProperty() == IWorkbenchPartConstants::INTEGER_PROPERTY) { partRef->PropertyChanged(event->GetSource(), event->GetNewValue().Cast()->GetValue()); } else { partRef->PropertyChanged(event); } } WorkbenchPartReference::WorkbenchPartReference() : state(STATE_LAZY), pinned(false), image(0) { propertyChangeListener = new PropertyChangeListener(this); } WorkbenchPartReference::~WorkbenchPartReference() { this->Register(); part = 0; pane = 0; this->UnRegister(false); } bool WorkbenchPartReference::IsDisposed() const { return state == STATE_DISPOSED; } void WorkbenchPartReference::CheckReference() { if (state == STATE_DISPOSED) { throw Poco::RuntimeException("Error: IWorkbenchPartReference disposed"); //$NON-NLS-1$ } } /** * Calling this with deferEvents(true) will queue all property change events until a subsequent * call to deferEvents(false). This should be used at the beginning of a batch of related changes * to prevent duplicate property change events from being sent. * * @param shouldQueue */ //void WorkbenchPartReference::DeferEvents(bool shouldQueue) { // queueEvents = shouldQueue; // // if (queueEvents == false) { // // do not use nextSetBit, to allow compilation against JCL Foundation (bug 80053) // for (int i = 0, n = queuedEvents.size(); i < n; ++i) { // if (queuedEvents.get(i)) { // firePropertyChange(i); // queuedEvents.clear(i); // } // } // } // } void WorkbenchPartReference::SetPartName(const std::string& newPartName) { if (partName == newPartName) { return; } partName = newPartName; this->FirePropertyChange(IWorkbenchPartConstants::PROP_PART_NAME); } void WorkbenchPartReference::SetContentDescription( const std::string& newContentDescription) { if (contentDescription == newContentDescription) { return; } contentDescription = newContentDescription; this->FirePropertyChange(IWorkbenchPartConstants::PROP_CONTENT_DESCRIPTION); } void WorkbenchPartReference::SetImageDescriptor( ImageDescriptor::Pointer descriptor) { if (imageDescriptor == descriptor) { return; } void* oldImage = image; ImageDescriptor::Pointer oldDescriptor = imageDescriptor; image = 0; imageDescriptor = descriptor; // Don't queue events triggered by image changes. We'll dispose the image // immediately after firing the event, so we need to fire it right away. this->ImmediateFirePropertyChange(IWorkbenchPartConstants::PROP_TITLE); if (queueEvents) { // If there's a PROP_TITLE event queued, remove it from the queue because // we've just fired it. queuedEvents.erase(IWorkbenchPartConstants::PROP_TITLE); } // If we had allocated the old image, deallocate it now (AFTER we fire the property change // -- listeners may need to clean up references to the old image) if (oldImage && oldDescriptor) { //JFaceResources.getResources().destroy(oldDescriptor); oldDescriptor->DestroyImage(oldImage); } } void WorkbenchPartReference::SetToolTip(const std::string& newToolTip) { if (tooltip == newToolTip) { return; } tooltip = newToolTip; this->FirePropertyChange(IWorkbenchPartConstants::PROP_TITLE); } void WorkbenchPartReference::PropertyChanged(Object::Pointer /*source*/, int propId) { // We handle these properties directly (some of them may be transformed // before firing events to workbench listeners) if (propId == IWorkbenchPartConstants::PROP_CONTENT_DESCRIPTION || propId == IWorkbenchPartConstants::PROP_PART_NAME || propId == IWorkbenchPartConstants::PROP_TITLE) { this->RefreshFromPart(); } else { // Any other properties are just reported to listeners verbatim this->FirePropertyChange(propId); } // Let the model manager know as well // if (propId == IWorkbenchPartConstants::PROP_DIRTY) { // IWorkbenchPart actualPart = getPart(false); // if (actualPart != null) { // SaveablesList modelManager = (SaveablesList) actualPart.getSite().getService(ISaveablesLifecycleListener.class); // modelManager.dirtyChanged(actualPart); // } // } } void WorkbenchPartReference::PropertyChanged(PropertyChangeEvent::Pointer event) { this->FirePropertyChange(event); } /** * Refreshes all cached values with the values from the real part */ void WorkbenchPartReference::RefreshFromPart() { this->DeferEvents(true); SetPartName(ComputePartName()); SetContentDescription(ComputeContentDescription()); SetToolTip(GetRawToolTip()); //SetImageDescriptor(ComputeImageDescriptor()); this->DeferEvents(false); } ImageDescriptor::Pointer WorkbenchPartReference::ComputeImageDescriptor() { if (part) { return ImageDescriptor::CreateFromImage(part->GetTitleImage()); } return defaultImageDescriptor; } void WorkbenchPartReference::Init(const std::string& id, const std::string& tooltip, ImageDescriptor::Pointer desc, const std::string& paneName, const std::string& contentDescription) { this->id = id; this->tooltip = tooltip; this->partName = paneName; this->contentDescription = contentDescription; this->defaultImageDescriptor = desc; this->imageDescriptor = this->ComputeImageDescriptor(); } /** * @see IWorkbenchPart */ void WorkbenchPartReference::AddPropertyListener( IPropertyChangeListener::Pointer listener) { propChangeEvents.AddListener(listener); } /** * @see IWorkbenchPart */ void WorkbenchPartReference::RemovePropertyListener( IPropertyChangeListener::Pointer listener) { propChangeEvents.RemoveListener(listener); } std::string WorkbenchPartReference::GetId() const { if (!part.IsNull()) { IWorkbenchPartSite::Pointer site = part->GetSite(); if (!site.IsNull()) { return site->GetId(); } } return id; } std::string WorkbenchPartReference::GetTitleToolTip() const { return tooltip; } std::string WorkbenchPartReference::GetRawToolTip() const { return part->GetTitleToolTip(); } /** * Returns the pane name for the part * * @return the pane name for the part */ std::string WorkbenchPartReference::GetPartName() const { return partName; } /** * Gets the part name directly from the associated workbench part, * or the empty string if none. * * @return */ std::string WorkbenchPartReference::GetRawPartName() const { return part->GetPartName(); } std::string WorkbenchPartReference::ComputePartName() const { return this->GetRawPartName(); } /** * Returns the content description for this part. * * @return the pane name for the part */ std::string WorkbenchPartReference::GetContentDescription() const { return contentDescription; } /** * Computes a new content description for the part. Subclasses may override to change the * default behavior * * @return the new content description for the part */ std::string WorkbenchPartReference::ComputeContentDescription() const { return this->GetRawContentDescription(); } /** * Returns the content description as set directly by the part, or the empty string if none * * @return the unmodified content description from the part (or the empty string if none) */ std::string WorkbenchPartReference::GetRawContentDescription() const { return part->GetContentDescription(); } bool WorkbenchPartReference::IsDirty() const { if (part.Cast ().IsNull()) { return false; } return part.Cast ()->IsDirty(); } void* WorkbenchPartReference::GetTitleImage() { if (this->IsDisposed()) { //return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_DEF_VIEW); return 0; } if (!image && imageDescriptor) { //image = JFaceResources.getResources().createImageWithDefault(imageDescriptor); image = imageDescriptor->CreateImage(); } return image; } ImageDescriptor::Pointer WorkbenchPartReference::GetTitleImageDescriptor() const { if (this->IsDisposed()) { //return PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_DEF_VIEW); return ImageDescriptor::Pointer(0); } return imageDescriptor; } void WorkbenchPartReference::FireVisibilityChange() { this->FirePropertyChange(IWorkbenchPartConstants::PROP_VISIBLE); } // /* package */ void fireZoomChange() { // fireInternalPropertyChange(INTERNAL_PROPERTY_ZOOMED); // } bool WorkbenchPartReference::GetVisible() { if (this->IsDisposed()) { return false; } return this->GetPane()->GetVisible(); } void WorkbenchPartReference::SetVisible(bool isVisible) { if (this->IsDisposed()) { return; } this->GetPane()->SetVisible(isVisible); } void WorkbenchPartReference::DeferEvents(bool shouldQueue) { queueEvents = shouldQueue; if (queueEvents == false) { std::set::iterator iter = queuedEvents.begin(); while (iter != queuedEvents.end()) { this->FirePropertyChange(*iter); queuedEvents.erase(iter++); } } } void WorkbenchPartReference::FirePropertyChange(int id) { if (queueEvents) { queuedEvents.insert(id); return; } this->ImmediateFirePropertyChange(id); } void WorkbenchPartReference::ImmediateFirePropertyChange(int id) { //UIListenerLogging.logPartReferencePropertyChange(this, id); ObjectInt::Pointer value(new ObjectInt(id)); Object::Pointer source(this); PropertyChangeEvent::Pointer event( new PropertyChangeEvent(source, IWorkbenchPartConstants::INTEGER_PROPERTY, value, value)); propChangeEvents.propertyChange(event); } IWorkbenchPart::Pointer WorkbenchPartReference::GetPart(bool restore) { if (this->IsDisposed()) { return IWorkbenchPart::Pointer(0); } if (part.IsNull() && restore) { if (state == STATE_CREATION_IN_PROGRESS) { // IStatus result = WorkbenchPlugin.getStatus( // new PartInitException(NLS.bind("Warning: Detected recursive attempt by part {0} to create itself (this is probably, but not necessarily, a bug)", //$NON-NLS-1$ // getId()))); WorkbenchPlugin::Log("Warning: Detected recursive attempt by part " + GetId() + " to create itself (this is probably, but not necessarily, a bug)"); return IWorkbenchPart::Pointer(0); } try { state = STATE_CREATION_IN_PROGRESS; IWorkbenchPart::Pointer newPart = this->CreatePart(); if (!newPart.IsNull()) { part = newPart; // Add a dispose listener to the part. This dispose listener does nothing but log an exception // if the part's widgets get disposed unexpectedly. The workbench part reference is the only // object that should dispose this control, and it will remove the listener before it does so. //this->GetPane().getControl().addDisposeListener(prematureDisposeListener); part->AddPropertyListener(propertyChangeListener); this->RefreshFromPart(); this->FirePropertyChange(IWorkbenchPartConstants::PROP_OPENED); //ISizeProvider sizeProvider = (ISizeProvider) Util.getAdapter(part, ISizeProvider.class); //if (sizeProvider != null) { // If this part has a preferred size, indicate that the preferred size may have changed at this point if (this->GetSizeFlags(true) != 0 || this->GetSizeFlags(false) != 0) { this->FirePropertyChange(IWorkbenchPartConstants::PROP_PREFERRED_SIZE); } //} } state = STATE_CREATED; } catch (Poco::Exception& e) { state = STATE_CREATED; std::cerr << e.displayText() << std::flush; throw e; } catch (std::exception& e) { state = STATE_CREATED; throw e; } } return part; } /** * Returns the part pane for this part reference. Does not return null. Should not be called * if the reference has been disposed. * * TODO: clean up all code that has any possibility of calling this on a disposed reference * and make this method throw an exception if anyone else attempts to do so. * * @return */ PartPane::Pointer WorkbenchPartReference::GetPane() { // Note: we should never call this if the reference has already been disposed, since it // may cause a PartPane to be created and leaked. if (pane.IsNull()) { pane = this->CreatePane(); } return pane; } void WorkbenchPartReference::Dispose() { if (this->IsDisposed()) { return; } // Store the current title, tooltip, etc. so that anyone that they can be returned to // anyone that held on to the disposed reference. partName = GetPartName(); contentDescription = GetContentDescription(); tooltip = GetTitleToolTip(); if (state == STATE_CREATION_IN_PROGRESS) { // IStatus result = WorkbenchPlugin.getStatus( // new PartInitException(NLS.bind("Warning: Blocked recursive attempt by part {0} to dispose itself during creation", //$NON-NLS-1$ // getId()))); WorkbenchPlugin::Log("Warning: Blocked recursive attempt by part" + GetId() + " to dispose itself during creation"); return; } // Disposing the pane disposes the part's widgets. The part's widgets need to be disposed before the part itself. // if (pane != 0) { // // Remove the dispose listener since this is the correct place for the widgets to get disposed // Control targetControl = getPane().getControl(); // if (targetControl != null) { // targetControl.removeDisposeListener(prematureDisposeListener); // } // pane->Dispose(); // } this->DoDisposePart(); if (!pane.IsNull()) { //pane.removeContributions(); } //clearListenerList(internalPropChangeListeners); //clearListenerList(partChangeListeners); void* oldImage = image; ImageDescriptor::Pointer oldDescriptor = imageDescriptor; image = 0; state = STATE_DISPOSED; imageDescriptor = ImageDescriptor::GetMissingImageDescriptor(); defaultImageDescriptor = ImageDescriptor::GetMissingImageDescriptor(); this->ImmediateFirePropertyChange(IWorkbenchPartConstants::PROP_TITLE); //clearListenerList(propChangeListeners); if (oldImage) { //JFaceResources.getResources().destroy(oldDescriptor); oldDescriptor->DestroyImage(oldImage); } pane = 0; } void WorkbenchPartReference::DoDisposePart() { if (part) { //this->FireInternalPropertyChange(INTERNAL_PROPERTY_CLOSED); this->FirePropertyChange(IWorkbenchPartConstants::PROP_CLOSED); // Don't let exceptions in client code bring us down. Log them and continue. try { part->RemovePropertyListener(propertyChangeListener); // if (part instanceof IWorkbenchPart3) // { // ((IWorkbenchPart3) part).removePartPropertyListener( // partPropertyChangeListener); // } // part->Dispose(); part = 0; } catch (const Poco::RuntimeException& e) { WorkbenchPlugin::Log(e); } catch (const std::exception& e) { std::string msg("Exception in WorkbenchPartReference::DoDisposePart: "); msg.append(e.what()); WorkbenchPlugin::Log(msg); } part = 0; } } /** * Clears all of the listeners in a listener list. TODO Bug 117519 Remove * this method when fixed. * * @param list * The list to be clear; must not be null. */ //private: void clearListenerList(const ListenerList list) { // final Object[] listeners = list.getListeners(); // for (int i = 0; i < listeners.length; i++) { // list.remove(listeners[i]); // } // } void WorkbenchPartReference::SetPinned(bool newPinned) { if (IsDisposed()) { return; } if (newPinned == pinned) { return; } pinned = newPinned; //SetImageDescriptor(computeImageDescriptor()); this->FirePropertyChange(IWorkbenchPartConstants::PROP_PINNED); } bool WorkbenchPartReference::IsPinned() const { return pinned; } std::string WorkbenchPartReference::GetPartProperty(const std::string& key) const { if (part != 0) { return part->GetPartProperty(key); } else { std::map::const_iterator itr = propertyCache.find(key); if (itr == propertyCache.end()) return ""; return itr->second; } } void WorkbenchPartReference::FirePropertyChange( PropertyChangeEvent::Pointer event) { propChangeEvents.propertyChange(event); } void WorkbenchPartReference::CreatePartProperties( IWorkbenchPart::Pointer workbenchPart) { for (std::map::iterator iter = propertyCache.begin(); iter != propertyCache.end(); ++iter) { workbenchPart->SetPartProperty(iter->first, iter->second); } } int WorkbenchPartReference::ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredResult) { ISizeProvider* sizeProvider = Util::GetAdapter(part); if (sizeProvider) { return sizeProvider->ComputePreferredSize(width, availableParallel, availablePerpendicular, preferredResult); } return preferredResult; } int WorkbenchPartReference::GetSizeFlags(bool width) { ISizeProvider* sizeProvider = Util::GetAdapter(part); if (sizeProvider) { return sizeProvider->GetSizeFlags(width); } return 0; } } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPartReference.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPartReference.h index 617a13b0db..18fda8aa85 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPartReference.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPartReference.h @@ -1,304 +1,304 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWORKBENCHPARTREFERENCE_H_ #define BERRYWORKBENCHPARTREFERENCE_H_ #include -#include "../berryISizeProvider.h" -#include "../berryIWorkbenchPartReference.h" -#include "../berryIWorkbenchPart.h" +#include "berryISizeProvider.h" +#include "berryIWorkbenchPartReference.h" +#include "berryIWorkbenchPart.h" #include //TODO should be removed #include -#include "../berryImageDescriptor.h" +#include "berryImageDescriptor.h" namespace berry { class PartPane; /** * \ingroup org_blueberry_ui_internal * */ class BERRY_UI WorkbenchPartReference : virtual public IWorkbenchPartReference, public ISizeProvider { public: berryObjectMacro(WorkbenchPartReference); // State constants ////////////////////////////// /** * State constant indicating that the part is not created yet */ public: static int STATE_LAZY; // = 0 /** * State constant indicating that the part is in the process of being created */ public: static int STATE_CREATION_IN_PROGRESS; // = 1 /** * State constant indicating that the part has been created */ public: static int STATE_CREATED; // = 2 /** * State constant indicating that the reference has been disposed (the reference shouldn't be * used anymore) */ public: static int STATE_DISPOSED; // = 3 /** * Current state of the reference. Used to detect recursive creation errors, disposed * references, etc. */ private: int state; protected: IWorkbenchPart::Pointer part; protected: SmartPointer pane; private: std::string id; private: bool pinned; private: std::string tooltip; /** * Stores the current Image for this part reference. Lazily created. Null if not allocated. */ private: void* image; private: SmartPointer defaultImageDescriptor; /** * Stores the current image descriptor for the part. */ private: SmartPointer imageDescriptor; /** * API listener list */ private: IPropertyChangeListener::Events propChangeEvents; //private: ListenerList partChangeListeners = new ListenerList(); private: std::string partName; private: std::string contentDescription; protected: std::map propertyCache; /** * Used to remember which events have been queued. */ private: std::set queuedEvents; private: bool queueEvents; //private: static DisposeListener prematureDisposeListener = new DisposeListener() { // public void widgetDisposed(DisposeEvent e) { // WorkbenchPlugin.log(new RuntimeException("Widget disposed too early!")); //$NON-NLS-1$ // } // }; private: struct PropertyChangeListener : public IPropertyChangeListener { PropertyChangeListener(WorkbenchPartReference* ref); void PropertyChange(PropertyChangeEvent::Pointer event); private: WorkbenchPartReference* partRef; }; private: IPropertyChangeListener::Pointer propertyChangeListener; /** * Calling this with deferEvents(true) will queue all property change events until a subsequent * call to deferEvents(false). This should be used at the beginning of a batch of related changes * to prevent duplicate property change events from being sent. * * @param shouldQueue */ private: void DeferEvents(bool shouldQueue); public: WorkbenchPartReference(); public: ~WorkbenchPartReference(); public: virtual bool IsDisposed() const; protected: virtual void CheckReference(); /** * Calling this with deferEvents(true) will queue all property change events until a subsequent * call to deferEvents(false). This should be used at the beginning of a batch of related changes * to prevent duplicate property change events from being sent. * * @param shouldQueue */ //private: virtual void DeferEvents(bool shouldQueue); protected: virtual void SetPartName(const std::string& newPartName); protected: virtual void SetContentDescription(const std::string& newContentDescription); protected: virtual void SetImageDescriptor(SmartPointer descriptor); protected: virtual void SetToolTip(const std::string& newToolTip); protected: virtual void PropertyChanged(Object::Pointer source, int propId); protected: virtual void PropertyChanged(PropertyChangeEvent::Pointer event); /** * Refreshes all cached values with the values from the real part */ protected: virtual void RefreshFromPart(); protected: virtual SmartPointer ComputeImageDescriptor(); public: virtual void Init(const std::string& id, const std::string& tooltip, SmartPointer desc, const std::string& paneName, const std::string& contentDescription); /** * @see IWorkbenchPart */ public: virtual void AddPropertyListener(IPropertyChangeListener::Pointer listener); /** * @see IWorkbenchPart */ public: virtual void RemovePropertyListener(IPropertyChangeListener::Pointer listener); public: std::string GetId() const; public: virtual std::string GetTitleToolTip() const; protected: std::string GetRawToolTip() const; /** * Returns the pane name for the part * * @return the pane name for the part */ public: virtual std::string GetPartName() const; /** * Gets the part name directly from the associated workbench part, * or the empty string if none. * * @return */ protected: std::string GetRawPartName() const; protected: virtual std::string ComputePartName() const; /** * Returns the content description for this part. * * @return the pane name for the part */ public: virtual std::string GetContentDescription() const; /** * Computes a new content description for the part. Subclasses may override to change the * default behavior * * @return the new content description for the part */ protected: virtual std::string ComputeContentDescription() const; /** * Returns the content description as set directly by the part, or the empty string if none * * @return the unmodified content description from the part (or the empty string if none) */ protected: std::string GetRawContentDescription() const; public: virtual bool IsDirty() const; public: virtual void* GetTitleImage(); public: virtual SmartPointer GetTitleImageDescriptor() const; public: virtual void FireVisibilityChange(); // /* package */ virtual void fireZoomChange(); public: virtual bool GetVisible(); public: virtual void SetVisible(bool isVisible); protected: virtual void FirePropertyChange(int id); private: void ImmediateFirePropertyChange(int id); public: IWorkbenchPart::Pointer GetPart(bool restore); protected: virtual IWorkbenchPart::Pointer CreatePart() = 0; protected: virtual SmartPointer CreatePane() = 0; /** * Returns the part pane for this part reference. Does not return null. * * @return */ public: SmartPointer GetPane(); public: void Dispose(); /** * Clears all of the listeners in a listener list. TODO Bug 117519 Remove * this method when fixed. * * @param list * The list to be clear; must not be null. */ //private: void clearListenerList(const ListenerList list); public: virtual void SetPinned(bool newPinned); public: virtual bool IsPinned() const; protected: void DoDisposePart(); /* (non-Javadoc) * @see org.blueberry.ui.IWorkbenchPartReference#getPartProperty(java.lang.String) */ public: virtual std::string GetPartProperty(const std::string& key) const; protected: virtual void FirePropertyChange(PropertyChangeEvent::Pointer event); protected: virtual void CreatePartProperties(IWorkbenchPart::Pointer workbenchPart); public: int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredResult); public: int GetSizeFlags(bool width); }; } // namespace berry #endif /*BERRYWORKBENCHPARTREFERENCE_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPlugin.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPlugin.cpp index 5152a9ee1e..b02e5b25a6 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPlugin.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPlugin.cpp @@ -1,330 +1,330 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryLog.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchRegistryConstants.h" #include "berryWorkbench.h" #include "berryPlatform.h" #include "intro/berryEditorIntroAdapterPart.h" -#include "../berryImageDescriptor.h" +#include "berryImageDescriptor.h" #include #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 editorRegistry; delete viewRegistry; delete perspRegistry; delete introRegistry; } bool WorkbenchPlugin::HasExecutableExtension( IConfigurationElement::Pointer element, const std::string& extensionName) { std::string attr; if (element->GetAttribute(extensionName, attr)) return true; std::string elementText(element->GetValue()); if (elementText != "") return true; IConfigurationElement::vector children(element->GetChildren(extensionName)); if (children.size() == 1) { if (children[0]->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS, attr)) return true; } return false; } bool WorkbenchPlugin::IsBundleLoadedForExecutableExtension( IConfigurationElement::Pointer element, const std::string& extensionName) { IBundle::Pointer bundle(WorkbenchPlugin::GetBundleForExecutableExtension(element, extensionName)); if (bundle.IsNull()) return true; return bundle->GetState() == IBundle::BUNDLE_ACTIVE; } IBundle::Pointer WorkbenchPlugin::GetBundleForExecutableExtension( IConfigurationElement::Pointer element, const std::string& extensionName) { // this code is derived heavily from // ConfigurationElement.createExecutableExtension. std::string prop; std::string executable; std::string contributorName; std::string::size_type i; if (extensionName != "") element->GetAttribute(extensionName, prop); else { // property not specified, try as element value prop = element->GetValue(); if (prop != "") { Poco::trimInPlace(prop); } } if (prop == "") { // property not defined, try as a child element IConfigurationElement::vector exec(element->GetChildren(extensionName)); if (exec.size() != 0) exec[0]->GetAttribute("plugin", contributorName); //$NON-NLS-1$ } else { // simple property or element value, parse it into its components i = prop.find_first_of(':'); if (i != std::string::npos) executable = Poco::trim(prop.substr(0, i)); else executable = prop; i = executable.find_first_of('/'); if (i != std::string::npos) contributorName = Poco::trim(executable.substr(0, i)); } if (contributorName == "") contributorName = element->GetContributor(); return Platform::GetBundle(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) { 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(); // } //}); } 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; } IPresentationFactory* WorkbenchPlugin::GetPresentationFactory() { if (presentationFactory != 0) return presentationFactory; std::string targetID = Workbench::GetInstance()->GetPresentationId(); presentationFactory = this->CreateExtension( WorkbenchRegistryConstants::PL_PRESENTATION_FACTORIES, "factory", targetID); if (presentationFactory == 0) WorkbenchPlugin::Log("Error creating presentation factory: " + targetID + " -- class is not an IPresentationFactory"); return presentationFactory; } void WorkbenchPlugin::Log(const std::string& message) { BERRY_INFO << "LOG: " << message << std::endl; //inst->GetLog().log(message); } void WorkbenchPlugin::Log(const Poco::RuntimeException& exc) { BERRY_INFO << "LOG: " << exc.message() << std::endl; //inst->GetLog().log(exc); } void WorkbenchPlugin::Log(const std::string& message, const Poco::RuntimeException& t) { PlatformException exc(message, t); WorkbenchPlugin::Log(exc); } void WorkbenchPlugin::Log(const std::string& clazz, const std::string& methodName, const Poco::RuntimeException& t) { std::string msg = "Exception in " + clazz + "." + methodName + ": " + t.what(); WorkbenchPlugin::Log(msg, t); } void WorkbenchPlugin::start(ctkPluginContext* context) { //context.addBundleListener(getBundleListener()); AbstractUICTKPlugin::start(context); bundleContext = context; BERRY_REGISTER_EXTENSION_CLASS(EditorIntroAdapterPart, context) // 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 std::vector WorkbenchPlugin::GetBundles() //{ // return bundleContext.IsNull() ? std::vector() : bundleContext->GetBundles(); //} ctkPluginContext* WorkbenchPlugin::GetPluginContext() { return bundleContext; } void WorkbenchPlugin::stop(ctkPluginContext* context) { AbstractUICTKPlugin::stop(context); delete perspRegistry; } bool WorkbenchPlugin::GetDataPath(Poco::Path& path) { QFileInfo fileInfo = bundleContext->getDataFile(""); path.assign(fileInfo.absolutePath().toStdString() + '/'); return fileInfo.isWritable(); } } Q_EXPORT_PLUGIN2(org_blueberry_ui, berry::WorkbenchPlugin) diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPlugin.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPlugin.h index ebc31f9d03..a7124869a1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPlugin.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchPlugin.h @@ -1,475 +1,475 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWORKBENCHPLUGIN_H_ #define BERRYWORKBENCHPLUGIN_H_ #include #include #include #include -#include "../berryAbstractUICTKPlugin.h" -#include "../berryPlatformUI.h" -#include "../presentations/berryIPresentationFactory.h" +#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 { /** * \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 QObject, public AbstractUICTKPlugin { Q_OBJECT Q_INTERFACES(ctkPluginActivator) private: //static const std::string 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; 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 std::string& 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 * @since 3.3 */ static bool HasExecutableExtension(IConfigurationElement::Pointer element, const std::string& 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. * @since 3.3 */ static bool IsBundleLoadedForExecutableExtension( IConfigurationElement::Pointer element, const std::string& 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. * @since 3.3 */ static IBundle::Pointer GetBundleForExecutableExtension(IConfigurationElement::Pointer element, const std::string& 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(); /** * Returns the presentation factory with the given id, or null 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 std::string extensionPointId, const std::string& elementName, const std::string& targetID) { const IExtensionPoint* extensionPoint = Platform::GetExtensionPointService() ->GetExtensionPoint("" + PlatformUI::PLUGIN_ID + "." + extensionPointId); if (extensionPoint == 0) { WorkbenchPlugin ::Log("Unable to find extension. Extension point: " + extensionPointId + " not found"); //$NON-NLS-1$ //$NON-NLS-2$ return 0; } // Loop through the config elements. IConfigurationElement::Pointer targetElement(0); IConfigurationElement::vector elements(Platform::GetExtensionPointService() ->GetConfigurationElementsFor("" + PlatformUI::PLUGIN_ID + "." + extensionPointId)); for (unsigned int j = 0; j < elements.size(); j++) { if (elementName == "" || elementName == elements[j]->GetName()) { std::string strID; elements[j]->GetAttribute("id", strID); 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 //$NON-NLS-1$ + " in extension point: " + extensionPointId); //$NON-NLS-1$ return 0; } // Create the extension. try { C* impl = targetElement->CreateExecutableExtension("class"); //$NON-NLS-1$ if (impl == 0) { // support legacy BlueBerry extensions impl = targetElement->CreateExecutableExtension("class", C::GetManifestName()); } return impl; } catch (CoreException e) { // log it since we cannot safely display a dialog. WorkbenchPlugin::Log("Unable to create extension: " + targetID //$NON-NLS-1$ + " in extension point: " + extensionPointId); //$NON-NLS-1$ } return 0; } public: /** * Return the perspective registry. * @return IPerspectiveRegistry. The registry for the receiver. */ IPerspectiveRegistry* GetPerspectiveRegistry(); /** * Returns the introduction registry. * * @return the introduction registry. * @since 3.0 */ 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 std::string& message); /** * Log the throwable. * @param t */ static void Log(const Poco::RuntimeException& 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 std::string& message, const Poco::RuntimeException& 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 std::string& clazz, const std::string& methodName, const Poco::RuntimeException& t); /* * (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 * @since 3.0 */ //const std::vector GetBundles(); /** * Returns the bundle context associated with the workbench plug-in. * * @return the bundle context * @since 3.1 */ 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. * @since 3.1 */ bool GetDataPath(Poco::Path& path); }; } #endif /*BERRYWORKBENCHPLUGIN_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchRegistryConstants.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchRegistryConstants.cpp index 68f9f506ad..696115ed41 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchRegistryConstants.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchRegistryConstants.cpp @@ -1,566 +1,566 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWorkbenchRegistryConstants.h" -#include "../berryPlatformUI.h" +#include "berryPlatformUI.h" namespace berry { const std::string WorkbenchRegistryConstants::ATT_ACCELERATOR = "accelerator"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_ADAPTABLE = "adaptable"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_ADVISORID = "triggerPointAdvisorId"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_ALLOW_LABEL_UPDATE = "allowLabelUpdate";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_ALLOW_MULTIPLE = "allowMultiple"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_RESTORABLE = "restorable"; const std::string WorkbenchRegistryConstants::ATT_CAN_FINISH_EARLY = "canFinishEarly"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_CATEGORY = "category"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_CATEGORY_ID = "categoryId"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_CLASS = "class"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_CLOSEABLE = "closeable"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_COLORFACTORY = "colorFactory"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_COMMAND = "command";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_COMMAND_ID = "commandId"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_CONFIGURATION = "configuration"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_CONTENT_DETECTOR = "contentDetector"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_CONTENT_TYPE_ID = "contentTypeId"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_CONTEXT_ID = "contextId"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_CONTRIBUTOR_CLASS = "contributorClass"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_CONVERTER = "converter"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_DEFAULT = "default";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_DEFAULT_HANDLER = "defaultHandler"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_DEFAULTS_TO = "defaultsTo"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_DEFINITION_ID = "definitionId";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_DESCRIPTION = "description"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_DESCRIPTION_IMAGE = "descriptionImage"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_DISABLEDICON = "disabledIcon";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_ENABLES_FOR = "enablesFor"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_EXTENSIONS = "extensions";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_FAST_VIEW_WIDTH_RATIO = "fastViewWidthRatio"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_FILENAMES = "filenames";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_FILL_MAJOR = "fillMajor";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_FILL_MINOR = "fillMinor";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_FIXED = "fixed";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_HAS_PAGES = "hasPages"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_HELP_CONTEXT_ID = "helpContextId";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_HELP_HREF = "helpHref"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_HOVERICON = "hoverIcon";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_ICON = "icon"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_ID = "id"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_IMAGE_STYLE = "imageStyle"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_IS_EDITABLE = "isEditable"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_KEY = "key"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_KEY_CONFIGURATION_ID = "keyConfigurationId"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_KEY_SEQUENCE = "keySequence"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_LABEL = "label"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_LAUNCHER = "launcher";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_LIGHTWEIGHT = "lightweight"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_LOCALE = "locale"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_LOCATION = "location"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_MATCHING_STRATEGY = "matchingStrategy"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_MENU_ID = "menuId"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_MENUBAR_PATH = "menubarPath";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_MNEMONIC = "mnemonic"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_MINIMIZED = "minimized"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_MOVEABLE = "moveable"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_NAME = "name"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_NAME_FILTER = "nameFilter"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_NODE = "node"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_OBJECTCLASS = "objectClass";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_OPTIONAL = "optional"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_OS = "os"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_PARENT = "parent"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_PARENT_CATEGORY = "parentCategory"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_PARENT_ID = "parentId"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_PARENT_SCOPE = "parentScope"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_PATH = "path"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_PLATFORM = "platform"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_POSITION = "position"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_PRESENTATIONID = "presentationId"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_PRODUCTID = "productId"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_PROJECT = "project";//$NON-NLS-1$ /** const std::string WorkbenchRegistryConstants::ATT_PULLDOWN = "pulldown"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_RATIO = "ratio"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_RELATIONSHIP = "relationship";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_RELATIVE = "relative";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_RELATIVE_TO = "relativeTo"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_RETARGET = "retarget";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_RETURN_TYPE_ID = "returnTypeId"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_ROLE = "role"; const std::string WorkbenchRegistryConstants::ATT_SCHEME_ID = "schemeId"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_SCOPE = "scope"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_SEPARATORS_VISIBLE = "separatorsVisible"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_SEQUENCE = "sequence"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_SHOW_TITLE = "showTitle";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_SINGLETON = "singleton";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_SPLASH_ID = "splashId"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_STANDALONE = "standalone";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_STATE = "state";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_STRING = "string"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_STYLE = "style";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_TARGET_ID = "targetID";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_TOOLBAR_PATH = "toolbarPath";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_TOOLTIP = "tooltip";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_TYPE = "type"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_TYPE_ID = "typeId"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_VALUE = "value"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_VISIBLE = "visible";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_WS = "ws"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::AUTOGENERATED_PREFIX = "AUTOGEN:::"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_ACCELERATOR_CONFIGURATIONS = "acceleratorConfigurations"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_ACCELERATOR_SCOPES = "acceleratorScopes"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_ACTION_DEFINITIONS = "actionDefinitions"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_ACTION_SET_PART_ASSOCIATIONS = "actionSetPartAssociations"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_ACTION_SETS = "actionSets"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_ACTIVITIES = "activities"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_ACTIVITYSUPPORT = "activitySupport"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_BINDINGS = "bindings"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_BROWSER_SUPPORT = "browserSupport"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_COLOR_DEFINITIONS = "colorDefinitions"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_COMMAND_IMAGES = "commandImages"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_COMMANDS = "commands"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_CONTEXTS = "contexts"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_DECORATORS = "decorators"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_DROP_ACTIONS = "dropActions"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_EDITOR = "editors"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_EDITOR_ACTIONS = "editorActions"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_ELEMENT_FACTORY = "elementFactories"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_ENCODINGS = "encodings"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_EXPORT = "exportWizards"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_FONT_DEFINITIONS = "fontDefinitions"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_HANDLERS = "handlers"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_HELPSUPPORT = "helpSupport"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_IMPORT = "importWizards"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_INTRO = "intro"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_KEYWORDS = "keywords"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_MENUS = "menus"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_MENU_CONTRIBUTION = "menuContribution"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_NEW = "newWizards"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_PERSPECTIVE_EXTENSIONS = "perspectiveExtensions"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_PERSPECTIVES = "perspectives"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_POPUP_MENU = "popupMenus"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_PREFERENCE_TRANSFER = "preferenceTransfer"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_PREFERENCES = "preferencePages"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_PRESENTATION_FACTORIES = "presentationFactories"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_PROPERTY_PAGES = "propertyPages"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_STARTUP = "startup"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_SPLASH_HANDLERS = "splashHandlers"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_SYSTEM_SUMMARY_SECTIONS = "systemSummarySections"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_THEMES = "themes"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_VIEW_ACTIONS = "viewActions"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_VIEWS = "views"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::PL_WORKINGSETS = "workingSets"; //$NON-NLS-1$ // const std::string WorkbenchRegistryConstants::EXTENSION_ACCELERATOR_CONFIGURATIONS = PlatformUI::PLUGIN_ID // + '.' + PL_ACCELERATOR_CONFIGURATIONS; // // const std::string WorkbenchRegistryConstants::EXTENSION_ACCELERATOR_SCOPES = PlatformUI::PLUGIN_ID // + '.' + PL_ACCELERATOR_SCOPES; // // const std::string WorkbenchRegistryConstants::EXTENSION_ACTION_DEFINITIONS = PlatformUI::PLUGIN_ID // + '.' + PL_ACTION_DEFINITIONS; // // const std::string WorkbenchRegistryConstants::EXTENSION_ACTION_SETS = PlatformUI::PLUGIN_ID // + '.' + WorkbenchRegistryConstants::PL_ACTION_SETS; // // const std::string WorkbenchRegistryConstants::EXTENSION_BINDINGS = PlatformUI::PLUGIN_ID + '.' // + PL_BINDINGS; // // const std::string WorkbenchRegistryConstants::EXTENSION_COMMAND_IMAGES = PlatformUI::PLUGIN_ID // + '.' + PL_COMMAND_IMAGES; // // const std::string WorkbenchRegistryConstants::EXTENSION_COMMANDS = PlatformUI::PLUGIN_ID + '.' // + PL_COMMANDS; // // const std::string WorkbenchRegistryConstants::EXTENSION_CONTEXTS = PlatformUI::PLUGIN_ID + '.' // + PL_CONTEXTS; // // const std::string WorkbenchRegistryConstants::EXTENSION_EDITOR_ACTIONS = PlatformUI::PLUGIN_ID // + '.' + PL_EDITOR_ACTIONS; // // const std::string WorkbenchRegistryConstants::EXTENSION_HANDLERS = PlatformUI::PLUGIN_ID + '.' // + PL_HANDLERS; // // const std::string WorkbenchRegistryConstants::EXTENSION_MENUS = PlatformUI::PLUGIN_ID + '.' // + PL_MENUS; // // const std::string WorkbenchRegistryConstants::COMMON_MENU_ADDITIONS = PlatformUI::PLUGIN_ID + '.' // + PL_MENUS + '2'; // // const std::string WorkbenchRegistryConstants::EXTENSION_POPUP_MENUS = PlatformUI::PLUGIN_ID // + '.' + PL_POPUP_MENU; // // const std::string WorkbenchRegistryConstants::EXTENSION_VIEW_ACTIONS = PlatformUI::PLUGIN_ID // + '.' + PL_VIEW_ACTIONS; const std::string WorkbenchRegistryConstants::POSITION_AFTER = "after"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::POSITION_BEFORE = "before"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::POSITION_END = "end"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::POSITION_START = "start"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::STYLE_PULLDOWN = "pulldown"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::STYLE_RADIO = "radio"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::STYLE_TOGGLE = "toggle"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_ACCELERATOR_CONFIGURATION = "acceleratorConfiguration"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_ACCELERATOR_SCOPE = "acceleratorScope"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_ACTION = "action"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_ACTION_DEFINITION = "actionDefinition"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_ACTION_SET = "actionSet";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_ACTION_SET_PART_ASSOCIATION = "actionSetPartAssociation";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_ACTIVE_KEY_CONFIGURATION = "activeKeyConfiguration"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_ACTIVE_WHEN = "activeWhen"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_ACTIVITY_IMAGE_BINDING = "activityImageBinding"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_ADVISORPRODUCTBINDING = "triggerPointAdvisorProductBinding"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_BAR = "bar"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_CATEGORY = "category";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_CATEGORY_IMAGE_BINDING = "categoryImageBinding"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_CATEGORYDEFINITION = "themeElementCategory"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_CATEGORYPRESENTATIONBINDING = "categoryPresentationBinding"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_CLASS = ATT_CLASS; const std::string WorkbenchRegistryConstants::TAG_COLORDEFINITION = "colorDefinition"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_COLOROVERRIDE = "colorOverride"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_COLORVALUE = "colorValue"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_COMMAND = "command"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_COMMAND_PARAMETER = "commandParameter"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_COMMAND_PARAMETER_TYPE = "commandParameterType"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_CONTENT_TYPE_BINDING = "contentTypeBinding"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_CONTEXT = "context"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_DATA = "data"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_DEFAULT_HANDLER = ATT_DEFAULT_HANDLER; const std::string WorkbenchRegistryConstants::TAG_DESCRIPTION = "description"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_DYNAMIC = "dynamic"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_EDITOR = "editor";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_EDITOR_CONTRIBUTION = "editorContribution"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_ENABLED_WHEN = "enabledWhen"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_ENABLEMENT = "enablement"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_ENTRY = "entry"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_FILTER = "filter"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_FONTDEFINITION = "fontDefinition"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_FONTOVERRIDE = "fontOverride"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_FONTVALUE = "fontValue"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_GROUP = "group"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_GROUP_MARKER = "groupMarker"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_HANDLER = "handler"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_HANDLER_SUBMISSION = "handlerSubmission"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_HINT = "hint"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_IMAGE = "image"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_KEY = "key"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_KEY_BINDING = "keyBinding"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_KEY_CONFIGURATION = "keyConfiguration"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_LOCATION = "location"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_LOCATION_URI = "locationURI"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_LAYOUT = "layout"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_MAPPING = "mapping"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_MENU = "menu"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_NEW_WIZARD_SHORTCUT = "newWizardShortcut";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_OBJECT_CONTRIBUTION = "objectContribution";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_ORDER = "order"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_PARAMETER = "parameter"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_PART = "part";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_PERSP_SHORTCUT = "perspectiveShortcut";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_PERSPECTIVE = "perspective";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_PERSPECTIVE_EXTENSION = "perspectiveExtension";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_PRIMARYWIZARD = "primaryWizard"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_REFERENCE = "reference"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_SCHEME = "scheme"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_SCOPE = "scope"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_SELECTION = "selection"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_SEPARATOR = "separator"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_SETTINGS_TRANSFER = "settingsTransfer"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_SHOW_IN_PART = "showInPart";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_STATE = "state"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_SPLASH_HANDLER = "splashHandler"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_SPLASH_HANDLER_PRODUCT_BINDING = "splashHandlerProductBinding"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_STICKYVIEW = "stickyView";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_SUPPORT = "support"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_THEME = "theme";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_TRANSFER = "transfer";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_TRIGGERPOINT = "triggerPoint"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_TRIGGERPOINTADVISOR = "triggerPointAdvisor"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_VIEW = "view";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_VIEW_SHORTCUT = "viewShortcut";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_VIEW_CONTRIBUTION = "viewContribution"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_VIEWER_CONTRIBUTION = "viewerContribution"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_VISIBILITY = "visibility"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_VISIBLE_WHEN = "visibleWhen"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_WIDGET = "widget"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_CONTROL = "control"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_WIZARD = "wizard";//$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_WORKING_SET = "workingSet"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TYPE_GROUP = "group"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TYPE_ITEM = "item"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TYPE_MENU = "menu"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TYPE_WIDGET = "widget"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_TOOLBAR = "toolbar"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_SERVICE_FACTORY = "serviceFactory"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_SERVICE = "service"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATTR_FACTORY_CLASS = "factoryClass"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATTR_SERVICE_CLASS = "serviceClass"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_SOURCE_PROVIDER = "sourceProvider"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATTR_PROVIDER = "provider"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::TAG_VARIABLE = "variable"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_PRIORITY_LEVEL = "priorityLevel"; //$NON-NLS-1$ const std::string WorkbenchRegistryConstants::ATT_MODE = "mode"; } // namespace berry diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchServiceRegistry.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchServiceRegistry.cpp index 936a29cc8d..ee40b45400 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchServiceRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchServiceRegistry.cpp @@ -1,266 +1,266 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryLog.h" #include "berryWorkbenchServiceRegistry.h" -#include "../berryISources.h" -#include "../berryISourceProvider.h" -#include "../berryPlatformUI.h" -#include "../berryImageDescriptor.h" +#include "berryISources.h" +#include "berryISourceProvider.h" +#include "berryPlatformUI.h" +#include "berryImageDescriptor.h" -#include "../services/berryIServiceFactory.h" +#include "services/berryIServiceFactory.h" #include "berryServiceLocator.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchRegistryConstants.h" #include "berrySourcePriorityNameMapping.h" #include namespace berry { const std::string WorkbenchServiceRegistry::WORKBENCH_LEVEL = "workbench"; //$NON-NLS-1$ const std::string WorkbenchServiceRegistry::EXT_ID_SERVICES = "org.blueberry.ui.services"; //$NON-NLS-1$ WorkbenchServiceRegistry* WorkbenchServiceRegistry::registry = 0; const IServiceLocator::Pointer WorkbenchServiceRegistry::GLOBAL_PARENT = IServiceLocator::Pointer(new GlobalParentLocator()); std::string* WorkbenchServiceRegistry::supportedLevels() { static std::string levels[] = { ISources::ACTIVE_CONTEXT_NAME(), ISources::ACTIVE_SHELL_NAME(), ISources::ACTIVE_WORKBENCH_WINDOW_NAME(), ISources::ACTIVE_EDITOR_ID_NAME(), ISources::ACTIVE_PART_ID_NAME(), ISources::ACTIVE_SITE_NAME() }; return levels; } const unsigned int WorkbenchServiceRegistry::supportedLevelsCount = 6; WorkbenchServiceRegistry::WorkbenchServiceRegistry() { // PlatformUI::GetWorkbench().getExtensionTracker().registerHandler(this, // ExtensionTracker .createExtensionPointFilter(getExtensionPoint())); } WorkbenchServiceRegistry::ServiceFactoryHandle::ServiceFactoryHandle( IServiceFactory::ConstPointer _factory) : factory(_factory) { } WorkbenchServiceRegistry::ServiceFactoryHandle::Pointer WorkbenchServiceRegistry::LoadFromRegistry( const std::string& key) { ServiceFactoryHandle::Pointer result; const std::vector serviceFactories = this->GetExtensionPoint()->GetConfigurationElements(); try { bool done = false; for (unsigned int i = 0; i < serviceFactories.size() && !done; i++) { std::vector serviceNameElements = serviceFactories[i]->GetChildren( WorkbenchRegistryConstants::TAG_SERVICE); for (unsigned int j = 0; j < serviceNameElements.size() && !done; j++) { std::string serviceName; serviceNameElements[j]->GetAttribute( WorkbenchRegistryConstants::ATTR_SERVICE_CLASS, serviceName); if (key == serviceName) { done = true; } } if (done) { IServiceFactory::Pointer f( serviceFactories[i]->CreateExecutableExtension( WorkbenchRegistryConstants::ATTR_FACTORY_CLASS)); if (f.IsNull()) { // support legacy BlueBerry extensions f = serviceFactories[i]->CreateExecutableExtension( WorkbenchRegistryConstants::ATTR_FACTORY_CLASS, IServiceFactory::GetManifestName()); } ServiceFactoryHandle::Pointer handle(new ServiceFactoryHandle(f)); // PlatformUI.getWorkbench().getExtensionTracker().registerObject( // serviceFactories[i].getDeclaringExtension(), handle, // IExtensionTracker.REF_WEAK); std::vector serviceNames; for (unsigned int j = 0; j < serviceNameElements.size(); j++) { std::string serviceName; serviceNameElements[j]->GetAttribute( WorkbenchRegistryConstants::ATTR_SERVICE_CLASS, serviceName); if (factories.find(serviceName) != factories.end()) { WorkbenchPlugin::Log("Factory already exists for " + serviceName); } else { factories.insert(std::make_pair(serviceName, handle)); serviceNames.push_back(serviceName); } } handle->serviceNames = serviceNames; result = handle; } } } catch (CoreException& e) { //StatusManager.getManager().handle(e.getStatus()); BERRY_ERROR << "CoreException: " << e.displayText() << std::endl; } return result; } const IExtensionPoint* WorkbenchServiceRegistry::GetExtensionPoint() { IExtensionPointService::Pointer reg = Platform::GetExtensionPointService(); const IExtensionPoint* ep = reg->GetExtensionPoint(EXT_ID_SERVICES); return ep; } void WorkbenchServiceRegistry::ProcessVariables( const std::vector& children) { for (unsigned int i = 0; i < children.size(); i++) { std::string name; children[i]->GetAttribute(WorkbenchRegistryConstants::ATT_NAME, name); if (name.empty()) { continue; } std::string level; children[i]->GetAttribute(WorkbenchRegistryConstants::ATT_PRIORITY_LEVEL, level); if (level.empty()) { level = WORKBENCH_LEVEL; } else { bool found = false; const std::string* const supportedLevels = this->supportedLevels(); for (unsigned int j = 0; j < supportedLevelsCount && !found; j++) { if (supportedLevels[j] == level) { found = true; } } if (!found) { level = WORKBENCH_LEVEL; } } int existingPriority = SourcePriorityNameMapping::GetMapping(level); int newPriority = existingPriority << 1; SourcePriorityNameMapping::AddMapping(name, newPriority); } } Object::Pointer WorkbenchServiceRegistry::GlobalParentLocator::GetService( const std::string& /*api*/) { return Object::Pointer(0); } bool WorkbenchServiceRegistry::GlobalParentLocator::HasService( const std::string& /*api*/) const { return false; } WorkbenchServiceRegistry* WorkbenchServiceRegistry::GetRegistry() { if (registry == 0) { registry = new WorkbenchServiceRegistry(); } return registry; } Object::Pointer WorkbenchServiceRegistry::GetService(const std::string& key, const IServiceLocator::Pointer parentLocator, const ServiceLocator::ConstPointer locator) { ServiceFactoryHandle::Pointer handle(factories[key]); if (!handle) { handle = this->LoadFromRegistry(key); } if (handle) { Object::Pointer result(handle->factory->Create(key, parentLocator, locator)); if (result) { //handle->serviceLocators.insert(locator, new Object()); return result; } } return Object::Pointer(0); } std::vector WorkbenchServiceRegistry::GetSourceProviders() { std::vector providers; const IExtensionPoint* ep = this->GetExtensionPoint(); std::vector elements = ep->GetConfigurationElements(); for (unsigned int i = 0; i < elements.size(); i++) { if (elements[i]->GetName() == WorkbenchRegistryConstants::TAG_SOURCE_PROVIDER) { try { ISourceProvider::Pointer provider(elements[i]->CreateExecutableExtension( WorkbenchRegistryConstants::ATTR_PROVIDER)); if (provider.IsNull()) { // support legacy BlueBerry extensions provider = elements[i]->CreateExecutableExtension( WorkbenchRegistryConstants::ATTR_PROVIDER, ISourceProvider::GetManifestName()); } providers.push_back(provider); this->ProcessVariables(elements[i]->GetChildren( WorkbenchRegistryConstants::TAG_VARIABLE)); } catch (CoreException& e) { //StatusManager.getManager().handle(e.getStatus()); BERRY_ERROR << "CoreException: " << e.displayText() << std::endl; } } } return providers; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchServiceRegistry.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchServiceRegistry.h index cfaa2e2a2d..716a6b3658 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchServiceRegistry.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchServiceRegistry.h @@ -1,147 +1,147 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWORKBENCHSERVICEREGISTRY_H_ #define BERRYWORKBENCHSERVICEREGISTRY_H_ -#include "../services/berryIServiceLocator.h" +#include "services/berryIServiceLocator.h" #include #include namespace berry { struct ISourceProvider; struct IServiceFactory; struct IExtensionPoint; struct IConfigurationElement; class ServiceLocator; /** * This class will create a service from the matching factory. If the factory * doesn't exist, it will try and load it from the registry. * * @since 3.4 */ class WorkbenchServiceRegistry { // implements IExtensionChangeHandler { private: /** * */ static const std::string WORKBENCH_LEVEL; // = "workbench"; //$NON-NLS-1$ static const std::string EXT_ID_SERVICES; // = "org.blueberry.ui.services"; //$NON-NLS-1$ static WorkbenchServiceRegistry* registry; // = 0; WorkbenchServiceRegistry(); struct ServiceFactoryHandle : public Object { berryObjectMacro(ServiceFactoryHandle) SmartPointer factory; // TODO used in removeExtension to react to bundles being unloaded //WeakHashMap serviceLocators = new WeakHashMap(); std::vector serviceNames; ServiceFactoryHandle(SmartPointer factory); }; std::map factories; ServiceFactoryHandle::Pointer LoadFromRegistry(const std::string& key); const IExtensionPoint* GetExtensionPoint(); static std::string* supportedLevels(); static const unsigned int supportedLevelsCount; void ProcessVariables( const std::vector >& children); struct GlobalParentLocator: public IServiceLocator { Object::Pointer GetService(const std::string& api); bool HasService(const std::string& api) const; }; public: static WorkbenchServiceRegistry* GetRegistry(); /** * Used as the global service locator's parent. */ static const IServiceLocator::Pointer GLOBAL_PARENT; // = new GlobalParentLocator(); Object::Pointer GetService(const std::string& key, const IServiceLocator::Pointer parentLocator, const SmartPointer locator); std::vector > GetSourceProviders(); // void addExtension(IExtensionTracker tracker, IExtension extension) { // // we don't need to react to adds because we are not caching the extensions we find - // // next time a service is requested, we will look at all extensions again in // // loadFromRegistry // } // void removeExtension(IExtension extension, Object[] objects) { // for (int i = 0; i < objects.length; i++) { // Object object = objects[i]; // if (object instanceof ServiceFactoryHandle) { // ServiceFactoryHandle handle = (ServiceFactoryHandle) object; // Set locatorSet = handle.serviceLocators.keySet(); // ServiceLocator[] locators = (ServiceLocator[]) locatorSet.toArray(new ServiceLocator[locatorSet.size()]); // Arrays.sort(locators, new Comparator(){ // public int compare(Object o1, Object o2) { // ServiceLocator loc1 = (ServiceLocator) o1; // ServiceLocator loc2 = (ServiceLocator) o2; // int l1 = ((IWorkbenchLocationService) loc1 // .getService(IWorkbenchLocationService.class)) // .getServiceLevel(); // int l2 = ((IWorkbenchLocationService) loc2 // .getService(IWorkbenchLocationService.class)) // .getServiceLevel(); // return l1 < l2 ? -1 : (l1 > l2 ? 1 : 0); // } // }); // for (int j = 0; j < locators.length; j++) { // ServiceLocator serviceLocator = locators[j]; // if (!serviceLocator.isDisposed()) { // serviceLocator.unregisterServices(handle.serviceNames); // } // } // handle.factory = null; // for (int j = 0; j < handle.serviceNames.length; j++) { // String serviceName = handle.serviceNames[j]; // if (factories.get(serviceName) == handle) { // factories.remove(serviceName); // } // } // } // } // } }; } #endif /* BERRYWORKBENCHSERVICEREGISTRY_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchTestable.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchTestable.cpp index 24f76d886b..942d305a32 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchTestable.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchTestable.cpp @@ -1,110 +1,110 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWorkbenchTestable.h" -#include "../berryDisplay.h" -#include "../berryIWorkbench.h" +#include "berryDisplay.h" +#include "berryIWorkbench.h" #include namespace berry { WorkbenchTestable::WorkbenchTestRunnable::WorkbenchTestRunnable(TestableObject* testable) : testable(testable) { } void WorkbenchTestable::WorkbenchTestRunnable::run() { // // Some tests (notably the startup performance tests) do not want to wait for early startup. // // Allow this to be disabled by specifying the system property: org.eclipse.ui.testsWaitForEarlyStartup=false // // For details, see bug 94129 [Workbench] Performance test regression caused by workbench harness change // if (!"false".equalsIgnoreCase(System.getProperty(PlatformUI.PLUGIN_ID + ".testsWaitForEarlyStartup"))) { //$NON-NLS-1$ //$NON-NLS-2$ // waitForEarlyStartup(); // } testable->GetTestHarness()->RunTests(); } class WorkbenchCloseRunnable: public Poco::Runnable { public: WorkbenchCloseRunnable(IWorkbench* workbench) : workbench(workbench) { } void run() { poco_assert(workbench->Close()); } private: IWorkbench* workbench; }; WorkbenchTestable::WorkbenchTestable() : thread("WorkbenchTestable"), testRunnable(this) { // do nothing } void WorkbenchTestable::Init(Display* display, IWorkbench* workbench) { poco_assert(display); poco_assert(workbench); this->display = display; this->workbench = workbench; if (GetTestHarness()) { // don't use a job, since tests often wait for all jobs to complete before proceeding thread.start(testRunnable); } } void WorkbenchTestable::TestingStarting() { poco_assert(workbench); // oldAutomatedMode = ErrorDialog.AUTOMATED_MODE; // ErrorDialog.AUTOMATED_MODE = true; // oldIgnoreErrors = SafeRunnable.getIgnoreErrors(); // SafeRunnable.setIgnoreErrors(true); } void WorkbenchTestable::RunTest(Poco::Runnable* testRunnable) { poco_assert(workbench); display->SyncExec(testRunnable); } void WorkbenchTestable::TestingFinished() { // force events to be processed, and ensure the close is done in the UI thread WorkbenchCloseRunnable runnable(workbench); display->SyncExec(&runnable); // ErrorDialog.AUTOMATED_MODE = oldAutomatedMode; // SafeRunnable.setIgnoreErrors(oldIgnoreErrors); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchTestable.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchTestable.h index f2df03f18f..a1a22dbed2 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchTestable.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchTestable.h @@ -1,125 +1,125 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWORKBENCHTESTABLE_H_ #define BERRYWORKBENCHTESTABLE_H_ -#include "../testing/berryTestableObject.h" +#include "testing/berryTestableObject.h" #include namespace berry { class Display; struct IWorkbench; /** * The Workbench's testable object facade to a test harness. * * @since 3.0 */ class WorkbenchTestable: public TestableObject { private: Display* display; IWorkbench* workbench; bool oldAutomatedMode; bool oldIgnoreErrors; Poco::Thread thread; class WorkbenchTestRunnable: public Poco::Runnable { public: WorkbenchTestRunnable(TestableObject* testable); void run(); private: TestableObject* testable; }; WorkbenchTestRunnable testRunnable; public: berryObjectMacro( WorkbenchTestable) /** * Constructs a new workbench testable object. */ WorkbenchTestable(); /** * Initializes the workbench testable with the display and workbench, * and notifies all listeners that the tests can be run. * * @param display the display * @param workbench the workbench */ void Init(Display* display, IWorkbench* workbench); /** * The WorkbenchTestable implementation of this * TestableObject method ensures that the workbench * has been set. */ void TestingStarting(); /** * The WorkbenchTestable implementation of this * TestableObject method flushes the event queue, * runs the test in a syncExec, then flushes the * event queue again. */ void RunTest(Poco::Runnable* testRunnable); /** * The WorkbenchTestable implementation of this * TestableObject method flushes the event queue, * then closes the workbench. */ void TestingFinished(); private: /** * Waits for the early startup job to complete. */ // void WaitForEarlyStartup() { // try { // Job::GetJobManager()->Join(Workbench::EARLY_STARTUP_FAMILY, 0); // } catch (OperationCanceledException e) { // // ignore // } catch (InterruptedException e) { // // ignore // } // } }; } #endif /* BERRYWORKBENCHTESTABLE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindow.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindow.cpp index 05fab16d53..03367d15db 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindow.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindow.cpp @@ -1,1779 +1,1779 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWorkbenchWindow.h" -#include "../berryIWorkbenchPage.h" -#include "../berryIPerspectiveDescriptor.h" -#include "../berryUIException.h" -#include "../berryConstants.h" +#include "berryIWorkbenchPage.h" +#include "berryIPerspectiveDescriptor.h" +#include "berryUIException.h" +#include "berryConstants.h" #include "intro/berryIntroConstants.h" #include "berryWorkbenchPlugin.h" #include "berryWorkbenchPage.h" #include "berryWorkbench.h" #include "berryWorkbenchConstants.h" #include "berryPartSite.h" #include "berryIServiceLocatorCreator.h" -#include "../tweaklets/berryGuiWidgetsTweaklet.h" -#include "../tweaklets/berryWorkbenchTweaklet.h" +#include "tweaklets/berryGuiWidgetsTweaklet.h" +#include "tweaklets/berryWorkbenchTweaklet.h" -#include "../services/berryIServiceFactory.h" +#include "services/berryIServiceFactory.h" -#include "../berryPlatformUI.h" +#include "berryPlatformUI.h" -#include "../berryDebugUtil.h" +#include "berryDebugUtil.h" namespace berry { const int WorkbenchWindow::FILL_ALL_ACTION_BARS = ActionBarAdvisor::FILL_MENU_BAR | ActionBarAdvisor::FILL_COOL_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), emptyWindowContentsCreated( false), emptyWindowContents(0), asMaximizedState(false), partService( this), serviceLocatorOwner( new ServiceLocatorOwner(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::Pointer slc = workbench->GetService(IServiceLocatorCreator::GetManifestName()).Cast< IServiceLocatorCreator> (); IServiceLocator::Pointer locator(workbench); this->serviceLocator = slc->CreateServiceLocator(IServiceLocator::WeakPtr( locator), IServiceFactory::ConstPointer(0), IDisposable::WeakPtr( serviceLocatorOwner)).Cast (); // initializeDefaultServices(); // Add contribution managers that are exposed to other plugins. //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()"; } Object::Pointer WorkbenchWindow::GetService(const std::string& key) { return serviceLocator->GetService(key); } bool WorkbenchWindow::HasService(const std::string& key) const { return serviceLocator->HasService(key); } Shell::Pointer WorkbenchWindow::GetShell() { 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::Pointer l) { perspectiveEvents.AddListener(l); } void WorkbenchWindow::RemovePerspectiveListener(IPerspectiveListener::Pointer 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 std::string& 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 std::string& 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(int flags) { // Workbench workbench = getWorkbenchImpl(); // workbench.largeUpdateStart(); //try { this->GetActionBarAdvisor()->FillActionBars(flags); // final IMenuService menuService = (IMenuService) serviceLocator // .getService(IMenuService.class); // menuService.populateContributionManager( // (ContributionManager) getActionBars().getMenuManager(), // MenuUtil.MAIN_MENU); // ICoolBarManager coolbar = getActionBars().getCoolBarManager(); // if (coolbar != null) { // menuService.populateContributionManager( // (ContributionManager) coolbar, // MenuUtil.MAIN_TOOLBAR); // } // // } finally { // workbench.largeUpdateEnd(); // } } Point WorkbenchWindow::GetInitialSize() { return this->GetWindowConfigurer()->GetInitialSize(); } bool WorkbenchWindow::Close() { //BERRY_INFO << "WorkbenchWindow::Close()"; if (controlResizeListener) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->RemoveControlListener(GetShell()->GetControl(), controlResizeListener); } bool ret = false; //BusyIndicator.showWhile(null, new Runnable() { // public void run() { ret = this->BusyClose(); // } // }); if (!ret && controlResizeListener) { Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(GetShell()->GetControl(), controlResizeListener); } 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()) { 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. /* final IContextService contextService = (IContextService) workbench.getService(IContextService.class); contextService.unregisterShell(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(); } } IWorkbenchPage::Pointer WorkbenchWindow::GetActivePage() { return pageList.GetActive(); } IWorkbench* WorkbenchWindow::GetWorkbench() { return PlatformUI::GetWorkbench(); } IPartService* WorkbenchWindow::GetPartService() { return &partService; } ISelectionService* WorkbenchWindow::GetSelectionService() { return partService.GetSelectionService(); } 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; } void* WorkbenchWindow::GetPageComposite() { return pageComposite; } void* 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) { //pageComposite = Tweaklets::Get(WorkbenchTweaklet::KEY)->CreateDefaultWindowContents(shell); this->CreatePageComposite(shell->GetControl()); } bool WorkbenchWindow::UnableToRestorePage(IMemento::Pointer pageMem) { std::string 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. Rectangle displayBounds; // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { displayBounds = Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetScreenSize(); //displayBounds = GetShell()->GetDisplay()->GetBounds(); // }}); Rectangle shellBounds; // 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); // }}); // // } // } memento->GetInteger(WorkbenchConstants::TAG_X, shellBounds.x); memento->GetInteger(WorkbenchConstants::TAG_Y, shellBounds.y); memento->GetInteger(WorkbenchConstants::TAG_WIDTH, shellBounds.width); memento->GetInteger(WorkbenchConstants::TAG_HEIGHT, shellBounds.height); if (!shellBounds.IsEmpty()) { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { if (!shellBounds.Intersects(displayBounds)) { Rectangle clientArea(Tweaklets::Get(GuiWidgetsTweaklet::KEY)->GetAvailableScreenSize()); shellBounds.x = clientArea.x; shellBounds.y = clientArea.y; } GetShell()->SetBounds(shellBounds); // }}); } std::string maximized; memento->GetString(WorkbenchConstants::TAG_MAXIMIZED, maximized); if (maximized == "true") { // StartupThreading.runWithoutExceptions(new StartupRunnable() { // // public void runWithException() { GetShell()->SetMaximized(true); // }}); } std::string 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; std::vector pageArray = memento ->GetChildren(WorkbenchConstants::TAG_PAGE); for (std::size_t i = 0; i < pageArray.size(); i++) { IMemento::Pointer pageMem = pageArray[i]; std::string strFocus; pageMem->GetString(WorkbenchConstants::TAG_FOCUS, strFocus); if (strFocus.empty()) { continue; } // Get the input factory. IAdaptable* input = 0; IMemento::Pointer inputMem = pageMem->GetChild(WorkbenchConstants::TAG_INPUT); if (inputMem) { std::string factoryID; inputMem->GetString(WorkbenchConstants::TAG_FACTORY_ID, factoryID); if (factoryID.empty()) { 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.empty()) { newActivePage = newPage; } } // If there are no pages create a default. if (pageList.IsEmpty()) { try { const std::string defPerspID = this->GetWorkbenchImpl()->GetPerspectiveRegistry() ->GetDefaultPerspective(); if (!defPerspID.empty()) { 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 std::string& 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) { std::string perspId = this->GetWorkbenchImpl()->GetDefaultPerspectiveId(); return this->OpenPage(perspId, input); } IWorkbenchPage::Pointer WorkbenchWindow::BusyOpenPage( const std::string& 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::LargeUpdateStart() { largeUpdates++; } void WorkbenchWindow::LargeUpdateEnd() { if (--largeUpdates == 0) { //TODO WorkbenchWindow update action bars after large update //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); // } //}); } 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() { if (windowConfigurer.IsNull()) { // lazy initialize windowConfigurer = new WorkbenchWindowConfigurer(WorkbenchWindow::Pointer(this)); } return windowConfigurer; } void WorkbenchWindow::ConfigureShell(Shell::Pointer shell) { Window::ConfigureShell(shell); detachedWindowShells = new ShellPool(shell, Constants::TITLE | Constants::MAX | Constants::CLOSE | Constants::RESIZE | Constants::BORDER ); std::string title = this->GetWindowConfigurer()->BasicGetTitle(); if (title != "") { shell->SetText(title); } // final IWorkbench workbench = getWorkbench(); // workbench.getHelpSystem().setHelp(shell, // IWorkbenchHelpContextIds.WORKBENCH_WINDOW); // final IContextService contextService = (IContextService) getWorkbench().getService(IContextService.class); // contextService.registerShell(shell, IContextService.TYPE_WINDOW); this->TrackShellActivation(shell); this->TrackShellResize(shell); } 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) { void* 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.remove(object); std::size_t origSize = pagesInCreationOrder.size(); pagesInCreationOrder.remove(object); return origSize != pagesInCreationOrder.size(); } void WorkbenchWindow::PageList::Clear() { pagesInCreationOrder.clear(); pagesInActivationOrder.clear(); active = 0; } bool WorkbenchWindow::PageList::IsEmpty() { return pagesInCreationOrder.empty(); } const std::list& WorkbenchWindow::PageList::GetPages() { return pagesInCreationOrder; } void WorkbenchWindow::PageList::SetActive(IWorkbenchPage::Pointer page) { if (active == page) { return; } active = page; if (page.IsNotNull()) { pagesInActivationOrder.remove(page); pagesInActivationOrder.push_back(page); } } WorkbenchPage::Pointer WorkbenchWindow::PageList::GetActive() { 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); } std::list::reverse_iterator riter = pagesInActivationOrder.rbegin(); return (++riter)->Cast(); } WorkbenchWindow::ShellActivationListener::ShellActivationListener(WorkbenchWindow::Pointer w) : window(w) { } void WorkbenchWindow::ShellActivationListener::ShellActivated(ShellEvent::Pointer /*event*/) { 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::ShellActivationListener::ShellDeactivated(ShellEvent::Pointer /*event*/) { 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); } } void WorkbenchWindow::TrackShellActivation(Shell::Pointer shell) { shellActivationListener = new ShellActivationListener(WorkbenchWindow::Pointer(this)); shell->AddShellListener(shellActivationListener); } WorkbenchWindow::ControlResizeListener::ControlResizeListener(WorkbenchWindow* w) : window(w) { } GuiTk::IControlListener::Events::Types WorkbenchWindow::ControlResizeListener::GetEventTypes() const { return Events::MOVED | Events::RESIZED; } void WorkbenchWindow:: ControlResizeListener::ControlMoved(GuiTk::ControlEvent::Pointer /*e*/) { this->SaveBounds(); } void WorkbenchWindow:: ControlResizeListener::ControlResized(GuiTk::ControlEvent::Pointer /*e*/) { this->SaveBounds(); } void WorkbenchWindow::ControlResizeListener::SaveBounds() { WorkbenchWindow::Pointer wnd(window); Shell::Pointer shell = wnd->GetShell(); if (shell == 0) { return; } // if (shell->IsDisposed()) // { // return; // } if (shell->GetMinimized()) { return; } if (shell->GetMaximized()) { wnd->asMaximizedState = true; return; } wnd->asMaximizedState = false; wnd->normalBounds = shell->GetBounds(); } void WorkbenchWindow::TrackShellResize(Shell::Pointer newShell) { controlResizeListener = new ControlResizeListener(this); Tweaklets::Get(GuiWidgetsTweaklet::KEY)->AddControlListener(newShell->GetControl(), controlResizeListener); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindow.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindow.h index a419413ef9..00488e3319 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindow.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindow.h @@ -1,631 +1,631 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWORKBENCHWINDOW_H_ #define BERRYWORKBENCHWINDOW_H_ -#include "../berryIWorkbenchWindow.h" +#include "berryIWorkbenchWindow.h" -#include "../berryIPerspectiveListener.h" -#include "../guitk/berryGuiTkIControlListener.h" -#include "../berryWindow.h" +#include "berryIPerspectiveListener.h" +#include "guitk/berryGuiTkIControlListener.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 "application/berryWorkbenchAdvisor.h" +#include "application/berryWorkbenchWindowAdvisor.h" +#include "application/berryActionBarAdvisor.h" #include namespace berry { struct IWorkbench; struct IWorkbenchPage; class WorkbenchPage; struct IPartService; struct ISelectionService; struct IPerspectiveDescriptor; class Workbench; /** * \ingroup org_blueberry_ui * */ class BERRY_UI WorkbenchWindow: public Window, public IWorkbenchWindow { public: berryObjectMacro(WorkbenchWindow); WorkbenchWindow(int number); ~WorkbenchWindow(); Object::Pointer GetService(const std::string& key); bool HasService(const std::string& key) const; int Open(); bool Close(); Shell::Pointer GetShell(); /** * @see org.blueberry.ui.IPageService */ void AddPerspectiveListener(IPerspectiveListener::Pointer l); /** * @see org.blueberry.ui.IPageService */ void RemovePerspectiveListener(IPerspectiveListener::Pointer l); /** * @see org.blueberry.ui.IPageService */ IPerspectiveListener::Events& GetPerspectiveEvents(); SmartPointer GetActivePage(); /** * Sets the active page within the window. * * @param in * identifies the new active page, or null for no * active page */ void SetActivePage(SmartPointer in); IWorkbench* GetWorkbench(); IPartService* GetPartService(); ISelectionService* GetSelectionService(); SmartPointer OpenPage(const std::string& perspectiveId, IAdaptable* input); SmartPointer OpenPage(IAdaptable* input); //TODO menu manager //virtual void* 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(); /** *

    * 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(); 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. */ void* GetPageComposite(); /** * Creates and remembers the client composite, under which workbench pages * create their controls. * * @since 3.0 */ virtual void* CreatePageComposite(void* parent) = 0; /** * 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 */ void* CreateContents(Shell::Pointer parent); /** * Creates the default contents and layout of the shell. * * @param shell * the shell */ virtual void CreateDefaultContents(Shell::Pointer 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(); /* * @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(int flags); /** * The WorkbenchWindow implementation of this method * delegates to the window configurer. * * @since 3.0 */ Point 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 std::string& 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. * * @since 3.0 */ void* pageComposite; private: /** * Constant indicating that all the actions bars should be filled. * * @since 3.0 */ static const int 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 */ WorkbenchWindowConfigurer::Pointer windowConfigurer; WorkbenchWindowAdvisor* windowAdvisor; ActionBarAdvisor::Pointer actionBarAdvisor; 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; /** * The map of services maintained by the workbench window. These services * are initialized during workbench window during the * {@link #configureShell(Shell)}. */ ServiceLocator::Pointer serviceLocator; bool emptyWindowContentsCreated; void* emptyWindowContents; Rectangle normalBounds; bool asMaximizedState; IPerspectiveListener::Events perspectiveEvents; WWinPartService partService; 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; std::list > pagesInCreationOrder; // List of pages where the top is the last activated. std::list > pagesInActivationOrder; // The page explicitly activated SmartPointer active; public: typedef std::list >::iterator iterator; bool Add(SmartPointer object); iterator Begin(); iterator End(); void Clear(); bool Contains(SmartPointer object); bool Remove(SmartPointer object); bool IsEmpty(); const std::list >& GetPages(); void SetActive(SmartPointer page); SmartPointer GetActive(); 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 std::string& changeId); /** * Fires perspective changed for an affected part */ void FirePerspectiveChanged(SmartPointer , IPerspectiveDescriptor::Pointer perspective, IWorkbenchPartReference::Pointer partRef, const std::string& 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 ShellActivationListener: public IShellListener { ShellActivationListener(WorkbenchWindow::Pointer window); void ShellActivated(ShellEvent::Pointer event); void ShellDeactivated(ShellEvent::Pointer event); private: WorkbenchWindow::WeakPtr window; }; IShellListener::Pointer shellActivationListener; /** * Hooks a listener to track the activation and deactivation of the window's * shell. Notifies the active part and editor of the change */ void TrackShellActivation(Shell::Pointer shell); struct ControlResizeListener: public GuiTk::IControlListener { ControlResizeListener(WorkbenchWindow* window); GuiTk::IControlListener::Events::Types GetEventTypes() const; void ControlMoved(GuiTk::ControlEvent::Pointer e); void ControlResized(GuiTk::ControlEvent::Pointer e); private: void SaveBounds(); WorkbenchWindow* window; }; GuiTk::IControlListener::Pointer controlResizeListener; /** * 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); }; } #endif /*BERRYWORKBENCHWINDOW_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindowConfigurer.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindowConfigurer.cpp index 673b563e16..50255f99a0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindowConfigurer.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindowConfigurer.cpp @@ -1,267 +1,267 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWorkbenchWindowConfigurer.h" #include "berryWorkbenchWindow.h" -#include "../berryImageDescriptor.h" +#include "berryImageDescriptor.h" #include "berryWorkbench.h" #include "berryWorkbenchPage.h" #include "berryEditorSashContainer.h" #include "berryWorkbenchPlugin.h" #include "berryQtDnDControlWidget.h" namespace berry { WorkbenchWindowConfigurer::WindowActionBarConfigurer::WindowActionBarConfigurer(WorkbenchWindow::WeakPtr wnd) : window(wnd) { } void WorkbenchWindowConfigurer::WindowActionBarConfigurer::SetProxy(IActionBarConfigurer::Pointer proxy) { this->proxy = proxy; } IWorkbenchWindowConfigurer::Pointer WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetWindowConfigurer() { return WorkbenchWindow::Pointer(window)->GetWindowConfigurer(); } void* WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetMenuManager() { if (proxy.IsNotNull()) { return proxy->GetMenuManager(); } //TODO window menu manager //return window->GetMenuManager(); return 0; } WorkbenchWindowConfigurer::WorkbenchWindowConfigurer(WorkbenchWindow::Pointer window) : shellStyle(0), showPerspectiveBar(false), showStatusLine(true), showToolBar(true), showMenuBar(true), showProgressIndicator(false), initialSize(1024,768) { if (window.IsNull()) { throw Poco::InvalidArgumentException(); } this->window = window; windowTitle = "BlueBerry Application"; } IWorkbenchWindow::Pointer WorkbenchWindowConfigurer::GetWindow() { return IWorkbenchWindow::Pointer(window); } IWorkbenchConfigurer::Pointer WorkbenchWindowConfigurer::GetWorkbenchConfigurer() { return dynamic_cast(PlatformUI::GetWorkbench())->GetWorkbenchConfigurer(); } std::string WorkbenchWindowConfigurer::BasicGetTitle() { return windowTitle; } std::string WorkbenchWindowConfigurer::GetTitle() { Shell::Pointer shell = window.Lock()->GetShell(); if (shell) { // update the cached title windowTitle = shell->GetText(); } return windowTitle; } void WorkbenchWindowConfigurer::SetTitle(const std::string& title) { windowTitle = title; Shell::Pointer shell = window.Lock()->GetShell(); if (shell) { shell->SetText(title); } } bool WorkbenchWindowConfigurer::GetShowMenuBar() { return showMenuBar; } void WorkbenchWindowConfigurer::SetShowMenuBar(bool show) { showMenuBar = show; // WorkbenchWindow win = (WorkbenchWindow) getWindow(); // Shell shell = win.getShell(); // if (shell != null) // { // boolean showing = shell.getMenuBar() != null; // if (show != showing) // { // if (show) // { // shell.setMenuBar(win.getMenuBarManager().getMenu()); // } // else // { // shell.setMenuBar(null); // } // } // } } bool WorkbenchWindowConfigurer::GetShowCoolBar() { return showToolBar; } void WorkbenchWindowConfigurer::SetShowCoolBar(bool show) { showToolBar = show; //window.setCoolBarVisible(show); // @issue need to be able to reconfigure after window's controls created } bool WorkbenchWindowConfigurer::GetShowPerspectiveBar() { return showPerspectiveBar; } void WorkbenchWindowConfigurer::SetShowPerspectiveBar(bool show) { showPerspectiveBar = show; //window.setPerspectiveBarVisible(show); // @issue need to be able to reconfigure after window's controls created } bool WorkbenchWindowConfigurer::GetShowStatusLine() { return showStatusLine; } void WorkbenchWindowConfigurer::SetShowStatusLine(bool show) { showStatusLine = show; // @issue need to be able to reconfigure after window's controls created } bool WorkbenchWindowConfigurer::GetShowProgressIndicator() { return showProgressIndicator; } void WorkbenchWindowConfigurer::SetShowProgressIndicator(bool show) { showProgressIndicator = show; // @issue need to be able to reconfigure after window's controls created } void WorkbenchWindowConfigurer::AddEditorAreaTransfer(const QStringList& transfers) { if (transfers.isEmpty()) return; int oldSize = transferTypes.size(); transferTypes.unite(QSet::fromList(transfers)); if (transferTypes.size() == oldSize) return; WorkbenchPage::Pointer page = window.Lock()->GetActivePage().Cast(); if (page) { QtDnDControlWidget* dropTarget = static_cast(page->GetEditorPresentation()->GetLayoutPart().Cast()->GetParent()); dropTarget->SetTransferTypes(transferTypes.toList()); } } void WorkbenchWindowConfigurer::ConfigureEditorAreaDropListener(const IDropTargetListener::Pointer& listener) { if (listener == 0) return; dropTargetListener = listener; WorkbenchPage::Pointer page = window.Lock()->GetActivePage().Cast(); if (page) { QtDnDControlWidget* dropTarget = static_cast(page->GetEditorPresentation()->GetLayoutPart().Cast()->GetParent()); dropTarget->AddDropListener(listener.GetPointer()); } } QStringList WorkbenchWindowConfigurer::GetTransfers() const { return transferTypes.toList(); } IDropTargetListener::Pointer WorkbenchWindowConfigurer::GetDropTargetListener() const { return dropTargetListener; } IActionBarConfigurer::Pointer WorkbenchWindowConfigurer::GetActionBarConfigurer() { if (actionBarConfigurer.IsNull()) { // lazily initialize actionBarConfigurer = new WindowActionBarConfigurer(window); } return actionBarConfigurer; } int WorkbenchWindowConfigurer::GetShellStyle() { return shellStyle; } void WorkbenchWindowConfigurer::SetShellStyle(int shellStyle) { this->shellStyle = shellStyle; } Point WorkbenchWindowConfigurer::GetInitialSize() { return initialSize; } void WorkbenchWindowConfigurer::SetInitialSize(Point size) { initialSize = size; } void WorkbenchWindowConfigurer::CreateDefaultContents(Shell::Pointer shell) { WorkbenchWindow::Pointer(window)->CreateDefaultContents(shell); } void* WorkbenchWindowConfigurer::CreatePageComposite(void* parent) { return WorkbenchWindow::Pointer(window)->CreatePageComposite(parent); } bool WorkbenchWindowConfigurer::SaveState(IMemento::Pointer memento) { return WorkbenchWindow::Pointer(window)->SaveState(memento); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindowConfigurer.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindowConfigurer.h index 7022ad84a0..59a8dfcf08 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindowConfigurer.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/berryWorkbenchWindowConfigurer.h @@ -1,457 +1,457 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWORKBENCHWINDOWCONFIGURER_H_ #define BERRYWORKBENCHWINDOWCONFIGURER_H_ -#include "../application/berryIActionBarConfigurer.h" -#include "../application/berryIWorkbenchConfigurer.h" -#include "../application/berryIWorkbenchWindowConfigurer.h" +#include "application/berryIActionBarConfigurer.h" +#include "application/berryIWorkbenchConfigurer.h" +#include "application/berryIWorkbenchWindowConfigurer.h" #include #include namespace berry { class WorkbenchWindow; /** * Internal class providing special access for configuring workbench windows. *

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

    *

    * This class is not intended to be instantiated or subclassed by clients. *

    * * @since 3.0 */ class WorkbenchWindowConfigurer : public IWorkbenchWindowConfigurer { friend class WorkbenchWindow; public: berryObjectMacro(WorkbenchWindowConfigurer); /** * The workbench window associated with this configurer. */ private: WeakPointer window; /** * The shell style bits to use when the window's shell is being created. */ private: int shellStyle; /** * The window title to set when the window's shell has been created. */ private: std::string windowTitle; /** * Whether the workbench window should show the fast view bars. */ //private: boolean showFastViewBars = false; /** * Whether the workbench window should show the perspective bar */ private: bool showPerspectiveBar; /** * Whether the workbench window should show the status line. */ private: bool showStatusLine; /** * Whether the workbench window should show the main tool bar. */ private: bool showToolBar; /** * Whether the workbench window should show the main menu bar. */ private: bool showMenuBar; /** * Whether the workbench window should have a progress indicator. */ private: bool showProgressIndicator; /** * Table to hold arbitrary key-data settings (key type: String, * value type: Object). * @see #setData */ //private: Map extraData = new HashMap(1); /** * Holds the list drag and drop Transfer for the * editor area */ private: QSet transferTypes; /** * The DropTargetListener implementation for handling a * drop into the editor area. */ private: IDropTargetListener::Pointer dropTargetListener; /** * The initial size to use for the shell. */ private: Point initialSize; /** * Action bar configurer that changes this workbench window. * This implementation keeps track of of cool bar items */ private: class WindowActionBarConfigurer : public IActionBarConfigurer { private: IActionBarConfigurer::Pointer proxy; private: WeakPointer window; public: berryObjectMacro(WindowActionBarConfigurer); public: WindowActionBarConfigurer(WeakPointer wnd); /** * Sets the proxy to use, or null for none. * * @param proxy the proxy */ public: void SetProxy(IActionBarConfigurer::Pointer proxy); /* (non-Javadoc) * @see org.blueberry.ui.application.IActionBarConfigurer#getWindowConfigurer() */ public: IWorkbenchWindowConfigurer::Pointer GetWindowConfigurer(); /** * Returns whether the given id is for a cool item. * * @param the item id * @return true if it is a cool item, * and false otherwise */ // /* package */boolean containsCoolItem(String id) { // ICoolBarManager cbManager = getCoolBarManager(); // if (cbManager == null) { // return false; // } // IContributionItem cbItem = cbManager.find(id); // if (cbItem == null) { // return false; // } // //@ issue: maybe we should check if cbItem is visible? // return true; // } /* (non-Javadoc) * @see org.blueberry.ui.application.IActionBarConfigurer */ // public: IStatusLineManager getStatusLineManager() { // if (proxy != null) { // return proxy.getStatusLineManager(); // } // return window.getStatusLineManager(); // } /* (non-Javadoc) * @see org.blueberry.ui.application.IActionBarConfigurer */ public: void* GetMenuManager(); /* (non-Javadoc) * @see org.blueberry.ui.internal.AbstractActionBarConfigurer */ // public: ICoolBarManager getCoolBarManager() { // if (proxy != null) { // return proxy.getCoolBarManager(); // } // return window.getCoolBarManager2(); // } /* (non-Javadoc) * @see org.blueberry.ui.application.IActionBarConfigurer */ // public: void registerGlobalAction(IAction action) { // if (proxy != null) { // proxy.registerGlobalAction(action); // } // window.registerGlobalAction(action); // } /* (non-Javadoc) * @see org.blueberry.ui.application.IActionBarConfigurer#createToolBarManager() */ // public: IToolBarManager createToolBarManager() { // if (proxy != null) { // return proxy.createToolBarManager(); // } // return getActionBarPresentationFactory().createToolBarManager(); // } /* (non-Javadoc) * @see org.blueberry.ui.application.IActionBarConfigurer#createToolBarContributionItem(org.blueberry.jface.action.IToolBarManager, java.lang.String) */ // public: IToolBarContributionItem createToolBarContributionItem(IToolBarManager toolBarManager, String id) { // if (proxy != null) { // return proxy.createToolBarContributionItem(toolBarManager, id); // } // return getActionBarPresentationFactory().createToolBarContributionItem(toolBarManager, id); // } }; /** * Object for configuring this workbench window's action bars. * Lazily initialized to an instance unique to this window. */ private: WindowActionBarConfigurer::Pointer actionBarConfigurer; /** * Creates a new workbench window configurer. *

    * This method is declared package-private:. Clients obtain instances * via {@link WorkbenchAdvisor#getWindowConfigurer * WorkbenchAdvisor.getWindowConfigurer} *

    * * @param window the workbench window that this object configures * @see WorkbenchAdvisor#getWindowConfigurer */ public: WorkbenchWindowConfigurer(SmartPointer window); /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#getWindow */ public: IWorkbenchWindow::Pointer GetWindow(); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#getWorkbenchConfigurer() */ public: IWorkbenchConfigurer::Pointer GetWorkbenchConfigurer(); /** * Returns the title as set by setTitle, without consulting the shell. * * @return the window title as set, or null if not set */ /* package */std::string BasicGetTitle(); /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#getTitle */ public: std::string GetTitle(); /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#setTitle */ public: void SetTitle(const std::string& title); /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#getShowMenuBar */ public: bool GetShowMenuBar(); /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#setShowMenuBar */ public: void SetShowMenuBar(bool show); /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#getShowToolBar */ public: bool GetShowCoolBar(); /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ public: void SetShowCoolBar(bool show); /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ public: bool GetShowPerspectiveBar(); /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ public: void SetShowPerspectiveBar(bool show); /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#getShowStatusLine */ public: bool GetShowStatusLine(); /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#setShowStatusLine */ public: void SetShowStatusLine(bool show); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ public: bool GetShowProgressIndicator(); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ public: void SetShowProgressIndicator(bool show); /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#getData */ // public: Object getData(String key) { // if (key == null) { // throw new IllegalArgumentException(); // } // return extraData.get(key); // } /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#setData */ // public: void setData(String key, Object data) { // if (key == null) { // throw new IllegalArgumentException(); // } // if (data != null) { // extraData.put(key, data); // } else { // extraData.remove(key); // } // } /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#addEditorAreaTransfer */ public: void AddEditorAreaTransfer(const QStringList& transferTypes); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ public: void ConfigureEditorAreaDropListener(const IDropTargetListener::Pointer &listener); /** * Returns the array of Transfer added by the application */ public: QStringList GetTransfers() const; /** * Returns the drop listener provided by the application. */ public: IDropTargetListener::Pointer GetDropTargetListener() const; /* (non-javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ public: IActionBarConfigurer::Pointer GetActionBarConfigurer(); /** * Returns whether the given id is for a cool item. * * @param the item id * @return true if it is a cool item, * and false otherwise */ // /* package */boolean containsCoolItem(String id) { // // trigger lazy initialization // getActionBarConfigurer(); // return actionBarConfigurer.containsCoolItem(id); // } /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ public: int GetShellStyle(); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ public: void SetShellStyle(int shellStyle); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ public: Point GetInitialSize(); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ public: void SetInitialSize(Point size); /** * Creates the default window contents. * * @param shell the shell */ public: void CreateDefaultContents(Shell::Pointer shell); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ // public: Menu createMenuBar() { // return window.getMenuManager().createMenuBar(window.getShell()); // } /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ // public: Control createCoolBarControl(Composite parent) { // ICoolBarManager coolBarManager = window.getCoolBarManager2(); // if (coolBarManager != null) { // if (coolBarManager instanceof ICoolBarManager2) { // return ((ICoolBarManager2) coolBarManager).createControl2(parent); // } // if (coolBarManager instanceof CoolBarManager) { // return ((CoolBarManager) coolBarManager).createControl(parent); // } // } // return null; // } /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ // public: Control createStatusLineControl(Composite parent) { // return window.getStatusLineManager().createControl(parent); // } /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer */ public: void* CreatePageComposite(void* parent); /* (non-Javadoc) * @see org.blueberry.ui.application.IWorkbenchWindowConfigurer#saveState(org.blueberry.ui.IMemento) */ public: bool SaveState(IMemento::Pointer memento) ; }; } #endif /*BERRYWORKBENCHWINDOWCONFIGURER_H_*/ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryEditorIntroAdapterPart.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryEditorIntroAdapterPart.cpp index 212e6bdf5c..4d08b9136e 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryEditorIntroAdapterPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryEditorIntroAdapterPart.cpp @@ -1,148 +1,148 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryEditorIntroAdapterPart.h" #include "berryIntroPartAdapterSite.h" -#include "../berryWorkbench.h" -#include "../berryWorkbenchPlugin.h" +#include "internal/berryWorkbench.h" +#include "internal/berryWorkbenchPlugin.h" namespace berry { EditorIntroAdapterPart::EditorIntroAdapterPart() : propChangeListener(new PropertyChangeIntAdapter(this, &EditorIntroAdapterPart::PropertyChange)) { } EditorIntroAdapterPart::EditorIntroAdapterPart(const EditorIntroAdapterPart& other) { Q_UNUSED(other) throw std::runtime_error("Copy constructor not implemented"); } void EditorIntroAdapterPart::SetStandby(bool standby) { // final Control control = ((PartSite) getSite()).getPane().getControl(); // BusyIndicator.showWhile(control.getDisplay(), new Runnable() { // public void run() { // try { // control.setRedraw(false); introPart->StandbyStateChanged(standby); // } finally { // control.setRedraw(true); // } // // setBarVisibility(standby); // } // }); } void EditorIntroAdapterPart::CreatePartControl(void* parent) { //addPaneListener(); introPart->CreatePartControl(parent); } EditorIntroAdapterPart::~EditorIntroAdapterPart() { //setBarVisibility(true); if(introPart) { introPart->RemovePropertyListener(propChangeListener); GetSite()->GetWorkbenchWindow()->GetWorkbench()->GetIntroManager()->CloseIntro( introPart); } } void* EditorIntroAdapterPart::GetTitleImage() { return introPart->GetTitleImage(); } std::string EditorIntroAdapterPart::GetPartName() { // this method is called eagerly before our init method is called (and // therefore before our intropart is created). By default return // the view title from the view declaration. We will fire a property // change to set the title to the proper value in the init method. return introPart.IsNull() ? EditorPart::GetPartName() : introPart->GetPartName(); } void EditorIntroAdapterPart::Init(IEditorSite::Pointer site, IEditorInput::Pointer input) { Workbench* workbench = dynamic_cast(site->GetWorkbenchWindow()->GetWorkbench()); try { introPart = workbench->GetWorkbenchIntroManager()->CreateNewIntroPart(); // reset the part name of this view to be that of the intro title SetPartName(introPart->GetPartName()); introPart->AddPropertyListener(propChangeListener); introSite = IIntroSite::Pointer(new IntroPartAdapterSite(site, workbench->GetIntroDescriptor())); introPart->Init(introSite, IMemento::Pointer(0)); } catch (CoreException& e) { //TODO IStatus // WorkbenchPlugin.log( // IntroMessages.Intro_could_not_create_proxy, // new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, // IStatus.ERROR, IntroMessages.Intro_could_not_create_proxy, e)); WorkbenchPlugin::Log("Could not create intro editor proxy.", e); } this->SetSite(site); this->SetInput(input); } void EditorIntroAdapterPart::DoSave(/*IProgressMonitor monitor*/) { } void EditorIntroAdapterPart::DoSaveAs() { } bool EditorIntroAdapterPart::IsDirty() const { return false; } bool EditorIntroAdapterPart::IsSaveAsAllowed() const { return false; } void EditorIntroAdapterPart::PropertyChange(Object::Pointer /*source*/, int propId) { FirePropertyChange(propId); } void EditorIntroAdapterPart::SetFocus() { introPart->SetFocus(); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIIntroDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIIntroDescriptor.h index 203a375662..de42960753 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIIntroDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIIntroDescriptor.h @@ -1,77 +1,77 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYIINTRODESCRIPTOR_H_ #define BERRYIINTRODESCRIPTOR_H_ #include #include -#include "../../intro/berryIIntroPart.h" +#include "intro/berryIIntroPart.h" #include #include namespace berry { /** * Describes an introduction extension. * * @since 3.0 */ struct IIntroDescriptor : public Object { berryInterfaceMacro(IIntroDescriptor, berry) /** * Creates an instance of the intro part defined in the descriptor. */ virtual IIntroPart::Pointer CreateIntro() throw(CoreException) = 0; /** * Returns the role of the intro part (view or editor) * @return the role of the part */ virtual int GetRole() const = 0; /** * Returns the part id. * * @return the id of the part */ virtual std::string GetId() const = 0; /** * Returns the descriptor of the image for this part. * * @return the descriptor of the image to display next to this part */ virtual ImageDescriptor::Pointer GetImageDescriptor() const = 0; /** * Return the label override string for this part. * * @return the label override string or the empty string if one has not * been specified */ virtual std::string GetLabelOverride() const = 0; }; } #endif /* BERRYIINTRODESCRIPTOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIntroDescriptor.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIntroDescriptor.cpp index f6d046b9aa..465c0f593b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIntroDescriptor.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIntroDescriptor.cpp @@ -1,132 +1,132 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryIntroDescriptor.h" #include "berryIntroConstants.h" -#include "../berryWorkbenchRegistryConstants.h" +#include "internal/berryWorkbenchRegistryConstants.h" #include namespace berry { IntroDescriptor::IntroDescriptor(IConfigurationElement::Pointer configElement) throw (CoreException) : element(configElement) { std::string val; if (!configElement->GetAttribute(WorkbenchRegistryConstants::ATT_CLASS, val)) { //TODO IStatus /* throw CoreException(new Status(IStatus.ERROR, configElement .getNamespace(), 0, "Invalid extension (Missing class name): " + getId(), //$NON-NLS-1$ null)); */ throw CoreException(configElement->GetContributor() + ": Invalid extension (Missing className): " + GetId()); } } SmartPointer IntroDescriptor::CreateIntro() throw (CoreException) { IIntroPart::Pointer intro(element->CreateExecutableExtension( WorkbenchRegistryConstants::ATT_CLASS)); if (intro.IsNull()) { intro = element->CreateExecutableExtension( WorkbenchRegistryConstants::ATT_CLASS, IIntroPart::GetManifestName()); } return intro; } IntroContentDetector::Pointer IntroDescriptor::GetIntroContentDetector() throw (CoreException) { std::string val; if (!element->GetAttribute(WorkbenchRegistryConstants::ATT_CONTENT_DETECTOR, val)) { return IntroContentDetector::Pointer(0); } IntroContentDetector::Pointer detector( element->CreateExecutableExtension( WorkbenchRegistryConstants::ATT_CONTENT_DETECTOR)); if (detector.IsNull()) { // support legacy BlueBerry extensions detector = element->CreateExecutableExtension( WorkbenchRegistryConstants::ATT_CONTENT_DETECTOR, IntroContentDetector::GetManifestName()); } return detector; } int IntroDescriptor::GetRole() const { std::string role; if (!element->GetAttribute(WorkbenchRegistryConstants::ATT_ROLE, role)) { return IntroConstants::INTRO_ROLE_VIEW; } if (role == "editor") return IntroConstants::INTRO_ROLE_EDITOR; else return IntroConstants::INTRO_ROLE_VIEW; } std::string IntroDescriptor::GetId() const { std::string id; element->GetAttribute(WorkbenchRegistryConstants::ATT_ID, id); return id; } std::string IntroDescriptor::GetPluginId() const { return element->GetContributor(); } ImageDescriptor::Pointer IntroDescriptor::GetImageDescriptor() const { if (imageDescriptor) { return imageDescriptor; } std::string iconName; if (!element->GetAttribute(WorkbenchRegistryConstants::ATT_ICON, iconName)) { return ImageDescriptor::Pointer(); } imageDescriptor = AbstractUIPlugin::ImageDescriptorFromPlugin( element->GetContributor(), iconName); return imageDescriptor; } IConfigurationElement::Pointer IntroDescriptor::GetConfigurationElement() const { return element; } std::string IntroDescriptor::GetLabelOverride() const { std::string label; element->GetAttribute(WorkbenchRegistryConstants::ATT_LABEL, label); return label; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIntroDescriptor.h b/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIntroDescriptor.h index 9787b85146..d526f05135 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIntroDescriptor.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIntroDescriptor.h @@ -1,91 +1,91 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYINTRODESCRIPTOR_H_ #define BERRYINTRODESCRIPTOR_H_ #include "berryIIntroDescriptor.h" -#include "../../intro/berryIntroContentDetector.h" -#include "../../intro/berryIIntroPart.h" +#include "intro/berryIntroContentDetector.h" +#include "intro/berryIIntroPart.h" #include #include namespace berry { /** * Describes an introduction extension. * */ class IntroDescriptor: public IIntroDescriptor { private: IConfigurationElement::Pointer element; mutable ImageDescriptor::Pointer imageDescriptor; public: berryObjectMacro(IntroDescriptor) /** * Create a new IntroDescriptor for an extension. */ IntroDescriptor(IConfigurationElement::Pointer configElement) throw (CoreException); /* * @see IIntroDescriptor#CreateIntro() */ IIntroPart::Pointer CreateIntro() throw (CoreException); IntroContentDetector::Pointer GetIntroContentDetector() throw (CoreException); int GetRole() const; /* * @see IIntroDescriptor#GetId() */ std::string GetId() const; std::string GetPluginId() const; /* * @see IIntroDescriptor#GetImageDescriptor() */ ImageDescriptor::Pointer GetImageDescriptor() const; /** * Returns the configuration element. * * @return the configuration element */ IConfigurationElement::Pointer GetConfigurationElement() const; /* * @see IIntroDescriptor#GetLabelOverride() */ std::string GetLabelOverride() const; }; } #endif /* BERRYINTRODESCRIPTOR_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIntroRegistry.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIntroRegistry.cpp index 320f942b66..9afe0230a0 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIntroRegistry.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryIntroRegistry.cpp @@ -1,173 +1,173 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryIntroRegistry.h" #include "berryIConfigurationElement.h" #include "berryIntroDescriptor.h" -#include "../berryRegistryReader.h" -#include "../berryWorkbenchPlugin.h" +#include "internal/berryRegistryReader.h" +#include "internal/berryWorkbenchPlugin.h" namespace berry { const std::string IntroRegistry::TAG_INTRO = "intro"; const std::string IntroRegistry::TAG_INTROPRODUCTBINDING = "introProductBinding"; const std::string IntroRegistry::ATT_INTROID = "introId"; const std::string IntroRegistry::ATT_PRODUCTID = "productId"; std::string IntroRegistry::GetIntroForProduct( const std::string& targetProductId, const std::vector& extensions) const { for (std::size_t i = 0; i < extensions.size(); i++) { std::vector elements( extensions[i] ->GetConfigurationElements()); for (std::size_t j = 0; j < elements.size(); j++) { if (elements[j]->GetName() == TAG_INTROPRODUCTBINDING) { std::string introId; bool hasIntroId = elements[j]->GetAttribute(ATT_INTROID, introId); std::string productId; bool hasProductId = elements[j]->GetAttribute(ATT_PRODUCTID, productId); if (!hasIntroId || !hasProductId) { //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$ */ WorkbenchPlugin::Log( elements[j]->GetDeclaringExtension()->GetNamespace() + ": 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()); } std::vector IntroRegistry::GetIntros() const { const IExtensionPoint* point = Platform::GetExtensionPointService()->GetExtensionPoint( PlatformUI::PLUGIN_ID + "." + WorkbenchRegistryConstants::PL_INTRO); if (!point) { return std::vector(); } std::vector extensions(point->GetExtensions()); extensions = RegistryReader::OrderExtensions(extensions); std::vector list; for (std::size_t i = 0; i < extensions.size(); i++) { std::vector elements( extensions[i] ->GetConfigurationElements()); for (std::size_t 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 (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 std::string& targetProductId) const { const IExtensionPoint* point = Platform::GetExtensionPointService()->GetExtensionPoint( PlatformUI::PLUGIN_ID + "." + WorkbenchRegistryConstants::PL_INTRO); if (!point) { return IIntroDescriptor::Pointer(); } std::vector extensions(point->GetExtensions()); extensions = RegistryReader::OrderExtensions(extensions); std::string targetIntroId = GetIntroForProduct(targetProductId, extensions); if (targetIntroId.empty()) { return IIntroDescriptor::Pointer(); } IIntroDescriptor::Pointer descriptor; std::vector intros(GetIntros()); for (std::size_t i = 0; i < intros.size(); i++) { if (intros[i]->GetId() == targetIntroId) { descriptor = intros[i]; break; } } return descriptor; } IIntroDescriptor::Pointer IntroRegistry::GetIntro(const std::string& id) const { std::vector intros(GetIntros()); for (std::size_t 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/src/internal/intro/berryViewIntroAdapterPart.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryViewIntroAdapterPart.cpp index fcb741c7d2..a7f71d91f6 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryViewIntroAdapterPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryViewIntroAdapterPart.cpp @@ -1,122 +1,122 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryViewIntroAdapterPart.h" #include "berryIntroPartAdapterSite.h" -#include "../berryWorkbench.h" -#include "../berryWorkbenchPlugin.h" +#include "internal/berryWorkbench.h" +#include "internal/berryWorkbenchPlugin.h" namespace berry { ViewIntroAdapterPart::ViewIntroAdapterPart() : propChangeListener(new PropertyChangeIntAdapter(this, &ViewIntroAdapterPart::PropertyChange)) { } void ViewIntroAdapterPart::SetStandby(bool standby) { // final Control control = ((PartSite) getSite()).getPane().getControl(); // BusyIndicator.showWhile(control.getDisplay(), new Runnable() { // public void run() { // try { // control.setRedraw(false); introPart->StandbyStateChanged(standby); // } finally { // control.setRedraw(true); // } // // setBarVisibility(standby); // } // }); } void ViewIntroAdapterPart::CreatePartControl(void* parent) { //addPaneListener(); introPart->CreatePartControl(parent); } ViewIntroAdapterPart::~ViewIntroAdapterPart() { //setBarVisibility(true); introPart->RemovePropertyListener(propChangeListener); GetSite()->GetWorkbenchWindow()->GetWorkbench()->GetIntroManager()->CloseIntro( introPart); } void* ViewIntroAdapterPart::GetTitleImage() { return introPart->GetTitleImage(); } std::string ViewIntroAdapterPart::GetPartName() { // this method is called eagerly before our init method is called (and // therefore before our intropart is created). By default return // the view title from the view declaration. We will fire a property // change to set the title to the proper value in the init method. return introPart.IsNull() ? ViewPart::GetPartName() : introPart->GetPartName(); } void ViewIntroAdapterPart::Init(IViewSite::Pointer site, IMemento::Pointer memento) throw (PartInitException) { ViewPart::Init(site); Workbench* workbench = dynamic_cast(site->GetWorkbenchWindow()->GetWorkbench()); try { introPart = workbench->GetWorkbenchIntroManager() ->CreateNewIntroPart(); // reset the part name of this view to be that of the intro title SetPartName(introPart->GetPartName()); introPart->AddPropertyListener(propChangeListener); introSite = IIntroSite::Pointer(new IntroPartAdapterSite(site, workbench->GetIntroDescriptor())); introPart->Init(introSite, memento); } catch (CoreException& e) { //TODO IStatus // WorkbenchPlugin.log( // IntroMessages.Intro_could_not_create_proxy, // new Status(IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, // IStatus.ERROR, IntroMessages.Intro_could_not_create_proxy, e)); WorkbenchPlugin::Log("Could not create intro view proxy.", e); } } void ViewIntroAdapterPart::PropertyChange(Object::Pointer /*source*/, int propId) { FirePropertyChange(propId); } void ViewIntroAdapterPart::SetFocus() { introPart->SetFocus(); } void ViewIntroAdapterPart::SaveState(IMemento::Pointer memento) { introPart->SaveState(memento); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryWorkbenchIntroManager.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryWorkbenchIntroManager.cpp index 7cc5a5bc14..d42f70641b 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryWorkbenchIntroManager.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/internal/intro/berryWorkbenchIntroManager.cpp @@ -1,347 +1,347 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryWorkbenchIntroManager.h" #include "berryIntroConstants.h" -#include "../berryWorkbench.h" -#include "../berryWorkbenchPage.h" -#include "../berryWorkbenchPlugin.h" -#include "../berryPerspective.h" -#include "../berryNullEditorInput.h" +#include "internal/berryWorkbench.h" +#include "internal/berryWorkbenchPage.h" +#include "internal/berryWorkbenchPlugin.h" +#include "internal/berryPerspective.h" +#include "internal/berryNullEditorInput.h" namespace berry { void WorkbenchIntroManager::CreateIntro( SmartPointer preferredWindow) { IIntroDescriptor::Pointer descr = this->workbench->GetIntroDescriptor(); if (!descr) { return; } IWorkbenchPage::Pointer workbenchPage = preferredWindow->GetActivePage(); if (!workbenchPage) { return; } try { if (IntroIsView()) { workbenchPage->ShowView(IntroConstants::INTRO_VIEW_ID); } else { IEditorInput::Pointer input(new NullEditorInput()); workbenchPage->OpenEditor(input, IntroConstants::INTRO_EDITOR_ID); } } catch (PartInitException& e) { //TODO IStatus // WorkbenchPlugin::Log(IntroMessages.Intro_could_not_create_part, new Status( // IStatus.ERROR, WorkbenchPlugin.PI_WORKBENCH, IStatus.ERROR, // IntroMessages.Intro_could_not_create_part, e)); WorkbenchPlugin::Log("Could not create intro part.", e); } } bool WorkbenchIntroManager::IntroIsView() const { IIntroDescriptor::Pointer descr = this->workbench->GetIntroDescriptor(); if (descr) { return descr->GetRole() == IntroConstants::INTRO_ROLE_VIEW; } return true; } WorkbenchIntroManager::WorkbenchIntroManager(Workbench* workbench) : workbench(workbench) { // workbench.getExtensionTracker().registerHandler(new IExtensionChangeHandler(){ // // /* (non-Javadoc) // * @see org.eclipse.core.runtime.dynamicHelpers.IExtensionChangeHandler#addExtension(org.eclipse.core.runtime.dynamicHelpers.IExtensionTracker, org.eclipse.core.runtime.IExtension) // */ // public void addExtension(IExtensionTracker tracker,IExtension extension) { // //Do nothing // } // // /* (non-Javadoc) // * @see org.eclipse.core.runtime.dynamicHelpers.IExtensionChangeHandler#removeExtension(org.eclipse.core.runtime.IExtension, java.lang.Object[]) // */ // public void removeExtension(IExtension source, Object[] objects) { // for (int i = 0; i < objects.length; i++) { // if (objects[i] instanceof IIntroPart) { // closeIntro((IIntroPart) objects[i]); // } // } // // }}, null); } bool WorkbenchIntroManager::CloseIntro(IIntroPart::Pointer part) { if (!introPart || introPart != part) { return false; } IWorkbenchPart::Pointer introView = GetIntroAdapterPart(); if (introView) { //assumption is that there is only ever one intro per workbench //if we ever support one per window then this will need revisiting IWorkbenchPage::Pointer page = introView->GetSite()->GetPage(); if (IntroIsView()) { IViewReference::Pointer reference = page->FindViewReference( IntroConstants::INTRO_VIEW_ID); page->HideView(introView.Cast()); if (!reference || reference->GetPart(false) == 0) { introPart = 0; return true; } return false; } else { std::vector references(page->FindEditors(IEditorInput::Pointer(0), IntroConstants::INTRO_EDITOR_ID, IWorkbenchPage::MATCH_ID)); poco_assert(references.size() < 2); if (references.empty()) return false; if (page->CloseEditors(std::list(references.begin(), references.end()), false)) { introPart = 0; return true; } return false; } } // if there is no part then null our reference introPart = 0; return true; } IIntroPart::Pointer WorkbenchIntroManager::ShowIntro(SmartPointer< IWorkbenchWindow> preferredWindow, bool standby) { if (!preferredWindow) { preferredWindow = this->workbench->GetActiveWorkbenchWindow(); } if (!preferredWindow) { return IIntroPart::Pointer(0); } IWorkbenchPart::Pointer part = GetIntroAdapterPart(); if (!part) { CreateIntro(preferredWindow); } else { try { IWorkbenchPage::Pointer page = part->GetSite()->GetPage(); IWorkbenchWindow::Pointer window = page->GetWorkbenchWindow(); if (window != preferredWindow) { window->GetShell()->SetActive(); } if (IntroIsView()) { page->ShowView(IntroConstants::INTRO_VIEW_ID); } else { IEditorInput::Pointer input(new NullEditorInput()); page->OpenEditor(input, IntroConstants::INTRO_EDITOR_ID); } } catch (PartInitException& e) { //TODO IStatus // WorkbenchPlugin::Log("Could not open intro", new Status(IStatus.ERROR, // WorkbenchPlugin.PI_WORKBENCH, IStatus.ERROR, "Could not open intro", // e)); //$NON-NLS-1$ //$NON-NLS-2$ WorkbenchPlugin::Log("Could not open intro", e); } } SetIntroStandby(introPart, standby); return introPart; } bool WorkbenchIntroManager::IsIntroInWindow( SmartPointer testWindow) const { IWorkbenchPart::Pointer part = GetIntroAdapterPart(); if (!part) { return false; } IWorkbenchWindow::Pointer window = part->GetSite()->GetWorkbenchWindow(); if (window == testWindow) { return true; } return false; } void WorkbenchIntroManager::SetIntroStandby(IIntroPart::Pointer part, bool /*standby*/) { if (!introPart || introPart != part) { return; } IWorkbenchPart::Pointer introPart = GetIntroAdapterPart(); if (!introPart) { return; } // PartPane::Pointer pane = viewIntroAdapterPart->GetSite().Cast()->GetPane(); // if (standby == !pane.isZoomed()) // { // // the zoom state is already correct - just update the part's state. // viewIntroAdapterPart.setStandby(standby); // return; // } // // viewIntroAdapterPart.getSite().getPage().toggleZoom(pane.getPartReference()); } bool WorkbenchIntroManager::IsIntroStandby(IIntroPart::Pointer part) const { if (!introPart || introPart != part) { return false; } IWorkbenchPart::Pointer introPart = GetIntroAdapterPart(); if (!introPart) { return false; } //return !((PartSite) introPart.getSite()).getPane().isZoomed(); return false; } IIntroPart::Pointer WorkbenchIntroManager::GetIntro() const { return introPart; } IWorkbenchPart::Pointer WorkbenchIntroManager::GetIntroAdapterPart() const { std::vector windows(this->workbench->GetWorkbenchWindows()); for (std::size_t i = 0; i < windows.size(); i++) { IWorkbenchWindow::Pointer window = windows[i]; WorkbenchPage::Pointer page = window->GetActivePage().Cast(); if (!page) { continue; } if (IntroIsView()) { std::vector perspDescs(page->GetOpenPerspectives()); for (std::size_t j = 0; j < perspDescs.size(); j++) { IPerspectiveDescriptor::Pointer descriptor = perspDescs[j]; IViewReference::Pointer reference = page->FindPerspective(descriptor)->FindView( IntroConstants::INTRO_VIEW_ID); if (reference) { return reference->GetView(false); } } } else { std::vector references(page->FindEditors(IEditorInput::Pointer(0), IntroConstants::INTRO_EDITOR_ID, IWorkbenchPage::MATCH_ID)); poco_assert(references.size() < 2); if (references.size() == 1) return references.front()->GetEditor(false); } } return IWorkbenchPart::Pointer(0); } IIntroPart::Pointer WorkbenchIntroManager::CreateNewIntroPart() throw (CoreException) { IntroDescriptor::Pointer introDescriptor(workbench->GetIntroDescriptor()); introPart = (introDescriptor == 0 ? IIntroPart::Pointer(0) : introDescriptor->CreateIntro()); // if (introPart) // { // workbench.getExtensionTracker().registerObject( // introDescriptor.getConfigurationElement() .getDeclaringExtension(), // introPart, IExtensionTracker.REF_WEAK); // } return introPart; } bool WorkbenchIntroManager::HasIntro() const { return workbench->GetIntroDescriptor() != 0; } bool WorkbenchIntroManager::IsNewContentAvailable() { IntroDescriptor::Pointer introDescriptor = workbench->GetIntroDescriptor(); if (!introDescriptor) { return false; } try { IntroContentDetector::Pointer contentDetector = introDescriptor->GetIntroContentDetector(); if (contentDetector) { return contentDetector->IsNewContentAvailable(); } } catch (CoreException& ex) { //TODO IStatus // WorkbenchPlugin.log(new Status(IStatus.WARNING, // WorkbenchPlugin.PI_WORKBENCH, IStatus.WARNING, // "Could not load intro content detector", ex)); //$NON-NLS-1$ WorkbenchPlugin::Log("Could not load intro content detector", ex); } return false; } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/intro/berryIntroPart.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/intro/berryIntroPart.cpp index 6e25896802..239127fec1 100644 --- a/BlueBerry/Bundles/org.blueberry.ui/src/intro/berryIntroPart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/intro/berryIntroPart.cpp @@ -1,190 +1,190 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryIntroPart.h" #include #include #include #include -#include "../util/berrySafeRunnable.h" -#include "../internal/berryWorkbenchRegistryConstants.h" +#include "util/berrySafeRunnable.h" +#include "internal/berryWorkbenchRegistryConstants.h" namespace berry { class PropChangedRunnable: public SafeRunnable { public: berryObjectMacro(PropChangedRunnable) IPropertyChangeListener::Events::EventType::AbstractDelegate* delegate; PropChangedRunnable(PropertyChangeEvent::Pointer event) : event(event) { } void Run() { delegate->Execute(event); } private: PropertyChangeEvent::Pointer event; }; std::string IntroPart::GetDefaultTitle() const { return "Welcome"; } void IntroPart::FirePropertyChange(int propertyId) { ObjectInt::Pointer val(new ObjectInt(propertyId)); Object::Pointer source(this); PropertyChangeEvent::Pointer event(new PropertyChangeEvent(source, IWorkbenchPartConstants::INTEGER_PROPERTY, val, val)); typedef IPropertyChangeListener::Events::EventType::ListenerList ListenerList; PropChangedRunnable::Pointer runnable(new PropChangedRunnable(event)); const ListenerList& listeners = propChangeEvents.propertyChange.GetListeners(); for (ListenerList::const_iterator iter = listeners.begin(); iter != listeners.end(); ++iter) { runnable->delegate = *iter; SafeRunner::Run(runnable); } } IConfigurationElement::Pointer IntroPart::GetConfigurationElement() { return configElement; } void* IntroPart::GetDefaultImage() const { return 0; } void IntroPart::SetSite(IIntroSite::Pointer site) { this->partSite = site; } void IntroPart::SetTitleImage(void* titleImage) { //Do not send changes if they are the same if (this->titleImage == titleImage) { return; } this->titleImage = titleImage; FirePropertyChange(IWorkbenchPartConstants::PROP_TITLE); } void IntroPart::SetTitle(const std::string& titleLabel) { if (this->titleLabel == titleLabel) return; this->titleLabel = titleLabel; FirePropertyChange(IWorkbenchPartConstants::PROP_TITLE); } void IntroPart::AddPropertyListener(IPropertyChangeListener::Pointer l) { propChangeEvents.AddListener(l); } IntroPart::~IntroPart() { } IIntroSite::Pointer IntroPart::GetIntroSite() const { return partSite; } void* IntroPart::GetTitleImage() const { if (titleImage != 0) { return titleImage; } return GetDefaultImage(); } std::string IntroPart::GetPartName() const { if (!titleLabel.empty()) { return titleLabel; } return GetDefaultTitle(); } void IntroPart::Init(IIntroSite::Pointer site, IMemento::Pointer /*memento*/) throw (PartInitException) { SetSite(site); } void IntroPart::RemovePropertyListener(IPropertyChangeListener::Pointer l) { propChangeEvents.RemoveListener(l); } void IntroPart::SaveState(IMemento::Pointer /*memento*/) { //no-op } void IntroPart::SetInitializationData(IConfigurationElement::Pointer cfig, const std::string& /*propertyName*/, Object::Pointer /*data*/) { // Save config element. configElement = cfig; cfig->GetAttribute(WorkbenchRegistryConstants::ATT_LABEL, titleLabel); // Icon. std::string strIcon; if (!cfig->GetAttribute(WorkbenchRegistryConstants::ATT_ICON, strIcon)) { return; } imageDescriptor = AbstractUIPlugin::ImageDescriptorFromPlugin( configElement->GetContributor(), strIcon); if (!imageDescriptor) { return; } titleImage = imageDescriptor->CreateImage(true); } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIPresentablePart.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIPresentablePart.cpp index bbd0935d63..260e225dc1 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIPresentablePart.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIPresentablePart.cpp @@ -1,39 +1,39 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryIPresentablePart.h" -#include "../berryIWorkbenchPartConstants.h" +#include "berryIWorkbenchPartConstants.h" namespace berry { const int IPresentablePart::PROP_DIRTY = IWorkbenchPartConstants::PROP_DIRTY; const int IPresentablePart::PROP_INPUT = IWorkbenchPartConstants::PROP_INPUT; const int IPresentablePart::PROP_TITLE = IWorkbenchPartConstants::PROP_TITLE; const int IPresentablePart::PROP_CONTENT_DESCRIPTION = IWorkbenchPartConstants::PROP_CONTENT_DESCRIPTION; const int IPresentablePart::PROP_PART_NAME = IWorkbenchPartConstants::PROP_PART_NAME; const int IPresentablePart::PROP_BUSY = 0x92; const int IPresentablePart::PROP_TOOLBAR = 0x93; const int IPresentablePart::PROP_HIGHLIGHT_IF_BACK = 0x94; const int IPresentablePart::PROP_PANE_MENU = 0x302; const int IPresentablePart::PROP_PREFERRED_SIZE = IWorkbenchPartConstants::PROP_PREFERRED_SIZE; } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIPresentablePart.h b/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIPresentablePart.h index 9a6265d3cc..13e213e1a2 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIPresentablePart.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIPresentablePart.h @@ -1,268 +1,268 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYIPRESENTABLEPART_H_ #define BERRYIPRESENTABLEPART_H_ #include -#include "../berryISizeProvider.h" -#include "../berryRectangle.h" -#include "../berryIPropertyChangeListener.h" +#include "berryISizeProvider.h" +#include "berryRectangle.h" +#include "berryIPropertyChangeListener.h" namespace berry { /** * This is a skin's interface to the contents of a view or editor. Note that this * is essentially the same as IWorkbenchPart, except it does not provide access * to lifecycle events and allows repositioning of the part. * * Not intended to be implemented by clients. * * @since 3.0 * @since 3.4 now extends {@link org.blueberry.ui.ISizeProvider} * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI IPresentablePart : public Object, public ISizeProvider { berryInterfaceMacro(IPresentablePart, berry); /** * The property id for isDirty. */ static const int PROP_DIRTY; // = IWorkbenchPartConstants.PROP_DIRTY; /** * The property id for getEditorInput. */ static const int PROP_INPUT; // = IWorkbenchPartConstants.PROP_INPUT; /** * The property id for getTitle, getTitleImage * and getTitleToolTip. */ static const int PROP_TITLE; // = IWorkbenchPartConstants.PROP_TITLE; /** * The property id for IWorkbenchPart2.getContentDescription() */ static const int PROP_CONTENT_DESCRIPTION; // = IWorkbenchPartConstants.PROP_CONTENT_DESCRIPTION; /** * The property id for IWorkbenchPart2.getContentDescription() */ static const int PROP_PART_NAME; // = IWorkbenchPartConstants.PROP_PART_NAME; /** * The property id for isBusy. */ static const int PROP_BUSY; // = 0x92; /** * The property id for toolbar changes */ static const int PROP_TOOLBAR; // = 0x93; /** * The property id for highlighting the * part if it is not in front. */ static const int PROP_HIGHLIGHT_IF_BACK; // = 0x94; /** * The property id for pane menu changes */ static const int PROP_PANE_MENU; // = 0x302; /** * The property id for preferred size changes * @since 3.4 */ static const int PROP_PREFERRED_SIZE; // = IWorkbenchPartConstants.PROP_PREFERRED_SIZE; /** * Sets the bounds of this part. * * @param bounds bounding rectangle (not null) */ virtual void SetBounds(const Rectangle& bounds) = 0; /** * Notifies the part whether or not it is visible in the current * perspective. A part is visible iff any part of its widgetry can * be seen. * * @param isVisible true if the part has just become visible, false * if the part has just become hidden */ virtual void SetVisible(bool isVisible) = 0; /** * Forces this part to have focus. */ virtual void SetFocus() = 0; /** * Adds a listener for changes to properties of this workbench part. * Has no effect if an identical listener is already registered. *

    * The properties ids are defined by the PROP_* constants, above. *

    * * @param listener a property listener (not null) */ virtual void AddPropertyListener(IPropertyChangeListener::Pointer listener) = 0; /** * Remove a listener that was previously added using addPropertyListener. * * @param listener a property listener (not null) */ virtual void RemovePropertyListener(IPropertyChangeListener::Pointer listener) = 0; /** * Returns the short name of the part. This is used as the text on * the tab when this part is stacked on top of other parts. * * @return the short name of the part (not null) */ virtual std::string GetName() const = 0; /** * Returns the title of this workbench part. If this value changes * the part must fire a property listener event with * PROP_TITLE. *

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

    * * @return the workbench part title (not null) */ virtual std::string GetTitle() const = 0; /** * Returns the status message from the part's title, or the empty string if none. * This is a substring of the part's title. A typical title will consist of * the part name, a separator, and a status message describing the current contents. *

    * Presentations can query getName() and getTitleStatus() if they want to display * the status message and name separately, or they can use getTitle() if they want * to display the entire title. *

    * * @return the status message or the empty string if none (not null) */ virtual std::string GetTitleStatus() const = 0; /** * Returns the title image of this workbench part. If this value changes * the part must fire a property listener event with * PROP_TITLE. *

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

    * * @return the title image */ virtual void* GetTitleImage() = 0; /** * Returns the title tool tip text of this workbench part. 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 std::string GetTitleToolTip() const = 0; /** * Returns true iff the contents of this part have changed recently. For * editors, this indicates that the part has changed since the last save. * For views, this indicates that the view contains interesting changes * that it wants to draw the user's attention to. * * @return true iff the part is dirty */ virtual bool IsDirty() const = 0; /** * Return true if the the receiver is currently in a busy state. * @return boolean true if busy */ virtual bool IsBusy() const = 0; /** * Returns true iff this part can be closed * * @return true iff this part can be closed * @since 3.1 */ virtual bool IsCloseable() const = 0; /** * Returns the local toolbar for this part, or null if this part does not * have a local toolbar. Callers must not dispose or downcast the return value. * * @return the local toolbar for the part, or null if none */ virtual void* GetToolBar() = 0; /** * Returns the menu for this part or null if none * * @return the menu for this part or null if none */ //virtual IPartMenu getMenu(); /** * Returns an SWT control that can be used to indicate the tab order for * this part. This can be returned as part of the result to * {@link StackPresentation#getTabList(IPresentablePart)}. Any other use of this control is * unsupported. This may return a placeholder control that is only * meaningful in the context of getTabList. * * @return the part's control (not null) */ virtual void* GetControl() = 0; /** * Get a property from the part's arbitrary property set. *

    * Note: this is a different set of properties than the ones covered * by the PROP_* constants. *

    * * @param key * The property key to retrieve. Must not be null. * @return the property, or null if that property is not set. * @since 3.3 */ virtual std::string GetPartProperty(const std::string& key) const = 0; }; } #endif /* BERRYIPRESENTABLEPART_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIPresentationFactory.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIPresentationFactory.cpp index 0957998c5c..b30b6ef8b0 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIPresentationFactory.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIPresentationFactory.cpp @@ -1,30 +1,30 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryIPresentationFactory.h" -#include "../berryConstants.h" +#include "berryConstants.h" namespace berry { int IPresentationFactory::SASHTYPE_NORMAL = 0; int IPresentationFactory::SASHTYPE_FLOATING = 1 << 1; int IPresentationFactory::SASHORIENTATION_HORIZONTAL = Constants::HORIZONTAL; // 1<<8 int IPresentationFactory::SASHORIENTATION_VERTICAL = Constants::VERTICAL; // 1<<9 } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIStackPresentationSite.h b/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIStackPresentationSite.h index 31aa0d4230..0b7b8a9d64 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIStackPresentationSite.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryIStackPresentationSite.h @@ -1,192 +1,192 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYISTACKPRESENTATIONSITE_H_ #define BERRYISTACKPRESENTATIONSITE_H_ #include #include #include "berryIPresentablePart.h" #include -#include "../berryPoint.h" +#include "berryPoint.h" namespace berry { /** * Represents the main interface between a StackPresentation and the workbench. * * Not intended to be implemented by clients. * * @since 3.0 * @noimplement This interface is not intended to be implemented by clients. */ struct BERRY_UI IStackPresentationSite : public Object { berryInterfaceMacro(IStackPresentationSite, berry); static int STATE_MINIMIZED; // = 0; static int STATE_MAXIMIZED; // = 1; static int STATE_RESTORED; // = 2; /** * Sets the state of the container. Called by the presentation when the * user causes the the container to be minimized, maximized, etc. * * @param newState one of the STATE_* constants */ virtual void SetState(int newState) = 0; /** * Returns the current state of the site (one of the STATE_* constants) * * @return the current state of the site (one of the STATE_* constants) */ virtual int GetState() = 0; /** * Returns true iff the site supports the given state * * @param state one of the STATE_* constants, above * @return true iff the site supports the given state */ virtual bool SupportsState(int state) = 0; /** * Begins dragging the given part * * @param beingDragged the part to drag (not null) * @param initialPosition the mouse position at the time of the initial mousedown * (display coordinates, not null) * @param keyboard true iff the drag was initiated via mouse dragging, * and false if the drag may be using the keyboard */ virtual void DragStart(IPresentablePart::Pointer beingDragged, Point& initialPosition, bool keyboard) = 0; /** * Closes the given set of parts. * * @param toClose the set of parts to close (Not null. All of the entries must be non-null) */ virtual void Close(const std::vector& toClose) = 0; /** * Begins dragging the entire stack of parts * * @param initialPosition the mouse position at the time of the initial mousedown (display coordinates, * not null) * @param keyboard true iff the drag was initiated via mouse dragging, * and false if the drag may be using the keyboard */ virtual void DragStart(Point& initialPosition, bool keyboard) = 0; /** * Returns true iff this site will allow the given part to be closed * * @param toClose part to test (not null) * @return true iff the part may be closed */ virtual bool IsCloseable(IPresentablePart::Pointer toClose) = 0; /** * Returns true iff the given part can be dragged. If this * returns false, the given part should not trigger a drag. * * @param toMove part to test (not null) * @return true iff this part is a valid drag source */ virtual bool IsPartMoveable(IPresentablePart::Pointer toMove) = 0; /** * Returns true iff this entire stack can be dragged * * @return true iff the stack can be dragged */ virtual bool IsStackMoveable() = 0; /** * Makes the given part active * * @param toSelect */ virtual void SelectPart(IPresentablePart::Pointer toSelect) = 0; /** * Returns the currently selected part or null if the stack is empty * * @return the currently selected part or null if the stack is empty */ virtual IPresentablePart::Pointer GetSelectedPart() = 0; /** * Adds system actions to the given menu manager. The site may * make use of the following group ids: *
      *
    • close, for close actions
    • *
    • size, for resize actions
    • *
    • misc, for miscellaneous actions
    • *
    * The presentation can control the insertion position by creating * these group IDs where appropriate. * * @param menuManager the menu manager to populate */ //virtual void AddSystemActions(IMenuManager menuManager); /** * Notifies the workbench that the preferred size of the presentation has * changed. Hints to the workbench that it should trigger a layout at the * next opportunity. * * @since 3.1 */ virtual void FlushLayout() = 0; /** * Returns the list of presentable parts currently in this site * * @return the list of presentable parts currently in this site * @since 3.1 */ virtual std::list GetPartList() = 0; /** * Returns the property with the given id or null. Folder * properties are an extensible mechanism for perspective authors to * customize the appearance of view stacks. The list of customizable * properties is determined by the presentation factory, and set in the * perspective factory. * * @param id * Must not be null. * @return property value, or null if the property is not * set. * @since 3.3 */ virtual std::string GetProperty(const std::string& id) = 0; }; } #endif /* BERRYISTACKPRESENTATIONSITE_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryStackDropResult.h b/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryStackDropResult.h index 1dd1efbb43..9a5be8a933 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryStackDropResult.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryStackDropResult.h @@ -1,80 +1,80 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYSTACKDROPRESULT_H_ #define BERRYSTACKDROPRESULT_H_ #include #include -#include "../berryRectangle.h" +#include "berryRectangle.h" namespace berry { /** * This structure describes a drop event that will cause a dragged part * to be stacked in a position currently occupied by another part. * */ class BERRY_UI StackDropResult : public Object { public: berryObjectMacro(StackDropResult); private: Rectangle snapRectangle; Object::Pointer cookie; public: /** * Creates a drop result * * @param snapRectangle region that should be highlighted by the tracking * rectangle (display coordinates) * @param cookie the presentation may attach an object to this drop result * in order to identify the drop location. This object will be passed back into the * presentation's add method. */ StackDropResult(const Rectangle& snapRectangle, Object::Pointer cookie); /** * Returns a rectangle (screen coordinates) describing the target location * for this drop operation. While dragging, the tracking rectangle will * snap to this position. * * @return a snap rectangle (not null) */ Rectangle GetSnapRectangle(); /** * Returns the cookie for this drop result. This object provided by the presentation, * but is remembered by the workbench. It will be given back to the presentation's add * method to indicate that a part is being added as a result of a drop operation. * * @return the drop cookie for this drop result */ Object::Pointer GetCookie(); }; } #endif /* BERRYSTACKDROPRESULT_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryStackPresentation.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryStackPresentation.cpp index 37344b51fe..db49d22fb1 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryStackPresentation.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryStackPresentation.cpp @@ -1,106 +1,106 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryStackPresentation.h" -#include "../berryConstants.h" +#include "berryConstants.h" namespace berry { const int StackPresentation::AS_INACTIVE = 0; const int StackPresentation::AS_ACTIVE_FOCUS = 1; const int StackPresentation::AS_ACTIVE_NOFOCUS = 2; StackPresentation::StackPresentation(IStackPresentationSite::Pointer stackSite) : site(stackSite) { poco_assert(stackSite.IsNotNull()); } StackPresentation::~StackPresentation() { // Do not remove empty destructor. Otherwise, the WeakPointer member "site" // will be destroyed in a strange way and the destruction of a DefaultStackPresentationSite // instance will notify the WeakPointer "site" (although it was destroyed, the // DefaultStackPresentationSite somehow still has a MessageDelegate for the destroy // event, pointing to the destroyed "site"). } IStackPresentationSite::Pointer StackPresentation::GetSite() { return site.Lock(); } Point StackPresentation::ComputeMinimumSize() { return Point(0, 0); } int StackPresentation::GetSizeFlags(bool /*width*/) { bool hasMaximumSize = this->GetSite()->GetState() == IStackPresentationSite::STATE_MINIMIZED; return Constants::MIN | (hasMaximumSize ? Constants::MAX : 0); } int StackPresentation::ComputePreferredSize(bool width, int /*availableParallel*/, int /*availablePerpendicular*/, int preferredResult) { Point p = this->ComputeMinimumSize(); int minSize = width ? p.x : p.y; if (this->GetSite()->GetState() == IStackPresentationSite::STATE_MINIMIZED || preferredResult < minSize) { return minSize; } return preferredResult; } void StackPresentation::MovePart(IPresentablePart::Pointer toMove, Object::Pointer cookie) { this->RemovePart(toMove); this->AddPart(toMove, cookie); if (this->GetSite()->GetSelectedPart() == toMove) { this->SelectPart(toMove); toMove->SetFocus(); } } void StackPresentation::SaveState(IPresentationSerializer* /*context*/, IMemento::Pointer /*memento*/) { } void StackPresentation::RestoreState(IPresentationSerializer* /*context*/, IMemento::Pointer /*memento*/) { } void StackPresentation::ShowPartList() { } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryStackPresentation.h b/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryStackPresentation.h index ac48da6624..f0407185f8 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryStackPresentation.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/presentations/berryStackPresentation.h @@ -1,276 +1,276 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYSTACKPRESENTATION_H_ #define BERRYSTACKPRESENTATION_H_ #include #include #include "berryIStackPresentationSite.h" #include "berryIPresentationSerializer.h" #include "berryStackDropResult.h" -#include "../berryISizeProvider.h" -#include "../berryIMemento.h" +#include "berryISizeProvider.h" +#include "berryIMemento.h" namespace berry { /** * This represents an object that can supply trim around a IPresentablePart. * Clients can implement subclasses to provide the appearance for editor workbooks, * view folders, fast views, and detached windows. *

    * StackPresentations do not store any persistent state and cannot * directly make changes to the workbench. They are given an IStackPresentationSite * reference on creation, which allows them to send events and requests to the workbench. * However, the workbench is free to ignore these requests. The workbench will call one * of the public methods on StackPresentation when (and if) the presentation is expected to * change state. *

    *

    * For example, if the user clicks a button that is intended to close a part, the * StackPresentation will send a close request to its site, but should not assume * that the part has been closed until the workbench responds with a call * StackPresentation.remove. *

    * * @since 3.0 */ class BERRY_UI StackPresentation : public Object, public ISizeProvider { public: berryObjectMacro(StackPresentation); private: /** * The presentation site. */ IStackPresentationSite::WeakPtr site; protected: /** * Constructs a new stack presentation with the given site. * * @param stackSite the stack site */ StackPresentation(IStackPresentationSite::Pointer stackSite); ~StackPresentation(); /** * Returns the presentation site (not null). * @return IStackPresentationSite */ IStackPresentationSite::Pointer GetSite(); public: /** * Inactive state. This is the default state for deselected presentations. */ static const int AS_INACTIVE; // = 0; /** * Activation state indicating that one of the parts in the presentation currently has focus */ static const int AS_ACTIVE_FOCUS; // = 1; /** * Activation state indicating that none of the parts in the presentation have focus, but * one of the parts is being used as the context for global menus and toolbars */ static const int AS_ACTIVE_NOFOCUS; // = 2; /** * Sets the bounding rectangle for this presentation. * * @param bounds new bounding rectangle (not null) */ virtual void SetBounds(const Rectangle& bounds) = 0; /** * Returns the minimum size for this stack. The stack is prevented * from being resized smaller than this amount, and this is used as * the default size for the stack when it is minimized. Typically, * this is the amount of space required to fit the minimize, close, * and maximize buttons and one tab. * * @return the minimum size for this stack (not null) * * @deprecated replaced by computePreferredSize */ virtual Point ComputeMinimumSize(); /* * @see ISizeProvider#getSizeFlags(boolean) */ virtual int GetSizeFlags(bool width); /* * @see ISizeProvider#computePreferredSize(boolean, int, int, int) */ virtual int ComputePreferredSize(bool width, int availableParallel, int availablePerpendicular, int preferredResult); /** * This is invoked to notify the presentation that its activation * state has changed. StackPresentations can have three possible activation * states (see the AS_* constants above) * * @param newState one of AS_INACTIVE, AS_ACTIVE, or AS_ACTIVE_NOFOCUS */ virtual void SetActive(int newState) = 0; /** * This causes the presentation to become visible or invisible. * When a presentation is invisible, it must not respond to user * input or modify its parts. For example, a presentations will * be made invisible if it belongs to a perspective and the user * switches to another perspective. * * @param isVisible the state to set visibility to * * @since 3.0 */ virtual void SetVisible(bool isVisible) = 0; /** * Sets the state of the presentation. That is, notifies the presentation * that is has been minimized, maximized, or restored. Note that this method * is the only way that a presentation is allowed to change its state. *

    * If a presentation wishes to minimize itself, it must call setState * on its associated IStackPresentationSite. If the site chooses to respond * to the state change, it will call this method at the correct time. * The presentation should not call this method directly. *

    * * @param state one of the IStackPresentationSite.STATE_* constants. */ virtual void SetState(int state) = 0; /** * Returns the control for this presentation * * @return the control for this presentation (not null) */ virtual void* GetControl() = 0; /** * Adds the given part to the stack. The presentation is free to determine * where the part should be inserted. If the part is being inserted as the * result of a drag/drop operation, it will be given a cookie * identifying the drop location. Has no effect if an identical part is * already in the presentation. * * @param newPart the new part to add (not null) * @param cookie an identifier for a drop location, or null. When the presentation * attaches a cookie to a StackDropResult, that cookie is passed back into * addPart when a part is actually dropped in that location. */ virtual void AddPart(IPresentablePart::Pointer newPart, Object::Pointer cookie) = 0; /** * Removes the given part from the stack. * * @param oldPart the part to remove (not null) */ virtual void RemovePart(IPresentablePart::Pointer oldPart) = 0; /** * Moves a part to a new location as the result of a drag/drop * operation within this presentation. * * @param toMove a part that already belongs to this presentation * @param cookie a drop cookie returned by StackPresentation#dragOver * @since 3.1 */ virtual void MovePart(IPresentablePart::Pointer toMove, Object::Pointer cookie); /** * Brings the specified part to the foreground. This should not affect * the current focus. * * @param toSelect the new active part (not null) */ virtual void SelectPart(IPresentablePart::Pointer toSelect) = 0; /** * This method is invoked whenever a part is dragged over the stack's control. * It returns a StackDropResult if and only if the part may be dropped in this * location. * * @param currentControl the control being dragged over * @param location cursor location (display coordinates) * @return a StackDropResult or null if the presentation does not have * a drop target in this location. */ virtual StackDropResult::Pointer DragOver(void* currentControl, const Point& location) = 0; /** * Instructs the presentation to display the system menu * */ // virtual void ShowSystemMenu() = 0; /** * Instructs the presentation to display the pane menu */ // virtual void ShowPaneMenu() = 0; /** * Instructs the presentation to display a list of all parts in the stack, and * allow the user to change the selection using the keyboard. */ virtual void ShowPartList(); /** * Saves the state of this presentation to the given memento. * * @param context object that can be used to generate unique IDs for IPresentableParts (this * may be a temporary object - the presentation should not keep any references to it) * @param memento memento where the data will be saved */ virtual void SaveState(IPresentationSerializer* context, IMemento::Pointer memento); /** * Restores the state of this presentation to a previously saved state. * * @param context object that can be used to find IPresentableParts given string IDs (this * may be a temporary object - the presentation should not keep any references to it) * @param memento memento where the data will be saved */ virtual void RestoreState(IPresentationSerializer* context, IMemento::Pointer memento); /** * Returns the tab-key traversal order for the given IPresentablePart. * * @param part the part * @return the tab-key traversal order */ virtual std::vector GetTabList(IPresentablePart::Pointer part) = 0; }; } #endif /* BERRYSTACKPRESENTATION_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryDnDTweaklet.cpp b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryDnDTweaklet.cpp index e90f3b512e..ba770c4840 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryDnDTweaklet.cpp +++ b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryDnDTweaklet.cpp @@ -1,65 +1,65 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryDnDTweaklet.h" -#include "../berryConstants.h" +#include "berryConstants.h" namespace berry { Tweaklets::TweakKey DnDTweaklet::KEY = Tweaklets::TweakKey(); DnDTweaklet::CursorType DnDTweaklet::PositionToCursorType(int positionConstant) { if (positionConstant == Constants::LEFT) return CURSOR_LEFT; if (positionConstant == Constants::RIGHT) return CURSOR_RIGHT; if (positionConstant == Constants::TOP) return CURSOR_TOP; if (positionConstant == Constants::BOTTOM) return CURSOR_BOTTOM; if (positionConstant == Constants::CENTER) return CURSOR_CENTER; return CURSOR_INVALID; } int DnDTweaklet::CursorTypeToPosition(CursorType dragCursorId) { switch (dragCursorId) { case CURSOR_LEFT: return Constants::LEFT; case CURSOR_RIGHT: return Constants::RIGHT; case CURSOR_TOP: return Constants::TOP; case CURSOR_BOTTOM: return Constants::BOTTOM; case CURSOR_CENTER: return Constants::CENTER; default: return Constants::DEFAULT; } } } diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryDnDTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryDnDTweaklet.h index e7c4b85502..72328bb974 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryDnDTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryDnDTweaklet.h @@ -1,68 +1,68 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYDNDTWEAKLET_H_ #define BERRYDNDTWEAKLET_H_ #include #include -#include "../internal/berryTweaklets.h" +#include "internal/berryTweaklets.h" namespace berry { struct ITracker; /** * Provides the set of cursors used for drag-and-drop. */ struct BERRY_UI DnDTweaklet { static Tweaklets::TweakKey KEY; enum CursorType { CURSOR_INVALID, CURSOR_LEFT, CURSOR_RIGHT, CURSOR_TOP, CURSOR_BOTTOM, CURSOR_CENTER, CURSOR_OFFSCREEN, CURSOR_FASTVIEW}; static CursorType PositionToCursorType(int positionConstant); /** * Converts a DnDTweaklet::CursorType (CURSOR_LEFT, CURSOR_RIGHT, CURSOR_TOP, CURSOR_BOTTOM, CURSOR_CENTER) into a BlueBerry constant * (Constants::LEFT, Constants::RIGHT, Constants::TOP, Constants::BOTTOM, Constants::CENTER) * * @param dragCursorId * @return a BlueBerry Constants::* constant */ static int CursorTypeToPosition(CursorType dragCursorId); virtual ITracker* CreateTracker() = 0; }; } Q_DECLARE_INTERFACE(berry::DnDTweaklet, "org.blueberry.DnDTweaklet") #endif /* BERRYDNDTWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryGuiWidgetsTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryGuiWidgetsTweaklet.h index 1fd16f42e6..3199911ea8 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryGuiWidgetsTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryGuiWidgetsTweaklet.h @@ -1,214 +1,214 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYGUIWIDGETSTWEAKLET_H_ #define BERRYGUIWIDGETSTWEAKLET_H_ #include -#include "../internal/berryTweaklets.h" -#include "../guitk/berryGuiTkISelectionListener.h" -#include "../guitk/berryGuiTkIControlListener.h" -#include "../berryRectangle.h" -#include "../berryShell.h" - -//#include "../commands/berryIMenu.h" -//#include "../commands/berryIMenuItem.h" +#include "internal/berryTweaklets.h" +#include "guitk/berryGuiTkISelectionListener.h" +#include "guitk/berryGuiTkIControlListener.h" +#include "berryRectangle.h" +#include "berryShell.h" + +//#include "commands/berryIMenu.h" +//#include "commands/berryIMenuItem.h" namespace berry { struct BERRY_UI GuiWidgetsTweaklet { static Tweaklets::TweakKey KEY; virtual void AddSelectionListener(void* widget, GuiTk::ISelectionListener::Pointer listener) = 0; virtual void RemoveSelectionListener(void* widget, GuiTk::ISelectionListener::Pointer listener) = 0; /** * Adds the listener to the collection of listeners who will * be notified when the widget is moved or resized, by sending * it one of the messages defined in the IControlListener * interface. * * @param listener the listener which should be notified * * @see IControlListener * @see #RemoveControlListener */ virtual void AddControlListener(void* widget, GuiTk::IControlListener::Pointer listener) = 0; /** * Removes the listener from the collection of listeners who will * be notified when the widget is moved or resized. * * @param listener the listener which should no longer be notified * * @see IControlListener * @see #AddControlListener */ virtual void RemoveControlListener(void* widget, GuiTk::IControlListener::Pointer listener) = 0; virtual bool GetEnabled(void* widget) = 0; virtual void SetEnabled(void* widget, bool enabled) = 0; virtual void SetBounds(void* widget, const Rectangle& bounds) = 0; virtual Rectangle GetBounds(void* widget) = 0; virtual void SetVisible(void* widget, bool visible) = 0; virtual bool GetVisible(void* widget) = 0; virtual bool IsVisible(void* widget) = 0; virtual Rectangle GetClientArea(void* widget) = 0; virtual void* GetParent(void* widget) = 0; virtual bool SetParent(void* widget, void* parent) = 0; virtual void SetData(void* widget, const std::string& id, Object::Pointer data) = 0; virtual Object::Pointer GetData(void* widget, const std::string& id) = 0; virtual Point GetCursorLocation() = 0; virtual void* GetCursorControl() = 0; virtual void* FindControl(const std::vector& shells, const Point& location) = 0; /** * Determines if one control is a child of another. Returns true iff the second * argument is a child of the first (or the same object). * * @param potentialParent * @param childToTest * @return */ virtual bool IsChild(void* potentialParent, void* childToTest) = 0; /** * Returns the control which currently has keyboard focus, * or null if keyboard events are not currently going to * any of the controls built by the currently running * application. * * @return the control under the cursor */ virtual void* GetFocusControl() = 0; virtual bool IsReparentable(void* widget) = 0; virtual void MoveAbove(void* widgetToMove, void* widget) = 0; virtual void MoveBelow(void* widgetToMove, void* widget) = 0; virtual void Dispose(void* widget) = 0; virtual Shell::Pointer CreateShell(Shell::Pointer parent, int style) = 0; virtual void DisposeShell(Shell::Pointer shell) = 0; virtual void* CreateComposite(void* parent) = 0; virtual std::vector GetShells() = 0; virtual Shell::Pointer GetShell(void* widget) = 0; virtual Shell::Pointer GetActiveShell() = 0; // command framework interface classes //virtual IMenu::Pointer CreateMenu(void*, IMenu::Style = IMenu::POP_UP) = 0; //virtual IMenu::Pointer CreateMenu(IMenu::Pointer parent) = 0; //virtual IMenuItem::Pointer CreateMenuItem(IMenu::Pointer, IMenuItem::Style, int index = -1) = 0; /** * @brief returns the coordinates of the center point of the primary screen * (where the application starts) of the current desktop. * * @param i the number of the screen (if there are multiple). If i = -1 * a rectangle representing the size of the virtual desktop is returned. * @return the screen Geometry. * @see GetScreenNumber() * @see GetPrimaryScreenNumber() */ virtual Rectangle GetScreenSize(int i = -1) = 0; virtual Rectangle GetAvailableScreenSize(int i = -1) = 0; virtual int GetClosestScreenNumber(const Rectangle&) = 0; /** * @brief Gets the number of available screens in a multi-screen environment. * * @return the number of available screens in a multi-screen environment. */ virtual unsigned int GetScreenNumber() = 0; /** * @brief Gets the number of the primary screen. * * @return the number of the primary screen. */ virtual int GetPrimaryScreenNumber() = 0; /** * Converts the given rectangle from display coordinates to the local coordinate system * of the given object * * @param coordinateSystem local coordinate system (widget) being converted to * @param toConvert rectangle to convert * @return a rectangle in control coordinates * @since 3.0 */ virtual Rectangle ToControl(void* coordinateSystem, const Rectangle& toConvert) = 0; /** * Converts the given point from display coordinates to the local coordinate system * of the given object * * @param coordinateSystem local coordinate system (widget) being converted to * @param toConvert point to convert * @return a point in control coordinates * @since 3.0 */ virtual Point ToControl(void* coordinateSystem, const Point& toConvert) = 0; /** * Converts the given rectangle from the local coordinate system of the given object * into display coordinates. * * @param coordinateSystem local coordinate system (widget) being converted from * @param toConvert rectangle to convert * @return a rectangle in display coordinates * @since 3.0 */ virtual Rectangle ToDisplay(void* coordinateSystem, const Rectangle& toConvert) = 0; /** * Converts the given point from the local coordinate system of the given object * into display coordinates. * * @param coordinateSystem local coordinate system (widget) being converted from * @param toConvert point to convert * @return a point in display coordinates * @since 3.0 */ virtual Point ToDisplay(void* coordinateSystem, const Point& toConvert) = 0; }; } Q_DECLARE_INTERFACE(berry::GuiWidgetsTweaklet, "org.blueberry.GuiWidgetsTweaklet") #endif /* BERRYGUIWIDGETSTWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryITracker.h b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryITracker.h index da5d203d9b..a66c0a6391 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryITracker.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryITracker.h @@ -1,56 +1,56 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYITRACKER_H_ #define BERRYITRACKER_H_ #include "berryDnDTweaklet.h" -#include "../berryRectangle.h" -#include "../guitk/berryGuiTkIControlListener.h" +#include "berryRectangle.h" +#include "guitk/berryGuiTkIControlListener.h" namespace berry { /** * Instances of this class implement a rubber banding rectangle that is * drawn onto a parent control or display. * These rectangles can be specified to respond to mouse and key events * by either moving or resizing themselves accordingly. Trackers are * typically used to represent window geometries in a lightweight manner. * */ struct ITracker { virtual ~ITracker() {} virtual Rectangle GetRectangle() = 0; virtual void SetRectangle(const Rectangle& rectangle) = 0; virtual void SetCursor(DnDTweaklet::CursorType cursor) = 0; virtual bool Open() = 0; virtual void AddControlListener(GuiTk::IControlListener::Pointer listener) = 0; virtual void RemoveControlListener(GuiTk::IControlListener::Pointer listener) = 0; }; } #endif /* BERRYITRACKER_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryImageTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryImageTweaklet.h index 0f87d631ce..013abaf066 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryImageTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryImageTweaklet.h @@ -1,49 +1,49 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYIMAGETWEAKLET_H_ #define BERRYIMAGETWEAKLET_H_ #include -#include "../internal/berryTweaklets.h" -#include "../berryImageDescriptor.h" +#include "internal/berryTweaklets.h" +#include "berryImageDescriptor.h" #include namespace berry { /** * Provides the set of cursors used for drag-and-drop. */ struct BERRY_UI ImageTweaklet { static Tweaklets::TweakKey KEY; virtual SmartPointer CreateFromFile(const std::string& filename, const std::string& pluginid) = 0; virtual SmartPointer CreateFromImage(void* img) = 0; virtual SmartPointer GetMissingImageDescriptor() = 0; virtual void DestroyImage(const void* img) = 0; }; } Q_DECLARE_INTERFACE(berry::ImageTweaklet, "org.blueberry.ImageTweaklet") #endif /* BERRYIMAGETWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryMessageDialogTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryMessageDialogTweaklet.h index 4f153f068e..302b5bbc7f 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryMessageDialogTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryMessageDialogTweaklet.h @@ -1,158 +1,158 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYMESSAGEDIALOGTWEAKLET_H_ #define BERRYMESSAGEDIALOGTWEAKLET_H_ #include -#include "../berryShell.h" +#include "berryShell.h" -#include "../dialogs/berryIDialog.h" -#include "../internal/berryTweaklets.h" +#include "dialogs/berryIDialog.h" +#include "internal/berryTweaklets.h" #include #include #include namespace berry { /** * A dialog for showing messages to the user. */ struct BERRY_UI MessageDialogTweaklet { static Tweaklets::TweakKey KEY; /** * Convenience method to open a simple confirm (OK/Cancel) dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message * @return true if the user presses the OK button, * false otherwise */ virtual bool OpenConfirm(Shell::Pointer parent, const std::string& title, const std::string& message) = 0; /** * Convenience method to open a standard error dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message */ virtual void OpenError(Shell::Pointer parent, const std::string& title, const std::string& message) = 0; /** * Convenience method to open a standard information dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message */ virtual void OpenInformation(Shell::Pointer parent, const std::string& title, const std::string& message) = 0; /** * Convenience method to open a simple Yes/No question dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message * @return true if the user presses the OK button, * false otherwise */ virtual bool OpenQuestion(Shell::Pointer parent, const std::string& title, const std::string& message) = 0; /** * Convenience method to open a standard warning dialog. * * @param parent * the parent shell of the dialog, or null if none * @param title * the dialog's title, or null if none * @param message * the message */ virtual void OpenWarning(Shell::Pointer parent, const std::string& title, const std::string& message) = 0; /** * Create a message dialog. Note that the dialog will have no visual * representation (no widgets) until it is told to open. *

    * The labels of the buttons to appear in the button bar are supplied in * this constructor as an array. The open method will return * the index of the label in this array corresponding to the button that was * pressed to close the dialog. If the dialog was dismissed without pressing * a button (ESC, etc.) then -1 is returned. Note that the open * method blocks. *

    * * @param parentShell * the parent shell * @param dialogTitle * the dialog title, or null if none * @param dialogTitleImage * the dialog title image, or null if none * @param dialogMessage * the dialog message * @param dialogImageType * one of the following values: *
      *
    • IDialog::NONE for a dialog with no * image
    • *
    • IDialog::ERR for a dialog with an * error image
    • *
    • IDialog::INFORMATION for a dialog * with an information image
    • *
    • IDialog::QUESTION for a dialog with a * question image
    • *
    • IDialog::WARNING for a dialog with a * warning image
    • *
    * @param dialogButtonLabels * an array of labels for the buttons in the button bar * @param defaultIndex * the index in the button label array of the default button */ virtual IDialog::Pointer MessageDialog(Shell::Pointer parentShell, const std::string& dialogTitle, void* dialogTitleImage, const std::string& dialogMessage, int dialogImageType, const std::vector& dialogButtonLabels, int defaultIndex) = 0; }; } Q_DECLARE_INTERFACE(berry::MessageDialogTweaklet, "org.blueberry.MessageDialogTweaklet") #endif /* BERRYMESSAGEDIALOGTWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchPageTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchPageTweaklet.h index 9cf9f808ef..4cec36389c 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchPageTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchPageTweaklet.h @@ -1,45 +1,45 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWORKBENCHPAGETWEAKLET_H_ #define BERRYWORKBENCHPAGETWEAKLET_H_ -#include "../internal/berryTweaklets.h" -#include "../berryIWorkbenchPage.h" +#include "internal/berryTweaklets.h" +#include "berryIWorkbenchPage.h" namespace berry { struct BERRY_UI WorkbenchPageTweaklet { static Tweaklets::TweakKey KEY; virtual void* CreateClientComposite(void* pageControl) = 0; virtual void* CreatePaneControl(void* parent) = 0; virtual Object::Pointer CreateStatusPart(void* parent, const std::string& title, const std::string& msg) = 0; virtual IEditorPart::Pointer CreateErrorEditorPart(const std::string& partName, const std::string& msg) = 0; }; } Q_DECLARE_INTERFACE(berry::WorkbenchPageTweaklet, "org.blueberry.WorkbenchPageTweaklet") #endif /* BERRYWORKBENCHPAGETWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchTweaklet.h b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchTweaklet.h index 26bdfb63ae..bfb321d0ce 100755 --- a/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchTweaklet.h +++ b/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchTweaklet.h @@ -1,54 +1,54 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef BERRYWORKBENCHTWEAKLET_H_ #define BERRYWORKBENCHTWEAKLET_H_ -#include "../internal/berryTweaklets.h" +#include "internal/berryTweaklets.h" -#include "../berryShell.h" -#include "../berryDisplay.h" -#include "../dialogs/berryIDialog.h" +#include "berryShell.h" +#include "berryDisplay.h" +#include "dialogs/berryIDialog.h" namespace berry { class WorkbenchWindow; struct BERRY_UI WorkbenchTweaklet { static Tweaklets::TweakKey KEY; static const std::string DIALOG_ID_SHOW_VIEW; // = "org.blueberry.ui.dialogs.showview"; virtual Display* CreateDisplay() = 0; virtual bool IsRunning() = 0; virtual SmartPointer CreateWorkbenchWindow(int number) = 0; virtual IDialog::Pointer CreateStandardDialog(const std::string& id) = 0; }; } Q_DECLARE_INTERFACE(berry::WorkbenchTweaklet, "org.blueberry.WorkbenchTweaklet") #endif /* BERRYWORKBENCHTWEAKLET_H_ */ diff --git a/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.cpp b/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.cpp index 04c3df5882..26983b2a14 100644 --- a/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.cpp +++ b/BlueBerry/Bundles/org.blueberry.uitest/src/harness/berryUITestCase.cpp @@ -1,269 +1,269 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryUITestCase.h" #include #include -#include "../util/berryEmptyPerspective.h" +#include "util/berryEmptyPerspective.h" #ifdef BLUEBERRY_DEBUG_SMARTPOINTER #include #endif namespace berry { IAdaptable* UITestCase::GetPageInput() { return 0; } UITestCase::UITestCase(const std::string& testName) : TestCase(testName) { // ErrorDialog.NO_UI = true; fWorkbench = PlatformUI::GetWorkbench(); } void UITestCase::failexc(const std::string& message, const std::exception& e, long lineNumber, const std::string& fileName) { //TODO IStatus // If the exception is a CoreException with a multistatus // then print out the multistatus so we can see all the info. // if (e instanceof CoreException) { // IStatus status = ((CoreException) e).getStatus(); // write(status, 0); // } else // e.printStackTrace(); fail(message + ": " + e.what(), lineNumber, fileName); } IWorkbenchWindow::Pointer UITestCase::OpenTestWindow() { return OpenTestWindow(EmptyPerspective::PERSP_ID); } IWorkbenchWindow::Pointer UITestCase::OpenTestWindow( const std::string& perspectiveId) { try { IWorkbenchWindow::Pointer window = fWorkbench->OpenWorkbenchWindow( perspectiveId, GetPageInput()); WaitOnShell(window->GetShell()); return window; } catch (WorkbenchException& e) { failmsg(e.displayText()); return IWorkbenchWindow::Pointer(0); } } void UITestCase::CloseAllTestWindows() { std::list::iterator i = testWindows.begin(); while (!testWindows.empty()) { testWindows.back()->Close(); testWindows.pop_back(); } } IWorkbenchPage::Pointer UITestCase::OpenTestPage(IWorkbenchWindow::Pointer /*win*/) { // IWorkbenchPage[] pages = openTestPage(win, 1); // if (pages != null) // return pages[0]; // else return IWorkbenchPage::Pointer(0); } std::vector UITestCase::OpenTestPage( IWorkbenchWindow::Pointer /*win*/, int /*pageTotal*/) { // try { // IWorkbenchPage[] pages = new IWorkbenchPage[pageTotal]; // IAdaptable input = getPageInput(); // // for (int i = 0; i < pageTotal; i++) { // pages[i] = win.openPage(EmptyPerspective.PERSP_ID, input); // } // return pages; // } catch (WorkbenchException e) { // fail(); // return null; // } return std::vector(); } void UITestCase::CloseAllPages(IWorkbenchWindow::Pointer /*window*/) { // IWorkbenchPage[] pages = window.getPages(); // for (int i = 0; i < pages.length; i++) // pages[i].close(); } void UITestCase::Trace(const std::string& msg) { std::cerr << msg << std::endl; } void UITestCase::setUp() { Trace("----- " + this->name()); Trace(this->name() + ": setUp..."); AddWindowListener(); berry::TestCase::setUp(); } void UITestCase::DoSetUp() { // do nothing. } void UITestCase::tearDown() { Trace(this->name() + ": tearDown...\n"); RemoveWindowListener(); berry::TestCase::tearDown(); } void UITestCase::DoTearDown() { ProcessEvents(); CloseAllTestWindows(); ProcessEvents(); } void UITestCase::ProcessEvents() { // Display display = PlatformUI.getWorkbench().getDisplay(); // if (display != null) // while (display.readAndDispatch()) // ; } void UITestCase::ManageWindows(bool manage) { windowListener->SetEnabled(manage); } IWorkbench* UITestCase::GetWorkbench() { return fWorkbench; } UITestCase::TestWindowListener::TestWindowListener(std::list< IWorkbenchWindow::Pointer>& testWindows) : enabled(true), testWindows(testWindows) { } void UITestCase::TestWindowListener::SetEnabled(bool enabled) { this->enabled = enabled; } void UITestCase::TestWindowListener::WindowActivated( IWorkbenchWindow::Pointer /*window*/) { // do nothing } void UITestCase::TestWindowListener::WindowDeactivated( IWorkbenchWindow::Pointer /*window*/) { // do nothing } void UITestCase::TestWindowListener::WindowClosed( IWorkbenchWindow::Pointer window) { if (enabled) testWindows.remove(window); } void UITestCase::TestWindowListener::WindowOpened( IWorkbenchWindow::Pointer window) { if (enabled) testWindows.push_back(window); } void UITestCase::Indent(std::ostream& output, unsigned int indent) { for (unsigned int i = 0; i < indent; i++) output << " "; } // void UITestCase::Write(IStatus status, unsigned int indent) { // PrintStream output = System.out; // indent(output, indent); // output.println("Severity: " + status.getSeverity()); // // indent(output, indent); // output.println("Plugin ID: " + status.getPlugin()); // // indent(output, indent); // output.println("Code: " + status.getCode()); // // indent(output, indent); // output.println("Message: " + status.getMessage()); // // if (status.getException() != null) { // indent(output, indent); // output.print("Exception: "); // status.getException().printStackTrace(output); // } // // if (status.isMultiStatus()) { // IStatus[] children = status.getChildren(); // for (int i = 0; i < children.length; i++) // write(children[i], indent + 1); // } // } void UITestCase::AddWindowListener() { windowListener = new TestWindowListener(testWindows); fWorkbench->AddWindowListener(windowListener); } void UITestCase::RemoveWindowListener() { if (windowListener) { fWorkbench->RemoveWindowListener(windowListener); } } void UITestCase::WaitOnShell(Shell::Pointer /*shell*/) { ProcessEvents(); // long endTime = System.currentTimeMillis() + 5000; // // while (shell.getDisplay().getActiveShell() != shell // && System.currentTimeMillis() < endTime) { // processEvents(); // } } } diff --git a/BlueBerry/Bundles/org.blueberry.uitest/src/internal/berryPluginActivator.cpp b/BlueBerry/Bundles/org.blueberry.uitest/src/internal/berryPluginActivator.cpp index d32cab4c90..7f87a6ecd1 100644 --- a/BlueBerry/Bundles/org.blueberry.uitest/src/internal/berryPluginActivator.cpp +++ b/BlueBerry/Bundles/org.blueberry.uitest/src/internal/berryPluginActivator.cpp @@ -1,46 +1,46 @@ /*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryPluginActivator.h" -#include "../berryUITestApplication.h" -#include "../util/berryEmptyPerspective.h" +#include "berryUITestApplication.h" +#include "util/berryEmptyPerspective.h" #include namespace berry { org_blueberry_uitest_Activator::org_blueberry_uitest_Activator() { } void org_blueberry_uitest_Activator::start(ctkPluginContext* context) { BERRY_REGISTER_EXTENSION_CLASS(UITestApplication, context) BERRY_REGISTER_EXTENSION_CLASS(EmptyPerspective, context) } void org_blueberry_uitest_Activator::stop(ctkPluginContext* context) { Q_UNUSED(context) } } Q_EXPORT_PLUGIN2(org_blueberry_uitest, berry::org_blueberry_uitest_Activator)