Removed unused classes

This commit is contained in:
Georgy Litvinov 2021-03-13 15:53:04 +01:00
parent 6ad91477cc
commit 29d275e26d
38 changed files with 0 additions and 7793 deletions

View file

@ -1,187 +0,0 @@
/************************************************************************
*
* ByteArrayXStream.java
*
* Copyright: 2002-2008 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* 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

@ -1,870 +0,0 @@
/************************************************************************
*
* ConfigurationDialogBase.java
*
* Copyright: 2002-2015 by Henrik Just
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-04-09)
*
*/
package org.openoffice.da.comp.w2lcommon.filter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.sun.star.awt.XContainerWindowEventHandler;
import com.sun.star.awt.XDialog;
import com.sun.star.awt.XDialogProvider2;
import com.sun.star.awt.XWindow;
import com.sun.star.container.NoSuchElementException;
import com.sun.star.io.NotConnectedException;
import com.sun.star.io.XInputStream;
import com.sun.star.io.XOutputStream;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.ucb.CommandAbortedException;
import com.sun.star.ucb.XSimpleFileAccess2;
import com.sun.star.ui.dialogs.ExecutableDialogResults;
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 w2phtml.api.ComplexOption;
import w2phtml.api.Config;
import w2phtml.api.ConverterFactory;
import w2phtml.util.Misc;
import com.sun.star.lib.uno.helper.WeakBase;
import com.sun.star.lib.uno.adapter.XInputStreamToInputStreamAdapter;
import com.sun.star.lib.uno.adapter.XOutputStreamToOutputStreamAdapter;
import org.openoffice.da.comp.w2lcommon.helper.DialogAccess;
import org.openoffice.da.comp.w2lcommon.helper.FilePicker;
import org.openoffice.da.comp.w2lcommon.helper.StyleNameProvider;
/** This is a base implementation of a uno component which supports several option pages
* with a single <code>XContainerWindowEventHandler</code>. The title of the dialogs
* are used to differentiate between the individual pages
*/
public abstract class ConfigurationDialogBase extends WeakBase implements XContainerWindowEventHandler {
// The full path to the configuration file we handle
private String sConfigFileName = null;
// The component context
protected XComponentContext xContext;
// File picker wrapper
protected FilePicker filePicker = null;
// UNO simple file access service
protected XSimpleFileAccess2 sfa2 = null;
// UNO path substitution
protected XStringSubstitution xPathSub = null;
// The configuration implementation
protected Config config;
// The individual page handlers (the subclass must populate this)
protected Map<String,PageHandler> pageHandlers = new HashMap<String,PageHandler>();
// The subclass must provide these:
// MIME type of the document type we configure
protected abstract String getMIMEType();
// The dialog library containing the "new" and "delete" dialogs
protected abstract String getDialogLibraryName();
// The file name used for persistent storage of the edited configuration
protected abstract String getConfigFileName();
/** Create a new <code>ConfigurationDialogBase</code> */
public ConfigurationDialogBase(XComponentContext xContext) {
this.xContext = xContext;
// Get the file picker
filePicker = new FilePicker(xContext);
// Get the SimpleFileAccess service
try {
Object sfaObject = xContext.getServiceManager().createInstanceWithContext(
"com.sun.star.ucb.SimpleFileAccess", xContext);
sfa2 = (XSimpleFileAccess2) UnoRuntime.queryInterface(XSimpleFileAccess2.class, sfaObject);
}
catch (com.sun.star.uno.Exception e) {
// failed to get SimpleFileAccess service (should not happen)
}
// Create the config file name
try {
Object psObject = xContext.getServiceManager().createInstanceWithContext(
"com.sun.star.util.PathSubstitution", xContext);
xPathSub = (XStringSubstitution) UnoRuntime.queryInterface(XStringSubstitution.class, psObject);
sConfigFileName = xPathSub.substituteVariables("$(user)/"+getConfigFileName(), false);
}
catch (com.sun.star.uno.Exception e) {
// failed to get PathSubstitution service (should not happen)
}
// Create the configuration
config = ConverterFactory.createConverter(getMIMEType()).getConfig();
}
// Implement XContainerWindowEventHandler
public boolean callHandlerMethod(XWindow xWindow, Object event, String sMethod)
throws com.sun.star.lang.WrappedTargetException {
XDialog xDialog = (XDialog)UnoRuntime.queryInterface(XDialog.class, xWindow);
String sTitle = xDialog.getTitle();
if (!pageHandlers.containsKey(sTitle)) {
throw new com.sun.star.lang.WrappedTargetException("Unknown dialog "+sTitle);
}
DialogAccess dlg = new DialogAccess(xDialog);
try {
if (sMethod.equals("external_event") ) {
return handleExternalEvent(dlg, sTitle, event);
}
}
catch (com.sun.star.uno.RuntimeException e) {
throw e;
}
catch (com.sun.star.uno.Exception e) {
throw new com.sun.star.lang.WrappedTargetException(sMethod, this, e);
}
return pageHandlers.get(sTitle).handleEvent(dlg, sMethod);
}
private boolean handleExternalEvent(DialogAccess dlg, String sTitle, Object aEventObject) throws com.sun.star.uno.Exception {
try {
String sMethod = AnyConverter.toString(aEventObject);
if (sMethod.equals("ok")) {
loadConfig(); // The file may have been changed by other pages, thus we reload
pageHandlers.get(sTitle).getControls(dlg);
saveConfig();
return true;
}
else if (sMethod.equals("back") || sMethod.equals("initialize")) {
loadConfig();
pageHandlers.get(sTitle).setControls(dlg);
return true;
}
}
catch (com.sun.star.lang.IllegalArgumentException e) {
throw new com.sun.star.lang.IllegalArgumentException(
"Method external_event requires a string in the event object argument.", this,(short) -1);
}
return false;
}
// Load the user configuration from file
private void loadConfig() {
if (sfa2!=null && sConfigFileName!=null) {
try {
XInputStream xIs = sfa2.openFileRead(sConfigFileName);
if (xIs!=null) {
InputStream is = new XInputStreamToInputStreamAdapter(xIs);
config.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
}
}
}
// Save the user configuration
private void saveConfig() {
if (sfa2!=null && sConfigFileName!=null) {
try {
//Remove the file if it exists
if (sfa2.exists(sConfigFileName)) {
sfa2.kill(sConfigFileName);
}
// Then write the new contents
XOutputStream xOs = sfa2.openFileWrite(sConfigFileName);
if (xOs!=null) {
OutputStream os = new XOutputStreamToOutputStreamAdapter(xOs);
config.write(os);
os.close();
xOs.closeOutput();
}
}
catch (IOException e) {
// ignore
}
catch (NotConnectedException e) {
// ignore
}
catch (CommandAbortedException e) {
// ignore
}
catch (com.sun.star.uno.Exception e) {
// ignore
}
}
}
// Inner class to handle the individual option pages
protected abstract class PageHandler {
protected abstract void getControls(DialogAccess dlg);
protected abstract void setControls(DialogAccess dlg);
protected abstract boolean handleEvent(DialogAccess dlg, String sMethodName);
// Methods to set and get controls based on config
protected void checkBoxFromConfig(DialogAccess dlg, String sCheckBoxName, String sConfigName) {
dlg.setCheckBoxStateAsBoolean(sCheckBoxName, "true".equals(config.getOption(sConfigName)));
}
protected void checkBoxToConfig(DialogAccess dlg, String sCheckBoxName, String sConfigName) {
config.setOption(sConfigName, Boolean.toString(dlg.getCheckBoxStateAsBoolean(sCheckBoxName)));
}
protected void textFieldFromConfig(DialogAccess dlg, String sTextBoxName, String sConfigName) {
dlg.setTextFieldText(sTextBoxName, config.getOption(sConfigName));
}
protected void textFieldToConfig(DialogAccess dlg, String sTextBoxName, String sConfigName) {
config.setOption(sConfigName, dlg.getTextFieldText(sTextBoxName));
}
protected void listBoxFromConfig(DialogAccess dlg, String sListBoxName, String sConfigName, String[] sConfigValues, short nDefault) {
String sCurrentValue = config.getOption(sConfigName);
int nCount = sConfigValues.length;
for (short i=0; i<nCount; i++) {
if (sConfigValues[i].equals(sCurrentValue)) {
dlg.setListBoxSelectedItem(sListBoxName, i);
return;
}
}
dlg.setListBoxSelectedItem(sListBoxName, nDefault);
}
protected void listBoxToConfig(DialogAccess dlg, String sListBoxName, String sConfigName, String[] sConfigValues) {
config.setOption(sConfigName, sConfigValues[dlg.getListBoxSelectedItem(sListBoxName)]);
}
// Method to get a named dialog
protected XDialog getDialog(String sDialogName) {
XMultiComponentFactory xMCF = xContext.getServiceManager();
try {
Object provider = xMCF.createInstanceWithContext(
"com.sun.star.awt.DialogProvider2", xContext);
XDialogProvider2 xDialogProvider = (XDialogProvider2)
UnoRuntime.queryInterface(XDialogProvider2.class, provider);
String sDialogUrl = "vnd.sun.star.script:"+sDialogName+"?location=application";
return xDialogProvider.createDialog(sDialogUrl);
}
catch (Exception e) {
return null;
}
}
// Method to display delete dialog
protected boolean deleteItem(String sName) {
XDialog xDialog=getDialog(getDialogLibraryName()+".DeleteDialog");
if (xDialog!=null) {
DialogAccess ddlg = new DialogAccess(xDialog);
String sLabel = ddlg.getLabelText("DeleteLabel");
sLabel = sLabel.replaceAll("%s", sName);
ddlg.setLabelText("DeleteLabel", sLabel);
boolean bDelete = xDialog.execute()==ExecutableDialogResults.OK;
xDialog.endExecute();
return bDelete;
}
return false;
}
}
protected abstract class CustomFileHandler extends PageHandler {
// The file name
private String sCustomFileName;
public CustomFileHandler() {
super();
try {
sCustomFileName = xPathSub.substituteVariables("$(user)/"+getFileName(), false);
}
catch (NoSuchElementException e) {
sCustomFileName = getFileName();
}
}
// The subclass must provide these
protected abstract String getSuffix();
protected abstract String getFileName();
protected abstract void useCustomInner(DialogAccess dlg, boolean bUseCustom);
@Override protected void setControls(DialogAccess dlg) {
String sText = "";
boolean bUseCustom = false;
if (fileExists(sCustomFileName)) {
sText = loadFile(sCustomFileName);
bUseCustom = true;
}
else if (fileExists(sCustomFileName+".bak")) {
sText = loadFile(sCustomFileName+".bak");
}
// Currently ignore failure to load the file
if (sText==null) { sText=""; }
dlg.setCheckBoxStateAsBoolean("UseCustom"+getSuffix(), bUseCustom);
dlg.setTextFieldText("Custom"+getSuffix(), sText);
useCustomChange(dlg);
}
@Override protected void getControls(DialogAccess dlg) {
if (dlg.getCheckBoxStateAsBoolean("UseCustom"+getSuffix())) {
saveFile(sCustomFileName,dlg.getTextFieldText("Custom"+getSuffix()));
killFile(sCustomFileName+".bak");
}
else {
saveFile(sCustomFileName+".bak",dlg.getTextFieldText("Custom"+getSuffix()));
killFile(sCustomFileName);
}
}
@Override protected boolean handleEvent(DialogAccess dlg, String sMethod) {
if (sMethod.equals("UseCustom"+getSuffix()+"Change")) {
useCustomChange(dlg);
return true;
}
else if (sMethod.equals("Load"+getSuffix()+"Click")) {
loadCustomClick(dlg);
return true;
}
return false;
}
private void useCustomChange(DialogAccess dlg) {
boolean bUseCustom = dlg.getCheckBoxStateAsBoolean("UseCustom"+getSuffix());
dlg.setControlEnabled("Custom"+getSuffix(), bUseCustom);
dlg.setControlEnabled("Load"+getSuffix()+"Button", bUseCustom);
useCustomInner(dlg,bUseCustom);
}
protected void loadCustomClick(DialogAccess dlg) {
String sFileName=filePicker.getPath();
if (sFileName!=null) {
String sText = loadFile(sFileName);
if (sText!=null) {
dlg.setTextFieldText("Custom"+getSuffix(), sText);
}
}
}
// Helpers for sfa2
// Checks that the file exists
protected boolean fileExists(String sFileName) {
try {
return sfa2!=null && sfa2.exists(sFileName);
}
catch (CommandAbortedException e) {
}
catch (com.sun.star.uno.Exception e) {
}
return false;
}
// Delete a file if it exists, return true on success
protected boolean killFile(String sFileName) {
try {
if (sfa2!=null && sfa2.exists(sFileName)) {
sfa2.kill(sFileName);
return true;
}
}
catch (com.sun.star.uno.Exception e) {
}
return false;
}
// Load a text file, returns null on failure
private String loadFile(String sFileName) {
if (sfa2!=null) {
try {
XInputStream xIs = sfa2.openFileRead(sFileName);
if (xIs!=null) {
InputStream is = new XInputStreamToInputStreamAdapter(xIs);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder buf = new StringBuilder();
String sLine;
try {
while ((sLine = reader.readLine())!=null) {
buf.append(sLine).append('\n');
}
reader.close();
is.close();
}
catch (IOException e) {
}
xIs.closeInput();
return buf.toString();
}
}
catch (com.sun.star.uno.Exception e) {
}
}
return null;
}
// Save a text file, return true on success
protected boolean saveFile(String sFileName, String sText) {
killFile(sFileName);
try {
XOutputStream xOs = sfa2.openFileWrite(sFileName);
if (xOs!=null) {
OutputStream os = new XOutputStreamToOutputStreamAdapter(xOs);
try {
OutputStreamWriter osw = new OutputStreamWriter(os,"UTF-8");
osw.write(sText);
osw.flush();
os.close();
}
catch (IOException e) {
xOs.closeOutput();
return false;
}
xOs.closeOutput();
return true;
}
}
catch (com.sun.star.uno.Exception e) {
}
return false;
}
}
protected abstract class UserListPageHandler extends PageHandler {
// Methods to handle user controlled lists
protected boolean deleteCurrentItem(DialogAccess dlg, String sListName) {
String[] sItems = dlg.getListBoxStringItemList(sListName);
short nSelected = dlg.getListBoxSelectedItem(sListName);
if (nSelected>=0 && deleteItem(sItems[nSelected])) {
int nOldLen = sItems.length;
String[] sNewItems = new String[nOldLen-1];
if (nSelected>0) {
System.arraycopy(sItems, 0, sNewItems, 0, nSelected);
}
if (nSelected<nOldLen-1) {
System.arraycopy(sItems, nSelected+1, sNewItems, nSelected, nOldLen-1-nSelected);
}
dlg.setListBoxStringItemList(sListName, sNewItems);
short nNewSelected = nSelected<nOldLen-1 ? nSelected : (short)(nSelected-1);
dlg.setListBoxSelectedItem(sListName, nNewSelected);
return true;
}
return false;
}
private String newItem(Set<String> suggestions) {
XDialog xDialog=getDialog(getDialogLibraryName()+".NewDialog");
if (xDialog!=null) {
String[] sItems = Misc.sortStringSet(suggestions);
DialogAccess ndlg = new DialogAccess(xDialog);
ndlg.setListBoxStringItemList("Name", sItems);
String sResult = null;
if (xDialog.execute()==ExecutableDialogResults.OK) {
DialogAccess dlg = new DialogAccess(xDialog);
sResult = dlg.getTextFieldText("Name");
}
xDialog.endExecute();
return sResult;
}
return null;
}
protected String appendItem(DialogAccess dlg, String sListName, Set<String> suggestions) {
String[] sItems = dlg.getListBoxStringItemList(sListName);
String sNewItem = newItem(suggestions);
if (sNewItem!=null) {
int nOldLen = sItems.length;
for (short i=0; i<nOldLen; i++) {
if (sNewItem.equals(sItems[i])) {
// Item already exists, select the existing one
dlg.setListBoxSelectedItem(sListName, i);
return null;
}
}
String[] sNewItems = new String[nOldLen+1];
System.arraycopy(sItems, 0, sNewItems, 0, nOldLen);
sNewItems[nOldLen]=sNewItem;
dlg.setListBoxStringItemList(sListName, sNewItems);
dlg.setListBoxSelectedItem(sListName, (short)nOldLen);
}
return sNewItem;
}
}
protected abstract class StylesPageHandler extends UserListPageHandler {
// The subclass must define these
protected String[] sFamilyNames;
protected String[] sOOoFamilyNames;
// Our data
private ComplexOption[] styleMap;
protected short nCurrentFamily = -1;
private String sCurrentStyleName = null;
// Access to display names of the styles in the current document
protected StyleNameProvider styleNameProvider = null;
// Some methods to be implemented by the subclass
protected abstract String getDefaultConfigName();
protected abstract void getControls(DialogAccess dlg, Map<String,String> attr);
protected abstract void setControls(DialogAccess dlg, Map<String,String> attr);
protected abstract void clearControls(DialogAccess dlg);
protected abstract void prepareControls(DialogAccess dlg, boolean bHasDefinitions);
// Constructor
protected StylesPageHandler(int nCount) {
// Get the style name provider
styleNameProvider = new StyleNameProvider(xContext);
// Reset the options
styleMap = new ComplexOption[nCount];
for (int i=0; i<nCount; i++) {
styleMap[i] = new ComplexOption();
}
}
// Implement abstract methods from super
protected void setControls(DialogAccess dlg) {
// Load style maps from config (translating keys to display names)
int nCount = sFamilyNames.length;
for (int i=0; i<nCount; i++) {
ComplexOption configMap = config.getComplexOption(sFamilyNames[i]+"-map");
styleMap[i].clear();
Map<String,String> displayNames = styleNameProvider.getDisplayNames(sOOoFamilyNames[i]);
copyStyles(configMap, styleMap[i], displayNames);
}
// Display paragraph maps first
nCurrentFamily = -1;
sCurrentStyleName = null;
dlg.setListBoxSelectedItem("StyleFamily", (short)1);
styleFamilyChange(dlg);
}
protected void getControls(DialogAccess dlg) {
updateStyleMaps(dlg);
// Save style maps to config (translating keys back to internal names)
int nCount = sFamilyNames.length;
for (int i=0; i<nCount; i++) {
ComplexOption configMap = config.getComplexOption(sFamilyNames[i]+"-map");
configMap.clear();
Map<String,String> internalNames = styleNameProvider.getInternalNames(sOOoFamilyNames[i]);
copyStyles(styleMap[i], configMap, internalNames);
}
}
protected boolean handleEvent(DialogAccess dlg, String sMethod) {
if (sMethod.equals("StyleFamilyChange")) {
styleFamilyChange(dlg);
return true;
}
else if (sMethod.equals("StyleNameChange")) {
styleNameChange(dlg);
return true;
}
else if (sMethod.equals("NewStyleClick")) {
newStyleClick(dlg);
return true;
}
else if (sMethod.equals("DeleteStyleClick")) {
deleteStyleClick(dlg);
return true;
}
else if (sMethod.equals("LoadDefaultsClick")) {
loadDefaultsClick(dlg);
return true;
}
return false;
}
// Internal methods
private void updateStyleMaps(DialogAccess dlg) {
// Save the current style map, if any
if (nCurrentFamily>-1 && sCurrentStyleName!=null) {
getControls(dlg,styleMap[nCurrentFamily].get(sCurrentStyleName));
}
}
private void styleFamilyChange(DialogAccess dlg) {
short nNewFamily = dlg.getListBoxSelectedItem("StyleFamily");
if (nNewFamily>-1 && nNewFamily!=nCurrentFamily) {
// The user has changed the family; load and display the corresponding style names
updateStyleMaps(dlg);
nCurrentFamily = nNewFamily;
sCurrentStyleName = null;
String[] sStyleNames = Misc.sortStringSet(styleMap[nNewFamily].keySet());
dlg.setListBoxStringItemList("StyleName", sStyleNames);
if (sStyleNames.length>0) {
dlg.setListBoxSelectedItem("StyleName", (short)0);
}
else {
dlg.setListBoxSelectedItem("StyleName", (short)-1);
}
updateStyleControls(dlg);
styleNameChange(dlg);
}
}
private void styleNameChange(DialogAccess dlg) {
if (nCurrentFamily>-1) {
updateStyleMaps(dlg);
short nStyleNameItem = dlg.getListBoxSelectedItem("StyleName");
if (nStyleNameItem>=0) {
sCurrentStyleName = dlg.getListBoxStringItemList("StyleName")[nStyleNameItem];
setControls(dlg,styleMap[nCurrentFamily].get(sCurrentStyleName));
}
else {
sCurrentStyleName = null;
clearControls(dlg);
}
}
}
private void newStyleClick(DialogAccess dlg) {
if (nCurrentFamily>-1) {
updateStyleMaps(dlg);
// Invalidate current style name in any case (appendItem returns null if the user
// selects an existing style, but it still changes the current item)
sCurrentStyleName = null;
String sNewName = appendItem(dlg, "StyleName",styleNameProvider.getInternalNames(sOOoFamilyNames[nCurrentFamily]).keySet());
if (sNewName!=null) {
styleMap[nCurrentFamily].put(sNewName, new HashMap<String,String>());
clearControls(dlg);
}
styleNameChange(dlg);
updateStyleControls(dlg);
}
}
private void deleteStyleClick(DialogAccess dlg) {
if (nCurrentFamily>-1 && sCurrentStyleName!=null) {
String sStyleName = sCurrentStyleName;
if (deleteCurrentItem(dlg,"StyleName")) {
styleMap[nCurrentFamily].remove(sStyleName);
sCurrentStyleName=null;
styleNameChange(dlg);
}
updateStyleControls(dlg);
}
}
private void loadDefaultsClick(DialogAccess dlg) {
updateStyleMaps(dlg);
// Count styles that we will overwrite
Config clean = ConverterFactory.createConverter(getMIMEType()).getConfig();
clean.readDefaultConfig(getDefaultConfigName());
int nCount = 0;
int nFamilyCount = sFamilyNames.length;
for (int i=0; i<nFamilyCount; i++) {
ComplexOption cleanMap = clean.getComplexOption(sFamilyNames[i]+"-map");
Map<String,String> displayNames = styleNameProvider.getDisplayNames(sOOoFamilyNames[i]);
for (String sName : cleanMap.keySet()) {
String sDisplayName = (displayNames!=null && displayNames.containsKey(sName)) ? displayNames.get(sName) : "";
if (styleMap[i].containsKey(sDisplayName)) { nCount++; }
}
}
// Display confirmation dialog
boolean bConfirm = false;
XDialog xDialog=getDialog(getDialogLibraryName()+".LoadDefaults");
if (xDialog!=null) {
DialogAccess ldlg = new DialogAccess(xDialog);
if (nCount>0) {
String sLabel = ldlg.getLabelText("OverwriteLabel");
sLabel = sLabel.replaceAll("%s", Integer.toString(nCount));
ldlg.setLabelText("OverwriteLabel", sLabel);
}
else {
ldlg.setLabelText("OverwriteLabel", "");
}
bConfirm = xDialog.execute()==ExecutableDialogResults.OK;
xDialog.endExecute();
}
// Do the replacement
if (bConfirm) {
for (int i=0; i<nFamilyCount; i++) {
ComplexOption cleanMap = clean.getComplexOption(sFamilyNames[i]+"-map");
Map<String,String> displayNames = styleNameProvider.getDisplayNames(sOOoFamilyNames[i]);
copyStyles(cleanMap, styleMap[i], displayNames);
}
}
// Force update of the user interface
nCurrentFamily = -1;
sCurrentStyleName = null;
styleFamilyChange(dlg);
}
private void updateStyleControls(DialogAccess dlg) {
boolean bHasMappings = dlg.getListBoxStringItemList("StyleName").length>0;
dlg.setControlEnabled("DeleteStyleButton", bHasMappings);
prepareControls(dlg,bHasMappings);
}
private void copyStyles(ComplexOption source, ComplexOption target, Map<String,String> nameTranslation) {
for (String sName : source.keySet()) {
String sNewName = sName;
if (nameTranslation!=null && nameTranslation.containsKey(sName)) {
sNewName = nameTranslation.get(sName);
}
target.copy(sNewName, source.get(sName));
}
}
}
protected abstract class AttributePageHandler extends PageHandler {
// The subclass must define this
protected String[] sAttributeNames;
// Our data
private ComplexOption attributeMap = new ComplexOption();
private int nCurrentAttribute = -1;
// Some methods to be implemented by subclass
protected abstract void getControls(DialogAccess dlg, Map<String,String> attr);
protected abstract void setControls(DialogAccess dlg, Map<String,String> attr);
protected abstract void prepareControls(DialogAccess dlg, boolean bEnable);
// Implement abstract methods from our super
protected void setControls(DialogAccess dlg) {
// Load attribute maps from config
attributeMap.clear();
attributeMap.copyAll(config.getComplexOption("text-attribute-map"));
// Update the dialog
nCurrentAttribute = -1;
dlg.setListBoxSelectedItem("FormattingAttribute", (short)0);
formattingAttributeChange(dlg);
}
protected void getControls(DialogAccess dlg) {
updateAttributeMaps(dlg);
// Save attribute maps to config
ComplexOption configMap = config.getComplexOption("text-attribute-map");
configMap.clear();
for (String s: attributeMap.keySet()) {
Map<String,String> attr = attributeMap.get(s);
if (!attr.containsKey("deleted") || attr.get("deleted").equals("false")) {
configMap.copy(s, attr);
}
}
}
protected boolean handleEvent(DialogAccess dlg, String sMethod) {
if (sMethod.equals("FormattingAttributeChange")) {
formattingAttributeChange(dlg);
return true;
}
else if (sMethod.equals("CustomAttributeChange")) {
customAttributeChange(dlg);
return true;
}
return false;
}
// Internal methods
private void updateAttributeMaps(DialogAccess dlg) {
// Save the current attribute map, if any
if (nCurrentAttribute>-1) {
String sName = sAttributeNames[nCurrentAttribute];
if (!attributeMap.containsKey(sName)) {
attributeMap.put(sName, new HashMap<String,String>());
}
Map<String,String> attr = attributeMap.get(sName);
attr.put("deleted", Boolean.toString(!dlg.getCheckBoxStateAsBoolean("CustomAttribute")));
getControls(dlg,attr);
attributeMap.put(sName, attr);
}
}
private void formattingAttributeChange(DialogAccess dlg) {
updateAttributeMaps(dlg);
short nNewAttribute = dlg.getListBoxSelectedItem("FormattingAttribute");
if (nNewAttribute>-1 && nNewAttribute!=nCurrentAttribute) {
nCurrentAttribute = nNewAttribute;
String sName = sAttributeNames[nCurrentAttribute];
if (!attributeMap.containsKey(sName)) {
attributeMap.put(sName, new HashMap<String,String>());
attributeMap.get(sName).put("deleted", "true");
}
Map<String,String> attr = attributeMap.get(sName);
dlg.setCheckBoxStateAsBoolean("CustomAttribute", !attr.containsKey("deleted") || attr.get("deleted").equals("false"));
customAttributeChange(dlg);
setControls(dlg,attr);
}
}
private void customAttributeChange(DialogAccess dlg) {
prepareControls(dlg,dlg.getCheckBoxStateAsBoolean("CustomAttribute"));
}
}
}

View file

@ -1,86 +0,0 @@
/************************************************************************
*
* EPSCleaner.java
*
* Copyright: 2002-2009 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.0 (2009-03-09)
*/
package org.openoffice.da.comp.w2lcommon.filter;
/** This class removes redundant binary information from EPS files created by OOo.
* See the issue http://qa.openoffice.org/issues/show_bug.cgi?id=25256
* According to this message http://markmail.org/message/dc6rprmtktxuq35v
* on dev@openoffice.org the binary data is an EPSI preview in TIFF format
* TODO: Is it possible to avoid this export?
*/
public class EPSCleaner {
// Signatures for start and end in eps
private byte[] psStart;
private byte[] psEnd;
public EPSCleaner() {
try {
psStart = "%!PS-Adobe".getBytes("US-ASCII");
psEnd = "%%EOF".getBytes("US-ASCII");
}
catch (java.io.UnsupportedEncodingException ex) {
// US-ASCII *is* supported :-)
}
}
//
public 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

@ -1,187 +0,0 @@
/************************************************************************
*
* ExportFilterBase.java
*
* Copyright: 2002-2014 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2014-10-06)
*
*/
package org.openoffice.da.comp.w2lcommon.filter;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.lang.XServiceName;
import com.sun.star.lang.XTypeProvider;
import com.sun.star.uno.Type;
import com.sun.star.uno.XComponentContext;
import com.sun.star.xml.sax.XDocumentHandler;
import w2phtml.util.SimpleDOMBuilder;
import com.sun.star.xml.XExportFilter;
import org.openoffice.da.comp.w2lcommon.helper.MessageBox;
import java.io.IOException;
/** This class provides an abstract UNO component which implements an XExportFilter.
* The filter is actually generic and only the constructor and 3 strings needs
* to be 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 String __displayName = "";
private XComponentContext xComponentContext = null;
private SimpleDOMBuilder domBuilder = new SimpleDOMBuilder();
private UNOConverter converter = null;
/** Construct a new ExportFilterBase from a given component context
*
* @param xComponentContext the component context used to instantiate new UNO services
*/
public ExportFilterBase(XComponentContext xComponentContext) {
this.xComponentContext = xComponentContext;
}
// ---------------------------------------------------------------------------
// Implementation of XExportFilter:
public boolean exporter(com.sun.star.beans.PropertyValue[] aSourceData,
java.lang.String[] msUserData) {
// Create a suitable converter
converter = new UNOConverter(aSourceData, xComponentContext);
return true;
}
// ---------------------------------------------------------------------------
// Implementation of XDocumentHandler:
// A flat XML DOM tree is created by the SAX events and finally converted
public void startDocument () {
//Do nothing
}
public void endDocument()throws com.sun.star.uno.RuntimeException {
try{
converter.convert(domBuilder.getDOM());
}
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 sTagName, com.sun.star.xml.sax.XAttributeList xAttribs) {
domBuilder.startElement(sTagName);
int nLen = xAttribs.getLength();
for (short i=0;i<nLen;i++) {
domBuilder.setAttribute(xAttribs.getNameByIndex(i), xAttribs.getValueByIndex(i));
}
}
public void endElement(String sTagName){
domBuilder.endElement();
}
public void characters(String sText){
domBuilder.characters(sText);
}
public void ignorableWhitespace(String str){
}
public void processingInstruction(String aTarget, String aData){
}
public void setDocumentLocator(com.sun.star.xml.sax.XLocator xLocator){
}
// ---------------------------------------------------------------------------
// Implement methods from interface 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;
}
public String[] getSupportedServiceNames() {
String[] stringSupportedServiceNames = { __serviceName };
return( stringSupportedServiceNames );
}
}

