Initial import

git-svn-id: svn://svn.code.sf.net/p/writer2latex/code/trunk@5 f0f2a975-2e09-46c8-9428-3b39399b9f3c
This commit is contained in:
henrikjust 2009-02-20 09:37:06 +00:00
parent 75e32b1e8f
commit b0b66fcae9
252 changed files with 49000 additions and 0 deletions

View file

@ -0,0 +1,188 @@
/************************************************************************
*
* ByteArrayXStream.java
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Copyright: 2002-2008 by Henrik Just
*
* All Rights Reserved.
*
* Version 1.0 (2008-07-22)
*
*/
package org.openoffice.da.comp.w2lcommon.filter;
// This class is based on these java uno adapter classes:
// com.sun.star.lib.uno.adapter.ByteArrayToXInputStreamAdapter;
// com.sun.star.lib.uno.adapter.XOutputStreamToByteArrayAdapter;
// See http://go-oo.org/lxr/source/udk/javaunohelper/com/sun/star/lib/uno/adapter/XOutputStreamToByteArrayAdapter.java
// and http://go-oo.org/lxr/source/udk/javaunohelper/com/sun/star/lib/uno/adapter/ByteArrayToXInputStreamAdapter.java
// for original source
import com.sun.star.io.XInputStream;
import com.sun.star.io.XOutputStream;
import com.sun.star.io.XSeekable;
import com.sun.star.io.XStream;
/** <p>This is a java-uno adapter class which implements XStream using a
* byte array. (We need this because XGraphicProvider demans read/write access
* when storing a graphic to a stream.)</p>
*/
public class ByteArrayXStream implements XInputStream, XOutputStream, XSeekable, XStream {
// Keep data about our byte array (we read and write to the same byte array)
private int initialSize = 100240; // 10 kb
private int size = 0; // The current buffer size
private int position = 0; // The current write position, always<=size
private int readPosition = 0; // The current read position, always<=position
private boolean closed = false; // The XStream is closed
private byte[] buffer; // The buffer
// Constructor: Initialize the byte array
public ByteArrayXStream() {
size = initialSize;
buffer = new byte[size];
}
// Implementation of XOutputStream
public void closeOutput()
throws com.sun.star.io.NotConnectedException,
com.sun.star.io.BufferSizeExceededException,
com.sun.star.io.IOException {
// trim buffer
if ( buffer.length > position) {
byte[] newBuffer = new byte[position];
System.arraycopy(buffer, 0, newBuffer, 0, position);
buffer = newBuffer;
}
closed = true;
}
public void flush()
throws com.sun.star.io.NotConnectedException,
com.sun.star.io.BufferSizeExceededException,
com.sun.star.io.IOException {
}
public void writeBytes(byte[] values)
throws com.sun.star.io.NotConnectedException,
com.sun.star.io.BufferSizeExceededException,
com.sun.star.io.IOException {
if ( values.length > size-position ) {
byte[] newBuffer = null;
while ( values.length > size-position )
size *= 2;
newBuffer = new byte[size];
System.arraycopy(buffer, 0, newBuffer, 0, position);
buffer = newBuffer;
}
System.arraycopy(values, 0, buffer, position, values.length);
position += values.length;
}
// Implementation of XInputStream
private void _check() throws com.sun.star.io.NotConnectedException, com.sun.star.io.IOException {
if(closed) {
throw new com.sun.star.io.IOException("input closed");
}
}
public int available() throws com.sun.star.io.NotConnectedException, com.sun.star.io.IOException {
_check();
return position - readPosition;
}
public void closeInput() throws com.sun.star.io.NotConnectedException, com.sun.star.io.IOException {
closed = true;
}
public int readBytes(byte[][] values, int param) throws com.sun.star.io.NotConnectedException, com.sun.star.io.BufferSizeExceededException, com.sun.star.io.IOException {
_check();
try {
int remain = (int)(position - readPosition);
if (param > remain) param = remain;
/* ARGH!!! */
if (values[0] == null){
values[0] = new byte[param];
// System.err.println("allocated new buffer of "+param+" bytes");
}
System.arraycopy(buffer, readPosition, values[0], 0, param);
// System.err.println("readbytes() -> "+param);
readPosition += param;
return param;
} catch (ArrayIndexOutOfBoundsException ae) {
// System.err.println("readbytes() -> ArrayIndexOutOfBounds");
ae.printStackTrace();
throw new com.sun.star.io.BufferSizeExceededException("buffer overflow");
} catch (Exception e) {
// System.err.println("readbytes() -> Exception: "+e.getMessage());
e.printStackTrace();
throw new com.sun.star.io.IOException("error accessing buffer");
}
}
public int readSomeBytes(byte[][] values, int param) throws com.sun.star.io.NotConnectedException, com.sun.star.io.BufferSizeExceededException, com.sun.star.io.IOException {
// System.err.println("readSomebytes()");
return readBytes(values, param);
}
public void skipBytes(int param) throws com.sun.star.io.NotConnectedException, com.sun.star.io.BufferSizeExceededException, com.sun.star.io.IOException {
// System.err.println("skipBytes("+param+")");
_check();
if (param > (position - readPosition))
throw new com.sun.star.io.BufferSizeExceededException("buffer overflow");
readPosition += param;
}
// Implementation of XSeekable
public long getLength() throws com.sun.star.io.IOException {
// System.err.println("getLength() -> "+m_length);
if (buffer != null) return position;
else throw new com.sun.star.io.IOException("no bytes");
}
public long getPosition() throws com.sun.star.io.IOException {
// System.err.println("getPosition() -> "+m_pos);
if (buffer != null) return readPosition;
else throw new com.sun.star.io.IOException("no bytes");
}
public void seek(long param) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.io.IOException {
// System.err.println("seek("+param+")");
if (buffer != null) {
if (param < 0 || param > position) throw new com.sun.star.lang.IllegalArgumentException("invalid seek position");
else readPosition = (int)param;
} else throw new com.sun.star.io.IOException("no bytes");
}
// Implementation of XStream
public XInputStream getInputStream() { return this; }
public XOutputStream getOutputStream() { return this; }
// Get the buffer
public byte[] getBuffer() { return buffer; }
}

View file

