summaryrefslogtreecommitdiffstats
path: root/installerbuilder/libinstaller/createshortcutoperation.cpp
blob: 0aea4af636f4b2c074101be567f36201b15ff9e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/**************************************************************************
**
** This file is part of Qt SDK**
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).*
**
** Contact:  Nokia Corporation qt-info@nokia.com**
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception version
** 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you are unsure which license is appropriate for your use, please contact
** (qt-info@nokia.com).
**
**************************************************************************/
//#include "kdupdaterupdateoperations.h"
#include <KDUpdater/kdupdaterapplication.h>
#include <KDUpdater/kdupdaterpackagesinfo.h>

#include "createshortcutoperation.h"
#include "common/errors.h"
#include "common/fileutils.h"
#include "common/utils.h"

#include <QDir>
#include <QFileInfo>
#include <QTemporaryFile>

#include <algorithm>
#include <cerrno>

#ifdef Q_WS_WIN
#include <windows.h>
#include <shlobj.h>
#endif

using namespace QInstaller;

static bool createLink( QString fileName, QString linkName, QString workingDir, QString arguments = QString() )
{
#ifdef Q_WS_WIN
    bool ret = false;
    fileName = QDir::toNativeSeparators(fileName);
    linkName = QDir::toNativeSeparators(linkName);
    if ( workingDir.isEmpty() )
        workingDir = QFileInfo(fileName).absolutePath();
    workingDir = QDir::toNativeSeparators(workingDir);

    //### assume that they add .lnk

    IShellLink *psl;
    bool neededCoInit = false;

    HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl);

    if (hres == CO_E_NOTINITIALIZED) { // COM was not initialized
        neededCoInit = true;
        CoInitialize(NULL);
        hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **)&psl);
    }

    if (SUCCEEDED(hres)) {
        hres = psl->SetPath((wchar_t *)fileName.utf16());
        if( SUCCEEDED( hres ) && !arguments.isNull() )
            hres = psl->SetArguments((wchar_t*)arguments.utf16() );
        if (SUCCEEDED(hres)) {
            hres = psl->SetWorkingDirectory((wchar_t *)workingDir.utf16());
            if (SUCCEEDED(hres)) {
                IPersistFile *ppf;
                hres = psl->QueryInterface(IID_IPersistFile, (void **)&ppf);
                if (SUCCEEDED(hres)) {
                    hres = ppf->Save((wchar_t*)linkName.utf16(), TRUE);
                    if (SUCCEEDED(hres))
                        ret = true;
                    ppf->Release();
                }
            }
        }
        psl->Release();
    }

    if (neededCoInit)
        CoUninitialize();

    return ret;
#else
    Q_UNUSED( workingDir )
    Q_UNUSED( arguments )
    return QFile::link( fileName, linkName );
#endif
}

/*
TRANSLATOR QInstaller::CreateShortcutOperation
*/

CreateShortcutOperation::CreateShortcutOperation()
{
    setName( QLatin1String( "CreateShortcut" ) );
}

CreateShortcutOperation::~CreateShortcutOperation()
{
    deleteFileNowOrLater( value( QLatin1String( "backupOfExistingShortcut" ) ).toString() );
}

static bool isWorkingDirOption( const QString& s ) {
    return s.startsWith( QLatin1String("workingDirectory=") );
}

static QString getWorkingDir( QStringList& args ) {
    QString workingDir;
    // if the args contain an option in the form "workingDirectory=...", find it and consume it
    QStringList::iterator wdiropt = std::find_if( args.begin(), args.end(), isWorkingDirOption );
    if ( wdiropt != args.end() ) {
        workingDir = wdiropt->mid( QString::fromLatin1("workingDirectory=").size() );
        args.erase( wdiropt );
    }
    return workingDir;
}

void CreateShortcutOperation::backup()
{
    QStringList args = this->arguments();
    getWorkingDir( args ); //consume workingDirectory= option

    const QString path = QDir::fromNativeSeparators( QFileInfo( args.at( 1 ) ).absolutePath() );

    //verbose() << "dir to create shortcut in " << path << std::endl;

    QDir createdDir = QDir::root();

    // find out, which part of the path is the first one we actually need to create
    int end = 0;
    QStringList directoriesToCreate;
    while( true )
    {
        QString p = path.section( QLatin1String("/"), 0, ++end );
        createdDir = QDir( p );
        if( !createdDir.exists() )
        {            
            directoriesToCreate.push_back( QDir::toNativeSeparators( createdDir.absolutePath() ) );
            verbose() << " backup created dir_pre " << QDir::toNativeSeparators( createdDir.absolutePath() ) << std::endl;
            if ( p == path)
                break;

        }
        else if( p == path )
        {
            // everything did already exist -> nothing to do for us (nothing to revert then, either)
            createdDir = QDir::root();
            break;
        }
    }
    verbose() << " backup created dir " << createdDir.absolutePath() << std::endl;

    setValue( QLatin1String( "createddirs" ), directoriesToCreate );

    //link creation context
    const QString linkLocation = arguments()[ 1 ];
    if( !QFile::exists( linkLocation ) )
        return;

    try {
        setValue( QLatin1String( "backupOfExistingShortcut" ), generateTemporaryFileName( linkLocation ) );
    } catch ( const QInstaller::Error& e ) {
        setErrorString( e.message() );
        return;
    }

    QFile f( linkLocation );
    if( !f.copy( value( QLatin1String( "backupOfExistingShortcut" ) ).toString() ) )
        setErrorString( QObject::tr( "Could not backup file %1: %2" ).arg( linkLocation, f.errorString() ) );
}

bool CreateShortcutOperation::performOperation()
{
    QStringList args = this->arguments();
    const QString workingDir = getWorkingDir( args );

    if( args.count() != 2 && args.count() != 3 )
    {
        setError( InvalidArguments );
        setErrorString( QObject::tr("Invalid arguments: %1 arguments given, 2 or 3 expected (optional: \"workingDirectory=...\").").arg( args.count() ) );
        return false;
    }

    const QString& linkTarget = args.at( 0 );
    const QString& linkLocation = args.at( 1 );
    const QString targetArguments = args.count() == 3 ? args[ 2 ] : QString();

    const QString dirName = QFileInfo( linkLocation ).absolutePath();

    //verbose() << "dir to create shortcut in " << dirName << std::endl;

    errno = 0;

    const bool dirAlreadyExists = QDir( dirName ).exists();
    const bool created = dirAlreadyExists || QDir::root().mkpath(dirName);

    if ( !created ) {
        setError( UserDefinedError );
        setErrorString( tr("Could not create folder %1: %2.").arg( QDir::toNativeSeparators( dirName ), QLatin1String(strerror(errno)) ) );
        return false;
    }

    TempDirDeleter deleter( dirName );

    if( dirAlreadyExists )
        deleter.releaseAll();

#if 0 // disabled for now, isDir() also returns true if the link exists and points to a folder, then removing it fails
    // link creation
    if ( QFileInfo( linkLocation ).isDir() ) {
        errno = 0;
        if ( !QDir().rmdir( linkLocation ) ) {
            setError( UserDefinedError );
            setErrorString( QObject::tr( "Could not create link: failed to remove folder %1: %2" ).arg( QDir::toNativeSeparators( linkLocation ), QLatin1String(strerror(errno)) ) );
            return false;
        }
    }
#endif

    QString err;

    if( QFile::exists( linkLocation ) && !deleteFileNowOrLater( linkLocation, &err ) )
    {
        setError( UserDefinedError );
        setErrorString( QObject::tr( "Failed to overwrite %1: %2" ).arg( QDir::toNativeSeparators( linkLocation ), err ) );
        return false;
    }

    const bool linked = createLink( linkTarget, linkLocation, workingDir, targetArguments );
    if ( !linked ) {
        setError( UserDefinedError );
        setErrorString( tr("Could not create link %1: %2").arg( QDir::toNativeSeparators( linkLocation ), qt_error_string() ) );
        return false;
    }
    deleter.releaseAll();
    return true;
}

bool CreateShortcutOperation::undoOperation()
{       
    const QString linkLocation = arguments()[ 1 ];
    const QStringList args = this->arguments();
    verbose() << " undo Shortcutoperation with arguments ";
    Q_FOREACH( const QString& val, args )
            verbose() << val << " ";
    verbose() << std::endl;

    // first remove the link
    if( !deleteFileNowOrLater( linkLocation ) )
    {
        setErrorString( QObject::tr( "Could not delete file %1" ).arg( linkLocation ) );
        return false;
    }
    verbose() << " link has been deleted " << std::endl;

    if( hasValue( QLatin1String( "backupOfExistingShortcut" ) ) ){

        const QString backupOfExistingShortcut = value( QLatin1String( "backupOfExistingShortcut" ) ).toString();
        const bool success = QFile::copy( backupOfExistingShortcut, linkLocation ) && deleteFileNowOrLater( backupOfExistingShortcut );
        if( !success ){
            setErrorString( QObject::tr( "Could not restore backup file into %1" ).arg( linkLocation ) );
            return success;
        }
    }
    verbose() << " got behin backup " << std::endl;

    const QStringList createdDirsPaths = value( QLatin1String( "createddirs" ) ).toStringList();
    if ( createdDirsPaths.isEmpty() ) //no dir to delete (QDir( createdDirPath ) would return the current working directory -> never do that
        return true;

    const bool forceremoval = QVariant( value( QLatin1String( "forceremoval" ) ) ).toBool();
    QListIterator<QString> it( createdDirsPaths );
    for ( it.toBack(); it.hasPrevious(); )
    {
        const QString createdDirPath = it.previous();
        const QDir createdDir = QDir( createdDirPath );
        verbose() << createdDir.absolutePath() << std::endl;
        if( createdDir == QDir::root() )
            return true;
        QString errorString;
        if( forceremoval )
        {
            verbose() << " forced removal of path " << createdDir.path() << std::endl;
            try{
                removeDirectory( createdDir.path(), false );
            }catch(const QInstaller::Error e){
                setError( UserDefinedError, e.message() );
               return false;
            }
        }
        else
        {
            // even remove some hidden, OS-created files in there
#if defined Q_WS_MAC
            QFile::remove( createdDir.path() + QLatin1String( "/.DS_Store" ) );
#elif defined Q_WS_WIN
            QFile::remove( createdDir.path() + QLatin1String( "/Thumbs.db" ) );
#endif

            errno = 0;
            verbose() << " removal of path " << createdDir.path() << std::endl;
            const bool result = QDir::root().rmdir( createdDir.path() );
            if ( !result ) {
                if ( errorString.isEmpty() )
                    setError( UserDefinedError, tr("Cannot remove directory %1: %2").arg( createdDir.path(), errorString ) );
                else
                    setError( UserDefinedError, tr("Cannot remove directory %1: %2").arg( createdDir.path(), QLatin1String(strerror(errno)) ) );
                return result;
            }
        }
    }
    return true;
}

bool CreateShortcutOperation::testOperation()
{
    return true;
}

CreateShortcutOperation* CreateShortcutOperation::clone() const
{
    return new CreateShortcutOperation();
}