View file

@ -1,433 +0,0 @@
/************************************************************************
*
* FilterDataParser.java
*
* Copyright: 2002-2015 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-05-06)
*
*/
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.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.util.XStringSubstitution;
import w2phtml.api.Converter;
import com.sun.star.lib.uno.adapter.XInputStreamToInputStreamAdapter;
import com.sun.star.lib.uno.adapter.XOutputStreamToOutputStreamAdapter;
import org.openoffice.da.comp.w2lcommon.helper.PropertyHelper;
/** 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 {
// TODO: Use JSON format
//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 FilterOptions property to the given converter.
* The property must be a comma separated list of name=value items.
* @param options an <code>Any</code> containing the FilterOptions property
* @param converter a <code>writer2latex.api.Converter</code> implementation
*/
public void applyFilterOptions(Object options, Converter converter) {
// Get the string from the data, if possible
if (AnyConverter.isString(options)) {
String sOptions = AnyConverter.toString(options);
if (sOptions!=null) {
// Convert to array
String[] sItems = sOptions.split(",");
int nItemCount = sItems.length;
PropertyValue[] filterData = new PropertyValue[nItemCount];
for (int i=0; i<nItemCount; i++) {
String[] sItem = sItems[i].split("=");
filterData[i] = new PropertyValue();
filterData[i].Name = sItem[0];
filterData[i].Value = sItem.length>1 ? sItem[1] : "";
System.out.println(filterData[i].Name+" "+filterData[i].Value);
}
applyParsedFilterData(filterData,converter);
}
}
}
/** Apply the given FilterData property to the given converter.
* The property must be an array of PropertyValue objects.
* @param data an <code>Any</code> 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;
if (filterData!=null) {
applyParsedFilterData(filterData,converter);
}
}
}
catch (com.sun.star.lang.IllegalArgumentException e) {
// Failed to convert to array; should not happen - ignore
}
}
}
private void applyParsedFilterData(PropertyValue[] filterData, Converter converter) {
PropertyHelper props = new PropertyHelper(filterData);
// Get the special properties TemplateURL, StyleSheetURL, ResourceURL, Resources, 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 styles = props.get("StyleSheetURL");
String sStyleSheet = null;
if (styles!=null && AnyConverter.isString(styles)) {
try {
sStyleSheet = substituteVariables(AnyConverter.toString(styles));
}
catch (com.sun.star.lang.IllegalArgumentException e) {
// Failed to convert to String; should not happen - ignore
}
}
// This property accepts an URL pointing to a folder containing the resources to include
Object resourcedir = props.get("ResourceURL");
String sResourceURL = null;
if (resourcedir!=null && AnyConverter.isString(resourcedir)) {
try {
sResourceURL = substituteVariables(AnyConverter.toString(resourcedir));
}
catch (com.sun.star.lang.IllegalArgumentException e) {
// Failed to convert to String; should not happen - ignore
}
}
// This property accepts a semicolon separated list of <URL>[[::<file name>]::<mime type>]
Object resources = props.get("Resources");
String[] sResources = null;
if (resources!=null && AnyConverter.isString(resources)) {
try {
sResources = substituteVariables(AnyConverter.toString(resources)).split(";");
}
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
}
}
// Load the style sheet from the specified URL, if any
if (sfa2!=null && sStyleSheet!=null && sStyleSheet.length()>0) {
try {
XInputStream xIs = sfa2.openFileRead(sStyleSheet);
if (xIs!=null) {
InputStream is = new XInputStreamToInputStreamAdapter(xIs);
converter.readStyleSheet(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
}
}
// Load the resource from the specified folder URL, if any
if (sfa2!=null && sResourceURL!=null && sResourceURL.length()>0) {
String[] sURLs;
try {
sURLs = sfa2.getFolderContents(sResourceURL, false); // do not include folders
for (String sURL : sURLs) {
XInputStream xIs = sfa2.openFileRead(sURL);
if (xIs!=null) {
String sFileName = sURL.substring(sURL.lastIndexOf('/')+1);
InputStream is = new XInputStreamToInputStreamAdapter(xIs);
converter.readResource(is,sFileName,null);
is.close();
xIs.closeInput();
}
}
} catch (IOException e) {
// ignore
} catch (CommandAbortedException e1) {
// ignore
} catch (Exception e1) {
// ignore
}
}
// Load the resources from the specified URLs, if any
if (sfa2!=null && sResources!=null) {
for (String sResource : sResources) {
// Format is <URL>[[::<file name>]::<mime type>]
String[] sParts = sResource.split("::");
if (sParts.length>0) {
String sURL=sParts[0];
String sFileName;
String sMediaType=null;
if (sParts.length==3) {
sFileName = sParts[1];
sMediaType = sParts[2];
}
else {
sFileName = sURL.substring(sURL.lastIndexOf('/')+1);
if (sParts.length==2) {
sMediaType = sParts[1];
}
}
try {
XInputStream xIs = sfa2.openFileRead(sURL);
if (xIs!=null) {
InputStream is = new XInputStreamToInputStreamAdapter(xIs);
converter.readResource(is, sFileName, sMediaType);
is.close();
xIs.closeInput();
} // otherwise wrong format, ignore
}
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<String> keys = props.keys();
while (keys.hasMoreElements()) {
String sKey = keys.nextElement();
if (!"ConfigURL".equals(sKey) && !"TemplateURL".equals(sKey) && !"StyleSheetURL".equals(sKey)
&& !"Resources".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

@ -1,66 +0,0 @@
/************************************************************************
*
* GraphicConverterImpl.java
*
* Copyright: 2002-2008 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.0 (2008-07-21)
*
*/
package org.openoffice.da.comp.w2lcommon.filter;
import com.sun.star.uno.XComponentContext;
import w2phtml.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

@ -1,153 +0,0 @@
/************************************************************************
*
* GraphicConverterImpl1.java
*
* Copyright: 2002-2014 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.4 (2014-09-05)
*/
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 w2phtml.api.GraphicConverter;
import w2phtml.api.MIMETypes;
import com.sun.star.uno.UnoRuntime;
/** 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 {
private XGraphicProvider xGraphicProvider;
private EPSCleaner epsCleaner;
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;
}
epsCleaner = new EPSCleaner();
}
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 and SVG
if ((MIMETypes.EPS.equals(sTargetMime) || MIMETypes.SVG.equals(sTargetMime)) &&
(MIMETypes.EMF.equals(sSourceMime) || 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.EMF.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.EMF.equals(sSourceMime) && !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.flush();
xTarget.closeOutput();
if (MIMETypes.EPS.equals(sTargetMime)) {
return epsCleaner.cleanEps(xTarget.getBuffer());
}
else {
byte[] converted = xTarget.getBuffer();
if (converted.length>0) { // Older versions of AOO/LO fails to convert to SVG (empty result)
return converted;
}
return null;
}
}
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;
}
}
}

View file

@ -1,267 +0,0 @@
/************************************************************************
*
* GraphicConverterImpl2.java
*
* Copyright: 2002-2015 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-07-30)
*
*/
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 w2phtml.api.GraphicConverter;
import w2phtml.api.MIMETypes;
import com.sun.star.lib.uno.adapter.ByteArrayToXInputStreamAdapter;
import com.sun.star.lib.uno.adapter.XOutputStreamToByteArrayAdapter;
/** 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<String,String> importFilter;
private Hashtable<String,String> exportFilter;
private EPSCleaner epsCleaner;
public GraphicConverterImpl2(XComponentContext xComponentContext) {
this.xComponentContext = xComponentContext;
importFilter = new Hashtable<String,String>();
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<String,String>();
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");
epsCleaner = new EPSCleaner();
}
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 support conversion of bitmaps and SVM into PDF, EPS and SVG
// TODO: SVG does not seem to work in all versions of OOo/LO?
// Trying WMF/EMF 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.EMF.equals(sSourceMime);
boolean bSupportsTarget = MIMETypes.PDF.equals(sTargetMime) || MIMETypes.EPS.equals(sTargetMime) ||
MIMETypes.SVG.equals(sTargetMime);
return bSupportsSource && bSupportsTarget;
}
public byte[] convert(byte[] source, String sSourceMime, String sTargetMime) {
// Open a hidden sdraw document
XMultiComponentFactory xMCF = xComponentContext.getServiceManager();
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);
PropertyValue[] fileProps = new PropertyValue[3];
fileProps[0] = new PropertyValue();
fileProps[0].Name = "FilterName";
fileProps[0].Value = 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 = 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();
if (MIMETypes.EPS.equals(sTargetMime)) {
return epsCleaner.cleanEps(result);
}
else {
return result;
}
}
catch (com.sun.star.beans.PropertyVetoException e) {
}
catch (com.sun.star.beans.UnknownPropertyException e) {
}
catch (com.sun.star.io.IOException e) {
}
catch (com.sun.star.lang.IllegalArgumentException e) {
}
catch (com.sun.star.lang.IndexOutOfBoundsException e) {
}
catch (com.sun.star.lang.WrappedTargetException e) {
}
catch (com.sun.star.uno.Exception e) {
}
// 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

@ -1,46 +0,0 @@
/************************************************************************
*
* Messages.java
*
* Copyright: 2002-2015 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-05-28)
*
*/
package org.openoffice.da.comp.w2lcommon.filter;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
private static final String BUNDLE_NAME = "org.openoffice.da.comp.w2lcommon.filter.messages"; //$NON-NLS-1$
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
.getBundle(BUNDLE_NAME);
private Messages() {
}
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}

View file

