summaryrefslogtreecommitdiff
path: root/apps/wizard/unshield/unshieldworker.cpp
blob: f84658bf352fe92384b1933d84911a353462f55e (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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
#include "unshieldworker.hpp"

#include <QDebug>

#include <QReadLocker>
#include <QWriteLocker>
#include <QFileDialog>
#include <QFileInfo>
#include <QStringList>
#include <QTextStream>
#include <QTextCodec>
#include <QFile>
#include <QDir>
#include <QDirIterator>

Wizard::UnshieldWorker::UnshieldWorker(QObject *parent) :
    QObject(parent),
    mIniSettings()
{
    unshield_set_log_level(0);

    mPath = QString();
    mIniPath = QString();
    mDiskPath = QString();

    // Default to Latin encoding
    mIniCodec = QTextCodec::codecForName("windows-1252");

    mInstallMorrowind = false;
    mInstallTribunal = false;
    mInstallBloodmoon = false;

    mMorrowindDone = false;
    mTribunalDone = false;
    mBloodmoonDone = false;

    mStopped = false;

    qRegisterMetaType<Wizard::Component>("Wizard::Component");
}

Wizard::UnshieldWorker::~UnshieldWorker()
{
}

void Wizard::UnshieldWorker::stopWorker()
{
    mStopped = true;
    mWait.wakeOne();
}

void Wizard::UnshieldWorker::setInstallComponent(Wizard::Component component, bool install)
{
    QWriteLocker writeLock(&mLock);
    switch (component) {

    case Wizard::Component_Morrowind:
        mInstallMorrowind = install;
        break;
    case Wizard::Component_Tribunal:
        mInstallTribunal = install;
        break;
    case Wizard::Component_Bloodmoon:
        mInstallBloodmoon = install;
        break;
    }
}

bool Wizard::UnshieldWorker::getInstallComponent(Component component)
{
    QReadLocker readLock(&mLock);
    switch (component) {

    case Wizard::Component_Morrowind:
        return mInstallMorrowind;
    case Wizard::Component_Tribunal:
        return mInstallTribunal;
    case Wizard::Component_Bloodmoon:
        return mInstallBloodmoon;
    }

    return false;
}

void Wizard::UnshieldWorker::setComponentDone(Component component, bool done)
{
    QWriteLocker writeLock(&mLock);
    switch (component) {

    case Wizard::Component_Morrowind:
        mMorrowindDone = done;
        break;
    case Wizard::Component_Tribunal:
        mTribunalDone = done;
        break;
    case Wizard::Component_Bloodmoon:
        mBloodmoonDone = done;
        break;
    }
}

bool Wizard::UnshieldWorker::getComponentDone(Component component)
{
    QReadLocker readLock(&mLock);
    switch (component)
    {

    case Wizard::Component_Morrowind:
        return mMorrowindDone;
    case Wizard::Component_Tribunal:
        return mTribunalDone;
    case Wizard::Component_Bloodmoon:
        return mBloodmoonDone;
    }

    return false;
}

void Wizard::UnshieldWorker::setPath(const QString &path)
{
    QWriteLocker writeLock(&mLock);
    mPath = path;
}

void Wizard::UnshieldWorker::setIniPath(const QString &path)
{
    QWriteLocker writeLock(&mLock);
    mIniPath = path;
}

void Wizard::UnshieldWorker::setDiskPath(const QString &path)
{
    QWriteLocker writeLock(&mLock);
    mDiskPath = path;
    mWait.wakeAll();
}

QString Wizard::UnshieldWorker::getPath()
{
    QReadLocker readLock(&mLock);
    return mPath;
}

QString Wizard::UnshieldWorker::getIniPath()
{
    QReadLocker readLock(&mLock);
    return mIniPath;
}

QString Wizard::UnshieldWorker::getDiskPath()
{
    QReadLocker readLock(&mLock);
    return mDiskPath;
}


void Wizard::UnshieldWorker::setIniCodec(QTextCodec *codec)
{
    QWriteLocker writeLock(&mLock);
    mIniCodec = codec;
}

bool Wizard::UnshieldWorker::setupSettings()
{
    // Create Morrowind.ini settings map
    if (getIniPath().isEmpty())
        return false;

    QFile file(getIniPath());

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        emit error(tr("Failed to open Morrowind configuration file!"),
                   tr("Opening %1 failed: %2.").arg(getIniPath(), file.errorString()));
        return false;
    }

    QTextStream stream(&file);
    stream.setCodec(mIniCodec);

    mIniSettings.readFile(stream);

    return true;
}

