Package com.CompPad

Source Code of com.CompPad.AddOn$AddonListener

/* Copyright 2011 Toby D. Rule

  This file is part of CompPad, an OpenOffice extension to provide live
  mathematical and engineering calculations within a Writer document.

    CompPad is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    CompPad is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with CompPad.  If not, see <http://www.gnu.org/licenses/>.
*/
package com.CompPad;
import com.sun.star.awt.KeyEvent;
import com.sun.star.awt.XUserInputInterception;
import java.util.Arrays;
import com.sun.star.beans.UnknownPropertyException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.uno.XInterface;
import com.sun.star.frame.FrameAction;
import com.sun.star.frame.FrameActionEvent;
import com.sun.star.frame.XLayoutManager;
import com.sun.star.awt.XWindow;
import com.sun.star.awt.XWindow2;
import com.sun.star.beans.NamedValue;
import com.sun.star.beans.PropertyValue;
import com.sun.star.frame.ControlEvent;
import com.sun.star.frame.XController;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XDispatch;
import com.sun.star.frame.XDispatchProvider;
import com.sun.star.frame.XFrame;
import com.sun.star.frame.XModel;
import com.sun.star.lang.EventObject;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.lib.uno.helper.Factory;
import com.sun.star.lang.XSingleComponentFactory;
import com.sun.star.registry.XRegistryKey;
import com.sun.star.lib.uno.helper.WeakBase;
import com.sun.star.text.XTextDocument;
import com.sun.star.util.XURLTransformer;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.text.XTextContent;
import com.sun.star.beans.XPropertySet;
import com.sun.star.document.XEmbeddedObjectSupplier;
import com.sun.star.frame.ControlCommand;
import com.sun.star.frame.FeatureStateEvent;
import com.sun.star.lang.XTypeProvider;
import com.sun.star.text.TextContentAnchorType;
import com.sun.star.text.XTextRange;
import com.sun.star.text.XTextViewCursor;
import com.sun.star.text.XTextViewCursorSupplier;
import com.sun.star.uno.Any;
import com.sun.star.util.URL;
import com.sun.star.view.XSelectionSupplier;
import java.awt.Event;
import java.util.Hashtable;
import java.util.ArrayList;

class myHandler extends java.util.logging.Handler{

    @Override
    public void publish(LogRecord record) {
        System.out.println("Logger: "+record.getMessage());
    }

    @Override
    public void flush() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void close() throws SecurityException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}