@ -1,542 +0,0 @@
/************************************************************************
*
* OptionsDialogBase.java
*
* Copyright: 2002-2014 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.4 (2014-11-01)
*
*/
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.XDocumentPropertiesSupplier;
import com.sun.star.frame.XDesktop;
import com.sun.star.lang.XComponent;
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 org.openoffice.da.comp.w2lcommon.helper.DialogBase;
import org.openoffice.da.comp.w2lcommon.helper.MacroExpander;
import org.openoffice.da.comp.w2lcommon.helper.PropertyHelper;
import org.openoffice.da.comp.w2lcommon.helper.XPropertySetHelper;
/** 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<String>();
}
//////////////////////////////////////////////////////////////////////////
// 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 endDialog() {
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<String> lockedOptions;
//////////////////////////////////////////////////////////////////////////
// Some private utility methods
// 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
XDocumentPropertiesSupplier xDocPropsSuppl =
UnoRuntime.queryInterface(XDocumentPropertiesSupplier.class, xComponent);
return xDocPropsSuppl.getDocumentProperties().getTemplateName();
}
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 = XPropertySetHelper.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 = XPropertySetHelper.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 = XPropertySetHelper.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] = XPropertySetHelper.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 = XPropertySetHelper.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 = XPropertySetHelper.getPropertyValueAsString(xTplProps,"TemplateName");
if (sTemplateName.equals(sTheTemplateName)) {
String sConfigName = XPropertySetHelper.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 = XPropertySetHelper.getPropertyValueAsShort(xProps,"Config");
if (nConfig<nStdConfigs) {
setListBoxSelectedItem("Config",nConfig);
}
else { // Registry configurations are stored by name
String sConfigName = XPropertySetHelper.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 = XPropertySetHelper.getPropertyValue(xProps,"Configurations");
XNameAccess xNameAccess = (XNameAccess)
UnoRuntime.queryInterface(XNameAccess.class,configurations);
short nConfig = getListBoxSelectedItem("Config");
int nStdConfigs = getListBoxStringItemList("Config").length - sConfigNames.length;
if (nConfig>=nStdConfigs) { // only handle registry configurations
int i = nConfig-nStdConfigs;
XPropertySetHelper.setPropertyValue(xProps,"ConfigName",sConfigNames[i]);
try {
Object config = xNameAccess.getByName(sConfigNames[i]);
XPropertySet xCfgProps = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class,config);
MacroExpander expander = new MacroExpander(xContext);
filterData.put("ConfigURL",expander.expandMacros(XPropertySetHelper.getPropertyValueAsString(xCfgProps,"ConfigURL")));
filterData.put("TemplateURL",expander.expandMacros(XPropertySetHelper.getPropertyValueAsString(xCfgProps,"TargetTemplateURL")));
filterData.put("StyleSheetURL",expander.expandMacros(XPropertySetHelper.getPropertyValueAsString(xCfgProps,"StyleSheetURL")));
// The resources are provided as a set
Object resources = XPropertySetHelper.getPropertyValue(xCfgProps,"Resources");
XNameAccess xResourceNameAccess = (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class,resources);
if (xResourceNameAccess!=null) {
StringBuilder buf = new StringBuilder();
String[] sResourceNames = xResourceNameAccess.getElementNames();
for (String sName : sResourceNames) {
Object resource = xResourceNameAccess.getByName(sName);
XPropertySet xResourceProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class,resource);
String sURL = expander.expandMacros(XPropertySetHelper.getPropertyValueAsString(xResourceProps,"URL"));
String sFileName = expander.expandMacros(XPropertySetHelper.getPropertyValueAsString(xResourceProps,"FileName"));
String sMediaType = expander.expandMacros(XPropertySetHelper.getPropertyValueAsString(xResourceProps,"MediaType"));
if (buf.length()>0) { buf.append(';'); }
buf.append(sURL).append("::").append(sFileName).append("::").append(sMediaType);
}
filterData.put("Resources",buf.toString());
}
}
catch (Exception e) {
}
}
else { // Standard configurations have no name
XPropertySetHelper.setPropertyValue(xProps,"ConfigName","");
}
XPropertySetHelper.setPropertyValue(xProps,"Config",nConfig);
return nConfig;
}
// Check box option (boolean)
protected boolean loadCheckBoxOption(XPropertySet xProps, String sName) {
boolean bValue = XPropertySetHelper.getPropertyValueAsBoolean(xProps,sName);
setCheckBoxStateAsBoolean(sName, bValue);
return bValue;
}
protected boolean saveCheckBoxOption(XPropertySet xProps, String sName) {
boolean bValue = getCheckBoxStateAsBoolean(sName);
XPropertySetHelper.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 = XPropertySetHelper.getPropertyValueAsShort(xProps, sName);
setListBoxSelectedItem(sName ,nValue);
return nValue;
}
protected short saveListBoxOption(XPropertySet xProps, String sName) {
short nValue = getListBoxSelectedItem(sName);
XPropertySetHelper.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 = XPropertySetHelper.getPropertyValueAsString(xProps, sName);
setComboBoxText(sName ,sValue);
return sValue;
}
protected String saveComboBoxOption(XPropertySet xProps, String sName) {
String sValue = getComboBoxText(sName);
XPropertySetHelper.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 = XPropertySetHelper.getPropertyValueAsString(xProps, sName);
setTextFieldText(sName ,sValue);
return sValue;
}
protected String saveTextFieldOption(XPropertySet xProps, String sName) {
String sValue = getTextFieldText(sName);
XPropertySetHelper.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 = XPropertySetHelper.getPropertyValueAsInteger(xProps, sName);
setNumericFieldValue(sName, nValue);
return nValue;
}
protected int saveNumericOption(XPropertySet xProps, String sName) {
int nValue = getNumericFieldValue(sName);
XPropertySetHelper.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

@ -1,264 +0,0 @@
/************************************************************************
*
* UNOConverter.java
*
* Copyright: 2002-2015 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-05-06)
*
*/
package org.openoffice.da.comp.w2lcommon.filter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import org.w3c.dom.Document;
import com.sun.star.beans.PropertyValue;
import com.sun.star.io.XInputStream;
import com.sun.star.io.XOutputStream;
import com.sun.star.lib.uno.adapter.XInputStreamToInputStreamAdapter;
import com.sun.star.lib.uno.adapter.XOutputStreamToOutputStreamAdapter;
import com.sun.star.ucb.XSimpleFileAccess2;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Type;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import w2phtml.api.Converter;
import w2phtml.api.ConverterFactory;
import w2phtml.api.ConverterResult;
import w2phtml.api.OutputFile;
import w2phtml.util.Misc;
/** This class provides conversion using UNO:
* Graphics conversion is done using appropriate UNO services.
* Files are written to an URL using UCB.
* The document source document can be provided as an <code>XInputStream</code> or as a DOM tree
*/
public class UNOConverter {
private XComponentContext xComponentContext;
private Converter converter;
private String sTargetFormat = null;
private XOutputStream xos = null;
private String sURL = null;
/** Construct a new UNODocumentConverter from an array of arguments
*
* @param xComponentContext the component context used to instantiate new UNO services
* @param lArguments arguments providing FilterName, URL, OutputStream (optional), FilterData (optional)
* and FilterOptions (optional, alternative to FilterData)
*/
public UNOConverter(PropertyValue[] lArguments, XComponentContext xComponentContext) {
this.xComponentContext = xComponentContext;
// Create mapping from filter names to target media types
HashMap<String,String> filterNames = new HashMap<String,String>();
//filterNames.put("org.openoffice.da.writer2latex","application/x-latex");
//filterNames.put("org.openoffice.da.writer2bibtex","application/x-bibtex");
filterNames.put("org.openoffice.da.writer2xhtml","text/html");
filterNames.put("org.openoffice.da.writer2xhtml11","application/xhtml11");
filterNames.put("org.openoffice.da.writer2xhtml5","text/html5");
filterNames.put("org.openoffice.da.writer2xhtml.mathml","application/xhtml+xml");
filterNames.put("org.openoffice.da.writer2xhtml.epub","application/epub+zip");
filterNames.put("org.openoffice.da.writer2xhtml.epub3","epub3");
filterNames.put("org.openoffice.da.calc2xhtml","text/html");
filterNames.put("org.openoffice.da.calc2xhtml11","application/xhtml11");
filterNames.put("org.openoffice.da.calc2xhtml5","text/html5");
// Get the arguments
Object filterData = null;
Object filterOptions = null;
PropertyValue[] pValue = lArguments;
for (int i = 0 ; i < pValue.length; i++) {
try {
if (pValue[i].Name.compareTo("FilterName")==0) {
String sFilterName = (String)AnyConverter.toObject(new Type(String.class), pValue[i].Value);
if (filterNames.containsKey(sFilterName)) {
sTargetFormat = filterNames.get(sFilterName);
}
else {
sTargetFormat = sFilterName;
}
}
if (pValue[i].Name.compareTo("OutputStream")==0){
xos = (XOutputStream)AnyConverter.toObject(new Type(XOutputStream.class), pValue[i].Value);
}
if (pValue[i].Name.compareTo("URL")==0){
sURL = (String)AnyConverter.toObject(new Type(String.class), pValue[i].Value);
}
if (pValue[i].Name.compareTo("FilterData")==0) {
filterData = pValue[i].Value;
}
if (pValue[i].Name.compareTo("FilterOptions")==0) {
filterOptions = pValue[i].Value;
}
}
catch(com.sun.star.lang.IllegalArgumentException AnyExec){
System.err.println("\nIllegalArgumentException "+AnyExec);
}
}
if (sURL==null){
sURL="";
}
// Create converter and supply it with filter data and a suitable graphic converter
converter = ConverterFactory.createConverter(sTargetFormat);
if (converter==null) {
throw new com.sun.star.uno.RuntimeException("Failed to create converter to "+sTargetFormat);
}
if (filterData!=null) {
FilterDataParser fdp = new FilterDataParser(xComponentContext);
fdp.applyFilterData(filterData,converter);
}
else if (filterOptions!=null) {
FilterDataParser fdp = new FilterDataParser(xComponentContext);
fdp.applyFilterOptions(filterOptions,converter);
}
converter.setGraphicConverter(new GraphicConverterImpl(xComponentContext));
}
/** Convert a document given by a DOM tree
*
* @param dom the DOMsource
* @throws IOException
*/
public void convert(Document dom) throws IOException {
writeFiles(converter.convert(dom, Misc.makeFileName(getFileName(sURL)),true));
}
/** Convert a document given by an XInputStream
*
* @param xis the input stream
* @throws IOException
*/
public void convert(XInputStream xis) throws IOException {
InputStream is = new XInputStreamToInputStreamAdapter(xis);
writeFiles(converter.convert(is, Misc.makeFileName(getFileName(sURL))));
}
private void writeFiles(ConverterResult result) throws IOException {
Iterator<OutputFile> docEnum = result.iterator();
if (docEnum.hasNext()) {
// The master document is written to the supplied XOutputStream, if any
if (xos!=null) {
XOutputStreamToOutputStreamAdapter newxos =new XOutputStreamToOutputStreamAdapter(xos);
docEnum.next().write(newxos);
newxos.flush();
newxos.close();
}
// Additional files are written directly using UCB
if (docEnum.hasNext() && sURL.startsWith("file:")) {
// Initialize the file access (used to write all additional output files)
XSimpleFileAccess2 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)
}
if (sfa2!=null) {
// 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()) {
OutputFile docOut = docEnum.next();
// Get the file name and the (optional) directory name
String sFullFileName = Misc.makeHref(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 use a Pipe for the transport
Object xPipeObj = xComponentContext.getServiceManager().createInstanceWithContext(
"com.sun.star.io.Pipe", xComponentContext);
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){
throw new IOException("Error writing file "+sFileName+" "+e.getMessage());
}
}
}
}
}
else {
// The converter did not produce any files (should not happen)
throw new IOException("Conversion failed: Internal error");
}
}
private 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;
}
}

View file

@ -1,326 +0,0 @@
/************************************************************************
*
* UNOPublisher.java
*
* Copyright: 2002-2018 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2018-03-06)
*
*/
package org.openoffice.da.comp.w2lcommon.filter;
import java.io.IOException;
import java.util.regex.Pattern;
import org.openoffice.da.comp.w2lcommon.helper.MessageBox;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertyAccess;
import com.sun.star.frame.XController;
import com.sun.star.frame.XFrame;
import com.sun.star.frame.XModel;
import com.sun.star.frame.XStorable;
import com.sun.star.io.XInputStream;
import com.sun.star.task.XStatusIndicator;
import com.sun.star.task.XStatusIndicatorFactory;
import com.sun.star.ucb.XSimpleFileAccess2;
import com.sun.star.ui.dialogs.ExecutableDialogResults;
import com.sun.star.ui.dialogs.XExecutableDialog;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.util.XModifiable;
import w2phtml.util.Misc;
/** This class converts an open office document to another format
*/
public class UNOPublisher {
public enum TargetFormat { xhtml, xhtml11, xhtml_mathml, html5, epub, epub3 };
private String sAppName;
protected XComponentContext xContext;
protected XFrame xFrame;
private XModel xModel = null;
private PropertyValue[] mediaProps = null;
/** Create a new <code>UNOPublisher</code> based on a loaded office document
*
* @param xContext the component context from which new UNO services are instantiated
* @param xFrame the current frame
* @param sAppName the name of the application using the <code>UNOPublisher</code>
*/
public UNOPublisher(XComponentContext xContext, XFrame xFrame, String sAppName) {
this.xContext = xContext;
this.xFrame = xFrame;
this.sAppName = sAppName;
// Get the model for the document from the frame
XController xController = xFrame.getController();
if (xController!=null) {
xModel = xController.getModel();
}
}
/** Publish the document associated with this <code>UNOPublisher</code>. This involves five steps:
* (1) Check that the document is saved in the local file system.
* (2) Display the options dialog.
* (3) Save the document (if the modified flag is true).
* (4) Convert the document.
* (5) Post process the document, e.g. displaying the result
*
* @param format the target format
* @return true if the publishing was successful
*/
public boolean publish(TargetFormat format) {
if (documentSaved() && updateMediaProperties(format)) {
// Create a (somewhat coarse grained) status indicator/progress bar
XStatusIndicatorFactory xFactory = (com.sun.star.task.XStatusIndicatorFactory)
UnoRuntime.queryInterface(com.sun.star.task.XStatusIndicatorFactory.class, xFrame);
XStatusIndicator xStatus = xFactory.createStatusIndicator();
xStatus.start(sAppName,10);
xStatus.setValue(1); // At least we have started, that's 10% :-)
try {
// Save document if required
saveDocument();
xStatus.setValue(4); // Document saved, that's 40%
// Convert to desired format
UNOConverter converter = new UNOConverter(mediaProps, xContext);
// Initialize the file access (to read the office document)
XSimpleFileAccess2 sfa2 = null;
try {
Object sfaObject = xContext.getServiceManager().createInstanceWithContext(
"com.sun.star.ucb.SimpleFileAccess", xContext); //$NON-NLS-1$
sfa2 = (XSimpleFileAccess2) UnoRuntime.queryInterface(XSimpleFileAccess2.class, sfaObject);
}
catch (com.sun.star.uno.Exception e) {
// failed to get SimpleFileAccess service (should not happen)
}
XInputStream xis = sfa2.openFileRead(xModel.getURL());
converter.convert(xis);
xis.closeInput();
}
catch (IOException e) {
xStatus.end();
MessageBox msgBox = new MessageBox(xContext, xFrame);
msgBox.showMessage(sAppName,Messages.getString("UNOPublisher.failexport")); //$NON-NLS-1$
return false;
}
catch (com.sun.star.uno.Exception e) {
xStatus.end();
MessageBox msgBox = new MessageBox(xContext, xFrame);
msgBox.showMessage(sAppName,Messages.getString("UNOPublisher.failexport")); //$NON-NLS-1$
return false;
}
xStatus.setValue(7); // Document is converted, that's 70%
postProcess(getTargetURL(format),format);
xStatus.setValue(10); // Export is finished (The user will usually not see this...)
xStatus.end();
return true;
}
return false;
}
/** Filter the file name to avoid unwanted characters
*
* @param sFileName the original file name
* @return the filtered file name
*/
protected String filterFileName(String sFileName) {
return sFileName;
}
/** Post process the media properties after displaying the dialog
*
* @param mediaProps the media properties as set by the dialog
* @return the updated media properties
*/
protected PropertyValue[] postProcessMediaProps(PropertyValue[] mediaProps) {
return mediaProps;
}
/** Post process the document after conversion.
*
* @param sTargetURL URL of the converted document
* @param format the target format
*/
protected void postProcess(String sTargetURL, TargetFormat format) {
}
/** Check that the document is saved in a location, we can use
*
* @return true if everthing is o.k.
*/
public boolean documentSaved() {
String sDocumentUrl = xModel.getURL();
if (sDocumentUrl.length()==0) { // The document has no location
MessageBox msgBox = new MessageBox(xContext, xFrame);
msgBox.showMessage(sAppName,Messages.getString("UNOPublisher.savedocument")); //$NON-NLS-1$
return false;
}
else if (!".odt".equals(Misc.getFileExtension(sDocumentUrl)) && !".fodt".equals(Misc.getFileExtension(sDocumentUrl)) && !".ods".equals(Misc.getFileExtension(sDocumentUrl)) && !".fods".equals(Misc.getFileExtension(sDocumentUrl))) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
MessageBox msgBox = new MessageBox(xContext, xFrame);
msgBox.showMessage(sAppName,Messages.getString("UNOPublisher.saveodt")); //$NON-NLS-1$
return false;
}
else if (!sDocumentUrl.startsWith("file:")) { //$NON-NLS-1$
MessageBox msgBox = new MessageBox(xContext, xFrame);
msgBox.showMessage(sAppName,Messages.getString("UNOPublisher.savefilesystem")); //$NON-NLS-1$
return false;
}
else if (System.getProperty("os.name").startsWith("Windows")) { //$NON-NLS-1$ //$NON-NLS-2$
// Avoid UNC paths (LaTeX does not like them)
Pattern windowsPattern = Pattern.compile("^file:///[A-Za-z][|:].*"); //$NON-NLS-1$
if (!windowsPattern.matcher(sDocumentUrl).matches()) {
MessageBox msgBox = new MessageBox(xContext, xFrame);
msgBox.showMessage(sAppName,
Messages.getString("UNOPublisher.savedrivename")); //$NON-NLS-1$
return false;
}
}
return true;
}
private boolean saveDocument() {
XModifiable xModifiable = (XModifiable) UnoRuntime.queryInterface(XModifiable.class, xModel);
if (xModifiable.isModified()) { // The document is modified and need to be saved
XStorable xStorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, xModel);
try {
xStorable.store();
} catch (com.sun.star.io.IOException e) {
return false;
}
}
return true;
}
// Some utility methods
/** Get the target path (or null if the document is not saved)
*
* @return the path
*/
public String getTargetPath() {
if (xModel.getURL().length()>0) {
String sBaseURL = Misc.removeExtension(xModel.getURL());
return Misc.getPath(sBaseURL);
}
return null;
}
/** Get the target file name (or null if the document is not saved)
*
* @return the file name
*/
public String getTargetFileName() {
if (xModel.getURL().length()>0) {
String sBaseURL = Misc.removeExtension(xModel.getURL());
return filterFileName(Misc.getFileName(sBaseURL));
}
return null;
}
protected String getTargetURL(TargetFormat format) {
return getTargetPath()+getTargetFileName()+getTargetExtension(format);
}
private void prepareMediaProperties(TargetFormat format) {
// Create inital media properties
mediaProps = new PropertyValue[2];
mediaProps[0] = new PropertyValue();
mediaProps[0].Name = "FilterName"; //$NON-NLS-1$
mediaProps[0].Value = getFilterName(format);
mediaProps[1] = new PropertyValue();
mediaProps[1].Name = "URL"; //$NON-NLS-1$
mediaProps[1].Value = getTargetURL(format);
}
private boolean updateMediaProperties(TargetFormat format) {
prepareMediaProperties(format);
String sDialogName = getDialogName(format);
if (sDialogName!=null) {
try {
// Display options dialog
Object dialog = xContext.getServiceManager()
.createInstanceWithContext(sDialogName, xContext);
XPropertyAccess xPropertyAccess = (XPropertyAccess)
UnoRuntime.queryInterface(XPropertyAccess.class, dialog);
xPropertyAccess.setPropertyValues(mediaProps);
XExecutableDialog xDialog = (XExecutableDialog)
UnoRuntime.queryInterface(XExecutableDialog.class, dialog);
if (xDialog.execute()==ExecutableDialogResults.OK) {
mediaProps = postProcessMediaProps(xPropertyAccess.getPropertyValues());
return true;
}
}
catch (com.sun.star.beans.UnknownPropertyException e) {
// setPropertyValues will not fail..
}
catch (com.sun.star.uno.Exception e) {
// getServiceManager will not fail..
}
}
// No dialog exists, or the dialog was cancelled
mediaProps = null;
return false;
}
private static String getTargetExtension(TargetFormat format) {
switch (format) {
case xhtml: return ".html"; //$NON-NLS-1$
case xhtml11: return ".xhtml"; //$NON-NLS-1$
case xhtml_mathml: return ".xhtml"; //$NON-NLS-1$
case html5: return ".html"; //$NON-NLS-1$
case epub: return ".epub"; //$NON-NLS-1$
case epub3: return ".epub"; //$NON-NLS-1$
default: return ""; //$NON-NLS-1$
}
}
private static String getDialogName(TargetFormat format) {
switch (format) {
case xhtml:
case xhtml11: return "org.openoffice.da.comp.writer2xhtml.XhtmlOptionsDialog"; //$NON-NLS-1$
case xhtml_mathml:
case html5: return "org.openoffice.da.comp.writer2xhtml.XhtmlOptionsDialogMath"; //$NON-NLS-1$
case epub: return "org.openoffice.da.comp.writer2xhtml.EpubOptionsDialog"; //$NON-NLS-1$
case epub3: return "org.openoffice.da.comp.writer2xhtml.Epub3OptionsDialog"; //$NON-NLS-1$
default: return null;
}
}
private static String getFilterName(TargetFormat format) {
switch (format) {
case xhtml: return "org.openoffice.da.writer2xhtml"; //$NON-NLS-1$
case xhtml11: return "org.openoffice.da.writer2xhtml11"; //$NON-NLS-1$
case xhtml_mathml: return "org.openoffice.da.writer2xhtml.mathml"; //$NON-NLS-1$
case html5: return "org.openoffice.da.writer2xhtml5"; //$NON-NLS-1$
case epub: return "org.openoffice.da.writer2xhtml.epub"; //$NON-NLS-1$
case epub3: return "org.openoffice.da.writer2xhtml.epub3"; //$NON-NLS-1$
default: return ""; //$NON-NLS-1$
}
}
}

View file

@ -1,5 +0,0 @@
UNOPublisher.failexport=Error: Failed to export document
UNOPublisher.savedocument=Please save the document first
UNOPublisher.saveodt=Please save the document in OpenDocument format (.odt)
UNOPublisher.savefilesystem=Please save the document in the local file system
UNOPublisher.savedrivename=Please save the document on a location with a drive name

View file

@ -1,5 +0,0 @@
UNOPublisher.failexport=Fejl: Kunne ikke eksportere dokumentet
UNOPublisher.savedocument=Gem dokumentet først
UNOPublisher.saveodt=Gem dokumentet i OpenDocument-format (.odt)
UNOPublisher.savefilesystem=Gem dokumentet i det lokale filsystem
UNOPublisher.savedrivename=Gem dokumentet et sted med et drevbogstav

View file

@ -1,355 +0,0 @@
/************************************************************************
*
* DialogAccess.java
*
* Copyright: 2002-2015 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-04-15)
*
*/
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.beans.XPropertySet;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.util.Date;
/** This class provides some convenient methods to access a uno dialog
*/
public class DialogAccess {
/** The XDialog containing the controls. */
private XDialog xDialog = null;
// State of a checkbox
public static final short CHECKBOX_NOT_CHECKED = 0;
public static final short CHECKBOX_CHECKED = 1;
public static final short CHECKBOX_DONT_KNOW = 2;
public DialogAccess(XDialog xDialog) {
this.xDialog = xDialog;
}
protected void setDialog(XDialog xDialog) {
this.xDialog = xDialog;
}
protected XDialog getDialog() {
return this.xDialog;
}
//////////////////////////////////////////////////////////////////////////
// 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
public 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;
}
public boolean getControlEnabled(String sControlName) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
return ((Boolean) xPropertySet.getPropertyValue("Enabled")).booleanValue();
}
catch (Exception e) {
// Will fail if the control does not exist
return false;
}
}
public 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
System.out.println(e);
}
}
public short getCheckBoxState(String sControlName) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
return ((Short) xPropertySet.getPropertyValue("State")).shortValue();
}
catch (Exception e) {
System.out.println(e);
// Will fail if the control does not exist or is not a checkbox
return CHECKBOX_DONT_KNOW;
}
}
public boolean getCheckBoxStateAsBoolean(String sControlName) {
return getCheckBoxState(sControlName)==CHECKBOX_CHECKED;
}
public 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
}
}
public void setCheckBoxStateAsBoolean(String sControlName, boolean bChecked) {
setCheckBoxState(sControlName,bChecked ? CHECKBOX_CHECKED : CHECKBOX_NOT_CHECKED);
}
public 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];
}
}
public 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
}
}
public 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;
}
}
public 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
}
}
public short getListBoxLineCount(String sControlName) {
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;
}
}
public 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
}
}
public 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 "";
}
}
public 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
}
}
public String getLabelText(String sControlName) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
return (String) xPropertySet.getPropertyValue("Label");
}
catch (Exception e) {
// Will fail if the control does not exist or is not a label
return "";
}
}
public void setLabelText(String sControlName, String sLabel) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
xPropertySet.setPropertyValue("Label",sLabel);
}
catch (Exception e) {
// Will fail if the control does not exist or is not a label
}
}
public 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 "";
}
}
public 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
}
}
public 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 "";
}
}
public 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
}
}
public int getDateFieldValue(String sControlName) {
XPropertySet xPropertySet = getControlProperties(sControlName);
try {
Object dateObject = xPropertySet.getPropertyValue("Date");
if (dateObject instanceof Date) {
// Since LO 4.1
Date date = (Date) dateObject;
return 10000*date.Year+100*date.Month+date.Day;
}
else if (dateObject instanceof Integer) {
// AOO and older versions of LO
return ((Integer) dateObject).intValue();
}
else {
// The date field does not have a value
return 0;
}
}
catch (Exception e) {
// Will fail if the control does not exist or is not a date field
return 0;
}
}
public void setDateFieldValue(String sControlName, int nValue) {
XPropertySet xPropertySet = getControlProperties(sControlName);
Date date = new Date();
date.Year = (short) (nValue/10000);
date.Month = (short) ((nValue%10000)/100);
date.Day = (short) (nValue%100);
// TODO: Use reflection to identify the correct type of the property
try {
// Since LO 4.1
xPropertySet.setPropertyValue("Date", date);
} catch (Exception e) {
// AOO and older versions of LO
try {
xPropertySet.setPropertyValue("Date", nValue);
} catch (Exception e1) {
}
}
}
public 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;
}
}
public 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
}
}
}