@ -0,0 +1,504 @@
/************************************************************************
*
* ExportFilterBase.java
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Copyright: 2002-2008 by Henrik Just
*
* All Rights Reserved.
*
* Version 1.0 (2008-11-24)
*
*/
// This file was originally based on OOo's XMergeBridge, which is (c) by Sun Microsystems
package org.openoffice.da.comp.w2lcommon.filter;
import com.sun.star.lib.uno.adapter.XInputStreamToInputStreamAdapter;
import com.sun.star.lib.uno.adapter.XOutputStreamToOutputStreamAdapter;
//import com.sun.star.beans.PropertyValue;
import com.sun.star.io.XInputStream;
import com.sun.star.io.XOutputStream;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.lang.XServiceName;
import com.sun.star.lang.XTypeProvider;
import com.sun.star.uno.AnyConverter;
import com.sun.star.ucb.XSimpleFileAccess2;
import com.sun.star.uno.Type;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
//import com.sun.star.xml.sax.InputSource;
//import com.sun.star.xml.sax.XParser;
import com.sun.star.xml.sax.XDocumentHandler;
import com.sun.star.xml.XExportFilter;
import org.openoffice.da.comp.w2lcommon.helper.MessageBox;
//import org.openoffice.da.comp.w2lcommon.helper.PropertyHelper;
import writer2latex.api.Converter;
import writer2latex.api.ConverterFactory;
import writer2latex.api.ConverterResult;
import writer2latex.api.OutputFile;
import java.util.Iterator;
//import java.util.Enumeration;
//import java.util.Vector;
import java.io.*;
//import javax.xml.parsers.*;
//import org.xml.sax.SAXException;
//import java.net.URI;
/** This class provides an abstract uno component which implements an XExportFilter.
* The filter is actually generic and only then constructor and 3 strings needs
* to changed by the subclass.
*/
public abstract class ExportFilterBase implements
XExportFilter,
XServiceName,
XServiceInfo,
XDocumentHandler,
XTypeProvider {
/** Service name for the component */
public static final String __serviceName = "";
/** Implementation name for the component */
public static final String __implementationName = "";
/** Filter name to include in error messages */
public static final String __displayName = "";
private static XComponentContext xComponentContext = null;
protected static XMultiServiceFactory xMSF;
private static XInputStream xInStream =null;
private static XOutputStream xOutStream=null;
private static XOutputStream xos = null;
private static String sdMime=null;
private static String sURL="";
private Object filterData;
private XSimpleFileAccess2 sfa2;
/** We need to get the Service Manager from the Component context to
* instantiate certain services, hence this constructor.
* The subclass must override this to set xMSF properly from the reigstration class
*/
public ExportFilterBase(XComponentContext xComponentContext1) {
xComponentContext = xComponentContext1;
xMSF = null;
}
// Some utility methods:
String getFileName(String origName) {
String name=null;
if (origName !=null) {
if(origName.equalsIgnoreCase(""))
name = "OutFile";
else {
if (origName.lastIndexOf("/")>=0) {
origName=origName.substring(origName.lastIndexOf("/")+1,origName.length());
}
if (origName.lastIndexOf(".")>=0) {
name = origName.substring(0,(origName.lastIndexOf(".")));
}
else {
name=origName;
}
}
}
else{
name = "OutFile";
}
return name;
}
public String replace(String origString, String origChar, String replaceChar){
String tmp="";
int index=origString.indexOf(origChar);
if(index !=-1){
while (index !=-1){
String first =origString.substring(0,index);
first=first.concat(replaceChar);
tmp=tmp.concat(first);
origString=origString.substring(index+1,origString.length());
index=origString.indexOf(origChar);
if(index==-1) {
tmp=tmp.concat(origString);
}
}
}
return tmp;
}
public String needsMask(String origString) {
if (origString.indexOf("&")!=-1){
origString=replace(origString,"&","&amp;");
}
if (origString.indexOf("\"")!=-1){
origString=replace(origString,"\"","&quot;");
}
if (origString.indexOf("<")!=-1){
origString=replace(origString,"<","&lt;");
}
if (origString.indexOf(">")!=-1){
origString=replace(origString,">","&gt;");
}
return origString;
}
// Implementation of XExportFilter:
public boolean exporter(com.sun.star.beans.PropertyValue[] aSourceData,
java.lang.String[] msUserData) throws com.sun.star.uno.RuntimeException{
sURL=null;
filterData = null;
// Get user data from configuration (type detection)
//String udConvertClass=msUserData[0];
//String udImport =msUserData[2];
//String udExport =msUserData[3];
sdMime = msUserData[5];
// Get source data (only the OutputStream and the URL are actually used)
com.sun.star.beans.PropertyValue[] pValue = aSourceData;
for (int i = 0 ; i < pValue.length; i++) {
try{
if (pValue[i].Name.compareTo("OutputStream")==0){
xos=(com.sun.star.io.XOutputStream)AnyConverter.toObject(new Type(com.sun.star.io.XOutputStream.class), pValue[i].Value);
}
//if (pValue[i].Name.compareTo("FileName")==0){
// sFileName=(String)AnyConverter.toObject(new Type(java.lang.String.class), pValue[i].Value);
//}
if (pValue[i].Name.compareTo("URL")==0){
sURL=(String)AnyConverter.toObject(new Type(java.lang.String.class), pValue[i].Value);
}
//if (pValue[i].Name.compareTo("Title")==0){
// title=(String)AnyConverter.toObject(new Type(java.lang.String.class), pValue[i].Value);
//}
if (pValue[i].Name.compareTo("FilterData")==0) {
filterData = pValue[i].Value;
}
}
catch(com.sun.star.lang.IllegalArgumentException AnyExec){
System.err.println("\nIllegalArgumentException "+AnyExec);
}
}
if (sURL==null){
sURL="";
}
// Create a pipe to be used by the XDocumentHandler implementation:
try {
Object xPipeObj=xMSF.createInstance("com.sun.star.io.Pipe");
xInStream = (XInputStream) UnoRuntime.queryInterface(
XInputStream.class , xPipeObj );
xOutStream = (XOutputStream) UnoRuntime.queryInterface(
XOutputStream.class , xPipeObj );
}
catch (Exception e){
System.err.println("Exception "+e);
return false;
}
return true;
}
// Implementation of XDocumentHandler:
// Flat xml is created by the sax events and passed through the pipe
// created by exporter()
public void startDocument () {
//Do nothing
}
public void endDocument()throws com.sun.star.uno.RuntimeException {
try{
xOutStream.closeOutput();
convert(xInStream,xos);
}
catch (IOException e){
MessageBox msgBox = new MessageBox(xComponentContext);
msgBox.showMessage(__displayName+": IO error in conversion",
e.toString()+" at "+e.getStackTrace()[0].toString());
throw new com.sun.star.uno.RuntimeException(e.getMessage());
}
catch (Exception e){
MessageBox msgBox = new MessageBox(xComponentContext);
msgBox.showMessage(__displayName+": Internal error in conversion",
e.toString()+" at "+e.getStackTrace()[0].toString());
throw new com.sun.star.uno.RuntimeException(__displayName+" Exception");
}
}
public void startElement (String str, com.sun.star.xml.sax.XAttributeList xattribs)
{
str="<".concat(str);
if (xattribs !=null)
{
str= str.concat(" ");
int len=xattribs.getLength();
for (short i=0;i<len;i++)
{
str=str.concat(xattribs.getNameByIndex(i));
str=str.concat("=\"");
str=str.concat(needsMask(xattribs.getValueByIndex(i)));
str=str.concat("\" ");
}
}
str=str.concat(">");
try{
xOutStream.writeBytes(str.getBytes("UTF-8"));
}
catch (Exception e){
System.err.println("\n"+e);
}
}
public void endElement(String str){
str="</".concat(str);
str=str.concat(">");
try{
xOutStream.writeBytes(str.getBytes("UTF-8"));
}
catch (Exception e){
System.err.println("\n"+e);
}
}
public void characters(String str){
str=needsMask(str);
try{
xOutStream.writeBytes(str.getBytes("UTF-8"));
}
catch (Exception e){
System.err.println("\n"+e);
}
}
public void ignorableWhitespace(String str){
}
public void processingInstruction(String aTarget, String aData){
}
public void setDocumentLocator(com.sun.star.xml.sax.XLocator xLocator){
}
// This is the actual conversion method, using Writer2LaTeX to convert
// the flat xml recieved from the XInputStream, and writing the result
// to the XOutputStream. The XMLExporter does not support export to
// compound documents with multiple output files; so the main file
// is written to the XOutStream and other files are written using ucb.
public void convert (com.sun.star.io.XInputStream xml,com.sun.star.io.XOutputStream exportStream)
throws com.sun.star.uno.RuntimeException, IOException {
// Initialise the file access
sfa2 = null;
try {
Object sfaObject = xComponentContext.getServiceManager().createInstanceWithContext(
"com.sun.star.ucb.SimpleFileAccess", xComponentContext);
sfa2 = (XSimpleFileAccess2) UnoRuntime.queryInterface(XSimpleFileAccess2.class, sfaObject);
}
catch (com.sun.star.uno.Exception e) {
// failed to get SimpleFileAccess service (should not happen)
}
// Get base name from the url provided by OOo
String sName= getFileName(sURL);
// Adapter for input stream (OpenDocument flat xml)
XInputStreamToInputStreamAdapter xis =new XInputStreamToInputStreamAdapter(xml);
// Adapter for output stream (Main output file)
XOutputStreamToOutputStreamAdapter newxos =new XOutputStreamToOutputStreamAdapter(exportStream);
// Create converter
Converter converter = ConverterFactory.createConverter(sdMime);
if (converter==null) {
throw new com.sun.star.uno.RuntimeException("Failed to create converter to "+sdMime);
}
// Apply the FilterData to the converter
if (filterData!=null) {
FilterDataParser fdp = new FilterDataParser(xComponentContext);
fdp.applyFilterData(filterData,converter);
}
// Do conversion
converter.setGraphicConverter(new GraphicConverterImpl(xComponentContext));
ConverterResult dataOut = null;
try {
dataOut = converter.convert(xis,sName);
}
catch (IOException e) {
// Fail silently
}
// Write out files
Iterator docEnum = dataOut.iterator();
// Remove the file name part of the url
String sNewURL = null;
if (sURL.lastIndexOf("/")>-1) {
// Take the url up to and including the last slash
sNewURL = sURL.substring(0,sURL.lastIndexOf("/")+1);
}
else {
// The url does not include a path; this should not really happen,
// but in this case we will write to the current default directory
sNewURL = "";
}
while (docEnum.hasNext() && sURL.startsWith("file:")) {
OutputFile docOut = (OutputFile)docEnum.next();
if (dataOut.getMasterDocument()==docOut) {
// The master document is written to the XOutStream supplied
// by the XMLFilterAdaptor
docOut.write(newxos);
newxos.flush();
newxos.close();
}
else {
// Additional documents are written directly using ucb
// Get the file name and the (optional) directory name
String sFullFileName = docOut.getFileName();
String sDirName = "";
String sFileName = sFullFileName;
int nSlash = sFileName.indexOf("/");
if (nSlash>-1) {
sDirName = sFileName.substring(0,nSlash);
sFileName = sFileName.substring(nSlash+1);
}
try{
// Create subdirectory if required
if (sDirName.length()>0 && !sfa2.exists(sNewURL+sDirName)) {
sfa2.createFolder(sNewURL+sDirName);
}
// writeFile demands an InputStream, so we need a pipe
Object xPipeObj=xMSF.createInstance("com.sun.star.io.Pipe");
XInputStream xInStream
= (XInputStream) UnoRuntime.queryInterface(XInputStream.class, xPipeObj );
XOutputStream xOutStream
= (XOutputStream) UnoRuntime.queryInterface(XOutputStream.class, xPipeObj );
OutputStream outStream = new XOutputStreamToOutputStreamAdapter(xOutStream);
// Feed the pipe with content...
docOut.write(outStream);
outStream.flush();
outStream.close();
xOutStream.closeOutput();
// ...and then write the content to the url
sfa2.writeFile(sNewURL+sFullFileName,xInStream);
}
catch (Throwable e){
MessageBox msgBox = new MessageBox(xComponentContext);
msgBox.showMessage(__displayName+": Error writing files",
e.toString()+" at "+e.getStackTrace()[0].toString());
}
}
}
}
// Implement methods from interface XTypeProvider
// Implementation of XTypeProvider
public com.sun.star.uno.Type[] getTypes() {
Type[] typeReturn = {};
try {
typeReturn = new Type[] {
new Type( XTypeProvider.class ),
new Type( XExportFilter.class ),
new Type( XServiceName.class ),
new Type( XServiceInfo.class ) };
}
catch( Exception exception ) {
}
return( typeReturn );
}
public byte[] getImplementationId() {
byte[] byteReturn = {};
byteReturn = new String( "" + this.hashCode() ).getBytes();
return( byteReturn );
}
// Implement method from interface XServiceName
public String getServiceName() {
return( __serviceName );
}
// Implement methods from interface XServiceInfo
public boolean supportsService(String stringServiceName) {
return( stringServiceName.equals( __serviceName ) );
}
public String getImplementationName() {
return __implementationName;
//return( W2LExportFilter.class.getName() );
}
public String[] getSupportedServiceNames() {
String[] stringSupportedServiceNames = { __serviceName };
return( stringSupportedServiceNames );
}
}

View file

@ -0,0 +1,271 @@
/************************************************************************
*
* FilterDataParser.java
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Copyright: 2002-2008 by Henrik Just
*
* All Rights Reserved.
*
* Version 1.0 (2008-11-22)
*
*/
package org.openoffice.da.comp.w2lcommon.filter;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import com.sun.star.beans.PropertyValue;
import com.sun.star.io.NotConnectedException;
import com.sun.star.io.XInputStream;
import com.sun.star.io.XOutputStream;
import com.sun.star.ucb.CommandAbortedException;
import com.sun.star.ucb.XSimpleFileAccess2;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.util.XStringSubstitution;
import com.sun.star.lib.uno.adapter.XInputStreamToInputStreamAdapter;
import com.sun.star.lib.uno.adapter.XOutputStreamToOutputStreamAdapter;
import org.openoffice.da.comp.w2lcommon.helper.PropertyHelper;
import writer2latex.api.Converter;
/** This class parses the FilterData property passed to the filter and
* applies it to a <code>Converter</code>
* All errors are silently ignored
*/
public class FilterDataParser {
//private static XComponentContext xComponentContext = null;
private XSimpleFileAccess2 sfa2;
private XStringSubstitution xPathSub;
public FilterDataParser(XComponentContext xComponentContext) {
//this.xComponentContext = xComponentContext;
// Get the SimpleFileAccess service
sfa2 = null;
try {
Object sfaObject = xComponentContext.getServiceManager().createInstanceWithContext(
"com.sun.star.ucb.SimpleFileAccess", xComponentContext);
sfa2 = (XSimpleFileAccess2) UnoRuntime.queryInterface(XSimpleFileAccess2.class, sfaObject);
}
catch (com.sun.star.uno.Exception e) {
// failed to get SimpleFileAccess service (should not happen)
}
// Get the PathSubstitution service
xPathSub = null;
try {
Object psObject = xComponentContext.getServiceManager().createInstanceWithContext(
"com.sun.star.util.PathSubstitution", xComponentContext);
xPathSub = (XStringSubstitution) UnoRuntime.queryInterface(XStringSubstitution.class, psObject);
}
catch (com.sun.star.uno.Exception e) {
// failed to get PathSubstitution service (should not happen)
}
}
/** Apply the given FilterData property to the given converter
* @param data an Any containing the FilterData property
* @param converter a <code>writer2latex.api.Converter</code> implementation
*/
public void applyFilterData(Object data, Converter converter) {
// Get the array from the data, if possible
PropertyValue[] filterData = null;
if (AnyConverter.isArray(data)) {
try {
Object[] arrayData = (Object[]) AnyConverter.toArray(data);
if (arrayData instanceof PropertyValue[]) {
filterData = (PropertyValue[]) arrayData;
}
}
catch (com.sun.star.lang.IllegalArgumentException e) {
// Failed to convert to array; should not happen - ignore
}
}
if (filterData==null) { return; }
PropertyHelper props = new PropertyHelper(filterData);
// Get the special properties TemplateURL, ConfigURL and AutoCreate
Object tpl = props.get("TemplateURL");
String sTemplate = null;
if (tpl!=null && AnyConverter.isString(tpl)) {
try {
sTemplate = substituteVariables(AnyConverter.toString(tpl));
}
catch (com.sun.star.lang.IllegalArgumentException e) {
// Failed to convert to String; should not happen - ignore
}
}
Object auto = props.get("AutoCreate");
boolean bAutoCreate = false;
if (auto!=null && AnyConverter.isString(auto)) {
try {
if ("true".equals(AnyConverter.toString(auto))) {
bAutoCreate = true;
}
}
catch (com.sun.star.lang.IllegalArgumentException e) {
// Failed to convert to String; should not happen - ignore
}
}
Object cfg = props.get("ConfigURL");
String sConfig = null;
if (cfg!=null && AnyConverter.isString(cfg)) {
try {
sConfig = substituteVariables(AnyConverter.toString(cfg));
}
catch (com.sun.star.lang.IllegalArgumentException e) {
// Failed to convert to String; should not happen - ignore
}
}
// Load the template from the specified URL, if any
if (sfa2!=null && sTemplate!=null && sTemplate.length()>0) {
try {
XInputStream xIs = sfa2.openFileRead(sTemplate);
if (xIs!=null) {
InputStream is = new XInputStreamToInputStreamAdapter(xIs);
converter.readTemplate(is);
is.close();
xIs.closeInput();
}
}
catch (IOException e) {
// ignore
}
catch (NotConnectedException e) {
// ignore
}
catch (CommandAbortedException e) {
// ignore
}
catch (com.sun.star.uno.Exception e) {
// ignore
}
}
// Create config if required
try {
if (bAutoCreate && sfa2!=null && sConfig!=null && !sConfig.startsWith("*") && !sfa2.exists(sConfig)) {
// Note: Requires random access, ie. must be a file URL:
XOutputStream xOs = sfa2.openFileWrite(sConfig);
if (xOs!=null) {
OutputStream os = new XOutputStreamToOutputStreamAdapter(xOs);
converter.getConfig().write(os);
os.flush();
os.close();
xOs.closeOutput();
}
}
}
catch (IOException e) {
// ignore
}
catch (NotConnectedException e) {
// ignore
}
catch (CommandAbortedException e) {
// Ignore
}
catch (com.sun.star.uno.Exception e) {
// Ignore
}
// Load the configuration from the specified URL, if any
if (sConfig!=null) {
if (sConfig.startsWith("*")) { // internal configuration
try {
converter.getConfig().readDefaultConfig(sConfig.substring(1));
}
catch (IllegalArgumentException e) {
// ignore
}
}
else if (sfa2!=null) { // real URL
try {
XInputStream xIs = sfa2.openFileRead(sConfig);;
if (xIs!=null) {
InputStream is = new XInputStreamToInputStreamAdapter(xIs);
converter.getConfig().read(is);
is.close();
xIs.closeInput();
}
}
catch (IOException e) {
// Ignore
}
catch (NotConnectedException e) {
// Ignore
}
catch (CommandAbortedException e) {
// Ignore
}
catch (com.sun.star.uno.Exception e) {
// Ignore
}
}
}
// Read further configuration properties
Enumeration keys = props.keys();
while (keys.hasMoreElements()) {
String sKey = (String) keys.nextElement();
if (!"ConfigURL".equals(sKey) && !"TemplateURL".equals(sKey) && !"AutoCreate".equals(sKey)) {
Object value = props.get(sKey);
if (AnyConverter.isString(value)) {
try {
converter.getConfig().setOption(sKey,AnyConverter.toString(value));
}
catch (com.sun.star.lang.IllegalArgumentException e) {
// Failed to convert to String; should not happen - ignore
}
}
}
}
}
private String substituteVariables(String sUrl) {
if (xPathSub!=null) {
try {
return xPathSub.substituteVariables(sUrl, false);
}
catch (com.sun.star.container.NoSuchElementException e) {
// Found an unknown variable, no substitution
// (This will only happen if false is replaced by true above)
return sUrl;
}
}
else { // Not path substitution available
return sUrl;
}
}
}

View file

@ -0,0 +1,67 @@
/************************************************************************
*
* GraphicConverterImpl.java
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Copyright: 2002-2008 by Henrik Just
*
* All Rights Reserved.
*
* Version 1.0 (2008-07-21)
*
*/
package org.openoffice.da.comp.w2lcommon.filter;
import com.sun.star.uno.XComponentContext;
import writer2latex.api.GraphicConverter;
public class GraphicConverterImpl implements GraphicConverter {
private GraphicConverter graphicConverter1;
private GraphicConverter graphicConverter2;
public GraphicConverterImpl(XComponentContext xComponentContext) {
graphicConverter1 = new GraphicConverterImpl1(xComponentContext);
graphicConverter2 = new GraphicConverterImpl2(xComponentContext);
}
public boolean supportsConversion(String sSourceMime, String sTargetMime, boolean bCrop, boolean bResize) {
return graphicConverter1.supportsConversion(sSourceMime, sTargetMime, bCrop, bResize) ||
graphicConverter2.supportsConversion(sSourceMime, sTargetMime, bCrop, bResize);
}
public byte[] convert(byte[] source, String sSourceMime, String sTargetMime) {
byte[] result = null;
// Prefer the simple implementation (GraphicProvider)
if (graphicConverter1.supportsConversion(sSourceMime, sTargetMime, false, false)) {
result = graphicConverter1.convert(source, sSourceMime, sTargetMime);
}
// If this is not possible or fails, try the complex implementation
if (result==null) {
result = graphicConverter2.convert(source, sSourceMime, sTargetMime);
}
return result;
}
}

View file