bool Wizard::UnshieldWorker::writeSettings()
{
    if (getIniPath().isEmpty())
        return false;

    QFile file(getIniPath());

    if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
        emit error(tr("Failed to open Morrowind configuration file!"),
                   tr("Opening %1 failed: %2.").arg(getIniPath(), file.errorString()));
        return false;
    }

    QTextStream stream(&file);
    stream.setCodec(mIniCodec);

    if (!mIniSettings.writeFile(getIniPath(), stream)) {
         emit error(tr("Failed to write Morrowind configuration file!"),
                    tr("Writing to %1 failed: %2.").arg(getIniPath(), file.errorString()));
         return false;
    }

    return true;
}

bool Wizard::UnshieldWorker::removeDirectory(const QString &dirName)
{
    bool result = false;
    QDir dir(dirName);

    if (dir.exists(dirName))
    {
        QFileInfoList list(dir.entryInfoList(QDir::NoDotAndDotDot |
                                               QDir::System | QDir::Hidden |
                                               QDir::AllDirs | QDir::Files, QDir::DirsFirst));
        for (const QFileInfo& info : list)
        {
            if (info.isDir()) {
                result = removeDirectory(info.absoluteFilePath());
            } else {
                result = QFile::remove(info.absoluteFilePath());
            }

            if (!result)
                return result;
        }

        result = dir.rmdir(dirName);
    }
    return result;
}

bool Wizard::UnshieldWorker::copyFile(const QString &source, const QString &destination, bool keepSource)
{
    QDir dir;
    QFile file;

    QFileInfo info(destination);

    if (info.exists()) {
        if (!dir.remove(info.absoluteFilePath()))
            return false;
    }

    if (file.copy(source, destination)) {
        if (!keepSource) {
            if (!file.remove(source))
                return false;
        } else {
            return true;
        }
    } else {
        return false;
    }

    return true;
}

bool Wizard::UnshieldWorker::copyDirectory(const QString &source, const QString &destination, bool keepSource)
{
    QDir sourceDir(source);
    QDir destDir(destination);
    bool result = true;

    if (!destDir.exists()) {
        if (!sourceDir.mkpath(destination))
            return false;
    }

    destDir.refresh();

    if (!destDir.exists())
        return false;

    QFileInfoList list(sourceDir.entryInfoList(QDir::NoDotAndDotDot |
                                                 QDir::System | QDir::Hidden |
                                                 QDir::AllDirs | QDir::Files, QDir::DirsFirst));

    for (const QFileInfo &info : list)
    {
        QString relativePath(info.absoluteFilePath());
        relativePath.remove(source);

        QString destinationPath(destDir.absolutePath() + relativePath);

        if (info.isSymLink())
            continue;

        if (info.isDir()) {
            result = copyDirectory(info.absoluteFilePath(), destinationPath);
        } else {
            result = copyFile(info.absoluteFilePath(), destinationPath);
        }
    }

    if (!keepSource)
        return result && removeDirectory(sourceDir.absolutePath());

    return result;
}

bool Wizard::UnshieldWorker::installFile(const QString &fileName, const QString &path, Qt::MatchFlags flags, bool keepSource)
{
    return installFiles(fileName, path, flags, keepSource, true);
}

bool Wizard::UnshieldWorker::installFiles(const QString &fileName, const QString &path, Qt::MatchFlags flags, bool keepSource, bool single)
{
    QDir dir(path);

    if (!dir.exists())
        return false;

    QStringList files(findFiles(fileName, path, flags));

    for (const QString &file : files)
    {
        QFileInfo info(file);
        emit textChanged(tr("Installing: %1").arg(info.fileName()));

        if (single) {
            return copyFile(info.absoluteFilePath(), getPath() + QDir::separator() + info.fileName(), keepSource);
        } else {
            if (!copyFile(info.absoluteFilePath(), getPath() + QDir::separator() + info.fileName(), keepSource))
                return false;
        }
    }

    return true;
}

bool Wizard::UnshieldWorker::installDirectories(const QString &dirName, const QString &path, bool recursive, bool keepSource)
{
    QDir dir(path);

    if (!dir.exists())
        return false;

    QStringList directories(findDirectories(dirName, path, recursive));

    for (const QString &dir : directories)
    {
        QFileInfo info(dir);
        emit textChanged(tr("Installing: %1 directory").arg(info.fileName()));
        if (!copyDirectory(info.absoluteFilePath(), getPath() + QDir::separator() + info.fileName(), keepSource))
            return false;
    }

    return true;
}