View file

@ -1,203 +0,0 @@
/************************************************************************
*
* DialogBase.java
*
* Copyright: 2002-2015 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-04-15)
*
*/
package org.openoffice.da.comp.w2lcommon.helper;
import com.sun.star.awt.XDialog;
import com.sun.star.awt.XDialogEventHandler;
import com.sun.star.awt.XDialogProvider2;
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 extends DialogAccess 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();
/** End the dialog after execution (eg. save settings to the registry)
* The subclass must implement this
*/
protected abstract void endDialog();
//////////////////////////////////////////////////////////////////////////
// Some private global variables
// The component context (from constructor)
protected XComponentContext xContext;
// The dialog title (created by XExecutableDialog implementation)
private String sTitle;
//////////////////////////////////////////////////////////////////////////
// The constructor
/** Create a new OptionsDialogBase */
public DialogBase(XComponentContext xContext) {
super(null);
this.xContext = xContext;
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";
setDialog(xDialogProvider.createDialogWithHandler(sDialogUrl, this));
if (sTitle!=null) { getDialog().setTitle(sTitle); }
// Do initialization using method from subclass
initialize();
// Execute the dialog
short nResult = getDialog().execute();
if (nResult == ExecutableDialogResults.OK) {
// Finalize after execution of dialog using method from subclass
endDialog();
}
getDialog().endExecute();
return nResult;
}
catch (Exception e) {
// 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];
}
}

View file

@ -1,92 +0,0 @@
/************************************************************************
*
* FiledMasterNameProvider.java
*
* Copyright: 2002-2010 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.2 (2010-12-09)
*
*/
package org.openoffice.da.comp.w2lcommon.helper;
import java.util.HashSet;
import java.util.Set;
import com.sun.star.container.XNameAccess;
import com.sun.star.frame.XController;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XModel;
import com.sun.star.text.XTextFieldsSupplier;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
/** This class provides access to the names of all field masters in the current document
*/
public class FieldMasterNameProvider {
private String[] fieldMasterNames;
/** Construct a new <code>FieldMasterNameProvider</code>
*
* @param xContext the component context to get the desktop from
*/
public FieldMasterNameProvider(XComponentContext xContext) {
fieldMasterNames = new String[0];
// TODO: This code should be shared (identical with StyleNameProvider...)
// Get the model for the current frame
XModel xModel = null;
try {
Object desktop = xContext.getServiceManager().createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
XDesktop xDesktop = (XDesktop)UnoRuntime.queryInterface(XDesktop.class, desktop);
XController xController = xDesktop.getCurrentFrame().getController();
if (xController!=null) {
xModel = xController.getModel();
}
}
catch (Exception e) {
// do nothing
}
// Get the field masters from the model
if (xModel!=null) {
XTextFieldsSupplier xSupplier = (XTextFieldsSupplier) UnoRuntime.queryInterface(
XTextFieldsSupplier.class, xModel);
if (xSupplier!=null) {
XNameAccess xFieldMasters = xSupplier.getTextFieldMasters();
fieldMasterNames = xFieldMasters.getElementNames();
}
}
}
/** Get the names of all field masters relative to a given prefix
*
* @param sPrefix the prefix to look for, e.g. "com.sun.star.text.fieldmaster.SetExpression."
* @return a read only <code>Set</code> containing all known names with the given prefix, stripped for the prefix
*/
public Set<String> getFieldMasterNames(String sPrefix) {
Set<String> names = new HashSet<String>();
for (String sName : fieldMasterNames) {
if (sName.startsWith(sPrefix)) {
names.add(sName.substring(sPrefix.length()));
}
}
return names;
}
}

View file

@ -1,125 +0,0 @@
/************************************************************************
*
* FilePicker.java
*
* Copyright: 2002-2014 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.4 (2014-09-24)
*
*/
package org.openoffice.da.comp.w2lcommon.helper;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.XComponent;
import com.sun.star.ui.dialogs.ExecutableDialogResults;
import com.sun.star.ui.dialogs.XExecutableDialog;
import com.sun.star.ui.dialogs.XFilePicker;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
public class FilePicker {
private XComponentContext xContext;
// The default directory for the dialog
private String sDirectoryURL;
/** Convenience wrapper class for the UNO file picker service
*
* @param xContext the UNO component context from which the file picker can be created
*/
public FilePicker(XComponentContext xContext) {
this.xContext = xContext;
sDirectoryURL = null;
}
/** Get one or more user selected paths with a file picker
*
* Warning: This does not work on all platforms when using native file pickers
* (but always when using Office file pickers)
*
* @return array containing the path URLs or null if the dialog is canceled
*/
public String[] getPaths() {
return getPaths(true);
}
/** Get a user selected path with a file picker
*
* @return the path URL or null if the dialog is canceled
*/
public String getPath() {
String[] sPaths = getPaths(false);
if (sPaths!=null && sPaths.length>0) {
return sPaths[0];
}
return null;
}
private String[] getPaths(boolean bAllowMultiSelection) {
// Create FilePicker
Object filePicker = null;
try {
// Note: Could be changed for OfficeFilePicker to always use internal file pickers
filePicker = xContext.getServiceManager().createInstanceWithContext("com.sun.star.ui.dialogs.FilePicker", xContext);
}
catch (com.sun.star.uno.Exception e) {
return null;
}
// Get the required interfaces
XFilePicker xFilePicker = (XFilePicker) UnoRuntime.queryInterface(XFilePicker.class, filePicker);
XExecutableDialog xExecutable = (XExecutableDialog) UnoRuntime.queryInterface(XExecutableDialog.class, xFilePicker);
// Configure the file picker
xFilePicker.setMultiSelectionMode(bAllowMultiSelection);
if (sDirectoryURL!=null) {
try {
xFilePicker.setDisplayDirectory(sDirectoryURL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
// Get the paths
String[] sPaths = null;
if (xExecutable.execute() == ExecutableDialogResults.OK) {
sDirectoryURL = xFilePicker.getDisplayDirectory();
String[] sPathList = xFilePicker.getFiles();
int nCount = sPathList.length;
if (nCount>1) {
// According to the spec, the first entry is the path and remaining entries are file names
sPaths = new String[nCount-1];
for (int i=1; i<nCount; i++) {
sPaths[i-1]=sPathList[0] + sPathList[i];
}
}
else if (nCount==1) {
sPaths = sPathList;
}
}
// Dispose the file picker
XComponent xComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, xFilePicker);
xComponent.dispose();
return sPaths;
}
}

View file

@ -1,81 +0,0 @@
/************************************************************************
*
* FolderPicker.java
*
* Copyright: 2002-2010 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.2 (2010-10-11)
*
*/
package org.openoffice.da.comp.w2lcommon.helper;
import com.sun.star.lang.XComponent;
import com.sun.star.ui.dialogs.ExecutableDialogResults;
import com.sun.star.ui.dialogs.XExecutableDialog;
import com.sun.star.ui.dialogs.XFolderPicker;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
public class FolderPicker {
private XComponentContext xContext;
/** Convenience wrapper class for the UNO folder picker service
*
* @param xContext the UNO component context from which the folder picker can be created
*/
public FolderPicker(XComponentContext xContext) {
this.xContext = xContext;
}
/** Get a user selected path with a folder picker
*
* @return the path or null if the dialog is canceled
*/
public String getPath() {
// Create FolderPicker
Object folderPicker = null;
try {
folderPicker = xContext.getServiceManager().createInstanceWithContext("com.sun.star.ui.dialogs.FolderPicker", xContext);
}
catch (com.sun.star.uno.Exception e) {
return null;
}
// Display the FolderPicker
XFolderPicker xFolderPicker = (XFolderPicker) UnoRuntime.queryInterface(XFolderPicker.class, folderPicker);
XExecutableDialog xExecutable = (XExecutableDialog) UnoRuntime.queryInterface(XExecutableDialog.class, xFolderPicker);
// Get the path
String sPath = null;
if (xExecutable.execute() == ExecutableDialogResults.OK) {
sPath = xFolderPicker.getDirectory();
}
// Dispose the folder picker
XComponent xComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, folderPicker);
if (xComponent!=null) { // Seems not to be ??
xComponent.dispose();
}
return sPath;
}
}

View file

@ -1,68 +0,0 @@
/************************************************************************
*
* MacroExpander.java
*
* Copyright: 2002-2010 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.2 (2010-03-12)
*
*/
package org.openoffice.da.comp.w2lcommon.helper;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.util.XMacroExpander;
public class MacroExpander {
private XMacroExpander xExpander;
/** Convenience wrapper class for the UNO Macro Expander singleton
*
* @param xContext the UNO component context from which "theMacroExpander" can be created
*/
public MacroExpander(XComponentContext xContext) {
Object expander = xContext.getValueByName("/singletons/com.sun.star.util.theMacroExpander");
xExpander = (XMacroExpander) UnoRuntime.queryInterface (XMacroExpander.class, expander);
}
/** Expand macros in a string
*
* @param s the string
* @return the expanded string
*/
public String expandMacros(String s) {
if (xExpander!=null && 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);
try {
return xExpander.expandMacros(s);
}
catch (IllegalArgumentException e) {
// Unknown macro name found, proceed and hope for the best
return s;
}
}
else {
return s;
}
}
}

View file

@ -1,104 +0,0 @@
/************************************************************************
*
* MessageBox.java
*
* Copyright: 2002-2015 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-02-16)
*
*/
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(200,100,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

@ -1,77 +0,0 @@
/************************************************************************
*
* PropertyHelper.java
*
* Copyright: 2002-2008 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* 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<String, Object> data;
public PropertyHelper() {
data = new Hashtable<String, Object>();
}
public PropertyHelper(PropertyValue[] props) {
data = new Hashtable<String, Object>();
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<String> keys() {
return data.keys();
}
public PropertyValue[] toArray() {
int nSize = data.size();
PropertyValue[] props = new PropertyValue[nSize];
int i=0;
Enumeration<String> keys = keys();
while (keys.hasMoreElements()) {
String sKey = keys.nextElement();
props[i] = new PropertyValue();
props[i].Name = sKey;
props[i++].Value = get(sKey);
}
return props;
}
}

View file

@ -1,85 +0,0 @@
/**
* RegistryHelper.java
*
* Copyright: 2002-2009 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.2 (2009-05-01)
*
*
*/
package org.openoffice.da.comp.w2lcommon.helper;
import com.sun.star.beans.PropertyValue;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
/** This class defines convenience methods to access the OOo registry
* using a given base path
*/
public class RegistryHelper {
private XComponentContext xContext;
/** Construct a new RegistryHelper using a given component context
*
* @param xContext the context to use to create new services
*/
public RegistryHelper(XComponentContext xContext) {
this.xContext = xContext;
}
/** Get a registry view relative to the given path
*
* @param sPath the base path within the registry
* @param bUpdate true if we need update access
* @return the registry view
* @throws com.sun.star.uno.Exception
*/
public Object getRegistryView(String sPath, boolean bUpdate)
throws com.sun.star.uno.Exception {
//Object provider = xMSF.createInstance(
Object provider = xContext.getServiceManager().createInstanceWithContext(
"com.sun.star.configuration.ConfigurationProvider", xContext);
XMultiServiceFactory xProvider = (XMultiServiceFactory)
UnoRuntime.queryInterface(XMultiServiceFactory.class,provider);
PropertyValue[] args = new PropertyValue[1];
args[0] = new PropertyValue();
args[0].Name = "nodepath";
args[0].Value = sPath;
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
*
* @param view the view to dispose
*/
public void disposeRegistryView(Object view) {
XComponent xComponent = (XComponent)
UnoRuntime.queryInterface(XComponent.class,view);
xComponent.dispose();
}
}

View file

@ -1,78 +0,0 @@
/************************************************************************
*
* SimpleDialog.java
*
* Copyright: 2002-2011 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.2 (2011-02-23)
*
*/
package org.openoffice.da.comp.w2lcommon.helper;
import com.sun.star.awt.XDialog;
import com.sun.star.awt.XDialogProvider2;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
/** This is a simple helper class to display and access a dialog based on an
* XML description (using the DialogProvider2 service).
* Unlike DialogBase, this class creates a dialog <em>without</em> event handlers.
*
* TODO: Use this class in ConfigurationDialogBase
*/
public class SimpleDialog {
private XDialog xDialog;
private DialogAccess dialogAccess;
/** Create a new dialog
*
* @param xContext the component context from which to get the service manager
* @param sDialogPath the path to the dialog
*/
public SimpleDialog(XComponentContext xContext, String sDialogPath) {
XMultiComponentFactory xMCF = xContext.getServiceManager();
try {
Object provider = xMCF.createInstanceWithContext("com.sun.star.awt.DialogProvider2", xContext);
XDialogProvider2 xDialogProvider = (XDialogProvider2) UnoRuntime.queryInterface(XDialogProvider2.class, provider);
String sDialogUrl = "vnd.sun.star.script:"+sDialogPath+"?location=application";
xDialog = xDialogProvider.createDialog(sDialogUrl);
dialogAccess = new DialogAccess(xDialog);
} catch (com.sun.star.uno.Exception e) {
xDialog = null;
dialogAccess = null;
}
}
/** Get the UNO dialog
*
* @return the dialog, or null if creation failed
*/
public XDialog getDialog() {
return xDialog;
}
/** Get access to the controls of the dialog
*
* @return the control access helper, or null if creation failed
*/
public DialogAccess getControls() {
return dialogAccess;
}
}

View file

@ -1,54 +0,0 @@
/************************************************************************
*
* StreamGobbler.java
*
* Copyright: 2002-2015 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-04-05)
*
*/
package org.openoffice.da.comp.w2lcommon.helper;
import java.io.*;
public class StreamGobbler extends Thread {
InputStream is;
String type;
public StreamGobbler(InputStream is, String type) {
this.is = is;
this.type = type;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
//String line=null;
//while ( (line = br.readLine()) != null) {
while ( br.readLine() != null) {
// Do nothing...
}
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}

View file

@ -1,142 +0,0 @@
/************************************************************************
*
* StyleNameProvider.java
*
* Copyright: 2002-2009 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.2 (2009-11-08)
*
*/
package org.openoffice.da.comp.w2lcommon.helper;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import com.sun.star.beans.UnknownPropertyException;
import com.sun.star.beans.XPropertySet;
import com.sun.star.container.NoSuchElementException;
import com.sun.star.container.XNameAccess;
import com.sun.star.container.XNameContainer;
import com.sun.star.frame.XController;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XModel;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.style.XStyleFamiliesSupplier;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
/** This class provides access to the style names and localized style names of the current document
*/
public class StyleNameProvider {
private Map<String,Map<String,String>> displayNameCollection;
private Map<String,Map<String,String>> internalNameCollection;
/** Construct a new <code>StyleNameProvider</code>
*
* @param xContext the componemt context to get the desktop from
*/
public StyleNameProvider(XComponentContext xContext) {
displayNameCollection = new HashMap<String,Map<String,String>>();
internalNameCollection = new HashMap<String,Map<String,String>>();
// Get the model for the current frame
XModel xModel = null;
try {
Object desktop = xContext.getServiceManager().createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
XDesktop xDesktop = (XDesktop)UnoRuntime.queryInterface(XDesktop.class, desktop);
XController xController = xDesktop.getCurrentFrame().getController();
if (xController!=null) {
xModel = xController.getModel();
}
}
catch (Exception e) {
// do nothing
}
// Get the styles from the model
if (xModel!=null) {
XStyleFamiliesSupplier xSupplier = (XStyleFamiliesSupplier) UnoRuntime.queryInterface(
XStyleFamiliesSupplier.class, xModel);
if (xSupplier!=null) {
XNameAccess xFamilies = xSupplier.getStyleFamilies();
String[] sFamilyNames = xFamilies.getElementNames();
for (String sFamilyName : sFamilyNames) {
Map<String,String> displayNames = new HashMap<String,String>();
displayNameCollection.put(sFamilyName, displayNames);
Map<String,String> internalNames = new HashMap<String,String>();
internalNameCollection.put(sFamilyName, internalNames);
try {
XNameContainer xFamily = (XNameContainer) UnoRuntime.queryInterface(
XNameContainer.class, xFamilies.getByName(sFamilyName));
if (xFamily!=null) {
String[] sStyleNames = xFamily.getElementNames();
for (String sStyleName : sStyleNames) {
XPropertySet xProps = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, xFamily.getByName(sStyleName));
if (xProps!=null) {
String sDisplayName = (String) xProps.getPropertyValue("DisplayName");
displayNames.put(sStyleName, sDisplayName);
internalNames.put(sDisplayName, sStyleName);
}
}
}
}
catch (WrappedTargetException e) {
// ignore
}
catch (NoSuchElementException e) {
// will not happen
}
catch (UnknownPropertyException e) {
// will not happen
}
}
}
}
}
/** Get the mapping of internal names to display names for a style family
*
* @param sFamily the style family (for text documents this should be CharacterStyles, ParagraphStyles, FrameStyles, PageStyles or NumberingStyles)
* @return a read only map from internal names to display names, or null if the family is not known to the provider
*/
public Map<String,String> getDisplayNames(String sFamily) {
if (displayNameCollection.containsKey(sFamily)) {
return Collections.unmodifiableMap(displayNameCollection.get(sFamily));
}
return null;
}
/** Get the mapping of display names to internal names for a style family
*
* @param sFamily the style family (for text documents this should be CharacterStyles, ParagraphStyles, FrameStyles, PageStyles or NumberingStyles)
* @return a read only map from display names to internal names, or null if the family is not known to the provider
*/
public Map<String,String> getInternalNames(String sFamily) {
if (internalNameCollection.containsKey(sFamily)) {
return Collections.unmodifiableMap(internalNameCollection.get(sFamily));
}
return null;
}
}

View file

@ -1,99 +0,0 @@
/************************************************************************
*
* XPropertySetHelper.java
*
* Copyright: 2002-2008 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.0 (2008-07-21)
*
*/
package org.openoffice.da.comp.w2lcommon.helper;
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;
/** Helper class providing staic convenience methods for accesing an XPropertySet
* The helpers will fail silently if names or data is provided, but the user is expected to
* apply them with correct data only...
*/
public class XPropertySetHelper {
public static Object getPropertyValue(XPropertySet xProps, String sName) {
try {
return xProps.getPropertyValue(sName);
}
catch (UnknownPropertyException e) {
return null;
}
catch (WrappedTargetException e) {
return null;
}
}
public static 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) {
}
}
public static String getPropertyValueAsString(XPropertySet xProps, String sName) {
Object value = getPropertyValue(xProps,sName);
return value instanceof String ? (String) value : "";
}
public static int getPropertyValueAsInteger(XPropertySet xProps, String sName) {
Object value = getPropertyValue(xProps,sName);
return value instanceof Integer ? ((Integer) value).intValue() : 0;
}
public static void setPropertyValue(XPropertySet xProps, String sName, int nValue) {
setPropertyValue(xProps,sName,new Integer(nValue));
}
public static short getPropertyValueAsShort(XPropertySet xProps, String sName) {
Object value = getPropertyValue(xProps,sName);
return value instanceof Short ? ((Short) value).shortValue() : 0;
}
public static void setPropertyValue(XPropertySet xProps, String sName, short nValue) {
setPropertyValue(xProps,sName,new Short(nValue));
}
public static boolean getPropertyValueAsBoolean(XPropertySet xProps, String sName) {
Object value = getPropertyValue(xProps,sName);
return value instanceof Boolean ? ((Boolean) value).booleanValue() : false;
}
public static void setPropertyValue(XPropertySet xProps, String sName, boolean bValue) {
setPropertyValue(xProps,sName,new Boolean(bValue));
}
}

View file

