Hi API-ML,

due to your help with the menubar, I used the same for toolbars.

Greetings, Tobias
<?xml version="1.0"?>
<!--
$RCSfile: $
last change: $Revision: $ $Author: $ $Date: $

(c)2003 by the copyright holders listed with the author-tags.
If no explicit copyright holder is mentioned with a certain author,
the author him-/herself is the copyright holder. All rights reserved.

Public Documentation License Notice:

The contents of this Documentation are subject to the
Public Documentation License Version 1.0 (the "License");
you may only use this Documentation if you comply with
the terms of this License. A copy of the License is
available at http://www.openoffice.org/licenses/PDL.html

The Original Documentation can be found in the CVS archives
of openoffice.org at the place specified by RCSfile: in this header.

The Initial Writer(s) of the Original Documentation are listed
with the author-tags below.

The Contributor(s) are listed with the author-tags below
without the marker for being an initial author.

All Rights Reserved.
-->

<snippet language="Java" application="Database">

<keywords>
	<keyword>Toolbar</keyword>
	<keyword>open document</keyword>
	<keyword>start openoffice</keyword>
	<keyword>transient</keyword>
</keywords>

<authors>
	<author id="tobiaskrais" initial="false" email="[EMAIL PROTECTED]">Tobias Krais</author>
</authors>

<question heading="Open Document and Transient Remove Toolbar entries">How to start OpenOffice, load a document and remove toolbar entries transient?
</question>

<answer>
<p>This code snippet bootstraps OpenOffice, loads a document, gets </p>
<p>the active toolbars, searches it and removes the searched toolbar</p>
<p>icons.</p>
<listing>package de.twc.oocom.snippets;


import java.io.File;
import java.util.Vector;

import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.bridge.UnoUrlResolver;
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.comp.helper.BootstrapException;
import com.sun.star.container.XIndexAccess;
import com.sun.star.container.XIndexContainer;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XFrame;
import com.sun.star.frame.XLayoutManager;
import com.sun.star.frame.XStorable;
import com.sun.star.io.IOException;
import com.sun.star.lang.EventObject;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.IndexOutOfBoundsException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.ui.XUIElement;
import com.sun.star.ui.XUIElementSettings;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.util.CloseVetoException;
import com.sun.star.util.XCloseListener;
import com.sun.star.util.XCloseable;

public class TemporaryRemoveToolbarEntry {
    
    public TemporaryRemoveToolbarEntry(){
        // Empty Constructor for OOComNG
    }
    
    // The file that should be processed, e.g. &quot;/tmp/hello_world.ods&quot;
    private String source_File = &quot;/home/tobias/test.odt&quot;;
    
    // Value is not necessary.
    private String ooport = &quot;9000&quot;;
    
    // OpenOffice Desktop
    Object desktop = null;
    
    /**
     * Main method.
     * 
     * @param args
     */
    public static void main(String[] args){
        
        TemporaryRemoveToolbarEntry myOOComNG = new TemporaryRemoveToolbarEntry();
        myOOComNG.viewDocument();
    }
    
    /**
     * This method sets document properties, opens the document and personalizes
     * the toolbars.
     */
    private void viewDocument()
    {
        // Construct the document properties
        PropertyValue[] myProperties = new PropertyValue[1];
        PropertyValue xProperty = new PropertyValue();
        xProperty.Name = &quot;ReadOnly&quot;;
        xProperty.Value = new Boolean(false);
        myProperties[0] = xProperty;
        
        // Open the document
        XComponent openDocument = openDocument(myProperties);
        
        try
        {
            // Get Layout Manager
            XLayoutManager xLayoutManager = getLayoutManager(desktop);
            
            // Personalize toolbars
            changeToolbars(xLayoutManager, &quot;.uno:Save&quot;, &quot;remove&quot;);
        }
        catch (Exception e)
        {
            System.out.println(&quot;Cannot personalize toolbars:&quot;);
            System.out.println(e.getLocalizedMessage());
        }
        
        // initial close listener
        XCloseable close = (XCloseable)UnoRuntime.queryInterface(
                com.sun.star.util.XCloseable.class, openDocument);
        
        final long last_modified_old = new File(source_File).lastModified();
        
        close.addCloseListener(new XCloseListener() {
            public void queryClosing(EventObject arg0, boolean arg1)
            throws CloseVetoException {
                File file = new File(source_File);
                // TODO Auto-generated method stub
                long last_modified = file.lastModified();
                if (last_modified != last_modified_old) {
                    System.exit(0);
                } else {
                    // XModifiable modi = openDocument.interfaces.getXModifiable();
                    // System.out.println(modi.isModified());
                    System.exit(1);
                }
            }
            
            public void notifyClosing(EventObject arg0) {
                // TODO Auto-generated method stub
            }
            
            public void disposing(EventObject arg0) {
                // TODO Auto-generated method stub
            }
        });
        
        // wait for closing document
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }
    }
    
    /**
     * This method return a Layout Manager of an opened OpenOffice.
     * 
     * @param desktop
     * @return
     */
    public XLayoutManager getLayoutManager(Object desktop)
    {
        XDesktop xDesktop = (XDesktop)
        UnoRuntime.queryInterface(XDesktop.class, desktop);
        XFrame xFrame = xDesktop.getCurrentFrame();
        
        XPropertySet xps = (XPropertySet)
        UnoRuntime.queryInterface(XPropertySet.class, xFrame);
        
        XLayoutManager xLayoutManager = null;
        try 
        {
            xLayoutManager = (XLayoutManager)
            UnoRuntime.queryInterface(XLayoutManager.class,
                    xps.getPropertyValue(&quot;LayoutManager&quot;));
        }
        catch (Exception e)
        {
            System.out.println(&quot;Cannot get Layout Manager:&quot;);
            System.out.println(e.getLocalizedMessage());
        }
        return xLayoutManager;
    }
    
    /**
     * This method removes the &quot;Save&quot; items from OpenOffice menus. Changes are
     * transient.
     * 
     * @param xLayoutManager
     * @param CommandURL
     * @param action
     * @throws Exception
     */
    public void changeToolbars(XLayoutManager xLayoutManager,
            String CommandURL,
            String action)
    throws Exception
    {
        final String[] toolbars = { &quot;private:resource/toolbar/alignmentbar&quot;,
                &quot;private:resource/toolbar/arrowshapes&quot;,
                &quot;private:resource/toolbar/basicshapes&quot;,
                &quot;private:resource/toolbar/calloutshapes&quot;,
                &quot;private:resource/toolbar/colorbar&quot;,
                &quot;private:resource/toolbar/drawbar&quot;,
                &quot;private:resource/toolbar/drawobjectbar&quot;,
                &quot;private:resource/toolbar/extrusionobjectbar&quot;,
                &quot;private:resource/toolbar/fontworkobjectbar&quot;,
                &quot;private:resource/toolbar/fontworkshapetypes&quot;,
                &quot;private:resource/toolbar/formatobjectbar&quot;,
                &quot;private:resource/toolbar/formcontrols&quot;,
                &quot;private:resource/toolbar/formdesign&quot;,
                &quot;private:resource/toolbar/formsfilterbar&quot;,
                &quot;private:resource/toolbar/formsnavigationbar&quot;,
                &quot;private:resource/toolbar/formsobjectbar&quot;,
                &quot;private:resource/toolbar/formtextobjectbar&quot;,
                &quot;private:resource/toolbar/fullscreenbar&quot;,
                &quot;private:resource/toolbar/graphicobjectbar&quot;,
                &quot;private:resource/toolbar/insertbar&quot;,
                &quot;private:resource/toolbar/insertcellsbar&quot;,
                &quot;private:resource/toolbar/insertobjectbar&quot;,
                &quot;private:resource/toolbar/mediaobjectbar&quot;,
                &quot;private:resource/toolbar/moreformcontrols&quot;,
                &quot;private:resource/toolbar/previewbar&quot;,
                &quot;private:resource/toolbar/standardbar&quot;,
                &quot;private:resource/toolbar/starshapes&quot;,
                &quot;private:resource/toolbar/symbolshapes&quot;,
                &quot;private:resource/toolbar/textobjectbar&quot;,
                &quot;private:resource/toolbar/toolbar&quot;,
        &quot;private:resource/toolbar/viewerbar&quot;};
        
        for (int i = 0; i &lt; toolbars.length; i++)
        {
            if (xLayoutManager.getElement(toolbars[i]) != null)
            {
                // Getting the toolbar
                XUIElement myToolbar 
                = xLayoutManager.getElement(toolbars[i]);
                
                // Getting the toolbar settings
                XUIElementSettings myToolBarSettings = (XUIElementSettings)
                UnoRuntime.queryInterface(XUIElementSettings.class,
                        myToolbar);
                // Casting the settings into a container to be able to get the
                // properties
                XIndexContainer myToolBarSettingsContainer = (XIndexContainer)
                UnoRuntime.queryInterface(
                        XIndexContainer.class,
                        myToolBarSettings.getSettings(true));
                
                // Creating a Vector containing all toolbars with a &quot;Save&quot; item
                Vector foundSaveToolbarItems = searchXIndexContainerForItem(
                        CommandURL,
                        myToolBarSettingsContainer,
                        new Vector());
                if(action.equals(&quot;remove&quot;))
                {
                    // Remove the toolbar items
                    removeXIndexContainerItems(foundSaveToolbarItems);
                }
                else
                {
                    System.out.println(&quot;Unknown action: &apos;&quot; + action + &quot;&apos;&quot;);
                }
                
                // Make changes only transient (temporary).
                com.sun.star.beans.XPropertySet xPropSet = (XPropertySet)
                UnoRuntime.queryInterface(XPropertySet.class, myToolbar);
                xPropSet.setPropertyValue(&quot;Persistent&quot;, new Boolean(false));
                
                // Apply changes
                myToolBarSettings.setSettings(myToolBarSettingsContainer);
            }
        }
    }
    
    /**
     * This method bootstraps a OpenOffice and returns it&apos;s Desktop.
     * 
     * @return
     */
    public Object bootstrapOpenOffice()
    {
        XComponentContext xRemoteContext = null;
        try
        {
            // Connect or start a OpenOffice instance
            xRemoteContext = Bootstrap.bootstrap();
            System.out.println(&quot;Connected to a running OpenOffice ...&quot;);
        }
        catch (BootstrapException e)
        {
            System.out.println(&quot;Unable to start OpenOffice. Starter says:&quot;);
            System.out.println(e.getLocalizedMessage());
        }
        // get OO desktop
        XMultiComponentFactory xRemoteServiceManager 
        = xRemoteContext.getServiceManager();
        Object desktop = null;
        try
        {
            desktop = xRemoteServiceManager.createInstanceWithContext(
                    &quot;com.sun.star.frame.Desktop&quot;, xRemoteContext
            );
        }
        catch (Exception e)
        {
            System.out.println(&quot;OpenOffice started, but can&apos;t get Desktop:&quot;);
            System.out.println(e.getLocalizedMessage());
        }
        
        return desktop;
    }
    
    /**
     * This method connects to a running OpenOffice or, if none found starts it.
     * Afterwards a specified document is loaded. 
     * 
     * @param documentProperties
     * @return
     */
    private XComponent openDocument(PropertyValue[] documentProperties)
    {
        // Getting a running OpenOffice
        desktop = bootstrapOpenOffice();
        
        // Query the XComponentLoader interface from the desktop
        XComponentLoader xComponentLoader = (XComponentLoader)
        UnoRuntime.queryInterface(XComponentLoader.class, desktop);
        
        // Load a given document
        XComponent openedDocument = null;
        try
        {
            openedDocument = xComponentLoader.loadComponentFromURL(
                    &quot;file://&quot; + source_File,        // File folder and name
                    &quot;_blank&quot;,                       // New windos
                    Integer.parseInt(ooport),       // Port OO listens on
                    documentProperties);            // Special properties
        }
        catch(Exception e)
        {
            System.out.println(&quot;OpenOffice runs, but error opening document:&quot;);
            System.out.println(e.getLocalizedMessage());
        }
        
        if (openedDocument == null) {
            System.err.println(&quot;I found the document but cannot open it...&quot;);
            System.exit(-4);
        }
        return openedDocument;
    }
    
    /**
     * Method that removes the given menu items. The given Vector contains a
     * XIndexContainer at first position (the menu containing the Item to remove)
     * and an Integer at second position (the item number of the item to remove.
     * The changes are transient (temporary).
     * 
     * @param itemsToRemove
     * @throws IndexOutOfBoundsException
     * @throws WrappedTargetException
     */
    public void removeXIndexContainerItems(Vector itemsToRemove) throws
    IndexOutOfBoundsException,
    WrappedTargetException
    {
        // Starting with the last Element, because removing changes item index
        for (int i = itemsToRemove.size() -1; i &gt;= 0; i--)
        {
            Vector thisVectorItem = (Vector)itemsToRemove.elementAt(i);
            XIndexContainer thisMenuContainer = (XIndexContainer)
            thisVectorItem.elementAt(0);
            Integer menuPosition = (Integer)thisVectorItem.elementAt(1);
            
            // remove the item, but settings must be set to make it visible
            thisMenuContainer.removeByIndex(menuPosition.intValue());
        }
    }
    
    /**
     * Method that searches menus and its submenus for the &quot;CommandURL&quot;
     * property. The returned Vector consists of Vectors. Each contained Vector
     * has two values. The first gives the XIndexContainer where the searched
     * menu item was found, the second is an Integer that tells the position
     * where the menu item was found.   
     * 
     * @param myCommandURL
     * @param myMenuContainer
     * @param foundMenuItems
     * @return
     * @throws IllegalArgumentException
     * @throws IndexOutOfBoundsException
     * @throws WrappedTargetException
     */
    public Vector searchXIndexContainerForItem(String myCommandURL,
            XIndexContainer myMenuContainer, Vector foundMenuItems)
    throws IllegalArgumentException,
    IndexOutOfBoundsException,
    WrappedTargetException  {
        
        if(myMenuContainer != null) {
            for(int g = 0; g &lt; myMenuContainer.getCount(); g++) {
                // Getting the properties of the given container
                PropertyValue[] gMenuItem = (PropertyValue[])
                com.sun.star.uno.AnyConverter.toObject(
                        PropertyValue[].class,
                        myMenuContainer.getByIndex(g));
                for(int h = 0; h &lt; gMenuItem.length; h++)
                {
                    if(gMenuItem[h].Name.equals(&quot;CommandURL&quot;))
                    {
                        if(gMenuItem[h].Value.equals(myCommandURL))
                        {
                            Vector thisMenuItem = new Vector();
                            thisMenuItem.addElement(myMenuContainer);
                            thisMenuItem.addElement(g);
                            foundMenuItems.addElement(thisMenuItem);
                            break;
                        }
                    }
                    else if(gMenuItem[h].Name.equals(&quot;ItemDescriptorContainer&quot;))
                    {
                        XIndexAccess subMenuAccess = (XIndexAccess)
                        com.sun.star.uno.AnyConverter.toObject(
                                XIndexAccess.class,
                                gMenuItem[h].Value);
                        XIndexContainer subMenuContainer = (XIndexContainer)
                        UnoRuntime.queryInterface(
                                XIndexContainer.class, subMenuAccess);
                        if(subMenuAccess != null)
                        {
                            searchXIndexContainerForItem(myCommandURL,
                                    subMenuContainer,
                                    foundMenuItems);
                        }
                    }
                }
            }
        }
        return foundMenuItems;
    }
}</listing>
</answer>

<versions>
</versions>

<operating-systems>
<operating-system name="All"/>
</operating-systems>

<changelog>
</changelog>

</snippet>

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to