public final class AddOn extends WeakBase
   implements com.sun.star.lang.XServiceInfo,
              com.sun.star.frame.XDispatchProvider,
              com.sun.star.lang.XInitialization,
              com.sun.star.frame.XDispatch,
              com.sun.star.frame.XControlNotificationListener
{
    private static final String  loggerName = "com.CompPad";
    static Logger myLogger;
    private final XComponentContext m_xContext;
    private com.sun.star.frame.XFrame m_xFrame;
    /* new addon for each frame */
    private static Hashtable<XFrame,AddOn> addOns;
    /* This contains new addons before they are initialized */

    /* Here are some fields that are related to the current selection */
    private Object lastSelection;
    private boolean formulaSelected=false;
    private boolean selectionListenerActive = true;
    private XController controller;
    private String fieldText="";
    private boolean solving=false;
    // hashtable of selectionChangeListeners for each frame
//    private Hashtable<XFrame,AddonListener>
//            selectionChangeListeners;
    private AddonListener selectionChangeListener;
    private com.sun.star.frame.XStatusListener editFieldListener;
    private static boolean keysIntercepted = false;
    private static final String m_implementationName = AddOn.class.getName();
    private static final String[] m_serviceNames = {
        "com.sun.star.frame.ProtocolHandler" };
//    private XFrame xFrame;
    // static initialization block
    static {
            // Set up logger
            Logger.getLogger(loggerName).addHandler(new myHandler());
            myLogger = Logger.getLogger(loggerName);
            myLogger.setLevel(Level.ALL);
    }
    public AddOn( XComponentContext context )
    {
        m_xContext = context;
        myLogger.log(Level.FINE, "Addon Constructor, context: "+ context);
    };


    public static boolean hasFrame(XFrame xFrame){
        if (AddOn.addOns==null){
            return false;
        }
        if (AddOn.addOns.containsKey(xFrame)){
            return true;
        }
        else{
            return false;
        }
    }
    public static AddOn getInstance(XFrame xFrame){
        return AddOn.addOns.get(xFrame);
    }
    public synchronized void controlEvent(ControlEvent arg0) {
//        System.out.println ("controlEvent: " + arg0.aURL.Protocol+" "
//                + arg0.aURL.Path + arg0.aURL.Name + " "+  arg0.Event+"; "
//                + arg0.aInformation[0].Name + "; " +arg0.aInformation[0].Value
//                + "; " + arg0.aURL.Complete);
//        System.out.println("Information: "+Arrays.asList(arg0.aInformation));
        if (arg0.aInformation[0].Name.equals("Source") && keysIntercepted == false){
            myLogger.fine("Adding keyHandler");
            ((XUserInputInterception)UnoRuntime.queryInterface(
                    XUserInputInterception.class,
                    ((XFrame)(((Any)arg0.aInformation[0].Value).getObject())).getController()))
                    .addKeyHandler(selectionChangeListener);
            keysIntercepted=true;
        }


        if ( arg0.aURL.Protocol.equals("com.CompPad.addon:") )
            {
                if (arg0.aURL.Path.equals("editExprField")) {
                    if (arg0.Event.equals("TextChanged")){
                        /* Set text of editField */
                        fieldText = (String)arg0.aInformation[0].Value;
                    }
                    if (arg0.Event.equals("FocusLost")){
                        /* Update the formula */
                        myLogger.log(Level.FINE,
                                "FocusLost");
                        if (formulaSelected){
                            try{
                                updateExpression(fieldText);
                            }
                            catch(java.lang.Exception ex){
                                myLogger.log(Level.WARNING,
                                        "updateExpression Error "+ ex.getMessage());
                            }
                        }
                        if (!selectionListenerActive){
                            setFieldText("");
                        }

                    }
                    if (arg0.Event.equals("FocusSet")){
                        // focus set on formula edit box.
                        // If !selectionListenerActive, then update text
                        // when someone clicks on it.
                        myLogger.log(Level.FINE, "FocusSet");
                        if (!selectionListenerActive){
                            myLogger.log(Level.FINE, "selectionListenerActive==false: Setting editField text");
                            /* Get the embedded component */
                            XModel xMod = m_xFrame.getController().getModel();
                            Object oSelect = xMod.getCurrentSelection();
                            lastSelection = oSelect;
                            XPropertySet xPS = (XPropertySet)UnoRuntime
                                    .queryInterface(XPropertySet.class, oSelect);
                            //    oSelect = oController.getSelection()
                            if (xPS!=null){


                                com.sun.star.lang.XComponent xc =
                                        ((XEmbeddedObjectSupplier)UnoRuntime.queryInterface(
                                        XEmbeddedObjectSupplier.class,oSelect))
                                        .getEmbeddedObject();
                                // Got a couple of properties to check here so try/catch
                                try{
                                    String clsid = (String) xPS.getPropertyValue("CLSID");
                                    if ( clsid.equals(com.CompPad.OOO.OOODocument.CLSID_FORMULA)){

                                        // get xPS interface for component
                                        XPropertySet xPSc = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class, xc);
                                        // get the formula text property
                                        String formulaText = (String)(xPSc.getPropertyValue("Formula"));
                                        myLogger.log(
                                                Level.FINE, "Formula Selected, formulaText="+formulaText);
                                        setFieldText(formulaText);
                                        formulaSelected=true;
                                        myLogger.log(Level.FINE,"formulaSelected=true");
                                    }
                                    else{
                                        // Otherwise, a formula is not selected
                                        formulaSelected=false;
                                        myLogger.log(Level.FINE,"formulaSelected=false");
                                    }
                                }
                                catch (UnknownPropertyException ex){
                                    myLogger.log(
                                            Level.FINE,"Unkown Property Exception");
                                }
                                catch(Exception ex){
                                    myLogger.log(
                                            Level.FINE,"Exception "+ex.getMessage());
                                }

                            }
                            else{
                                // Otherwise, a formula is not selected
                                formulaSelected=false;
                                myLogger.log(Level.FINE,"formulaSelected=false");
                            }
                        }

                    }

                }
                    // C++ example gets the editExprField dispatch heretialize
            }

    }
    /* addon factory inner class */
    static class AddonFactory implements XSingleComponentFactory{
        public AddonFactory(){

        }


//        public Object createInstanceWithContext(XComponentContext arg0) throws Exception {
//            /* Doesn't really matter what context is.  What matters is what
//             * frame is used to initialize it. Don't try to do anything
//             * with it until it is initialized!!! */
//            XFrame xFrame = getFrameFromContext(arg0);
//            System.out.println("createInstanceWithContext, XFrame: "+xFrame);
//            if (addOns==null){
//                addOns = new Hashtable<XFrame,AddOn>();
//            }
//            if ( ! addOns.containsKey(xFrame)){
//                addOns.put(xFrame, new AddOn(arg0));
//            }
//            System.out.println("      addons: "+addOns.size());
//            return addOns.get(xFrame);
//        }
        public Object createInstanceWithContext(XComponentContext arg0) throws Exception {
            return new AddOnAdapter(arg0);
        }

        public Object createInstanceWithArgumentsAndContext(Object[] object, XComponentContext context) throws Exception {
            XFrame xFrame = (com.sun.star.frame.XFrame)UnoRuntime.queryInterface(
                com.sun.star.frame.XFrame.class, object[0]);
            if (xFrame==null){
                return null;
            }
            // hasFrame will return false until it's initialized
            if (AddOn.hasFrame(xFrame)){
                AddOn.getInstance(xFrame).m_xFrame= xFrame;
                return AddOn.getInstance(xFrame);
            }
            else{
                // context is only used to get URL parser
                AddOn newAddOn = new AddOn(context);
                newAddOn.initialize(object);
                return newAddOn;
            }
        }
    }
    /* I think I need to implement my own factory for this addon, because otherwise
     * it keeps creating new instances of AddOn when it should just return
     * the same instance
     */
    public static XSingleComponentFactory __getComponentFactory( String sImplementationName ) {
        XSingleComponentFactory xFactory = null;
        myLogger.log(
                    Level.FINE, "getComponentFactory s:"+sImplementationName+" m:"+m_implementationName);
        if ( sImplementationName.equals( m_implementationName ) ){
//            xFactory = Factory.createComponentFactory(AddOn.class, m_serviceNames);
//        return xFactory;
            xFactory = new AddonFactory();
        }
        return new AddonFactory();
    }

    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.frame.XDispatchProvider:
    public com.sun.star.frame.XDispatch queryDispatch( com.sun.star.util.URL aURL,
                                                       String sTargetFrameName,
                                                       int iSearchFlags )
    {
        myLogger.fine("queryDispatch: "+ aURL.Complete
                + "; target frame: "+sTargetFrameName);
//        System.out.println("queryDispatch: "+ aURL.Complete
//                + "; target frame: "+sTargetFrameName);
            if ( aURL.Protocol.compareTo("com.CompPad.addon:") == 0 )
            {
                if ( aURL.Path.compareTo("CreateExpression") == 0 )
                    return this;
                if ( aURL.Path.compareTo("EvaluateExpressions") == 0 )
                    return this;
                if ( aURL.Path.compareTo("ToggleSelectionListener") == 0 )
                    return this;
                if (aURL.Path.compareTo("cancelEdit") == 0)
                    return this;
                if (aURL.Path.compareTo("applyEdit") == 0)
                    return this;
                if (aURL.Path.compareTo("editExprField") == 0)
                    return this;
            }
            return null;
    }


    // com.sun.star.frame.XDispatchProvider:
    public com.sun.star.frame.XDispatch[] queryDispatches(
         com.sun.star.frame.DispatchDescriptor[] seqDescriptors )
    {
        int nCount = seqDescriptors.length;
        com.sun.star.frame.XDispatch[] seqDispatcher =
            new com.sun.star.frame.XDispatch[seqDescriptors.length];

        for( int i=0; i < nCount; ++i )
        {
            seqDispatcher[i] = queryDispatch(seqDescriptors[i].FeatureURL,
                                             seqDescriptors[i].FrameName,
                                             seqDescriptors[i].SearchFlags );
        }
        return seqDispatcher;
    }

    // com.sun.star.lang.XInitialization:
    public void initialize( Object[] object )
        throws Exception
    {
        if ( object.length > 0 ){
            myLogger.log(Level.FINE,"Logger Test " + AddOn.class.getName() );

            XFrame xFrame = (com.sun.star.frame.XFrame)UnoRuntime.queryInterface(
                com.sun.star.frame.XFrame.class, object[0]);



            // only re-initialize if it's a new frame
            myLogger.log(
                    Level.FINE, "Initializing addon, XFrame "+ m_xFrame);
            if (xFrame==null){
                return;
            }
           
            m_xFrame = xFrame;
            myLogger.log(
                    Level.FINE, "Initializing addon, XFrame "+ m_xFrame);
            selectionChangeListener= new AddonListener();
            ((XSelectionSupplier)UnoRuntime.queryInterface(
                    XSelectionSupplier.class,m_xFrame.getController()))
                    .addSelectionChangeListener(selectionChangeListener);

            /* Get UI elements from frames layout manager */
            XLayoutManager xLM = (XLayoutManager) ((Any)(((XPropertySet)UnoRuntime.queryInterface(XPropertySet.class,m_xFrame)).getPropertyValue("LayoutManager"))).getObject();
            for (com.sun.star.ui.XUIElement a:Arrays.asList(xLM.getElements())){
                myLogger.log(
                    Level.FINEST, "UIElements " + Arrays.asList(
                        ((XTypeProvider)UnoRuntime.queryInterface(
                        XTypeProvider.class,a.getRealInterface())).getTypes()));
                XWindow2 xw2 = (XWindow2)UnoRuntime.queryInterface(
                        XWindow2.class,a.getRealInterface());

            }

           

            /* Instantiate selection change listener */

            /* add the selection change listener to the controller */
            myLogger.log(
                    Level.FINE, " Added selectionChangeListener to "+m_xFrame.toString());

            m_xFrame.addFrameActionListener(selectionChangeListener);

            /* Get interfaces of controller */
            myLogger.log(
                    Level.FINE, "xController Interfaces "+
                    Arrays.asList(((XTypeProvider)UnoRuntime.queryInterface(
                    XTypeProvider.class,m_xFrame.getController())).getTypes()));



            /* See what interface of frame are */
            myLogger.log(
                    Level.FINE, "xFrame Interfaces "+
                    Arrays.asList(
                    ((XTypeProvider)UnoRuntime.queryInterface(
                    XTypeProvider.class,m_xFrame)).getTypes()));
            /* Get title of frame */
            myLogger.log(
                    Level.FINE, "Frame Title "+
                    ((com.sun.star.frame.XTitle)UnoRuntime.queryInterface(
                    com.sun.star.frame.XTitle.class,m_xFrame)).getTitle());
           
            /* get sub frames */
            List<XFrame>  framelist =  Arrays.asList(
                    ((com.sun.star.frame.XFramesSupplier)UnoRuntime.queryInterface(
                    com.sun.star.frame.XFramesSupplier.class,m_xFrame))
                    .getFrames().queryFrames(com.sun.star.frame.FrameSearchFlag.ALL));
            myLogger.log(
                    Level.FINE, "SubFrames "+framelist);

            /* get XUserInputInterception and do addKeyHandler for main frame */

            ((XUserInputInterception)UnoRuntime.queryInterface(
                    XUserInputInterception.class,m_xFrame.getController()))
                    .addKeyHandler(selectionChangeListener);


           



            if (AddOn.addOns==null){
                AddOn.addOns = new Hashtable<XFrame,AddOn>();
            }
            AddOn.addOns.put(xFrame, this);
            myLogger.log(
                    Level.FINE, "      addons: "+addOns.size());
       }


    }

    // com.sun.star.frame.XDispatch:
     public void dispatch( com.sun.star.util.URL aURL,
                           com.sun.star.beans.PropertyValue[] aArguments )
    {
    myLogger.log(
                    Level.FINE, "dispatch: " + aURL.Complete + "; "+aArguments);

    try {
         if ( aURL.Protocol.compareTo("com.CompPad.addon:") == 0 )
        {
            XFrame xFrame = m_xFrame;
            XTextDocument xTextDoc = (XTextDocument)UnoRuntime.queryInterface(XTextDocument.class,
                    xFrame.getController().getModel());

            myLogger.log(
                    Level.FINE, "xTextDoc "+xTextDoc);
            XMultiComponentFactory xServiceManager =
                    m_xContext.getServiceManager();

            /* create expression, select expression and move focus to the
             formula edit field */
            if ( aURL.Path.compareTo("CreateExpression") == 0 ){
                /* This is just a button for "insert - object - formula "*/
                XDispatchProvider xDP =
                        (XDispatchProvider)UnoRuntime.queryInterface(
                        XDispatchProvider.class, xFrame);
                XURLTransformer xParser =
                        (XURLTransformer) UnoRuntime.queryInterface(
                        XURLTransformer.class,
                        xServiceManager.createInstanceWithContext(
                        "com.sun.star.util.URLTransformer",m_xContext));
                com.sun.star.util.URL[] aParseURL = new com.sun.star.util.URL[1];
                aParseURL[0] = new com.sun.star.util.URL();
                aParseURL[0].Complete = ".uno:InsertObjectStarMath";
                xParser.parseStrict (aParseURL);
                XDispatch xDispatcher = xDP.queryDispatch(aParseURL[0],"",0);
                if(xDispatcher!=null){
                    PropertyValue[] Properties = new PropertyValue[0];
                    xDispatcher.dispatch (aParseURL[0],Properties);
                }
                else{
                    myLogger.log(Level.FINE,"xDispater is null, that's odd.");
                }

                return;

            }
            if ( aURL.Path.compareTo("EvaluateExpressions") == 0 ){
                // add your own code here, says the autogenerated comment.
                /* This is a netbeans auto-generated try-catch and I need to
                 * go through this in detail later */
                solving = true;
                CompPad compPad = new CompPad();
                compPad.newDocument(xTextDoc);
                solving = false;
                // update formula value
                updateFieldText();
                return;
            }
            if ( aURL.Path.compareTo("ToggleSelectionListener") == 0 ){
                // Toggle the selectionChangeListener.
                // Mainly for testing purposes.
                if (selectionListenerActive==true){
                    ((XSelectionSupplier)UnoRuntime.queryInterface(
                            XSelectionSupplier.class,m_xFrame.getController()))
                            .removeSelectionChangeListener(selectionChangeListener);
                    selectionListenerActive=false;

                }
                else{
                    ((XSelectionSupplier)UnoRuntime.queryInterface(
                            XSelectionSupplier.class,m_xFrame.getController()))
                            .addSelectionChangeListener(selectionChangeListener);
                    selectionListenerActive=true;
                }

            }
            if ( aURL.Path.compareTo("cancelEdit") == 0 ){
                // re-set editfield text content to formulaText
                if (formulaSelected){
                    com.sun.star.lang.XComponent xc =
                            ((XEmbeddedObjectSupplier)UnoRuntime
                            .queryInterface(XEmbeddedObjectSupplier.class,lastSelection))
                            .getEmbeddedObject();
                    setFieldText( (String) ( ( (XPropertySet)UnoRuntime
                            .queryInterface(XPropertySet.class, xc))
                            .getPropertyValue("Formula")));
                }
                else{
                    setFieldText("");
                }
                return;
            }
            if ( aURL.Path.compareTo("applyEdit") == 0 ){
                if (formulaSelected){
                    updateExpression(fieldText);

                }
                else{
                    XTextContent xTC = createExpression(fieldText);
                    // controller should have been set in createExpression
                    XSelectionSupplier xSelSup = (XSelectionSupplier) UnoRuntime.queryInterface(
                                XSelectionSupplier.class, controller);
                    xSelSup.select(xTC);
                        // Move the cursor to the right
                }
            }
            if ( aURL.Path.compareTo("editExprField") == 0 ){
                // if control is activated (by pressing "return")
                if (aArguments[0].Name.equals("KeyModifier")){
                    // If formula is selected, then update the formula
                    if (formulaSelected){
                        myLogger.log(
                                Level.FINE, "updating expression");
                        updateExpression(fieldText);
                    }
                    else{
                        myLogger.log(
                                Level.FINE, "logger: "+myLogger);
                        myLogger.fine("creating new expression");
                        myLogger.log(
                                Level.FINE, "creating new expression");
                        XTextContent xTC = createExpression(fieldText);
                        // controller should have been set in createExpression
//                        XSelectionSupplier xSelSup = (XSelectionSupplier) UnoRuntime.queryInterface(
//                                    XSelectionSupplier.class, controller);
//                        xSelSup.select(xTC);
                        ((XSelectionSupplier) UnoRuntime.queryInterface(
                                    XSelectionSupplier.class, controller)).select(xTC);
                        if (!selectionListenerActive){
                            // Set formulaSelected so that next time it will
                            // update the expression
                            formulaSelected = true;
                            // set lastSelection
                            lastSelection = m_xFrame.getController().getModel().getCurrentSelection();
                        }
                    }
                    // If no formula selected, then create formula with text in box
                }
                return;
            }
        }
    } catch (java.lang.Exception ex) {
        solving = false;
        myLogger.log(Level.SEVERE, "dispatch Exception", ex);
    }
    }

    public void addStatusListener( com.sun.star.frame.XStatusListener xControl,
                                    com.sun.star.util.URL aURL )
    {
        // See what we get
        // For now we just want one status listener for the editExprField control,
        // but we need to check that it's for this frame.
        if (aURL.Complete.equals("com.CompPad.addon:editExprField")){
            myLogger.log(
                    Level.FINE, "  addStatusListener "+aURL.Complete+" "+xControl);
            myLogger.log(
                    Level.FINE, "  editFieldListener "+editFieldListener);
            editFieldListener = xControl;
        }
    }

    public void removeStatusListener( com.sun.star.frame.XStatusListener xControl,
                                       com.sun.star.util.URL aURL )
    {
        myLogger.log(
                    Level.FINE, "  removeStatusListener "+aURL.Complete);
    }

    /* Inner class to provide xSelectionChangeListener */
    class AddonListener
            implements com.sun.star.view.XSelectionChangeListener,
            com.sun.star.awt.XKeyHandler,
            com.sun.star.frame.XFrameActionListener{
        public synchronized void selectionChanged(EventObject arg0) {
            try {
                /* Don't check for selection change while evaluating expressions */
                if (!solving){

                   myLogger.fine("selectionChanged, fieldText: "+fieldText
                            +" editFieldListener "+editFieldListener.hashCode());

                    /* Check if the selection is an OOOMath object */
                    XModel xMod = m_xFrame.getController().getModel();
                    Object oSelect = xMod.getCurrentSelection();
                    if (oSelect == lastSelection){
                        return;
                    }
                    lastSelection = oSelect;
                    XPropertySet xPS = (XPropertySet)UnoRuntime
                            .queryInterface(XPropertySet.class, oSelect);
                    //    oSelect = oController.getSelection()
                    if (xPS==null){
                        myLogger.finest("xPS==null");
                        formulaSelected=false;
                        setFieldText("");
                        return;
                    }
                    String clsid="";
                    if (xPS.getPropertySetInfo().hasPropertyByName("CLSID")){
                        clsid = (String) xPS.getPropertyValue("CLSID");
                    }
                    if ( clsid.equals(com.CompPad.OOO.OOODocument.CLSID_FORMULA)){
                        /* Get the embedded component */
                        com.sun.star.lang.XComponent xc =
                                ((XEmbeddedObjectSupplier)UnoRuntime.queryInterface(
                                XEmbeddedObjectSupplier.class,oSelect))
                                .getEmbeddedObject();
                        myLogger.fine("clsid = "+clsid+" XCompnent xc = "+xc);
                        // For some reason, this is coming back null!!!
                        // we'll try getting our selection again!
                        if (xc==null){
                            oSelect = xMod.getCurrentSelection();
                            xc =
                                ((XEmbeddedObjectSupplier)UnoRuntime.queryInterface(
                                XEmbeddedObjectSupplier.class,oSelect))
                                .getEmbeddedObject();
                        }
                        // get xPS interface for component
                        XPropertySet xPSc = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class, xc);
                        // get the formula text property
                        String formulaText = (String)(xPSc.getPropertyValue("Formula"));
                        myLogger.log(
                                Level.FINE, "Formula Selected, formulaText="+formulaText);
                        setFieldText(formulaText);
                        formulaSelected=true;
                    }

                }
            } catch (java.lang.Exception ex) {
                myLogger.log(Level.SEVERE, "selectionChanged Exception: "+ex.getMessage(),ex);
            }

        }
        public boolean keyPressed(com.sun.star.awt.KeyEvent e){
//            System.out.println("KeyPressed "+e.KeyCode);
            return false;
        }
        public boolean keyReleased(com.sun.star.awt.KeyEvent e){
//            System.out.println("KeyReleased "+e.KeyCode);
            return false;
        }

        /* Set the text value of the edit field */
        public void disposing(EventObject arg0) {
            myLogger.log(
                    Level.FINE, "Disposing AddOn "+this);
            AddOn.addOns.remove(m_xFrame);
        }

        public void frameAction(FrameActionEvent arg0) {

            myLogger.log(
                    Level.FINE, "FrameAction "+arg0.Action);

            if (arg0.Action.equals(FrameAction.FRAME_UI_ACTIVATED)){
                myLogger.log(
                    Level.FINE, "FrameUIActivated "
                        + m_xFrame.getContainerWindow().getPosSize().Height);

            }
        }


    }

    /* Set the value of the editField text */
    private void setFieldText(String text){
        try {
            if (editFieldListener!=null && !fieldText.equals(text)){
                NamedValue[] nv = new NamedValue[1];
                nv[0] = new NamedValue();
                nv[0].Name = "Text";
                nv[0].Value = text;
                ControlCommand cc = new ControlCommand();
                cc.Command = "SetText";
                cc.Arguments = nv;
                /* send dispatch to frame */
                XMultiComponentFactory xServiceManager = m_xContext.getServiceManager();
                XURLTransformer xParser = (XURLTransformer) UnoRuntime.queryInterface(
                            XURLTransformer.class,
                            xServiceManager.createInstanceWithContext(
                            "com.sun.star.util.URLTransformer",m_xContext));
                URL[] aParseURL = new URL[1];
                aParseURL[0] = new URL();
                aParseURL[0].Complete = "com.CompPad.addon:editExprField";
                xParser.parseStrict(aParseURL);
                FeatureStateEvent aEvent = new FeatureStateEvent();
                aEvent.FeatureURL = aParseURL[0];
                aEvent.Source = this;
                aEvent.IsEnabled = true;
                aEvent.Requery = false;
                aEvent.State = cc;
                /* Now I need to get an xStatusListener from the
                control so I can call the statusChanged method to
                send the comand */
                editFieldListener.statusChanged(aEvent);
            }
            else{
                return;
            }
        } catch (java.lang.Exception ex) {
            myLogger.log(Level.SEVERE, "setFieldText Exception ", ex);
        }
    }
    private void updateFieldText() throws java.lang.Exception {
        /* Check if the selection is an OOOMath object */
        XModel xMod = m_xFrame.getController().getModel();
        Object oSelect = xMod.getCurrentSelection();
        XPropertySet xPS = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class, oSelect);
        //    oSelect = oController.getSelection()
        if (xPS==null){
            myLogger.finest("updateFieldText xPS==null");
            formulaSelected=false;
            myLogger.log(Level.FINE,"formulaSelected=false");
            setFieldText("");
            return;
        }
        String clsid = (String) xPS.getPropertyValue("CLSID");
        if ( clsid.equals(com.CompPad.OOO.OOODocument.CLSID_FORMULA)){
            /* Get the formula text */
            com.sun.star.lang.XComponent xc =
                    ((XEmbeddedObjectSupplier)UnoRuntime.queryInterface(
                    XEmbeddedObjectSupplier.class,oSelect))
                    .getEmbeddedObject();
            String formulaText = (String)(((XPropertySet)UnoRuntime.queryInterface(XPropertySet.class, xc)).getPropertyValue("Formula"));
            myLogger.log(
                    Level.FINE, "updateFieldText formulaText = "+formulaText);
            setFieldText(formulaText);
            formulaSelected=true;
        }

    }
    private XTextContent createExpression(String formulaText) throws java.lang.Exception{
        /* Cleanup needed! */
        myLogger.log(
                    Level.FINE, "createExpression");
        XFrame xFrame = m_xFrame;
        XMultiServiceFactory xMSF = (XMultiServiceFactory)
                UnoRuntime.queryInterface(XMultiServiceFactory.class,
                    xFrame.getController().getModel());
        XTextContent xObj = (XTextContent) UnoRuntime.queryInterface(
                XTextContent.class,
                xMSF.createInstance( "com.sun.star.text.TextEmbeddedObject" ));
        XPropertySet xPS = (com.sun.star.beans.XPropertySet)
                UnoRuntime.queryInterface(XPropertySet.class, xObj);
        xPS.setPropertyValue("CLSID", com.CompPad.OOO.OOODocument.CLSID_FORMULA);
        /* Change the anchor type to "as character" before inserting */
        XPropertySet xFrameProps = (XPropertySet) UnoRuntime.queryInterface(
                XPropertySet.class, xObj );
        xFrameProps.setPropertyValue("AnchorType", TextContentAnchorType.AS_CHARACTER);
        /* Then embed at the cursor */
//        XModel xModel = (XModel) UnoRuntime.queryInterface(XModel.class, oComponent);
//        controller = xModel.getCurrentController();
        controller = xFrame.getController();
        XTextViewCursorSupplier xViewCursorSupplier = (XTextViewCursorSupplier) UnoRuntime.queryInterface(
                 XTextViewCursorSupplier.class, controller);
        XTextViewCursor xViewCursor = xViewCursorSupplier.getViewCursor();
        //XTextRange xRange = (XTextRange)
        //        UnoRuntime.queryInterface(XTextRange.class, xViewCursor);
        XTextRange xRange = xViewCursor.getStart();

//        ((XTextDocument)UnoRuntime.queryInterface(XTextDocument.class,
//                    xFrame.getController().getModel()))
//                    .getText().insertTextContent(xRange, xObj, true);
        xRange.getText().insertTextContent(xRange, xObj, true);


        /* set the value of the formula text */
        com.sun.star.lang.XComponent xc =
                ((XEmbeddedObjectSupplier)UnoRuntime.queryInterface(
                XEmbeddedObjectSupplier.class,xObj))
                .getEmbeddedObject();
        ((XPropertySet)UnoRuntime
                .queryInterface(XPropertySet.class, xc))
                .setPropertyValue("Formula",formulaText);
        return xObj;
    }
    private void updateExpression(String formulaText) throws java.lang.Exception {
        /* formulaSelected is true, so assume that current
         * object is a formula */
        myLogger.fine("updateExpression formulaText = "+ formulaText);
        myLogger.fine("lastSelection "+lastSelection);
        XEmbeddedObjectSupplier xEOS = (XEmbeddedObjectSupplier)UnoRuntime.queryInterface(
                XEmbeddedObjectSupplier.class,lastSelection);
        myLogger.finest("xEOS "+xEOS);
        com.sun.star.lang.XComponent xc = xEOS.getEmbeddedObject();
        ((XPropertySet)UnoRuntime.queryInterface(XPropertySet.class, xc)).setPropertyValue("Formula",formulaText);
    }
    /* Get current frame from context */
    private static XFrame getFrameFromContext(XComponentContext xContext) throws java.lang.Exception{
            XTextDocument xTextDoc=null;
            XMultiComponentFactory xServiceManager =
                    xContext.getServiceManager();
            Object odesktop = xServiceManager.createInstanceWithContext(
                    "com.sun.star.frame.Desktop", xContext);
            XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(
                    XDesktop.class, odesktop);
            // get the XDesktop interface
            return xDesktop.getCurrentFrame();
    }
}
TOP

Related Classes of com.CompPad.AddOn$AddonListener

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.