1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3 * This file is part of the LibreOffice project.
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/.
9 * This file incorporates work covered by the following license notice:
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 .
20 #include <config_features.h>
22 #if HAVE_FEATURE_MACOSX_SANDBOX
24 #include <Foundation/Foundation.h>
28 #include "cmdlineargs.hxx"
29 #include <osl/thread.hxx>
30 #include <tools/stream.hxx>
31 #include <rtl/ustring.hxx>
32 #include <rtl/process.h>
33 #include <comphelper/lok.hxx>
34 #include <comphelper/processfactory.hxx>
35 #include <com/sun/star/uri/ExternalUriReferenceTranslator.hpp>
36 #include <unotools/bootstrap.hxx>
38 #include <rtl/strbuf.hxx>
39 #include <osl/file.hxx>
40 #include <sal/log.hxx>
42 using namespace com::sun::star::lang
;
43 using namespace com::sun::star::uri
;
44 using namespace com::sun::star::uno
;
51 OUString
translateExternalUris(OUString
const & input
) {
53 css::uri::ExternalUriReferenceTranslator::create(
54 comphelper::getProcessComponentContext())->
55 translateToInternal(input
));
56 return t
.isEmpty() ? input
: t
;
59 std::vector
< OUString
> translateExternalUris(
60 std::vector
< OUString
> const & input
)
62 std::vector
< OUString
> t
;
63 t
.reserve(input
.size());
64 for (auto const& elem
: input
)
66 t
.push_back(translateExternalUris(elem
));
71 class ExtCommandLineSupplier
: public CommandLineArgs::Supplier
{
73 explicit ExtCommandLineSupplier():
75 comphelper::LibreOfficeKit::isActive()
76 ? 0 : rtl_getAppCommandArgCount()),
80 if (utl::Bootstrap::getProcessWorkingDir(url
)) {
85 virtual std::optional
< OUString
> getCwdUrl() override
{ return m_cwdUrl
; }
87 virtual bool next(OUString
* argument
) override
{
88 OSL_ASSERT(argument
!= nullptr);
89 if (m_index
< m_count
) {
90 rtl_getAppCommandArg(m_index
++, &argument
->pData
);
98 std::optional
< OUString
> m_cwdUrl
;
103 enum class CommandLineEvent
{
104 Open
, Print
, View
, Start
, PrintTo
,
105 ForceOpen
, ForceNew
, Conversion
, BatchPrint
108 // Office URI Schemes: see https://msdn.microsoft.com/en-us/library/dn906146
109 // This functions checks if the arg is an Office URI.
110 // If applicable, it updates arg to inner URI.
111 // If no event argument is explicitly set in command line,
112 // then it returns updated command line event,
113 // according to Office URI command.
114 CommandLineEvent
CheckOfficeURI(/* in,out */ OUString
& arg
, CommandLineEvent curEvt
)
116 // 1. Strip the scheme name
118 bool isOfficeURI
= ( arg
.startsWithIgnoreAsciiCase("vnd.libreoffice.command:", &rest1
) // Proposed extended schema
119 || arg
.startsWithIgnoreAsciiCase("ms-word:", &rest1
)
120 || arg
.startsWithIgnoreAsciiCase("ms-powerpoint:", &rest1
)
121 || arg
.startsWithIgnoreAsciiCase("ms-excel:", &rest1
)
122 || arg
.startsWithIgnoreAsciiCase("ms-visio:", &rest1
)
123 || arg
.startsWithIgnoreAsciiCase("ms-access:", &rest1
));
128 tools::Long nURIlen
= -1;
130 // URL might be encoded
131 OUString decoded_rest
= rest1
.replaceAll("%7C", "|").replaceAll("%7c", "|");
133 // 2. Discriminate by command name (incl. 1st command argument descriptor)
134 // Extract URI: everything up to possible next argument
135 if (decoded_rest
.startsWith("ofv|u|", &rest2
))
137 // Open for view - override only in default mode
138 if (curEvt
== CommandLineEvent::Open
)
139 curEvt
= CommandLineEvent::View
;
140 nURIlen
= rest2
.indexOf("|");
142 else if (decoded_rest
.startsWith("ofe|u|", &rest2
))
144 // Open for editing - override only in default mode
145 if (curEvt
== CommandLineEvent::Open
)
146 curEvt
= CommandLineEvent::ForceOpen
;
147 nURIlen
= rest2
.indexOf("|");
149 else if (decoded_rest
.startsWith("nft|u|", &rest2
))
151 // New from template - override only in default mode
152 if (curEvt
== CommandLineEvent::Open
)
153 curEvt
= CommandLineEvent::ForceNew
;
154 nURIlen
= rest2
.indexOf("|");
155 // TODO: process optional second argument (default save-to location)
156 // For now, we just ignore it
160 // Abbreviated scheme: <scheme-name>:URI
162 // override only in default mode
163 if (curEvt
== CommandLineEvent::Open
)
164 curEvt
= CommandLineEvent::View
;
168 nURIlen
= rest2
.getLength();
169 arg
= rest2
.copy(0, nURIlen
);
173 // Skip single newline (be it *NIX LF, MacOS CR, of Win CRLF)
174 // Changes the offset, and returns true if moved
175 bool SkipNewline(const char* & pStr
)
177 if ((*pStr
!= '\r') && (*pStr
!= '\n'))
186 // Web query: http://support.microsoft.com/kb/157482
187 CommandLineEvent
CheckWebQuery(/* in,out */ OUString
& arg
, CommandLineEvent curEvt
)
189 // Only handle files with extension .iqy
190 if (!arg
.endsWithIgnoreAsciiCase(".iqy"))
193 static osl::Mutex aMutex
;
194 osl::MutexGuard
aGuard(aMutex
);
199 // Cannot use translateExternalUris yet, because process service factory is not yet available
200 if (osl::FileBase::getFileURLFromSystemPath(arg
, sFileURL
) != osl::FileBase::RC::E_None
)
202 SvFileStream
stream(sFileURL
, StreamMode::READ
);
204 const sal_Int32 nBufLen
= 32000;
205 char sBuffer
[nBufLen
];
206 size_t nRead
= stream
.ReadBytes(sBuffer
, nBufLen
);
207 if (nRead
< 8) // WEB\n1\n...
210 const char* pPos
= sBuffer
;
211 if (strncmp(pPos
, "WEB", 3) != 0)
214 if (!SkipNewline(pPos
))
219 if (!SkipNewline(pPos
))
222 OStringBuffer
aResult(static_cast<unsigned int>(nRead
));
225 const char* pPos1
= pPos
;
226 const char* pEnd
= sBuffer
+ nRead
;
227 while ((pPos1
< pEnd
) && (*pPos1
!= '\r') && (*pPos1
!= '\n'))
229 aResult
.append(pPos
, pPos1
- pPos
);
230 if (pPos1
< pEnd
) // newline
233 } while ((nRead
= stream
.ReadBytes(sBuffer
, nBufLen
)) > 0);
237 arg
= OStringToOUString(aResult
.makeStringAndClear(), osl_getThreadTextEncoding());
238 return CommandLineEvent::ForceNew
;
242 SAL_WARN("desktop.app", "An error processing Web Query file: " << arg
);
250 CommandLineArgs::Supplier::Exception::Exception() {}
252 CommandLineArgs::Supplier::Exception::Exception(Exception
const &) {}
254 CommandLineArgs::Supplier::Exception::~Exception() {}
256 CommandLineArgs::Supplier::Exception
&
257 CommandLineArgs::Supplier::Exception::operator =(Exception
const &)
260 CommandLineArgs::Supplier::~Supplier() {}
262 // initialize class with command line parameters from process environment
263 CommandLineArgs::CommandLineArgs()
266 ExtCommandLineSupplier s
;
267 ParseCommandLine_Impl( s
);
270 CommandLineArgs::CommandLineArgs( Supplier
& supplier
)
273 ParseCommandLine_Impl( supplier
);
276 void CommandLineArgs::ParseCommandLine_Impl( Supplier
& supplier
)
278 m_cwdUrl
= supplier
.getCwdUrl();
279 CommandLineEvent eCurrentEvent
= CommandLineEvent::Open
;
284 if ( !supplier
.next( &aArg
) )
289 if ( !aArg
.isEmpty() )
293 OUString oDeprecatedArg
;
294 if (!aArg
.startsWith("--", &oArg
) && aArg
.startsWith("-", &oArg
)
295 && aArg
.getLength() > 2) // -h, -?, -n, -o, -p are still valid
297 oDeprecatedArg
= aArg
; // save here, since aArg can change later
301 if ( oArg
== "minimized" )
305 else if ( oArg
== "invisible" )
309 else if ( oArg
== "norestore" )
313 else if ( oArg
== "nodefault" )
317 else if ( oArg
== "headless" )
321 else if ( oArg
== "eventtesting" )
323 m_eventtesting
= true;
325 else if ( oArg
== "safe-mode" )
329 else if ( oArg
== "cat" )
332 m_conversionparams
= "txt:Text";
333 eCurrentEvent
= CommandLineEvent::Conversion
;
336 else if ( oArg
== "script-cat" )
339 eCurrentEvent
= CommandLineEvent::Conversion
;
342 else if ( oArg
== "quickstart" )
344 #if defined(ENABLE_QUICKSTART_APPLET)
347 m_noquickstart
= false;
349 else if ( oArg
== "quickstart=no" )
351 m_noquickstart
= true;
352 m_quickstart
= false;
354 else if ( oArg
== "terminate_after_init" )
356 m_terminateafterinit
= true;
358 else if ( oArg
== "nofirststartwizard" )
360 // Do nothing, accept only for backward compatibility
362 else if ( oArg
== "nologo" )
366 #if HAVE_FEATURE_MULTIUSER_ENVIRONMENT
367 else if ( oArg
== "nolockcheck" )
369 m_nolockcheck
= true;
372 else if ( oArg
== "help" || aArg
== "-h" || aArg
== "-?" )
376 else if ( oArg
== "helpwriter" )
380 else if ( oArg
== "helpcalc" )
384 else if ( oArg
== "helpdraw" )
388 else if ( oArg
== "helpimpress" )
390 m_helpimpress
= true;
392 else if ( oArg
== "helpbase" )
396 else if ( oArg
== "helpbasic" )
400 else if ( oArg
== "helpmath" )
404 else if ( oArg
== "protector" )
406 // Not relevant for us here, but can be used in unit tests.
407 // Usually unit tests would not end up here, but e.g. the
408 // LOK Tiled Rendering tests end up running a full soffice
409 // process, and we can't bail on the use of --protector.
411 // We specifically need to consume the following 2 arguments
413 if ((!supplier
.next(&aArg
) || !supplier
.next(&aArg
)) && m_unknown
.isEmpty())
414 m_unknown
= "--protector must be followed by two arguments";
416 else if ( oArg
== "version" )
420 else if ( oArg
.startsWith("splash-pipe=") )
425 /* #i84053# ignore -psn on Mac
426 Platform dependent #ifdef here is ugly, however this is currently
427 the only platform dependent parameter. Should more appear
428 we should find a better solution
430 else if ( aArg
.startsWith("-psn") )
432 oDeprecatedArg
.clear();
435 #if HAVE_FEATURE_MACOSX_SANDBOX
436 else if ( oArg
== "nstemporarydirectory" )
438 printf("%s\n", [NSTemporaryDirectory() UTF8String
]);
443 /* fdo#57203 ignore -Embedding on Windows
444 when LibreOffice is launched by COM+
446 else if ( oArg
== "Embedding" )
448 oDeprecatedArg
.clear();
451 else if ( oArg
.startsWith("infilter=", &rest
))
453 m_infilter
.push_back(rest
);
455 else if ( oArg
.startsWith("accept=", &rest
))
457 m_accept
.push_back(rest
);
459 else if ( oArg
.startsWith("unaccept=", &rest
))
461 m_unaccept
.push_back(rest
);
463 else if ( oArg
.startsWith("language=", &rest
))
467 else if ( oArg
.startsWith("pidfile=", &rest
))
471 else if ( oArg
== "writer" )
474 m_bDocumentArgs
= true;
476 else if ( oArg
== "calc" )
479 m_bDocumentArgs
= true;
481 else if ( oArg
== "draw" )
484 m_bDocumentArgs
= true;
486 else if ( oArg
== "impress" )
489 m_bDocumentArgs
= true;
491 else if ( oArg
== "base" )
494 m_bDocumentArgs
= true;
496 else if ( oArg
== "global" )
499 m_bDocumentArgs
= true;
501 else if ( oArg
== "math" )
504 m_bDocumentArgs
= true;
506 else if ( oArg
== "web" )
509 m_bDocumentArgs
= true;
511 else if ( aArg
== "-n" )
513 // force new documents based on the following documents
514 eCurrentEvent
= CommandLineEvent::ForceNew
;
516 else if ( aArg
== "-o" )
518 // force open documents regardless if they are templates or not
519 eCurrentEvent
= CommandLineEvent::ForceOpen
;
521 else if ( oArg
== "pt" )
523 // Print to special printer
524 eCurrentEvent
= CommandLineEvent::PrintTo
;
525 // first argument after "-pt" must be the printer name
526 if (supplier
.next(&aArg
))
527 m_printername
= aArg
;
528 else if (m_unknown
.isEmpty())
529 m_unknown
= "--pt must be followed by printername";
531 else if ( aArg
== "-p" )
533 // Print to default printer
534 eCurrentEvent
= CommandLineEvent::Print
;
536 else if ( oArg
== "view")
539 eCurrentEvent
= CommandLineEvent::View
;
541 else if ( oArg
== "show" )
544 eCurrentEvent
= CommandLineEvent::Start
;
546 else if ( oArg
== "display" )
548 // The command line argument following --display should
549 // always be treated as the argument of --display.
550 // --display and its argument are handled "out of line"
551 // in Unix-only desktop/unx/source/splashx.c and vcl/unx/*,
552 // and just ignored here
553 (void)supplier
.next(&aArg
);
555 else if ( oArg
== "convert-to" )
557 eCurrentEvent
= CommandLineEvent::Conversion
;
558 // first argument must be the params
559 if (supplier
.next(&aArg
))
561 m_conversionparams
= aArg
;
562 // It doesn't make sense to use convert-to without headless.
565 else if (m_unknown
.isEmpty())
566 m_unknown
= "--convert-to must be followed by output_file_extension[:output_filter_name]";
568 else if ( oArg
== "print-to-file" )
570 eCurrentEvent
= CommandLineEvent::BatchPrint
;
572 else if ( oArg
== "printer-name" )
574 if (eCurrentEvent
== CommandLineEvent::BatchPrint
)
576 // first argument is the printer name
577 if (supplier
.next(&aArg
))
578 m_printername
= aArg
;
579 else if (m_unknown
.isEmpty())
580 m_unknown
= "--printer-name must be followed by printername";
582 else if (m_unknown
.isEmpty())
584 m_unknown
= "--printer-name must directly follow --print-to-file";
587 else if ( oArg
== "outdir" )
589 if (eCurrentEvent
== CommandLineEvent::Conversion
||
590 eCurrentEvent
== CommandLineEvent::BatchPrint
)
592 if (supplier
.next(&aArg
))
593 m_conversionout
= aArg
;
594 else if (m_unknown
.isEmpty())
595 m_unknown
= "--outdir must be followed by output directory path";
597 else if (m_unknown
.isEmpty())
599 m_unknown
= "--outdir must directly follow either output filter specification of --convert-to, or --print-to-file or its printer specification";
602 else if ( eCurrentEvent
== CommandLineEvent::Conversion
603 && oArg
== "convert-images-to" )
605 if (supplier
.next(&aArg
))
606 m_convertimages
= aArg
;
607 else if (m_unknown
.isEmpty())
608 m_unknown
= "--convert-images-to must be followed by an image type";
610 else if ( aArg
.startsWith("-") )
612 // because it's impossible to filter these options that
613 // are handled in the soffice shell script with the
614 // primitive tools that /bin/sh offers, ignore them here
618 oArg
!= "backtrace" &&
620 oArg
!= "valgrind" &&
621 // for X Session Management, handled in
622 // vcl/unx/generic/app/sm.cxx:
623 oArg
!= "session=" &&
625 //ignore additional legacy options that don't do anything anymore
626 oArg
!= "nocrashreport" &&
631 oDeprecatedArg
.clear();
635 // handle this argument as a filename
637 // First check if this is an Office URI
638 // This will possibly adjust event for this argument
639 // and put real URI to aArg
640 CommandLineEvent eThisEvent
= CheckOfficeURI(aArg
, eCurrentEvent
);
642 // Now check if this is a Web Query file
643 eThisEvent
= CheckWebQuery(aArg
, eThisEvent
);
647 case CommandLineEvent::Open
:
648 m_openlist
.push_back(aArg
);
649 m_bDocumentArgs
= true;
651 case CommandLineEvent::View
:
652 m_viewlist
.push_back(aArg
);
653 m_bDocumentArgs
= true;
655 case CommandLineEvent::Start
:
656 m_startlist
.push_back(aArg
);
657 m_bDocumentArgs
= true;
659 case CommandLineEvent::Print
:
660 m_printlist
.push_back(aArg
);
661 m_bDocumentArgs
= true;
663 case CommandLineEvent::PrintTo
:
664 m_printtolist
.push_back(aArg
);
665 m_bDocumentArgs
= true;
667 case CommandLineEvent::ForceNew
:
668 m_forcenewlist
.push_back(aArg
);
669 m_bDocumentArgs
= true;
671 case CommandLineEvent::ForceOpen
:
672 m_forceopenlist
.push_back(aArg
);
673 m_bDocumentArgs
= true;
675 case CommandLineEvent::Conversion
:
676 case CommandLineEvent::BatchPrint
:
677 m_conversionlist
.push_back(aArg
);
682 if (!oDeprecatedArg
.isEmpty())
684 OString
sArg(OUStringToOString(oDeprecatedArg
, osl_getThreadTextEncoding()));
685 fprintf(stderr
, "Warning: %s is deprecated. Use -%s instead.\n", sArg
.getStr(), sArg
.getStr());
691 void CommandLineArgs::InitParamValues()
702 m_eventtesting
= false;
703 m_quickstart
= false;
704 m_noquickstart
= false;
705 m_terminateafterinit
= false;
707 m_nolockcheck
= false;
718 m_helpwriter
= false;
723 m_helpimpress
= false;
726 m_splashpipe
= false;
728 m_bDocumentArgs
= false;
734 bool CommandLineArgs::HasModuleParam() const
736 return m_writer
|| m_calc
|| m_draw
|| m_impress
|| m_global
|| m_math
740 std::vector
< OUString
> CommandLineArgs::GetOpenList() const
742 return translateExternalUris(m_openlist
);
745 std::vector
< OUString
> CommandLineArgs::GetViewList() const
747 return translateExternalUris(m_viewlist
);
750 std::vector
< OUString
> CommandLineArgs::GetStartList() const
752 return translateExternalUris(m_startlist
);
755 std::vector
< OUString
> CommandLineArgs::GetForceOpenList() const
757 return translateExternalUris(m_forceopenlist
);
760 std::vector
< OUString
> CommandLineArgs::GetForceNewList() const
762 return translateExternalUris(m_forcenewlist
);
765 std::vector
< OUString
> CommandLineArgs::GetPrintList() const
767 return translateExternalUris(m_printlist
);
770 std::vector
< OUString
> CommandLineArgs::GetPrintToList() const
772 return translateExternalUris(m_printtolist
);
775 std::vector
< OUString
> CommandLineArgs::GetConversionList() const
777 return translateExternalUris(m_conversionlist
);
780 OUString
CommandLineArgs::GetConversionOut() const
782 return translateExternalUris(m_conversionout
);
785 } // namespace desktop
787 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */