diff options
51 files changed, 3699 insertions, 3372 deletions
diff --git a/dbaccess/source/core/api/query.cxx b/dbaccess/source/core/api/query.cxx index a3a66290d5b51..eda2c1ac8c14d 100644 --- a/dbaccess/source/core/api/query.cxx +++ b/dbaccess/source/core/api/query.cxx @@ -430,6 +430,12 @@ void OQuery::registerProperties() } // ----------------------------------------------------------------------------- +::rtl::OUString OQuery::determineContentType() const +{ + return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "application/vnd.org.openoffice.DatabaseQuery" ) ); +} + +// ----------------------------------------------------------------------------- //........................................................................ } // namespace dbaccess //........................................................................ diff --git a/dbaccess/source/core/api/query.hxx b/dbaccess/source/core/api/query.hxx index 2055100e71793..dd200764d364d 100644 --- a/dbaccess/source/core/api/query.hxx +++ b/dbaccess/source/core/api/query.hxx @@ -169,6 +169,9 @@ protected: virtual void rebuildColumns( ); + // OContentHelper overridables + virtual ::rtl::OUString determineContentType() const; + private: void registerProperties(); }; diff --git a/dbaccess/source/core/api/querycontainer.cxx b/dbaccess/source/core/api/querycontainer.cxx index 00ce37c4191e5..89124a9751c95 100644 --- a/dbaccess/source/core/api/querycontainer.cxx +++ b/dbaccess/source/core/api/querycontainer.cxx @@ -387,6 +387,13 @@ void SAL_CALL OQueryContainer::disposing( const ::com::sun::star::lang::EventObj ODefinitionContainer::disposing(_rSource); } } + +// ----------------------------------------------------------------------------- +::rtl::OUString OQueryContainer::determineContentType() const +{ + return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "application/vnd.org.openoffice.DatabaseQueryContainer" ) ); +} + // ----------------------------------------------------------------------------- Reference< XContent > OQueryContainer::implCreateWrapper(const ::rtl::OUString& _rName) { diff --git a/dbaccess/source/core/dataaccess/ComponentDefinition.cxx b/dbaccess/source/core/dataaccess/ComponentDefinition.cxx index b26a7c46f9f9d..452931848e5c5 100644 --- a/dbaccess/source/core/dataaccess/ComponentDefinition.cxx +++ b/dbaccess/source/core/dataaccess/ComponentDefinition.cxx @@ -240,6 +240,15 @@ Reference< XPropertySetInfo > SAL_CALL OComponentDefinition::getPropertySetInfo( Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } + +// ----------------------------------------------------------------------------- +::rtl::OUString OComponentDefinition::determineContentType() const +{ + return m_bTable + ? ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "application/vnd.org.openoffice.DatabaseTable" ) ) + : ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "application/vnd.org.openoffice.DatabaseCommandDefinition" ) ); +} + // ----------------------------------------------------------------------------- Reference< XNameAccess> OComponentDefinition::getColumns() throw (RuntimeException) { diff --git a/dbaccess/source/core/dataaccess/ComponentDefinition.hxx b/dbaccess/source/core/dataaccess/ComponentDefinition.hxx index acf908ee762da..e6f49dbbcbe67 100644 --- a/dbaccess/source/core/dataaccess/ComponentDefinition.hxx +++ b/dbaccess/source/core/dataaccess/ComponentDefinition.hxx @@ -195,6 +195,10 @@ protected: virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw (::com::sun::star::uno::Exception); + + // OContentHelper overridables + virtual ::rtl::OUString determineContentType() const; + private: void registerProperties(); }; diff --git a/dbaccess/source/core/dataaccess/ContentHelper.cxx b/dbaccess/source/core/dataaccess/ContentHelper.cxx index e4c1d781d63bd..b43292aada371 100644 --- a/dbaccess/source/core/dataaccess/ContentHelper.cxx +++ b/dbaccess/source/core/dataaccess/ContentHelper.cxx @@ -159,9 +159,16 @@ Reference< XContentIdentifier > SAL_CALL OContentHelper::getIdentifier( ) throw // return Reference< XContentIdentifier >(); } // ----------------------------------------------------------------------------- -::rtl::OUString SAL_CALL OContentHelper::getContentType( ) throw (RuntimeException) +::rtl::OUString SAL_CALL OContentHelper::getContentType() throw (RuntimeException) { - return getImplementationName(); + ::osl::MutexGuard aGuard(m_aMutex); + + if ( !m_pImpl->m_aProps.aContentType ) + { // content type not yet retrieved + m_pImpl->m_aProps.aContentType.reset( determineContentType() ); + } + + return *m_pImpl->m_aProps.aContentType; } // ----------------------------------------------------------------------------- void SAL_CALL OContentHelper::addContentEventListener( const Reference< XContentEventListener >& _rxListener ) throw (RuntimeException) @@ -415,7 +422,7 @@ Sequence< Any > OContentHelper::setPropertyValues(const Sequence< PropertyValue try { - rename( aNewValue ); + impl_rename_throw( aNewValue ,false); OSL_ENSURE( m_pImpl->m_aProps.aTitle == aNewValue, "OContentHelper::setPropertyValues('Title'): rename did not work!" ); aEvent.NewValue = makeAny( aNewValue ); @@ -491,7 +498,7 @@ Reference< XRow > OContentHelper::getPropertyValues( const Sequence< Property >& if ( rProp.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "ContentType" ) ) ) { - xRow->appendString ( rProp, m_pImpl->m_aProps.aContentType ); + xRow->appendString ( rProp, getContentType() ); } else if ( rProp.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Title" ) ) ) { @@ -526,7 +533,7 @@ Reference< XRow > OContentHelper::getPropertyValues( const Sequence< Property >& getCppuType( static_cast< const rtl::OUString * >( 0 ) ), PropertyAttribute::BOUND | PropertyAttribute::READONLY ), - m_pImpl->m_aProps.aContentType ); + getContentType() ); xRow->appendString ( Property( rtl::OUString::createFromAscii( "Title" ), -1, @@ -669,42 +676,69 @@ void SAL_CALL OContentHelper::setParent( const Reference< XInterface >& _xParent } // ----------------------------------------------------------------------------- -void SAL_CALL OContentHelper::rename( const ::rtl::OUString& newName ) throw (SQLException, ElementExistException, RuntimeException) +void OContentHelper::impl_rename_throw(const ::rtl::OUString& _sNewName,bool _bNotify ) { - ::osl::MutexGuard aGuard(m_aMutex); - if ( newName.equals( m_pImpl->m_aProps.aTitle ) ) + osl::ClearableGuard< osl::Mutex > aGuard(m_aMutex); + if ( _sNewName.equals( m_pImpl->m_aProps.aTitle ) ) return; - - Reference<XNameContainer> xNameCont(m_xParentContainer,UNO_QUERY); - if ( xNameCont.is() ) + try { - if ( xNameCont->hasByName(newName) ) - throw ElementExistException(newName,*this); + Sequence< PropertyChangeEvent > aChanges( 1 ); - try - { - if ( xNameCont->hasByName(m_pImpl->m_aProps.aTitle) ) - xNameCont->removeByName(m_pImpl->m_aProps.aTitle); + aChanges[0].Source = static_cast< cppu::OWeakObject * >( this ); + aChanges[0].Further = sal_False; + aChanges[0].PropertyName = PROPERTY_NAME; + aChanges[0].PropertyHandle = PROPERTY_ID_NAME; + aChanges[0].OldValue <<= m_pImpl->m_aProps.aTitle; + aChanges[0].NewValue <<= _sNewName; - m_pImpl->m_aProps.aTitle = newName; - xNameCont->insertByName(m_pImpl->m_aProps.aTitle,makeAny(Reference<XContent>(*this,UNO_QUERY))); - notifyDataSourceModified(); - } - catch(IllegalArgumentException) - { - throw SQLException(); - } - catch(NoSuchElementException) - { - throw SQLException(); - } - catch(WrappedTargetException) - { - throw SQLException(); - } + aGuard.clear(); + + m_pImpl->m_aProps.aTitle = _sNewName; + if ( _bNotify ) + notifyPropertiesChange( aChanges ); + notifyDataSourceModified(); } - else - m_pImpl->m_aProps.aTitle = newName; + catch(const PropertyVetoException&) + { + throw ElementExistException(_sNewName,*this); + } +} +// ----------------------------------------------------------------------------- +void SAL_CALL OContentHelper::rename( const ::rtl::OUString& newName ) throw (SQLException, ElementExistException, RuntimeException) +{ + + impl_rename_throw(newName); + //Reference<XNameContainer> xNameCont(m_xParentContainer,UNO_QUERY); + //if ( xNameCont.is() ) + //{ + // if ( xNameCont->hasByName(newName) ) + // throw ElementExistException(newName,*this); + + // try + // { + // if ( xNameCont->hasByName(m_pImpl->m_aProps.aTitle) ) + // xNameCont->removeByName(m_pImpl->m_aProps.aTitle); + + // m_pImpl->m_aProps.aTitle = newName; + // xNameCont->insertByName(m_pImpl->m_aProps.aTitle,makeAny(Reference<XContent>(*this,UNO_QUERY))); + // notifyDataSourceModified(); + // } + // catch(IllegalArgumentException) + // { + // throw SQLException(); + // } + // catch(NoSuchElementException) + // { + // throw SQLException(); + // } + // catch(WrappedTargetException) + // { + // throw SQLException(); + // } + //} + //else + // m_pImpl->m_aProps.aTitle = newName; } // ----------------------------------------------------------------------------- diff --git a/dbaccess/source/core/dataaccess/commandcontainer.cxx b/dbaccess/source/core/dataaccess/commandcontainer.cxx index 0a7e0449b53e3..2c51a9b188692 100644 --- a/dbaccess/source/core/dataaccess/commandcontainer.cxx +++ b/dbaccess/source/core/dataaccess/commandcontainer.cxx @@ -69,7 +69,7 @@ OCommandContainer::OCommandContainer( const Reference< ::com::sun::star::lang::X ,const TContentPtr& _pImpl ,sal_Bool _bTables ) - :ODefinitionContainer(_xORB,_xParentContainer,_pImpl) + :ODefinitionContainer(_xORB,_xParentContainer,_pImpl,!_bTables) ,m_bTables(_bTables) { DBG_CTOR(OCommandContainer, NULL); @@ -106,6 +106,12 @@ Reference< XInterface > SAL_CALL OCommandContainer::createInstance( ) throw (Exc return m_aContext.createComponent( (::rtl::OUString)( m_bTables ? SERVICE_SDB_TABLEDEFINITION : SERVICE_SDB_COMMAND_DEFINITION ) ); } +// ----------------------------------------------------------------------------- +::rtl::OUString OCommandContainer::determineContentType() const +{ + return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "application/vnd.org.openoffice.DatabaseCommandDefinitionContainer" ) ); +} + //........................................................................ } // namespace dbaccess //........................................................................ diff --git a/dbaccess/source/core/dataaccess/commandcontainer.hxx b/dbaccess/source/core/dataaccess/commandcontainer.hxx index 19cd8e717a6b1..4015b1072470a 100644 --- a/dbaccess/source/core/dataaccess/commandcontainer.hxx +++ b/dbaccess/source/core/dataaccess/commandcontainer.hxx @@ -81,6 +81,10 @@ protected: // ODefinitionContainer virtual ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent > createObject(const ::rtl::OUString& _rName); + +protected: + // OContentHelper overridables + virtual ::rtl::OUString determineContentType() const; }; //........................................................................ diff --git a/dbaccess/source/core/dataaccess/commanddefinition.hxx b/dbaccess/source/core/dataaccess/commanddefinition.hxx index bd849f89e4645..6a50395d11ed7 100644 --- a/dbaccess/source/core/dataaccess/commanddefinition.hxx +++ b/dbaccess/source/core/dataaccess/commanddefinition.hxx @@ -132,6 +132,7 @@ public: // OPropertySetHelper DECLARE_PROPERTYCONTAINER_DEFAULTS( ); + private: // helper void registerProperties(); diff --git a/dbaccess/source/core/dataaccess/definitioncontainer.cxx b/dbaccess/source/core/dataaccess/definitioncontainer.cxx index 5b023dcaff4f8..01a3b65b5c8a7 100644 --- a/dbaccess/source/core/dataaccess/definitioncontainer.cxx +++ b/dbaccess/source/core/dataaccess/definitioncontainer.cxx @@ -144,11 +144,13 @@ DBG_NAME(ODefinitionContainer) ODefinitionContainer::ODefinitionContainer( const Reference< XMultiServiceFactory >& _xORB , const Reference< XInterface >& _xParentContainer , const TContentPtr& _pImpl + , bool _bCheckSlash ) :OContentHelper(_xORB,_xParentContainer,_pImpl) ,m_aApproveListeners(m_aMutex) ,m_aContainerListeners(m_aMutex) ,m_bInPropertyChange(sal_False) + ,m_bCheckSlash(_bCheckSlash) { m_pImpl->m_aProps.bIsDocument = sal_False; m_pImpl->m_aProps.bIsFolder = sal_True; @@ -645,7 +647,7 @@ void ODefinitionContainer::approveNewObject(const ::rtl::OUString& _sName,const *this, 0 ); - if ( _sName.indexOf( '/' ) != -1 ) + if ( m_bCheckSlash && _sName.indexOf( '/' ) != -1 ) throw IllegalArgumentException( m_aErrorHelper.getErrorMessage( ErrorCondition::DB_OBJECT_NAME_WITH_SLASHES ), *this, @@ -681,7 +683,7 @@ void ODefinitionContainer::approveNewObject(const ::rtl::OUString& _sName,const void SAL_CALL ODefinitionContainer::propertyChange( const PropertyChangeEvent& evt ) throw (RuntimeException) { ClearableMutexGuard aGuard(m_aMutex); - if(evt.PropertyName == (rtl::OUString) PROPERTY_NAME) + if(evt.PropertyName == (rtl::OUString) PROPERTY_NAME || evt.PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Title" ) )) { m_bInPropertyChange = sal_True; try @@ -708,7 +710,7 @@ void SAL_CALL ODefinitionContainer::vetoableChange( const PropertyChangeEvent& a { MutexGuard aGuard(m_aMutex); - if(aEvent.PropertyName == (rtl::OUString) PROPERTY_NAME) + if(aEvent.PropertyName == (rtl::OUString) PROPERTY_NAME || aEvent.PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "Title" ) ) ) { ::rtl::OUString sNewName; aEvent.NewValue >>= sNewName; @@ -725,7 +727,10 @@ void ODefinitionContainer::addObjectListener(const Reference< XContent >& _xNewO { xProp->addPropertyChangeListener(PROPERTY_NAME, this); xProp->addVetoableChangeListener(PROPERTY_NAME, this); - } + //::rtl::OUString sTitle(RTL_CONSTASCII_USTRINGPARAM( "Title" )); + //xProp->addPropertyChangeListener(sTitle, this); + //xProp->addVetoableChangeListener(sTitle, this); + } // if ( xProp.is() ) } // ----------------------------------------------------------------------------- void ODefinitionContainer::removeObjectListener(const Reference< XContent >& _xNewObject) @@ -736,6 +741,9 @@ void ODefinitionContainer::removeObjectListener(const Reference< XContent >& _xN { xProp->removePropertyChangeListener(PROPERTY_NAME, this); xProp->removeVetoableChangeListener(PROPERTY_NAME, this); + //::rtl::OUString sTitle(RTL_CONSTASCII_USTRINGPARAM( "Title" )); + //xProp->removePropertyChangeListener(sTitle, this); + //xProp->removeVetoableChangeListener(sTitle, this); } } // ----------------------------------------------------------------------------- diff --git a/dbaccess/source/core/dataaccess/documentcontainer.cxx b/dbaccess/source/core/dataaccess/documentcontainer.cxx index 859855b0bc0c9..6ccbb4d03a034 100644 --- a/dbaccess/source/core/dataaccess/documentcontainer.cxx +++ b/dbaccess/source/core/dataaccess/documentcontainer.cxx @@ -181,7 +181,12 @@ Sequence< ::rtl::OUString > SAL_CALL ODocumentContainer::getSupportedServiceName aSupported[0] = m_bFormsContainer ? SERVICE_NAME_FORM_COLLECTION : SERVICE_NAME_REPORT_COLLECTION; return aSupported; } + // ----------------------------------------------------------------------------- +::rtl::OUString ODocumentContainer::determineContentType() const +{ + return ::rtl::OUString(); +} //-------------------------------------------------------------------------- Reference< XContent > ODocumentContainer::createObject( const ::rtl::OUString& _rName) @@ -288,7 +293,7 @@ Reference< XInterface > SAL_CALL ODocumentContainer::createInstanceWithArguments } if ( ( aClassID.getLength() == 0 ) && ( 0 == sURL.getLength() ) ) - ODocumentDefinition::GetDocumentServiceFromMediaType( getContainerStorage(), sPersistentName, m_aContext.getLegacyServiceFactory(), aClassID ); + ODocumentDefinition::GetDocumentServiceFromMediaType( getContainerStorage(), sPersistentName, m_aContext, aClassID ); } ODefinitionContainer_Impl::const_iterator aFind = rDefinitions.find( sName ); diff --git a/dbaccess/source/core/dataaccess/documentcontainer.hxx b/dbaccess/source/core/dataaccess/documentcontainer.hxx index 888798495a0e6..b5c5a16e0383a 100644 --- a/dbaccess/source/core/dataaccess/documentcontainer.hxx +++ b/dbaccess/source/core/dataaccess/documentcontainer.hxx @@ -134,11 +134,16 @@ public: // helper ::rtl::Reference<OContentHelper> getContent(const ::rtl::OUString& _sName) const; - ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage> getContainerStorage() const; + ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > getContainerStorage() const; protected: virtual ~ODocumentContainer(); -// ODefinitionContainer + + /** OContentHelper + */ + virtual ::rtl::OUString determineContentType() const; + + // ODefinitionContainer virtual ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent > createObject( const ::rtl::OUString& _rName ); diff --git a/dbaccess/source/core/dataaccess/documentdefinition.cxx b/dbaccess/source/core/dataaccess/documentdefinition.cxx index db239fd116543..50c3083fbc9a1 100644 --- a/dbaccess/source/core/dataaccess/documentdefinition.cxx +++ b/dbaccess/source/core/dataaccess/documentdefinition.cxx @@ -283,13 +283,38 @@ namespace DatabaseObject = ::com::sun::star::sdb::application::DatabaseObject; #define DEFAULT_WIDTH 10000 #define DEFAULT_HEIGHT 7500 -//........................................................................ +//............................................................................. namespace dbaccess { -//........................................................................ +//............................................................................. typedef ::boost::optional< bool > optional_bool; + //========================================================================= + //= helper + //========================================================================= + namespace + { + // -------------------------------------------------------------------- + ::rtl::OUString lcl_determineContentType_nothrow( const Reference< XStorage >& _rxContainerStorage, + const ::rtl::OUString& _rEntityName ) + { + ::rtl::OUString sContentType; + try + { + Reference< XStorage > xContainerStorage( _rxContainerStorage, UNO_QUERY_THROW ); + ::utl::SharedUNOComponent< XPropertySet > xStorageProps( + xContainerStorage->openStorageElement( _rEntityName, ElementModes::READ ), UNO_QUERY_THROW ); + OSL_VERIFY( xStorageProps->getPropertyValue( INFO_MEDIATYPE ) >>= sContentType ); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION(); + } + return sContentType; + } + } + //================================================================== // OEmbedObjectHolder //================================================================== @@ -467,61 +492,47 @@ namespace dbaccess m_xParentContainer = _xParent; } -::rtl::OUString ODocumentDefinition::GetDocumentServiceFromMediaType( const Reference< XStorage >& xStorage - ,const ::rtl::OUString& sEntName - ,const Reference< XMultiServiceFactory >& _xORB - ,Sequence< sal_Int8 >& _rClassId - ) +// ----------------------------------------------------------------------------- +::rtl::OUString ODocumentDefinition::GetDocumentServiceFromMediaType( const Reference< XStorage >& _rxContainerStorage, + const ::rtl::OUString& _rEntityName, const ::comphelper::ComponentContext& _rContext, + Sequence< sal_Int8 >& _rClassId ) +{ + return GetDocumentServiceFromMediaType( + lcl_determineContentType_nothrow( _rxContainerStorage, _rEntityName ), + _rContext, _rClassId ); +} + +// ----------------------------------------------------------------------------- +::rtl::OUString ODocumentDefinition::GetDocumentServiceFromMediaType( const ::rtl::OUString& _rMediaType, + const ::comphelper::ComponentContext& _rContext, Sequence< sal_Int8 >& _rClassId ) { ::rtl::OUString sResult; try { - if ( xStorage->isStorageElement( sEntName ) ) + ::comphelper::MimeConfigurationHelper aConfigHelper( _rContext.getLegacyServiceFactory() ); + sResult = aConfigHelper.GetDocServiceNameFromMediaType( _rMediaType ); + _rClassId = aConfigHelper.GetSequenceClassIDRepresentation(aConfigHelper.GetExplicitlyRegisteredObjClassID( _rMediaType )); + if ( !_rClassId.getLength() && sResult.getLength() ) { - // the object must be based on storage - - Reference< XPropertySet > xPropSet( xStorage->openStorageElement( sEntName, ElementModes::READ ), UNO_QUERY_THROW ); - - ::rtl::OUString aMediaType; - try { - Any aAny = xPropSet->getPropertyValue( INFO_MEDIATYPE ); - aAny >>= aMediaType; - } - catch ( Exception& ) + Reference< XNameAccess > xObjConfig = aConfigHelper.GetObjConfiguration(); + if ( xObjConfig.is() ) { - } - ::comphelper::MimeConfigurationHelper aConfigHelper(_xORB); - sResult = aConfigHelper.GetDocServiceNameFromMediaType(aMediaType); - _rClassId = aConfigHelper.GetSequenceClassIDRepresentation(aConfigHelper.GetExplicitlyRegisteredObjClassID(aMediaType)); - if ( !_rClassId.getLength() && sResult.getLength() ) - { - Reference< XNameAccess > xObjConfig = aConfigHelper.GetObjConfiguration(); - if ( xObjConfig.is() ) + Sequence< ::rtl::OUString > aClassIDs = xObjConfig->getElementNames(); + for ( sal_Int32 nInd = 0; nInd < aClassIDs.getLength(); nInd++ ) { - try + Reference< XNameAccess > xObjectProps; + ::rtl::OUString aEntryDocName; + + if ( ( xObjConfig->getByName( aClassIDs[nInd] ) >>= xObjectProps ) && xObjectProps.is() + && ( xObjectProps->getByName(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ObjectDocumentServiceName")) + ) >>= aEntryDocName ) + && aEntryDocName.equals( sResult ) ) { - Sequence< ::rtl::OUString > aClassIDs = xObjConfig->getElementNames(); - for ( sal_Int32 nInd = 0; nInd < aClassIDs.getLength(); nInd++ ) - { - Reference< XNameAccess > xObjectProps; - ::rtl::OUString aEntryDocName; - - if ( ( xObjConfig->getByName( aClassIDs[nInd] ) >>= xObjectProps ) && xObjectProps.is() - && ( xObjectProps->getByName(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ObjectDocumentServiceName")) - ) >>= aEntryDocName ) - && aEntryDocName.equals( sResult ) ) - { - _rClassId = aConfigHelper.GetSequenceClassIDRepresentation(aClassIDs[nInd]); - break; - } - } + _rClassId = aConfigHelper.GetSequenceClassIDRepresentation(aClassIDs[nInd]); + break; } - catch( Exception& ) - {} } } - - ::comphelper::disposeComponent( xPropSet ); } } catch ( Exception& ) @@ -1030,8 +1041,8 @@ void ODocumentDefinition::onCommandOpenSomething( const Any& _rOpenArgument, con impl_onActivateEmbeddedObject(); } - // LLA: Alle fillReportData() calls prfen, sollte es welche geben, die danach noch viel machen - // LLA: sollten wir einen _aGuard Pointer bergeben, sonst erstmal als Referenz + // LLA: Alle fillReportData() calls prfen, sollte es welche geben, die danach noch viel machen + // LLA: sollten wir einen _aGuard Pointer bergeben, sonst erstmal als Referenz fillReportData(_aGuard); _out_rComponent <<= xModel; } @@ -1094,10 +1105,13 @@ Any SAL_CALL ODocumentDefinition::execute( const Command& aCommand, sal_Int32 Co Environment ); // Unreachable } - Reference< XStorage> xStorage(aIni[0],UNO_QUERY); + Reference< XStorage> xDest(aIni[0],UNO_QUERY); ::rtl::OUString sPersistentName; aIni[1] >>= sPersistentName; - loadEmbeddedObject( true ); + Reference< XStorage> xStorage = getContainerStorage(); + // ----------------------------------------------------------------------------- + xStorage->copyElementTo(m_pImpl->m_aProps.sPersistentName,xDest,sPersistentName); + /*loadEmbeddedObject( true ); Reference<XEmbedPersist> xPersist(m_xEmbeddedObject,UNO_QUERY); if ( xPersist.is() ) { @@ -1106,7 +1120,7 @@ Any SAL_CALL ODocumentDefinition::execute( const Command& aCommand, sal_Int32 Co m_xEmbeddedObject->changeState(EmbedStates::LOADED); } else - throw CommandAbortedException(); + throw CommandAbortedException();*/ } else if ( aCommand.Name.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "preview" ) ) ) { @@ -1529,7 +1543,15 @@ namespace // ----------------------------------------------------------------------------- sal_Bool ODocumentDefinition::objectSupportsEmbeddedScripts() const { - bool bAllowDocumentMacros = !m_pImpl->m_pDataSource || m_pImpl->m_pDataSource->hasAnyObjectWithMacros(); +// bool bAllowDocumentMacros = !m_pImpl->m_pDataSource || m_pImpl->m_pDataSource->hasAnyObjectWithMacros(); + // TODO: revert to the disabled code. The current version is just to be able + // to integrate an intermediate version of the CWS, which should behave as + // if no macros in DB docs are allowed + bool bAllowDocumentMacros = !m_pImpl->m_pDataSource->hasMacroStorages(); + // even if the current version is not able to create documents which contain macros, + // later versions will be. Such documents contain macro/script storages in the + // document root storage, in which case we need to disable the per-form/report + // scripting. // if *any* of the objects of the database document already has macros, we continue to allow it // to have them, until the user did a migration. @@ -1537,6 +1559,13 @@ sal_Bool ODocumentDefinition::objectSupportsEmbeddedScripts() const return bAllowDocumentMacros; } + +// ----------------------------------------------------------------------------- +::rtl::OUString ODocumentDefinition::determineContentType() const +{ + return lcl_determineContentType_nothrow( getContainerStorage(), m_pImpl->m_aProps.sPersistentName ); +} + // ----------------------------------------------------------------------------- Sequence< PropertyValue > ODocumentDefinition::fillLoadArgs( const Reference< XConnection>& _xConnection, const bool _bSuppressMacros, const bool _bReadOnly, const Sequence< PropertyValue >& _rAdditionalArgs, Sequence< PropertyValue >& _out_rEmbeddedObjectDescriptor ) @@ -1629,7 +1658,7 @@ void ODocumentDefinition::loadEmbeddedObject( const Reference< XConnection >& _x } else { - sDocumentService = GetDocumentServiceFromMediaType( xStorage, m_pImpl->m_aProps.sPersistentName, m_aContext.getLegacyServiceFactory(), aClassID ); + sDocumentService = GetDocumentServiceFromMediaType( getContentType(), m_aContext, aClassID ); // check if we are not a form and // the com.sun.star.report.pentaho.SOReportJobFactory is not present. if ( !m_bForm && !sDocumentService.equalsAscii("com.sun.star.text.TextDocument")) @@ -1642,6 +1671,7 @@ void ODocumentDefinition::loadEmbeddedObject( const Reference< XConnection >& _x { com::sun::star::io::WrongFormatException aWFE; aWFE.Message = ::rtl::OUString::createFromAscii("Extension not present."); + // TODO: resource throw aWFE; } } diff --git a/dbaccess/source/core/dataaccess/documentdefinition.hxx b/dbaccess/source/core/dataaccess/documentdefinition.hxx index 97c3aa85659e3..510d9f30153c1 100644 --- a/dbaccess/source/core/dataaccess/documentdefinition.hxx +++ b/dbaccess/source/core/dataaccess/documentdefinition.hxx @@ -168,11 +168,17 @@ public: static ::com::sun::star::uno::Sequence< sal_Int8 > getDefaultDocumentTypeClassId(); - static ::rtl::OUString GetDocumentServiceFromMediaType( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage - ,const ::rtl::OUString& sEntName - ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB - ,::com::sun::star::uno::Sequence< sal_Int8 >& _rClassId - ); + static ::rtl::OUString GetDocumentServiceFromMediaType( + const ::rtl::OUString& _rMediaType, + const ::comphelper::ComponentContext& _rContext, + ::com::sun::star::uno::Sequence< sal_Int8 >& _rClassId + ); + static ::rtl::OUString GetDocumentServiceFromMediaType( + const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _rxContainerStorage, + const ::rtl::OUString& _rEntityName, + const ::comphelper::ComponentContext& _rContext, + ::com::sun::star::uno::Sequence< sal_Int8 >& _rClassId + ); private: /** does necessary initializations after our embedded object has been switched to ACTIVE @@ -211,14 +217,18 @@ private: bool impl_close_throw(); -protected: +private: // OPropertyArrayUsageHelper virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const; virtual void getPropertyDefaultByHandle( sal_Int32 _nHandle, ::com::sun::star::uno::Any& _rDefault ) const; + // helper virtual void SAL_CALL disposing(); + // OContentHelper overridables + virtual ::rtl::OUString determineContentType() const; + private: /** fills the load arguments */ diff --git a/dbaccess/source/core/inc/ContentHelper.hxx b/dbaccess/source/core/inc/ContentHelper.hxx index 697ec70fcdb27..0f5247528709f 100644 --- a/dbaccess/source/core/inc/ContentHelper.hxx +++ b/dbaccess/source/core/inc/ContentHelper.hxx @@ -103,7 +103,8 @@ namespace dbaccess struct ContentProperties { ::rtl::OUString aTitle; // Title - ::rtl::OUString aContentType; // ContentType + ::boost::optional< ::rtl::OUString > + aContentType; // ContentType (aka MediaType aka MimeType) sal_Bool bIsDocument; // IsDocument sal_Bool bIsFolder; // IsFolder sal_Bool bAsTemplate; // AsTemplate @@ -156,6 +157,8 @@ namespace dbaccess getProperties( const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > & xEnv ); + void impl_rename_throw(const ::rtl::OUString& _sNewName,bool _bNotify = true); + protected: ::cppu::OInterfaceContainerHelper m_aContentListeners; PropertyChangeListenerContainer m_aPropertyChangeListeners; @@ -231,6 +234,9 @@ namespace dbaccess ::com::sun::star::beans::Property >& rProperties ); inline TContentPtr getImpl() const { return m_pImpl; } + + protected: + virtual ::rtl::OUString determineContentType() const = 0; }; //........................................................................ diff --git a/dbaccess/source/core/inc/DatabaseDataProvider.hxx b/dbaccess/source/core/inc/DatabaseDataProvider.hxx index 31f3d694bbbf3..68d67808e9215 100644 --- a/dbaccess/source/core/inc/DatabaseDataProvider.hxx +++ b/dbaccess/source/core/inc/DatabaseDataProvider.hxx @@ -202,8 +202,8 @@ private: virtual void SAL_CALL disposing(); void impl_fillRowSet_throw(); - bool impl_executeRowSet_throw(::osl::ResettableMutexGuard& _rClearForNotifies); - bool fillParameters( ::osl::ResettableMutexGuard& _rClearForNotifies, const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& _rxCompletionHandler ); + void impl_executeRowSet_nothrow(::osl::ResettableMutexGuard& _rClearForNotifies); + bool impl_fillParameters_nothrow( ::osl::ResettableMutexGuard& _rClearForNotifies); void impl_fillInternalDataProvider_throw(); void impl_invalidateParameter_nothrow(); @@ -228,6 +228,7 @@ private: ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet > m_xRowSet; ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XInternalDataProvider > m_xInternal; ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XRangeXMLConversion> m_xRangeConversion; + ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler> m_xHandler; // the object doin' most of the work - an SDB-rowset ::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation> m_xAggregate; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xAggregateSet; diff --git a/dbaccess/source/core/inc/definitioncontainer.hxx b/dbaccess/source/core/inc/definitioncontainer.hxx index 0740eab777e93..0abbe34aa95ac 100644 --- a/dbaccess/source/core/inc/definitioncontainer.hxx +++ b/dbaccess/source/core/inc/definitioncontainer.hxx @@ -174,6 +174,7 @@ protected: m_aContainerListeners; sal_Bool m_bInPropertyChange; + bool m_bCheckSlash; protected: /** Additionally to our own approvals which new elements must pass, derived classes @@ -204,7 +205,8 @@ public: ODefinitionContainer( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB , const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xParentContainer - ,const TContentPtr& _pImpl + , const TContentPtr& _pImpl + , bool _bCheckSlash = true ); // ::com::sun::star::uno::XInterface diff --git a/dbaccess/source/core/inc/querycontainer.hxx b/dbaccess/source/core/inc/querycontainer.hxx index 08830d4ccc2b0..869371f7ade4f 100644 --- a/dbaccess/source/core/inc/querycontainer.hxx +++ b/dbaccess/source/core/inc/querycontainer.hxx @@ -209,6 +209,10 @@ namespace dbaccess // ::com::sun::star::container::XNameAccess virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw(::com::sun::star::uno::RuntimeException); + protected: + // OContentHelper overridables + virtual ::rtl::OUString determineContentType() const; + private: // helper /** create a query object wrapping a CommandDefinition given by name. To retrieve the object, the CommandDescription diff --git a/dbaccess/source/core/misc/DatabaseDataProvider.cxx b/dbaccess/source/core/misc/DatabaseDataProvider.cxx index d6851cf14901f..33c437f970b9d 100644 --- a/dbaccess/source/core/misc/DatabaseDataProvider.cxx +++ b/dbaccess/source/core/misc/DatabaseDataProvider.cxx @@ -6,8 +6,8 @@ * * OpenOffice.org - a multi-platform office productivity suite * - * $RCSfile: DatabaseDataProvider.cxx,v $ - * $Revision: 1.5.34.1 $ + * $RCSfile$ + * $Revision$ * * This file is part of OpenOffice.org. * @@ -35,6 +35,7 @@ #include "cppuhelper/implbase1.hxx" #include <comphelper/types.hxx> #include <connectivity/FValue.hxx> +#include <connectivity/dbtools.hxx> #include <rtl/ustrbuf.hxx> #include <com/sun/star/task/XInteractionHandler.hpp> @@ -42,8 +43,6 @@ #include <com/sun/star/sdb/CommandType.hpp> #include <com/sun/star/sdbc/XRow.hpp> #include <com/sun/star/sdbc/XResultSet.hpp> -#include <com/sun/star/sdbc/XResultSetMetaData.hpp> -#include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp> #include <com/sun/star/beans/NamedValue.hpp> #include <com/sun/star/chart/ChartDataRowSource.hpp> #include <com/sun/star/chart/XChartDataArray.hpp> @@ -86,7 +85,7 @@ DatabaseDataProvider::DatabaseDataProvider(uno::Reference< uno::XComponentContex m_xAggregate.set(m_xRowSet,uno::UNO_QUERY); m_xAggregateSet.set(m_xRowSet,uno::UNO_QUERY); uno::Reference<beans::XPropertySet> xProp(static_cast< ::cppu::OWeakObject* >( this ),uno::UNO_QUERY); - m_aFilterManager.initialize( xProp, m_xAggregateSet ); + m_aFilterManager.initialize( m_xAggregateSet ); m_aParameterManager.initialize( xProp, m_xAggregate ); m_xAggregateSet->setPropertyValue(PROPERTY_COMMAND_TYPE,uno::makeAny(m_CommandType)); m_xAggregateSet->setPropertyValue(PROPERTY_ESCAPE_PROCESSING,uno::makeAny(m_EscapeProcessing)); @@ -158,12 +157,14 @@ uno::Reference< uno::XInterface > DatabaseDataProvider::Create(uno::Reference< u void SAL_CALL DatabaseDataProvider::initialize(const uno::Sequence< uno::Any > & aArguments) throw (uno::RuntimeException, uno::Exception) { osl::MutexGuard g(m_aMutex); - const uno::Any* pIter = aArguments.getConstArray(); - const uno::Any* pEnd = pIter + aArguments.getLength(); + const uno::Any* pIter = aArguments.getConstArray(); + const uno::Any* pEnd = pIter + aArguments.getLength(); for(;pIter != pEnd;++pIter) { - if ( !m_xActiveConnection.is() && ((*pIter) >>= m_xActiveConnection) ) - break; + if ( !m_xActiveConnection.is() ) + (*pIter) >>= m_xActiveConnection; + else if ( !m_xHandler.is() ) + (*pIter) >>= m_xHandler; } m_xAggregateSet->setPropertyValue( PROPERTY_ACTIVE_CONNECTION, uno::makeAny( m_xActiveConnection ) ); } @@ -179,14 +180,12 @@ void SAL_CALL DatabaseDataProvider::initialize(const uno::Sequence< uno::Any > & try { impl_fillRowSet_throw(); - bRet = impl_executeRowSet_throw(aClearForNotifies); - if ( bRet ) - impl_fillInternalDataProvider_throw(); + impl_executeRowSet_nothrow(aClearForNotifies); + impl_fillInternalDataProvider_throw(); + bRet = true; } - catch(const uno::Exception& e) + catch(const uno::Exception& /*e*/) { - (void)e; - OSL_ENSURE(0,"Exception caught!"); } } if ( !bRet ) // no command set or an error occured, use Internal data handler @@ -500,18 +499,16 @@ void SAL_CALL DatabaseDataProvider::setDataSourceName(const ::rtl::OUString& the set(PROPERTY_DATASOURCENAME,the_value,m_DataSourceName); } // ----------------------------------------------------------------------------- -bool DatabaseDataProvider::impl_executeRowSet_throw(::osl::ResettableMutexGuard& _rClearForNotifies) +void DatabaseDataProvider::impl_executeRowSet_nothrow(::osl::ResettableMutexGuard& _rClearForNotifies) { - uno::Reference<task::XInteractionHandler> xHandler( - m_xContext->getServiceManager()->createInstanceWithContext( - ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.InteractionHandler")) - ,m_xContext), - uno::UNO_QUERY); - if (!fillParameters(_rClearForNotifies, xHandler)) - return false; - - m_xRowSet->execute(); - return true; + try + { + if ( impl_fillParameters_nothrow(_rClearForNotifies) ) + m_xRowSet->execute(); + } + catch(const uno::Exception&) + { + } } // ----------------------------------------------------------------------------- void DatabaseDataProvider::impl_fillInternalDataProvider_throw() @@ -519,19 +516,25 @@ void DatabaseDataProvider::impl_fillInternalDataProvider_throw() // clear the data before fill the new one uno::Reference< chart::XChartDataArray> xChartData(m_xInternal,uno::UNO_QUERY); if ( xChartData.is() ) + { xChartData->setData(uno::Sequence< uno::Sequence<double> >()); + xChartData->setColumnDescriptions(uno::Sequence< ::rtl::OUString >()); + m_xInternal->deleteSequence(0); + } + + uno::Sequence< ::rtl::OUString > aColumns = ::dbtools::getFieldNamesByCommandDescriptor(getActiveConnection() + ,getCommandType() + ,m_Command); // fill the data - uno::Reference< sdbc::XResultSet> xRes(m_xRowSet,uno::UNO_QUERY); - uno::Reference< sdbc::XRow> xRow(m_xRowSet,uno::UNO_QUERY); - uno::Reference< sdbc::XResultSetMetaDataSupplier> xResMDSup(m_xRowSet,uno::UNO_QUERY); - uno::Reference< sdbc::XResultSetMetaData> xResultSetMetaData = xResMDSup->getMetaData(); + uno::Reference< sdbc::XResultSet> xRes(m_xRowSet,uno::UNO_QUERY_THROW); + uno::Reference< sdbc::XRow> xRow(m_xRowSet,uno::UNO_QUERY_THROW); uno::Sequence< uno::Any > aLabelArgs(1); - const sal_Int32 nCount = xResultSetMetaData->getColumnCount(); - for (sal_Int32 i = 2; i <= nCount; ++i) + const sal_Int32 nCount = aColumns.getLength(); + for (sal_Int32 i = 1; i < nCount; ++i) { - aLabelArgs[0] <<= xResultSetMetaData->getColumnName(i); + aLabelArgs[0] <<= aColumns[i]; // i == 0 is the category const ::rtl::OUString sLabelRange = lcl_getLabel() + ::rtl::OUString::valueOf(i - 1); m_xInternal->setDataByRangeRepresentation(sLabelRange,aLabelArgs); } @@ -543,6 +546,22 @@ void DatabaseDataProvider::impl_fillInternalDataProvider_throw() ++nRowCount; for (sal_Int32 j = 1; j <= nCount; ++j) aDataValues[j-1].push_back(uno::makeAny(xRow->getString(j))); + } // while( xRes->next() && (!m_RowLimit || nRowCount < m_RowLimit) ) + if ( !nRowCount ) + { + nRowCount = 3; + const double fDefaultData[ ] = + { 9.10, 3.20, 4.54, + 2.40, 8.80, 9.65, + 3.10, 1.50, 3.70, + 4.30, 9.02, 6.20 }; + for (sal_Int32 j = 1,k = 0; j <= nCount; ++j,++k) + { + sal_Int32 nSize = sizeof(fDefaultData)/sizeof(fDefaultData[0]); + if ( k >= nSize ) + k = 0; + aDataValues[j-1].push_back(uno::makeAny(fDefaultData[k])); + } } ::std::vector< ::std::vector< uno::Any > >::iterator aDataValuesIter = aDataValues.begin(); const ::std::vector< ::std::vector< uno::Any > >::iterator aDataValuesEnd = aDataValues.end(); @@ -559,7 +578,7 @@ void DatabaseDataProvider::impl_fillInternalDataProvider_throw() else m_xInternal->setDataByRangeRepresentation(::rtl::OUString::valueOf(nPos-1),uno::Sequence< uno::Any >(&(*aDataValuesIter->begin()),aDataValuesIter->size())); } - } + } // for (sal_Int32 nPos = 0;nRowCount && aDataValuesIter != aDataValuesEnd ; ++aDataValuesIter,++nPos) } // ----------------------------------------------------------------------------- void DatabaseDataProvider::impl_fillRowSet_throw() @@ -569,14 +588,14 @@ void DatabaseDataProvider::impl_fillRowSet_throw() xParam->clearParameters( ); } // ----------------------------------------------------------------------------- -bool DatabaseDataProvider::fillParameters( ::osl::ResettableMutexGuard& _rClearForNotifies, const uno::Reference< task::XInteractionHandler >& _rxCompletionHandler ) +bool DatabaseDataProvider::impl_fillParameters_nothrow( ::osl::ResettableMutexGuard& _rClearForNotifies) { // do we have to fill the parameters again? if ( !m_aParameterManager.isUpToDate() ) m_aParameterManager.updateParameterInfo( m_aFilterManager ); if ( m_aParameterManager.isUpToDate() ) - return m_aParameterManager.fillParameterValues( _rxCompletionHandler, _rClearForNotifies ); + return m_aParameterManager.fillParameterValues( m_xHandler, _rClearForNotifies ); return true; } @@ -723,11 +742,8 @@ void SAL_CALL DatabaseDataProvider::clearParameters() throw( SQLException, Runti //------------------------------------------------------------------------------ void SAL_CALL DatabaseDataProvider::execute() throw( SQLException, RuntimeException ) { - ::osl::ResettableMutexGuard aGuard(m_aMutex); - impl_fillRowSet_throw(); - bool bRet = impl_executeRowSet_throw(aGuard); - if ( bRet ) - impl_fillInternalDataProvider_throw(); + uno::Sequence< beans::PropertyValue > aEmpty; + createDataSourcePossible(aEmpty); } //------------------------------------------------------------------------------ void SAL_CALL DatabaseDataProvider::addRowSetListener(const uno::Reference<sdbc::XRowSetListener>& _rListener) throw( RuntimeException ) diff --git a/dbaccess/source/ext/macromigration/migrationengine.cxx b/dbaccess/source/ext/macromigration/migrationengine.cxx index 824e236ef9eb6..9c1447bb84da8 100644 --- a/dbaccess/source/ext/macromigration/migrationengine.cxx +++ b/dbaccess/source/ext/macromigration/migrationengine.cxx @@ -49,6 +49,7 @@ #include <com/sun/star/frame/XModel.hpp> #include <com/sun/star/frame/XComponentLoader.hpp> #include <com/sun/star/ucb/XCommandProcessor.hpp> +#include <com/sun/star/ucb/XContent.hpp> #include <com/sun/star/embed/XComponentSupplier.hpp> #include <com/sun/star/embed/ElementModes.hpp> #include <com/sun/star/document/XStorageBasedDocument.hpp> @@ -66,11 +67,13 @@ #include <com/sun/star/drawing/XDrawPagesSupplier.hpp> #include <com/sun/star/script/XEventAttacherManager.hpp> #include <com/sun/star/script/XLibraryContainerPassword.hpp> +#include <com/sun/star/io/WrongFormatException.hpp> /** === end UNO includes === **/ #include <comphelper/documentinfo.hxx> #include <comphelper/interaction.hxx> #include <comphelper/namedvaluecollection.hxx> +#include <comphelper/storagehelper.hxx> #include <comphelper/string.hxx> #include <comphelper/types.hxx> #include <cppuhelper/exc_hlp.hxx> @@ -111,6 +114,7 @@ namespace dbmm using ::com::sun::star::frame::XModel; using ::com::sun::star::frame::XComponentLoader; using ::com::sun::star::ucb::XCommandProcessor; + using ::com::sun::star::ucb::XContent; using ::com::sun::star::ucb::Command; using ::com::sun::star::embed::XComponentSupplier; using ::com::sun::star::task::XStatusIndicator; @@ -138,6 +142,7 @@ namespace dbmm using ::com::sun::star::script::XEventAttacherManager; using ::com::sun::star::script::ScriptEventDescriptor; using ::com::sun::star::script::XLibraryContainerPassword; + using ::com::sun::star::io::WrongFormatException; /** === end UNO using === **/ namespace ElementModes = ::com::sun::star::embed::ElementModes; @@ -158,12 +163,15 @@ namespace dbmm Reference< XModel > xDocument; // valid only temporarily ::rtl::OUString sHierarchicalName; SubDocumentType eType; + size_t nNumber; - SubDocument( const Reference< XCommandProcessor >& _rxCommandProcessor, const ::rtl::OUString& _rName, const SubDocumentType _eType ) + SubDocument( const Reference< XCommandProcessor >& _rxCommandProcessor, const ::rtl::OUString& _rName, + const SubDocumentType _eType, const size_t _nNumber ) :xCommandProcessor( _rxCommandProcessor ) ,xDocument() ,sHierarchicalName( _rName ) ,eType( _eType ) + ,nNumber( _nNumber ) { } }; @@ -265,7 +273,31 @@ namespace dbmm } //---------------------------------------------------------------- - static bool lcl_loadSubDocument_nothrow( SubDocument& _rDocument, + ::rtl::OUString lcl_getMimeType_nothrow( const Reference< XCommandProcessor >& _rxContent ) + { + ::rtl::OUString sMimeType; + try + { + Reference< XContent > xContent( _rxContent, UNO_QUERY_THROW ); + sMimeType = xContent->getContentType(); + } + catch( const Exception& ) + { + DBG_UNHANDLED_EXCEPTION(); + } + return sMimeType; + } + + //---------------------------------------------------------------- + enum OpenDocResult + { + eOpenedDoc, + eIgnoreDoc, + eFailure + }; + + //---------------------------------------------------------------- + static OpenDocResult lcl_loadSubDocument_nothrow( SubDocument& _rDocument, const Reference< XStatusIndicator >& _rxProgress, MigrationLog& _rLogger ) { OSL_PRECOND( !_rDocument.xDocument.is(), "lcl_loadSubDocument_nothrow: already loaded!" ); @@ -292,13 +324,31 @@ namespace dbmm } catch( const Exception& ) { - _rLogger.logFailure( MigrationError( - ERR_OPENING_SUB_DOCUMENT_FAILED, - lcl_getSubDocumentDescription( _rDocument ), - ::cppu::getCaughtException() - ) ); + Any aError( ::cppu::getCaughtException() ); + + bool bCausedByNewStyleReport = + ( _rDocument.eType == eReport ) + && ( aError.isExtractableTo( ::cppu::UnoType< WrongFormatException >::get() ) ) + && ( lcl_getMimeType_nothrow( _rDocument.xCommandProcessor ).equalsAscii( "application/vnd.sun.xml.report" ) ); + + if ( bCausedByNewStyleReport ) + { + _rLogger.logRecoverable( MigrationError( + ERR_NEW_STYLE_REPORT, + lcl_getSubDocumentDescription( _rDocument ) + ) ); + return eIgnoreDoc; + } + else + { + _rLogger.logFailure( MigrationError( + ERR_OPENING_SUB_DOCUMENT_FAILED, + lcl_getSubDocumentDescription( _rDocument ), + aError + ) ); + } } - return _rDocument.xDocument.is(); + return _rDocument.xDocument.is() ? eOpenedDoc : eFailure; } //---------------------------------------------------------------- @@ -822,8 +872,8 @@ namespace dbmm ); ~MigrationEngine_Impl(); - inline sal_Int32 getFormCount() const { return m_nFormCount; } - inline sal_Int32 getReportCount()const { return m_nReportCount; } + inline size_t getFormCount() const { return m_nFormCount; } + inline size_t getReportCount()const { return m_nReportCount; } bool migrateAll(); private: @@ -995,12 +1045,10 @@ namespace dbmm //-------------------------------------------------------------------- namespace { - size_t lcl_collectHierarchicalElementNames_throw( + void lcl_collectHierarchicalElementNames_throw( const Reference< XNameAccess >& _rxContainer, const ::rtl::OUString& _rContainerLoc, - SubDocuments& _out_rDocs, const SubDocumentType _eType ) + SubDocuments& _out_rDocs, const SubDocumentType _eType, size_t& _io_counter ) { - size_t nAddedElements = 0; - const ::rtl::OUString sHierarhicalBase( _rContainerLoc.getLength() ? ::rtl::OUStringBuffer( _rContainerLoc ).appendAscii( "/" ).makeStringAndClear() : ::rtl::OUString() ); @@ -1017,7 +1065,7 @@ namespace dbmm Reference< XNameAccess > xSubContainer( aElement, UNO_QUERY ); if ( xSubContainer.is() ) { - nAddedElements += lcl_collectHierarchicalElementNames_throw( xSubContainer, sElementName, _out_rDocs, _eType ); + lcl_collectHierarchicalElementNames_throw( xSubContainer, sElementName, _out_rDocs, _eType, _io_counter ); } else { @@ -1025,12 +1073,10 @@ namespace dbmm OSL_ENSURE( xCommandProcessor.is(), "lcl_collectHierarchicalElementNames_throw: no container, and no comand processor? What *is* it, then?!" ); if ( xCommandProcessor.is() ) { - _out_rDocs.push_back( SubDocument( xCommandProcessor, sElementName, _eType ) ); - ++nAddedElements; + _out_rDocs.push_back( SubDocument( xCommandProcessor, sElementName, _eType, ++_io_counter ) ); } } } - return nAddedElements; } } @@ -1044,10 +1090,12 @@ namespace dbmm try { Reference< XNameAccess > xDocContainer( m_xDocument->getFormDocuments(), UNO_SET_THROW ); - m_nFormCount = lcl_collectHierarchicalElementNames_throw( xDocContainer, ::rtl::OUString(), m_aSubDocs, eForm ); + m_nFormCount = 0; + lcl_collectHierarchicalElementNames_throw( xDocContainer, ::rtl::OUString(), m_aSubDocs, eForm, m_nFormCount ); xDocContainer.set( m_xDocument->getReportDocuments(), UNO_SET_THROW ); - m_nReportCount = lcl_collectHierarchicalElementNames_throw( xDocContainer, ::rtl::OUString(), m_aSubDocs, eReport ); + m_nReportCount = 0; + lcl_collectHierarchicalElementNames_throw( xDocContainer, ::rtl::OUString(), m_aSubDocs, eReport, m_nReportCount ); } catch( const Exception& ) { @@ -1075,13 +1123,14 @@ namespace dbmm // load the document ::rtl::Reference< ProgressCapture > pStatusIndicator( new ProgressCapture( sObjectName, m_rProgress ) ); SubDocument aSubDocument( _rDocument ); - if ( !lcl_loadSubDocument_nothrow( aSubDocument, pStatusIndicator.get(), m_rLogger ) ) + OpenDocResult eResult = lcl_loadSubDocument_nothrow( aSubDocument, pStatusIndicator.get(), m_rLogger ); + if ( eResult != eOpenedDoc ) { pStatusIndicator->dispose(); m_rProgress.endObject(); m_rLogger.finishedDocument( m_nCurrentDocumentID ); m_nCurrentDocumentID = -1; - return false; + return ( eResult == eIgnoreDoc ); } // ----------------- @@ -1145,32 +1194,69 @@ namespace dbmm namespace { static ::rtl::OUString lcl_createTargetLibName( const SubDocument& _rDocument, - const ::rtl::OUString& _rSourceLibName, const Reference< XNameAccess >& _rxTargetStorage ) + const ::rtl::OUString& _rSourceLibName, const Reference< XNameAccess >& _rxTargetContainer ) { - // a prefix denoting the type + // The new library name is composed from the prefix, the base name, and the old library name. const ::rtl::OUString sPrefix( ::rtl::OUString::createFromAscii( _rDocument.eType == eForm ? "Form_" : "Report_" ) ); - ::rtl::OUStringBuffer aBuffer; - aBuffer.append( sPrefix ); - - // first try with the base name of the sub document - aBuffer.append( _rDocument.sHierarchicalName.copy( + ::rtl::OUString sBaseName( _rDocument.sHierarchicalName.copy( _rDocument.sHierarchicalName.lastIndexOf( '/' ) + 1 ) ); - aBuffer.appendAscii( "_" ); - aBuffer.append( _rSourceLibName ); - ::rtl::OUString sTargetName( aBuffer.makeStringAndClear() ); - if ( !_rxTargetStorage->hasByName( sTargetName ) ) - return sTargetName; - - // if this name is already used (which is valid, since documents with the same base - // name can exist in different logical folders), then use the complete name - aBuffer.append( sPrefix ); - aBuffer.append( ::comphelper::string::searchAndReplaceAllAsciiWithAscii( - _rDocument.sHierarchicalName, "/", "_" ) ); - aBuffer.appendAscii( "_" ); - aBuffer.append( _rSourceLibName ); - return aBuffer.makeStringAndClear(); + // Normalize this name. In our current storage implementation (and script containers in a document + // are finally mapped to sub storages of the document storage), not all characters are allowed. + // The bug requesting to change this is #i95409#. + // Unfortunately, the storage implementation does not complain if you use invalid characters/names, but instead + // it silently accepts them, and produces garbage in the file (#i95408). + // So, until especially the former is fixed, we need to strip the name from all invalid characters. + // #i95865# / 2008-11-06 / frank.schoenheit@sun.com + + // The general idea is to replace invalid characters with '_'. However, since "valid" essentially means + // ASCII only, this implies that for a lot of languages, we would simply replace everything with '_', + // which of course is not desired. + // So, we use a heuristics: If the name contains at most 3 invalid characters, and as many valid as invalid + // characters, then we use the replacement. Otherwise, we just use a unambiguous number for the sub document. + sal_Int32 nValid=0, nInvalid=0; + const sal_Unicode* pBaseName = sBaseName.getStr(); + const sal_Int32 nBaseNameLen = sBaseName.getLength(); + for ( sal_Int32 i=0; i<nBaseNameLen; ++i ) + { + if ( ::comphelper::IsValidZipEntryFileName( pBaseName + i, 1, sal_False ) ) + ++nValid; + else + ++nInvalid; + } + if ( ( nInvalid <= 3 ) && ( nInvalid * 2 <= nValid ) ) + { // not "too many" invalid => replace them + ::rtl::OUStringBuffer aReplacement; + aReplacement.ensureCapacity( nBaseNameLen ); + aReplacement.append( sBaseName ); + const sal_Unicode* pReplacement = aReplacement.getStr(); + for ( sal_Int32 i=0; i<nBaseNameLen; ++i ) + { + if ( !::comphelper::IsValidZipEntryFileName( pReplacement + i, 1, sal_False ) ) + aReplacement.setCharAt( i, '_' ); + } + sBaseName = aReplacement.makeStringAndClear(); + + ::rtl::OUStringBuffer aNewLibNameAttempt; + aNewLibNameAttempt.append( sPrefix ); + aNewLibNameAttempt.append( sBaseName ); + aNewLibNameAttempt.appendAscii( "_" ); + aNewLibNameAttempt.append( _rSourceLibName ); + ::rtl::OUString sTargetName( aNewLibNameAttempt.makeStringAndClear() ); + if ( !_rxTargetContainer->hasByName( sTargetName ) ) + return sTargetName; + } + // "too many" invalid characters, or the name composed with the base name was already used. + // (The latter is valid, since there can be multiple sub documents with the same base name, + // in different levels in the hierarchy.) + // In this case, just use the umambiguous sub document number. + ::rtl::OUStringBuffer aNewLibName; + aNewLibName.append( sPrefix ); + aNewLibName.append( ::rtl::OUString::valueOf( sal_Int64( _rDocument.nNumber ) ) ); + aNewLibName.appendAscii( "_" ); + aNewLibName.append( _rSourceLibName ); + return aNewLibName.makeStringAndClear(); } } @@ -1314,8 +1400,8 @@ namespace dbmm { m_rLogger.logFailure( MigrationError( ERR_COMMITTING_SCRIPT_STORAGES_FAILED, - lcl_getSubDocumentDescription( _rDocument ), - getScriptTypeDisplayName( _eScriptType ) + getScriptTypeDisplayName( _eScriptType ), + lcl_getSubDocumentDescription( _rDocument ) ) ); return false; } @@ -1340,8 +1426,8 @@ namespace dbmm { m_rLogger.logFailure( MigrationError( ERR_GENERAL_SCRIPT_MIGRATION_FAILURE, - lcl_getSubDocumentDescription( _rDocument ), getScriptTypeDisplayName( _eScriptType ), + lcl_getSubDocumentDescription( _rDocument ), aException ) ); } diff --git a/dbaccess/source/ext/macromigration/migrationerror.hxx b/dbaccess/source/ext/macromigration/migrationerror.hxx index ce5bcabb23f2b..84b972f0e9bf4 100644 --- a/dbaccess/source/ext/macromigration/migrationerror.hxx +++ b/dbaccess/source/ext/macromigration/migrationerror.hxx @@ -65,7 +65,8 @@ namespace dbmm ERR_DOCUMENT_BACKUP_FAILED, ERR_UNKNOWN_SCRIPT_FOLDER, ERR_EXAMINING_SCRIPTS_FOLDER_FAILED, - ERR_PASSWORD_VERIFICATION_FAILED + ERR_PASSWORD_VERIFICATION_FAILED, + ERR_NEW_STYLE_REPORT }; //==================================================================== diff --git a/dbaccess/source/ext/macromigration/migrationlog.cxx b/dbaccess/source/ext/macromigration/migrationlog.cxx index 4c94bc0a45de9..df41a1199b1fc 100644 --- a/dbaccess/source/ext/macromigration/migrationlog.cxx +++ b/dbaccess/source/ext/macromigration/migrationlog.cxx @@ -248,18 +248,18 @@ namespace dbmm switch ( _rError.eType ) { case ERR_OPENING_SUB_DOCUMENT_FAILED: - pAsciiErrorDescription = "opening '#name#' failed"; - aAsciiParameterNames.push_back( "#name#" ); + pAsciiErrorDescription = "opening '#doc#' failed"; + aAsciiParameterNames.push_back( "#doc#" ); break; case ERR_CLOSING_SUB_DOCUMENT_FAILED: - pAsciiErrorDescription = "closing '#name#' failed"; - aAsciiParameterNames.push_back( "#name#" ); + pAsciiErrorDescription = "closing '#doc#' failed"; + aAsciiParameterNames.push_back( "#doc#" ); break; case ERR_STORAGE_COMMIT_FAILED: - pAsciiErrorDescription = "committing the changes for document '#name#' failed"; - aAsciiParameterNames.push_back( "#name#" ); + pAsciiErrorDescription = "committing the changes for document '#doc#' failed"; + aAsciiParameterNames.push_back( "#doc#" ); break; case ERR_STORING_DATABASEDOC_FAILED: @@ -289,7 +289,7 @@ namespace dbmm break; case ERR_GENERAL_SCRIPT_MIGRATION_FAILURE: - pAsciiErrorDescription = "general error during migrationg #scripttype# scripts of document '#doc#'"; + pAsciiErrorDescription = "general error while migrating #scripttype# scripts of document '#doc#'"; aAsciiParameterNames.push_back( "#scripttype#" ); aAsciiParameterNames.push_back( "#doc#" ); break; @@ -325,7 +325,7 @@ namespace dbmm break; case ERR_ADJUSTING_DOCUMENT_EVENTS_FAILED: - pAsciiErrorDescription = "adjusting events for document #doc# failed"; + pAsciiErrorDescription = "adjusting events for document '#doc#' failed"; aAsciiParameterNames.push_back( "#doc#" ); break; @@ -367,6 +367,11 @@ namespace dbmm aAsciiParameterNames.push_back( "#name#" ); break; + case ERR_NEW_STYLE_REPORT: + pAsciiErrorDescription = "#doc# could not be processed, since you don't have the Sun Report Builder (TM) extension installed."; + aAsciiParameterNames.push_back( "#doc#" ); + break; + // do *not* add a default case here: Without a default, some compilers will warn you when // you miss a newly-introduced enum value here } diff --git a/dbaccess/source/ui/app/AppController.cxx b/dbaccess/source/ui/app/AppController.cxx index ccac5237d7dc2..85bc7a0d8d23d 100644 --- a/dbaccess/source/ui/app/AppController.cxx +++ b/dbaccess/source/ui/app/AppController.cxx @@ -1322,7 +1322,11 @@ void OApplicationController::Execute(sal_uInt16 _nId, const Sequence< PropertyVa { getContainer()->selectContainer(E_NONE); getContainer()->selectContainer(E_TABLE); + // #i95524# + getContainer()->Invalidate(); + refreshTables(); } + } break; case ID_BROWSER_SORTUP: @@ -2822,6 +2826,10 @@ sal_Bool SAL_CALL OApplicationController::attachModel(const Reference< XModel > sal_Int32 nValue = 0; pIter->Value >>= nValue; m_ePreviewMode = static_cast<PreviewMode>(nValue); + if ( getView() ) + { + getContainer()->switchPreview(m_ePreviewMode); + } } } catch( const Exception& ) diff --git a/dbaccess/source/ui/control/RelationControl.cxx b/dbaccess/source/ui/control/RelationControl.cxx index b782d309d9dbe..08416eb7496ee 100644 --- a/dbaccess/source/ui/control/RelationControl.cxx +++ b/dbaccess/source/ui/control/RelationControl.cxx @@ -452,7 +452,7 @@ namespace dbaui const OJoinTableView* pView = _pSource->getTableView(); OTableConnection* pConn = pView->GetTabConn(_pSource,_pDest); - if ( pConn ) + if ( pConn && !m_pConnData->GetConnLineDataList()->empty() ) { m_pConnData->CopyFrom(*pConn->GetData()); m_pBoxControl->getContainer()->notifyConnectionChange(); diff --git a/dbaccess/source/ui/dlg/ExtensionNotPresent.src b/dbaccess/source/ui/dlg/ExtensionNotPresent.src index 6a96bccf8b9dd..ea4cdee8b3103 100644 --- a/dbaccess/source/ui/dlg/ExtensionNotPresent.src +++ b/dbaccess/source/ui/dlg/ExtensionNotPresent.src @@ -1,89 +1,91 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: ExtensionNotPresent.src,v $ - * $Revision: 1.5 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * <http://www.openoffice.org/license.html> - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -#include "ExtensionNotPresent.hrc" -#include "dbaccess_helpid.hrc" -#include "dbu_resource.hrc" -#include <svx/globlmn.hrc> -#include <svx/svxids.hrc> - - -String RID_STR_EXTENSION_NOT_PRESENT -{ - Text [ en-US ] = "To open a report you require the extension %RPT_EXTENSION_NAME.\n\nClick 'Download...' to download and install the extension."; -}; -// To open a report you require the extension Sun Report Designer weiss der Geier Hauptsache extra langer Name -// String RID_STR_EXTENSION_NAME -// { -// Text = "Sun(TM) Report Builder"; -// }; - -ModalDialog RID_EXTENSION_NOT_PRESENT_DLG -{ - OutputSize = TRUE ; - SVLook = TRUE ; - Size = MAP_APPFONT ( DLG_WIDTH , DLG_HEIGHT ) ; - Text [ en-US ] = "%PRODUCTNAME %PRODUCTVERSION" ; - HelpId = HID_EXTENSION_NOT_PRESENT_DLG; - Moveable = TRUE ; - Closeable = TRUE ; - - // most of the calulated values here are overridden by the ExtensionNotPresent ctor itself. - FixedImage FI_WARNING - { - Pos = MAP_APPFONT (CELL_PADDING / 2, CELL_PADDING) ; - Size = (32, 32); - Fixed=BMP_EXCEPTION_WARNING; - }; - - - FixedText FT_TEXT - { - Pos = MAP_APPFONT ( 32 , CELL_PADDING ) ; - Size = MAP_APPFONT ( DLG_WIDTH - LEFT_PADDING - RIGHT_PADDING , 3 * (FIXEDTEXT_HEIGHT + 2) ) ; - // Border = TRUE ; - // Text will set outside from RID_STR_EXTENSION_NOT_PRESENT - }; - - PushButton PB_DOWNLOAD - { - Pos = MAP_APPFONT ( DLG_WIDTH / 2 - (CELL_PADDING/2) - BUTTON_WIDTH, ACTION_LINE_START ) ; - Size = MAP_APPFONT ( BUTTON_WIDTH , BUTTON_HEIGHT ) ; - DefButton = TRUE ; - TabStop = TRUE ; - Text [ en-US ] = "~Download..." ; - }; - - CancelButton PB_CANCEL - { - Pos = MAP_APPFONT ( DLG_WIDTH / 2 + (CELL_PADDING/2), ACTION_LINE_START) ; - Size = MAP_APPFONT ( BUTTON_WIDTH , BUTTON_HEIGHT ) ; - TabStop = TRUE ; - }; -}; +/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ExtensionNotPresent.src,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+#include "ExtensionNotPresent.hrc"
+#include "dbaccess_helpid.hrc"
+#include "dbu_resource.hrc"
+#include <svx/globlmn.hrc>
+#include <svx/svxids.hrc>
+
+
+String RID_STR_EXTENSION_NOT_PRESENT
+{
+ // #i96130# use hard coded name
+ Text [ en-US ] = "To open a report you require the extension Sun™ Report Builder.\n\nClick 'Download...' to download and install the extension.";
+ // OLD: Text [ en-US ] = "To open a report you require the extension %RPT_EXTENSION_NAME.\n\nClick 'Download...' to download and install the extension.";
+};
+// To open a report you require the extension Sun Report Designer weiss der Geier Hauptsache extra langer Name
+// String RID_STR_EXTENSION_NAME
+// {
+// Text = "Sun(TM) Report Builder";
+// };
+
+ModalDialog RID_EXTENSION_NOT_PRESENT_DLG
+{
+ OutputSize = TRUE ;
+ SVLook = TRUE ;
+ Size = MAP_APPFONT ( DLG_WIDTH , DLG_HEIGHT ) ;
+ Text [ en-US ] = "%PRODUCTNAME %PRODUCTVERSION" ;
+ HelpId = HID_EXTENSION_NOT_PRESENT_DLG;
+ Moveable = TRUE ;
+ Closeable = TRUE ;
+
+ // most of the calulated values here are overridden by the ExtensionNotPresent ctor itself.
+ FixedImage FI_WARNING
+ {
+ Pos = MAP_APPFONT (CELL_PADDING / 2, CELL_PADDING) ;
+ Size = (32, 32);
+ Fixed=BMP_EXCEPTION_WARNING;
+ };
+
+
+ FixedText FT_TEXT
+ {
+ Pos = MAP_APPFONT ( 32 , CELL_PADDING ) ;
+ Size = MAP_APPFONT ( DLG_WIDTH - LEFT_PADDING - RIGHT_PADDING , 3 * (FIXEDTEXT_HEIGHT + 2) ) ;
+ // Border = TRUE ;
+ // Text will set outside from RID_STR_EXTENSION_NOT_PRESENT
+ };
+
+ PushButton PB_DOWNLOAD
+ {
+ Pos = MAP_APPFONT ( DLG_WIDTH / 2 - (CELL_PADDING/2) - BUTTON_WIDTH, ACTION_LINE_START ) ;
+ Size = MAP_APPFONT ( BUTTON_WIDTH , BUTTON_HEIGHT ) ;
+ DefButton = TRUE ;
+ TabStop = TRUE ;
+ Text [ en-US ] = "~Download..." ;
+ };
+
+ CancelButton PB_CANCEL
+ {
+ Pos = MAP_APPFONT ( DLG_WIDTH / 2 + (CELL_PADDING/2), ACTION_LINE_START) ;
+ Size = MAP_APPFONT ( BUTTON_WIDTH , BUTTON_HEIGHT ) ;
+ TabStop = TRUE ;
+ };
+};
diff --git a/dbaccess/source/ui/inc/QueryDesignView.hxx b/dbaccess/source/ui/inc/QueryDesignView.hxx index 1078946a5dc51..a84eca1ffb00a 100644 --- a/dbaccess/source/ui/inc/QueryDesignView.hxx +++ b/dbaccess/source/ui/inc/QueryDesignView.hxx @@ -146,7 +146,7 @@ namespace dbaui // called when a table from tabeview was deleted void TableDeleted(const ::rtl::OUString& rAliasName); - BOOL getColWidth( const ::rtl::OUString& rAliasName, const ::rtl::OUString& rFieldName, sal_uInt32& nWidth ); + sal_Int32 getColWidth( sal_uInt16 _nColPos) const; void fillValidFields(const ::rtl::OUString& strTableName, ComboBox* pFieldList); void SaveUIConfig(); diff --git a/dbaccess/source/ui/inc/querycontroller.hxx b/dbaccess/source/ui/inc/querycontroller.hxx index b79e6ea6dfc56..70be5b60407a5 100644 --- a/dbaccess/source/ui/inc/querycontroller.hxx +++ b/dbaccess/source/ui/inc/querycontroller.hxx @@ -77,10 +77,11 @@ namespace dbaui OTableFields m_vTableFieldDesc; OTableFields m_vUnUsedFieldsDesc; // contains fields which aren't visible and don't have any criteria + ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > m_aFieldInformation; + ::svxform::OSystemParseContext* m_pParseContext; ::connectivity::OSQLParser m_aSqlParser; ::connectivity::OSQLParseTreeIterator* m_pSqlIterator; - ::std::vector<sal_uInt32> m_vColumnWidth; ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSQLQueryComposer > m_xComposer; /// if we're editing an existing view, this is non-NULL @@ -167,12 +168,10 @@ namespace dbaui void setSplitPos(sal_Int32 _nSplitPos) { m_nSplitPos = _nSplitPos;} void setVisibleRows(sal_Int32 _nVisibleRows) { m_nVisibleRows = _nVisibleRows;} + sal_Int32 getColWidth(sal_uInt16 _nColPos) const; + ::connectivity::OSQLParser& getParser() { return m_aSqlParser; } ::connectivity::OSQLParseTreeIterator& getParseIterator() { return *m_pSqlIterator; } - sal_uInt32 getColWidth(sal_uInt16 _nPos) const - { - return m_vColumnWidth.size() < _nPos ? m_vColumnWidth[_nPos] : sal_uInt32(0); - } virtual sal_Bool Construct(Window* pParent); diff --git a/dbaccess/source/ui/misc/controllerframe.cxx b/dbaccess/source/ui/misc/controllerframe.cxx index f0c93586f26c7..e20f5e04b35b0 100644 --- a/dbaccess/source/ui/misc/controllerframe.cxx +++ b/dbaccess/source/ui/misc/controllerframe.cxx @@ -108,7 +108,7 @@ namespace dbaui private: void impl_checkDisposed_throw() const; - void impl_actOnFrameWindow_nothrow( bool _bRegister ); + void impl_registerOnFrameContainerWindow_nothrow( bool _bRegister ); private: ControllerFrame_Data* m_pData; @@ -125,6 +125,7 @@ namespace dbaui ,m_xDocEventBroadcaster() ,m_pListener() ,m_bActive( false ) + ,m_bLivesInTopWindow( false ) { } @@ -133,6 +134,7 @@ namespace dbaui Reference< XDocumentEventBroadcaster > m_xDocEventBroadcaster; ::rtl::Reference< FrameWindowActivationListener > m_pListener; bool m_bActive; + bool m_bLivesInTopWindow; }; //==================================================================== @@ -206,7 +208,7 @@ namespace dbaui if ( !xCompController.is() ) return; - if ( _rData.m_bActive ) + if ( _rData.m_bActive && _rData.m_bLivesInTopWindow ) { // set the "current component" at the SfxObjectShell Reference< XModel > xModel( xCompController->getModel() ); @@ -259,7 +261,7 @@ namespace dbaui FrameWindowActivationListener::FrameWindowActivationListener( ControllerFrame_Data& _rData ) :m_pData( &_rData ) { - impl_actOnFrameWindow_nothrow( true ); + impl_registerOnFrameContainerWindow_nothrow( true ); } //-------------------------------------------------------------------- @@ -270,14 +272,14 @@ namespace dbaui //-------------------------------------------------------------------- void FrameWindowActivationListener::dispose() { - impl_actOnFrameWindow_nothrow( false ); + impl_registerOnFrameContainerWindow_nothrow( false ); m_pData = NULL; } //-------------------------------------------------------------------- - void FrameWindowActivationListener::impl_actOnFrameWindow_nothrow( bool _bRegister ) + void FrameWindowActivationListener::impl_registerOnFrameContainerWindow_nothrow( bool _bRegister ) { - OSL_ENSURE( m_pData && m_pData->m_xFrame.is(), "FrameWindowActivationListener::impl_actOnFrameWindow_nothrow: no frame!" ); + OSL_ENSURE( m_pData && m_pData->m_xFrame.is(), "FrameWindowActivationListener::impl_registerOnFrameContainerWindow_nothrow: no frame!" ); if ( !m_pData || !m_pData->m_xFrame.is() ) return; @@ -286,8 +288,11 @@ namespace dbaui void ( SAL_CALL XTopWindow::*pListenerAction )( const Reference< XTopWindowListener >& ) = _bRegister ? &XTopWindow::addTopWindowListener : &XTopWindow::removeTopWindowListener; - Reference< XTopWindow > xFrameContainer( m_pData->m_xFrame->getContainerWindow(), UNO_QUERY_THROW ); - (xFrameContainer.get()->*pListenerAction)( this ); + Reference< XTopWindow > xFrameContainer( m_pData->m_xFrame->getContainerWindow(), UNO_QUERY ); + if ( _bRegister ) + m_pData->m_bLivesInTopWindow = xFrameContainer.is(); + if ( xFrameContainer.is() ) + (xFrameContainer.get()->*pListenerAction)( this ); } catch( const Exception& ) { diff --git a/dbaccess/source/ui/querydesign/QTableWindow.cxx b/dbaccess/source/ui/querydesign/QTableWindow.cxx index a02b5e993c194..fe4e3512cb7f9 100644 --- a/dbaccess/source/ui/querydesign/QTableWindow.cxx +++ b/dbaccess/source/ui/querydesign/QTableWindow.cxx @@ -148,8 +148,10 @@ sal_Bool OQueryTableWindow::Init() if (m_strInitialAlias.getLength() ) // Der Alias wurde explizit mit angegeben sAliasName = m_strInitialAlias; - else + else if ( GetTable().is() ) GetTable()->getPropertyValue( PROPERTY_NAME ) >>= sAliasName; + else + return sal_False; // Alias mit fortlaufender Nummer versehen if (pContainer->CountTableAlias(sAliasName, m_nAliasNum)) diff --git a/dbaccess/source/ui/querydesign/QueryDesignFieldUndoAct.hxx b/dbaccess/source/ui/querydesign/QueryDesignFieldUndoAct.hxx index 34b74f0569e57..0973aeb767fb2 100644 --- a/dbaccess/source/ui/querydesign/QueryDesignFieldUndoAct.hxx +++ b/dbaccess/source/ui/querydesign/QueryDesignFieldUndoAct.hxx @@ -100,7 +100,7 @@ namespace dbaui public: OTabFieldSizedUndoAct(OSelectionBrowseBox* pSelBrwBox) : OQueryDesignFieldUndoAct(pSelBrwBox, STR_QUERY_UNDO_SIZE_COLUMN), m_nNextWidth(0) { } - inline void SetOriginalWidth(long nWidth) { OSL_ENSURE(m_nNextWidth != 0,"Width is 0!");m_nNextWidth = nWidth; } + inline void SetOriginalWidth(long nWidth) { m_nNextWidth = nWidth; } virtual void Undo(); virtual void Redo() { Undo(); } diff --git a/dbaccess/source/ui/querydesign/QueryDesignView.cxx b/dbaccess/source/ui/querydesign/QueryDesignView.cxx index 87bfaffa6d7cc..713395d0f1246 100644 --- a/dbaccess/source/ui/querydesign/QueryDesignView.cxx +++ b/dbaccess/source/ui/querydesign/QueryDesignView.cxx @@ -2840,20 +2840,13 @@ SqlParseError OQueryDesignView::InsertField( const OTableFieldDescRef& rInfo, sa return m_pSelectionBox->InsertField( rInfo, BROWSER_INVALIDID,bVis, bActivate ).isValid() ? eOk : eTooManyColumns; } // ----------------------------------------------------------------------------- -sal_Bool OQueryDesignView::getColWidth( const ::rtl::OUString& rAliasName, const ::rtl::OUString& rFieldName, sal_uInt32& nWidth ) +sal_Int32 OQueryDesignView::getColWidth(sal_uInt16 _nColPos) const { - OTableFields& aFields = static_cast<OQueryController&>(getController()).getTableFieldDesc(); - OTableFields::iterator aIter = aFields.begin(); - for(;aIter != aFields.end();++aIter) - { - if( rAliasName == (*aIter)->GetFieldAlias() && rFieldName == (*aIter)->GetField()) - { - nWidth = (*aIter)->GetColWidth(); - return sal_True; - } - } - - return sal_False; + static sal_Int32 s_nDefaultWidth = GetTextWidth(String(RTL_CONSTASCII_USTRINGPARAM("0"))) * 15; + sal_Int32 nWidth = static_cast<OQueryController&>(getController()).getColWidth(_nColPos); + if ( !nWidth ) + nWidth = s_nDefaultWidth; + return nWidth; } //------------------------------------------------------------------------------ void OQueryDesignView::fillValidFields(const ::rtl::OUString& sAliasName, ComboBox* pFieldList) diff --git a/dbaccess/source/ui/querydesign/SelectionBrowseBox.cxx b/dbaccess/source/ui/querydesign/SelectionBrowseBox.cxx index 241e5f439909a..12b3093e96643 100644 --- a/dbaccess/source/ui/querydesign/SelectionBrowseBox.cxx +++ b/dbaccess/source/ui/querydesign/SelectionBrowseBox.cxx @@ -1658,8 +1658,11 @@ void OSelectionBrowseBox::InsertColumn(OTableFieldDescRef pEntry, USHORT& _nColu pEntry->SetFunction(sFunctionName); } + nColumnId = pEntry->GetColumnId(); + + SetColWidth(nColumnId,getDesignView()->getColWidth(GetColumnPos(nColumnId)-1)); // Neuzeichnen - Rectangle aInvalidRect = GetInvalidRect( pEntry->GetColumnId() ); + Rectangle aInvalidRect = GetInvalidRect( nColumnId ); Invalidate( aInvalidRect ); ActivateCell( nCurrentRow, nCurCol ); @@ -1707,11 +1710,6 @@ OTableFieldDescRef OSelectionBrowseBox::InsertField(const OTableFieldDescRef& _r // Neue Spaltenbeschreibung OTableFieldDescRef pEntry = _rInfo; pEntry->SetVisible(bVis); - sal_uInt32 nColWidth; - if( getDesignView()->getColWidth(_rInfo->GetAlias(), _rInfo->GetField(), nColWidth) ) - pEntry->SetColWidth( (sal_uInt16)nColWidth ); - else - pEntry->SetColWidth( (sal_uInt16)DEFAULT_SIZE ); // Spalte einfuegen InsertColumn( pEntry, _nColumnPostion ); diff --git a/dbaccess/source/ui/querydesign/TableConnection.cxx b/dbaccess/source/ui/querydesign/TableConnection.cxx index 95fb6bc38681b..11e9da016f0d1 100644 --- a/dbaccess/source/ui/querydesign/TableConnection.cxx +++ b/dbaccess/source/ui/querydesign/TableConnection.cxx @@ -156,12 +156,24 @@ namespace dbaui //------------------------------------------------------------------------ OTableWindow* OTableConnection::GetSourceWin() const { - return m_pParent->GetTabWindow( GetData()->getReferencingTable()->GetWinName() ); + TTableWindowData::value_type pRef = GetData()->getReferencingTable(); + OTableWindow* pRet = m_pParent->GetTabWindow( pRef->GetWinName() ); + if ( !pRet ) + { + pRet = m_pParent->GetTabWindow( pRef->GetComposedName() ); + } + return pRet; } //------------------------------------------------------------------------ OTableWindow* OTableConnection::GetDestWin() const { - return m_pParent->GetTabWindow( GetData()->getReferencedTable()->GetWinName() ); + TTableWindowData::value_type pRef = GetData()->getReferencedTable(); + OTableWindow* pRet = m_pParent->GetTabWindow( pRef->GetWinName() ); + if ( !pRet ) + { + pRet = m_pParent->GetTabWindow( pRef->GetComposedName() ); + } + return pRet; } //------------------------------------------------------------------------ diff --git a/dbaccess/source/ui/querydesign/TableFieldDescription.cxx b/dbaccess/source/ui/querydesign/TableFieldDescription.cxx index 0b93274c05ae7..0949c8f5dc11a 100644 --- a/dbaccess/source/ui/querydesign/TableFieldDescription.cxx +++ b/dbaccess/source/ui/querydesign/TableFieldDescription.cxx @@ -156,42 +156,42 @@ void OTableFieldDesc::Load(const ::com::sun::star::beans::PropertyValue& _rPrope DBG_CHKTHIS(OTableFieldDesc,NULL); Sequence<PropertyValue> aFieldDesc; _rProperty.Value >>= aFieldDesc; - if ( aFieldDesc.getLength() == 13 ) + //if ( aFieldDesc.getLength() == 12 ) { sal_Int32 nCount = aFieldDesc.getLength(); for (sal_Int32 nPos = 0; nPos < nCount; ++nPos) { - if ( aFieldDesc[nPos].Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AliasName")) ) + if ( aFieldDesc[nPos].Name.equalsAscii("AliasName") ) aFieldDesc[nPos].Value >>= m_aAliasName; - else if ( aFieldDesc[nPos].Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("TableName")) ) + else if ( aFieldDesc[nPos].Name.equalsAscii("TableName") ) aFieldDesc[nPos].Value >>= m_aTableName; - else if ( aFieldDesc[nPos].Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("FieldName")) ) + else if ( aFieldDesc[nPos].Name.equalsAscii("FieldName") ) aFieldDesc[nPos].Value >>= m_aFieldName; - else if ( aFieldDesc[nPos].Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("FieldAlias")) ) + else if ( aFieldDesc[nPos].Name.equalsAscii("FieldAlias") ) aFieldDesc[nPos].Value >>= m_aFieldAlias; - else if ( aFieldDesc[nPos].Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("FunctionName")) ) + else if ( aFieldDesc[nPos].Name.equalsAscii("FunctionName") ) aFieldDesc[nPos].Value >>= m_aFunctionName; - else if ( aFieldDesc[nPos].Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DataType")) ) + else if ( aFieldDesc[nPos].Name.equalsAscii("DataType") ) aFieldDesc[nPos].Value >>= m_eDataType; - else if ( aFieldDesc[nPos].Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("FunctionType")) ) + else if ( aFieldDesc[nPos].Name.equalsAscii("FunctionType") ) aFieldDesc[nPos].Value >>= m_eFunctionType; - else if ( aFieldDesc[nPos].Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("FieldType")) ) + else if ( aFieldDesc[nPos].Name.equalsAscii("FieldType") ) { sal_Int32 nTemp = 0; aFieldDesc[nPos].Value >>= nTemp; m_eFieldType = static_cast<ETableFieldType>(nTemp); } - else if ( aFieldDesc[nPos].Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("OrderDir")) ) + else if ( aFieldDesc[nPos].Name.equalsAscii("OrderDir") ) { sal_Int32 nTemp = 0; aFieldDesc[nPos].Value >>= nTemp; m_eOrderDir = static_cast<EOrderDir>(nTemp); } - else if ( aFieldDesc[nPos].Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ColWidth")) ) + else if ( aFieldDesc[nPos].Name.equalsAscii("ColWidth") ) aFieldDesc[nPos].Value >>= m_nColWidth; - else if ( aFieldDesc[nPos].Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("GroupBy")) ) + else if ( aFieldDesc[nPos].Name.equalsAscii("GroupBy") ) aFieldDesc[nPos].Value >>= m_bGroupBy; - else if ( aFieldDesc[nPos].Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Visible")) ) + else if ( aFieldDesc[nPos].Name.equalsAscii("Visible") ) aFieldDesc[nPos].Value >>= m_bVisible; } } diff --git a/dbaccess/source/ui/querydesign/querycontroller.cxx b/dbaccess/source/ui/querydesign/querycontroller.cxx index 4bbd4e1dd419f..48f51b31d5fdd 100644 --- a/dbaccess/source/ui/querydesign/querycontroller.cxx +++ b/dbaccess/source/ui/querydesign/querycontroller.cxx @@ -931,6 +931,7 @@ void OQueryController::impl_initialize() } } + getUndoMgr()->Clear(); if ( ( m_bGraphicalDesign ) @@ -1138,39 +1139,36 @@ void OQueryController::saveViewSettings(Sequence<PropertyValue>& _rViewProps) // ----------------------------------------------------------------------------- void OQueryController::loadViewSettings(const Sequence<PropertyValue>& _rViewProps) { - ////////////////////////////////////////////////////////////////////// - // Liste loeschen - OTableFields().swap(m_vTableFieldDesc); - const PropertyValue *pIter = _rViewProps.getConstArray(); const PropertyValue *pEnd = pIter + _rViewProps.getLength(); for (; pIter != pEnd; ++pIter) { - if ( pIter->Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SplitterPosition")) ) + if ( pIter->Name.equalsAscii("SplitterPosition") ) { pIter->Value >>= m_nSplitPos; } - else if ( pIter->Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VisibleRows")) ) + else if ( pIter->Name.equalsAscii("VisibleRows") ) { pIter->Value >>= m_nVisibleRows; } - else if ( pIter->Name == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Fields")) ) + else if ( pIter->Name.equalsAscii("Fields") ) { - Sequence<PropertyValue> aFields; - pIter->Value >>= aFields; - m_vTableFieldDesc.reserve(aFields.getLength() + 1); - const PropertyValue *pFieldIter = aFields.getConstArray(); - const PropertyValue *pFieldEnd = pFieldIter + aFields.getLength(); - for (; pFieldIter != pFieldEnd; ++pFieldIter) - { - OTableFieldDescRef pData = new OTableFieldDesc(); - pData->Load(*pFieldIter); - m_vTableFieldDesc.push_back(pData); - } + pIter->Value >>= m_aFieldInformation; } } } // ----------------------------------------------------------------------------- +sal_Int32 OQueryController::getColWidth(sal_uInt16 _nColPos) const +{ + if ( _nColPos < m_aFieldInformation.getLength() ) + { + ::std::auto_ptr<OTableFieldDesc> pField( new OTableFieldDesc()); + pField->Load(m_aFieldInformation[_nColPos]); + return pField->GetColWidth(); + } + return 0; +} +// ----------------------------------------------------------------------------- Reference<XNameAccess> OQueryController::getObjectContainer() const { Reference< XNameAccess > xElements; @@ -1595,8 +1593,8 @@ short OQueryController::saveModified() void OQueryController::impl_reset() { bool bValid = false; - Sequence< PropertyValue > aLayoutInformation; + Sequence< PropertyValue > aLayoutInformation; // get command from the query if a query name was supplied if ( !editingCommand() ) { @@ -1657,7 +1655,6 @@ void OQueryController::impl_reset() DBG_UNHANDLED_EXCEPTION(); } } - if ( m_sStatement.getLength() ) { setQueryComposer(); diff --git a/dbaccess/source/ui/tabledesign/TableController.cxx b/dbaccess/source/ui/tabledesign/TableController.cxx index 72b2a0382fbfe..33990f5f296a4 100644 --- a/dbaccess/source/ui/tabledesign/TableController.cxx +++ b/dbaccess/source/ui/tabledesign/TableController.cxx @@ -677,6 +677,8 @@ sal_Bool SAL_CALL OTableController::suspend(sal_Bool /*_bSuspend*/) throw( Runti ::osl::MutexGuard aGuard( getMutex() ); if ( getView() && getView()->IsInModalMode() ) return sal_False; + if ( getView() ) + static_cast<OTableDesignView*>(getView())->GrabFocus(); sal_Bool bCheck = sal_True; if ( isModified() ) { diff --git a/reportdesign/java/com/sun/star/report/SDBCReportDataFactory.java b/reportdesign/java/com/sun/star/report/SDBCReportDataFactory.java index 915e4523504a7..463bf0a44f11d 100644 --- a/reportdesign/java/com/sun/star/report/SDBCReportDataFactory.java +++ b/reportdesign/java/com/sun/star/report/SDBCReportDataFactory.java @@ -1,639 +1,637 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: SDBCReportDataFactory.java,v $ - * $Revision: 1.9.18.1 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * <http://www.openoffice.org/license.html> - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -package com.sun.star.report; - -import com.sun.star.beans.PropertyVetoException; -import com.sun.star.beans.UnknownPropertyException; -import com.sun.star.beans.XPropertySet; -import com.sun.star.container.NoSuchElementException; -import com.sun.star.container.XIndexAccess; -import com.sun.star.lang.IllegalArgumentException; -import com.sun.star.lang.WrappedTargetException; -import com.sun.star.sdbc.XConnection; -import com.sun.star.container.XNameAccess; -import com.sun.star.lang.XComponent; -import com.sun.star.lang.XMultiServiceFactory; -import com.sun.star.sdb.CommandType; -import com.sun.star.sdb.XCompletedExecution; -import com.sun.star.sdb.XParametersSupplier; -import com.sun.star.sdb.XQueriesSupplier; -import com.sun.star.sdb.XSingleSelectQueryComposer; -import com.sun.star.sdb.tools.XConnectionTools; -import com.sun.star.sdbc.SQLException; -import com.sun.star.sdbc.XParameters; -import com.sun.star.sdbc.XPreparedStatement; -import com.sun.star.uno.Exception; -import java.util.Map; - -import com.sun.star.sdbc.XRowSet; -import com.sun.star.sdbcx.XColumnsSupplier; -import com.sun.star.sdbcx.XTablesSupplier; -import com.sun.star.task.XInteractionHandler; -import com.sun.star.uno.UnoRuntime; -import com.sun.star.uno.XComponentContext; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import org.jfree.util.Log; - -/** - * Very primitive implementation, just to show how this could be used ... - * - */ -public class SDBCReportDataFactory implements DataSourceFactory -{ - - public static final String COMMAND_TYPE = "command-type"; - public static final String ESCAPE_PROCESSING = "escape-processing"; - public static final String GROUP_EXPRESSIONS = "group-expressions"; - public static final String MASTER_VALUES = "master-values"; - public static final String DETAIL_COLUMNS = "detail-columns"; - public static final String UNO_FILTER = "Filter"; - private static final String APPLY_FILTER = "ApplyFilter"; - private static final String UNO_COMMAND = "Command"; - private static final String UNO_ORDER = "Order"; - private static final String UNO_APPLY_FILTER = "ApplyFilter"; - private static final String UNO_COMMAND_TYPE = "CommandType"; - private final XConnection connection; - private final XComponentContext m_cmpCtx; - private static final int FAILED = 0; - private static final int DONE = 1; - private static final int RETRIEVE_COLUMNS = 2; - private static final int RETRIEVE_OBJECT = 3; - private static final int HANDLE_QUERY = 4; - private static final int HANDLE_TABLE = 5; - private static final int HANDLE_SQL = 6; - - public SDBCReportDataFactory(final XComponentContext cmpCtx, final XConnection connection) - { - this.connection = connection; - m_cmpCtx = cmpCtx; - } - - public DataSource queryData(final String command, final Map parameters) throws DataSourceException - { - try - { - if (command == null) - { - return new SDBCReportData(null); - } - int commandType = CommandType.COMMAND; - final String commandTypeValue = (String) parameters.get(COMMAND_TYPE); - if (commandTypeValue != null) - { - if (commandTypeValue.equals("query")) - { - commandType = CommandType.QUERY; - } - else if (commandTypeValue.equals("table")) - { - commandType = CommandType.TABLE; - } - else - { - commandType = CommandType.COMMAND; - } - } - final XRowSet rowSet = createRowSet(command, commandType, parameters); - final XPropertySet rowSetProp = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, rowSet); - - final XConnectionTools tools = (XConnectionTools) UnoRuntime.queryInterface(XConnectionTools.class, connection); - fillOrderStatement(command, commandType, parameters, tools, rowSetProp); - - if (command.length() != 0) - { - final int oldParameterCount = fillParameter(parameters, tools, command, commandType, rowSet); - - final XCompletedExecution execute = (XCompletedExecution) UnoRuntime.queryInterface(XCompletedExecution.class, rowSet); - if (execute != null && oldParameterCount > 0) - { - final XInteractionHandler handler = (XInteractionHandler) UnoRuntime.queryInterface(XInteractionHandler.class, m_cmpCtx.getServiceManager().createInstanceWithContext("com.sun.star.sdb.InteractionHandler", m_cmpCtx)); - execute.executeWithCompletion(handler); - } - else - { - rowSet.execute(); - } - } - return new SDBCReportData(rowSet); - } - catch (Exception ex) - { - throw new DataSourceException(ex.getMessage(), ex); - } - } - - private String getOrderStatement(final int commandType, final String command, final List groupExpressions) - { - final StringBuffer order = new StringBuffer(); - final int count = groupExpressions.size(); - if (count != 0) - { - try - { - final String quote = connection.getMetaData().getIdentifierQuoteString(); - final XComponent[] hold = new XComponent[1]; - final XNameAccess columns = getFieldsByCommandDescriptor(commandType, command, hold); - - for (int i = 0; i < count; i++) - { - final Object[] pair = (Object[]) groupExpressions.get(i); - String expression = (String) pair[0]; - - if (columns.hasByName(expression)) - { - expression = quote + expression + quote; - } - expression = expression.trim(); // Trim away white spaces - - if (expression.length() > 0) - { - order.append(expression); - if (order.length() > 0) - { - order.append(' '); - } - final String sorting = (String) pair[1]; - if (sorting == null || sorting.equals(OfficeToken.FALSE)) - { - order.append("DESC"); - } - if ((i + 1) < count) - { - order.append(' '); - } - } - } - } - catch (IndexOutOfBoundsException ex) - { - Log.error("ReportProcessing failed", ex); - } - catch (SQLException ex) - { - Log.error("ReportProcessing failed", ex); - } - } - return order.toString(); - } - - private XNameAccess getFieldsByCommandDescriptor(final int commandType, final String command, final XComponent[] out) throws SQLException - { - final Class[] parameter = new Class[3]; - parameter[0] = Integer.class; - parameter[1] = String.class; - parameter[2] = out.getClass(); - final XConnectionTools tools = (XConnectionTools) UnoRuntime.queryInterface(XConnectionTools.class, connection); - try - { - tools.getClass().getMethod("getFieldsByCommandDescriptor", parameter); - return tools.getFieldsByCommandDescriptor(commandType, command, out); - } - catch (NoSuchMethodException ex) - { - } - - XNameAccess xFields = null; - // some kind of state machine to ease the sharing of code - int eState = FAILED; - switch (commandType) - { - case CommandType.TABLE: - eState = HANDLE_TABLE; - break; - case CommandType.QUERY: - eState = HANDLE_QUERY; - break; - case CommandType.COMMAND: - eState = HANDLE_SQL; - break; - } - - // needed in various states: - XNameAccess xObjectCollection = null; - XColumnsSupplier xSupplyColumns = null; - - try - { - // go! - while ((DONE != eState) && (FAILED != eState)) - { - switch (eState) - { - case HANDLE_TABLE: - { - // initial state for handling the tables - - // get the table objects - final XTablesSupplier xSupplyTables = (XTablesSupplier) UnoRuntime.queryInterface(XTablesSupplier.class, connection); - if (xSupplyTables != null) - { - xObjectCollection = xSupplyTables.getTables(); - // if something went wrong 'til here, then this will be handled in the next state - - // next state: get the object - } - eState = RETRIEVE_OBJECT; - } - break; - - case HANDLE_QUERY: - { - // initial state for handling the tables - - // get the table objects - final XQueriesSupplier xSupplyQueries = (XQueriesSupplier) UnoRuntime.queryInterface(XQueriesSupplier.class, connection); - if (xSupplyQueries != null) - { - xObjectCollection = xSupplyQueries.getQueries(); - // if something went wrong 'til here, then this will be handled in the next state - - // next state: get the object - } - eState = RETRIEVE_OBJECT; - } - break; - - case RETRIEVE_OBJECT: - // here we should have an object (aka query or table) collection, and are going - // to retrieve the desired object - - // next state: default to FAILED - eState = FAILED; - - if (xObjectCollection != null && xObjectCollection.hasByName(command)) - { - xSupplyColumns = (XColumnsSupplier) UnoRuntime.queryInterface(XColumnsSupplier.class, xObjectCollection.getByName(command)); - - // next: go for the columns - eState = RETRIEVE_COLUMNS; - } - break; - - case RETRIEVE_COLUMNS: - // next state: default to FAILED - eState = FAILED; - - if (xSupplyColumns != null) - { - xFields = xSupplyColumns.getColumns(); - // that's it - eState = DONE; - } - break; - - case HANDLE_SQL: - { - String sStatementToExecute = command; - - // well, the main problem here is to handle statements which contain a parameter - // If we would simply execute a parametrized statement, then this will fail because - // we cannot supply any parameter values. - // Thus, we try to analyze the statement, and to append a WHERE 0=1 filter criterion - // This should cause every driver to not really execute the statement, but to return - // an empty result set with the proper structure. We then can use this result set - // to retrieve the columns. - - try - { - final XMultiServiceFactory xComposerFac = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, connection); - - if (xComposerFac != null) - { - final XSingleSelectQueryComposer xComposer = (XSingleSelectQueryComposer) UnoRuntime.queryInterface(XSingleSelectQueryComposer.class, xComposerFac.createInstance("com.sun.star.sdb.SingleSelectQueryComposer")); - if (xComposer != null) - { - xComposer.setQuery(sStatementToExecute); - - // Now set the filter to a dummy restriction which will result in an empty - // result set. - xComposer.setFilter("0=1"); - - sStatementToExecute = xComposer.getQuery(); - } - } - } - catch (com.sun.star.uno.Exception ex) - { - // silent this error, this was just a try. If we're here, we did not change sStatementToExecute, - // so it will still be _rCommand, which then will be executed without being touched - } - - // now execute - XPreparedStatement xStatement = connection.prepareStatement(sStatementToExecute); - // transfer ownership of this temporary object to the caller - out[0] = (XComponent) UnoRuntime.queryInterface(XComponent.class, xStatement); - - // set the "MaxRows" to 0. This is just in case our attempt to append a 0=1 filter - // failed - in this case, the MaxRows restriction should at least ensure that there - // is no data returned (which would be potentially expensive) - final XPropertySet xStatementProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xStatement); - try - { - if (xStatementProps != null) - { - xStatementProps.setPropertyValue("MaxRows", new Integer(0)); - } - } - catch (com.sun.star.uno.Exception ex) - { - // oh damn. Not much of a chance to recover, we will no retrieve the complete - // full blown result set - } - - xSupplyColumns = (XColumnsSupplier) UnoRuntime.queryInterface(XColumnsSupplier.class, xStatement.executeQuery()); - // this should have given us a result set which does not contain any data, but - // the structural information we need - - // so the next state is to get the columns - eState = RETRIEVE_COLUMNS; - } - break; - default: - eState = FAILED; - } - } - } - catch (com.sun.star.uno.Exception ex) - { - } - return xFields; - } - - private XSingleSelectQueryComposer getComposer(final XConnectionTools tools, - final String command, - final int commandType) - { - final Class[] parameter = new Class[2]; - parameter[0] = Integer.class; - parameter[1] = String.class; - try - { - final Object[] param = new Object[2]; - param[0] = new Integer(commandType); - param[1] = command; - return (XSingleSelectQueryComposer) tools.getClass().getMethod("getComposer", parameter).invoke(tools, param); - } - catch (NoSuchMethodException ex) - { - } - catch (IllegalAccessException ex) - { - // should not happen - // assert False - } - catch (java.lang.reflect.InvocationTargetException ex) - { - // should not happen - // assert False - } - try - { - final XMultiServiceFactory factory = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, connection); - final XSingleSelectQueryComposer out = (XSingleSelectQueryComposer) UnoRuntime.queryInterface(XSingleSelectQueryComposer.class, factory.createInstance("com.sun.star.sdb.SingleSelectQueryAnalyzer")); - final String quote = connection.getMetaData().getIdentifierQuoteString(); - String statement = command; - switch (commandType) - { - case CommandType.TABLE: - statement = "SELECT * FROM " + quote + command + quote; - break; - case CommandType.QUERY: - { - final XQueriesSupplier xSupplyQueries = (XQueriesSupplier) UnoRuntime.queryInterface(XQueriesSupplier.class, connection); - final XNameAccess queries = xSupplyQueries.getQueries(); - if (queries.hasByName(command)) - { - final XPropertySet prop = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, queries.getByName(command)); - final Boolean escape = (Boolean) prop.getPropertyValue("EscapeProcessing"); - if (escape.booleanValue()) - { - statement = (String) prop.getPropertyValue(UNO_COMMAND); - final XSingleSelectQueryComposer composer = getComposer(tools, statement, CommandType.COMMAND); - if (composer != null) - { - final String order = (String) prop.getPropertyValue(UNO_ORDER); - if (order != null && order.length() != 0) - { - composer.setOrder(order); - } - final Boolean applyFilter = (Boolean) prop.getPropertyValue(UNO_APPLY_FILTER); - if (applyFilter.booleanValue()) - { - final String filter = (String) prop.getPropertyValue(UNO_FILTER); - if (filter != null && filter.length() != 0) - { - composer.setFilter(filter); - } - } - statement = composer.getQuery(); - } - } - } - } - break; - case CommandType.COMMAND: - statement = command; - break; - } - out.setElementaryQuery(statement); - return out; - } - catch (Exception e) - { - } - return null; - } - - int fillParameter(final Map parameters, - final XConnectionTools tools, - final String command, - final int commandType, final XRowSet rowSet) - throws SQLException, - UnknownPropertyException, - PropertyVetoException, - IllegalArgumentException, - WrappedTargetException - { - int oldParameterCount = 0; - - final XSingleSelectQueryComposer composer = getComposer(tools, command, commandType); - if (composer != null) - { - // get old parameter count - final XParametersSupplier paraSup = (XParametersSupplier) UnoRuntime.queryInterface(XParametersSupplier.class, composer); - if (paraSup != null) - { - final XIndexAccess params = paraSup.getParameters(); - if (params != null) - { - oldParameterCount = params.getCount(); - } - } - final ArrayList masterValues = (ArrayList) parameters.get(MASTER_VALUES); - if (masterValues != null && !masterValues.isEmpty()) - { - // Vector masterColumns = (Vector) parameters.get("master-columns"); - final ArrayList detailColumns = (ArrayList) parameters.get(DETAIL_COLUMNS); - - // create the new filter - final String quote = connection.getMetaData().getIdentifierQuoteString(); - final StringBuffer oldFilter = new StringBuffer(); - oldFilter.append(composer.getFilter()); - if (oldFilter.length() != 0) - { - oldFilter.append(" AND "); - } - int newParamterCounter = 1; - for (final Iterator it = detailColumns.iterator(); it.hasNext(); - ++newParamterCounter) - { - final String detail = (String) it.next(); - //String master = (String) masterIt.next(); - oldFilter.append(quote); - oldFilter.append(detail); - oldFilter.append(quote); - oldFilter.append(" = :link_"); - oldFilter.append(newParamterCounter); - if (it.hasNext()) - { - oldFilter.append(" AND "); - } - } - - composer.setFilter(oldFilter.toString()); - - final String sQuery = composer.getQuery(); - final XPropertySet rowSetProp = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, rowSet); - rowSetProp.setPropertyValue(UNO_COMMAND, sQuery); - rowSetProp.setPropertyValue(UNO_COMMAND_TYPE, - new Integer(CommandType.COMMAND)); - - final XParameters para = (XParameters) UnoRuntime.queryInterface(XParameters.class, rowSet); - - for (int i = 0; - i < masterValues.size(); - i++) - { - Object object = masterValues.get(i); - if (object instanceof BigDecimal) - { - object = ((BigDecimal) object).toString(); - } - para.setObject(oldParameterCount + i + 1, object); - } - } - } - - return oldParameterCount; - } - - final XRowSet createRowSet(final String command, - final int commandType, final Map parameters) - throws Exception - { - final XRowSet rowSet = (XRowSet) UnoRuntime.queryInterface(XRowSet.class, m_cmpCtx.getServiceManager().createInstanceWithContext("com.sun.star.sdb.RowSet", m_cmpCtx)); - final XPropertySet rowSetProp = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, rowSet); - - rowSetProp.setPropertyValue("ActiveConnection", connection); - final Boolean escapeProcessing = (Boolean)parameters.get(ESCAPE_PROCESSING); - rowSetProp.setPropertyValue("EscapeProcessing", escapeProcessing); - rowSetProp.setPropertyValue(UNO_COMMAND_TYPE, new Integer(commandType)); - rowSetProp.setPropertyValue(UNO_COMMAND, command); - - final String filter = (String) parameters.get(UNO_FILTER); - if (filter != null) - { - rowSetProp.setPropertyValue("Filter", filter); - rowSetProp.setPropertyValue(APPLY_FILTER, Boolean.valueOf(filter.length() != 0)); - } - else - { - rowSetProp.setPropertyValue(APPLY_FILTER, Boolean.FALSE); - } - return rowSet; - } - - void fillOrderStatement(final String command, - final int commandType, final Map parameters, - final XConnectionTools tools, - final XPropertySet rowSetProp) - throws SQLException, - UnknownPropertyException, - PropertyVetoException, - IllegalArgumentException, - WrappedTargetException, - NoSuchElementException - { - final StringBuffer order = new StringBuffer(getOrderStatement(commandType, command, (ArrayList) parameters.get(GROUP_EXPRESSIONS))); - if (order.length() > 0 && commandType != CommandType.TABLE) - { - String statement = command; - final XSingleSelectQueryComposer composer = getComposer(tools, command, commandType); - if (composer != null) - { - statement = composer.getQuery(); - composer.setQuery(statement); - final String sOldOrder = composer.getOrder(); - if (sOldOrder.length() > 0) - { - order.append(','); - order.append(sOldOrder); - composer.setOrder(""); - statement = composer.getQuery(); - } - } - else - { - if (commandType == CommandType.QUERY) - { - final XQueriesSupplier xSupplyQueries = (XQueriesSupplier) UnoRuntime.queryInterface(XQueriesSupplier.class, connection); - final XNameAccess queries = xSupplyQueries.getQueries(); - if (queries.hasByName(command)) - { - final XPropertySet prop = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, queries.getByName(command)); - final String queryCommand = (String) prop.getPropertyValue(UNO_COMMAND); - statement = "SELECT * FROM (" + queryCommand + ")"; - } - } - else - { - statement = "SELECT * FROM (" + command + ")"; - } - } - rowSetProp.setPropertyValue(UNO_COMMAND, statement); - rowSetProp.setPropertyValue(UNO_COMMAND_TYPE, new Integer(CommandType.COMMAND)); - } - rowSetProp.setPropertyValue("Order", order.toString()); - } -} - +/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: SDBCReportDataFactory.java,v $
+ * $Revision: 1.9.18.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package com.sun.star.report;
+
+import com.sun.star.beans.PropertyVetoException;
+import com.sun.star.beans.UnknownPropertyException;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.container.NoSuchElementException;
+import com.sun.star.container.XIndexAccess;
+import com.sun.star.lang.IllegalArgumentException;
+import com.sun.star.lang.WrappedTargetException;
+import com.sun.star.sdbc.XConnection;
+import com.sun.star.container.XNameAccess;
+import com.sun.star.lang.XComponent;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.sdb.CommandType;
+import com.sun.star.sdb.XCompletedExecution;
+import com.sun.star.sdb.XParametersSupplier;
+import com.sun.star.sdb.XQueriesSupplier;
+import com.sun.star.sdb.XSingleSelectQueryComposer;
+import com.sun.star.sdb.tools.XConnectionTools;
+import com.sun.star.sdbc.SQLException;
+import com.sun.star.sdbc.XParameters;
+import com.sun.star.sdbc.XPreparedStatement;
+import com.sun.star.uno.Exception;
+import java.util.Map;
+
+import com.sun.star.sdbc.XRowSet;
+import com.sun.star.sdbcx.XColumnsSupplier;
+import com.sun.star.sdbcx.XTablesSupplier;
+import com.sun.star.task.XInteractionHandler;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.XComponentContext;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import org.jfree.util.Log;
+
+/**
+ * Very primitive implementation, just to show how this could be used ...
+ *
+ */
+public class SDBCReportDataFactory implements DataSourceFactory
+{
+
+ public static final String COMMAND_TYPE = "command-type";
+ public static final String ESCAPE_PROCESSING = "escape-processing";
+ public static final String GROUP_EXPRESSIONS = "group-expressions";
+ public static final String MASTER_VALUES = "master-values";
+ public static final String MASTER_COLUMNS = "master-columns";
+ public static final String DETAIL_COLUMNS = "detail-columns";
+ public static final String UNO_FILTER = "Filter";
+ private static final String APPLY_FILTER = "ApplyFilter";
+ private static final String UNO_COMMAND = "Command";
+ private static final String UNO_ORDER = "Order";
+ private static final String UNO_APPLY_FILTER = "ApplyFilter";
+ private static final String UNO_COMMAND_TYPE = "CommandType";
+ private final XConnection connection;
+ private final XComponentContext m_cmpCtx;
+ private static final int FAILED = 0;
+ private static final int DONE = 1;
+ private static final int RETRIEVE_COLUMNS = 2;
+ private static final int RETRIEVE_OBJECT = 3;
+ private static final int HANDLE_QUERY = 4;
+ private static final int HANDLE_TABLE = 5;
+ private static final int HANDLE_SQL = 6;
+
+ public SDBCReportDataFactory(final XComponentContext cmpCtx, final XConnection connection)
+ {
+ this.connection = connection;
+ m_cmpCtx = cmpCtx;
+ }
+
+ public DataSource queryData(final String command, final Map parameters) throws DataSourceException
+ {
+ try
+ {
+ if ( command == null )
+ {
+ return new SDBCReportData(null);
+ }
+ int commandType = CommandType.COMMAND;
+ final String commandTypeValue = (String) parameters.get(COMMAND_TYPE);
+ if ( commandTypeValue != null )
+ {
+ if ( commandTypeValue.equals("query") )
+ {
+ commandType = CommandType.QUERY;
+ }
+ else if ( commandTypeValue.equals("table") )
+ {
+ commandType = CommandType.TABLE;
+ }
+ else
+ {
+ commandType = CommandType.COMMAND;
+ }
+ }
+ final XRowSet rowSet = createRowSet(command, commandType, parameters);
+ final XPropertySet rowSetProp = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, rowSet);
+
+ final XConnectionTools tools = (XConnectionTools) UnoRuntime.queryInterface(XConnectionTools.class, connection);
+ fillOrderStatement(command, commandType, parameters, tools, rowSetProp);
+
+ if ( command.length() != 0 )
+ {
+ final int oldParameterCount = fillParameter(parameters, tools, command, commandType, rowSet);
+
+ final XCompletedExecution execute = (XCompletedExecution) UnoRuntime.queryInterface(XCompletedExecution.class, rowSet);
+ if ( execute != null && oldParameterCount > 0 )
+ {
+ final XInteractionHandler handler = (XInteractionHandler) UnoRuntime.queryInterface(XInteractionHandler.class, m_cmpCtx.getServiceManager().createInstanceWithContext("com.sun.star.sdb.InteractionHandler", m_cmpCtx));
+ execute.executeWithCompletion(handler);
+ }
+ else
+ {
+ rowSet.execute();
+ }
+ }
+ return new SDBCReportData(rowSet);
+ } catch ( Exception ex )
+ {
+ throw new DataSourceException(ex.getMessage(), ex);
+ }
+ }
+
+ private String getOrderStatement(final int commandType, final String command, final List groupExpressions)
+ {
+ final StringBuffer order = new StringBuffer();
+ final int count = groupExpressions.size();
+ if ( count != 0 )
+ {
+ try
+ {
+ final String quote = connection.getMetaData().getIdentifierQuoteString();
+ final XComponent[] hold = new XComponent[1];
+ final XNameAccess columns = getFieldsByCommandDescriptor(commandType, command, hold);
+
+ for (int i = 0; i < count; i++)
+ {
+ final Object[] pair = (Object[]) groupExpressions.get(i);
+ String expression = (String) pair[0];
+
+ if ( columns.hasByName(expression) )
+ {
+ expression = quote + expression + quote;
+ }
+ expression = expression.trim(); // Trim away white spaces
+
+ if ( expression.length() > 0 )
+ {
+ order.append(expression);
+ if ( order.length() > 0 )
+ {
+ order.append(' ');
+ }
+ final String sorting = (String) pair[1];
+ if ( sorting == null || sorting.equals(OfficeToken.FALSE) )
+ {
+ order.append("DESC");
+ }
+ if ( (i + 1) < count )
+ {
+ order.append(' ');
+ }
+ }
+ }
+ } catch ( IndexOutOfBoundsException ex )
+ {
+ Log.error("ReportProcessing failed", ex);
+ } catch ( SQLException ex )
+ {
+ Log.error("ReportProcessing failed", ex);
+ }
+ }
+ return order.toString();
+ }
+
+ private XNameAccess getFieldsByCommandDescriptor(final int commandType, final String command, final XComponent[] out) throws SQLException
+ {
+ final Class[] parameter = new Class[3];
+ parameter[0] = Integer.class;
+ parameter[1] = String.class;
+ parameter[2] = out.getClass();
+ final XConnectionTools tools = (XConnectionTools) UnoRuntime.queryInterface(XConnectionTools.class, connection);
+ try
+ {
+ tools.getClass().getMethod("getFieldsByCommandDescriptor", parameter);
+ return tools.getFieldsByCommandDescriptor(commandType, command, out);
+ } catch ( NoSuchMethodException ex )
+ {
+ }
+
+ XNameAccess xFields = null;
+ // some kind of state machine to ease the sharing of code
+ int eState = FAILED;
+ switch ( commandType )
+ {
+ case CommandType.TABLE:
+ eState = HANDLE_TABLE;
+ break;
+ case CommandType.QUERY:
+ eState = HANDLE_QUERY;
+ break;
+ case CommandType.COMMAND:
+ eState = HANDLE_SQL;
+ break;
+ }
+
+ // needed in various states:
+ XNameAccess xObjectCollection = null;
+ XColumnsSupplier xSupplyColumns = null;
+
+ try
+ {
+ // go!
+ while ((DONE != eState) && (FAILED != eState))
+ {
+ switch ( eState )
+ {
+ case HANDLE_TABLE:
+ {
+ // initial state for handling the tables
+
+ // get the table objects
+ final XTablesSupplier xSupplyTables = (XTablesSupplier) UnoRuntime.queryInterface(XTablesSupplier.class, connection);
+ if ( xSupplyTables != null )
+ {
+ xObjectCollection = xSupplyTables.getTables();
+ // if something went wrong 'til here, then this will be handled in the next state
+
+ // next state: get the object
+ }
+ eState = RETRIEVE_OBJECT;
+ }
+ break;
+
+ case HANDLE_QUERY:
+ {
+ // initial state for handling the tables
+
+ // get the table objects
+ final XQueriesSupplier xSupplyQueries = (XQueriesSupplier) UnoRuntime.queryInterface(XQueriesSupplier.class, connection);
+ if ( xSupplyQueries != null )
+ {
+ xObjectCollection = xSupplyQueries.getQueries();
+ // if something went wrong 'til here, then this will be handled in the next state
+
+ // next state: get the object
+ }
+ eState = RETRIEVE_OBJECT;
+ }
+ break;
+
+ case RETRIEVE_OBJECT:
+ // here we should have an object (aka query or table) collection, and are going
+ // to retrieve the desired object
+
+ // next state: default to FAILED
+ eState = FAILED;
+
+ if ( xObjectCollection != null && xObjectCollection.hasByName(command) )
+ {
+ xSupplyColumns = (XColumnsSupplier) UnoRuntime.queryInterface(XColumnsSupplier.class, xObjectCollection.getByName(command));
+
+ // next: go for the columns
+ eState = RETRIEVE_COLUMNS;
+ }
+ break;
+
+ case RETRIEVE_COLUMNS:
+ // next state: default to FAILED
+ eState = FAILED;
+
+ if ( xSupplyColumns != null )
+ {
+ xFields = xSupplyColumns.getColumns();
+ // that's it
+ eState = DONE;
+ }
+ break;
+
+ case HANDLE_SQL:
+ {
+ String sStatementToExecute = command;
+
+ // well, the main problem here is to handle statements which contain a parameter
+ // If we would simply execute a parametrized statement, then this will fail because
+ // we cannot supply any parameter values.
+ // Thus, we try to analyze the statement, and to append a WHERE 0=1 filter criterion
+ // This should cause every driver to not really execute the statement, but to return
+ // an empty result set with the proper structure. We then can use this result set
+ // to retrieve the columns.
+
+ try
+ {
+ final XMultiServiceFactory xComposerFac = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, connection);
+
+ if ( xComposerFac != null )
+ {
+ final XSingleSelectQueryComposer xComposer = (XSingleSelectQueryComposer) UnoRuntime.queryInterface(XSingleSelectQueryComposer.class, xComposerFac.createInstance("com.sun.star.sdb.SingleSelectQueryComposer"));
+ if ( xComposer != null )
+ {
+ xComposer.setQuery(sStatementToExecute);
+
+ // Now set the filter to a dummy restriction which will result in an empty
+ // result set.
+ xComposer.setFilter("0=1");
+
+ sStatementToExecute = xComposer.getQuery();
+ }
+ }
+ } catch ( com.sun.star.uno.Exception ex )
+ {
+ // silent this error, this was just a try. If we're here, we did not change sStatementToExecute,
+ // so it will still be _rCommand, which then will be executed without being touched
+ }
+
+ // now execute
+ XPreparedStatement xStatement = connection.prepareStatement(sStatementToExecute);
+ // transfer ownership of this temporary object to the caller
+ out[0] = (XComponent) UnoRuntime.queryInterface(XComponent.class, xStatement);
+
+ // set the "MaxRows" to 0. This is just in case our attempt to append a 0=1 filter
+ // failed - in this case, the MaxRows restriction should at least ensure that there
+ // is no data returned (which would be potentially expensive)
+ final XPropertySet xStatementProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xStatement);
+ try
+ {
+ if ( xStatementProps != null )
+ {
+ xStatementProps.setPropertyValue("MaxRows", new Integer(0));
+ }
+ } catch ( com.sun.star.uno.Exception ex )
+ {
+ // oh damn. Not much of a chance to recover, we will no retrieve the complete
+ // full blown result set
+ }
+
+ xSupplyColumns = (XColumnsSupplier) UnoRuntime.queryInterface(XColumnsSupplier.class, xStatement.executeQuery());
+ // this should have given us a result set which does not contain any data, but
+ // the structural information we need
+
+ // so the next state is to get the columns
+ eState = RETRIEVE_COLUMNS;
+ }
+ break;
+ default:
+ eState = FAILED;
+ }
+ }
+ } catch ( com.sun.star.uno.Exception ex )
+ {
+ }
+ return xFields;
+ }
+
+ private XSingleSelectQueryComposer getComposer(final XConnectionTools tools,
+ final String command,
+ final int commandType)
+ {
+ final Class[] parameter = new Class[2];
+ parameter[0] = int.class;
+ parameter[1] = String.class;
+ try
+ {
+ final Object[] param = new Object[2];
+ param[0] = new Integer(commandType);
+ param[1] = command;
+ return (XSingleSelectQueryComposer) tools.getClass().getMethod("getComposer", parameter).invoke(tools, param);
+ } catch ( NoSuchMethodException ex )
+ {
+ } catch ( IllegalAccessException ex )
+ {
+ // should not happen
+ // assert False
+ } catch ( java.lang.reflect.InvocationTargetException ex )
+ {
+ // should not happen
+ // assert False
+ }
+ try
+ {
+ final XMultiServiceFactory factory = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, connection);
+ final XSingleSelectQueryComposer out = (XSingleSelectQueryComposer) UnoRuntime.queryInterface(XSingleSelectQueryComposer.class, factory.createInstance("com.sun.star.sdb.SingleSelectQueryAnalyzer"));
+ final String quote = connection.getMetaData().getIdentifierQuoteString();
+ String statement = command;
+ switch ( commandType )
+ {
+ case CommandType.TABLE:
+ statement = "SELECT * FROM " + quote + command + quote;
+ break;
+ case CommandType.QUERY:
+ {
+ final XQueriesSupplier xSupplyQueries = (XQueriesSupplier) UnoRuntime.queryInterface(XQueriesSupplier.class, connection);
+ final XNameAccess queries = xSupplyQueries.getQueries();
+ if ( queries.hasByName(command) )
+ {
+ final XPropertySet prop = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, queries.getByName(command));
+ final Boolean escape = (Boolean) prop.getPropertyValue("EscapeProcessing");
+ if (escape.booleanValue())
+ {
+ statement = (String) prop.getPropertyValue(UNO_COMMAND);
+ final XSingleSelectQueryComposer composer = getComposer(tools, statement, CommandType.COMMAND);
+ if (composer != null)
+ {
+ final String order = (String) prop.getPropertyValue(UNO_ORDER);
+ if (order != null && order.length() != 0)
+ {
+ composer.setOrder(order);
+ }
+ final Boolean applyFilter = (Boolean) prop.getPropertyValue(UNO_APPLY_FILTER);
+ if (applyFilter.booleanValue())
+ {
+ final String filter = (String) prop.getPropertyValue(UNO_FILTER);
+ if (filter != null && filter.length() != 0)
+ {
+ composer.setFilter(filter);
+ }
+ }
+ statement = composer.getQuery();
+ }
+ }
+ }
+ }
+ break;
+ case CommandType.COMMAND:
+ statement = command;
+ break;
+ }
+ out.setElementaryQuery(statement);
+ return out;
+ } catch ( Exception e )
+ {
+ }
+ return null;
+ }
+
+ int fillParameter(final Map parameters,
+ final XConnectionTools tools,
+ final String command,
+ final int commandType, final XRowSet rowSet)
+ throws SQLException,
+ UnknownPropertyException,
+ PropertyVetoException,
+ IllegalArgumentException,
+ WrappedTargetException
+ {
+ int oldParameterCount = 0;
+
+ final XSingleSelectQueryComposer composer = getComposer(tools, command, commandType);
+ if ( composer != null )
+ {
+ final XPropertySet rowSetProp = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, rowSet);
+ if ( ((Boolean)rowSetProp.getPropertyValue(APPLY_FILTER)).booleanValue() )
+ {
+ composer.setFilter((String)rowSetProp.getPropertyValue("Filter"));
+ }
+ // get old parameter count
+ final XParametersSupplier paraSup = (XParametersSupplier) UnoRuntime.queryInterface(XParametersSupplier.class, composer);
+ if ( paraSup != null )
+ {
+ final XIndexAccess params = paraSup.getParameters();
+ if ( params != null )
+ {
+ oldParameterCount = params.getCount();
+ }
+ }
+ final ArrayList masterValues = (ArrayList) parameters.get(MASTER_VALUES);
+ if ( masterValues != null && !masterValues.isEmpty() )
+ {
+ // Vector masterColumns = (Vector) parameters.get("master-columns");
+ final ArrayList detailColumns = (ArrayList) parameters.get(DETAIL_COLUMNS);
+ if ( oldParameterCount < detailColumns.size() )
+ {
+ // create the new filter
+ final String quote = connection.getMetaData().getIdentifierQuoteString();
+ final StringBuffer oldFilter = new StringBuffer();
+ oldFilter.append(composer.getFilter());
+ if ( oldFilter.length() != 0 )
+ {
+ oldFilter.append(" AND ");
+ }
+ int newParamterCounter = 1;
+ for (final Iterator it = detailColumns.iterator(); it.hasNext();
+ ++newParamterCounter)
+ {
+ final String detail = (String) it.next();
+ //String master = (String) masterIt.next();
+ oldFilter.append(quote);
+ oldFilter.append(detail);
+ oldFilter.append(quote);
+ oldFilter.append(" = :link_");
+ oldFilter.append(newParamterCounter);
+ if ( it.hasNext() )
+ {
+ oldFilter.append(" AND ");
+ }
+ }
+
+ composer.setFilter(oldFilter.toString());
+ }
+ else
+ oldParameterCount = 0;
+
+ final String sQuery = composer.getQuery();
+ rowSetProp.setPropertyValue(UNO_COMMAND, sQuery);
+ rowSetProp.setPropertyValue(UNO_COMMAND_TYPE,
+ new Integer(CommandType.COMMAND));
+
+ final XParameters para = (XParameters) UnoRuntime.queryInterface(XParameters.class, rowSet);
+
+ for (int i = 0;
+ i < masterValues.size();
+ i++)
+ {
+ Object object = masterValues.get(i);
+ if ( object instanceof BigDecimal )
+ {
+ object = ((BigDecimal) object).toString();
+ }
+ para.setObject(oldParameterCount + i + 1, object);
+ }
+ }
+ }
+
+ return oldParameterCount;
+ }
+
+ private final XRowSet createRowSet(final String command,
+ final int commandType, final Map parameters)
+ throws Exception
+ {
+ final XRowSet rowSet = (XRowSet) UnoRuntime.queryInterface(XRowSet.class, m_cmpCtx.getServiceManager().createInstanceWithContext("com.sun.star.sdb.RowSet", m_cmpCtx));
+ final XPropertySet rowSetProp = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, rowSet);
+
+ rowSetProp.setPropertyValue("ActiveConnection", connection);
+ final Boolean escapeProcessing = (Boolean)parameters.get(ESCAPE_PROCESSING);
+ rowSetProp.setPropertyValue("EscapeProcessing", escapeProcessing);
+ rowSetProp.setPropertyValue(UNO_COMMAND_TYPE, new Integer(commandType));
+ rowSetProp.setPropertyValue(UNO_COMMAND, command);
+
+ final String filter = (String) parameters.get(UNO_FILTER);
+ if ( filter != null )
+ {
+ rowSetProp.setPropertyValue("Filter", filter);
+ rowSetProp.setPropertyValue(APPLY_FILTER, Boolean.valueOf(filter.length() != 0));
+ }
+ else
+ {
+ rowSetProp.setPropertyValue(APPLY_FILTER, Boolean.FALSE);
+ }
+ return rowSet;
+ }
+
+ void fillOrderStatement(final String command,
+ final int commandType, final Map parameters,
+ final XConnectionTools tools,
+ final XPropertySet rowSetProp)
+ throws SQLException,
+ UnknownPropertyException,
+ PropertyVetoException,
+ IllegalArgumentException,
+ WrappedTargetException,
+ NoSuchElementException
+ {
+ final StringBuffer order = new StringBuffer(getOrderStatement(commandType, command, (ArrayList) parameters.get(GROUP_EXPRESSIONS)));
+ if ( order.length() > 0 && commandType != CommandType.TABLE )
+ {
+ String statement = command;
+ final XSingleSelectQueryComposer composer = getComposer(tools, command, commandType);
+ if ( composer != null )
+ {
+ statement = composer.getQuery();
+ composer.setQuery(statement);
+ final String sOldOrder = composer.getOrder();
+ if ( sOldOrder.length() > 0 )
+ {
+ order.append(',');
+ order.append(sOldOrder);
+ composer.setOrder("");
+ statement = composer.getQuery();
+ }
+ }
+ else
+ {
+ if ( commandType == CommandType.QUERY )
+ {
+ final XQueriesSupplier xSupplyQueries = (XQueriesSupplier) UnoRuntime.queryInterface(XQueriesSupplier.class, connection);
+ final XNameAccess queries = xSupplyQueries.getQueries();
+ if ( queries.hasByName(command) )
+ {
+ final XPropertySet prop = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, queries.getByName(command));
+ final String queryCommand = (String) prop.getPropertyValue(UNO_COMMAND);
+ statement = "SELECT * FROM (" + queryCommand + ")";
+ }
+ }
+ else
+ {
+ statement = "SELECT * FROM (" + command + ")";
+ }
+ }
+ rowSetProp.setPropertyValue(UNO_COMMAND, statement);
+ rowSetProp.setPropertyValue(UNO_COMMAND_TYPE, new Integer(CommandType.COMMAND));
+ }
+ rowSetProp.setPropertyValue("Order", order.toString());
+ }
+}
+
diff --git a/reportdesign/java/com/sun/star/report/function/metadata/MetaDataFunctionCategory.java b/reportdesign/java/com/sun/star/report/function/metadata/MetaDataFunctionCategory.java index f7daee9fdb23b..3a5b43aee9fdd 100644 --- a/reportdesign/java/com/sun/star/report/function/metadata/MetaDataFunctionCategory.java +++ b/reportdesign/java/com/sun/star/report/function/metadata/MetaDataFunctionCategory.java @@ -1,48 +1,48 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: MetaDataFunctionCategory.java,v $ - * $Revision: 1.2 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * <http://www.openoffice.org/license.html> - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -package com.sun.star.report.function.metadata; - -import org.jfree.formula.function.AbstractFunctionCategory; -import org.jfree.formula.function.FunctionCategory; - -/** - * - * @author Ocke Janssen - */ -public class MetaDataFunctionCategory extends AbstractFunctionCategory -{ - - public static final FunctionCategory CATEGORY = new MetaDataFunctionCategory(); - - private MetaDataFunctionCategory() - { - super("com.sun.star.report.functions.metadata.category"); - } -} +/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: MetaDataFunctionCategory.java,v $
+ * $Revision: 1.2 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package com.sun.star.report.function.metadata;
+
+import org.jfree.formula.function.AbstractFunctionCategory;
+import org.jfree.formula.function.FunctionCategory;
+
+/**
+ *
+ * @author Ocke Janssen
+ */
+public class MetaDataFunctionCategory extends AbstractFunctionCategory
+{
+
+ public static final FunctionCategory CATEGORY = new MetaDataFunctionCategory();
+
+ private MetaDataFunctionCategory()
+ {
+ super("com.sun.star.report.function.metadata.category");
+ }
+}
diff --git a/reportdesign/java/com/sun/star/report/function/metadata/category.properties b/reportdesign/java/com/sun/star/report/function/metadata/category.properties index 44b7ed1d5e9b5..7240967b7d572 100644 --- a/reportdesign/java/com/sun/star/report/function/metadata/category.properties +++ b/reportdesign/java/com/sun/star/report/function/metadata/category.properties @@ -1,33 +1,33 @@ -#************************************************************************* -# -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# Copyright 2008 by Sun Microsystems, Inc. -# -# OpenOffice.org - a multi-platform office productivity suite -# -# $RCSfile: category.properties,v $ -# -# $Revision: 1.2 $ -# -# This file is part of OpenOffice.org. -# -# OpenOffice.org is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License version 3 -# only, as published by the Free Software Foundation. -# -# OpenOffice.org is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License version 3 for more details -# (a copy is included in the LICENSE file that accompanied this code). -# -# You should have received a copy of the GNU Lesser General Public License -# version 3 along with OpenOffice.org. If not, see -# <http://www.openoffice.org/license.html> -# for a copy of the LGPLv3 License. -# -#************************************************************************* - -display-name=MetaData -description=Contains functions about meta data
\ No newline at end of file +#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: category.properties,v $
+#
+# $Revision: 1.2 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+display-name=Document Information
+description=Contains functions to access document information.
diff --git a/reportdesign/java/com/sun/star/report/pentaho/layoutprocessor/ObjectOleLayoutController.java b/reportdesign/java/com/sun/star/report/pentaho/layoutprocessor/ObjectOleLayoutController.java index 5ce156c2be09c..8cddecd485641 100644 --- a/reportdesign/java/com/sun/star/report/pentaho/layoutprocessor/ObjectOleLayoutController.java +++ b/reportdesign/java/com/sun/star/report/pentaho/layoutprocessor/ObjectOleLayoutController.java @@ -1,125 +1,125 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: ObjectOleLayoutController.java,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * <http://www.openoffice.org/license.html> - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -package com.sun.star.report.pentaho.layoutprocessor; - -import com.sun.star.report.SDBCReportDataFactory; -import com.sun.star.report.pentaho.OfficeNamespaces; -import com.sun.star.report.OfficeToken; -import com.sun.star.report.pentaho.model.ObjectOleElement; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import org.jfree.report.DataSourceException; -import org.jfree.report.ReportDataFactoryException; -import org.jfree.report.ReportProcessingException; -import org.jfree.report.flow.ReportTarget; -import org.jfree.report.flow.layoutprocessor.LayoutController; -import org.jfree.layouting.util.AttributeMap; -import org.jfree.report.DataFlags; -import org.jfree.report.DataRow; -import org.jfree.report.JFreeReportInfo; -import org.jfree.report.structure.Element; - -/** - * - * @author Ocke Janssen - */ -public class ObjectOleLayoutController extends AbstractReportElementLayoutController -{ - - public ObjectOleLayoutController() - { - } - - protected boolean isValueChanged() - { - final ObjectOleElement element = (ObjectOleElement) getNode(); - final List masterfields = element.getMasterfields(); - final DataRow view = getFlowController().getMasterRow().getGlobalView(); - for (final Iterator iter = masterfields.iterator(); iter.hasNext();) - { - final String master = (String) iter.next(); - try - { - final DataFlags flags = view.getFlags(master); - if (flags != null && flags.isChanged()) - { - return true; - } - } - catch (DataSourceException e) - { - // ignore .. assume that the reference has not changed. - } - } - return false; - } - - protected LayoutController delegateContentGeneration(final ReportTarget target) throws ReportProcessingException, ReportDataFactoryException, DataSourceException - { - final ObjectOleElement element = (ObjectOleElement) getNode(); - final String url = element.getUrl(); - if (url != null) - { - final AttributeMap ole = new AttributeMap(); - ole.setAttribute(JFreeReportInfo.REPORT_NAMESPACE, Element.NAMESPACE_ATTRIBUTE, OfficeNamespaces.INTERNAL_NS); - ole.setAttribute(JFreeReportInfo.REPORT_NAMESPACE, Element.TYPE_ATTRIBUTE, OfficeToken.OBJECT_OLE); - ole.setAttribute(OfficeNamespaces.INTERNAL_NS, "href", url); - ole.setAttribute(OfficeNamespaces.INTERNAL_NS, "class-id", element.getClassid()); - final List masterfields = element.getMasterfields(); - final List values = new ArrayList(); - final DataRow view = getFlowController().getMasterRow().getGlobalView(); - for (final Iterator iter = masterfields.iterator(); iter.hasNext();) - { - final String master = (String) iter.next(); - try - { - final DataFlags flags = view.getFlags(master); - if (flags != null) - { - values.add(flags.getValue()); - } - } - catch (DataSourceException e) - { - // ignore .. assume that the reference has not changed. - } - } - ole.setAttribute(OfficeNamespaces.INTERNAL_NS, "master-columns", masterfields); - ole.setAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.MASTER_VALUES, values); - ole.setAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.DETAIL_COLUMNS, element.getDetailfields()); - - target.startElement(ole); - target.endElement(ole); - } - - return join(getFlowController()); - } -} +/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ObjectOleLayoutController.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package com.sun.star.report.pentaho.layoutprocessor;
+
+import com.sun.star.report.SDBCReportDataFactory;
+import com.sun.star.report.pentaho.OfficeNamespaces;
+import com.sun.star.report.OfficeToken;
+import com.sun.star.report.pentaho.model.ObjectOleElement;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import org.jfree.report.DataSourceException;
+import org.jfree.report.ReportDataFactoryException;
+import org.jfree.report.ReportProcessingException;
+import org.jfree.report.flow.ReportTarget;
+import org.jfree.report.flow.layoutprocessor.LayoutController;
+import org.jfree.layouting.util.AttributeMap;
+import org.jfree.report.DataFlags;
+import org.jfree.report.DataRow;
+import org.jfree.report.JFreeReportInfo;
+import org.jfree.report.structure.Element;
+
+/**
+ *
+ * @author Ocke Janssen
+ */
+public class ObjectOleLayoutController extends AbstractReportElementLayoutController
+{
+
+ public ObjectOleLayoutController()
+ {
+ }
+
+ protected boolean isValueChanged()
+ {
+ final ObjectOleElement element = (ObjectOleElement) getNode();
+ final List masterfields = element.getMasterfields();
+ final DataRow view = getFlowController().getMasterRow().getGlobalView();
+ for (final Iterator iter = masterfields.iterator(); iter.hasNext();)
+ {
+ final String master = (String) iter.next();
+ try
+ {
+ final DataFlags flags = view.getFlags(master);
+ if (flags != null && flags.isChanged())
+ {
+ return true;
+ }
+ }
+ catch (DataSourceException e)
+ {
+ // ignore .. assume that the reference has not changed.
+ }
+ }
+ return false;
+ }
+
+ protected LayoutController delegateContentGeneration(final ReportTarget target) throws ReportProcessingException, ReportDataFactoryException, DataSourceException
+ {
+ final ObjectOleElement element = (ObjectOleElement) getNode();
+ final String url = element.getUrl();
+ if (url != null)
+ {
+ final AttributeMap ole = new AttributeMap();
+ ole.setAttribute(JFreeReportInfo.REPORT_NAMESPACE, Element.NAMESPACE_ATTRIBUTE, OfficeNamespaces.INTERNAL_NS);
+ ole.setAttribute(JFreeReportInfo.REPORT_NAMESPACE, Element.TYPE_ATTRIBUTE, OfficeToken.OBJECT_OLE);
+ ole.setAttribute(OfficeNamespaces.INTERNAL_NS, "href", url);
+ ole.setAttribute(OfficeNamespaces.INTERNAL_NS, "class-id", element.getClassid());
+ final List masterfields = element.getMasterfields();
+ final List values = new ArrayList();
+ final DataRow view = getFlowController().getMasterRow().getGlobalView();
+ for (final Iterator iter = masterfields.iterator(); iter.hasNext();)
+ {
+ final String master = (String) iter.next();
+ try
+ {
+ final DataFlags flags = view.getFlags(master);
+ if (flags != null)
+ {
+ values.add(flags.getValue());
+ }
+ }
+ catch (DataSourceException e)
+ {
+ // ignore .. assume that the reference has not changed.
+ }
+ }
+ ole.setAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.MASTER_COLUMNS, masterfields);
+ ole.setAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.MASTER_VALUES, values);
+ ole.setAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.DETAIL_COLUMNS, element.getDetailfields());
+
+ target.startElement(ole);
+ target.endElement(ole);
+ }
+
+ return join(getFlowController());
+ }
+}
diff --git a/reportdesign/java/com/sun/star/report/pentaho/output/OfficeDocumentReportTarget.java b/reportdesign/java/com/sun/star/report/pentaho/output/OfficeDocumentReportTarget.java index faaaed0dcd319..623a4a77b6108 100644 --- a/reportdesign/java/com/sun/star/report/pentaho/output/OfficeDocumentReportTarget.java +++ b/reportdesign/java/com/sun/star/report/pentaho/output/OfficeDocumentReportTarget.java @@ -1,1636 +1,1636 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: OfficeDocumentReportTarget.java,v $ - * $Revision: 1.9 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * <http://www.openoffice.org/license.html> - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -package com.sun.star.report.pentaho.output; - -import com.sun.star.report.DataSourceFactory; -import java.awt.Image; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.StringWriter; -import java.io.Writer; -import java.util.Iterator; -import java.util.Map; -import java.util.zip.DeflaterOutputStream; -import java.util.zip.InflaterInputStream; - -import com.sun.star.report.ImageService; -import com.sun.star.report.InputRepository; -import com.sun.star.report.OutputRepository; -import com.sun.star.report.SDBCReportDataFactory; -import com.sun.star.report.pentaho.OfficeNamespaces; -import com.sun.star.report.OfficeToken; -import com.sun.star.report.pentaho.layoutprocessor.ImageElementContext; -import com.sun.star.report.pentaho.model.OfficeDocument; -import com.sun.star.report.pentaho.model.OfficeStyle; -import com.sun.star.report.pentaho.model.OfficeStyles; -import com.sun.star.report.pentaho.model.OfficeStylesCollection; -import com.sun.star.report.pentaho.styles.LengthCalculator; -import com.sun.star.report.pentaho.styles.StyleMapper; -import java.util.ArrayList; -import org.jfree.io.IOUtils; -import org.jfree.layouting.input.style.parser.CSSValueFactory; -import org.jfree.layouting.input.style.parser.StyleSheetParserUtil; -import org.jfree.layouting.input.style.values.CSSNumericValue; -import org.jfree.layouting.layouter.style.CSSValueResolverUtility; -import org.jfree.layouting.namespace.NamespaceDefinition; -import org.jfree.layouting.namespace.Namespaces; -import org.jfree.layouting.util.AttributeMap; -import org.jfree.report.DataFlags; -import org.jfree.report.DataSourceException; -import org.jfree.report.JFreeReportBoot; -import org.jfree.report.JFreeReportInfo; -import org.jfree.report.ReportProcessingException; -import org.jfree.report.flow.AbstractReportTarget; -import org.jfree.report.flow.ReportJob; -import org.jfree.report.flow.ReportStructureRoot; -import org.jfree.report.flow.ReportTargetUtil; -import org.jfree.report.structure.Element; -import org.jfree.report.structure.Section; -import org.jfree.report.util.AttributeNameGenerator; -import org.jfree.report.util.IntegerCache; -import org.jfree.report.util.MemoryByteArrayOutputStream; -import org.jfree.resourceloader.ResourceException; -import org.jfree.resourceloader.ResourceKey; -import org.jfree.resourceloader.ResourceManager; -import org.jfree.util.FastStack; -import org.jfree.util.LineBreakIterator; -import org.jfree.util.Log; -import org.jfree.xmlns.common.AttributeList; -import org.jfree.xmlns.writer.DefaultTagDescription; -import org.jfree.xmlns.writer.XmlWriter; -import org.jfree.xmlns.writer.XmlWriterSupport; -import org.w3c.css.sac.LexicalUnit; - -/** - * Todo: Document me! - * - * @author Thomas Morgner - * @since 08.03.2007 - */ -public abstract class OfficeDocumentReportTarget extends AbstractReportTarget -{ - - public static final String HORIZONTAL_POS = "horizontal-pos"; - public static final String TAG_DEF_PREFIX = "com.sun.star.report.pentaho.output."; - public static final int ROLE_NONE = 0; - public static final int ROLE_REPORT_HEADER = 1; - public static final int ROLE_REPORT_FOOTER = 2; - public static final int ROLE_GROUP_HEADER = 3; - public static final int ROLE_GROUP_FOOTER = 4; - public static final int ROLE_REPEATING_GROUP_HEADER = 5; - public static final int ROLE_REPEATING_GROUP_FOOTER = 6; - public static final int ROLE_PAGE_HEADER = 7; - public static final int ROLE_PAGE_FOOTER = 8; - public static final int ROLE_DETAIL = 9; - public static final int ROLE_VARIABLES = 10; - public static final int ROLE_TEMPLATE = 11; - public static final int ROLE_SPREADSHEET_PAGE_HEADER = 12; - public static final int ROLE_SPREADSHEET_PAGE_FOOTER = 13; - public static final int STATE_IN_DOCUMENT = 0; - public static final int STATE_IN_BODY = 1; - public static final int STATE_IN_CONTENT = 2; - public static final int STATE_IN_GROUP = 3; - public static final int STATE_IN_GROUP_BODY = 4; - public static final int STATE_IN_SECTION = 5; - public static final int STATE_IN_OTHER = 6; - public static final int STATE_IN_GROUP_INSTANCE = 7; - public static final String FAILED = "Failed"; - public static final String VERTICAL_POS = "vertical-pos"; - private static final String ZERO_CM = "0cm"; - - protected static class BufferState - { - - private final XmlWriter xmlWriter; - private final MemoryByteArrayOutputStream xmlBuffer; - private final OfficeStylesCollection stylesCollection; - - protected BufferState(final XmlWriter xmlWriter, - final MemoryByteArrayOutputStream xmlBuffer, - final OfficeStylesCollection stylesCollection) - { - this.stylesCollection = stylesCollection; - this.xmlWriter = xmlWriter; - this.xmlBuffer = xmlBuffer; - } - - public OfficeStylesCollection getStylesCollection() - { - return stylesCollection; - } - - public XmlWriter getXmlWriter() - { - return xmlWriter; - } - - public String getXmlBuffer() throws ReportProcessingException - { - try - { - final byte[] zippedData = xmlBuffer.getRaw(); - final InputStreamReader reader = new InputStreamReader(new InflaterInputStream(new ByteArrayInputStream(zippedData, 0, xmlBuffer.getLength())), "UTF-16"); - final StringWriter writer = new StringWriter((zippedData.length / 2) + 1); - IOUtils.getInstance().copyWriter(reader, writer); - return writer.toString(); - } - catch (IOException e) - { - throw new ReportProcessingException("Failed to copy buffer", e); - } - } - - public Reader getXmlAsReader() throws ReportProcessingException - { - try - { - final byte[] zippedData = xmlBuffer.getRaw(); - return new InputStreamReader(new InflaterInputStream(new ByteArrayInputStream(zippedData, 0, xmlBuffer.getLength())), "UTF-16"); - } - catch (IOException e) - { - throw new ReportProcessingException("Failed to copy buffer", e); - } - } - } - - protected static class GroupContext - { - - private final GroupContext parent; - private int iterationCount; - private boolean groupWithRepeatingSection; - - protected GroupContext(final GroupContext parent) - { - this.parent = parent; - } - - public GroupContext getParent() - { - return parent; - } - - public int getIterationCount() - { - return iterationCount; - } - - public void setIterationCount(final int iterationCount) - { - this.iterationCount = iterationCount; - } - - public boolean isGroupWithRepeatingSection() - { - return groupWithRepeatingSection; - } - - public void setGroupWithRepeatingSection(final boolean groupWithRepeatingSection) - { - this.groupWithRepeatingSection = groupWithRepeatingSection; - } - - public String toString() - { - return "GroupContext{" + - "parent=" + parent + - ", iterationCount=" + iterationCount + - ", groupWithRepeatingSection=" + groupWithRepeatingSection + - '}'; - } - } - private final FastStack states; - private int currentRole; - private final FastStack xmlWriters; - private XmlWriter rootXmlWriter; - /** - * This styles-collection contains all styles that were predefined in the report definition file. The common styles - * and the master-styles will be written unmodified, the automatic styles will be ignored. - */ - private OfficeStylesCollection predefinedStylesCollection; - /** - * This styles-collection contains all master-styles that have been generated by the report definition process. It - * also contains all automatic styles that have been generated for the page-bands (and the pagebands as well). - */ - private OfficeStylesCollection globalStylesCollection; - /** - * The content styles collection contains all automatic styles that have been generated for the normal-flow content. - */ - private OfficeStylesCollection contentStylesCollection; - private final OutputRepository outputRepository; - private final InputRepository inputRepository; - private final AttributeNameGenerator tableNameGenerator; - private final AttributeNameGenerator frameNameGenerator; - private final AttributeNameGenerator autoStyleNameGenerator; - private final String target; - private static final int INITIAL_BUFFER_SIZE = 40960; - private StyleMapper styleMapper; - private StyleSheetParserUtil styleSheetParserUtil; - private final AttributeNameGenerator imageNames; - private final ImageProducer imageProducer; - private final OleProducer oleProducer; - private GroupContext groupContext; - private static final boolean DEBUG_ELEMENTS = - JFreeReportBoot.getInstance().getExtendedConfig().getBoolProperty("com.sun.star.report.pentaho.output.DebugElements"); - - protected OfficeDocumentReportTarget(final ReportJob reportJob, - final ResourceManager resourceManager, - final ResourceKey baseResource, - final InputRepository inputRepository, - final OutputRepository outputRepository, - final String target, - final ImageService imageService, - final DataSourceFactory datasourcefactory) - throws ReportProcessingException - { - super(reportJob, resourceManager, baseResource); - if (imageService == null) - { - throw new NullPointerException("ImageService must not be null"); - } - if (target == null) - { - throw new NullPointerException("Target-Name must not be null"); - } - - this.target = target; - - this.tableNameGenerator = new AttributeNameGenerator(); - this.frameNameGenerator = new AttributeNameGenerator(); - this.autoStyleNameGenerator = new AttributeNameGenerator(); - this.outputRepository = outputRepository; - this.inputRepository = inputRepository; - this.states = new FastStack(); - this.xmlWriters = new FastStack(); - this.imageNames = new AttributeNameGenerator(); - - this.imageProducer = new ImageProducer(inputRepository, outputRepository, imageService); - this.oleProducer = new OleProducer(inputRepository, outputRepository, imageService, datasourcefactory); - - try - { - final ResourceManager realResourceManager = getResourceManager(); - styleMapper = StyleMapper.loadInstance(realResourceManager); - } - catch (ResourceException e) - { - throw new ReportProcessingException("Failed to load style-mapper", e); - } - } - - protected abstract String getTargetMimeType(); - - protected OutputRepository getOutputRepository() - { - return outputRepository; - } - - protected InputRepository getInputRepository() - { - return inputRepository; - } - - /** - * Starts the output of a new office document. This method writes the generic 'office:document-content' tag along with - * all known namespace declarations. - * - * @param report the report object. - * @throws DataSourceException if there was an error accessing the datasource - * @throws ReportProcessingException if some other error occured. - */ - public void startReport(final ReportStructureRoot report) - throws DataSourceException, ReportProcessingException - { - imageNames.reset(); - this.groupContext = new GroupContext(null); - - final DefaultTagDescription tagDescription = createTagDescription(); - try - { - final OutputStream outputStream = outputRepository.createOutputStream(target, "text/xml"); - final Writer writer = new OutputStreamWriter(outputStream, "UTF-8"); - - this.rootXmlWriter = new XmlWriter(writer, tagDescription); - this.rootXmlWriter.setAlwaysAddNamespace(true); - - final AttributeList rootAttributes = new AttributeList(); - rootAttributes.addNamespaceDeclaration("office", OfficeNamespaces.OFFICE_NS); - rootAttributes.addNamespaceDeclaration("style", OfficeNamespaces.STYLE_NS); - rootAttributes.addNamespaceDeclaration("text", OfficeNamespaces.TEXT_NS); - rootAttributes.addNamespaceDeclaration("table", OfficeNamespaces.TABLE_NS); - rootAttributes.addNamespaceDeclaration("draw", OfficeNamespaces.DRAWING_NS); - rootAttributes.addNamespaceDeclaration("fo", OfficeNamespaces.FO_NS); - rootAttributes.addNamespaceDeclaration("xlink", OfficeNamespaces.XLINK_NS); - rootAttributes.addNamespaceDeclaration("dc", OfficeNamespaces.PURL_NS); - rootAttributes.addNamespaceDeclaration("meta", OfficeNamespaces.META_NS); - rootAttributes.addNamespaceDeclaration("number", OfficeNamespaces.DATASTYLE_NS); - rootAttributes.addNamespaceDeclaration("svg", OfficeNamespaces.SVG_NS); - rootAttributes.addNamespaceDeclaration("chart", OfficeNamespaces.CHART_NS); - rootAttributes.addNamespaceDeclaration("dr3d", OfficeNamespaces.DR3D_NS); - rootAttributes.addNamespaceDeclaration("math", OfficeNamespaces.MATHML_NS); - rootAttributes.addNamespaceDeclaration("form", OfficeNamespaces.FORM_NS); - rootAttributes.addNamespaceDeclaration("script", OfficeNamespaces.SCRIPT_NS); - rootAttributes.addNamespaceDeclaration("ooo", OfficeNamespaces.OO2004_NS); - rootAttributes.addNamespaceDeclaration("ooow", OfficeNamespaces.OOW2004_NS); - rootAttributes.addNamespaceDeclaration("oooc", OfficeNamespaces.OOC2004_NS); - rootAttributes.addNamespaceDeclaration("dom", OfficeNamespaces.XML_EVENT_NS); - rootAttributes.addNamespaceDeclaration("xforms", OfficeNamespaces.XFORMS_NS); - rootAttributes.addNamespaceDeclaration("xsd", OfficeNamespaces.XSD_NS); - rootAttributes.addNamespaceDeclaration("xsi", OfficeNamespaces.XSI_NS); - rootAttributes.setAttribute(OfficeNamespaces.OFFICE_NS, "version", "1.0"); - - this.rootXmlWriter.writeXmlDeclaration("UTF-8"); - this.rootXmlWriter.writeTag(OfficeNamespaces.OFFICE_NS, "document-content", rootAttributes, XmlWriterSupport.OPEN); - - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_DOCUMENT)); - - autoStyleNameGenerator.reset(); - tableNameGenerator.reset(); - frameNameGenerator.reset(); - - final OfficeDocument reportDoc = (OfficeDocument) report; - predefinedStylesCollection = reportDoc.getStylesCollection(); - - final OfficeStyles commonStyles = predefinedStylesCollection.getCommonStyles(); - if (!commonStyles.containsStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS)) - { - final OfficeStyle graphicsDefaultStyle = new OfficeStyle(); - graphicsDefaultStyle.setStyleFamily(OfficeToken.GRAPHIC); - graphicsDefaultStyle.setStyleName(OfficeToken.GRAPHICS); - final Element graphicProperties = produceFirstChild(graphicsDefaultStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES); - graphicProperties.setAttribute(OfficeNamespaces.TEXT_NS, "anchor-type", OfficeToken.PARAGRAPH); - graphicProperties.setAttribute(OfficeNamespaces.SVG_NS, "x", ZERO_CM); - graphicProperties.setAttribute(OfficeNamespaces.SVG_NS, "y", ZERO_CM); - graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "wrap", "dynamic"); - graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "number-wrapped-paragraphs", "no-limit"); - graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "wrap-contour", OfficeToken.FALSE); - graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, VERTICAL_POS, "from-top"); // changed for chart - - graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "vertical-rel", OfficeToken.PARAGRAPH); - graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, HORIZONTAL_POS, "from-left"); // changed for chart - - graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "horizontal-rel", OfficeToken.PARAGRAPH); - commonStyles.addStyle(graphicsDefaultStyle); - } - - // Make sure that later generated styles do not overwrite existing styles. - fillStyleNameGenerator(predefinedStylesCollection); - - contentStylesCollection = new OfficeStylesCollection(); - globalStylesCollection = new OfficeStylesCollection(); - - startBuffering(contentStylesCollection, true); - } - catch (IOException e) - { - throw new ReportProcessingException(FAILED, e); - } - } - - protected AttributeNameGenerator getAutoStyleNameGenerator() - { - return autoStyleNameGenerator; - } - - private void fillStyleNameGenerator(final OfficeStylesCollection stylesCollection) - { - final OfficeStyles commonStyles = stylesCollection.getCommonStyles(); - final OfficeStyle[] allCommonStyles = commonStyles.getAllStyles(); - for (int i = 0; i < allCommonStyles.length; i++) - { - final OfficeStyle style = allCommonStyles[i]; - autoStyleNameGenerator.generateName(style.getStyleName()); - } - - final OfficeStyles autoStyles = stylesCollection.getAutomaticStyles(); - final OfficeStyle[] allAutoStyles = autoStyles.getAllStyles(); - for (int i = 0; i < allAutoStyles.length; i++) - { - final OfficeStyle style = allAutoStyles[i]; - autoStyleNameGenerator.generateName(style.getStyleName()); - } - } - - public OfficeStylesCollection getPredefinedStylesCollection() - { - return predefinedStylesCollection; - } - - public OfficeStylesCollection getGlobalStylesCollection() - { - return globalStylesCollection; - } - - public OfficeStylesCollection getContentStylesCollection() - { - return contentStylesCollection; - } - - /** - * Returns the XML-Writer tag description. This description defines whether an element can have character data inside. - * Such element will disable the indention, as in that case the additional whitespaces might alter the meaning of the - * element's contents. - * - * @return the tag description library. - */ - protected DefaultTagDescription createTagDescription() - { - final DefaultTagDescription tagDescription = new DefaultTagDescription(); - tagDescription.configure(JFreeReportBoot.getInstance().getGlobalConfig(), - OfficeDocumentReportTarget.TAG_DEF_PREFIX); - return tagDescription; - } - - /** - * Returns the current processing state. - * - * @return the processing state. - */ - protected int getCurrentState() - { - if (states.isEmpty()) - { - throw new IllegalStateException(); - } - final Integer o = (Integer) states.peek(); - return o.intValue(); - } - - /** - * Starts the processing of an element and updates the processing state. This will select an apropriate handler method - * for the call and will call one of the start* methods. - * - * @param attrs the attribute map for the current element - * @throws DataSourceException - * @throws ReportProcessingException - */ - public final void startElement(final AttributeMap attrs) - throws DataSourceException, ReportProcessingException - { - // todo - if (DEBUG_ELEMENTS) - { - Log.debug("Starting " + getCurrentState() + '/' + states.size() + ' ' + - ReportTargetUtil.getNamespaceFromAttribute(attrs) + " -> " + - ReportTargetUtil.getElemenTypeFromAttribute(attrs)); - } - try - { - switch (getCurrentState()) - { - case OfficeDocumentReportTarget.STATE_IN_DOCUMENT: - { - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OFFICE_NS, "body", attrs)) - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_BODY)); - startBody(attrs); - } - else - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_OTHER)); - if (!isFilteredNamespace(ReportTargetUtil.getNamespaceFromAttribute(attrs))) - { - startOther(attrs); - } - } - break; - } - case OfficeDocumentReportTarget.STATE_IN_BODY: - { - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OFFICE_NS, "report", attrs)) - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_CONTENT)); - startContent(attrs); - } - else - { - throw new IllegalStateException("The 'office:body' element must have exactly one child of type 'report'"); - } - break; - } - case OfficeDocumentReportTarget.STATE_IN_CONTENT: - { - // Either a ordinary section or a group .. - // A group. - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "report-body", attrs)) - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP_BODY)); - startGroupBody(attrs); - } - else - { - // Either a template-section, page-header, page-footer, report-header, report-footer - // or variables-section - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION)); - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "template", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_TEMPLATE; - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "page-header", attrs)) - { - if ("spreadsheet-section".equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "role"))) - { - currentRole = OfficeDocumentReportTarget.ROLE_SPREADSHEET_PAGE_HEADER; - } - else - { - currentRole = OfficeDocumentReportTarget.ROLE_PAGE_HEADER; - } - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "page-footer", attrs)) - { - if ("spreadsheet-section".equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "role"))) - { - currentRole = OfficeDocumentReportTarget.ROLE_SPREADSHEET_PAGE_FOOTER; - } - else - { - currentRole = OfficeDocumentReportTarget.ROLE_PAGE_FOOTER; - } - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "report-header", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_REPORT_HEADER; - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "report-footer", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_REPORT_FOOTER; - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "variables-section", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_VARIABLES; - } - else - { - throw new IllegalStateException("Expected either 'template', 'report-body', " + - "'report-header', 'report-footer', 'variables-section', 'page-header' or 'page-footer'"); - } - startReportSection(attrs, currentRole); - } - break; - } - case OfficeDocumentReportTarget.STATE_IN_GROUP_BODY: - { - // We now expect either an other group or a detail band. - - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group", attrs)) - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP)); - groupContext = new GroupContext(groupContext); - startGroup(attrs); - } - else - { - // Either a variables-section, or a detail-band - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION)); - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "detail", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_DETAIL; - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "variables-section", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_VARIABLES; - } - else - { - throw new IllegalStateException("Expected either 'group', 'detail' or 'variables-section'"); - } - startReportSection(attrs, currentRole); - } - break; - } - case OfficeDocumentReportTarget.STATE_IN_GROUP: - { - // A group can carry a repeating group header/footer or a group-instance section. - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "group-instance", attrs)) - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP_INSTANCE)); - startGroupInstance(attrs); - } - else - { - // repeating group header/footer, but *no* variables section - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION)); - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-header", attrs) && - OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "repeated-section"))) - { - currentRole = OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER; - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-footer", attrs) && - OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "repeated-section"))) - { - currentRole = OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER; - } - else - { - throw new IllegalStateException("Expected either 'group-instance', " + - "'repeating group-header' or 'repeating group-footer'"); - } - startReportSection(attrs, currentRole); - } - break; - } - case OfficeDocumentReportTarget.STATE_IN_GROUP_INSTANCE: - { - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "group-body", attrs)) - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP_BODY)); - startGroupBody(attrs); - } - else - { - // Either a group-header or group-footer or variables-section - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION)); - if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-header", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_GROUP_HEADER; - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-footer", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_GROUP_FOOTER; - } - else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "variables-section", attrs)) - { - currentRole = OfficeDocumentReportTarget.ROLE_VARIABLES; - } - else - { - throw new IllegalStateException("Expected either 'group-body', 'group-header', 'group-footer' or 'variables-section'"); - } - startReportSection(attrs, currentRole); - } - break; - } - case OfficeDocumentReportTarget.STATE_IN_SECTION: - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_OTHER)); - startOther(attrs); - break; - } - case OfficeDocumentReportTarget.STATE_IN_OTHER: - { - states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_OTHER)); - startOther(attrs); - break; - } - default: - throw new IllegalStateException("Failure: " + getCurrentState()); - } - } - catch (IOException ioe) - { - Log.error("ReportProcessing failed", ioe); - throw new ReportProcessingException("Failed to write content", ioe); - } -// finally -// { -// Log.debug ("Started " + getNamespaceFromAttribute(attrs) + ":" + -// getElemenTypeFromAttribute(attrs) + " -> " + getCurrentState()); -// } - } - - protected GroupContext getGroupContext() - { - return groupContext; - } - - protected void performStyleProcessing(final AttributeMap attrs) - throws ReportProcessingException - { - final OfficeStylesCollection stylesCollection = getStylesCollection(); - final OfficeStylesCollection predefCollection = getPredefinedStylesCollection(); - final OfficeStylesCollection globalStylesCollection = getGlobalStylesCollection(); - - final String elementNamespace = - ReportTargetUtil.getNamespaceFromAttribute(attrs); - final String elementName = - ReportTargetUtil.getElemenTypeFromAttribute(attrs); - - final String[] namespaces = attrs.getNameSpaces(); - for (int i = 0; i < namespaces.length; i++) - { - final String attrNamespace = namespaces[i]; - if (isFilteredNamespace(attrNamespace)) - { - continue; - } - - final Map attributes = attrs.getAttributes(attrNamespace); - final Iterator iterator = attributes.entrySet().iterator(); - while (iterator.hasNext()) - { - final Map.Entry entry = (Map.Entry) iterator.next(); - final String attrName = (String) entry.getKey(); - final String attrValue = String.valueOf(entry.getValue()); - - final String styleFamily = styleMapper.getStyleFamilyFor(elementNamespace, elementName, attrNamespace, attrName); - if (styleFamily == null) - { - // None of the known style attributes. - continue; - } - - if (styleMapper.isListOfStyles(elementNamespace, elementName, attrNamespace, attrName)) - { - // ignored for now. - Log.warn("List of styles is not yet implemented."); - continue; - } - - // Copy styles is only called once per style. - StyleUtilities.copyStyle(styleFamily, attrValue, stylesCollection, globalStylesCollection, predefCollection); - } - } - } - - protected void startBody(final AttributeMap attrs) - throws IOException - { - getXmlWriter().writeTag(OfficeNamespaces.OFFICE_NS, "body", XmlWriterSupport.OPEN); - } - - private final boolean allowBuffering(final int role) - { - return (role == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER || - role == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER || - role == OfficeDocumentReportTarget.ROLE_TEMPLATE); - } - - protected void startReportSection(final AttributeMap attrs, final int role) - throws IOException, DataSourceException, ReportProcessingException - { - if (allowBuffering(role)) - { - startBuffering(new OfficeStylesCollection(), true); - } - } - - protected abstract void startContent(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException; - - protected void startGroup(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException - { - final Object repeatingHeaderOrFooter = attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "repeating-header-or-footer"); - if (OfficeToken.TRUE.equals(repeatingHeaderOrFooter)) - { - getGroupContext().setGroupWithRepeatingSection(true); - } - - final Object iterationCount = attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "iteration-count"); - if (iterationCount instanceof Number) - { - final Number itNumber = (Number) iterationCount; - getGroupContext().setIterationCount(itNumber.intValue()); - } - } - - protected void startGroupInstance(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException - { - } - - protected void startGroupBody(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException - { - } - - protected abstract void startOther(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException; - - public void processText(final String text) - throws DataSourceException, ReportProcessingException - { - try - { - final XmlWriter xmlWriter = getXmlWriter(); - final LineBreakIterator lb = new LineBreakIterator(text); - while (lb.hasNext()) - { - final String line = (String) lb.next(); - final String normalizedText = XmlWriterSupport.normalize(line, false); - xmlWriter.writeText(normalizedText); - if (lb.hasNext()) - { - xmlWriter.writeTag(OfficeNamespaces.TEXT_NS, "line-break", XmlWriterSupport.CLOSE); - } - } - } - catch (IOException e) - { - throw new ReportProcessingException(FAILED, e); - } - } - - protected boolean isFilteredNamespace(final String namespace) - { - if (Namespaces.LIBLAYOUT_NAMESPACE.equals(namespace)) - { - return true; - } - if (JFreeReportInfo.REPORT_NAMESPACE.equals(namespace)) - { - return true; - } - if (OfficeNamespaces.INTERNAL_NS.equals(namespace)) - { - return true; - } - if (JFreeReportInfo.COMPATIBILITY_NAMESPACE.equals(namespace)) - { - return true; - } - if (OfficeNamespaces.OOREPORT_NS.equals(namespace)) - { - return true; - } - return false; - } - - public void processContent(final DataFlags value) - throws DataSourceException, ReportProcessingException - { - final Object rawvalue = value.getValue(); - if (rawvalue == null) - { - return; - } - - // special handler for image (possibly also for URL ..) - if (rawvalue instanceof Image) - { - // do nothing yet. We should define something for that later .. - return; - } - - final XmlWriter xmlWriter = getXmlWriter(); - final String text = String.valueOf(rawvalue); - try - { - final LineBreakIterator lb = new LineBreakIterator(text); - while (lb.hasNext()) - { - final String line = (String) lb.next(); - final String normalizedText = XmlWriterSupport.normalize(line, false); - xmlWriter.writeText(normalizedText); - if (lb.hasNext()) - { - xmlWriter.writeTag(OfficeNamespaces.TEXT_NS, "line-break", XmlWriterSupport.CLOSE); - } - } - } - catch (IOException e) - { - throw new ReportProcessingException(FAILED, e); - } - } - - public final void endElement(final AttributeMap attrs) - throws DataSourceException, ReportProcessingException - { - // final int oldState = getCurrentState(); - try - { - - switch (getCurrentState()) - { - case OfficeDocumentReportTarget.STATE_IN_OTHER: - { - endOther(attrs); - break; - } - case OfficeDocumentReportTarget.STATE_IN_SECTION: - { - endReportSection(attrs, currentRole); - currentRole = OfficeDocumentReportTarget.ROLE_NONE; - break; - } - case OfficeDocumentReportTarget.STATE_IN_GROUP: - { - endGroup(attrs); - groupContext = groupContext.getParent(); - break; - } - case OfficeDocumentReportTarget.STATE_IN_GROUP_INSTANCE: - { - endGroupInstance(attrs); - break; - } - case OfficeDocumentReportTarget.STATE_IN_GROUP_BODY: - { - endGroupBody(attrs); - break; - } - case OfficeDocumentReportTarget.STATE_IN_CONTENT: - { - endContent(attrs); - break; - } - case OfficeDocumentReportTarget.STATE_IN_BODY: - { - endBody(attrs); - break; - } - case OfficeDocumentReportTarget.STATE_IN_DOCUMENT: - { - throw new IllegalStateException("This cannot be."); - } - default: - { - throw new IllegalStateException("Invalid state encountered."); - } - } - } - catch (IOException ioe) - { - throw new ReportProcessingException("IO Error while writing content", - ioe); - } finally - { - states.pop(); - - if (DEBUG_ELEMENTS) - { - Log.debug("Finished " + getCurrentState() + "/" + states.size() + " " + - ReportTargetUtil.getNamespaceFromAttribute(attrs) + ":" + - ReportTargetUtil.getElemenTypeFromAttribute(attrs)); - } - - } - } - - protected void endGroupBody(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException - { - } - - protected void endGroupInstance(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException - { - } - - public int getCurrentRole() - { - return currentRole; - } - - protected abstract void endOther(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException; - - protected void endReportSection(final AttributeMap attrs, - final int role) - throws IOException, DataSourceException, ReportProcessingException - { - if (allowBuffering(role)) - { - finishBuffering(); - } - } - - protected void endGroup(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException - { - } - - protected abstract void endContent(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException; - - protected void endBody(final AttributeMap attrs) - throws IOException, DataSourceException, ReportProcessingException - { - getXmlWriter().writeCloseTag(); - } - - public void endReport(final ReportStructureRoot report) - throws DataSourceException, ReportProcessingException - { - if (xmlWriters.size() != 1) - { - throw new IllegalStateException("Invalid writer-stack state"); - } - - try - { - final StylesWriter inlineStylesWriter = new StylesWriter(rootXmlWriter); - inlineStylesWriter.writeContentStyles(predefinedStylesCollection, contentStylesCollection); - - final BufferState state = finishBuffering(); - this.rootXmlWriter.writeStream(state.getXmlAsReader()); - - final OutputStream stylesOutStream = - outputRepository.createOutputStream("styles.xml", "text/xml"); - final OutputStreamWriter osw = - new OutputStreamWriter(stylesOutStream, "UTF-8"); - final StylesWriter stylesWriter = new StylesWriter(osw); - stylesWriter.writeGlobalStyles(predefinedStylesCollection, globalStylesCollection); - stylesWriter.close(); - - this.rootXmlWriter.writeCloseTag(); - this.rootXmlWriter.close(); - } - catch (IOException e) - { - throw new ReportProcessingException(FAILED, e); - } - } - - public XmlWriter getXmlWriter() - { - final BufferState bufferState = (BufferState) xmlWriters.peek(); - return bufferState.getXmlWriter(); - } - - public OfficeStylesCollection getStylesCollection() - { - final BufferState bufferState = (BufferState) xmlWriters.peek(); - return bufferState.getStylesCollection(); - } - - public void startBuffering(final OfficeStylesCollection stylesCollection, - final boolean indent) throws ReportProcessingException - { - final XmlWriter currentWriter; - if (xmlWriters.isEmpty()) - { - currentWriter = rootXmlWriter; - } - else - { - final BufferState bufferState = (BufferState) xmlWriters.peek(); - currentWriter = bufferState.getXmlWriter(); - } - - try - { - final MemoryByteArrayOutputStream out = - new MemoryByteArrayOutputStream(INITIAL_BUFFER_SIZE, 256 * INITIAL_BUFFER_SIZE); - final DeflaterOutputStream deflateOut = new DeflaterOutputStream(out); - final OutputStreamWriter xmlBuffer = new OutputStreamWriter(deflateOut, "UTF-16"); - // final StringWriter xmlBuffer = new StringWriter - // (OfficeDocumentReportTarget.INITIAL_BUFFER_SIZE); - final XmlWriter contentXmlWriter = new XmlWriter(xmlBuffer, createTagDescription()); - contentXmlWriter.copyNamespaces(currentWriter); - if (indent) - { - contentXmlWriter.setAdditionalIndent(currentWriter.getCurrentIndentLevel()); - contentXmlWriter.setWriteFinalLinebreak(true); - } - else - { - contentXmlWriter.setWriteFinalLinebreak(false); - } - contentXmlWriter.setAlwaysAddNamespace(true); - xmlWriters.push(new BufferState(contentXmlWriter, out, stylesCollection)); - } - catch (IOException ioe) - { - throw new ReportProcessingException("Unable to create the buffer"); - } - } - - public BufferState finishBuffering() throws ReportProcessingException - { - final BufferState state = (BufferState) xmlWriters.pop(); - try - { - state.getXmlWriter().close(); - } - catch (IOException e) - { - Log.error("ReportProcessing failed", e); - } - return state; - } - - public void commit() - throws ReportProcessingException - { - // do not call flush before the report is fully finished. Every flush - // causes the Office-Backend to fully ZIP all contents (it acts like a - // 'Save' call from the UI) and that's expensive like hell - } - - public NamespaceDefinition getNamespaceByUri(final String uri) - { - return null; - } - - protected AttributeList buildAttributeList(final AttributeMap attrs) - { - final AttributeList attrList = new AttributeList(); - final String[] namespaces = attrs.getNameSpaces(); - for (int i = 0; i < namespaces.length; i++) - { - final String attrNamespace = namespaces[i]; - if (isFilteredNamespace(attrNamespace)) - { - continue; - } - - final Map localAttributes = attrs.getAttributes(attrNamespace); - final Iterator entries = localAttributes.entrySet().iterator(); - while (entries.hasNext()) - { - final Map.Entry entry = (Map.Entry) entries.next(); - final String key = String.valueOf(entry.getKey()); - if (OfficeNamespaces.TABLE_NS.equals(attrNamespace) && - "name".equals(key)) - { - final String tableName = String.valueOf(entry.getValue()); - final String saneName = sanitizeName(tableName); - attrList.setAttribute(attrNamespace, key, - tableNameGenerator.generateName(saneName)); - } - else if (OfficeNamespaces.DRAWING_NS.equals(attrNamespace) && - "name".equals(key)) - { - final String objectName = String.valueOf(entry.getValue()); - attrList.setAttribute(attrNamespace, key, - frameNameGenerator.generateName(objectName)); - } - else - { - attrList.setAttribute(attrNamespace, key, String.valueOf(entry.getValue())); - } - } - } - return attrList; - } - - protected String sanitizeName(final String name) - { - // A table name cannot contain spaces and should only contain - // ascii-characters. - if (name == null) - { - return ""; - } - final char[] chars = name.toCharArray(); - final StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < chars.length; i++) - { - final char aChar = chars[i]; - if (Character.isWhitespace(aChar)) - { - buffer.append('_'); - } - else - { - buffer.append(aChar); - } - } - return buffer.toString(); - } - - /** - * Returns the length in point. This method is f**king slow, it eats half of the processing time. I surely should - * replace it with something more efficient later. - * - * @param text - * @return - */ - protected CSSNumericValue parseLength(final String text) - { - if (styleSheetParserUtil == null) - { - styleSheetParserUtil = StyleSheetParserUtil.getInstance(); - } - - final LexicalUnit cssValue = styleSheetParserUtil.parseLexicalStyleValue( - text); - return CSSValueFactory.createLengthValue(cssValue); - } - - protected boolean isRepeatingSection() - { - return (currentRole == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER || - currentRole == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER || - currentRole == OfficeDocumentReportTarget.ROLE_PAGE_FOOTER || - currentRole == OfficeDocumentReportTarget.ROLE_PAGE_HEADER || - currentRole == OfficeDocumentReportTarget.ROLE_VARIABLES); - - } - - protected OfficeStyle deriveStyle(final String styleFamily, final String styleName) - throws ReportProcessingException - { - // autogenerate a style. The style has already been added to the current - // auto-collection. - final OfficeStyle style = StyleUtilities.deriveStyle(styleFamily, styleName, - getStylesCollection(), getGlobalStylesCollection(), - getPredefinedStylesCollection(), getAutoStyleNameGenerator()); - return style; - } - - protected void startImageProcessing(final AttributeMap attrs) - throws ReportProcessingException - { - final Object imageData = attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, OfficeToken.IMAGE_DATA); - final boolean preserveIRI = OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, OfficeToken.PRESERVE_IRI)); - - // for the first shot, do nothing fancy .. - final ImageProducer.OfficeImage image = imageProducer.produceImage(imageData, preserveIRI); - if (image != null) - { - final ImageElementContext imageContext = (ImageElementContext) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "image-context"); - - // When scaling, we have to create an image-style. - final CSSNumericValue width = image.getWidth(); // always in 100th of a mm - - final CSSNumericValue height = image.getHeight(); // always in 100th of a mm - - Log.debug("Image " + imageData + " Width: " + width + ", Height: " + height); - if (width == null || height == null) - { - return; - } - - CSSNumericValue imageAreaWidthVal; - CSSNumericValue imageAreaHeightVal; - String styleName = null; - if (imageContext != null) - { - imageAreaWidthVal = computeImageWidth(imageContext); - imageAreaHeightVal = computeImageHeight(imageContext); - - if (imageAreaWidthVal == null || imageAreaHeightVal == null) - { - Log.debug("Image data returned from context is invalid. Maybe this is not an image?"); - return; - } - else - { - // compute the clip-area .. - final CSSNumericValue normalizedImageWidth = - CSSValueResolverUtility.convertLength(width, imageAreaWidthVal.getType()); - final CSSNumericValue normalizedImageHeight = - CSSValueResolverUtility.convertLength(height, imageAreaHeightVal.getType()); - - final boolean scale = OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, OfficeToken.SCALE)); - if (!scale && normalizedImageWidth.getValue() > 0 && normalizedImageHeight.getValue() > 0) - { - final double clipWidth = normalizedImageWidth.getValue() - imageAreaWidthVal.getValue(); - final double clipHeight = normalizedImageHeight.getValue() - imageAreaHeightVal.getValue(); - if (clipWidth > 0 && clipHeight > 0) - { - final OfficeStyle imageStyle = deriveStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS); - final Element graphProperties = produceFirstChild(imageStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES); - final StringBuffer buffer = new StringBuffer(); - buffer.append("rect("); - buffer.append(clipHeight / 2); - buffer.append(imageAreaHeightVal.getType().getType()); - buffer.append(' '); - buffer.append(clipWidth / 2); - buffer.append(imageAreaWidthVal.getType().getType()); - buffer.append(' '); - buffer.append(clipHeight / 2); - buffer.append(imageAreaHeightVal.getType().getType()); - buffer.append(' '); - buffer.append(clipWidth / 2); - buffer.append(imageAreaWidthVal.getType().getType()); - buffer.append(')'); - graphProperties.setAttribute(OfficeNamespaces.FO_NS, "clip", buffer.toString()); - - styleName = imageStyle.getStyleName(); - getStylesCollection().getAutomaticStyles().addStyle(imageStyle); - } - else if (clipWidth > 0) - { - final OfficeStyle imageStyle = deriveStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS); - final Element graphProperties = produceFirstChild(imageStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES); - final StringBuffer buffer = new StringBuffer(); - buffer.append("rect(0cm "); - buffer.append(clipWidth / 2); - buffer.append(imageAreaWidthVal.getType().getType()); - buffer.append(" 0cm "); - buffer.append(clipWidth / 2); - buffer.append(imageAreaWidthVal.getType().getType()); - buffer.append(')'); - graphProperties.setAttribute(OfficeNamespaces.FO_NS, "clip", buffer.toString()); - - styleName = imageStyle.getStyleName(); - getStylesCollection().getAutomaticStyles().addStyle(imageStyle); - imageAreaHeightVal = normalizedImageHeight; - } - else if (clipHeight > 0) - { - final OfficeStyle imageStyle = deriveStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS); - final Element graphProperties = produceFirstChild(imageStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES); - final StringBuffer buffer = new StringBuffer(); - buffer.append("rect("); - buffer.append(clipHeight / 2); - buffer.append(imageAreaHeightVal.getType().getType()); - buffer.append(" 0cm "); - buffer.append(clipHeight / 2); - buffer.append(imageAreaHeightVal.getType().getType()); - buffer.append(" 0cm)"); - graphProperties.setAttribute(OfficeNamespaces.FO_NS, "clip", buffer.toString()); - - styleName = imageStyle.getStyleName(); - getStylesCollection().getAutomaticStyles().addStyle(imageStyle); - imageAreaWidthVal = normalizedImageWidth; - } - else - { - imageAreaWidthVal = normalizedImageWidth; - imageAreaHeightVal = normalizedImageHeight; - } - } - } - // If we do scale, then we simply use the given image-area-size as valid image size and dont - // care about the image itself .. - } - else - { - Log.debug("There is no image-context, so we have to rely on the image's natural bounds. " + - "This may go awfully wrong."); - imageAreaWidthVal = image.getWidth(); - imageAreaHeightVal = image.getHeight(); - } - - final AttributeList frameList = new AttributeList(); - frameList.setAttribute(OfficeNamespaces.DRAWING_NS, "name", imageNames.generateName("Image")); - if (styleName != null) - { - frameList.setAttribute(OfficeNamespaces.DRAWING_NS, OfficeToken.STYLE_NAME, styleName); - } - frameList.setAttribute(OfficeNamespaces.TEXT_NS, "anchor-type", OfficeToken.PARAGRAPH); - frameList.setAttribute(OfficeNamespaces.SVG_NS, "z-index", "0"); - frameList.setAttribute(OfficeNamespaces.SVG_NS, "x", ZERO_CM); - frameList.setAttribute(OfficeNamespaces.SVG_NS, "y", ZERO_CM); - - Log.debug("Image " + imageData + " A-Width: " + imageAreaWidthVal + ", A-Height: " + imageAreaHeightVal); - - if (imageAreaWidthVal != null) - { - frameList.setAttribute(OfficeNamespaces.SVG_NS, - "width", imageAreaWidthVal.getValue() + imageAreaWidthVal.getType().getType()); - } - - if (imageAreaHeightVal != null) - { - frameList.setAttribute(OfficeNamespaces.SVG_NS, - "height", imageAreaHeightVal.getValue() + imageAreaHeightVal.getType().getType()); - } - - - final AttributeList imageList = new AttributeList(); - imageList.setAttribute(OfficeNamespaces.XLINK_NS, "href", image.getEmbeddableLink()); - imageList.setAttribute(OfficeNamespaces.XLINK_NS, "type", "simple"); - imageList.setAttribute(OfficeNamespaces.XLINK_NS, "show", "embed"); - imageList.setAttribute(OfficeNamespaces.XLINK_NS, "actuate", "onLoad"); - - - try - { - getXmlWriter().writeTag(OfficeNamespaces.DRAWING_NS, "frame", frameList, XmlWriterSupport.OPEN); - getXmlWriter().writeTag(OfficeNamespaces.DRAWING_NS, OfficeToken.IMAGE, imageList, XmlWriterSupport.CLOSE); - getXmlWriter().writeCloseTag(); - } - catch (IOException ioe) - { - throw new ReportProcessingException(FAILED, ioe); - } - } - } - - private CSSNumericValue computeImageWidth(final ImageElementContext imageElementContext) - { - final LengthCalculator calculator = new LengthCalculator(); - final String[] strings = imageElementContext.getColStyles(); - for (int i = 0; i < strings.length; i++) - { - final String styleName = strings[i]; - final CSSNumericValue value = computeColumnWidth(styleName); - if (value != null) - { - calculator.add(value); - } - } - return calculator.getResult(); - } - - private CSSNumericValue computeImageHeight(final ImageElementContext imageElementContext) - { - final LengthCalculator calculator = new LengthCalculator(); - final String[] strings = imageElementContext.getRowStyles(); - for (int i = 0; i < strings.length; i++) - { - final String styleName = strings[i]; - final CSSNumericValue value = computeRowHeight(styleName); - if (value != null) - { - calculator.add(value); - } - } - return calculator.getResult(); - } - - protected CSSNumericValue computeRowHeight(final String rowStyle) - { - final OfficeStylesCollection contentStyles = getContentStylesCollection(); - final OfficeStyle style = contentStyles.getStyle(OfficeToken.TABLE_ROW, rowStyle); - if (style != null) - { - final Element element = style.getTableRowProperties(); - if (element != null) - { - final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "row-height"); - if (height != null) - { - return parseLength(height); - } - } - - final String styleParent = style.getStyleParent(); - if (styleParent != null) - { - return computeRowHeight(styleParent); - } - } - - final OfficeStylesCollection globalStyles = getGlobalStylesCollection(); - final OfficeStyle globalStyle = globalStyles.getStyle(OfficeToken.TABLE_ROW, rowStyle); - if (globalStyle != null) - { - final Element element = globalStyle.getTableRowProperties(); - if (element != null) - { - final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "row-height"); - if (height != null) - { - return parseLength(height); - } - } - final String styleParent = globalStyle.getStyleParent(); - if (styleParent != null) - { - return computeRowHeight(styleParent); - } - } - - final OfficeStylesCollection predefStyles = getPredefinedStylesCollection(); - final OfficeStyle predefStyle = predefStyles.getStyle(OfficeToken.TABLE_ROW, rowStyle); - if (predefStyle != null) - { - final Element element = predefStyle.getTableRowProperties(); - if (element != null) - { - final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "row-height"); - if (height != null) - { - return parseLength(height); - } - } - final String styleParent = predefStyle.getStyleParent(); - if (styleParent != null) - { - return computeRowHeight(styleParent); - } - } - // not found. - return null; - } - - protected CSSNumericValue computeColumnWidth(final String colStyle) - { - final OfficeStylesCollection contentStyles = getContentStylesCollection(); - final OfficeStyle style = contentStyles.getStyle(OfficeToken.TABLE_COLUMN, colStyle); - if (style != null) - { - final Element element = style.getTableColumnProperties(); - if (element != null) - { - final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "column-width"); - if (height != null) - { - return parseLength(height); - } - } - - final String styleParent = style.getStyleParent(); - if (styleParent != null) - { - return computeRowHeight(styleParent); - } - } - - final OfficeStylesCollection globalStyles = getGlobalStylesCollection(); - final OfficeStyle globalStyle = globalStyles.getStyle(OfficeToken.TABLE_COLUMN, colStyle); - if (globalStyle != null) - { - final Element element = globalStyle.getTableColumnProperties(); - if (element != null) - { - final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "column-width"); - if (height != null) - { - return parseLength(height); - } - } - final String styleParent = globalStyle.getStyleParent(); - if (styleParent != null) - { - return computeRowHeight(styleParent); - } - } - - final OfficeStylesCollection predefStyles = getPredefinedStylesCollection(); - final OfficeStyle predefStyle = predefStyles.getStyle(OfficeToken.TABLE_COLUMN, colStyle); - if (predefStyle != null) - { - final Element element = predefStyle.getTableColumnProperties(); - if (element != null) - { - final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "column-width"); - if (height != null) - { - return parseLength(height); - } - } - final String styleParent = predefStyle.getStyleParent(); - if (styleParent != null) - { - return computeRowHeight(styleParent); - } - } - // not found. - return null; - } - - protected Element produceFirstChild(final Section style, - final String nameSpace, - final String type) - { - Element paragraphProps = style.findFirstChild(nameSpace, type); - if (paragraphProps == null) - { - paragraphProps = new Section(); - paragraphProps.setNamespace(nameSpace); - paragraphProps.setType(type); - style.addNode(paragraphProps); - } - return paragraphProps; - } - - protected void startChartProcessing(final AttributeMap attrs) - throws ReportProcessingException - { - final String classId = (String) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "class-id"); - final String chartUrl = (String) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "href"); - final ArrayList masterColumns = (ArrayList) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "master-columns"); - final ArrayList masterValues = (ArrayList) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.MASTER_VALUES); - final ArrayList detailColumns = (ArrayList) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.DETAIL_COLUMNS); - final String href = oleProducer.produceOle(chartUrl, masterColumns, masterValues, detailColumns); - - final AttributeList oleList = new AttributeList(); - oleList.setAttribute(OfficeNamespaces.DRAWING_NS, "class-id", classId); - oleList.setAttribute(OfficeNamespaces.XLINK_NS, "href", "./" + href); - oleList.setAttribute(OfficeNamespaces.XLINK_NS, "type", "simple"); - oleList.setAttribute(OfficeNamespaces.XLINK_NS, "show", "embed"); - oleList.setAttribute(OfficeNamespaces.XLINK_NS, "actuate", "onLoad"); - - try - { - getXmlWriter().writeTag(OfficeNamespaces.DRAWING_NS, OfficeToken.OBJECT_OLE, oleList, XmlWriterSupport.CLOSE); - } - catch (IOException ioe) - { - throw new ReportProcessingException(FAILED, ioe); - } - - - } -} +/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OfficeDocumentReportTarget.java,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package com.sun.star.report.pentaho.output;
+
+import com.sun.star.report.DataSourceFactory;
+import java.awt.Image;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.zip.DeflaterOutputStream;
+import java.util.zip.InflaterInputStream;
+
+import com.sun.star.report.ImageService;
+import com.sun.star.report.InputRepository;
+import com.sun.star.report.OutputRepository;
+import com.sun.star.report.SDBCReportDataFactory;
+import com.sun.star.report.pentaho.OfficeNamespaces;
+import com.sun.star.report.OfficeToken;
+import com.sun.star.report.pentaho.layoutprocessor.ImageElementContext;
+import com.sun.star.report.pentaho.model.OfficeDocument;
+import com.sun.star.report.pentaho.model.OfficeStyle;
+import com.sun.star.report.pentaho.model.OfficeStyles;
+import com.sun.star.report.pentaho.model.OfficeStylesCollection;
+import com.sun.star.report.pentaho.styles.LengthCalculator;
+import com.sun.star.report.pentaho.styles.StyleMapper;
+import java.util.ArrayList;
+import org.jfree.io.IOUtils;
+import org.jfree.layouting.input.style.parser.CSSValueFactory;
+import org.jfree.layouting.input.style.parser.StyleSheetParserUtil;
+import org.jfree.layouting.input.style.values.CSSNumericValue;
+import org.jfree.layouting.layouter.style.CSSValueResolverUtility;
+import org.jfree.layouting.namespace.NamespaceDefinition;
+import org.jfree.layouting.namespace.Namespaces;
+import org.jfree.layouting.util.AttributeMap;
+import org.jfree.report.DataFlags;
+import org.jfree.report.DataSourceException;
+import org.jfree.report.JFreeReportBoot;
+import org.jfree.report.JFreeReportInfo;
+import org.jfree.report.ReportProcessingException;
+import org.jfree.report.flow.AbstractReportTarget;
+import org.jfree.report.flow.ReportJob;
+import org.jfree.report.flow.ReportStructureRoot;
+import org.jfree.report.flow.ReportTargetUtil;
+import org.jfree.report.structure.Element;
+import org.jfree.report.structure.Section;
+import org.jfree.report.util.AttributeNameGenerator;
+import org.jfree.report.util.IntegerCache;
+import org.jfree.report.util.MemoryByteArrayOutputStream;
+import org.jfree.resourceloader.ResourceException;
+import org.jfree.resourceloader.ResourceKey;
+import org.jfree.resourceloader.ResourceManager;
+import org.jfree.util.FastStack;
+import org.jfree.util.LineBreakIterator;
+import org.jfree.util.Log;
+import org.jfree.xmlns.common.AttributeList;
+import org.jfree.xmlns.writer.DefaultTagDescription;
+import org.jfree.xmlns.writer.XmlWriter;
+import org.jfree.xmlns.writer.XmlWriterSupport;
+import org.w3c.css.sac.LexicalUnit;
+
+/**
+ * Todo: Document me!
+ *
+ * @author Thomas Morgner
+ * @since 08.03.2007
+ */
+public abstract class OfficeDocumentReportTarget extends AbstractReportTarget
+{
+
+ public static final String HORIZONTAL_POS = "horizontal-pos";
+ public static final String TAG_DEF_PREFIX = "com.sun.star.report.pentaho.output.";
+ public static final int ROLE_NONE = 0;
+ public static final int ROLE_REPORT_HEADER = 1;
+ public static final int ROLE_REPORT_FOOTER = 2;
+ public static final int ROLE_GROUP_HEADER = 3;
+ public static final int ROLE_GROUP_FOOTER = 4;
+ public static final int ROLE_REPEATING_GROUP_HEADER = 5;
+ public static final int ROLE_REPEATING_GROUP_FOOTER = 6;
+ public static final int ROLE_PAGE_HEADER = 7;
+ public static final int ROLE_PAGE_FOOTER = 8;
+ public static final int ROLE_DETAIL = 9;
+ public static final int ROLE_VARIABLES = 10;
+ public static final int ROLE_TEMPLATE = 11;
+ public static final int ROLE_SPREADSHEET_PAGE_HEADER = 12;
+ public static final int ROLE_SPREADSHEET_PAGE_FOOTER = 13;
+ public static final int STATE_IN_DOCUMENT = 0;
+ public static final int STATE_IN_BODY = 1;
+ public static final int STATE_IN_CONTENT = 2;
+ public static final int STATE_IN_GROUP = 3;
+ public static final int STATE_IN_GROUP_BODY = 4;
+ public static final int STATE_IN_SECTION = 5;
+ public static final int STATE_IN_OTHER = 6;
+ public static final int STATE_IN_GROUP_INSTANCE = 7;
+ public static final String FAILED = "Failed";
+ public static final String VERTICAL_POS = "vertical-pos";
+ private static final String ZERO_CM = "0cm";
+
+ protected static class BufferState
+ {
+
+ private final XmlWriter xmlWriter;
+ private final MemoryByteArrayOutputStream xmlBuffer;
+ private final OfficeStylesCollection stylesCollection;
+
+ protected BufferState(final XmlWriter xmlWriter,
+ final MemoryByteArrayOutputStream xmlBuffer,
+ final OfficeStylesCollection stylesCollection)
+ {
+ this.stylesCollection = stylesCollection;
+ this.xmlWriter = xmlWriter;
+ this.xmlBuffer = xmlBuffer;
+ }
+
+ public OfficeStylesCollection getStylesCollection()
+ {
+ return stylesCollection;
+ }
+
+ public XmlWriter getXmlWriter()
+ {
+ return xmlWriter;
+ }
+
+ public String getXmlBuffer() throws ReportProcessingException
+ {
+ try
+ {
+ final byte[] zippedData = xmlBuffer.getRaw();
+ final InputStreamReader reader = new InputStreamReader(new InflaterInputStream(new ByteArrayInputStream(zippedData, 0, xmlBuffer.getLength())), "UTF-16");
+ final StringWriter writer = new StringWriter((zippedData.length / 2) + 1);
+ IOUtils.getInstance().copyWriter(reader, writer);
+ return writer.toString();
+ }
+ catch (IOException e)
+ {
+ throw new ReportProcessingException("Failed to copy buffer", e);
+ }
+ }
+
+ public Reader getXmlAsReader() throws ReportProcessingException
+ {
+ try
+ {
+ final byte[] zippedData = xmlBuffer.getRaw();
+ return new InputStreamReader(new InflaterInputStream(new ByteArrayInputStream(zippedData, 0, xmlBuffer.getLength())), "UTF-16");
+ }
+ catch (IOException e)
+ {
+ throw new ReportProcessingException("Failed to copy buffer", e);
+ }
+ }
+ }
+
+ protected static class GroupContext
+ {
+
+ private final GroupContext parent;
+ private int iterationCount;
+ private boolean groupWithRepeatingSection;
+
+ protected GroupContext(final GroupContext parent)
+ {
+ this.parent = parent;
+ }
+
+ public GroupContext getParent()
+ {
+ return parent;
+ }
+
+ public int getIterationCount()
+ {
+ return iterationCount;
+ }
+
+ public void setIterationCount(final int iterationCount)
+ {
+ this.iterationCount = iterationCount;
+ }
+
+ public boolean isGroupWithRepeatingSection()
+ {
+ return groupWithRepeatingSection;
+ }
+
+ public void setGroupWithRepeatingSection(final boolean groupWithRepeatingSection)
+ {
+ this.groupWithRepeatingSection = groupWithRepeatingSection;
+ }
+
+ public String toString()
+ {
+ return "GroupContext{" +
+ "parent=" + parent +
+ ", iterationCount=" + iterationCount +
+ ", groupWithRepeatingSection=" + groupWithRepeatingSection +
+ '}';
+ }
+ }
+ private final FastStack states;
+ private int currentRole;
+ private final FastStack xmlWriters;
+ private XmlWriter rootXmlWriter;
+ /**
+ * This styles-collection contains all styles that were predefined in the report definition file. The common styles
+ * and the master-styles will be written unmodified, the automatic styles will be ignored.
+ */
+ private OfficeStylesCollection predefinedStylesCollection;
+ /**
+ * This styles-collection contains all master-styles that have been generated by the report definition process. It
+ * also contains all automatic styles that have been generated for the page-bands (and the pagebands as well).
+ */
+ private OfficeStylesCollection globalStylesCollection;
+ /**
+ * The content styles collection contains all automatic styles that have been generated for the normal-flow content.
+ */
+ private OfficeStylesCollection contentStylesCollection;
+ private final OutputRepository outputRepository;
+ private final InputRepository inputRepository;
+ private final AttributeNameGenerator tableNameGenerator;
+ private final AttributeNameGenerator frameNameGenerator;
+ private final AttributeNameGenerator autoStyleNameGenerator;
+ private final String target;
+ private static final int INITIAL_BUFFER_SIZE = 40960;
+ private StyleMapper styleMapper;
+ private StyleSheetParserUtil styleSheetParserUtil;
+ private final AttributeNameGenerator imageNames;
+ private final ImageProducer imageProducer;
+ private final OleProducer oleProducer;
+ private GroupContext groupContext;
+ private static final boolean DEBUG_ELEMENTS =
+ JFreeReportBoot.getInstance().getExtendedConfig().getBoolProperty("com.sun.star.report.pentaho.output.DebugElements");
+
+ protected OfficeDocumentReportTarget(final ReportJob reportJob,
+ final ResourceManager resourceManager,
+ final ResourceKey baseResource,
+ final InputRepository inputRepository,
+ final OutputRepository outputRepository,
+ final String target,
+ final ImageService imageService,
+ final DataSourceFactory datasourcefactory)
+ throws ReportProcessingException
+ {
+ super(reportJob, resourceManager, baseResource);
+ if (imageService == null)
+ {
+ throw new NullPointerException("ImageService must not be null");
+ }
+ if (target == null)
+ {
+ throw new NullPointerException("Target-Name must not be null");
+ }
+
+ this.target = target;
+
+ this.tableNameGenerator = new AttributeNameGenerator();
+ this.frameNameGenerator = new AttributeNameGenerator();
+ this.autoStyleNameGenerator = new AttributeNameGenerator();
+ this.outputRepository = outputRepository;
+ this.inputRepository = inputRepository;
+ this.states = new FastStack();
+ this.xmlWriters = new FastStack();
+ this.imageNames = new AttributeNameGenerator();
+
+ this.imageProducer = new ImageProducer(inputRepository, outputRepository, imageService);
+ this.oleProducer = new OleProducer(inputRepository, outputRepository, imageService, datasourcefactory);
+
+ try
+ {
+ final ResourceManager realResourceManager = getResourceManager();
+ styleMapper = StyleMapper.loadInstance(realResourceManager);
+ }
+ catch (ResourceException e)
+ {
+ throw new ReportProcessingException("Failed to load style-mapper", e);
+ }
+ }
+
+ protected abstract String getTargetMimeType();
+
+ protected OutputRepository getOutputRepository()
+ {
+ return outputRepository;
+ }
+
+ protected InputRepository getInputRepository()
+ {
+ return inputRepository;
+ }
+
+ /**
+ * Starts the output of a new office document. This method writes the generic 'office:document-content' tag along with
+ * all known namespace declarations.
+ *
+ * @param report the report object.
+ * @throws DataSourceException if there was an error accessing the datasource
+ * @throws ReportProcessingException if some other error occured.
+ */
+ public void startReport(final ReportStructureRoot report)
+ throws DataSourceException, ReportProcessingException
+ {
+ imageNames.reset();
+ this.groupContext = new GroupContext(null);
+
+ final DefaultTagDescription tagDescription = createTagDescription();
+ try
+ {
+ final OutputStream outputStream = outputRepository.createOutputStream(target, "text/xml");
+ final Writer writer = new OutputStreamWriter(outputStream, "UTF-8");
+
+ this.rootXmlWriter = new XmlWriter(writer, tagDescription);
+ this.rootXmlWriter.setAlwaysAddNamespace(true);
+
+ final AttributeList rootAttributes = new AttributeList();
+ rootAttributes.addNamespaceDeclaration("office", OfficeNamespaces.OFFICE_NS);
+ rootAttributes.addNamespaceDeclaration("style", OfficeNamespaces.STYLE_NS);
+ rootAttributes.addNamespaceDeclaration("text", OfficeNamespaces.TEXT_NS);
+ rootAttributes.addNamespaceDeclaration("table", OfficeNamespaces.TABLE_NS);
+ rootAttributes.addNamespaceDeclaration("draw", OfficeNamespaces.DRAWING_NS);
+ rootAttributes.addNamespaceDeclaration("fo", OfficeNamespaces.FO_NS);
+ rootAttributes.addNamespaceDeclaration("xlink", OfficeNamespaces.XLINK_NS);
+ rootAttributes.addNamespaceDeclaration("dc", OfficeNamespaces.PURL_NS);
+ rootAttributes.addNamespaceDeclaration("meta", OfficeNamespaces.META_NS);
+ rootAttributes.addNamespaceDeclaration("number", OfficeNamespaces.DATASTYLE_NS);
+ rootAttributes.addNamespaceDeclaration("svg", OfficeNamespaces.SVG_NS);
+ rootAttributes.addNamespaceDeclaration("chart", OfficeNamespaces.CHART_NS);
+ rootAttributes.addNamespaceDeclaration("dr3d", OfficeNamespaces.DR3D_NS);
+ rootAttributes.addNamespaceDeclaration("math", OfficeNamespaces.MATHML_NS);
+ rootAttributes.addNamespaceDeclaration("form", OfficeNamespaces.FORM_NS);
+ rootAttributes.addNamespaceDeclaration("script", OfficeNamespaces.SCRIPT_NS);
+ rootAttributes.addNamespaceDeclaration("ooo", OfficeNamespaces.OO2004_NS);
+ rootAttributes.addNamespaceDeclaration("ooow", OfficeNamespaces.OOW2004_NS);
+ rootAttributes.addNamespaceDeclaration("oooc", OfficeNamespaces.OOC2004_NS);
+ rootAttributes.addNamespaceDeclaration("dom", OfficeNamespaces.XML_EVENT_NS);
+ rootAttributes.addNamespaceDeclaration("xforms", OfficeNamespaces.XFORMS_NS);
+ rootAttributes.addNamespaceDeclaration("xsd", OfficeNamespaces.XSD_NS);
+ rootAttributes.addNamespaceDeclaration("xsi", OfficeNamespaces.XSI_NS);
+ rootAttributes.setAttribute(OfficeNamespaces.OFFICE_NS, "version", "1.0");
+
+ this.rootXmlWriter.writeXmlDeclaration("UTF-8");
+ this.rootXmlWriter.writeTag(OfficeNamespaces.OFFICE_NS, "document-content", rootAttributes, XmlWriterSupport.OPEN);
+
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_DOCUMENT));
+
+ autoStyleNameGenerator.reset();
+ tableNameGenerator.reset();
+ frameNameGenerator.reset();
+
+ final OfficeDocument reportDoc = (OfficeDocument) report;
+ predefinedStylesCollection = reportDoc.getStylesCollection();
+
+ final OfficeStyles commonStyles = predefinedStylesCollection.getCommonStyles();
+ if (!commonStyles.containsStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS))
+ {
+ final OfficeStyle graphicsDefaultStyle = new OfficeStyle();
+ graphicsDefaultStyle.setStyleFamily(OfficeToken.GRAPHIC);
+ graphicsDefaultStyle.setStyleName(OfficeToken.GRAPHICS);
+ final Element graphicProperties = produceFirstChild(graphicsDefaultStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES);
+ graphicProperties.setAttribute(OfficeNamespaces.TEXT_NS, "anchor-type", OfficeToken.PARAGRAPH);
+ graphicProperties.setAttribute(OfficeNamespaces.SVG_NS, "x", ZERO_CM);
+ graphicProperties.setAttribute(OfficeNamespaces.SVG_NS, "y", ZERO_CM);
+ graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "wrap", "dynamic");
+ graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "number-wrapped-paragraphs", "no-limit");
+ graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "wrap-contour", OfficeToken.FALSE);
+ graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, VERTICAL_POS, "from-top"); // changed for chart
+
+ graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "vertical-rel", OfficeToken.PARAGRAPH);
+ graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, HORIZONTAL_POS, "from-left"); // changed for chart
+
+ graphicProperties.setAttribute(OfficeNamespaces.STYLE_NS, "horizontal-rel", OfficeToken.PARAGRAPH);
+ commonStyles.addStyle(graphicsDefaultStyle);
+ }
+
+ // Make sure that later generated styles do not overwrite existing styles.
+ fillStyleNameGenerator(predefinedStylesCollection);
+
+ contentStylesCollection = new OfficeStylesCollection();
+ globalStylesCollection = new OfficeStylesCollection();
+
+ startBuffering(contentStylesCollection, true);
+ }
+ catch (IOException e)
+ {
+ throw new ReportProcessingException(FAILED, e);
+ }
+ }
+
+ protected AttributeNameGenerator getAutoStyleNameGenerator()
+ {
+ return autoStyleNameGenerator;
+ }
+
+ private void fillStyleNameGenerator(final OfficeStylesCollection stylesCollection)
+ {
+ final OfficeStyles commonStyles = stylesCollection.getCommonStyles();
+ final OfficeStyle[] allCommonStyles = commonStyles.getAllStyles();
+ for (int i = 0; i < allCommonStyles.length; i++)
+ {
+ final OfficeStyle style = allCommonStyles[i];
+ autoStyleNameGenerator.generateName(style.getStyleName());
+ }
+
+ final OfficeStyles autoStyles = stylesCollection.getAutomaticStyles();
+ final OfficeStyle[] allAutoStyles = autoStyles.getAllStyles();
+ for (int i = 0; i < allAutoStyles.length; i++)
+ {
+ final OfficeStyle style = allAutoStyles[i];
+ autoStyleNameGenerator.generateName(style.getStyleName());
+ }
+ }
+
+ public OfficeStylesCollection getPredefinedStylesCollection()
+ {
+ return predefinedStylesCollection;
+ }
+
+ public OfficeStylesCollection getGlobalStylesCollection()
+ {
+ return globalStylesCollection;
+ }
+
+ public OfficeStylesCollection getContentStylesCollection()
+ {
+ return contentStylesCollection;
+ }
+
+ /**
+ * Returns the XML-Writer tag description. This description defines whether an element can have character data inside.
+ * Such element will disable the indention, as in that case the additional whitespaces might alter the meaning of the
+ * element's contents.
+ *
+ * @return the tag description library.
+ */
+ protected DefaultTagDescription createTagDescription()
+ {
+ final DefaultTagDescription tagDescription = new DefaultTagDescription();
+ tagDescription.configure(JFreeReportBoot.getInstance().getGlobalConfig(),
+ OfficeDocumentReportTarget.TAG_DEF_PREFIX);
+ return tagDescription;
+ }
+
+ /**
+ * Returns the current processing state.
+ *
+ * @return the processing state.
+ */
+ protected int getCurrentState()
+ {
+ if (states.isEmpty())
+ {
+ throw new IllegalStateException();
+ }
+ final Integer o = (Integer) states.peek();
+ return o.intValue();
+ }
+
+ /**
+ * Starts the processing of an element and updates the processing state. This will select an apropriate handler method
+ * for the call and will call one of the start* methods.
+ *
+ * @param attrs the attribute map for the current element
+ * @throws DataSourceException
+ * @throws ReportProcessingException
+ */
+ public final void startElement(final AttributeMap attrs)
+ throws DataSourceException, ReportProcessingException
+ {
+ // todo
+ if (DEBUG_ELEMENTS)
+ {
+ Log.debug("Starting " + getCurrentState() + '/' + states.size() + ' ' +
+ ReportTargetUtil.getNamespaceFromAttribute(attrs) + " -> " +
+ ReportTargetUtil.getElemenTypeFromAttribute(attrs));
+ }
+ try
+ {
+ switch (getCurrentState())
+ {
+ case OfficeDocumentReportTarget.STATE_IN_DOCUMENT:
+ {
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OFFICE_NS, "body", attrs))
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_BODY));
+ startBody(attrs);
+ }
+ else
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_OTHER));
+ if (!isFilteredNamespace(ReportTargetUtil.getNamespaceFromAttribute(attrs)))
+ {
+ startOther(attrs);
+ }
+ }
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_BODY:
+ {
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OFFICE_NS, "report", attrs))
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_CONTENT));
+ startContent(attrs);
+ }
+ else
+ {
+ throw new IllegalStateException("The 'office:body' element must have exactly one child of type 'report'");
+ }
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_CONTENT:
+ {
+ // Either a ordinary section or a group ..
+ // A group.
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "report-body", attrs))
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP_BODY));
+ startGroupBody(attrs);
+ }
+ else
+ {
+ // Either a template-section, page-header, page-footer, report-header, report-footer
+ // or variables-section
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION));
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "template", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_TEMPLATE;
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "page-header", attrs))
+ {
+ if ("spreadsheet-section".equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "role")))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_SPREADSHEET_PAGE_HEADER;
+ }
+ else
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_PAGE_HEADER;
+ }
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "page-footer", attrs))
+ {
+ if ("spreadsheet-section".equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "role")))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_SPREADSHEET_PAGE_FOOTER;
+ }
+ else
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_PAGE_FOOTER;
+ }
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "report-header", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_REPORT_HEADER;
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "report-footer", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_REPORT_FOOTER;
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "variables-section", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_VARIABLES;
+ }
+ else
+ {
+ throw new IllegalStateException("Expected either 'template', 'report-body', " +
+ "'report-header', 'report-footer', 'variables-section', 'page-header' or 'page-footer'");
+ }
+ startReportSection(attrs, currentRole);
+ }
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_GROUP_BODY:
+ {
+ // We now expect either an other group or a detail band.
+
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group", attrs))
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP));
+ groupContext = new GroupContext(groupContext);
+ startGroup(attrs);
+ }
+ else
+ {
+ // Either a variables-section, or a detail-band
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION));
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "detail", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_DETAIL;
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "variables-section", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_VARIABLES;
+ }
+ else
+ {
+ throw new IllegalStateException("Expected either 'group', 'detail' or 'variables-section'");
+ }
+ startReportSection(attrs, currentRole);
+ }
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_GROUP:
+ {
+ // A group can carry a repeating group header/footer or a group-instance section.
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "group-instance", attrs))
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP_INSTANCE));
+ startGroupInstance(attrs);
+ }
+ else
+ {
+ // repeating group header/footer, but *no* variables section
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION));
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-header", attrs) &&
+ OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "repeated-section")))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER;
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-footer", attrs) &&
+ OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "repeated-section")))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER;
+ }
+ else
+ {
+ throw new IllegalStateException("Expected either 'group-instance', " +
+ "'repeating group-header' or 'repeating group-footer'");
+ }
+ startReportSection(attrs, currentRole);
+ }
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_GROUP_INSTANCE:
+ {
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "group-body", attrs))
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_GROUP_BODY));
+ startGroupBody(attrs);
+ }
+ else
+ {
+ // Either a group-header or group-footer or variables-section
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_SECTION));
+ if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-header", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_GROUP_HEADER;
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.OOREPORT_NS, "group-footer", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_GROUP_FOOTER;
+ }
+ else if (ReportTargetUtil.isElementOfType(OfficeNamespaces.INTERNAL_NS, "variables-section", attrs))
+ {
+ currentRole = OfficeDocumentReportTarget.ROLE_VARIABLES;
+ }
+ else
+ {
+ throw new IllegalStateException("Expected either 'group-body', 'group-header', 'group-footer' or 'variables-section'");
+ }
+ startReportSection(attrs, currentRole);
+ }
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_SECTION:
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_OTHER));
+ startOther(attrs);
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_OTHER:
+ {
+ states.push(IntegerCache.getInteger(OfficeDocumentReportTarget.STATE_IN_OTHER));
+ startOther(attrs);
+ break;
+ }
+ default:
+ throw new IllegalStateException("Failure: " + getCurrentState());
+ }
+ }
+ catch (IOException ioe)
+ {
+ Log.error("ReportProcessing failed", ioe);
+ throw new ReportProcessingException("Failed to write content", ioe);
+ }
+// finally
+// {
+// Log.debug ("Started " + getNamespaceFromAttribute(attrs) + ":" +
+// getElemenTypeFromAttribute(attrs) + " -> " + getCurrentState());
+// }
+ }
+
+ protected GroupContext getGroupContext()
+ {
+ return groupContext;
+ }
+
+ protected void performStyleProcessing(final AttributeMap attrs)
+ throws ReportProcessingException
+ {
+ final OfficeStylesCollection stylesCollection = getStylesCollection();
+ final OfficeStylesCollection predefCollection = getPredefinedStylesCollection();
+ final OfficeStylesCollection globalStylesCollection = getGlobalStylesCollection();
+
+ final String elementNamespace =
+ ReportTargetUtil.getNamespaceFromAttribute(attrs);
+ final String elementName =
+ ReportTargetUtil.getElemenTypeFromAttribute(attrs);
+
+ final String[] namespaces = attrs.getNameSpaces();
+ for (int i = 0; i < namespaces.length; i++)
+ {
+ final String attrNamespace = namespaces[i];
+ if (isFilteredNamespace(attrNamespace))
+ {
+ continue;
+ }
+
+ final Map attributes = attrs.getAttributes(attrNamespace);
+ final Iterator iterator = attributes.entrySet().iterator();
+ while (iterator.hasNext())
+ {
+ final Map.Entry entry = (Map.Entry) iterator.next();
+ final String attrName = (String) entry.getKey();
+ final String attrValue = String.valueOf(entry.getValue());
+
+ final String styleFamily = styleMapper.getStyleFamilyFor(elementNamespace, elementName, attrNamespace, attrName);
+ if (styleFamily == null)
+ {
+ // None of the known style attributes.
+ continue;
+ }
+
+ if (styleMapper.isListOfStyles(elementNamespace, elementName, attrNamespace, attrName))
+ {
+ // ignored for now.
+ Log.warn("List of styles is not yet implemented.");
+ continue;
+ }
+
+ // Copy styles is only called once per style.
+ StyleUtilities.copyStyle(styleFamily, attrValue, stylesCollection, globalStylesCollection, predefCollection);
+ }
+ }
+ }
+
+ protected void startBody(final AttributeMap attrs)
+ throws IOException
+ {
+ getXmlWriter().writeTag(OfficeNamespaces.OFFICE_NS, "body", XmlWriterSupport.OPEN);
+ }
+
+ private final boolean allowBuffering(final int role)
+ {
+ return (role == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER ||
+ role == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER ||
+ role == OfficeDocumentReportTarget.ROLE_TEMPLATE);
+ }
+
+ protected void startReportSection(final AttributeMap attrs, final int role)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ if (allowBuffering(role))
+ {
+ startBuffering(new OfficeStylesCollection(), true);
+ }
+ }
+
+ protected abstract void startContent(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException;
+
+ protected void startGroup(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ final Object repeatingHeaderOrFooter = attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "repeating-header-or-footer");
+ if (OfficeToken.TRUE.equals(repeatingHeaderOrFooter))
+ {
+ getGroupContext().setGroupWithRepeatingSection(true);
+ }
+
+ final Object iterationCount = attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "iteration-count");
+ if (iterationCount instanceof Number)
+ {
+ final Number itNumber = (Number) iterationCount;
+ getGroupContext().setIterationCount(itNumber.intValue());
+ }
+ }
+
+ protected void startGroupInstance(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ }
+
+ protected void startGroupBody(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ }
+
+ protected abstract void startOther(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException;
+
+ public void processText(final String text)
+ throws DataSourceException, ReportProcessingException
+ {
+ try
+ {
+ final XmlWriter xmlWriter = getXmlWriter();
+ final LineBreakIterator lb = new LineBreakIterator(text);
+ while (lb.hasNext())
+ {
+ final String line = (String) lb.next();
+ final String normalizedText = XmlWriterSupport.normalize(line, false);
+ xmlWriter.writeText(normalizedText);
+ if (lb.hasNext())
+ {
+ xmlWriter.writeTag(OfficeNamespaces.TEXT_NS, "line-break", XmlWriterSupport.CLOSE);
+ }
+ }
+ }
+ catch (IOException e)
+ {
+ throw new ReportProcessingException(FAILED, e);
+ }
+ }
+
+ protected boolean isFilteredNamespace(final String namespace)
+ {
+ if (Namespaces.LIBLAYOUT_NAMESPACE.equals(namespace))
+ {
+ return true;
+ }
+ if (JFreeReportInfo.REPORT_NAMESPACE.equals(namespace))
+ {
+ return true;
+ }
+ if (OfficeNamespaces.INTERNAL_NS.equals(namespace))
+ {
+ return true;
+ }
+ if (JFreeReportInfo.COMPATIBILITY_NAMESPACE.equals(namespace))
+ {
+ return true;
+ }
+ if (OfficeNamespaces.OOREPORT_NS.equals(namespace))
+ {
+ return true;
+ }
+ return false;
+ }
+
+ public void processContent(final DataFlags value)
+ throws DataSourceException, ReportProcessingException
+ {
+ final Object rawvalue = value.getValue();
+ if (rawvalue == null)
+ {
+ return;
+ }
+
+ // special handler for image (possibly also for URL ..)
+ if (rawvalue instanceof Image)
+ {
+ // do nothing yet. We should define something for that later ..
+ return;
+ }
+
+ final XmlWriter xmlWriter = getXmlWriter();
+ final String text = String.valueOf(rawvalue);
+ try
+ {
+ final LineBreakIterator lb = new LineBreakIterator(text);
+ while (lb.hasNext())
+ {
+ final String line = (String) lb.next();
+ final String normalizedText = XmlWriterSupport.normalize(line, false);
+ xmlWriter.writeText(normalizedText);
+ if (lb.hasNext())
+ {
+ xmlWriter.writeTag(OfficeNamespaces.TEXT_NS, "line-break", XmlWriterSupport.CLOSE);
+ }
+ }
+ }
+ catch (IOException e)
+ {
+ throw new ReportProcessingException(FAILED, e);
+ }
+ }
+
+ public final void endElement(final AttributeMap attrs)
+ throws DataSourceException, ReportProcessingException
+ {
+ // final int oldState = getCurrentState();
+ try
+ {
+
+ switch (getCurrentState())
+ {
+ case OfficeDocumentReportTarget.STATE_IN_OTHER:
+ {
+ endOther(attrs);
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_SECTION:
+ {
+ endReportSection(attrs, currentRole);
+ currentRole = OfficeDocumentReportTarget.ROLE_NONE;
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_GROUP:
+ {
+ endGroup(attrs);
+ groupContext = groupContext.getParent();
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_GROUP_INSTANCE:
+ {
+ endGroupInstance(attrs);
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_GROUP_BODY:
+ {
+ endGroupBody(attrs);
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_CONTENT:
+ {
+ endContent(attrs);
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_BODY:
+ {
+ endBody(attrs);
+ break;
+ }
+ case OfficeDocumentReportTarget.STATE_IN_DOCUMENT:
+ {
+ throw new IllegalStateException("This cannot be.");
+ }
+ default:
+ {
+ throw new IllegalStateException("Invalid state encountered.");
+ }
+ }
+ }
+ catch (IOException ioe)
+ {
+ throw new ReportProcessingException("IO Error while writing content",
+ ioe);
+ } finally
+ {
+ states.pop();
+
+ if (DEBUG_ELEMENTS)
+ {
+ Log.debug("Finished " + getCurrentState() + "/" + states.size() + " " +
+ ReportTargetUtil.getNamespaceFromAttribute(attrs) + ":" +
+ ReportTargetUtil.getElemenTypeFromAttribute(attrs));
+ }
+
+ }
+ }
+
+ protected void endGroupBody(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ }
+
+ protected void endGroupInstance(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ }
+
+ public int getCurrentRole()
+ {
+ return currentRole;
+ }
+
+ protected abstract void endOther(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException;
+
+ protected void endReportSection(final AttributeMap attrs,
+ final int role)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ if (allowBuffering(role))
+ {
+ finishBuffering();
+ }
+ }
+
+ protected void endGroup(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ }
+
+ protected abstract void endContent(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException;
+
+ protected void endBody(final AttributeMap attrs)
+ throws IOException, DataSourceException, ReportProcessingException
+ {
+ getXmlWriter().writeCloseTag();
+ }
+
+ public void endReport(final ReportStructureRoot report)
+ throws DataSourceException, ReportProcessingException
+ {
+ if (xmlWriters.size() != 1)
+ {
+ throw new IllegalStateException("Invalid writer-stack state");
+ }
+
+ try
+ {
+ final StylesWriter inlineStylesWriter = new StylesWriter(rootXmlWriter);
+ inlineStylesWriter.writeContentStyles(predefinedStylesCollection, contentStylesCollection);
+
+ final BufferState state = finishBuffering();
+ this.rootXmlWriter.writeStream(state.getXmlAsReader());
+
+ final OutputStream stylesOutStream =
+ outputRepository.createOutputStream("styles.xml", "text/xml");
+ final OutputStreamWriter osw =
+ new OutputStreamWriter(stylesOutStream, "UTF-8");
+ final StylesWriter stylesWriter = new StylesWriter(osw);
+ stylesWriter.writeGlobalStyles(predefinedStylesCollection, globalStylesCollection);
+ stylesWriter.close();
+
+ this.rootXmlWriter.writeCloseTag();
+ this.rootXmlWriter.close();
+ }
+ catch (IOException e)
+ {
+ throw new ReportProcessingException(FAILED, e);
+ }
+ }
+
+ public XmlWriter getXmlWriter()
+ {
+ final BufferState bufferState = (BufferState) xmlWriters.peek();
+ return bufferState.getXmlWriter();
+ }
+
+ public OfficeStylesCollection getStylesCollection()
+ {
+ final BufferState bufferState = (BufferState) xmlWriters.peek();
+ return bufferState.getStylesCollection();
+ }
+
+ public void startBuffering(final OfficeStylesCollection stylesCollection,
+ final boolean indent) throws ReportProcessingException
+ {
+ final XmlWriter currentWriter;
+ if (xmlWriters.isEmpty())
+ {
+ currentWriter = rootXmlWriter;
+ }
+ else
+ {
+ final BufferState bufferState = (BufferState) xmlWriters.peek();
+ currentWriter = bufferState.getXmlWriter();
+ }
+
+ try
+ {
+ final MemoryByteArrayOutputStream out =
+ new MemoryByteArrayOutputStream(INITIAL_BUFFER_SIZE, 256 * INITIAL_BUFFER_SIZE);
+ final DeflaterOutputStream deflateOut = new DeflaterOutputStream(out);
+ final OutputStreamWriter xmlBuffer = new OutputStreamWriter(deflateOut, "UTF-16");
+ // final StringWriter xmlBuffer = new StringWriter
+ // (OfficeDocumentReportTarget.INITIAL_BUFFER_SIZE);
+ final XmlWriter contentXmlWriter = new XmlWriter(xmlBuffer, createTagDescription());
+ contentXmlWriter.copyNamespaces(currentWriter);
+ if (indent)
+ {
+ contentXmlWriter.setAdditionalIndent(currentWriter.getCurrentIndentLevel());
+ contentXmlWriter.setWriteFinalLinebreak(true);
+ }
+ else
+ {
+ contentXmlWriter.setWriteFinalLinebreak(false);
+ }
+ contentXmlWriter.setAlwaysAddNamespace(true);
+ xmlWriters.push(new BufferState(contentXmlWriter, out, stylesCollection));
+ }
+ catch (IOException ioe)
+ {
+ throw new ReportProcessingException("Unable to create the buffer");
+ }
+ }
+
+ public BufferState finishBuffering() throws ReportProcessingException
+ {
+ final BufferState state = (BufferState) xmlWriters.pop();
+ try
+ {
+ state.getXmlWriter().close();
+ }
+ catch (IOException e)
+ {
+ Log.error("ReportProcessing failed", e);
+ }
+ return state;
+ }
+
+ public void commit()
+ throws ReportProcessingException
+ {
+ // do not call flush before the report is fully finished. Every flush
+ // causes the Office-Backend to fully ZIP all contents (it acts like a
+ // 'Save' call from the UI) and that's expensive like hell
+ }
+
+ public NamespaceDefinition getNamespaceByUri(final String uri)
+ {
+ return null;
+ }
+
+ protected AttributeList buildAttributeList(final AttributeMap attrs)
+ {
+ final AttributeList attrList = new AttributeList();
+ final String[] namespaces = attrs.getNameSpaces();
+ for (int i = 0; i < namespaces.length; i++)
+ {
+ final String attrNamespace = namespaces[i];
+ if (isFilteredNamespace(attrNamespace))
+ {
+ continue;
+ }
+
+ final Map localAttributes = attrs.getAttributes(attrNamespace);
+ final Iterator entries = localAttributes.entrySet().iterator();
+ while (entries.hasNext())
+ {
+ final Map.Entry entry = (Map.Entry) entries.next();
+ final String key = String.valueOf(entry.getKey());
+ if (OfficeNamespaces.TABLE_NS.equals(attrNamespace) &&
+ "name".equals(key))
+ {
+ final String tableName = String.valueOf(entry.getValue());
+ final String saneName = sanitizeName(tableName);
+ attrList.setAttribute(attrNamespace, key,
+ tableNameGenerator.generateName(saneName));
+ }
+ else if (OfficeNamespaces.DRAWING_NS.equals(attrNamespace) &&
+ "name".equals(key))
+ {
+ final String objectName = String.valueOf(entry.getValue());
+ attrList.setAttribute(attrNamespace, key,
+ frameNameGenerator.generateName(objectName));
+ }
+ else
+ {
+ attrList.setAttribute(attrNamespace, key, String.valueOf(entry.getValue()));
+ }
+ }
+ }
+ return attrList;
+ }
+
+ protected String sanitizeName(final String name)
+ {
+ // A table name cannot contain spaces and should only contain
+ // ascii-characters.
+ if (name == null)
+ {
+ return "";
+ }
+ final char[] chars = name.toCharArray();
+ final StringBuffer buffer = new StringBuffer();
+ for (int i = 0; i < chars.length; i++)
+ {
+ final char aChar = chars[i];
+ if (Character.isWhitespace(aChar))
+ {
+ buffer.append('_');
+ }
+ else
+ {
+ buffer.append(aChar);
+ }
+ }
+ return buffer.toString();
+ }
+
+ /**
+ * Returns the length in point. This method is f**king slow, it eats half of the processing time. I surely should
+ * replace it with something more efficient later.
+ *
+ * @param text
+ * @return
+ */
+ protected CSSNumericValue parseLength(final String text)
+ {
+ if (styleSheetParserUtil == null)
+ {
+ styleSheetParserUtil = StyleSheetParserUtil.getInstance();
+ }
+
+ final LexicalUnit cssValue = styleSheetParserUtil.parseLexicalStyleValue(
+ text);
+ return CSSValueFactory.createLengthValue(cssValue);
+ }
+
+ protected boolean isRepeatingSection()
+ {
+ return (currentRole == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_FOOTER ||
+ currentRole == OfficeDocumentReportTarget.ROLE_REPEATING_GROUP_HEADER ||
+ currentRole == OfficeDocumentReportTarget.ROLE_PAGE_FOOTER ||
+ currentRole == OfficeDocumentReportTarget.ROLE_PAGE_HEADER ||
+ currentRole == OfficeDocumentReportTarget.ROLE_VARIABLES);
+
+ }
+
+ protected OfficeStyle deriveStyle(final String styleFamily, final String styleName)
+ throws ReportProcessingException
+ {
+ // autogenerate a style. The style has already been added to the current
+ // auto-collection.
+ final OfficeStyle style = StyleUtilities.deriveStyle(styleFamily, styleName,
+ getStylesCollection(), getGlobalStylesCollection(),
+ getPredefinedStylesCollection(), getAutoStyleNameGenerator());
+ return style;
+ }
+
+ protected void startImageProcessing(final AttributeMap attrs)
+ throws ReportProcessingException
+ {
+ final Object imageData = attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, OfficeToken.IMAGE_DATA);
+ final boolean preserveIRI = OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, OfficeToken.PRESERVE_IRI));
+
+ // for the first shot, do nothing fancy ..
+ final ImageProducer.OfficeImage image = imageProducer.produceImage(imageData, preserveIRI);
+ if (image != null)
+ {
+ final ImageElementContext imageContext = (ImageElementContext) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "image-context");
+
+ // When scaling, we have to create an image-style.
+ final CSSNumericValue width = image.getWidth(); // always in 100th of a mm
+
+ final CSSNumericValue height = image.getHeight(); // always in 100th of a mm
+
+ Log.debug("Image " + imageData + " Width: " + width + ", Height: " + height);
+ if (width == null || height == null)
+ {
+ return;
+ }
+
+ CSSNumericValue imageAreaWidthVal;
+ CSSNumericValue imageAreaHeightVal;
+ String styleName = null;
+ if (imageContext != null)
+ {
+ imageAreaWidthVal = computeImageWidth(imageContext);
+ imageAreaHeightVal = computeImageHeight(imageContext);
+
+ if (imageAreaWidthVal == null || imageAreaHeightVal == null)
+ {
+ Log.debug("Image data returned from context is invalid. Maybe this is not an image?");
+ return;
+ }
+ else
+ {
+ // compute the clip-area ..
+ final CSSNumericValue normalizedImageWidth =
+ CSSValueResolverUtility.convertLength(width, imageAreaWidthVal.getType());
+ final CSSNumericValue normalizedImageHeight =
+ CSSValueResolverUtility.convertLength(height, imageAreaHeightVal.getType());
+
+ final boolean scale = OfficeToken.TRUE.equals(attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, OfficeToken.SCALE));
+ if (!scale && normalizedImageWidth.getValue() > 0 && normalizedImageHeight.getValue() > 0)
+ {
+ final double clipWidth = normalizedImageWidth.getValue() - imageAreaWidthVal.getValue();
+ final double clipHeight = normalizedImageHeight.getValue() - imageAreaHeightVal.getValue();
+ if (clipWidth > 0 && clipHeight > 0)
+ {
+ final OfficeStyle imageStyle = deriveStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS);
+ final Element graphProperties = produceFirstChild(imageStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES);
+ final StringBuffer buffer = new StringBuffer();
+ buffer.append("rect(");
+ buffer.append(clipHeight / 2);
+ buffer.append(imageAreaHeightVal.getType().getType());
+ buffer.append(' ');
+ buffer.append(clipWidth / 2);
+ buffer.append(imageAreaWidthVal.getType().getType());
+ buffer.append(' ');
+ buffer.append(clipHeight / 2);
+ buffer.append(imageAreaHeightVal.getType().getType());
+ buffer.append(' ');
+ buffer.append(clipWidth / 2);
+ buffer.append(imageAreaWidthVal.getType().getType());
+ buffer.append(')');
+ graphProperties.setAttribute(OfficeNamespaces.FO_NS, "clip", buffer.toString());
+
+ styleName = imageStyle.getStyleName();
+ getStylesCollection().getAutomaticStyles().addStyle(imageStyle);
+ }
+ else if (clipWidth > 0)
+ {
+ final OfficeStyle imageStyle = deriveStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS);
+ final Element graphProperties = produceFirstChild(imageStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES);
+ final StringBuffer buffer = new StringBuffer();
+ buffer.append("rect(0cm ");
+ buffer.append(clipWidth / 2);
+ buffer.append(imageAreaWidthVal.getType().getType());
+ buffer.append(" 0cm ");
+ buffer.append(clipWidth / 2);
+ buffer.append(imageAreaWidthVal.getType().getType());
+ buffer.append(')');
+ graphProperties.setAttribute(OfficeNamespaces.FO_NS, "clip", buffer.toString());
+
+ styleName = imageStyle.getStyleName();
+ getStylesCollection().getAutomaticStyles().addStyle(imageStyle);
+ imageAreaHeightVal = normalizedImageHeight;
+ }
+ else if (clipHeight > 0)
+ {
+ final OfficeStyle imageStyle = deriveStyle(OfficeToken.GRAPHIC, OfficeToken.GRAPHICS);
+ final Element graphProperties = produceFirstChild(imageStyle, OfficeNamespaces.STYLE_NS, OfficeToken.GRAPHIC_PROPERTIES);
+ final StringBuffer buffer = new StringBuffer();
+ buffer.append("rect(");
+ buffer.append(clipHeight / 2);
+ buffer.append(imageAreaHeightVal.getType().getType());
+ buffer.append(" 0cm ");
+ buffer.append(clipHeight / 2);
+ buffer.append(imageAreaHeightVal.getType().getType());
+ buffer.append(" 0cm)");
+ graphProperties.setAttribute(OfficeNamespaces.FO_NS, "clip", buffer.toString());
+
+ styleName = imageStyle.getStyleName();
+ getStylesCollection().getAutomaticStyles().addStyle(imageStyle);
+ imageAreaWidthVal = normalizedImageWidth;
+ }
+ else
+ {
+ imageAreaWidthVal = normalizedImageWidth;
+ imageAreaHeightVal = normalizedImageHeight;
+ }
+ }
+ }
+ // If we do scale, then we simply use the given image-area-size as valid image size and dont
+ // care about the image itself ..
+ }
+ else
+ {
+ Log.debug("There is no image-context, so we have to rely on the image's natural bounds. " +
+ "This may go awfully wrong.");
+ imageAreaWidthVal = image.getWidth();
+ imageAreaHeightVal = image.getHeight();
+ }
+
+ final AttributeList frameList = new AttributeList();
+ frameList.setAttribute(OfficeNamespaces.DRAWING_NS, "name", imageNames.generateName("Image"));
+ if (styleName != null)
+ {
+ frameList.setAttribute(OfficeNamespaces.DRAWING_NS, OfficeToken.STYLE_NAME, styleName);
+ }
+ frameList.setAttribute(OfficeNamespaces.TEXT_NS, "anchor-type", OfficeToken.PARAGRAPH);
+ frameList.setAttribute(OfficeNamespaces.SVG_NS, "z-index", "0");
+ frameList.setAttribute(OfficeNamespaces.SVG_NS, "x", ZERO_CM);
+ frameList.setAttribute(OfficeNamespaces.SVG_NS, "y", ZERO_CM);
+
+ Log.debug("Image " + imageData + " A-Width: " + imageAreaWidthVal + ", A-Height: " + imageAreaHeightVal);
+
+ if (imageAreaWidthVal != null)
+ {
+ frameList.setAttribute(OfficeNamespaces.SVG_NS,
+ "width", imageAreaWidthVal.getValue() + imageAreaWidthVal.getType().getType());
+ }
+
+ if (imageAreaHeightVal != null)
+ {
+ frameList.setAttribute(OfficeNamespaces.SVG_NS,
+ "height", imageAreaHeightVal.getValue() + imageAreaHeightVal.getType().getType());
+ }
+
+
+ final AttributeList imageList = new AttributeList();
+ imageList.setAttribute(OfficeNamespaces.XLINK_NS, "href", image.getEmbeddableLink());
+ imageList.setAttribute(OfficeNamespaces.XLINK_NS, "type", "simple");
+ imageList.setAttribute(OfficeNamespaces.XLINK_NS, "show", "embed");
+ imageList.setAttribute(OfficeNamespaces.XLINK_NS, "actuate", "onLoad");
+
+
+ try
+ {
+ getXmlWriter().writeTag(OfficeNamespaces.DRAWING_NS, "frame", frameList, XmlWriterSupport.OPEN);
+ getXmlWriter().writeTag(OfficeNamespaces.DRAWING_NS, OfficeToken.IMAGE, imageList, XmlWriterSupport.CLOSE);
+ getXmlWriter().writeCloseTag();
+ }
+ catch (IOException ioe)
+ {
+ throw new ReportProcessingException(FAILED, ioe);
+ }
+ }
+ }
+
+ private CSSNumericValue computeImageWidth(final ImageElementContext imageElementContext)
+ {
+ final LengthCalculator calculator = new LengthCalculator();
+ final String[] strings = imageElementContext.getColStyles();
+ for (int i = 0; i < strings.length; i++)
+ {
+ final String styleName = strings[i];
+ final CSSNumericValue value = computeColumnWidth(styleName);
+ if (value != null)
+ {
+ calculator.add(value);
+ }
+ }
+ return calculator.getResult();
+ }
+
+ private CSSNumericValue computeImageHeight(final ImageElementContext imageElementContext)
+ {
+ final LengthCalculator calculator = new LengthCalculator();
+ final String[] strings = imageElementContext.getRowStyles();
+ for (int i = 0; i < strings.length; i++)
+ {
+ final String styleName = strings[i];
+ final CSSNumericValue value = computeRowHeight(styleName);
+ if (value != null)
+ {
+ calculator.add(value);
+ }
+ }
+ return calculator.getResult();
+ }
+
+ protected CSSNumericValue computeRowHeight(final String rowStyle)
+ {
+ final OfficeStylesCollection contentStyles = getContentStylesCollection();
+ final OfficeStyle style = contentStyles.getStyle(OfficeToken.TABLE_ROW, rowStyle);
+ if (style != null)
+ {
+ final Element element = style.getTableRowProperties();
+ if (element != null)
+ {
+ final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "row-height");
+ if (height != null)
+ {
+ return parseLength(height);
+ }
+ }
+
+ final String styleParent = style.getStyleParent();
+ if (styleParent != null)
+ {
+ return computeRowHeight(styleParent);
+ }
+ }
+
+ final OfficeStylesCollection globalStyles = getGlobalStylesCollection();
+ final OfficeStyle globalStyle = globalStyles.getStyle(OfficeToken.TABLE_ROW, rowStyle);
+ if (globalStyle != null)
+ {
+ final Element element = globalStyle.getTableRowProperties();
+ if (element != null)
+ {
+ final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "row-height");
+ if (height != null)
+ {
+ return parseLength(height);
+ }
+ }
+ final String styleParent = globalStyle.getStyleParent();
+ if (styleParent != null)
+ {
+ return computeRowHeight(styleParent);
+ }
+ }
+
+ final OfficeStylesCollection predefStyles = getPredefinedStylesCollection();
+ final OfficeStyle predefStyle = predefStyles.getStyle(OfficeToken.TABLE_ROW, rowStyle);
+ if (predefStyle != null)
+ {
+ final Element element = predefStyle.getTableRowProperties();
+ if (element != null)
+ {
+ final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "row-height");
+ if (height != null)
+ {
+ return parseLength(height);
+ }
+ }
+ final String styleParent = predefStyle.getStyleParent();
+ if (styleParent != null)
+ {
+ return computeRowHeight(styleParent);
+ }
+ }
+ // not found.
+ return null;
+ }
+
+ protected CSSNumericValue computeColumnWidth(final String colStyle)
+ {
+ final OfficeStylesCollection contentStyles = getContentStylesCollection();
+ final OfficeStyle style = contentStyles.getStyle(OfficeToken.TABLE_COLUMN, colStyle);
+ if (style != null)
+ {
+ final Element element = style.getTableColumnProperties();
+ if (element != null)
+ {
+ final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "column-width");
+ if (height != null)
+ {
+ return parseLength(height);
+ }
+ }
+
+ final String styleParent = style.getStyleParent();
+ if (styleParent != null)
+ {
+ return computeRowHeight(styleParent);
+ }
+ }
+
+ final OfficeStylesCollection globalStyles = getGlobalStylesCollection();
+ final OfficeStyle globalStyle = globalStyles.getStyle(OfficeToken.TABLE_COLUMN, colStyle);
+ if (globalStyle != null)
+ {
+ final Element element = globalStyle.getTableColumnProperties();
+ if (element != null)
+ {
+ final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "column-width");
+ if (height != null)
+ {
+ return parseLength(height);
+ }
+ }
+ final String styleParent = globalStyle.getStyleParent();
+ if (styleParent != null)
+ {
+ return computeRowHeight(styleParent);
+ }
+ }
+
+ final OfficeStylesCollection predefStyles = getPredefinedStylesCollection();
+ final OfficeStyle predefStyle = predefStyles.getStyle(OfficeToken.TABLE_COLUMN, colStyle);
+ if (predefStyle != null)
+ {
+ final Element element = predefStyle.getTableColumnProperties();
+ if (element != null)
+ {
+ final String height = (String) element.getAttribute(OfficeNamespaces.STYLE_NS, "column-width");
+ if (height != null)
+ {
+ return parseLength(height);
+ }
+ }
+ final String styleParent = predefStyle.getStyleParent();
+ if (styleParent != null)
+ {
+ return computeRowHeight(styleParent);
+ }
+ }
+ // not found.
+ return null;
+ }
+
+ protected Element produceFirstChild(final Section style,
+ final String nameSpace,
+ final String type)
+ {
+ Element paragraphProps = style.findFirstChild(nameSpace, type);
+ if (paragraphProps == null)
+ {
+ paragraphProps = new Section();
+ paragraphProps.setNamespace(nameSpace);
+ paragraphProps.setType(type);
+ style.addNode(paragraphProps);
+ }
+ return paragraphProps;
+ }
+
+ protected void startChartProcessing(final AttributeMap attrs)
+ throws ReportProcessingException
+ {
+ final String classId = (String) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "class-id");
+ final String chartUrl = (String) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, "href");
+ final ArrayList masterColumns = (ArrayList) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.MASTER_COLUMNS);
+ final ArrayList masterValues = (ArrayList) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.MASTER_VALUES);
+ final ArrayList detailColumns = (ArrayList) attrs.getAttribute(OfficeNamespaces.INTERNAL_NS, SDBCReportDataFactory.DETAIL_COLUMNS);
+ final String href = oleProducer.produceOle(chartUrl, masterColumns, masterValues, detailColumns);
+
+ final AttributeList oleList = new AttributeList();
+ oleList.setAttribute(OfficeNamespaces.DRAWING_NS, "class-id", classId);
+ oleList.setAttribute(OfficeNamespaces.XLINK_NS, "href", "./" + href);
+ oleList.setAttribute(OfficeNamespaces.XLINK_NS, "type", "simple");
+ oleList.setAttribute(OfficeNamespaces.XLINK_NS, "show", "embed");
+ oleList.setAttribute(OfficeNamespaces.XLINK_NS, "actuate", "onLoad");
+
+ try
+ {
+ getXmlWriter().writeTag(OfficeNamespaces.DRAWING_NS, OfficeToken.OBJECT_OLE, oleList, XmlWriterSupport.CLOSE);
+ }
+ catch (IOException ioe)
+ {
+ throw new ReportProcessingException(FAILED, ioe);
+ }
+
+
+ }
+}
diff --git a/reportdesign/source/filter/xml/xmlCell.cxx b/reportdesign/source/filter/xml/xmlCell.cxx index 0294839672e62..e4c394622f697 100644 --- a/reportdesign/source/filter/xml/xmlCell.cxx +++ b/reportdesign/source/filter/xml/xmlCell.cxx @@ -171,7 +171,7 @@ SvXMLImportContext* OXMLCell::CreateChildContext( m_nCurrentCount = m_pContainer->getSection()->getCount(); uno::Reference< uno::XInterface> xInt = xFactor->createInstance(SERVICE_FORMATTEDFIELD); Reference< report::XFormattedField > xControl(xInt,uno::UNO_QUERY); - pContext = new OXMLSubDocument( rImport, _nPrefix, _rLocalName,xControl.get(),m_pContainer); + pContext = new OXMLSubDocument( rImport, _nPrefix, _rLocalName,xControl.get(),m_pContainer, this /* give the current cell as parent*/ ); } break; @@ -285,6 +285,11 @@ void OXMLCell::Characters( const ::rtl::OUString& rChars ) } } +void OXMLCell::setContainsShape(bool _bContainsShape) +{ + m_bContainsShape = _bContainsShape; +} + //---------------------------------------------------------------------------- } // namespace rptxml // ----------------------------------------------------------------------------- diff --git a/reportdesign/source/filter/xml/xmlCell.hxx b/reportdesign/source/filter/xml/xmlCell.hxx index 122aac8f8976c..2726a50da521b 100644 --- a/reportdesign/source/filter/xml/xmlCell.hxx +++ b/reportdesign/source/filter/xml/xmlCell.hxx @@ -68,6 +68,7 @@ namespace rptxml virtual void EndElement(); void setComponent(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent >& _xComponent); + void setContainsShape(bool _bContainsShapes); }; // ----------------------------------------------------------------------------- } // namespace rptxml diff --git a/reportdesign/source/filter/xml/xmlExportDocumentHandler.cxx b/reportdesign/source/filter/xml/xmlExportDocumentHandler.cxx index 086ed401cbe2b..6e76f28cdc12e 100644 --- a/reportdesign/source/filter/xml/xmlExportDocumentHandler.cxx +++ b/reportdesign/source/filter/xml/xmlExportDocumentHandler.cxx @@ -1,397 +1,396 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: xmlExportDocumentHandler.cxx,v $ - * $Revision: 1.5 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * <http://www.openoffice.org/license.html> - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -#include "precompiled_reportdesign.hxx" - -#include "xmlExportDocumentHandler.hxx" -#include <com/sun/star/sdb/CommandType.hpp> -#include <com/sun/star/chart2/data/XDatabaseDataProvider.hpp> -#include <com/sun/star/reflection/XProxyFactory.hpp> -#include <com/sun/star/sdb/CommandType.hpp> -#include <comphelper/sequence.hxx> -#include <comphelper/sequenceashashmap.hxx> -#include <comphelper/documentconstants.hxx> -#include <xmloff/attrlist.hxx> -#include <xmloff/xmltoken.hxx> -#include <xmloff/xmlement.hxx> -#include <xmloff/xmluconv.hxx> -#include <svtools/saveopt.hxx> -#include <rtl/ustrbuf.hxx> -#include <connectivity/dbtools.hxx> -#include <rtl/ustrbuf.hxx> - -namespace rptxml -{ -using namespace ::com::sun::star; -using namespace ::xmloff::token; - -void lcl_exportPrettyPrinting(const uno::Reference< xml::sax::XDocumentHandler >& _xDelegatee) -{ - SvtSaveOptions aSaveOpt; - if ( aSaveOpt.IsPrettyPrinting() ) - { - static const ::rtl::OUString s_sWhitespaces(RTL_CONSTASCII_USTRINGPARAM(" ")); - _xDelegatee->ignorableWhitespace(s_sWhitespaces); - } -} - -::rtl::OUString lcl_createAttribute(const xmloff::token::XMLTokenEnum& _eNamespace,const xmloff::token::XMLTokenEnum& _eAttribute) -{ - ::rtl::OUStringBuffer sQName; - // ...if it's in our map, make the prefix - sQName.append ( xmloff::token::GetXMLToken(_eNamespace) ); - sQName.append ( sal_Unicode(':') ); - sQName.append ( xmloff::token::GetXMLToken(_eAttribute) ); - return sQName.makeStringAndClear(); -} - -void lcl_correctCellAddress(const ::rtl::OUString & _sName, const uno::Reference< xml::sax::XAttributeList > & xAttribs) -{ - SvXMLAttributeList* pList = SvXMLAttributeList::getImplementation(xAttribs); - ::rtl::OUString sCellAddress = pList->getValueByName(_sName); - const sal_Int32 nPos = sCellAddress.lastIndexOf('$'); - if ( nPos != -1 ) - { - sCellAddress = sCellAddress.copy(0,nPos); - sCellAddress += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("$65535")); - pList->RemoveAttribute(_sName); - pList->AddAttribute(_sName,sCellAddress); - } -} - -ExportDocumentHandler::ExportDocumentHandler(uno::Reference< uno::XComponentContext > const & context) : - m_xContext(context) - ,m_nCurrentCellIndex(0) - ,m_bTableRowsStarted(false) - ,m_bFirstRowExported(false) - ,m_bExportChar(false) -{ -} -// ----------------------------------------------------------------------------- -ExportDocumentHandler::~ExportDocumentHandler() -{ - if ( m_xProxy.is() ) - { - m_xProxy->setDelegator( NULL ); - m_xProxy.clear(); - } -} -IMPLEMENT_GET_IMPLEMENTATION_ID(ExportDocumentHandler) -IMPLEMENT_FORWARD_REFCOUNT( ExportDocumentHandler, ExportDocumentHandler_BASE ) -//------------------------------------------------------------------------ -::rtl::OUString SAL_CALL ExportDocumentHandler::getImplementationName( ) throw(uno::RuntimeException) -{ - return getImplementationName_Static(); -} - -//------------------------------------------------------------------------ -sal_Bool SAL_CALL ExportDocumentHandler::supportsService( const ::rtl::OUString& ServiceName ) throw(uno::RuntimeException) -{ - return ::comphelper::existsValue(ServiceName,getSupportedServiceNames_static()); -} - -//------------------------------------------------------------------------ -uno::Sequence< ::rtl::OUString > SAL_CALL ExportDocumentHandler::getSupportedServiceNames( ) throw(uno::RuntimeException) -{ - uno::Sequence< ::rtl::OUString > aSupported; - if ( m_xServiceInfo.is() ) - aSupported = m_xServiceInfo->getSupportedServiceNames(); - return ::comphelper::concatSequences(getSupportedServiceNames_static(),aSupported); -} - -//------------------------------------------------------------------------ -::rtl::OUString ExportDocumentHandler::getImplementationName_Static( ) throw(uno::RuntimeException) -{ - return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.report.ExportDocumentHandler")); -} - -//------------------------------------------------------------------------ -uno::Sequence< ::rtl::OUString > ExportDocumentHandler::getSupportedServiceNames_static( ) throw(uno::RuntimeException) -{ - uno::Sequence< ::rtl::OUString > aSupported(1); - aSupported[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.report.ExportDocumentHandler")); - return aSupported; -} - -//------------------------------------------------------------------------ -uno::Reference< uno::XInterface > SAL_CALL ExportDocumentHandler::create( const uno::Reference< uno::XComponentContext >& _rxContext ) -{ - return *(new ExportDocumentHandler( _rxContext )); -} -// xml::sax::XDocumentHandler: -void SAL_CALL ExportDocumentHandler::startDocument() throw (uno::RuntimeException, xml::sax::SAXException) -{ - m_xDelegatee->startDocument(); -} - -void SAL_CALL ExportDocumentHandler::endDocument() throw (uno::RuntimeException, xml::sax::SAXException) -{ - m_xDelegatee->endDocument(); -} - -void SAL_CALL ExportDocumentHandler::startElement(const ::rtl::OUString & _sName, const uno::Reference< xml::sax::XAttributeList > & xAttribs) throw (uno::RuntimeException, xml::sax::SAXException) -{ - bool bExport = true; - if ( _sName.equalsAscii("office:chart") ) - { - SvXMLAttributeList* pList = new SvXMLAttributeList(); - uno::Reference< xml::sax::XAttributeList > xNewAttribs = pList; - ::rtl::OUStringBuffer sValue; - static SvXMLEnumMapEntry aXML_CommnadTypeEnumMap[] = - { - { XML_TABLE, sdb::CommandType::TABLE }, - { XML_QUERY, sdb::CommandType::QUERY }, - // { XML_COMMAND, CommandType::COMMAND }, // default - { XML_TOKEN_INVALID, 0 } - }; - if ( SvXMLUnitConverter::convertEnum( sValue, static_cast<sal_uInt16>(m_xDatabaseDataProvider->getCommandType()),aXML_CommnadTypeEnumMap ) ) - { - pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_COMMAND_TYPE),sValue.makeStringAndClear()); - } - ::rtl::OUString sComamnd = m_xDatabaseDataProvider->getCommand(); - if ( sComamnd.getLength() ) - pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_COMMAND),sComamnd); - - ::rtl::OUString sFilter( m_xDatabaseDataProvider->getFilter() ); - if ( sFilter.getLength() ) - pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_FILTER),sFilter); - - sal_Bool bEscapeProcessing( m_xDatabaseDataProvider->getEscapeProcessing() ); - if ( !bEscapeProcessing ) - pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_ESCAPE_PROCESSING),::xmloff::token::GetXMLToken( XML_FALSE )); - - pList->AddAttribute(lcl_createAttribute(XML_NP_OFFICE,XML_MIMETYPE),MIMETYPE_OASIS_OPENDOCUMENT_CHART); - - m_xDelegatee->startElement(lcl_createAttribute(XML_NP_OFFICE,XML_REPORT),xNewAttribs); - - /*const uno::Sequence< ::rtl::OUString > aDetailFields = m_xDatabaseDataProvider->getDetailFields(); - if ( aDetailFields.getLength() ) - { - lcl_exportPrettyPrinting(m_xDelegatee); - m_xDelegatee->startElement(lcl_createAttribute(XML_NP_RPT,XML_MASTER_DETAIL_FIELDS),NULL); - const uno::Sequence< ::rtl::OUString > aMasterFields = m_xDatabaseDataProvider->getMasterFields(); - OSL_ENSURE(aDetailFields.getLength() == aMasterFields.getLength(),"not equal length for master and detail fields!"); - const ::rtl::OUString sDetailToken = lcl_createAttribute(XML_NP_RPT, XML_DETAIL); - const ::rtl::OUString sMasterToken = lcl_createAttribute(XML_NP_RPT, XML_MASTER); - const ::rtl::OUString sElementToken = lcl_createAttribute(XML_NP_RPT,XML_MASTER_DETAIL_FIELD); - const ::rtl::OUString* pDetailFieldsIter = aDetailFields.getConstArray(); - const ::rtl::OUString* pIter = aMasterFields.getConstArray(); - const ::rtl::OUString* pEnd = pIter + aMasterFields.getLength(); - for(;pIter != pEnd;++pIter,++pDetailFieldsIter) - { - pList = new SvXMLAttributeList(); - xNewAttribs = pList; - pList->AddAttribute( sMasterToken , *pIter ); - if ( pDetailFieldsIter->getLength() ) - pList->AddAttribute( sDetailToken , *pDetailFieldsIter ); - lcl_exportPrettyPrinting(m_xDelegatee); - m_xDelegatee->startElement(sElementToken,xNewAttribs); - lcl_exportPrettyPrinting(m_xDelegatee); - m_xDelegatee->endElement(sElementToken); - } - lcl_exportPrettyPrinting(m_xDelegatee); - m_xDelegatee->endElement(lcl_createAttribute(XML_NP_RPT,XML_MASTER_DETAIL_FIELDS)); - }*/ - bExport = false; - } - else if ( _sName.equalsAscii("table:table") ) - { - m_xDelegatee->startElement(lcl_createAttribute(XML_NP_RPT,XML_DETAIL),NULL); - lcl_exportPrettyPrinting(m_xDelegatee); - } - else if ( _sName.equalsAscii("table:table-rows") ) - m_bTableRowsStarted = true; - else if ( m_bTableRowsStarted && m_bFirstRowExported && (_sName.equalsAscii("table:table-row") || _sName.equalsAscii("table:table-cell")) ) - bExport = false; - else if ( _sName.equalsAscii("chart:plot-area")) - { - SvXMLAttributeList* pList = SvXMLAttributeList::getImplementation(xAttribs); - pList->RemoveAttribute(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("table:cell-range-address"))); - } - else if ( _sName.equalsAscii("chart:categories")) - { - static ::rtl::OUString s_sCellAddress(lcl_createAttribute(XML_NP_TABLE,XML_CELL_RANGE_ADDRESS)); - lcl_correctCellAddress(s_sCellAddress,xAttribs); - } - else if ( _sName.equalsAscii("chart:series")) - { - static ::rtl::OUString s_sCellAddress(lcl_createAttribute(XML_NP_CHART,XML_VALUES_CELL_RANGE_ADDRESS)); - lcl_correctCellAddress(s_sCellAddress,xAttribs); - } - else if ( m_bTableRowsStarted && !m_bFirstRowExported && _sName.equalsAscii("table:table-cell") ) - { - SvXMLAttributeList* pList = SvXMLAttributeList::getImplementation(xAttribs); - static ::rtl::OUString s_sValue(lcl_createAttribute(XML_NP_OFFICE,XML_VALUE)); - pList->RemoveAttribute(s_sValue); - } - else if ( m_bTableRowsStarted && _sName.equalsAscii("text:p") ) - { - if ( !m_bFirstRowExported ) - { - SvXMLAttributeList* pList = SvXMLAttributeList::getImplementation(xAttribs); - pList->RemoveAttribute(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("text:id"))); - m_xDelegatee->startElement(_sName,xAttribs); - pList = new SvXMLAttributeList(); - uno::Reference< xml::sax::XAttributeList > xNewAttribs = pList; - - ::rtl::OUString sFormula; - if( m_nCurrentCellIndex < m_aColumns.getLength() ) - { - sFormula += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("field:[")); - sFormula += m_aColumns[m_nCurrentCellIndex]; - sFormula += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("]")); - } - pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_FORMULA),sFormula); - - m_xDelegatee->startElement(lcl_createAttribute(XML_NP_RPT,XML_FORMATTED_TEXT),xNewAttribs); - m_xDelegatee->startElement(lcl_createAttribute(XML_NP_RPT,XML_REPORT_ELEMENT),NULL); - m_xDelegatee->startElement(lcl_createAttribute(XML_NP_RPT,XML_REPORT_COMPONENT),NULL); - m_bExportChar = true; - - ++m_nCurrentCellIndex; - } - bExport = false; - } - if ( bExport ) - m_xDelegatee->startElement(_sName,xAttribs); -} -// ----------------------------------------------------------------------------- -void SAL_CALL ExportDocumentHandler::endElement(const ::rtl::OUString & _sName) throw (uno::RuntimeException, xml::sax::SAXException) -{ - bool bExport = true; - ::rtl::OUString sNewName = _sName; - if ( _sName.equalsAscii("office:chart") ) - { - sNewName = lcl_createAttribute(XML_NP_OFFICE,XML_REPORT); - } - else if ( _sName.equalsAscii("table:table") ) - { - m_xDelegatee->endElement(_sName); - lcl_exportPrettyPrinting(m_xDelegatee); - sNewName = lcl_createAttribute(XML_NP_RPT,XML_DETAIL); - } - else if ( _sName.equalsAscii("table:table-rows") ) - m_bTableRowsStarted = false; - else if ( m_bTableRowsStarted && m_bFirstRowExported && (_sName.equalsAscii("table:table-row") || _sName.equalsAscii("table:table-cell")) ) - bExport = false; - else if ( m_bTableRowsStarted && _sName.equalsAscii("table:table-row") ) - m_bFirstRowExported = true; - else if ( m_bTableRowsStarted && _sName.equalsAscii("text:p") ) - { - bExport = !m_bFirstRowExported; - if ( bExport ) - { - m_bExportChar = false; - m_xDelegatee->endElement(lcl_createAttribute(XML_NP_RPT,XML_REPORT_COMPONENT)); - m_xDelegatee->endElement(lcl_createAttribute(XML_NP_RPT,XML_REPORT_ELEMENT)); - m_xDelegatee->endElement(lcl_createAttribute(XML_NP_RPT,XML_FORMATTED_TEXT)); - } - } - - if ( bExport ) - m_xDelegatee->endElement(sNewName); -} - -void SAL_CALL ExportDocumentHandler::characters(const ::rtl::OUString & aChars) throw (uno::RuntimeException, xml::sax::SAXException) -{ - if ( !(m_bTableRowsStarted || m_bFirstRowExported) ) - m_xDelegatee->characters(aChars); - else if ( m_bExportChar ) - { - static const ::rtl::OUString s_sZero(RTL_CONSTASCII_USTRINGPARAM("0")); - m_xDelegatee->characters(s_sZero); - } -} - -void SAL_CALL ExportDocumentHandler::ignorableWhitespace(const ::rtl::OUString & aWhitespaces) throw (uno::RuntimeException, xml::sax::SAXException) -{ - m_xDelegatee->ignorableWhitespace(aWhitespaces); -} - -void SAL_CALL ExportDocumentHandler::processingInstruction(const ::rtl::OUString & aTarget, const ::rtl::OUString & aData) throw (uno::RuntimeException, xml::sax::SAXException) -{ - m_xDelegatee->processingInstruction(aTarget,aData); -} - -void SAL_CALL ExportDocumentHandler::setDocumentLocator(const uno::Reference< xml::sax::XLocator > & xLocator) throw (uno::RuntimeException, xml::sax::SAXException) -{ - m_xDelegatee->setDocumentLocator(xLocator); -} -void SAL_CALL ExportDocumentHandler::initialize( const uno::Sequence< uno::Any >& _aArguments ) throw (uno::Exception, uno::RuntimeException) -{ - ::osl::MutexGuard aGuard(m_aMutex); - comphelper::SequenceAsHashMap aArgs(_aArguments); - m_xDelegatee = aArgs.getUnpackedValueOrDefault(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DocumentHandler")),m_xDelegatee); - m_xModel = aArgs.getUnpackedValueOrDefault(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Model")),m_xModel); - - OSL_ENSURE(m_xDelegatee.is(),"No document handler avialable!"); - if ( !m_xDelegatee.is() || !m_xModel.is() ) - throw uno::Exception(); - - m_xDatabaseDataProvider.set(m_xModel->getDataProvider(),uno::UNO_QUERY); - if ( !m_xDatabaseDataProvider.is() ) - throw uno::Exception(); - - uno::Reference< reflection::XProxyFactory > xProxyFactory( m_xContext->getServiceManager()->createInstanceWithContext( - ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.reflection.ProxyFactory")),m_xContext), - uno::UNO_QUERY); - m_xProxy = xProxyFactory->createProxy(m_xDelegatee.get()); - ::comphelper::query_aggregation(m_xProxy,m_xDelegatee); - m_xTypeProvider.set(m_xDelegatee,uno::UNO_QUERY); - m_xServiceInfo.set(m_xDelegatee,uno::UNO_QUERY); - - // set ourself as delegator - m_xProxy->setDelegator( *this ); - - const ::rtl::OUString sCommand = m_xDatabaseDataProvider->getCommand(); - if ( sCommand.getLength() ) - m_aColumns = ::dbtools::getFieldNamesByCommandDescriptor(m_xDatabaseDataProvider->getActiveConnection() - ,m_xDatabaseDataProvider->getCommandType() - ,sCommand); -} -// -------------------------------------------------------------------------------- -uno::Any SAL_CALL ExportDocumentHandler::queryInterface( const uno::Type& _rType ) throw (uno::RuntimeException) -{ - uno::Any aReturn = ExportDocumentHandler_BASE::queryInterface(_rType); - return aReturn.hasValue() ? aReturn : (m_xProxy.is() ? m_xProxy->queryAggregation(_rType) : aReturn); -} -// -------------------------------------------------------------------------------- -uno::Sequence< uno::Type > SAL_CALL ExportDocumentHandler::getTypes( ) throw (uno::RuntimeException) -{ - if ( m_xTypeProvider.is() ) - return ::comphelper::concatSequences( - ExportDocumentHandler_BASE::getTypes(), - m_xTypeProvider->getTypes() - ); - return ExportDocumentHandler_BASE::getTypes(); -} - -// ----------------------------------------------------------------------------- -} // namespace rptxml -// ----------------------------------------------------------------------------- +/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: xmlExportDocumentHandler.cxx,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+#include "precompiled_reportdesign.hxx"
+
+#include "xmlExportDocumentHandler.hxx"
+#include <com/sun/star/sdb/CommandType.hpp>
+#include <com/sun/star/chart2/data/XDatabaseDataProvider.hpp>
+#include <com/sun/star/reflection/XProxyFactory.hpp>
+#include <com/sun/star/sdb/CommandType.hpp>
+#include <comphelper/sequence.hxx>
+#include <comphelper/sequenceashashmap.hxx>
+#include <comphelper/documentconstants.hxx>
+#include <xmloff/attrlist.hxx>
+#include <xmloff/xmltoken.hxx>
+#include <xmloff/xmlement.hxx>
+#include <xmloff/xmluconv.hxx>
+#include <svtools/saveopt.hxx>
+#include <rtl/ustrbuf.hxx>
+#include <connectivity/dbtools.hxx>
+#include <rtl/ustrbuf.hxx>
+
+namespace rptxml
+{
+using namespace ::com::sun::star;
+using namespace ::xmloff::token;
+
+void lcl_exportPrettyPrinting(const uno::Reference< xml::sax::XDocumentHandler >& _xDelegatee)
+{
+ SvtSaveOptions aSaveOpt;
+ if ( aSaveOpt.IsPrettyPrinting() )
+ {
+ static const ::rtl::OUString s_sWhitespaces(RTL_CONSTASCII_USTRINGPARAM(" "));
+ _xDelegatee->ignorableWhitespace(s_sWhitespaces);
+ }
+}
+
+::rtl::OUString lcl_createAttribute(const xmloff::token::XMLTokenEnum& _eNamespace,const xmloff::token::XMLTokenEnum& _eAttribute)
+{
+ ::rtl::OUStringBuffer sQName;
+ // ...if it's in our map, make the prefix
+ sQName.append ( xmloff::token::GetXMLToken(_eNamespace) );
+ sQName.append ( sal_Unicode(':') );
+ sQName.append ( xmloff::token::GetXMLToken(_eAttribute) );
+ return sQName.makeStringAndClear();
+}
+
+void lcl_correctCellAddress(const ::rtl::OUString & _sName, const uno::Reference< xml::sax::XAttributeList > & xAttribs)
+{
+ SvXMLAttributeList* pList = SvXMLAttributeList::getImplementation(xAttribs);
+ ::rtl::OUString sCellAddress = pList->getValueByName(_sName);
+ const sal_Int32 nPos = sCellAddress.lastIndexOf('$');
+ if ( nPos != -1 )
+ {
+ sCellAddress = sCellAddress.copy(0,nPos);
+ sCellAddress += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("$65535"));
+ pList->RemoveAttribute(_sName);
+ pList->AddAttribute(_sName,sCellAddress);
+ }
+}
+
+ExportDocumentHandler::ExportDocumentHandler(uno::Reference< uno::XComponentContext > const & context) :
+ m_xContext(context)
+ ,m_nCurrentCellIndex(0)
+ ,m_bTableRowsStarted(false)
+ ,m_bFirstRowExported(false)
+ ,m_bExportChar(false)
+{
+}
+// -----------------------------------------------------------------------------
+ExportDocumentHandler::~ExportDocumentHandler()
+{
+ if ( m_xProxy.is() )
+ {
+ m_xProxy->setDelegator( NULL );
+ m_xProxy.clear();
+ }
+}
+IMPLEMENT_GET_IMPLEMENTATION_ID(ExportDocumentHandler)
+IMPLEMENT_FORWARD_REFCOUNT( ExportDocumentHandler, ExportDocumentHandler_BASE )
+//------------------------------------------------------------------------
+::rtl::OUString SAL_CALL ExportDocumentHandler::getImplementationName( ) throw(uno::RuntimeException)
+{
+ return getImplementationName_Static();
+}
+
+//------------------------------------------------------------------------
+sal_Bool SAL_CALL ExportDocumentHandler::supportsService( const ::rtl::OUString& ServiceName ) throw(uno::RuntimeException)
+{
+ return ::comphelper::existsValue(ServiceName,getSupportedServiceNames_static());
+}
+
+//------------------------------------------------------------------------
+uno::Sequence< ::rtl::OUString > SAL_CALL ExportDocumentHandler::getSupportedServiceNames( ) throw(uno::RuntimeException)
+{
+ uno::Sequence< ::rtl::OUString > aSupported;
+ if ( m_xServiceInfo.is() )
+ aSupported = m_xServiceInfo->getSupportedServiceNames();
+ return ::comphelper::concatSequences(getSupportedServiceNames_static(),aSupported);
+}
+
+//------------------------------------------------------------------------
+::rtl::OUString ExportDocumentHandler::getImplementationName_Static( ) throw(uno::RuntimeException)
+{
+ return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.report.ExportDocumentHandler"));
+}
+
+//------------------------------------------------------------------------
+uno::Sequence< ::rtl::OUString > ExportDocumentHandler::getSupportedServiceNames_static( ) throw(uno::RuntimeException)
+{
+ uno::Sequence< ::rtl::OUString > aSupported(1);
+ aSupported[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.report.ExportDocumentHandler"));
+ return aSupported;
+}
+
+//------------------------------------------------------------------------
+uno::Reference< uno::XInterface > SAL_CALL ExportDocumentHandler::create( const uno::Reference< uno::XComponentContext >& _rxContext )
+{
+ return *(new ExportDocumentHandler( _rxContext ));
+}
+// xml::sax::XDocumentHandler:
+void SAL_CALL ExportDocumentHandler::startDocument() throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ m_xDelegatee->startDocument();
+}
+
+void SAL_CALL ExportDocumentHandler::endDocument() throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ m_xDelegatee->endDocument();
+}
+
+void SAL_CALL ExportDocumentHandler::startElement(const ::rtl::OUString & _sName, const uno::Reference< xml::sax::XAttributeList > & xAttribs) throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ bool bExport = true;
+ if ( _sName.equalsAscii("office:chart") )
+ {
+ SvXMLAttributeList* pList = new SvXMLAttributeList();
+ uno::Reference< xml::sax::XAttributeList > xNewAttribs = pList;
+ ::rtl::OUStringBuffer sValue;
+ static SvXMLEnumMapEntry aXML_CommnadTypeEnumMap[] =
+ {
+ { XML_TABLE, sdb::CommandType::TABLE },
+ { XML_QUERY, sdb::CommandType::QUERY },
+ // { XML_COMMAND, CommandType::COMMAND }, // default
+ { XML_TOKEN_INVALID, 0 }
+ };
+ if ( SvXMLUnitConverter::convertEnum( sValue, static_cast<sal_uInt16>(m_xDatabaseDataProvider->getCommandType()),aXML_CommnadTypeEnumMap ) )
+ {
+ pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_COMMAND_TYPE),sValue.makeStringAndClear());
+ }
+ const ::rtl::OUString sComamnd = m_xDatabaseDataProvider->getCommand();
+ if ( sComamnd.getLength() )
+ pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_COMMAND),sComamnd);
+
+ const ::rtl::OUString sFilter( m_xDatabaseDataProvider->getFilter() );
+ if ( sFilter.getLength() )
+ pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_FILTER),sFilter);
+
+ const sal_Bool bEscapeProcessing( m_xDatabaseDataProvider->getEscapeProcessing() );
+ if ( !bEscapeProcessing )
+ pList->AddAttribute(lcl_createAttribute(XML_NP_RPT,XML_ESCAPE_PROCESSING),::xmloff::token::GetXMLToken( XML_FALSE ));
+
+ pList->AddAttribute(lcl_createAttribute(XML_NP_OFFICE,XML_MIMETYPE),MIMETYPE_OASIS_OPENDOCUMENT_CHART);
+
+ m_xDelegatee->startElement(lcl_createAttribute(XML_NP_OFFICE,XML_REPORT),xNewAttribs);
+ bExport = false;
+ }
+ else if ( _sName.equalsAscii("table:table") )
+ {
+ m_xDelegatee->startElement(lcl_createAttribute(XML_NP_RPT,XML_DETAIL),NULL);
+ lcl_exportPrettyPrinting(m_xDelegatee);
+ }
+ else if ( _sName.equalsAscii("table:table-rows") )
+ {
+ m_xDelegatee->startElement(_sName,xAttribs);
+ exportTableRows();
+ bExport = false;
+ m_bTableRowsStarted = true;
+ m_bFirstRowExported = true;
+ }
+ else if ( m_bTableRowsStarted && m_bFirstRowExported && (_sName.equalsAscii("table:table-row") || _sName.equalsAscii("table:table-cell")) )
+ bExport = false;
+ else if ( _sName.equalsAscii("chart:plot-area"))
+ {
+ SvXMLAttributeList* pList = SvXMLAttributeList::getImplementation(xAttribs);
+ pList->RemoveAttribute(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("table:cell-range-address")));
+ }
+ else if ( _sName.equalsAscii("chart:categories"))
+ {
+ static ::rtl::OUString s_sCellAddress(lcl_createAttribute(XML_NP_TABLE,XML_CELL_RANGE_ADDRESS));
+ lcl_correctCellAddress(s_sCellAddress,xAttribs);
+ }
+ else if ( _sName.equalsAscii("chart:series"))
+ {
+ static ::rtl::OUString s_sCellAddress(lcl_createAttribute(XML_NP_CHART,XML_VALUES_CELL_RANGE_ADDRESS));
+ lcl_correctCellAddress(s_sCellAddress,xAttribs);
+ }
+ else if ( m_bTableRowsStarted && !m_bFirstRowExported && _sName.equalsAscii("table:table-cell") )
+ {
+ SvXMLAttributeList* pList = SvXMLAttributeList::getImplementation(xAttribs);
+ static ::rtl::OUString s_sValue(lcl_createAttribute(XML_NP_OFFICE,XML_VALUE));
+ pList->RemoveAttribute(s_sValue);
+ }
+ else if ( m_bTableRowsStarted && _sName.equalsAscii("text:p") )
+ {
+ bExport = false;
+ }
+ if ( bExport )
+ m_xDelegatee->startElement(_sName,xAttribs);
+}
+// -----------------------------------------------------------------------------
+void SAL_CALL ExportDocumentHandler::endElement(const ::rtl::OUString & _sName) throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ bool bExport = true;
+ ::rtl::OUString sNewName = _sName;
+ if ( _sName.equalsAscii("office:chart") )
+ {
+ sNewName = lcl_createAttribute(XML_NP_OFFICE,XML_REPORT);
+ }
+ else if ( _sName.equalsAscii("table:table") )
+ {
+ m_xDelegatee->endElement(_sName);
+ lcl_exportPrettyPrinting(m_xDelegatee);
+ sNewName = lcl_createAttribute(XML_NP_RPT,XML_DETAIL);
+ }
+ else if ( _sName.equalsAscii("table:table-rows") )
+ m_bTableRowsStarted = false;
+ else if ( m_bTableRowsStarted && m_bFirstRowExported && (_sName.equalsAscii("table:table-row") || _sName.equalsAscii("table:table-cell")) )
+ bExport = false;
+ else if ( m_bTableRowsStarted && _sName.equalsAscii("table:table-row") )
+ m_bFirstRowExported = true;
+ else if ( m_bTableRowsStarted && _sName.equalsAscii("text:p") )
+ {
+ bExport = !m_bFirstRowExported;
+ }
+
+ if ( bExport )
+ m_xDelegatee->endElement(sNewName);
+}
+
+void SAL_CALL ExportDocumentHandler::characters(const ::rtl::OUString & aChars) throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ if ( !(m_bTableRowsStarted || m_bFirstRowExported) )
+ m_xDelegatee->characters(aChars);
+ else if ( m_bExportChar )
+ {
+ static const ::rtl::OUString s_sZero(RTL_CONSTASCII_USTRINGPARAM("0"));
+ m_xDelegatee->characters(s_sZero);
+ }
+}
+
+void SAL_CALL ExportDocumentHandler::ignorableWhitespace(const ::rtl::OUString & aWhitespaces) throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ m_xDelegatee->ignorableWhitespace(aWhitespaces);
+}
+
+void SAL_CALL ExportDocumentHandler::processingInstruction(const ::rtl::OUString & aTarget, const ::rtl::OUString & aData) throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ m_xDelegatee->processingInstruction(aTarget,aData);
+}
+
+void SAL_CALL ExportDocumentHandler::setDocumentLocator(const uno::Reference< xml::sax::XLocator > & xLocator) throw (uno::RuntimeException, xml::sax::SAXException)
+{
+ m_xDelegatee->setDocumentLocator(xLocator);
+}
+void SAL_CALL ExportDocumentHandler::initialize( const uno::Sequence< uno::Any >& _aArguments ) throw (uno::Exception, uno::RuntimeException)
+{
+ ::osl::MutexGuard aGuard(m_aMutex);
+ comphelper::SequenceAsHashMap aArgs(_aArguments);
+ m_xDelegatee = aArgs.getUnpackedValueOrDefault(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DocumentHandler")),m_xDelegatee);
+ m_xModel = aArgs.getUnpackedValueOrDefault(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Model")),m_xModel);
+
+ OSL_ENSURE(m_xDelegatee.is(),"No document handler avialable!");
+ if ( !m_xDelegatee.is() || !m_xModel.is() )
+ throw uno::Exception();
+
+ m_xDatabaseDataProvider.set(m_xModel->getDataProvider(),uno::UNO_QUERY);
+ if ( !m_xDatabaseDataProvider.is() )
+ throw uno::Exception();
+
+ uno::Reference< reflection::XProxyFactory > xProxyFactory( m_xContext->getServiceManager()->createInstanceWithContext(
+ ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.reflection.ProxyFactory")),m_xContext),
+ uno::UNO_QUERY);
+ m_xProxy = xProxyFactory->createProxy(m_xDelegatee.get());
+ ::comphelper::query_aggregation(m_xProxy,m_xDelegatee);
+ m_xTypeProvider.set(m_xDelegatee,uno::UNO_QUERY);
+ m_xServiceInfo.set(m_xDelegatee,uno::UNO_QUERY);
+
+ // set ourself as delegator
+ m_xProxy->setDelegator( *this );
+
+ const ::rtl::OUString sCommand = m_xDatabaseDataProvider->getCommand();
+ if ( sCommand.getLength() )
+ m_aColumns = ::dbtools::getFieldNamesByCommandDescriptor(m_xDatabaseDataProvider->getActiveConnection()
+ ,m_xDatabaseDataProvider->getCommandType()
+ ,sCommand);
+}
+// --------------------------------------------------------------------------------
+uno::Any SAL_CALL ExportDocumentHandler::queryInterface( const uno::Type& _rType ) throw (uno::RuntimeException)
+{
+ uno::Any aReturn = ExportDocumentHandler_BASE::queryInterface(_rType);
+ return aReturn.hasValue() ? aReturn : (m_xProxy.is() ? m_xProxy->queryAggregation(_rType) : aReturn);
+}
+// --------------------------------------------------------------------------------
+uno::Sequence< uno::Type > SAL_CALL ExportDocumentHandler::getTypes( ) throw (uno::RuntimeException)
+{
+ if ( m_xTypeProvider.is() )
+ return ::comphelper::concatSequences(
+ ExportDocumentHandler_BASE::getTypes(),
+ m_xTypeProvider->getTypes()
+ );
+ return ExportDocumentHandler_BASE::getTypes();
+}
+// -----------------------------------------------------------------------------
+void ExportDocumentHandler::exportTableRows()
+{
+ const ::rtl::OUString sRow( lcl_createAttribute(XML_NP_TABLE, XML_TABLE_ROW) );
+ m_xDelegatee->startElement(sRow,NULL);
+
+ const ::rtl::OUString sValueType( lcl_createAttribute(XML_NP_OFFICE, XML_VALUE_TYPE) );
+
+ const static ::rtl::OUString s_sFieldPrefix(RTL_CONSTASCII_USTRINGPARAM("field:["));
+ const static ::rtl::OUString s_sFieldPostfix(RTL_CONSTASCII_USTRINGPARAM("]"));
+ const ::rtl::OUString sCell( lcl_createAttribute(XML_NP_TABLE, XML_TABLE_CELL) );
+ const ::rtl::OUString sP( lcl_createAttribute(XML_NP_TEXT, XML_P) );
+ const ::rtl::OUString sFtext(lcl_createAttribute(XML_NP_RPT,XML_FORMATTED_TEXT) );
+ const ::rtl::OUString sRElement(lcl_createAttribute(XML_NP_RPT,XML_REPORT_ELEMENT) );
+ const ::rtl::OUString sRComponent( lcl_createAttribute(XML_NP_RPT,XML_REPORT_COMPONENT) ) ;
+ const ::rtl::OUString sFormulaAttrib( lcl_createAttribute(XML_NP_RPT,XML_FORMULA) );
+ const static ::rtl::OUString s_sString(RTL_CONSTASCII_USTRINGPARAM("string"));
+ const static ::rtl::OUString s_sFloat(RTL_CONSTASCII_USTRINGPARAM("float"));
+
+ SvXMLAttributeList* pCellAtt = new SvXMLAttributeList();
+ uno::Reference< xml::sax::XAttributeList > xCellAtt = pCellAtt;
+ pCellAtt->AddAttribute(sValueType,s_sString);
+
+ ::rtl::OUString sFormula;
+ const sal_Int32 nCount = m_aColumns.getLength();
+ for(sal_Int32 i = 0; i < nCount ; ++i)
+ {
+ sFormula = s_sFieldPrefix;
+ sFormula += m_aColumns[i];
+ sFormula += s_sFieldPostfix;
+ SvXMLAttributeList* pList = new SvXMLAttributeList();
+ uno::Reference< xml::sax::XAttributeList > xAttribs = pList;
+ pList->AddAttribute(sFormulaAttrib,sFormula);
+
+ m_xDelegatee->startElement(sCell,xCellAtt);
+ if ( i == 0 )
+ {
+ pCellAtt->RemoveAttribute(sValueType);
+ pCellAtt->AddAttribute(sValueType,s_sFloat);
+ }
+ m_xDelegatee->startElement(sP,NULL);
+ m_xDelegatee->startElement(sFtext,xAttribs);
+ m_xDelegatee->startElement(sRElement,NULL);
+ m_xDelegatee->startElement(sRComponent,NULL);
+
+ m_xDelegatee->endElement(sRComponent);
+ m_xDelegatee->endElement(sRElement);
+ m_xDelegatee->endElement(sFtext);
+ m_xDelegatee->endElement(sP);
+ m_xDelegatee->endElement(sCell);
+ } // for(sal_Int32 i = 0; i < nCount ; ++i)
+
+ m_xDelegatee->endElement(sRow);
+}
+// -----------------------------------------------------------------------------
+} // namespace rptxml
+// -----------------------------------------------------------------------------
diff --git a/reportdesign/source/filter/xml/xmlExportDocumentHandler.hxx b/reportdesign/source/filter/xml/xmlExportDocumentHandler.hxx index cfb78c62df461..be97bdc030f7b 100644 --- a/reportdesign/source/filter/xml/xmlExportDocumentHandler.hxx +++ b/reportdesign/source/filter/xml/xmlExportDocumentHandler.hxx @@ -1,105 +1,106 @@ -/************************************************************************* - * - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * Copyright 2008 by Sun Microsystems, Inc. - * - * OpenOffice.org - a multi-platform office productivity suite - * - * $RCSfile: xmlExportDocumentHandler.hxx,v $ - * $Revision: 1.4 $ - * - * This file is part of OpenOffice.org. - * - * OpenOffice.org is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 3 - * only, as published by the Free Software Foundation. - * - * OpenOffice.org is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License version 3 for more details - * (a copy is included in the LICENSE file that accompanied this code). - * - * You should have received a copy of the GNU Lesser General Public License - * version 3 along with OpenOffice.org. If not, see - * <http://www.openoffice.org/license.html> - * for a copy of the LGPLv3 License. - * - ************************************************************************/ -#ifndef RPT_EXPORTDOCUMENTHANDLER_HXX_INCLUDED -#define RPT_EXPORTDOCUMENTHANDLER_HXX_INCLUDED - -#include "sal/config.h" -#include "com/sun/star/uno/XComponentContext.hpp" -#include <cppuhelper/implbase3.hxx> -#include "com/sun/star/xml/sax/XDocumentHandler.hpp" -#include <com/sun/star/lang/XInitialization.hpp> -#include <com/sun/star/lang/XServiceInfo.hpp> -#include <com/sun/star/lang/XTypeProvider.hpp> -#include <com/sun/star/chart2/XChartDocument.hpp> -#include "com/sun/star/chart2/data/XDatabaseDataProvider.hpp" -#include <comphelper/uno3.hxx> - -namespace rptxml -{ -typedef ::cppu::WeakAggImplHelper3< ::com::sun::star::xml::sax::XDocumentHandler - , ::com::sun::star::lang::XInitialization - , ::com::sun::star::lang::XServiceInfo> ExportDocumentHandler_BASE; - -class ExportDocumentHandler : public ExportDocumentHandler_BASE -{ -public: - // XServiceInfo - static versions - static ::rtl::OUString getImplementationName_Static( ) throw(::com::sun::star::uno::RuntimeException); - static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_static( ) throw(::com::sun::star::uno::RuntimeException); - static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL - create(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >&); -public: - explicit ExportDocumentHandler(::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & context); - -private: - // XServiceInfo - virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); - virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); - virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException); - - DECLARE_XINTERFACE( ) - DECLARE_XTYPEPROVIDER( ) - - // ::com::sun::star::xml::sax::XDocumentHandler: - virtual void SAL_CALL startDocument() throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - virtual void SAL_CALL endDocument() throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - virtual void SAL_CALL startElement(const ::rtl::OUString & aName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttribs) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - virtual void SAL_CALL endElement(const ::rtl::OUString & aName) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - virtual void SAL_CALL characters(const ::rtl::OUString & aChars) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - virtual void SAL_CALL ignorableWhitespace(const ::rtl::OUString & aWhitespaces) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - virtual void SAL_CALL processingInstruction(const ::rtl::OUString & aTarget, const ::rtl::OUString & aData) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - virtual void SAL_CALL setDocumentLocator(const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > & xLocator) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException); - - virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); - -private: - ExportDocumentHandler(ExportDocumentHandler &); // not defined - void operator =(ExportDocumentHandler &); // not defined - - virtual ~ExportDocumentHandler(); - - ::osl::Mutex m_aMutex; - ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext; - ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > m_xDelegatee; - ::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation > m_xProxy; - ::com::sun::star::uno::Reference< ::com::sun::star::lang::XTypeProvider > m_xTypeProvider; - ::com::sun::star::uno::Reference< ::com::sun::star::lang::XServiceInfo > m_xServiceInfo; - ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartDocument > m_xModel; - ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDatabaseDataProvider > m_xDatabaseDataProvider; - ::com::sun::star::uno::Sequence< ::rtl::OUString > m_aColumns; - sal_Int32 m_nCurrentCellIndex; - bool m_bTableRowsStarted; - bool m_bFirstRowExported; - bool m_bExportChar; -}; -// ----------------------------------------------------------------------------- -} // namespace rptxml -// ----------------------------------------------------------------------------- -#endif // RPT_EXPORTDOCUMENTHANDLER_HXX_INCLUDED +/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: xmlExportDocumentHandler.hxx,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+#ifndef RPT_EXPORTDOCUMENTHANDLER_HXX_INCLUDED
+#define RPT_EXPORTDOCUMENTHANDLER_HXX_INCLUDED
+
+#include "sal/config.h"
+#include "com/sun/star/uno/XComponentContext.hpp"
+#include <cppuhelper/implbase3.hxx>
+#include "com/sun/star/xml/sax/XDocumentHandler.hpp"
+#include <com/sun/star/lang/XInitialization.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/lang/XTypeProvider.hpp>
+#include <com/sun/star/chart2/XChartDocument.hpp>
+#include "com/sun/star/chart2/data/XDatabaseDataProvider.hpp"
+#include <comphelper/uno3.hxx>
+
+namespace rptxml
+{
+typedef ::cppu::WeakAggImplHelper3< ::com::sun::star::xml::sax::XDocumentHandler
+ , ::com::sun::star::lang::XInitialization
+ , ::com::sun::star::lang::XServiceInfo> ExportDocumentHandler_BASE;
+
+class ExportDocumentHandler : public ExportDocumentHandler_BASE
+{
+public:
+ // XServiceInfo - static versions
+ static ::rtl::OUString getImplementationName_Static( ) throw(::com::sun::star::uno::RuntimeException);
+ static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_static( ) throw(::com::sun::star::uno::RuntimeException);
+ static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
+ create(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >&);
+public:
+ explicit ExportDocumentHandler(::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & context);
+
+private:
+ // XServiceInfo
+ virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException);
+
+ DECLARE_XINTERFACE( )
+ DECLARE_XTYPEPROVIDER( )
+
+ // ::com::sun::star::xml::sax::XDocumentHandler:
+ virtual void SAL_CALL startDocument() throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+ virtual void SAL_CALL endDocument() throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+ virtual void SAL_CALL startElement(const ::rtl::OUString & aName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttribs) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+ virtual void SAL_CALL endElement(const ::rtl::OUString & aName) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+ virtual void SAL_CALL characters(const ::rtl::OUString & aChars) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+ virtual void SAL_CALL ignorableWhitespace(const ::rtl::OUString & aWhitespaces) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+ virtual void SAL_CALL processingInstruction(const ::rtl::OUString & aTarget, const ::rtl::OUString & aData) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+ virtual void SAL_CALL setDocumentLocator(const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > & xLocator) throw (::com::sun::star::uno::RuntimeException, ::com::sun::star::xml::sax::SAXException);
+
+ virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+
+ void exportTableRows();
+private:
+ ExportDocumentHandler(ExportDocumentHandler &); // not defined
+ void operator =(ExportDocumentHandler &); // not defined
+
+ virtual ~ExportDocumentHandler();
+
+ ::osl::Mutex m_aMutex;
+ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;
+ ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > m_xDelegatee;
+ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation > m_xProxy;
+ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XTypeProvider > m_xTypeProvider;
+ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XServiceInfo > m_xServiceInfo;
+ ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartDocument > m_xModel;
+ ::com::sun::star::uno::Reference< ::com::sun::star::chart2::data::XDatabaseDataProvider > m_xDatabaseDataProvider;
+ ::com::sun::star::uno::Sequence< ::rtl::OUString > m_aColumns;
+ sal_Int32 m_nCurrentCellIndex;
+ bool m_bTableRowsStarted;
+ bool m_bFirstRowExported;
+ bool m_bExportChar;
+};
+// -----------------------------------------------------------------------------
+} // namespace rptxml
+// -----------------------------------------------------------------------------
+#endif // RPT_EXPORTDOCUMENTHANDLER_HXX_INCLUDED
diff --git a/reportdesign/source/filter/xml/xmlSubDocument.cxx b/reportdesign/source/filter/xml/xmlSubDocument.cxx index b561499728bc4..4ad6b9a2ec286 100644 --- a/reportdesign/source/filter/xml/xmlSubDocument.cxx +++ b/reportdesign/source/filter/xml/xmlSubDocument.cxx @@ -29,6 +29,7 @@ ************************************************************************/ #include "precompiled_reportdesign.hxx" #include "xmlSubDocument.hxx" +#include "xmlCell.hxx" #include "xmlfilter.hxx" #include <xmloff/xmltoken.hxx> #include <xmloff/xmlnmspe.hxx> @@ -52,9 +53,11 @@ OXMLSubDocument::OXMLSubDocument( ORptFilter& rImport, sal_uInt16 nPrfx ,const ::rtl::OUString& rLName ,const Reference< XReportComponent > & _xComponent - ,OXMLTable* _pContainer) : + ,OXMLTable* _pContainer + ,OXMLCell* _pCellParent) : OXMLReportElementBase( rImport, nPrfx, rLName,_xComponent.get(),_pContainer) ,m_xFake(_xComponent) +,m_pCellParent(_pCellParent) ,m_nCurrentCount(0) ,m_bContainsShape(false) { @@ -95,6 +98,11 @@ SvXMLImportContext* OXMLSubDocument::_CreateChildContext( uno::Reference< drawing::XShapes > xShapes = m_pContainer->getSection().get(); pContext = xShapeImportHelper->CreateGroupChildContext(GetImport(),_nPrefix,_rLocalName,xAttrList,xShapes); m_bContainsShape = true; + if (m_pCellParent) + { + // #i94115 say to the parent Cell it contains shapes + m_pCellParent->setContainsShape(true); + } } break; default: @@ -114,7 +122,8 @@ void OXMLSubDocument::EndElement() m_xComponent.set(m_pContainer->getSection()->getByIndex(m_nCurrentCount),uno::UNO_QUERY); if ( m_xComponent.is() ) { - m_pContainer->addCell(m_xComponent.get()); + // #i94115# this is no longer need. + // m_pContainer->addCell(m_xComponent.get()); if ( !m_aMasterFields.empty() ) m_xComponent->setMasterFields(Sequence< ::rtl::OUString>(&*m_aMasterFields.begin(),m_aMasterFields.size())); diff --git a/reportdesign/source/filter/xml/xmlSubDocument.hxx b/reportdesign/source/filter/xml/xmlSubDocument.hxx index 4f91d13e41a50..5d0bc900b1469 100644 --- a/reportdesign/source/filter/xml/xmlSubDocument.hxx +++ b/reportdesign/source/filter/xml/xmlSubDocument.hxx @@ -37,12 +37,14 @@ namespace rptxml { class ORptFilter; + class OXMLCell; class OXMLSubDocument : public OXMLReportElementBase, public IMasterDetailFieds { ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> m_xComponent; ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> m_xFake; ::std::vector< ::rtl::OUString> m_aMasterFields; ::std::vector< ::rtl::OUString> m_aDetailFields; + OXMLCell* m_pCellParent; sal_Int32 m_nCurrentCount; bool m_bContainsShape; @@ -58,7 +60,8 @@ namespace rptxml ,sal_uInt16 nPrfx ,const ::rtl::OUString& rLName ,const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent >& _xComponent - ,OXMLTable* _pContainer); + ,OXMLTable* _pContainer + ,OXMLCell* _pCellParent); virtual ~OXMLSubDocument(); virtual void EndElement(); diff --git a/reportdesign/source/ui/report/DesignView.cxx b/reportdesign/source/ui/report/DesignView.cxx index b7dedea9f2e4a..933e7766fa404 100644 --- a/reportdesign/source/ui/report/DesignView.cxx +++ b/reportdesign/source/ui/report/DesignView.cxx @@ -34,6 +34,7 @@ #include "ReportController.hxx" #include <comphelper/types.hxx> #include <svtools/syslocale.hxx> +#include <svtools/viewoptions.hxx> #include "RptDef.hxx" #include "UITools.hxx" #include "RptObject.hxx" @@ -48,6 +49,7 @@ #include "ScrollHelper.hxx" #include "Navigator.hxx" #include "SectionWindow.hxx" +#include "RptResId.hrc" #include <vcl/svapp.hxx> namespace rptui @@ -204,12 +206,16 @@ ODesignView::~ODesignView() } if ( m_pAddField ) { + SvtViewOptions aDlgOpt( E_WINDOW, String::CreateFromInt32( UID_RPT_RPT_APP_VIEW ) );
+ aDlgOpt.SetWindowState( ::rtl::OUString::createFromAscii( m_pAddField->GetWindowState((WINDOWSTATE_MASK_X | WINDOWSTATE_MASK_Y | WINDOWSTATE_MASK_STATE | WINDOWSTATE_MASK_MINIMIZED)).GetBuffer() ) );
notifySystemWindow(this,m_pAddField,::comphelper::mem_fun(&TaskPaneList::RemoveWindow)); ::std::auto_ptr<Window> aTemp2(m_pAddField); m_pAddField = NULL; } if ( m_pReportExplorer ) { + SvtViewOptions aDlgOpt( E_WINDOW, String::CreateFromInt32( RID_NAVIGATOR ) );
+ aDlgOpt.SetWindowState( ::rtl::OUString::createFromAscii( m_pReportExplorer->GetWindowState((WINDOWSTATE_MASK_X | WINDOWSTATE_MASK_Y | WINDOWSTATE_MASK_STATE | WINDOWSTATE_MASK_MINIMIZED)).GetBuffer() ) ); notifySystemWindow(this,m_pReportExplorer,::comphelper::mem_fun(&TaskPaneList::RemoveWindow)); ::std::auto_ptr<Window> aTemp2(m_pReportExplorer); m_pReportExplorer = NULL; @@ -560,6 +566,9 @@ void ODesignView::toggleReportExplorer() { OReportController& rReportController = getController(); m_pReportExplorer = new ONavigator(this,rReportController); + SvtViewOptions aDlgOpt( E_WINDOW, String::CreateFromInt32( RID_NAVIGATOR ) ); + if ( aDlgOpt.Exists() )
+ m_pReportExplorer->SetWindowState( ByteString( aDlgOpt.GetWindowState().getStr(), RTL_TEXTENCODING_ASCII_US ) ); m_pReportExplorer->AddEventListener(LINK(&rReportController,OReportController,EventLstHdl)); notifySystemWindow(this,m_pReportExplorer,::comphelper::mem_fun(&TaskPaneList::AddWindow)); } @@ -592,6 +601,9 @@ void ODesignView::toggleAddField() xReport = xSection->getReportDefinition(); } m_pAddField = new OAddFieldWindow(rReportController,this); + SvtViewOptions aDlgOpt( E_WINDOW, String::CreateFromInt32( UID_RPT_RPT_APP_VIEW ) );
+ if ( aDlgOpt.Exists() )
+ m_pAddField->SetWindowState( ByteString( aDlgOpt.GetWindowState().getStr(), RTL_TEXTENCODING_ASCII_US ) );
m_pAddField->Update(); m_pAddField->AddEventListener(LINK(&rReportController,OReportController,EventLstHdl)); notifySystemWindow(this,m_pAddField,::comphelper::mem_fun(&TaskPaneList::AddWindow)); diff --git a/reportdesign/source/ui/report/ReportController.cxx b/reportdesign/source/ui/report/ReportController.cxx index 2bb3d3d5dbc8a..0cfad2e263418 100644 --- a/reportdesign/source/ui/report/ReportController.cxx +++ b/reportdesign/source/ui/report/ReportController.cxx @@ -2952,7 +2952,6 @@ void OReportController::createControl(const Sequence< PropertyValue >& _aArgs,co ,NULL,NULL,_nObjectId,::rtl::OUString(),ReportInventor,OBJ_DLG_FIXEDTEXT, NULL,pSectionWindow->getReportSection().getPage(),m_aReportModel.get(), pLabel,pControl); - delete pLabel; pNewControl = pControl; @@ -2975,7 +2974,11 @@ void OReportController::createControl(const Sequence< PropertyValue >& _aArgs,co { if ( xInfo->hasPropertyByName(sProps[i]) && xShapeInfo->hasPropertyByName(sProps[i]) ) xUnoProp->setPropertyValue(sProps[i],xShapeProp->getPropertyValue(sProps[i])); - } + } // for(size_t i = 0; i < sizeof(sProps)/sizeof(sProps[0]);++i) + + if ( xInfo->hasPropertyByName(PROPERTY_BORDER) && xShapeInfo->hasPropertyByName(PROPERTY_CONTROLBORDER) ) + xUnoProp->setPropertyValue(PROPERTY_BORDER,xShapeProp->getPropertyValue(PROPERTY_CONTROLBORDER)); + if ( xInfo->hasPropertyByName(PROPERTY_DATAFIELD) && _sFunction.getLength() ) { @@ -3279,7 +3282,10 @@ void OReportController::addPairControls(const Sequence< PropertyValue >& aArgs) ReportFormula aFormula( ReportFormula::Field, sName ); xUnoProp->setPropertyValue( PROPERTY_DATAFIELD, uno::makeAny( aFormula.getCompleteFormula() ) ); - } + } // if ( xInfo->hasPropertyByName(PROPERTY_DATAFIELD) ) + + if ( xInfo->hasPropertyByName(PROPERTY_BORDER) && xShapeInfo->hasPropertyByName(PROPERTY_CONTROLBORDER) ) + xUnoProp->setPropertyValue(PROPERTY_BORDER,xShapeProp->getPropertyValue(PROPERTY_CONTROLBORDER)); pObjs[i]->CreateMediator(sal_True); // need SectionView from the above or follow Section diff --git a/reportdesign/source/ui/report/ReportSection.cxx b/reportdesign/source/ui/report/ReportSection.cxx index cf462c8b14564..570574e4c51d0 100644 --- a/reportdesign/source/ui/report/ReportSection.cxx +++ b/reportdesign/source/ui/report/ReportSection.cxx @@ -50,6 +50,7 @@ #include <svx/svditer.hxx> #include <svx/dbaexchange.hxx> +#include <vcl/svapp.hxx> #include <com/sun/star/datatransfer/clipboard/XClipboard.hpp> #include <toolkit/helper/convert.hxx> @@ -69,6 +70,7 @@ #include <svtools/itempool.hxx> #include <svtools/extcolorcfg.hxx> #include <unotools/confignode.hxx> +#include <framework/imageproducer.hxx> // ============================================================================= namespace rptui @@ -460,6 +462,39 @@ void OReportSection::SelectAll(const sal_uInt16 _nObjectType) } } } +void lcl_insertMenuItemImages(PopupMenu& rContextMenu,OReportController& rController,const uno::Reference< report::XReportDefinition>& _xReportDefinition,uno::Reference<frame::XFrame>& _rFrame,BOOL _bHiContrast) +{ + const USHORT nCount = rContextMenu.GetItemCount(); + for (USHORT i = 0; i < nCount; ++i) + { + if ( MENUITEM_SEPARATOR != rContextMenu.GetItemType(i)) + { + const USHORT nId = rContextMenu.GetItemId(i); + PopupMenu* pPopupMenu = rContextMenu.GetPopupMenu( nId ); + if ( pPopupMenu ) + { + lcl_insertMenuItemImages(*pPopupMenu,rController,_xReportDefinition,_rFrame,_bHiContrast); + } + else + { + const ::rtl::OUString sCommand = rContextMenu.GetItemCommand(nId); + rContextMenu.SetItemImage(nId,framework::GetImageFromURL(_rFrame,sCommand,FALSE,_bHiContrast)); + if ( nId == SID_PAGEHEADERFOOTER ) + { + String sText = String(ModuleRes((_xReportDefinition.is() && _xReportDefinition->getPageHeaderOn()) ? RID_STR_PAGEHEADERFOOTER_DELETE : RID_STR_PAGEHEADERFOOTER_INSERT)); + rContextMenu.SetItemText(nId,sText); + } + else if ( nId == SID_REPORTHEADERFOOTER ) + { + String sText = String(ModuleRes((_xReportDefinition.is() && _xReportDefinition->getReportHeaderOn()) ? RID_STR_REPORTHEADERFOOTER_DELETE : RID_STR_REPORTHEADERFOOTER_INSERT)); + rContextMenu.SetItemText(nId,sText); + } + } + rContextMenu.CheckItem(nId,rController.isCommandChecked(nId)); + rContextMenu.EnableItem(nId,rController.isCommandEnabled(nId)); + } + } // for (USHORT i = 0; i < nCount; ++i) +} //---------------------------------------------------------------------------- void OReportSection::Command( const CommandEvent& _rCEvt ) { @@ -468,29 +503,15 @@ void OReportSection::Command( const CommandEvent& _rCEvt ) { case COMMAND_CONTEXTMENU: { + const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings(); + BOOL bHiContrast = rSettings.GetMenuColor().IsDark(); OReportController& rController = m_pParent->getViewsWindow()->getView()->getReportView()->getController(); + uno::Reference<frame::XFrame> xFrame = rController.getFrame(); PopupMenu aContextMenu( ModuleRes( RID_MENU_REPORT ) ); uno::Reference< report::XReportDefinition> xReportDefinition = getSection()->getReportDefinition(); - const USHORT nCount = aContextMenu.GetItemCount(); - for (USHORT i = 0; i < nCount; ++i) - { - if ( MENUITEM_SEPARATOR != aContextMenu.GetItemType(i)) - { - const USHORT nId = aContextMenu.GetItemId(i); - if ( nId == SID_PAGEHEADERFOOTER ) - { - String sText = String(ModuleRes((xReportDefinition.is() && xReportDefinition->getPageHeaderOn()) ? RID_STR_PAGEHEADERFOOTER_DELETE : RID_STR_PAGEHEADERFOOTER_INSERT)); - aContextMenu.SetItemText(nId,sText); - } - else if ( nId == SID_REPORTHEADERFOOTER ) - { - String sText = String(ModuleRes((xReportDefinition.is() && xReportDefinition->getReportHeaderOn()) ? RID_STR_REPORTHEADERFOOTER_DELETE : RID_STR_REPORTHEADERFOOTER_INSERT)); - aContextMenu.SetItemText(nId,sText); - } - aContextMenu.CheckItem(nId,rController.isCommandChecked(nId)); - aContextMenu.EnableItem(nId,rController.isCommandEnabled(nId)); - } - } // for (USHORT i = 0; i < nCount; ++i) + + lcl_insertMenuItemImages(aContextMenu,rController,xReportDefinition,xFrame,bHiContrast); + Point aPos = _rCEvt.GetMousePosPixel(); m_pView->EndAction(); const USHORT nId = aContextMenu.Execute(this, aPos); diff --git a/reportdesign/util/makefile.mk b/reportdesign/util/makefile.mk index 293fb86918736..10f0836710e66 100644 --- a/reportdesign/util/makefile.mk +++ b/reportdesign/util/makefile.mk @@ -131,6 +131,7 @@ SHL2STDLIBS= \ $(COMPHELPERLIB) \ $(CPPUHELPERLIB) \ $(CPPULIB) \ + $(FWELIB) \ $(SO2LIB) \ $(I18NISOLANGLIB) \ $(SALLIB) |