void Wizard::UnshieldWorker::extract()
{
    if (getInstallComponent(Wizard::Component_Morrowind))
    {
        if (!getComponentDone(Wizard::Component_Morrowind))
            if (!setupComponent(Wizard::Component_Morrowind))
                return;
    }

    if (getInstallComponent(Wizard::Component_Tribunal))
    {
        if (!getComponentDone(Wizard::Component_Tribunal))
            if (!setupComponent(Wizard::Component_Tribunal))
                return;
    }

    if (getInstallComponent(Wizard::Component_Bloodmoon))
    {
        if (!getComponentDone(Wizard::Component_Bloodmoon))
            if (!setupComponent(Wizard::Component_Bloodmoon))
                return;
    }

    // Update Morrowind configuration
    if (getInstallComponent(Wizard::Component_Tribunal))
    {
        mIniSettings.setValue(QLatin1String("Archives/Archive 0"), QVariant(QString("Tribunal.bsa")));
        mIniSettings.setValue(QLatin1String("Game Files/GameFile1"), QVariant(QString("Tribunal.esm")));
    }

    if (getInstallComponent(Wizard::Component_Bloodmoon))
    {
        mIniSettings.setValue(QLatin1String("Archives/Archive 0"), QVariant(QString("Bloodmoon.bsa")));
        mIniSettings.setValue(QLatin1String("Game Files/GameFile1"), QVariant(QString("Bloodmoon.esm")));
    }

    if (getInstallComponent(Wizard::Component_Tribunal) &&
            getInstallComponent(Wizard::Component_Bloodmoon))
    {
        mIniSettings.setValue(QLatin1String("Archives/Archive 0"), QVariant(QString("Tribunal.bsa")));
        mIniSettings.setValue(QLatin1String("Archives/Archive 1"), QVariant(QString("Bloodmoon.bsa")));
        mIniSettings.setValue(QLatin1String("Game Files/GameFile1"), QVariant(QString("Tribunal.esm")));
        mIniSettings.setValue(QLatin1String("Game Files/GameFile2"), QVariant(QString("Bloodmoon.esm")));
    }

    // Write the settings to the Morrowind config file
    if (!writeSettings())
        return;

    // Remove the temporary directory
    removeDirectory(getPath() + QDir::separator() + QLatin1String("extract-temp"));

    // Fill the progress bar
    int total = 0;

    if (getInstallComponent(Wizard::Component_Morrowind))
        total = 100;

    if (getInstallComponent(Wizard::Component_Tribunal))
        total = total + 100;

    if (getInstallComponent(Wizard::Component_Bloodmoon))
        total = total + 100;

    emit textChanged(tr("Installation finished!"));
    emit progressChanged(total);
    emit finished();
}

bool Wizard::UnshieldWorker::setupComponent(Component component)
{
    QString name;
    switch (component) {

    case Wizard::Component_Morrowind:
        name = QLatin1String("Morrowind");
        break;
    case Wizard::Component_Tribunal:
        name = QLatin1String("Tribunal");
        break;
    case Wizard::Component_Bloodmoon:
        name = QLatin1String("Bloodmoon");
        break;
    }

    if (name.isEmpty()) {
        emit error(tr("Component parameter is invalid!"), tr("An invalid component parameter was supplied."));
        return false;
    }

    bool found = false;
    QString cabFile;
    QDir disk;

    // Keep showing the file dialog until we find the necessary install files
    while (!found) {
        if (getDiskPath().isEmpty()) {
            QReadLocker readLock(&mLock);
            emit requestFileDialog(component);
            mWait.wait(&mLock);
            if(mStopped) {
                qDebug() << "We are asked to stop !!";
                break;
            }
            disk.setPath(getDiskPath());
        } else {
            disk.setPath(getDiskPath());
        }

        QStringList list(findFiles(QLatin1String("data1.hdr"), disk.absolutePath()));

        for (const QString &file : list)
        {

            qDebug() << "current archive: " << file;

            if (component == Wizard::Component_Morrowind)
            {
                bool morrowindFound = findInCab(QLatin1String("Morrowind.bsa"), file);
                bool tribunalFound = findInCab(QLatin1String("Tribunal.bsa"), file);
                bool bloodmoonFound = findInCab(QLatin1String("Bloodmoon.bsa"), file);

                if (morrowindFound) {
                    // Check if we have correct archive, other archives have Morrowind.bsa too
                    if (tribunalFound == bloodmoonFound)
                    {
                        cabFile = file;
                        found = true; // We have a GoTY disk or a Morrowind-only disk
                    }
                }
            } else {

                if (findInCab(name + QLatin1String(".bsa"), file)) {
                    cabFile = file;
                    found = true;
                }
            }

        }

        if (!found)
        {
            emit textChanged(tr("Failed to find a valid archive containing %1.bsa! Retrying.").arg(name));
            QReadLocker readLock(&mLock);
            emit requestFileDialog(component);
            mWait.wait(&mLock);
        }
    }

    if (installComponent(component, cabFile)) {
        setComponentDone(component, true);
        return true;
    } else {
        return false;
    }

    return true;
}

