Difference between revisions of "Writer/Smart Tags"

From Apache OpenOffice Wiki
Jump to: navigation, search
(Change to update source editor version)
(47 intermediate revisions by 7 users not shown)
Line 1: Line 1:
 +
{{Documentation/Candidate}}
 +
{{Writer Project|Category=Writer/API}}
 +
 
=Introduction=
 
=Introduction=
  
Smart Tags were introduced in Microsoft Office XP and allow to recognize words that have a special meaning to the user and furthermore allow to execute certain actions for a recognized word. Experimental support for smart tags is included in the OpenOffice.org 2.2 release, thanks to a code contribution by [http://www.fabalabs.org Fabalabs Software GmbH]. In order to use this functionality, external UNO components (so-called smart tag libraries) have to be installed. This document explains how to write own smart tag libraries and how to integrate them into your installation of OpenOffice.org. The necessary interfaces for smart tag libraries currently have the status "unpublished" because they are still work in progress. So be aware that you may have to modify the code of your components if you want to use them with the next release of OpenOffice.org. Smart tag extensions (aka packages) must set the version dependency to 2.2.
+
Smart tags have been introduced with MS Office XP to add contextual information to Office documents. The OpenOffice.org smart tag project has been initiated by Jakob Lechner/[http://www.fabalabs.org Fabalabs Software GmbH]. OpenOffice.org 2.2 included a first draft of the new smart tag API, for OpenOffice.org 2.3 this API has been enhanced significantly. In order to use this functionality, external UNO components (so-called smart tag libraries) have to be installed. This document explains how to write your own smart tag libraries and how to integrate them into your installation of OpenOffice.org. The necessary interfaces for smart tag libraries currently have the status "unpublished" but will most likely be published in the next version of OpenOffice.org.
  
=Basic functionality of Smart Tags=
+
=Basic Functionality of Smart Tags=
  
 
Basically smart tags UNO components consist of two parts:
 
Basically smart tags UNO components consist of two parts:
  
* A recognizer
+
* A recognizer component
* An action library.
+
* An action component
  
If a recognizer component is installed in OpenOffice.org its recognize() method will be invoked by OpenOffice.org Writer for every word found in the opened document. The recognize method then decides if the word has some specific meaning and returns true or false. Recognized words will be underlined violet in OpenOffice.org Writer. If the control key is pressed and the mouse is moved over a underlined word the mouse cursor changes to a hand. When you click on the word with the left mouse button (still holding the control key) a context menu is opened. This is where action libraries come into play. An action library provides actions for recognized words. The captions of available actions are displayed in the context menu. When you click on one entry in the context menu the invokeAction() method of the action library component is called. This method subsequently executes the appropriate action (a simple action might be opening some URL in the browser).
+
If a recognizer component is installed in OpenOffice.org its recognize() method will be invoked by OpenOffice.org Writer for every paragraph found in the opened document. The recognize method then decides if any of the words has some specific meaning. Recognized words will be underlined violet in OpenOffice.org Writer. Ctrl-click on a recognized smart tag opens the smart tag menu. This is where action libraries come into play. An action library provides actions for recognized words. The captions of available actions are displayed in the smart tag menu. When you click on one entry in the context menu the invokeAction() method of the action library component is called. This method subsequently executes the appropriate action (a simple action might be opening some URL in the browser).
  
 
Here is a sceenshot of an example smart tag component which recognizes document property keywords like author, subject, title etc. There is only one action defined. This action inserts the value of the recognized document property into the text document.
 
Here is a sceenshot of an example smart tag component which recognizes document property keywords like author, subject, title etc. There is only one action defined. This action inserts the value of the recognized document property into the text document.
  
 
[[Image:stag_screenshot1.gif]]
 
[[Image:stag_screenshot1.gif]]
 +
  
 
=The Services=
 
=The Services=
Line 25: Line 29:
 
The SmartTagRecognizer service exports the interface XSmartTagRecognizer. Accordingly the service SmartTagAction
 
The SmartTagRecognizer service exports the interface XSmartTagRecognizer. Accordingly the service SmartTagAction
 
exports the interface XSmartTagAction.
 
exports the interface XSmartTagAction.
 +
  
 
=The Interfaces=
 
=The Interfaces=
Line 34: Line 39:
 
==The Recognizer Interface==
 
==The Recognizer Interface==
  
For a look at the recognizer interface definition go to this [http://go-ooo.org/lxr/source/api/offapi/com/sun/star/smarttags/XSmartTagRecognizer.idl page].
+
For a look at the recognizer interface definition go to this [http://svn.services.openoffice.org/opengrok/xref/Current%20%28trunk%29/offapi/com/sun/star/smarttags/XSmartTagRecognizer.idl page].
 
+
This interface is comprised of 7 methods which have to be implemented by a recognizer component.
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | string getName()
+
|-
+
| rowspan="1" style="width:15%" | '''Arguments'''
+
| None.
+
|-
+
| '''Return Value'''
+
| Retuns the name of the Regonizer component.
+
|}
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | string getDescription()
+
|-
+
| rowspan="1" style="width:15%" | '''Arguments'''
+
| None.
+
|-
+
| '''Return Value'''
+
| Returns a textual description of the recognizer component.
+
|}
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | long getSmartTagCount()
+
|-
+
| rowspan="1" style="width:15%" | '''Arguments'''
+
| None.
+
|-
+
| '''Return Value'''
+
| The return value indicates how many smart tags are included in the recognizer component.
+
|}
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | string getSmartTagName()
+
|-
+
| rowspan="1" style="width:15%" | '''Arguments'''
+
| sal_Int32 '''nSmartTagIndex''': Index of the wanted smart tag. Value needs to be between 0 and the number of smart tags available (exclusively).
+
|-
+
| '''Return Value'''
+
| Returns the name of one specific smart tag in this recognizer. This name is needed to associate the recognizer part of a smart tag with the action part. Thus there mustn't be two recognizer components installed that include a recognizer withthe same name.
+
|}
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | string getSmartTagCaption()
+
|-
+
| rowspan="2" style="width:15%" | '''Arguments'''
+
| sal_Int32 '''nSmartTagIndex''': Index of the wanted smart tag. Value needs to be between 0 and the number of smart tags available (exclusively).
+
|-
+
| XController '''xController''': The reference to the controller of the current document.
+
|-
+
| '''Return Value'''
+
| Returns the caption of one specific smart tag in this recognizer. The caption will be display by OpenOffice.org Writer in the context menu.
+
|}
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | boolean Recognize()
+
|-
+
| rowspan="3" style="width:15%" | '''Arguments'''
+
| OUString '''aWord''': Word that shall be checked by smarttag.
+
|-
+
| sal_Int32 '''nSmartTagIndex''': Index of the wanted smart tag. Value needs to be between 0 and the number of smart tags available (exclusively).
+
|-
+
| XController '''xController''': The reference to the controller of the current document.
+
|-
+
| '''Return Value'''
+
| Returns true if the passed word has a special meaning to the smart tag. Otherwise false is returned.
+
|}
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | void initialize()
+
|-
+
| rowspan="1" style="width:15%" | '''Description'''
+
| This method is used for initializing the recognizer component and is currently needed by Writer to use xml based smart tags (see example below). For your own smart tag components you can implement this method with an empty body.
+
|-
+
| rowspan="1" style="width:15%" | '''Arguments'''
+
| sequence<any> '''aArguments''': Initialization arguments
+
|-
+
| '''Return Value'''
+
| None.
+
|}
+
 
+
 
+
==The Action Library Interface==
+
 
+
For a look at the action library interface definition go to this [http://go-ooo.org/lxr/source/api/offapi/com/sun/star/smarttags/XSmartTagAction.idl page].
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | string getName()
+
|-
+
| rowspan="1" style="width:15%" | '''Arguments'''
+
| None.
+
|-
+
| '''Return Value'''
+
| Returns the name of the action library component.
+
|}
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | string getDescription()
+
|-
+
| rowspan="1" style="width:15%" | '''Arguments'''
+
| None.
+
|-
+
| '''Return Value'''
+
| Returns a textual description of the action library component.
+
|}
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | long getSmartTagCount()
+
|-
+
| rowspan="1" style="width:15%" | '''Arguments'''
+
| None.
+
|-
+
| '''Return Value'''
+
| The return value indicates how many smart tags are included in the action library component.
+
|}
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | string getSmartTagName()
+
|-
+
| rowspan="1" style="width:15%" | '''Arguments'''
+
| sal_Int32 '''nSmartTagIndex''': Index of the wanted smart tag. Value needs to be between 0 and the number of smart tags available (exclusively).
+
|-
+
| '''Return Value'''
+
| Returns the name of one specific smart tag in this action component. This name is needed to associate the actions of a smart tag with the corresponding recognizer.
+
|}
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | string getSmartTagCaption()
+
|-
+
| rowspan="2" style="width:15%" | '''Arguments'''
+
| sal_Int32 '''nSmartTagIndex''': Index of the wanted smart tag. Value needs to be between 0 and the number of smart tags available (exclusively).
+
|-
+
| XController '''xController''': The reference to the controller of the current document.
+
|-
+
| '''Return Value'''
+
| Returns the caption of one specific smart tag in this action component. The caption will be display by OpenOffice.org Writer in the context menu.
+
|}
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | long getActionCount()
+
|-
+
| rowspan="2" style="width:15%" | '''Arguments'''
+
| sal_Int32 '''nSmartTagIndex''': Index of the wanted smart tag. Value needs to be between 0 and the number of smart tags available (exclusively).
+
|-
+
| XController '''xController''': The reference to the controller of the current document.
+
|-
+
| '''Return Value'''
+
| Returns the number of available actions of one specific smart tag in this action library.
+
|}
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | string getActionCaption()
+
|-
+
| rowspan="3" style="width:15%" | '''Arguments'''
+
| sal_Int32 '''nSmartTagIndex''': Index of the wanted smart tag. Value needs to be between 0 and the number of smart tags available (exclusively).
+
|-
+
| sal_Int32 '''nActionIndex''': Index of the wanted action. Value needs to be between 0 and the number of actions available for the specified smart tag (nSmartTagIndex).
+
|-
+
| XController '''xController''': The reference to the controller of the current document.
+
|-
+
| '''Return Value'''
+
| This function returns the caption of an action of one specific smart tag in this action library.
+
|}
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | void invokeAction()
+
|-
+
| rowspan="4" style="width:15%" | '''Arguments'''
+
| sal_Int32 '''nSmartTagIndex''': Index of the wanted smart tag. Value needs to be between 0 and the number of smart tags available (exclusively).
+
|-
+
| sal_Int32 '''nActionIndex''': Index of the wanted action. Value needs to be between 0 and the number of actions available for the specified smart tag (nSmartTagIndex).
+
|-
+
| string aWord: Word that was recognized as actionable.
+
|-
+
| XController '''xController''': The reference to the controller of the current document.
+
|-
+
| '''Return Value'''
+
| None.
+
|}
+
 