@ -0,0 +1,194 @@
/************************************************************************
*
* GraphicConverterImpl1.java
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Copyright: 2002-2008 by Henrik Just
*
* All Rights Reserved.
*/
// Version 1.0 (2008-11-22)
package org.openoffice.da.comp.w2lcommon.filter;
// Java uno helper class
import com.sun.star.lib.uno.adapter.ByteArrayToXInputStreamAdapter;
// UNO classes
import com.sun.star.beans.PropertyValue;
import com.sun.star.graphic.XGraphic;
import com.sun.star.graphic.XGraphicProvider;
//import com.sun.star.io.XInputStream;
//import com.sun.star.io.XOutputStream;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.UnoRuntime;
//import java.io.InputStream;
//import java.io.OutputStream;
import writer2latex.api.GraphicConverter;
import writer2latex.api.MIMETypes;
/** A GraphicConverter implementation which uses the GraphicProvider service
* to convert the graphic. This service does only support simple format
* conversion using the "internal" graphics filters in Draw. Advanced features
* like pdf, crop and resize thus cannot be handled.
*/
public class GraphicConverterImpl1 implements GraphicConverter {
// Signatures for start and end in exp
private byte[] psStart;
private byte[] psEnd;
private XGraphicProvider xGraphicProvider;
public GraphicConverterImpl1(XComponentContext xComponentContext) {
try {
// Get the XGraphicProvider interface of the GraphicProvider service
XMultiComponentFactory xMCF = xComponentContext.getServiceManager();
Object graphicProviderObject = xMCF.createInstanceWithContext("com.sun.star.graphic.GraphicProvider", xComponentContext);
xGraphicProvider = (XGraphicProvider) UnoRuntime.queryInterface(XGraphicProvider.class, graphicProviderObject);
}
catch (com.sun.star.uno.Exception ex) {
System.err.println("Failed to get XGraphicProvider object");
xGraphicProvider = null;
}
try {
psStart = "%!PS-Adobe".getBytes("US-ASCII");
psEnd = "%%EOF".getBytes("US-ASCII");
}
catch (java.io.UnsupportedEncodingException ex) {
// US-ASCII *is* supported :-)
}
}
public boolean supportsConversion(String sSourceMime, String sTargetMime, boolean bCrop, boolean bResize) {
// We don't support cropping and resizing
if (bCrop || bResize) { return false; }
// We can convert vector formats to eps:
if (MIMETypes.EPS.equals(sTargetMime) && (MIMETypes.WMF.equals(sSourceMime) && MIMETypes.SVM.equals(sSourceMime))) {
return true;
}
// And we can convert all formats to bitmaps
boolean bSupportsSource =
MIMETypes.PNG.equals(sSourceMime) || MIMETypes.JPEG.equals(sSourceMime) ||
MIMETypes.GIF.equals(sSourceMime) || MIMETypes.TIFF.equals(sSourceMime) ||
MIMETypes.BMP.equals(sSourceMime) || MIMETypes.WMF.equals(sSourceMime) ||
MIMETypes.SVM.equals(sSourceMime);
boolean bSupportsTarget =
MIMETypes.PNG.equals(sTargetMime) || MIMETypes.JPEG.equals(sTargetMime) ||
MIMETypes.GIF.equals(sTargetMime) || MIMETypes.TIFF.equals(sTargetMime) ||
MIMETypes.BMP.equals(sTargetMime);
return bSupportsSource && bSupportsTarget;
}
public byte[] convert(byte[] source, String sSourceMime, String sTargetMime) {
// It seems that the GraphicProvider can only create proper eps if
// the source is a vector format, hence
if (MIMETypes.EPS.equals(sTargetMime)) {
if (!MIMETypes.WMF.equals(sSourceMime) && !MIMETypes.SVM.equals(sSourceMime)) {
return null;
}
}
ByteArrayToXInputStreamAdapter xSource = new ByteArrayToXInputStreamAdapter(source);
ByteArrayXStream xTarget = new ByteArrayXStream();
try {
// Read the source
PropertyValue[] sourceProps = new PropertyValue[1];
sourceProps[0] = new PropertyValue();
sourceProps[0].Name = "InputStream";
sourceProps[0].Value = xSource;
XGraphic result = xGraphicProvider.queryGraphic(sourceProps);
// Store as new type
PropertyValue[] targetProps = new PropertyValue[2];
targetProps[0] = new PropertyValue();
targetProps[0].Name = "MimeType";
targetProps[0].Value = sTargetMime;
targetProps[1] = new PropertyValue();
targetProps[1].Name = "OutputStream";
targetProps[1].Value = xTarget;
xGraphicProvider.storeGraphic(result,targetProps);
// Close the output and return the result
xTarget.closeOutput();
xTarget.flush();
if (MIMETypes.EPS.equals(sTargetMime)) {
return cleanEps(xTarget.getBuffer());
}
else {
return xTarget.getBuffer();
}
}
catch (com.sun.star.io.IOException e) {
return null;
}
catch (com.sun.star.lang.IllegalArgumentException e) {
return null;
}
catch (com.sun.star.lang.WrappedTargetException e) {
return null;
}
catch (Throwable e) {
return null;
}
}
private byte[] cleanEps(byte[] blob) {
int n = blob.length;
int nStart = 0;
for (int i=0; i<n; i++) {
if (match(blob,psStart,i)) {
nStart=i;
break;
}
}
int nEnd = n;
for (int i=nStart; i<n; i++) {
if (match(blob,psEnd,i)) {
nEnd=i+psEnd.length;
break;
}
}
byte[] newBlob = new byte[nEnd-nStart];
System.arraycopy(blob,nStart,newBlob,0,nEnd-nStart);
return newBlob;
}
private boolean match(byte[] blob, byte[] sig, int nStart) {
int n = sig.length;
if (nStart+n>=blob.length) { return false; }
for (int i=0; i<n; i++) {
if (blob[nStart+i]!=sig[i]) { return false; }
}
return true;
}
}

View file

@ -0,0 +1,267 @@
/************************************************************************
*
* GraphicConverterImpl2.java
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Copyright: 2002-2008 by Henrik Just
*
* All Rights Reserved.
*
* Version 1.0 (2008-10-07)
*
*/
package org.openoffice.da.comp.w2lcommon.filter;
import java.util.Hashtable;
import com.sun.star.awt.Point;
import com.sun.star.awt.Size;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.drawing.XDrawPage;
import com.sun.star.drawing.XDrawPages;
import com.sun.star.drawing.XDrawPagesSupplier;
import com.sun.star.drawing.XShape;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.util.XRefreshable;
import com.sun.star.lib.uno.adapter.ByteArrayToXInputStreamAdapter;
import com.sun.star.lib.uno.adapter.XOutputStreamToByteArrayAdapter;
import writer2latex.api.GraphicConverter;
import writer2latex.api.MIMETypes;
/** A GraphicConverter implementation which uses a hidden Draw document to
* store the graphic, providing more control over the image than the
* simple GraphicProvider implementation.
*/
public class GraphicConverterImpl2 implements GraphicConverter {
private XComponentContext xComponentContext;
private Hashtable importFilter;
private Hashtable exportFilter;
public GraphicConverterImpl2(XComponentContext xComponentContext) {
this.xComponentContext = xComponentContext;
importFilter = new Hashtable();
importFilter.put(MIMETypes.BMP, "BMP - MS Windows");
//importFilter.put(MIMETypes.EMF, "EMF - MS Windows Metafile");
importFilter.put(MIMETypes.EPS, "EPS - Encapsulated PostScript");
importFilter.put(MIMETypes.GIF, "GIF - Graphics Interchange Format");
importFilter.put(MIMETypes.JPEG, "JPG - JPEG");
importFilter.put(MIMETypes.PNG, "PNG - Portable Network Graphic");
importFilter.put(MIMETypes.SVM, "SVM - StarView Metafile");
importFilter.put(MIMETypes.TIFF, "TIF - Tag Image File");
importFilter.put(MIMETypes.WMF, "WMF - MS Windows Metafile");
exportFilter = new Hashtable();
exportFilter.put(MIMETypes.BMP,"draw_bmp_Export");
//exportFilter.put(MIMETypes.EMF,"draw_emf_Export");
exportFilter.put(MIMETypes.EPS,"draw_eps_Export");
exportFilter.put(MIMETypes.GIF,"draw_gif_Export");
exportFilter.put(MIMETypes.JPEG,"draw_jpg_Export");
exportFilter.put(MIMETypes.PNG,"draw_png_Export");
//exportFilter.put(MIMETypes.SVG,"draw_svg_Export");
exportFilter.put(MIMETypes.SVM,"draw_svm_Export");
exportFilter.put(MIMETypes.TIFF,"draw_tif_Export");
exportFilter.put(MIMETypes.WMF,"draw_wmf_Export");
exportFilter.put(MIMETypes.PDF,"draw_pdf_Export");
}
public boolean supportsConversion(String sSourceMime, String sTargetMime, boolean bCrop, boolean bResize) {
// We don't support cropping and resizing
if (bCrop || bResize) { return false; }
// We currently only support conversion of svm into pdf
// Trying wmf causes an IllegalArgumentException "URL seems to be an unsupported one"
// Seems to be an OOo bug; workaround: Use temporary files..??
boolean bSupportsSource = MIMETypes.SVM.equals(sSourceMime);
/*MIMETypes.PNG.equals(sSourceMime) || MIMETypes.JPEG.equals(sSourceMime) ||
MIMETypes.GIF.equals(sSourceMime) || MIMETypes.TIFF.equals(sSourceMime) ||
MIMETypes.BMP.equals(sSourceMime) || MIMETypes.WMF.equals(sSourceMime) ||
MIMETypes.SVM.equals(sSourceMime);*/
return bSupportsSource && MIMETypes.PDF.equals(sTargetMime);
}
public byte[] convert(byte[] source, String sSourceMime, String sTargetMime) {
// Open a hidden sdraw document
XMultiComponentFactory xMCF = xComponentContext.getServiceManager();
org.openoffice.da.comp.w2lcommon.helper.MessageBox msgBox = new org.openoffice.da.comp.w2lcommon.helper.MessageBox(xComponentContext);
try {
// Load the graphic into a new draw document as xDocument
// using a named filter
Object desktop = xMCF.createInstanceWithContext(
"com.sun.star.frame.Desktop", xComponentContext);
XComponentLoader xComponentLoader = (XComponentLoader)
UnoRuntime.queryInterface(XComponentLoader.class, desktop);
//msgBox.showMessage("Graphics","Trying to load using filter name "+importFilter.get(sSourceMime));
PropertyValue[] fileProps = new PropertyValue[3];
fileProps[0] = new PropertyValue();
fileProps[0].Name = "FilterName";
fileProps[0].Value = (String) importFilter.get(sSourceMime);
fileProps[1] = new PropertyValue();
fileProps[1].Name = "InputStream";
fileProps[1].Value = new ByteArrayToXInputStreamAdapter(source);
fileProps[2] = new PropertyValue();
fileProps[2].Name = "Hidden";
fileProps[2].Value = new Boolean(true);
XComponent xDocument = xComponentLoader.loadComponentFromURL(
"private:stream", "_blank", 0, fileProps);
// Get the first draw page as xDrawPage
XDrawPagesSupplier xDrawPagesSupplier = (XDrawPagesSupplier)
UnoRuntime.queryInterface(XDrawPagesSupplier.class, xDocument);
XDrawPages xDrawPages = xDrawPagesSupplier.getDrawPages();
Object drawPage = xDrawPages.getByIndex(0);
XDrawPage xDrawPage = (XDrawPage) UnoRuntime.queryInterface(
XDrawPage.class, drawPage);
// Get the shape as xShape
Object shape = xDrawPage.getByIndex(0);
XShape xShape = (XShape) UnoRuntime.queryInterface(XShape.class, shape);
// Move the shape to upper left corner of the page
Point position = new Point();
position.X = 0;
position.Y = 0;
xShape.setPosition(position);
// Adjust the page size and margin to the size of the graphic
XPropertySet xPageProps = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, xDrawPage);
Size size = xShape.getSize();
xPageProps.setPropertyValue("Width", new Integer(size.Width));
xPageProps.setPropertyValue("Height", new Integer(size.Height));
xPageProps.setPropertyValue("BorderTop", new Integer(0));
xPageProps.setPropertyValue("BorderBottom", new Integer(0));
xPageProps.setPropertyValue("BorderLeft", new Integer(0));
xPageProps.setPropertyValue("BorderRight", new Integer(0));
// Export the draw document (xDocument)
refreshDocument(xDocument);
XOutputStreamToByteArrayAdapter outputStream = new XOutputStreamToByteArrayAdapter();
PropertyValue[] exportProps = new PropertyValue[3];
exportProps[0] = new PropertyValue();
exportProps[0].Name = "FilterName";
exportProps[0].Value = (String) exportFilter.get(sTargetMime);
exportProps[1] = new PropertyValue();
exportProps[1].Name = "OutputStream";
exportProps[1].Value = outputStream;
exportProps[2] = new PropertyValue();
exportProps[2].Name = "Overwrite";
exportProps[2].Value = new Boolean(true);
XStorable xStore = (XStorable) UnoRuntime.queryInterface (
XStorable.class, xDocument);
xStore.storeToURL ("private:stream", exportProps);
outputStream.closeOutput();
byte[] result = outputStream.getBuffer();
xDocument.dispose();
return result;
}
catch (com.sun.star.beans.PropertyVetoException e) {
msgBox.showMessage("Exception",e.toString());
}
catch (com.sun.star.beans.UnknownPropertyException e) {
msgBox.showMessage("Exception",e.toString());
}
catch (com.sun.star.io.IOException e) {
msgBox.showMessage("Exception",e.toString());
}
catch (com.sun.star.lang.IllegalArgumentException e) {
msgBox.showMessage("Exception",e.toString());
}
catch (com.sun.star.lang.IndexOutOfBoundsException e) {
msgBox.showMessage("Exception",e.toString());
}
catch (com.sun.star.lang.WrappedTargetException e) {
msgBox.showMessage("Exception",e.toString());
}
catch (com.sun.star.uno.Exception e) {
msgBox.showMessage("Exception",e.toString());
}
// Conversion failed, for whatever reason
return null;
}
protected void refreshDocument(XComponent document) {
XRefreshable refreshable = (XRefreshable) UnoRuntime.queryInterface(XRefreshable.class, document);
if (refreshable != null) {
refreshable.refresh();
}
}
/* Dim SelSize As New com.sun.star.awt.Size
SelSize = oGraphic.Size
oDrawGraphic.GraphicURL = oGraphic.GraphicURL
oDrawGraphic.Size = SelSize
oDrawPage.add(oDrawGraphic)
oDrawGraphic.GraphicCrop = oGraphic.GraphicCrop
oDrawPage.Width = oGraphic.Size.Width
oDrawPage.Height = oGraphic.Size.Height
Dim aFilterData (1) As new com.sun.star.beans.PropertyValue
aFilterData(0).Name = "PixelWidth" '
aFilterData(0).Value = oDrawPage.Width/100 * iPixels / 25.40
aFilterData(1).Name = "PixelHeight"
aFilterData(1).Value = oDrawPage.Height/100 * iPixels / 25.40
Export( oDrawPage, sURLImageResized , aFilterData() )
On error resume Next
oDrawDoc.Close(True)
On error goto 0
SUB Export( xObject, sFileUrl As String, aFilterData )
Dim xExporter As Object
xExporter = createUnoService( "com.sun.star.drawing.GraphicExportFilter" )
xExporter.SetSourceDocument( xObject )
Dim aArgs (2) As new com.sun.star.beans.PropertyValue
'sFileURL = ConvertToURL(sFileURL)
aArgs(0).Name = "FilterName"
aArgs(0).Value = "jpg"
aArgs(1).Name = "URL"
aArgs(1).Value = sFileURL
'print sFileURL
aArgs(2).Name = "FilterData"
aArgs(2).Value = aFilterData
xExporter.filter( aArgs() )
END SUB*/
}

View file