bool Wizard::UnshieldWorker::installComponent(Component component, const QString &path)
{
    QString name;
    switch (component) {

    case Wizard::Component_Morrowind:
        name = QLatin1String("Morrowind");
        break;
    case Wizard::Component_Tribunal:
        name = QLatin1String("Tribunal");
        break;
    case Wizard::Component_Bloodmoon:
        name = QLatin1String("Bloodmoon");
        break;
    }

    if (name.isEmpty()) {
        emit error(tr("Component parameter is invalid!"), tr("An invalid component parameter was supplied."));
        return false;
    }

    emit textChanged(tr("Installing %1").arg(name));

    QFileInfo info(path);

    if (!info.exists()) {
        emit error(tr("Installation media path not set!"), tr("The source path for %1 was not set.").arg(name));
        return false;
    }

    // Create temporary extract directory
    // TODO: Use QTemporaryDir in Qt 5.0
    QString tempPath(getPath() + QDir::separator() + QLatin1String("extract-temp"));
    QDir temp;

    // Make sure the temporary folder is empty
    removeDirectory(tempPath);

    if (!temp.mkpath(tempPath)) {
        emit error(tr("Cannot create temporary directory!"), tr("Failed to create %1.").arg(tempPath));
        return false;
    }

    temp.setPath(tempPath);

    if (!temp.mkdir(name)) {
        emit error(tr("Cannot create temporary directory!"), tr("Failed to create %1.").arg(temp.absoluteFilePath(name)));
        return false;
    }

    if (!temp.cd(name)) {
        emit error(tr("Cannot move into temporary directory!"), tr("Failed to move into %1.").arg(temp.absoluteFilePath(name)));
        return false;
    }

    // Extract the installation files
    if (!extractCab(info.absoluteFilePath(), temp.absolutePath()))
        return false;

    // Move the files from the temporary path to the destination folder
    emit textChanged(tr("Moving installation files"));

    // Install extracted directories
    QStringList directories;
    directories << QLatin1String("BookArt")
                << QLatin1String("Fonts")
                << QLatin1String("Icons")
                << QLatin1String("Meshes")
                << QLatin1String("Music")
                << QLatin1String("Sound")
                << QLatin1String("Splash")
                << QLatin1String("Textures")
                << QLatin1String("Video");

    for (const QString &dir : directories)
    {
        if (!installDirectories(dir, temp.absolutePath())) {
            emit error(tr("Could not install directory!"),
                       tr("Installing %1 to %2 failed.").arg(dir, temp.absolutePath()));
            return false;
        }
    }

    // Install directories from disk
    for (const QString &dir : directories)
    {
        if (!installDirectories(dir, info.absolutePath(), false, true)) {
            emit error(tr("Could not install directory!"),
                       tr("Installing %1 to %2 failed.").arg(dir, info.absolutePath()));
            return false;
        }

    }

    // Install translation files
    QStringList extensions;
    extensions << QLatin1String(".cel")
               << QLatin1String(".top")
               << QLatin1String(".mrk");

    for (const QString &extension : extensions)
    {
        if (!installFiles(extension, info.absolutePath(), Qt::MatchEndsWith)) {
            emit error(tr("Could not install translation file!"),
                       tr("Failed to install *%1 files.").arg(extension));
            return false;
        }
    }

    if (component == Wizard::Component_Morrowind)
    {
        QStringList files;
        files << QLatin1String("Morrowind.esm")
              << QLatin1String("Morrowind.bsa");

        for (const QString &file : files)
        {
            if (!installFile(file, temp.absolutePath())) {
                emit error(tr("Could not install Morrowind data file!"),
                           tr("Failed to install %1.").arg(file));
                return false;
            }
        }

        // Copy Morrowind configuration file
        if (!installFile(QLatin1String("Morrowind.ini"), temp.absolutePath())) {
            emit error(tr("Could not install Morrowind configuration file!"),
                       tr("Failed to install %1.").arg(QLatin1String("Morrowind.ini")));
            return false;
        }

        // Setup Morrowind configuration
        setIniPath(getPath() + QDir::separator() + QLatin1String("Morrowind.ini"));

        if (!setupSettings())
            return false;
    }

    if (component == Wizard::Component_Tribunal)
    {
        QFileInfo sounds(temp.absoluteFilePath(QLatin1String("Sounds")));
        QString dest(getPath() + QDir::separator() + QLatin1String("Sound"));

        if (sounds.exists()) {
            emit textChanged(tr("Installing: Sound directory"));
            if (!copyDirectory(sounds.absoluteFilePath(), dest)) {
                emit error(tr("Could not install directory!"),
                           tr("Installing %1 to %2 failed.").arg(sounds.absoluteFilePath(), dest));
                return false;
            }

        }

        QStringList files;
        files << QLatin1String("Tribunal.esm")
              << QLatin1String("Tribunal.bsa");

        for (const QString &file : files)
        {
            if (!installFile(file, temp.absolutePath())) {
                emit error(tr("Could not find Tribunal data file!"),
                           tr("Failed to find %1.").arg(file));
                return false;
            }
        }
    }

    if (component == Wizard::Component_Bloodmoon)
    {
        QFileInfo original(getPath() + QDir::separator() + QLatin1String("Tribunal.esm"));

        if (original.exists()) {
            if (!installFile(QLatin1String("Tribunal.esm"), temp.absolutePath())) {
                emit error(tr("Could not find Tribunal patch file!"),
                           tr("Failed to find %1.").arg(QLatin1String("Tribunal.esm")));
                return false;
            }
        }

        QStringList files;
        files << QLatin1String("Bloodmoon.esm")
              << QLatin1String("Bloodmoon.bsa");

        for (const QString &file : files)
        {
            if (!installFile(file, temp.absolutePath())) {
                emit error(tr("Could not find Bloodmoon data file!"),
                           tr("Failed to find %1.").arg(file));
                return false;
            }
        }

        // Load Morrowind configuration settings from the setup script
        QStringList list(findFiles(QLatin1String("setup.inx"), getDiskPath()));

        emit textChanged(tr("Updating Morrowind configuration file"));

        for (const QString &inx : list)
        {
             mIniSettings.parseInx(inx);
        }
    }

    // Finally, install Data Files directories from temp and disk
    QStringList datafiles(findDirectories(QLatin1String("Data Files"), temp.absolutePath()));
    datafiles.append(findDirectories(QLatin1String("Data Files"), info.absolutePath()));

    for (const QString &dir : datafiles)
    {
        QFileInfo info(dir);
        emit textChanged(tr("Installing: %1 directory").arg(info.fileName()));

        if (!copyDirectory(info.absoluteFilePath(), getPath())) {
            emit error(tr("Could not install directory!"),
                       tr("Installing %1 to %2 failed.").arg(info.absoluteFilePath(), getPath()));
            return false;
        }
    }

    emit textChanged(tr("%1 installation finished!").arg(name));
    return true;

}

bool Wizard::UnshieldWorker::extractFile(Unshield *unshield, const QString &destination, const QString &prefix, int index, int counter)
{
    bool success = false;
    QString path(destination);
    path.append(QDir::separator());

    int directory = unshield_file_directory(unshield, index);

    if (!prefix.isEmpty())
        path.append(prefix + QDir::separator());

    if (directory >= 0)
        path.append(QString::fromUtf8(unshield_directory_name(unshield, directory)) + QDir::separator());

    // Ensure the path has the right separators
    path.replace(QLatin1Char('\\'), QDir::separator());
    path = QDir::toNativeSeparators(path);

    // Ensure the target path exists
    QDir dir;
    if (!dir.mkpath(path))
        return false;

    QString fileName(path);
    fileName.append(QString::fromUtf8(unshield_file_name(unshield, index)));

    // Calculate the percentage done
    int progress = (((float) counter / (float) unshield_file_count(unshield)) * 100);

    if (getComponentDone(Wizard::Component_Morrowind))
        progress = progress + 100;

    if (getComponentDone(Wizard::Component_Tribunal))
        progress = progress + 100;

    emit textChanged(tr("Extracting: %1").arg(QString::fromUtf8(unshield_file_name(unshield, index))));
    emit progressChanged(progress);

    QByteArray array(fileName.toUtf8());
    success = unshield_file_save(unshield, index, array.constData());

    if (!success) {
        qDebug() << "error";
        dir.remove(fileName);
    }

    return success;
}

