diff options
Diffstat (limited to '')
56 files changed, 5666 insertions, 0 deletions
diff --git a/scripting/examples/basic/InsertColouredText.xba b/scripting/examples/basic/InsertColouredText.xba new file mode 100644 index 000000000..e97b5dfd8 --- /dev/null +++ b/scripting/examples/basic/InsertColouredText.xba @@ -0,0 +1,141 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd"> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<script:module xmlns:script="http://openoffice.org/2000/script" script:name="InsertColouredText" script:language="StarBasic">' *** +' InsertColouredText basic script +' Uses a user interface to insert text of a specified colour to the +' start and end of a document +' +' author Neil Montgomery +' created August 12, 2002 +' *** + + +' Main subprocedure to start script +Sub Main + dialogShow() +End Sub + + +' Global reference to the dialog object +Dim oDialog as Object + + +' Uses the loadDialog subprocedure to load and execute the dialog box +Sub dialogShow + oDialog = loadDialog("Standard","InsertColouredTextDialog") + oDialog.execute() +End Sub + + +' *** +' Loads the dialog from the dialog library +' +' param Libname the library name where dialog is stored +' param DialogName the name of the dialog +' param oLibContainer library container to hold the loaded dialog library (optional) +' return runtime dialog object +' *** +Function loadDialog(Libname as String, DialogName as String, Optional oLibContainer) + Dim oLib as Object + Dim oLibDialog as Object + Dim oRuntimeDialog as Object + + ' If the optional oLibContainer is not passed to the function then + ' DialogLibraries is loaded by default + If isMissing(oLibContainer ) then + oLibContainer = DialogLibraries + End If + + ' Loads the specified library, then loads the dialog + oLibContainer.loadLibrary(LibName) + oLib = oLibContainer.getByName(Libname) + oLibDialog = oLib.getByName(DialogName) + oRuntimeDialog = createUnoDialog(oLibDialog) + + ' Returns the runtime dialog object + loadDialog() = oRuntimeDialog +End Function + + + +' *** +' Gets the RGB integer values and new text string from the dialog +' then writes the new coloured text to the start and end of the document +' +' *** +Sub getFromDialog + Dim oDocument As Object + Dim oText As Object + Dim oCursor As Object + + ' Create a document object for the current document then create text and + ' cursor objects + oDocument = StarDesktop.ActiveFrame.Controller.Model + oText = oDocument.Text + oCursor = oText.createTextCursor() + + ' Write the coloured text to the start and end of the document + oCursor.gotoStart(false) + oCursor.CharColor = getColor() + oCursor.setString("New text at start: " + getNewText()) + oCursor.gotoEnd(false) + oCursor.CharColor = getColor() + oCursor.setString("New text at end: " + getNewText()) +End Sub + + + +' *** +' Reads the RGB integer values from the dialog +' +' returns long representing the RGB value +' *** +Function getColor() as Long + Dim oRedText as Object + Dim oGreenText as Object + Dim oBlueText as Object + Dim nColor As Long + + ' Get the three RGB values + oRedText = oDialog.GetControl("RedTextBox") + oGreenText = oDialog.GetControl("GreenTextBox") + oBlueText = oDialog.GetControl("BlueTextBox") + + ' Convert the values to long type and return the value + nColor = RGB(oRedText.Text,oGreenText.Text,oBlueText.Text) + getColor = nColor +End Function + + + +' *** +' Reads the new text from the dialog +' +' returns string the new text +' *** +Function getNewText() as String + Dim oNewText As Object + Dim sNewText As String + + ' Gets the string from dialog and returns the new text + oNewText = oDialog.GetControl("NewTextBox") + sNewText = oNewText.Text + getNewText = sNewText +End Function</script:module>
\ No newline at end of file diff --git a/scripting/examples/basic/InsertColouredTextDialog.xdl b/scripting/examples/basic/InsertColouredTextDialog.xdl new file mode 100644 index 000000000..2fa7768bc --- /dev/null +++ b/scripting/examples/basic/InsertColouredTextDialog.xdl @@ -0,0 +1,34 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE dlg:window PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "dialog.dtd"> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<dlg:window xmlns:dlg="http://openoffice.org/2000/dialog" xmlns:script="http://openoffice.org/2000/script" dlg:id="InsertColouredTextDialog" dlg:left="113" dlg:top="112" dlg:width="178" dlg:height="138" dlg:closeable="true" dlg:moveable="true"> + <dlg:bulletinboard> + <dlg:textfield dlg:id="RedTextBox" dlg:tab-index="0" dlg:left="37" dlg:top="26" dlg:width="20" dlg:height="17"/> + <dlg:textfield dlg:id="GreenTextBox" dlg:tab-index="1" dlg:left="73" dlg:top="26" dlg:width="20" dlg:height="17"/> + <dlg:textfield dlg:id="BlueTextBox" dlg:tab-index="2" dlg:left="109" dlg:top="26" dlg:width="20" dlg:height="17"/> + <dlg:textfield dlg:id="NewTextBox" dlg:tab-index="3" dlg:left="57" dlg:top="67" dlg:width="57" dlg:height="15"/> + <dlg:button dlg:id="CommandButton1" dlg:tab-index="4" dlg:left="49" dlg:top="97" dlg:width="75" dlg:height="15" dlg:value="Insert New Coloured Text"> + <script:event script:event-name="on-mousedown" script:location="application" script:macro-name="Standard.InsertColouredText.getFromDialog" script:language="StarBasic"/> + </dlg:button> + <dlg:text dlg:id="Label1" dlg:tab-index="5" dlg:left="44" dlg:top="12" dlg:width="7" dlg:height="10" dlg:value="R"/> + <dlg:text dlg:id="Label2" dlg:tab-index="6" dlg:left="78" dlg:top="12" dlg:width="7" dlg:height="10" dlg:value="G"/> + <dlg:text dlg:id="Label3" dlg:tab-index="7" dlg:left="114" dlg:top="12" dlg:width="7" dlg:height="10" dlg:value="B"/> + <dlg:text dlg:id="Label4" dlg:tab-index="8" dlg:left="71" dlg:top="56" dlg:width="26" dlg:height="8" dlg:value="New Text"/> + </dlg:bulletinboard> +</dlg:window>
\ No newline at end of file diff --git a/scripting/examples/basic/SearchAndReplace.xba b/scripting/examples/basic/SearchAndReplace.xba new file mode 100644 index 000000000..24c61d8e9 --- /dev/null +++ b/scripting/examples/basic/SearchAndReplace.xba @@ -0,0 +1,126 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd"> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<script:module xmlns:script="http://openoffice.org/2000/script" script:name="SearchAndReplace" script:language="StarBasic">' *** +' SearchAndReplace basic script +' Uses a user interface to search and replace the specified strings +' +' author Neil Montgomery +' created August 12, 2002 +' *** + + +' Main subprocedure to start script +Sub Main + dialogShow() +End Sub + + +' Global reference to the dialog object +Dim oDialog as Object + + +' Uses the loadDialog subprocedure to load and execute the dialog box +Sub dialogShow + oDialog = loadDialog("Standard","SearchAndReplaceDialog") + oDialog.execute() +End Sub + + + +' *** +' Loads the dialog from the dialog library +' +' param Libname the library name where dialog is stored +' param DialogName the name of the dialog +' param oLibContainer library container to hold the loaded dialog library (optional) +' return runtime dialog object +' *** +Function loadDialog(Libname as String, DialogName as String, Optional oLibContainer) + Dim oLib as Object + Dim oLibDialog as Object + Dim oRuntimeDialog as Object + + If isMissing(oLibContainer ) then + oLibContainer = DialogLibraries + End If + oLibContainer.loadLibrary(LibName) + oLib = oLibContainer.getByName(Libname) + oLibDialog = oLib.getByName(DialogName) + oRuntimeDialog = createUnoDialog(oLibDialog) + loadDialog() = oRuntimeDialog +End Function + + + +' *** +' Creates a connection to the current document. +' Gets the search and replace keys from the dialog and replaces all +' instances of the search key with the replace key. +' +' *** +Sub getInfoFromDialog + Dim oDocument As Object + Dim oSearch As Object + Dim oFound As Object + Dim oFoundCursor As Object + Dim oSearchText as Object + Dim oReplaceText as Object + + ' Create a document object for the current document then create text and + ' cursor objects + oDocument = StarDesktop.ActiveFrame.Controller.Model + oSearch = oDocument.createSearchDescriptor + + ' Replace all instances of the search string with the replace string + oSearch.SearchString = getSearchKey() + oSearch.ReplaceString = getReplaceKey() + oDocument.replaceAll(oSearch) +End Sub + + +' *** +' Gets the search key string from the dialog +' +' returns string representing the search key +' *** +Function getSearchKey() as String + Dim sSearch As String + + ' Get the search key from the dialog + oSearchText = oDialog.GetControl("SearchKeyTextBox") + sSearch = oSearchText.Text + getSearchKey = sSearch +End Function + + + +' *** +' Gets the replace key string from the dialog +' +' returns string representing the replace key +' *** +Function getReplaceKey() as String + Dim sReplace As String + + ' Get the replace key from the dialog + oReplaceText = oDialog.GetControl("ReplaceKeyTextBox") + sReplace = oReplaceText.Text + getReplaceKey = sReplace +End Function</script:module> diff --git a/scripting/examples/basic/SearchAndReplaceDialog.xdl b/scripting/examples/basic/SearchAndReplaceDialog.xdl new file mode 100644 index 000000000..9503dbf57 --- /dev/null +++ b/scripting/examples/basic/SearchAndReplaceDialog.xdl @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE dlg:window PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "dialog.dtd"> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<dlg:window xmlns:dlg="http://openoffice.org/2000/dialog" xmlns:script="http://openoffice.org/2000/script" dlg:id="SearchAndReplaceDialog" dlg:left="113" dlg:top="112" dlg:width="178" dlg:height="138" dlg:closeable="true" dlg:moveable="true"> + <dlg:bulletinboard> + <dlg:textfield dlg:id="SearchKeyTextBox" dlg:tab-index="0" dlg:left="28" dlg:top="31" dlg:width="53" dlg:height="13"/> + <dlg:textfield dlg:id="ReplaceKeyTextBox" dlg:tab-index="1" dlg:left="102" dlg:top="31" dlg:width="51" dlg:height="13"/> + <dlg:button dlg:id="CommandButton1" dlg:tab-index="2" dlg:left="59" dlg:top="79" dlg:width="62" dlg:height="13" dlg:value="Search And Replace"> + <script:event script:event-name="on-mousedown" script:location="application" script:macro-name="Standard.SearchAndReplace.getInfoFromDialog" script:language="StarBasic"/> + </dlg:button> + <dlg:text dlg:id="Label1" dlg:tab-index="3" dlg:left="37" dlg:top="20" dlg:width="33" dlg:height="8" dlg:value="Search Key"/> + <dlg:text dlg:id="Label2" dlg:tab-index="4" dlg:left="109" dlg:top="20" dlg:width="35" dlg:height="8" dlg:value="Replace Key"/> + </dlg:bulletinboard> +</dlg:window>
\ No newline at end of file diff --git a/scripting/examples/basic/dialog.xlb b/scripting/examples/basic/dialog.xlb new file mode 100644 index 000000000..95dc3a123 --- /dev/null +++ b/scripting/examples/basic/dialog.xlb @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE library:library PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "library.dtd"> +<library:library xmlns:library="http://openoffice.org/2000/library" library:name="Standard" library:readonly="false" library:passwordprotected="false"> + <library:element library:name="InsertColouredTextDialog"/> + <library:element library:name="SearchAndReplaceDialog"/> +</library:library> diff --git a/scripting/examples/basic/script.xlb b/scripting/examples/basic/script.xlb new file mode 100644 index 000000000..fa7dd6103 --- /dev/null +++ b/scripting/examples/basic/script.xlb @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE library:library PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "library.dtd"> +<library:library xmlns:library="http://openoffice.org/2000/library" library:name="Standard" library:readonly="false" library:passwordprotected="false"> + <library:element library:name="InsertColouredText"/> + <library:element library:name="SearchAndReplace"/> +</library:library> diff --git a/scripting/examples/beanshell/Capitalise/capitalise.bsh b/scripting/examples/beanshell/Capitalise/capitalise.bsh new file mode 100644 index 000000000..6b68e010f --- /dev/null +++ b/scripting/examples/beanshell/Capitalise/capitalise.bsh @@ -0,0 +1,111 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +// Change the case of a selection, or current word from upper case, +// to first char upper case, to all lower case to upper case... +import com.sun.star.uno.UnoRuntime; +import com.sun.star.frame.XModel; +import com.sun.star.view.XSelectionSupplier; +import com.sun.star.container.XIndexAccess; +import com.sun.star.text.XText; +import com.sun.star.text.XTextRange; +import com.sun.star.text.XWordCursor; +import com.sun.star.script.provider.XScriptContext; + +// return the new string based on the string passed in +String getNewString( theString ) { + String newString; + if(theString==null || theString.length()==0) { + return newString; + } + // should we tokenize on "."? + if(Character.isUpperCase(theString.charAt(0)) && theString.length()>=2 && Character.isUpperCase(theString.charAt(1))) { // first two chars are UC => first UC, rest LC + newString=theString.substring(0,1).toUpperCase()+theString.substring(1).toLowerCase(); + } else if (Character.isUpperCase(theString.charAt(0))) { // first char UC => all to LC + newString=theString.toLowerCase(); + } else { // all to UC. + newString=theString.toUpperCase(); + } + return newString; +} + +//the method that does the work +void capitalise() { + + // get the number of regions selected + count = xIndexAccess.getCount(); + if(count>=1) { //ie we have a selection + for(i=0;i<count;i++) { + // get the i-th region selected + xTextRange = (XTextRange) + UnoRuntime.queryInterface(XTextRange.class, xIndexAccess.getByIndex(i)); + System.out.println("string: "+xTextRange.getString()); + // get the selected string + theString = xTextRange.getString(); + if(theString.length()==0) { + // sadly we can have a selection where nothing is selected + // in this case we get the XWordCursor and make a selection! + xText = (XText) + UnoRuntime.queryInterface(XText.class, xTextRange.getText()); + xWordCursor = (XWordCursor) + UnoRuntime.queryInterface(XWordCursor.class, xText.createTextCursorByRange(xTextRange)); + // move the Word cursor to the start of the word if it's not + // already there + if(!xWordCursor.isStartOfWord()) { + xWordCursor.gotoStartOfWord(false); + } + // move the cursor to the next word, selecting all chars + // in between + xWordCursor.gotoNextWord(true); + // get the selected string + theString = xWordCursor.getString(); + // get the new string + newString = getNewString(theString); + if(newString!=null) { + // set the new string + xWordCursor.setString(newString); + // keep the current selection + xSelectionSupplier.select(xWordCursor); + } + } else { + newString = getNewString( theString ); + if(newString!=null) { + // set the new string + xTextRange.setString(newString); + // keep the current selection + xSelectionSupplier.select(xTextRange); + } + } + + } + } +} + +// The XSCRIPTCONTEXT variable is of type XScriptContext and is available to +// all BeanShell scripts executed by the Script Framework +xModel = (XModel) + UnoRuntime.queryInterface(XModel.class, XSCRIPTCONTEXT.getDocument()); +//the writer controller impl supports the css.view.XSelectionSupplier interface +xSelectionSupplier = (XSelectionSupplier) + UnoRuntime.queryInterface(XSelectionSupplier.class, xModel.getCurrentController()); +//see section 7.5.1 of developers' guide +xIndexAccess = (XIndexAccess) + UnoRuntime.queryInterface(XIndexAccess.class, xSelectionSupplier.getSelection()); + +//call the method that does the work +capitalise(); +return 0; diff --git a/scripting/examples/beanshell/Capitalise/parcel-descriptor.xml b/scripting/examples/beanshell/Capitalise/parcel-descriptor.xml new file mode 100644 index 000000000..d6fb419aa --- /dev/null +++ b/scripting/examples/beanshell/Capitalise/parcel-descriptor.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<parcel language="BeanShell" xmlns:parcel="scripting.dtd"> + + <script language="BeanShell"> + <locale lang="en"> + <displayname value="Capitalise"/> + <description> + Change the case of a selection, or current word from upper case, to first char upper case, to all lower case to upper case... + </description> + </locale> + <functionname value="capitalise.bsh"/> + <logicalname value="Capitalise.BeanShell"/> + </script> + +</parcel> diff --git a/scripting/examples/beanshell/HelloWorld/helloworld.bsh b/scripting/examples/beanshell/HelloWorld/helloworld.bsh new file mode 100644 index 000000000..4ff9cd42e --- /dev/null +++ b/scripting/examples/beanshell/HelloWorld/helloworld.bsh @@ -0,0 +1,34 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +// Hello World in BeanShell +import com.sun.star.uno.UnoRuntime; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XText; +import com.sun.star.text.XTextRange; + +// get the document from the scripting context which is made available to all +// scripts +oDoc = XSCRIPTCONTEXT.getDocument(); +//get the XTextDocument interface +xTextDoc = (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class,oDoc); +//get the XText interface +xText = xTextDoc.getText(); +// get an (empty) XTextRange at the end of the document +xTextRange = xText.getEnd(); +// set the string +xTextRange.setString( "Hello World (in BeanShell)" ); diff --git a/scripting/examples/beanshell/HelloWorld/parcel-descriptor.xml b/scripting/examples/beanshell/HelloWorld/parcel-descriptor.xml new file mode 100644 index 000000000..e4c073b5f --- /dev/null +++ b/scripting/examples/beanshell/HelloWorld/parcel-descriptor.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<parcel language="BeanShell" xmlns:parcel="scripting.dtd"> + + <script language="BeanShell"> + <locale lang="en"> + <displayname value="Hello World"/> + <description> + Adds the string "Hello World" into the current text doc. + </description> + </locale> + <functionname value="helloworld.bsh"/> + <logicalname value="HelloWorld.BeanShell"/> + </script> + +</parcel> diff --git a/scripting/examples/beanshell/Highlight/ButtonPressHandler.bsh b/scripting/examples/beanshell/Highlight/ButtonPressHandler.bsh new file mode 100644 index 000000000..ac6efacce --- /dev/null +++ b/scripting/examples/beanshell/Highlight/ButtonPressHandler.bsh @@ -0,0 +1,123 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +// this code is bound to the events generated by the buttons in the dialog +// it will close the dialog or find and highlight the text entered in the +// dialog (depending on the button pressed) +import com.sun.star.uno.*; +import com.sun.star.awt.*; +import com.sun.star.lang.*; +import com.sun.star.beans.*; +import com.sun.star.util.*; +import com.sun.star.script.framework.browse.DialogFactory; + +// Get the ActionEvent object from the ARGUMENTS list +ActionEvent event = (ActionEvent) ARGUMENTS[0]; + +// Each argument is of type Any so we must use the AnyConverter class to +// convert it into the interface or primitive type we expect +XButton button = (XButton)AnyConverter.toObject( + new Type(XButton.class), event.Source); + +// We can now query for the model of the button and get its properties +XControl control = (XControl)UnoRuntime.queryInterface(XControl.class, button); +XControlModel cmodel = control.getModel(); +XPropertySet pset = (XPropertySet)UnoRuntime.queryInterface( + XPropertySet.class, cmodel); + +if (pset.getPropertyValue("Label").equals("Exit")) +{ + // We can get the XDialog in which this control appears by calling + // getContext() on the XControl interface + XDialog xDialog = (XDialog)UnoRuntime.queryInterface( + XDialog.class, control.getContext()); + + // Close the dialog + xDialog.endExecute(); +} +else +{ + // We can get the list of controls for this dialog by calling + // getContext() on the XControl interface of the button + XControlContainer controls = (XControlContainer)UnoRuntime.queryInterface( + XControlContainer.class, control.getContext()); + + // Now get the text field control from the list + XTextComponent textField = (XTextComponent) + UnoRuntime.queryInterface( + XTextComponent.class, controls.getControl("HighlightTextField")); + + String searchKey = textField.getText(); + + // highlight the text in red + java.awt.Color cRed = new java.awt.Color(255, 0, 0); + int red = cRed.getRGB(); + + XReplaceable replaceable = (XReplaceable) + UnoRuntime.queryInterface(XReplaceable.class, XSCRIPTCONTEXT.getDocument()); + + XReplaceDescriptor descriptor = + (XReplaceDescriptor) replaceable.createReplaceDescriptor(); + + // Gets a XPropertyReplace object for altering the properties + // of the replaced text + XPropertyReplace xPropertyReplace = (XPropertyReplace) + UnoRuntime.queryInterface(XPropertyReplace.class, descriptor); + + // Sets the replaced text property fontweight value to Bold + PropertyValue wv = new PropertyValue("CharWeight", -1, + new Float(com.sun.star.awt.FontWeight.BOLD), + com.sun.star.beans.PropertyState.DIRECT_VALUE); + + // Sets the replaced text property color value to RGB parameter + PropertyValue cv = new PropertyValue("CharColor", -1, + new Integer(red), + com.sun.star.beans.PropertyState.DIRECT_VALUE); + + // Apply the properties + PropertyValue[] props = new PropertyValue[] { cv, wv }; + + try { + xPropertyReplace.setReplaceAttributes(props); + + // Only matches whole words and case sensitive + descriptor.setPropertyValue( + "SearchCaseSensitive", new Boolean(true)); + descriptor.setPropertyValue("SearchWords", new Boolean(true)); + } + catch (com.sun.star.beans.UnknownPropertyException upe) { + System.err.println("Error setting up search properties"); + return; + } + catch (com.sun.star.beans.PropertyVetoException pve) { + System.err.println("Error setting up search properties"); + return; + } + catch (com.sun.star.lang.WrappedTargetException wte) { + System.err.println("Error setting up search properties"); + return; + } + + // Replaces all instances of searchKey with new Text properties + // and gets the number of instances of the searchKey + descriptor.setSearchString(searchKey); + descriptor.setReplaceString(searchKey); + replaceable.replaceAll(descriptor); +} + +// BeanShell scripts in LibreOffice should always return 0 +return 0; diff --git a/scripting/examples/beanshell/Highlight/ShowDialog.bsh b/scripting/examples/beanshell/Highlight/ShowDialog.bsh new file mode 100644 index 000000000..95ccc32bb --- /dev/null +++ b/scripting/examples/beanshell/Highlight/ShowDialog.bsh @@ -0,0 +1,140 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +// this script serves as an example of how to launch a Basic Dialog +// from a script +import com.sun.star.uno.UnoRuntime; +import com.sun.star.script.provider.XScriptContext; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.EventObject; +import com.sun.star.uno.Type; +import com.sun.star.uno.AnyConverter; +import com.sun.star.text.XTextDocument; +import com.sun.star.beans.PropertyValue; +import com.sun.star.script.XLibraryContainer; +import com.sun.star.awt.*; +import com.sun.star.util.*; + +boolean tryLoadingLibrary( xmcf, context, name ) +{ + try + { + obj = xmcf.createInstanceWithContext( + "com.sun.star.script.Application" + name + "LibraryContainer", + context.getComponentContext()); + + xLibraryContainer = (XLibraryContainer) + UnoRuntime.queryInterface(XLibraryContainer.class, obj); + + System.err.println("Got XLibraryContainer"); + + serviceObj = context.getComponentContext().getValueByName( + "/singletons/com.sun.star.util.theMacroExpander"); + + xme = (XMacroExpander) AnyConverter.toObject( + new Type(XMacroExpander.class), serviceObj); + + bootstrapName = "bootstraprc"; + if (System.getProperty("os.name").startsWith("Windows")) + { + bootstrapName = "bootstrap.ini"; + } + + libURL = xme.expandMacros( + "$BRAND_BASE_DIR/$BRAND_SHARE_SUBDIR/basic/ScriptBindingLibrary/" + + name.toLowerCase() + ".xlb/"); + + System.err.println("libURL is: " + libURL); + + xLibraryContainer.createLibraryLink( + "ScriptBindingLibrary", libURL, false); + + System.err.println("liblink created"); + + } + catch (com.sun.star.uno.Exception e) + { + System.err.println("Got an exception loading lib: " + e.getMessage()); + return false; + } + return true; +} + +// get the XMultiComponentFactory from the XSCRIPTCONTEXT +XMultiComponentFactory xmcf = + XSCRIPTCONTEXT.getComponentContext().getServiceManager(); + +Object[] args = new Object[1]; +args[0] = XSCRIPTCONTEXT.getDocument(); + +Object obj; +try { + // try to create an instance of the DialogProvider + obj = xmcf.createInstanceWithArgumentsAndContext( + "com.sun.star.awt.DialogProvider", args, + XSCRIPTCONTEXT.getComponentContext()); + /* + obj = xmcf.createInstanceWithContext( + "com.sun.star.awt.DialogProvider", + XSCRIPTCONTEXT.getComponentContext()); + */ +} +catch (com.sun.star.uno.Exception e) { + System.err.println("Error getting DialogProvider object"); + return 0; +} + +// get the XDialogProvider interface from the object created above +XDialogProvider xDialogProvider = (XDialogProvider) + UnoRuntime.queryInterface(XDialogProvider.class, obj); + +System.err.println("Got DialogProvider, now get dialog"); + +try { + // try to create the Highlight dialog (found in the ScriptBindingLibrary) + findDialog = xDialogProvider.createDialog("vnd.sun.star.script:" + + "ScriptBindingLibrary.Highlight?location=application"); + if( findDialog == null ) + { + if (tryLoadingLibrary(xmcf, XSCRIPTCONTEXT, "Dialog") == false || + tryLoadingLibrary(xmcf, XSCRIPTCONTEXT, "Script") == false) + { + System.err.println("Error loading ScriptBindingLibrary"); + return 0; + } + else + { + // try to create the Highlight dialog (found in the ScriptBindingLibrary) + findDialog = xDialogProvider.createDialog("vnd.sun.star.script:" + + "ScriptBindingLibrary.Highlight?location=application"); + } + } +} +catch (java.lang.Exception e) { + System.err.println("Got exception on first creating dialog: " + + e.getMessage()); +} + +// execute the dialog in a new thread (so that this script can finish) +Thread t = new Thread() { + public void run() { + findDialog.execute(); + } +}; +t.start(); + +return 0; diff --git a/scripting/examples/beanshell/Highlight/highlighter.bsh b/scripting/examples/beanshell/Highlight/highlighter.bsh new file mode 100644 index 000000000..a69f76e1a --- /dev/null +++ b/scripting/examples/beanshell/Highlight/highlighter.bsh @@ -0,0 +1,166 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +import com.sun.star.uno.UnoRuntime; +import com.sun.star.util.XReplaceable; +import com.sun.star.util.XReplaceDescriptor; +import com.sun.star.util.XPropertyReplace; +import com.sun.star.beans.PropertyValue; +import com.sun.star.text.XTextDocument; +import com.sun.star.script.provider.XScriptContext; + +int replaceText(searchKey, color, bold) { + + result = 0; + + try { + // Create an XReplaceable object and an XReplaceDescriptor + replaceable = (XReplaceable) + UnoRuntime.queryInterface(XReplaceable.class, xTextDocument); + + descriptor = + (XReplaceDescriptor) replaceable.createReplaceDescriptor(); + + // Gets a XPropertyReplace object for altering the properties + // of the replaced text + xPropertyReplace = (XPropertyReplace) + UnoRuntime.queryInterface(XPropertyReplace.class, descriptor); + + // Sets the replaced text property fontweight value to Bold or Normal + wv = null; + if (bold) { + wv = new PropertyValue("CharWeight", -1, + new Float(com.sun.star.awt.FontWeight.BOLD), + com.sun.star.beans.PropertyState.DIRECT_VALUE); + } + else { + wv = new PropertyValue("CharWeight", -1, + new Float(com.sun.star.awt.FontWeight.NORMAL), + com.sun.star.beans.PropertyState.DIRECT_VALUE); + } + + // Sets the replaced text property color value to RGB color parameter + cv = new PropertyValue("CharColor", -1, new Integer(color), + com.sun.star.beans.PropertyState.DIRECT_VALUE); + + // Apply the properties + PropertyValue[] props = { cv, wv }; + xPropertyReplace.setReplaceAttributes(props); + + // Only matches whole words and case sensitive + descriptor.setPropertyValue("SearchCaseSensitive", new Boolean(true)); + descriptor.setPropertyValue("SearchWords", new Boolean(true)); + + // Replaces all instances of searchKey with new Text properties + // and gets the number of instances of the searchKey + descriptor.setSearchString(searchKey); + descriptor.setReplaceString(searchKey); + result = replaceable.replaceAll(descriptor); + + } + catch (Exception e) { + } + + return result; +} + +searchKey = ""; + +// The XSCRIPTCONTEXT variable is of type XScriptContext and is available to +// all BeanShell scripts executed by the Script Framework +xTextDocument = (XTextDocument) + UnoRuntime.queryInterface(XTextDocument.class, XSCRIPTCONTEXT.getDocument()); + +// Create a JButton and add an ActionListener +// When clicked the value for the searchKey is read and passed to replaceText +myListener = new ActionListener() { + actionPerformed(ActionEvent e) { + searchKey = findTextBox.getText(); + + if(searchKey.equalsIgnoreCase("")) { + JOptionPane.showMessageDialog(null, + "No text entered for search", + "No text", JOptionPane.INFORMATION_MESSAGE); + } + else { + // highlight the text in red + cRed = new Color(255, 0, 0); + red = cRed.getRGB(); + num = replaceText(searchKey, red, true); + + if(num > 0) { + int response = JOptionPane.showConfirmDialog(null, + searchKey + " was found " + num + + " times\nDo you wish to keep the text highlighted?", + "Confirm highlight", JOptionPane.YES_NO_OPTION, + JOptionPane.QUESTION_MESSAGE); + + if (response == 1) { + cBlack = new Color(255, 255, 255); + black = cBlack.getRGB(); + replaceText(searchKey, black, false); + } + } + else { + JOptionPane.showMessageDialog(null, + "No matches were found", "Not found", + JOptionPane.INFORMATION_MESSAGE); + } + } + } +}; + + +exitListener = new ActionListener() { + actionPerformed(ActionEvent e) { + frame.dispose(); + } +}; + + +searchButton = new JButton("Highlight"); +searchButton.addActionListener(myListener); + +exitButton = new JButton("Exit"); +exitButton.addActionListener(exitListener); + +buttonPanel = new JPanel(); +buttonPanel.setLayout(new FlowLayout()); +buttonPanel.add(searchButton); +buttonPanel.add(exitButton); + + +// Create a JPanel containing one JTextField for the search text. +searchPanel = new JPanel(); +searchPanel.setLayout(new FlowLayout()); +findTextBox = new JTextField(20); +findWhat = new JLabel("Find What: "); +searchPanel.add(findWhat); +searchPanel.add(findTextBox); + +// Create frame and add a window listener +frame = new JFrame("Highlight Text"); +frame.setSize(350,130); +frame.setLocation(430,430); +frame.setResizable(false); +// Add the panel and button to the frame +frame.getContentPane().setLayout(new GridLayout(2,1,10,10)); +frame.getContentPane().add(searchPanel); +frame.getContentPane().add(buttonPanel); + +frame.setVisible(true); +frame.pack(); diff --git a/scripting/examples/beanshell/Highlight/parcel-descriptor.xml b/scripting/examples/beanshell/Highlight/parcel-descriptor.xml new file mode 100644 index 000000000..a2a3773a9 --- /dev/null +++ b/scripting/examples/beanshell/Highlight/parcel-descriptor.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<parcel language="BeanShell" xmlns:parcel="scripting.dtd"> + <script language="BeanShell"> + <locale lang="en"> + <displayname value="ShowDialog" /> + <description> + Example of how to show a dialog from BeanShell + </description> + </locale> + <functionname value="ShowDialog.bsh" /> + <logicalname value="ShowDialog.BeanShell" /> + </script> + <script language="BeanShell"> + <locale lang="en"> + <displayname value="ButtonPressHandler" /> + <description> + Example of handle button press events for the Dialog + </description> + </locale> + <functionname value="ButtonPressHandler.bsh" /> + <logicalname value="ButtonPressHandler.BeanShell" /> + </script> +</parcel> + diff --git a/scripting/examples/beanshell/InteractiveBeanShell/interactive.bsh b/scripting/examples/beanshell/InteractiveBeanShell/interactive.bsh new file mode 100644 index 000000000..0e82f1df0 --- /dev/null +++ b/scripting/examples/beanshell/InteractiveBeanShell/interactive.bsh @@ -0,0 +1,21 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +// Pops up a window into which you can type BeanShell code and run it +// against the current document +editor(); +return 0; diff --git a/scripting/examples/beanshell/InteractiveBeanShell/parcel-descriptor.xml b/scripting/examples/beanshell/InteractiveBeanShell/parcel-descriptor.xml new file mode 100644 index 000000000..0911ac56a --- /dev/null +++ b/scripting/examples/beanshell/InteractiveBeanShell/parcel-descriptor.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<parcel language="BeanShell" xmlns:parcel="scripting.dtd"> + + <script language="BeanShell"> + <locale lang="en"> + <displayname value="Interactive BeanShell"/> + <description> + Pops up a window into which you can type BeanShell code and run it against the current document + </description> + </locale> + <functionname value="interactive.bsh"/> + <logicalname value="Interactive.BeanShell"/> + </script> + +</parcel> diff --git a/scripting/examples/beanshell/MemoryUsage/memusage.bsh b/scripting/examples/beanshell/MemoryUsage/memusage.bsh new file mode 100644 index 000000000..3929f6435 --- /dev/null +++ b/scripting/examples/beanshell/MemoryUsage/memusage.bsh @@ -0,0 +1,137 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Type; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.document.XEmbeddedObjectSupplier; +import com.sun.star.awt.ActionEvent; +import com.sun.star.awt.Rectangle; +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.PropertyValue; + +import com.sun.star.container.*; +import com.sun.star.chart.*; +import com.sun.star.table.*; +import com.sun.star.sheet.*; + +import com.sun.star.script.provider.XScriptContext; + +createSpreadsheet() +{ + loader = (XComponentLoader) + UnoRuntime.queryInterface( + XComponentLoader.class, XSCRIPTCONTEXT.getDesktop()); + + comp = loader.loadComponentFromURL( + "private:factory/scalc", "_blank", 4, new PropertyValue[0]); + + doc = (XSpreadsheetDocument) + UnoRuntime.queryInterface(XSpreadsheetDocument.class, comp); + + index = (XIndexAccess) + UnoRuntime.queryInterface(XIndexAccess.class, doc.getSheets()); + + sheet = (XSpreadsheet) AnyConverter.toObject( + new Type(com.sun.star.sheet.XSpreadsheet.class), index.getByIndex(0)); + + return sheet; +} + +addData(sheet, date, total, free) +{ + // set the labels + sheet.getCellByPosition(0, 0).setFormula("Used"); + sheet.getCellByPosition(0, 1).setFormula("Free"); + sheet.getCellByPosition(0, 2).setFormula("Total"); + + // set the values in the cells + sheet.getCellByPosition(1, 0).setValue(total - free); + sheet.getCellByPosition(1, 1).setValue(free); + sheet.getCellByPosition(1, 2).setValue(total); +} + +addChart(sheet) +{ + rect = new Rectangle(); + rect.X = 500; + rect.Y = 3000; + rect.Width = 10000; + rect.Height = 8000; + + range = (XCellRange) UnoRuntime.queryInterface(XCellRange.class, sheet); + myRange = range.getCellRangeByName("A1:B2"); + + rangeAddr = (XCellRangeAddressable) + UnoRuntime.queryInterface(XCellRangeAddressable.class, myRange); + + myAddr = rangeAddr.getRangeAddress(); + + CellRangeAddress[] addr = new CellRangeAddress[1]; + addr[0] = myAddr; + + supp = (XTableChartsSupplier) + UnoRuntime.queryInterface( XTableChartsSupplier.class, sheet); + charts = supp.getCharts(); + charts.addNewByName("Example", rect, addr, false, true); + + try { Thread.sleep(3000); } catch (java.lang.InterruptedException e) { } + + // get the diagram and Change some of the properties + chartsAccess = (XNameAccess) + UnoRuntime.queryInterface( XNameAccess.class, charts); + + tchart = (XTableChart) + UnoRuntime.queryInterface( + XTableChart.class, chartsAccess.getByName("Example")); + + eos = (XEmbeddedObjectSupplier) + UnoRuntime.queryInterface( XEmbeddedObjectSupplier.class, tchart ); + xifc = eos.getEmbeddedObject(); + + xChart = (XChartDocument) + UnoRuntime.queryInterface(XChartDocument.class, xifc); + + xDocMSF = (XMultiServiceFactory) + UnoRuntime.queryInterface(XMultiServiceFactory.class, xChart); + + diagObject = xDocMSF.createInstance("com.sun.star.chart.PieDiagram"); + xDiagram = (XDiagram) + UnoRuntime.queryInterface(XDiagram.class, diagObject); + xChart.setDiagram(xDiagram); + + propset = (XPropertySet) + UnoRuntime.queryInterface( XPropertySet.class, xChart.getTitle() ); + propset.setPropertyValue("String", "JVM Memory Usage"); +} + +runtime = Runtime.getRuntime(); +generator = new Random(); +date = new Date(); + +// allocate a random number of bytes so that the data changes +len = (int)(generator.nextFloat() * runtime.freeMemory() / 5); +bytes = new byte[len]; + +sheet = createSpreadsheet(); +addData(sheet, date.toString(), runtime.totalMemory(), runtime.freeMemory()); +addChart(sheet); + +return 0; diff --git a/scripting/examples/beanshell/MemoryUsage/parcel-descriptor.xml b/scripting/examples/beanshell/MemoryUsage/parcel-descriptor.xml new file mode 100644 index 000000000..46c7ce422 --- /dev/null +++ b/scripting/examples/beanshell/MemoryUsage/parcel-descriptor.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<parcel language="BeanShell" xmlns:parcel="scripting.dtd"> + + <script language="BeanShell"> + <locale lang="en"> + <displayname value="BeanShell JVM Usage"/> + <description> + Updates a spreadsheet with the current memory usage statistics for the Java Virtual Machine + </description> + </locale> + <functionname value="memusage.bsh"/> + <logicalname value="MemoryUsage.BeanShell"/> + </script> + +</parcel> diff --git a/scripting/examples/beanshell/WordCount/parcel-descriptor.xml b/scripting/examples/beanshell/WordCount/parcel-descriptor.xml new file mode 100644 index 000000000..5887e4991 --- /dev/null +++ b/scripting/examples/beanshell/WordCount/parcel-descriptor.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<parcel language="BeanShell" xmlns:parcel="scripting.dtd"> + + <script language="BeanShell"> + <locale lang="en"> + <displayname value="Word Count"/> + <description> + Provides a word count of the selected text in A Writer document. + </description> + </locale> + <functionname value="wordcount.bsh"/> + <logicalname value="WordCount.BeanShell"/> + </script> + +</parcel> diff --git a/scripting/examples/beanshell/WordCount/wordcount.bsh b/scripting/examples/beanshell/WordCount/wordcount.bsh new file mode 100644 index 000000000..b068d8a7d --- /dev/null +++ b/scripting/examples/beanshell/WordCount/wordcount.bsh @@ -0,0 +1,82 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +//Provides a word count of the selected text in a Writer document. +import com.sun.star.uno.UnoRuntime; +import com.sun.star.frame.XModel; +import com.sun.star.view.XSelectionSupplier; +import com.sun.star.container.XIndexAccess; +import com.sun.star.text.XText; +import com.sun.star.text.XTextRange; +import com.sun.star.script.provider.XScriptContext; + +// display the count in a Swing dialog +void doDisplay(numWords) { + wordsLabel = new JLabel("Word count = " + numWords); + closeButton = new JButton("Close"); + frame = new JFrame("Word Count"); + closeButton.addActionListener(new ActionListener() { + actionPerformed(ActionEvent e) { + frame.setVisible(false); + } + }); + frame.getContentPane().setLayout(new BorderLayout()); + frame.getContentPane().add(wordsLabel, BorderLayout.CENTER); + frame.getContentPane().add(closeButton, BorderLayout.SOUTH); + frame.pack(); + frame.setSize(190,90); + frame.setLocation(430,430); + frame.setVisible(true); +} + +int wordcount() { + + result = 0; + + // iterate through each of the selections + count = xIndexAccess.getCount(); + for(i=0;i<count;i++) { + // get the XTextRange of the selection + xTextRange = (XTextRange) + UnoRuntime.queryInterface(XTextRange.class, xIndexAccess.getByIndex(i)); + //System.out.println("string: "+xTextRange.getString()); + // use the standard J2SE delimiters to tokenize the string + // obtained from the XTextRange + strTok = new StringTokenizer(xTextRange.getString()); + result += strTok.countTokens(); + } + + doDisplay(result); + return result; +} + +// The XSCRIPTCONTEXT variable is of type XScriptContext and is available to +// all BeanShell scripts executed by the Script Framework +xModel = (XModel) + UnoRuntime.queryInterface(XModel.class, XSCRIPTCONTEXT.getDocument()); +//the writer controller impl supports the css.view.XSelectionSupplier interface +xSelectionSupplier = (XSelectionSupplier) + UnoRuntime.queryInterface(XSelectionSupplier.class, xModel.getCurrentController()); +//see section 7.5.1 of developers' guide +// the getSelection provides an XIndexAccess to the one or more selections +xIndexAccess = (XIndexAccess) + UnoRuntime.queryInterface(XIndexAccess.class, xSelectionSupplier.getSelection()); + +count = wordcount(); +System.out.println("count = "+count); +return 0; diff --git a/scripting/examples/java/HelloWorld/HelloWorld.java b/scripting/examples/java/HelloWorld/HelloWorld.java new file mode 100644 index 000000000..1c960da32 --- /dev/null +++ b/scripting/examples/java/HelloWorld/HelloWorld.java @@ -0,0 +1,42 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +import com.sun.star.script.provider.XScriptContext; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XTextRange; +import com.sun.star.text.XText; +/** + * HelloWorld class + * + */ +public class HelloWorld { + public static void printHW(XScriptContext xSc) { + + // getting the text document object + XTextDocument xtextdocument = (XTextDocument) UnoRuntime.queryInterface( + XTextDocument.class, xSc.getDocument()); + XText xText = xtextdocument.getText(); + XTextRange xTextRange = xText.getEnd(); + xTextRange.setString("Hello World (in Java)"); + + }// printHW + +} diff --git a/scripting/examples/java/HelloWorld/parcel-descriptor.xml b/scripting/examples/java/HelloWorld/parcel-descriptor.xml new file mode 100644 index 000000000..57e2e04c9 --- /dev/null +++ b/scripting/examples/java/HelloWorld/parcel-descriptor.xml @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<parcel language="Java" xmlns:parcel="scripting.dtd"> + <script language="Java"> + <locale lang="en"> + <displayname value="HelloWorld.Java"/> + <description> + Prints "Hello World". + </description> + </locale> + <functionname value="org.libreoffice.example.java_scripts.HelloWorld.printHW"/> + <logicalname value="HelloWorld.printHW"/> + <languagedepprops> + <prop name="classpath" value="HelloWorld.jar"/> + </languagedepprops> + </script> +</parcel> diff --git a/scripting/examples/java/Highlight/HighlightText.java b/scripting/examples/java/Highlight/HighlightText.java new file mode 100644 index 000000000..f39ccbfa2 --- /dev/null +++ b/scripting/examples/java/Highlight/HighlightText.java @@ -0,0 +1,233 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.script.provider.XScriptContext; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.EventObject; +import com.sun.star.uno.Type; +import com.sun.star.uno.AnyConverter; +import com.sun.star.text.XTextDocument; +import com.sun.star.beans.PropertyValue; +import com.sun.star.script.XLibraryContainer; +import com.sun.star.awt.*; +import com.sun.star.util.*; + +import java.awt.Color; + +public class HighlightText implements com.sun.star.awt.XActionListener { + + // UNO awt components of the Highlight dialog + XDialog findDialog = null; + XTextComponent findTextBox; + + // The document being searched + XTextDocument theDocument; + + // The text to be searched for + private String searchKey = ""; + + public void showForm(XScriptContext context) { + System.err.println("Starting showForm"); + + XMultiComponentFactory xmcf = + context.getComponentContext().getServiceManager(); + + Object[] args = new Object[1]; + args[0] = context.getDocument(); + + Object obj; + + try { + obj = xmcf.createInstanceWithArgumentsAndContext( + "com.sun.star.awt.DialogProvider", args, + context.getComponentContext()); + } catch (com.sun.star.uno.Exception e) { + System.err.println("Error getting DialogProvider object"); + return; + } + + XDialogProvider xDialogProvider = (XDialogProvider) + UnoRuntime.queryInterface(XDialogProvider.class, obj); + + System.err.println("Got DialogProvider, now get dialog"); + + try { + findDialog = xDialogProvider.createDialog( + "vnd.sun.star.script:" + + "ScriptBindingLibrary.Highlight?location=application"); + } catch (java.lang.Exception e) { + System.err.println("Got exception on first creating dialog: " + + e.getMessage()); + } + + if (findDialog == null) { + if (!tryLoadingLibrary(xmcf, context, "Dialog") || + !tryLoadingLibrary(xmcf, context, "Script")) { + System.err.println("Error loading ScriptBindingLibrary"); + return; + } + + try { + findDialog = xDialogProvider.createDialog( + "vnd.sun.star.script://" + + "ScriptBindingLibrary.Highlight?location=application"); + } catch (com.sun.star.lang.IllegalArgumentException iae) { + System.err.println("Error loading ScriptBindingLibrary"); + return; + } + } + + XControlContainer controls = (XControlContainer) + UnoRuntime.queryInterface(XControlContainer.class, findDialog); + + XButton highlightButton = (XButton) UnoRuntime.queryInterface( + XButton.class, controls.getControl("HighlightButton")); + highlightButton.setActionCommand("Highlight"); + + findTextBox = (XTextComponent) UnoRuntime.queryInterface( + XTextComponent.class, controls.getControl("HighlightTextField")); + + XButton exitButton = (XButton) UnoRuntime.queryInterface( + XButton.class, controls.getControl("ExitButton")); + exitButton.setActionCommand("Exit"); + + theDocument = (XTextDocument) UnoRuntime.queryInterface( + XTextDocument.class, context.getDocument()); + + highlightButton.addActionListener(this); + exitButton.addActionListener(this); + + findDialog.execute(); + } + + public void actionPerformed(ActionEvent e) { + if (e.ActionCommand.equals("Exit")) { + findDialog.endExecute(); + return; + } else if (e.ActionCommand.equals("Highlight")) { + searchKey = findTextBox.getText(); + + // highlight the text in red + Color cRed = new Color(255, 0, 0); + int red = cRed.getRGB(); + + XReplaceable replaceable = (XReplaceable) + UnoRuntime.queryInterface(XReplaceable.class, theDocument); + + XReplaceDescriptor descriptor = + (XReplaceDescriptor) replaceable.createReplaceDescriptor(); + + // Gets a XPropertyReplace object for altering the properties + // of the replaced text + XPropertyReplace xPropertyReplace = (XPropertyReplace) + UnoRuntime.queryInterface(XPropertyReplace.class, descriptor); + + // Sets the replaced text property fontweight value to Bold + PropertyValue wv = new PropertyValue("CharWeight", -1, + new Float(com.sun.star.awt.FontWeight.BOLD), + com.sun.star.beans.PropertyState.DIRECT_VALUE); + + // Sets the replaced text property color value to RGB parameter + PropertyValue cv = new PropertyValue("CharColor", -1, + Integer.valueOf(red), + com.sun.star.beans.PropertyState.DIRECT_VALUE); + + // Apply the properties + PropertyValue[] props = new PropertyValue[] { cv, wv }; + + try { + xPropertyReplace.setReplaceAttributes(props); + + // Only matches whole words and case sensitive + descriptor.setPropertyValue( + "SearchCaseSensitive", Boolean.TRUE); + descriptor.setPropertyValue("SearchWords", Boolean.TRUE); + } catch (com.sun.star.beans.UnknownPropertyException upe) { + System.err.println("Error setting up search properties"); + return; + } catch (com.sun.star.beans.PropertyVetoException pve) { + System.err.println("Error setting up search properties"); + return; + } catch (com.sun.star.lang.WrappedTargetException wte) { + System.err.println("Error setting up search properties"); + return; + } catch (com.sun.star.lang.IllegalArgumentException iae) { + System.err.println("Error setting up search properties"); + return; + } + + // Replaces all instances of searchKey with new Text properties + // and gets the number of instances of the searchKey + descriptor.setSearchString(searchKey); + descriptor.setReplaceString(searchKey); + replaceable.replaceAll(descriptor); + } + } + + public void disposing(EventObject o) { + // do nothing + } + + private boolean tryLoadingLibrary( + XMultiComponentFactory xmcf, XScriptContext context, String name) { + System.err.println("Try to load ScriptBindingLibrary"); + + try { + Object obj = xmcf.createInstanceWithContext( + "com.sun.star.script.Application" + name + "LibraryContainer", + context.getComponentContext()); + + XLibraryContainer xLibraryContainer = (XLibraryContainer) + UnoRuntime.queryInterface(XLibraryContainer.class, obj); + + System.err.println("Got XLibraryContainer"); + + Object serviceObj = context.getComponentContext().getValueByName( + "/singletons/com.sun.star.util.theMacroExpander"); + + XMacroExpander xme = (XMacroExpander) AnyConverter.toObject( + new Type(XMacroExpander.class), serviceObj); + + String bootstrapName = "bootstraprc"; + + if (System.getProperty("os.name").startsWith("Windows")) { + bootstrapName = "bootstrap.ini"; + } + + String libURL = xme.expandMacros( + "$BRAND_BASE_DIR/$BRAND_SHARE_SUBDIR/basic/ScriptBindingLibrary/" + + name.toLowerCase() + ".xlb/"); + + System.err.println("libURL is: " + libURL); + + xLibraryContainer.createLibraryLink( + "ScriptBindingLibrary", libURL, false); + + System.err.println("liblink created"); + + } catch (com.sun.star.uno.Exception e) { + System.err.println("Got an exception loading lib: " + e.getMessage()); + return false; + } + + return true; + } +} diff --git a/scripting/examples/java/Highlight/parcel-descriptor.xml b/scripting/examples/java/Highlight/parcel-descriptor.xml new file mode 100644 index 000000000..bf3a86f94 --- /dev/null +++ b/scripting/examples/java/Highlight/parcel-descriptor.xml @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<parcel language="Java" xmlns:parcel="scripting.dtd"> + <script language="Java"> + <locale lang="en"> + <displayname value="HighlightText.showForm"/> + <description> + Text highlighting + </description> + </locale> + <functionname value="org.libreoffice.example.java_scripts.HighlightText.showForm"/> + <logicalname value="HighlightText.showForm"/> + <languagedepprops> + <prop name="classpath" value="Highlight.jar"/> + </languagedepprops> + </script> +</parcel> diff --git a/scripting/examples/java/MemoryUsage/MemoryUsage.java b/scripting/examples/java/MemoryUsage/MemoryUsage.java new file mode 100644 index 000000000..a01d2bace --- /dev/null +++ b/scripting/examples/java/MemoryUsage/MemoryUsage.java @@ -0,0 +1,157 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +import java.util.Random; +import java.util.Date; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Type; +import com.sun.star.uno.XInterface; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.document.XEmbeddedObjectSupplier; +import com.sun.star.awt.Rectangle; +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.PropertyValue; + +import com.sun.star.container.*; +import com.sun.star.chart.*; +import com.sun.star.table.*; +import com.sun.star.sheet.*; + +import com.sun.star.script.provider.XScriptContext; + +public class MemoryUsage { + public void updateMemoryUsage(XScriptContext ctxt) + throws Exception { + XSpreadsheet sheet = createSpreadsheet(ctxt); + + Runtime runtime = Runtime.getRuntime(); + Random generator = new Random(); + Date date = new Date(); + + // allocate a random amount of memory + int len = (int)(generator.nextFloat() * runtime.freeMemory() / 5); + byte[] bytes = new byte[len]; + + addData(sheet, date.toString(), + runtime.totalMemory(), runtime.freeMemory()); + + addChart(sheet); + } + + private XSpreadsheet createSpreadsheet(XScriptContext ctxt) + throws Exception { + XComponentLoader loader = (XComponentLoader) + UnoRuntime.queryInterface( + XComponentLoader.class, ctxt.getDesktop()); + + XComponent comp = loader.loadComponentFromURL( + "private:factory/scalc", "_blank", 4, new PropertyValue[0]); + + XSpreadsheetDocument doc = (XSpreadsheetDocument) + UnoRuntime.queryInterface(XSpreadsheetDocument.class, comp); + + XIndexAccess index = (XIndexAccess) + UnoRuntime.queryInterface(XIndexAccess.class, doc.getSheets()); + + XSpreadsheet sheet = (XSpreadsheet) AnyConverter.toObject( + new Type(com.sun.star.sheet.XSpreadsheet.class), index.getByIndex(0)); + + return sheet; + } + + private void addData( + XSpreadsheet sheet, String date, long total, long free) + throws Exception { + sheet.getCellByPosition(0, 0).setFormula("Used"); + sheet.getCellByPosition(0, 1).setFormula("Free"); + sheet.getCellByPosition(0, 2).setFormula("Total"); + + sheet.getCellByPosition(1, 0).setValue(total - free); + sheet.getCellByPosition(1, 1).setValue(free); + sheet.getCellByPosition(1, 2).setValue(total); + } + + private void addChart(XSpreadsheet sheet) + throws Exception { + Rectangle rect = new Rectangle(); + rect.X = 500; + rect.Y = 3000; + rect.Width = 10000; + rect.Height = 8000; + + XCellRange range = (XCellRange) + UnoRuntime.queryInterface(XCellRange.class, sheet); + + XCellRange myRange = + range.getCellRangeByName("A1:B2"); + + XCellRangeAddressable rangeAddr = (XCellRangeAddressable) + UnoRuntime.queryInterface(XCellRangeAddressable.class, myRange); + + CellRangeAddress myAddr = rangeAddr.getRangeAddress(); + + CellRangeAddress[] addr = new CellRangeAddress[1]; + addr[0] = myAddr; + + XTableChartsSupplier supp = (XTableChartsSupplier) + UnoRuntime.queryInterface(XTableChartsSupplier.class, sheet); + + XTableCharts charts = supp.getCharts(); + charts.addNewByName("Example", rect, addr, false, true); + + try { + Thread.sleep(3000); + } catch (InterruptedException e) { } + + // get the diagram and Change some of the properties + XNameAccess chartsAccess = (XNameAccess) + UnoRuntime.queryInterface(XNameAccess.class, charts); + + XTableChart tchart = (XTableChart) + UnoRuntime.queryInterface( + XTableChart.class, chartsAccess.getByName("Example")); + + XEmbeddedObjectSupplier eos = (XEmbeddedObjectSupplier) + UnoRuntime.queryInterface(XEmbeddedObjectSupplier.class, tchart); + + XInterface xifc = eos.getEmbeddedObject(); + + XChartDocument xChart = (XChartDocument) + UnoRuntime.queryInterface(XChartDocument.class, xifc); + + XMultiServiceFactory xDocMSF = (XMultiServiceFactory) + UnoRuntime.queryInterface(XMultiServiceFactory.class, xChart); + + Object diagObject = + xDocMSF.createInstance("com.sun.star.chart.PieDiagram"); + + XDiagram xDiagram = (XDiagram) + UnoRuntime.queryInterface(XDiagram.class, diagObject); + + xChart.setDiagram(xDiagram); + + XPropertySet propset = (XPropertySet) + UnoRuntime.queryInterface(XPropertySet.class, xChart.getTitle()); + propset.setPropertyValue("String", "JVM Memory Usage"); + } +} diff --git a/scripting/examples/java/MemoryUsage/parcel-descriptor.xml b/scripting/examples/java/MemoryUsage/parcel-descriptor.xml new file mode 100644 index 000000000..eb55ffe9a --- /dev/null +++ b/scripting/examples/java/MemoryUsage/parcel-descriptor.xml @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<parcel language="Java" xmlns:parcel="scripting.dtd"> + <script language="Java"> + <locale lang="en"> + <displayname value="MemoryUtils.MemUsage"/> + <description> + Text highlighting + </description> + </locale> + <functionname value="org.libreoffice.example.java_scripts.MemoryUsage.updateMemoryUsage"/> + <logicalname value="MemoryUtils.MemUsage"/> + <languagedepprops> + <prop name="classpath" value="MemoryUsage.jar"/> + </languagedepprops> + </script> +</parcel> diff --git a/scripting/examples/java/Newsgroup/MimeConfiguration.java b/scripting/examples/java/Newsgroup/MimeConfiguration.java new file mode 100644 index 000000000..03b964834 --- /dev/null +++ b/scripting/examples/java/Newsgroup/MimeConfiguration.java @@ -0,0 +1,211 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.uno.XComponentContext; +import com.sun.star.script.framework.runtime.XScriptContext; +import com.sun.star.util.XStringSubstitution; + +import javax.mail.*; +import javax.activation.*; + +import java.io.*; + + +public class MimeConfiguration { + + // Office Installation path + private static String instPath = ""; + + + public static boolean createFiles(XScriptContext xsc) { + try { + XComponentContext xcc = xsc.getComponentContext(); + XMultiComponentFactory xmf = xcc.getServiceManager(); + + Object pathSub = + xmf.createInstanceWithContext("com.sun.star.comp.framework.PathSubstitution", + xcc); + XStringSubstitution stringSub = (XStringSubstitution) UnoRuntime.queryInterface( + XStringSubstitution.class, pathSub); + instPath = stringSub.getSubstituteVariableValue("$(inst)"); + + } catch (com.sun.star.beans.UnknownPropertyException upe) { + System.out.println("com.sun.star.beans.UnknownPropertyException"); + upe.printStackTrace(); + } catch (com.sun.star.uno.Exception e) { + System.out.println("com.sun.star.uno.Exception"); + e.printStackTrace(); + } + + writeMailCap(); + writeMimeTypes(); + + // ToDo: include status feedback to StatusWindow + return true; + } + + + + + private static void writeMailCap() { + String mailcapPath = getConfigDir() + System.getProperty("file.separator") + + "mailcap"; + + try { + if (! new File(java.net.URLDecoder.decode(mailcapPath)).exists()) { + File mailcapFile = new File(mailcapPath); + FileWriter out = new FileWriter(mailcapFile); + String[] lines = getMailcapText(); + + for (int i = 0; i < lines.length; i++) { + out.write(lines[i], 0, lines[i].length()); + } + + out.close(); + } else { + } + + + + // use prog dir, if not there then java.io to create/write new file + MailcapCommandMap map = new MailcapCommandMap(mailcapPath); + CommandMap.setDefaultCommandMap(map); + } catch (IOException ioe) { + ioe.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + private static String[] getMailcapText() { + String[] mailcapText = { + "#\n", + "# Default mailcap file for the JavaMail System.\n", + "#\n", + "# JavaMail content-handlers:\n", + "#\n", + "text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain\n", + "text/html;; x-java-content-handler=com.sun.mail.handlers.text_html\n", + "text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml\n", + "image/gif;; x-java-content-handler=com.sun.mail.handlers.image_gif\n", + "image/jpeg;; x-java-content-handler=com.sun.mail.handlers.image_jpeg\n", + "multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed\n", + "message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822\n" + }; + + return mailcapText; + } + + + + private static void writeMimeTypes() { + String mimetypesPath = getConfigDir() + System.getProperty("file.separator") + + "mimetypes.default"; + + try { + if (! new File(java.net.URLDecoder.decode(mimetypesPath)).exists()) { + File mimetypesFile = new File(mimetypesPath); + FileWriter out = new FileWriter(mimetypesFile); + String[] lines = getMimeTypesText(); + + for (int i = 0; i < lines.length; i++) { + out.write(lines[i], 0, lines[i].length()); + } + + out.close(); + } else { + } + + MimetypesFileTypeMap mimeTypes = new MimetypesFileTypeMap(mimetypesPath); + FileTypeMap.setDefaultFileTypeMap(mimeTypes); + } catch (IOException ioe) { + ioe.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + private static String[] getMimeTypesText() { + String[] mimesText = { + "#\n", + "# A simple, old format, mime.types file\n", + "#\n", + "text/html html htm HTML HTM\n", + "text/plain txt text TXT TEXT\n", + "image/gif gif GIF\n", + "image/ief ief\n", + "image/jpeg jpeg jpg jpe JPG\n", + "image/tiff tiff tif\n", + "image/x-xwindowdump xwd\n", + "application/postscript ai eps ps\n", + "application/rtf rtf\n", + "application/x-tex tex\n", + "application/x-texinfo texinfo texi\n", + "application/x-troff t tr roff\n", + "audio/basic au\n", + "audio/midi midi mid\n", + "audio/x-aifc aifc\n", + "audio/x-aiff aif aiff\n", + "audio/x-mpeg mpeg mpg\n", + "audio/x-wav wav\n", + "video/mpeg mpeg mpg mpe\n", + "video/quicktime qt mov\n", + "video/x-msvideo avi\n" + }; + + return mimesText; + } + + + private static String getConfigDir() { + // mailcap file must be written to the Office user/config directory + + // instPath is a URL, needs to be converted to a system pathname + String config = instPath + "/user/config"; + String configNonURL = ""; + + if (System.getProperty("os.name").indexOf("Windows") != -1) { + // Windows + // removes "file:///" + int start = 8; + configNonURL = config.substring(start, config.length()); + + // Convert forward to back-slashes + while (configNonURL.indexOf("/") != -1) { + int fSlash = configNonURL.indexOf("/"); + String firstPart = configNonURL.substring(0, fSlash); + String secondPart = configNonURL.substring(fSlash + 1, configNonURL.length()); + configNonURL = firstPart + "\\" + secondPart; + } + } else { + // Unix/Linux + // removes "file://" + int start = 7; + configNonURL = config.substring(start, config.length()); + } + + return configNonURL; + } + +} diff --git a/scripting/examples/java/Newsgroup/NewsGroup.java b/scripting/examples/java/Newsgroup/NewsGroup.java new file mode 100644 index 000000000..4c1708a05 --- /dev/null +++ b/scripting/examples/java/Newsgroup/NewsGroup.java @@ -0,0 +1,39 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +public class NewsGroup { + + private String hostname = ""; + private String newsgroupName = ""; + + public NewsGroup(String host, String group) { + hostname = host; + newsgroupName = group; + } + + public String getHostName() { + return hostname; + } + + public String getNewsgroupName() { + return newsgroupName; + } + +} diff --git a/scripting/examples/java/Newsgroup/OfficeAttachment.java b/scripting/examples/java/Newsgroup/OfficeAttachment.java new file mode 100644 index 000000000..75c0f4d45 --- /dev/null +++ b/scripting/examples/java/Newsgroup/OfficeAttachment.java @@ -0,0 +1,250 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +//import com.sun.star.frame.XComponentLoader; +import java.io.*; +import com.sun.star.lang.XComponent; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.frame.XStorable; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.frame.XModel; +import com.sun.star.script.framework.runtime.XScriptContext; + +// for debug only +import javax.swing.JOptionPane; + +public class OfficeAttachment { + + private StatusWindow status = null; + private XStorable storedDoc = null; + private File htmlFile = null; + private File officeFile = null; + private boolean isHtmlDoc = false; + private boolean isOfficeDoc = false; + private String templocationURL = ""; + private String templocationSystem = ""; + private String attachmentName = ""; + private String statusLine = ""; + + public OfficeAttachment(XScriptContext xsc, StatusWindow sw, boolean html, + boolean office) { + status = sw; + isHtmlDoc = html; + isOfficeDoc = office; + + templocationSystem = templocationURL = System.getProperty("user.home"); + + if (System.getProperty("os.name").indexOf("Windows") != -1) { + while (templocationURL.indexOf("\\") != -1) { + int sepPos = templocationURL.indexOf("\\"); + String firstPart = templocationURL.substring(0, sepPos); + String lastPart = templocationURL.substring(sepPos + 1, + templocationURL.length()); + templocationURL = firstPart + "/" + lastPart; + } + } + + try { + statusLine = "Querying Office for current document"; + status.setStatus(1, statusLine); + XScriptContext scriptcontext = xsc; + XModel xmodel = scriptcontext.getDocument(); + storedDoc = (XStorable) UnoRuntime.queryInterface(XStorable.class, xmodel); + // find document name from storedDoc + attachmentName = storedDoc.getLocation(); + } catch (Exception e) { + //UNO error + status.setStatus(1, "Error: " + statusLine); + } + + if (attachmentName.equalsIgnoreCase("")) { + attachmentName = "Attachment"; + } else { + int lastSep = attachmentName.lastIndexOf("/"); + attachmentName = attachmentName.substring(lastSep + 1, attachmentName.length()); + int dot = attachmentName.indexOf("."); + attachmentName = attachmentName.substring(0, dot); + } + } + + + public boolean createTempDocs() { + String filenameURL = "file:///" + templocationURL + "/" + attachmentName; + + try { + if (isHtmlDoc) { + statusLine = "Saving doc in HTML format"; + status.setStatus(4, statusLine); + PropertyValue[] propertyvalue_html = new PropertyValue[2]; + propertyvalue_html[0] = new PropertyValue(); + propertyvalue_html[0].Name = "Overwrite"; + propertyvalue_html[0].Value = Boolean.TRUE; + propertyvalue_html[1] = new PropertyValue(); + propertyvalue_html[1].Name = ("FilterName"); + propertyvalue_html[1].Value = "swriter: HTML (StarWriter)"; + storedDoc.storeAsURL(filenameURL + ".html", propertyvalue_html); + + File homedir = new File(templocationSystem); + File homefiles[] = homedir.listFiles(); + String file = ""; + + for (int i = 0; i < homefiles.length; i++) { + if (homefiles[i].getName().equals(attachmentName + ".html")) { + file = homefiles[i].getAbsolutePath(); + } + } + + htmlFile = new File(file); + } + + if (isOfficeDoc) { + statusLine = "Saving doc in .sxw format"; + status.setStatus(4, statusLine); + PropertyValue[] propertyvalue_sxw = new PropertyValue[2]; + propertyvalue_sxw[0] = new PropertyValue(); + propertyvalue_sxw[0].Name = "Overwrite"; + propertyvalue_sxw[0].Value = Boolean.TRUE; + propertyvalue_sxw[1] = new PropertyValue(); + propertyvalue_sxw[1].Name = "Overwrite"; + propertyvalue_sxw[1].Value = Boolean.TRUE; + storedDoc.storeAsURL(filenameURL + ".sxw", propertyvalue_sxw); + + File homedir = new File(templocationSystem); + + File homefiles[] = homedir.listFiles(); + String file = ""; + + for (int i = 0; i < homefiles.length; i++) { + if (homefiles[i].getName().equals(attachmentName + ".sxw")) { + file = homefiles[i].getAbsolutePath(); + } + } + + officeFile = new File(file); + } + + } catch (SecurityException se) { + status.setStatus(4, "Error: " + statusLine); + System.out.println("Security error while saving temporary Document(s). Check file permissions in home directory."); + se.printStackTrace(); + htmlFile = null; + officeFile = null; + return false; + } catch (Exception e) { + status.setStatus(4, "Error: " + statusLine); + System.out.println("Error saving temporary Document(s)"); + e.printStackTrace(); + htmlFile = null; + officeFile = null; + return false; + } + + return true; + } + + + public boolean removeTempDocs() { + /* + if( !htmlFile.exists() && !officeFile.exists() ) + { + System.out.println("Error: Document(s) have not been saved." ); + } + */ + + statusLine = "Removing temp docs"; + status.setStatus(13, statusLine); + + try { + if (isOfficeDoc && isHtmlDoc) { + htmlFile.delete(); + officeFile.delete(); + } else { + if (isOfficeDoc) { + officeFile.delete(); + } else { + htmlFile.delete(); + } + } + } catch (SecurityException se) { + status.setStatus(13, "Error: " + statusLine); + System.out.println("Security Error while deleting temporary Document(s). Check file permissions in home directory."); + se.printStackTrace(); + return false; + } + + return true; + } + + + public void cleanUpOnError() { + try { + if (isOfficeDoc && isHtmlDoc) { + htmlFile.delete(); + officeFile.delete(); + } else { + if (isOfficeDoc) { + officeFile.delete(); + } else { + htmlFile.delete(); + } + } + } catch (SecurityException se) { + System.out.println("Security Error while deleting temporary Document(s). Check file permissions in home directory."); + se.printStackTrace(); + } + } + + + public File[] getAttachments() { + + statusLine = "Retrieving temp docs"; + status.setStatus(8, statusLine); + + File attachments[] = null; + + if (isOfficeDoc && isHtmlDoc) { + attachments = new File[2]; + attachments[0] = htmlFile; + attachments[1] = officeFile; + } else { + if (isOfficeDoc) { + attachments = new File[1]; + attachments[0] = officeFile; + } else { + attachments = new File[1]; + attachments[0] = htmlFile; + } + } + + return attachments; + } + + + public boolean isHtmlAttachment() { + return isHtmlDoc; + } + + + public boolean isOfficeAttachment() { + return isOfficeDoc; + } + +} diff --git a/scripting/examples/java/Newsgroup/PostNewsgroup.java b/scripting/examples/java/Newsgroup/PostNewsgroup.java new file mode 100644 index 000000000..6c6ecdf37 --- /dev/null +++ b/scripting/examples/java/Newsgroup/PostNewsgroup.java @@ -0,0 +1,633 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.border.*; +import java.util.Vector; +import com.sun.star.script.framework.runtime.XScriptContext; + + +public class PostNewsgroup extends JFrame { + + // Post to newsgroup objects + private NewsGroup[] subscribedNewsgroups = null; + private XScriptContext xscriptcontext = null; + + private final int FRAMEX = 300; + private final int FRAMEY = 300; + private final int TEXTBOXWIDTH = 300; + private final int TEXTBOXHEIGHT = 24; + private final int TEXTAREAHEIGHT = 70; + private final int BUTTONWIDTH = 80; + private final int BUTTONHEIGHT = 30; + + private PostNewsgroup window = null; + private JComboBox newsgroupComboBox = null; + private JTextField hostTextField = null; + private JTextField replyTextField = null; + private JTextField subjectTextField = null; + private JTextArea commentTextArea = null; + private JRadioButton officeHtmlButton = null; + private JRadioButton officeButton = null; + private JRadioButton htmlButton = null; + private JButton postButton = null; + private JButton cancelButton = null; + + // JFrame for launch progress dialog + private StatusWindow statusWindow = null; + private String statusLine = ""; + + // Tool tip text + private final String newsgroupText = "Newsgroup name"; + private final String hostText = "Newsgroup host/server name"; + private final String replyText = "Email address to reply to"; + private final String subjectText = "Subject title for the mail"; + private final String commentText = "Additional comment on mail"; + private final String officeHtmlText = + "Post as both Office and HTML attachments"; + private final String officeText = "Post as Office attachment only"; + private final String htmlText = "Post as HTML attachment only"; + private final String postText = "Post to newsgroup"; + private final String cancelText = "Cancel post to newsgroup"; + + + public void post(XScriptContext xsc) { + xscriptcontext = xsc; + window = this; + + // create mailcap and mimetypes files (fix for classloader problem) + MimeConfiguration.createFiles(xscriptcontext); + + this.setTitle("Post Document To Newsgroup"); + this.setLocation(FRAMEX, FRAMEY); + + this.addFocusListener(new FocusAdapter() { + public void focusGained(FocusEvent event) { + System.out.println("Focus gained"); + window.update(window.getGraphics()); + } + + public void focusLost(FocusEvent event) { + System.out.println("Focus lost"); + } + }); + + Container container = getContentPane(); + container.setLayout(new GridBagLayout()); + GridBagConstraints constraints = new GridBagConstraints(); + constraints.fill = GridBagConstraints.BOTH; + + JPanel labelPanel = constructLabelPanel(); + JPanel textPanel = constructTextPanel(); + JPanel optionPanel = constructOptionPanel(); + JPanel buttonPanel = constructButtonPanel(); + + constraints.gridx = 0; + constraints.gridy = 0; + constraints.gridwidth = 1; + constraints.gridheight = 3; + constraints.insets = new Insets(15, 15, 5, 5); + container.add(labelPanel, constraints); + + constraints.gridx = 1; + constraints.gridy = 0; + constraints.gridwidth = 4; + constraints.gridheight = 3; + constraints.insets = new Insets(15, 5, 5, 15); + container.add(textPanel, constraints); + + constraints.gridx = 0; + constraints.gridy = 3; + constraints.gridwidth = 5; + constraints.gridheight = 1; + constraints.insets = new Insets(5, 15, 5, 15); + container.add(optionPanel, constraints); + + constraints.gridx = 0; + constraints.gridy = 4; + constraints.gridwidth = 5; + constraints.gridheight = 1; + constraints.insets = new Insets(5, 5, 5, 5); + container.add(buttonPanel, constraints); + + this.pack(); + this.setResizable(false); + this.setVisible(true); + } + + + private JPanel constructLabelPanel() { + JLabel newsgroupLabel = new JLabel("Newsgroup:"); + JLabel hostLabel = new JLabel("Host:"); + JLabel replyLabel = new JLabel("Reply:"); + JLabel subjectLabel = new JLabel("Subject:"); + JLabel commentLabel = new JLabel("Comment:"); + + newsgroupLabel.setToolTipText(newsgroupText); + hostLabel.setToolTipText(hostText); + replyLabel.setToolTipText(replyText); + subjectLabel.setToolTipText(subjectText); + commentLabel.setToolTipText(commentText); + + JPanel newsgroupPanel = new JPanel(); + newsgroupPanel.setLayout(new BorderLayout()); + newsgroupPanel.add(newsgroupLabel, "West"); + JPanel hostPanel = new JPanel(); + hostPanel.setLayout(new BorderLayout()); + hostPanel.add(hostLabel, "West"); + JPanel replyPanel = new JPanel(); + replyPanel.setLayout(new BorderLayout()); + replyPanel.add(replyLabel, "West"); + JPanel subjectPanel = new JPanel(); + subjectPanel.setLayout(new BorderLayout()); + subjectPanel.add(subjectLabel, "West"); + JPanel commentPanel = new JPanel(); + commentPanel.setLayout(new BorderLayout()); + commentPanel.add(commentLabel, "West"); + JPanel emptyPanel = new JPanel(); + + final int labelWidth = 80; + newsgroupPanel.setPreferredSize(new Dimension(labelWidth, TEXTBOXHEIGHT)); + hostPanel.setPreferredSize(new Dimension(labelWidth, TEXTBOXHEIGHT)); + replyPanel.setPreferredSize(new Dimension(labelWidth, TEXTBOXHEIGHT)); + subjectPanel.setPreferredSize(new Dimension(labelWidth, TEXTBOXHEIGHT)); + commentPanel.setPreferredSize(new Dimension(labelWidth, TEXTBOXHEIGHT)); + + JPanel panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + GridBagConstraints constraints = new GridBagConstraints(); + constraints.fill = GridBagConstraints.BOTH; + constraints.insets = new Insets(5, 5, 5, 5); + + constraints.gridx = 0; + constraints.gridy = 0; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.weightx = constraints.weighty = 0.0; + panel.add(newsgroupPanel, constraints); + + constraints.gridx = 0; + constraints.gridy = 1; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add(hostPanel, constraints); + + constraints.gridx = 0; + constraints.gridy = 2; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add(replyPanel, constraints); + + constraints.gridx = 0; + constraints.gridy = 3; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add(subjectPanel, constraints); + + constraints.gridx = 0; + constraints.gridy = 4; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add(commentPanel, constraints); + + constraints.gridx = 0; + constraints.gridy = 5; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.weightx = constraints.weighty = 1.0; + panel.add(emptyPanel, constraints); + + return panel; + } + + + private JPanel constructTextPanel() { + hostTextField = new JTextField(); + hostTextField.setPreferredSize(new Dimension(TEXTBOXWIDTH, TEXTBOXHEIGHT)); + hostTextField.setToolTipText(hostText); + hostTextField.setBorder(new EtchedBorder()); + + //optionPanel.setBorder( new TitledBorder( new EtchedBorder(), "Document Format" ) ); + newsgroupComboBox = getNewsgroupCombo(); + + replyTextField = new JTextField(); + replyTextField.setPreferredSize(new Dimension(TEXTBOXWIDTH, TEXTBOXHEIGHT)); + replyTextField.setToolTipText(replyText); + replyTextField.setBorder(new EtchedBorder()); + + subjectTextField = new JTextField(); + subjectTextField.setPreferredSize(new Dimension(TEXTBOXWIDTH, TEXTBOXHEIGHT)); + subjectTextField.setToolTipText(subjectText); + subjectTextField.setBorder(new EtchedBorder()); + + commentTextArea = new JTextArea(); + commentTextArea.setPreferredSize(new Dimension(TEXTBOXWIDTH, TEXTAREAHEIGHT)); + commentTextArea.setToolTipText(commentText); + commentTextArea.setBorder(new EtchedBorder()); + + JPanel panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + GridBagConstraints constraints = new GridBagConstraints(); + constraints.fill = GridBagConstraints.BOTH; + constraints.insets = new Insets(5, 5, 5, 5); + + constraints.gridx = 0; + constraints.gridy = 0; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add(newsgroupComboBox, constraints); + + constraints.gridx = 0; + constraints.gridy = 1; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add(hostTextField, constraints); + + constraints.gridx = 0; + constraints.gridy = 2; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add(replyTextField, constraints); + + constraints.gridx = 0; + constraints.gridy = 3; + constraints.gridwidth = 1; + constraints.gridheight = 1; + panel.add(subjectTextField, constraints); + + constraints.gridx = 0; + constraints.gridy = 4; + constraints.gridwidth = 1; + constraints.gridheight = 2; + panel.add(commentTextArea, constraints); + + return panel; + } + + + private JComboBox getNewsgroupCombo() { + newsgroupComboBox = new JComboBox(); + //newsgroupComboBox.setBorder( new EtchedBorder() ); + + newsgroupComboBox.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + // when newsgroup is selected + if (subscribedNewsgroups != null) { + int position = newsgroupComboBox.getSelectedIndex(); + + if (position != -1) { + hostTextField.setText(subscribedNewsgroups[ position ].getHostName()); + newsgroupComboBox.setToolTipText("Newsgroup name: " + + subscribedNewsgroups[ position ].getNewsgroupName() + " (Host name: " + + subscribedNewsgroups[ position ].getHostName() + ")"); + } + } + } + }); + + NewsGroup groupToSend = null; + SubscribedNewsgroups newsgroups = new SubscribedNewsgroups(); + subscribedNewsgroups = newsgroups.getNewsGroups(); + + // Test for no .mozilla or no subscribed newsgroups + // subscribedNewsgroups = null; + + if (subscribedNewsgroups == null) { + JOptionPane.showMessageDialog(window, + "No subscribed newsgroups found in mozilla/netscape profile \nPlease enter newsgroup and host name", + "Newsgroups Information", JOptionPane.INFORMATION_MESSAGE); + } else { + // Copy all newsgroups into a vector for comparison + // Alter entries (to include host name) if duplication is found + ArrayList vector = new ArrayList(subscribedNewsgroups.length); + + for (int i = 0; i < subscribedNewsgroups.length; i++) { + vector.add(subscribedNewsgroups[i].getNewsgroupName()); + } + + // Compare and alter + for (int i = 0; i < subscribedNewsgroups.length; i++) { + // check if combo box already has a newsgroup with same name + // then add host name to differentiate + for (int j = 0; j < subscribedNewsgroups.length; j++) { + if (j != i + && subscribedNewsgroups[j].getNewsgroupName().equalsIgnoreCase( + subscribedNewsgroups[i].getNewsgroupName())) { + vector.set(j, subscribedNewsgroups[j].getNewsgroupName() + " (" + + subscribedNewsgroups[j].getHostName() + ")"); + vector.set(i, subscribedNewsgroups[i].getNewsgroupName() + " (" + + subscribedNewsgroups[i].getHostName() + ")"); + } + } + } + + // Copy converted newsgroups from vector to combo box + for (int i = 0; i < subscribedNewsgroups.length; i++) { + newsgroupComboBox.addItem(vector.elementAt(i)); + } + }// else + + newsgroupComboBox.setPreferredSize(new Dimension(TEXTBOXWIDTH, TEXTBOXHEIGHT)); + newsgroupComboBox.setEditable(true); + + return newsgroupComboBox; + } + + + + private JPanel constructOptionPanel() { + officeHtmlButton = new JRadioButton("Office and HTML", true); + officeHtmlButton.setToolTipText(officeHtmlText); + + officeButton = new JRadioButton("Office"); + officeButton.setToolTipText(officeText); + + htmlButton = new JRadioButton("HTML"); + htmlButton.setToolTipText(htmlText); + + JRadioButton[] rbuttons = { officeHtmlButton, officeButton, htmlButton }; + ButtonGroup radioButtonGroup = new ButtonGroup(); + + for (int i = 0; i < rbuttons.length; i++) { + radioButtonGroup.add(rbuttons[i]); + } + + JPanel optionPanel = new JPanel(); + optionPanel.setBorder(new TitledBorder(new EtchedBorder(), "Document Format")); + optionPanel.setLayout(new GridBagLayout()); + GridBagConstraints constraints = new GridBagConstraints(); + constraints.fill = GridBagConstraints.BOTH; + + constraints.gridx = 0; + constraints.gridy = 0; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.insets = new Insets(5, 5, 5, 30); + optionPanel.add(officeHtmlButton, constraints); + + constraints.gridx = 1; + constraints.gridy = 0; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.insets = new Insets(5, 20, 5, 30); + optionPanel.add(officeButton, constraints); + + constraints.gridx = 2; + constraints.gridy = 0; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.insets = new Insets(5, 20, 5, 5); + optionPanel.add(htmlButton, constraints); + + return optionPanel; + } + + + + public boolean sendingActions() { + // posting actions + // Validate the data + if (isValidData()) { + // Create status window + StatusWindow statusWindow = new StatusWindow(window, "Posting to Newsgroup", + FRAMEX, FRAMEY); + + statusWindow.setVisible(true); + statusLine = "Ready to send..."; + statusWindow.setStatus(0, statusLine); + + // Get the boolean values for HTML/Office document + // params: ( XScriptContext, StatusWindow, html document, office document ) + + boolean html = false; + boolean office = false; + + if (officeHtmlButton.isSelected()) { + html = true; + office = true; + } + + if (officeButton.isSelected()) { + office = true; + html = false; + } + + if (htmlButton.isSelected()) { + html = true; + office = false; + } + + OfficeAttachment officeAttach = new OfficeAttachment(xscriptcontext, + statusWindow, html, office); + + statusLine = "Getting user input"; + statusWindow.setStatus(2, statusLine); + // Get replyto, subject, comment from textboxes + String replyto = replyTextField.getText(); + String subject = subjectTextField.getText(); + String comment = commentTextArea.getText(); + + // Get newsgroup from combo box (corresponding position) + String host = ""; + String group = ""; + int position = newsgroupComboBox.getSelectedIndex(); + + if (subscribedNewsgroups == null || position == -1) { + host = hostTextField.getText(); + group = newsgroupComboBox.getSelectedItem().toString(); + } else { + host = subscribedNewsgroups[ position ].getHostName(); + group = subscribedNewsgroups[ position ].getNewsgroupName(); + } + + statusLine = "Creating sender object"; + statusWindow.setStatus(3, statusLine); + Sender sender = new Sender(statusWindow, officeAttach, replyto, subject, + comment, host, group); + + if (!sender.sendMail()) { + statusWindow.enableCancelButton(true); + officeAttach.cleanUpOnError(); + return false; + } + + statusLine = "Send is complete"; + statusWindow.setStatus(14, statusLine); + } else { + return false; + } + + return true; + } + + + private JPanel constructButtonPanel() { + Action postAction = new AbstractAction() { + public void actionPerformed(ActionEvent event) { + // posting actions + sendingActions(); + }// actionPerformed + }; + + Action cancelAction = new AbstractAction() { + public void actionPerformed(ActionEvent event) { + // cancelling actions + window.dispose(); + } + }; + + postButton = new JButton(); + postButton.setAction(postAction); + postButton.setToolTipText(postText); + postButton.setText("Post"); + postButton.setPreferredSize(new Dimension(BUTTONWIDTH + 20, BUTTONHEIGHT)); + + cancelButton = new JButton(); + cancelButton.setAction(cancelAction); + cancelButton.setToolTipText(cancelText); + cancelButton.setText("Cancel"); + cancelButton.setPreferredSize(new Dimension(BUTTONWIDTH + 20, BUTTONHEIGHT)); + + JSeparator sep = new JSeparator(SwingConstants.HORIZONTAL); + + JPanel buttonPanel = new JPanel(); + buttonPanel.setLayout(new GridBagLayout()); + GridBagConstraints constraints = new GridBagConstraints(); + constraints.fill = GridBagConstraints.BOTH; + constraints.insets = new Insets(5, 5, 5, 5); + + JPanel emptyPanel1 = new JPanel(); + emptyPanel1.setPreferredSize(new Dimension(BUTTONWIDTH, BUTTONHEIGHT)); + + JPanel emptyPanel2 = new JPanel(); + emptyPanel2.setPreferredSize(new Dimension(BUTTONWIDTH, BUTTONHEIGHT)); + + constraints.gridx = 0; + constraints.gridy = 0; + constraints.gridwidth = 4; + constraints.gridheight = 1; + buttonPanel.add(sep, constraints); + + constraints.gridx = 0; + constraints.gridy = 1; + constraints.gridwidth = 1; + constraints.gridheight = 1; + buttonPanel.add(emptyPanel1, constraints); + + constraints.gridx = 1; + constraints.gridy = 1; + constraints.gridwidth = 1; + constraints.gridheight = 1; + buttonPanel.add(emptyPanel2, constraints); + + constraints.gridx = 2; + constraints.gridy = 1; + constraints.gridwidth = 1; + constraints.gridheight = 1; + buttonPanel.add(postButton, constraints); + + constraints.gridx = 3; + constraints.gridy = 1; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.insets = new Insets(5, 5, 5, 0); + buttonPanel.add(cancelButton, constraints); + + return buttonPanel; + } + + + public void enableButtons(boolean enable) { + if (enable) { + postButton.setEnabled(true); + cancelButton.setEnabled(true); + } else { + postButton.setEnabled(false); + cancelButton.setEnabled(false); + } + } + + + private boolean isValidData() { + // newsgroupComboBox must not be blank (format? dots and whitespace) + String newsgroupString = ""; + int position = newsgroupComboBox.getSelectedIndex(); + + if (subscribedNewsgroups == null || position == -1) { + newsgroupString = newsgroupComboBox.getSelectedItem().toString(); + } else { + newsgroupString = subscribedNewsgroups[ position ].getNewsgroupName(); + } + + if (newsgroupString.length() == 0) { + newsgroupComboBox.requestFocus(); + JOptionPane.showMessageDialog(window, "Please enter a newsgroup name", + "Input Error", JOptionPane.ERROR_MESSAGE); + return false; + } + + + // hostTextField must not be blank (format?) + String hostString = hostTextField.getText(); + + if (hostString.length() == 0) { + hostTextField.requestFocus(); + JOptionPane.showMessageDialog(window, "Please enter a hostname", "Input Error", + JOptionPane.ERROR_MESSAGE); + return false; + } + + + // replyTextField must have <string>@<string>.<string> + // (string at least 2 chars long) + // consider <s>.<s>@<s>.<s>.<s> format? (array of dot positions?) + String replyString = replyTextField.getText(); + int atPos = replyString.indexOf("@"); + int dotPos = replyString.lastIndexOf("."); + int length = replyString.length(); + + if (length == 0 || atPos == -1 || dotPos == -1 || atPos < 2 || dotPos < atPos + || dotPos + 2 == length || atPos + 2 == dotPos + || atPos != replyString.lastIndexOf("@") || replyString.indexOf(" ") != -1) { + replyTextField.requestFocus(); + JOptionPane.showMessageDialog(window, + "Please enter a valid reply to email address", "Input Error", + JOptionPane.ERROR_MESSAGE); + return false; + } + + + // subjectTextField must not be blank? + String subjectString = subjectTextField.getText(); + + if (subjectString.length() == 0) { + subjectTextField.requestFocus(); + JOptionPane.showMessageDialog(window, "Please enter subject title", + "Input Error", JOptionPane.ERROR_MESSAGE); + return false; + } + + // details are valid + return true; + } + +} diff --git a/scripting/examples/java/Newsgroup/Sender.java b/scripting/examples/java/Newsgroup/Sender.java new file mode 100644 index 000000000..00b3db87b --- /dev/null +++ b/scripting/examples/java/Newsgroup/Sender.java @@ -0,0 +1,141 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +import javax.mail.*; +import javax.mail.internet.*; +import com.msoft.mail.provider.nntp.NNTPTransport; +import java.util.Properties; +import java.io.*; +import javax.activation.*; + + +public class Sender { + // Constructor params: + private StatusWindow status = null; + private OfficeAttachment attachments = null; + private String replyto = ""; + private String subject = ""; + private String comment = ""; + private String hostname = ""; + private String newsgroup = ""; + private String statusLine = ""; + + + + public Sender(StatusWindow sw, OfficeAttachment attach, String reply, + String sub, String com, String host, String group) { + status = sw; + attachments = attach; + replyto = reply; + subject = sub; + comment = com; + hostname = host; + newsgroup = group; + } + + + + public boolean sendMail() { + int statusPos = 5; + + try { + attachments.createTempDocs(); + // Property for any information + Properties props = new Properties(); + + // Create unique session (null is unused authenticator info) + statusLine = "Creating unique session"; + status.setStatus(statusPos, statusLine); // 5 + Session session = Session.getInstance(props, null); + + // Create message + statusPos++; // 6 + statusLine = "Creating message"; + status.setStatus(statusPos, statusLine); + MimeMessage message = new MimeMessage(session); + message.setFrom(new InternetAddress(replyto)); + message.setSubject(subject); + message.setText(comment); + message.addHeader("Newsgroups", newsgroup); + + // Buildup bodypart with text and attachments + Multipart multipart = new MimeMultipart(); + + BodyPart messageBodyPart = new MimeBodyPart(); + messageBodyPart.setText(comment); + multipart.addBodyPart(messageBodyPart); + + statusPos++; // 7 + statusLine = "Adding attachment(s)"; + status.setStatus(statusPos, statusLine); + File attachs[] = attachments.getAttachments(); + + for (int i = 0; i < attachs.length; i++) { + messageBodyPart = new MimeBodyPart(); + DataSource filesource = new FileDataSource(attachs[i]); + messageBodyPart.setDataHandler(new DataHandler(filesource)); + messageBodyPart.setFileName(attachs[i].getName()); + multipart.addBodyPart(messageBodyPart); + } + + // Add multipart to mail + message.setContent(multipart); + + // Create and send NNTP transport + statusPos += 2; // 9 + statusLine = "Creating NNTP transport"; + status.setStatus(statusPos, statusLine); + Transport transport = new NNTPTransport(session, + new URLName("news:" + newsgroup)); + + // Null parameters are for user name and password + statusPos++; // 10 + statusLine = "Connecting to mail server"; + status.setStatus(statusPos, statusLine); + transport.connect(hostname, null, null); + + statusPos++; // 11 + statusLine = "Sending message"; + status.setStatus(statusPos, statusLine); + transport.sendMessage(message, message.getAllRecipients()); + + statusPos++; // 12 + statusLine = "Closing transport"; + status.setStatus(statusPos, statusLine); + transport.close(); + + // Clean up when finished + attachments.removeTempDocs(); + + return true; + } catch (MessagingException me) { + if (statusPos == 10) { + statusLine = "Error connecting (User authentication?)"; + } + + status.setStatus(statusPos, statusLine); + System.out.println("Error sending message: "); + me.printStackTrace(); + return false; + } + + } + +} diff --git a/scripting/examples/java/Newsgroup/StatusWindow.java b/scripting/examples/java/Newsgroup/StatusWindow.java new file mode 100644 index 000000000..7b37c8fa7 --- /dev/null +++ b/scripting/examples/java/Newsgroup/StatusWindow.java @@ -0,0 +1,147 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.border.*; + +public class StatusWindow extends JFrame { + + private JProgressBar progressBar = null; + private JTextField statusLabel = null; + private JButton cancelButton = null; + private JFrame statusWindow = null; + private PostNewsgroup mainWindow = null; + + private final int MAXPROGRESS = 13; + private final int MINPROGRESS = 0; + + + public StatusWindow(PostNewsgroup mw, String title, int parentX, int parentY) { + this.setTitle(title); + this.setLocation(parentX + 100, parentY + 100); + statusWindow = this; + mainWindow = mw; + + mainWindow.enableButtons(false); + + statusWindow.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent event) { + mainWindow.enableButtons(true); + } + }); + + progressBar = new JProgressBar(); + progressBar.setStringPainted(true); + progressBar.setMaximum(MAXPROGRESS); + progressBar.setMinimum(MINPROGRESS); + progressBar.setSize(30, 400); + + JLabel progLabel = new JLabel("Progress:"); + + JPanel progressPanel = new JPanel(); + progressPanel.setLayout(new BorderLayout(10, 0)); + progressPanel.add(progLabel, "West"); + progressPanel.add(progressBar, "East"); + + statusLabel = new JTextField(); + statusLabel.setColumns(25); + statusLabel.setEditable(false); + statusLabel.setBorder(null); + JPanel statusPanel = new JPanel(); + statusPanel.setLayout(new BorderLayout()); + statusPanel.add(statusLabel, "West"); + + cancelButton = new JButton("Cancel"); + cancelButton.setSize(30, 100); + cancelButton.setEnabled(false); + cancelButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent event) { + // cancelling actions + mainWindow.enableButtons(true); + statusWindow.dispose(); + } + }); + + JPanel buttonPanel = new JPanel(); + buttonPanel.setLayout(new BorderLayout(0, 5)); + buttonPanel.add(cancelButton, "East"); + buttonPanel.add(new JSeparator(SwingConstants.HORIZONTAL), "North"); + + Container container = getContentPane(); + container.setLayout(new GridBagLayout()); + GridBagConstraints constraints = new GridBagConstraints(); + constraints.fill = GridBagConstraints.BOTH; + + constraints.gridx = 0; + constraints.gridy = 0; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.insets = new Insets(15, 15, 10, 15); + container.add(progressPanel, constraints); + + constraints.gridx = 0; + constraints.gridy = 1; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.insets = new Insets(10, 15, 10, 15); + container.add(statusPanel, constraints); + + constraints.gridx = 0; + constraints.gridy = 2; + constraints.gridwidth = 1; + constraints.gridheight = 1; + constraints.insets = new Insets(10, 15, 5, 15); + container.add(buttonPanel, constraints); + + this.pack(); + this.setResizable(false); + + } + + + public void setStatus(int progress, String status) { + progressBar.setValue(progress); + statusLabel.setText(status); + statusLabel.setToolTipText(status); + + if (progress == MAXPROGRESS) { + cancelButton.setEnabled(true); + cancelButton.setText("Close"); + } + + update(getGraphics()); + mainWindow.update(mainWindow.getGraphics()); + } + + + public void enableCancelButton(boolean enable) { + if (enable) { + cancelButton.setEnabled(true); + cancelButton.setText("Finish"); + } else { + cancelButton.setEnabled(false); + cancelButton.setText("Cancel"); + } + + } + +} diff --git a/scripting/examples/java/Newsgroup/SubscribedNewsgroups.java b/scripting/examples/java/Newsgroup/SubscribedNewsgroups.java new file mode 100644 index 000000000..eb135a3e8 --- /dev/null +++ b/scripting/examples/java/Newsgroup/SubscribedNewsgroups.java @@ -0,0 +1,349 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +import java.io.*; +import java.util.Vector; + + +public class SubscribedNewsgroups { + + + private static NewsGroup[] allSubscribed = null; + private static boolean windows = false; + + public static void main(String[] args) { + // Test the class + SubscribedNewsgroups subscribed = new SubscribedNewsgroups(); + + NewsGroup allGroups[] = subscribed.getNewsGroups(); + + if (allGroups == null) { + System.out.println("Could not find subscribed newsgroups from mozilla/netscape mailrc files"); + } else { + for (int i = 0; i < allGroups.length; i++) { + System.out.println("Hostname is: " + allGroups[i].getHostName() + + " Newsgroup is: " + allGroups[i].getNewsgroupName()); + } + } + } + + + + // Only public method of the class + // Returns and array of unique NewsGroup objects + public NewsGroup[] getNewsGroups() { + windows = false; + + if (System.getProperty("os.name").indexOf("Windows") != -1) { + windows = true; + } + + String mozillaHome = ""; + + if (windows) { + mozillaHome = System.getProperty("user.home") + + System.getProperty("file.separator") + "Application Data" + + System.getProperty("file.separator") + "Mozilla" + + System.getProperty("file.separator") + "Profiles"; + } else { + mozillaHome = System.getProperty("user.home") + + System.getProperty("file.separator") + ".mozilla"; + } + + if (!new File(mozillaHome).isDirectory()) { + return null; + } + + // Get all the profiles belonging to the user + File profiles[] = findProfiles(new File(mozillaHome)); + + if (profiles.length < 1) { + return null; + } + + // Get the News directory for each profile + File allNewsDirs[] = new File[ profiles.length ]; + + for (int i = 0; i < profiles.length; i++) { + File newsDir = findNewsDir(profiles[i]); + allNewsDirs[i] = newsDir; + } + + // Check that at least one News directory exists and remove nulls + boolean newsFound = false; + + for (int i = 0; i < allNewsDirs.length; i++) { + if (allNewsDirs[i] != null) { + newsFound = true; + break; + } + } + + if (!newsFound) { + return null; + } + + // Get all the mailrc files for each News directory + File allMailrcs[] = findMailrcFiles(allNewsDirs); + + if (allMailrcs == null) { + return null; + } + + ArrayList<NewsGroup> subscribed = new ArrayList<NewsGroup>(); + + // Get the newsgroups in each mailrc file + for (int i = 0; i < allMailrcs.length; i++) { + File mailrc = (File) allMailrcs[i]; + NewsGroup newsgroup[] = findNewsgroups(mailrc); + + //if the Newsgroup has not already been added to the list + for (int j = 0; j < newsgroup.length; j++) { + // if newsgroup is unique then add to the list + if (!listed(newsgroup[j], subscribed)) { + subscribed.addElement(newsgroup[j]); + } + } + } + + // Copy all unique Newsgroups into the global array + allSubscribed = new NewsGroup[ subscribed.size() ]; + subscribed.toArray(allSubscribed); + + // Test that at least one subscribed newsgroup has been found + if (allSubscribed.length < 1) { + return null; + } + + return allSubscribed; + } + + + + + // Tests if the NewsGroup object has already been listed by another mailrc file + private static boolean listed(NewsGroup newsgroup, + ArrayList<NewsGroup> uniqueSubscription) { + for (int i = 0; i < uniqueSubscription.size(); i++) { + NewsGroup tempGroup = uniqueSubscription.elementAt(i); + + // Test for duplication + if (newsgroup.getHostName().equalsIgnoreCase(tempGroup.getHostName()) && + newsgroup.getNewsgroupName().equalsIgnoreCase(tempGroup.getNewsgroupName())) + return true; + } + + return false; + } + + + + + // Finds all the NewsGroups in an individual mailrc file + private static NewsGroup[] findNewsgroups(File mailrcfile) { + + String hostname = ""; + String newsgroup = ""; + NewsGroup mailrcNewsGroups[] = null; + + //Retrieve name of news host/server from file name + //Sequentially access each of the newsgroups + //If the newsgroup is not already contained in the global NewsGroup[] array then add it + + String filename = mailrcfile.getPath(); + + if (windows) { + // Windows format "staroffice-news.germany.sun.com.rc" + int hostNameStart = filename.lastIndexOf("\\") + 1; + int hostNameEnd = filename.indexOf(".rc"); + hostname = filename.substring(hostNameStart, hostNameEnd); + } else { + // Unix/Linux format "newsrc-staroffice-news.germany.sun.com" + int hostNameStart = filename.lastIndexOf("newsrc-") + 7; + hostname = filename.substring(hostNameStart, filename.length()); + } + + // Assumes the content format in Window is the same as Unix/Linux (unknown at the moment) + // i.e. a list of newsgroups each ending with a ":" + LineNumberReader in = null; + + try { + in = new LineNumberReader(new FileReader(mailrcfile)); + ArrayList groups = new ArrayList(); + String inString = ""; + int line = 0; + + while (inString != null) { + in.setLineNumber(line); + inString = in.readLine(); + line++; + + if (inString != null) { + int newsgroupEnd = inString.indexOf(":"); + newsgroup = inString.substring(0, newsgroupEnd); + NewsGroup group = new NewsGroup(hostname, newsgroup); + groups.addElement(group); + } + } + + mailrcNewsGroups = new NewsGroup[ groups.size() ]; + groups.copyInto(mailrcNewsGroups); + in.close(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + + return mailrcNewsGroups; + } + + + // Finds all the mailrc files for all the given News directories + private static File[] findMailrcFiles(File[] newsDirs) { + ArrayList allFiles = new ArrayList(); + + for (int i = 0; i < newsDirs.length; i++) { + if (newsDirs[i] != null) { + File mailrcFiles[] = newsDirs[i].listFiles(new VersionFilter()); + + if (mailrcFiles != null) { + for (int j = 0; j < mailrcFiles.length; j++) { + allFiles.addElement(mailrcFiles[j]); + } + } + } + } + + File allMailrcFiles[] = new File[ allFiles.size() ]; + allFiles.copyInto(allMailrcFiles); + + if (allMailrcFiles.length == 0) { + return null; + } + + return allMailrcFiles; + } + + + // Finds all profiles belonging to one user (can be more than one) + private static File[] findProfiles(File start) { + // Get all files and directories in .mozilla + File allFiles[] = start.listFiles(); + File[] dirs = new File[allFiles.length]; + int dirCounter = 0; + + // Remove files leaving directories only + for (int i = 0; i < allFiles.length; i++) { + if (allFiles[i].isDirectory()) { + dirs[dirCounter] = allFiles[i]; + dirCounter++; + } + } + + // Add each directory to a user profile array + File[] profileDirs = new File[dirCounter]; + + for (int i = 0; i < dirCounter; i++) { + profileDirs[i] = dirs[i]; + } + + // return a File array containing the profile dirs + return profileDirs; + } + + + // Recursively searches for the News directory for a given profile directory + private static File findNewsDir(File start) { + File mailrcFile = null; + + // File array containing all matches for the version filter ("News") + File files[] = start.listFiles(new VersionFilter()); + + // If the array is empty then no matches were found + if (files.length == 0) { + // File array of all the directories in File start + File dirs[] = start.listFiles(new DirFilter()); + + // for each of the directories check for a match + for (int i = 0; i < dirs.length; i++) { + mailrcFile = findNewsDir(dirs[i]); + + if (mailrcFile != null) { + // break the for loop + break; + } + } + } else { + // end recursion + // Check for a News directory inside the News directory (fix for bug) + // Original solution had only "mailrcFile = files[0];" + + boolean noChildNews = true; + File checkChildNewsDirs[] = files[0].listFiles(new VersionFilter()); + + if (checkChildNewsDirs != null) { + for (int i = 0; i < checkChildNewsDirs.length; i++) { + if (checkChildNewsDirs[i].getName().equals("News")) { + noChildNews = false; + break; + } + } + } + + if (noChildNews) { + mailrcFile = files[0]; + } else { + String childNewsPathName = files[0].getAbsolutePath() + + System.getProperty("file.separator") + "News"; + mailrcFile = new File(childNewsPathName); + } + + } + + // return a File representing the News dir in a profile + return mailrcFile; + } +} + + + +class DirFilter implements FileFilter { + public boolean accept(File aFile) { + return aFile.isDirectory(); + } +} + + +class VersionFilter implements FileFilter { + public boolean accept(File aFile) { + if (System.getProperty("os.name").indexOf("Windows") != -1) { + if (aFile.getName().compareToIgnoreCase("News") == 0 || + aFile.getName().indexOf(".rc") != -1) { + return true; + } + } else { + if (aFile.getName().compareToIgnoreCase("News") == 0 || + aFile.getName().indexOf("newsrc") != -1) { + return true; + } + } + + return false; + } +} diff --git a/scripting/examples/java/debugger/DebugRunner.java b/scripting/examples/java/debugger/DebugRunner.java new file mode 100644 index 000000000..a3b4869fe --- /dev/null +++ b/scripting/examples/java/debugger/DebugRunner.java @@ -0,0 +1,87 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +import java.io.File; +import java.io.InputStream; +import java.io.IOException; +import java.net.URL; +import java.net.URLDecoder; + +import com.sun.star.uno.XComponentContext; +import com.sun.star.script.framework.provider.PathUtils; +import com.sun.star.script.provider.XScriptContext; + +public class DebugRunner { + + private static final String FILE_URL_PREFIX = + System.getProperty("os.name").startsWith("Windows") == true ? + "file:///" : "file://"; + + public void go(final XScriptContext xsctxt, String language, String uri, + String filename) { + + OOScriptDebugger debugger; + String path = ""; + + if (language.equals("JavaScript")) { + debugger = new OORhinoDebugger(); + } else if (language.equals("BeanShell")) { + debugger = new OOBeanShellDebugger(); + } else { + return; + } + + if (uri.startsWith(FILE_URL_PREFIX)) { + uri = URLDecoder.decode(uri); + String s = uri.substring(FILE_URL_PREFIX.length()); + File f = new File(s); + + if (f.exists()) { + if (f.isDirectory()) { + if (!filename.equals("")) { + path = new File(f, filename).getAbsolutePath(); + } + } else { + path = f.getAbsolutePath(); + } + } + + debugger.go(xsctxt, path); + } else { + if (!uri.endsWith("/")) { + uri += "/"; + } + + String script = uri + filename; + InputStream is; + + try { + is = PathUtils.getScriptFileStream( + script, xsctxt.getComponentContext()); + + if (is != null) { + debugger.go(xsctxt, is); + } + } catch (IOException ioe) { + System.out.println("Error loading script: " + script); + } + } + } +} diff --git a/scripting/examples/java/debugger/OOBeanShellDebugger.java b/scripting/examples/java/debugger/OOBeanShellDebugger.java new file mode 100644 index 000000000..68a508784 --- /dev/null +++ b/scripting/examples/java/debugger/OOBeanShellDebugger.java @@ -0,0 +1,393 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +import javax.swing.JFrame; +import javax.swing.JTextArea; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFileChooser; +import javax.swing.JOptionPane; +import javax.swing.text.Document; +import javax.swing.event.DocumentListener; +import javax.swing.event.DocumentEvent; + +import java.awt.FlowLayout; +import java.awt.Graphics; +import java.awt.Color; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Polygon; +import java.awt.Rectangle; +import java.awt.Dimension; +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; + +import java.io.File; +import java.io.InputStream; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; + +import com.sun.star.script.provider.XScriptContext; +import bsh.Interpreter; + +public class OOBeanShellDebugger implements OOScriptDebugger, ActionListener, + DocumentListener { + + private JFrame frame; + private JTextArea ta; + private GlyphGutter gg; + private XScriptContext context; + private int currentPosition = -1; + private int linecount; + private Interpreter sessionInterpreter; + private Thread execThread = null; + private String filename = null; + + /* Entry point for script execution */ + public void go(XScriptContext context, String filename) { + if (filename != null && filename != "") { + try { + FileInputStream fis = new FileInputStream(filename); + this.filename = filename; + go(context, fis); + } catch (IOException ioe) { + JOptionPane.showMessageDialog(frame, + "Error loading file: " + ioe.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + } + } + } + + /* Entry point for script execution */ + public void go(XScriptContext context, InputStream in) { + this.context = context; + initUI(); + + if (in != null) { + try { + loadFile(in); + } catch (IOException ioe) { + JOptionPane.showMessageDialog(frame, + "Error loading stream: " + ioe.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + } + } + } + + public void loadFile(InputStream in) throws IOException { + + /* Remove ourselves as a DocumentListener while loading the file + so we don't get a storm of DocumentEvents during loading */ + ta.getDocument().removeDocumentListener(this); + + byte[] contents = new byte[1024]; + int len = 0, pos = 0; + + while ((len = in.read(contents, 0, 1024)) != -1) { + ta.insert(new String(contents, 0, len), pos); + pos += len; + } + + try { + in.close(); + } catch (IOException ignore) { + } + + /* Update the GlyphGutter and add back the DocumentListener */ + gg.update(); + ta.getDocument().addDocumentListener(this); + } + + private void initUI() { + frame = new JFrame("BeanShell Debug Window"); + ta = new JTextArea(); + ta.setRows(15); + ta.setColumns(40); + ta.setLineWrap(false); + linecount = ta.getLineCount(); + + gg = new GlyphGutter(this); + + final JScrollPane sp = new JScrollPane(); + sp.setViewportView(ta); + sp.setRowHeaderView(gg); + + ta.getDocument().addDocumentListener(this); + String[] labels = {"Run", "Clear", "Save", "Close"}; + JPanel p = new JPanel(); + p.setLayout(new FlowLayout()); + + for (int i = 0; i < labels.length; i++) { + JButton b = new JButton(labels[i]); + b.addActionListener(this); + p.add(b); + + if (labels[i].equals("Save") && filename == null) { + b.setEnabled(false); + } + } + + frame.getContentPane().add(sp, "Center"); + frame.getContentPane().add(p, "South"); + frame.pack(); + frame.show(); + } + + /* Implementation of DocumentListener interface */ + public void insertUpdate(DocumentEvent e) { + doChanged(e); + } + + public void removeUpdate(DocumentEvent e) { + doChanged(e); + } + + public void changedUpdate(DocumentEvent e) { + doChanged(e); + } + + /* If the number of lines in the JTextArea has changed then update the + GlyphGutter */ + public void doChanged(DocumentEvent e) { + if (linecount != ta.getLineCount()) { + gg.update(); + linecount = ta.getLineCount(); + } + } + + private void startExecution() { + execThread = new Thread() { + public void run() { + Interpreter interpreter = new Interpreter(); + interpreter.getNameSpace().clear(); + + // reset position and repaint gutter so no red arrow appears + currentPosition = -1; + gg.repaint(); + + try { + interpreter.set("context", context); + interpreter.eval(ta.getText()); + } catch (bsh.EvalError err) { + currentPosition = err.getErrorLineNumber() - 1; + + try { + // scroll to line of the error + int line = ta.getLineStartOffset(currentPosition); + Rectangle rect = ta.modelToView(line); + ta.scrollRectToVisible(rect); + } catch (Exception e) { + // couldn't scroll to line, do nothing + } + + gg.repaint(); + + JOptionPane.showMessageDialog(frame, "Error at line " + + String.valueOf(err.getErrorLineNumber()) + + "\n\n: " + err.getErrorText(), + "Error", JOptionPane.ERROR_MESSAGE); + } catch (Exception e) { + JOptionPane.showMessageDialog(frame, + "Error: " + e.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + } + } + }; + execThread.start(); + } + + private void promptForSaveName() { + JFileChooser chooser = new JFileChooser(); + chooser.setFileFilter(new javax.swing.filechooser.FileFilter() { + public boolean accept(File f) { + if (f.isDirectory() || f.getName().endsWith(".bsh")) { + return true; + } + + return false; + } + + public String getDescription() { + return ("BeanShell files: *.bsh"); + } + }); + + int ret = chooser.showSaveDialog(frame); + + if (ret == JFileChooser.APPROVE_OPTION) { + filename = chooser.getSelectedFile().getAbsolutePath(); + + if (!filename.endsWith(".bsh")) { + filename += ".bsh"; + } + } + + } + + private void saveTextArea() { + if (filename == null) { + promptForSaveName(); + } + + FileOutputStream fos = null; + + if (filename != null) { + try { + File f = new File(filename); + fos = new FileOutputStream(f); + String s = ta.getText(); + fos.write(s.getBytes(), 0, s.length()); + } catch (IOException ioe) { + JOptionPane.showMessageDialog(frame, + "Error saving file: " + ioe.getMessage(), + "Error", JOptionPane.ERROR_MESSAGE); + } finally { + if (fos != null) { + try { + fos.close(); + } catch (IOException ignore) { + } + } + } + } + } + + public void actionPerformed(ActionEvent e) { + if (e.getActionCommand().equals("Run")) { + startExecution(); + } else if (e.getActionCommand().equals("Close")) { + frame.dispose(); + } else if (e.getActionCommand().equals("Save")) { + saveTextArea(); + } else if (e.getActionCommand().equals("Clear")) { + ta.setText(""); + } + } + + public JTextArea getTextArea() { + return ta; + } + + public int getCurrentPosition() { + return currentPosition; + } +} + +class GlyphGutter extends JComponent { + + private OOBeanShellDebugger debugger; + private final String DUMMY_STRING = "99"; + + GlyphGutter(OOBeanShellDebugger debugger) { + this.debugger = debugger; + update(); + } + + public void update() { + JTextArea textArea = debugger.getTextArea(); + Font font = textArea.getFont(); + setFont(font); + + FontMetrics metrics = getFontMetrics(font); + int h = metrics.getHeight(); + int lineCount = textArea.getLineCount() + 1; + + String dummy = Integer.toString(lineCount); + + if (dummy.length() < 2) { + dummy = DUMMY_STRING; + } + + Dimension d = new Dimension(); + d.width = metrics.stringWidth(dummy) + 16; + d.height = lineCount * h + 100; + setPreferredSize(d); + setSize(d); + } + + public void paintComponent(Graphics g) { + JTextArea textArea = debugger.getTextArea(); + + Font font = textArea.getFont(); + g.setFont(font); + + FontMetrics metrics = getFontMetrics(font); + Rectangle clip = g.getClipBounds(); + + g.setColor(getBackground()); + g.fillRect(clip.x, clip.y, clip.width, clip.height); + + int ascent = metrics.getMaxAscent(); + int h = metrics.getHeight(); + int lineCount = textArea.getLineCount() + 1; + + int startLine = clip.y / h; + int endLine = (clip.y + clip.height) / h + 1; + int width = getWidth(); + + if (endLine > lineCount) { + endLine = lineCount; + } + + for (int i = startLine; i < endLine; i++) { + String text; + text = Integer.toString(i + 1) + " "; + int w = metrics.stringWidth(text); + int y = i * h; + g.setColor(Color.blue); + g.drawString(text, 0, y + ascent); + int x = width - ascent; + + // if currentPosition is not -1 then a red arrow will be drawn + if (i == debugger.getCurrentPosition()) { + drawArrow(g, ascent, x, y); + } + } + } + + private void drawArrow(Graphics g, int ascent, int x, int y) { + Polygon arrow = new Polygon(); + int dx = x; + y += ascent - 10; + int dy = y; + arrow.addPoint(dx, dy + 3); + arrow.addPoint(dx + 5, dy + 3); + + for (x = dx + 5; x <= dx + 10; x++, y++) { + arrow.addPoint(x, y); + } + + for (x = dx + 9; x >= dx + 5; x--, y++) { + arrow.addPoint(x, y); + } + + arrow.addPoint(dx + 5, dy + 7); + arrow.addPoint(dx, dy + 7); + + g.setColor(Color.red); + g.fillPolygon(arrow); + g.setColor(Color.black); + g.drawPolygon(arrow); + } +}; + diff --git a/scripting/examples/java/debugger/OORhinoDebugger.java b/scripting/examples/java/debugger/OORhinoDebugger.java new file mode 100644 index 000000000..5144637ac --- /dev/null +++ b/scripting/examples/java/debugger/OORhinoDebugger.java @@ -0,0 +1,97 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +import javax.swing.SwingUtilities; +import java.io.InputStream; + +import org.mozilla.javascript.Context; +import org.mozilla.javascript.Scriptable; +import org.mozilla.javascript.ImporterTopLevel; +import org.mozilla.javascript.tools.debugger.Main; +import org.mozilla.javascript.tools.debugger.ScopeProvider; + +import com.sun.star.script.provider.XScriptContext; + +public class OORhinoDebugger implements OOScriptDebugger { + + public void go(final XScriptContext xsctxt, String filename) { + Main sdb = initUI(xsctxt); + + // This is the method we've added to open a file when starting + // the Rhino debugger + sdb.openFile(filename); + } + + public void go(final XScriptContext xsctxt, InputStream in) { + Main sdb = initUI(xsctxt); + + // Open a stream in the debugger + sdb.openStream(in); + } + + // This code is based on the main method of the Rhino Debugger Main class + // We pass in the XScriptContext in the global scope for script execution + private Main initUI(final XScriptContext xsctxt) { + try { + final Main sdb = new Main("Rhino JavaScript Debugger"); + swingInvoke(new Runnable() { + public void run() { + sdb.pack(); + sdb.setSize(640, 640); + sdb.setVisible(true); + } + }); + sdb.setExitAction(new Runnable() { + public void run() { + sdb.dispose(); + } + }); + Context.addContextListener(sdb); + sdb.setScopeProvider(new ScopeProvider() { + public Scriptable getScope() { + Context ctxt = Context.enter(); + ImporterTopLevel scope = new ImporterTopLevel(ctxt); + Scriptable jsArgs = Context.toObject(xsctxt, scope); + scope.put("XSCRIPTCONTEXT", scope, jsArgs); + Context.exit(); + return scope; + } + }); + return sdb; + } catch (Exception exc) { + exc.printStackTrace(); + } + + return null; + } + + static void swingInvoke(Runnable f) { + if (SwingUtilities.isEventDispatchThread()) { + f.run(); + return; + } + + try { + SwingUtilities.invokeAndWait(f); + } catch (Exception exc) { + exc.printStackTrace(); + } + } +} diff --git a/scripting/examples/java/debugger/OOScriptDebugger.java b/scripting/examples/java/debugger/OOScriptDebugger.java new file mode 100644 index 000000000..61fdbe73d --- /dev/null +++ b/scripting/examples/java/debugger/OOScriptDebugger.java @@ -0,0 +1,27 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +import java.io.InputStream; +import com.sun.star.script.provider.XScriptContext; + +public interface OOScriptDebugger { + public void go(XScriptContext ctxt, String filename); + public void go(XScriptContext ctxt, InputStream in); +} diff --git a/scripting/examples/java/debugger/parcel-descriptor.xml b/scripting/examples/java/debugger/parcel-descriptor.xml new file mode 100644 index 000000000..93fbeabbe --- /dev/null +++ b/scripting/examples/java/debugger/parcel-descriptor.xml @@ -0,0 +1,34 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<parcel language="Java"> + + <script language="Java"> + <locale lang="en"> + <displayname value="Scripting Framework Debugger" /> + <description>Script that starts debuggers for JavaScript and BeanShell + </description> + </locale> + <logicalname value="org.libreoffice.example.java_scripts._$DebugRunner.Debug" /> + <functionname value="DebugRunner.go" /> + <languagedepprops> + <prop name="classpath" value="debugger.jar"/> + </languagedepprops> + </script> +</parcel> + diff --git a/scripting/examples/java/selector/ScriptSelector.java b/scripting/examples/java/selector/ScriptSelector.java new file mode 100644 index 000000000..ed3cfd441 --- /dev/null +++ b/scripting/examples/java/selector/ScriptSelector.java @@ -0,0 +1,488 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package org.libreoffice.example.java_scripts; + +import javax.swing.*; +import javax.swing.tree.*; +import javax.swing.table.*; +import javax.swing.event.*; +import javax.swing.border.*; +import java.awt.*; +import java.awt.event.*; +import java.util.*; +import java.beans.*; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.Exception; +import com.sun.star.uno.Any; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Type; +import com.sun.star.uno.XComponentContext; + +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XComponent; +import com.sun.star.frame.XModel; +import com.sun.star.frame.FrameSearchFlag; +import com.sun.star.frame.XDispatchProvider; +import com.sun.star.frame.XDispatchHelper; +import com.sun.star.frame.XDispatch; +import com.sun.star.util.XURLTransformer; +import com.sun.star.beans.*; +import com.sun.star.script.XInvocation; + +import com.sun.star.lib.uno.helper.PropertySet; + +import com.sun.star.script.browse.XBrowseNode; +import com.sun.star.script.browse.BrowseNodeTypes; +import com.sun.star.script.browse.XBrowseNodeFactory; +import com.sun.star.script.browse.BrowseNodeFactoryViewTypes; +import com.sun.star.script.provider.XScriptContext; +import com.sun.star.script.provider.XScript; +import com.sun.star.script.provider.XScriptProvider; + +public class ScriptSelector { + + private static final int BIG_GAP = 10; + private static final int MED_GAP = 5; + + private ScriptSelectorPanel selectorPanel; + + public ScriptSelector() { + } + + public void showOrganizer(final XScriptContext ctxt) { + try { + XBrowseNode root = getRootNode(ctxt); + + final XScriptProvider msp = + (XScriptProvider)UnoRuntime.queryInterface( + XScriptProvider.class, root); + + final JFrame client = new JFrame("Script"); + + selectorPanel = new ScriptSelectorPanel(root); + + final JButton runButton, closeButton, createButton, + editButton, deleteButton; + + runButton = new JButton("Run"); + runButton.setEnabled(false); + + closeButton = new JButton("Close"); + + editButton = new JButton("Edit"); + editButton.setEnabled(false); + + JPanel northButtons = + new JPanel(new GridLayout(2, 1, MED_GAP, MED_GAP)); + + northButtons.add(runButton); + northButtons.add(closeButton); + + createButton = new JButton("Create"); + createButton.setEnabled(false); + + deleteButton = new JButton("Delete"); + deleteButton.setEnabled(false); + + JPanel southButtons = + new JPanel(new GridLayout(3, 1, MED_GAP, MED_GAP)); + + southButtons.add(editButton); + southButtons.add(createButton); + southButtons.add(deleteButton); + + selectorPanel.tree.addTreeSelectionListener( + new TreeSelectionListener() { + public void valueChanged(TreeSelectionEvent e) { + XBrowseNode xbn = selectorPanel.getSelection(); + XPropertySet props = (XPropertySet) + UnoRuntime.queryInterface(XPropertySet.class, xbn); + + checkEnabled(props, "Creatable", createButton); + checkEnabled(props, "Deletable", deleteButton); + checkEnabled(props, "Editable", editButton); + + if (xbn != null && + xbn.getType() == BrowseNodeTypes.SCRIPT) { + runButton.setEnabled(true); + } else { + runButton.setEnabled(false); + } + } + } + ); + + ActionListener listener = new ActionListener() { + public void actionPerformed(ActionEvent event) { + if (event.getSource() == runButton) { + String uri = selectorPanel.textField.getText(); + + try { + XScript script = msp.getScript(uri); + + Object[][] out = new Object[1][0]; + out[0] = new Object[0]; + + short[][] num = new short[1][0]; + num[0] = new short[0]; + + script.invoke(new Object[0], num, out); + } catch (Exception e) { + e.printStackTrace(); + } + } else if (event.getSource() == closeButton) { + client.dispose(); + } else if (event.getSource() == editButton) { + DefaultMutableTreeNode node = + (DefaultMutableTreeNode) + selectorPanel.tree.getLastSelectedPathComponent(); + + if (node == null) return; + + showEditor(ctxt, node); + } else if (event.getSource() == createButton) { + DefaultMutableTreeNode node = + (DefaultMutableTreeNode) + selectorPanel.tree.getLastSelectedPathComponent(); + + if (node == null) return; + + doCreate(ctxt, node); + } else if (event.getSource() == deleteButton) { + DefaultMutableTreeNode node = + (DefaultMutableTreeNode) + selectorPanel.tree.getLastSelectedPathComponent(); + + if (node == null) return; + + doDelete(ctxt, node); + } + } + }; + + runButton.addActionListener(listener); + closeButton.addActionListener(listener); + createButton.addActionListener(listener); + editButton.addActionListener(listener); + deleteButton.addActionListener(listener); + + JPanel buttonPanel = new JPanel(new BorderLayout()); + buttonPanel.add(northButtons, BorderLayout.NORTH); + buttonPanel.add(southButtons, BorderLayout.SOUTH); + + JPanel mainPanel = new JPanel(new BorderLayout(MED_GAP, MED_GAP)); + mainPanel.setBorder( + new EmptyBorder(BIG_GAP, BIG_GAP, BIG_GAP, BIG_GAP)); + mainPanel.add(selectorPanel, BorderLayout.CENTER); + mainPanel.add(buttonPanel, BorderLayout.EAST); + + client.getContentPane().add(mainPanel); + client.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + client.setSize(500, 350); + + // set the x and y locations so that the frame is in the + // centre of the screen + Dimension d = client.getToolkit().getScreenSize(); + + int x = (int)((d.getWidth() - client.getWidth()) / 2); + int y = (int)((d.getHeight() - client.getHeight()) / 2); + + client.setLocation(x, y); + + client.show(); + } catch (com.sun.star.uno.RuntimeException rue) { + rue.printStackTrace(); + } catch (java.lang.Exception e) { + e.printStackTrace(); + } + } + + public void showOrganizer(final XScriptContext ctxt, + final com.sun.star.awt.MouseEvent e) { + showOrganizer(ctxt); + } + + public void showOrganizer(final XScriptContext ctxt, + final com.sun.star.awt.ActionEvent e) { + showOrganizer(ctxt); + } + + private void doDelete( + XScriptContext ctxt, DefaultMutableTreeNode node) { + Object obj = node.getUserObject(); + XInvocation inv = + (XInvocation)UnoRuntime.queryInterface( + XInvocation.class, obj); + Object[] args = new Object[] { ctxt }; + + try { + Object result = inv.invoke("Deletable", args, + new short[1][0], new Object[1][0]); + + if (result != null && AnyConverter.toBoolean(result) == true) { + selectorPanel.removeNode(node); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void doCreate( + XScriptContext ctxt, DefaultMutableTreeNode node) { + Object obj = node.getUserObject(); + XInvocation inv = + (XInvocation)UnoRuntime.queryInterface( + XInvocation.class, obj); + Object[] args = new Object[] { ctxt }; + + try { + Object result = inv.invoke("Creatable", args, + new short[1][0], new Object[1][0]); + + if (result != null) { + XBrowseNode xbn = (XBrowseNode) + AnyConverter.toObject(new Type(XBrowseNode.class), result); + selectorPanel.addNode(node, xbn); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void showEditor( + XScriptContext ctxt, DefaultMutableTreeNode node) { + Object obj = node.getUserObject(); + XInvocation inv = + (XInvocation)UnoRuntime.queryInterface( + XInvocation.class, obj); + Object[] args = new Object[] { ctxt }; + + try { + inv.invoke("Editable", args, + new short[1][0], new Object[1][0]); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void checkEnabled(XPropertySet props, String name, + JButton button) { + boolean enable = false; + + try { + if (props != null) { + Object o = props.getPropertyValue(name); + enable = AnyConverter.toBoolean( + props.getPropertyValue(name)); + } + } catch (com.sun.star.lang.IllegalArgumentException iae) { + // leave enable set to false + } catch (com.sun.star.beans.UnknownPropertyException upe) { + // leave enable set to false + } catch (com.sun.star.lang.WrappedTargetException wte) { + // leave enable set to false + } + + button.setEnabled(enable); + } + + private XBrowseNode getRootNode(XScriptContext ctxt) { + + XBrowseNode result = null; + + + XComponentContext xcc = ctxt.getComponentContext(); + XMultiComponentFactory xmcf = xcc.getServiceManager(); + XBrowseNodeFactory xBrowseFac = (XBrowseNodeFactory) + UnoRuntime.queryInterface(XBrowseNodeFactory.class, xcc.getValueByName( + "/singletons/com.sun.star.script.browse.theBrowseNodeFactory")); + + + result = (XBrowseNode)UnoRuntime.queryInterface( + XBrowseNode.class, xBrowseFac.createView( + BrowseNodeFactoryViewTypes.MACROORGANIZER)); + return result; + } +} + +class ScriptSelectorPanel extends JPanel { + + private XBrowseNode myrootnode = null; + public JTextField textField; + public JTree tree; + public DefaultTreeModel treeModel; + + public ScriptSelectorPanel(XBrowseNode root) { + this.myrootnode = root; + initUI(); + } + + public XBrowseNode getSelection() { + DefaultMutableTreeNode node = (DefaultMutableTreeNode) + tree.getLastSelectedPathComponent(); + + if (node == null) { + return null; + } + + return (XBrowseNode)node.getUserObject(); + } + + private void initUI() { + setLayout(new BorderLayout()); + + DefaultMutableTreeNode top = + new DefaultMutableTreeNode(myrootnode) { + public String toString() { + return ((XBrowseNode)getUserObject()).getName(); + } + }; + initNodes(myrootnode, top); + treeModel = new DefaultTreeModel(top); + tree = new JTree(treeModel); + + tree.setCellRenderer(new ScriptTreeRenderer()); + + tree.getSelectionModel().setSelectionMode + (TreeSelectionModel.SINGLE_TREE_SELECTION); + + tree.addTreeSelectionListener(new TreeSelectionListener() { + public void valueChanged(TreeSelectionEvent e) { + XBrowseNode xbn = getSelection(); + XPropertySet props = (XPropertySet)UnoRuntime.queryInterface( + XPropertySet.class, xbn); + + if (xbn == null) { + textField.setText(""); + return; + } + + String str = xbn.getName(); + + if (xbn.getType() == BrowseNodeTypes.SCRIPT && props != null) { + try { + str = AnyConverter.toString( + props.getPropertyValue("URI")); + } catch (Exception ignore) { + // default will be used + } + } + + textField.setText(str); + } + }); + + JScrollPane scroller = new JScrollPane(tree); + add(scroller, BorderLayout.CENTER); + + textField = new JTextField(); + add(textField, BorderLayout.SOUTH); + } + + public void removeNode(DefaultMutableTreeNode node) { + MutableTreeNode parent = (MutableTreeNode)(node.getParent()); + + if (parent != null) { + treeModel.removeNodeFromParent(node); + } + } + + public void addNode(DefaultMutableTreeNode parent, XBrowseNode xbn) { + DefaultMutableTreeNode newNode = + new DefaultMutableTreeNode(xbn) { + public String toString() { + return ((XBrowseNode)getUserObject()).getName(); + } + }; + + treeModel.insertNodeInto(newNode, parent, parent.getChildCount()); + tree.scrollPathToVisible(new TreePath(newNode.getPath())); + } + + private void initNodes(XBrowseNode parent, DefaultMutableTreeNode top) { + if (parent == null || parent.hasChildNodes() == false) { + return; + } + + XBrowseNode[] children = parent.getChildNodes(); + + try { + if (children != null) { + for (int i = 0; i < children.length; i++) { + if (children[i] == null) { + continue; + } + + DefaultMutableTreeNode newNode = + new DefaultMutableTreeNode(children[i]) { + public String toString() { + return ((XBrowseNode)getUserObject()).getName(); + } + }; + top.add(newNode); + initNodes(children[i], newNode); + } + } + } catch (java.lang.Exception e) { + e.printStackTrace(); + } + } +} + +class ScriptTreeRenderer extends DefaultTreeCellRenderer { + + private ImageIcon sofficeIcon; + private ImageIcon scriptIcon; + private ImageIcon containerIcon; + + public ScriptTreeRenderer() { + sofficeIcon = new ImageIcon(getClass().getResource("soffice.gif")); + scriptIcon = new ImageIcon(getClass().getResource("script.gif")); + containerIcon = new ImageIcon(getClass().getResource("container.gif")); + } + + public Component getTreeCellRendererComponent( + JTree tree, + Object value, + boolean sel, + boolean expanded, + boolean leaf, + int row, + boolean hasFocus) { + + super.getTreeCellRendererComponent( + tree, value, sel, + expanded, leaf, row, + hasFocus); + + DefaultMutableTreeNode node = (DefaultMutableTreeNode)value; + XBrowseNode xbn = (XBrowseNode)node.getUserObject(); + + if (xbn.getType() == BrowseNodeTypes.SCRIPT) { + setIcon(scriptIcon); + } else if (xbn.getType() == BrowseNodeTypes.CONTAINER) { + setIcon(containerIcon); + } else if (xbn.getType() == BrowseNodeTypes.ROOT) { + setIcon(sofficeIcon); + } + + return this; + } +} diff --git a/scripting/examples/java/selector/container.gif b/scripting/examples/java/selector/container.gif Binary files differnew file mode 100644 index 000000000..3a345f9bf --- /dev/null +++ b/scripting/examples/java/selector/container.gif diff --git a/scripting/examples/java/selector/parcel-descriptor.xml b/scripting/examples/java/selector/parcel-descriptor.xml new file mode 100644 index 000000000..1f4b8ec38 --- /dev/null +++ b/scripting/examples/java/selector/parcel-descriptor.xml @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<parcel language="Java" xmlns:parcel="scripting.dtd"> + <script language="Java"> + <locale lang="en"> + <displayname value="Script Selector"/> + <description> + Prototype Script Selector GUI for StarOffice + </description> + </locale> + <functionname value="org.libreoffice.example.java_scripts.ScriptSelector.showOrganizer"/> + <logicalname value="ScriptSelector.showOrganizer"/> + <languagedepprops> + <prop name="classpath" value="selector.jar"/> + </languagedepprops> + </script> +</parcel> diff --git a/scripting/examples/java/selector/script.gif b/scripting/examples/java/selector/script.gif Binary files differnew file mode 100644 index 000000000..d3b3768ca --- /dev/null +++ b/scripting/examples/java/selector/script.gif diff --git a/scripting/examples/java/selector/soffice.gif b/scripting/examples/java/selector/soffice.gif Binary files differnew file mode 100644 index 000000000..88124d87d --- /dev/null +++ b/scripting/examples/java/selector/soffice.gif diff --git a/scripting/examples/javascript/ExportSheetsToHTML/exportsheetstohtml.js b/scripting/examples/javascript/ExportSheetsToHTML/exportsheetstohtml.js new file mode 100644 index 000000000..37f9e5afb --- /dev/null +++ b/scripting/examples/javascript/ExportSheetsToHTML/exportsheetstohtml.js @@ -0,0 +1,88 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +// When this script is run on an existing, saved, spreadsheet, +// eg. /home/testuser/myspreadsheet.sxc, the script will export +// each sheet to a separate html file, +// eg. /home/testuser/myspreadsheet_sheet1.html, +// /home/testuser/myspreadsheet_sheet2.html etc +importClass(Packages.com.sun.star.uno.UnoRuntime); +importClass(Packages.com.sun.star.sheet.XSpreadsheetDocument); +importClass(Packages.com.sun.star.container.XIndexAccess); +importClass(Packages.com.sun.star.beans.XPropertySet); +importClass(Packages.com.sun.star.beans.PropertyValue); +importClass(Packages.com.sun.star.util.XModifiable); +importClass(Packages.com.sun.star.frame.XStorable); +importClass(Packages.com.sun.star.frame.XModel); +importClass(Packages.com.sun.star.uno.AnyConverter); +importClass(Packages.com.sun.star.uno.Type); + +importClass(java.lang.System); + +//get the document object from the scripting context +oDoc = XSCRIPTCONTEXT.getDocument(); +//get the XSpreadsheetDocument interface from the document +xSDoc = UnoRuntime.queryInterface(XSpreadsheetDocument, oDoc); +//get the XModel interface from the document +xModel = UnoRuntime.queryInterface(XModel,oDoc); +//get the XIndexAccess interface used to access each sheet +xSheetsIndexAccess = UnoRuntime.queryInterface(XIndexAccess, xSDoc.getSheets()); +//get the XStorable interface used to save the document +xStorable = UnoRuntime.queryInterface(XStorable,xSDoc); +//get the XModifiable interface used to indicate if the document has been +//changed +xModifiable = UnoRuntime.queryInterface(XModifiable,xSDoc); + +//set up an array of PropertyValue objects used to save each sheet in the +//document +storeProps = new Array;//PropertyValue[1]; +storeProps[0] = new PropertyValue(); +storeProps[0].Name = "FilterName"; +storeProps[0].Value = "HTML (StarCalc)"; +storeUrl = xModel.getURL(); +storeUrl = storeUrl.substring(0,storeUrl.lastIndexOf('.')); + +//set only one sheet visible, and store to HTML doc +for(var i=0;i<xSheetsIndexAccess.getCount();i++) +{ + setAllButOneHidden(xSheetsIndexAccess,i); + xModifiable.setModified(false); + xStorable.storeToURL(storeUrl+"_sheet"+(i+1)+".html", storeProps); +} + +// now set all visible again +for(var i=0;i<xSheetsIndexAccess.getCount();i++) +{ + xPropSet = AnyConverter.toObject( new Type(XPropertySet), xSheetsIndexAccess.getByIndex(i)); + xPropSet.setPropertyValue("IsVisible", true); +} + +function setAllButOneHidden(xSheetsIndexAccess,vis) { + //System.err.println("count="+xSheetsIndexAccess.getCount()); + //get an XPropertySet interface for the vis-th sheet + xPropSet = AnyConverter.toObject( new Type(XPropertySet), xSheetsIndexAccess.getByIndex(vis)); + //set the vis-th sheet to be visible + xPropSet.setPropertyValue("IsVisible", true); + // set all other sheets to be invisible + for(var i=0;i<xSheetsIndexAccess.getCount();i++) + { + xPropSet = AnyConverter.toObject( new Type(XPropertySet), xSheetsIndexAccess.getByIndex(i)); + if(i!=vis) { + xPropSet.setPropertyValue("IsVisible", false); + } + } +} diff --git a/scripting/examples/javascript/ExportSheetsToHTML/parcel-descriptor.xml b/scripting/examples/javascript/ExportSheetsToHTML/parcel-descriptor.xml new file mode 100644 index 000000000..be8880ab0 --- /dev/null +++ b/scripting/examples/javascript/ExportSheetsToHTML/parcel-descriptor.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<parcel language="JavaScript" xmlns:parcel="scripting.dtd"> + + <script language="JavaScript"> + <locale lang="en"> + <displayname value="ExportSheetsToHTML"/> + <description> + Saves each sheet in the current Calc document as a separate HTML file in the same directory as the original Calc document. + </description> + </locale> + <functionname value="exportsheetstohtml.js"/> + <logicalname value="ExportSheetsToHTML.JavaScript"/> + </script> + +</parcel> diff --git a/scripting/examples/javascript/HelloWorld/helloworld.js b/scripting/examples/javascript/HelloWorld/helloworld.js new file mode 100644 index 000000000..f04fdfd8a --- /dev/null +++ b/scripting/examples/javascript/HelloWorld/helloworld.js @@ -0,0 +1,33 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +// Hello World in JavaScript +importClass(Packages.com.sun.star.uno.UnoRuntime); +importClass(Packages.com.sun.star.text.XTextDocument); +importClass(Packages.com.sun.star.text.XText); +importClass(Packages.com.sun.star.text.XTextRange); + +//get the document from the scripting context +oDoc = XSCRIPTCONTEXT.getDocument(); +//get the XTextDocument interface +xTextDoc = UnoRuntime.queryInterface(XTextDocument,oDoc); +//get the XText interface +xText = xTextDoc.getText(); +//get an (empty) XTextRange interface at the end of the text +xTextRange = xText.getEnd(); +//set the text in the XTextRange +xTextRange.setString( "Hello World (in JavaScript)" ); diff --git a/scripting/examples/javascript/HelloWorld/parcel-descriptor.xml b/scripting/examples/javascript/HelloWorld/parcel-descriptor.xml new file mode 100644 index 000000000..65ea9fd75 --- /dev/null +++ b/scripting/examples/javascript/HelloWorld/parcel-descriptor.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<parcel language="JavaScript" xmlns:parcel="scripting.dtd"> + + <script language="JavaScript"> + <locale lang="en"> + <displayname value="Hello World"/> + <description> + Adds the string "Hello World" into the current text doc. + </description> + </locale> + <functionname value="helloworld.js"/> + <logicalname value="HelloWorld.JavaScript"/> + </script> + +</parcel> diff --git a/scripting/examples/javascript/Highlight/ButtonPressHandler.js b/scripting/examples/javascript/Highlight/ButtonPressHandler.js new file mode 100644 index 000000000..e0fbde240 --- /dev/null +++ b/scripting/examples/javascript/Highlight/ButtonPressHandler.js @@ -0,0 +1,122 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +//this script acts as a handler for the buttons in the Highlight dialog +importClass(Packages.com.sun.star.uno.UnoRuntime); +importClass(Packages.com.sun.star.uno.Type); +importClass(Packages.com.sun.star.uno.AnyConverter); + +importClass(Packages.com.sun.star.awt.XButton); +importClass(Packages.com.sun.star.awt.XControl); +importClass(Packages.com.sun.star.awt.ActionEvent); +importClass(Packages.com.sun.star.awt.XControlModel); +importClass(Packages.com.sun.star.awt.XControlContainer); +importClass(Packages.com.sun.star.awt.XDialog); +importClass(Packages.com.sun.star.awt.XTextComponent); + +importClass(Packages.com.sun.star.util.XReplaceable); +importClass(Packages.com.sun.star.util.XReplaceDescriptor); +importClass(Packages.com.sun.star.util.XPropertyReplace); + +importClass(Packages.com.sun.star.beans.XPropertySet); +importClass(Packages.com.sun.star.beans.PropertyValue); + +// Scripting Framework DialogFactory class +importClass(Packages.com.sun.star.script.framework.browse.DialogFactory); + +// Get the ActionEvent object from the ARGUMENTS list +event = ARGUMENTS[0]; + +// Each argument is of type Any so we must use the AnyConverter class to +// convert it into the interface or primitive type we expect +button = AnyConverter.toObject(new Type(XButton), event.Source); + +// We can now query for the model of the button and get its properties +control = UnoRuntime.queryInterface(XControl, button); +cmodel = control.getModel(); +pset = UnoRuntime.queryInterface(XPropertySet, cmodel); + +if (pset.getPropertyValue("Label").equals("Exit")) +{ + // We can get the XDialog in which this control appears by calling + // getContext() on the XControl interface + xDialog = UnoRuntime.queryInterface( + XDialog, control.getContext()); + + // Close the dialog + xDialog.endExecute(); +} +else +{ + // We can get the list of controls for this dialog by calling + // getContext() on the XControl interface of the button + controls = UnoRuntime.queryInterface( + XControlContainer, control.getContext()); + + // Now get the text field control from the list + textField = + UnoRuntime.queryInterface( + XTextComponent, controls.getControl("HighlightTextField")); + + searchKey = textField.getText(); + + // highlight the text in red + red = java.awt.Color.red.getRGB(); + + replaceable = + UnoRuntime.queryInterface(XReplaceable, XSCRIPTCONTEXT.getDocument()); + + descriptor = replaceable.createReplaceDescriptor(); + + // Gets a XPropertyReplace object for altering the properties + // of the replaced text + xPropertyReplace = UnoRuntime.queryInterface(XPropertyReplace, descriptor); + + // Sets the replaced text property fontweight value to Bold + wv = new PropertyValue("CharWeight", -1, + new java.lang.Float(Packages.com.sun.star.awt.FontWeight.BOLD), + Packages.com.sun.star.beans.PropertyState.DIRECT_VALUE); + + // Sets the replaced text property color value to RGB parameter + cv = new PropertyValue("CharColor", -1, + new java.lang.Integer(red), + Packages.com.sun.star.beans.PropertyState.DIRECT_VALUE); + + // Apply the properties + props = new Array; + props[0] = cv; + props[1] = wv; + + try { + xPropertyReplace.setReplaceAttributes(props); + + // Only matches whole words and case sensitive + descriptor.setPropertyValue( + "SearchCaseSensitive", new java.lang.Boolean(true)); + descriptor.setPropertyValue("SearchWords", new java.lang.Boolean(true)); + + // Replaces all instances of searchKey with new Text properties + // and gets the number of instances of the searchKey + descriptor.setSearchString(searchKey); + descriptor.setReplaceString(searchKey); + replaceable.replaceAll(descriptor); + } + catch (e) { + java.lang.System.err.println("Error setting up search properties" + + e.getMessage()); + } +} diff --git a/scripting/examples/javascript/Highlight/ShowDialog.js b/scripting/examples/javascript/Highlight/ShowDialog.js new file mode 100644 index 000000000..d659d9622 --- /dev/null +++ b/scripting/examples/javascript/Highlight/ShowDialog.js @@ -0,0 +1,131 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +importClass(Packages.com.sun.star.uno.UnoRuntime); +importClass(Packages.com.sun.star.lang.XMultiComponentFactory); +importClass(Packages.com.sun.star.awt.XDialogProvider); +importClass(Packages.com.sun.star.awt.XDialog); +importClass(Packages.com.sun.star.uno.Exception); +importClass(Packages.com.sun.star.script.provider.XScriptContext); + +importClass(java.lang.Thread); +importClass(java.lang.System); + +function tryLoadingLibrary( xmcf, context, name ) +{ + try + { + obj = xmcf.createInstanceWithContext( + "com.sun.star.script.Application" + name + "LibraryContainer", + context.getComponentContext()); + + xLibraryContainer = UnoRuntime.queryInterface(XLibraryContainer, obj); + + System.err.println("Got XLibraryContainer"); + + serviceObj = context.getComponentContext().getValueByName( + "/singletons/com.sun.star.util.theMacroExpander"); + + xme = AnyConverter.toObject(new Type(XMacroExpander), serviceObj); + + bootstrapName = "bootstraprc"; + if (System.getProperty("os.name").startsWith("Windows")) + { + bootstrapName = "bootstrap.ini"; + } + + libURL = xme.expandMacros( + "$BRAND_BASE_DIR/$BRAND_SHARE_SUBDIR/basic/ScriptBindingLibrary/" + + name.toLowerCase() + ".xlb/"); + + System.err.println("libURL is: " + libURL); + + xLibraryContainer.createLibraryLink( + "ScriptBindingLibrary", libURL, false); + + System.err.println("liblink created"); + + } + catch (e) + { + System.err.println("Got an exception loading lib: " + e.getMessage()); + return false; + } + return true; +} + +function getDialogProvider() +{ + // UNO awt components of the Highlight dialog + //get the XMultiServiceFactory + xmcf = XSCRIPTCONTEXT.getComponentContext().getServiceManager(); + + args = new Array; + //get the XDocument from the context + args[0] = XSCRIPTCONTEXT.getDocument(); + + //try to create the DialogProvider + try { + obj = xmcf.createInstanceWithArgumentsAndContext( + "com.sun.star.awt.DialogProvider", args, + XSCRIPTCONTEXT.getComponentContext()); + } + catch (e) { + System.err.println("Error getting DialogProvider object"); + return null; + } + + return UnoRuntime.queryInterface(XDialogProvider, obj); +} + +//get the DialogProvider +xDialogProvider = getDialogProvider(); + +if (xDialogProvider != null) +{ + //try to create the Highlight dialog (found in the ScriptBinding library) + try + { + findDialog = xDialogProvider.createDialog("vnd.sun.star.script:" + + "ScriptBindingLibrary.Highlight?location=application"); + if( findDialog == null ) + { + if (tryLoadingLibrary(xmcf, XSCRIPTCONTEXT, "Dialog") == false || + tryLoadingLibrary(xmcf, XSCRIPTCONTEXT, "Script") == false) + { + System.err.println("Error loading ScriptBindingLibrary"); + } + else + { + // try to create the Highlight dialog (found in the + // ScriptBindingLibrary) + findDialog = xDialogProvider.createDialog("vnd.sun.star.script:" + + "ScriptBindingLibrary.Highlight?location=application"); + } + } + + //launch the dialog + if ( findDialog != null ) + { + findDialog.execute(); + } + } + catch (e) { + System.err.println("Got exception on first creating dialog: " + + e.getMessage()); + } +} diff --git a/scripting/examples/javascript/Highlight/parcel-descriptor.xml b/scripting/examples/javascript/Highlight/parcel-descriptor.xml new file mode 100644 index 000000000..e6d6bb7b1 --- /dev/null +++ b/scripting/examples/javascript/Highlight/parcel-descriptor.xml @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . +--> +<parcel language="JavaScript" xmlns:parcel="scripting.dtd"> + <script language="JavaScript"> + <locale lang="en"> + <displayname value="ShowDialog" /> + <description> + Example of how to show a dialog from JavaScript + </description> + </locale> + <functionname value="ShowDialog.js" /> + <logicalname value="ShowDialog.JavaScript" /> + </script> + <script language="JavaScript"> + <locale lang="en"> + <displayname value="ButtonPressHandler" /> + <description> + Example of handle button press events for the Dialog + </description> + </locale> + <functionname value="ButtonPressHandler.js" /> + <logicalname value="ButtonPressHandler.JavaScript" /> + </script> +</parcel> + diff --git a/scripting/examples/python/Capitalise.py b/scripting/examples/python/Capitalise.py new file mode 100644 index 000000000..05e82a37a --- /dev/null +++ b/scripting/examples/python/Capitalise.py @@ -0,0 +1,80 @@ +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# + +# helper function +def getNewString( theString ) : + if( not theString or len(theString) ==0) : + return "" + # should we tokenize on "."? + if theString[0].isupper() and len(theString)>=2 and theString[1].isupper() : + # first two chars are UC => first UC, rest LC + newString=theString[0:1].upper() + theString[1:].lower(); + elif theString[0].isupper(): + # first char UC => all to LC + newString=theString.lower() + else: # all to UC. + newString=theString.upper() + return newString; + +def capitalisePython( ): + """Change the case of a selection, or current word from upper case, to first char upper case, to all lower case to upper case...""" + import string + + # The context variable is of type XScriptContext and is available to + # all BeanShell scripts executed by the Script Framework + xModel = XSCRIPTCONTEXT.getDocument() + + #the writer controller impl supports the css.view.XSelectionSupplier interface + xSelectionSupplier = xModel.getCurrentController() + + #see section 7.5.1 of developers' guide + xIndexAccess = xSelectionSupplier.getSelection() + count = xIndexAccess.getCount(); + if(count>=1): #ie we have a selection + i=0 + while i < count : + xTextRange = xIndexAccess.getByIndex(i); + #print "string: " + xTextRange.getString(); + theString = xTextRange.getString(); + if len(theString)==0 : + # sadly we can have a selection where nothing is selected + # in this case we get the XWordCursor and make a selection! + xText = xTextRange.getText(); + xWordCursor = xText.createTextCursorByRange(xTextRange); + if not xWordCursor.isStartOfWord(): + xWordCursor.gotoStartOfWord(False); + xWordCursor.gotoNextWord(True); + theString = xWordCursor.getString(); + newString = getNewString(theString); + if newString : + xWordCursor.setString(newString); + xSelectionSupplier.select(xWordCursor); + else : + + newString = getNewString( theString ); + if newString: + xTextRange.setString(newString); + xSelectionSupplier.select(xTextRange); + i+= 1 + + +# lists the scripts, that shall be visible inside OOo. Can be omitted, if +# all functions shall be visible, however here getNewString shall be suppressed +g_exportedScripts = capitalisePython, + +# vim: set shiftwidth=4 softtabstop=4 expandtab: diff --git a/scripting/examples/python/HelloWorld.py b/scripting/examples/python/HelloWorld.py new file mode 100644 index 000000000..8c3c9a814 --- /dev/null +++ b/scripting/examples/python/HelloWorld.py @@ -0,0 +1,38 @@ +# HelloWorld python script for the scripting framework + +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# + +def HelloWorldPython( ): + """Prints the string 'Hello World(in Python)' into the current document""" +#get the doc from the scripting context which is made available to all scripts + desktop = XSCRIPTCONTEXT.getDesktop() + model = desktop.getCurrentComponent() +#check whether there's already an opened document. Otherwise, create a new one + if not hasattr(model, "Text"): + model = desktop.loadComponentFromURL( + "private:factory/swriter","_blank", 0, () ) +#get the XText interface + text = model.Text +#create an XTextRange at the end of the document + tRange = text.End +#and set the string + tRange.String = "Hello World (in Python)" + return None + +# vim: set shiftwidth=4 softtabstop=4 expandtab: diff --git a/scripting/examples/python/InsertText.py b/scripting/examples/python/InsertText.py new file mode 100644 index 000000000..e04874d52 --- /dev/null +++ b/scripting/examples/python/InsertText.py @@ -0,0 +1,61 @@ +# HelloWorld python script for the scripting framework + +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# + +def InsertText(text): + """Inserts the argument string into the current document. + If there is a selection, the selection is replaced by it.""" + + # Get the doc from the scripting context which is made available to all scripts + desktop = XSCRIPTCONTEXT.getDesktop() + model = desktop.getCurrentComponent() + + # Check whether there's already an opened document. + if not hasattr(model, "Text"): + return + + # The context variable is of type XScriptContext and is available to + # all BeanShell scripts executed by the Script Framework + xModel = XSCRIPTCONTEXT.getDocument() + + #the writer controller impl supports the css.view.XSelectionSupplier interface + xSelectionSupplier = xModel.getCurrentController() + + #see section 7.5.1 of developers' guide + xIndexAccess = xSelectionSupplier.getSelection() + count = xIndexAccess.getCount(); + if count >= 1: #ie we have a selection + i = 0 + + while i < count: + xTextRange = xIndexAccess.getByIndex(i); + theString = xTextRange.getString(); + if not len(theString): + # Nothing really selected; just insert. + xText = xTextRange.getText(); + xWordCursor = xText.createTextCursorByRange(xTextRange); + xWordCursor.setString(text); + xSelectionSupplier.select(xWordCursor); + else: + # Replace the selection. + xTextRange.setString(text); + xSelectionSupplier.select(xTextRange); + + i += 1 + diff --git a/scripting/examples/python/NamedRanges.py b/scripting/examples/python/NamedRanges.py new file mode 100644 index 000000000..34307ae84 --- /dev/null +++ b/scripting/examples/python/NamedRanges.py @@ -0,0 +1,59 @@ +# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +import traceback +import uno + +def GetNamedRanges(): + """Returns a list of the named ranges in the document. + """ + try: + desktop = XSCRIPTCONTEXT.getDesktop() + model = desktop.getCurrentComponent() + rangeNames = model.NamedRanges.ElementNames + result = [] + for i in rangeNames: + range = model.NamedRanges.getByName(i).Content + result.append((i, range)) + return result + except Exception as e: + print("Caught Exception: " + str(e)) + tb = e.__traceback__ + traceback.print_tb(tb) + return None + +def DefineNamedRange(sheet, x0, y0, width, height, name): + """Defines a new (or replaces an existing) named range on a sheet, + using zero-based absolute coordinates + """ + desktop = XSCRIPTCONTEXT.getDesktop() + model = desktop.getCurrentComponent() + # FIXME: Is there some Python-callable API to turn a row and column into an A1 string? + # This obviously works only for the first 26 columns. + abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + content = "$" + sheet + "." + "$" + abc[x0 : x0+1] + "$" + str(y0+1) + ":" + "$" + abc[x0+width-1 : x0+width] + "$" + str(y0+height) + position = uno.createUnoStruct('com.sun.star.table.CellAddress') + position.Sheet = 0 + position.Column = 0 + position.Row = 0 + model.NamedRanges.addNewByName(name, content, position, 0) + return None + +def DeleteNamedRange(name): + try: + desktop = XSCRIPTCONTEXT.getDesktop() + model = desktop.getCurrentComponent() + model.NamedRanges.removeByName(name) + except Exception as e: + print("Caught Exception: " + str(e)) + tb = e.__traceback__ + traceback.print_tb(tb) + return None + +# vim: set shiftwidth=4 softtabstop=4 expandtab: diff --git a/scripting/examples/python/SetCellColor.py b/scripting/examples/python/SetCellColor.py new file mode 100644 index 000000000..743a6daa9 --- /dev/null +++ b/scripting/examples/python/SetCellColor.py @@ -0,0 +1,15 @@ +def SetCellColor(x, y, color): + """Sets the background of the cell at (x,y) (zero-based column and row + indices, for example (2,3) == C4) on the first sheet and + returns the contents of the cell as a string. + """ + #get the doc from the scripting context which is made available to all scripts + desktop = XSCRIPTCONTEXT.getDesktop() + model = desktop.getCurrentComponent() + #check whether there's already an opened document + if not hasattr(model, "Sheets"): + return "" + sheet = model.Sheets.Sheet1 + cell = sheet.getCellByPosition(x, y) + cell.CellBackColor = color + return cell.String diff --git a/scripting/examples/python/pythonSamples/TableSample.py b/scripting/examples/python/pythonSamples/TableSample.py new file mode 100644 index 000000000..a92c862c2 --- /dev/null +++ b/scripting/examples/python/pythonSamples/TableSample.py @@ -0,0 +1,116 @@ +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# + +import uno + +# a UNO struct later needed to create a document +from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK +from com.sun.star.text.TextContentAnchorType import AS_CHARACTER +from com.sun.star.awt import Size + +from com.sun.star.lang import XMain + +def insertTextIntoCell( table, cellName, text, color ): + tableText = table.getCellByName( cellName ) + cursor = tableText.createTextCursor() + cursor.setPropertyValue( "CharColor", color ) + tableText.setString( text ) + + +def createTable(): + """creates a new writer document and inserts a table with some data (also known as the SWriter sample)""" + ctx = uno.getComponentContext() + smgr = ctx.ServiceManager + desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx) + + # open a writer document + doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () ) + + text = doc.Text + cursor = text.createTextCursor() + text.insertString( cursor, "The first line in the newly created text document.\n", 0 ) + text.insertString( cursor, "Now we are in the second line\n" , 0 ) + + # create a text table + table = doc.createInstance( "com.sun.star.text.TextTable" ) + + # with 4 rows and 4 columns + table.initialize( 4,4) + + text.insertTextContent( cursor, table, 0 ) + rows = table.Rows + + table.setPropertyValue( "BackTransparent", uno.Bool(0) ) + table.setPropertyValue( "BackColor", 13421823 ) + row = rows.getByIndex(0) + row.setPropertyValue( "BackTransparent", uno.Bool(0) ) + row.setPropertyValue( "BackColor", 6710932 ) + + textColor = 16777215 + + insertTextIntoCell( table, "A1", "FirstColumn", textColor ) + insertTextIntoCell( table, "B1", "SecondColumn", textColor ) + insertTextIntoCell( table, "C1", "ThirdColumn", textColor ) + insertTextIntoCell( table, "D1", "SUM", textColor ) + + values = ( (22.5,21.5,121.5), + (5615.3,615.3,-615.3), + (-2315.7,315.7,415.7) ) + table.getCellByName("A2").setValue(22.5) + table.getCellByName("B2").setValue(5615.3) + table.getCellByName("C2").setValue(-2315.7) + table.getCellByName("D2").setFormula("sum <A2:C2>") + + table.getCellByName("A3").setValue(21.5) + table.getCellByName("B3").setValue(615.3) + table.getCellByName("C3").setValue(-315.7) + table.getCellByName("D3").setFormula("sum <A3:C3>") + + table.getCellByName("A4").setValue(121.5) + table.getCellByName("B4").setValue(-615.3) + table.getCellByName("C4").setValue(415.7) + table.getCellByName("D4").setFormula("sum <A4:C4>") + + + cursor.setPropertyValue( "CharColor", 255 ) + cursor.setPropertyValue( "CharShadowed", uno.Bool(1) ) + + text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 ) + text.insertString( cursor, " This is a colored Text - blue with shadow\n" , 0 ) + text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 ) + + textFrame = doc.createInstance( "com.sun.star.text.TextFrame" ) + textFrame.setSize( Size(15000,400)) + textFrame.setPropertyValue( "AnchorType" , AS_CHARACTER ) + + text.insertTextContent( cursor, textFrame, 0 ) + + textInTextFrame = textFrame.getText() + cursorInTextFrame = textInTextFrame.createTextCursor() + textInTextFrame.insertString( cursorInTextFrame, "The first line in the newly created text frame.", 0 ) + textInTextFrame.insertString( cursorInTextFrame, "\nWith this second line the height of the rame raises.",0) + text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 ) + + cursor.setPropertyValue( "CharColor", 65536 ) + cursor.setPropertyValue( "CharShadowed", uno.Bool(0) ) + + text.insertString( cursor, " That's all for now !!" , 0 ) + +g_exportedScripts = createTable, + +# vim: set shiftwidth=4 softtabstop=4 expandtab: |