LibreOffice Module desktop (master) 1
dispatchwatcher.cxx
Go to the documentation of this file.
1/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2/*
3 * This file is part of the LibreOffice project.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 * This file incorporates work covered by the following license notice:
10 *
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 */
19
20#include <sal/config.h>
21
22#include <sal/log.hxx>
23#include <sfx2/docfile.hxx>
24#include <sfx2/docfilt.hxx>
25#include <sfx2/fcontnr.hxx>
26#include <svl/fstathelper.hxx>
27
28#include <app.hxx>
29#include "dispatchwatcher.hxx"
30#include "officeipcthread.hxx"
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>
54
58#include <tools/urlobj.hxx>
60#include <unotools/tempfile.hxx>
61
62#include <osl/thread.hxx>
63#include <osl/file.hxx>
64#include <iostream>
65#include <string_view>
66#include <utility>
67
68using namespace ::osl;
69using namespace ::com::sun::star::uno;
70using namespace ::com::sun::star::util;
71using namespace ::com::sun::star::lang;
72using namespace ::com::sun::star::frame;
73using namespace ::com::sun::star::container;
74using namespace ::com::sun::star::beans;
75using namespace ::com::sun::star::view;
76using namespace ::com::sun::star::task;
77using namespace ::com::sun::star::document;
78
79namespace document = ::com::sun::star::document;
80
81namespace desktop
82{
83
84namespace {
85
86struct DispatchHolder
87{
88 DispatchHolder( URL _aURL, Reference< XDispatch > const & rDispatch ) :
89 aURL(std::move( _aURL )), xDispatch( rDispatch ) {}
90
92 Reference< XDispatch > xDispatch;
93};
94
95std::shared_ptr<const SfxFilter> impl_lookupExportFilterForUrl( std::u16string_view rUrl, std::u16string_view rFactory )
96{
97 // create the list of filters
98 OUString sQuery = "getSortedFilterList()"
99 ":module=" +
100 OUString::Concat(rFactory) + // use long name here !
101 ":iflags=" +
102 OUString::number(static_cast<sal_Int32>(SfxFilterFlags::EXPORT)) +
103 ":eflags=" +
104 OUString::number(static_cast<int>(SFX_FILTER_NOTINSTALLED));
105
106 const Reference< XComponentContext > xContext( comphelper::getProcessComponentContext() );
107 const Reference< XContainerQuery > xFilterFactory(
108 xContext->getServiceManager()->createInstanceWithContext( "com.sun.star.document.FilterFactory", xContext ),
109 UNO_QUERY_THROW );
110
111 std::shared_ptr<const SfxFilter> pBestMatch;
112
113 const Reference< XEnumeration > xFilterEnum(
114 xFilterFactory->createSubSetEnumerationByQuery( sQuery ), UNO_SET_THROW );
115 while ( xFilterEnum->hasMoreElements() )
116 {
117 comphelper::SequenceAsHashMap aFilterProps( xFilterEnum->nextElement() );
118 const OUString aName( aFilterProps.getUnpackedValueOrDefault( "Name", OUString() ) );
119 if ( !aName.isEmpty() )
120 {
121 std::shared_ptr<const SfxFilter> pFilter( SfxFilter::GetFilterByName( aName ) );
122 if ( pFilter && pFilter->CanExport() && pFilter->GetWildcard().Matches( rUrl ) )
123 {
124 if ( !pBestMatch || ( SfxFilterFlags::PREFERED & pFilter->GetFilterFlags() ) )
125 pBestMatch = pFilter;
126 }
127 }
128 }
129
130 return pBestMatch;
131}
132
133std::shared_ptr<const SfxFilter> impl_getExportFilterFromUrl(
134 const OUString& rUrl, const OUString& rFactory)
135{
136 try
137 {
138 const Reference< XComponentContext > xContext( comphelper::getProcessComponentContext() );
139 const Reference< document::XTypeDetection > xTypeDetector(
140 xContext->getServiceManager()->createInstanceWithContext( "com.sun.star.document.TypeDetection", xContext ),
141 UNO_QUERY_THROW );
142 const OUString aTypeName( xTypeDetector->queryTypeByURL( rUrl ) );
143
144 std::shared_ptr<const SfxFilter> pFilter( SfxFilterMatcher( rFactory ).GetFilter4EA( aTypeName, SfxFilterFlags::EXPORT ) );
145 if ( !pFilter )
146 pFilter = impl_lookupExportFilterForUrl( rUrl, rFactory );
147 if ( !pFilter )
148 {
149 OUString aTempName;
150 FileBase::getSystemPathFromFileURL( rUrl, aTempName );
151 OString aSource = OUStringToOString ( aTempName, osl_getThreadTextEncoding() );
152 std::cerr << "Error: no export filter for " << aSource << " found, aborting." << std::endl;
153 }
154
155 return pFilter;
156 }
157 catch ( const Exception& )
158 {
159 return nullptr;
160 }
161}
162
163OUString impl_GuessFilter( const OUString& rUrlOut, const OUString& rDocService )
164{
165 OUString aOutFilter;
166 std::shared_ptr<const SfxFilter> pOutFilter = impl_getExportFilterFromUrl( rUrlOut, rDocService );
167 if (pOutFilter)
168 aOutFilter = pOutFilter->GetFilterName();
169
170 return aOutFilter;
171}
172
174void scriptCat(const Reference< XModel >& xDoc )
175{
176 Reference< XEmbeddedScripts > xScriptAccess( xDoc, UNO_QUERY );
177 if (!xScriptAccess)
178 {
179 std::cout << "No script access\n";
180 return;
181 }
182
183 // ignore xScriptAccess->getDialogLibraries() for now
184 Reference< css::script::XLibraryContainer2 > xLibraries(
185 xScriptAccess->getBasicLibraries() );
186
187 if ( !xLibraries.is() )
188 {
189 std::cout << "No script libraries\n";
190 return;
191 }
192
193 const Sequence< OUString > aLibNames = xLibraries->getElementNames();
194 std::cout << "Libraries: " << aLibNames.getLength() << "\n";
195 for (OUString const & libName : aLibNames)
196 {
197 std::cout << "Library: '" << libName << "' children: ";
198 Reference< XNameContainer > xContainer;
199 try {
200 if (!xLibraries->isLibraryLoaded( libName ))
201 xLibraries->loadLibrary( libName );
202 xContainer = Reference< XNameContainer >(
203 xLibraries->getByName( libName ), UNO_QUERY );
204 }
205 catch (const css::uno::Exception &e)
206 {
207 std::cout << "[" << libName << "] - failed to load library: " << e.Message << "\n";
208 continue;
209 }
210 if( !xContainer.is() )
211 std::cout << "0\n";
212 else
213 {
214 Sequence< OUString > aObjectNames = xContainer->getElementNames();
215
216 std::cout << aObjectNames.getLength() << "\n\n";
217 for ( sal_Int32 j = 0 ; j < aObjectNames.getLength() ; ++j )
218 {
219 const OUString &rObjectName = aObjectNames[j];
220
221 try
222 {
223 Any aCode = xContainer->getByName( rObjectName );
224 OUString aCodeString;
225
226 if (! (aCode >>= aCodeString ) )
227 std::cout << "[" << rObjectName << "] - error fetching code\n";
228 else
229 std::cout << "[" << rObjectName << "]\n"
230 << aCodeString.trim()
231 << "\n[/" << rObjectName << "]\n";
232 }
233 catch (const css::uno::Exception &e)
234 {
235 std::cout << "[" << rObjectName << "] - exception " << e.Message << " fetching code\n";
236 }
237
238 if (j < aObjectNames.getLength() - 1)
239 std::cout << "\n----------------------------------------------------------\n";
240 std::cout << "\n";
241 }
242 }
243 }
244}
245
246// Perform batch print
247void batchPrint( std::u16string_view rPrinterName, const Reference< XPrintable > &xDoc,
248 const INetURLObject &aObj, const OUString &aName )
249{
250 OUString aFilterOut;
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 );
257
258 INetURLObject aOutFilename( aObj );
259 aOutFilename.SetExtension( u"pdf" );
260 FileBase::getFileURLFromSystemPath( aFilterOut, aFilterOut );
261 OUString aOutFile = aFilterOut + "/" + aOutFilename.getName();
262
263 OUString aTempName;
264 FileBase::getSystemPathFromFileURL( aName, aTempName );
265 OString aSource8 = OUStringToOString ( aTempName, osl_getThreadTextEncoding() );
266 FileBase::getSystemPathFromFileURL( aOutFile, aTempName );
267 OString aTargetURL8 = OUStringToOString(aTempName, osl_getThreadTextEncoding() );
268
269 std::cout << "print " << aSource8 << " -> " << aTargetURL8;
270 std::cout << " using " << (aPrinterName.isEmpty() ? "<default_printer>" : OUStringToOString( aPrinterName, osl_getThreadTextEncoding() ));
271 std::cout << std::endl;
272
273 // create the custom printer, if given
274 Sequence < PropertyValue > aPrinterArgs;
275 if( !aPrinterName.isEmpty() )
276 {
277 aPrinterArgs = { comphelper::makePropertyValue("Name", aPrinterName) };
278 xDoc->setPrinter( aPrinterArgs );
279 }
280
281 // print ( also without user interaction )
282 aPrinterArgs = { comphelper::makePropertyValue("FileName", aOutFile),
283 comphelper::makePropertyValue("Wait", true) };
284 xDoc->print( aPrinterArgs );
285}
286
287// Get xDoc module name
288OUString getName(const Reference< XInterface > & xDoc)
289{
290 Reference< XModel > xModel( xDoc, UNO_QUERY );
291 if (!xModel)
292 return OUString();
293 utl::MediaDescriptor aMediaDesc( xModel->getArgs() );
294 OUString aDocService = aMediaDesc.getUnpackedValueOrDefault(utl::MediaDescriptor::PROP_DOCUMENTSERVICE, OUString() );
295 if (aDocService == "com.sun.star.text.TextDocument")
296 return "Writer";
297 else if (aDocService == "com.sun.star.text.GlobalDocument")
298 return "Writer master";
299 else if (aDocService == "com.sun.star.text.WebDocument")
300 return "Writer/Web";
301 else if (aDocService == "com.sun.star.drawing.DrawingDocument")
302 return "Draw";
303 else if (aDocService == "com.sun.star.presentation.PresentationDocument")
304 return "Impress";
305 else if (aDocService == "com.sun.star.sheet.SpreadsheetDocument")
306 return "Calc";
307 else if (aDocService == "com.sun.star.script.BasicIDE")
308 return "Basic";
309 else if (aDocService == "com.sun.star.formula.FormulaProperties")
310 return "Math";
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")
320 return "Database";
321
322 return OUString();
323}
324
325} // anonymous namespace
326
328 : m_nRequestCount(0)
329{
330}
331
332
334{
335}
336
337
338bool DispatchWatcher::executeDispatchRequests( const std::vector<DispatchRequest>& aDispatchRequestsList, bool bNoTerminate )
339{
340 Reference< XDesktop2 > xDesktop = css::frame::Desktop::create( ::comphelper::getProcessComponentContext() );
341
342 std::vector< DispatchHolder > aDispatches;
343 bool bSetInputFilter = false;
344 OUString aForcedInputFilter;
345
346 for (auto const & aDispatchRequest: aDispatchRequestsList)
347 {
348 // Set Input Filter
349 if ( aDispatchRequest.aRequestType == REQUEST_INFILTER )
350 {
351 bSetInputFilter = true;
352 aForcedInputFilter = aDispatchRequest.aURL;
354 continue;
355 }
356
357 // create parameter array
358 std::vector<PropertyValue> aArgs;
359
360 // mark request as user interaction from outside
361 aArgs.emplace_back("Referer", 0, Any(OUString("private:OpenEvent")),
362 PropertyState_DIRECT_VALUE);
363
364 OUString aTarget("_default");
365
366 if ( aDispatchRequest.aRequestType == REQUEST_PRINT ||
367 aDispatchRequest.aRequestType == REQUEST_PRINTTO ||
368 aDispatchRequest.aRequestType == REQUEST_BATCHPRINT ||
369 aDispatchRequest.aRequestType == REQUEST_CONVERSION ||
370 aDispatchRequest.aRequestType == REQUEST_CAT ||
371 aDispatchRequest.aRequestType == REQUEST_SCRIPT_CAT)
372 {
373 // documents opened for printing are opened readonly because they must be opened as a
374 // new document and this document could be open already
375 aArgs.emplace_back("ReadOnly", 0, Any(true), PropertyState_DIRECT_VALUE);
376 // always open a new document for printing, because it must be disposed afterwards
377 aArgs.emplace_back("OpenNewView", 0, Any(true), PropertyState_DIRECT_VALUE);
378 // printing is done in a hidden view
379 aArgs.emplace_back("Hidden", 0, Any(true), PropertyState_DIRECT_VALUE);
380 // load document for printing without user interaction
381 aArgs.emplace_back("Silent", 0, Any(true), PropertyState_DIRECT_VALUE);
382
383 // hidden documents should never be put into open tasks
384 aTarget = "_blank";
385 }
386 else
387 {
388 Reference < XInteractionHandler2 > xInteraction(
389 InteractionHandler::createWithParent(::comphelper::getProcessComponentContext(), nullptr) );
390
391 aArgs.emplace_back("InteractionHandler", 0, Any(xInteraction),
392 PropertyState_DIRECT_VALUE);
393
394 aArgs.emplace_back("MacroExecutionMode", 0,
395 Any(css::document::MacroExecMode::USE_CONFIG),
396 PropertyState_DIRECT_VALUE);
397
398 aArgs.emplace_back("UpdateDocMode", 0,
399 Any(css::document::UpdateDocMode::ACCORDING_TO_CONFIG),
400 PropertyState_DIRECT_VALUE);
401 }
402
403 if ( !aDispatchRequest.aPreselectedFactory.isEmpty() )
404 {
405 aArgs.emplace_back(utl::MediaDescriptor::PROP_DOCUMENTSERVICE, 0,
406 Any(aDispatchRequest.aPreselectedFactory),
407 PropertyState_DIRECT_VALUE);
408 }
409
410 OUString aName( GetURL_Impl( aDispatchRequest.aURL, aDispatchRequest.aCwdUrl ) );
411
412 // load the document ... if they are loadable!
413 // Otherwise try to dispatch it ...
414 Reference < XPrintable > xDoc;
415 if(
416 ( aName.startsWith( ".uno" ) ) ||
417 ( aName.startsWith( "slot:" ) ) ||
418 ( aName.startsWith( "macro:" ) ) ||
419 ( aName.startsWith("vnd.sun.star.script") )
420 )
421 {
422 // Attention: URL must be parsed full. Otherwise some detections on it will fail!
423 // It doesn't matter, if parser isn't available. Because; We try loading of URL then ...
424 URL aURL ;
425 aURL.Complete = aName;
426
427 Reference < XDispatch > xDispatcher ;
428 Reference < XURLTransformer > xParser ( URLTransformer::create(::comphelper::getProcessComponentContext()) );
429
430 if( xParser.is() )
431 xParser->parseStrict( aURL );
432
433 xDispatcher = xDesktop->queryDispatch( aURL, OUString(), 0 );
435 !xDispatcher.is(), "desktop.app",
436 "unsupported dispatch request <" << aName << ">");
437 if( xDispatcher.is() )
438 {
439 // Remember request so we can find it in statusChanged!
441
442 // Use local vector to store dispatcher because we have to fill our request container before
443 // we can dispatch. Otherwise it would be possible that statusChanged is called before we dispatched all requests!!
444 aDispatches.emplace_back( aURL, xDispatcher );
445 }
446 }
447 else if ( aName.startsWith( "service:" ) )
448 {
449 // TODO: the dispatch has to be done for loadComponentFromURL as well.
450 URL aURL ;
451 aURL.Complete = aName;
452
453 Reference < XDispatch > xDispatcher ;
454 Reference < XURLTransformer > xParser ( URLTransformer::create(::comphelper::getProcessComponentContext()) );
455
456 if( xParser.is() )
457 xParser->parseStrict( aURL );
458
459 xDispatcher = xDesktop->queryDispatch( aURL, OUString(), 0 );
460
461 if( xDispatcher.is() )
462 {
463 try
464 {
465 // We have to be listener to catch errors during dispatching URLs.
466 // Otherwise it would be possible to have an office running without an open
467 // window!!
468 Sequence < PropertyValue > aArgs2{ comphelper::makePropertyValue("SynchronMode",
469 true) };
470 Reference < XNotifyingDispatch > xDisp( xDispatcher, UNO_QUERY );
471 if ( xDisp.is() )
472 xDisp->dispatchWithNotification( aURL, aArgs2, this );
473 else
474 xDispatcher->dispatch( aURL, aArgs2 );
475 }
476 catch (const css::uno::Exception&)
477 {
479 "desktop.app",
480 "Desktop::OpenDefault() ignoring Exception while calling XNotifyingDispatch");
481 }
482 }
483 }
484 else
485 {
486 INetURLObject aObj( aName );
487 if ( aObj.GetProtocol() == INetProtocol::PrivSoffice )
488 aTarget = "_default";
489
490 // Set "AsTemplate" argument according to request type
491 if ( aDispatchRequest.aRequestType == REQUEST_FORCENEW ||
492 aDispatchRequest.aRequestType == REQUEST_FORCEOPEN )
493 {
494 aArgs.emplace_back("AsTemplate", 0,
495 Any(aDispatchRequest.aRequestType == REQUEST_FORCENEW),
496 PropertyState_DIRECT_VALUE);
497 }
498
499 // if we are called in viewmode, open document read-only
500 if(aDispatchRequest.aRequestType == REQUEST_VIEW) {
501 aArgs.emplace_back("ReadOnly", 0, Any(true), PropertyState_DIRECT_VALUE);
502 }
503
504 // if we are called with --show set Start in mediadescriptor
505 if(aDispatchRequest.aRequestType == REQUEST_START) {
506 aArgs.emplace_back("StartPresentation", 0, Any(true), PropertyState_DIRECT_VALUE);
507 }
508
509 // Force input filter, if possible
510 if( bSetInputFilter )
511 {
512 sal_Int32 nFilterOptionsIndex = 0;
513 aArgs.emplace_back("FilterName", 0,
514 Any(aForcedInputFilter.getToken(0, ':', nFilterOptionsIndex)),
515 PropertyState_DIRECT_VALUE);
516
517 if (0 < nFilterOptionsIndex)
518 {
519 aArgs.emplace_back("FilterOptions", 0,
520 Any(aForcedInputFilter.copy(nFilterOptionsIndex)),
521 PropertyState_DIRECT_VALUE);
522 }
523 }
524
525 // This is a synchron loading of a component so we don't have to deal with our statusChanged listener mechanism.
526 try
527 {
529 xDesktop, aName, aTarget, comphelper::containerToSequence(aArgs)),
530 UNO_QUERY);
531 }
532 catch (const css::lang::IllegalArgumentException&)
533 {
535 "desktop.app",
536 "Dispatchwatcher IllegalArgumentException while calling loadComponentFromURL");
537 }
538 catch (const css::io::IOException&)
539 {
541 "desktop.app",
542 "Dispatchwatcher IOException while calling loadComponentFromURL");
543 }
544 if ( aDispatchRequest.aRequestType == REQUEST_OPEN ||
545 aDispatchRequest.aRequestType == REQUEST_VIEW ||
546 aDispatchRequest.aRequestType == REQUEST_START ||
547 aDispatchRequest.aRequestType == REQUEST_FORCEOPEN ||
548 aDispatchRequest.aRequestType == REQUEST_FORCENEW )
549 {
550 // request is completed
552 }
553 else if ( aDispatchRequest.aRequestType == REQUEST_PRINT ||
554 aDispatchRequest.aRequestType == REQUEST_PRINTTO ||
555 aDispatchRequest.aRequestType == REQUEST_BATCHPRINT ||
556 aDispatchRequest.aRequestType == REQUEST_CONVERSION ||
557 aDispatchRequest.aRequestType == REQUEST_CAT ||
558 aDispatchRequest.aRequestType == REQUEST_SCRIPT_CAT )
559 {
560 if ( xDoc.is() )
561 {
562 // Do we need to save the document in a different format?
563 if ( aDispatchRequest.aRequestType == REQUEST_CONVERSION ||
564 aDispatchRequest.aRequestType == REQUEST_CAT )
565 {
566// FIXME: factor out into a method ...
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 )
574 nFilterIndex = -1;
575
576 OUString aFilterOut;
577 OUString aImgOut;
578 OUString aFilter;
579 OUString aFilterExt;
580 bool bGuess = false;
581
582 if( nFilterIndex >= 0 )
583 {
584 aFilter = aParam.copy( nFilterIndex+1, nPathIndex-nFilterIndex-1 );
585 aFilterExt = aParam.copy( 0, nFilterIndex );
586 }
587 else
588 {
589 // Guess
590 bGuess = true;
591 aFilterExt = aParam.copy( 0, nPathIndex );
592 }
593
594 if( nImgFilterIndex >= 0 )
595 {
596 aImgOut = aParam.copy( nImgFilterIndex+1 );
597 aFilterOut = aParam.copy( nPathIndex+1, nImgFilterIndex-nPathIndex-1 );
598 }
599 else
600 aFilterOut = aParam.copy( nPathIndex+1 );
601
602 FileBase::getFileURLFromSystemPath( aFilterOut, aFilterOut );
603 INetURLObject aOutFilename(aFilterOut);
604 aOutFilename.Append(aObj.getName(INetURLObject::LAST_SEGMENT, true,
606 aOutFilename.SetExtension(aFilterExt);
607 OUString aOutFile
609
610 std::unique_ptr<utl::TempFileNamed> fileForCat;
611 if( aDispatchRequest.aRequestType == REQUEST_CAT )
612 {
613 fileForCat = std::make_unique<utl::TempFileNamed>();
614 if (fileForCat->IsValid())
615 fileForCat->EnableKillingFile();
616 else
617 std::cerr << "Error: Cannot create temporary file..." << std::endl ;
618 aOutFile = fileForCat->GetURL();
619 }
620
621 if ( bGuess )
622 {
623 OUString aDocService;
624 Reference< XModel > xModel( xDoc, UNO_QUERY );
625 if ( xModel.is() )
626 {
627 utl::MediaDescriptor aMediaDesc( xModel->getArgs() );
628 aDocService = aMediaDesc.getUnpackedValueOrDefault(utl::MediaDescriptor::PROP_DOCUMENTSERVICE, OUString() );
629 }
630 aFilter = impl_GuessFilter( aOutFile, aDocService );
631 }
632
633 bool bMultiFileTarget = false;
634
635 if (aFilter.isEmpty())
636 {
637 std::cerr << "Error: no export filter" << std::endl;
638 }
639 else
640 {
641 sal_Int32 nFilterOptionsIndex = aFilter.indexOf(':');
642 sal_Int32 nProps = ( 0 < nFilterOptionsIndex ) ? 4 : 3;
643
644 if ( !aImgOut.isEmpty() )
645 nProps +=1;
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;
652
653 pconversionProperties[2].Name = "FilterName";
654 if( 0 < nFilterOptionsIndex )
655 {
656 OUString sFilterName = aFilter.copy(0, nFilterOptionsIndex);
657 OUString sFilterOptions = aFilter.copy(nFilterOptionsIndex + 1);
658
659 if (sFilterName == "Text - txt - csv (StarCalc)")
660 {
661 sal_Int32 nIdx(0);
662 // If the 11th token is '-1' then we export a file
663 // per sheet where the file name is based on the suggested
664 // output filename concatenated with the sheet name, so adjust
665 // the output and overwrite messages
666 // If the 11th token is not present or numeric 0 then the
667 // default sheet is exported with the output filename. If it
668 // is numeric >0 then that sheet (1-based) with the output
669 // filename concatenated with the sheet name. So even if
670 // that is a single file, the multi file target mechanism is
671 // used.
672 const OUString aTok(sFilterOptions.getToken(11, ',', nIdx));
673 // Actual validity is checked in Calc, here just check for
674 // presence of numeric value at start.
675 bMultiFileTarget = (!aTok.isEmpty() && aTok.toInt32() != 0);
676 }
677
678 pconversionProperties[2].Value <<= sFilterName;
679
680 pconversionProperties[3].Name = "FilterOptions";
681 pconversionProperties[3].Value <<= sFilterOptions;
682 }
683 else
684 {
685 pconversionProperties[2].Value <<= aFilter;
686 }
687
688 if ( !aImgOut.isEmpty() )
689 {
690 assert(conversionProperties[nProps-1].Name.isEmpty());
691 pconversionProperties[nProps-1].Name = "ImageFilter";
692 pconversionProperties[nProps-1].Value <<= aImgOut;
693 }
694
695 OUString aTempName;
696 FileBase::getSystemPathFromFileURL(aName, aTempName);
697 OString aSource8 = OUStringToOString(aTempName, osl_getThreadTextEncoding());
698 FileBase::getSystemPathFromFileURL(aOutFile, aTempName);
699 OString aTargetURL8 = OUStringToOString(aTempName, osl_getThreadTextEncoding());
700 if (aDispatchRequest.aRequestType != REQUEST_CAT)
701 {
702 OUString name=getName(xDoc);
703 std::cout << "convert " << aSource8;
704 if (!name.isEmpty())
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;
709 if (!bMultiFileTarget && FStatHelper::IsDocument(aOutFile))
710 std::cout << "Overwriting: " << OUStringToOString(aTempName, osl_getThreadTextEncoding()) << std::endl ;
711 }
712 try
713 {
714 xStorable->storeToURL(aOutFile, conversionProperties);
715 }
716 catch (const Exception& rException)
717 {
718 std::cerr << "Error: Please verify input parameters...";
719 if (!rException.Message.isEmpty())
720 std::cerr << " (" << rException.Message << ")";
721 std::cerr << std::endl;
722 }
723
724 if (fileForCat && fileForCat->IsValid())
725 {
726 SvStream* aStream = fileForCat->GetStream(StreamMode::STD_READ);
727 while (aStream->good())
728 {
729 OString aStr;
730 aStream->ReadLine(aStr, SAL_MAX_INT32);
731 for (sal_Int32 i = 0; i < aStr.getLength(); ++i)
732 {
733 std::cout << aStr[i];
734 }
735 std::cout << std::endl;
736 }
737 }
738 }
739 }
740 }
741 else if ( aDispatchRequest.aRequestType == REQUEST_SCRIPT_CAT )
742 {
743 Reference< XModel > xModel( xDoc, UNO_QUERY );
744 if( xModel.is() )
745 scriptCat( xModel );
746 }
747 else if ( aDispatchRequest.aRequestType == REQUEST_BATCHPRINT )
748 {
749 batchPrint( aDispatchRequest.aPrinterName, xDoc, aObj, aName );
750 }
751 else
752 {
753 if ( aDispatchRequest.aRequestType == REQUEST_PRINTTO )
754 {
755 // create the printer
756 Sequence < PropertyValue > aPrinterArgs{ comphelper::makePropertyValue(
757 "Name", aDispatchRequest.aPrinterName) };
758 xDoc->setPrinter( aPrinterArgs );
759 }
760
761 // print ( also without user interaction )
762 Sequence < PropertyValue > aPrinterArgs{ comphelper::makePropertyValue("Wait",
763 true) };
764 xDoc->print( aPrinterArgs );
765 }
766 }
767 else
768 {
769 std::cerr << "Error: source file could not be loaded" << std::endl;
770 }
771
772 // remove the document
773 try
774 {
775 Reference < XCloseable > xClose( xDoc, UNO_QUERY );
776 if ( xClose.is() )
777 xClose->close( true );
778 else
779 {
780 Reference < XComponent > xComp( xDoc, UNO_QUERY );
781 if ( xComp.is() )
782 xComp->dispose();
783 }
784 }
785 catch (const css::util::CloseVetoException&)
786 {
787 }
788
789 // request is completed
791 }
792 }
793 }
794
795 if ( !aDispatches.empty() )
796 {
797 // Execute all asynchronous dispatches now after we placed them into our request container!
798 Sequence < PropertyValue > aArgs{
799 comphelper::makePropertyValue("Referer", OUString("private:OpenEvent")),
800 comphelper::makePropertyValue("SynchronMode", true)
801 };
802
803 for (const DispatchHolder & aDispatche : aDispatches)
804 {
805 Reference< XDispatch > xDispatch = aDispatche.xDispatch;
806 Reference < XNotifyingDispatch > xDisp( xDispatch, UNO_QUERY );
807 if ( xDisp.is() )
808 xDisp->dispatchWithNotification( aDispatche.aURL, aArgs, this );
809 else
810 {
812 xDispatch->dispatch( aDispatche.aURL, aArgs );
813 }
814 }
815 }
816
817 bool bEmpty = (m_nRequestCount == 0);
818
819 // No more asynchronous requests?
820 // The requests are removed from the request container after they called back to this
821 // implementation via statusChanged!!
822 if ( bEmpty && !bNoTerminate /*m_aRequestContainer.empty()*/ )
823 {
824 // We have to check if we have an open task otherwise we have to shutdown the office.
825 Reference< XElementAccess > xList = xDesktop->getFrames();
826
827 if ( !xList->hasElements() )
828 {
829 // We don't have any task open so we have to shutdown ourself!!
830 return xDesktop->terminate();
831 }
832 }
833
834 return false;
835}
836
837
838void SAL_CALL DispatchWatcher::disposing( const css::lang::EventObject& )
839{
840}
841
842
843void SAL_CALL DispatchWatcher::dispatchFinished( const DispatchResultEvent& )
844{
845 int nCount = --m_nRequestCount;
848 {
849 // We have to check if we have an open task otherwise we have to shutdown the office.
850 Reference< XDesktop2 > xDesktop = css::frame::Desktop::create( ::comphelper::getProcessComponentContext() );
851 Reference< XElementAccess > xList = xDesktop->getFrames();
852
853 if ( !xList->hasElements() )
854 {
855 // We don't have any task open so we have to shutdown ourself!!
856 xDesktop->terminate();
857 }
858 }
859}
860
861} // namespace desktop
862
863/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
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 good() const
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 constexpr OUStringLiteral PROP_DOCUMENTSERVICE
int nCount
#define TOOLS_WARN_EXCEPTION(area, stream)
Reference< XDispatch > xDispatch
URL aURL
#define SFX_FILTER_NOTINSTALLED
const char * name
static uno::Reference< css::uno::XComponentContext > xContext
Definition: init.cxx:2642
OUString aName
#define SAL_WARN_IF(condition, area, stream)
aStr
SVL_DLLPUBLIC bool IsDocument(const OUString &rURL)
@ Exception
css::uno::Sequence< DstElementType > containerToSequence(const SrcType &i_Container)
Reference< XComponentContext > getProcessComponentContext()
css::beans::PropertyValue makePropertyValue(const OUString &rName, T &&rValue)
Definition: app.cxx:167
OUString GetURL_Impl(const OUString &rName, std::optional< OUString > const &cwdUrl)
Definition: app.cxx:2189
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)
int i
OString OUStringToOString(std::u16string_view str, ConnectionSettings const *settings)
Reference< XModel > xModel
OUString Name
#define SAL_MAX_INT32