bool Wizard::UnshieldWorker::extractCab(const QString &cabFile, const QString &destination)
{
    bool success = false;

    QByteArray array(cabFile.toUtf8());

    Unshield *unshield;
    unshield = unshield_open(array.constData());

    if (!unshield) {
        emit error(tr("Failed to open InstallShield Cabinet File."), tr("Opening %1 failed.").arg(cabFile));
        unshield_close(unshield);
        return false;
    }

    int counter = 0;

    for (int i=0; i<unshield_file_group_count(unshield); ++i)
    {
        UnshieldFileGroup *group = unshield_file_group_get(unshield, i);

        for (size_t j=group->first_file; j<=group->last_file; ++j)
        {
            if (mStopped) {
                qDebug() << "We're asked to stop!";

                unshield_close(unshield);
                return true;
            }

            if (unshield_file_is_valid(unshield, j)) {
                success = extractFile(unshield, destination, group->name, j, counter);

                if (!success) {
                    QString name(QString::fromUtf8(unshield_file_name(unshield, j)));

                    emit error(tr("Failed to extract %1.").arg(name),
                               tr("Complete path: %1").arg(destination + QDir::separator() + name));

                    unshield_close(unshield);
                    return false;
                }

                ++counter;
            }
        }
    }

    unshield_close(unshield);
    return success;
}

QString Wizard::UnshieldWorker::findFile(const QString &fileName, const QString &path)
{
    return findFiles(fileName, path).first();
}

QStringList Wizard::UnshieldWorker::findFiles(const QString &fileName, const QString &path, int depth, bool recursive,
                                              bool directories, Qt::MatchFlags flags)
{
    static const int MAXIMUM_DEPTH = 10;

    if (depth >= MAXIMUM_DEPTH) {
        qWarning("Maximum directory depth limit reached.");
        return QStringList();
    }

    QStringList result;
    QDir dir(path);

    // Prevent parsing over the complete filesystem
    if (dir == QDir::rootPath())
        return QStringList();

    if (!dir.exists())
        return QStringList();

    QFileInfoList list(dir.entryInfoList(QDir::NoDotAndDotDot |
                                         QDir::AllDirs | QDir::Files, QDir::DirsFirst));
    for (const QFileInfo& info : list)
    {
        if (info.isSymLink())
            continue;

        if (info.isDir()) {
            if (directories)
            {
                if (!info.fileName().compare(fileName, Qt::CaseInsensitive)) {
                    result.append(info.absoluteFilePath());
                } else {
                    if (recursive)
                        result.append(findFiles(fileName, info.absoluteFilePath(), depth + 1, recursive, true));
                }
            } else {
                if (recursive)
                    result.append(findFiles(fileName, info.absoluteFilePath(), depth + 1));
            }
        } else {
            if (directories)
                break;

            switch (flags) {
            case Qt::MatchExactly:
                if (!info.fileName().compare(fileName, Qt::CaseInsensitive))
                    result.append(info.absoluteFilePath());
                break;
            case Qt::MatchEndsWith:
                if (info.fileName().endsWith(fileName, Qt::CaseInsensitive))
                    result.append(info.absoluteFilePath());
                break;
            }
        }
    }

    return result;
}

QStringList Wizard::UnshieldWorker::findDirectories(const QString &dirName, const QString &path, bool recursive)
{
    return findFiles(dirName, path, 0, true, true);
}

bool Wizard::UnshieldWorker::findInCab(const QString &fileName, const QString &cabFile)
{
    QByteArray array(cabFile.toUtf8());

    Unshield *unshield;
    unshield = unshield_open(array.constData());

    if (!unshield) {
        emit error(tr("Failed to open InstallShield Cabinet File."), tr("Opening %1 failed.").arg(cabFile));
        unshield_close(unshield);
        return false;
    }

    for (int i=0; i<unshield_file_group_count(unshield); ++i)
    {
        UnshieldFileGroup *group = unshield_file_group_get(unshield, i);

        for (size_t j=group->first_file; j<=group->last_file; ++j)
        {

            if (unshield_file_is_valid(unshield, j)) {
                QString current(QString::fromUtf8(unshield_file_name(unshield, j)));
                if (current.toLower() == fileName.toLower()) {
                    unshield_close(unshield);
                    return true; // File is found!
                }
            }
        }
    }

    unshield_close(unshield);
    return false;
}