+
 
+
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
+
! colspan="2" style="background:#ffdead;" | void initialize()
+
|-
+
| rowspan="1" style="width:15%" | '''Description'''
+
| This method is used for initializing the action library component and is currently needed by Writer to use xml based smart tags (see example below). For your own smart tag components you can implement this method with an empty body.
+
|-
+
| rowspan="1" style="width:15%" | '''Arguments'''
+
| sequence<any> '''aArguments''': Initialization arguments
+
|-
+
| '''Return Value'''
+
| None.
+
|}
+
 
+
 
+
=Example implementations=
+
 
+
==Document Properties Smart Tag==
+
 
+
===Recognizer===
+
 
+
 
+
As described above the recognizer matches document property keywords like title, author, description etc. The matching of scanned words of the current document is done by the Recognize() method as you can see below. This recognizer component contains just one smart tag type. Thus the getSmartTagCount() method returns 1. The name of this recognizer ("example_smarttag") is returned by the method getSmartTagName(). Of course this component needs to suport the SmartTagRecognizer service. Therefore the getSupportedServiceNames() method has to return a sequence containing the appropriate service name ("com.sun.star.smarttags.SmartTagRecognizer"). Each UNO component needs an unique implementation name. With different implementation names multiple recognizer components can be installed on your system in parallel. The implementation name of this example is  "org.openoffice.comp.smarttags.recognizer.example".
+
 
+
 
+
<code>[cpp]
+
// Listing: Class definition of ExampleRecognizer
+
 
+
class ExampleRecognizer : public ::cppu::WeakImplHelper2<
+
  com::sun::star::smarttags::XSmartTagRecognizer, XServiceInfo> {
+
 
+
private:
+
  OUString aName;
+
  OUString aDescription;
+
  Reference< XMultiServiceFactory > xServiceManager;
+
public:
+
  ExampleRecognizer(Reference< XMultiServiceFactory > _xServiceManager);
+
  ~ExampleRecognizer();
+
 
+
  // XSmartTagRecognizer
+
  virtual inline OUString SAL_CALL getName() throw (RuntimeException) { return aName; }
+
  virtual OUString SAL_CALL getDescription() throw (RuntimeException) { return aDescription; }
+
  virtual sal_Int32 SAL_CALL getSmartTagCount() throw (RuntimeException) { return 1; } 
+
  virtual OUString SAL_CALL getSmartTagName (sal_Int32 nSmartTagIndex) throw (RuntimeException);
+
  virtual OUString SAL_CALL getSmartTagCaption( sal_Int32 nSmartTagIndex,
+
const Reference< XController >& xController ) throw (RuntimeException);
+
  virtual sal_Bool SAL_CALL Recognize(const OUString& aWord, sal_Int32 nSmartTagIndex,
+
      const Reference< XController >& xController) throw (RuntimeException);
+
  virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
+
            throw (RuntimeException);
+
 
+
  ////////////////////////////////////////////////////////////
+
  // Service specific part
+
  ////////////////////////////////////////////////////////////
+
 
+
  // XServiceInfo
+
  virtual OUString SAL_CALL getImplementationName() throw(RuntimeException);
+
  virtual sal_Bool SAL_CALL supportsService( const OUString& rServiceName )
+
    throw(RuntimeException);
+
  virtual Sequence< OUString > SAL_CALL getSupportedServiceNames()
+
    throw(RuntimeException);
+
  static inline OUString getImplementationName_Static() throw();
+
  static Sequence< OUString > getSupportedServiceNames_Static() throw();
+
};
+
</code>
+
 
+
 
+
<code>[cpp]
+
// Listing: Method implementation of ExampleRecognizer
+
 
+
#define C2U(cChar) OUString::createFromAscii(cChar)
+
 
+
#define IMPLNAME "org.openoffice.comp.smarttags.recognizer.example"
+
#define SN_SMARTTAG_RECOGNIZER  "com.sun.star.smarttags.SmartTagRecognizer"
+
#define SMARTTAG_NAME C2U("example_smarttag")
+
 
+
ExampleRecognizer::ExampleRecognizer(Reference< XMultiServiceFactory > _xServiceManager) {
+
  xServiceManager = _xServiceManager;
+
}
+
 
+
OUString SAL_CALL ExampleRecognizer::getSmartTagName( sal_Int32 nSmartTagIndex) throw (RuntimeException) {
+
  if (nSmartTagIndex == 0)
+
    return SMARTTAG_NAME;
+
  else
+
    return C2U("");
+
}
+
 
+
OUString SAL_CALL ExampleRecognizer::getSmartTagCaption( sal_Int32 nSmartTagIndex,
+
const Reference< XController >& xController) throw (RuntimeException) {
+
  return C2U("Document Properties");
+
}
+
 
+
sal_Bool SAL_CALL ExampleRecognizer::Recognize(const OUString& aWord, sal_Int32 nSmartTagIndex,
+
const Reference< XController >& xController) throw (RuntimeException) {
+
  if (nSmartTagIndex !=  0) return sal_False;
+
 
+
  if (aWord.equalsIgnoreAsciiCase(C2U("Title"))) return sal_True;
+
  if (aWord.equalsIgnoreAsciiCase(C2U("Author"))) return sal_True;
+
  if (aWord.equalsIgnoreAsciiCase(C2U("Keywords"))) return sal_True;
+
  if (aWord.equalsIgnoreAsciiCase(C2U("Description"))) return sal_True;
+
  return sal_False;
+
+
}
+
 
+
void ExampleRecognizer::initialize( const Sequence< Any >& aArguments ) throw (RuntimeException) {
+
  // empty
+
}
+
 
+
///////////////////////////////////////////////////////////////////////////
+
// Service specific part
+
///////////////////////////////////////////////////////////////////////////
+
 
+
OUString SAL_CALL ExampleRecognizer::getImplementationName() throw(RuntimeException)
+
{
+
  return getImplementationName_Static();
+
}
+
 
+
inline OUString ExampleRecognizer::getImplementationName_Static() throw()
+
{
+
  return C2U(IMPLNAME);
+
}
+
 
+
sal_Bool SAL_CALL ExampleRecognizer::supportsService( const OUString& ServiceName )
+
  throw(RuntimeException)
+
{
+
  Sequence< OUString > aSNL = getSupportedServiceNames();
+
  const OUString * pArray = aSNL.getConstArray();
+
  for( INT32 i = 0; i < aSNL.getLength(); i++ )
+
    if( pArray[i] == ServiceName )
+
      return TRUE;
+
  return FALSE;
+
}
+
 
+
Sequence< OUString > SAL_CALL ExampleRecognizer::getSupportedServiceNames()
+
  throw(RuntimeException)
+
{
+
  return getSupportedServiceNames_Static();
+
}
+
 
+
Sequence< OUString > ExampleRecognizer::getSupportedServiceNames_Static()
+
  throw()
+
{
+
  Sequence< OUString > aSNS( 1 );
+
  aSNS.getArray()[0] = C2U( SN_SMARTTAG_RECOGNIZER );
+
  return aSNS;
+
}
+
 
+
extern "C" sal_Bool SAL_CALL component_writeInfo(void * /*pServiceManager*/,
+
registry::XRegistryKey * pRegistryKey ) {
+
  try {
+
    String aImpl( '/' );
+
    aImpl += ExampleRecognizer::getImplementationName_Static().getStr();
+
    aImpl.AppendAscii( "/UNO/SERVICES" );
+
    Reference< registry::XRegistryKey > xNewKey =
+
      pRegistryKey->createKey( aImpl );
+
    Sequence< OUString > aServices =
+
      ExampleRecognizer::getSupportedServiceNames_Static();
+
    for( INT32 i = 0; i < aServices.getLength(); i++ )
+
      xNewKey->createKey( aServices.getConstArray()[i] );
+
   
+
    return sal_True;
+
  }
+
  catch(Exception &) {
+
    return sal_False;
+
  }
+
 
+
}
+
 
+
Reference< XInterface > SAL_CALL ExampleRecognizer_create(
+
const Reference< XMultiServiceFactory > & xMgr )
+
{
+
  Reference<XInterface> ref (static_cast<XSmartTagRecognizer*>(new ExampleRecognizer(xMgr)));
+
  return ref;
+
}
+
 
+
extern "C" void * SAL_CALL component_getFactory(
+
    const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
+
{
+
    void * pRet = 0;
+
    // which implementation is required?
+
    if (pServiceManager && ( !ExampleRecognizer::getImplementationName_Static().compareToAscii( pImplName ) ) )
+
    {
+
        Reference< XSingleServiceFactory > xFactory(
+
          cppu::createSingleFactory( // helper function from cppuhelper lib
+
          reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
+
          ExampleRecognizer::getImplementationName_Static(),
+
          ExampleRecognizer_create,
+
          ExampleRecognizer::getSupportedServiceNames_Static() ) );
+
        if (xFactory.is())
+
        {
+
          xFactory->acquire();
+
          pRet = xFactory.get();
+
        }
+
    }
+
    return pRet;
+
}
+
</code>
+
 
+
 
+
===Action Library===
+
 
+
 
+
Implementing an action library is quite similar to implementing the recognizer. Of course you have to support the action service instead of the recongizer service. Thus the appropriate service name is "com.sun.star.smarttags.SmartTagAction". The implementation name of the action component has to be different too. In this expample the name "org.openoffice.comp.smarttags.action.example" was chosen. But the name of the smart tag this components provides actions for has to be the same name used in the recognizer component (i.e. "example_smarttag"). Since this component just provides actions for one smart tag type the getSmartTagCount() method returns 1. And for this single smart tag the component just provides one action, as you can see in the invokeAction() method. This action retrieves the value of document property which was recognized and inserts it just behind the recognized word.
+
 
+
<code>[cpp]
+
// Listing: Class definition of ExampleActionlib
+
 
+
class ExampleActionlib : public ::cppu::WeakImplHelper2<
+
  com::sun::star::smarttags::XSmartTagAction, XServiceInfo> {
+
 
+
private:
+
  OUString aName;
+
  OUString aDescription;
+
  Reference< XMultiServiceFactory > xServiceManager;
+
public:
+
  ExampleActionlib(Reference< XMultiServiceFactory > _xServiceManager);
+
  ~ExampleActionlib();
+
 
+
  // XSmartTagAction
+
  virtual inline OUString SAL_CALL getName() throw (RuntimeException) { return aName; }
+
  virtual OUString SAL_CALL getDescription() throw (RuntimeException) { return aDescription; }
+
  virtual sal_Int32 SAL_CALL getSmartTagCount() throw (RuntimeException) { return 1; } 
+
  virtual OUString SAL_CALL getSmartTagName( sal_Int32 nSmartTagIndex ) throw (RuntimeException);
+
  virtual OUString SAL_CALL getSmartTagCaption( sal_Int32 nSmartTagIndex,
+
const Reference< XController >& xController ) throw (RuntimeException);
+
  virtual sal_Int32 SAL_CALL getActionCount( sal_Int32 nSmartTagIndex,
+
  const Reference< XController >& xController ) throw (RuntimeException);
+
  virtual OUString SAL_CALL getActionCaption( sal_Int32 nSmartTagIndex, sal_Int32 nActionIndex,
+
    const Reference< XController >& xController ) throw (RuntimeException);
+
  virtual void SAL_CALL invokeAction (sal_Int32 nSmartTagIndex, sal_Int32 nActionIndex,
+
      const Reference< XTextRange >& xRange,
+
      const Reference< XController >& xController ) throw (RuntimeException);
+
 
+
  virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
+
            throw (RuntimeException);
+
 
+
  ////////////////////////////////////////////////////////////
+
  // Service specific part
+
  ////////////////////////////////////////////////////////////
+
 
+
  // XServiceInfo
+
  virtual OUString SAL_CALL getImplementationName() throw(RuntimeException);
+
  virtual sal_Bool SAL_CALL supportsService( const OUString& rServiceName )
+
    throw(RuntimeException);
+
  virtual Sequence< OUString > SAL_CALL getSupportedServiceNames()
+
    throw(RuntimeException);
+
  static inline OUString getImplementationName_Static() throw();
+
  static Sequence< OUString > getSupportedServiceNames_Static() throw();
+
};
+
</code>
+
 
+
 
+
<code>[cpp]
+
// Listing: Method implementation of ExampleActionlib
+
 
+
#define C2U(cChar) OUString::createFromAscii(cChar)
+
 
+
#define IMPLNAME "org.openoffice.comp.smarttags.action.example"
+
#define SN_SMARTTAG_ACTION  "com.sun.star.smarttags.SmartTagAction"
+
#define SMARTTAG_NAME C2U("example_smarttag")
+
 
+
ExampleActionlib::ExampleActionlib(Reference< XMultiServiceFactory > _xServiceManager) {
+
  xServiceManager = _xServiceManager;
+
}
+
 
+
OUString SAL_CALL ExampleActionlib::getSmartTagName( sal_Int32 nSmartTagIndex) throw (RuntimeException) {
+
  if (nSmartTagIndex == 0)
+
    return SMARTTAG_NAME;
+
  else
+
    return C2U("");
+
}
+
 
+
OUString SAL_CALL ExampleActionlib::getSmartTagCaption( sal_Int32 nSmartTagIndex,
+
  const Reference< XController >& xController) throw (RuntimeException) {
+
  return C2U("Document Properties");
+
}
+
 
+
sal_Int32 SAL_CALL ExampleActionlib::getActionCount(sal_Int32 nSmartTagIndex,
+
    const Reference< XController >& xController) throw (RuntimeException) {
+
  if (nSmartTagIndex == 0)
+
    return 1;
+
  else
+
    return 0;
+
}
+
 
+
OUString SAL_CALL ExampleActionlib::getActionCaption(sal_Int32 nSmartTagIndex, sal_Int32 nActionIndex,
+
    const Reference< XController >& xController) throw (RuntimeException) {
+
  if (nSmartTagIndex == 0) {
+
    switch (nActionIndex) {
+
    case 0:
+
      return C2U("Insert document property value");
+
      break;
+
    default:
+
      break;
+
    }
+
  }
+
  return C2U("");
+
}
+
 
+
void SAL_CALL ExampleActionlib::invokeAction(sal_Int32 nSmartTagIndex, sal_Int32 nActionIndex,
+
    const Reference< XTextRange >& xRange,
+
    const Reference< XController >& xController) throw (RuntimeException) {
+
 
+
  if (!xController.is()) return;
+
  Reference<XModel> xModel = xController->getModel();
+
  if (!xModel.is()) return;
+
  Reference<XTextDocument> xTextDocument (xModel, UNO_QUERY);
+
  if (!xTextDocument.is()) return;
+
 
+
  if (nSmartTagIndex == 0) {
+
    if (nActionIndex == 0) {
+
      Reference<XDocumentInfoSupplier> xDocInfoSupplier (xTextDocument, UNO_QUERY);
+
      if(!xDocInfoSupplier.is()) return;
+
      Reference<XDocumentInfo> xDocInfo = xDocInfoSupplier->getDocumentInfo();
+
      if(!xDocInfo.is()) return;
+
      Reference<XPropertySet> xProps (xDocInfo, UNO_QUERY);
+
      if (!xProps.is()) return;
+
      Any a = xProps->getPropertyValue(xRange->getString());
+
      OUString s;
+
      a >>= s;
+
      if (s) {
+
Reference<XTextCursor> xCursor = xRange->getText()->createTextCursorByRange(xRange->getEnd());
+
// check if colon follows word
+
xCursor->goRight(1, sal_True);
+
if (xCursor->getString().indexOf(C2U(":")) != -1)  {
+
  xTextDocument->getText()->insertString(xCursor->getEnd(), C2U(" ") + s, sal_False);
+
}
+
else {
+
  xTextDocument->getText()->insertString(xRange->getEnd(), C2U(": ") + s, sal_False);
+
}
+
 
+
      } 
+
    } 
+
  }
+
 
+
}
+
 
+
void ExampleActionlib::initialize( const Sequence< Any >& aArguments ) throw (RuntimeException) {
+
  // empty
+
}
+
 
+
///////////////////////////////////////////////////////////////////////////
+
// Service specific part
+
///////////////////////////////////////////////////////////////////////////
+
 
+
OUString SAL_CALL ExampleActionlib::getImplementationName() throw(RuntimeException)
+
{
+
  return getImplementationName_Static();
+
}
+
 
+
inline OUString ExampleActionlib::getImplementationName_Static() throw()
+
{
+
  return C2U(IMPLNAME);
+
}
+
 
+
sal_Bool SAL_CALL ExampleActionlib::supportsService( const OUString& ServiceName )
+
  throw(RuntimeException)
+
{
+
  Sequence< OUString > aSNL = getSupportedServiceNames();
+
  const OUString * pArray = aSNL.getConstArray();
+
  for( INT32 i = 0; i < aSNL.getLength(); i++ )
+
    if( pArray[i] == ServiceName )
+
      return TRUE;
+
  return FALSE;
+
}
+
 
+
Sequence< OUString > SAL_CALL ExampleActionlib::getSupportedServiceNames()
+
  throw(RuntimeException)
+
{
+
  return getSupportedServiceNames_Static();
+
}
+
 
+
Sequence< OUString > ExampleActionlib::getSupportedServiceNames_Static()
+
  throw()
+
{
+
  Sequence< OUString > aSNS( 1 );
+
  aSNS.getArray()[0] = C2U( SN_SMARTTAG_ACTION );
+
  return aSNS;
+
}
+
 
+
extern "C" sal_Bool SAL_CALL component_writeInfo(void * /*pServiceManager*/,
+
registry::XRegistryKey * pRegistryKey ) {
+
  try {
+
    String aImpl( '/' );
+
    aImpl += ExampleActionlib::getImplementationName_Static().getStr();
+
    aImpl.AppendAscii( "/UNO/SERVICES" );
+
    Reference< registry::XRegistryKey > xNewKey =
+
      pRegistryKey->createKey( aImpl );
+
    Sequence< OUString > aServices =
+
      ExampleActionlib::getSupportedServiceNames_Static();
+
    for( INT32 i = 0; i < aServices.getLength(); i++ )
+
      xNewKey->createKey( aServices.getConstArray()[i] );
+
   
+
    return sal_True;
+
  }
+
  catch(Exception &) {
+
    return sal_False;
+
  }
+
 
+
}
+
 
+
Reference< XInterface > SAL_CALL ExampleActionlib_create(
+
const Reference< XMultiServiceFactory > & xMgr )
+
{
+
  Reference<XInterface> ref (static_cast<XSmartTagAction*>(new ExampleActionlib(xMgr)));
+
  return ref;
+
}
+
 
+
extern "C" void * SAL_CALL component_getFactory(
+
    const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
+
{
+
    void * pRet = 0;
+
    // which implementation is required?
+
    if (pServiceManager && ( !ExampleActionlib::getImplementationName_Static().compareToAscii( pImplName ) ) )
+
    {
+
        Reference< XSingleServiceFactory > xFactory(
+
          cppu::createSingleFactory( // helper function from cppuhelper lib
+
          reinterpret_cast< XMultiServiceFactory * >( pServiceManager ),
+
          ExampleActionlib::getImplementationName_Static(),
+
          ExampleActionlib_create,
+
          ExampleActionlib::getSupportedServiceNames_Static() ) );
+
        if (xFactory.is())
+
        {
+
          xFactory->acquire();
+
          pRet = xFactory.get();
+
        }
+
    }
+
    return pRet;
+
}
+
</code>
+
 
+
 
+
==XML based Smart Tags==
+
 
+
In some cases you just want to match a list of words or regular expressions and open some URL associated with these words. For such simple smart tag components Microsoft Office provides the possiblity to define a recognizer or an action library with a XML schema. These simple smart tag descriptions are called "Microsoft Office Smart Tag Lists" (MOSTL). Below you can find an example XML description which defines some OOo related terms and some actions involving OOo websites. The XML description is pretty self-explanatory. As mentioned it is also possible to specify regular expressions in order to recognize certain word patterns. If you want to see how regular expressions are defined have a look at this [http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dno2k3ta/html/odc_regex_smarttags_2003.asp site].
+
 
+
<code>[xml]
+
<FL:smarttaglist xmlns:FL="http://schemas.microsoft.com/office/smarttags/2003/mostl">
+
<FL:name>OOo Smart Tags</FL:name>
+
<FL:lcid>1033</FL:lcid>
+
<FL:description>OOo Smart Tags</FL:description>
+
<FL:smarttag type="urn:schemas-openoffice-org:smarttags#ooo">
+
 
+
    <FL:caption>OOo Smart Tags</FL:caption>
+
    <FL:terms>
+
        <FL:termlist>OpenOffice.org, Writer, OOo, UNO</FL:termlist>
+
    </FL:terms>
+
 
+
    <FL:actions>
+
        <FL:action id="ooo1">
+
          <FL:caption>OpenOffice.org Homepage</FL:caption>
+
          <FL:url>http://www.openoffice.org</FL:url>
+
        </FL:action>
+
        <FL:action id="ooo2">
+
          <FL:caption>Download OpenOffice.org</FL:caption>
+
          <FL:url>http://download.openoffice.org/index.html</FL:url>
+
        </FL:action>
+
<FL:action id="ooo3">
+
          <FL:caption>Search in OOo Wiki</FL:caption>
+
          <FL:url>http://wiki.services.openoffice.org/wiki/Special:Search?search={TEXT}&amp;fulltext=Search</FL:url>
+
        </FL:action>
+
    </FL:actions>
+
 
+
</FL:smarttag>
+
</FL:smarttaglist>
+
</code>
+
 
+
In order to use XML based smart tags with OpenOffice.org a smart tag component was written which implements the Recognizer and Action Library interfaces as described in the sections above. This component parses XML files which comply with the MOSTL schema. The behavior of the recognize and the invokeAction methods is determined by the given XML description. The XML files currently have to reside in a subfolder called "smarttags" in the "share" folder of your OOo installation. For each XML file in this directory OOo Writer creates an instance of the MOSTL Smart Tag component.
+
 
+
The source code of the MOSTL Smart Tag component can be found here: [[Media:mostl.tar.gz]]
+
 
+
The MOSTL component depends on the [http://xmlsoft.org/ libxml] library and can be compiled with [http://download.openoffice.org/index.html OpenOffice.org SDK].
+
 
+
=See also=
+
 
+
*[[Constructing_Components|Great tutorial about constucting UNO components]]
+
*[http://blogs.sun.com/GullFOSS/entry/successful_community_project_smart_tags Blog entry about smart tag project]
+
 
+
=API Changes for OOo 2.3=
+
 
+
For OOo 2.3, the Smart tag API has been enhanced considerably:
+
 
+
==The Recognizer Interface==
+
  
 
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
 
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
Line 721: Line 47:
 
  | obtains a name that describes this recognizer component.
 
  | obtains a name that describes this recognizer component.
 
  |-
 
  |-
  | rowspan="1" | '''Arguments'''
+
  | '''Arguments'''
 
  | [in] ::com::sun::star::lang::Locale '''aLocale''': Is used for localization of the name.
 
  | [in] ::com::sun::star::lang::Locale '''aLocale''': Is used for localization of the name.
 
  |-
 
  |-
Line 735: Line 61:
 
  | obtains a detailed description of this recognizer component.
 
  | obtains a detailed description of this recognizer component.
 
  |-
 
  |-
  | rowspan="1" | '''Arguments'''
+
  | '''Arguments'''
 
  | [in] ::com::sun::star::lang::Locale '''aLocale''': Is used for localization of the description.
 
  | [in] ::com::sun::star::lang::Locale '''aLocale''': Is used for localization of the description.
 
  |-
 
  |-
Line 749: Line 75:
 
  | The number of smart tag types supported by this recognizer component.
 
  | The number of smart tag types supported by this recognizer component.
 
  |-
 
  |-
  | rowspan="1" | '''Arguments'''
+
  | '''Arguments'''
 
  | None.
 
  | None.
 
  |-
 
  |-
Line 763: Line 89:
 
  | obtains the name of one specific smart tag type supported by this recognizer component.
 
  | obtains the name of one specific smart tag type supported by this recognizer component.
 
  |-
 
  |-
  | rowspan="1" | '''Arguments'''
+
  | '''Arguments'''
 
  | [in] long '''nSmartTagIndex''': Index of the wanted smart tag type.
 
  | [in] long '''nSmartTagIndex''': Index of the wanted smart tag type.
 
  |-
 
  |-
Line 777: Line 103:
 
  | obtains the URL that can be used to download new or updated recognizers.
 
  | obtains the URL that can be used to download new or updated recognizers.
 
  |-
 
  |-
  | rowspan="1" | '''Arguments'''
+
  | '''Arguments'''
 
  | [in] long '''nSmartTagIndex''': Index of the wanted smart tag type.
 
  | [in] long '''nSmartTagIndex''': Index of the wanted smart tag type.
 
  |-
 
  |-
Line 845: Line 171:
 
  | None.
 
  | None.
 
  |}
 
  |}
 +
  
 
==The Action Interface==
 
==The Action Interface==
 +
 +
For a look at the action library interface definition go to this [http://svn.services.openoffice.org/opengrok/xref/Current%20%28trunk%29/offapi/com/sun/star/smarttags/XSmartTagAction.idl page].
  
 
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
 
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
Line 1,064: Line 393:
 
  | a boolean indicating whether the smart tag indicator should be visible.
 
  | a boolean indicating whether the smart tag indicator should be visible.
 
  |}
 
  |}
 +
 +
 +
 +
=Smart Tags Step-by-Step Tutorial=
 +
 +
First you should make sure that you have all of these at hand:
 +
 +
* [http://download.openoffice.org/index.html OpenOffice.org 2.3]
 +
* [http://download.openoffice.org/2.3.0/sdk.html The OpenOffice.org SDK]
 +
* [http://www.netbeans.info/downloads/index.php The NetBeans IDE]
 +
* [http://wiki.services.openoffice.org/wiki/OpenOffice_NetBeans_Integration The NetBeans OOo API Plugin]
 +
 +
After you have installed the NetBeans OOo API Plugin, you are offered a new project type „OpenOffice.org component“:
 +
 +
[[Image:NetBeans1.png]]
 +
 +
 +
 +
In the next dialog, you are asked for a name and the location of your new project:
 +
 +
[[Image:NetBeans2.png]]
 +
 +
 +
 +
After this, you have to choose which service you want to implement. For our example, we implement the com.sun.star.smarttag.SmartTagRecognizer service:
 +
 +
[[Image:NetBeans3.png]]
 +
 +
 +
 +
Once you have created the new project, you have to add a SmartTagAction service to your project. For this, go to “File – New File” and add a new “Java UNO Object”:
 +
 +
[[Image:NetBeans4.png]]
 +
 +
 +
 +
Choose a name for your action class and pick com.com.sun.star.smarttags.SmartTagAction from the list of services:
 +
 +
[[Image:NetBeans5.png]]
 +
 +
 +
 +
Finally the OOo API Plugin creates a skeleton of the implementation. So all that's left to do is implementing the required functions:
 +
 +
[[Image:NetBeans6.png]]
 +
 +
 +
 +
The following tables shows the minimal set of function you should to implement. Except from the recognize() and invokeAction() functions, non of these require actual coding:
 +
 +
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
 +
! style="background:#ffdead;"| SmartTagRecognizer
 +
! style="background:#ffdead;"| Comment
 +
|-
 +
| '''getSmartTagCount()'''
 +
| the number of supported smart tag types, usually 1
 +
|-
 +
| '''getSmartTagName(...)'''
 +
| returns an internal name for each supported smart tag type
 +
|-
 +
| '''getName(...)'''
 +
| returns an UI string for the recognizer component
 +
|-
 +
| '''recognize(...)'''
 +
| see below
 +
|}
 +
 +
 +
 +
{| border=1 cellspacing=0 cellpadding=5 style="width:75%"
 +
! style="background:#ffdead;"| SmartTagAction
 +
! style="background:#ffdead;"| Comment
 +
|-
 +
| '''getSmartTagCount()'''
 +
| the number of supported smart tag types, usually 1
 +
|-
 +
| '''getSmartTagName(...)'''
 +
| returns an internal name for each supported smart tag type
 +
|-
 +
| '''getSmartTagCaption(...)'''
 +
| returns the UI name of the new smart tag types
 +
|-
 +
| '''getActionCount(...)'''
 +
| the number of provided actions for each smart tag type
 +
|-
 +
| '''getActionID(...)'''
 +
| returns an ID for each provided action
 +
|-
 +
| '''getActionCaptionFromID(...)'''
 +
| returns an UI string for each provided action
 +
|-
 +
| '''invokeAction(...)'''
 +
| see below
 +
|}
 +
 +
 +
Here is some code that shows how the recognize() function can be implemented:
 +
 +
<source lang="java">
 +
public void recognize(String aText, int nStart, int nLength, com.sun.star.smarttags.SmartTagRecognizerMode eDataType, 
 +
    com.sun.star.lang.Locale aLocale, com.sun.star.text.XTextMarkup xTextMarkup, String aApplicationName,
 +
    com.sun.star.frame.XController xController, com.sun.star.i18n.XBreakIterator xTokenizer)
 +
{
 +
    final int nEndPos = nStart + nLength;
 +
 +
    Boundary aWordBounds = xTokenizer.getWordBoundary( aText, nStart, aLocale, WordType.DICTIONARY_WORD, true );
 +
 +
    // iterate over all words
 +
    while ( aWordBounds.startPos < aWordBounds.endPos && aWordBounds.endPos <= nEndPos ) {
 +
        final String aWord = aText.substring( aWordBounds.startPos, aWordBounds.endPos );
 +
 +
        // check current word
 +
        if ( aWord.matchesMyCriteria() ) {
 +
            XStringKeyMap xProps = null;
 +
 +
            // pass the smart tag data to the application
 +
            xTextMarkup.commitTextMarkup( TextMarkupType.SMARTTAG,
 +
                                          m_SmartTagType,
 +
                                          aWordBounds.startPos,
 +
                                          aWordBounds.endPos - aWordBounds.startPos,
 +
                                          xProps );
 +
        }
 +
 +
        // continue with next word
 +
        aWordBounds = xTokenizer.nextWord( aText, aWordBounds.startPos, aLocale, WordType.DICTIONARY_WORD );
 +
    }
 +
}
 +
</source>
 +
 +
And finally, here is an example for the invokeAcion() function:
 +
 +
<source lang="java">
 +
public void invokeAction(int nActionID, String aApplicationName, com.sun.star.frame.XController xController,
 +
    com.sun.star.text.XTextRange xTarget, com.sun.star.container.XStringKeyMap xProperties,
 +
    String aText, String aXML, com.sun.star.lang.Locale aLocale) throws com.sun.star.lang.IllegalArgumentException
 +
{
 +
    try {
 +
        // get SystemShellExecute to execute URLS
 +
        final XMultiComponentFactory xFact = m_xContext.getServiceManager();
 +
        final Object xObject = xFact.createInstanceWithContext("com.sun.star.system.SystemShellExecute", m_xContext);
 +
        final XSystemShellExecute xSystemShellExecute = (XSystemShellExecute) UnoRuntime.queryInterface(XSystemShellExecute.class, xObject);
 +
        String aURLString = "www.openoffice.org";
 +
        xSystemShellExecute.execute( aURLString, "", com.sun.star.system.SystemShellExecuteFlags.DEFAULTS );
 +
    } catch (Exception ex) {
 +
        ex.printStackTrace();
 +
    }
 +
}
 +
</source>
 +
 +
 +
Once you have implemented all the required functions, it's time to test you implementation. In the context menu of the project, you can either choose to create an oxt package which can be installed using the OpenOffice.org extension manager, or you can even do a live deployment of your extensions and start debugging your code!
 +
 +
And that's it. In the next section you can find some sample implementations that might also give you some hints of how to implement the required functions:
 +
 +
=Example Implementations=
 +
 +
Here you find some example implementations of smart tag components. They should serve as examples of how to implement your own smart tag components, so don't expect to find full featured, thoroughly tested components.
 +
 +
==Document Property Smart Tag==
 +
 +
The recognizer identifies document property keywords. The action component offers to replace the smart tag text in the document by the respective value from the document properties.
 +
 +
===Recognizer===
 +
 +
As described above the recognizer matches document property keywords like title, author, description etc. The matching of scanned words of the current document is done by the Recognize() method as you can see below. This recognizer component contains just one smart tag type. Thus the getSmartTagCount() method returns 1. The name of this recognizer ("Document Property Recognizer") is returned by the method getName().
 +
 +
<source lang="java">
 +
package org.openoffice;
 +
 +
import com.sun.star.container.XStringKeyMap;
 +
import com.sun.star.i18n.Boundary;
 +
import com.sun.star.i18n.WordType;
 +
import com.sun.star.lang.XSingleComponentFactory;
 +
import com.sun.star.lib.uno.helper.Factory;
 +
import com.sun.star.lib.uno.helper.WeakBase;
 +
import com.sun.star.registry.XRegistryKey;
 +
import com.sun.star.text.TextMarkupType;
 +
import com.sun.star.uno.XComponentContext;
 +
 +
public final class DocumentPropertyRecognizer extends WeakBase
 +
  implements com.sun.star.lang.XServiceInfo,
 +
              com.sun.star.smarttags.XSmartTagRecognizer
 +
{
 +
    private final XComponentContext m_xContext;
 +
    private static final String m_SmartTagType = "mynamespace#docproperty";
 +
    private static final String m_implementationName = DocumentPropertyRecognizer.class.getName();
 +
    private static final String[] m_serviceNames = {
 +
        "com.sun.star.smarttags.SmartTagRecognizer" };
 +
 +
 +
    public DocumentPropertyRecognizer( XComponentContext context ) {
 +
        m_xContext = context;
 +
    };
 +
 +
    public static XSingleComponentFactory __getComponentFactory( String sImplementationName ) {
 +
        XSingleComponentFactory xFactory = null;
 +
 +
        if ( sImplementationName.equals( m_implementationName ) )
 +
            xFactory = Factory.createComponentFactory(DocumentPropertyRecognizer.class, m_serviceNames);
 +
        return xFactory;
 +
    }
 +
 +
    public static boolean __writeRegistryServiceInfo( XRegistryKey xRegistryKey ) {
 +
        return Factory.writeRegistryServiceInfo(m_implementationName,
 +
                                                m_serviceNames,
 +
                                                xRegistryKey);
 +
    }
 +
 +
    // com.sun.star.lang.XServiceInfo:
 +
    public String getImplementationName() {
 +
        return m_implementationName;
 +
    }
 +
 +
    public boolean supportsService( String sService ) {
 +
        int len = m_serviceNames.length;
 +
 +
        for( int i=0; i < len; i++) {
 +
            if (sService.equals(m_serviceNames[i]))
 +
                return true;
 +
        }
 +
        return false;
 +
    }
 +
 +
    public String[] getSupportedServiceNames() {
 +
        return m_serviceNames;
 +
    }
 +
 +
    // com.sun.star.lang.XInitialization:
 +
    public void initialize(Object[] aArguments) throws com.sun.star.uno.Exception {
 +
    }
 +
 +
    // com.sun.star.smarttags.XSmartTagRecognizer:
 +
    public int getSmartTagCount() {
 +
        return 1;
 +
    }
 +
 +
    public String getName(com.sun.star.lang.Locale aLocale) {
 +
        return new String("Document Property Recognizer");
 +
    }
 +
 +
    public String getDescription(com.sun.star.lang.Locale aLocale) {
 +
        return new String();
 +
    }
 +
 +
    public String getSmartTagName(int nSmartTagIndex) throws com.sun.star.lang.IndexOutOfBoundsException {
 +
        return m_SmartTagType;
 +
    }
 +
 +
    public String getSmartTagDownloadURL(int nSmartTagIndex) throws com.sun.star.lang.IndexOutOfBoundsException {
 +
        return new String();
 +
    }
 +
 +
    public void recognize(String aText, int nStart, int nLength, com.sun.star.smarttags.SmartTagRecognizerMode eDataType,
 +
        com.sun.star.lang.Locale aLocale, com.sun.star.text.XTextMarkup xTextMarkup, String aApplicationName,
 +
        com.sun.star.frame.XController xController, com.sun.star.i18n.XBreakIterator xTokenizer) {
 +
        final int nEndPos = nStart + nLength;
 +
 +
        Boundary aWordBounds = xTokenizer.getWordBoundary( aText, nStart, aLocale, WordType.DICTIONARY_WORD, true );
 +
 +
        while ( aWordBounds.startPos < aWordBounds.endPos && aWordBounds.endPos <= nEndPos ) {
 +
            final String aWord = aText.substring( aWordBounds.startPos, aWordBounds.endPos );
 +
            if ( aWord.equalsIgnoreCase("Title") || aWord.equalsIgnoreCase("Author") ||
 +
                aWord.equalsIgnoreCase("Keywords") || aWord.equalsIgnoreCase("Description") ) {
 +
                XStringKeyMap xProps = null;
 +
                xTextMarkup.commitTextMarkup( TextMarkupType.SMARTTAG,
 +
                                              m_SmartTagType,
 +
                                              aWordBounds.startPos,
 +
                                              aWordBounds.endPos - aWordBounds.startPos,
 +
                                              xProps );
 +
            }
 +
 +
            aWordBounds = xTokenizer.nextWord( aText, aWordBounds.startPos, aLocale, WordType.DICTIONARY_WORD );
 +
        }
 +
    }
 +
 +
    public boolean hasPropertyPage(int nSmartTagIndex, com.sun.star.lang.Locale aLocale) throws com.sun.star.lang.IndexOutOfBoundsException {
 +
        return false;
 +
    }
 +
 +
    public void displayPropertyPage(int nSmartTagIndex, com.sun.star.lang.Locale aLocale) throws com.sun.star.lang.IndexOutOfBoundsException {
 +
    }
 +
 +
}
 +
</source>
 +
 +
===Action===
 +
 +
Implementing an action library is quite similar to implementing the recognizer. Of course you have to support the action service instead of the recongizer service. Since this component just provides actions for one smart tag type the getSmartTagCount() method returns 1. And for this single smart tag the component just provides one action, as you can see in the invokeAction() method. This action retrieves the document properties value and inserts it into the document.
 +
 +
<source lang="java">
 +
package org.openoffice;
 +
 +
import com.sun.star.beans.XPropertySet;
 +
import com.sun.star.document.XDocumentInfo;
 +
import com.sun.star.document.XDocumentInfoSupplier;
 +
import com.sun.star.frame.XModel;
 +
import com.sun.star.lang.XSingleComponentFactory;
 +
import com.sun.star.lib.uno.helper.Factory;
 +
import com.sun.star.lib.uno.helper.WeakBase;
 +
import com.sun.star.registry.XRegistryKey;
 +
import com.sun.star.uno.UnoRuntime;
 +
import com.sun.star.uno.XComponentContext;
 +
 +
public final class DocumentPropertyAction extends WeakBase
 +
  implements com.sun.star.lang.XServiceInfo,
 +
              com.sun.star.smarttags.XSmartTagAction
 +
{
 +
    private final XComponentContext m_xContext;
 +
    private static final String m_implementationName = DocumentPropertyAction.class.getName();
 +
    private static final String[] m_serviceNames = {
 +
        "com.sun.star.smarttags.SmartTagAction" };
 +
 +
    public DocumentPropertyAction( XComponentContext context ) {
 +
        m_xContext = context;
 +
    };
 +
 +
    public static XSingleComponentFactory __getComponentFactory( String sImplementationName ) {
 +
        XSingleComponentFactory xFactory = null;
 +
 +
        if ( sImplementationName.equals( m_implementationName ) )
 +
            xFactory = Factory.createComponentFactory(DocumentPropertyAction.class, m_serviceNames);
 +
        return xFactory;
 +
    }
 +
 +
    public static boolean __writeRegistryServiceInfo( XRegistryKey xRegistryKey ) {
 +
        return Factory.writeRegistryServiceInfo(m_implementationName,
 +
                                                m_serviceNames,
 +
                                                xRegistryKey);
 +
    }
 +
 +
    // com.sun.star.lang.XServiceInfo:
 +
    public String getImplementationName() {
 +
        return m_implementationName;
 +
    }
 +
 +
    public boolean supportsService( String sService ) {
 +
        int len = m_serviceNames.length;
 +
 +
        for( int i=0; i < len; i++) {
 +
            if (sService.equals(m_serviceNames[i]))
 +
                return true;
 +
        }
 +
        return false;
 +
    }
 +
 +
    public String[] getSupportedServiceNames() {
 +
        return m_serviceNames;
 +
    }
 +
 +
    // com.sun.star.lang.XInitialization:
 +
    public void initialize(Object[] aArguments) throws com.sun.star.uno.Exception {
 +
    }
 +
 +
    // com.sun.star.smarttags.XSmartTagAction:
 +
    public int getSmartTagCount() {
 +
        return 1;
 +
    }
 +
 +
    public String getName(com.sun.star.lang.Locale aLocale) {
 +
        return new String();
 +
    }
 +
 +
    public String getDescription(com.sun.star.lang.Locale aLocale) {
 +
        return new String();
 +
    }
 +
 +
    public String getSmartTagName(int nSmartTagIndex) throws com.sun.star.lang.IndexOutOfBoundsException {
 +
        return new String("mynamespace#docproperty");
 +
    }
 +
 +
    public String getSmartTagCaption(int nSmartTagIndex, com.sun.star.lang.Locale aLocale) throws com.sun.star.lang.IndexOutOfBoundsException {
 +
        return new String("Document Property");
 +
    }
 +
 +
    public int getActionCount(String aSmartTagName, com.sun.star.frame.XController xController) {
 +
        return 1;
 +
    }
 +
 +
    public int getActionID(String aSmartTagName, int nActionIndex, com.sun.star.frame.XController xController) throws com.sun.star.lang.IllegalArgumentException {
 +
        return 500 + nActionIndex;
 +
    }
 +
 +
    public String getActionCaptionFromID(int nActionID, String aApplicationName, com.sun.star.lang.Locale aLocale, com.sun.star.container.XStringKeyMap xProperties, String aText, String aXML, com.sun.star.frame.XController xController, com.sun.star.text.XTextRange xTarget) throws com.sun.star.lang.IllegalArgumentException {
 +
        return new String("Replace with value from document properties");
 +
    }
 +
 +
    public String getActionNameFromID(int nActionID, com.sun.star.frame.XController xController) throws com.sun.star.lang.IllegalArgumentException {
 +
        return new String();
 +
    }
 +
 +
    public void invokeAction(int nActionID, String aApplicationName, com.sun.star.frame.XController xController, com.sun.star.text.XTextRange xTarget, com.sun.star.container.XStringKeyMap xProperties, String aText, String aXML, com.sun.star.lang.Locale aLocale) throws com.sun.star.lang.IllegalArgumentException {
 +
        XModel xModel = xController.getModel();
 +
        XDocumentInfoSupplier xDocInfoSupplier = (XDocumentInfoSupplier) UnoRuntime.queryInterface(XDocumentInfoSupplier.class, xModel); 
 +
        XDocumentInfo xDocInf = xDocInfoSupplier.getDocumentInfo();
 +
        XPropertySet xProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xDocInf);
 +
        try {
 +
            String aValue = (String)xProps.getPropertyValue(xTarget.getString());
 +
            xTarget.setString(aValue);
 +
        } catch (Exception ex) {
 +
            ex.printStackTrace();
 +
        }
 +
    }
 +
 +
    public boolean isCaptionDynamic(int nActionID, String aApplicationName, com.sun.star.frame.XController xController, com.sun.star.lang.Locale aLocale) throws com.sun.star.lang.IllegalArgumentException {
 +
        return false;
 +
    }
 +
 +
    public boolean isShowSmartTagIndicator(int nActionID, String aApplicationName, com.sun.star.frame.XController xController, com.sun.star.lang.Locale aLocale) throws com.sun.star.lang.IllegalArgumentException {
 +
        return false;
 +
    }
 +
}
 +
</source>
 +
 +
==OOo Names Recognizer==
 +
 +
This smart tag component recognizes OOo user names and offeres two actions:
 +
 +
* lookup issuezilla bugs of that user and
 +
* replace the OOo name by the real name.
 +
 +
The list of OOo user names can be edited using the smart tag properties dialog.
 +
 +
You can download the NetBeans project files here: [[Media:ooonamesrecognizer_ooo23.zip]]. Please note that you need to install the [http://wiki.services.openoffice.org/wiki/OpenOffice_NetBeans_Integration OpenOffice.org API Plugin]
 +
 +
==MOSTL Smart Tags==
 +
 +
In some cases you just want to match a list of words or regular expressions and open some URL associated with these words. For such simple smart tag components Microsoft Office provides the possiblity to define a recognizer or an action library with a XML schema. These simple smart tag descriptions are called "Microsoft Office Smart Tag Lists" (MOSTL). Below you can find an example XML description which defines some OOo related terms and some actions involving OOo websites. The XML description is pretty self-explanatory. As mentioned it is also possible to specify regular expressions in order to recognize certain word patterns. If you want to see how regular expressions are defined have a look at this [http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dno2k3ta/html/odc_regex_smarttags_2003.asp site].
 +
 +
<source lang="xml">
 +
<FL:smarttaglist xmlns:FL="http://schemas.microsoft.com/office/smarttags/2003/mostl">
 +
<FL:name>OOo Smart Tags</FL:name>
 +
<FL:lcid>1033</FL:lcid>
 +
<FL:description>OOo Smart Tags</FL:description>
 +
<FL:smarttag type="urn:schemas-openoffice-org:smarttags#ooo">
 +
    <FL:caption>OOo Smart Tags</FL:caption>
 +
    <FL:terms>
 +
        <FL:termlist>OpenOffice.org, Writer, OOo, UNO</FL:termlist>
 +
    </FL:terms>
 +
    <FL:actions>
 +
        <FL:action id="ooo1">
 +
          <FL:caption>OpenOffice.org Homepage</FL:caption>
 +
          <FL:url>http://www.openoffice.org</FL:url>
 +
        </FL:action>
 +
        <FL:action id="ooo2">
 +
          <FL:caption>Download OpenOffice.org</FL:caption>
 +
          <FL:url>http://download.openoffice.org/index.html</FL:url>
 +
        </FL:action>
 +
        <FL:action id="ooo3">
 +
          <FL:caption>Search in OOo Wiki</FL:caption>
 +
          <FL:url>http://wiki.services.openoffice.org/wiki/Special:Search?search={TEXT}&amp;fulltext=Search</FL:url>
 +
        </FL:action>
 +
    </FL:actions>
 +
</FL:smarttag>
 +
</FL:smarttaglist>
 +
</source>
 +
 +
In order to use XML based smart tags with OpenOffice.org a smart tag component was written which implements the Recognizer and Action Library interfaces as described in the sections above. This component parses XML files which comply with the MOSTL schema. The behavior of the recognize and the invokeAction methods is determined by the given XML description. The XML files currently have to reside in a subfolder called "smarttags" in the "share" or "user" folder of your OOo installation.
 +
 +
The source code of the MOSTL Smart Tag component can be found here: [[Media:mostl_ooo23.zip]]. Here is the ready-to-install extension, as usual: use [[Media:mostl_ooo23.oxt]] at your own risk. These are two MOSTL xml files showing you how to use term lists and regular expressions: [[Media:mostl_xmlfiles.zip]].
 +
 +
The MOSTL component depends on the [http://xmlsoft.org/ libxml] library and can be compiled with [http://download.openoffice.org/index.html OpenOffice.org SDK].
 +
 +
=See also=
 +
 +
*[[Constructing_Components|Great tutorial about constucting UNO components]]
 +
*[http://blogs.sun.com/GullFOSS/entry/successful_community_project_smart_tags Blog entry about smart tag project]

Revision as of 01:17, 4 September 2012

Writer Icon.png

Writer Project

Please view the guidelines
before contributing.

Popular Subcategories:

Extension:DynamicPageList (DPL), version 2.3.0 : Warning: No results.

Internal Documentation:

Extension:DynamicPageList (DPL), version 2.3.0 : Warning: No results.

API Documentation:

Ongoing Efforts:

Extension:DynamicPageList (DPL), version 2.3.0 : Warning: No results.

Sw.OpenOffice.org


Introduction

Smart tags have been introduced with MS Office XP to add contextual information to Office documents. The OpenOffice.org smart tag project has been initiated by Jakob Lechner/Fabalabs Software GmbH. OpenOffice.org 2.2 included a first draft of the new smart tag API, for OpenOffice.org 2.3 this API has been enhanced significantly. In order to use this functionality, external UNO components (so-called smart tag libraries) have to be installed. This document explains how to write your own smart tag libraries and how to integrate them into your installation of OpenOffice.org. The necessary interfaces for smart tag libraries currently have the status "unpublished" but will most likely be published in the next version of OpenOffice.org.

Basic Functionality of Smart Tags

Basically smart tags UNO components consist of two parts:

  • A recognizer component
  • An action component

If a recognizer component is installed in OpenOffice.org its recognize() method will be invoked by OpenOffice.org Writer for every paragraph found in the opened document. The recognize method then decides if any of the words has some specific meaning. Recognized words will be underlined violet in OpenOffice.org Writer. Ctrl-click on a recognized smart tag opens the smart tag menu. This is where action libraries come into play. An action library provides actions for recognized words. The captions of available actions are displayed in the smart tag menu. When you click on one entry in the context menu the invokeAction() method of the action library component is called. This method subsequently executes the appropriate action (a simple action might be opening some URL in the browser).

Here is a sceenshot of an example smart tag component which recognizes document property keywords like author, subject, title etc. There is only one action defined. This action inserts the value of the recognized document property into the text document.

Stag screenshot1.gif


The Services

For supporting external smart tag components two new service definitions have been added to offapi:

  • com.sun.star.smarttags.SmartTagRecognizer
  • com.sun.star.smarttags.SmartTagAction

The SmartTagRecognizer service exports the interface XSmartTagRecognizer. Accordingly the service SmartTagAction exports the interface XSmartTagAction.


The Interfaces

Recognizer and action components are collections of smart tags. This means a smart tag component can contain recognizers or actions for different topics, e.g. a smart tag for recognizing email addresses and another one for recognizing dates and times can be packed into one single recognizer component (accordingly actions for both the email and the date smart tag can be combined in one action component).

Next sections explain the interfaces of recognizer and action components in detail.

The Recognizer Interface

For a look at the recognizer interface definition go to this page.

string getName()
Description obtains a name that describes this recognizer component.
Arguments [in] ::com::sun::star::lang::Locale aLocale: Is used for localization of the name.
Return Value the name of the recognizer component.


string getDescription()
Description obtains a detailed description of this recognizer component.
Arguments [in] ::com::sun::star::lang::Locale aLocale: Is used for localization of the description.
Return Value the description of the recognizer component.


long getSmartTagCount()
Description The number of smart tag types supported by this recognizer component.
Arguments None.
Return Value The number of smart tag types supported by this recognizer component.


string getSmartTagName()
Description obtains the name of one specific smart tag type supported by this recognizer component.
Arguments [in] long nSmartTagIndex: Index of the wanted smart tag type.
Return Value the unique name of the smart tag type. Smart tag type names are always in the format of namespaceURI#tagname.


string getSmartTagDownloadURL()
Description obtains the URL that can be used to download new or updated recognizers.
Arguments [in] long nSmartTagIndex: Index of the wanted smart tag type.
Return Value the download URL.


void recognize()
Description recognizes smart tags.
Arguments [in] string aText: The text that should be scanned by the recognizer.
[in] long nStart: Denotes the start position of the region to scan.
[in] long nLength: Denotes the length of the text to scan.
[in] SmartTagRecognizerMode eDataType: This value indicates the type of the passed text.
[in] com::sun::star::lang::Locale aLocale: Is used to indicate the language of the passed text.
[in] com::sun::star::text::XTextMarkup xTextMarkup: This object is used to submit any recognized smart tags to the calling application.
[in] string aApplicationName: A string containing the name of the calling application.
[in] com::sun::star::frame::XController xController: The current controller of the document.
[in] com::sun::star::i18n::XBreakIterator xTokenizer: This can be used to tokenize the string to recognize.
Return Value None.


boolean hasPropertyPage()
Description indicates whether there is a property page for a smart tag type.
Arguments [in] long nSmartTagIndex: Index of the wanted smart tag type.
[in] ::com::sun::star::lang::Locale aLocale: Is used for localization of the property page.
Return Value None.


void displayPropertyPage()
Description launches the property page for a smart tag type.
Arguments [in] long nSmartTagIndex: Index of the wanted smart tag type.
[in] ::com::sun::star::lang::Locale aLocale: Is used for localization of the property page.
Return Value None.


The Action Interface

For a look at the action library interface definition go to this page.

string getName()
Description obtains a name that describes this action component.
Arguments [in] ::com::sun::star::lang::Locale aLocale: Is used for localization of the name.
Return Value the name of the action component.


string getDescription()
Description obtains a detailed description of this action component.
Arguments [in] ::com::sun::star::lang::Locale aLocale: Is used for localization of the description.
Return Value the description of the action component.


long getSmartTagCount()
Description The number of smart tag types supported by this action component.
Arguments None.
Return Value The number of smart tag types supported by this action component.


string getSmartTagName()
Description obtains the name of one specific smart tag type supported by this action component.
Arguments [in] long nSmartTagIndex: Index of the wanted smart tag type.
Return Value the unique name of the smart tag type. Smart tag type names are always in the format of namespaceURI#tagname.


string getSmartTagCaption()
Description obtains the caption of the smart tag type for using in user interfaces.
Arguments [in] long nSmartTagIndex: Index of the wanted smart tag type.
in] ::com::sun::star::lang::Locale aLocale: Is used for localization of the caption.
Return Value the caption associated with the smart tag type.


long getActionCount()
Description obtains the number of actions provided for a specifiy smart tag type.
Arguments [in] string aSmartTagName: Name of the wanted smart tag type. This is one of the names obtained by getSmartTagName()
[in] com::sun::star::frame::XController xController: The current controller of the document.
Return Value the number of actions available for the given smart tag type.


long getActionID()
Description obtains a unique integer identifier for an action.
Arguments [in] string aSmartTagName: Name of the wanted smart tag type. This is one of the names obtained by getSmartTagName()
[in] long nActionIndex: The index of the action for the given smart tag type.
[in] com::sun::star::frame::XController xController: The current controller of the document.
Return Value the unique integer identifier for the requested action.


string getActionCaptionFromID()
Description obtains a caption for a specified action for use in user interfaces.
Arguments [in] long nActionID: The identifier of the requested action.
[in] string aApplicationName: A string containing the name of the calling application.
[in] ::com::sun::star::lang::Locale aLocale: Is used for localization of the caption.
[in] com::sun::star::container::XStringKeyMap xProperties: Contains additional smart tag properties collected by the smart tag recognizer.
[in] string aText: The calling application can pass the text of the smart tag to the action component.
[in] string aXML: A string that is a XML representation of the smart tag.
[in] com::sun::star::frame::XController xController: The current controller of the document.
[in] com::sun::star::text::XTextRange xTarget: A text range representing the smart tag in the document.
Return Value the caption of the requested action.


string getActionNameFromID()
Description obtains a language independant name of an action.
Arguments [in] long nActionID: The identifier of the requested action.
[in] com::sun::star::frame::XController xController: The current controller of the document.
Return Value the language independant name of the specified action.


void invokeAction()
Description invokes an action.
Arguments [in] long nActionID: The identifier of the requested action.
[in] string aApplicationName: A string containing the name of the calling application.
[in] com::sun::star::frame::XController xController: The current controller of the document.
[in] com::sun::star::text::XTextRange xTarget: A text range representing the smart tag in the document.
[in] com::sun::star::container::XStringKeyMap xProperties: Contains additional smart tag properties collected by the smart tag recognizer.
[in] string aText: The calling application can pass the text of the smart tag to the action component.
[in] string aXML: A string that is a XML representation of the smart tag.
[in] ::com::sun::star::lang::Locale aLocale: Is used for localization of the caption.
Return Value None.


boolean isCaptionDynamic()
Description determines whether a caption is dynamic.
Arguments [in] long nActionID: The identifier of the requested action.
[in] string aApplicationName: A string containing the name of the calling application.
[in] ::com::sun::star::lang::Locale aLocale: Is used for localization.
[in] com::sun::star::frame::XController xController: The current controller of the document.
Return Value a boolean indicating whether the caption is dynamic.


boolean isShowSmartTagIndicator()
Description determines whether the smart tag indicator should be visible.
Arguments [in] long nActionID: The identifier of the requested action.
[in] string aApplicationName: A string containing the name of the calling application.
[in] ::com::sun::star::lang::Locale aLocale: Is used for localization.
[in] com::sun::star::frame::XController xController: The current controller of the document.
Return Value a boolean indicating whether the smart tag indicator should be visible.


Smart Tags Step-by-Step Tutorial

First you should make sure that you have all of these at hand:

After you have installed the NetBeans OOo API Plugin, you are offered a new project type „OpenOffice.org component“:

NetBeans1.png


In the next dialog, you are asked for a name and the location of your new project:

NetBeans2.png


After this, you have to choose which service you want to implement. For our example, we implement the com.sun.star.smarttag.SmartTagRecognizer service:

NetBeans3.png


Once you have created the new project, you have to add a SmartTagAction service to your project. For this, go to “File – New File” and add a new “Java UNO Object”:

NetBeans4.png


Choose a name for your action class and pick com.com.sun.star.smarttags.SmartTagAction from the list of services:

NetBeans5.png


Finally the OOo API Plugin creates a skeleton of the implementation. So all that's left to do is implementing the required functions:

NetBeans6.png


The following tables shows the minimal set of function you should to implement. Except from the recognize() and invokeAction() functions, non of these require actual coding:

SmartTagRecognizer Comment
getSmartTagCount() the number of supported smart tag types, usually 1
getSmartTagName(...) returns an internal name for each supported smart tag type
getName(...) returns an UI string for the recognizer component
recognize(...) see below


SmartTagAction Comment
getSmartTagCount() the number of supported smart tag types, usually 1
getSmartTagName(...) returns an internal name for each supported smart tag type
getSmartTagCaption(...) returns the UI name of the new smart tag types
getActionCount(...) the number of provided actions for each smart tag type
getActionID(...) returns an ID for each provided action
getActionCaptionFromID(...) returns an UI string for each provided action
invokeAction(...) see below


Here is some code that shows how the recognize() function can be implemented:

 public void recognize(String aText, int nStart, int nLength, com.sun.star.smarttags.SmartTagRecognizerMode eDataType,  
    com.sun.star.lang.Locale aLocale, com.sun.star.text.XTextMarkup xTextMarkup, String aApplicationName, 
    com.sun.star.frame.XController xController, com.sun.star.i18n.XBreakIterator xTokenizer)
 {
    final int nEndPos = nStart + nLength;
 
    Boundary aWordBounds = xTokenizer.getWordBoundary( aText, nStart, aLocale, WordType.DICTIONARY_WORD, true );
 
    // iterate over all words 
    while ( aWordBounds.startPos < aWordBounds.endPos && aWordBounds.endPos <= nEndPos ) {
        final String aWord = aText.substring( aWordBounds.startPos, aWordBounds.endPos );
 
        // check current word 
        if ( aWord.matchesMyCriteria() ) {
            XStringKeyMap xProps = null;
 
            // pass the smart tag data to the application
            xTextMarkup.commitTextMarkup( TextMarkupType.SMARTTAG,
                                          m_SmartTagType,
                                          aWordBounds.startPos,
                                          aWordBounds.endPos - aWordBounds.startPos,
                                          xProps );
        }
 
        // continue with next word
        aWordBounds = xTokenizer.nextWord( aText, aWordBounds.startPos, aLocale, WordType.DICTIONARY_WORD );
    }
 }

And finally, here is an example for the invokeAcion() function:

 public void invokeAction(int nActionID, String aApplicationName, com.sun.star.frame.XController xController,
    com.sun.star.text.XTextRange xTarget, com.sun.star.container.XStringKeyMap xProperties,
    String aText, String aXML, com.sun.star.lang.Locale aLocale) throws com.sun.star.lang.IllegalArgumentException
 {
    try {
        // get SystemShellExecute to execute URLS
        final XMultiComponentFactory xFact = m_xContext.getServiceManager();
        final Object xObject = xFact.createInstanceWithContext("com.sun.star.system.SystemShellExecute", m_xContext);
        final XSystemShellExecute xSystemShellExecute = (XSystemShellExecute) UnoRuntime.queryInterface(XSystemShellExecute.class, xObject);
        String aURLString = "www.openoffice.org";
        xSystemShellExecute.execute( aURLString, "", com.sun.star.system.SystemShellExecuteFlags.DEFAULTS );
    } catch (Exception ex) {
        ex.printStackTrace();
    }
 }


Once you have implemented all the required functions, it's time to test you implementation. In the context menu of the project, you can either choose to create an oxt package which can be installed using the OpenOffice.org extension manager, or you can even do a live deployment of your extensions and start debugging your code!

And that's it. In the next section you can find some sample implementations that might also give you some hints of how to implement the required functions:

Example Implementations

Here you find some example implementations of smart tag components. They should serve as examples of how to implement your own smart tag components, so don't expect to find full featured, thoroughly tested components.

Document Property Smart Tag

The recognizer identifies document property keywords. The action component offers to replace the smart tag text in the document by the respective value from the document properties.

Recognizer

As described above the recognizer matches document property keywords like title, author, description etc. The matching of scanned words of the current document is done by the Recognize() method as you can see below. This recognizer component contains just one smart tag type. Thus the getSmartTagCount() method returns 1. The name of this recognizer ("Document Property Recognizer") is returned by the method getName().

 package org.openoffice;
 
 import com.sun.star.container.XStringKeyMap;
 import com.sun.star.i18n.Boundary;
 import com.sun.star.i18n.WordType;
 import com.sun.star.lang.XSingleComponentFactory;
 import com.sun.star.lib.uno.helper.Factory;
 import com.sun.star.lib.uno.helper.WeakBase;
 import com.sun.star.registry.XRegistryKey;
 import com.sun.star.text.TextMarkupType;
 import com.sun.star.uno.XComponentContext;
 
 public final class DocumentPropertyRecognizer extends WeakBase
   implements com.sun.star.lang.XServiceInfo,
              com.sun.star.smarttags.XSmartTagRecognizer
 {
    private final XComponentContext m_xContext;
    private static final String m_SmartTagType = "mynamespace#docproperty";
    private static final String m_implementationName = DocumentPropertyRecognizer.class.getName();
    private static final String[] m_serviceNames = {
        "com.sun.star.smarttags.SmartTagRecognizer" };
 
 
    public DocumentPropertyRecognizer( XComponentContext context ) {
        m_xContext = context;
    };
 
    public static XSingleComponentFactory __getComponentFactory( String sImplementationName ) {
        XSingleComponentFactory xFactory = null;
 
        if ( sImplementationName.equals( m_implementationName ) )
            xFactory = Factory.createComponentFactory(DocumentPropertyRecognizer.class, m_serviceNames);
        return xFactory;
    }
 
    public static boolean __writeRegistryServiceInfo( XRegistryKey xRegistryKey ) {
        return Factory.writeRegistryServiceInfo(m_implementationName,
                                                m_serviceNames,
                                                xRegistryKey);
    }
 
    // com.sun.star.lang.XServiceInfo:
    public String getImplementationName() {
         return m_implementationName;
    }
 
    public boolean supportsService( String sService ) {
        int len = m_serviceNames.length;
 
        for( int i=0; i < len; i++) {
            if (sService.equals(m_serviceNames[i]))
                return true;
        }
        return false;
    }
 
    public String[] getSupportedServiceNames() {
        return m_serviceNames;
    }
 
    // com.sun.star.lang.XInitialization:
    public void initialize(Object[] aArguments) throws com.sun.star.uno.Exception {
    }
 
    // com.sun.star.smarttags.XSmartTagRecognizer:
    public int getSmartTagCount() {
        return 1;
    }
 
    public String getName(com.sun.star.lang.Locale aLocale) {
        return new String("Document Property Recognizer");
    }
 
    public String getDescription(com.sun.star.lang.Locale aLocale) {
        return new String();
    }
 
    public String getSmartTagName(int nSmartTagIndex) throws com.sun.star.lang.IndexOutOfBoundsException {
        return m_SmartTagType;
    }
 
    public String getSmartTagDownloadURL(int nSmartTagIndex) throws com.sun.star.lang.IndexOutOfBoundsException {
        return new String();
    }
 
    public void recognize(String aText, int nStart, int nLength, com.sun.star.smarttags.SmartTagRecognizerMode eDataType, 
        com.sun.star.lang.Locale aLocale, com.sun.star.text.XTextMarkup xTextMarkup, String aApplicationName, 
        com.sun.star.frame.XController xController, com.sun.star.i18n.XBreakIterator xTokenizer) {
        final int nEndPos = nStart + nLength;
 
        Boundary aWordBounds = xTokenizer.getWordBoundary( aText, nStart, aLocale, WordType.DICTIONARY_WORD, true );
 
        while ( aWordBounds.startPos < aWordBounds.endPos && aWordBounds.endPos <= nEndPos ) {
            final String aWord = aText.substring( aWordBounds.startPos, aWordBounds.endPos );
            if ( aWord.equalsIgnoreCase("Title") || aWord.equalsIgnoreCase("Author") ||
                 aWord.equalsIgnoreCase("Keywords") || aWord.equalsIgnoreCase("Description") ) {
                XStringKeyMap xProps = null;
                xTextMarkup.commitTextMarkup( TextMarkupType.SMARTTAG,
                                              m_SmartTagType,
                                              aWordBounds.startPos,
                                              aWordBounds.endPos - aWordBounds.startPos,
                                              xProps );
            }
 
            aWordBounds = xTokenizer.nextWord( aText, aWordBounds.startPos, aLocale, WordType.DICTIONARY_WORD );
        }
    }
 
    public boolean hasPropertyPage(int nSmartTagIndex, com.sun.star.lang.Locale aLocale) throws com.sun.star.lang.IndexOutOfBoundsException {
        return false;
    }
 
    public void displayPropertyPage(int nSmartTagIndex, com.sun.star.lang.Locale aLocale) throws com.sun.star.lang.IndexOutOfBoundsException {
    }
 
 }

Action

Implementing an action library is quite similar to implementing the recognizer. Of course you have to support the action service instead of the recongizer service. Since this component just provides actions for one smart tag type the getSmartTagCount() method returns 1. And for this single smart tag the component just provides one action, as you can see in the invokeAction() method. This action retrieves the document properties value and inserts it into the document.

 package org.openoffice;
 
 import com.sun.star.beans.XPropertySet;
 import com.sun.star.document.XDocumentInfo;
 import com.sun.star.document.XDocumentInfoSupplier;
 import com.sun.star.frame.XModel;
 import com.sun.star.lang.XSingleComponentFactory;
 import com.sun.star.lib.uno.helper.Factory;
 import com.sun.star.lib.uno.helper.WeakBase;
 import com.sun.star.registry.XRegistryKey;
 import com.sun.star.uno.UnoRuntime;
 import com.sun.star.uno.XComponentContext;
 
 public final class DocumentPropertyAction extends WeakBase
   implements com.sun.star.lang.XServiceInfo,
              com.sun.star.smarttags.XSmartTagAction
 {
    private final XComponentContext m_xContext;
    private static final String m_implementationName = DocumentPropertyAction.class.getName();
    private static final String[] m_serviceNames = {
        "com.sun.star.smarttags.SmartTagAction" };
 
    public DocumentPropertyAction( XComponentContext context ) {
        m_xContext = context;
    };
 
    public static XSingleComponentFactory __getComponentFactory( String sImplementationName ) {
        XSingleComponentFactory xFactory = null;
 
        if ( sImplementationName.equals( m_implementationName ) )
            xFactory = Factory.createComponentFactory(DocumentPropertyAction.class, m_serviceNames);
        return xFactory;
    }
 
    public static boolean __writeRegistryServiceInfo( XRegistryKey xRegistryKey ) {
        return Factory.writeRegistryServiceInfo(m_implementationName,
                                                m_serviceNames,
                                                xRegistryKey);
    }
 
    // com.sun.star.lang.XServiceInfo:
    public String getImplementationName() {
         return m_implementationName;
    }
 
    public boolean supportsService( String sService ) {
        int len = m_serviceNames.length;
 
        for( int i=0; i < len; i++) {
            if (sService.equals(m_serviceNames[i]))
                return true;
        }
        return false;
    }
 
    public String[] getSupportedServiceNames() {
        return m_serviceNames;
    }
 
    // com.sun.star.lang.XInitialization:
    public void initialize(Object[] aArguments) throws com.sun.star.uno.Exception {
    }
 
    // com.sun.star.smarttags.XSmartTagAction:
    public int getSmartTagCount() {
        return 1;
    }
 
    public String getName(com.sun.star.lang.Locale aLocale) {
        return new String();
    }
 
    public String getDescription(com.sun.star.lang.Locale aLocale) {
        return new String();
    }
 
    public String getSmartTagName(int nSmartTagIndex) throws com.sun.star.lang.IndexOutOfBoundsException {
        return new String("mynamespace#docproperty");
    }
 
    public String getSmartTagCaption(int nSmartTagIndex, com.sun.star.lang.Locale aLocale) throws com.sun.star.lang.IndexOutOfBoundsException {
        return new String("Document Property");
    }
 
    public int getActionCount(String aSmartTagName, com.sun.star.frame.XController xController) {
        return 1;
    }
 
    public int getActionID(String aSmartTagName, int nActionIndex, com.sun.star.frame.XController xController) throws com.sun.star.lang.IllegalArgumentException {
        return 500 + nActionIndex;
    }
 
    public String getActionCaptionFromID(int nActionID, String aApplicationName, com.sun.star.lang.Locale aLocale, com.sun.star.container.XStringKeyMap xProperties, String aText, String aXML, com.sun.star.frame.XController xController, com.sun.star.text.XTextRange xTarget) throws com.sun.star.lang.IllegalArgumentException {
        return new String("Replace with value from document properties");
    }
 
    public String getActionNameFromID(int nActionID, com.sun.star.frame.XController xController) throws com.sun.star.lang.IllegalArgumentException {
        return new String();
    }
 
    public void invokeAction(int nActionID, String aApplicationName, com.sun.star.frame.XController xController, com.sun.star.text.XTextRange xTarget, com.sun.star.container.XStringKeyMap xProperties, String aText, String aXML, com.sun.star.lang.Locale aLocale) throws com.sun.star.lang.IllegalArgumentException {
        XModel xModel = xController.getModel();
        XDocumentInfoSupplier xDocInfoSupplier = (XDocumentInfoSupplier) UnoRuntime.queryInterface(XDocumentInfoSupplier.class, xModel);  
        XDocumentInfo xDocInf = xDocInfoSupplier.getDocumentInfo();
        XPropertySet xProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xDocInf);
        try {
            String aValue = (String)xProps.getPropertyValue(xTarget.getString());
            xTarget.setString(aValue);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
 
    public boolean isCaptionDynamic(int nActionID, String aApplicationName, com.sun.star.frame.XController xController, com.sun.star.lang.Locale aLocale) throws com.sun.star.lang.IllegalArgumentException {
        return false;
    }
 
    public boolean isShowSmartTagIndicator(int nActionID, String aApplicationName, com.sun.star.frame.XController xController, com.sun.star.lang.Locale aLocale) throws com.sun.star.lang.IllegalArgumentException {
        return false;
    }
 }

OOo Names Recognizer

This smart tag component recognizes OOo user names and offeres two actions:

  • lookup issuezilla bugs of that user and
  • replace the OOo name by the real name.

The list of OOo user names can be edited using the smart tag properties dialog.

You can download the NetBeans project files here: Media:ooonamesrecognizer_ooo23.zip. Please note that you need to install the OpenOffice.org API Plugin

MOSTL Smart Tags

In some cases you just want to match a list of words or regular expressions and open some URL associated with these words. For such simple smart tag components Microsoft Office provides the possiblity to define a recognizer or an action library with a XML schema. These simple smart tag descriptions are called "Microsoft Office Smart Tag Lists" (MOSTL). Below you can find an example XML description which defines some OOo related terms and some actions involving OOo websites. The XML description is pretty self-explanatory. As mentioned it is also possible to specify regular expressions in order to recognize certain word patterns. If you want to see how regular expressions are defined have a look at this site.

 <FL:smarttaglist xmlns:FL="http://schemas.microsoft.com/office/smarttags/2003/mostl">
 <FL:name>OOo Smart Tags</FL:name> 
 <FL:lcid>1033</FL:lcid>
 <FL:description>OOo Smart Tags</FL:description>
 <FL:smarttag type="urn:schemas-openoffice-org:smarttags#ooo">
    <FL:caption>OOo Smart Tags</FL:caption>
    <FL:terms>
        <FL:termlist>OpenOffice.org, Writer, OOo, UNO</FL:termlist>
    </FL:terms>
    <FL:actions>
        <FL:action id="ooo1"> 
          <FL:caption>OpenOffice.org Homepage</FL:caption>
          <FL:url>http://www.openoffice.org</FL:url>
        </FL:action>
        <FL:action id="ooo2"> 
          <FL:caption>Download OpenOffice.org</FL:caption>
          <FL:url>http://download.openoffice.org/index.html</FL:url>
        </FL:action>
        <FL:action id="ooo3"> 
          <FL:caption>Search in OOo Wiki</FL:caption>
          <FL:url>http://wiki.services.openoffice.org/wiki/Special:Search?search={TEXT}&amp;fulltext=Search</FL:url>
        </FL:action>
    </FL:actions>
 </FL:smarttag>
 </FL:smarttaglist>

In order to use XML based smart tags with OpenOffice.org a smart tag component was written which implements the Recognizer and Action Library interfaces as described in the sections above. This component parses XML files which comply with the MOSTL schema. The behavior of the recognize and the invokeAction methods is determined by the given XML description. The XML files currently have to reside in a subfolder called "smarttags" in the "share" or "user" folder of your OOo installation.

The source code of the MOSTL Smart Tag component can be found here: Media:mostl_ooo23.zip. Here is the ready-to-install extension, as usual: use Media:mostl_ooo23.oxt at your own risk. These are two MOSTL xml files showing you how to use term lists and regular expressions: Media:mostl_xmlfiles.zip.

The MOSTL component depends on the libxml library and can be compiled with OpenOffice.org SDK.

See also

Personal tools