@ -1,588 +0,0 @@
/************************************************************************
*
* ConfigurationDialog.java
*
* Copyright: 2002-2015 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-06-16)
*
*/
package org.openoffice.da.comp.writer2xhtml;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;
import org.openoffice.da.comp.w2lcommon.filter.ConfigurationDialogBase;
import org.openoffice.da.comp.w2lcommon.helper.DialogAccess;
import com.sun.star.container.NoSuchElementException;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.ucb.CommandAbortedException;
import com.sun.star.uno.Exception;
import com.sun.star.uno.XComponentContext;
import w2phtml.api.Converter;
import w2phtml.api.ConverterFactory;
public class ConfigurationDialog extends ConfigurationDialogBase implements XServiceInfo {
private String sResourceDirName;
// Implement the interface XServiceInfo
/** The component will be registered under this name.
*/
public static String __serviceName = "org.openoffice.da.writer2xhtml.ConfigurationDialog";
/** The component should also have an implementation name.
*/
public static String __implementationName = "org.openoffice.da.comp.writer2xhtml.ConfigurationDialog";
public boolean supportsService(String sServiceName) {
return sServiceName.equals(__serviceName);
}
public String getImplementationName() {
return __implementationName;
}
public String[] getSupportedServiceNames() {
String[] sSupportedServiceNames = { __serviceName };
return sSupportedServiceNames;
}
// Configure the base class
@Override protected String getMIMEType() { return "text/html"; }
@Override protected String getDialogLibraryName() { return "w2phtml2"; }
@Override protected String getConfigFileName() { return "writer2xhtml.xml"; }
/** Construct a new <code>ConfigurationDialog</code> */
public ConfigurationDialog(XComponentContext xContext) {
super(xContext);
// Create the resource dir name
try {
sResourceDirName = xPathSub.substituteVariables("$(user)/writer2xhtml-resources", false);
}
catch (NoSuchElementException e) {
sResourceDirName = "writer2xhtml-resources";
}
pageHandlers.put("General", new GeneralHandler());
pageHandlers.put("Template", new TemplateHandler());
pageHandlers.put("Stylesheets", new StylesheetsHandler());
pageHandlers.put("Formatting", new FormattingHandler());
pageHandlers.put("Styles1", new Styles1Handler());
pageHandlers.put("Styles2", new Styles2Handler());
pageHandlers.put("Formatting", new FormattingHandler());
pageHandlers.put("Content", new ContentHandler());
}
// Implement remaining method from XContainerWindowEventHandler
public String[] getSupportedMethodNames() {
String[] sNames = { "EncodingChange", // General
"CustomTemplateChange", "LoadTemplateClick", "TemplateKeyup", // Template
"UseCustomStylesheetChange", "IncludeCustomStylesheetClick", "LoadStylesheetClick",
"NewResourceClick", "DeleteResourceClick", // Stylesheet
"StyleFamilyChange", "StyleNameChange", "NewStyleClick", "DeleteStyleClick", "LoadDefaultsClick" // Styles1
};
return sNames;
}
// the page handlers
private final String[] sCharElements = { "span", "abbr", "acronym", "b", "big", "cite", "code", "del", "dfn", "em", "i",
"ins", "kbd", "samp", "small", "strong", "sub", "sup", "tt", "var", "q" };
private class GeneralHandler extends PageHandler {
private final String[] sEncodingValues = { "UTF-8", "UTF-16", "ISO-8859-1", "US-ASCII" };
@Override protected void setControls(DialogAccess dlg) {
checkBoxFromConfig(dlg, "NoDoctype", "no_doctype");
listBoxFromConfig(dlg, "Encoding", "encoding", sEncodingValues, (short) 0);
checkBoxFromConfig(dlg, "AddBOM", "add_bom");
if ("true".equals(config.getOption("hexadecimal_entities"))) {
dlg.setListBoxSelectedItem("HexadecimalEntities", (short) 0);
}
else {
dlg.setListBoxSelectedItem("HexadecimalEntities", (short) 1);
}
checkBoxFromConfig(dlg, "UseNamedEntities", "use_named_entities");
checkBoxFromConfig(dlg, "Multilingual", "multilingual");
checkBoxFromConfig(dlg, "PrettyPrint", "pretty_print");
encodingChange(dlg);
}
@Override protected void getControls(DialogAccess dlg) {
checkBoxToConfig(dlg, "NoDoctype", "no_doctype");
listBoxToConfig(dlg, "Encoding", "encoding", sEncodingValues);
checkBoxToConfig(dlg, "AddBOM", "add_bom");
config.setOption("hexadecimal_entities", Boolean.toString(dlg.getListBoxSelectedItem("HexadecimalEntities")==(short)0));
checkBoxToConfig(dlg, "UseNamedEntities", "use_named_entities");
checkBoxToConfig(dlg, "Multilingual", "multilingual");
checkBoxToConfig(dlg, "PrettyPrint", "pretty_print");
}
@Override protected boolean handleEvent(DialogAccess dlg, String sMethod) {
if (sMethod.equals("EncodingChange")) {
encodingChange(dlg);
return true;
}
return false;
}
private void encodingChange(DialogAccess dlg) {
int nEncoding = dlg.getListBoxSelectedItem("Encoding");
dlg.setControlEnabled("AddBOM", nEncoding==0); // Only for UTF-8
dlg.setControlEnabled("HexadecimalEntitiesLabel", nEncoding>1); // Not for UNICODE
dlg.setControlEnabled("HexadecimalEntities", nEncoding>1); // Not for UNICODE
}
}
private class TemplateHandler extends CustomFileHandler {
protected String getSuffix() {
return "Template";
}
protected String getFileName() {
return "writer2xhtml-template.xhtml";
}
protected void useCustomInner(DialogAccess dlg, boolean bEnable) {
dlg.setControlEnabled("TestTemplateLabel", bEnable);
dlg.setControlEnabled("ContentIdLabel", bEnable);
dlg.setControlEnabled("ContentId", bEnable);
dlg.setControlEnabled("HeaderIdLabel", bEnable);
dlg.setControlEnabled("HeaderId", bEnable);
dlg.setControlEnabled("FooterIdLabel", bEnable);
dlg.setControlEnabled("FooterId", bEnable);
dlg.setControlEnabled("PanelIdLabel", bEnable);
dlg.setControlEnabled("PanelId", bEnable);
}
@Override protected void setControls(DialogAccess dlg) {
super.setControls(dlg);
String[] sCustomIds = config.getOption("template_ids").split(",");
if (sCustomIds.length>0) { dlg.setComboBoxText("ContentId", sCustomIds[0]); }
if (sCustomIds.length>1) { dlg.setComboBoxText("HeaderId", sCustomIds[1]); }
if (sCustomIds.length>2) { dlg.setComboBoxText("FooterId", sCustomIds[2]); }
if (sCustomIds.length>3) { dlg.setComboBoxText("PanelId", sCustomIds[3]); }
testTemplate(dlg);
}
@Override protected void getControls(DialogAccess dlg) {
super.getControls(dlg);
config.setOption("template_ids",
dlg.getComboBoxText("ContentId").trim()+","+
dlg.getComboBoxText("HeaderId").trim()+","+
dlg.getComboBoxText("FooterId").trim()+","+
dlg.getComboBoxText("PanelId").trim());
}
@Override protected boolean handleEvent(DialogAccess dlg, String sMethod) {
if (super.handleEvent(dlg, sMethod)) {
return true;
}
if (sMethod.equals("TemplateKeyup")) {
testTemplate(dlg);
return true;
}
return false;
}
@Override protected void loadCustomClick(DialogAccess dlg) {
super.loadCustomClick(dlg);
testTemplate(dlg);
}
private void testTemplate(DialogAccess dlg) {
Converter converter = ConverterFactory.createConverter("text/html");
String sTemplate = dlg.getTextFieldText("CustomTemplate").trim();
if (sTemplate.length()>0) { // Only display error message if there is content
try {
converter.readTemplate(new ByteArrayInputStream(sTemplate.getBytes()));
dlg.setLabelText("TestTemplateLabel", "");
} catch (IOException e) {
dlg.setLabelText("TestTemplateLabel", "ERROR: "+e.getMessage());
}
}
else {
dlg.setLabelText("TestTemplateLabel", "");
}
}
}
private class StylesheetsHandler extends CustomFileHandler {
protected String getSuffix() {
return "Stylesheet";
}
protected String getFileName() {
return "writer2xhtml-styles.css";
}
protected void useCustomInner(DialogAccess dlg, boolean bEnable) {
dlg.setControlEnabled("ResourceLabel", bEnable);
dlg.setControlEnabled("Resources", bEnable);
dlg.setControlEnabled("NewResourceButton", bEnable);
dlg.setControlEnabled("DeleteResourceButton", bEnable);
updateResources(dlg);
}
@Override protected void setControls(DialogAccess dlg) {
super.setControls(dlg);
dlg.setCheckBoxStateAsBoolean("LinkCustomStylesheet", config.getOption("custom_stylesheet").length()>0);
textFieldFromConfig(dlg, "CustomStylesheetURL", "custom_stylesheet");
linkCustomStylesheetChange(dlg);
updateResources(dlg);
}
@Override protected void getControls(DialogAccess dlg) {
super.getControls(dlg);
if (dlg.getCheckBoxStateAsBoolean("LinkCustomStylesheet")) {
textFieldToConfig(dlg, "CustomStylesheetURL", "custom_stylesheet");
}
else {
config.setOption("custom_stylesheet", "");
}
}
@Override protected boolean handleEvent(DialogAccess dlg, String sMethod) {
if (super.handleEvent(dlg, sMethod)) {
return true;
}
if (sMethod.equals("LinkCustomStylesheetChange")) {
linkCustomStylesheetChange(dlg);
return true;
}
else if (sMethod.equals("NewResourceClick")) {
newResourceClick(dlg);
return true;
}
else if (sMethod.equals("DeleteResourceClick")) {
deleteResourceClick(dlg);
return true;
}
return false;
}
private void linkCustomStylesheetChange(DialogAccess dlg) {
boolean bLinkCustomStylesheet = dlg.getCheckBoxStateAsBoolean("LinkCustomStylesheet");
dlg.setControlEnabled("CustomStylesheetURLLabel", bLinkCustomStylesheet);
dlg.setControlEnabled("CustomStylesheetURL", bLinkCustomStylesheet);
}
private void newResourceClick(DialogAccess dlg) {
String[] sFileNames=filePicker.getPaths();
if (sFileNames!=null) {
createResourceDir();
for (String sFileName : sFileNames) {
String sBaseFileName = sFileName.substring(sFileName.lastIndexOf('/')+1);
try {
String sTargetFileName = sResourceDirName+"/"+sBaseFileName;
if (fileExists(sTargetFileName)) { killFile(sTargetFileName); }
sfa2.copy(sFileName, sTargetFileName);
} catch (CommandAbortedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
updateResources(dlg);
}
}
private void deleteResourceClick(DialogAccess dlg) {
int nItem = dlg.getListBoxSelectedItem("Resources");
if (nItem>=0) {
String sFileName = dlg.getListBoxStringItemList("Resources")[nItem];
if (deleteItem(sFileName)) {
killFile(sResourceDirName+"/"+sFileName);
updateResources(dlg);
}
}
}
private void updateResources(DialogAccess dlg) {
createResourceDir();
try {
String[] sFiles = sfa2.getFolderContents(sResourceDirName, false); // do not include folders
int nCount = sFiles.length;
for (int i=0; i<nCount; i++) {
sFiles[i] = sFiles[i].substring(sFiles[i].lastIndexOf('/')+1);
}
dlg.setListBoxStringItemList("Resources", sFiles);
} catch (CommandAbortedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void createResourceDir() {
try {
if (!sfa2.isFolder(sResourceDirName)) {
sfa2.createFolder(sResourceDirName);
}
} catch (CommandAbortedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private class Styles1Handler extends StylesPageHandler {
private final String[] sXhtmlFamilyNames = { "text", "paragraph", "heading", "list", "frame" };
private final String[] sXhtmlOOoFamilyNames = { "CharacterStyles", "ParagraphStyles", "ParagraphStyles", "NumberingStyles", "FrameStyles" };
private final String[] sParElements = { "p", "h1", "h2", "h3", "h4", "h5", "h6", "address", "dd", "dt", "pre" };
private final String[] sParBlockElements = { "div", "blockquote", "dl" };
private final String[] sEmpty = { };
private String[][] sElements = new String[5][];
private String[][] sBlockElements = new String[5][];
protected Styles1Handler() {
super(5);
sFamilyNames = sXhtmlFamilyNames;
sOOoFamilyNames = sXhtmlOOoFamilyNames;
sElements[0] = sCharElements;
sElements[1] = sParElements;
sElements[2] = sParElements;
sElements[3] = sEmpty;
sElements[4] = sEmpty;
sBlockElements[0] = sEmpty;
sBlockElements[1] = sParBlockElements;
sBlockElements[2] = sParBlockElements;
sBlockElements[3] = sEmpty;
sBlockElements[4] = sEmpty;
}
protected String getDefaultConfigName() {
return "cleanxhtml.xml";
}
protected void setControls(DialogAccess dlg, Map<String,String> attr) {
if (!attr.containsKey("element")) { attr.put("element", ""); }
if (!attr.containsKey("css")) { attr.put("css", ""); }
dlg.setComboBoxText("Element", attr.get("element"));
dlg.setTextFieldText("Css", none2empty(attr.get("css")));
if (nCurrentFamily==1 || nCurrentFamily==2) {
if (!attr.containsKey("before")) { attr.put("before", ""); }
if (!attr.containsKey("after")) { attr.put("after", ""); }
dlg.setTextFieldText("Before", attr.get("before"));
dlg.setTextFieldText("After", attr.get("after"));
}
else {
dlg.setTextFieldText("Before", "");
dlg.setTextFieldText("After", "");
}
if (nCurrentFamily==1 || nCurrentFamily==2) {
if (!attr.containsKey("block-element")) { attr.put("block-element", ""); }
if (!attr.containsKey("block-css")) { attr.put("block-css", ""); }
dlg.setComboBoxText("BlockElement", attr.get("block-element"));
dlg.setTextFieldText("BlockCss", none2empty(attr.get("block-css")));
}
else {
dlg.setComboBoxText("BlockElement", "");
dlg.setTextFieldText("BlockCss", "");
}
}
protected void getControls(DialogAccess dlg, Map<String,String> attr) {
attr.put("element", dlg.getComboBoxText("Element"));
attr.put("css", empty2none(dlg.getTextFieldText("Css")));
if (nCurrentFamily==1 || nCurrentFamily==2) {
attr.put("before", dlg.getTextFieldText("Before"));
attr.put("after", dlg.getTextFieldText("After"));
}
if (nCurrentFamily==1 || nCurrentFamily==2) {
attr.put("block-element", dlg.getComboBoxText("BlockElement"));
attr.put("block-css", empty2none(dlg.getTextFieldText("BlockCss")));
}
}
protected void clearControls(DialogAccess dlg) {
dlg.setComboBoxText("Element", "");
dlg.setTextFieldText("Css", "");
dlg.setTextFieldText("Before", "");
dlg.setTextFieldText("After", "");
dlg.setComboBoxText("BlockElement", "");
dlg.setTextFieldText("BlockCss", "");
}
protected void prepareControls(DialogAccess dlg, boolean bHasMappings) {
dlg.setListBoxStringItemList("Element", sElements[nCurrentFamily]);
dlg.setListBoxStringItemList("BlockElement", sBlockElements[nCurrentFamily]);
dlg.setControlEnabled("ElementLabel", bHasMappings && nCurrentFamily<=2);
dlg.setControlEnabled("Element", bHasMappings && nCurrentFamily<=2);
dlg.setControlEnabled("CssLabel", bHasMappings);
dlg.setControlEnabled("Css", bHasMappings);
dlg.setControlEnabled("BeforeLabel", bHasMappings && (nCurrentFamily==1 || nCurrentFamily==2));
dlg.setControlEnabled("Before", bHasMappings && (nCurrentFamily==1 || nCurrentFamily==2));
dlg.setControlEnabled("AfterLabel", bHasMappings && (nCurrentFamily==1 || nCurrentFamily==2));
dlg.setControlEnabled("After", bHasMappings && (nCurrentFamily==1 || nCurrentFamily==2));
dlg.setControlEnabled("BlockElementLabel", bHasMappings && (nCurrentFamily==1 || nCurrentFamily==2));
dlg.setControlEnabled("BlockElement", bHasMappings && (nCurrentFamily==1 || nCurrentFamily==2));
dlg.setControlEnabled("BlockCssLabel", bHasMappings && (nCurrentFamily==1 || nCurrentFamily==2));
dlg.setControlEnabled("BlockCss", bHasMappings && (nCurrentFamily==1 || nCurrentFamily==2));
}
}
private class Styles2Handler extends AttributePageHandler {
private String[] sXhtmlAttributeNames = { "bold", "italics", "fixed", "superscript", "subscript", "underline", "overstrike" };
public Styles2Handler() {
sAttributeNames = sXhtmlAttributeNames;
}
@Override public void setControls(DialogAccess dlg) {
super.setControls(dlg);
textFieldFromConfig(dlg,"TabstopStyle","tabstop_style");
}
@Override public void getControls(DialogAccess dlg) {
super.getControls(dlg);
textFieldToConfig(dlg,"TabstopStyle","tabstop_style");
}
protected void setControls(DialogAccess dlg, Map<String,String> attr) {
if (!attr.containsKey("element")) { attr.put("element", ""); }
if (!attr.containsKey("css")) { attr.put("css", ""); }
dlg.setListBoxStringItemList("Element", sCharElements);
dlg.setComboBoxText("Element", attr.get("element"));
dlg.setTextFieldText("Css", none2empty(attr.get("css")));
}
protected void getControls(DialogAccess dlg, Map<String,String> attr) {
attr.put("element", dlg.getComboBoxText("Element"));
attr.put("css", empty2none(dlg.getTextFieldText("Css")));
}
protected void prepareControls(DialogAccess dlg, boolean bEnable) {
dlg.setControlEnabled("ElementLabel", bEnable);
dlg.setControlEnabled("Element", bEnable);
dlg.setControlEnabled("CssLabel", bEnable);
dlg.setControlEnabled("Css", bEnable);
}
}
private class FormattingHandler extends PageHandler {
private final String[] sExportValues = { "convert_all", "ignore_styles", "ignore_hard", "ignore_all" };
private final String[] sListExportValues = { "css1", "css1_hack", "hard_labels" };
@Override protected void setControls(DialogAccess dlg) {
listBoxFromConfig(dlg, "Formatting", "formatting", sExportValues, (short) 0);
listBoxFromConfig(dlg, "FrameFormatting", "frame_formatting", sExportValues, (short) 0);
// OOo does not support styles for sections and tables, hence this simplified variant
dlg.setCheckBoxStateAsBoolean("SectionFormatting",
config.getOption("section_formatting").equals("convert_all") ||
config.getOption("section_formatting").equals("ignore_styles"));
dlg.setCheckBoxStateAsBoolean("TableFormatting",
config.getOption("table_formatting").equals("convert_all") ||
config.getOption("table_formatting").equals("ignore_styles"));
checkBoxFromConfig(dlg, "IgnoreTableDimensions", "ignore_table_dimensions");
listBoxFromConfig(dlg, "ListFormatting", "list_formatting", sListExportValues, (short) 0);
textFieldFromConfig(dlg, "MaxWidth", "max_width");
checkBoxFromConfig(dlg, "SeparateStylesheet", "separate_stylesheet");
}
@Override protected void getControls(DialogAccess dlg) {
listBoxToConfig(dlg, "Formatting", "formatting", sExportValues);
listBoxToConfig(dlg, "FrameFormatting", "frame_formatting", sExportValues);
config.setOption("section_formatting", dlg.getCheckBoxStateAsBoolean("SectionFormatting") ? "convert_all" : "ignore_all");
config.setOption("table_formatting", dlg.getCheckBoxStateAsBoolean("TableFormatting") ? "convert_all" : "ignore_all");
checkBoxToConfig(dlg, "IgnoreTableDimensions", "ignore_table_dimensions");
listBoxToConfig(dlg, "ListFormatting", "list_formatting", sListExportValues);
textFieldToConfig(dlg, "MaxWidth", "max_width");
checkBoxToConfig(dlg, "SeparateStylesheet", "separate_stylesheet");
}
@Override protected boolean handleEvent(DialogAccess dlg, String sMethod) {
return false;
}
}
private class ContentHandler extends PageHandler {
private final String[] sFormulaValues = { "image+starmath", "image+latex", "starmath", "latex" };
@Override protected void setControls(DialogAccess dlg) {
listBoxFromConfig(dlg, "Formulas", "formulas", sFormulaValues, (short) 0);
textFieldFromConfig(dlg, "EndnotesHeading", "endnotes_heading");
textFieldFromConfig(dlg, "FootnotesHeading", "footnotes_heading");
checkBoxFromConfig(dlg, "EmbedSvg", "embed_svg");
checkBoxFromConfig(dlg, "EmbedImg", "embed_img");
}
@Override protected void getControls(DialogAccess dlg) {
listBoxToConfig(dlg, "Formulas", "formulas", sFormulaValues);
textFieldToConfig(dlg, "EndnotesHeading", "endnotes_heading");
textFieldToConfig(dlg, "FootnotesHeading", "footnotes_heading");
checkBoxToConfig(dlg, "EmbedSvg", "embed_svg");
checkBoxToConfig(dlg, "EmbedImg", "embed_img");
}
@Override protected boolean handleEvent(DialogAccess dlg, String sMethod) {
return false;
}
}
private String none2empty(String s) {
return s.equals("(none)") ? "" : s;
}
private String empty2none(String s) {
String t = s.trim();
return t.length()==0 ? "(none)" : t;
}
}

View file

@ -1,47 +0,0 @@
/************************************************************************
*
* Epub3OptionsDialog.java
*
* Copyright: 2002-2016 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-05-05)
*
*/
package org.openoffice.da.comp.writer2xhtml;
import com.sun.star.uno.XComponentContext;
/** This class provides a UNO component which implements a filter UI for the
* EPUB 3 export. In this version the option to include NCX is enabled.
*/
public class Epub3OptionsDialog extends EpubOptionsDialog {
/** The component will be registered under this name.
*/
public static String __serviceName = "org.openoffice.da.writer2xhtml.Epub3OptionsDialog";
/** The component should also have an implementation name.
*/
public static String __implementationName = "org.openoffice.da.comp.writer2xhtml.Epub3OptionsDialog";
/** Create a new Epub3OptionsDialog */
public Epub3OptionsDialog(XComponentContext xContext) {
super(xContext);
}
}

View file

@ -1,707 +0,0 @@
/************************************************************************
*
* EpubMetadataDialog.java
*
* Copyright: 2002-2011 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.2 (2011-07-20)
*
*/
package org.openoffice.da.comp.writer2xhtml;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.openoffice.da.comp.w2lcommon.helper.DialogBase;
import org.openoffice.da.comp.w2lcommon.helper.SimpleDialog;
import com.sun.star.awt.XDialog;
import com.sun.star.beans.IllegalTypeException;
import com.sun.star.beans.NotRemoveableException;
import com.sun.star.beans.Property;
import com.sun.star.beans.PropertyExistException;
import com.sun.star.beans.PropertyVetoException;
import com.sun.star.beans.UnknownPropertyException;
import com.sun.star.beans.XPropertyContainer;
import com.sun.star.beans.XPropertySet;
import com.sun.star.document.XDocumentProperties;
import com.sun.star.document.XDocumentPropertiesSupplier;
import com.sun.star.frame.XDesktop;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.WrappedTargetException;
import com.sun.star.lang.XComponent;
import com.sun.star.ui.dialogs.ExecutableDialogResults;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.util.DateTime;
import w2phtml.util.CSVList;
import w2phtml.util.Misc;
// TODO: Create the UNO helper class DocumentPropertiesAccess
/** This class provides a UNO component which implements a custom metadata editor UI for the EPUB export
*/
public class EpubMetadataDialog extends DialogBase {
// Author data
private class AuthorInfo {
String sName = "";
boolean isCreator = true;
String sRole = "";
}
// Date data
private class DateInfo {
int nDate = 0;
String sEvent = "";
}
// All the user defined properties we handle
private static final String IDENTIFIER="Identifier";
private static final String CREATOR="Creator";
private static final String CONTRIBUTOR="Contributor";
private static final String DATE="Date";
private static final String PUBLISHER="Publisher";
private static final String TYPE="Type";
private static final String FORMAT="Format";
private static final String SOURCE="Source";
private static final String RELATION="Relation";
private static final String COVERAGE="Coverage";
private static final String RIGHTS="Rights";
private static final String[] sRoles = {"", "adp", "ann", "arr", "art", "asn", "aut", "aqt", "aft", "aui", "ant", "bkp",
"clb", "cmm", "dsr", "edt", "ill", "lyr", "mdc", "mus", "nrt", "oth", "pht", "prt", "red", "rev", "spn", "ths", "trc", "trl"};
private static HashMap<String,Short> backRoles;
static {
backRoles = new HashMap<String,Short>();
int nCount = sRoles.length;
for (short i=0; i<nCount; i++) {
backRoles.put(sRoles[i], i);
}
}
// Access to the document properties
private XDocumentProperties xDocumentProperties=null;
private XPropertyContainer xUserProperties=null;
private XPropertySet xUserPropertySet=null;
// Author and date bookkeeping
private Vector<AuthorInfo> authors = new Vector<AuthorInfo>();
private Vector<DateInfo> dates = new Vector<DateInfo>();
// Number formatter
private NumberFormat formatter = new DecimalFormat("00");
// Pattern matcher for dates
Pattern datePattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
public EpubMetadataDialog(XComponentContext xContext) {
super(xContext);
}
/** The component will be registered under this name.
*/
public static String __serviceName = "org.openoffice.da.writer2xhtml.EpubMetadataDialog";
/** The component should also have an implementation name.
*/
public static String __implementationName = "org.openoffice.da.comp.writer2xhtml.EpubMetadataDialog";
// --------------------------------------------------
// Ensure that the super can find us :-)
@Override public String getDialogLibraryName() {
return "w2phtml2";
}
@Override public String getDialogName() {
return "EpubMetadata";
}
// --------------------------------------------------
// Implement the interface XDialogEventHandler
@Override public boolean callHandlerMethod(XDialog xDialog, Object event, String sMethod) {
if (sMethod.equals("UseCustomIdentifierChange")) {
return useCustomIdentifierChange();
}
else if (sMethod.equals("AuthorAddClick")) {
return authorAddclick();
}
else if (sMethod.equals("AuthorModifyClick")) {
return authorModifyclick();
}
else if (sMethod.equals("AuthorDeleteClick")) {
return authorDeleteclick();
}
else if (sMethod.equals("AuthorUpClick")) {
return authorUpclick();
}
else if (sMethod.equals("AuthorDownClick")) {
return authorDownclick();
}
else if (sMethod.equals("DateAddClick")) {
return dateAddClick();
}
else if (sMethod.equals("DateModifyClick")) {
return dateModifyClick();
}
else if (sMethod.equals("DateDeleteClick")) {
return dateDeleteClick();
}
else if (sMethod.equals("DateUpClick")) {
return dateUpClick();
}
else if (sMethod.equals("DateDownClick")) {
return dateDownClick();
}
return false;
}
@Override public String[] getSupportedMethodNames() {
String[] sNames = { "UseCustomIdentifierChange",
"AuthorAddClick", "AuthorModifyClick", "AuthorDeleteClick", "AuthorUpClick", "AuthorDownClick",
"DataAddClick", "DateModifyClick", "DateDeleteClick", "DateUpClick", "DateDownClick"};
return sNames;
}
private boolean useCustomIdentifierChange() {
boolean bEnabled = getCheckBoxStateAsBoolean("UseCustomIdentifier");
setControlEnabled("IdentifierLabel",bEnabled);
setControlEnabled("Identifier",bEnabled);
setControlEnabled("IdentifierTypeLabel",bEnabled);
setControlEnabled("IdentifierType",bEnabled);
return true;
}
private boolean authorAddclick() {
SimpleDialog dialog = new SimpleDialog(xContext,"w2phtml2.AuthorDialog");
if (dialog.getDialog()!=null) {
dialog.getControls().setListBoxSelectedItem("Type", (short) 0);
dialog.getControls().setListBoxSelectedItem("Role", (short) 0);
if (dialog.getDialog().execute()==ExecutableDialogResults.OK) {
AuthorInfo author = new AuthorInfo();
author.sName = dialog.getControls().getTextFieldText("Author");
author.sRole = sRoles[dialog.getControls().getListBoxSelectedItem("Role")];
author.isCreator = dialog.getControls().getListBoxSelectedItem("Type")==0;
authors.add(author);
updateAuthorList((short) (authors.size()-1));
}
dialog.getDialog().endExecute();
}
return true;
}
private boolean authorModifyclick() {
short nIndex = getListBoxSelectedItem("Authors");
AuthorInfo author = authors.get(nIndex);
SimpleDialog dialog = new SimpleDialog(xContext,"w2phtml2.AuthorDialog");
if (dialog.getDialog()!=null) {
dialog.getControls().setTextFieldText("Author", author.sName);
dialog.getControls().setListBoxSelectedItem("Type", author.isCreator ? (short)0 : (short) 1);
dialog.getControls().setListBoxSelectedItem("Role", backRoles.containsKey(author.sRole)? backRoles.get(author.sRole) : (short)0);
if (dialog.getDialog().execute()==ExecutableDialogResults.OK) {
author.sName = dialog.getControls().getTextFieldText("Author");
author.sRole = sRoles[dialog.getControls().getListBoxSelectedItem("Role")];
author.isCreator = dialog.getControls().getListBoxSelectedItem("Type")==0;
updateAuthorList(nIndex);
}
dialog.getDialog().endExecute();
}
return true;
}
private boolean authorDeleteclick() {
if (authors.size()>0) {
SimpleDialog dialog = new SimpleDialog(xContext,"w2phtml2.DeleteDialog");
if (dialog.getDialog()!=null) {
short nIndex = getListBoxSelectedItem("Authors");
String sLabel = dialog.getControls().getLabelText("DeleteLabel");
sLabel = sLabel.replaceAll("%s", authors.get(nIndex).sName);
dialog.getControls().setLabelText("DeleteLabel", sLabel);
if (dialog.getDialog().execute()==ExecutableDialogResults.OK) {
authors.remove(nIndex);
updateAuthorList(nIndex<authors.size() ? (short) nIndex : (short) (nIndex-1));
}
}
}
return true;
}
private boolean authorUpclick() {
short nIndex = getListBoxSelectedItem("Authors");
if (nIndex>0) {
AuthorInfo author = authors.get(nIndex);
authors.set(nIndex, authors.get(nIndex-1));
authors.set(nIndex-1, author);
updateAuthorList((short) (nIndex-1));
}
return true;
}
private boolean authorDownclick() {
short nIndex = getListBoxSelectedItem("Authors");
if (nIndex+1<authors.size()) {
AuthorInfo author = authors.get(nIndex);
authors.set(nIndex, authors.get(nIndex+1));
authors.set(nIndex+1, author);
updateAuthorList((short) (nIndex+1));
}
return true;
}
private boolean dateAddClick() {
SimpleDialog dialog = new SimpleDialog(xContext,"w2phtml2.DateDialog");
if (dialog.getDialog()!=null) {
dialog.getControls().setDateFieldValue("Date", datetime2int(xDocumentProperties.getModificationDate()));
if (dialog.getDialog().execute()==ExecutableDialogResults.OK) {
DateInfo date = new DateInfo();
date.nDate = dialog.getControls().getDateFieldValue("Date");
date.sEvent = dialog.getControls().getTextFieldText("Event").trim();
dates.add(date);
updateDateList((short) (dates.size()-1));
}
dialog.getDialog().endExecute();
}
return true;
}
private boolean dateModifyClick() {
short nIndex = getListBoxSelectedItem("Dates");
DateInfo date = dates.get(nIndex);
SimpleDialog dialog = new SimpleDialog(xContext,"w2phtml2.DateDialog");
if (dialog.getDialog()!=null) {
dialog.getControls().setDateFieldValue("Date", date.nDate);
dialog.getControls().setTextFieldText("Event", date.sEvent);
if (dialog.getDialog().execute()==ExecutableDialogResults.OK) {
date.nDate = dialog.getControls().getDateFieldValue("Date");
date.sEvent = dialog.getControls().getTextFieldText("Event").trim();
updateDateList(nIndex);
}
dialog.getDialog().endExecute();
}
return true;
}
private boolean dateDeleteClick() {
if (dates.size()>0) {
SimpleDialog dialog = new SimpleDialog(xContext,"w2phtml2.DeleteDialog");
if (dialog.getDialog()!=null) {
short nIndex = getListBoxSelectedItem("Dates");
String sLabel = dialog.getControls().getLabelText("DeleteLabel");
sLabel = sLabel.replaceAll("%s", formatDate(dates.get(nIndex).nDate));
dialog.getControls().setLabelText("DeleteLabel", sLabel);
if (dialog.getDialog().execute()==ExecutableDialogResults.OK) {
dates.remove(nIndex);
updateDateList(nIndex<dates.size() ? (short) nIndex : (short) (nIndex-1));
}
}
}
return true;
}
private boolean dateUpClick() {
short nIndex = getListBoxSelectedItem("Dates");
if (nIndex>0) {
DateInfo date = dates.get(nIndex);
dates.set(nIndex, dates.get(nIndex-1));
dates.set(nIndex-1, date);
updateDateList((short) (nIndex-1));
}
return true;
}
private boolean dateDownClick() {
short nIndex = getListBoxSelectedItem("Dates");
if (nIndex+1<dates.size()) {
DateInfo date = dates.get(nIndex);
dates.set(nIndex, dates.get(nIndex+1));
dates.set(nIndex+1, date);
updateDateList((short) (nIndex+1));
}
return true;
}
// --------------------------------------------------
// Get and set properties from and to current document
@Override protected void initialize() {
// Get the document properties
XDesktop xDesktop;
Object desktop;
try {
desktop = xContext.getServiceManager().createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
} catch (Exception e) {
// Failed to get desktop
return;
}
xDesktop = (XDesktop) UnoRuntime.queryInterface(com.sun.star.frame.XDesktop.class, desktop);
XComponent xComponent = xDesktop.getCurrentComponent();
XDocumentPropertiesSupplier xSupplier = (XDocumentPropertiesSupplier) UnoRuntime.queryInterface(XDocumentPropertiesSupplier.class, xComponent);
// Get the document properties (we need several interfaces)
xDocumentProperties = xSupplier.getDocumentProperties();
xUserProperties= xDocumentProperties.getUserDefinedProperties();
xUserPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xUserProperties);
// Get the custom identifier and set the text fields
String[] sIdentifiers = getProperties(IDENTIFIER,false);
setCheckBoxStateAsBoolean("UseCustomIdentifier",sIdentifiers.length>0);
useCustomIdentifierChange();
if (sIdentifiers.length>0) { // Use the first if we have several...
setTextFieldText("Identifier",getStringValue(sIdentifiers[0]));
setTextFieldText("IdentifierType",getSuffix(sIdentifiers[0]));
}
// Get the authors and set the list box
String[] sCreators = getProperties(CREATOR,false);
for (String sCreator : sCreators) {
AuthorInfo creator = new AuthorInfo();
creator.sName = getStringValue(sCreator);
creator.sRole = getSuffix(sCreator);
creator.isCreator = true;
authors.add(creator);
}
String[] sContributors = getProperties(CONTRIBUTOR,false);
for (String sContributor : sContributors) {
AuthorInfo contributor = new AuthorInfo();
contributor.sName = getStringValue(sContributor);
contributor.sRole = getSuffix(sContributor);
contributor.isCreator = false;
authors.add(contributor);
}
updateAuthorList((short) 0);
// Get the dates and set the list box
String[] sDates = getProperties(DATE,false);
for (String sDate : sDates) {
DateInfo date = new DateInfo();
DateTime dt = getDateValue(sDate);
if (dt!=null) { // We accept either a date
date.nDate = datetime2int(dt);
}
else { // Or a string in the form yyyy-mm-dd
date.nDate = parseDate(getStringValue(sDate));
}
date.sEvent = getSuffix(sDate);
dates.add(date);
}
updateDateList((short) 0);
// Get the standard properties and set the text fields
setTextFieldText("Title",xDocumentProperties.getTitle());
setTextFieldText("Subject",xDocumentProperties.getSubject());
String[] sKeywords = xDocumentProperties.getKeywords();
CSVList keywords = new CSVList(", ");
for (String sKeyword : sKeywords) {
keywords.addValue(sKeyword);
}
setTextFieldText("Keywords",keywords.toString());
setTextFieldText("Description",xDocumentProperties.getDescription());
// Get the simple user properties and set the text fields
readSimpleProperty(PUBLISHER);
readSimpleProperty(TYPE);
readSimpleProperty(FORMAT);
readSimpleProperty(SOURCE);
readSimpleProperty(RELATION);
readSimpleProperty(COVERAGE);
readSimpleProperty(RIGHTS);
}
@Override protected void endDialog() {
// Set the custom identifier from the text fields
String[] sIdentifiers = getProperties(IDENTIFIER,false);
for (String sIdentifier : sIdentifiers) { // Remove old identifier(s)
removeProperty(sIdentifier);
}
if (getCheckBoxStateAsBoolean("UseCustomIdentifier")) {
String sName = IDENTIFIER;
if (getTextFieldText("IdentifierType").trim().length()>0) {
sName+="."+getTextFieldText("IdentifierType").trim();
}
addProperty(sName);
setValue(sName,getTextFieldText("Identifier"));
}
// Set the authors from the list box
String[] sCreators = getProperties(CREATOR,false);
for (String sCreator : sCreators) { // remove old creators
removeProperty(sCreator);
}
String[] sContributors = getProperties(CONTRIBUTOR,false);
for (String sContributor : sContributors) { // remove old contributors
removeProperty(sContributor);
}
int i=0;
for (AuthorInfo author : authors) {
String sName = (author.isCreator ? CREATOR : CONTRIBUTOR)+formatter.format(++i);
if (author.sRole.length()>0) {
sName+="."+author.sRole;
}
addProperty(sName);
setValue(sName,author.sName);
}
// Set the dates from the list box
String[] sDates = getProperties(DATE,false);
for (String sDate : sDates) { // remove old dates
removeProperty(sDate);
}
i=0;
for (DateInfo date : dates) {
String sName = DATE+formatter.format(++i);
if (date.sEvent.length()>0) {
sName+="."+date.sEvent;
}
addProperty(sName);
setValue(sName,formatDate(date.nDate));
// Doesn't work (why not?)
//setValue(sName,int2datetime(date.nDate));
}
// Set the standard properties from the text fields
xDocumentProperties.setTitle(getTextFieldText("Title"));
xDocumentProperties.setSubject(getTextFieldText("Subject"));
String[] sKeywords = getTextFieldText("Keywords").split(",");
for (int j=0; j<sKeywords.length; j++) {
sKeywords[j] = sKeywords[j].trim();
}
xDocumentProperties.setKeywords(sKeywords);
xDocumentProperties.setDescription(getTextFieldText("Description"));
// Set the simple user properties from the text fields
writeSimpleProperty(PUBLISHER);
writeSimpleProperty(TYPE);
writeSimpleProperty(FORMAT);
writeSimpleProperty(SOURCE);
writeSimpleProperty(RELATION);
writeSimpleProperty(COVERAGE);
writeSimpleProperty(RIGHTS);
}
// Get the suffix of a user defined property (portion after fist ., if any)
private String getSuffix(String sPropertyName) {
int nDot = sPropertyName.indexOf(".");
return nDot>-1 ? sPropertyName.substring(nDot+1) : "";
}
// Get all currently defined user properties with a specific name or prefix
private String[] getProperties(String sPrefix, boolean bComplete) {
HashSet<String> names = new HashSet<String>();
Property[] xProps = xUserPropertySet.getPropertySetInfo().getProperties();
for (Property prop : xProps) {
String sName = prop.Name;
String sLCName = sName.toLowerCase();
String sLCPrefix = sPrefix.toLowerCase();
if ((bComplete && sLCName.equals(sLCPrefix)) || (!bComplete && sLCName.startsWith(sLCPrefix))) {
names.add(sName);
}
}
return Misc.sortStringSet(names);
}
// Add a user property
private void addProperty(String sName) {
try {
xUserProperties.addProperty(sName, (short) 128, ""); // 128 means removeable, last parameter is default value
} catch (PropertyExistException e) {
} catch (IllegalTypeException e) {
} catch (IllegalArgumentException e) {
}
}
// Delete a user property
private void removeProperty(String sName) {
try {
xUserProperties.removeProperty(sName);
} catch (UnknownPropertyException e) {
} catch (NotRemoveableException e) {
}
}
// Set the value of a user property (failing silently if the property does not exist)
private void setValue(String sName, Object value) {
try {
xUserPropertySet.setPropertyValue(sName, value);
} catch (UnknownPropertyException e) {
} catch (PropertyVetoException e) {
} catch (IllegalArgumentException e) {
} catch (WrappedTargetException e) {
}
}
// Get the string value of a user property (returning null if the property does not exist)
private String getStringValue(String sName) {
Object value = getValue(sName);
if (value!=null && AnyConverter.isString(value)) {
try {
return AnyConverter.toString(value);
} catch (IllegalArgumentException e) {
return null;
}
}
return null;
}
private DateTime getDateValue(String sName) {
Object value = getValue(sName);
if (value!=null && value instanceof DateTime) {
return (DateTime) value;
}
return null;
}
// Get the value of a user property (returning null if the property does not exist)
private Object getValue(String sName) {
try {
return xUserPropertySet.getPropertyValue(sName);
} catch (UnknownPropertyException e) {
return null;
} catch (WrappedTargetException e) {
return null;
}
}
private void updateAuthorList(short nItem) {
int nCount = authors.size();
if (nCount>0) {
String[] sAuthors = new String[nCount];
for (int i=0; i<nCount; i++) {
AuthorInfo author = authors.get(i);
sAuthors[i] = author.sName
+" ("
+(author.isCreator ? "creator":"contributor")
+(author.sRole.length()>0 ? ", "+author.sRole : "")
+")";
}
setListBoxStringItemList("Authors", sAuthors);
setListBoxSelectedItem("Authors",nItem);
setControlEnabled("Authors", true);
}
else { // Display the fall-back author
String[] sAuthors = new String[1];
//sAuthors[0] = xDocumentProperties.getAuthor()+" (default creator)";
sAuthors[0] = xDocumentProperties.getModifiedBy()+" (default creator)";
setListBoxStringItemList("Authors", sAuthors);
setControlEnabled("Authors", false);
}
setControlEnabled("ModifyAuthorButton",nCount>0);
setControlEnabled("DeleteAuthorButton",nCount>0);
setControlEnabled("AuthorUpButton",nCount>1);
setControlEnabled("AuthorDownButton",nCount>1);
}
private void updateDateList(short nItem) {
int nCount = dates.size();
if (nCount>0) {
String[] sDates = new String[nCount];
for (int i=0; i<nCount; i++) {
DateInfo date = dates.get(i);
sDates[i] = formatDate(date.nDate);
if (date.sEvent.length()>0) {
sDates[i]+=" (" + date.sEvent + ")";
}
}
setListBoxStringItemList("Dates", sDates);
setListBoxSelectedItem("Dates",nItem);
setControlEnabled("Dates", true);
}
else { // Display the fall-back date
String[] sDates = new String[1];
sDates[0] = formatDate(datetime2int(xDocumentProperties.getModificationDate()))+" (default date)";
setListBoxStringItemList("Dates", sDates);
setControlEnabled("Dates", false);
}
setControlEnabled("ModifyDateButton",nCount>0);
setControlEnabled("DeleteDateButton",nCount>0);
setControlEnabled("DateUpButton",nCount>1);
setControlEnabled("DateDownButton",nCount>1);
}
private void readSimpleProperty(String sName) {
String[] sNames = getProperties(sName,true);
if (sNames.length>0) {
String sValue = getStringValue(sNames[0]);
if (sValue!=null) {
setTextFieldText(sName, sValue);
}
}
}
private void writeSimpleProperty(String sName) {
String[] sOldNames = getProperties(sName,true);
for (String sOldName : sOldNames) {
removeProperty(sOldName);
}
String sValue = getTextFieldText(sName);
if (sValue.length()>0) {
addProperty(sName);
setValue(sName,sValue);
}
}
// Date fields uses integers for dates (format yyyymmdd)
// Document properties uses com.sun.star.util.DateTime
// Also dates should be formatted as yyyy-mm-dd as strings
// Thus we need a few conversion methods
// Format a integer date as yyyy-mm-dd
private String formatDate(int nDate) {
String sDate = Integer.toString(nDate);
if (sDate.length()==8) {
return sDate.substring(0,4)+"-"+sDate.substring(4, 6)+"-"+sDate.substring(6);
}
else {
return "???";
}
}
// Parse a string as a date in the format yyyy-mm-dd (returning 0 on failure)
private int parseDate(String sDate) {
Matcher matcher = datePattern.matcher(sDate);
if (matcher.matches()) {
return Misc.getPosInteger(matcher.group(1)+matcher.group(2)+matcher.group(3),0);
}
return 0;
}
// Convert an integer to com.sun.star.util.DateTime
/*private DateTime int2datetime(int nDate) {
DateTime date = new DateTime();
date.Year = (short) (nDate/10000);
date.Month = (short) ((nDate%10000)/100);
date.Day = (short) (nDate%100);
return date;
}*/
// Convert a com.sun.star.util.DateTime to integer
private int datetime2int(DateTime date) {
return 10000*date.Year+100*date.Month+date.Day;
}
}

View file

@ -1,341 +0,0 @@
/************************************************************************
*
* EpubOptionsDialog.java
*
* Copyright: 2002-2015 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-04-28)
*
*/
package org.openoffice.da.comp.writer2xhtml;
import java.awt.GraphicsEnvironment;
import com.sun.star.awt.XDialog;
import com.sun.star.beans.XPropertySet;
import com.sun.star.lang.XComponent;
import com.sun.star.ui.dialogs.XExecutableDialog;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import org.openoffice.da.comp.w2lcommon.helper.PropertyHelper;
import org.openoffice.da.comp.w2lcommon.filter.OptionsDialogBase;
/** This class provides a UNO component which implements a filter UI for the
* EPUB export
*/
public class EpubOptionsDialog extends OptionsDialogBase {
/** The component will be registered under this name.
*/
public static String __serviceName = "org.openoffice.da.writer2xhtml.EpubOptionsDialog";
/** The component should also have an implementation name.
*/
public static String __implementationName = "org.openoffice.da.comp.writer2xhtml.EpubOptionsDialog";
@Override public String getDialogLibraryName() { return "w2phtml2"; }
/** Return the name of the dialog within the library
*/
@Override public String getDialogName() { return "EpubOptions"; }
/** Return the name of the registry path
*/
@Override public String getRegistryPath() {
return "/org.openoffice.da.Writer2xhtml.Options/EpubOptions";
}
/** Create a new EpubOptionsDialog */
public EpubOptionsDialog(XComponentContext xContext) {
super(xContext);
xMSF = W2XRegistration.xMultiServiceFactory;
}
/** Load settings from the registry to the dialog */
@Override protected void loadSettings(XPropertySet xProps) {
// Style
loadConfig(xProps);
int nScaling = loadNumericOption(xProps, "Scaling");
if (nScaling<=1) { // Workaround for an obscure bug in the extension manager
setNumericFieldValue("Scaling",100);
}
loadCheckBoxOption(xProps, "RelativeFontSize");
loadNumericOption(xProps, "FontScaling");
int nFontScaling = loadNumericOption(xProps, "FontScaling");
if (nFontScaling<=1) {
setNumericFieldValue("FontScaling",100);
}
loadCheckBoxOption(xProps, "RelativeFontSize");
loadCheckBoxOption(xProps, "UseDefaultFont");
loadComboBoxOption(xProps, "DefaultFontName");
loadCheckBoxOption(xProps, "ConvertToPx");
loadListBoxOption(xProps, "ImageSize");
// Fill the font name list with all installed fonts
setListBoxStringItemList("DefaultFontName",
GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
// AutoCorrect
loadCheckBoxOption(xProps, "IgnoreHardLineBreaks");
loadCheckBoxOption(xProps, "IgnoreEmptyParagraphs");
loadCheckBoxOption(xProps, "IgnoreDoubleSpaces");
// Special content
loadCheckBoxOption(xProps, "DisplayHiddenText");
loadCheckBoxOption(xProps, "Notes");
// Document division
loadListBoxOption(xProps, "SplitLevel");
loadListBoxOption(xProps, "PageBreakSplit");
loadCheckBoxOption(xProps, "UseImageSplit");
loadNumericOption(xProps, "ImageSplit");
loadCheckBoxOption(xProps, "CoverImage");
loadCheckBoxOption(xProps, "UseSplitAfter");
loadNumericOption(xProps, "SplitAfter");
// Navigation table
loadListBoxOption(xProps, "ExternalTocDepth");
loadCheckBoxOption(xProps, "IncludeToc");
loadCheckBoxOption(xProps, "IncludeNCX");
updateLockedOptions();
enableControls();
}
/** Save settings from the dialog to the registry and create FilterData */
@Override protected void saveSettings(XPropertySet xProps, PropertyHelper helper) {
// Style
short nConfig = saveConfig(xProps, helper);
switch (nConfig) {
case 0: helper.put("ConfigURL","*default.xml"); break;
case 1: helper.put("ConfigURL","$(user)/writer2xhtml.xml");
helper.put("AutoCreate","true");
helper.put("TemplateURL", "$(user)/writer2xhtml-template.xhtml");
helper.put("StyleSheetURL", "$(user)/writer2xhtml-styles.css");
helper.put("ResourceURL", "$(user)/writer2xhtml-resources");
}
saveNumericOptionAsPercentage(xProps, helper, "Scaling", "scaling");
saveCheckBoxOption(xProps, helper, "RelativeFontSize", "relative_font_size");
saveNumericOptionAsPercentage(xProps, helper, "FontScaling", "font_scaling");
saveCheckBoxOption(xProps, helper, "UseDefaultFont", "use_default_font");
saveTextFieldOption(xProps, helper, "DefaultFontName", "default_font_name");
saveCheckBoxOption(xProps, helper, "ConvertToPx", "convert_to_px");
saveListBoxOption(xProps, "ImageSize");
switch (getListBoxSelectedItem("ImageSize")) {
case 0: helper.put("image_size", "absolute"); break;
case 1: helper.put("image_size", "relative"); break;
case 2: helper.put("image_size", "none");
}
// AutoCorrect
saveCheckBoxOption(xProps, helper, "IgnoreHardLineBreaks", "ignore_hard_line_breaks");
saveCheckBoxOption(xProps, helper, "IgnoreEmptyParagraphs", "ignore_empty_paragraphs");
saveCheckBoxOption(xProps, helper, "IgnoreDoubleSpaces", "ignore_double_spaces");
// Special content
saveCheckBoxOption(xProps, helper, "DisplayHiddenText", "display_hidden_text");
saveCheckBoxOption(xProps, helper, "Notes", "notes");
// Document division
short nSplitLevel = saveListBoxOption(xProps, "SplitLevel");
if (!isLocked("split_level")) {
helper.put("split_level",Integer.toString(nSplitLevel));
}
short nPageBreakSplit = saveListBoxOption(xProps, "PageBreakSplit");
if (!isLocked("page_break_split")) {
switch (nPageBreakSplit) {
case 0: helper.put("page_break_split","none"); break;
case 1: helper.put("page_break_split", "styles"); break;
case 2: helper.put("page_break_split", "explicit"); break;
case 3: helper.put("page_break_split", "all");
}
}
boolean bUseImageSplit = saveCheckBoxOption(xProps, "UseImageSplit");
int nImageSplit = saveNumericOption(xProps, "ImageSplit");
if (!isLocked("image_split")) {
if (bUseImageSplit) {
helper.put("image_split", nImageSplit+"%");
}
else {
helper.put("image_split", "none");
}
}
saveCheckBoxOption(xProps, helper, "CoverImage", "cover_image");
boolean bUseSplitAfter = saveCheckBoxOption(xProps, "UseSplitAfter");
int nSplitAfter = saveNumericOption(xProps, "SplitAfter");
if (!isLocked("split_after")) {
if (bUseSplitAfter) {
helper.put("split_after", Integer.toString(nSplitAfter));
}
else {
helper.put("split_after", "0");
}
}
// Navigation table
short nExternalTocDepth = saveListBoxOption(xProps, "ExternalTocDepth");
helper.put("external_toc_depth", Integer.toString(nExternalTocDepth+1));
saveCheckBoxOption(xProps, helper, "IncludeToc", "include_toc");
saveCheckBoxOption(xProps, helper, "IncludeNCX", "include_ncx");
}
// Implement XDialogEventHandler
@Override public boolean callHandlerMethod(XDialog xDialog, Object event, String sMethod) {
if (sMethod.equals("ConfigChange")) {
updateLockedOptions();
enableControls();
}
else if (sMethod.equals("RelativeFontSizeChange")) {
relativeFontSizeChange();
}
else if (sMethod.equals("UseDefaultFontChange")) {
useDefaultFontChange();
}
else if (sMethod.equals("EditMetadataClick")) {
editMetadataClick();
}
else if (sMethod.equals("UseImageSplitChange")) {
useImageSplitChange();
}
else if (sMethod.equals("UseSplitAfterChange")) {
useSplitAfterChange();
}
return true;
}
@Override public String[] getSupportedMethodNames() {
String[] sNames = { "ConfigChange", "RelativeFontSizeChange", "UseDefaultFontChange", "EditMetadataClick",
"UseImageSplitChange", "UseSplitAfterChange" };
return sNames;
}
private void enableControls() {
// Style
setControlEnabled("ScalingLabel",!isLocked("scaling"));
setControlEnabled("Scaling",!isLocked("scaling"));
boolean bRelativeFontSize = getCheckBoxStateAsBoolean("RelativeFontSize");
setControlEnabled("RelativeFontSize",!isLocked("relative_font_size"));
setControlEnabled("FontScalingLabel", !isLocked("font_scaling") && bRelativeFontSize);
setControlEnabled("FontScaling",!isLocked("font_scaling") && bRelativeFontSize);
setControlEnabled("FontScalingPercentLabel", !isLocked("font_scaling") && bRelativeFontSize);
boolean bUseDefaultFont = getCheckBoxStateAsBoolean("UseDefaultFont");
setControlEnabled("UseDefaultFont",!isLocked("use_default_font"));
setControlEnabled("DefaultFontNameLabel",!isLocked("default_font_name") && bUseDefaultFont);
setControlEnabled("DefaultFontName",!isLocked("default_font_name") && bUseDefaultFont);
setControlEnabled("ConvertToPx",!isLocked("convert_to_px"));
setControlEnabled("ImageSize",!isLocked("image_size"));
// AutoCorrect
setControlEnabled("IgnoreHardLineBreaks",!isLocked("ignore_hard_line_breaks"));
setControlEnabled("IgnoreEmptyParagraphs",!isLocked("ignore_empty_paragraphs"));
setControlEnabled("IgnoreDoubleSpaces",!isLocked("ignore_double_spaces"));
// Special content
setControlEnabled("DisplayHiddenText",!isLocked("display_hidden_text"));
setControlEnabled("Notes",!isLocked("notes"));
// Document division
setControlEnabled("SplitLevelLabel",!isLocked("split_level"));
setControlEnabled("SplitLevel",!isLocked("split_level"));
setControlEnabled("PageBreakSplitLabel",!isLocked("page_break_split"));
setControlEnabled("PageBreakSplit",!isLocked("page_break_split"));
boolean bUseImageSplit = getCheckBoxStateAsBoolean("UseImageSplit");
setControlEnabled("UseImageSplit",!isLocked("image_split"));
setControlEnabled("ImageSplitLabel",!isLocked("image_split") && bUseImageSplit);
setControlEnabled("ImageSplit",!isLocked("image_split") && bUseImageSplit);
setControlEnabled("ImageSplitPercentLabel",!isLocked("image_split") && bUseImageSplit);
setControlEnabled("CoverImage", !isLocked("cover_image"));
boolean bUseSplitAfter = getCheckBoxStateAsBoolean("UseSplitAfter");
setControlEnabled("UseSplitAfter",!isLocked("split_after"));
setControlEnabled("SplitAfterLabel",!isLocked("split_after") && bUseSplitAfter);
setControlEnabled("SplitAfter",!isLocked("split_after") && bUseSplitAfter);
// Navigation table
setControlEnabled("ExternalTocDepthLabel", !isLocked("external_toc_depth"));
setControlEnabled("ExternalTocDepth", !isLocked("external_toc_depth"));
setControlEnabled("IncludeToc", !isLocked("include_toc"));
setControlEnabled("IncludeNCX", (this instanceof Epub3OptionsDialog) && !isLocked("include_ncx"));
}
private void relativeFontSizeChange() {
if (!isLocked("font_scaling")) {
boolean bState = getCheckBoxStateAsBoolean("RelativeFontSize");
setControlEnabled("FontScalingLabel", bState);
setControlEnabled("FontScaling", bState);
setControlEnabled("FontScalingPercentLabel", bState);
}
}
private void useDefaultFontChange() {
if (!isLocked("default_font_name")) {
boolean bState = getCheckBoxStateAsBoolean("UseDefaultFont");
setControlEnabled("DefaultFontNameLabel", bState);
setControlEnabled("DefaultFontName", bState);
}
}
private void editMetadataClick() {
Object dialog;
try {
dialog = xContext.getServiceManager().createInstanceWithContext("org.openoffice.da.writer2xhtml.EpubMetadataDialog", xContext);
XExecutableDialog xDialog = (XExecutableDialog) UnoRuntime.queryInterface(XExecutableDialog.class, dialog);
xDialog.execute();
// Dispose the dialog after execution (to free up the memory)
XComponent xComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, dialog);
if (xComponent!=null) {
xComponent.dispose();
}
} catch (Exception e) {
// Failed to get dialog
}
}
private void useImageSplitChange() {
if (!isLocked("image_split")) {
boolean bEnable = getCheckBoxStateAsBoolean("UseImageSplit");
setControlEnabled("ImageSplitLabel",bEnable);
setControlEnabled("ImageSplit",bEnable);
setControlEnabled("ImageSplitPercentLabel",bEnable);
}
}
private void useSplitAfterChange() {
if (!isLocked("split_after")) {
boolean bState = getCheckBoxStateAsBoolean("UseSplitAfter");
setControlEnabled("SplitAfterLabel",bState);
setControlEnabled("SplitAfter",bState);
}
}
}

View file

@ -1,261 +0,0 @@
/************************************************************************
*
* ToolbarSettingsDialog.java
*
* Copyright: 2002-2015 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-04-05)
*
*/
package org.openoffice.da.comp.writer2xhtml;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import com.sun.star.awt.XContainerWindowEventHandler;
import com.sun.star.awt.XDialog;
import com.sun.star.awt.XWindow;
import com.sun.star.beans.XPropertySet;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.util.XChangesBatch;
import com.sun.star.lib.uno.helper.WeakBase;
import org.openoffice.da.comp.w2lcommon.helper.DialogAccess;
import org.openoffice.da.comp.w2lcommon.helper.FilePicker;
import org.openoffice.da.comp.w2lcommon.helper.RegistryHelper;
import org.openoffice.da.comp.w2lcommon.helper.XPropertySetHelper;
/** This class provides a uno component which implements the configuration
* of the writer2xhtml toolbar
*/
public final class ToolbarSettingsDialog
extends WeakBase
implements XServiceInfo, XContainerWindowEventHandler {
public static final String REGISTRY_PATH = "/org.openoffice.da.Writer2xhtml.toolbar.ToolbarOptions/Settings";
private XComponentContext xContext;
private FilePicker filePicker;
/** The component will be registered under this name.
*/
public static String __serviceName = "org.openoffice.da.writer2xhtml.ToolbarSettingsDialog";
/** The component should also have an implementation name.
*/
public static String __implementationName = "org.openoffice.da.comp.writer2xhtml.ToolbarSettingsDialog";
/** Create a new ToolbarSettingsDialog */
public ToolbarSettingsDialog(XComponentContext xContext) {
this.xContext = xContext;
filePicker = new FilePicker(xContext);
}
// Implement XContainerWindowEventHandler
public boolean callHandlerMethod(XWindow xWindow, Object event, String sMethod)
throws com.sun.star.lang.WrappedTargetException {
XDialog xDialog = (XDialog)UnoRuntime.queryInterface(XDialog.class, xWindow);
DialogAccess dlg = new DialogAccess(xDialog);
try {
if (sMethod.equals("external_event") ){
return handleExternalEvent(dlg, event);
}
else if (sMethod.equals("XhtmlFormatChange")) {
return true;
}
else if (sMethod.equals("XhtmlViewChange")) {
return xhtmlViewChange(dlg);
}
else if (sMethod.equals("XhtmlBrowseClick")) {
return xhtmlBrowseClick(dlg);
}
else if (sMethod.equals("EpubFormatChange")) {
return true;
}
else if (sMethod.equals("EpubViewChange")) {
return epubViewChange(dlg);
}
else if (sMethod.equals("EpubBrowseClick")) {
return epubBrowseClick(dlg);
}
}
catch (com.sun.star.uno.RuntimeException e) {
throw e;
}
catch (com.sun.star.uno.Exception e) {
throw new com.sun.star.lang.WrappedTargetException(sMethod, this, e);
}
return false;
}
public String[] getSupportedMethodNames() {
String[] sNames = { "external_event", "XhtmlFormatChange", "XhtmlViewChange", "XhtmlBrowseClick",
"EpupFormatChange", "EpubViewChange", "EpubBrowseClick" };
return sNames;
}
// 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;
}
// Private stuff
private boolean handleExternalEvent(DialogAccess dlg, Object aEventObject)
throws com.sun.star.uno.Exception {
try {
String sMethod = AnyConverter.toString(aEventObject);
if (sMethod.equals("ok")) {
saveConfiguration(dlg);
return true;
} else if (sMethod.equals("back") || sMethod.equals("initialize")) {
loadConfiguration(dlg);
enableXhtmlExecutable(dlg);
enableEpubExecutable(dlg);
return true;
}
}
catch (com.sun.star.lang.IllegalArgumentException e) {
throw new com.sun.star.lang.IllegalArgumentException(
"Method external_event requires a string in the event object argument.", this,(short) -1);
}
return false;
}
private void loadConfiguration(DialogAccess dlg) {
RegistryHelper registry = new RegistryHelper(xContext);
try {
Object view = registry.getRegistryView(REGISTRY_PATH, false);
XPropertySet xProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class,view);
dlg.setListBoxSelectedItem("XhtmlFormat",
XPropertySetHelper.getPropertyValueAsShort(xProps, "XhtmlFormat"));
dlg.setListBoxSelectedItem("XhtmlView",
XPropertySetHelper.getPropertyValueAsShort(xProps, "XhtmlView"));
dlg.setTextFieldText("XhtmlExecutable",
XPropertySetHelper.getPropertyValueAsString(xProps, "XhtmlExecutable"));
dlg.setListBoxSelectedItem("EpubFormat",
XPropertySetHelper.getPropertyValueAsShort(xProps, "EpubFormat"));
dlg.setListBoxSelectedItem("EpubView",
XPropertySetHelper.getPropertyValueAsShort(xProps, "EpubView"));
dlg.setTextFieldText("EpubExecutable",
XPropertySetHelper.getPropertyValueAsString(xProps, "EpubExecutable"));
} catch (Exception e) {
// Failed to get registry view
}
}
private void saveConfiguration(DialogAccess dlg) {
RegistryHelper registry = new RegistryHelper(xContext);
try {
Object view = registry.getRegistryView(REGISTRY_PATH, true);
XPropertySet xProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class,view);
XPropertySetHelper.setPropertyValue(xProps, "XhtmlFormat", dlg.getListBoxSelectedItem("XhtmlFormat"));
XPropertySetHelper.setPropertyValue(xProps, "XhtmlView", dlg.getListBoxSelectedItem("XhtmlView"));
XPropertySetHelper.setPropertyValue(xProps, "XhtmlExecutable", dlg.getTextFieldText("XhtmlExecutable"));
XPropertySetHelper.setPropertyValue(xProps, "EpubFormat", dlg.getListBoxSelectedItem("EpubFormat"));
XPropertySetHelper.setPropertyValue(xProps, "EpubView", dlg.getListBoxSelectedItem("EpubView"));
XPropertySetHelper.setPropertyValue(xProps, "EpubExecutable", dlg.getTextFieldText("EpubExecutable"));
// Commit registry changes
XChangesBatch xUpdateContext = (XChangesBatch)
UnoRuntime.queryInterface(XChangesBatch.class,view);
try {
xUpdateContext.commitChanges();
}
catch (Exception e) {
// ignore
}
registry.disposeRegistryView(view);
}
catch (Exception e) {
// Failed to get registry view
}
}
private boolean xhtmlViewChange(DialogAccess dlg) {
enableXhtmlExecutable(dlg);
return true;
}
private void enableXhtmlExecutable(DialogAccess dlg) {
int nItem = dlg.getListBoxSelectedItem("XhtmlView");
dlg.setControlEnabled("XhtmlExecutable", nItem==2);
dlg.setControlEnabled("XhtmlBrowseButton", nItem==2);
}
private boolean xhtmlBrowseClick(DialogAccess dlg) {
browseForExecutable(dlg,"XhtmlExecutable");
return true;
}
private boolean epubViewChange(DialogAccess dlg) {
enableEpubExecutable(dlg);
return true;
}
private void enableEpubExecutable(DialogAccess dlg) {
int nItem = dlg.getListBoxSelectedItem("EpubView");
dlg.setControlEnabled("EpubExecutable", nItem==2);
dlg.setControlEnabled("EpubBrowseButton", nItem==2);
}
private boolean epubBrowseClick(DialogAccess dlg) {
browseForExecutable(dlg,"EpubExecutable");
return true;
}
private boolean browseForExecutable(DialogAccess dlg, String sControlName) {
String sPath = filePicker.getPath();
if (sPath!=null) {
try {
dlg.setComboBoxText(sControlName, new File(new URI(sPath)).getCanonicalPath());
}
catch (IOException e) {
}
catch (URISyntaxException e) {
}
}
return true;
}
}

View file

@ -1,54 +0,0 @@
/************************************************************************
*
* W2XExportFilter.java
*
* Copyright: 2002-2014 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2014-10-06)
*
*/
package org.openoffice.da.comp.writer2xhtml;
import com.sun.star.uno.XComponentContext;
import org.openoffice.da.comp.w2lcommon.filter.ExportFilterBase;
/** This class implements the xhtml export filter component
*/
public class W2XExportFilter extends ExportFilterBase {
/** Service name for the component */
public static final String __serviceName = "org.openoffice.da.comp.writer2xhtml.W2XExportFilter";
/** Implementation name for the component */
public static final String __implementationName = "org.openoffice.da.comp.writer2xhtml.W2XExportFilter";
/** Filter name to include in error messages */
public final String __displayName = "Writer2xhtml";
public W2XExportFilter(XComponentContext xComponentContext1) {
super(xComponentContext1);
}
}

View file

@ -1,150 +0,0 @@
/************************************************************************
*
* W2XRegistration.java
*
* Copyright: 2002-2015 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-04-28)
*
*/
package org.openoffice.da.comp.writer2xhtml;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.lang.XSingleServiceFactory;
import com.sun.star.registry.XRegistryKey;
import com.sun.star.comp.loader.FactoryHelper;
/** This class provides a static method to instantiate our uno components
* on demand (__getServiceFactory()), and a static method to give
* information about the components (__writeRegistryServiceInfo()).
* Furthermore, it saves the XMultiServiceFactory provided to the
* __getServiceFactory method for future reference by the componentes.
*/
public class W2XRegistration {
public static XMultiServiceFactory xMultiServiceFactory;
/**
* Returns a factory for creating the service.
* This method is called by the <code>JavaLoader</code>
*
* @return returns a <code>XSingleServiceFactory</code> for creating the
* component
*
* @param implName the name of the implementation for which a
* service is desired
* @param multiFactory the service manager to be used if needed
* @param regKey the registryKey
*
* @see com.sun.star.comp.loader.JavaLoader
*/
public static XSingleServiceFactory __getServiceFactory(String implName,
XMultiServiceFactory multiFactory, XRegistryKey regKey) {
xMultiServiceFactory = multiFactory;
XSingleServiceFactory xSingleServiceFactory = null;
if (implName.equals(Writer2xhtml.__implementationName) ) {
xSingleServiceFactory = FactoryHelper.getServiceFactory(Writer2xhtml.class,
Writer2xhtml.__serviceName,
multiFactory,
regKey);
}
else if (implName.equals(W2XExportFilter.class.getName()) ) {
xSingleServiceFactory = FactoryHelper.getServiceFactory(W2XExportFilter.class,
W2XExportFilter.__serviceName,
multiFactory,
regKey);
}
else if (implName.equals(XhtmlOptionsDialog.__implementationName)) {
xSingleServiceFactory = FactoryHelper.getServiceFactory(XhtmlOptionsDialog.class,
XhtmlOptionsDialog.__serviceName,
multiFactory,
regKey);
}
else if (implName.equals(XhtmlOptionsDialogMath.__implementationName)) {
xSingleServiceFactory = FactoryHelper.getServiceFactory(XhtmlOptionsDialogMath.class,
XhtmlOptionsDialogMath.__serviceName,
multiFactory,
regKey);
}
else if (implName.equals(EpubOptionsDialog.__implementationName)) {
xSingleServiceFactory = FactoryHelper.getServiceFactory(EpubOptionsDialog.class,
EpubOptionsDialog.__serviceName,
multiFactory,
regKey);
}
else if (implName.equals(Epub3OptionsDialog.__implementationName)) {
xSingleServiceFactory = FactoryHelper.getServiceFactory(Epub3OptionsDialog.class,
Epub3OptionsDialog.__serviceName,
multiFactory,
regKey);
}
else if (implName.equals(EpubMetadataDialog.__implementationName)) {
xSingleServiceFactory = FactoryHelper.getServiceFactory(EpubMetadataDialog.class,
EpubMetadataDialog.__serviceName,
multiFactory,
regKey);
}
else if (implName.equals(ConfigurationDialog.__implementationName)) {
xSingleServiceFactory = FactoryHelper.getServiceFactory(ConfigurationDialog.class,
ConfigurationDialog.__serviceName,
multiFactory,
regKey);
}
else if (implName.equals(ToolbarSettingsDialog.__implementationName)) {
xSingleServiceFactory = FactoryHelper.getServiceFactory(ToolbarSettingsDialog.class,
ToolbarSettingsDialog.__serviceName,
multiFactory,
regKey);
}
return xSingleServiceFactory;
}
/**
* Writes the service information into the given registry key.
* This method is called by the <code>JavaLoader</code>
* <p>
* @return returns true if the operation succeeded
* @param regKey the registryKey
* @see com.sun.star.comp.loader.JavaLoader
*/
public static boolean __writeRegistryServiceInfo(XRegistryKey regKey) {
return
FactoryHelper.writeRegistryServiceInfo(Writer2xhtml.__implementationName,
Writer2xhtml.__serviceName, regKey) &
FactoryHelper.writeRegistryServiceInfo(W2XExportFilter.__implementationName,
W2XExportFilter.__serviceName, regKey) &
FactoryHelper.writeRegistryServiceInfo(XhtmlOptionsDialog.__implementationName,
XhtmlOptionsDialog.__serviceName, regKey) &
FactoryHelper.writeRegistryServiceInfo(XhtmlOptionsDialogMath.__implementationName,
XhtmlOptionsDialogMath.__serviceName, regKey) &
FactoryHelper.writeRegistryServiceInfo(EpubOptionsDialog.__implementationName,
EpubOptionsDialog.__serviceName, regKey) &
FactoryHelper.writeRegistryServiceInfo(Epub3OptionsDialog.__implementationName,
Epub3OptionsDialog.__serviceName, regKey) &
FactoryHelper.writeRegistryServiceInfo(EpubMetadataDialog.__implementationName,
EpubMetadataDialog.__serviceName, regKey) &
FactoryHelper.writeRegistryServiceInfo(ConfigurationDialog.__implementationName,
ConfigurationDialog.__serviceName, regKey) &
FactoryHelper.writeRegistryServiceInfo(ToolbarSettingsDialog.__implementationName,
ToolbarSettingsDialog.__serviceName, regKey);
}
}

View file

@ -1,209 +0,0 @@
/************************************************************************
*
* Writer2xhtml.java
*
* Copyright: 2002-2015 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-04-05)
*
*/
package org.openoffice.da.comp.writer2xhtml;
// TODO: Create common base for dispatcher classes
import com.sun.star.beans.XPropertySet;
import com.sun.star.frame.XFrame;
import com.sun.star.lang.XComponent;
import com.sun.star.lib.uno.helper.WeakBase;
import com.sun.star.ui.dialogs.XExecutableDialog;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import org.openoffice.da.comp.w2lcommon.filter.UNOPublisher.TargetFormat;
import org.openoffice.da.comp.w2lcommon.helper.RegistryHelper;
import org.openoffice.da.comp.w2lcommon.helper.XPropertySetHelper;
/** This class implements the ui (dispatch) commands provided by Writer2xhtml.
*/
public final class Writer2xhtml extends WeakBase
implements com.sun.star.lang.XServiceInfo,
com.sun.star.frame.XDispatchProvider,
com.sun.star.lang.XInitialization,
com.sun.star.frame.XDispatch {
private static final String PROTOCOL = "org.openoffice.da.writer2xhtml:";
// From constructor+initialization
private final XComponentContext m_xContext;
private XFrame m_xFrame;
private XhtmlUNOPublisher unoPublisher = null;
// Global data
public static final String __implementationName = Writer2xhtml.class.getName();
public static final String __serviceName = "com.sun.star.frame.ProtocolHandler";
private static final String[] m_serviceNames = { __serviceName };
public Writer2xhtml(XComponentContext xContext) {
m_xContext = xContext;
}
// com.sun.star.lang.XInitialization:
public void initialize( Object[] object )
throws com.sun.star.uno.Exception {
if ( object.length > 0 ) {
// The first item is the current frame
m_xFrame = (com.sun.star.frame.XFrame) UnoRuntime.queryInterface(
com.sun.star.frame.XFrame.class, object[0]);
}
}
// com.sun.star.lang.XServiceInfo:
public String getImplementationName() {
return __implementationName;
}
public boolean supportsService( String sService ) {
int len = m_serviceNames.length;
for( int i=0; i < len; i++) {
if (sService.equals(m_serviceNames[i]))
return true;
}
return false;
}
public String[] getSupportedServiceNames() {
return m_serviceNames;
}
// com.sun.star.frame.XDispatchProvider:
public com.sun.star.frame.XDispatch queryDispatch( com.sun.star.util.URL aURL,
String sTargetFrameName, int iSearchFlags ) {
if ( aURL.Protocol.compareTo(PROTOCOL) == 0 ) {
if ( aURL.Path.compareTo("PublishAsXHTML") == 0 )
return this;
else if ( aURL.Path.compareTo("PublishAsEPUB") == 0 )
return this;
else if ( aURL.Path.compareTo("EditEPUBDocumentProperties") == 0 )
return this;
}
return null;
}
public com.sun.star.frame.XDispatch[] queryDispatches(
com.sun.star.frame.DispatchDescriptor[] seqDescriptors ) {
int nCount = seqDescriptors.length;
com.sun.star.frame.XDispatch[] seqDispatcher =
new com.sun.star.frame.XDispatch[seqDescriptors.length];
for( int i=0; i < nCount; ++i ) {
seqDispatcher[i] = queryDispatch(seqDescriptors[i].FeatureURL,
seqDescriptors[i].FrameName,
seqDescriptors[i].SearchFlags );
}
return seqDispatcher;
}
// com.sun.star.frame.XDispatch:
public void dispatch( com.sun.star.util.URL aURL,
com.sun.star.beans.PropertyValue[] aArguments ) {
if ( aURL.Protocol.compareTo(PROTOCOL) == 0 ) {
if ( aURL.Path.compareTo("PublishAsXHTML") == 0 ) {
publishAsXhtml();
return;
}
else if ( aURL.Path.compareTo("PublishAsEPUB") == 0 ) {
publishAsEpub();
return;
}
else if ( aURL.Path.compareTo("EditEPUBDocumentProperties") == 0 ) {
editDocumentProperties();
return;
}
}
}
public void addStatusListener( com.sun.star.frame.XStatusListener xControl,
com.sun.star.util.URL aURL ) {
}
public void removeStatusListener( com.sun.star.frame.XStatusListener xControl,
com.sun.star.util.URL aURL ) {
}
// The actual commands...
private void editDocumentProperties() {
Object dialog;
try {
dialog = m_xContext.getServiceManager().createInstanceWithContext("org.openoffice.da.writer2xhtml.EpubMetadataDialog", m_xContext);
XExecutableDialog xDialog = (XExecutableDialog) UnoRuntime.queryInterface(XExecutableDialog.class, dialog);
xDialog.execute();
// Dispose the dialog after execution (to free up the memory)
XComponent xComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, dialog);
if (xComponent!=null) {
xComponent.dispose();
}
} catch (Exception e) {
// Failed to get dialog
}
}
private void publishAsXhtml() {
RegistryHelper registry = new RegistryHelper(m_xContext);
try {
Object view = registry.getRegistryView(ToolbarSettingsDialog.REGISTRY_PATH, false);
XPropertySet xProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class,view);
short nXhtmlFormat = XPropertySetHelper.getPropertyValueAsShort(xProps, "XhtmlFormat");
switch (nXhtmlFormat) {
case 0: publish(TargetFormat.xhtml); break;
case 1: publish(TargetFormat.xhtml11); break;
case 2: publish(TargetFormat.xhtml_mathml); break;
case 3: publish(TargetFormat.html5);
}
} catch (Exception e) {
// Failed to get registry view
}
}
private void publishAsEpub() {
RegistryHelper registry = new RegistryHelper(m_xContext);
try {
Object view = registry.getRegistryView(ToolbarSettingsDialog.REGISTRY_PATH, false);
XPropertySet xProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class,view);
short nEpubFormat = XPropertySetHelper.getPropertyValueAsShort(xProps, "EpubFormat");
switch (nEpubFormat) {
case 0: publish(TargetFormat.epub); break;
case 1: publish(TargetFormat.epub3);
}
} catch (Exception e) {
// Failed to get registry view
}
}
private void publish(TargetFormat format) {
if (unoPublisher==null) {
unoPublisher = new XhtmlUNOPublisher(m_xContext,m_xFrame,"Writer2xhtml");
}
unoPublisher.publish(format);
}
}

View file

@ -1,242 +0,0 @@
/************************************************************************
*
* XhtmlOptionsDialog.java
*
* Copyright: 2002-2014 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.4 (2014-09-25)
*
*/
package org.openoffice.da.comp.writer2xhtml;
import com.sun.star.awt.XDialog;
import com.sun.star.beans.XPropertySet;
import com.sun.star.uno.XComponentContext;
import org.openoffice.da.comp.w2lcommon.helper.PropertyHelper;
import org.openoffice.da.comp.w2lcommon.filter.OptionsDialogBase;
/** This class provides a uno component which implements a filter ui for the
* Xhtml export
*/
public class XhtmlOptionsDialog extends OptionsDialogBase {
/** The component will be registered under this name.
*/
public static String __serviceName = "org.openoffice.da.writer2xhtml.XhtmlOptionsDialog";
/** The component should also have an implementation name.
*/
public static String __implementationName = "org.openoffice.da.comp.writer2xhtml.XhtmlOptionsDialog";
public String getDialogLibraryName() { return "w2phtml"; }
/** Return the name of the dialog within the library
*/
public String getDialogName() { return "XhtmlOptions"; }
/** Return the name of the registry path
*/
public String getRegistryPath() {
return "/org.openoffice.da.Writer2xhtml.Options/XhtmlOptions";
}
/** Create a new XhtmlOptionsDialog */
public XhtmlOptionsDialog(XComponentContext xContext) {
super(xContext);
xMSF = W2XRegistration.xMultiServiceFactory;
}
/** Load settings from the registry to the dialog */
protected void loadSettings(XPropertySet xProps) {
// Style
loadConfig(xProps);
loadCheckBoxOption(xProps, "ConvertToPx");
int nScaling = loadNumericOption(xProps, "Scaling");
if (nScaling<=1) { // Workaround for an obscure bug in the extension manager
setNumericFieldValue("Scaling",100);
}
loadTextFieldOption(xProps, "MinLetterSpacing");
loadTextFieldOption(xProps, "MaxWidth");
loadTextFieldOption(xProps, "PageBreakStyle");
loadCheckBoxOption(xProps, "InlineCSS");
loadCheckBoxOption(xProps, "EmbedImg");
loadCheckBoxOption(xProps, "EmbedSVG");
loadCheckBoxOption(xProps, "Greenstone");
// Special content
loadCheckBoxOption(xProps, "Notes");
loadCheckBoxOption(xProps, "UseDublinCore");
// AutoCorrect
loadCheckBoxOption(xProps, "IgnoreHardLineBreaks");
loadCheckBoxOption(xProps, "IgnoreEmptyParagraphs");
loadCheckBoxOption(xProps, "IgnoreDoubleSpaces");
// Files
loadCheckBoxOption(xProps, "AlignSplitsToPages");
loadCheckBoxOption(xProps, "Split");
loadListBoxOption(xProps, "SplitLevel");
loadListBoxOption(xProps, "RepeatLevels");
loadCheckBoxOption(xProps, "SaveImagesInSubdir");
loadCheckBoxOption(xProps, "UseMathjax");
updateLockedOptions();
enableControls();
}
/** Save settings from the dialog to the registry and create FilterData */
protected void saveSettings(XPropertySet xProps, PropertyHelper helper) {
// Style
short nConfig = saveConfig(xProps, helper);
String[] sCoreStyles = { "Chocolate", "Midnight", "Modernist",
"Oldstyle", "Steely", "Swiss", "Traditional", "Ultramarine" };
switch (nConfig) {
case 0: helper.put("ConfigURL","*default.xml"); break;
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8: helper.put("ConfigURL","*cleanxhtml.xml");
helper.put("custom_stylesheet", "http://www.w3.org/StyleSheets/Core/"+sCoreStyles[nConfig-1]);
break;
case 9: helper.put("ConfigURL","$(user)/writer2xhtml.xml");
helper.put("AutoCreate","true");
helper.put("TemplateURL", "$(user)/writer2xhtml-template.xhtml");
helper.put("StyleSheetURL", "$(user)/writer2xhtml-styles.css");
}
saveTextFieldOption(xProps, helper, "MinLetterSpacing", "min_letter_spacing");
saveTextFieldOption(xProps, helper, "MaxWidth", "max_width");
saveTextFieldOption(xProps, helper, "PageBreakStyle", "page_break_style");
saveCheckBoxOption(xProps, helper, "ConvertToPx", "convert_to_px");
saveNumericOptionAsPercentage(xProps, helper, "Scaling", "scaling");
// Special content
saveCheckBoxOption(xProps, helper, "InlineCSS", "css_inline");
saveCheckBoxOption(xProps, helper, "EmbedImg", "embed_svg");
saveCheckBoxOption(xProps, helper, "EmbedSVG", "embed_img");
saveCheckBoxOption(xProps, helper, "Greenstone", "greenstone");
saveCheckBoxOption(xProps, helper, "AlignSplitsToPages","align_splits_to_pages");
saveCheckBoxOption(xProps, helper, "Notes", "notes");
saveCheckBoxOption(xProps, helper, "UseDublinCore", "use_dublin_core");
// AutoCorrect
saveCheckBoxOption(xProps, helper, "IgnoreHardLineBreaks", "ignore_hard_line_breaks");
saveCheckBoxOption(xProps, helper, "IgnoreEmptyParagraphs", "ignore_empty_paragraphs");
saveCheckBoxOption(xProps, helper, "IgnoreDoubleSpaces", "ignore_double_spaces");
// Files
boolean bSplit = saveCheckBoxOption(xProps, "Split");
short nSplitLevel = saveListBoxOption(xProps, "SplitLevel");
short nRepeatLevels = saveListBoxOption(xProps, "RepeatLevels");
if (!isLocked("split_level")) {
if (bSplit) {
helper.put("split_level",Integer.toString(nSplitLevel+1));
helper.put("repeat_levels",Integer.toString(nRepeatLevels));
}
else {
helper.put("split_level","0");
}
}
saveCheckBoxOption(xProps, helper, "SaveImagesInSubdir", "save_images_in_subdir");
saveCheckBoxOption(xProps, helper, "UseMathjax", "use_mathjax");
}
// Implement XDialogEventHandler
public boolean callHandlerMethod(XDialog xDialog, Object event, String sMethod) {
if (sMethod.equals("ConfigChange")) {
updateLockedOptions();
enableControls();
}
else if (sMethod.equals("SplitChange")) {
enableSplitLevel();
}
return true;
}
public String[] getSupportedMethodNames() {
String[] sNames = { "ConfigChange", "SplitChange" };
return sNames;
}
private void enableControls() {
// Style
setControlEnabled("ScalingLabel",!isLocked("scaling"));
setControlEnabled("Scaling",!isLocked("scaling"));
setControlEnabled("MinLetterSpacing",!isLocked("min_letter_spacing"));
setControlEnabled("MaxWidth",!isLocked("max_width"));
setControlEnabled("PageBreakStyle",!isLocked("page_break_style"));
setControlEnabled("ConvertToPx",!isLocked("convert_to_px"));
// Special content
setControlEnabled("InlineCSS",!isLocked("css_inline"));
setControlEnabled("EmbedImg",!isLocked("embed_img"));
setControlEnabled("EmbedSVG",!isLocked("embed_svg"));
setControlEnabled("Greenstone",!isLocked("greenstone"));
setControlEnabled("AlignSplitsToPages",!isLocked("align_splits_to_pages"));
setControlEnabled("Notes",!isLocked("notes"));
setControlEnabled("UseDublinCore",!isLocked("use_dublin_core"));
// AutoCorrect
setControlEnabled("IgnoreHardLineBreaks",!isLocked("ignore_hard_line_breaks"));
setControlEnabled("IgnoreEmptyParagraphs",!isLocked("ignore_empty_paragraphs"));
setControlEnabled("IgnoreDoubleSpaces",!isLocked("ignore_double_spaces"));
// Files
boolean bSplit = getCheckBoxStateAsBoolean("Split");
setControlEnabled("Split",!isLocked("split_level"));
setControlEnabled("SplitLevelLabel",!isLocked("split_level") && bSplit);
setControlEnabled("SplitLevel",!isLocked("split_level") && bSplit);
setControlEnabled("RepeatLevelsLabel",!isLocked("repeat_levels") && !isLocked("split_level") && bSplit);
setControlEnabled("RepeatLevels",!isLocked("repeat_levels") && !isLocked("split_level") && bSplit);
setControlEnabled("SaveImagesInSubdir",!isLocked("save_images_in_subdir"));
setControlEnabled("UseMathjax",(this instanceof XhtmlOptionsDialogMath) && !isLocked("use_mathjax"));
}
private void enableSplitLevel() {
if (!isLocked("split_level")) {
boolean bState = getCheckBoxStateAsBoolean("Split");
setControlEnabled("SplitLevelLabel",bState);
setControlEnabled("SplitLevel",bState);
if (!isLocked("repeat_levels")) {
setControlEnabled("RepeatLevelsLabel",bState);
setControlEnabled("RepeatLevels",bState);
}
}
}
}

