Coverage Report

Created: 2026-03-31 11:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libreoffice/include/unotools/tempfile.hxx
Line
Count
Source
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
#pragma once
20
21
#include <unotools/unotoolsdllapi.h>
22
#include <com/sun/star/io/XInputStream.hpp>
23
#include <com/sun/star/io/XOutputStream.hpp>
24
#include <com/sun/star/io/XStream.hpp>
25
#include <com/sun/star/io/XSeekable.hpp>
26
#include <com/sun/star/io/XTruncate.hpp>
27
#include <comphelper/bytereader.hxx>
28
#include <cppuhelper/implbase.hxx>
29
#include <memory>
30
#include <mutex>
31
#include <optional>
32
33
class SvFileStream;
34
class SvStream;
35
enum class StreamMode;
36
37
namespace utl
38
{
39
40
41
/**
42
  This is the "fast" temp file. Different OSes have different ideas how this should work, so this
43
  class presents an interface that is fast across Windows and Unix (which differ in how they want
44
  temp files to work).
45
  The key point is that such a temporary file is only a readable/writeable stream, and does not have
46
  a filename, or a location in the filesystem hierarchy.
47
  If you need a name or a URL, you should use TempFileNamed, which is slower, but creates an actual
48
  file in the filesystem.
49
*/
50
class UNOTOOLS_DLLPUBLIC TempFileFast
51
{
52
    std::unique_ptr<SvFileStream> mxStream;
53
54
public:
55
                    TempFileFast();
56
                    TempFileFast(TempFileFast && other) noexcept;
57
                    ~TempFileFast();
58
59
                    /**
60
                    Returns a stream to the tempfiles data; the stream is owned by the tempfile object, so you have to keep this
61
                    alive as long as you want to use the stream.
62
                    */
63
    SvStream*       GetStream( StreamMode eMode );
64
65
                    /**
66
                    Close and destroy the owned stream object if any.
67
                    */
68
    void            CloseStream();
69
70
};
71
72
/**
73
Only create a "physical" file name for a temporary file that would be valid at that moment.
74
Should only be used for 3rd party code with a file name interface that wants to create the file by itself.
75
If you want to convert file name into a URL, always use class LocalFileHelper, but never use any
76
conversion functions of osl.
77
*/
78
UNOTOOLS_DLLPUBLIC OUString CreateTempName();
79
80
UNOTOOLS_DLLPUBLIC OUString CreateTempURL( const OUString* pParent=nullptr, bool bDirectory=false );
81
82
/**
83
Same as above; additionally the name starts with some given characters followed by a counter ( example:
84
rLeadingChars="abc" means "abc0","abc1" and so on, depending on existing files in the folder ).
85
The extension string may be f.e. ".txt" or "", if no extension string is given, ".tmp" is used
86
    @param  _bStartWithZero If set to false names will be generated like "abc","abc0","abc1"
87
    @param  bCreateParentDirs If rLeadingChars contains a slash, this will create the required
88
            parent directories.
89
*/
90
UNOTOOLS_DLLPUBLIC OUString CreateTempURL( std::u16string_view rLeadingChars, bool _bStartWithZero=true, std::u16string_view pExtension={},
91
                          const OUString* pParent=nullptr, bool bCreateParentDirs=false );
92
93
/**
94
The TempNameBaseDirectory is a subfolder in the folder that is passed as a "physical" file name in the
95
SetTempNameBaseDirectory method.
96
This subfolder will be used if a TempFile or TempName is created without a parent name or a parent name
97
that does not belong to the local file system.
98
The caller of the SetTempNameBase is responsible for deleting this folder and all temporary files in it.
99
The return value of both methods is the complete "physical" name of the tempname base folder.
100
It is not a URL because all URLs must be "UCB compatible", so there may be no suitable URL at all.
101
*/
102
UNOTOOLS_DLLPUBLIC OUString SetTempNameBaseDirectory( const OUString &rBaseName );
103
104
// Return the URL of the temp directory (the one set with SetTempNameBaseDirectory or the
105
// default tempfile folder):
106
UNOTOOLS_DLLPUBLIC OUString GetTempNameBaseDirectory();
107
108
/**
109
    The class TempFile gives access to temporary files in the local file system. Sometimes they are needed because a 3rd party
110
    code has a file name based interface, or some file access has to be done locally without transferring tons of bytes to or
111
    from a remote system.
112
    Creating a UCB content on a TempFile is only possible if a UCP for the local file system is present.
113
    TempFiles can always be accessed by SvFileStreams or Sot/SvStorages using the "physical" file name ( not the URL, because
114
    this may be a non-file URL, see below ), but if a UCB content can be created, it is also possible to take the URL and use
115
    the UCB helper classes for streams. For convenience use UcbStreamHelper.
116
    A Tempfile always has a "physical" file name ( a file name in the local computers host notation ) but it has a
117
    "UCB compatible" URL only if a UCP for the local file system exists. This URL may have its own URL scheme
118
    ( not necessarily "file://" ! ). The TempFile class methods take this into account, but other simple conversions like
119
    the osl functions do not.
120
    So it is a potential error to convert between the filename and the URL of a TempFile object using functions or methods
121
    outside this class.
122
*/
123
class UNOTOOLS_DLLPUBLIC TempFileNamed
124
{
125
    OUString    aName;
126
    std::unique_ptr<SvStream>
127
                pStream;
128
    bool        bIsDirectory;
129
    bool        bKillingFileEnabled;
130
131
public:
132
                    /**
133
                    Create a temporary file or directory, in the default tempfile folder or if possible in a given folder.
134
                    This given folder ( the "parent" parameter ( if not NULL ) ) must be a "UCB compatible" URL.
135
                    The temporary object is created in the local file system, even if there is no UCB that can access it.
136
                    If the given folder is part of the local file system, the TempFile is created in this folder.
137
                    */
138
                    TempFileNamed( const OUString* pParent=nullptr, bool bDirectory=false );
139
140
                    /**
141
                    Same as above; additionally the name starts with some given characters followed by a counter ( example:
142
                    rLeadingChars="abc" means "abc0","abc1" and so on, depending on existing files in the folder ).
143
                    The extension string may be f.e. ".txt" or "", if no extension string is given, ".tmp" is used
144
                        @param  _bStartWithZero If set to false names will be generated like "abc","abc0","abc1"
145
                        @param  bCreateParentDirs If rLeadingChars contains a slash, this will create the required
146
                                parent directories.
147
                    */
148
                    TempFileNamed( std::u16string_view rLeadingChars, bool _bStartWithZero=true, std::u16string_view pExtension={},
149
                              const OUString* pParent = nullptr, bool bCreateParentDirs=false );
150
151
                    TempFileNamed(TempFileNamed && other) noexcept;
152
153
                    /**
154
                    TempFile will be removed from disk in dtor if EnableKillingFile(true) was called before.
155
                    Temporary directories will be removed recursively in that case.
156
                    */
157
                    ~TempFileNamed();
158
159
                    /**
160
                    Returns sal_True if it has a valid file name.
161
                    */
162
    bool            IsValid() const;
163
164
                    /**
165
                    Returns the URL of the tempfile object.
166
                    If you want to have the system path file name, use the GetFileName() method of this object
167
                    */
168
    OUString const & GetURL() const;
169
170
                    /**
171
                    Returns the system path name of the tempfile in host notation
172
                    If you want to have the URL, use the GetURL() method of this object.
173
                    */
174
    OUString        GetFileName() const;
175
176
                    /**
177
                    Returns a stream to the tempfiles data; the stream is owned by the tempfile object, so you have to keep this
178
                    alive as long as you want to use the stream. If the TempFile object is destroyed, it also destroys the
179
                    stream object, the underlying file is only deleted if EnableKillingFile(true) has been called before!
180
                    */
181
    SvStream*       GetStream( StreamMode eMode );
182
183
                    /**
184
                    Let the TempFile object close and destroy the owned stream object if any.
185
                    */
186
    void            CloseStream();
187
188
                    /**
189
                    If enabled the file will be removed from disk when the dtor is called ( default is not enabled )
190
                    */
191
    void            EnableKillingFile( bool bEnable=true )
192
360k
                    { bKillingFileEnabled = bEnable; }
193
194
};
195
196
197
typedef ::cppu::WeakImplHelper<
198
     css::io::XStream
199
    , css::io::XSeekable
200
    , css::io::XInputStream
201
    , css::io::XOutputStream
202
    , css::io::XTruncate> TempFileFastService_Base;
203
class UNOTOOLS_DLLPUBLIC TempFileFastService final : public TempFileFastService_Base,
204
    public comphelper::ByteReader, public comphelper::ByteWriter
205
{
206
    std::optional<utl::TempFileFast> mpTempFile;
207
    std::mutex maMutex;
208
    SvStream* mpStream;
209
    bool mbInClosed;
210
    bool mbOutClosed;
211
212
    SAL_DLLPRIVATE void checkError () const;
213
    SAL_DLLPRIVATE void checkConnected ();
214
215
public:
216
    explicit TempFileFastService ();
217
    SAL_DLLPRIVATE virtual ~TempFileFastService () override;
218
219
    // XInputStream
220
    virtual ::sal_Int32 SAL_CALL readBytes( css::uno::Sequence< ::sal_Int8 >& aData, ::sal_Int32 nBytesToRead ) override;
221
    SAL_DLLPRIVATE virtual ::sal_Int32 SAL_CALL readSomeBytes( css::uno::Sequence< ::sal_Int8 >& aData, ::sal_Int32 nMaxBytesToRead ) override;
222
    SAL_DLLPRIVATE virtual void SAL_CALL skipBytes( ::sal_Int32 nBytesToSkip ) override;
223
    SAL_DLLPRIVATE virtual ::sal_Int32 SAL_CALL available(  ) override;
224
    SAL_DLLPRIVATE virtual void SAL_CALL closeInput(  ) override;
225
    // XOutputStream
226
    virtual void SAL_CALL writeBytes( const css::uno::Sequence< ::sal_Int8 >& aData ) override;
227
    SAL_DLLPRIVATE virtual void SAL_CALL flush(  ) override;
228
    virtual void SAL_CALL closeOutput(  ) override;
229
    // XSeekable
230
    virtual void SAL_CALL seek( sal_Int64 location ) override;
231
    virtual sal_Int64 SAL_CALL getPosition(  ) override;
232
    SAL_DLLPRIVATE virtual sal_Int64 SAL_CALL getLength(  ) override;
233
    // XStream
234
    virtual css::uno::Reference< css::io::XInputStream > SAL_CALL getInputStream(  ) override;
235
    virtual css::uno::Reference< css::io::XOutputStream > SAL_CALL getOutputStream(  ) override;
236
    // XTruncate
237
    SAL_DLLPRIVATE virtual void SAL_CALL truncate() override;
238
239
    // comphelper::ByteReader
240
    virtual sal_Int32 readSomeBytes(sal_Int8* aData, sal_Int32 nBytesToRead) override;
241
    // comphelper::ByteWriter
242
    virtual void writeBytes(const sal_Int8* aData, sal_Int32 nBytesToWrite) override;
243
244
};
245
246
247
}
248
249
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */