From ed5640d8b587fbcfed7dd7967f3de04b37a76f26 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 11:06:44 +0200 Subject: Adding upstream version 4:7.4.7. Signed-off-by: Daniel Baumann --- .../filter/detection/typeDetection/Helper.java | 431 ++++++++++++++++ .../detection/typeDetection/TypeDetection.java | 546 +++++++++++++++++++++ .../detection/typeDetection/TypeDetection.props | 31 ++ .../filter/detection/typeDetection/files.csv | 117 +++++ .../filter/detection/typeDetection/makefile.mk | 109 ++++ .../detection/typeDetection/preselectedFilter.csv | 6 + .../detection/typeDetection/preselectedType.csv | 6 + .../filter/detection/typeDetection/serviceName.csv | 6 + .../filter/misc/FinalizedMandatoryTest.java | 304 ++++++++++++ .../filter/misc/TypeDetection6FileFormat.java | 127 +++++ .../filter/misc/TypeDetection6FileFormat.xcu | 42 ++ filter/qa/cppunit/data/xslt/copy.xslt | 9 + filter/qa/cppunit/msfilter-test.cxx | 76 +++ filter/qa/cppunit/priority-test.cxx | 85 ++++ filter/qa/cppunit/xslt-test.cxx | 207 ++++++++ filter/qa/data/picture.pdf | Bin 0 -> 13829 bytes filter/qa/pdf.cxx | 347 +++++++++++++ filter/qa/unit/data/TransparentText.odg | Bin 0 -> 9354 bytes filter/qa/unit/data/attributeRedefinedTest.odp | Bin 0 -> 12610 bytes filter/qa/unit/data/calc.ots | Bin 0 -> 9564 bytes filter/qa/unit/data/custom-bullet.fodp | 36 ++ filter/qa/unit/data/empty.doc | 0 filter/qa/unit/data/empty.odp | 0 filter/qa/unit/data/empty.ods | 0 filter/qa/unit/data/empty.odt | 0 filter/qa/unit/data/empty.pptx | 0 filter/qa/unit/data/filter-dialogs-test.txt | 49 ++ filter/qa/unit/data/impress.otp | Bin 0 -> 15382 bytes filter/qa/unit/data/preserve-jpg.odt | Bin 0 -> 10052 bytes filter/qa/unit/data/semi-transparent-fill.odg | Bin 0 -> 10597 bytes filter/qa/unit/data/semi-transparent-line.odg | Bin 0 -> 8874 bytes filter/qa/unit/data/shape-nographic.odp | Bin 0 -> 14769 bytes filter/qa/unit/data/tdf114428.xhtml | 9 + filter/qa/unit/data/writer.ott | Bin 0 -> 10017 bytes filter/qa/unit/filter-dialogs-test.cxx | 61 +++ filter/qa/unit/svg.cxx | 380 ++++++++++++++ filter/qa/unit/textfilterdetect.cxx | 199 ++++++++ 37 files changed, 3183 insertions(+) create mode 100644 filter/qa/complex/filter/detection/typeDetection/Helper.java create mode 100644 filter/qa/complex/filter/detection/typeDetection/TypeDetection.java create mode 100644 filter/qa/complex/filter/detection/typeDetection/TypeDetection.props create mode 100644 filter/qa/complex/filter/detection/typeDetection/files.csv create mode 100644 filter/qa/complex/filter/detection/typeDetection/makefile.mk create mode 100644 filter/qa/complex/filter/detection/typeDetection/preselectedFilter.csv create mode 100644 filter/qa/complex/filter/detection/typeDetection/preselectedType.csv create mode 100644 filter/qa/complex/filter/detection/typeDetection/serviceName.csv create mode 100644 filter/qa/complex/filter/misc/FinalizedMandatoryTest.java create mode 100644 filter/qa/complex/filter/misc/TypeDetection6FileFormat.java create mode 100644 filter/qa/complex/filter/misc/TypeDetection6FileFormat.xcu create mode 100644 filter/qa/cppunit/data/xslt/copy.xslt create mode 100644 filter/qa/cppunit/msfilter-test.cxx create mode 100644 filter/qa/cppunit/priority-test.cxx create mode 100644 filter/qa/cppunit/xslt-test.cxx create mode 100644 filter/qa/data/picture.pdf create mode 100644 filter/qa/pdf.cxx create mode 100644 filter/qa/unit/data/TransparentText.odg create mode 100644 filter/qa/unit/data/attributeRedefinedTest.odp create mode 100644 filter/qa/unit/data/calc.ots create mode 100644 filter/qa/unit/data/custom-bullet.fodp create mode 100644 filter/qa/unit/data/empty.doc create mode 100644 filter/qa/unit/data/empty.odp create mode 100644 filter/qa/unit/data/empty.ods create mode 100644 filter/qa/unit/data/empty.odt create mode 100644 filter/qa/unit/data/empty.pptx create mode 100644 filter/qa/unit/data/filter-dialogs-test.txt create mode 100644 filter/qa/unit/data/impress.otp create mode 100644 filter/qa/unit/data/preserve-jpg.odt create mode 100644 filter/qa/unit/data/semi-transparent-fill.odg create mode 100644 filter/qa/unit/data/semi-transparent-line.odg create mode 100644 filter/qa/unit/data/shape-nographic.odp create mode 100644 filter/qa/unit/data/tdf114428.xhtml create mode 100644 filter/qa/unit/data/writer.ott create mode 100644 filter/qa/unit/filter-dialogs-test.cxx create mode 100644 filter/qa/unit/svg.cxx create mode 100644 filter/qa/unit/textfilterdetect.cxx (limited to 'filter/qa') diff --git a/filter/qa/complex/filter/detection/typeDetection/Helper.java b/filter/qa/complex/filter/detection/typeDetection/Helper.java new file mode 100644 index 000000000..23eb07fc4 --- /dev/null +++ b/filter/qa/complex/filter/detection/typeDetection/Helper.java @@ -0,0 +1,431 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +package complex.filter.detection.typeDetection; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.io.NotConnectedException; +import com.sun.star.io.XInputStream; + +import helper.StreamSimulator; + +import java.io.*; +import java.net.URL; +import java.net.URLConnection; +import java.util.Iterator; +import java.util.HashMap; +import java.util.StringTokenizer; +import java.util.ArrayList; + +import lib.TestParameters; +import share.LogWriter; +import util.PropertyName; +import util.utils; + + + +/** Helper class for "TypeDetection" + * This class do file handling. + */ +public class Helper { + + /** The runner log writer + * @member m_log for log purposes + * @member m_sTestDocPath directory for searching files to load + * @member m_vFiles list of all files described in "files.csv" + * @member m_hFileURLs contains the position of a file name in the m_vFiles Vector + * @member m_hFileTypes contains the position of a file type in the m_vFiles Vector + * @member m_param the test parameters + */ + + private final LogWriter m_log; + + private final String m_sTestDocPath; + + private final ArrayList> m_vFiles; + + private final HashMap m_hFileURLs = new HashMap(); + + private final HashMap m_hFileTypes = new HashMap(); + + private final TestParameters m_param; + + /** + * construct a new instance of this class + * It creates the "todo" list and position lists for URL and + * and Type inside the "todo" list + * + * @param param the test parameters + * + * @param log the log writer + */ + + public Helper(TestParameters param, LogWriter log) { + + m_param = param; + m_log = log; + + + // get all files from the given directory + m_sTestDocPath = (String)param.get("TestDocumentPath"); + + // get all files from "files.csv" + m_vFiles = getToDoList((String)m_param.get("csv.files")); + + createFilesList(); + } + + + /** Reads a comma separated file (CSV). Every line of the file is + * represented by an Vector entry. Every data entry of a row is + * also stored in a Vector. So the returned value is a + * Vector[][] where the first dimension represents a row + * and the second dimension includes the data values. + * @param csvFileName the name of the csv file + * @return Vector filled with Vector filled with data of a row + */ + public ArrayList> getToDoList(String csvFileName){ + + try { + + ArrayList> vAll = new ArrayList>(); + ArrayList vFields = new ArrayList(); + + // get content of file + ArrayList content = getCSVFileContent(csvFileName); + + // remove superfluous content like "#" started lines + content = removeSuperfluousContent(content); + + // replace all place holders in file + content = replacePlaceHolder(content); + + // create Enumeration + Iterator contentEnum = content.iterator(); + + // the first line contains field names of the columns + // split line by ";" + StringTokenizer fields = new StringTokenizer( + contentEnum.next(),";"); + int fieldCount = 0; + while (fields.hasMoreElements()){ + vFields.add(fields.nextToken()); + fieldCount++; + } + + // fill vData with data of CSV-row + while (contentEnum.hasNext()){ + ArrayList vData = new ArrayList(); + + StringTokenizer data = new StringTokenizer( + contentEnum.next(),";", true); + + // example: data = "firstData;secondData;;forthData" + // => three tokens => missing one data because the imagine + // "thirdData" was not received by data.nextToken() + // Therefore here comes a special handling for empty data + boolean nextIsData = false; + int dataCount = 0; + while (data.hasMoreTokens()) { + String myToken = data.nextToken(); + // if the "thirdData" will be received, myToken=";" but + // vData must add an empty String + if (myToken.equals(";")){ + if (nextIsData ) { + vData.add(""); + dataCount++; + nextIsData = false; + } + nextIsData = true; + } else { + vData.add(myToken); + dataCount++; + nextIsData = false; + } + } + for (int i=dataCount; i < fieldCount; i++) vData.add(""); + vAll.add(vData); + } + + + return vAll; + + } catch(ClassCastException e) { + e.printStackTrace(); + } + return null; + } + + /** The csv files "files", "preselectedFilter", "preselectedType" and + * "serviceName" are delivered beside this class. This function seeks for + * the csv files and read them. + * @param csvFileName the name of the csv file + * @return a Vector containing the content of the file. if the file + * cannot be read + */ + + private ArrayList getCSVFileContent(String csvFileName) { + try { + ArrayList content = new ArrayList(); + BufferedReader br; + String line; + if ( m_param.getBool(PropertyName.DEBUG_IS_ACTIVE) ) { + System.out.println("Looking for "+csvFileName); + } + + URL url = getClassURL(csvFileName); + + if (url != null) { + URLConnection connection = url.openConnection(); + InputStream in = connection.getInputStream(); + + br = new BufferedReader(new InputStreamReader(in)); + try { + while( ( line = br.readLine() ) != null ) { + content.add( line ); + } + } catch (IOException e) { + br.close(); + return null; + } + br.close(); + return content; + } + + }catch (IOException e) { + }catch(NullPointerException e) { + return null; + } + return null; + } + + /** returns a XInputStream of given file + * @param filePath the path to the file which should be loaded + * @return the XInputStream, if the + * file cannot be read + * @throws NotConnectedException was thrown if it was not possible to open filePath + */ + public XInputStream getFileStream( String filePath ) + throws NotConnectedException { + return new StreamSimulator(filePath, true, m_param); + } + + /** replaces place holder in preselectedFilter. + * Because of filter names depend on StarOffice version like + * "StarOffice 6.0 Textdokument" or ""StarSuite 7 Textdokument" + * The filter names must be changed. The place holder will be replaced + * by an equivalent in "typeDetection.props" + * @param content the content of a csv file + * @return changed file content + */ + private ArrayList replacePlaceHolder(ArrayList content){ + + ArrayList vReturn = new ArrayList(); + + ArrayList placeHolders = new ArrayList(); + Iterator paramsIter = m_param.keySet().iterator(); + String placeHolder = (String)m_param.get("placeHolder"); + + // get all place holders from typeDetection.csv + while (paramsIter.hasNext()){ + String holderKey = paramsIter.next(); + if (holderKey.startsWith(placeHolder)){ + placeHolders.add(holderKey); + } + } + + // replace all occurrences of place holders in 'CSVData' + Iterator cont = content.iterator(); + + while( cont.hasNext() ) { + + String line = cont.next(); + String newLine = line; + Iterator holders = placeHolders.iterator(); + + while( holders.hasNext() ) { + + String holder = holders.next(); + int startPos = line.indexOf(holder); + + if (startPos > -1){ + try{ + String holderValue = (String) m_param.get(holder); + + newLine = newLine.substring(0,startPos) + holderValue + + newLine.substring(startPos + holder.length()); + + } catch (java.lang.IndexOutOfBoundsException e){ + m_log.println("ERROR: problems while creating placeholder" + + " replaced list: "+ e); + } + } + } + vReturn.add(newLine); + } + return vReturn; + } + + /** Removes lines of an ascii file content which starts with "#" + * or are empty + * @param content content of a csv file + * @return a stripped Vector + */ + private ArrayList removeSuperfluousContent(ArrayList content){ + ArrayList newContent = new ArrayList(); + Iterator cont = content.iterator(); + while( cont.hasNext() ) { + String line = cont.next(); + if (( ! line.startsWith( "#" ))&& ( line.length() != 0 )) { + newContent.add( line ); + } + } + return newContent; + } + + /** returns a MediaDescriptor filled with given properties and + * values. + * @param propNames String Array of property names + * @param values Object Array of property values + * @return PropertyValue[] + * @see com.sun.star.beans.PropertyValue + * @see com.sun.star.document.MediaDescriptor + */ + public PropertyValue[] createMediaDescriptor(String[] propNames, Object[] values) { + PropertyValue[] props = new PropertyValue[propNames.length] ; + + for (int i = 0; i < props.length; i++) { + props[i] = new PropertyValue() ; + props[i].Name = propNames[i] ; + if (values != null && i < values.length) { + props[i].Value = values[i] ; + } + } + + return props ; + } + + /** Appends system file separator if needed + * @param s the system path + * @return system path with ending system file separator + */ + public String ensureEndingFileSep(String s){ + if(s != null && !s.equals("") && !s.endsWith(File.separator)){ + s = s.trim() + File.separator; + }else if(s == null) + s = ""; + return s; + } + + /** Returns the file URL for the given file name assembled by + * "TestDocumentPath" of typeDetection.props and "fileURL" of files.csv + * @param fileAlias the alias name of the file + * @return file URL + * @throws FileAliasNotFoundException was thrown if alias does not exist + */ + public String getURLforfileAlias(String fileAlias) + throws FileAliasNotFoundException{ + try{ + String fileURL = m_hFileURLs.get(fileAlias).toString(); + return utils.getFullURL(ensureEndingFileSep(m_sTestDocPath) + fileURL); + } catch (NullPointerException e){ + throw new FileAliasNotFoundException(fileAlias, e); + } + + } + + /** Returns the file type for the given file name containing in files.csv + * @param fileAlias the alias name of the file + * @return file type + * @throws FileAliasNotFoundException was thrown if not alias was thrown + */ + public String getTypeforfileAlias(String fileAlias) + throws FileAliasNotFoundException{ + try{ + return m_hFileTypes.get(fileAlias).toString(); + } catch (NullPointerException e){ + throw new FileAliasNotFoundException(fileAlias, e); + } + } + + /** + * Fills the Hashtable m_hFileURLs with all file names and their URL + * and the Hashtable m_hFileTypes with all file names and their file + * type name. This information is extracted from "files.csv" + * This is for faster access to get fileURL and fileType of fileAlias + */ + private void createFilesList(){ + for (int i = 0; i < m_vFiles.size();i++){ + ArrayList toDo = m_vFiles.get(i); + m_hFileURLs.put(toDo.get(0), toDo.get(1)); + m_hFileTypes.put(toDo.get(0), toDo.get(2)); + } + } + + + /** Validate the returned file type for the file alias with the + * possible file types + * @param currentFileType the returned file type + * @param fileTypes all possible file types + * @return true if valid + */ + public boolean checkFileType(String currentFileType, String fileTypes){ + + StringTokenizer data = new StringTokenizer(fileTypes,":", true); + + boolean found = false; + while (data.hasMoreElements()) { + + String actualFileType = data.nextElement().toString(); + + found = found || currentFileType.equals(actualFileType); + } + return found; + } + + /** creates an input/output parameter of PropertyValue[]. + * @return PropertyValue[][] + * @param PropVal a PropertyValue + */ + public PropertyValue[][] createInOutPropertyValue(PropertyValue[] PropVal){ + PropertyValue[][] dummy = new PropertyValue[1][]; + dummy[0] = PropVal; + return dummy; + } + + private URL getClassURL(String fileName){ + String PackagePath = this.getClass().getPackage().getName().replace('.','/'); + return this.getClass().getResource("/" + PackagePath +"/" + fileName); + } + + public String getClassURLString(String fileName){ + return getClassURL(fileName).toString().replaceAll("file:",""); + } + + +} + +/** This exception should be thrown if a method seeks for an invalid alias name */ +class FileAliasNotFoundException extends java.lang.Exception{ + /** throws error message with wrong alias name + * @param fileAlias the alias name + */ + public FileAliasNotFoundException(String fileAlias, Throwable cause){ + super("Could not get '"+fileAlias +"'", cause); + } +} diff --git a/filter/qa/complex/filter/detection/typeDetection/TypeDetection.java b/filter/qa/complex/filter/detection/typeDetection/TypeDetection.java new file mode 100644 index 000000000..2c7a6934a --- /dev/null +++ b/filter/qa/complex/filter/detection/typeDetection/TypeDetection.java @@ -0,0 +1,546 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +package complex.filter.detection.typeDetection; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.document.XTypeDetection; +import com.sun.star.io.NotConnectedException; +import com.sun.star.io.XInputStream; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; +import complexlib.ComplexTestCase; +import java.io.File; + +import java.util.Iterator; +import java.util.ArrayList; +import util.utils; + + + +/** Check "TypeDetection" + *

+ * This test will check the file type detection. This will be done by filling + * properties of a MediaDescriptor. + * + * In the test method checkByURLonly the + * MediaDescriptor was filled at once with the URL of a test + * file. At second it was filled with a XInputStream from test + * file. In both subtests the returned file type must match with an expected + * type. + * + * In the test method checkPreselectedType the + * MediaDescriptor was filled with the URL of the test file and + * with the name of a type which should be used. The returned type of the + * TypeDetection must match with an expected type. + * + * In the test method checkPreselectedFilter the + * MediaDescriptor was filled with the URL of the test file and + * with the name of a filter which should be used. The returned type of the + * TypeDetection must match with an expected type. + * + * In the test method checkPreselectedDocService the + * MediaDescriptor was filled with the URL of the test file and + * with the name of a document service which should be used. The returned type + * of the TypeDetection must match with an expected type. + * + * + * To get information on which test file should support which type, filter and + * document service, this information was collected from configuration files: + *

+ *

+ *

+ * typeDetection.props

+ * At first there will be the typeDetection.props. Here the following + * properties should be set (with example values): + * + * TestDocumentPath=file:///path/to/my/testdocuments + * placeHolder=% + * %SO6productname=StarOffice + * %SO6formatversion=6.0 + * + * TestDocumentPath: this is the path to your test documents. If + * you have grouped your documents ie. by writer, calc, ... then it should be + * the root path. To specify the particular sub folders you have to use + * csv.files + *

+ * files.csv: In this file all test documents are listed. + * Syntax: fileAlias;fileURL;defaultURLFileType;StreamFileTypes + * Example: + * + * Writer6_1;Writer/Writer6.sxw;writer_StarOffice_XML_Writer;writer_StarOffice_XML_Writer + * text1;Writer/Text.txt:generic_Text:generic_Text + * + * The first example shows you the following: + * Writer6_1 is a free chosen name + * Writer/Writer6.sxw is the document path. This will be assembled + * by TestDocumentPath from typeDetection.props. + * writer_StarOffice_XML_Writer: this is the default file type of + * this file + * + * The second example displays two document types for + * XInputStream (generic_Text). These + * two document types are listed by a colon ':' as separator. + * This is needed because XInputStream can detect a text file as + * generic_Text. + *

+ * + *

+ * preselectedFilter.csv

+ * In this file you can choose a special + * filter to detect the document. This makes sense ie. for csv-files: You can + * open csv files as Writer or as Calc. To check this case you have to specify + * in csv.files a fileAlias like ?csv_writer? and ?csv_calc? with + * the same fileURL and its specific defaultFileType. + * The returned file type by TypeDetection must be equal to the + * corresponding defaultFileType from csv.files + * + * Syntax: fileAlias;FilterName;FilterOptions;FilterData + * Example: Writer6_1;%SO6productname %SO6formatversion Textdocument; + * + * The example shows the following: + * Writer6_1 is the same as in csv.files + * %SO6productname %SO6formatversion Textdokument is the filter + * name which should be used. Here we have a special: %SO6productname + * %SO6formatversion will be replaced by the equals of + * typeDetection.props. The filter names depends on the Office + * name and version. So a future Office could be called ?StarSuite 8?. + * FilterOptions is not relevant for this filter. But ie. for csv + * filter this entry could be used to specify the separator of the csv file. + * FilterData if filter needs some FilterData arguments you can + * specify them here + * + *

+ *

+ * preselectedType.csv

+ * In this file you can preselect the type + * TypeDetection should use. + * The file type returned by TypeDetection must be equal to the + * preselected file type. + * Note: If you try to use invalid types you will get a failed test because + * TypeDetection tries to find out the type itself. + * + * Syntax: fileAlias;fileType + * Example: Writer6_1;writer_StarOffice_XML_Writer + * + * This example shows the following: + * Writer6_1 is the same as in csv.files + * writer_StarOffice_XML_Writer is the file type which was used as + * parameter in MediaDescriptor. This type must be returned from + * TypeDetection + * + *

+ *

+ * serviceName.csv

In this file you can preselect a service name + * to detect the file type. The file type returned by + * TypeDetection must be equal to the corresponding + * defaultFileType from csv.files + * + * Syntax: fileAlias;serviceName + * Example: Writer6_1;com.sun.star.text.FormatDetector + * + * This example shows the following: + * Writer6_1 is the same as in csv.files + * com.sun.star.text.FormatDetector is the service name which was + * used as parameter in MediaDescriptor. + * + * + *

+ * All these files will be copied by make file beside of + * typeDetection.class. + * @see com.sun.star.document.XTypeDetection + * @see com.sun.star.document.MediaDescriptor + */ +public class TypeDetection extends ComplexTestCase { + + /** + * @member m_xDetection the object to test + * @member helper instance of helper class + */ + + static XTypeDetection m_xDetection; + static Helper helper = null; + + /** + * A function to tell the framework, which test functions are available. + * @return All test methods. + */ + @Override + public String[] getTestMethodNames() { + return new String[]{"checkByURLonly", + "checkPreselectedType", + "checkPreselectedFilter", + "checkPreselectedDocService", + "checkStreamLoader", + "checkStreamLoader"}; + + } + + /** Create the environment for following tests. + * Use either a component loader from desktop or + * from frame + * @throws Exception Exception + */ + public void before() throws Exception { + + // create TypeDetection + XMultiServiceFactory xMSF = param.getMSF(); + assure("Could not get XMultiServiceFactory", xMSF != null); + + Object oInterface = xMSF.createInstance( + "com.sun.star.document.TypeDetection"); + + if (oInterface == null) { + failed("Service wasn't created") ; + } + + XInterface oObj = (XInterface) oInterface ; + log.println("ImplName: "+utils.getImplName(oObj)); + + m_xDetection = UnoRuntime.queryInterface(XTypeDetection.class, oInterface); + Iterator k = param.keySet().iterator(); + while (k.hasNext()){ + String kName = k.next(); + log.println(kName + ":" + param.get(kName).toString()); + } + // create instance of helper class + helper = new Helper(param, log); + + } + + /** + * close the environment + */ + public void after() { + } + + /** + * The MediaDescriptor was filled with the URL of a file. The + * type of the file is known and must be returned by + * MediaDescriptor + * + * Syntax of files.csv: + * fileAlias;fileURL;fileType + * + */ + public void checkByURLonly() { + try{ + log.println("### checkByURLonly() ###"); + ArrayList> CSVData = helper.getToDoList( + (String)param.get("csv.files")); + Iterator> allToDos = CSVData.iterator(); + + while (allToDos.hasNext()){ + ArrayList toDo = allToDos.next(); + + String fileAlias = toDo.get(0); + String fileURL = toDo.get(1); + String URLfileType = toDo.get(2); + String StreamfileType = toDo.get(3); + + fileURL = utils.getFullURL(helper.ensureEndingFileSep( + (String)param.get("TestDocumentPath")) + fileURL); + + log.println("actual '"+ fileAlias + + "' ['" + URLfileType + "']: '" + fileURL); + + checkMediaDescriptorURL(fileAlias, fileURL, URLfileType); + checkMediaDescriptorXInputStream(fileAlias, fileURL, StreamfileType); + } + + } catch (ClassCastException e){ + failed(e.toString(), ContinueWithTest.YES); + } + } + + /** To check the TypeDetection by URL the MediaDescriptor + * was filled at first with the URL only, at second with XInputStream + * only. The TypeDetection must return the expected value + * @param fileAlias the alias name of the test file + * @param fileURL the URL of the test file + * @param fileType the expected type of the test file + * @see com.sun.star.document.MediaDescriptor + */ + private void checkMediaDescriptorURL( + String fileAlias, String fileURL, String fileType){ + + PropertyValue[] MediaDescriptor = helper.createMediaDescriptor( + new String[] {"URL"}, + new Object[] {fileURL}); + log.println("check only by URL..."); + + String type = m_xDetection.queryTypeByDescriptor( + helper.createInOutPropertyValue(MediaDescriptor), true); + + boolean fileTypeOK = helper.checkFileType(type, fileType); + + assure("\nURL-test : " + fileAlias + ":\n\treturned type: '" + type + + "'\n\texpected type: '" + fileType + "'",fileTypeOK ,ContinueWithTest.YES); + } + + /** Fills a MediaDescriptor with a XInputStream of the test + * file given by URL. + * Then the MediaDescriptor was used as parameter for TypeDetection. + * The TypeDetection must return expected type + * @param fileAlias the alias name of the test file + * @param fileURL the URL of the test file + * @param fileType the expected type of the test file + * @see com.sun.star.document.MediaDescriptor + * @see com.sun.star.io.XInputStream + */ + private void checkMediaDescriptorXInputStream( + String fileAlias, String fileURL, String fileType){ + + XInputStream xStream = null; + + try{ + xStream = helper.getFileStream( fileURL ); + } catch (NotConnectedException e) { + failed("Could not get XInputStream from file :'" + fileURL + "'",ContinueWithTest.YES); + return; + } + + PropertyValue[] MediaDescriptor = helper.createMediaDescriptor( + new String[] {"InputStream"}, + new Object[] {xStream}); + log.println("check only by XInputStream..."); + + String type = m_xDetection.queryTypeByDescriptor( + helper.createInOutPropertyValue(MediaDescriptor), true); + + boolean fileTypeOK = helper.checkFileType(type, fileType); + + assure("\nXInputStream-test: " + fileAlias + ":\n\treturned type: '" + type + + "'\n\texpected type: '" + fileType + "'", fileTypeOK, ContinueWithTest.YES); + + } + + /** + * The MediaDescriptor was filled with the URL of a file. The + * type of the file is known and must be returned by + * MediaDescriptor + * + * Syntax of files.csv: + * fileAlias;fileURL;fileType + * + */ + public void checkPreselectedType() { + try{ + log.println("### checkPreselectedType() ###"); + + ArrayList> CSVData = helper.getToDoList( + (String)param.get("csv.preselectedType")); + Iterator> allToDos = CSVData.iterator(); + + while (allToDos.hasNext()){ + try{ + ArrayList toDo = allToDos.next(); + + String fileAlias = toDo.get(0); + String fileURL = helper.getURLforfileAlias(fileAlias); + String preselectFileType = toDo.get(1); + String expectedFileType = toDo.get(2); + + PropertyValue[] MediaDescriptor = helper.createMediaDescriptor( + new String[] {"URL", "MediaType"}, + new Object[] {fileURL, preselectFileType}); + log.println("check '" + fileAlias + "' with MediaType: '" + + preselectFileType + "'"); + + String type = m_xDetection.queryTypeByDescriptor( + helper.createInOutPropertyValue(MediaDescriptor), true); + + boolean fileTypeOK = helper.checkFileType(type, expectedFileType); + + assure("\n" + fileAlias + ":\n\treturned type: '" + type + + "'\n\texpected type: '" + expectedFileType + "'", + fileTypeOK, ContinueWithTest.YES); + + } catch (FileAliasNotFoundException e){ + failed(e.toString(),ContinueWithTest.YES); + } + + } + + } catch (ClassCastException e){ + failed(e.toString(), ContinueWithTest.YES); + } + } + + + /** + * Check loading from a stream. The source for the stream is the + * first fileAlias that matches "*.txt" in the file list + * of the given directory. + */ + public void checkPreselectedFilter() { + try{ + log.println("### checkPreselectedFilter() ###"); + + ArrayList> CSVData = helper.getToDoList( + (String)param.get("csv.preselectedFilter")); + Iterator> allToDos = CSVData.iterator(); + + while (allToDos.hasNext()){ + try{ + ArrayList toDo = allToDos.next(); + + String fileAlias = toDo.get(0); + String fileURL = helper.getURLforfileAlias(fileAlias); + String filterName = toDo.get(1); + String filterOptions = toDo.get(2); + String filterData = toDo.get(3); + String expectedType = toDo.get(4); + + PropertyValue[] MediaDescriptor = helper.createMediaDescriptor( + new String[] {"URL","FilterName", + "FilterOptions","FilterData"}, + new Object[] {fileURL, filterName, + filterOptions, filterData}); + + log.println("check '" + fileAlias + "' with filter: '" + + filterName + "'"); + + String type = m_xDetection.queryTypeByDescriptor( + helper.createInOutPropertyValue(MediaDescriptor), true); + + boolean fileTypeOK = helper.checkFileType(type, expectedType); + + assure("\n" + fileAlias + ":\n\treturned type: '" + type + + "'\n\texpected type: '" + expectedType + "'", + fileTypeOK,ContinueWithTest.YES); + + } catch (FileAliasNotFoundException e){ + failed(e.toString(),ContinueWithTest.YES); + } + + } + + } catch (ClassCastException e){ + failed(e.toString(), ContinueWithTest.YES); + } + } + + /** + * Check URL encoding. The first fileAlias that matches "*.sxw" + * is used as source for several encodings. + */ + public void checkPreselectedDocService() { + try{ + log.println("### checkPreselectedDocService() ###"); + + ArrayList> CSVData = helper.getToDoList((String)param.get("csv.serviceName")); + Iterator> allToDos = CSVData.iterator(); + + while (allToDos.hasNext()){ + try{ + ArrayList toDo = allToDos.next(); + + String fileAlias = toDo.get(0); + String fileURL = helper.getURLforfileAlias(fileAlias); + String serviceName = toDo.get(1); + String fileType = helper.getTypeforfileAlias(fileAlias); + + PropertyValue[] MediaDescriptor = helper.createMediaDescriptor( + new String[] {"URL", "DocumentService"}, + new Object[] {fileURL, serviceName}); + log.println("check " + fileAlias); + + String type = m_xDetection.queryTypeByDescriptor( + helper.createInOutPropertyValue(MediaDescriptor), true); + + boolean fileTypeOK = helper.checkFileType(type, fileType); + + assure("\n" + fileAlias + ":\n\treturned type: '" + type + + "'\t\nexpected type: '" + fileType + "'", + fileTypeOK, ContinueWithTest.YES); + + } catch (FileAliasNotFoundException e){ + failed(e.toString(),ContinueWithTest.YES); + } + + } + + } catch (ClassCastException e){ + failed(e.toString(), ContinueWithTest.YES); + } + } + + public void checkStreamLoader(){ + try{ + + /* + * As files, use the typeDetection.props and one of the csv files. + * Those can, via dmake, simply set rights on others. + * + */ + log.println("### checkStreamLoader() ###"); + String[] urls = new String[] { + helper.getClassURLString("TypeDetection.props"), + helper.getClassURLString("files.csv") }; + + for (int j=0; jcom.sun.star.document.FilterFactory and + * com.sun.star.document.TypeDetection. + * + * Each of these services represent a container of PropertyValue[]. + * The PropertyValue[] contains among others the properties called + * Finalized and Mandatory. If the property + * Finalized is set to true, a filter can be removed + * but will not be able to be changed. + * If the property Mandatory is set to true, the filter + * can not be removed. + * + * Every filter, which is registered to the office, will be tested. For every filter-test + * a new instance of the mentioned services will be created. + + * During the test the property UIName + * will be changed and the service will be flushed. The test checks for expected exceptions: + * If the property Finalized equals + * true the tests check if an Exception must be thrown. + * The next step of the test is the removal of the filter was removed, then the service + * will be flushed. The test checks for expected exceptions: If the property + * Mandatory equals true, an Exception must + * be thrown. + * This test results false state if there is no filter available with: + * Finalized=true + * Finalized=false + * Mandatory=true + * Mandatory=false + */ +public class FinalizedMandatoryTest +{ + + XMultiServiceFactory xMSF; + + /** Create the environment for following tests. + * Use either a component loader from desktop or + * from frame + * @throws Exception Exception + */ + @Before public void before() throws Exception + { + + // create TypeDetection + xMSF = getMSF(); + assertNotNull("Could not get XMultiServiceFactory", xMSF); + + } + + /** + * Creates an instance for the given serviceName + * @param serviceName the name of the service which should be created + * @throws Exception was thrown if creation fails + * @return XInterface of service + */ + private XInterface getTestObject(String serviceName) throws Exception + { + + Object oInterface = xMSF.createInstance(serviceName); + + assertNotNull("Service wasn't created", oInterface); + return (XInterface) oInterface; + } + + /** + * call the function checkReadonlySupport to test com.sun.star.document.FilterFactory + * @see com.sun.star.document.FilterFactory + */ + @Test public void checkReadonlySupportFilterFactory() throws Exception + { + checkReadonlySupport("com.sun.star.document.FilterFactory"); + } + + /* + * call the function checkReadonlySupport to test com.sun.star.document.TypeDetection + * @see com.sun.star.document.TypeDetection + */ + @Test public void checkReadonlySupportTypeDetection() throws Exception + { + checkReadonlySupport("com.sun.star.document.TypeDetection"); + } + + /* + * test the given service serviceName. + * For every filter a new instance was created and the tests started. + * @param serviceName the name of the service to test + */ + private void checkReadonlySupport(String serviceName) throws Exception + { + System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); + System.out.println("testing service '" + serviceName + "'"); + + XInterface oObj = null; + oObj = getTestObject(serviceName); + System.out.println("ImplName: " + util.utils.getImplName(oObj)); + + boolean mandatoryTrue = false; + boolean mandatoryFalse = false; + boolean finalizedTrue = false; + boolean finalizedFalse = false; + + + XNameAccess xNA = UnoRuntime.queryInterface(XNameAccess.class, oObj); + String[] filterNames = xNA.getElementNames(); + + // XNameContainer; XNameReplace + String filterName = filterNames[0]; + Object[] instance = null; + + for (int i = 0; i < filterNames.length; i++) + { + System.out.println("------------------------------------------------"); + filterName = filterNames[i]; + System.out.println(filterName); + + // testobject must new created for every test. + // We change in a loop the container and try to flush this changes. + // If we get an expected exception this container is corrupt. It's + // similar to a document which could not be saved because of invalid + // content. While you don't remove the invalid content you will never + // be able to save the document. Same here. + oObj = getTestObject(serviceName); + + xNA = UnoRuntime.queryInterface(XNameAccess.class, oObj); + XNameContainer xNC = UnoRuntime.queryInterface(XNameContainer.class, oObj); + XNameReplace xNR = UnoRuntime.queryInterface(XNameReplace.class, oObj); + XFlushable xFlush = UnoRuntime.queryInterface(XFlushable.class, oObj); + + instance = (Object[]) xNA.getByName(filterName); + PropertyValue[] props = (PropertyValue[]) instance; + + printPropertyValues(props); + + boolean isMandatory = ((Boolean) getPropertyValueValue(props, "Mandatory")).booleanValue(); + boolean isFinalized = ((Boolean) getPropertyValueValue(props, "Finalized")).booleanValue(); + + // memory if every state is available + mandatoryTrue |= isMandatory; + mandatoryFalse |= !isMandatory; + + finalizedTrue |= isFinalized; + finalizedFalse |= !isFinalized; + + //change the filter + setPropertyValueValue((PropertyValue[]) instance, "UIName", "dummy"); + + // 1a.) try to change the filter in the container + xNR.replaceByName(filterName, instance); + + // 1b.) try to write the changed filter to the configuration. + // This must result in an exception if the filter is finalized. + boolean flushError = false; + try + { + xFlush.flush(); + } + catch (WrappedTargetRuntimeException e) + { + flushError = true; + assertTrue("Unexpected exception while flushing changed filter '" + filterName + "'", isFinalized); + } + assertTrue("Expected exception was not thrown while flushing changed filter '" + filterName + "' Finalized:" + isFinalized, + !(flushError ^ isFinalized)); + + + + // 2a.) try to remove the filter from the container + xNC.removeByName(filterName); + // 1b.) try to write the changed filter to the configuration. + // This must result in an exception if the filter is mandatory + flushError = false; + try + { + xFlush.flush(); + } + catch (WrappedTargetRuntimeException e) + { + flushError = true; + assertTrue("Unexpected exception while flushing removed filter '" + filterName + "'", isMandatory); + } + assertTrue("Expected exception was not thrown while flushing removed filter '" + filterName + "' Mandatory:" + isMandatory, + !(flushError ^ isMandatory)); + } + String preMsg = "Could not find filter with state "; + String postMsg = " Please check if such filter is installed!"; + assertTrue(preMsg + "'Mandatory=true'" + postMsg, mandatoryTrue); + assertTrue(preMsg + "'Mandatory=false'" + postMsg, mandatoryFalse); + assertTrue(preMsg + "'Finalized=true'" + postMsg, finalizedTrue); + assertTrue(preMsg + "'Finalized=false'" + postMsg, finalizedFalse); + } + + /** + * print all properties with its values to logger. For debug purposes. + * @see stats.SimpleLogWriter + * @see com.sun.star.beans.PropertyValue + * @param props Sequence of PropertyValue + */ + protected void printPropertyValues(PropertyValue[] props) + { + int i = 0; + while (i < props.length) + { + System.out.println(props[i].Name + ":" + props[i].Value.toString()); + i++; + } + if (i < props.length) + { + System.out.println(props[i].Name + ":" + props[i].Value.toString()); + } + } + + /** + * returns the value of the specified (pName) property from a sequence of PropertyValue + * @param props a sequence of PropertyValue + * @param pName the name of the property the value should be returned + * @return the value of the property + */ + protected Object getPropertyValueValue(PropertyValue[] props, String pName) + { + int i = 0; + while (i < props.length && !props[i].Name.equals(pName)) + { + i++; + } + return i < props.length ? props[i].Value : null; + } + + /** + * set a value of the specified (pName) property inside a sequence of PropertyValue + * @param props sequence of PropertyValue + * @param pName name of the property which should be changed + * @param pValue the value the property should be assigned + */ + protected void setPropertyValueValue(PropertyValue[] props, String pName, Object pValue) + { + int i = 0; + while (i < props.length && !props[i].Name.equals(pName)) + { + i++; + } + props[i].Value = pValue; + } + + private XMultiServiceFactory getMSF() + { + return UnoRuntime.queryInterface(XMultiServiceFactory.class, connection.getComponentContext().getServiceManager()); + } + + // setup and close connections + @BeforeClass + public static void setUpConnection() throws Exception + { + System.out.println("setUpConnection()"); + connection.setUp(); + } + + @AfterClass + public static void tearDownConnection() + throws InterruptedException, com.sun.star.uno.Exception + { + System.out.println("tearDownConnection()"); + connection.tearDown(); + } + private static final OfficeConnection connection = new OfficeConnection(); +} diff --git a/filter/qa/complex/filter/misc/TypeDetection6FileFormat.java b/filter/qa/complex/filter/misc/TypeDetection6FileFormat.java new file mode 100644 index 000000000..009fd52cf --- /dev/null +++ b/filter/qa/complex/filter/misc/TypeDetection6FileFormat.java @@ -0,0 +1,127 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +package complex.filter.misc; + +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; + +import util.utils; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.openoffice.test.OfficeConnection; +import static org.junit.Assert.*; + + +public class TypeDetection6FileFormat +{ + + XMultiServiceFactory xMSF; + + /** Create the environment for following tests. + * Use either a component loader from desktop or + * from frame + * @throws Exception Exception + */ + @Before public void before() throws Exception + { + xMSF = getMSF(); + assertNotNull("Could not get XMultiServiceFactory", xMSF); + } + + /** + * call the function checkFileFormatSupport to test com.sun.star.document.FilterFactory + * @see com.sun.star.document.FilterFactory + */ + @Test public void checkFilterFactory() throws Exception + { + checkFileFormatSupport("com.sun.star.document.FilterFactory"); + } + + /** + * call the function checkFileFormatSupport to test com.sun.star.document.TypeDetection + * @see com.sun.star.document.TypeDetection + */ + @Test public void checkTypeDetection() throws Exception + { + checkFileFormatSupport("com.sun.star.document.TypeDetection"); + } + + /** + * test the given service serviceName. + * The serve was created and the filter 'TypeDetection6FileFormat' was searched + * @param serviceName the name of the service to test + */ + private void checkFileFormatSupport(String serviceName) throws Exception + { + System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); + System.out.println("testing service '" + serviceName + "'"); + + XInterface oObj = null; + oObj = getTestObject(serviceName); + System.out.println("ImplName: " + utils.getImplName(oObj)); + XNameAccess xNA = UnoRuntime.queryInterface(XNameAccess.class, oObj); + String msg = "Could not find filter 'TypeDetection6FileFormat'!"; + msg += "\nMaybe 'TypeDetection6FileFormat.xcu' is not registered."; + assertTrue(msg, xNA.hasByName("TypeDetection6FileFormat")); + } + + /** + * Creates an instance for the given serviceName + * @param serviceName the name of the service which should be created + * @throws Exception was thrown if creation fails + * @return XInterface of service + */ + public XInterface getTestObject(String serviceName) throws Exception + { + + Object oInterface = xMSF.createInstance(serviceName); + + if (oInterface == null) + { + fail("Service wasn't created"); + throw new Exception("could not create service '" + serviceName + "'"); + } + return (XInterface) oInterface; + } + + private XMultiServiceFactory getMSF() + { + return UnoRuntime.queryInterface(XMultiServiceFactory.class, connection.getComponentContext().getServiceManager()); + } + + // setup and close connections + @BeforeClass public static void setUpConnection() throws Exception { + System.out.println("setUpConnection()"); + connection.setUp(); + } + + @AfterClass public static void tearDownConnection() + throws InterruptedException, com.sun.star.uno.Exception + { + System.out.println("tearDownConnection()"); + connection.tearDown(); + } + + private static final OfficeConnection connection = new OfficeConnection(); + +} diff --git a/filter/qa/complex/filter/misc/TypeDetection6FileFormat.xcu b/filter/qa/complex/filter/misc/TypeDetection6FileFormat.xcu new file mode 100644 index 000000000..2206e6942 --- /dev/null +++ b/filter/qa/complex/filter/misc/TypeDetection6FileFormat.xcu @@ -0,0 +1,42 @@ + + + + + + + TypeDetection 6 FileFormat + TypeDetection 6 FileFormat + + + 1,,,,,, + + + + + + + FilterFactory 6 FileFormat + FilterFactory 6 FileFormat + + + 0,TypeDetection6FileFormat,,,,, + + + + diff --git a/filter/qa/cppunit/data/xslt/copy.xslt b/filter/qa/cppunit/data/xslt/copy.xslt new file mode 100644 index 000000000..d46172a41 --- /dev/null +++ b/filter/qa/cppunit/data/xslt/copy.xslt @@ -0,0 +1,9 @@ + + + + + + + + diff --git a/filter/qa/cppunit/msfilter-test.cxx b/filter/qa/cppunit/msfilter-test.cxx new file mode 100644 index 000000000..439aad88b --- /dev/null +++ b/filter/qa/cppunit/msfilter-test.cxx @@ -0,0 +1,76 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include +#include +#include + +#include +#include +#include + +#include + +namespace { + +class MSFilterTest + : public test::BootstrapFixtureBase +{ +public: + void testTransColToIco(); + + CPPUNIT_TEST_SUITE(MSFilterTest); + CPPUNIT_TEST(testTransColToIco); + CPPUNIT_TEST_SUITE_END(); +}; + +void MSFilterTest::testTransColToIco() +{ + const sal_uInt32 aStdCol[] = { + 0xeeeeee, 0xffff99, 0xff6600, 0xff3333, 0xff00cc, 0xff33ff, 0x9900ff, 0x6666ff, 0x00ccff, 0x66ffff, 0x33ff99, 0x99ff66, 0xccff00, + 0xdddddd, 0xffff66, 0xffcc00, 0xff9999, 0xff66cc, 0xff99ff, 0xcc66ff, 0x9999ff, 0x9999ff, 0x99ffff, 0x66ff99, 0x99ff99, 0xccff66, + 0xcccccc, 0xffff00, 0xff9900, 0xff6666, 0xff3399, 0xff66ff, 0x9933ff, 0x3333ff, 0x3399ff, 0x00ffff, 0x00ff66, 0x66ff66, 0x99ff33, + 0xb2b2b2, 0xcc9900, 0xff3300, 0xff0000, 0xff0066, 0xff00ff, 0x6600ff, 0x0000ff, 0x0066ff, 0x00cccc, 0x00cc33, 0x00cc00, 0x66ff00, + 0x999999, 0x996600, 0xcc3300, 0xcc0000, 0xcc0066, 0xcc00cc, 0x6600cc, 0x0000cc, 0x0066cc, 0x009999, 0x009933, 0x009900, 0x66cc00, + 0x808080, 0x663300, 0x801900, 0x990000, 0x990066, 0x990099, 0x330099, 0x000099, 0x006699, 0x006666, 0x007826, 0x006600, 0x669900, + 0x666666, 0x333300, 0x461900, 0x330000, 0x330033, 0x660066, 0x000033, 0x000066, 0x000080, 0x003333, 0x00331a, 0x003300, 0x193300, + 0x333333, 0x666633, 0x661900, 0x663333, 0x660033, 0x663366, 0x330066, 0x333366, 0x003366, 0x336666, 0x006633, 0x336633, 0x336600 }; + + const sal_uInt16 aExpected[] = { + 8, 7, 6, 6, 5, 5, 5, 2, 3, 3, 10, 4, 7, + 16, 7, 7, 6, 5, 5, 5, 2, 2, 3, 4, 4, 7, + 16, 7, 7, 6, 12, 5, 12, 2, 10, 3, 4, 4, 14, + 16, 14, 6, 6, 6, 5, 2, 2, 2, 3, 4, 4, 4, + 15, 14, 6, 6, 12, 5, 12, 2, 10, 10, 11, 11, 14, + 15, 1, 13, 13, 12, 12, 9, 9, 10, 10, 11, 11, 14, + 15, 14, 13, 13, 12, 12, 9, 9, 9, 10, 10, 11, 11, + 1, 14, 13, 13, 1, 12, 1, 9, 1, 10, 1, 11, 1 }; + + for( size_t i = 0; i < SAL_N_ELEMENTS(aStdCol); ++i) + { + const OString sMessage = "Index of unmatched color: " + OString::number(i); + CPPUNIT_ASSERT_EQUAL_MESSAGE(sMessage.getStr(), aExpected[i], + static_cast(msfilter::util::TransColToIco( Color(ColorTransparency, aStdCol[i]) ))); + } + + // tdf#92471 + CPPUNIT_ASSERT_EQUAL(sal_uInt16(2), static_cast(msfilter::util::TransColToIco( Color( 0x6666ff )))); + CPPUNIT_ASSERT_EQUAL(sal_uInt16(2), static_cast(msfilter::util::TransColToIco( Color( 0x6566ff )))); + CPPUNIT_ASSERT_EQUAL(sal_uInt16(2), static_cast(msfilter::util::TransColToIco( Color( 0x6665ff )))); + CPPUNIT_ASSERT_EQUAL(sal_uInt16(2), static_cast(msfilter::util::TransColToIco( Color( 0x6666fe )))); + +} + +CPPUNIT_TEST_SUITE_REGISTRATION(MSFilterTest); + +} + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/filter/qa/cppunit/priority-test.cxx b/filter/qa/cppunit/priority-test.cxx new file mode 100644 index 000000000..18e63c318 --- /dev/null +++ b/filter/qa/cppunit/priority-test.cxx @@ -0,0 +1,85 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +// Unit test to check that we get the right filters for the right extensions. + +#include +#include +#include + +#include + +#include +#include + +#include + + +using namespace css; + +namespace { + +class PriorityFilterTest + : public test::BootstrapFixtureBase +{ +public: + void testPriority(); + + CPPUNIT_TEST_SUITE(PriorityFilterTest); + CPPUNIT_TEST(testPriority); + CPPUNIT_TEST_SUITE_END(); +}; + +void PriorityFilterTest::testPriority() +{ + uno::Reference xDetection( + comphelper::getProcessServiceFactory()->createInstance("com.sun.star.document.TypeDetection"), uno::UNO_QUERY); + CPPUNIT_ASSERT_MESSAGE("No type detection component", xDetection.is()); + + static struct { + const char *pURL; + const char *pFormat; + } const aToCheck[] = { + { "file:///tmp/foo.xls", "calc_MS_Excel_97" } + // TODO: expand this to check more of these priorities + }; + + for (size_t i = 0; i < SAL_N_ELEMENTS(aToCheck); i++) + { + OUString aURL = OUString::createFromAscii(aToCheck[i].pURL); + try + { + OUString aTypeName = xDetection->queryTypeByURL(aURL); + + OUString aFormatCorrect = OUString::createFromAscii(aToCheck[i].pFormat); + OUString aMsg = "Mis-matching formats " + "'" + + aTypeName + + "' should be '" + + aFormatCorrect + + "'"; + CPPUNIT_ASSERT_EQUAL_MESSAGE(OUStringToOString(aMsg, + RTL_TEXTENCODING_UTF8).getStr(), + aFormatCorrect, aTypeName); + } + catch (const uno::Exception &e) + { + OUString aMsg = "Exception querying for type: '" + e.Message + "'"; + CPPUNIT_FAIL(OUStringToOString(aMsg, RTL_TEXTENCODING_UTF8).getStr()); + } + } +} + +CPPUNIT_TEST_SUITE_REGISTRATION(PriorityFilterTest); + +} + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/filter/qa/cppunit/xslt-test.cxx b/filter/qa/cppunit/xslt-test.cxx new file mode 100644 index 000000000..4e0c621d6 --- /dev/null +++ b/filter/qa/cppunit/xslt-test.cxx @@ -0,0 +1,207 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include + +#include +#include + +#include +#include +#include + +#include +#include + +#include + +#include + +#include +#include +#include +#include + +#include + +#include + + +using namespace ::com::sun::star; + + +namespace { + +class XsltFilterTest + : public test::BootstrapFixture +{ +public: + void testXsltCopyOld(); + void testXsltCopyNew(); + + CPPUNIT_TEST_SUITE(XsltFilterTest); + CPPUNIT_TEST(testXsltCopyOld); + CPPUNIT_TEST(testXsltCopyNew); + CPPUNIT_TEST_SUITE_END(); +}; + +class Listener : public ::cppu::WeakImplHelper +{ +public: + Listener() : m_bDone(false) {} + + void wait() { + std::unique_lock g(m_mutex); + m_cond.wait(g, [this]() { return m_bDone; }); + } + +private: + std::mutex m_mutex; + std::condition_variable m_cond; + bool m_bDone; + + virtual void SAL_CALL disposing(const lang::EventObject&) noexcept override {} + virtual void SAL_CALL started() noexcept override {} + virtual void SAL_CALL closed() noexcept override { notifyDone(); } + virtual void SAL_CALL terminated() noexcept override { notifyDone(); } + virtual void SAL_CALL error(const uno::Any& e) override + { + notifyDone(); // set on error too, otherwise main thread waits forever + SAL_WARN("filter.xslt", e); + CPPUNIT_FAIL("exception while in XSLT"); + } + + void notifyDone() { + std::scoped_lock g(m_mutex); + m_bDone = true; + m_cond.notify_all(); + } +}; + +void XsltFilterTest::testXsltCopyNew() +{ + OUString tempDirURL; + osl_getTempDirURL(&tempDirURL.pData); + oslFileHandle tempFile; + OUString tempURL; + osl::File::RC rc = osl::File::createTempFile(nullptr, &tempFile, &tempURL); + CPPUNIT_ASSERT_EQUAL(osl::FileBase::E_None, rc); + osl_closeFile(tempFile); // close it so xSFA can open it on WNT + + OUString source( + m_directories.getURLFromSrc(u"/filter/source/xsltfilter/xsltfilter.component")); + uno::Sequence args{ + uno::Any(beans::NamedValue("StylesheetURL", + uno::Any(m_directories.getURLFromSrc(u"/filter/qa/cppunit/data/xslt/copy.xslt")))), + uno::Any(beans::NamedValue("SourceURL", uno::Any(source))), + uno::Any(beans::NamedValue("TargetURL", uno::Any(tempURL))), + uno::Any(beans::NamedValue("SourceBaseURL", + uno::Any(m_directories.getURLFromSrc(u"/filter/source/xsltfilter/")))), + uno::Any(beans::NamedValue("TargetBaseURL", uno::Any(tempDirURL))), + uno::Any(beans::NamedValue("SystemType", uno::Any(OUString()))), + uno::Any(beans::NamedValue("PublicType", uno::Any(OUString()))) + }; + + uno::Reference xSFA = + ucb::SimpleFileAccess::create(getComponentContext()); + + uno::Reference xIn = xSFA->openFileRead(source); + uno::Reference xOut = xSFA->openFileWrite(tempURL); + + rtl::Reference xListener = new Listener(); + + uno::Reference xXslt( + xml::xslt::XSLTTransformer::create(getComponentContext(), args)); + + xXslt->addListener(xListener); + xXslt->setInputStream(xIn); + xXslt->setOutputStream(xOut); + + xXslt->start(); + + xListener->wait(); + + xIn->closeInput(); + xOut->closeOutput(); + + osl::File foo(tempURL); // apparently it's necessary to open it again? + foo.open(osl_File_OpenFlag_Read); + sal_uInt64 size(0); + foo.getSize(size); + CPPUNIT_ASSERT(size > 1000); // check that something happened + foo.close(); + osl_removeFile(tempURL.pData); +} + +void XsltFilterTest::testXsltCopyOld() +{ + OUString tempDirURL; + osl_getTempDirURL(&tempDirURL.pData); + oslFileHandle tempFile; + OUString tempURL; + osl::File::RC rc = osl::File::createTempFile(nullptr, &tempFile, &tempURL); + CPPUNIT_ASSERT_EQUAL(osl::FileBase::E_None, rc); + osl_closeFile(tempFile); // close it so xSFA can open it on WNT + + OUString source( + m_directories.getURLFromSrc(u"/filter/source/xsltfilter/xsltfilter.component")); + uno::Sequence args{ + uno::Any(beans::NamedValue("StylesheetURL", + uno::Any(m_directories.getURLFromSrc(u"/filter/qa/cppunit/data/xslt/copy.xslt")))), + uno::Any(beans::NamedValue("SourceURL", uno::Any(source))), + uno::Any(beans::NamedValue("TargetURL", uno::Any(tempURL))), + uno::Any(beans::NamedValue("SourceBaseURL", + uno::Any(m_directories.getURLFromSrc(u"/filter/source/xsltfilter/")))), + uno::Any(beans::NamedValue("TargetBaseURL", uno::Any(tempDirURL))), + uno::Any(beans::NamedValue("SystemType", uno::Any(OUString()))), + uno::Any(beans::NamedValue("PublicType", uno::Any(OUString()))) + }; + + uno::Reference xSFA = + ucb::SimpleFileAccess::create(getComponentContext()); + + uno::Reference xIn = xSFA->openFileRead(source); + uno::Reference xOut = xSFA->openFileWrite(tempURL); + + rtl::Reference xListener = new Listener(); + + uno::Reference xXslt( + getMultiServiceFactory()->createInstance( + "com.sun.star.comp.documentconversion.LibXSLTTransformer"), + uno::UNO_QUERY_THROW); + + uno::Reference xInit(xXslt, uno::UNO_QUERY_THROW); + xInit->initialize(args); + xXslt->addListener(xListener); + xXslt->setInputStream(xIn); + xXslt->setOutputStream(xOut); + + xXslt->start(); + + xListener->wait(); + + xIn->closeInput(); + xOut->closeOutput(); + + osl::File foo(tempURL); // apparently it's necessary to open it again? + foo.open(osl_File_OpenFlag_Read); + sal_uInt64 size(0); + foo.getSize(size); + CPPUNIT_ASSERT(size > 1000); // check that something happened + foo.close(); + osl_removeFile(tempURL.pData); +} + +CPPUNIT_TEST_SUITE_REGISTRATION(XsltFilterTest); + +} + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/filter/qa/data/picture.pdf b/filter/qa/data/picture.pdf new file mode 100644 index 000000000..79af2b349 Binary files /dev/null and b/filter/qa/data/picture.pdf differ diff --git a/filter/qa/pdf.cxx b/filter/qa/pdf.cxx new file mode 100644 index 000000000..ec5460b9f --- /dev/null +++ b/filter/qa/pdf.cxx @@ -0,0 +1,347 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +using namespace ::com::sun::star; + +namespace +{ +/// Covers filter/source/pdf/ fixes. +class Test : public test::BootstrapFixture, public unotest::MacrosTest +{ +private: + uno::Reference mxComponent; + +public: + void setUp() override; + void tearDown() override; + uno::Reference& getComponent() { return mxComponent; } +}; + +void Test::setUp() +{ + test::BootstrapFixture::setUp(); + MacrosTest::setUpNssGpg(m_directories, "filter_pdf"); + + mxDesktop.set(frame::Desktop::create(mxComponentContext)); +} + +void Test::tearDown() +{ + if (mxComponent.is()) + mxComponent->dispose(); + + test::BootstrapFixture::tearDown(); +} + +constexpr OUStringLiteral DATA_DIRECTORY = u"/filter/qa/data/"; + +CPPUNIT_TEST_FIXTURE(Test, testSignCertificateSubjectName) +{ + std::shared_ptr pPDFium = vcl::pdf::PDFiumLibrary::get(); + if (!pPDFium) + return; + + uno::Reference xSEInitializer + = xml::crypto::SEInitializer::create(mxComponentContext); + uno::Reference xSecurityContext + = xSEInitializer->createSecurityContext(OUString()); + uno::Reference xSecurityEnvironment + = xSecurityContext->getSecurityEnvironment(); + uno::Sequence aFilterData{ + comphelper::makePropertyValue("SignPDF", true), + comphelper::makePropertyValue( + "SignCertificateSubjectName", + OUString( + "CN=Xmlsecurity RSA Test example Alice,O=Xmlsecurity RSA Test,ST=England,C=UK")), + }; + if (!GetValidCertificate(xSecurityEnvironment->getPersonalCertificates(), aFilterData)) + { + return; + } + + // Given an empty document: + getComponent().set( + loadFromDesktop("private:factory/swriter", "com.sun.star.text.TextDocument")); + + // When exporting to PDF, and referring to a certificate using a subject name: + uno::Reference xFactory = getMultiServiceFactory(); + uno::Reference xFilter( + xFactory->createInstance("com.sun.star.document.PDFFilter"), uno::UNO_QUERY); + uno::Reference xExporter(xFilter, uno::UNO_QUERY); + xExporter->setSourceDocument(getComponent()); + SvMemoryStream aStream; + uno::Reference xOutputStream(new utl::OStreamWrapper(aStream)); + + uno::Sequence aDescriptor{ + comphelper::makePropertyValue("FilterName", OUString("writer_pdf_Export")), + comphelper::makePropertyValue("FilterData", aFilterData), + comphelper::makePropertyValue("OutputStream", xOutputStream), + }; + xFilter->filter(aDescriptor); + + // Then make sure the resulting PDF has a signature: + std::unique_ptr pPdfDocument + = pPDFium->openDocument(aStream.GetData(), aStream.GetSize(), OString()); + // Without the accompanying fix in place, this test would have failed, as signing was enabled + // without configuring a certificate, so the whole export failed. + CPPUNIT_ASSERT(pPdfDocument); + CPPUNIT_ASSERT_EQUAL(1, pPdfDocument->getSignatureCount()); +} + +CPPUNIT_TEST_FIXTURE(Test, testPdfDecompositionSize) +{ + std::shared_ptr pPDFium = vcl::pdf::PDFiumLibrary::get(); + if (!pPDFium) + return; + + // Given an empty Writer document: + getComponent().set( + loadFromDesktop("private:factory/swriter", "com.sun.star.text.TextDocument")); + + // When inserting a 267 points wide PDF image into the document: + uno::Sequence aArgs = { + comphelper::makePropertyValue("FileName", + m_directories.getURLFromSrc(DATA_DIRECTORY) + "picture.pdf"), + }; + dispatchCommand(getComponent(), ".uno:InsertGraphic", aArgs); + + // Then make sure that its size is correct: + uno::Reference xDrawPageSupplier(getComponent(), uno::UNO_QUERY); + uno::Reference xDrawPage = xDrawPageSupplier->getDrawPage(); + uno::Reference xShape(xDrawPage->getByIndex(0), uno::UNO_QUERY); + auto xGraphic = xShape->getPropertyValue("Graphic").get>(); + CPPUNIT_ASSERT(xGraphic.is()); + Graphic aGraphic(xGraphic); + basegfx::B2DRange aRange = aGraphic.getVectorGraphicData()->getRange(); + // Without the accompanying fix in place, this test would have failed with: + // - Expected: 9437 + // - Actual : 34176 + // i.e. the width was too large, it used all width of the body frame. + // 9437 mm100 is 267.507 points from the file. +#if defined MACOSX + // TODO the bitmap size is larger (75486) on macOS, but that should not affect the logic size. + (void)aRange; +#else + // Unfortunately, this test is DPI-dependent. + // Use some allowance (~1/2 pt) to let it pass on non-default DPI. + CPPUNIT_ASSERT_DOUBLES_EQUAL(9437, aRange.getWidth(), 20.0); +#endif +} + +CPPUNIT_TEST_FIXTURE(Test, testWatermarkColor) +{ + // Given an empty Writer document: + std::shared_ptr pPDFium = vcl::pdf::PDFiumLibrary::get(); + if (!pPDFium) + return; + getComponent().set( + loadFromDesktop("private:factory/swriter", "com.sun.star.text.TextDocument")); + + // When exporting that as PDF with a red watermark: + uno::Reference xFactory = getMultiServiceFactory(); + uno::Reference xFilter( + xFactory->createInstance("com.sun.star.document.PDFFilter"), uno::UNO_QUERY); + uno::Reference xExporter(xFilter, uno::UNO_QUERY); + xExporter->setSourceDocument(getComponent()); + SvMemoryStream aStream; + uno::Reference xOutputStream(new utl::OStreamWrapper(aStream)); + uno::Sequence aFilterData{ + comphelper::makePropertyValue("Watermark", OUString("X")), + comphelper::makePropertyValue("WatermarkColor", static_cast(0xff0000)), + }; + uno::Sequence aDescriptor{ + comphelper::makePropertyValue("FilterName", OUString("writer_pdf_Export")), + comphelper::makePropertyValue("FilterData", aFilterData), + comphelper::makePropertyValue("OutputStream", xOutputStream), + }; + xFilter->filter(aDescriptor); + + // Then make sure that the watermark color is correct: + std::unique_ptr pPdfDocument + = pPDFium->openDocument(aStream.GetData(), aStream.GetSize(), OString()); + CPPUNIT_ASSERT(pPdfDocument); + std::unique_ptr pPage = pPdfDocument->openPage(0); + CPPUNIT_ASSERT_EQUAL(1, pPage->getObjectCount()); + std::unique_ptr pPageObject = pPage->getObject(0); + CPPUNIT_ASSERT_EQUAL(1, pPageObject->getFormObjectCount()); + std::unique_ptr pFormObject = pPageObject->getFormObject(0); + Color aFillColor = pFormObject->getFillColor(); + // Without the accompanying fix in place, this test would have failed with: + // - Expected: rgba[ff0000ff] + // - Actual : rgba[00ff00ff] + // i.e. the color was the (default) green, not red. + CPPUNIT_ASSERT_EQUAL(Color(ColorTransparency, 0xff0000), aFillColor); +} + +CPPUNIT_TEST_FIXTURE(Test, testWatermarkFontHeight) +{ + // Given an empty Writer document: + std::shared_ptr pPDFium = vcl::pdf::PDFiumLibrary::get(); + if (!pPDFium) + return; + getComponent().set( + loadFromDesktop("private:factory/swriter", "com.sun.star.text.TextDocument")); + + // When exporting that as PDF with a 100pt-sized watermark: + uno::Reference xFactory = getMultiServiceFactory(); + uno::Reference xFilter( + xFactory->createInstance("com.sun.star.document.PDFFilter"), uno::UNO_QUERY); + uno::Reference xExporter(xFilter, uno::UNO_QUERY); + xExporter->setSourceDocument(getComponent()); + SvMemoryStream aStream; + uno::Reference xOutputStream(new utl::OStreamWrapper(aStream)); + sal_Int32 nExpectedFontSize = 100; + uno::Sequence aFilterData{ + comphelper::makePropertyValue("Watermark", OUString("X")), + comphelper::makePropertyValue("WatermarkFontHeight", nExpectedFontSize), + }; + uno::Sequence aDescriptor{ + comphelper::makePropertyValue("FilterName", OUString("writer_pdf_Export")), + comphelper::makePropertyValue("FilterData", aFilterData), + comphelper::makePropertyValue("OutputStream", xOutputStream), + }; + xFilter->filter(aDescriptor); + + // Then make sure that the watermark font size is correct: + std::unique_ptr pPdfDocument + = pPDFium->openDocument(aStream.GetData(), aStream.GetSize(), OString()); + CPPUNIT_ASSERT(pPdfDocument); + std::unique_ptr pPage = pPdfDocument->openPage(0); + CPPUNIT_ASSERT_EQUAL(1, pPage->getObjectCount()); + std::unique_ptr pPageObject = pPage->getObject(0); + CPPUNIT_ASSERT_EQUAL(1, pPageObject->getFormObjectCount()); + std::unique_ptr pFormObject = pPageObject->getFormObject(0); + sal_Int32 nFontSize = pFormObject->getFontSize(); + // Without the accompanying fix in place, this test would have failed with: + // - Expected: 100 + // - Actual : 594 + // i.e. the font size was automatic, could not specify an explicit size. + CPPUNIT_ASSERT_EQUAL(nExpectedFontSize, nFontSize); +} + +CPPUNIT_TEST_FIXTURE(Test, testWatermarkFontName) +{ + // Given an empty Writer document: + std::shared_ptr pPDFium = vcl::pdf::PDFiumLibrary::get(); + if (!pPDFium) + return; + getComponent().set( + loadFromDesktop("private:factory/swriter", "com.sun.star.text.TextDocument")); + + // When exporting that as PDF with a serif watermark: + uno::Reference xFactory = getMultiServiceFactory(); + uno::Reference xFilter( + xFactory->createInstance("com.sun.star.document.PDFFilter"), uno::UNO_QUERY); + uno::Reference xExporter(xFilter, uno::UNO_QUERY); + xExporter->setSourceDocument(getComponent()); + SvMemoryStream aStream; + uno::Reference xOutputStream(new utl::OStreamWrapper(aStream)); + OUString aExpectedFontName("Liberation Serif"); + uno::Sequence aFilterData{ + comphelper::makePropertyValue("Watermark", OUString("X")), + comphelper::makePropertyValue("WatermarkFontName", aExpectedFontName), + }; + uno::Sequence aDescriptor{ + comphelper::makePropertyValue("FilterName", OUString("writer_pdf_Export")), + comphelper::makePropertyValue("FilterData", aFilterData), + comphelper::makePropertyValue("OutputStream", xOutputStream), + }; + xFilter->filter(aDescriptor); + + // Then make sure that the watermark font name is correct: + std::unique_ptr pPdfDocument + = pPDFium->openDocument(aStream.GetData(), aStream.GetSize(), OString()); + CPPUNIT_ASSERT(pPdfDocument); + std::unique_ptr pPage = pPdfDocument->openPage(0); + CPPUNIT_ASSERT_EQUAL(1, pPage->getObjectCount()); + std::unique_ptr pPageObject = pPage->getObject(0); + CPPUNIT_ASSERT_EQUAL(1, pPageObject->getFormObjectCount()); + std::unique_ptr pFormObject = pPageObject->getFormObject(0); + OUString aFontName = pFormObject->getFontName(); + // Without the accompanying fix in place, this test would have failed with: + // - Expected: Liberation Serif + // - Actual : Helvetica + // i.e. the font name was sans, could not specify an explicit name. + CPPUNIT_ASSERT_EQUAL(aExpectedFontName, aFontName); +} + +CPPUNIT_TEST_FIXTURE(Test, testWatermarkRotateAngle) +{ + // Given an empty Writer document: + std::shared_ptr pPDFium = vcl::pdf::PDFiumLibrary::get(); + if (!pPDFium) + return; + getComponent().set( + loadFromDesktop("private:factory/swriter", "com.sun.star.text.TextDocument")); + + // When exporting that as PDF with a rotated watermark: + uno::Reference xFactory = getMultiServiceFactory(); + uno::Reference xFilter( + xFactory->createInstance("com.sun.star.document.PDFFilter"), uno::UNO_QUERY); + uno::Reference xExporter(xFilter, uno::UNO_QUERY); + xExporter->setSourceDocument(getComponent()); + SvMemoryStream aStream; + uno::Reference xOutputStream(new utl::OStreamWrapper(aStream)); + // 45.0 degrees, counter-clockwise. + sal_Int32 nExpectedRotateAngle = 45; + uno::Sequence aFilterData{ + comphelper::makePropertyValue("Watermark", OUString("X")), + comphelper::makePropertyValue("WatermarkRotateAngle", nExpectedRotateAngle * 10), + }; + uno::Sequence aDescriptor{ + comphelper::makePropertyValue("FilterName", OUString("writer_pdf_Export")), + comphelper::makePropertyValue("FilterData", aFilterData), + comphelper::makePropertyValue("OutputStream", xOutputStream), + }; + xFilter->filter(aDescriptor); + + // Then make sure that the watermark rotation angle is correct: + std::unique_ptr pPdfDocument + = pPDFium->openDocument(aStream.GetData(), aStream.GetSize(), OString()); + CPPUNIT_ASSERT(pPdfDocument); + std::unique_ptr pPage = pPdfDocument->openPage(0); + CPPUNIT_ASSERT_EQUAL(1, pPage->getObjectCount()); + std::unique_ptr pPageObject = pPage->getObject(0); + CPPUNIT_ASSERT_EQUAL(1, pPageObject->getFormObjectCount()); + std::unique_ptr pFormObject = pPageObject->getFormObject(0); + basegfx::B2DHomMatrix aMatrix = pFormObject->getMatrix(); + basegfx::B2DTuple aScale; + basegfx::B2DTuple aTranslate; + double fRotate{}; + double fShearX{}; + aMatrix.decompose(aScale, aTranslate, fRotate, fShearX); + sal_Int32 nActualRotateAngle = NormAngle360(basegfx::rad2deg<1>(fRotate)); + // Without the accompanying fix in place, this test would have failed with: + // - Expected: 45 + // - Actual : 270 + // i.e. the rotation angle was 270 for an A4 page, not the requested 45 degrees. + CPPUNIT_ASSERT_EQUAL(nExpectedRotateAngle, nActualRotateAngle); +} +} + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/filter/qa/unit/data/TransparentText.odg b/filter/qa/unit/data/TransparentText.odg new file mode 100644 index 000000000..d3027d17d Binary files /dev/null and b/filter/qa/unit/data/TransparentText.odg differ diff --git a/filter/qa/unit/data/attributeRedefinedTest.odp b/filter/qa/unit/data/attributeRedefinedTest.odp new file mode 100644 index 000000000..dfb814bfb Binary files /dev/null and b/filter/qa/unit/data/attributeRedefinedTest.odp differ diff --git a/filter/qa/unit/data/calc.ots b/filter/qa/unit/data/calc.ots new file mode 100644 index 000000000..d16d2307f Binary files /dev/null and b/filter/qa/unit/data/calc.ots differ diff --git a/filter/qa/unit/data/custom-bullet.fodp b/filter/qa/unit/data/custom-bullet.fodp new file mode 100644 index 000000000..4139260f9 --- /dev/null +++ b/filter/qa/unit/data/custom-bullet.fodp @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + hello + + + + + + + + diff --git a/filter/qa/unit/data/empty.doc b/filter/qa/unit/data/empty.doc new file mode 100644 index 000000000..e69de29bb diff --git a/filter/qa/unit/data/empty.odp b/filter/qa/unit/data/empty.odp new file mode 100644 index 000000000..e69de29bb diff --git a/filter/qa/unit/data/empty.ods b/filter/qa/unit/data/empty.ods new file mode 100644 index 000000000..e69de29bb diff --git a/filter/qa/unit/data/empty.odt b/filter/qa/unit/data/empty.odt new file mode 100644 index 000000000..e69de29bb diff --git a/filter/qa/unit/data/empty.pptx b/filter/qa/unit/data/empty.pptx new file mode 100644 index 000000000..e69de29bb diff --git a/filter/qa/unit/data/filter-dialogs-test.txt b/filter/qa/unit/data/filter-dialogs-test.txt new file mode 100644 index 000000000..22792ad28 --- /dev/null +++ b/filter/qa/unit/data/filter-dialogs-test.txt @@ -0,0 +1,49 @@ +# -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +# This file contains all dialogs that the unit tests in the module +# will work on if it is in script mode. It will read one-by-one, +# try to open it and create a screenshot that will be saved in +# workdir/screenshots using the pattern of the ui-file name. +# +# Syntax: +# - empty lines are allowed +# - lines starting with '#' are treated as comment +# - all other lines should contain a *.ui filename in the same +# notation as in the dialog constructors (see code) + +# +# The 'known' dialogs which have a hard-coded representation +# in registerKnownDialogsByID/createDialogByID +# + +# No known dialogs in filter for now + +# +# Dialogs without a hard-coded representation. These will +# be visualized using a fallback based on weld::Builder +# + +# currently deactivated, leads to problems and the test to not work +# This is typically a hint that these should be hard-coded in the +# test case since they need some document and model data to work + +filter/ui/pdfoptionsdialog.ui +filter/ui/xsltfilterdialog.ui +filter/ui/pdfgeneralpage.ui +filter/ui/pdfviewpage.ui +filter/ui/pdfuserinterfacepage.ui +filter/ui/pdfsecuritypage.ui +filter/ui/pdflinkspage.ui +filter/ui/pdfsignpage.ui +filter/ui/xmlfiltertabpagegeneral.ui +filter/ui/xmlfiltertabpagetransformation.ui +filter/ui/testxmlfilter.ui +filter/ui/warnpdfdialog.ui +filter/ui/xmlfiltersettings.ui diff --git a/filter/qa/unit/data/impress.otp b/filter/qa/unit/data/impress.otp new file mode 100644 index 000000000..199a5f9d4 Binary files /dev/null and b/filter/qa/unit/data/impress.otp differ diff --git a/filter/qa/unit/data/preserve-jpg.odt b/filter/qa/unit/data/preserve-jpg.odt new file mode 100644 index 000000000..83768bd47 Binary files /dev/null and b/filter/qa/unit/data/preserve-jpg.odt differ diff --git a/filter/qa/unit/data/semi-transparent-fill.odg b/filter/qa/unit/data/semi-transparent-fill.odg new file mode 100644 index 000000000..713f48991 Binary files /dev/null and b/filter/qa/unit/data/semi-transparent-fill.odg differ diff --git a/filter/qa/unit/data/semi-transparent-line.odg b/filter/qa/unit/data/semi-transparent-line.odg new file mode 100644 index 000000000..2d28a694c Binary files /dev/null and b/filter/qa/unit/data/semi-transparent-line.odg differ diff --git a/filter/qa/unit/data/shape-nographic.odp b/filter/qa/unit/data/shape-nographic.odp new file mode 100644 index 000000000..43186d614 Binary files /dev/null and b/filter/qa/unit/data/shape-nographic.odp differ diff --git a/filter/qa/unit/data/tdf114428.xhtml b/filter/qa/unit/data/tdf114428.xhtml new file mode 100644 index 000000000..f08f0fa4a --- /dev/null +++ b/filter/qa/unit/data/tdf114428.xhtml @@ -0,0 +1,9 @@ + + + + + Title of document + + hello world + diff --git a/filter/qa/unit/data/writer.ott b/filter/qa/unit/data/writer.ott new file mode 100644 index 000000000..1ded03150 Binary files /dev/null and b/filter/qa/unit/data/writer.ott differ diff --git a/filter/qa/unit/filter-dialogs-test.cxx b/filter/qa/unit/filter-dialogs-test.cxx new file mode 100644 index 000000000..946a1961d --- /dev/null +++ b/filter/qa/unit/filter-dialogs-test.cxx @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include +#include +#include + +using namespace ::com::sun::star; + +/// Test opening a dialog in filter +class FilterDialogsTest : public ScreenshotTest +{ +private: + /// helper method to populate KnownDialogs, called in setUp(). Needs to be + /// written and has to add entries to KnownDialogs + virtual void registerKnownDialogsByID(mapType& rKnownDialogs) override; + + /// dialog creation for known dialogs by ID. Has to be implemented for + /// each registered known dialog + virtual VclPtr createDialogByID(sal_uInt32 nID) override; + +public: + FilterDialogsTest(); + + // try to open a dialog + void openAnyDialog(); + + CPPUNIT_TEST_SUITE(FilterDialogsTest); + CPPUNIT_TEST(openAnyDialog); + CPPUNIT_TEST_SUITE_END(); +}; + +FilterDialogsTest::FilterDialogsTest() {} + +void FilterDialogsTest::registerKnownDialogsByID(mapType& /*rKnownDialogs*/) +{ + // fill map of known dialogs +} + +VclPtr FilterDialogsTest::createDialogByID(sal_uInt32 /*nID*/) +{ + return nullptr; +} + +void FilterDialogsTest::openAnyDialog() +{ + /// process input file containing the UXMLDescriptions of the dialogs to dump + processDialogBatchFile(u"filter/qa/unit/data/filter-dialogs-test.txt"); +} + +CPPUNIT_TEST_SUITE_REGISTRATION(FilterDialogsTest); + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/filter/qa/unit/svg.cxx b/filter/qa/unit/svg.cxx new file mode 100644 index 000000000..22695acd6 --- /dev/null +++ b/filter/qa/unit/svg.cxx @@ -0,0 +1,380 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +using namespace ::com::sun::star; + +constexpr OUStringLiteral DATA_DIRECTORY = u"/filter/qa/unit/data/"; + +/// SVG filter tests. +class SvgFilterTest : public test::BootstrapFixture, public unotest::MacrosTest, public XmlTestTools +{ +private: + uno::Reference mxComponent; + +public: + void setUp() override; + void tearDown() override; + void registerNamespaces(xmlXPathContextPtr& pXmlXpathCtx) override; + uno::Reference& getComponent() { return mxComponent; } + void load(std::u16string_view rURL); +}; + +void SvgFilterTest::setUp() +{ + test::BootstrapFixture::setUp(); + + mxDesktop.set(frame::Desktop::create(mxComponentContext)); +} + +void SvgFilterTest::tearDown() +{ + if (mxComponent.is()) + mxComponent->dispose(); + + test::BootstrapFixture::tearDown(); +} + +void SvgFilterTest::load(std::u16string_view rFileName) +{ + OUString aURL = m_directories.getURLFromSrc(DATA_DIRECTORY) + rFileName; + mxComponent = loadFromDesktop(aURL); +} + +void SvgFilterTest::registerNamespaces(xmlXPathContextPtr& pXmlXpathCtx) +{ + xmlXPathRegisterNs(pXmlXpathCtx, BAD_CAST("svg"), BAD_CAST("http://www.w3.org/2000/svg")); +} + +CPPUNIT_TEST_FIXTURE(SvgFilterTest, testPreserveJpg) +{ +#if !defined(MACOSX) + // Load a document with a jpeg image in it. + load(u"preserve-jpg.odt"); + + // Select the image. + dispatchCommand(getComponent(), ".uno:JumpToNextFrame", {}); + + // Export the selection to SVG. + uno::Reference xStorable(getComponent(), uno::UNO_QUERY_THROW); + SvMemoryStream aStream; + uno::Reference xOut = new utl::OOutputStreamWrapper(aStream); + utl::MediaDescriptor aMediaDescriptor; + aMediaDescriptor["FilterName"] <<= OUString("writer_svg_Export"); + aMediaDescriptor["SelectionOnly"] <<= true; + aMediaDescriptor["OutputStream"] <<= xOut; + xStorable->storeToURL("private:stream", aMediaDescriptor.getAsConstPropertyValueList()); + aStream.Seek(STREAM_SEEK_TO_BEGIN); + + // Make sure that the original JPG data is reused and we don't perform a PNG re-compress. + xmlDocUniquePtr pXmlDoc = parseXmlStream(&aStream); + OUString aAttributeValue = getXPath(pXmlDoc, "//svg:image", "href"); + + // Without the accompanying fix in place, this test would have failed with: + // - Expression: aAttributeValue.startsWith("data:image/jpeg") + // i.e. the SVG export result re-compressed the image as PNG, even if the original and the + // transformed image is the same, so there is no need for that. + CPPUNIT_ASSERT(aAttributeValue.startsWith("data:image/jpeg")); +#endif +} + +CPPUNIT_TEST_FIXTURE(SvgFilterTest, testSemiTransparentLine) +{ + // Load a document with a semi-transparent line shape. + load(u"semi-transparent-line.odg"); + + // Export it to SVG. + uno::Reference xStorable(getComponent(), uno::UNO_QUERY_THROW); + SvMemoryStream aStream; + uno::Reference xOut = new utl::OOutputStreamWrapper(aStream); + utl::MediaDescriptor aMediaDescriptor; + aMediaDescriptor["FilterName"] <<= OUString("draw_svg_Export"); + aMediaDescriptor["OutputStream"] <<= xOut; + xStorable->storeToURL("private:stream", aMediaDescriptor.getAsConstPropertyValueList()); + aStream.Seek(STREAM_SEEK_TO_BEGIN); + + // Get the style of the group around the actual element. + xmlDocUniquePtr pXmlDoc = parseXmlStream(&aStream); + OUString aStyle = getXPath( + pXmlDoc, "//svg:g[@class='com.sun.star.drawing.LineShape']/svg:g/svg:g", "style"); + // Without the accompanying fix in place, this test would have failed, as the style was + // "mask:url(#mask1)", not "opacity: ". + CPPUNIT_ASSERT(aStyle.startsWith("opacity: ", &aStyle)); + int nPercent = std::round(aStyle.toDouble() * 100); + // Make sure that the line is still 30% opaque, rather than completely invisible. + CPPUNIT_ASSERT_EQUAL(30, nPercent); +} + +CPPUNIT_TEST_FIXTURE(SvgFilterTest, testSemiTransparentFillWithTransparentLine) +{ + // Load a document with a shape with semi-transparent fill and line + load(u"semi-transparent-fill.odg"); + + // Export it to SVG. + uno::Reference xStorable(getComponent(), uno::UNO_QUERY_THROW); + SvMemoryStream aStream; + uno::Reference xOut = new utl::OOutputStreamWrapper(aStream); + utl::MediaDescriptor aMediaDescriptor; + aMediaDescriptor["FilterName"] <<= OUString("draw_svg_Export"); + aMediaDescriptor["OutputStream"] <<= xOut; + xStorable->storeToURL("private:stream", aMediaDescriptor.getAsConstPropertyValueList()); + aStream.Seek(STREAM_SEEK_TO_BEGIN); + + // Get the style of the group around the actual element. + xmlDocUniquePtr pXmlDoc = parseXmlStream(&aStream); + OUString aStyle = getXPath( + pXmlDoc, "//svg:g[@class='com.sun.star.drawing.EllipseShape']/svg:g/svg:g", "style"); + CPPUNIT_ASSERT(aStyle.startsWith("opacity: ", &aStyle)); + int nPercent = std::round(aStyle.toDouble() * 100); + // Make sure that the line is still 50% opaque + CPPUNIT_ASSERT_EQUAL(50, nPercent); + + // Get the stroke of the fill of the EllipseShape (it must be "none") + OUString aStroke = getXPath( + pXmlDoc, "//svg:g[@class='com.sun.star.drawing.EllipseShape']/svg:g/svg:path", "stroke"); + // Without the accompanying fix in place, this test would have failed, as the stroke was + // "rgb(255,255,255)", not "none". + CPPUNIT_ASSERT_EQUAL(OUString("none"), aStroke); +} + +CPPUNIT_TEST_FIXTURE(SvgFilterTest, testSemiTransparentText) +{ + // Two shapes, one with transparent text and the other one with + // opaque text. We expect both to be exported to the SVG with the + // correct transparency factor applied for the first shape. + + // Load draw document with transparent text in one box + load(u"TransparentText.odg"); + + // Export to SVG. + uno::Reference xStorable(getComponent(), uno::UNO_QUERY_THROW); + + SvMemoryStream aStream; + uno::Reference xOut = new utl::OOutputStreamWrapper(aStream); + utl::MediaDescriptor aMediaDescriptor; + aMediaDescriptor["FilterName"] <<= OUString("draw_svg_Export"); + aMediaDescriptor["OutputStream"] <<= xOut; + xStorable->storeToURL("private:stream", aMediaDescriptor.getAsConstPropertyValueList()); + aStream.Seek(STREAM_SEEK_TO_BEGIN); + + xmlDocUniquePtr pXmlDoc = parseXmlStream(&aStream); + + // We expect 2 groups of class "TextShape" that + // have some svg:text node inside. + // Without the accompanying fix in place, this test would have failed with: + // - Expected: 2 + // - Actual : 1 + // i.e. the 2nd shape lots its text. + + assertXPath(pXmlDoc, "//svg:g[@class='TextShape']//svg:text", 2); + + // First shape has semi-transparent text. + assertXPath(pXmlDoc, "//svg:text[1]/svg:tspan/svg:tspan/svg:tspan[@fill-opacity='0.8']"); + + // Second shape has normal text. + assertXPath(pXmlDoc, "//svg:text[2]/svg:tspan/svg:tspan/svg:tspan[@fill-opacity]", 0); +} + +CPPUNIT_TEST_FIXTURE(SvgFilterTest, testSemiTransparentMultiParaText) +{ + // Given a shape with semi-transparent, multi-paragraph text: + getComponent() + = loadFromDesktop("private:factory/simpress", "com.sun.star.drawing.DrawingDocument"); + uno::Reference xFactory(getComponent(), uno::UNO_QUERY); + uno::Reference xShape( + xFactory->createInstance("com.sun.star.drawing.TextShape"), uno::UNO_QUERY); + uno::Reference xDrawPagesSupplier(getComponent(), uno::UNO_QUERY); + uno::Reference xDrawPage(xDrawPagesSupplier->getDrawPages()->getByIndex(0), + uno::UNO_QUERY); + xDrawPage->add(xShape); + xShape->setSize(awt::Size(10000, 10000)); + uno::Reference xShapeText(xShape, uno::UNO_QUERY); + uno::Reference xCursor = xShapeText->createTextCursor(); + xShapeText->insertString(xCursor, "foo", /*bAbsorb=*/false); + xShapeText->insertControlCharacter(xCursor, text::ControlCharacter::APPEND_PARAGRAPH, + /*bAbsorb=*/false); + xShapeText->insertString(xCursor, "bar", /*bAbsorb=*/false); + uno::Reference xShapeProps(xShape, uno::UNO_QUERY); + xShapeProps->setPropertyValue("CharColor", uno::Any(static_cast(0xff0000))); + xShapeProps->setPropertyValue("CharTransparence", uno::Any(static_cast(20))); + + // When exporting to SVG: + uno::Reference xStorable(getComponent(), uno::UNO_QUERY_THROW); + SvMemoryStream aStream; + uno::Reference xOut = new utl::OOutputStreamWrapper(aStream); + utl::MediaDescriptor aMediaDescriptor; + aMediaDescriptor["FilterName"] <<= OUString("draw_svg_Export"); + aMediaDescriptor["OutputStream"] <<= xOut; + xStorable->storeToURL("private:stream", aMediaDescriptor.getAsConstPropertyValueList()); + aStream.Seek(STREAM_SEEK_TO_BEGIN); + + // Then make sure that the two semi-tranparent paragraphs have the same X position: + xmlDocUniquePtr pXmlDoc = parseXmlStream(&aStream); + assertXPath(pXmlDoc, "(//svg:g[@class='TextShape']//svg:tspan[@class='TextPosition'])[1]", "x", + "250"); + assertXPath(pXmlDoc, + "(//svg:g[@class='TextShape']//svg:tspan[@class='TextPosition'])[1]/svg:tspan", + "fill-opacity", "0.8"); + // Without the accompanying fix in place, this test would have failed with: + // - Expected: 250 + // - Actual : 8819 + // i.e. the X position of the second paragraph was wrong. + assertXPath(pXmlDoc, "(//svg:g[@class='TextShape']//svg:tspan[@class='TextPosition'])[2]", "x", + "250"); + assertXPath(pXmlDoc, + "(//svg:g[@class='TextShape']//svg:tspan[@class='TextPosition'])[2]/svg:tspan", + "fill-opacity", "0.8"); +} + +CPPUNIT_TEST_FIXTURE(SvgFilterTest, testShapeNographic) +{ + // Load a document containing a 3D shape. + load(u"shape-nographic.odp"); + + // Export to SVG. + uno::Reference xStorable(getComponent(), uno::UNO_QUERY_THROW); + SvMemoryStream aStream; + uno::Reference xOut = new utl::OOutputStreamWrapper(aStream); + utl::MediaDescriptor aMediaDescriptor; + aMediaDescriptor["FilterName"] <<= OUString("impress_svg_Export"); + aMediaDescriptor["OutputStream"] <<= xOut; + + // Without the accompanying fix in place, this test would have failed with: + // An uncaught exception of type com.sun.star.io.IOException + // - SfxBaseModel::impl_store failed: 0xc10(Error Area:Io Class:Write Code:16) + xStorable->storeToURL("private:stream", aMediaDescriptor.getAsConstPropertyValueList()); +} + +CPPUNIT_TEST_FIXTURE(SvgFilterTest, testCustomBullet) +{ + // Given a presentation with a custom bullet: + load(u"custom-bullet.fodp"); + + // When exporting that to SVG: + uno::Reference xStorable(getComponent(), uno::UNO_QUERY_THROW); + SvMemoryStream aStream; + uno::Reference xOut = new utl::OOutputStreamWrapper(aStream); + utl::MediaDescriptor aMediaDescriptor; + aMediaDescriptor["FilterName"] <<= OUString("impress_svg_Export"); + aMediaDescriptor["OutputStream"] <<= xOut; + xStorable->storeToURL("private:stream", aMediaDescriptor.getAsConstPropertyValueList()); + + // Then make sure the bullet glyph is not lost: + aStream.Seek(STREAM_SEEK_TO_BEGIN); + xmlDocUniquePtr pXmlDoc = parseXmlStream(&aStream); + // Without the accompanying fix in place, this test would have failed with: + // - Expected: 1 + // - Actual : 0 + // - XPath '//svg:g[@class='BulletChars']//svg:path' number of nodes is incorrect + // i.e. the custom bullet used '', but nobody produced a bullet-char-template-45, + // instead we need the path of the glyph inline. + CPPUNIT_ASSERT(!getXPath(pXmlDoc, "//svg:g[@class='BulletChars']//svg:path", "d").isEmpty()); +} + +CPPUNIT_TEST_FIXTURE(SvgFilterTest, attributeRedefinedTest) +{ + // Load document containing empty paragraphs with ids. + load(u"attributeRedefinedTest.odp"); + + // Export to SVG. + uno::Reference xStorable(getComponent(), uno::UNO_QUERY_THROW); + SvMemoryStream aStream; + uno::Reference xOut = new utl::OOutputStreamWrapper(aStream); + utl::MediaDescriptor aMediaDescriptor; + aMediaDescriptor["FilterName"] <<= OUString("impress_svg_Export"); + aMediaDescriptor["OutputStream"] <<= xOut; + xStorable->storeToURL("private:stream", aMediaDescriptor.getAsConstPropertyValueList()); + aStream.Seek(STREAM_SEEK_TO_BEGIN); + + xmlDocUniquePtr pXmlDoc = parseXmlStream(&aStream); + + // We expect four paragraph + // 2 empty paragraphs with ids + // 2 paragraphs with text + // Without the accompanying fix the test would have failed with + // Expected : 4 + // Actual : 2 + // i.e. 2 of the empty paragraph do not get generated even if there + // is id imported for the paragraphs + // If we don't create the empty paragraphs the id attribute gets redefined like this: + // + + OString xPath = "//svg:g[@class='TextShape']//svg:text[@class='SVGTextShape']//" + "svg:tspan[@class='TextParagraph']"; + assertXPath(pXmlDoc, xPath, 4); + + //assert that each tspan element with TextParagraph class has id and the tspan element of + //each empty paragraph does not contain tspan element with class TextPosition + assertXPath(pXmlDoc, xPath + "[1]", "id", "id4"); + assertXPath(pXmlDoc, xPath + "[2]", "id", "id5"); + assertXPath(pXmlDoc, xPath + "[2]//svg:tspan[@class='TextPosition']", 0); + assertXPath(pXmlDoc, xPath + "[3]", "id", "id6"); + assertXPath(pXmlDoc, xPath + "[3]//svg:tspan[@class='TextPosition']", 0); + assertXPath(pXmlDoc, xPath + "[4]", "id", "id7"); +} + +CPPUNIT_TEST_FIXTURE(SvgFilterTest, testTab) +{ + // Given a shape with "A\tB" text: + getComponent() = loadFromDesktop("private:factory/simpress", + "com.sun.star.presentation.PresentationDocument"); + uno::Reference xFactory(getComponent(), uno::UNO_QUERY); + uno::Reference xShape( + xFactory->createInstance("com.sun.star.drawing.TextShape"), uno::UNO_QUERY); + uno::Reference xDrawPagesSupplier(getComponent(), uno::UNO_QUERY); + uno::Reference xDrawPage(xDrawPagesSupplier->getDrawPages()->getByIndex(0), + uno::UNO_QUERY); + xDrawPage->add(xShape); + xShape->setSize(awt::Size(10000, 10000)); + uno::Reference xShapeText(xShape, uno::UNO_QUERY); + xShapeText->setString("A\tB"); + + // When exporting that document to SVG: + uno::Reference xStorable(getComponent(), uno::UNO_QUERY_THROW); + SvMemoryStream aStream; + uno::Reference xOut = new utl::OOutputStreamWrapper(aStream); + utl::MediaDescriptor aMediaDescriptor; + aMediaDescriptor["FilterName"] <<= OUString("impress_svg_Export"); + aMediaDescriptor["OutputStream"] <<= xOut; + xStorable->storeToURL("private:stream", aMediaDescriptor.getAsConstPropertyValueList()); + + // Then make sure the the tab is not lost: + aStream.Seek(STREAM_SEEK_TO_BEGIN); + xmlDocUniquePtr pXmlDoc = parseXmlStream(&aStream); + // Without the accompanying fix in place, this test would have failed with: + // - Expected: 2 + // - Actual : 1 + // i.e. the 2nd text portion was not positioned, which looked as if the tab is lost. + assertXPath(pXmlDoc, "//svg:g[@class='TextShape']//svg:tspan[@class='TextPosition']", 2); +} + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/filter/qa/unit/textfilterdetect.cxx b/filter/qa/unit/textfilterdetect.cxx new file mode 100644 index 000000000..3c8daf2f2 --- /dev/null +++ b/filter/qa/unit/textfilterdetect.cxx @@ -0,0 +1,199 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace com::sun::star::io +{ +class XInputStream; +} + +using namespace com::sun::star; + +namespace +{ +/// Test class for PlainTextFilterDetect. +class TextFilterDetectTest : public test::BootstrapFixture, public unotest::MacrosTest +{ +public: + void setUp() override; +}; + +void TextFilterDetectTest::setUp() +{ + test::BootstrapFixture::setUp(); + + mxDesktop.set(frame::Desktop::create(mxComponentContext)); +} + +constexpr OUStringLiteral DATA_DIRECTORY = u"/filter/qa/unit/data/"; + +CPPUNIT_TEST_FIXTURE(TextFilterDetectTest, testTdf114428) +{ + uno::Reference xDetect( + getMultiServiceFactory()->createInstance("com.sun.star.comp.filters.PlainTextFilterDetect"), + uno::UNO_QUERY); + OUString aURL = m_directories.getURLFromSrc(DATA_DIRECTORY) + "tdf114428.xhtml"; + SvFileStream aStream(aURL, StreamMode::READ); + uno::Reference xStream(new utl::OStreamWrapper(aStream)); + uno::Sequence aDescriptor + = { comphelper::makePropertyValue("DocumentService", + OUString("com.sun.star.text.TextDocument")), + comphelper::makePropertyValue("InputStream", xStream), + comphelper::makePropertyValue("TypeName", OUString("generic_HTML")) }; + xDetect->detect(aDescriptor); + utl::MediaDescriptor aMediaDesc(aDescriptor); + OUString aFilterName = aMediaDesc.getUnpackedValueOrDefault("FilterName", OUString()); + // This was empty, XML declaration caused HTML detect to not handle XHTML. + CPPUNIT_ASSERT_EQUAL(OUString("HTML (StarWriter)"), aFilterName); +} + +CPPUNIT_TEST_FIXTURE(TextFilterDetectTest, testEmptyFile) +{ + const OUString sDataDirectory = m_directories.getURLFromSrc(DATA_DIRECTORY); + auto supportsService = [](const uno::Reference& x, const OUString& s) { + return uno::Reference(x, uno::UNO_QUERY_THROW)->supportsService(s); + }; + + // Given an empty file, with a pptx extension + // When loading the file + auto xComponent = loadFromDesktop(sDataDirectory + "empty.pptx"); + + // Then make sure it is opened in Impress. + // Without the accompanying fix in place, this test would have failed, as it was opened in + // Writer instead. + CPPUNIT_ASSERT(supportsService(xComponent, "com.sun.star.presentation.PresentationDocument")); + xComponent->dispose(); + + // Now also test ODT + xComponent = loadFromDesktop(sDataDirectory + "empty.odt"); + // Make sure it opens in Writer. + CPPUNIT_ASSERT(supportsService(xComponent, "com.sun.star.text.TextDocument")); + xComponent->dispose(); + + // ... and ODS + xComponent = loadFromDesktop(sDataDirectory + "empty.ods"); + // Make sure it opens in Calc. + CPPUNIT_ASSERT(supportsService(xComponent, "com.sun.star.sheet.SpreadsheetDocument")); + xComponent->dispose(); + + // ... and ODP + xComponent = loadFromDesktop(sDataDirectory + "empty.odp"); + // Without the accompanying fix in place, this test would have failed, as it was opened in + // Writer instead. + CPPUNIT_ASSERT(supportsService(xComponent, "com.sun.star.presentation.PresentationDocument")); + xComponent->dispose(); + + // ... and DOC + // Without the accompanying fix in place, this test would have failed, the import filter aborted + // loading. + xComponent = loadFromDesktop(sDataDirectory + "empty.doc"); + CPPUNIT_ASSERT(supportsService(xComponent, "com.sun.star.text.TextDocument")); + { + uno::Reference xModel(xComponent, uno::UNO_QUERY); + uno::Sequence aArgs = xModel->getArgs(); + comphelper::SequenceAsHashMap aMap(aArgs); + OUString aFilterName; + aMap["FilterName"] >>= aFilterName; + // Without the accompanying fix in place, this test would have failed with: + // - Expected: MS Word 97 + // - Actual : MS WinWord 6.0 + // i.e. opening worked, but saving back failed instead of producing a WW8 binary file. + CPPUNIT_ASSERT_EQUAL(OUString("MS Word 97"), aFilterName); + } + xComponent->dispose(); + + // Now test with default templates set + + SfxObjectFactory::SetStandardTemplate("com.sun.star.presentation.PresentationDocument", + sDataDirectory + "impress.otp"); + SfxObjectFactory::SetStandardTemplate("com.sun.star.text.TextDocument", + sDataDirectory + "writer.ott"); + SfxObjectFactory::SetStandardTemplate("com.sun.star.sheet.SpreadsheetDocument", + sDataDirectory + "calc.ots"); + + xComponent = loadFromDesktop(sDataDirectory + "empty.pptx"); + { + uno::Reference xDoc(xComponent, uno::UNO_QUERY_THROW); + uno::Reference xPages(xDoc->getDrawPages(), uno::UNO_SET_THROW); + uno::Reference xPage(xPages->getByIndex(0), uno::UNO_QUERY_THROW); + uno::Reference xBox(xPage->getByIndex(0), uno::UNO_QUERY_THROW); + + // Make sure the template's text was loaded + CPPUNIT_ASSERT_EQUAL(OUString("Title of Impress template"), xBox->getString()); + } + xComponent->dispose(); + + xComponent = loadFromDesktop(sDataDirectory + "empty.odt"); + { + uno::Reference xDoc(xComponent, uno::UNO_QUERY_THROW); + uno::Reference xEA(xDoc->getText(), uno::UNO_QUERY_THROW); + uno::Reference xEnum(xEA->createEnumeration(), uno::UNO_SET_THROW); + uno::Reference xParagraph(xEnum->nextElement(), uno::UNO_QUERY_THROW); + + // Make sure the template's text was loaded + CPPUNIT_ASSERT_EQUAL(OUString(u"Writer template’s first line"), xParagraph->getString()); + } + xComponent->dispose(); + + xComponent = loadFromDesktop(sDataDirectory + "empty.ods"); + { + uno::Reference xDoc(xComponent, uno::UNO_QUERY_THROW); + uno::Reference xRA(xDoc->getSheets(), uno::UNO_QUERY_THROW); + uno::Reference xC(xRA->getCellByPosition(0, 0, 0), uno::UNO_QUERY_THROW); + + // Make sure the template's text was loaded + CPPUNIT_ASSERT_EQUAL(OUString(u"Calc template’s first cell"), xC->getString()); + } + xComponent->dispose(); + + xComponent = loadFromDesktop(sDataDirectory + "empty.odp"); + { + uno::Reference xDoc(xComponent, uno::UNO_QUERY_THROW); + uno::Reference xPages(xDoc->getDrawPages(), uno::UNO_SET_THROW); + uno::Reference xPage(xPages->getByIndex(0), uno::UNO_QUERY_THROW); + uno::Reference xBox(xPage->getByIndex(0), uno::UNO_QUERY_THROW); + + // Make sure the template's text was loaded + CPPUNIT_ASSERT_EQUAL(OUString("Title of Impress template"), xBox->getString()); + } + xComponent->dispose(); + + xComponent = loadFromDesktop(sDataDirectory + "empty.doc"); + { + uno::Reference xDoc(xComponent, uno::UNO_QUERY_THROW); + uno::Reference xEA(xDoc->getText(), uno::UNO_QUERY_THROW); + uno::Reference xEnum(xEA->createEnumeration(), uno::UNO_SET_THROW); + uno::Reference xParagraph(xEnum->nextElement(), uno::UNO_QUERY_THROW); + + // Make sure the template's text was loaded + CPPUNIT_ASSERT_EQUAL(OUString(u"Writer template’s first line"), xParagraph->getString()); + } + xComponent->dispose(); +} +} + +CPPUNIT_PLUGIN_IMPLEMENT(); + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ -- cgit v1.2.3