@ -0,0 +1,547 @@
/************************************************************************
*
* OptionsDialogBase.java
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Copyright: 2002-2008 by Henrik Just
*
* All Rights Reserved.
*
* Version 1.0 (2008-10-14)
*
*/
package org.openoffice.da.comp.w2lcommon.filter;
import java.util.HashSet;
import com.sun.star.awt.XDialogEventHandler;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertyAccess;
import com.sun.star.beans.XPropertySet;
import com.sun.star.container.XNameAccess;
import com.sun.star.document.XDocumentInfoSupplier;
import com.sun.star.frame.XDesktop;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.lang.XServiceName;
import com.sun.star.lang.XTypeProvider;
import com.sun.star.ui.dialogs.XExecutableDialog;
import com.sun.star.uno.Type;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.util.XChangesBatch;
import com.sun.star.util.XMacroExpander;
import org.openoffice.da.comp.w2lcommon.helper.DialogBase;
import org.openoffice.da.comp.w2lcommon.helper.PropertyHelper;
/** This class provides an abstract uno component which implements a filter ui
*/
public abstract class OptionsDialogBase extends DialogBase implements
XPropertyAccess { // Filter ui requires XExecutableDialog + XPropertyAccess
//////////////////////////////////////////////////////////////////////////
// The subclass must override the following; and override the
// implementation of XDialogEventHandler if needed
/** Load settings from the registry to the dialog
* The subclass must implement this
*/
protected abstract void loadSettings(XPropertySet xRegistryProps);
/** Save settings from the dialog to the registry and create FilterData
* The subclass must implement this
*/
protected abstract void saveSettings(XPropertySet xRegistryProps, PropertyHelper filterData);
/** Return the name of the library containing the dialog
*/
public abstract String getDialogLibraryName();
/** Return the name of the dialog within the library
*/
public abstract String getDialogName();
/** Return the path to the options in the registry */
public abstract String getRegistryPath();
/** Create a new OptionsDialogBase */
public OptionsDialogBase(XComponentContext xContext) {
super(xContext);
this.xMSF = null; // must be set properly by subclass
mediaProps = null;
sConfigNames = null;
lockedOptions = new HashSet();
}
//////////////////////////////////////////////////////////////////////////
// Implement some methods required by DialogBase
/** Initialize the dialog (eg. with settings from the registry)
*/
public void initialize() {
try {
// Prepare registry view
Object view = getRegistryView(false);
XPropertySet xProps = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class,view);
// Load settings using method from subclass
loadSettings(xProps);
// Dispose the registry view
disposeRegistryView(view);
}
catch (com.sun.star.uno.Exception e) {
// Failed to get registry view
}
}
/** Finalize the dialog after execution (eg. save settings to the registry)
*/
public void finalize() {
try {
// Prepare registry view
Object rwview = getRegistryView(true);
XPropertySet xProps = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class,rwview);
// Save settings and create FilterData using method from subclass
PropertyHelper filterData = new PropertyHelper();
saveSettings(xProps, filterData);
// Commit registry changes
XChangesBatch xUpdateContext = (XChangesBatch)
UnoRuntime.queryInterface(XChangesBatch.class,rwview);
try {
xUpdateContext.commitChanges();
}
catch (Exception e) {
// ignore
}
// Dispose the registry view
disposeRegistryView(rwview);
// Update the media properties with the FilterData
PropertyHelper helper = new PropertyHelper(mediaProps);
helper.put("FilterData",filterData.toArray());
mediaProps = helper.toArray();
}
catch (com.sun.star.uno.Exception e) {
// Failed to get registry view
}
}
//////////////////////////////////////////////////////////////////////////
// Some private global variables
// The service factory
protected XMultiServiceFactory xMSF;
// The media properties (set/get via XPropertyAccess implementation)
private PropertyValue[] mediaProps;
// Configuration names (stored during execution of dialog)
private String[] sConfigNames;
// Set of locked controls
private HashSet lockedOptions;
//////////////////////////////////////////////////////////////////////////
// Some private utility methods
// Perform macro extansion
private String expandMacros(String s) {
if (s.startsWith("vnd.sun.star.expand:")) {
// The string contains a macro, usually as a result of using %origin% in the registry
s = s.substring(20);
Object expander = xContext.getValueByName("/singletons/com.sun.star.util.theMacroExpander");
XMacroExpander xExpander = (XMacroExpander) UnoRuntime.queryInterface (XMacroExpander.class, expander);
try {
return xExpander.expandMacros(s);
}
catch (IllegalArgumentException e) {
// Unknown macro name found, proceed and hope for the best
return s;
}
}
else {
return s;
}
}
// Get the template name from the document with ui focus
private String getTemplateName() {
try {
// Get current component
Object desktop = xContext.getServiceManager()
.createInstanceWithContext("com.sun.star.frame.Desktop",xContext);
XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class,desktop);
XComponent xComponent = xDesktop.getCurrentComponent();
// Get the document info property set
XDocumentInfoSupplier xDocInfoSuppl = (XDocumentInfoSupplier)
UnoRuntime.queryInterface(XDocumentInfoSupplier.class, xComponent);
Object docInfo = xDocInfoSuppl.getDocumentInfo();
XPropertySet xDocInfo = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class, docInfo);
return getPropertyValueAsString(xDocInfo,"Template");
}
catch (Exception e) {
return "";
}
}
// Get a view of the options root in the registry
private Object getRegistryView(boolean bUpdate)
throws com.sun.star.uno.Exception {
Object provider = xMSF.createInstance(
"com.sun.star.configuration.ConfigurationProvider");
XMultiServiceFactory xProvider = (XMultiServiceFactory)
UnoRuntime.queryInterface(XMultiServiceFactory.class,provider);
PropertyValue[] args = new PropertyValue[1];
args[0] = new PropertyValue();
args[0].Name = "nodepath";
args[0].Value = getRegistryPath();
String sServiceName = bUpdate ?
"com.sun.star.configuration.ConfigurationUpdateAccess" :
"com.sun.star.configuration.ConfigurationAccess";
Object view = xProvider.createInstanceWithArguments(sServiceName,args);
return view;
}
// Dispose a previously obtained registry view
private void disposeRegistryView(Object view) {
XComponent xComponent = (XComponent)
UnoRuntime.queryInterface(XComponent.class,view);
xComponent.dispose();
}
//////////////////////////////////////////////////////////////////////////
// Implement uno interfaces
// Override getTypes() from the interface XTypeProvider
public Type[] getTypes() {
Type[] typeReturn = {};
try {
typeReturn = new Type[] {
new Type( XServiceName.class ),
new Type( XServiceInfo.class ),
new Type( XTypeProvider.class ),
new Type( XExecutableDialog.class ),
new Type( XPropertyAccess.class ),
new Type( XDialogEventHandler.class ) };
} catch(Exception exception) {
}
return typeReturn;
}
// Implement the interface XPropertyAccess
public PropertyValue[] getPropertyValues() {
return mediaProps;
}
public void setPropertyValues(PropertyValue[] props) {
mediaProps = props;
}
//////////////////////////////////////////////////////////////////////////
// Various utility methods to be used by the sublasses
// Helpers to load and save settings
protected void updateLockedOptions() {
lockedOptions.clear();
short nItem = getListBoxSelectedItem("Config");
int nStdConfigs = getListBoxStringItemList("Config").length - sConfigNames.length;
if (nItem>=nStdConfigs) {
// Get current configuration name
String sName = sConfigNames[nItem-nStdConfigs];
try {
// Prepare registry view
Object view = getRegistryView(false);
XPropertySet xProps = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class,view);
// Get the available configurations
Object configurations = getPropertyValue(xProps,"Configurations");
XNameAccess xConfigurations = (XNameAccess)
UnoRuntime.queryInterface(XNameAccess.class,configurations);
// Get the LockedOptions node from the desired configuration
String sLockedOptions = "";
Object config = xConfigurations.getByName(sName);
XPropertySet xCfgProps = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class,config);
sLockedOptions = getPropertyValueAsString(xCfgProps,"LockedOptions");
// Dispose the registry view
disposeRegistryView(view);
// Feed lockedOptions with the comma separated list of options
int nStart = 0;
for (int i=0; i<sLockedOptions.length(); i++) {
if (sLockedOptions.charAt(i)==',') {
lockedOptions.add(sLockedOptions.substring(nStart,i).trim());
nStart = i+1;
}
}
if (nStart<sLockedOptions.length()) {
lockedOptions.add(sLockedOptions.substring(nStart).trim());
}
}
catch (Exception e) {
// no options will be locked...
}
}
}
protected boolean isLocked(String sOptionName) {
return lockedOptions.contains(sOptionName);
}
// Configuration
protected void loadConfig(XPropertySet xProps) {
// The list box is extended with configurations from the registry
String[] sStdConfigs = getListBoxStringItemList("Config");
int nStdConfigs = sStdConfigs.length;
Object configurations = getPropertyValue(xProps,"Configurations");
XNameAccess xConfigurations = (XNameAccess)
UnoRuntime.queryInterface(XNameAccess.class,configurations);
sConfigNames = xConfigurations.getElementNames();
int nRegConfigs = sConfigNames.length;
String[] sAllConfigs = new String[nStdConfigs+nRegConfigs];
for (short i=0; i<nStdConfigs; i++) {
sAllConfigs[i] = sStdConfigs[i];
}
for (short i=0; i<nRegConfigs; i++) {
try {
Object config = xConfigurations.getByName(sConfigNames[i]);
XPropertySet xCfgProps = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class,config);
sAllConfigs[nStdConfigs+i] = getPropertyValueAsString(xCfgProps,"DisplayName");
}
catch (Exception e) {
sAllConfigs[nStdConfigs+i] = "";
}
}
setListBoxStringItemList("Config",sAllConfigs);
if (nStdConfigs+nRegConfigs<=12) {
setListBoxLineCount("Config",(short) (nStdConfigs+nRegConfigs));
}
else {
setListBoxLineCount("Config",(short) 12);
}
// Select item based on template name
String sTheTemplateName = getTemplateName();
Object templates = getPropertyValue(xProps,"Templates");
XNameAccess xTemplates = (XNameAccess)
UnoRuntime.queryInterface(XNameAccess.class,templates);
String[] sTemplateNames = xTemplates.getElementNames();
for (int i=0; i<sTemplateNames.length; i++) {
try {
Object template = xTemplates.getByName(sTemplateNames[i]);
XPropertySet xTplProps = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class,template);
String sTemplateName = getPropertyValueAsString(xTplProps,"TemplateName");
if (sTemplateName.equals(sTheTemplateName)) {
String sConfigName = getPropertyValueAsString(xTplProps,"ConfigName");
for (short j=0; j<nRegConfigs; j++) {
if (sConfigNames[j].equals(sConfigName)) {
setListBoxSelectedItem("Config",(short) (nStdConfigs+j));
return;
}
}
}
}
catch (Exception e) {
// ignore
}
}
// Select item based on value stored in registry
short nConfig = getPropertyValueAsShort(xProps,"Config");
if (nConfig<nStdConfigs) {
setListBoxSelectedItem("Config",nConfig);
}
else { // Registry configurations are stored by name
String sConfigName = getPropertyValueAsString(xProps,"ConfigName");
for (short i=0; i<nRegConfigs; i++) {
if (sConfigNames[i].equals(sConfigName)) {
setListBoxSelectedItem("Config",(short) (nStdConfigs+i));
}
}
}
}
protected short saveConfig(XPropertySet xProps, PropertyHelper filterData) {
// The Config list box is common for all dialogs
Object configurations = getPropertyValue(xProps,"Configurations");
XNameAccess xNameAccess = (XNameAccess)
UnoRuntime.queryInterface(XNameAccess.class,configurations);
boolean bFound = false;
short nConfig = getListBoxSelectedItem("Config");
int nStdConfigs = getListBoxStringItemList("Config").length - sConfigNames.length;
if (nConfig>=nStdConfigs) { // only handle registry configurations
int i = nConfig-nStdConfigs;
try {
Object config = xNameAccess.getByName(sConfigNames[i]);
XPropertySet xCfgProps = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class,config);
filterData.put("ConfigURL",expandMacros(getPropertyValueAsString(xCfgProps,"ConfigURL")));
filterData.put("TemplateURL",expandMacros(getPropertyValueAsString(xCfgProps,"TargetTemplateURL")));
setPropertyValue(xProps,"ConfigName",sConfigNames[i]);
bFound = true;
}
catch (Exception e) {
}
}
setPropertyValue(xProps,"Config",nConfig);
if (!bFound) { setPropertyValue(xProps,"ConfigName",""); }
return nConfig;
}
// Check box option (boolean)
protected boolean loadCheckBoxOption(XPropertySet xProps, String sName) {
boolean bValue = getPropertyValueAsBoolean(xProps,sName);
setCheckBoxStateAsBoolean(sName, bValue);
return bValue;
}
protected boolean saveCheckBoxOption(XPropertySet xProps, String sName) {
boolean bValue = getCheckBoxStateAsBoolean(sName);
setPropertyValue(xProps, sName, bValue);
return bValue;
}
protected boolean saveCheckBoxOption(XPropertySet xProps, PropertyHelper filterData,
String sName, String sOptionName) {
boolean bValue = saveCheckBoxOption(xProps, sName);
if (!isLocked(sOptionName)) {
filterData.put(sOptionName, Boolean.toString(bValue));
}
return bValue;
}
// List box option
protected short loadListBoxOption(XPropertySet xProps, String sName) {
short nValue = getPropertyValueAsShort(xProps, sName);
setListBoxSelectedItem(sName ,nValue);
return nValue;
}
protected short saveListBoxOption(XPropertySet xProps, String sName) {
short nValue = getListBoxSelectedItem(sName);
setPropertyValue(xProps, sName, nValue);
return nValue;
}
protected short saveListBoxOption(XPropertySet xProps, PropertyHelper filterData,
String sName, String sOptionName, String[] sValues) {
short nValue = saveListBoxOption(xProps, sName);
if (!isLocked(sOptionName) && (nValue>=0) && (nValue<sValues.length)) {
filterData.put(sOptionName, sValues[nValue]);
}
return nValue;
}
// Combo box option
protected String loadComboBoxOption(XPropertySet xProps, String sName) {
String sValue = getPropertyValueAsString(xProps, sName);
setComboBoxText(sName ,sValue);
return sValue;
}
protected String saveComboBoxOption(XPropertySet xProps, String sName) {
String sValue = getComboBoxText(sName);
setPropertyValue(xProps, sName, sValue);
return sValue;
}
protected String saveComboBoxOption(XPropertySet xProps, PropertyHelper filterData,
String sName, String sOptionName) {
String sValue = saveComboBoxOption(xProps, sName);
if (!isLocked(sOptionName)) {
filterData.put(sOptionName, sValue);
}
return sValue;
}
// Text Field option
protected String loadTextFieldOption(XPropertySet xProps, String sName) {
String sValue = getPropertyValueAsString(xProps, sName);
setTextFieldText(sName ,sValue);
return sValue;
}
protected String saveTextFieldOption(XPropertySet xProps, String sName) {
String sValue = getTextFieldText(sName);
setPropertyValue(xProps, sName, sValue);
return sValue;
}
protected String saveTextFieldOption(XPropertySet xProps, PropertyHelper filterData,
String sName, String sOptionName) {
String sValue = saveTextFieldOption(xProps, sName);
if (!isLocked(sOptionName)) {
filterData.put(sOptionName, sValue);
}
return sValue;
}
// Numeric option
protected int loadNumericOption(XPropertySet xProps, String sName) {
int nValue = getPropertyValueAsInteger(xProps, sName);
setNumericFieldValue(sName, nValue);
return nValue;
}
protected int saveNumericOption(XPropertySet xProps, String sName) {
int nValue = getNumericFieldValue(sName);
setPropertyValue(xProps, sName, nValue);
return nValue;
}
protected int saveNumericOptionAsPercentage(XPropertySet xProps,
PropertyHelper filterData, String sName, String sOptionName) {
int nValue = saveNumericOption(xProps, sName);
if (!isLocked(sOptionName)) {
filterData.put(sOptionName,Integer.toString(nValue)+"%");
}
return nValue;
}
}

View file

@ -0,0 +1,503 @@
/************************************************************************
*
* DialogBase.java
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Copyright: 2002-2008 by Henrik Just
*
* All Rights Reserved.
*
* Version 1.0 (2008-09-11)
*
*/
package org.openoffice.da.comp.w2lcommon.helper;
import com.sun.star.awt.XControl;
import com.sun.star.awt.XControlContainer;
import com.sun.star.awt.XControlModel;
import com.sun.star.awt.XDialog;
import com.sun.star.awt.XDialogEventHandler;
import com.sun.star.awt.XDialogProvider2;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.beans.UnknownPropertyException;
import com.sun.star.beans.XPropertySet;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.lang.XServiceName;
import com.sun.star.lang.XTypeProvider;
import com.sun.star.ui.dialogs.ExecutableDialogResults;
import com.sun.star.ui.dialogs.XExecutableDialog;
import com.sun.star.uno.Type;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
/** This class provides an abstract uno component which implements a dialog
* from an xml description (using the DialogProvider2 service)
*/
public abstract class DialogBase implements
XTypeProvider, XServiceInfo, XServiceName, // Uno component
XExecutableDialog, // Execute the dialog
XDialogEventHandler { // Event handling for dialog
//////////////////////////////////////////////////////////////////////////
// The subclass must override the following; and override the
// implementation of XDialogEventHandler if needed
/** The component will be registered under this name.
* The subclass must override this with a suitable name
*/
public static String __serviceName = "";
/** The component should also have an implementation name.
* The subclass must override this with a suitable name
*/
public static String __implementationName = "";
/** Return the name of the library containing the dialog
* The subclass must override this to provide the name of the library
*/
public abstract String getDialogLibraryName();
/** Return the name of the dialog within the library
* The subclass must override this to provide the name of the dialog
*/
public abstract String getDialogName();
/** Initialize the dialog (eg. with settings from the registry)
* The subclass must implement this
*/
protected abstract void initialize();
/** Finalize the dialog after execution (eg. save settings to the registry)
* The subclass must implement this
*/
protected abstract void finalize();
//////////////////////////////////////////////////////////////////////////
// Some constants
// State of a checkbox
protected static final short CHECKBOX_NOT_CHECKED = 0;
protected static final short CHECKBOX_CHECKED = 1;
protected static final short CHECKBOX_DONT_KNOW = 2;
//////////////////////////////////////////////////////////////////////////
// Some private global variables
// The component context (from constructor)
protected XComponentContext xContext;
// The dialog (created by XExecutableDialog implementation)
private XDialog xDialog;
private String sTitle;
//////////////////////////////////////////////////////////////////////////
// The constructor
/** Create a new OptionsDialogBase */
public DialogBase(XComponentContext xContext) {
this.xContext = xContext;
xDialog = null;
sTitle = null;
}
//////////////////////////////////////////////////////////////////////////
// Implement uno interfaces
// Implement the interface XTypeProvider
public Type[] getTypes() {
Type[] typeReturn = {};
try {
typeReturn = new Type[] {
new Type( XServiceName.class ),
new Type( XServiceInfo.class ),
new Type( XTypeProvider.class ),
new Type( XExecutableDialog.class ),
new Type( XDialogEventHandler.class ) };
} catch(Exception exception) {
}
return typeReturn;
}
public byte[] getImplementationId() {
byte[] byteReturn = {};
byteReturn = new String( "" + this.hashCode() ).getBytes();
return( byteReturn );
}
// Implement the interface XServiceName
public String getServiceName() {
return __serviceName;
}
// Implement the interface XServiceInfo
public boolean supportsService(String sServiceName) {
return sServiceName.equals(__serviceName);
}
public String getImplementationName() {
return __implementationName;
}
public String[] getSupportedServiceNames() {
String[] sSupportedServiceNames = { __serviceName };
return sSupportedServiceNames;
}
// Implement the interface XExecutableDialog
public void setTitle(String sTitle) {
this.sTitle = sTitle;
}
public short execute() {
try {
// Create the dialog
XMultiComponentFactory xMCF = xContext.getServiceManager();
Object provider = xMCF.createInstanceWithContext(
"com.sun.star.awt.DialogProvider2", xContext);
XDialogProvider2 xDialogProvider = (XDialogProvider2)
UnoRuntime.queryInterface(XDialogProvider2.class, provider);
String sDialogUrl = "vnd.sun.star.script:"+getDialogLibraryName()+"."
+getDialogName()+"?location=application";
xDialog = xDialogProvider.createDialogWithHandler(sDialogUrl, this);
if (sTitle!=null) { xDialog.setTitle(sTitle); }
// Do initialization using method from subclass
initialize();
// Execute the dialog
short nResult = xDialog.execute();
if (nResult == ExecutableDialogResults.OK) {
// Finalize after execution of dialog using method from subclass
finalize();
}
xDialog.endExecute();
return nResult;
}
catch (Exception e) {
MessageBox msgBox = new MessageBox(xContext);
msgBox.showMessage("Error",e.toString()+" "+e.getStackTrace()[0].toString());
// continue as if the dialog was executed OK
return ExecutableDialogResults.OK;
}
}
// Implement the interface XDialogEventHandler
public boolean callHandlerMethod(XDialog xDialog, Object event, String sMethod) {
// Do nothing, leaving the responsibility to the subclass
return true;
}
public String[] getSupportedMethodNames() {
// We do not support any method names, subclass should take care of this
return new String[0];
}
//////////////////////////////////////////////////////////////////////////
// Helpers to access controls in the dialog (to be used by the subclass)
// Note: The helpers fail silently if an exception occurs. Could query the
// the ClassId property for the control type and check that the property
// exists to ensure a correct behaviour in all cases, but as long as the
// helpers are used correctly, this doesn't really matter.
// Get the properties of a named control in the dialog
private XPropertySet getControlProperties(String sControlName) {
XControlContainer xContainer = (XControlContainer)
UnoRuntime.queryInterface(XControlContainer.class, xDialog);
XControl xControl = xContainer.getControl(sControlName);
XControlModel xModel = xControl.getModel();
XPropertySet xPropertySet = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class, xModel);
return xPropertySet;
}
protected void setControlEnabled(String sControlName, boolean bEnabled) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
xPropertySet.setPropertyValue("Enabled", new Boolean(bEnabled));
}
catch (Exception e) {
// Will fail if the control does not exist
}
}
protected short getCheckBoxState(String sControlName) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
return ((Short) xPropertySet.getPropertyValue("State")).shortValue();
}
catch (Exception e) {
// Will fail if the control does not exist or is not a checkbox
return CHECKBOX_DONT_KNOW;
}
}
protected boolean getCheckBoxStateAsBoolean(String sControlName) {
return getCheckBoxState(sControlName)==CHECKBOX_CHECKED;
}
protected void setCheckBoxState(String sControlName, short nState) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
xPropertySet.setPropertyValue("State",new Short(nState));
}
catch (Exception e) {
// will fail if the control does not exist or is not a checkbox or
// nState has an illegal value
}
}
protected void setCheckBoxStateAsBoolean(String sControlName, boolean bChecked) {
setCheckBoxState(sControlName,bChecked ? CHECKBOX_CHECKED : CHECKBOX_NOT_CHECKED);
}
protected String[] getListBoxStringItemList(String sControlName) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
return (String[]) xPropertySet.getPropertyValue("StringItemList");
}
catch (Exception e) {
// Will fail if the control does not exist or is not a list box
return new String[0];
}
}
protected void setListBoxStringItemList(String sControlName, String[] items) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
xPropertySet.setPropertyValue("StringItemList",items);
}
catch (Exception e) {
// Will fail if the control does not exist or is not a list box
}
}
protected short getListBoxSelectedItem(String sControlName) {
// Returns the first selected element in case of a multiselection
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
short[] selection = (short[]) xPropertySet.getPropertyValue("SelectedItems");
return selection[0];
}
catch (Exception e) {
// Will fail if the control does not exist or is not a list box
return -1;
}
}
protected void setListBoxSelectedItem(String sControlName, short nIndex) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
short[] selection = new short[1];
selection[0] = nIndex;
xPropertySet.setPropertyValue("SelectedItems",selection);
}
catch (Exception e) {
// Will fail if the control does not exist or is not a list box or
// nIndex is an illegal value
}
}
protected short getListBoxLineCount(String sControlName) {
// Returns the first selected element in case of a multiselection
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
return ((Short) xPropertySet.getPropertyValue("LineCount")).shortValue();
}
catch (Exception e) {
// Will fail if the control does not exist or is not a list box
return 0;
}
}
protected void setListBoxLineCount(String sControlName, short nLineCount) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
xPropertySet.setPropertyValue("LineCount",new Short(nLineCount));
}
catch (Exception e) {
// Will fail if the control does not exist or is not a list box or
// nLineCount is an illegal value
}
}
protected String getComboBoxText(String sControlName) {
// Returns the text of a combobox
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
return (String) xPropertySet.getPropertyValue("Text");
}
catch (Exception e) {
// Will fail if the control does not exist or is not a combo
return "";
}
}
protected void setComboBoxText(String sControlName, String sText) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
xPropertySet.setPropertyValue("Text", sText);
}
catch (Exception e) {
// Will fail if the control does not exist or is not a combo box or
// nText is an illegal value
}
}
protected String getTextFieldText(String sControlName) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
return (String) xPropertySet.getPropertyValue("Text");
}
catch (Exception e) {
// Will fail if the control does not exist or is not a text field
return "";
}
}
protected void setTextFieldText(String sControlName, String sText) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
xPropertySet.setPropertyValue("Text",sText);
}
catch (Exception e) {
// Will fail if the control does not exist or is not a text field
}
}
protected String getFormattedFieldText(String sControlName) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
return (String) xPropertySet.getPropertyValue("Text");
}
catch (Exception e) {
// Will fail if the control does not exist or is not a formatted field
return "";
}
}
protected void setFormattedFieldText(String sControlName, String sText) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
xPropertySet.setPropertyValue("Text",sText);
}
catch (Exception e) {
// Will fail if the control does not exist or is not a formatted field
}
}
protected int getNumericFieldValue(String sControlName) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
return ((Double) xPropertySet.getPropertyValue("Value")).intValue();
}
catch (Exception e) {
// Will fail if the control does not exist or is not a numeric field
return 0;
}
}
protected void setNumericFieldValue(String sControlName, int nValue) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
xPropertySet.setPropertyValue("Value",new Double(nValue));
}
catch (Exception e) {
// Will fail if the control does not exist or is not a numeric field
}
}
// Helpers for access to an XPropertySet. The helpers will fail silently if
// names or data is provided, but the subclass is expected to use them with
// correct data only...
protected Object getPropertyValue(XPropertySet xProps, String sName) {
try {
return xProps.getPropertyValue(sName);
}
catch (UnknownPropertyException e) {
return null;
}
catch (WrappedTargetException e) {
return null;
}
}
protected void setPropertyValue(XPropertySet xProps, String sName, Object value) {
try {
xProps.setPropertyValue(sName,value);
}
catch (UnknownPropertyException e) {
}
catch (PropertyVetoException e) { // unacceptable value
}
catch (IllegalArgumentException e) {
}
catch (WrappedTargetException e) {
}
}
protected String getPropertyValueAsString(XPropertySet xProps, String sName) {
Object value = getPropertyValue(xProps,sName);
return value instanceof String ? (String) value : "";
}
protected int getPropertyValueAsInteger(XPropertySet xProps, String sName) {
Object value = getPropertyValue(xProps,sName);
return value instanceof Integer ? ((Integer) value).intValue() : 0;
}
protected void setPropertyValue(XPropertySet xProps, String sName, int nValue) {
setPropertyValue(xProps,sName,new Integer(nValue));
}
protected short getPropertyValueAsShort(XPropertySet xProps, String sName) {
Object value = getPropertyValue(xProps,sName);
return value instanceof Short ? ((Short) value).shortValue() : 0;
}
protected void setPropertyValue(XPropertySet xProps, String sName, short nValue) {
setPropertyValue(xProps,sName,new Short(nValue));
}
protected boolean getPropertyValueAsBoolean(XPropertySet xProps, String sName) {
Object value = getPropertyValue(xProps,sName);
return value instanceof Boolean ? ((Boolean) value).booleanValue() : false;
}
protected void setPropertyValue(XPropertySet xProps, String sName, boolean bValue) {
setPropertyValue(xProps,sName,new Boolean(bValue));
}
}

View file

@ -0,0 +1,105 @@
/************************************************************************
*
* MessageBox.java
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Copyright: 2002-2008 by Henrik Just
*
* All Rights Reserved.
*
* Version 1.0 (2008-07-21)
*
*/
package org.openoffice.da.comp.w2lcommon.helper;
import com.sun.star.awt.Rectangle;
import com.sun.star.awt.WindowAttribute;
import com.sun.star.awt.WindowClass;
import com.sun.star.awt.WindowDescriptor;
import com.sun.star.awt.XMessageBox;
import com.sun.star.awt.XToolkit;
import com.sun.star.awt.XWindowPeer;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XFrame;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
/** This class provides simple access to a uno awt message box
*/
public class MessageBox {
private XFrame xFrame;
private XToolkit xToolkit;
/** Create a new MessageBox belonging to the current frame
*/
public MessageBox(XComponentContext xContext) {
this(xContext,null);
}
/** Create a new MessageBox belonging to a specific frame
*/
public MessageBox(XComponentContext xContext, XFrame xFrame) {
try {
Object toolkit = xContext.getServiceManager()
.createInstanceWithContext("com.sun.star.awt.Toolkit",xContext);
xToolkit = (XToolkit) UnoRuntime.queryInterface(XToolkit.class,toolkit);
if (xFrame==null) {
Object desktop = xContext.getServiceManager()
.createInstanceWithContext("com.sun.star.frame.Desktop",xContext);
XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class,desktop);
xFrame = xDesktop.getCurrentFrame();
}
this.xFrame = xFrame;
}
catch (Exception e) {
// Failed to get toolkit or frame
xToolkit = null;
xFrame = null;
}
}
public void showMessage(String sTitle, String sMessage) {
if (xToolkit==null || xFrame==null) { return; }
try {
WindowDescriptor descriptor = new WindowDescriptor();
descriptor.Type = WindowClass.MODALTOP;
descriptor.WindowServiceName = "infobox";
descriptor.ParentIndex = -1;
descriptor.Parent = (XWindowPeer) UnoRuntime.queryInterface(
XWindowPeer.class,xFrame.getContainerWindow());
descriptor.Bounds = new Rectangle(0,0,300,200);
descriptor.WindowAttributes = WindowAttribute.BORDER |
WindowAttribute.MOVEABLE | WindowAttribute.CLOSEABLE;
XWindowPeer xPeer = xToolkit.createWindow(descriptor);
if (xPeer!=null) {
XMessageBox xMessageBox = (XMessageBox)
UnoRuntime.queryInterface(XMessageBox.class,xPeer);
if (xMessageBox!=null) {
xMessageBox.setCaptionText(sTitle);
xMessageBox.setMessageText(sMessage);
xMessageBox.execute();
}
}
}
catch (Exception e) {
// ignore, give up...
}
}
}

View file

@ -0,0 +1,78 @@
/************************************************************************
*
* PropertyHelper.java
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Copyright: 2002-2008 by Henrik Just
*
* All Rights Reserved.
*
* Version 1.0 (2008-07-21)
*
*/
package org.openoffice.da.comp.w2lcommon.helper;
import java.util.Enumeration;
import java.util.Hashtable;
import com.sun.star.beans.PropertyValue;
/** This class provides access by name to a <code>PropertyValue</code> array
*/
public class PropertyHelper {
private Hashtable data;
public PropertyHelper() {
data = new Hashtable();
}
public PropertyHelper(PropertyValue[] props) {
data = new Hashtable();
int nLen = props.length;
for (int i=0; i<nLen; i++) {
data.put(props[i].Name,props[i].Value);
}
}
public void put(String sName, Object value) {
data.put(sName,value);
}
public Object get(String sName) {
return data.get(sName);
}
public Enumeration keys() {
return data.keys();
}
public PropertyValue[] toArray() {
int nSize = data.size();
PropertyValue[] props = new PropertyValue[nSize];
int i=0;
Enumeration keys = keys();
while (keys.hasMoreElements()) {
String sKey = (String) keys.nextElement();
props[i] = new PropertyValue();
props[i].Name = sKey;
props[i++].Value = get(sKey);
}
return props;
}
}