Procházet zdrojové kódy

Command line installer, headless installation and uninitialised memory fixes

- The installer has a command line mode in the same binary: without arguments it opens the window; with --cli, or any installation option, it installs (or verifies with --verify) from the terminal. Options: --iso, --output, --preset, --with, --without, --no-copy-data, --data-dir, --discard-originals, --ffmpeg, --timidity, --yes, --list-parts, --help and --version. Exit status 0 on success, 1 on failure, 2 for a wrong command line. Where the window asks, the command line stops unless --yes is given. In Windows it attaches to the console it was started from.
- The install steps that don't need the window (preflight checks, finding and copying the V-Gears data folder, required disk files, movie conversion, audio tool locations) moved from MainWindow to InstallSteps, used by both the window and the command line.
- The installer starts Ogre without a render system (Application::initOgreHeadless), so it needs no display, window or graphics driver. Meshes use system memory buffers and textures are only named. The window installer uses it too. A full installation produces the same files as with OpenGL.
- Enemy attacks were read twice from scene.bin, the second time without their animation, so every enemy had duplicated attacks with garbage animations that the AI could pick.
- Field tile images were not cleared, so the parts without tiles had whatever was in memory.
- The .da animation reader read past the end of truncated animations, and leaked its buffer.
- The installer TexFile didn't clear the images it saves, and leaked them.
- File reads past its end as zeros, instead of reading out of bounds (the .ab, .tex and kernel archive readers did), and zeroes its buffer when the file can't be read. The kernel archive reader stops when a header doesn't fit.
- FFmpeg converts audio bit exact, so the Ogg files are the same in every installation.
- Two installations now produce identical files.
- Tests for the command line parser and the FFmpeg arguments.
Iñigo Valentin před 2 dny
rodič
revize
f35eb2dd6c

+ 17 - 8
src/common/File.cpp

@@ -17,6 +17,8 @@
 #include <string.h>
 #include "common/File.h"
 #include "common/FileSystem.h"
+#include <algorithm>
+#include <cstring>
 #include "core/Logger.h"
 
 File::File(const Ogre::String& file):
@@ -27,7 +29,8 @@ File::File(const Ogre::String& file):
 {
     LOG_TRIVIAL("Loading file: " + file_name_ + "\n");
     buffer_size_ = FileSystem::GetFileSize(file_name_);
-    buffer_ = static_cast<u8*>(malloc(sizeof(u8) * buffer_size_));
+    // Zeroed, so a file that can't be read is empty data, not whatever was in memory.
+    buffer_ = static_cast<u8*>(calloc(buffer_size_, sizeof(u8)));
     if (!FileSystem::ReadFile(file_name_, buffer_, 0, buffer_size_))
         LOG_TRIVIAL("Warning: " + file_name_ + " not found!\n");
 }
@@ -68,21 +71,27 @@ const Ogre::String& File::GetFileName() const{return file_name_;}
 u32 File::GetFileSize() const{return buffer_size_;}
 
 void File::GetFileBuffer(u8* buffer, const u32 &start, const u32 &length) const{
-    memcpy(buffer, buffer_ + start, length);
+    // What is past the end of the file is read as zeros.
+    const u32 available = start < buffer_size_ ? std::min(length, buffer_size_ - start) : 0;
+    if (available > 0) memcpy(buffer, buffer_ + start, available);
+    if (available < length) memset(buffer + available, 0, length - available);
 }
 
-u8 File::GetU8(u32 offset) const{return *(buffer_ + offset);}
+// Many of the original files are read past their end by the parsers (truncated animations, headers of the
+// last entry of an archive...). Those bytes are read as zeros, instead of whatever is in memory after the file.
+
+u8 File::GetU8(u32 offset) const{return offset < buffer_size_ ? buffer_[offset] : 0;}
 
 u16 File::GetU16LE(u32 offset) const{
-    return (buffer_ + offset)[0] | ((buffer_ + offset)[1] << 8);
+    return GetU8(offset) | (GetU8(offset + 1) << 8);
 }
 
 u32 File::GetU32LE(u32 offset) const{
     return
-      (buffer_ + offset)[0]
-      | ((buffer_ + offset)[1] << 8)
-      | ((buffer_ + offset)[2] << 16)
-      | ((buffer_ + offset)[3] << 24);
+      static_cast<u32>(GetU8(offset))
+      | (static_cast<u32>(GetU8(offset + 1)) << 8)
+      | (static_cast<u32>(GetU8(offset + 2)) << 16)
+      | (static_cast<u32>(GetU8(offset + 3)) << 24);
 }
 
 u8 File::readU8(){

+ 34 - 1
src/common/VGearsApplication.cpp

@@ -41,6 +41,10 @@
 #include "data/VGearsTriggersFile.h"
 #include "data/VGearsMapListFile.h"
 #include "Version.h"
+#include <OgreControllerManager.h>
+#include <OgreDefaultHardwareBufferManager.h>
+#include <OgreMaterialManager.h>
+#include <OgreMeshManager.h>
 
 /**
  * Application singleton.
@@ -134,7 +138,32 @@ namespace VGears{
         return true;
     }
 
-    void Application::loadPlugins(){
+    bool Application::initOgreHeadless(){
+        if (_initialized) return false;
+        _initialized = true;
+        _headless = true;
+        // No plugins file is passed to Ogre: the plugins are looked for in several places, see loadPlugins.
+        _root = std::make_unique<Ogre::Root>("", config_filename_, log_filename_);
+        loadPlugins(true);
+        _overlay_system = std::make_unique<Ogre::OverlaySystem>();
+        Ogre::LogManager::getSingleton().getDefaultLog()->setLogDetail(Ogre::LL_BOREME);
+        // Without a render system nobody creates the hardware buffer manager, and meshes need one.
+        _buffer_manager = std::make_unique<Ogre::DefaultHardwareBufferManager>();
+        // What Ogre::Root::initialise and the render system do, except what needs a graphics driver: the
+        // controllers (used by animated materials), a texture manager for the textures named by the materials,
+        // the default material that new materials copy, and the built-in meshes.
+        if (Ogre::ControllerManager::getSingletonPtr() == nullptr)
+            _controller_manager = std::make_unique<Ogre::ControllerManager>();
+        _texture_manager = std::make_unique<Ogre::DefaultTextureManager>();
+        Ogre::MaterialManager::getSingleton().initialise();
+        Ogre::MeshManager::getSingleton()._initialise();
+        registerArchiveFactories();
+        loadResourcesConfig();
+        initComponents();
+        return true;
+    }
+
+    void Application::loadPlugins(bool skip_render_systems){
         const bfs::path plugins_file(bfs::absolute(bfs::path(plugins_filename_)));
         OgrePlugins::Config config;
         if (!OgrePlugins::ReadConfig(plugins_file, config))
@@ -148,6 +177,10 @@ namespace VGears{
           + std::to_string(OGRE_VERSION_PATCH)
         );
         for (const String& name : config.plugins){
+            if (skip_render_systems && name.compare(0, 13, "RenderSystem_") == 0){
+                Ogre::LogManager::getSingleton().logMessage("Not loading Ogre plugin " + name + ": no render system");
+                continue;
+            }
             const bfs::path file(OgrePlugins::Find(name, directories, ogre_version));
             if (file.empty()){
                 String searched;

+ 52 - 1
src/common/VGearsApplication.h

@@ -17,6 +17,9 @@
 
 #include <OgreRoot.h>
 #include <OgreOverlaySystem.h>
+#include <OgreHardwareBufferManager.h>
+#include <OgreControllerManager.h>
+#include <OgreTextureManager.h>
 #include <memory>
 #include "TypeDefine.h"
 
@@ -65,6 +68,26 @@ namespace VGears{
              */
             bool initOgre(bool hideWindow = false);
 
+            /**
+             * Initializes Ogre without a render system, for programs that only convert data.
+             *
+             * No window is created, so no display or graphics driver is needed. The render system plugins in the
+             * plugins file are not loaded, and meshes and skeletons are kept in system memory (see
+             * Ogre::DefaultHardwareBufferManager). Materials can name textures, but no texture is created (see
+             * Ogre::DefaultTextureManager). Nothing can be rendered.
+             *
+             * @return True if the system was succesfully initiated, false if there were errors or it was already
+             * initialized.
+             */
+            bool initOgreHeadless();
+
+            /**
+             * Tells if Ogre was initialized without a render system (see {@see initOgreHeadless}).
+             *
+             * @return True if there is no render system.
+             */
+            bool IsHeadless() const{return _headless;}
+
             /**
              * Retrieves the Ogre system main component.
              *
@@ -144,9 +167,10 @@ namespace VGears{
              *
              * Each plugin is looked for in the directories given by {@see OgrePlugins::SearchDirectories}.
              *
+             * @param[in] skip_render_systems True to not load the render system plugins.
              * @throws std::runtime_error If the plugins file can't be read or a plugin is not found.
              */
-            void loadPlugins(void);
+            void loadPlugins(bool skip_render_systems = false);
 
             /**
              * Loads the resource configuration from  the file.
@@ -285,11 +309,38 @@ namespace VGears{
              */
             bool _initialized = false;
 
+            /**
+             * True if Ogre was initialized without a render system.
+             */
+            bool _headless = false;
+
+            /**
+             * Hardware buffer manager used without a render system, that keeps the buffers in system memory.
+             *
+             * It is declared before the root so it is destroyed after it: the meshes, destroyed with the root,
+             * notify the buffer manager when their buffers are released.
+             */
+            std::unique_ptr<Ogre::HardwareBufferManager> _buffer_manager;
+
+            /**
+             * Controller manager used without a render system, if the root didn't create one.
+             *
+             * Declared before the root for the same reason as the buffer manager.
+             */
+            std::unique_ptr<Ogre::ControllerManager> _controller_manager;
+
             /**
              * Ogre main component.
              */
             std::unique_ptr<Ogre::Root> _root;
 
+            /**
+             * Texture manager used without a render system. Materials can name textures, but no texture is created.
+             *
+             * Declared after the root so it is destroyed before it, as the texture manager of a render system is.
+             */
+            std::unique_ptr<Ogre::TextureManager> _texture_manager;
+
             /**
              *The ogre overlay system.
              */

+ 2 - 0
src/data/VGearsBackgroundFile.cpp

@@ -114,6 +114,8 @@ namespace VGears{
         );
         Ogre::MemoryDataStream *buffer(new Ogre::MemoryDataStream(memory_size));
         uint32 *color(reinterpret_cast<uint32*>(buffer->getPtr()));
+        // The tiles don't fill the image: what they don't cover must be transparent, not whatever was in memory.
+        memset(color, 0, memory_size);
 
         int dst_x(0), dst_y(0);
         int dst_x_16(0), dst_y_16(0);

+ 3 - 0
src/installer/CMakeLists.txt

@@ -8,13 +8,16 @@ find_package(Qt5 COMPONENTS Core REQUIRED)
 set(INSTALLER_SOURCE_FILES
     main.cpp
     BattleDataInstaller.cpp
+    CliInstaller.cpp
     DataInstaller.cpp
     DiskImage.cpp
     FieldDataInstaller.cpp
     FieldTextWriter.cpp
+    InstallCommandLine.cpp
     InstallLayout.cpp
     InstallLog.cpp
     InstallOptions.cpp
+    InstallSteps.cpp
     ExternalTools.cpp
     InstallVerifier.cpp
     VideoFiles.cpp

+ 452 - 0
src/installer/CliInstaller.cpp

@@ -0,0 +1,452 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <cmath>
+#include <cstdio>
+#include <memory>
+#include <QtCore/QDir>
+#include <QtCore/QFile>
+#include <QtCore/QFileInfo>
+#include "CliInstaller.h"
+#include "DataInstaller.h"
+#include "DiskImage.h"
+#include "ExternalTools.h"
+#include "InstallLog.h"
+#include "InstallSteps.h"
+#include "InstallVerifier.h"
+
+#ifndef VGEARS_INSTALLER_VERSION
+#define VGEARS_INSTALLER_VERSION "unknown"
+#endif
+
+namespace{
+
+    // The messages are written with stdio, not with std::cout or std::cerr: while the installation log is open it
+    // captures those streams, and the progress and the summary don't belong in the log.
+
+    /**
+     * Writes a line to the standard output.
+     */
+    void Print(const std::string& text){
+        std::fputs((text + "\n").c_str(), stdout);
+        std::fflush(stdout);
+    }
+
+    /**
+     * Writes a line to the standard error.
+     */
+    void PrintError(const std::string& text){
+        std::fflush(stdout);
+        std::fputs((text + "\n").c_str(), stderr);
+        std::fflush(stderr);
+    }
+
+    /**
+     * Writes a list of problems to the standard error.
+     *
+     * @param[in] title Line written before the list.
+     * @param[in] problems The problems.
+     */
+    void PrintList(const std::string& title, const QStringList& problems){
+        PrintError(title);
+        for (const QString& problem : problems) PrintError("  - " + problem.toStdString());
+    }
+
+    /**
+     * Shows the progress of a task, one line for each percent.
+     */
+    class ProgressPrinter{
+
+        public:
+
+            /**
+             * Shows the progress, if it has changed since it was last shown.
+             *
+             * @param[in] progress The progress [0-100].
+             */
+            void Show(float progress){
+                const int percent = static_cast<int>(std::floor(progress));
+                if (percent <= last_) return;
+                last_ = percent;
+                char line[32];
+                std::snprintf(line, sizeof(line), "[%3d%%]", percent);
+                Print(line);
+            }
+
+        private:
+
+            int last_ = -1;
+    };
+
+    /**
+     * Opens the installation log in the installation directory.
+     *
+     * Its messages are already echoed to the terminal by the log itself, so no sink is needed.
+     */
+    void OpenInstallLog(const QString& output, bool append){
+        InstallLog::Get().Open((output + "installer.log").toStdString(), append);
+    }
+
+    /**
+     * Closes the installation log, and writes a summary of the problems.
+     */
+    void CloseInstallLog(){
+        InstallLog& log = InstallLog::Get();
+        log.EndStep();
+        const size_t errors = log.Count(InstallLog::ERROR_LEVEL);
+        const size_t warnings = log.Count(InstallLog::WARNING);
+        const std::string path = log.Path();
+        log.Close();
+        Print("");
+        Print(std::to_string(errors) + " error(s), " + std::to_string(warnings) + " warning(s).");
+        for (const std::string& message : log.First(InstallLog::ERROR_LEVEL, 10)) Print("  " + message);
+        if (errors > 10) Print("  ...");
+        Print("The full log is in " + path);
+    }
+
+    /**
+     * Checks that the audio tools the installation needs can be used.
+     *
+     * @param[in] options What is installed.
+     * @param[in] output The installation directory.
+     * @param[in] yes True to continue without the tools.
+     * @return True if the installation can go on.
+     */
+    bool CheckTools(const InstallOptions& options, const QString& output, bool yes){
+        const ExternalTools::Locations& locations = ExternalTools::CurrentLocations();
+        const InstallRules::ToolNeeds needs = InstallRules::ToolsNeeded(options);
+        const ExternalTools::Tool ffmpeg = needs.ffmpeg ? ExternalTools::FindFfmpeg(locations) : ExternalTools::Tool();
+        const ExternalTools::Tool timidity
+          = needs.timidity ? ExternalTools::FindTimidity(locations) : ExternalTools::Tool();
+        const bool missing_ffmpeg = needs.ffmpeg && !ffmpeg.usable;
+        const bool missing_timidity = needs.timidity && !timidity.usable;
+        if (needs.ffmpeg && ffmpeg.usable) Print("FFmpeg: " + ffmpeg.path + " (" + ExternalTools::ShortVersion(ffmpeg) + ")");
+        if (needs.timidity && timidity.usable)
+            Print("TiMidity: " + timidity.path + " (" + ExternalTools::ShortVersion(timidity) + ")");
+        const std::vector<std::string> consequences
+          = InstallRules::ToolConsequences(options, !missing_ffmpeg, !missing_timidity);
+        if (consequences.empty()) return true;
+
+        QStringList reasons;
+        if (missing_ffmpeg) reasons << QString::fromStdString("FFmpeg: " + ffmpeg.problem);
+        if (missing_timidity) reasons << QString::fromStdString("TiMidity: " + timidity.problem);
+        QStringList lost;
+        for (const std::string& line : consequences) lost << QString::fromStdString(line);
+        PrintList("The installer needs programs it can't use:", reasons);
+        PrintList("Without them:", lost);
+        if (yes) return true;
+        PrintError("");
+        PrintError("Install them, copy them to " + QDir::toNativeSeparators(output + "tools").toStdString()
+          + ", or give their paths with --ffmpeg and --timidity.");
+#if defined(_WIN32)
+        PrintError("Windows: download a build of FFmpeg (ffmpeg.exe) from https://ffmpeg.org/download.html. "
+          "TiMidity++ also needs its timidity.cfg and instrument files next to timidity.exe.");
+#elif defined(__APPLE__)
+        PrintError("macOS: brew install ffmpeg timidity");
+#else
+        PrintError("Debian, Ubuntu: sudo apt install ffmpeg timidity");
+        PrintError("Fedora: sudo dnf install ffmpeg timidity++");
+        PrintError("Arch: sudo pacman -S ffmpeg timidity++");
+#endif
+        PrintError("To install without them, use --yes.");
+        return false;
+    }
+
+    /**
+     * Extracts the videos of a game disk.
+     *
+     * @param[in] disk_image The game disk.
+     * @param[in] output The installation directory.
+     * @return The exit status.
+     */
+    int ExtractVideos(DiskImage& disk_image, const QString& output){
+        const QStringList errors = InstallSteps::CheckVideoOutput(output);
+        if (!errors.isEmpty()){
+            PrintList("The extraction can't start:", errors);
+            return CliInstaller::EXIT_FAILED;
+        }
+        // The installation log of a previous run is kept.
+        OpenInstallLog(output, true);
+        InstallLog::Get().Add("Extracting the videos of " + disk_image.getId() + "...");
+        ProgressPrinter progress;
+        int extracted = 0;
+        int skipped = 0;
+        bool ok = false;
+        try{
+            ok = disk_image.extractVideos(
+              output.toStdString() + "data/", [&progress](float value){progress.Show(value);},
+              [](const std::string& message){InstallLog::Get().Add(message);}, &extracted, &skipped
+            );
+            if (ok) InstallSteps::ConvertMovies(output.toStdString() + "data/video/");
+        }
+        catch (const std::exception& ex){
+            InstallLog::Get().Add(std::string("[ERROR] Video extraction failed: ") + ex.what());
+            ok = false;
+        }
+        if (ok){
+            progress.Show(100);
+            InstallLog::Get().Add(
+              "Videos extracted: " + std::to_string(extracted) + " new, " + std::to_string(skipped)
+              + " already installed."
+            );
+        }
+        else InstallLog::Get().Add("[ERROR] Some videos could not be extracted.");
+        CloseInstallLog();
+        return ok ? CliInstaller::EXIT_OK : CliInstaller::EXIT_FAILED;
+    }
+
+    /**
+     * Installs the game from the install disk.
+     *
+     * @param[in] arguments The command line.
+     * @param[in] disk_image The install disk.
+     * @param[in] output The installation directory.
+     * @return The exit status.
+     */
+    int Install(const InstallCommandLine::Arguments& arguments, DiskImage& disk_image, const QString& output){
+        const InstallOptions& options = arguments.options;
+        bool anything = false;
+        for (const InstallCommandLine::Part& part : InstallCommandLine::Parts()) anything |= options.*(part.option);
+        if (!anything){
+            PrintError("Nothing to install. Choose a preset, or parts with --with.");
+            return CliInstaller::EXIT_USAGE;
+        }
+        Print("Installing:");
+        for (const InstallCommandLine::Part& part : InstallCommandLine::Parts())
+            if (options.*(part.option)) Print("  - " + std::string(part.description));
+
+        // The V-Gears data folder to copy.
+        QString game_data;
+        if (arguments.copy_data){
+            game_data = arguments.data_dir.empty()
+              ? InstallSteps::FindGameDataDir() : QDir::cleanPath(QString::fromStdString(arguments.data_dir));
+            if (game_data.isEmpty()){
+                PrintError("The V-Gears 'data' folder was not found. Give it with --data-dir.");
+                return CliInstaller::EXIT_FAILED;
+            }
+            Print("V-Gears data files: " + QDir::toNativeSeparators(game_data).toStdString());
+        }
+
+        // Check everything that can be checked before touching the disk.
+        InstallSteps::PreflightResult preflight
+          = InstallSteps::RunPreflight(disk_image, output, arguments.copy_data, game_data);
+        for (
+          const std::string& problem
+          : InstallRules::Problems(options, QFile::exists(output + "data/fields/_fields.xml"))
+        ) preflight.errors << QString::fromStdString(problem);
+        if (!preflight.errors.isEmpty()){
+            PrintList("The installation can't start:", preflight.errors);
+            return CliInstaller::EXIT_FAILED;
+        }
+        if (!preflight.warnings.isEmpty()){
+            PrintList("Warnings:", preflight.warnings);
+            if (!arguments.yes){
+                PrintError("To install anyway, use --yes.");
+                return CliInstaller::EXIT_FAILED;
+            }
+        }
+        // The audio is converted with external programs: say now, before anything is extracted, if they are missing.
+        if (!CheckTools(options, output, arguments.yes)) return CliInstaller::EXIT_FAILED;
+
+        Print("Extracting " + disk_image.getPath() + "...");
+        if (!disk_image.extractImage(output.toStdString())){
+            PrintError("Failed to extract the ISO image.");
+            return CliInstaller::EXIT_FAILED;
+        }
+        if (disk_image.getContentPath().empty()){
+            PrintError("The extracted data path is invalid.");
+            return CliInstaller::EXIT_FAILED;
+        }
+        const std::vector<std::string> missing_files = InstallSteps::MissingRequiredFiles(disk_image);
+        if (!missing_files.empty()){
+            QStringList names;
+            for (const std::string& file : missing_files) names << QString::fromStdString(file);
+            PrintList("Some of the required files were not found among the extracted data:", names);
+            return CliInstaller::EXIT_FAILED;
+        }
+        // Copy the V-Gears data files (scripts, screens, fonts...) to the installation directory.
+        if (arguments.copy_data){
+            Print("Copying the V-Gears data files...");
+            if (!InstallSteps::CopyDirectory(game_data, output)){
+                PrintError("Failed to copy the V-Gears data files to the installation directory.");
+                return CliInstaller::EXIT_FAILED;
+            }
+        }
+        // The installer's Ogre setup loads plugins.cfg and resources.cfg from the working directory (and writes
+        // install.log there), so run from the installation directory.
+        if (!QFile::exists(output + "plugins.cfg") || !QFile::exists(output + "resources.cfg")){
+            PrintError("The installation directory must contain plugins.cfg and resources.cfg. Don't use --no-copy-data.");
+            return CliInstaller::EXIT_FAILED;
+        }
+        if (!QDir::setCurrent(output)){
+            PrintError("Could not enter the installation directory.");
+            return CliInstaller::EXIT_FAILED;
+        }
+
+        OpenInstallLog(output, false);
+        if (options.videos){
+            InstallLog::Get().Add(
+              "[WARNING] The install disk has no videos. To extract them, run the installer again with game disk 1, "
+              "2 or 3 as the ISO."
+            );
+        }
+        const DataInstaller::AdvancedOptions advanced
+          = InstallSteps::ToAdvancedOptions(options, arguments.keep_originals);
+        const auto write_line = [](const std::string line, int, bool){InstallLog::Get().Add(line);};
+        std::string error;
+        ProgressPrinter progress;
+        try{
+            DataInstaller installer(disk_image, QDir::toNativeSeparators(output).toStdString(), advanced, write_line);
+            float value = 0;
+            while (value < 100){
+                value = installer.Progress();
+                progress.Show(value);
+            }
+        }
+        catch (const std::exception& ex){
+            error = ex.what();
+        }
+        catch (...){
+            error = "Unknown error";
+        }
+        if (!error.empty()) InstallLog::Get().Add("[ERROR] Installation failed: " + error);
+        CloseInstallLog();
+        if (!error.empty()) return CliInstaller::EXIT_FAILED;
+        Print("Installation finished in " + QDir::toNativeSeparators(output).toStdString());
+        return CliInstaller::EXIT_OK;
+    }
+
+    /**
+     * Gets the installation directory of the command line, or the default one.
+     *
+     * @return The directory, normalized. Empty if there is none.
+     */
+    QString OutputDir(const InstallCommandLine::Arguments& arguments){
+        const QString dir = arguments.output.empty()
+          ? InstallSteps::DefaultInstallDir() : QString::fromStdString(arguments.output);
+        return dir.isEmpty() ? QString() : InstallSteps::NormalizeOutputDir(dir);
+    }
+
+    /**
+     * Verifies an installation.
+     *
+     * @return The exit status.
+     */
+    int Verify(const InstallCommandLine::Arguments& arguments){
+        const QString output = OutputDir(arguments);
+        if (output.isEmpty() || !QDir(output).exists()){
+            PrintError("The installation directory does not exist: " + output.toStdString());
+            return CliInstaller::EXIT_FAILED;
+        }
+        const QString game_data = arguments.data_dir.empty()
+          ? InstallSteps::FindGameDataDir() : QString::fromStdString(arguments.data_dir);
+        Print("Verifying " + QDir::toNativeSeparators(output).toStdString() + "...");
+        const VerifyResult result = VerifyInstallation(output.toStdString(), game_data.toStdString());
+        if (result.Ok()){
+            Print("Everything the game needs is installed (" + std::to_string(result.checked) + " checks).");
+            return CliInstaller::EXIT_OK;
+        }
+        std::string group;
+        for (const VerifyProblem& problem : result.problems){
+            if (problem.group != group){
+                group = problem.group;
+                Print(group + ":");
+            }
+            Print("  - " + problem.message);
+        }
+        Print(
+          std::to_string(result.problems.size()) + " problem(s) in " + std::to_string(result.checked) + " checks. If "
+          "you skipped a part of the installation on purpose (for example the music), its files are expected to be "
+          "missing."
+        );
+        return CliInstaller::EXIT_FAILED;
+    }
+
+}
+
+namespace CliInstaller{
+
+    int Run(const InstallCommandLine::Arguments& arguments, const std::string& program){
+        switch (arguments.mode){
+            case InstallCommandLine::Mode::HELP:
+                std::fputs(InstallCommandLine::Usage(program).c_str(), stdout);
+                return EXIT_OK;
+            case InstallCommandLine::Mode::VERSION:
+                Print("V-Gears Installer " + std::string(VGEARS_INSTALLER_VERSION));
+                return EXIT_OK;
+            case InstallCommandLine::Mode::LIST_PARTS:
+                for (const InstallCommandLine::Part& part : InstallCommandLine::Parts()){
+                    char line[128];
+                    std::snprintf(line, sizeof(line), "%-18s %s", part.name, part.description);
+                    Print(line);
+                }
+                return EXIT_OK;
+            case InstallCommandLine::Mode::INVALID:
+                PrintError(arguments.error);
+                PrintError("Run '" + program + " --help' for the usage.");
+                return EXIT_USAGE;
+            case InstallCommandLine::Mode::VERIFY:
+                return Verify(arguments);
+            case InstallCommandLine::Mode::INSTALL:
+                break;
+            case InstallCommandLine::Mode::GUI:
+                PrintError("The installer window can't be opened from the command line installer.");
+                return EXIT_USAGE;
+        }
+
+        const QString output = OutputDir(arguments);
+        if (output.isEmpty()){
+            PrintError("No installation directory: give one with --output.");
+            return EXIT_USAGE;
+        }
+        Print("Installation directory: " + QDir::toNativeSeparators(output).toStdString());
+
+        // The paths given must be the programs, and work.
+        if (!arguments.ffmpeg.empty()){
+            const ExternalTools::Tool tool = ExternalTools::ProbeFfmpeg(arguments.ffmpeg);
+            if (!tool.usable){
+                PrintError("FFmpeg can't be used: " + tool.problem);
+                return EXIT_FAILED;
+            }
+        }
+        if (!arguments.timidity.empty()){
+            const ExternalTools::Tool tool = ExternalTools::ProbeTimidity(arguments.timidity);
+            if (!tool.usable){
+                PrintError("TiMidity can't be used: " + tool.problem);
+                return EXIT_FAILED;
+            }
+        }
+        InstallSteps::SetToolLocations(output, arguments.ffmpeg, arguments.timidity);
+
+        if (!QFileInfo(QString::fromStdString(arguments.iso)).isReadable()){
+            PrintError("The ISO image can't be read: " + arguments.iso);
+            return EXIT_FAILED;
+        }
+        // The working directory changes during installation, so the path must be absolute.
+        DiskImage disk_image(QFileInfo(QString::fromStdString(arguments.iso)).absoluteFilePath().toStdString());
+        Print("Disk: " + disk_image.getId());
+        if (!disk_image.isValid()){
+            PrintError("The ISO is not a valid Final Fantasy VII image: " + disk_image.getErrorMessage());
+            return EXIT_FAILED;
+        }
+        // A game disk only has videos: extract them, without the rest of the installation.
+        if (disk_image.isVideoDisk()){
+            Print("Game disk: only its videos will be extracted.");
+            return ExtractVideos(disk_image, output);
+        }
+        return Install(arguments, disk_image, output);
+    }
+
+}

+ 55 - 0
src/installer/CliInstaller.h

@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <string>
+#include "InstallCommandLine.h"
+
+/**
+ * The installer without its window: it installs, or verifies an installation, from the command line.
+ *
+ * It does the same steps as the installer window (see InstallSteps), and writes the same installer.log. Where the
+ * window asks, it stops, unless the user said to continue with --yes.
+ */
+namespace CliInstaller{
+
+    /**
+     * Exit status when everything went well.
+     */
+    const int EXIT_OK = 0;
+
+    /**
+     * Exit status when the installation or the verification failed.
+     */
+    const int EXIT_FAILED = 1;
+
+    /**
+     * Exit status when the command line is wrong.
+     */
+    const int EXIT_USAGE = 2;
+
+    /**
+     * Does what the command line asks.
+     *
+     * A QCoreApplication must exist. The mode of the arguments must not be GUI.
+     *
+     * @param[in] arguments The parsed command line.
+     * @param[in] program Name of the program, for the usage text.
+     * @return The exit status.
+     */
+    int Run(const InstallCommandLine::Arguments& arguments, const std::string& program);
+
+}

+ 2 - 1
src/installer/DataInstaller.cpp

@@ -34,7 +34,8 @@ DataInstaller::DataInstaller(
   disk_image_(disk_image), output_dir_(output_dir), data_dir_(InstallLayout::DataDir(output_dir)),
   options_(options), write_output_line_(write_output_line)
 {
-    if (!application_.initOgre(true)) throw std::runtime_error("Ogre init failure");
+    // The installer only converts data, so it needs no render system, no window and no display.
+    if (!application_.initOgreHeadless()) throw std::runtime_error("Ogre init failure");
     Ogre::Log* default_log(Ogre::LogManager::getSingleton().getDefaultLog());
     assert( default_log );
     default_log->setLogDetail(Ogre::LL_LOW);

+ 2 - 2
src/installer/DataInstaller.h

@@ -475,12 +475,12 @@ class DataInstaller{
         /**
          * Substeps in the current installation step.
          */
-        int substeps_;
+        int substeps_ = 0;
 
         /**
          * Current substep in the current installation step.
          */
-        int cur_substep_;
+        int cur_substep_ = 0;
 
         /**
          * Weight of each installation step.

+ 11 - 3
src/installer/ExternalTools.cpp

@@ -251,7 +251,12 @@ namespace ExternalTools{
     }
 
     std::vector<std::string> FfmpegArguments(const std::string& input, const std::string& output){
-        return {"-hide_banner", "-loglevel", "panic", "-y", "-i", input, output};
+        // Bit exact: without it the Ogg stream serial number is random, so every installation writes different
+        // files.
+        return {
+          "-hide_banner", "-loglevel", "panic", "-y", "-i", input, "-fflags", "+bitexact", "-flags:a", "+bitexact",
+          output
+        };
     }
 
     std::vector<std::string> FfmpegStdinArguments(const std::string& output){
@@ -263,7 +268,7 @@ namespace ExternalTools{
         return {
           "-hide_banner", "-loglevel", "panic", "-y", "-i", "-", "-af",
           "areverse,silenceremove=start_periods=1:start_duration=0:start_threshold=-50dB"
-          ":start_silence=0.3:detection=peak,areverse",
+          ":start_silence=0.3:detection=peak,areverse", "-fflags", "+bitexact", "-flags:a", "+bitexact",
           output
         };
     }
@@ -317,7 +322,10 @@ namespace ExternalTools{
         // The sound. Some movies have none.
         const std::string ogg = directory + "/" + name + ".ogg";
         const RunResult sound = Run(
-          ffmpeg, {"-hide_banner", "-loglevel", "panic", "-y", "-i", input, "-vn", ogg}, -1
+          ffmpeg,
+          {"-hide_banner", "-loglevel", "panic", "-y", "-i", input, "-vn", "-fflags", "+bitexact", "-flags:a",
+           "+bitexact", ogg},
+          -1
         );
         if (!sound.started || !sound.finished || sound.exit_code != 0 || fs::file_size(ogg, ec) == 0 || ec)
             fs::remove(ogg, ec);

+ 293 - 0
src/installer/InstallCommandLine.cpp

@@ -0,0 +1,293 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <sstream>
+#include "InstallCommandLine.h"
+
+namespace{
+
+    /**
+     * Name of a preset in the command line, and the preset.
+     */
+    struct PresetName{
+        const char* name;
+        InstallPreset preset;
+    };
+
+    const PresetName kPresets[] = {
+      {"everything", InstallPreset::EVERYTHING},
+      {"fields", InstallPreset::FIELDS},
+      {"world-map", InstallPreset::WORLD_MAP},
+      {"battle", InstallPreset::BATTLE},
+      {"media", InstallPreset::MEDIA},
+      {"custom", InstallPreset::CUSTOM}
+    };
+
+    /**
+     * Splits a comma separated list, skipping empty items.
+     */
+    std::vector<std::string> SplitList(const std::string& list){
+        std::vector<std::string> items;
+        std::stringstream stream(list);
+        std::string item;
+        while (std::getline(stream, item, ',')) if (!item.empty()) items.push_back(item);
+        return items;
+    }
+
+    /**
+     * Finds a part by name.
+     *
+     * @return The part, or nullptr if there is no part with that name.
+     */
+    const InstallCommandLine::Part* FindPart(const std::string& name){
+        for (const InstallCommandLine::Part& part : InstallCommandLine::Parts()) if (name == part.name) return &part;
+        return nullptr;
+    }
+
+    /**
+     * Gets the names of the parts, separated by commas.
+     */
+    std::string PartNames(){
+        std::string names;
+        for (const InstallCommandLine::Part& part : InstallCommandLine::Parts())
+            names += (names.empty() ? "" : ", ") + std::string(part.name);
+        return names;
+    }
+
+    /**
+     * Gets the names of the presets, separated by commas.
+     */
+    std::string PresetNames(){
+        std::string names;
+        for (const PresetName& preset : kPresets) names += (names.empty() ? "" : ", ") + std::string(preset.name);
+        return names;
+    }
+
+    /**
+     * Marks the command line as wrong.
+     */
+    InstallCommandLine::Arguments Invalid(const std::string& error){
+        InstallCommandLine::Arguments arguments;
+        arguments.mode = InstallCommandLine::Mode::INVALID;
+        arguments.error = error;
+        return arguments;
+    }
+
+}
+
+namespace InstallCommandLine{
+
+    const std::vector<Part>& Parts(){
+        static const std::vector<Part> parts = {
+          {"kernel", "Kernel data: items, materia, characters...", &InstallOptions::kernel},
+          {"fields", "Field maps", &InstallOptions::fields},
+          {"field-models", "Field 3D models (needs fields)", &InstallOptions::field_models},
+          {"world-map", "World map", &InstallOptions::wm},
+          {"world-map-models", "World map 3D models (needs world-map)", &InstallOptions::wm_models},
+          {"battle-data", "Battle scenes", &InstallOptions::battle_data},
+          {"battle-models", "Battle 3D models", &InstallOptions::battle_models},
+          {"images", "Images", &InstallOptions::images},
+          {"sounds", "Sound effects (needs FFmpeg)", &InstallOptions::sounds},
+          {"music", "Music (needs TiMidity and FFmpeg)", &InstallOptions::music},
+          {"videos", "Videos (only from game disks 1, 2 and 3; needs FFmpeg)", &InstallOptions::videos}
+        };
+        return parts;
+    }
+
+    Arguments Parse(const std::vector<std::string>& args){
+        Arguments arguments;
+        bool cli = false;
+        bool verify = false;
+        bool list_parts = false;
+        bool help = false;
+        bool version = false;
+        bool preset_given = false;
+        std::vector<std::string> added;
+        std::vector<std::string> removed;
+        std::vector<std::string> unknown;
+        for (size_t i = 0; i < args.size(); ++ i){
+            std::string arg = args[i];
+            // "--option=value" is the same as "--option value".
+            std::string inline_value;
+            bool has_inline_value = false;
+            const size_t equals = arg.find('=');
+            if (arg.compare(0, 2, "--") == 0 && equals != std::string::npos){
+                inline_value = arg.substr(equals + 1);
+                arg = arg.substr(0, equals);
+                has_inline_value = true;
+            }
+            // Reads the value of an option. Returns false if it is missing.
+            std::string value;
+            const auto take_value = [&](){
+                if (has_inline_value){
+                    value = inline_value;
+                    return true;
+                }
+                if (i + 1 >= args.size()) return false;
+                value = args[++ i];
+                return true;
+            };
+            const auto needs_value = [&](const std::string& name){return "Missing value for " + name + ".";};
+
+            if (arg == "--cli") cli = true;
+            else if (arg == "--verify") verify = cli = true;
+            else if (arg == "--list-parts") list_parts = true;
+            else if (arg == "-h" || arg == "--help") help = true;
+            else if (arg == "-v" || arg == "--version") version = true;
+            else if (arg == "-y" || arg == "--yes") arguments.yes = cli = true;
+            else if (arg == "--no-copy-data"){
+                arguments.copy_data = false;
+                cli = true;
+            }
+            else if (arg == "--discard-originals"){
+                arguments.keep_originals = false;
+                cli = true;
+            }
+            else if (arg == "-i" || arg == "--iso"){
+                if (!take_value()) return Invalid(needs_value(arg));
+                arguments.iso = value;
+                cli = true;
+            }
+            else if (arg == "-o" || arg == "--output"){
+                if (!take_value()) return Invalid(needs_value(arg));
+                arguments.output = value;
+                cli = true;
+            }
+            else if (arg == "--data-dir"){
+                if (!take_value()) return Invalid(needs_value(arg));
+                arguments.data_dir = value;
+                cli = true;
+            }
+            else if (arg == "--ffmpeg"){
+                if (!take_value()) return Invalid(needs_value(arg));
+                arguments.ffmpeg = value;
+                cli = true;
+            }
+            else if (arg == "--timidity"){
+                if (!take_value()) return Invalid(needs_value(arg));
+                arguments.timidity = value;
+                cli = true;
+            }
+            else if (arg == "-p" || arg == "--preset"){
+                if (!take_value()) return Invalid(needs_value(arg));
+                bool found = false;
+                for (const PresetName& preset : kPresets){
+                    if (value == preset.name){
+                        arguments.preset = preset.preset;
+                        found = true;
+                    }
+                }
+                if (!found) return Invalid("Unknown preset '" + value + "'. The presets are: " + PresetNames() + ".");
+                preset_given = cli = true;
+            }
+            else if (arg == "--with" || arg == "--without"){
+                if (!take_value()) return Invalid(needs_value(arg));
+                for (const std::string& name : SplitList(value)){
+                    if (FindPart(name) == nullptr)
+                        return Invalid("Unknown part '" + name + "'. The parts are: " + PartNames() + ".");
+                    (arg == "--with" ? added : removed).push_back(name);
+                }
+                cli = true;
+            }
+            else unknown.push_back(args[i]);
+        }
+
+        // Requests for information are answered whatever else is in the command line.
+        if (help){
+            arguments.mode = Mode::HELP;
+            return arguments;
+        }
+        if (version){
+            arguments.mode = Mode::VERSION;
+            return arguments;
+        }
+        if (list_parts){
+            arguments.mode = Mode::LIST_PARTS;
+            return arguments;
+        }
+        // Without installer options, the window is opened, and Qt gets the rest of the arguments.
+        if (!cli){
+            arguments.mode = Mode::GUI;
+            return arguments;
+        }
+        if (!unknown.empty()) return Invalid("Unknown argument '" + unknown.front() + "'.");
+
+        // The parts: those of the preset, plus those added, minus those removed. Like in the window, the presets
+        // don't include the videos: they are not on the install disk, and the game disks only have videos.
+        arguments.options = InstallRules::Preset(arguments.preset, false);
+        for (const std::string& name : added) arguments.options.*(FindPart(name)->option) = true;
+        for (const std::string& name : removed) arguments.options.*(FindPart(name)->option) = false;
+        const InstallOptions selectable = InstallRules::Selectable(arguments.options);
+        for (const std::string& name : added){
+            const Part* part = FindPart(name);
+            if (arguments.options.*(part->option) && !(selectable.*(part->option)))
+                return Invalid("The part '" + name + "' can't be installed: " + part->description + ".");
+        }
+        InstallRules::ApplyDependencies(arguments.options);
+
+        if (verify){
+            if (!arguments.iso.empty()) return Invalid("--verify checks an installation, it doesn't take an ISO.");
+            if (preset_given || !added.empty() || !removed.empty())
+                return Invalid("--verify checks everything; it doesn't take a preset or parts.");
+            arguments.mode = Mode::VERIFY;
+            return arguments;
+        }
+        if (arguments.iso.empty()) return Invalid("No ISO image given. Use --iso <file>.");
+        arguments.mode = Mode::INSTALL;
+        return arguments;
+    }
+
+    std::string Usage(const std::string& program){
+        std::stringstream usage;
+        usage
+          << "Usage:\n"
+          << "  " << program << "                      Open the installer window.\n"
+          << "  " << program << " --cli --iso <file> [options]\n"
+          << "                                         Install from the command line.\n"
+          << "  " << program << " --verify [--output <dir>]\n"
+          << "                                         Check that an installation has everything the game needs.\n"
+          << "\n"
+          << "Installation options:\n"
+          << "  -i, --iso <file>         The disk image. The install disk installs the game; game disks 1, 2\n"
+          << "                           and 3 only add their videos to an installation.\n"
+          << "  -o, --output <dir>       Installation directory. Default: the one the game reads.\n"
+          << "  -p, --preset <name>      What to install: " << PresetNames() << ".\n"
+          << "                           Default: everything. 'custom' starts with nothing.\n"
+          << "      --with <parts>       Install these parts too (comma separated).\n"
+          << "      --without <parts>    Don't install these parts (comma separated).\n"
+          << "      --no-copy-data       Don't copy the V-Gears data files: the installation directory\n"
+          << "                           must already have them.\n"
+          << "      --data-dir <dir>     The V-Gears 'data' folder to copy. Default: looked for next to\n"
+          << "                           the installer and in the system.\n"
+          << "      --discard-originals  Delete the original files once converted.\n"
+          << "      --ffmpeg <file>      Path to FFmpeg. Default: looked for in the 'tools' folder of the\n"
+          << "                           installation and of the installer, then in the PATH.\n"
+          << "      --timidity <file>    Path to TiMidity. Looked for like FFmpeg.\n"
+          << "  -y, --yes                Continue when there are warnings or the audio tools are missing.\n"
+          << "\n"
+          << "Other options:\n"
+          << "      --cli                Use the command line, not the window. Implied by any option above.\n"
+          << "      --list-parts         List the parts that can be installed.\n"
+          << "  -h, --help               Show this help.\n"
+          << "  -v, --version            Show the version.\n"
+          << "\n"
+          << "Parts: " << PartNames() << ".\n"
+          << "\n"
+          << "Exit status: 0 if everything went well, 1 if the installation or the verification failed,\n"
+          << "2 if the command line is wrong.\n";
+        return usage.str();
+    }
+
+}

+ 180 - 0
src/installer/InstallCommandLine.h

@@ -0,0 +1,180 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <string>
+#include <vector>
+#include "InstallOptions.h"
+
+/**
+ * Command line of the installer.
+ *
+ * Without arguments the installer opens its window. With "--cli", or any of the installation options, it installs
+ * from the command line instead.
+ */
+namespace InstallCommandLine{
+
+    /**
+     * What the installer must do.
+     */
+    enum class Mode{
+
+        /**
+         * Open the installer window.
+         */
+        GUI,
+
+        /**
+         * Install from the command line.
+         */
+        INSTALL,
+
+        /**
+         * Verify an installation from the command line.
+         */
+        VERIFY,
+
+        /**
+         * Print the list of installable parts.
+         */
+        LIST_PARTS,
+
+        /**
+         * Print the usage.
+         */
+        HELP,
+
+        /**
+         * Print the version.
+         */
+        VERSION,
+
+        /**
+         * The command line is wrong. The error is in Arguments::error.
+         */
+        INVALID
+    };
+
+    /**
+     * The parsed command line.
+     */
+    struct Arguments{
+
+        /**
+         * What to do.
+         */
+        Mode mode = Mode::GUI;
+
+        /**
+         * Why the command line is wrong, when the mode is INVALID.
+         */
+        std::string error;
+
+        /**
+         * Path of the disk image.
+         */
+        std::string iso;
+
+        /**
+         * Installation directory. Empty to use the default one.
+         */
+        std::string output;
+
+        /**
+         * The preset the options start from.
+         */
+        InstallPreset preset = InstallPreset::EVERYTHING;
+
+        /**
+         * The parts to install: the preset, with the parts added and removed by the user.
+         */
+        InstallOptions options;
+
+        /**
+         * True to copy the V-Gears data files (configuration, scripts...) to the installation directory.
+         */
+        bool copy_data = true;
+
+        /**
+         * Path to the V-Gears data folder to copy. Empty to look for it.
+         */
+        std::string data_dir;
+
+        /**
+         * True to keep the original data after converting it.
+         */
+        bool keep_originals = true;
+
+        /**
+         * Path to FFmpeg. Empty to look for it.
+         */
+        std::string ffmpeg;
+
+        /**
+         * Path to TiMidity. Empty to look for it.
+         */
+        std::string timidity;
+
+        /**
+         * True to continue when there are warnings or the audio tools are missing, instead of stopping.
+         */
+        bool yes = false;
+    };
+
+    /**
+     * Name and description of an installable part.
+     */
+    struct Part{
+
+        /**
+         * Name used in the command line.
+         */
+        const char* name;
+
+        /**
+         * Description shown to the user.
+         */
+        const char* description;
+
+        /**
+         * The option of the part.
+         */
+        bool InstallOptions::* option;
+    };
+
+    /**
+     * Gets the installable parts.
+     */
+    const std::vector<Part>& Parts();
+
+    /**
+     * Parses the command line.
+     *
+     * Arguments that are not installer options are left for Qt when the window is opened (for example "-platform"),
+     * and are an error from the command line.
+     *
+     * @param[in] args The arguments, without the program name.
+     */
+    Arguments Parse(const std::vector<std::string>& args);
+
+    /**
+     * Gets the usage text.
+     *
+     * @param[in] program Name of the program.
+     */
+    std::string Usage(const std::string& program);
+
+}

+ 289 - 0
src/installer/InstallSteps.cpp

@@ -0,0 +1,289 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <iostream>
+#include <boost/filesystem.hpp>
+#include <QtCore/QCoreApplication>
+#include <QtCore/QDir>
+#include <QtCore/QDirIterator>
+#include <QtCore/QFile>
+#include <QtCore/QFileInfo>
+#include <QtCore/QObject>
+#include <QtCore/QStorageInfo>
+#include <OgrePrerequisites.h>
+#include "common/DataDirectory.h"
+#include "common/OgrePlugins.h"
+#include "ExternalTools.h"
+#include "InstallLog.h"
+#include "InstallSteps.h"
+#include "MovieCamera.h"
+
+#ifndef VGEARS_OGRE_PLUGIN_DIR
+#define VGEARS_OGRE_PLUGIN_DIR ""
+#endif
+
+namespace{
+
+    /**
+     * Minimum free space needed besides the ISO extraction: converted data, intermediate files and logs.
+     */
+    const qint64 kRequiredFreeSpace = 3LL * 1024 * 1024 * 1024;
+
+    /**
+     * Free space needed to extract the videos of a game disk.
+     */
+    const qint64 kRequiredVideoSpace = 1024LL * 1024 * 1024;
+
+    /**
+     * Checks that a directory can be created and written, and that it has enough free space.
+     *
+     * @param[in] output The directory, ending with '/'.
+     * @param[in] needed Free space needed, in bytes.
+     * @param[out] errors The problems found are added here.
+     */
+    void CheckWritable(const QString& output, qint64 needed, QStringList& errors){
+        if (!QDir().mkpath(output)){
+            errors << QObject::tr("The installation directory can't be created: %1").arg(output);
+            return;
+        }
+        QFile probe(output + ".v-gears-write-test");
+        if (!probe.open(QIODevice::WriteOnly))
+            errors << QObject::tr("The installation directory is not writable: %1").arg(output);
+        else{
+            probe.close();
+            probe.remove();
+        }
+        const QStorageInfo storage(output);
+        if (storage.isValid() && storage.bytesAvailable() < needed){
+            errors << QObject::tr("Not enough free space in %1: %2 MB available, about %3 MB needed.")
+              .arg(storage.rootPath()).arg(storage.bytesAvailable() / (1024 * 1024)).arg(needed / (1024 * 1024));
+        }
+    }
+
+    /**
+     * Names of the plugins in the plugins.cfg of a folder that the game won't find.
+     *
+     * The game looks for them in the same places (see VGears::OgrePlugins::SearchDirectories), so they don't need to
+     * be copied to the installation directory.
+     */
+    QStringList MissingOgrePlugins(const QString& source_dir){
+        namespace bfs = boost::filesystem;
+        QStringList missing;
+        const bfs::path dir(source_dir.toStdString());
+        VGears::OgrePlugins::Config config;
+        if (!VGears::OgrePlugins::ReadConfig(dir / "plugins.cfg", config)) return missing;
+        const std::vector<bfs::path> directories = VGears::OgrePlugins::SearchDirectories(
+          dir, config.folder, bfs::path(QCoreApplication::applicationDirPath().toStdString()), VGEARS_OGRE_PLUGIN_DIR
+        );
+        const std::string version = std::to_string(OGRE_VERSION_MAJOR) + "." + std::to_string(OGRE_VERSION_MINOR)
+          + "." + std::to_string(OGRE_VERSION_PATCH);
+        for (const std::string& name : config.plugins){
+            if (VGears::OgrePlugins::Find(name, directories, version).empty()) missing << QString::fromStdString(name);
+        }
+        return missing;
+    }
+
+}
+
+namespace InstallSteps{
+
+    QString DefaultInstallDir(){
+        const boost::filesystem::path dir = VGears::DataDirectory::DefaultDirectory();
+        return dir.empty() ? QString() : QDir::fromNativeSeparators(QString::fromStdString(dir.string()));
+    }
+
+    QString NormalizeOutputDir(const QString& dir){
+        QString output = QDir::fromNativeSeparators(dir);
+        if (QDir::isRelativePath(output)) output = QDir(output).absolutePath();
+        if (!output.endsWith("/")) output += "/";
+        return output;
+    }
+
+    QString FindGameDataDir(){
+        // The same places the game copies its files from when the data directory is empty, then the current directory.
+        std::vector<boost::filesystem::path> candidates = VGears::DataDirectory::TemplateCandidates(
+          boost::filesystem::path(QCoreApplication::applicationDirPath().toStdString())
+        );
+        candidates.emplace_back((QDir::currentPath() + "/data").toStdString());
+        candidates.emplace_back((QDir::currentPath() + "/../data").toStdString());
+        const boost::filesystem::path found = VGears::DataDirectory::FindTemplate(candidates, boost::filesystem::path());
+        return found.empty() ? QString() : QDir::cleanPath(QString::fromStdString(found.string()));
+    }
+
+    PreflightResult RunPreflight(
+      DiskImage& disk_image, const QString& output, bool copy_data, const QString& game_data_dir
+    ){
+        PreflightResult result;
+        const QString iso_path = QString::fromStdString(disk_image.getPath());
+
+        // Input.
+        if (iso_path.isEmpty()) result.errors << QObject::tr("No ISO image selected.");
+        else if (!QFileInfo(iso_path).isReadable())
+            result.errors << QObject::tr("The ISO image can't be read: %1").arg(iso_path);
+        else if (!disk_image.isValid())
+            result.errors << QObject::tr("The selected ISO is not a valid Final Fantasy VII image.");
+        else if (!disk_image.isSupported())
+            result.warnings << QString::fromStdString(disk_image.getWarningMessage());
+
+        // Output: it must be creatable and writable, with room for the extracted ISO plus the converted data.
+        CheckWritable(
+          output, kRequiredFreeSpace + (iso_path.isEmpty() ? 0 : QFileInfo(iso_path).size()), result.errors
+        );
+
+        // Configuration and plugins.
+        if (copy_data){
+            if (
+              game_data_dir.isEmpty() || !QFile::exists(game_data_dir + "/plugins.cfg")
+              || !QDir(game_data_dir + "/data").exists()
+            ){
+                result.errors << QObject::tr(
+                  "The V-Gears 'data' folder was not found (it must contain plugins.cfg and a data folder)."
+                );
+            }
+            else{
+                const QStringList missing = MissingOgrePlugins(game_data_dir);
+                if (!missing.isEmpty()){
+                    result.errors << QObject::tr("Ogre plugins not found in the data folder or the system: %1")
+                      .arg(missing.join(", "));
+                }
+            }
+        }
+        else{
+            if (!QFile::exists(output + "plugins.cfg") || !QFile::exists(output + "resources.cfg")){
+                result.errors << QObject::tr(
+                  "The installation directory has no plugins.cfg and resources.cfg. Enable 'Copy V-Gears data files'."
+                );
+            }
+            else{
+                const QStringList missing = MissingOgrePlugins(output);
+                if (!missing.isEmpty()){
+                    result.errors << QObject::tr(
+                      "Ogre plugins not found in the installation directory or the system: %1"
+                    ).arg(missing.join(", "));
+                }
+            }
+        }
+        return result;
+    }
+
+    QStringList CheckVideoOutput(const QString& output){
+        QStringList errors;
+        CheckWritable(output, kRequiredVideoSpace, errors);
+        return errors;
+    }
+
+    bool CopyDirectory(const QString& src, const QString& dst){
+        const QDir src_dir(src);
+        if (!QDir().mkpath(dst)) return false;
+        bool ok = true;
+        QDirIterator it(src, QDir::Files | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
+        while (it.hasNext()){
+            const QString file = it.next();
+            const QString target = dst + "/" + src_dir.relativeFilePath(file);
+            QDir().mkpath(QFileInfo(target).absolutePath());
+            if (QFile::exists(target)) QFile::remove(target);
+            if (!QFile::copy(file, target)){
+                std::cout << "Could not copy " << file.toStdString() << " to " << target.toStdString() << std::endl;
+                ok = false;
+            }
+        }
+        return ok;
+    }
+
+    std::vector<std::string> MissingRequiredFiles(DiskImage& disk_image){
+        // TODO: Enumerate files or find some better way to do this.
+        static const std::vector<std::string> required_files = {
+          "data/field/char.lgp",
+          "data/field/flevel.lgp",
+          "data/kernel/KERNEL.BIN",
+          "data/menu/menu_us.lgp",
+          "data/sound/audio.fmt",
+          "data/sound/audio.dat",
+          "data/music/music.idx",
+          "data/midi/midi.lgp",
+          "data/battle/scene.bin",
+          "data/battle/battle.lgp",
+          "data/battle/magic.lgp",
+          "data/wm/WM0.MAP",
+          "data/wm/WM2.MAP",
+          "data/wm/WM3.MAP",
+          "data/wm/world_us.lgp",
+          "ff7.exe"
+        };
+        std::vector<std::string> missing;
+        for (const std::string& file : required_files){
+            std::cout << "Checking for required file: " << file << std::endl;
+            if (!disk_image.filePath(file)) missing.push_back(file);
+        }
+        return missing;
+    }
+
+    void ConvertMovies(const std::string& video_dir){
+        const ExternalTools::Tool ffmpeg = ExternalTools::FindFfmpeg(ExternalTools::CurrentLocations());
+        if (!ffmpeg.usable){
+            InstallLog::Get().Add(
+              "[WARNING] FFmpeg can't be used, so the videos are not converted and the game can't play them: "
+              + ffmpeg.problem
+            );
+            return;
+        }
+        QDir directory(QString::fromStdString(video_dir));
+        for (const QString& file : directory.entryList({"*.avi"}, QDir::Files)){
+            const std::string name = QFileInfo(file).completeBaseName().toStdString();
+            const std::string destination = video_dir + name;
+            if (QFileInfo::exists(QString::fromStdString(destination + "/movie.xml"))) continue;
+            InstallLog::Get().Add("Converting " + name + ".avi...");
+            std::string error;
+            if (ExternalTools::ConvertMovie(
+                  ffmpeg.path, video_dir + file.toStdString(), destination, name,
+                  MovieCamera::LoadCamera(video_dir + "moviecam.lgp", name), &error
+                ))
+                InstallLog::Get().Add("Converted " + name);
+            else InstallLog::Get().Add("[WARNING] Could not convert " + name + ": " + error);
+        }
+    }
+
+    void SetToolLocations(const QString& install_dir, const std::string& ffmpeg, const std::string& timidity){
+        QString dir = QDir::fromNativeSeparators(install_dir);
+        if (!dir.isEmpty() && !dir.endsWith("/")) dir += "/";
+        ExternalTools::Locations& tools = ExternalTools::CurrentLocations();
+        tools.ffmpeg = ffmpeg;
+        tools.timidity = timidity;
+        const QString app_dir = QCoreApplication::applicationDirPath();
+        tools.directories.clear();
+        if (!dir.isEmpty()) tools.directories.push_back((dir + "tools").toStdString());
+        tools.directories.push_back((app_dir + "/tools").toStdString());
+        tools.directories.push_back(app_dir.toStdString());
+    }
+
+    DataInstaller::AdvancedOptions ToAdvancedOptions(const InstallOptions& options, bool keep_originals){
+        DataInstaller::AdvancedOptions advanced;
+        advanced.battle_data = options.battle_data;
+        advanced.battle_models = options.battle_models;
+        advanced.kernel = options.kernel;
+        advanced.images = options.images;
+        advanced.sounds = options.sounds;
+        advanced.music = options.music;
+        advanced.videos = false;
+        advanced.fields = options.fields;
+        advanced.field_models = options.fields && options.field_models;
+        advanced.wm = options.wm;
+        advanced.wm_models = options.wm && options.wm_models;
+        advanced.keep_originals = keep_originals;
+        advanced.clean_install = false;
+        return advanced;
+    }
+
+}

+ 139 - 0
src/installer/InstallSteps.h

@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <string>
+#include <vector>
+#include <QtCore/QString>
+#include <QtCore/QStringList>
+#include "DataInstaller.h"
+#include "DiskImage.h"
+#include "InstallOptions.h"
+
+/**
+ * Steps of an installation that don't depend on the user interface.
+ *
+ * They are shared by the installer window and the command line installer, so both install in the same way.
+ */
+namespace InstallSteps{
+
+    /**
+     * Result of the checks done before starting an installation.
+     */
+    struct PreflightResult{
+
+        /**
+         * Problems that prevent the installation.
+         */
+        QStringList errors;
+
+        /**
+         * Problems that the user can choose to ignore.
+         */
+        QStringList warnings;
+    };
+
+    /**
+     * Gets the default installation directory, the one the game reads its data from.
+     */
+    QString DefaultInstallDir();
+
+    /**
+     * Normalizes an installation directory: absolute, with '/' separators, and ending with '/'.
+     *
+     * The working directory changes during installation, so the path must be absolute.
+     */
+    QString NormalizeOutputDir(const QString& dir);
+
+    /**
+     * Finds the V-Gears "data" folder shipped with the game.
+     *
+     * It contains the configuration files and plugins (copied to the installation directory) and a "data" subfolder
+     * with the game data (copied to <installation directory>/data).
+     *
+     * @return Path of the folder, or an empty string if it can't be found.
+     */
+    QString FindGameDataDir();
+
+    /**
+     * Checks that an installation can succeed before anything is extracted or written.
+     *
+     * @param[in] disk_image The selected disk image.
+     * @param[in] output Absolute installation directory, ending with '/'.
+     * @param[in] copy_data True if the V-Gears data files will be copied.
+     * @param[in] game_data_dir The V-Gears "data" folder to copy (only used if copy_data is true).
+     */
+    PreflightResult RunPreflight(
+      DiskImage& disk_image, const QString& output, bool copy_data, const QString& game_data_dir
+    );
+
+    /**
+     * Checks that the videos of a game disk can be extracted to a directory.
+     *
+     * Only the output directory is needed: no plugins, no configuration, no Ogre.
+     *
+     * @param[in] output Absolute installation directory, ending with '/'.
+     * @return The problems found. Empty if the extraction can start.
+     */
+    QStringList CheckVideoOutput(const QString& output);
+
+    /**
+     * Recursively copies a directory, overwriting existing files.
+     *
+     * @return True if every file was copied.
+     */
+    bool CopyDirectory(const QString& src, const QString& dst);
+
+    /**
+     * Gets the files the installer needs that are not in an extracted install disk.
+     *
+     * @param[in] disk_image The disk image, already extracted.
+     * @return Paths of the missing files, relative to the disk. Empty if everything is there.
+     */
+    std::vector<std::string> MissingRequiredFiles(DiskImage& disk_image);
+
+    /**
+     * Converts the movies in a folder to what the game plays: frames and sound. The game can't
+     * decode the original videos. The movies that already have a converted folder are skipped,
+     * and the originals are kept so they are not extracted again.
+     *
+     * @param[in] video_dir Folder with the extracted movies.
+     */
+    void ConvertMovies(const std::string& video_dir);
+
+    /**
+     * Sets where FFmpeg and TiMidity are looked for.
+     *
+     * The order is: the paths given, a "tools" folder in the installation directory, a "tools" folder next to the
+     * installer, the installer folder, and the system PATH.
+     *
+     * @param[in] install_dir The installation directory. It can be empty.
+     * @param[in] ffmpeg Path to FFmpeg chosen by the user. It can be empty.
+     * @param[in] timidity Path to TiMidity chosen by the user. It can be empty.
+     */
+    void SetToolLocations(const QString& install_dir, const std::string& ffmpeg, const std::string& timidity);
+
+    /**
+     * Converts the options of an installation to the options of the data installer.
+     *
+     * Videos are not installed by the data installer: they are extracted from the game disks.
+     *
+     * @param[in] options The options of the installation.
+     * @param[in] keep_originals True to keep the original data after converting it.
+     */
+    DataInstaller::AdvancedOptions ToAdvancedOptions(const InstallOptions& options, bool keep_originals);
+
+}

+ 27 - 259
src/installer/MainWindow.cpp

@@ -45,193 +45,17 @@
 #include "InstallLayout.h"
 #include "InstallLog.h"
 #include "InstallOptions.h"
+#include "InstallSteps.h"
 #include "InstallVerifier.h"
 #include "MainWindow.h"
 #include "MovieCamera.h"
 #include <ui_MainWindow.h>
 
-namespace{
-
-    /**
-     * Converts the movies in a folder to what the game plays: frames and sound. The game can't
-     * decode the original videos. The movies that already have a converted folder are skipped,
-     * and the originals are kept so they are not extracted again.
-     *
-     * @param[in] video_dir Folder with the extracted movies.
-     */
-    void ConvertMovies(const std::string& video_dir){
-        const ExternalTools::Tool ffmpeg = ExternalTools::FindFfmpeg(ExternalTools::CurrentLocations());
-        if (!ffmpeg.usable){
-            InstallLog::Get().Add(
-              "[WARNING] FFmpeg can't be used, so the videos are not converted and the game can't play them: "
-              + ffmpeg.problem
-            );
-            return;
-        }
-        QDir directory(QString::fromStdString(video_dir));
-        for (const QString& file : directory.entryList({"*.avi"}, QDir::Files)){
-            const std::string name = QFileInfo(file).completeBaseName().toStdString();
-            const std::string destination = video_dir + name;
-            if (QFileInfo::exists(QString::fromStdString(destination + "/movie.xml"))) continue;
-            InstallLog::Get().Add("Converting " + name + ".avi...");
-            std::string error;
-            if (ExternalTools::ConvertMovie(
-                  ffmpeg.path, video_dir + file.toStdString(), destination, name,
-                  MovieCamera::LoadCamera(video_dir + "moviecam.lgp", name), &error
-                ))
-                InstallLog::Get().Add("Converted " + name);
-            else InstallLog::Get().Add("[WARNING] Could not convert " + name + ": " + error);
-        }
-    }
-}
-
 /**
  * Indicates if an installer has already been created.
  */
 static bool installer_created = false;
 
-/**
- * Finds the V-Gears "data" folder shipped with the game.
- *
- * It contains the configuration files and plugins (copied to the installation directory) and a "data" subfolder with
- * the game data (copied to <installation directory>/data).
- *
- * @return Path of the folder, or an empty string if it can't be found.
- */
-static QString FindGameDataDir(){
-    // The same places the game copies its files from when the data directory is empty, then the current directory.
-    std::vector<boost::filesystem::path> candidates = VGears::DataDirectory::TemplateCandidates(
-      boost::filesystem::path(QCoreApplication::applicationDirPath().toStdString())
-    );
-    candidates.emplace_back((QDir::currentPath() + "/data").toStdString());
-    candidates.emplace_back((QDir::currentPath() + "/../data").toStdString());
-    const boost::filesystem::path found = VGears::DataDirectory::FindTemplate(candidates, boost::filesystem::path());
-    return found.empty() ? QString() : QDir::cleanPath(QString::fromStdString(found.string()));
-}
-
-#ifndef VGEARS_OGRE_PLUGIN_DIR
-#define VGEARS_OGRE_PLUGIN_DIR ""
-#endif
-
-/**
- * Names of the plugins in the plugins.cfg of a folder that the game won't find.
- *
- * The game looks for them in the same places (see VGears::OgrePlugins::SearchDirectories), so they don't need to be
- * copied to the installation directory.
- */
-static QStringList MissingOgrePlugins(const QString& source_dir){
-    namespace bfs = boost::filesystem;
-    QStringList missing;
-    const bfs::path dir(source_dir.toStdString());
-    VGears::OgrePlugins::Config config;
-    if (!VGears::OgrePlugins::ReadConfig(dir / "plugins.cfg", config)) return missing;
-    const std::vector<bfs::path> directories = VGears::OgrePlugins::SearchDirectories(
-      dir, config.folder, bfs::path(QCoreApplication::applicationDirPath().toStdString()), VGEARS_OGRE_PLUGIN_DIR
-    );
-    const std::string version = std::to_string(OGRE_VERSION_MAJOR) + "." + std::to_string(OGRE_VERSION_MINOR) + "."
-      + std::to_string(OGRE_VERSION_PATCH);
-    for (const std::string& name : config.plugins){
-        if (VGears::OgrePlugins::Find(name, directories, version).empty()) missing << QString::fromStdString(name);
-    }
-    return missing;
-}
-
-/**
- * Minimum free space needed besides the ISO extraction: converted data, intermediate files and logs.
- */
-static const qint64 kRequiredFreeSpace = 3LL * 1024 * 1024 * 1024;
-
-/**
- * Result of the checks done before starting an installation.
- */
-struct PreflightResult{
-    QStringList errors;
-    QStringList warnings;
-};
-
-/**
- * Checks that an installation can succeed before anything is extracted or written.
- *
- * @param[in] disk_image The selected disk image.
- * @param[in] output Absolute installation directory, ending with '/'.
- * @param[in] copy_data True if the V-Gears data files will be copied.
- * @param[in] game_data_dir The V-Gears "data" folder to copy (only used if copy_data is true).
- */
-static PreflightResult RunPreflight(
-  DiskImage& disk_image, const QString& output, bool copy_data, const QString& game_data_dir
-){
-    PreflightResult result;
-    const QString iso_path = QString::fromStdString(disk_image.getPath());
-
-    // Input.
-    if (iso_path.isEmpty()) result.errors << QObject::tr("No ISO image selected.");
-    else if (!QFileInfo(iso_path).isReadable()) result.errors << QObject::tr("The ISO image can't be read: %1").arg(iso_path);
-    else if (!disk_image.isValid()) result.errors << QObject::tr("The selected ISO is not a valid Final Fantasy VII image.");
-    else if (!disk_image.isSupported()) result.warnings << QString::fromStdString(disk_image.getWarningMessage());
-
-    // Output: it must be creatable and writable.
-    if (!QDir().mkpath(output)) result.errors << QObject::tr("The installation directory can't be created: %1").arg(output);
-    else{
-        QFile probe(output + ".v-gears-write-test");
-        if (!probe.open(QIODevice::WriteOnly)) result.errors << QObject::tr("The installation directory is not writable: %1").arg(output);
-        else{
-            probe.close();
-            probe.remove();
-        }
-        // Free space: the extracted ISO plus the converted data.
-        QStorageInfo storage(output);
-        const qint64 needed = kRequiredFreeSpace + (iso_path.isEmpty() ? 0 : QFileInfo(iso_path).size());
-        if (storage.isValid() && storage.bytesAvailable() < needed){
-            result.errors << QObject::tr("Not enough free space in %1: %2 MB available, about %3 MB needed.")
-              .arg(storage.rootPath()).arg(storage.bytesAvailable() / (1024 * 1024)).arg(needed / (1024 * 1024));
-        }
-    }
-
-    // Configuration and plugins.
-    if (copy_data){
-        if (game_data_dir.isEmpty() || !QFile::exists(game_data_dir + "/plugins.cfg") || !QDir(game_data_dir + "/data").exists())
-            result.errors << QObject::tr("The V-Gears 'data' folder was not found (it must contain plugins.cfg and a data folder).");
-        else{
-            const QStringList missing = MissingOgrePlugins(game_data_dir);
-            if (!missing.isEmpty())
-                result.errors << QObject::tr("Ogre plugins not found in the data folder or the system: %1").arg(missing.join(", "));
-        }
-    }
-    else{
-        if (!QFile::exists(output + "plugins.cfg") || !QFile::exists(output + "resources.cfg"))
-            result.errors << QObject::tr("The installation directory has no plugins.cfg and resources.cfg. Enable 'Copy V-Gears data files'.");
-        else{
-            const QStringList missing = MissingOgrePlugins(output);
-            if (!missing.isEmpty())
-                result.errors << QObject::tr("Ogre plugins not found in the installation directory or the system: %1").arg(missing.join(", "));
-        }
-    }
-    return result;
-}
-
-/**
- * Recursively copies a directory, overwriting existing files.
- *
- * @return True if every file was copied.
- */
-static bool CopyDirectory(const QString& src, const QString& dst){
-    const QDir src_dir(src);
-    if (!QDir().mkpath(dst)) return false;
-    bool ok = true;
-    QDirIterator it(src, QDir::Files | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
-    while (it.hasNext()){
-        const QString file = it.next();
-        const QString target = dst + "/" + src_dir.relativeFilePath(file);
-        QDir().mkpath(QFileInfo(target).absolutePath());
-        if (QFile::exists(target)) QFile::remove(target);
-        if (!QFile::copy(file, target)){
-            std::cout << "Could not copy " << file.toStdString() << " to " << target.toStdString() << std::endl;
-            ok = false;
-        }
-    }
-    return ok;
-}
-
 MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), main_window_(new Ui::MainWindow){
     main_window_->setupUi(this);
     main_window_->advancedOptions->setVisible(main_window_->chk_advanced_options->isChecked());
@@ -411,7 +235,7 @@ void MainWindow::on_btn_verify_clicked(){
         QMessageBox::warning(this, tr("Verify install"), tr("The installation directory does not exist: %1").arg(dir));
         return;
     }
-    const VerifyResult result = VerifyInstallation(dir.toStdString(), FindGameDataDir().toStdString());
+    const VerifyResult result = VerifyInstallation(dir.toStdString(), InstallSteps::FindGameDataDir().toStdString());
     // The game can start if its configuration and the V-Gears data files are there.
     bool can_launch = true;
     QString text;
@@ -615,10 +439,7 @@ void MainWindow::on_btn_data_run_clicked(){
         return;
     }
     // Normalize the output path.
-    QString output = QDir::fromNativeSeparators(main_window_->line_data_dst->text());
-    if (!output.endsWith("/")) output += "/";
-    // The working directory changes during installation, so the path must be absolute.
-    if (QDir::isRelativePath(output)) output = QDir(output).absolutePath() + "/";
+    const QString output = InstallSteps::NormalizeOutputDir(main_window_->line_data_dst->text());
 
     // A game disk only has videos: extract them, without the rest of the installation.
     if (disk_image_.isValid() && disk_image_.isVideoDisk()){
@@ -630,7 +451,7 @@ void MainWindow::on_btn_data_run_clicked(){
     const bool copy_data = main_window_->chk_copy_data->checkState() == Qt::Checked;
     QString game_data;
     if (copy_data){
-        game_data = FindGameDataDir();
+        game_data = InstallSteps::FindGameDataDir();
         if (game_data.isEmpty()){
             game_data = QFileDialog::getExistingDirectory(
               this, tr("Select the V-Gears 'data' folder to copy"), QCoreApplication::applicationDirPath()
@@ -640,7 +461,7 @@ void MainWindow::on_btn_data_run_clicked(){
     }
 
     // Check everything that can be checked before touching the disk.
-    PreflightResult preflight = RunPreflight(disk_image_, output, copy_data, game_data);
+    InstallSteps::PreflightResult preflight = InstallSteps::RunPreflight(disk_image_, output, copy_data, game_data);
     for (const std::string& problem : InstallRules::Problems(CurrentOptions(), QFile::exists(output + "data/fields/_fields.xml")))
         preflight.errors << QString::fromStdString(problem);
     if (!preflight.errors.isEmpty()){
@@ -673,44 +494,23 @@ void MainWindow::on_btn_data_run_clicked(){
       }
       if (!input.endsWith("/")) input += "/";
 
-        // TODO: Enumerate files or find some better way to do this.
-        const std::vector<std::string> required_files = {
-          "data/field/char.lgp",
-          "data/field/flevel.lgp",
-          "data/kernel/KERNEL.BIN",
-          "data/menu/menu_us.lgp",
-          "data/sound/audio.fmt",
-          "data/sound/audio.dat",
-          "data/music/music.idx",
-          "data/midi/midi.lgp",
-          "data/battle/scene.bin",
-          "data/battle/battle.lgp",
-          "data/battle/magic.lgp",
-          "data/wm/WM0.MAP",
-          "data/wm/WM2.MAP",
-          "data/wm/WM3.MAP",
-          "data/wm/world_us.lgp",
-          "ff7.exe"
-        };
-
         // Ensure required files are in the input dir
-        for (auto& file : required_files){
-            std::cout << "Checking for required file: " << file << std::endl;
-            const auto matched_file = disk_image_.filePath(file);
-            if (!matched_file){
-                QMessageBox::critical(
-                  this, tr("Missing input file"),
-                  tr("Some of the required files were not found among the extracted data.\n\nMake sure that the file '")
-                    + file.c_str() + tr("' is in the extracted data.")
-                );
-                return;
-            }
+        const std::vector<std::string> missing_files = InstallSteps::MissingRequiredFiles(disk_image_);
+        if (!missing_files.empty()){
+            QStringList names;
+            for (const std::string& file : missing_files) names << QString::fromStdString(file);
+            QMessageBox::critical(
+              this, tr("Missing input file"),
+              tr("Some of the required files were not found among the extracted data.\n\nMake sure that these "
+                 "files are in the extracted data:\n\n%1").arg(names.join("\n"))
+            );
+            return;
         }
         // Copy the V-Gears data files (scripts, screens, fonts...) to the installation directory.
         if (copy_data){
             main_window_->data_log->append(tr("Copying data files from %1...").arg(game_data));
             // Everything in the folder goes to the installation directory, and its "data" subfolder to <dir>/data.
-            if (!CopyDirectory(game_data, output)){
+            if (!InstallSteps::CopyDirectory(game_data, output)){
                 QMessageBox::critical(
                   this, tr("Copy error"), tr("Failed to copy the V-Gears data files to the installation directory.")
                 );
@@ -747,25 +547,15 @@ void MainWindow::on_btn_data_run_clicked(){
         // Start data conversion
         try{
             // Parse advanced options.
-            DataInstaller::AdvancedOptions options;
-            options.battle_data = (Qt::Checked == main_window_->chk_battle_data->checkState());
-            options.battle_models = (Qt::Checked == main_window_->chk_battle_models->checkState());
-            options.kernel = (Qt::Checked == main_window_->chk_kernel->checkState());
-            options.images = (Qt::Checked == main_window_->chk_images->checkState());
-            options.sounds = (Qt::Checked == main_window_->chk_sounds->checkState());
-            options.music = (Qt::Checked == main_window_->chk_music->checkState());
-            options.videos = false;
+            DataInstaller::AdvancedOptions options = InstallSteps::ToAdvancedOptions(
+              CurrentOptions(), Qt::Checked == main_window_->chk_keep_original->checkState()
+            );
             if (Qt::Checked == main_window_->chk_videos->checkState()){
                 InstallLog::Get().Add(
                   "[WARNING] The install disk has no videos. To extract them, select game disk 1, 2 or 3 as the "
                   "ISO and install again (with a new installer window)."
                 );
             }
-            options.fields = (Qt::Checked == main_window_->chk_fields->checkState());
-            options.field_models = options.fields && (Qt::Checked == main_window_->chk_field_models->checkState());
-            options.wm = (Qt::Checked == main_window_->chk_wm->checkState());
-            options.wm_models = options.wm && (Qt::Checked == main_window_->chk_wm_models->checkState());
-            options.keep_originals = (Qt::Checked == main_window_->chk_keep_original->checkState());
             installer_created = true;
             install_started_ = true;
             const std::string output_path = QDir::toNativeSeparators(output).toStdString();
@@ -778,9 +568,8 @@ void MainWindow::on_btn_data_run_clicked(){
                     );
                 }
             };
-            // The installation runs in a worker thread so the window stays responsive. Ogre, and the OpenGL context
-            // it creates, belong to the thread that creates them, so the installer is created, run and destroyed
-            // there. Setting "BackgroundInstall" to false runs it in the UI thread, step by step from a timer.
+            // The installation runs in a worker thread so the window stays responsive. Ogre belongs to the thread
+            // that creates it, so the installer is created, run and destroyed there. Setting "BackgroundInstall" to false runs it in the UI thread, step by step from a timer.
             background_ = settings_->value("BackgroundInstall", true).toBool();
             if (background_){
                 stop_requested_ = false;
@@ -831,22 +620,7 @@ void MainWindow::OnInstallStopped(){EnableUi(true);}
 
 void MainWindow::StartVideoExtraction(const QString& output){
     // Only the output directory is needed: no plugins, no configuration, no Ogre.
-    QStringList errors;
-    if (!QDir().mkpath(output)) errors << tr("The installation directory can't be created: %1").arg(output);
-    else{
-        QFile probe(output + ".v-gears-write-test");
-        if (!probe.open(QIODevice::WriteOnly)) errors << tr("The installation directory is not writable: %1").arg(output);
-        else{
-            probe.close();
-            probe.remove();
-        }
-        const QStorageInfo storage(output);
-        const qint64 needed = 1024LL * 1024 * 1024;
-        if (storage.isValid() && storage.bytesAvailable() < needed){
-            errors << tr("Not enough free space in %1: %2 MB available, about %3 MB needed.")
-              .arg(storage.rootPath()).arg(storage.bytesAvailable() / (1024 * 1024)).arg(needed / (1024 * 1024));
-        }
-    }
+    const QStringList errors = InstallSteps::CheckVideoOutput(output);
     if (!errors.isEmpty()){
         QMessageBox::critical(
           this, tr("The extraction can't start"), tr("Fix these problems and try again:\n\n- %1").arg(errors.join("\n- "))
@@ -873,7 +647,7 @@ void MainWindow::StartVideoExtraction(const QString& output){
               },
               [](const std::string& message){InstallLog::Get().Add(message);}, &extracted, &skipped
             );
-            if (ok) ConvertMovies(output.toStdString() + "data/video/");
+            if (ok) InstallSteps::ConvertMovies(output.toStdString() + "data/video/");
         }
         catch (const std::exception& ex){
             error = ex.what();
@@ -900,16 +674,10 @@ void MainWindow::StartVideoExtraction(const QString& output){
 void MainWindow::UpdateToolLocations(const QString& install_dir){
     // Where to look for FFmpeg and TiMidity: what the user chose, then a "tools" folder in the installation
     // directory or next to the installer, then the system PATH.
-    QString dir = QDir::fromNativeSeparators(install_dir);
-    if (!dir.isEmpty() && !dir.endsWith("/")) dir += "/";
-    ExternalTools::Locations& tools = ExternalTools::CurrentLocations();
-    tools.ffmpeg = settings_->value("FFmpegPath").toString().toStdString();
-    tools.timidity = settings_->value("TimidityPath").toString().toStdString();
-    const QString app_dir = QCoreApplication::applicationDirPath();
-    tools.directories.clear();
-    if (!dir.isEmpty()) tools.directories.push_back((dir + "tools").toStdString());
-    tools.directories.push_back((app_dir + "/tools").toStdString());
-    tools.directories.push_back(app_dir.toStdString());
+    InstallSteps::SetToolLocations(
+      install_dir, settings_->value("FFmpegPath").toString().toStdString(),
+      settings_->value("TimidityPath").toString().toStdString()
+    );
 }
 
 void MainWindow::RefreshToolStatus(){

+ 11 - 7
src/installer/TexFile.cpp

@@ -140,7 +140,9 @@ void TexFile::SavePng(
         return;
     }
     // TODO: Warn if wrong palette index.
-    Ogre::Image* image = new Ogre::Image(Ogre::PF_R8G8B8A8_UINT, w, h);
+    // What the texture doesn't cover is transparent, not whatever was in memory.
+    Ogre::Image image(Ogre::PF_R8G8B8A8_UINT, w, h);
+    image.setTo(Ogre::ColourValue::ZERO);
     int target_x = 0;
     int target_y = 0;
     for (int c_y = y; c_y < height_ && c_y < y + h; c_y ++){
@@ -171,7 +173,7 @@ void TexFile::SavePng(
                     a = palettes_.at(palette).at(pixel_ref_.at(i)).a;
                 }
             }
-            image->setColourAt(Ogre::ColourValue(r, g, b, a), target_x, target_y, 0);
+            image.setColourAt(Ogre::ColourValue(r, g, b, a), target_x, target_y, 0);
             target_x ++;
             if (target_x >= w){
                 target_y ++;
@@ -179,7 +181,7 @@ void TexFile::SavePng(
             }
         }
     }
-    image->save(file_name);
+    image.save(file_name);
 }
 
 void TexFile::SavePng(std::string file_name, unsigned int palette){
@@ -196,7 +198,9 @@ void TexFile::SavePng(
         return;
     }
     // TODO: Warn if wrong palette index.
-    Ogre::Image* image = new Ogre::Image(Ogre::PF_R8G8B8A8_UINT, w1 + w2, h);
+    // What the texture doesn't cover is transparent, not whatever was in memory.
+    Ogre::Image image(Ogre::PF_R8G8B8A8_UINT, w1 + w2, h);
+    image.setTo(Ogre::ColourValue::ZERO);
     int target_x = 0;
     int target_y = 0;
     // First image
@@ -219,7 +223,7 @@ void TexFile::SavePng(
                 b = palettes_.at(palette).at(pixel_ref_.at(i)).b;
                 a = palettes_.at(palette).at(pixel_ref_.at(i)).a;
             }
-            image->setColourAt(Ogre::ColourValue(r, g, b, a), target_x, target_y, 0);
+            image.setColourAt(Ogre::ColourValue(r, g, b, a), target_x, target_y, 0);
             target_x ++;
             if (target_x >= w1){
                 target_y ++;
@@ -248,7 +252,7 @@ void TexFile::SavePng(
                 b = palettes_.at(palette).at(pixel_ref_.at(i)).b;
                 a = palettes_.at(palette).at(pixel_ref_.at(i)).a;
             }
-            image->setColourAt(Ogre::ColourValue(r, g, b, a), target_x, target_y, 0);
+            image.setColourAt(Ogre::ColourValue(r, g, b, a), target_x, target_y, 0);
             target_x ++;
             if (target_x >= w1 + w2){
                 target_y ++;
@@ -256,5 +260,5 @@ void TexFile::SavePng(
             }
         }
     }
-    image->save(file_name);
+    image.save(file_name);
 }

+ 3 - 2
src/installer/common/BinGZipFile.cpp

@@ -121,7 +121,8 @@ u32 BinGZipFile::GetNumberOfFiles(){return file_count_;}
 
 void BinGZipFile::InnerGetNumberOfFiles(){
     file_count_ = 0;
-    for (u32 pointer = 0; pointer < buffer_size_;){
+    // Each file has a 6 byte header, then the GZip data, whose header is checked: stop when they don't fit.
+    for (u32 pointer = 0; pointer + 6 + 8 <= buffer_size_;){
         u16 temp = GetU16LE(pointer);
         if (temp == 0xFFFF) temp = 0; // Hack to deal with scene.bin
         pointer += 6;
@@ -141,7 +142,7 @@ void BinGZipFile::InnerGetNumberOfFiles(){
 u32 BinGZipFile::InnerGetFileOffset(u32 file_index){
     if (file_index >= file_count_) return 0;
     u32 current_file = 0;
-    for (u32 pointer = 0; pointer < buffer_size_;){
+    for (u32 pointer = 0; pointer + 6 + 8 <= buffer_size_;){
         u16 temp = GetU16LE(pointer);
         pointer += 6;
         // Condition for GZip header

+ 0 - 8
src/installer/data/BattleSceneFile.cpp

@@ -259,14 +259,6 @@ void BattleSceneFile::Read(File file){
                 enemy.immunities.push_back(immunity);
             }
         }
-        for (int a = 0; a < 16; a ++){
-            if (scene_.enemy_data[e].attacks[a] == 0xFFFF) continue;
-            Enemy::Attack attack;
-            attack.id = scene_.enemy_data[e].attacks[a];
-            if (scene_.enemy_data[e].attack_camera[a] == 0xFFFF) attack.camera = -1;
-            else attack.camera = scene_.enemy_data[e].attack_camera[a];
-            enemy.attacks.push_back(attack);
-        }
         for (int m = 0; m < 3; m ++){
             if (scene_.enemy_data[e].maniputale_attacks[m] == 0xFFFF) continue;
             enemy.manipulate_attacks.push_back(scene_.enemy_data[e].maniputale_attacks[m]);

+ 6 - 3
src/installer/data/DaFile.cpp

@@ -26,8 +26,8 @@ DaFile::DaFile(File file): da_file_(file){
     animations_.clear();
     // Save file contents as a byte array.
     file.SetOffset(0);
-    da_bytes_ = new u8[file.GetFileSize()];
-    file.GetFileBuffer(da_bytes_, 0, file.GetFileSize());
+    da_bytes_.assign(file.GetFileSize(), 0);
+    if (!da_bytes_.empty()) file.GetFileBuffer(da_bytes_.data(), 0, da_bytes_.size());
     bit_offset_ = 0;
     file.SetOffset(0);
     Read();
@@ -211,7 +211,10 @@ int DaFile::GetBitsU(int bits){
     // Bits are read most significant first.
     int value = 0;
     for (int i = 0; i < bits; i ++){
-        const int byte = da_bytes_[bit_offset_ / 8];
+        // Some animations are cut short in the original files, and their last frame goes past the end of the
+        // file. Those bits are read as 0, instead of whatever is in memory after the file.
+        const size_t byte_index = bit_offset_ / 8;
+        const int byte = byte_index < da_bytes_.size() ? da_bytes_[byte_index] : 0;
         const int bit = (byte >> (7 - (bit_offset_ % 8))) & 1;
         value = (value << 1) | bit;
         bit_offset_ ++;

+ 1 - 1
src/installer/data/DaFile.h

@@ -294,7 +294,7 @@ class DaFile{
         /**
          * Contents of the da file as a byte array.
          */
-        u8* da_bytes_;
+        std::vector<u8> da_bytes_;
 
         /**
          * List of animations.

+ 3 - 3
src/installer/data/Enemy.h

@@ -51,20 +51,20 @@ struct Enemy{
         /**
          * Attack ID.
          */
-        u16 id;
+        u16 id = 0;
 
         /**
          * Camera ID to use during the attack.
          *
          * -1 to not move the camera.
          */
-        int camera;
+        int camera = -1;
 
         /**
          * Animation script of the model to play for the attack, as in the model animation scripts
          * ("scriptN"). -1 if there is none.
          */
-        int animation;
+        int animation = -1;
     };
 
     /**

+ 49 - 0
src/installer/main.cpp

@@ -13,19 +13,68 @@
  * GNU General Public License for more details.
  */
 
+#include <string>
+#include <vector>
+#include <QtCore/QCoreApplication>
 #include <QtWidgets/QApplication>
 #include <QtGui/QIcon>
+#ifdef _WIN32
+#include <cstdio>
+#include <windows.h>
+#endif
 
+#include "CliInstaller.h"
+#include "InstallCommandLine.h"
 #include "MainWindow.h"
 
+/**
+ * Connects the standard streams to the console the installer was started from.
+ *
+ * In Windows the installer is a window application, so it has no console of its own. Without this, nothing written
+ * from the command line would be seen.
+ */
+static void AttachToConsole(){
+#ifdef _WIN32
+    if (GetConsoleWindow() != nullptr) return;
+    if (!AttachConsole(ATTACH_PARENT_PROCESS)) return;
+    FILE* stream = nullptr;
+    freopen_s(&stream, "CONOUT$", "w", stdout);
+    freopen_s(&stream, "CONOUT$", "w", stderr);
+    freopen_s(&stream, "CONIN$", "r", stdin);
+    std::ios::sync_with_stdio(true);
+#endif
+}
+
+/**
+ * Gets the name of the program, for the usage text.
+ */
+static std::string ProgramName(const char* argv0){
+    std::string name = argv0 == nullptr ? std::string() : std::string(argv0);
+    const size_t slash = name.find_last_of("/\\");
+    if (slash != std::string::npos) name = name.substr(slash + 1);
+    return name.empty() ? std::string("v-gears-installer") : name;
+}
+
 /**
  * Installer main function.
  *
+ * Without arguments it opens the installer window. With command line options it installs from the command line
+ * instead (see InstallCommandLine).
+ *
  * @param[in] argc Number of arguments passed to the application.
  * @param[in] argv List of arguments passed to the application.
  * @return The application return code. 0 is OK.
  */
 int main(int argc, char *argv[]){
+    const InstallCommandLine::Arguments arguments
+      = InstallCommandLine::Parse(std::vector<std::string>(argv + (argc > 0 ? 1 : 0), argv + argc));
+    if (arguments.mode != InstallCommandLine::Mode::GUI){
+        AttachToConsole();
+        // No window, so no display is needed for Qt.
+        QCoreApplication::setApplicationName(QStringLiteral("v-gears-installer"));
+        QCoreApplication application(argc, argv);
+        return CliInstaller::Run(arguments, ProgramName(argc > 0 ? argv[0] : nullptr));
+    }
     QApplication::setApplicationName(QStringLiteral("v-gears-installer"));
     QApplication::setApplicationDisplayName(QStringLiteral("V-Gears Installer"));
     QApplication application(argc, argv);

+ 1 - 0
test/CMakeLists.txt

@@ -296,6 +296,7 @@ add_executable(v-gears-installer-tests
     installer/MovieCamera.cpp
     ${CMAKE_SOURCE_DIR}/src/installer/MovieCamera.cpp
     ${CMAKE_SOURCE_DIR}/src/installer/ExternalTools.cpp
+    ${CMAKE_SOURCE_DIR}/src/installer/InstallCommandLine.cpp
     ${CMAKE_SOURCE_DIR}/src/installer/InstallLayout.cpp
     ${CMAKE_SOURCE_DIR}/src/installer/InstallLog.cpp
     ${CMAKE_SOURCE_DIR}/src/installer/InstallOptions.cpp

+ 5 - 2
test/installer/ExternalTools.cpp

@@ -233,13 +233,16 @@ BOOST_AUTO_TEST_SUITE(ExternalToolsArgumentTests)
 
 BOOST_AUTO_TEST_CASE(FfmpegArgumentsDontNeedQuoting){
     const std::vector<std::string> expected = {
-      "-hide_banner", "-loglevel", "panic", "-y", "-i", "/path with spaces/in put.wav", "/out dir/o'ut.ogg"
+      "-hide_banner", "-loglevel", "panic", "-y", "-i", "/path with spaces/in put.wav", "-fflags", "+bitexact",
+      "-flags:a", "+bitexact", "/out dir/o'ut.ogg"
     };
     BOOST_CHECK(FfmpegArguments("/path with spaces/in put.wav", "/out dir/o'ut.ogg") == expected);
 }
 
 BOOST_AUTO_TEST_CASE(FfmpegReadsStdin){
-    const std::vector<std::string> expected = {"-hide_banner", "-loglevel", "panic", "-y", "-i", "-", "out.ogg"};
+    const std::vector<std::string> expected = {
+      "-hide_banner", "-loglevel", "panic", "-y", "-i", "-", "-fflags", "+bitexact", "-flags:a", "+bitexact", "out.ogg"
+    };
     BOOST_CHECK(FfmpegStdinArguments("out.ogg") == expected);
 }
 

+ 79 - 0
test/installer/InstallLogic.cpp

@@ -18,6 +18,7 @@
 #include <boost/filesystem.hpp>
 #include <algorithm>
 #include <fstream>
+#include "installer/InstallCommandLine.h"
 #include "installer/InstallLayout.h"
 #include "installer/InstallLog.h"
 #include "installer/InstallOptions.h"
@@ -579,3 +580,81 @@ BOOST_AUTO_TEST_CASE(LogCanBeAppended){
 }
 
 BOOST_AUTO_TEST_SUITE_END()
+
+// Command line.
+
+BOOST_AUTO_TEST_CASE(CommandLineWithoutInstallerOptionsOpensTheWindow){
+    using namespace InstallCommandLine;
+    BOOST_CHECK(Parse({}).mode == Mode::GUI);
+    // Qt's own arguments are left for the window.
+    BOOST_CHECK(Parse({"-platform", "xcb"}).mode == Mode::GUI);
+}
+
+BOOST_AUTO_TEST_CASE(CommandLineInstallDefaults){
+    using namespace InstallCommandLine;
+    const Arguments a = Parse({"--cli", "--iso", "disk.iso"});
+    BOOST_REQUIRE(a.mode == Mode::INSTALL);
+    BOOST_CHECK_EQUAL(a.iso, "disk.iso");
+    BOOST_CHECK(a.output.empty());
+    BOOST_CHECK(a.copy_data);
+    BOOST_CHECK(a.keep_originals);
+    BOOST_CHECK(!a.yes);
+    // Everything, except the videos, which are not on the install disk.
+    const InstallOptions o = a.options;
+    BOOST_CHECK(o.kernel && o.fields && o.field_models && o.wm && o.wm_models && o.battle_data && o.battle_models);
+    BOOST_CHECK(o.images && o.sounds && o.music);
+    BOOST_CHECK(!o.videos);
+}
+
+BOOST_AUTO_TEST_CASE(CommandLineInstallerOptionsImplyCli){
+    using namespace InstallCommandLine;
+    const Arguments a = Parse({"-i", "disk.iso", "-o", "/tmp/vg", "-y", "--no-copy-data", "--discard-originals"});
+    BOOST_REQUIRE(a.mode == Mode::INSTALL);
+    BOOST_CHECK_EQUAL(a.output, "/tmp/vg");
+    BOOST_CHECK(a.yes);
+    BOOST_CHECK(!a.copy_data);
+    BOOST_CHECK(!a.keep_originals);
+    // "--option=value" works too.
+    BOOST_CHECK_EQUAL(Parse({"--iso=other.iso"}).iso, "other.iso");
+}
+
+BOOST_AUTO_TEST_CASE(CommandLinePresetsAndParts){
+    using namespace InstallCommandLine;
+    Arguments a = Parse({"-i", "d.iso", "--preset", "battle", "--with", "music,images", "--without", "kernel"});
+    BOOST_REQUIRE(a.mode == Mode::INSTALL);
+    BOOST_CHECK(a.options.battle_data && a.options.battle_models && a.options.music && a.options.images);
+    BOOST_CHECK(!a.options.kernel && !a.options.fields && !a.options.sounds);
+
+    a = Parse({"-i", "d.iso", "-p", "custom", "--with", "fields"});
+    BOOST_REQUIRE(a.mode == Mode::INSTALL);
+    BOOST_CHECK(a.options.fields && !a.options.field_models && !a.options.kernel);
+
+    // Removing a part removes what depends on it.
+    a = Parse({"-i", "d.iso", "--without", "world-map"});
+    BOOST_REQUIRE(a.mode == Mode::INSTALL);
+    BOOST_CHECK(!a.options.wm && !a.options.wm_models);
+}
+
+BOOST_AUTO_TEST_CASE(CommandLineErrors){
+    using namespace InstallCommandLine;
+    BOOST_CHECK(Parse({"--cli"}).mode == Mode::INVALID);
+    BOOST_CHECK(Parse({"--iso"}).mode == Mode::INVALID);
+    BOOST_CHECK(Parse({"-i", "d.iso", "--preset", "nope"}).mode == Mode::INVALID);
+    BOOST_CHECK(Parse({"-i", "d.iso", "--with", "nope"}).mode == Mode::INVALID);
+    BOOST_CHECK(Parse({"-i", "d.iso", "--bogus"}).mode == Mode::INVALID);
+    // A part can't be added without what it needs.
+    BOOST_CHECK(Parse({"-i", "d.iso", "-p", "custom", "--with", "field-models"}).mode == Mode::INVALID);
+    BOOST_CHECK(Parse({"--verify", "-i", "d.iso"}).mode == Mode::INVALID);
+    BOOST_CHECK(Parse({"--verify", "--with", "music"}).mode == Mode::INVALID);
+}
+
+BOOST_AUTO_TEST_CASE(CommandLineOtherModes){
+    using namespace InstallCommandLine;
+    BOOST_CHECK(Parse({"--verify"}).mode == Mode::VERIFY);
+    BOOST_CHECK_EQUAL(Parse({"--verify", "-o", "/x"}).output, "/x");
+    BOOST_CHECK(Parse({"--help"}).mode == Mode::HELP);
+    BOOST_CHECK(Parse({"-i", "d.iso", "-h"}).mode == Mode::HELP);
+    BOOST_CHECK(Parse({"--version"}).mode == Mode::VERSION);
+    BOOST_CHECK(Parse({"--list-parts"}).mode == Mode::LIST_PARTS);
+    BOOST_CHECK(!Usage("v-gears-installer").empty());
+}