31#include <rtl/ustring.hxx>
34#include <com/sun/star/io/IOException.hpp>
35#include <com/sun/star/util/XCloseable.hpp>
36#include <com/sun/star/util/CloseVetoException.hpp>
37#include <com/sun/star/task/InteractionHandler.hpp>
38#include <com/sun/star/util/URL.hpp>
39#include <com/sun/star/frame/Desktop.hpp>
40#include <com/sun/star/container/XContainerQuery.hpp>
41#include <com/sun/star/container/XEnumeration.hpp>
42#include <com/sun/star/frame/XDispatch.hpp>
43#include <com/sun/star/frame/XNotifyingDispatch.hpp>
44#include <com/sun/star/beans/PropertyValue.hpp>
45#include <com/sun/star/view/XPrintable.hpp>
46#include <com/sun/star/util/URLTransformer.hpp>
47#include <com/sun/star/util/XURLTransformer.hpp>
48#include <com/sun/star/document/MacroExecMode.hpp>
49#include <com/sun/star/document/XTypeDetection.hpp>
50#include <com/sun/star/document/UpdateDocMode.hpp>
51#include <com/sun/star/frame/XStorable.hpp>
52#include <com/sun/star/script/XLibraryContainer2.hpp>
53#include <com/sun/star/document/XEmbeddedScripts.hpp>
62#include <osl/thread.hxx>
63#include <osl/file.hxx>
79namespace document = ::com::sun::star::document;
88 DispatchHolder( URL _aURL, Reference< XDispatch >
const & rDispatch ) :
95std::shared_ptr<const SfxFilter> impl_lookupExportFilterForUrl( std::u16string_view rUrl, std::u16string_view rFactory )
98 OUString sQuery =
"getSortedFilterList()"
100 OUString::Concat(rFactory) +
102 OUString::number(
static_cast<sal_Int32
>(SfxFilterFlags::EXPORT)) +
107 const Reference< XContainerQuery > xFilterFactory(
108 xContext->getServiceManager()->createInstanceWithContext(
"com.sun.star.document.FilterFactory",
xContext ),
111 std::shared_ptr<const SfxFilter> pBestMatch;
113 const Reference< XEnumeration > xFilterEnum(
114 xFilterFactory->createSubSetEnumerationByQuery( sQuery ), UNO_SET_THROW );
115 while ( xFilterEnum->hasMoreElements() )
119 if ( !
aName.isEmpty() )
122 if ( pFilter && pFilter->CanExport() && pFilter->GetWildcard().Matches( rUrl ) )
124 if ( !pBestMatch || ( SfxFilterFlags::PREFERED & pFilter->GetFilterFlags() ) )
125 pBestMatch = pFilter;
133std::shared_ptr<const SfxFilter> impl_getExportFilterFromUrl(
134 const OUString& rUrl,
const OUString& rFactory)
139 const Reference< document::XTypeDetection > xTypeDetector(
140 xContext->getServiceManager()->createInstanceWithContext(
"com.sun.star.document.TypeDetection",
xContext ),
142 const OUString aTypeName( xTypeDetector->queryTypeByURL( rUrl ) );
144 std::shared_ptr<const SfxFilter> pFilter(
SfxFilterMatcher( rFactory ).GetFilter4EA( aTypeName, SfxFilterFlags::EXPORT ) );
146 pFilter = impl_lookupExportFilterForUrl( rUrl, rFactory );
150 FileBase::getSystemPathFromFileURL( rUrl, aTempName );
152 std::cerr <<
"Error: no export filter for " << aSource <<
" found, aborting." << std::endl;
157 catch (
const Exception& )
163OUString impl_GuessFilter(
const OUString& rUrlOut,
const OUString& rDocService )
166 std::shared_ptr<const SfxFilter> pOutFilter = impl_getExportFilterFromUrl( rUrlOut, rDocService );
168 aOutFilter = pOutFilter->GetFilterName();
174void scriptCat(
const Reference< XModel >& xDoc )
176 Reference< XEmbeddedScripts > xScriptAccess( xDoc, UNO_QUERY );
179 std::cout <<
"No script access\n";
184 Reference< css::script::XLibraryContainer2 > xLibraries(
185 xScriptAccess->getBasicLibraries() );
187 if ( !xLibraries.is() )
189 std::cout <<
"No script libraries\n";
194 std::cout <<
"Libraries: " << aLibNames.getLength() <<
"\n";
195 for (OUString
const & libName : aLibNames)
197 std::cout <<
"Library: '" << libName <<
"' children: ";
198 Reference< XNameContainer > xContainer;
200 if (!xLibraries->isLibraryLoaded( libName ))
201 xLibraries->loadLibrary( libName );
202 xContainer = Reference< XNameContainer >(
203 xLibraries->getByName( libName ), UNO_QUERY );
205 catch (
const css::uno::Exception &e)
207 std::cout <<
"[" << libName <<
"] - failed to load library: " << e.Message <<
"\n";
210 if( !xContainer.is() )
216 std::cout << aObjectNames.getLength() <<
"\n\n";
217 for ( sal_Int32 j = 0 ; j < aObjectNames.getLength() ; ++j )
219 const OUString &rObjectName = aObjectNames[j];
223 Any aCode = xContainer->getByName( rObjectName );
224 OUString aCodeString;
226 if (! (aCode >>= aCodeString ) )
227 std::cout <<
"[" << rObjectName <<
"] - error fetching code\n";
229 std::cout <<
"[" << rObjectName <<
"]\n"
230 << aCodeString.trim()
231 <<
"\n[/" << rObjectName <<
"]\n";
233 catch (
const css::uno::Exception &e)
235 std::cout <<
"[" << rObjectName <<
"] - exception " << e.Message <<
" fetching code\n";
238 if (j < aObjectNames.getLength() - 1)
239 std::cout <<
"\n----------------------------------------------------------\n";
247void batchPrint( std::u16string_view rPrinterName,
const Reference< XPrintable > &xDoc,
251 OUString aPrinterName;
252 size_t nPathIndex = rPrinterName.rfind(
';' );
253 if( nPathIndex != std::u16string_view::npos )
254 aFilterOut=rPrinterName.substr( nPathIndex+1 );
255 if( nPathIndex != 0 )
256 aPrinterName=rPrinterName.substr( 0, nPathIndex );
259 aOutFilename.SetExtension( u
"pdf" );
260 FileBase::getFileURLFromSystemPath( aFilterOut, aFilterOut );
261 OUString aOutFile = aFilterOut +
"/" + aOutFilename.getName();
264 FileBase::getSystemPathFromFileURL( aName, aTempName );
266 FileBase::getSystemPathFromFileURL( aOutFile, aTempName );
267 OString aTargetURL8 =
OUStringToOString(aTempName, osl_getThreadTextEncoding() );
269 std::cout <<
"print " << aSource8 <<
" -> " << aTargetURL8;
270 std::cout <<
" using " << (aPrinterName.isEmpty() ?
"<default_printer>" :
OUStringToOString( aPrinterName, osl_getThreadTextEncoding() ));
271 std::cout << std::endl;
274 Sequence < PropertyValue > aPrinterArgs;
275 if( !aPrinterName.isEmpty() )
278 xDoc->setPrinter( aPrinterArgs );
284 xDoc->print( aPrinterArgs );
288OUString getName(
const Reference< XInterface > & xDoc)
290 Reference< XModel >
xModel( xDoc, UNO_QUERY );
295 if (aDocService ==
"com.sun.star.text.TextDocument")
297 else if (aDocService ==
"com.sun.star.text.GlobalDocument")
298 return "Writer master";
299 else if (aDocService ==
"com.sun.star.text.WebDocument")
301 else if (aDocService ==
"com.sun.star.drawing.DrawingDocument")
303 else if (aDocService ==
"com.sun.star.presentation.PresentationDocument")
305 else if (aDocService ==
"com.sun.star.sheet.SpreadsheetDocument")
307 else if (aDocService ==
"com.sun.star.script.BasicIDE")
309 else if (aDocService ==
"com.sun.star.formula.FormulaProperties")
311 else if (aDocService ==
"com.sun.star.sdb.RelationDesign")
312 return "Relation Design";
313 else if (aDocService ==
"com.sun.star.sdb.QueryDesign")
314 return "Query Design";
315 else if (aDocService ==
"com.sun.star.sdb.TableDesign")
316 return "Table Design";
317 else if (aDocService ==
"com.sun.star.sdb.DataSourceBrowser")
318 return "Data Source Browser";
319 else if (aDocService ==
"com.sun.star.sdb.DatabaseDocument")
342 std::vector< DispatchHolder > aDispatches;
343 bool bSetInputFilter =
false;
344 OUString aForcedInputFilter;
346 for (
auto const & aDispatchRequest: aDispatchRequestsList)
351 bSetInputFilter =
true;
352 aForcedInputFilter = aDispatchRequest.aURL;
358 std::vector<PropertyValue> aArgs;
361 aArgs.emplace_back(
"Referer", 0,
Any(OUString(
"private:OpenEvent")),
362 PropertyState_DIRECT_VALUE);
364 OUString aTarget(
"_default");
375 aArgs.emplace_back(
"ReadOnly", 0,
Any(
true), PropertyState_DIRECT_VALUE);
377 aArgs.emplace_back(
"OpenNewView", 0,
Any(
true), PropertyState_DIRECT_VALUE);
379 aArgs.emplace_back(
"Hidden", 0,
Any(
true), PropertyState_DIRECT_VALUE);
381 aArgs.emplace_back(
"Silent", 0,
Any(
true), PropertyState_DIRECT_VALUE);
388 Reference < XInteractionHandler2 > xInteraction(
389 InteractionHandler::createWithParent(::comphelper::getProcessComponentContext(),
nullptr) );
391 aArgs.emplace_back(
"InteractionHandler", 0,
Any(xInteraction),
392 PropertyState_DIRECT_VALUE);
394 aArgs.emplace_back(
"MacroExecutionMode", 0,
395 Any(css::document::MacroExecMode::USE_CONFIG),
396 PropertyState_DIRECT_VALUE);
398 aArgs.emplace_back(
"UpdateDocMode", 0,
399 Any(css::document::UpdateDocMode::ACCORDING_TO_CONFIG),
400 PropertyState_DIRECT_VALUE);
403 if ( !aDispatchRequest.aPreselectedFactory.isEmpty() )
406 Any(aDispatchRequest.aPreselectedFactory),
407 PropertyState_DIRECT_VALUE);
410 OUString
aName(
GetURL_Impl( aDispatchRequest.aURL, aDispatchRequest.aCwdUrl ) );
414 Reference < XPrintable > xDoc;
416 (
aName.startsWith(
".uno" ) ) ||
417 (
aName.startsWith(
"slot:" ) ) ||
418 (
aName.startsWith(
"macro:" ) ) ||
419 (
aName.startsWith(
"vnd.sun.star.script") )
427 Reference < XDispatch > xDispatcher ;
428 Reference < XURLTransformer > xParser (
URLTransformer::create(::comphelper::getProcessComponentContext()) );
431 xParser->parseStrict(
aURL );
433 xDispatcher = xDesktop->queryDispatch(
aURL, OUString(), 0 );
435 !xDispatcher.is(),
"desktop.app",
436 "unsupported dispatch request <" <<
aName <<
">");
437 if( xDispatcher.is() )
444 aDispatches.emplace_back(
aURL, xDispatcher );
447 else if (
aName.startsWith(
"service:" ) )
453 Reference < XDispatch > xDispatcher ;
454 Reference < XURLTransformer > xParser (
URLTransformer::create(::comphelper::getProcessComponentContext()) );
457 xParser->parseStrict(
aURL );
459 xDispatcher = xDesktop->queryDispatch(
aURL, OUString(), 0 );
461 if( xDispatcher.is() )
470 Reference < XNotifyingDispatch > xDisp( xDispatcher, UNO_QUERY );
472 xDisp->dispatchWithNotification(
aURL, aArgs2,
this );
474 xDispatcher->dispatch(
aURL, aArgs2 );
476 catch (
const css::uno::Exception&)
480 "Desktop::OpenDefault() ignoring Exception while calling XNotifyingDispatch");
487 if ( aObj.
GetProtocol() == INetProtocol::PrivSoffice )
488 aTarget =
"_default";
494 aArgs.emplace_back(
"AsTemplate", 0,
496 PropertyState_DIRECT_VALUE);
501 aArgs.emplace_back(
"ReadOnly", 0,
Any(
true), PropertyState_DIRECT_VALUE);
506 aArgs.emplace_back(
"StartPresentation", 0,
Any(
true), PropertyState_DIRECT_VALUE);
510 if( bSetInputFilter )
512 sal_Int32 nFilterOptionsIndex = 0;
513 aArgs.emplace_back(
"FilterName", 0,
514 Any(aForcedInputFilter.getToken(0,
':', nFilterOptionsIndex)),
515 PropertyState_DIRECT_VALUE);
517 if (0 < nFilterOptionsIndex)
519 aArgs.emplace_back(
"FilterOptions", 0,
520 Any(aForcedInputFilter.copy(nFilterOptionsIndex)),
521 PropertyState_DIRECT_VALUE);
532 catch (
const css::lang::IllegalArgumentException&)
536 "Dispatchwatcher IllegalArgumentException while calling loadComponentFromURL");
538 catch (
const css::io::IOException&)
542 "Dispatchwatcher IOException while calling loadComponentFromURL");
567 Reference< XStorable > xStorable( xDoc, UNO_QUERY );
568 if ( xStorable.is() ) {
569 OUString aParam = aDispatchRequest.aPrinterName;
570 sal_Int32 nPathIndex = aParam.lastIndexOf(
';' );
571 sal_Int32 nFilterIndex = aParam.indexOf(
':' );
572 sal_Int32 nImgFilterIndex = aParam.lastIndexOf(
'|' );
573 if( nPathIndex < nFilterIndex )
582 if( nFilterIndex >= 0 )
584 aFilter = aParam.copy( nFilterIndex+1, nPathIndex-nFilterIndex-1 );
585 aFilterExt = aParam.copy( 0, nFilterIndex );
591 aFilterExt = aParam.copy( 0, nPathIndex );
594 if( nImgFilterIndex >= 0 )
596 aImgOut = aParam.copy( nImgFilterIndex+1 );
597 aFilterOut = aParam.copy( nPathIndex+1, nImgFilterIndex-nPathIndex-1 );
600 aFilterOut = aParam.copy( nPathIndex+1 );
602 FileBase::getFileURLFromSystemPath( aFilterOut, aFilterOut );
610 std::unique_ptr<utl::TempFileNamed> fileForCat;
613 fileForCat = std::make_unique<utl::TempFileNamed>();
614 if (fileForCat->IsValid())
615 fileForCat->EnableKillingFile();
617 std::cerr <<
"Error: Cannot create temporary file..." << std::endl ;
618 aOutFile = fileForCat->GetURL();
623 OUString aDocService;
624 Reference< XModel >
xModel( xDoc, UNO_QUERY );
630 aFilter = impl_GuessFilter( aOutFile, aDocService );
633 bool bMultiFileTarget =
false;
635 if (aFilter.isEmpty())
637 std::cerr <<
"Error: no export filter" << std::endl;
641 sal_Int32 nFilterOptionsIndex = aFilter.indexOf(
':');
642 sal_Int32 nProps = ( 0 < nFilterOptionsIndex ) ? 4 : 3;
644 if ( !aImgOut.isEmpty() )
646 Sequence<PropertyValue> conversionProperties( nProps );
647 auto pconversionProperties = conversionProperties.getArray();
648 pconversionProperties[0].Name =
"ConversionRequestOrigin";
649 pconversionProperties[0].Value <<= OUString(
"CommandLine");
650 pconversionProperties[1].Name =
"Overwrite";
651 pconversionProperties[1].Value <<=
true;
653 pconversionProperties[2].Name =
"FilterName";
654 if( 0 < nFilterOptionsIndex )
656 OUString sFilterName = aFilter.copy(0, nFilterOptionsIndex);
657 OUString sFilterOptions = aFilter.copy(nFilterOptionsIndex + 1);
659 if (sFilterName ==
"Text - txt - csv (StarCalc)")
672 const OUString aTok(sFilterOptions.getToken(11,
',', nIdx));
675 bMultiFileTarget = (!aTok.isEmpty() && aTok.toInt32() != 0);
678 pconversionProperties[2].Value <<= sFilterName;
680 pconversionProperties[3].Name =
"FilterOptions";
681 pconversionProperties[3].Value <<= sFilterOptions;
685 pconversionProperties[2].Value <<= aFilter;
688 if ( !aImgOut.isEmpty() )
690 assert(conversionProperties[nProps-1].
Name.isEmpty());
691 pconversionProperties[nProps-1].Name =
"ImageFilter";
692 pconversionProperties[nProps-1].Value <<= aImgOut;
696 FileBase::getSystemPathFromFileURL(
aName, aTempName);
698 FileBase::getSystemPathFromFileURL(aOutFile, aTempName);
702 OUString
name=getName(xDoc);
703 std::cout <<
"convert " << aSource8;
705 std::cout <<
" as a " <<
name <<
" document";
706 if (!bMultiFileTarget)
707 std::cout <<
" -> " << aTargetURL8;
708 std::cout <<
" using filter : " <<
OUStringToOString(aFilter, osl_getThreadTextEncoding()) << std::endl;
710 std::cout <<
"Overwriting: " <<
OUStringToOString(aTempName, osl_getThreadTextEncoding()) << std::endl ;
714 xStorable->storeToURL(aOutFile, conversionProperties);
718 std::cerr <<
"Error: Please verify input parameters...";
719 if (!rException.Message.isEmpty())
720 std::cerr <<
" (" << rException.Message <<
")";
721 std::cerr << std::endl;
724 if (fileForCat && fileForCat->IsValid())
726 SvStream* aStream = fileForCat->GetStream(StreamMode::STD_READ);
727 while (aStream->
good())
731 for (sal_Int32
i = 0;
i <
aStr.getLength(); ++
i)
733 std::cout <<
aStr[
i];
735 std::cout << std::endl;
743 Reference< XModel >
xModel( xDoc, UNO_QUERY );
749 batchPrint( aDispatchRequest.aPrinterName, xDoc, aObj,
aName );
757 "Name", aDispatchRequest.aPrinterName) };
758 xDoc->setPrinter( aPrinterArgs );
764 xDoc->print( aPrinterArgs );
769 std::cerr <<
"Error: source file could not be loaded" << std::endl;
775 Reference < XCloseable > xClose( xDoc, UNO_QUERY );
777 xClose->close(
true );
780 Reference < XComponent > xComp( xDoc, UNO_QUERY );
785 catch (
const css::util::CloseVetoException&)
795 if ( !aDispatches.empty() )
798 Sequence < PropertyValue > aArgs{
803 for (
const DispatchHolder & aDispatche : aDispatches)
805 Reference< XDispatch >
xDispatch = aDispatche.xDispatch;
806 Reference < XNotifyingDispatch > xDisp(
xDispatch, UNO_QUERY );
808 xDisp->dispatchWithNotification( aDispatche.aURL, aArgs,
this );
812 xDispatch->dispatch( aDispatche.aURL, aArgs );
822 if ( bEmpty && !bNoTerminate )
825 Reference< XElementAccess > xList = xDesktop->getFrames();
827 if ( !xList->hasElements() )
830 return xDesktop->terminate();
851 Reference< XElementAccess > xList = xDesktop->getFrames();
853 if ( !xList->hasElements() )
856 xDesktop->terminate();
OUString getName(sal_Int32 nIndex=LAST_SEGMENT, bool bIgnoreFinalSlash=true, DecodeMechanism eMechanism=DecodeMechanism::ToIUri, rtl_TextEncoding eCharset=RTL_TEXTENCODING_UTF8) const
void SetExtension(std::u16string_view rTheExtension)
OUString GetMainURL(DecodeMechanism eMechanism, rtl_TextEncoding eCharset=RTL_TEXTENCODING_UTF8) const
INetProtocol GetProtocol() const
bool Append(std::u16string_view rTheSegment, EncodeMechanism eMechanism=EncodeMechanism::WasEncoded, rtl_TextEncoding eCharset=RTL_TEXTENCODING_UTF8)
static std::shared_ptr< const SfxFilter > GetFilterByName(const OUString &rName)
bool ReadLine(OStringBuffer &rStr, sal_Int32 nMaxBytesToRead=0xFFFE)
TValueType getUnpackedValueOrDefault(const OUString &sKey, const TValueType &aDefault) const
static COMPHELPER_DLLPUBLIC css::uno::Reference< css::lang::XComponent > dispatch(const css::uno::Reference< css::uno::XInterface > &xStartPoint, const OUString &sURL, const OUString &sTarget, const css::uno::Sequence< css::beans::PropertyValue > &lArguments)
virtual void SAL_CALL dispatchFinished(const css::frame::DispatchResultEvent &aEvent) override
virtual void SAL_CALL disposing(const css::lang::EventObject &Source) override
virtual ~DispatchWatcher() override
std::atomic< int > m_nRequestCount
bool executeDispatchRequests(const std::vector< DispatchRequest > &aDispatches, bool bNoTerminate)
static bool AreRequestsPending()
static void RequestsCompleted()
#define TOOLS_WARN_EXCEPTION(area, stream)
Reference< XDispatch > xDispatch
#define SFX_FILTER_NOTINSTALLED
static uno::Reference< css::uno::XComponentContext > xContext
#define SAL_WARN_IF(condition, area, stream)
SVL_DLLPUBLIC bool IsDocument(const OUString &rURL)
css::uno::Sequence< DstElementType > containerToSequence(const SrcType &i_Container)
Reference< XComponentContext > getProcessComponentContext()
css::beans::PropertyValue makePropertyValue(const OUString &rName, T &&rValue)
OUString GetURL_Impl(const OUString &rName, std::optional< OUString > const &cwdUrl)
css::uno::Reference< css::deployment::XPackageRegistry > create(css::uno::Reference< css::deployment::XPackageRegistry > const &xRootRegistry, OUString const &context, OUString const &cachePath, css::uno::Reference< css::uno::XComponentContext > const &xComponentContext)
OString OUStringToOString(std::u16string_view str, ConnectionSettings const *settings)
Reference< XModel > xModel