Browse Source

Broke up the longest functions of the scripts, the console and the installer window

- The update of the scripts has separate functions to sort the queues, draw the debug information, start and resume a script, count down waits and handle what a script returns.
- The input of the console has a function for each action.
- The install button runs the checks, the deletion of the previous installation, the extraction, the preparation and the conversion as separate steps.
Iñigo Valentin 4 days ago
parent
commit
d48ac49964

+ 184 - 248
src/engine/script/ScriptManager.cpp

@@ -119,264 +119,200 @@ void ScriptManager::Input(const VGears::Event& event){
 }
 
 void ScriptManager::Update(const ScriptManager::Type type){
-    // Remove the scripts that a request has replaced.
-    for (unsigned int i = 0; i < script_entity_.size(); ++ i){
-        if (script_entity_[i].type != type) continue;
-        for (size_t k = script_entity_[i].queue.size(); k --;){
-            if (script_entity_[i].queue[k].replaced) RemoveEntityScript(script_entity_[i], k);
-        }
+    RemoveReplacedScripts(type);
+    SortQueues(type);
+    // The debug information is drawn before the scripts run, so the ones that run once are seen.
+    DrawDebugQueues();
+    // Before updating entities, call on_update on the system timer.
+    RunString("Timer.update()");
+    for (size_t entity = 0; entity < script_entity_.size(); ++ entity){
+        if (script_entity_[entity].type == type) RunEntityScripts(entity);
     }
-    // Resort all queue. This will give correct info for debug draw.
-    for (unsigned int i = 0; i < script_entity_.size(); ++ i){
-        if (script_entity_[i].type == type){
-            if (script_entity_[i].queue.size() > 0){
-                if (script_entity_[i].resort == true){
-                    std::stable_sort(
-                      script_entity_[i].queue.begin(),
-                      script_entity_[i].queue.end(), priority_queue_compare
-                    );
-                    script_entity_[i].resort = false;
-                }
-            }
+}
+
+void ScriptManager::RemoveReplacedScripts(const Type type){
+    for (ScriptEntity& entity : script_entity_){
+        if (entity.type != type) continue;
+        for (size_t k = entity.queue.size(); k --;){
+            if (entity.queue[k].replaced) RemoveEntityScript(entity, k);
         }
     }
+}
 
-    // Draw debug before update. This way it will be possible to see
-    // scripts that run once
-    int debug = cv_debug_script.GetI();
-    if (debug != 0){
-        DEBUG_DRAW.SetTextAlignment(DEBUG_DRAW.LEFT);
-        DEBUG_DRAW.SetScreenSpace(true);
-        int y = 34;
-
-        for (unsigned int i = 0; i < 3; ++ i){
-            if ((debug & (1 << i)) != 0){
-                DEBUG_DRAW.SetColour(Ogre::ColourValue(0.8f, 0.8f, 0.0f, 1.0f));
-                DEBUG_DRAW.Text(
-                  10.0f, static_cast<float>(y), "Script \"" + script_entity_type[i] + "\" entity:"
-                );
-                y += 16;
-
-                for (unsigned int j = 0; j < script_entity_.size(); ++ j){
-                    if (script_entity_[j].type == i){
-                        Ogre::String text = script_entity_[j].name;
-                        unsigned int queue_size = script_entity_[j].queue.size();
-                        if (queue_size > 0){
-                            text += ": ";
-                            DEBUG_DRAW.SetColour(Ogre::ColourValue(0.8f, 0.8f, 0.0f, 1.0f));
-                        }
-                        else DEBUG_DRAW.SetColour(Ogre::ColourValue(0.5, 0.5, 0.5, 1));
-                        for (unsigned int k = 0; k < queue_size; ++ k){
-                            if (k > 0) text += ", ";
-                            text +=
-                              "("
-                              + Ogre::StringConverter::toString(script_entity_[j].queue[k].priority)
-                              + ")" + script_entity_[j].queue[k].function;
-
-                            if (script_entity_[j].queue[k].wait == true){
-                                if (script_entity_[j].queue[k].seconds_to_wait != 0){
-                                    text +=
-                                      ":wait("+ Ogre::StringConverter::toString(
-                                        script_entity_[j].queue[k].seconds_to_wait
-                                      ) + ")";
-                                }
-                            }
-                        }
-                        DEBUG_DRAW.Text(20.0f, static_cast<float>(y), text);
-                        y += 16;
-                    }
-                }
-            }
+void ScriptManager::SortQueues(const Type type){
+    for (ScriptEntity& entity : script_entity_){
+        if (entity.type != type || entity.queue.empty() || !entity.resort) continue;
+        std::stable_sort(entity.queue.begin(), entity.queue.end(), priority_queue_compare);
+        entity.resort = false;
+    }
+}
+
+void ScriptManager::DrawDebugQueues() const{
+    const int debug = cv_debug_script.GetI();
+    if (debug == 0) return;
+    DEBUG_DRAW.SetTextAlignment(DEBUG_DRAW.LEFT);
+    DEBUG_DRAW.SetScreenSpace(true);
+    int y = 34;
+    // The bits of the variable are the types of entities to show.
+    for (unsigned int type = 0; type < 3; ++ type){
+        if ((debug & (1 << type)) == 0) continue;
+        DEBUG_DRAW.SetColour(Ogre::ColourValue(0.8f, 0.8f, 0.0f, 1.0f));
+        DEBUG_DRAW.Text(
+          10.0f, static_cast<float>(y), "Script \"" + script_entity_type[type] + "\" entity:"
+        );
+        y += 16;
+        for (const ScriptEntity& entity : script_entity_){
+            if (entity.type != type) continue;
+            if (entity.queue.empty()) DEBUG_DRAW.SetColour(Ogre::ColourValue(0.5, 0.5, 0.5, 1));
+            else DEBUG_DRAW.SetColour(Ogre::ColourValue(0.8f, 0.8f, 0.0f, 1.0f));
+            DEBUG_DRAW.Text(20.0f, static_cast<float>(y), DescribeQueue(entity));
+            y += 16;
         }
     }
+}
 
-    // Before updating entities, call on_update on the system timer.
-    RunString("Timer.update()");
+Ogre::String ScriptManager::DescribeQueue(const ScriptEntity& entity){
+    Ogre::String text = entity.name;
+    for (size_t k = 0; k < entity.queue.size(); ++ k){
+        const QueueScript& script = entity.queue[k];
+        text += (k == 0) ? ": " : ", ";
+        text += "(" + Ogre::StringConverter::toString(script.priority) + ")" + script.function;
+        if (script.wait && script.seconds_to_wait != 0)
+            text += ":wait(" + Ogre::StringConverter::toString(script.seconds_to_wait) + ")";
+    }
+    return text;
+}
 
-    for (unsigned int i = 0; i < script_entity_.size(); ++ i){
-        if (script_entity_[i].type == type){
-            // One script of an entity is run each cycle, the first in the queue. If it yields
-            // without waiting for anything, as the ones that loop for ever, or until a flag
-            // changes, do, it doesn't take the cycle of the rest: the next one is run too. In the
-            // original game the scripts of an entity that have different priorities all run.
-            for (size_t script_index = 0; script_index < script_entity_[i].queue.size(); ++ script_index){
-                bool yielded = false;
-                current_script_id_.entity = script_entity_[i].name;
-                current_script_id_.function = script_entity_[i].queue[script_index].function;
-
-                if (script_entity_[i].queue[script_index].wait == false){
-                    if (script_entity_[i].queue[script_index].yield == false){
-                        LOG_TRIVIAL(
-                          "[SCRIPT] Start script \"" + current_script_id_.function
-                          + "\" for entity \"" + current_script_id_.entity + "\"."
-                        );
-
-                        for (const ScriptId& waiting : script_entity_[i].queue[script_index].paused_scripts_start)
-                            ContinueScriptExecution(waiting);
-                        script_entity_[i].queue[script_index].paused_scripts_start.clear();
-                        sol::object table = GetTableByEntityName(
-                          type, current_script_id_.entity,
-                          script_entity_[i].queue[script_index].state
-                        );
-                        sol::object function;
-                        if (table.get_type() == sol::type::table)
-                            function = table.as<sol::table>()[current_script_id_.function];
-                        if (
-                          table.get_type() == sol::type::table
-                          && function.get_type() == sol::type::function
-                        ){
-                            int ret = 0;
-                            lua_State* thread = script_entity_[i].queue[script_index].state;
-                            sol::coroutine coroutine(thread, sol::function(function));
-                            auto result = coroutine(
-                              table, script_entity_[i].queue[script_index].argument1,
-                              script_entity_[i].queue[script_index].argument2,
-                              script_entity_[i].queue[script_index].argument3
-                            );
-                            if (result.valid()){
-                                // The coroutine yields with the bound function
-                                // return value on top of the thread stack; a
-                                // completed script leaves its return value there.
-                                if (lua_gettop(thread) > 0 && lua_isnumber(thread, -1))
-                                    ret = static_cast<int>(lua_tointeger(thread, -1));
-                                lua_settop(thread, 0);
-                            }
-                            else{
-                                sol::error error = result;
-                                std::string msg = "LUA error in entity " + script_entity_[i].name
-                                  + " (" + current_script_id_.entity + ") " + " in function "
-                                  + script_entity_[i].queue[script_index].function + " ("
-                                  + current_script_id_.function + ")";
-                                if (lua_tostring(thread, -1) != nullptr){
-                                    msg = msg + ". Details: " + std::string(
-                                      lua_tostring(thread, -1)
-                                    );
-                                }
-                                msg = msg + ". Exception: " + error.what();
-                                LOG_ERROR(msg);
-                                lua_settop(thread, 0);
-                            }
-
-                            if (ret == 0){
-                                LOG_TRIVIAL(
-                                  "[SCRIPT] Script \"" + current_script_id_.function
-                                  + "\" for entity \"" + current_script_id_.entity + "\" finished."
-                                );
-                                if (script_entity_[i].queue[script_index].function != "on_update")
-                                    RemoveEntityScript(script_entity_[i], script_index);
-                            }
-                            else if (ret == 1){
-                                LOG_TRIVIAL(
-                                  "[SCRIPT] Script \"" + current_script_id_.function
-                                  + "\" for entity \"" + current_script_id_.entity
-                                  + "\" not paused and will be continued next cycle."
-                                );
-                                script_entity_[i].queue[script_index].yield = true;
-                                yielded = true;
-                            }
-                            else{
-                                LOG_TRIVIAL(
-                                  "[SCRIPT] Script \"" + current_script_id_.function
-                                  + "\" for entity \"" + current_script_id_.entity
-                                  + "\" not finished yet."
-                                );
-                                script_entity_[i].queue[script_index].yield = true;
-                                script_entity_[i].queue[script_index].wait = true;
-                            }
-                        }
-                        else{
-                            LOG_WARNING(
-                              "Script \"" + current_script_id_.function + "\" for entity \""
-                              + current_script_id_.entity + "\" doesn't exist."
-                            );
-                            RemoveEntityScript(script_entity_[i], script_index);
-                        }
-                    }
-                    else{
-                        LOG_TRIVIAL(
-                          "[SCRIPT] Continue function \"" + current_script_id_.function
-                          + "\" for entity \"" + current_script_id_.entity + "\"."
-                        );
-
-                        int ret = 0;
-                        lua_State* thread = script_entity_[i].queue[script_index].state;
-                        // sol.hpp bundles a compat53 shim: on LuaJIT this maps
-                        // to the native 2-argument lua_resume.
-                        int status = lua_resume(thread, nullptr, 0);
-                        if (status == LUA_YIELD || status == 0){
-                            if (lua_gettop(thread) > 0 && lua_isnumber(thread, -1))
-                                ret = static_cast<int>(lua_tointeger(thread, -1));
-                            lua_settop(thread, 0);
-                        }
-                        else{
-                            const char* error = lua_tostring(thread, -1);
-                            LOG_WARNING(
-                              Ogre::String(error != nullptr ? error : "unknown lua error")
-                            );
-                            lua_settop(thread, 0);
-                        }
-
-                        if (ret == 0){ // Finished.
-                            LOG_TRIVIAL(
-                              "[SCRIPT] Script \"" + current_script_id_.function
-                              + "\" for entity \"" + current_script_id_.entity + "\" finished."
-                            );
-
-                            // Stop yield for on_update.
-                            script_entity_[i].queue[script_index].yield = false;
-
-                            if (script_entity_[i].queue[script_index].function != "on_update")
-                                RemoveEntityScript(script_entity_[i], script_index);
-                        }
-                        else if (ret == 1){
-                            LOG_TRIVIAL(
-                              "[SCRIPT] Script \"" + current_script_id_.function
-                              + "\" for entity \"" + current_script_id_.entity
-                              + "\" not paused and will be continued next cycle."
-                            );
-                            yielded = true;
-                        }
-                        else{
-                            LOG_TRIVIAL(
-                              "[SCRIPT] Script \"" + current_script_id_.function
-                              + "\" for entity \"" + current_script_id_.entity
-                              + "\" not finished yet."
-                            );
-                            script_entity_[i].queue[script_index].wait = true;
-                        }
-                    }
-                }
-                else if (script_entity_[i].queue[script_index].seconds_to_wait > 0){
-                    script_entity_[i].queue[script_index].seconds_to_wait
-                      -= Timer::getSingleton().GetGameTimeDelta();
-                    script_entity_[i].queue[script_index].seconds_to_wait
-                      = (script_entity_[i].queue[script_index].seconds_to_wait < 0)
-                        ? 0 : script_entity_[i].queue[script_index].seconds_to_wait;
-
-                    if (script_entity_[i].queue[script_index].seconds_to_wait == 0)
-                        script_entity_[i].queue[script_index].wait = false;
-                }
-            
-                if (!yielded){
-                    // The scripts of an entity don't wait for each other in the original game. If
-                    // the first one is waiting (for another script to end, for example) and a
-                    // script that someone waits to start (request_start_sync) is queued behind
-                    // it, that script has to start, or the two would wait for each other forever
-                    // (the lines of mrkt3 do this with Aerith).
-                    bool start_waited_script = false;
-                    for (size_t next = script_index + 1; next < script_entity_[i].queue.size(); ++ next){
-                        const QueueScript& queued = script_entity_[i].queue[next];
-                        if (!queued.yield && !queued.wait && !queued.paused_scripts_start.empty()){
-                            script_index = next - 1;
-                            start_waited_script = true;
-                            break;
-                        }
-                    }
-                    if (!start_waited_script) break;
-                }
-            }
+void ScriptManager::RunEntityScripts(const size_t entity){
+    // One script of an entity is run each cycle, the first in the queue. If it yields without
+    // waiting for anything, as the ones that loop for ever, or until a flag changes, do, it
+    // doesn't take the cycle of the rest: the next one is run too. In the original game the
+    // scripts of an entity that have different priorities all run.
+    // Scripts can add entities and scripts while they run: no references to them are kept.
+    for (size_t index = 0; index < script_entity_[entity].queue.size(); ++ index){
+        current_script_id_.entity = script_entity_[entity].name;
+        current_script_id_.function = script_entity_[entity].queue[index].function;
+        bool yielded = false;
+        if (script_entity_[entity].queue[index].wait) CountDownWait(entity, index);
+        else if (script_entity_[entity].queue[index].yield) yielded = ResumeScript(entity, index);
+        else yielded = StartScript(entity, index);
+        if (!yielded && !SkipToWaitedScript(script_entity_[entity], index)) break;
+    }
+}
+
+bool ScriptManager::StartScript(const size_t entity, const size_t index){
+    LOG_TRIVIAL("[SCRIPT] Start " + CurrentScriptDescription() + ".");
+    for (const ScriptId& waiting : script_entity_[entity].queue[index].paused_scripts_start)
+        ContinueScriptExecution(waiting);
+    script_entity_[entity].queue[index].paused_scripts_start.clear();
+    const sol::object table = GetTableByEntityName(
+      script_entity_[entity].type, current_script_id_.entity,
+      script_entity_[entity].queue[index].state
+    );
+    sol::object function;
+    if (table.get_type() == sol::type::table)
+        function = table.as<sol::table>()[current_script_id_.function];
+    if (table.get_type() != sol::type::table || function.get_type() != sol::type::function){
+        LOG_WARNING(
+          "Script \"" + current_script_id_.function + "\" for entity \""
+          + current_script_id_.entity + "\" doesn't exist."
+        );
+        RemoveEntityScript(script_entity_[entity], index);
+        return false;
+    }
+    const QueueScript& script = script_entity_[entity].queue[index];
+    lua_State* thread = script.state;
+    sol::coroutine coroutine(thread, sol::function(function));
+    auto result = coroutine(table, script.argument1, script.argument2, script.argument3);
+    int returned = 0;
+    if (result.valid()) returned = TakeReturnValue(thread);
+    else{
+        const sol::error error = result;
+        std::string message = "LUA error in entity " + current_script_id_.entity
+          + " in function " + current_script_id_.function;
+        if (lua_tostring(thread, -1) != nullptr)
+            message += ". Details: " + std::string(lua_tostring(thread, -1));
+        message += std::string(". Exception: ") + error.what();
+        LOG_ERROR(message);
+        lua_settop(thread, 0);
+    }
+    return HandleReturnValue(entity, index, returned);
+}
+
+bool ScriptManager::ResumeScript(const size_t entity, const size_t index){
+    LOG_TRIVIAL("[SCRIPT] Continue " + CurrentScriptDescription() + ".");
+    lua_State* thread = script_entity_[entity].queue[index].state;
+    // sol.hpp bundles a compat53 shim: on LuaJIT this maps to the native 2-argument lua_resume.
+    const int status = lua_resume(thread, nullptr, 0);
+    int returned = 0;
+    if (status == LUA_YIELD || status == 0) returned = TakeReturnValue(thread);
+    else{
+        const char* error = lua_tostring(thread, -1);
+        LOG_WARNING(Ogre::String(error != nullptr ? error : "unknown lua error"));
+        lua_settop(thread, 0);
+    }
+    return HandleReturnValue(entity, index, returned);
+}
+
+int ScriptManager::TakeReturnValue(lua_State* thread){
+    // The coroutine yields with the bound function return value on top of the thread stack; a
+    // completed script leaves its return value there.
+    int value = 0;
+    if (lua_gettop(thread) > 0 && lua_isnumber(thread, -1))
+        value = static_cast<int>(lua_tointeger(thread, -1));
+    lua_settop(thread, 0);
+    return value;
+}
+
+bool ScriptManager::HandleReturnValue(const size_t entity, const size_t index, const int value){
+    QueueScript& script = script_entity_[entity].queue[index];
+    if (value == 0){
+        LOG_TRIVIAL("[SCRIPT] Finished " + CurrentScriptDescription() + ".");
+        // The on_update scripts stay, and start again.
+        script.yield = false;
+        if (script.function != "on_update") RemoveEntityScript(script_entity_[entity], index);
+        return false;
+    }
+    script.yield = true;
+    if (value == 1){
+        LOG_TRIVIAL(
+          "[SCRIPT] Not paused, will be continued next cycle: " + CurrentScriptDescription() + "."
+        );
+        return true;
+    }
+    LOG_TRIVIAL("[SCRIPT] Not finished yet: " + CurrentScriptDescription() + ".");
+    script.wait = true;
+    return false;
+}
+
+void ScriptManager::CountDownWait(const size_t entity, const size_t index){
+    QueueScript& script = script_entity_[entity].queue[index];
+    // Scripts that wait for something other than time are woken by it.
+    if (script.seconds_to_wait <= 0) return;
+    script.seconds_to_wait = std::max(
+      script.seconds_to_wait - Timer::getSingleton().GetGameTimeDelta(), 0.0f
+    );
+    if (script.seconds_to_wait == 0) script.wait = false;
+}
+
+bool ScriptManager::SkipToWaitedScript(const ScriptEntity& entity, size_t& index){
+    // The scripts of an entity don't wait for each other in the original game. If the first one is
+    // waiting (for another script to end, for example) and a script that someone waits to start
+    // (request_start_sync) is queued behind it, that script has to start, or the two would wait
+    // for each other forever (the lines of mrkt3 do this with Aerith).
+    for (size_t next = index + 1; next < entity.queue.size(); ++ next){
+        const QueueScript& queued = entity.queue[next];
+        if (!queued.yield && !queued.wait && !queued.paused_scripts_start.empty()){
+            index = next - 1;
+            return true;
         }
     }
+    return false;
+}
+
+Ogre::String ScriptManager::CurrentScriptDescription() const{
+    return "script \"" + current_script_id_.function + "\" for entity \""
+      + current_script_id_.entity + "\"";
 }
 
 void ScriptManager::UpdateDebug(){}

+ 92 - 0
src/engine/script/ScriptManager.h

@@ -472,6 +472,98 @@ class ScriptManager : public Manager, public Ogre::Singleton<ScriptManager>{
          */
         void UpdateWorld() override;
 
+        /**
+         * Removes the scripts that a request has replaced.
+         *
+         * @param[in] type Type of the entities.
+         */
+        void RemoveReplacedScripts(const Type type);
+
+        /**
+         * Sorts the queues of scripts that have changed, by priority.
+         *
+         * @param[in] type Type of the entities.
+         */
+        void SortQueues(const Type type);
+
+        /**
+         * Draws the queues of the entities, if the debug variable asks for it.
+         */
+        void DrawDebugQueues() const;
+
+        /**
+         * Describes the queue of an entity: its scripts, their priorities and waits.
+         *
+         * @param[in] entity The entity.
+         */
+        static Ogre::String DescribeQueue(const ScriptEntity& entity);
+
+        /**
+         * Runs the scripts of an entity that have to run this cycle.
+         *
+         * @param[in] entity Index of the entity.
+         */
+        void RunEntityScripts(const size_t entity);
+
+        /**
+         * Starts a script.
+         *
+         * @param[in] entity Index of the entity.
+         * @param[in] index Position of the script in the queue.
+         * @return True if the next script of the queue can run too.
+         */
+        bool StartScript(const size_t entity, const size_t index);
+
+        /**
+         * Continues a script that yielded.
+         *
+         * @param[in] entity Index of the entity.
+         * @param[in] index Position of the script in the queue.
+         * @return True if the next script of the queue can run too.
+         */
+        bool ResumeScript(const size_t entity, const size_t index);
+
+        /**
+         * Takes the value a script left on the stack of its thread, and empties it.
+         *
+         * @param[in] thread The thread of the script.
+         * @return The value, or 0 if there is none.
+         */
+        static int TakeReturnValue(lua_State* thread);
+
+        /**
+         * Updates a script that has run according to what it returned: 0 if it finished, 1 to continue
+         * in the next cycle and any other value if it waits for something.
+         *
+         * @param[in] entity Index of the entity.
+         * @param[in] index Position of the script in the queue.
+         * @param[in] value The value.
+         * @return True if the next script of the queue can run too.
+         */
+        bool HandleReturnValue(const size_t entity, const size_t index, const int value);
+
+        /**
+         * Counts down the time a script waits.
+         *
+         * @param[in] entity Index of the entity.
+         * @param[in] index Position of the script in the queue.
+         */
+        void CountDownWait(const size_t entity, const size_t index);
+
+        /**
+         * Looks for a script, later in a queue, that another script waits to start.
+         *
+         * @param[in] entity The entity.
+         * @param[in,out] index Position in the queue. Left just before the script found.
+         * @return True if there is one.
+         */
+        static bool SkipToWaitedScript(const ScriptEntity& entity, size_t& index);
+
+        /**
+         * Retrieves the names of the running script and of its entity, for the log.
+         */
+        Ogre::String CurrentScriptDescription() const;
+
         /**
          * Lua state.
          */

+ 114 - 148
src/engine/ui/Console.cpp

@@ -103,163 +103,129 @@ void Console::Input(const VGears::Event& event){
         if (event.type == VGears::ET_KEY_PRESS && event.param1 == OIS::KC_GRAVE) SetToVisible();
         return;
     }
-
-    // Input command.
-    else if (
-      event.type == VGears::ET_KEY_PRESS && (
-        event.param1 == OIS::KC_RETURN || event.param1 == OIS::KC_NUMPADENTER
-      ) && input_line_.size()
-    ){
-        if (auto_completition_.size() > 0)
-            input_line_ += auto_completition_[auto_completition_line_];
-        AddTextToOutput(input_line_);
-        AddInputToHistory();
-        // Backslashed text are console commands, otherwise - script commands.
-        if ('\\' == input_line_[0] || '/' == input_line_[0]){
-            if (input_line_.size() > 1){
-                // Remove backslash.
-                input_line_.erase(0, 1);
-                ExecuteCommand(input_line_);
-            }
-        }
-        else ExecuteScript();
-        input_line_.clear();
-        cursor_position_ = 0;
-        ResetAutoCompletion();
-    }
-    else if (event.type == VGears::ET_KEY_PRESS && event.param1 == OIS::KC_TAB) CompleteInput();
-    // Remove console.
-    else if (event.type == VGears::ET_KEY_PRESS && event.param1 == OIS::KC_GRAVE) SetToHide();
-    // History up
-    else if (
-      (event.type == VGears::ET_KEY_PRESS || event.type == VGears::ET_KEY_REPEAT_WAIT)
-      && event.param1 == OIS::KC_UP
-    ){
-        if (history_line_cycle_index_ < (int)history_.size() - 1){
-            ++ history_line_cycle_index_;
-            SetInputLineFromHistory();
-        }
-    }
-    // History down
-    else if (
-      (event.type == VGears::ET_KEY_PRESS || event.type == VGears::ET_KEY_REPEAT_WAIT)
-      && event.param1 == OIS::KC_DOWN
-    ){
-        if (history_line_cycle_index_ > 0){
-            -- history_line_cycle_index_;
-            SetInputLineFromHistory();
-        }
-    }
-    // Scroll display to previous row.
-    else if (event.type == VGears::ET_MOUSE_SCROLL && event.param1 > 0){
-        if (display_line_ > 0) display_line_ -= 1;
-    }
-    // Scroll display to next row.
-    else if (event.type == VGears::ET_MOUSE_SCROLL && event.param1 < 0){
-        if (display_line_ < output_line_.size()) display_line_ += 1;
-    }
-    // Scroll display to previous row.
-    else if (
-      (event.type == VGears::ET_KEY_PRESS || event.type == VGears::ET_KEY_REPEAT_WAIT)
-      && event.param1 == OIS::KC_PGUP
-    ){
-        if (display_line_ > 0) display_line_ -= 1;
-    }
-    // Scroll display to next row.
-    else if (
-      (event.type == VGears::ET_KEY_PRESS || event.type == VGears::ET_KEY_REPEAT_WAIT)
-      && event.param1 == OIS::KC_PGDOWN
-    ){
-        if (display_line_ < output_line_.size()) display_line_ += 1;
-    }
-    // Delete character after cursor.
-    else if (
-      (event.type == VGears::ET_KEY_PRESS || event.type == VGears::ET_KEY_REPEAT_WAIT)
-      && event.param1 == OIS::KC_DELETE
-    ){
-        if (auto_completition_.size() > 0) ResetAutoCompletion();
-        else{
-            if (input_line_.size() > 0 && cursor_position_ < input_line_.size())
-                input_line_.erase(cursor_position_, 1);
-        }
-    }
-    // Delete character before cursor.
-    else if (
-      (event.type == VGears::ET_KEY_PRESS || event.type == VGears::ET_KEY_REPEAT_WAIT)
-      && event.param1 == OIS::KC_BACK
-    ){
-        if (auto_completition_.size() > 0) ResetAutoCompletion();
-        else{
-            if (cursor_position_ > 0){
-                input_line_.erase(cursor_position_ - 1, 1);
-                -- cursor_position_;
-            }
-        }
-    }
-    // Move cursor to left.
-    else if (
-      (event.type == VGears::ET_KEY_PRESS || event.type == VGears::ET_KEY_REPEAT_WAIT)
-      && event.param1 == OIS::KC_LEFT
-    ){
-        if (auto_completition_.size() > 0){
-            input_line_ += auto_completition_[auto_completition_line_];
-            ResetAutoCompletion();
-        }
-        if (cursor_position_ > 0) -- cursor_position_;
-    }
-    // Move cursor to right.
-    else if (
-      (event.type == VGears::ET_KEY_PRESS || event.type == VGears::ET_KEY_REPEAT_WAIT)
-      && event.param1 == OIS::KC_RIGHT
-    ){
-        if (auto_completition_.size() > 0){
-            input_line_ += auto_completition_[auto_completition_line_];
-            ResetAutoCompletion();
-        }
-        if (cursor_position_ <  input_line_.size()) ++ cursor_position_;
+    if (event.type == VGears::ET_MOUSE_SCROLL){
+        if (event.param1 > 0) ScrollUp();
+        else if (event.param1 < 0) ScrollDown();
+        return;
     }
-    else if (event.type == VGears::ET_KEY_PRESS && event.param1 == OIS::KC_ESCAPE){
-        input_line_.clear();
-        cursor_position_ = 0;
-        ResetAutoCompletion();
+    const bool pressed = event.type == VGears::ET_KEY_PRESS;
+    if (!pressed && event.type != VGears::ET_KEY_REPEAT_WAIT) return;
+    if (pressed && InputPress(static_cast<int>(event.param1))) return;
+    switch (static_cast<int>(event.param1)){
+        case OIS::KC_UP: PreviousHistoryLine(); break;
+        case OIS::KC_DOWN: NextHistoryLine(); break;
+        case OIS::KC_PGUP: ScrollUp(); break;
+        case OIS::KC_PGDOWN: ScrollDown(); break;
+        case OIS::KC_DELETE: DeleteAfterCursor(); break;
+        case OIS::KC_BACK: DeleteBeforeCursor(); break;
+        case OIS::KC_LEFT:
+            AcceptCompletion();
+            if (cursor_position_ > 0) -- cursor_position_;
+            break;
+        case OIS::KC_RIGHT:
+            AcceptCompletion();
+            if (cursor_position_ < input_line_.size()) ++ cursor_position_;
+            break;
+        default: InsertCharacter(TranslateNumpad(event));
     }
-    // Move cursor to start of string.
-    else if (event.type == VGears::ET_KEY_PRESS && event.param1 == OIS::KC_HOME){
-        cursor_position_ = 0;
-        if (auto_completition_.size() > 0){
-            input_line_ += auto_completition_[auto_completition_line_];
+}
+
+bool Console::InputPress(const int key){
+    switch (key){
+        case OIS::KC_RETURN:
+        case OIS::KC_NUMPADENTER:
+            if (input_line_.size() == 0) return false;
+            ExecuteInput();
+            return true;
+        case OIS::KC_TAB: CompleteInput(); return true;
+        // Remove console.
+        case OIS::KC_GRAVE: SetToHide(); return true;
+        case OIS::KC_ESCAPE:
+            input_line_.clear();
+            cursor_position_ = 0;
             ResetAutoCompletion();
-        }
+            return true;
+        case OIS::KC_HOME:
+            AcceptCompletion();
+            cursor_position_ = 0;
+            return true;
+        case OIS::KC_END:
+            AcceptCompletion();
+            cursor_position_ = input_line_.size();
+            return true;
+        default: return false;
     }
-    // Move cursor to end of string.
-    else if (event.type == VGears::ET_KEY_PRESS && event.param1 == OIS::KC_END){
-        if (auto_completition_.size() > 0){
-            input_line_ += auto_completition_[auto_completition_line_];
-            ResetAutoCompletion();
+}
+
+void Console::ExecuteInput(){
+    if (auto_completition_.size() > 0)
+        input_line_ += auto_completition_[auto_completition_line_];
+    AddTextToOutput(input_line_);
+    AddInputToHistory();
+    // Backslashed text are console commands, otherwise - script commands.
+    if ('\\' == input_line_[0] || '/' == input_line_[0]){
+        if (input_line_.size() > 1){
+            // Remove backslash.
+            input_line_.erase(0, 1);
+            ExecuteCommand(input_line_);
         }
-        cursor_position_ = input_line_.size();
     }
-    // Input Ascii character.
-    else if (
-      (event.type == VGears::ET_KEY_PRESS || event.type == VGears::ET_KEY_REPEAT_WAIT)
-      && input_line_.size() < line_width_
-    ){
-        char legalchars[]
-          = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
-            "~!@#$%^&*()-_=+?{[]}|\\;:'\"<>,./? ";
-        char txt = TranslateNumpad(event);
-        for (unsigned int c = 0; c < sizeof(legalchars) - 1; ++ c){
-            if (legalchars[c] == txt){
-                std::string::iterator i = input_line_.begin() + cursor_position_;
-                input_line_.insert(i, txt);
-                ++ cursor_position_;
-                ResetAutoCompletion();
-                break;
-            }
-        }
+    else ExecuteScript();
+    input_line_.clear();
+    cursor_position_ = 0;
+    ResetAutoCompletion();
+}
+
+void Console::AcceptCompletion(){
+    if (auto_completition_.size() == 0) return;
+    input_line_ += auto_completition_[auto_completition_line_];
+    ResetAutoCompletion();
+}
+
+void Console::PreviousHistoryLine(){
+    if (history_line_cycle_index_ >= static_cast<int>(history_.size()) - 1) return;
+    ++ history_line_cycle_index_;
+    SetInputLineFromHistory();
+}
+
+void Console::NextHistoryLine(){
+    if (history_line_cycle_index_ <= 0) return;
+    -- history_line_cycle_index_;
+    SetInputLineFromHistory();
+}
+
+void Console::ScrollUp(){
+    if (display_line_ > 0) display_line_ -= 1;
+}
+
+void Console::ScrollDown(){
+    if (display_line_ < output_line_.size()) display_line_ += 1;
+}
+
+void Console::DeleteAfterCursor(){
+    if (auto_completition_.size() > 0) ResetAutoCompletion();
+    else if (cursor_position_ < input_line_.size()) input_line_.erase(cursor_position_, 1);
+}
+
+void Console::DeleteBeforeCursor(){
+    if (auto_completition_.size() > 0) ResetAutoCompletion();
+    else if (cursor_position_ > 0){
+        input_line_.erase(cursor_position_ - 1, 1);
+        -- cursor_position_;
     }
 }
 
+void Console::InsertCharacter(const char character){
+    static const std::string LEGAL_CHARACTERS
+      = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
+        "~!@#$%^&*()-_=+?{[]}|\\;:'\"<>,./? ";
+    if (input_line_.size() >= line_width_) return;
+    if (LEGAL_CHARACTERS.find(character) == std::string::npos) return;
+    input_line_.insert(input_line_.begin() + cursor_position_, character);
+    ++ cursor_position_;
+    ResetAutoCompletion();
+}
+
 char Console::TranslateNumpad(const VGears::Event& event){
     switch (static_cast<int>(event.param1)){
         case OIS::KC_NUMPAD0: return '0';

+ 56 - 0
src/engine/ui/Console.h

@@ -166,6 +166,62 @@ class Console : public Ogre::Singleton<Console>, public Ogre::LogListener{
          */
         char TranslateNumpad(const VGears::Event& event);
 
+        /**
+         * Does what a key does when it is pressed, but not while it is held.
+         *
+         * @param[in] key The key.
+         * @return False if the key does nothing when pressed.
+         */
+        bool InputPress(const int key);
+
+        /**
+         * Runs the input line, as a console command if it starts with a slash or a backslash and as a
+         * script otherwise.
+         */
+        void ExecuteInput();
+
+        /**
+         * Adds the suggested completion, if there is one, to the input line.
+         */
+        void AcceptCompletion();
+
+        /**
+         * Shows the previous line of the history.
+         */
+        void PreviousHistoryLine();
+
+        /**
+         * Shows the next line of the history.
+         */
+        void NextHistoryLine();
+
+        /**
+         * Scrolls the output a line up.
+         */
+        void ScrollUp();
+
+        /**
+         * Scrolls the output a line down.
+         */
+        void ScrollDown();
+
+        /**
+         * Deletes the character after the cursor, or the suggested completion.
+         */
+        void DeleteAfterCursor();
+
+        /**
+         * Deletes the character before the cursor, or the suggested completion.
+         */
+        void DeleteBeforeCursor();
+
+        /**
+         * Writes a character at the cursor, if it can be written and there is room.
+         *
+         * @param[in] character The character.
+         */
+        void InsertCharacter(const char character);
+
         /**
          * The console width.
          */

+ 179 - 153
src/installer/gui/MainWindow.cpp

@@ -440,31 +440,52 @@ void MainWindow::on_btn_data_run_clicked(){
     }
     // Normalize the output path.
     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()){
         StartVideoExtraction(output);
         return;
     }
-
-    // Locate the V-Gears data folder to copy, asking if it can't be found.
     const bool copy_data = main_window_->chk_copy_data->checkState() == Qt::Checked;
     QString game_data;
-    if (copy_data){
-        game_data = InstallSteps::FindGameDataDir();
-        if (game_data.isEmpty()){
-            game_data = QFileDialog::getExistingDirectory(
-              this, tr("Select the V-Gears 'data' folder to copy"), QCoreApplication::applicationDirPath()
-            );
-            if (game_data.isEmpty()) return;
-        }
+    if (copy_data && !FindDataToCopy(game_data)) return;
+    // Check everything that can be checked before touching the disk.
+    const bool clean = main_window_->chk_clean_install->checkState() == Qt::Checked;
+    if (!CheckInstallation(output, copy_data, game_data, clean)) return;
+    // The audio is converted with external programs: say now, before anything is extracted, if
+    // they are missing.
+    if (!ResolveMissingTools(CurrentOptions())) return;
+    // Everything is checked: the previous installation can be deleted.
+    if (clean && !DeletePreviousInstallation(output)) return;
+    // From here on, the installation directory is being changed: until it finishes, the record
+    // says so.
+    install_dir_ = output;
+    InstallSteps::MarkInstallStarted(output, CurrentOptions(), disk_image_.getId());
+    main_window_->data_progress_bar->setValue(0);
+    if (!ExtractDisk(output)) return;
+    if (!PrepareInstallationDir(output, copy_data, game_data)) return;
+    // Collect every message of the installation in one place: the log file, the log window and
+    // the summary.
+    UpdateToolLocations(output);
+    OpenInstallLog(output, false);
+    StartConversion(output);
+}
+
+bool MainWindow::FindDataToCopy(QString& game_data){
+    game_data = InstallSteps::FindGameDataDir();
+    if (game_data.isEmpty()){
+        game_data = QFileDialog::getExistingDirectory(
+          this, tr("Select the V-Gears 'data' folder to copy"), QCoreApplication::applicationDirPath()
+        );
     }
+    return !game_data.isEmpty();
+}
 
-    // Check everything that can be checked before touching the disk. A clean installation deletes the field maps
-    // that are already installed.
-    const bool clean = main_window_->chk_clean_install->checkState() == Qt::Checked;
+bool MainWindow::CheckInstallation(
+  const QString& output, const bool copy_data, const QString& game_data, const bool clean
+){
     InstallSteps::PreflightResult preflight
       = InstallSteps::RunPreflight(disk_image_, output, copy_data, game_data, clean);
+    // A clean installation deletes the field maps that are already installed.
     const bool fields_installed = !clean && QFile::exists(output + "game/field/maps/_fields.xml");
     for (const std::string& problem : InstallRules::Problems(CurrentOptions(), fields_installed))
         preflight.errors << QString::fromStdString(problem);
@@ -473,162 +494,167 @@ void MainWindow::on_btn_data_run_clicked(){
           this, tr("The installation can't start"),
           tr("Fix these problems and try again:\n\n- %1").arg(preflight.errors.join("\n- "))
         );
-        return;
+        return false;
     }
-    if (!preflight.warnings.isEmpty()){
-        const auto answer = QMessageBox::warning(
-          this, tr("Warnings"), tr("%1\n\nContinue anyway?").arg(preflight.warnings.join("\n")),
-          QMessageBox::Yes | QMessageBox::No, QMessageBox::No
+    if (preflight.warnings.isEmpty()) return true;
+    const auto answer = QMessageBox::warning(
+      this, tr("Warnings"), tr("%1\n\nContinue anyway?").arg(preflight.warnings.join("\n")),
+      QMessageBox::Yes | QMessageBox::No, QMessageBox::No
+    );
+    return answer == QMessageBox::Yes;
+}
+
+bool MainWindow::DeletePreviousInstallation(const QString& output){
+    if (!InstallLayout::IsInstallation(output.toStdString())) return true;
+    const auto answer = QMessageBox::warning(
+      this, tr("Clean install"),
+      tr("The data of the installation in %1 will be deleted before installing. The saves, the controls, the "
+         "game configuration and the videos are kept.\n\nContinue?").arg(QDir::toNativeSeparators(output)),
+      QMessageBox::Yes | QMessageBox::No, QMessageBox::No
+    );
+    if (answer != QMessageBox::Yes) return false;
+    const InstallLayout::CleanResult cleaned = InstallLayout::CleanInstallation(output.toStdString());
+    if (!cleaned.errors.empty()){
+        QStringList errors;
+        for (const std::string& error : cleaned.errors) errors << QString::fromStdString(error);
+        QMessageBox::critical(
+          this, tr("Clean install"),
+          tr("The previous installation could not be deleted:\n\n- %1").arg(errors.join("\n- "))
         );
-        if (answer != QMessageBox::Yes) return;
+        return false;
     }
-    // The audio is converted with external programs: say now, before anything is extracted, if they are missing.
-    if (!ResolveMissingTools(CurrentOptions())) return;
-    // Everything is checked: the previous installation can be deleted.
-    if (clean && InstallLayout::IsInstallation(output.toStdString())){
-        const auto answer = QMessageBox::warning(
-          this, tr("Clean install"),
-          tr("The data of the installation in %1 will be deleted before installing. The saves, the controls, the "
-             "game configuration and the videos are kept.\n\nContinue?").arg(QDir::toNativeSeparators(output)),
-          QMessageBox::Yes | QMessageBox::No, QMessageBox::No
+    main_window_->data_log->append(
+      tr("Deleted the previous installation (%1 files and folders).").arg(cleaned.removed)
+    );
+    return true;
+}
+
+std::function<void(float)> MainWindow::ShowPhase(
+  const InstallSteps::Phase phase, const QString& text
+){
+    // The extraction and the copy run in the window's thread: the progress is shown as they go,
+    // and the window is repainted, without taking the clicks (nothing can be started twice).
+    return [this, phase, text](float value){
+        ShowProgress(InstallSteps::OverallProgress(phase, value));
+        main_window_->label_progress->setText(text);
+        QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
+    };
+}
+
+bool MainWindow::ExtractDisk(const QString& output){
+    if (!disk_image_.extractImage(
+      output.toStdString(),
+      ShowPhase(InstallSteps::Phase::EXTRACT, tr("Extracting the install disk..."))
+    )){
+        QMessageBox::critical(this, tr("Extraction error"), tr("Failed to extract ISO file."));
+        return false;
+    }
+    if (disk_image_.getContentPath().empty()){
+        QMessageBox::critical(this, tr("Extraction error"), tr("Extracted data path is invalid."));
+        return false;
+    }
+    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"))
         );
-        if (answer != QMessageBox::Yes) return;
-        const InstallLayout::CleanResult cleaned = InstallLayout::CleanInstallation(output.toStdString());
-        if (!cleaned.errors.empty()){
-            QStringList errors;
-            for (const std::string& error : cleaned.errors) errors << QString::fromStdString(error);
+        return false;
+    }
+    return true;
+}
+
+bool MainWindow::PrepareInstallationDir(
+  const QString& output, const bool copy_data, const QString& game_data
+){
+    // 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.
+        if (!InstallSteps::CopyGameFiles(
+          game_data, output, ShowPhase(InstallSteps::Phase::COPY, tr("Copying the V-Gears data files..."))
+        )){
             QMessageBox::critical(
-              this, tr("Clean install"),
-              tr("The previous installation could not be deleted:\n\n- %1").arg(errors.join("\n- "))
+              this, tr("Copy error"), tr("Failed to copy the V-Gears data files to the installation directory.")
             );
-            return;
+            return false;
         }
-        main_window_->data_log->append(tr("Deleted the previous installation (%1 files and folders).").arg(cleaned.removed));
+        main_window_->data_log->append(tr("Data files copied."));
     }
-    // From here on, the installation directory is being changed: until it finishes, the record says so.
-    install_dir_ = output;
-    InstallSteps::MarkInstallStarted(output, CurrentOptions(), disk_image_.getId());
-    {
-        // The extraction and the copy run here, in the window's thread: the progress is shown as they go, and the
-        // window is repainted, without taking the clicks (nothing can be started twice).
-        main_window_->data_progress_bar->setValue(0);
-        const auto show_phase = [this](InstallSteps::Phase phase, const QString& text){
-            return [this, phase, text](float value){
-                ShowProgress(InstallSteps::OverallProgress(phase, value));
-                main_window_->label_progress->setText(text);
-                QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
-            };
-        };
-        bool extraction_success = disk_image_.extractImage(
-          output.toStdString(), show_phase(InstallSteps::Phase::EXTRACT, tr("Extracting the install disk..."))
+    // The installer's Ogre setup loads plugins.cfg and resources.cfg from the working directory
+    // (and writes logs/ogre.log there), so run from the installation directory. The plugins
+    // themselves are looked for in the same places as the game does (see
+    // VGears::OgrePlugins::SearchDirectories).
+    if (!QFile::exists(output + "plugins.cfg") || !QFile::exists(output + "resources.cfg")){
+        QMessageBox::critical(
+          this, tr("Missing configuration files"),
+          tr("The installation directory must contain plugins.cfg and resources.cfg.\n\n"
+             "Enable 'Copy V-Gears data files' to put them there.")
         );
-        if (!extraction_success) {
-            QMessageBox::critical(this, tr("Extraction error"), tr("Failed to extract ISO file."));
-            return;
-        }
+        return false;
+    }
+    if (!QDir::setCurrent(output)){
+        QMessageBox::critical(this, tr("Output error"), tr("Could not enter the installation directory."));
+        return false;
+    }
+    const QString problem = InstallSteps::PrepareInstallation(output);
+    if (!problem.isEmpty()){
+        QMessageBox::critical(
+          this, tr("Output error"), tr("Could not prepare the installation directory:\n\n%1").arg(problem)
+        );
+        return false;
+    }
+    return true;
+}
 
-      QString input = QDir::fromNativeSeparators(QString::fromStdString(disk_image_.getContentPath()));
-      if (input.isEmpty()) {
-        QMessageBox::critical(this, tr("Extraction error"), tr("Extracted data path is invalid."));
-        return;
-      }
-      if (!input.endsWith("/")) input += "/";
-
-        // Ensure required files are in the input dir
-        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.
-            if (!InstallSteps::CopyGameFiles(
-              game_data, output, show_phase(InstallSteps::Phase::COPY, tr("Copying the V-Gears data files..."))
-            )){
-                QMessageBox::critical(
-                  this, tr("Copy error"), tr("Failed to copy the V-Gears data files to the installation directory.")
-                );
-                return;
-            }
-            main_window_->data_log->append(tr("Data files copied."));
-        }
-        // The installer's Ogre setup loads plugins.cfg and resources.cfg from the working directory (and writes
-        // logs/ogre.log there), so run from the installation directory. The plugins themselves are looked for in the
-        // same places as the game does (see VGears::OgrePlugins::SearchDirectories).
-        if (!QFile::exists(output + "plugins.cfg") || !QFile::exists(output + "resources.cfg")){
-            QMessageBox::critical(
-              this, tr("Missing configuration files"),
-              tr("The installation directory must contain plugins.cfg and resources.cfg.\n\n"
-                 "Enable 'Copy V-Gears data files' to put them there.")
-            );
-            return;
-        }
-        if (!QDir::setCurrent(output)){
-            QMessageBox::critical(this, tr("Output error"), tr("Could not enter the installation directory."));
-            return;
-        }
-        const QString problem = InstallSteps::PrepareInstallation(output);
-        if (!problem.isEmpty()){
-            QMessageBox::critical(
-              this, tr("Output error"), tr("Could not prepare the installation directory:\n\n%1").arg(problem)
+void MainWindow::StartConversion(const QString& output){
+    try{
+        // Parse advanced options.
+        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."
             );
-            return;
         }
-        // Collect every message of the installation in one place: the log file, the log window and the summary.
-        UpdateToolLocations(output);
-        OpenInstallLog(output, false);
-        // Start data conversion
-        try{
-            // Parse advanced options.
-            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."
+        const std::string output_path = QDir::toNativeSeparators(output).toStdString();
+        const auto write_line = [this](const std::string log_line, int level, bool as_progress = false){
+            InstallLog::Get().Add(log_line);
+            if (as_progress){
+                const QString text = QString::fromStdString(log_line);
+                QMetaObject::invokeMethod(
+                  this, [this, text](){main_window_->label_progress->setText(text);}, Qt::QueuedConnection
                 );
             }
-            const std::string output_path = QDir::toNativeSeparators(output).toStdString();
-            const auto write_line = [this](const std::string log_line, int level, bool as_progress = false){
-                InstallLog::Get().Add(log_line);
-                if (as_progress){
-                    const QString text = QString::fromStdString(log_line);
-                    QMetaObject::invokeMethod(
-                      this, [this, text](){main_window_->label_progress->setText(text);}, Qt::QueuedConnection
-                    );
-                }
-            };
-            // 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;
-                OnInstallStarted();
-                worker_ = std::thread([this, options, output_path, write_line](){RunInstallation(options, output_path, write_line);});
-            }
-            else{
-                installer_ = std::make_unique<DataInstaller>(disk_image_, output_path, options, write_line);
-                OnInstallStarted();
-            }
+        };
+        // 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;
+            OnInstallStarted();
+            worker_ = std::thread([this, options, output_path, write_line](){
+                RunInstallation(options, output_path, write_line);
+            });
         }
-        catch (const std::exception& ex){
-            InstallLog::Get().Add(std::string("[ERROR] Installation failed: ") + ex.what());
-            InstallLog::Get().Close();
-            installer_.reset();
-            OnInstallStopped();
-            QMessageBox::critical(this, tr("Installation error"), ex.what());
+        else{
+            installer_ = std::make_unique<DataInstaller>(disk_image_, output_path, options, write_line);
+            OnInstallStarted();
         }
     }
+    catch (const std::exception& ex){
+        InstallLog::Get().Add(std::string("[ERROR] Installation failed: ") + ex.what());
+        InstallLog::Get().Close();
+        installer_.reset();
+        OnInstallStopped();
+        QMessageBox::critical(this, tr("Installation error"), ex.what());
+    }
 }
 
 void MainWindow::on_chk_advanced_options_stateChanged(){

+ 66 - 0
src/installer/gui/MainWindow.h

@@ -24,6 +24,7 @@
 #include <vector>
 #include "installer/steps/DataInstaller.h"
 #include "installer/formats/DiskImage.h"
+#include "installer/steps/InstallSteps.h"
 #include "installer/steps/ExternalTools.h"
 
 class QCheckBox;
@@ -167,6 +168,71 @@ class MainWindow : public QMainWindow{
          */
         void OpenInstallLog(const QString& dir, bool append);
 
+        /**
+         * Finds the V-Gears data folder to copy, asking for it if it can't be found.
+         *
+         * @param[out] game_data The folder.
+         * @return False if the user did not choose one.
+         */
+        bool FindDataToCopy(QString& game_data);
+
+        /**
+         * Checks that the installation can start, telling the problems and asking about the warnings.
+         *
+         * @param[in] output The installation directory.
+         * @param[in] copy_data If the V-Gears data files are copied.
+         * @param[in] game_data The folder with the data files.
+         * @param[in] clean If the previous installation is deleted.
+         * @return True if the installation can go on.
+         */
+        bool CheckInstallation(
+          const QString& output, const bool copy_data, const QString& game_data, const bool clean
+        );
+
+        /**
+         * Deletes the installation in a directory, if there is one, after asking.
+         *
+         * @param[in] output The installation directory.
+         * @return True if the installation can go on.
+         */
+        bool DeletePreviousInstallation(const QString& output);
+
+        /**
+         * Creates a function that shows the progress of a part of the installation.
+         *
+         * @param[in] phase The part.
+         * @param[in] text Description of what is done.
+         * @return Function that takes the progress of the part.
+         */
+        std::function<void(float)> ShowPhase(const InstallSteps::Phase phase, const QString& text);
+
+        /**
+         * Extracts the install disk and checks that it has the files that are needed.
+         *
+         * @param[in] output The installation directory.
+         * @return True if the installation can go on.
+         */
+        bool ExtractDisk(const QString& output);
+
+        /**
+         * Copies the data files to the installation directory and prepares it.
+         *
+         * @param[in] output The installation directory.
+         * @param[in] copy_data If the V-Gears data files are copied.
+         * @param[in] game_data The folder with the data files.
+         * @return True if the installation can go on.
+         */
+        bool PrepareInstallationDir(
+          const QString& output, const bool copy_data, const QString& game_data
+        );
+
+        /**
+         * Starts the conversion of the data, which goes on after this returns.
+         *
+         * @param[in] output The installation directory.
+         */
+        void StartConversion(const QString& output);
+
         /**
          * Extracts the videos of the selected game disk, in the worker thread.
          *