View file

@ -1,48 +0,0 @@
/************************************************************************
*
* XhtmlOptionsDialogMath.java
*
* Copyright: 2002-2004 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.4 (2014-08-18)
*
*/
package org.openoffice.da.comp.writer2xhtml;
import com.sun.star.uno.XComponentContext;
/** This class provides a uno component which implements a filter ui for the
* Xhtml export for the XHTML+MathML and HTML export.
* This variant of the dialog has the MathJax setting enabled
*/
public class XhtmlOptionsDialogMath extends XhtmlOptionsDialog {
/** The component will be registered under this name.
*/
public static String __serviceName = "org.openoffice.da.writer2xhtml.XhtmlOptionsDialogMath";
/** The component should also have an implementation name.
*/
public static String __implementationName = "org.openoffice.da.comp.writer2xhtml.XhtmlOptionsDialogMath";
/** Create a new XhtmlOptionsDialogMath */
public XhtmlOptionsDialogMath(XComponentContext xContext) {
super(xContext);
}
}

View file

@ -1,146 +0,0 @@
/************************************************************************
*
* XhtmlUNOPublisher.java
*
* Copyright: 2002-2015 by Henrik Just
*
* This file is part of Writer2LaTeX.
*
* Writer2LaTeX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Writer2LaTeX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Writer2LaTeX. If not, see <http://www.gnu.org/licenses/>.
*
* Version 1.6 (2015-04-05)
*
*/
package org.openoffice.da.comp.writer2xhtml;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
import org.openoffice.da.comp.w2lcommon.filter.UNOPublisher;
import org.openoffice.da.comp.w2lcommon.helper.MessageBox;
import org.openoffice.da.comp.w2lcommon.helper.RegistryHelper;
import org.openoffice.da.comp.w2lcommon.helper.StreamGobbler;
import org.openoffice.da.comp.w2lcommon.helper.XPropertySetHelper;
import com.sun.star.beans.XPropertySet;
import com.sun.star.frame.XFrame;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import w2phtml.util.Misc;
public class XhtmlUNOPublisher extends UNOPublisher {
public XhtmlUNOPublisher(XComponentContext xContext, XFrame xFrame, String sAppName) {
super(xContext, xFrame, sAppName);
}
/** Display the converted document depending on user settings
*
* @param sURL the URL of the converted document
* @param format the target format
*/
@Override protected void postProcess(String sURL, TargetFormat format) {
RegistryHelper registry = new RegistryHelper(xContext);
short nView = 1;
String sExecutable = null;
try {
Object view = registry.getRegistryView(ToolbarSettingsDialog.REGISTRY_PATH, false);
XPropertySet xProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class,view);
if (format==TargetFormat.xhtml || format==TargetFormat.xhtml11 || format==TargetFormat.xhtml_mathml || format==TargetFormat.html5) {
nView = XPropertySetHelper.getPropertyValueAsShort(xProps, "XhtmlView");
sExecutable = XPropertySetHelper.getPropertyValueAsString(xProps, "XhtmlExecutable");
}
else { // EPUB
nView = XPropertySetHelper.getPropertyValueAsShort(xProps, "EpubView");
sExecutable = XPropertySetHelper.getPropertyValueAsString(xProps, "EpubExecutable");
}
} catch (Exception e) {
// Failed to get registry view
}
File file = Misc.urlToFile(sURL);
if (file.exists()) {
if (nView==0) {
return;
}
else if (nView==1) {
if (openWithDefaultApplication(file)) {
return;
}
}
else if (nView==2) {
if (openWithCustomApplication(file, sExecutable)) {
return;
}
}
}
MessageBox msgBox = new MessageBox(xContext, xFrame);
msgBox.showMessage("w2phtml","Error: Failed to open exported document");
}
// Open the file in the default application on this system (if any)
private boolean openWithDefaultApplication(File file) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.open(file);
return true;
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
return false;
}
// Open the file with the user defined application
private boolean openWithCustomApplication(File file, String sExecutable) {
try {
Vector<String> command = new Vector<String>();
command.add(sExecutable);
command.add(file.getPath());
ProcessBuilder pb = new ProcessBuilder(command);
Process proc = pb.start();
// Gobble the error stream of the application
StreamGobbler errorGobbler = new
StreamGobbler(proc.getErrorStream(), "ERROR");
// Gobble the output stream of the application
StreamGobbler outputGobbler = new
StreamGobbler(proc.getInputStream(), "OUTPUT");
errorGobbler.start();
outputGobbler.start();
// The application exists if the process exits with 0
return proc.waitFor()==0;
}
catch (InterruptedException e) {
return false;
}
catch (IOException e) {
return false;
}
}
}