From d5a223dc47a4c06eafb85cac34c18788884f8252 Mon Sep 17 00:00:00 2001 From: the-e Date: Wed, 11 Nov 2026 19:47:35 +0100 Subject: [PATCH 01/26] Editors: fix overlapping selection groups QtFRED gave the group numbers 1 to 9 to the group functions as bit masks. Thus group 3 was the same as groups 1 and 2. Also, a ship in no group has the value -1, and -1 has all bits set. Such a ship matched each group in QtFRED and FRED2. Each group is now one bit, the same as in FRED2. The new shared functions ship_in_editor_group() and ship_set_editor_group() hold the meaning of -1, and QtFRED and FRED2 both use them. A ship in no group keeps -1, so the mission save writes no group data for it. Co-Authored-By: Claude Opus 5.5 --- code/missioneditor/common.cpp | 16 +++++++++++++ code/missioneditor/common.h | 6 +++++ fred2/fredview.cpp | 6 ++--- qtfred/src/ui/FredView.cpp | 43 +++++++++++++++-------------------- 4 files changed, 43 insertions(+), 28 deletions(-) diff --git a/code/missioneditor/common.cpp b/code/missioneditor/common.cpp index 8642c9a941a..5cdd449421e 100644 --- a/code/missioneditor/common.cpp +++ b/code/missioneditor/common.cpp @@ -110,6 +110,22 @@ anchor_t target_to_anchor(int target) return anchor_t(target); } +bool ship_in_editor_group(const ship& shipp, int group_bit) +{ + // -1 has all bits set, so test it first. + return shipp.group >= 0 && (shipp.group & group_bit) != 0; +} + +void ship_set_editor_group(ship& shipp, int group_bit, bool in_group) +{ + if (in_group) { + shipp.group = (shipp.group < 0 ? 0 : shipp.group) | group_bit; + } else if (shipp.group >= 0) { + // A ship in no group keeps -1, so that the mission save writes no group data for it. + shipp.group &= ~group_bit; + } +} + void update_custom_wing_indexes() { int i; diff --git a/code/missioneditor/common.h b/code/missioneditor/common.h index 698f4d88b68..8aebf3a2a63 100644 --- a/code/missioneditor/common.h +++ b/code/missioneditor/common.h @@ -45,6 +45,12 @@ int anchor_to_target(anchor_t anchor); anchor_t target_to_anchor(int target); +// ship::group holds the editor selection groups, one bit for each group. The value -1 means "in no group": +// a mission without +Group gives -1, and the mission save writes +Group only for a value of 0 or more. +class ship; +bool ship_in_editor_group(const ship& shipp, int group_bit); +void ship_set_editor_group(ship& shipp, int group_bit, bool in_group); + // Rebuild Starting_wings[], Squadron_wings[], TVT_wings[] from their parallel // name arrays via wing_name_lookup. void update_custom_wing_indexes(); diff --git a/fred2/fredview.cpp b/fred2/fredview.cpp index 15b7f251aff..b47dfcbdb78 100644 --- a/fred2/fredview.cpp +++ b/fred2/fredview.cpp @@ -4494,7 +4494,7 @@ void CFREDView::OnGroup(UINT nID) objp = GET_FIRST(&obj_used_list); while (objp != END_OF_LIST(&obj_used_list)) { if (objp->type == OBJ_SHIP) { - if (Ships[objp->instance].group & n) + if (ship_in_editor_group(Ships[objp->instance], n)) mark_object(OBJ_INDEX(objp)); } @@ -4510,13 +4510,13 @@ void CFREDView::OnSetGroup(UINT nID) object *objp; for (i=0; iflags[Object::Object_Flags::Marked]) { if (objp->type == OBJ_SHIP) { - Ships[objp->instance].group |= n; + ship_set_editor_group(Ships[objp->instance], n, true); } else err = 1; diff --git a/qtfred/src/ui/FredView.cpp b/qtfred/src/ui/FredView.cpp index a17fef0d342..687339b7743 100644 --- a/qtfred/src/ui/FredView.cpp +++ b/qtfred/src/ui/FredView.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include @@ -2910,34 +2911,26 @@ void FredView::on_actionDelete_Wing_triggered(bool) { } } void FredView::initializeGroupActions() { - // This is a bit ugly but it's easier than iterating though all actions in the menu... - connect(ui->actionGroup_1, &QAction::triggered, this, [this]() { onGroupSelected(1); }); - connect(ui->actionGroup_2, &QAction::triggered, this, [this]() { onGroupSelected(2); }); - connect(ui->actionGroup_3, &QAction::triggered, this, [this]() { onGroupSelected(3); }); - connect(ui->actionGroup_4, &QAction::triggered, this, [this]() { onGroupSelected(4); }); - connect(ui->actionGroup_5, &QAction::triggered, this, [this]() { onGroupSelected(5); }); - connect(ui->actionGroup_6, &QAction::triggered, this, [this]() { onGroupSelected(6); }); - connect(ui->actionGroup_7, &QAction::triggered, this, [this]() { onGroupSelected(7); }); - connect(ui->actionGroup_8, &QAction::triggered, this, [this]() { onGroupSelected(8); }); - connect(ui->actionGroup_9, &QAction::triggered, this, [this]() { onGroupSelected(9); }); - - - connect(ui->actionSetGroup_1, &QAction::triggered, this, [this]() { onSetGroup(1); }); - connect(ui->actionSetGroup_2, &QAction::triggered, this, [this]() { onSetGroup(2); }); - connect(ui->actionSetGroup_3, &QAction::triggered, this, [this]() { onSetGroup(3); }); - connect(ui->actionSetGroup_4, &QAction::triggered, this, [this]() { onSetGroup(4); }); - connect(ui->actionSetGroup_5, &QAction::triggered, this, [this]() { onSetGroup(5); }); - connect(ui->actionSetGroup_6, &QAction::triggered, this, [this]() { onSetGroup(6); }); - connect(ui->actionSetGroup_7, &QAction::triggered, this, [this]() { onSetGroup(7); }); - connect(ui->actionSetGroup_8, &QAction::triggered, this, [this]() { onSetGroup(8); }); - connect(ui->actionSetGroup_9, &QAction::triggered, this, [this]() { onSetGroup(9); }); + const std::array selectActions{ui->actionGroup_1, ui->actionGroup_2, ui->actionGroup_3, + ui->actionGroup_4, ui->actionGroup_5, ui->actionGroup_6, ui->actionGroup_7, ui->actionGroup_8, + ui->actionGroup_9}; + const std::array setActions{ui->actionSetGroup_1, ui->actionSetGroup_2, ui->actionSetGroup_3, + ui->actionSetGroup_4, ui->actionSetGroup_5, ui->actionSetGroup_6, ui->actionSetGroup_7, ui->actionSetGroup_8, + ui->actionSetGroup_9}; + + // Each group is one bit of ship::group, the same as in FRED2. + for (size_t i = 0; i < selectActions.size(); ++i) { + const int bit = 1 << static_cast(i); + connect(selectActions[i], &QAction::triggered, this, [this, bit]() { onGroupSelected(bit); }); + connect(setActions[i], &QAction::triggered, this, [this, bit]() { onSetGroup(bit); }); + } } void FredView::onGroupSelected(int group) { fred->unmark_all(); auto objp = GET_FIRST(&obj_used_list); while (objp != END_OF_LIST(&obj_used_list)) { if (objp->type == OBJ_SHIP) { - if (Ships[objp->instance].group & group) { + if (ship_in_editor_group(Ships[objp->instance], group)) { fred->markObject(OBJ_INDEX(objp)); } } @@ -2948,15 +2941,15 @@ void FredView::onGroupSelected(int group) { void FredView::onSetGroup(int group) { bool err = false; - for (auto i = 0; i < MAX_SHIPS; i++) { - Ships[i].group &= ~group; + for (auto& shipp : Ships) { + ship_set_editor_group(shipp, group, false); } auto objp = GET_FIRST(&obj_used_list); while (objp != END_OF_LIST(&obj_used_list)) { if (objp->flags[Object::Object_Flags::Marked]) { if (objp->type == OBJ_SHIP) { - Ships[objp->instance].group |= group; + ship_set_editor_group(Ships[objp->instance], group, true); } else { err = true; From e79ef1708da60e5aa4c059ffdae51ce04327f8fd Mon Sep 17 00:00:00 2001 From: the-e Date: Wed, 11 Nov 2026 19:47:41 +0100 Subject: [PATCH 02/26] QtFRED: keep the wing arrival distance when the target changes When the user chose a new arrival target, the wing editor set the arrival distance to 0, because the comparison was reversed. The save check then failed with "Arrival distance for wing ... must be greater than 0". The distance now stays. The editor raises it to the minimum for the new target only if it is smaller. Co-Authored-By: Claude Opus 5.5 --- qtfred/src/mission/dialogs/WingEditorDialogModel.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/qtfred/src/mission/dialogs/WingEditorDialogModel.cpp b/qtfred/src/mission/dialogs/WingEditorDialogModel.cpp index 38ab3537d58..9c6ba3bd8f2 100644 --- a/qtfred/src/mission/dialogs/WingEditorDialogModel.cpp +++ b/qtfred/src/mission/dialogs/WingEditorDialogModel.cpp @@ -1007,10 +1007,10 @@ void WingEditorDialogModel::setArrivalTarget(int targetIndex) modify(w->arrival_anchor, target_to_anchor(targetIndex)); - // Set the distance to minimum if current is smaller + // Keep the current distance. Raise it to the minimum for the new target only if it is smaller. int minDistance = getMinArrivalDistance(); - if (minDistance < w->arrival_distance) { - setArrivalDistance(0); + if (w->arrival_distance < minDistance) { + setArrivalDistance(minDistance); } modify(w->arrival_path_mask, 0); From 44361fb26e60e92fcb415286dc54ace9976dd1a6 Mon Sep 17 00:00:00 2001 From: the-e Date: Wed, 11 Nov 2026 19:47:54 +0100 Subject: [PATCH 03/26] Editors: share one minimum arrival distance rule The wing editor and the ship editor each had their own copy of the minimum arrival distance, and the copies were wrong in two ways: - With a special anchor such as "", both editors accepted a distance of 0. The mission parser changes 0 to 1, and the error checker rejects it. - The ship editor took the radius of the marked arriving ships. FRED2 and the wing editor take the radius of the target ship. arrival_location_uses_distance() in missionparse now gives the locations near a ship. The parser, the error checker, and both models use it. arrival_min_distance() in the shared editor code gives the minimum: 0 for a location without a distance, at least 1 otherwise, and min(500, 2 * target radius) near a real ship. The ship editor also checks the distance when the arrival location changes, and it does not accept negative distances. Co-Authored-By: Claude Opus 5.5 --- code/mission/missionparse.cpp | 30 ++++-- code/mission/missionparse.h | 3 + code/missioneditor/common.cpp | 17 ++++ code/missioneditor/common.h | 7 ++ .../ShipEditor/ShipEditorDialogModel.cpp | 94 +++++++------------ .../ShipEditor/ShipEditorDialogModel.h | 4 + .../mission/dialogs/WingEditorDialogModel.cpp | 49 +--------- qtfred/src/ui/util/ErrorChecker.cpp | 8 +- 8 files changed, 91 insertions(+), 121 deletions(-) diff --git a/code/mission/missionparse.cpp b/code/mission/missionparse.cpp index 848af7bc8e0..b34397b42e7 100644 --- a/code/mission/missionparse.cpp +++ b/code/mission/missionparse.cpp @@ -3493,11 +3493,7 @@ int parse_object(mission *pm, int /*flag*/, p_object *p_objp) stuff_int(&p_objp->arrival_distance); // Goober5000 - if ((p_objp->arrival_distance <= 0) && ( - (p_objp->arrival_location == ArrivalLocation::NEAR_SHIP) - || (p_objp->arrival_location == ArrivalLocation::IN_FRONT_OF_SHIP) || (p_objp->arrival_location == ArrivalLocation::IN_BACK_OF_SHIP) - || (p_objp->arrival_location == ArrivalLocation::ABOVE_SHIP) || (p_objp->arrival_location == ArrivalLocation::BELOW_SHIP) - || (p_objp->arrival_location == ArrivalLocation::TO_LEFT_OF_SHIP) || (p_objp->arrival_location == ArrivalLocation::TO_RIGHT_OF_SHIP) )) + if ((p_objp->arrival_distance <= 0) && arrival_location_uses_distance(p_objp->arrival_location)) { parse_warning_or_record("Arrival distance for ship %s cannot be %d — corrected to 1.", p_objp->name, p_objp->arrival_distance); p_objp->arrival_distance = 1; @@ -4956,11 +4952,7 @@ void parse_wing(mission *pm) stuff_int( &wingp->arrival_distance ); // Goober5000 - if ((wingp->arrival_distance <= 0) && ( - (wingp->arrival_location == ArrivalLocation::NEAR_SHIP) - || (wingp->arrival_location == ArrivalLocation::IN_FRONT_OF_SHIP) || (wingp->arrival_location == ArrivalLocation::IN_BACK_OF_SHIP) - || (wingp->arrival_location == ArrivalLocation::ABOVE_SHIP) || (wingp->arrival_location == ArrivalLocation::BELOW_SHIP) - || (wingp->arrival_location == ArrivalLocation::TO_LEFT_OF_SHIP) || (wingp->arrival_location == ArrivalLocation::TO_RIGHT_OF_SHIP) )) + if ((wingp->arrival_distance <= 0) && arrival_location_uses_distance(wingp->arrival_location)) { parse_warning_or_record("Arrival distance for wing %s cannot be %d — corrected to 1.", wingp->name, wingp->arrival_distance); wingp->arrival_distance = 1; @@ -8983,6 +8975,24 @@ int add_path_restriction() /** * Look for \, \, etc. */ +bool arrival_location_uses_distance(ArrivalLocation location) +{ + switch (location) { + case ArrivalLocation::NEAR_SHIP: + case ArrivalLocation::IN_FRONT_OF_SHIP: + case ArrivalLocation::IN_BACK_OF_SHIP: + case ArrivalLocation::ABOVE_SHIP: + case ArrivalLocation::BELOW_SHIP: + case ArrivalLocation::TO_LEFT_OF_SHIP: + case ArrivalLocation::TO_RIGHT_OF_SHIP: + return true; + case ArrivalLocation::AT_LOCATION: + case ArrivalLocation::FROM_DOCK_BAY: + return false; + } + return false; +} + anchor_t get_special_anchor(const char *name) { char tmp[NAME_LENGTH + 15]; diff --git a/code/mission/missionparse.h b/code/mission/missionparse.h index aa3236cc49f..9751c9386cf 100644 --- a/code/mission/missionparse.h +++ b/code/mission/missionparse.h @@ -290,6 +290,9 @@ enum class ArrivalLocation : int FROM_DOCK_BAY = 8 }; +// True for each arrival location near a target ship. Such a location needs an arrival distance greater than 0. +bool arrival_location_uses_distance(ArrivalLocation location); + // enums for departure locations. The integer values of these enums should match their counterparts in the departure location array #define MAX_DEPARTURE_NAMES 2 enum class DepartureLocation : int diff --git a/code/missioneditor/common.cpp b/code/missioneditor/common.cpp index 5cdd449421e..ed4b73a514f 100644 --- a/code/missioneditor/common.cpp +++ b/code/missioneditor/common.cpp @@ -21,6 +21,7 @@ #include "weapon/weapon.h" #include +#include // to keep track of data char Voice_abbrev_briefing[NAME_LENGTH]; @@ -110,6 +111,22 @@ anchor_t target_to_anchor(int target) return anchor_t(target); } +int arrival_min_distance(ArrivalLocation location, anchor_t anchor) +{ + if (!arrival_location_uses_distance(location)) + return 0; + + if (!anchor.isValid() || (anchor.value() & ANCHOR_SPECIAL_ARRIVAL)) + return 1; + + const int shipnum = anchor_to_target(anchor); + if (shipnum < 0 || shipnum >= MAX_SHIPS || Ships[shipnum].objnum < 0) + return 1; + + const float radius_distance = std::round(MIN_TARGET_ARRIVAL_MULTIPLIER * Objects[Ships[shipnum].objnum].radius); + return std::max(1, static_cast(std::min(MIN_TARGET_ARRIVAL_DISTANCE, radius_distance))); +} + bool ship_in_editor_group(const ship& shipp, int group_bit) { // -1 has all bits set, so test it first. diff --git a/code/missioneditor/common.h b/code/missioneditor/common.h index 8aebf3a2a63..bff0c669493 100644 --- a/code/missioneditor/common.h +++ b/code/missioneditor/common.h @@ -3,6 +3,8 @@ #include "mission/missionmessage.h" #include "ship/anchor_t.h" +enum class ArrivalLocation; + // Default AWACS range applied when the nebula intensity is unset or invalid constexpr float DEFAULT_NEBULA_RANGE = 3000.0f; @@ -45,6 +47,11 @@ int anchor_to_target(anchor_t anchor); anchor_t target_to_anchor(int target); +// The smallest arrival distance that the editors accept for an arrival location and anchor. +// It is 0 for a location that uses no distance. Near a ship it is min(500, 2 * radius of the target ship). +// For a special anchor (for example "") it is 1, because the distance must be greater than 0. +int arrival_min_distance(ArrivalLocation location, anchor_t anchor); + // ship::group holds the editor selection groups, one bit for each group. The value -1 means "in no group": // a mission without +Group gives -1, and the mission save writes +Group only for a value of 0 or more. class ship; diff --git a/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.cpp b/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.cpp index a0765e8ff5d..303fbb6d2ff 100644 --- a/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.cpp +++ b/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.cpp @@ -1161,6 +1161,8 @@ void ShipEditorDialogModel::setArrivalLocationIndex(const int value) } } } + // A change from "Hyperspace" to "Near Ship" needs a distance greater than 0. + enforceArrivalMinDist(); setModified(); _editor->missionChanged(); modelChanged(); @@ -1188,67 +1190,54 @@ bool ShipEditorDialogModel::arrivalNeedsTarget() const bool ShipEditorDialogModel::arrivalNeedsDistance() const { - switch (getArrivalLocation()) { - case ArrivalLocation::AT_LOCATION: - case ArrivalLocation::FROM_DOCK_BAY: - return false; - default: - return true; - } + return arrival_location_uses_distance(getArrivalLocation()); } int ShipEditorDialogModel::computeArrivalMinDist() const { - // Validation only applies when arriving near a ship (not hyperspace or dock bay) - if (getArrivalLocation() == ArrivalLocation::AT_LOCATION || - getArrivalLocation() == ArrivalLocation::FROM_DOCK_BAY) - return 0; - - // Validation doesn't apply to special anchors (negative value or ANCHOR_SPECIAL_ARRIVAL flag set) - if (_arrivalTarget < 0 || (_arrivalTarget & ANCHOR_SPECIAL_ARRIVAL)) - return 0; + // The same rule as the wing editor and FRED2: the radius of the target ship sets the minimum. + return arrival_min_distance(getArrivalLocation(), target_to_anchor(_arrivalTarget)); +} - // Compute the most restrictive minimum distance across all marked arriving ships - int max_d = 0; +void ShipEditorDialogModel::writeArrivalDistance(int value) +{ + _arrivalDist = value; for (auto* ptr = GET_FIRST(&obj_used_list); ptr != END_OF_LIST(&obj_used_list); ptr = GET_NEXT(ptr)) { - if (((ptr->type == OBJ_SHIP) || (ptr->type == OBJ_START)) && - ptr->flags[Object::Object_Flags::Marked] && - Ships[ptr->instance].wingnum < 0 && - Ships[ptr->instance].objnum >= 0) { - const int d = static_cast(std::min(MIN_TARGET_ARRIVAL_DISTANCE, - MIN_TARGET_ARRIVAL_MULTIPLIER * Objects[Ships[ptr->instance].objnum].radius)); - max_d = std::max(max_d, d); + if (((ptr->type == OBJ_SHIP) || (ptr->type == OBJ_START)) && (ptr->flags[Object::Object_Flags::Marked])) { + if (Ships[ptr->instance].wingnum < 0) { + Ships[ptr->instance].arrival_distance = value; + } } } - return max_d; } -void ShipEditorDialogModel::setArrivalTarget(const int value) +void ShipEditorDialogModel::enforceArrivalMinDist() { - if (_arrivalTarget == value) + const int min_dist = computeArrivalMinDist(); + if (min_dist <= 0 || _arrivalDist >= min_dist) return; - _arrivalTarget = value; - // Re-validate the existing arrival distance now that the target has changed. - // A target change from a special anchor to a real ship can make a previously - // acceptable distance too close. - const int min_dist = computeArrivalMinDist(); - if (min_dist > 0 && _arrivalDist > -min_dist && _arrivalDist < min_dist) { - const int clamped = (_arrivalDist < 0) ? -min_dist : min_dist; + // A minimum of 1 only prevents an invalid distance, so it needs no warning. + if (min_dist > 1) { QMessageBox::warning(nullptr, tr("Arrival Distance"), tr("Ship must arrive at least %1 meters away from target.\n" "Value has been reset to this. Use with caution!") .arg(min_dist)); - _arrivalDist = clamped; - for (auto* ptr = GET_FIRST(&obj_used_list); ptr != END_OF_LIST(&obj_used_list); ptr = GET_NEXT(ptr)) { - if (((ptr->type == OBJ_SHIP) || (ptr->type == OBJ_START)) && - ptr->flags[Object::Object_Flags::Marked] && - Ships[ptr->instance].wingnum < 0) { - Ships[ptr->instance].arrival_distance = clamped; - } - } } + writeArrivalDistance(min_dist); +} + +void ShipEditorDialogModel::setArrivalTarget(const int value) +{ + if (_arrivalTarget == value) + return; + _arrivalTarget = value; + + // Re-validate the existing arrival distance now that the target has changed. + // A target change from a special anchor to a real ship can make a previously + // acceptable distance too close. + enforceArrivalMinDist(); for (auto* ptr = GET_FIRST(&obj_used_list); ptr != END_OF_LIST(&obj_used_list); ptr = GET_NEXT(ptr)) { if (((ptr->type == OBJ_SHIP) || (ptr->type == OBJ_START)) && (ptr->flags[Object::Object_Flags::Marked])) { @@ -1272,25 +1261,8 @@ void ShipEditorDialogModel::setArrivalDistance(const int value) if (_arrivalDist == value) return; - const int min_dist = computeArrivalMinDist(); - int effective_value = value; - if (min_dist > 0 && value > -min_dist && value < min_dist) { - effective_value = (value < 0) ? -min_dist : min_dist; - QMessageBox::warning(nullptr, - tr("Arrival Distance"), - tr("Ship must arrive at least %1 meters away from target.\n" - "Value has been reset to this. Use with caution!") - .arg(min_dist)); - } - - _arrivalDist = effective_value; - for (auto* ptr = GET_FIRST(&obj_used_list); ptr != END_OF_LIST(&obj_used_list); ptr = GET_NEXT(ptr)) { - if (((ptr->type == OBJ_SHIP) || (ptr->type == OBJ_START)) && (ptr->flags[Object::Object_Flags::Marked])) { - if (Ships[ptr->instance].wingnum < 0) { - Ships[ptr->instance].arrival_distance = effective_value; - } - } - } + writeArrivalDistance(value); + enforceArrivalMinDist(); setModified(); _editor->missionChanged(); modelChanged(); diff --git a/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.h b/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.h index b69ab2034d1..3dcceeab7de 100644 --- a/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.h +++ b/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.h @@ -167,6 +167,10 @@ class ShipEditorDialogModel : public AbstractDialogModel { void shipCallsignClose(int baseShip); static int makeShipList(int* arr); int computeArrivalMinDist() const; + // Writes the arrival distance to the dialog and to each marked ship that is not in a wing. + void writeArrivalDistance(int value); + // Raises the arrival distance to computeArrivalMinDist() if it is smaller. + void enforceArrivalMinDist(); int _noDepartureWarp; int _noArrivalWarp; diff --git a/qtfred/src/mission/dialogs/WingEditorDialogModel.cpp b/qtfred/src/mission/dialogs/WingEditorDialogModel.cpp index 9c6ba3bd8f2..a2b985dafd1 100644 --- a/qtfred/src/mission/dialogs/WingEditorDialogModel.cpp +++ b/qtfred/src/mission/dialogs/WingEditorDialogModel.cpp @@ -199,13 +199,7 @@ bool WingEditorDialogModel::arrivalNeedsDistance() const if (!w) return false; - switch (w->arrival_location) { - case ArrivalLocation::AT_LOCATION: - case ArrivalLocation::FROM_DOCK_BAY: - return false; - default: - return true; - } + return arrival_location_uses_distance(w->arrival_location); } @@ -254,41 +248,8 @@ int WingEditorDialogModel::getMaxWaveThreshold() const int WingEditorDialogModel::getMinArrivalDistance() const { - if (!wingIsValid()) - return 0; - - const auto w = getCurrentWing(); - if (!w) - return 0; - - switch (w->arrival_location) { - case ArrivalLocation::AT_LOCATION: - case ArrivalLocation::FROM_DOCK_BAY: - return 0; - default: - break; - } - - const anchor_t anchor = w->arrival_anchor; - - // If special anchor or invalid, no radius to enforce - if (!anchor.isValid() || (anchor.value() & ANCHOR_SPECIAL_ARRIVAL)) - return 0; - - // Anchor should be a real ship - const int shipnum = anchor_to_target(anchor); - if (shipnum >= 0 && shipnum < MAX_SHIPS) { - const int objnum = Ships[shipnum].objnum; - if (objnum >= 0) { - const object& obj = Objects[objnum]; - - // Enforce at least min(500, 2.0 * target_radius) - float min_rad = std::round(MIN_TARGET_ARRIVAL_MULTIPLIER * obj.radius); - return std::min(MIN_TARGET_ARRIVAL_DISTANCE, min_rad); - } - } - - return 0; + const auto w = wingIsValid() ? getCurrentWing() : nullptr; + return w ? arrival_min_distance(w->arrival_location, w->arrival_anchor) : 0; } std::pair> WingEditorDialogModel::getLeaderList() const @@ -1035,9 +996,9 @@ void WingEditorDialogModel::setArrivalDistance(int newDistance) newDistance = 0; } - // Enforce safe min distance + // Enforce the minimum distance. It is 0 for a location that uses no distance. const int minD = getMinArrivalDistance(); - if (newDistance != 0 && std::abs(newDistance) < minD) { + if (newDistance < minD) { newDistance = minD; } diff --git a/qtfred/src/ui/util/ErrorChecker.cpp b/qtfred/src/ui/util/ErrorChecker.cpp index b943d7200c5..ad1e50797d8 100644 --- a/qtfred/src/ui/util/ErrorChecker.cpp +++ b/qtfred/src/ui/util/ErrorChecker.cpp @@ -433,9 +433,7 @@ int ErrorChecker::checkShips() { error("Ship \"%s\" has a negative departure delay", Ships[i].ship_name); } - if (Ships[i].arrival_location != ArrivalLocation::AT_LOCATION && - Ships[i].arrival_location != ArrivalLocation::FROM_DOCK_BAY && - Ships[i].arrival_distance <= 0) { + if (arrival_location_uses_distance(Ships[i].arrival_location) && Ships[i].arrival_distance <= 0) { error("Arrival distance for ship \"%s\" must be greater than 0", Ships[i].ship_name); } @@ -708,9 +706,7 @@ int ErrorChecker::checkWings() { error("Wing \"%s\" has a negative departure delay", Wings[i].name); } - if (Wings[i].arrival_location != ArrivalLocation::AT_LOCATION && - Wings[i].arrival_location != ArrivalLocation::FROM_DOCK_BAY && - Wings[i].arrival_distance <= 0) { + if (arrival_location_uses_distance(Wings[i].arrival_location) && Wings[i].arrival_distance <= 0) { error("Arrival distance for wing \"%s\" must be greater than 0", Wings[i].name); } From 0ea2871075d9a7b6c054450478aa40c9fda8b3c6 Mon Sep 17 00:00:00 2001 From: the-e Date: Wed, 11 Nov 2026 19:48:06 +0100 Subject: [PATCH 04/26] QtFRED: fix mixed-value spin boxes in multi-edit dialogs The Initial Status and Reinforcements dialogs show "-" in a spin box when the marked objects have different values. Two defects: - In the Initial Status dialog, the "-" text stayed after the box got a real value, so a real value at the minimum (for example a velocity of 0) also showed "-". - A typed value equal to the value under the "-" did not change the spin box, so Qt sent no signal and the dialog ignored the value. The new widget MixedValueSpinBox (a QSpinBox subclass) keeps the mixed state and the real minimum in members. setMixed() moves the minimum below the real range, so each value that the user enters is a change. The widget keeps typed values and arrow steps in the real range. setSingleValue() ends the mixed state. Both dialogs use the widget as a promoted widget, and the clamp code in the Reinforcements slots is removed. Co-Authored-By: Claude Opus 5.5 --- qtfred/source_groups.cmake | 2 + .../ui/dialogs/ReinforcementsEditorDialog.cpp | 36 +++---------- .../ShipEditor/ShipInitialStatusDialog.cpp | 34 +++++------- .../ShipEditor/ShipInitialStatusDialog.h | 2 + qtfred/src/ui/widgets/MixedValueSpinBox.cpp | 54 +++++++++++++++++++ qtfred/src/ui/widgets/MixedValueSpinBox.h | 38 +++++++++++++ qtfred/ui/ReinforcementsDialog.ui | 11 +++- qtfred/ui/ShipInitialStatus.ui | 13 +++-- 8 files changed, 134 insertions(+), 56 deletions(-) create mode 100644 qtfred/src/ui/widgets/MixedValueSpinBox.cpp create mode 100644 qtfred/src/ui/widgets/MixedValueSpinBox.h diff --git a/qtfred/source_groups.cmake b/qtfred/source_groups.cmake index 6718b68a21a..f81c73942dd 100644 --- a/qtfred/source_groups.cmake +++ b/qtfred/source_groups.cmake @@ -339,6 +339,8 @@ add_file_folder("Source/UI/Widgets" src/ui/widgets/ShipFlagCheckbox.cpp src/ui/widgets/SimpleListSelectDialog.cpp src/ui/widgets/SimpleListSelectDialog.h + src/ui/widgets/MixedValueSpinBox.cpp + src/ui/widgets/MixedValueSpinBox.h src/ui/widgets/MusicComboWidget.cpp src/ui/widgets/MusicComboWidget.h ) diff --git a/qtfred/src/ui/dialogs/ReinforcementsEditorDialog.cpp b/qtfred/src/ui/dialogs/ReinforcementsEditorDialog.cpp index 5493ac3c8e5..87ba7a42c15 100644 --- a/qtfred/src/ui/dialogs/ReinforcementsEditorDialog.cpp +++ b/qtfred/src/ui/dialogs/ReinforcementsEditorDialog.cpp @@ -65,20 +65,6 @@ void ReinforcementsDialog::closeEvent(QCloseEvent* e) } -static inline void setSpinMixed(QSpinBox* sb) -{ - sb->setSpecialValueText(QStringLiteral("-")); // special text for mixed values - sb->setMinimum(std::numeric_limits::min()); // sentinel below real min - sb->setValue(sb->minimum()); // triggers special text display -} - -static inline void setSpinNormal(QSpinBox* sb, int min, int max, int value) -{ - sb->setSpecialValueText(QString()); // disable special text - sb->setRange(min, max); - sb->setValue(value); -} - void ReinforcementsDialog::updateUi() { util::SignalBlockers blockers(this); @@ -129,17 +115,17 @@ void ReinforcementsDialog::updateUi() int use = _model->getUseCount(); if (use < 0) { - setSpinMixed(ui->useSpinBox); + ui->useSpinBox->setMixed(); } else { - setSpinNormal(ui->useSpinBox, 0, 16777215, use); + ui->useSpinBox->setSingleValue(use); } int delay = _model->getBeforeArrivalDelay(); if (delay < 0) { - setSpinMixed(ui->delaySpinBox); + ui->delaySpinBox->setMixed(); } else { - setSpinNormal(ui->delaySpinBox, 0, 16777215, delay); + ui->delaySpinBox->setSingleValue(delay); } } @@ -219,12 +205,7 @@ void ReinforcementsDialog::on_useSpinBox_valueChanged(int val) { // need to check that it's not empty so as not to pass nonsense values back to the model. if (ui->chosenShipsList->selectedItems().count() > 0) { - if (val < 0) { - val = 0; - - util::SignalBlockers blockers(this); - ui->useSpinBox->setValue(val); - } + // MixedValueSpinBox keeps each value that the user enters in the real range (0 or more). _model->setUseCount(val); } } @@ -233,12 +214,7 @@ void ReinforcementsDialog::on_delaySpinBox_valueChanged(int val) { // need to check that it's not empty so as not to pass nonsense values back to the model. if (ui->chosenShipsList->selectedItems().count() > 0) { - if (val < 0) { - val = 0; - - util::SignalBlockers blockers(this); - ui->delaySpinBox->setValue(val); - } + // MixedValueSpinBox keeps each value that the user enters in the real range (0 or more). _model->setBeforeArrivalDelay(val); } } diff --git a/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.cpp b/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.cpp index 1d28b170af9..02f011e7842 100644 --- a/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.cpp +++ b/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.cpp @@ -171,35 +171,29 @@ void ShipInitialStatusDialog::on_moveShipsCheckBox_toggled(bool value) { _model->setMoveShipsWhenUndocking(value); } -void ShipInitialStatusDialog::updateUi() +// Shows the value, or "-" when the model value is BLANKFIELD (the marked ships have different values). +void ShipInitialStatusDialog::setSpinBoxValueOrBlank(MixedValueSpinBox* spinBox, int value) { - util::SignalBlockers blockers(this); - auto value = _model->getVelocity(); - if (value != BLANKFIELD) { - ui->velocitySpinBox->setValue(value); + if (value == BLANKFIELD) { + spinBox->setMixed(); } else { - ui->velocitySpinBox->setSpecialValueText("-"); + spinBox->setSingleValue(value); } - value = _model->getHull(); - if (value != BLANKFIELD) { - ui->hullSpinBox->setValue(value); - } else { - ui->hullSpinBox->setSpecialValueText("-"); - } - value = _model->getHasShield(); +} +void ShipInitialStatusDialog::updateUi() +{ + util::SignalBlockers blockers(this); + setSpinBoxValueOrBlank(ui->velocitySpinBox, _model->getVelocity()); + setSpinBoxValueOrBlank(ui->hullSpinBox, _model->getHull()); + auto value = _model->getHasShield(); ui->hasShieldCheckBox->setCheckState(Qt::CheckState(value)); if (_model->getHasShield()) { ui->shieldHullSpinBox->setEnabled(true); } else { ui->shieldHullSpinBox->setEnabled(false); } - value = _model->getShieldHull(); - if (value != BLANKFIELD) { - ui->shieldHullSpinBox->setValue(value); - } else { - ui->shieldHullSpinBox->setSpecialValueText("-"); - } - ui->guardianSpinBox->setValue(_model->getGuardian()); + setSpinBoxValueOrBlank(ui->shieldHullSpinBox, _model->getShieldHull()); + setSpinBoxValueOrBlank(ui->guardianSpinBox, _model->getGuardian()); updateFlags(); updateDocks(); updateDockee(); diff --git a/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.h b/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.h index a3347683337..991c092e2cb 100644 --- a/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.h +++ b/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.h @@ -4,6 +4,7 @@ #include #include +#include namespace fso::fred::dialogs { @@ -54,6 +55,7 @@ class ShipInitialStatusDialog : public QDialog { EditorViewport* _viewport; void updateUi(); + void setSpinBoxValueOrBlank(MixedValueSpinBox* spinBox, int value); void updateFlags(); void updateDocks(); void updateDockee(); diff --git a/qtfred/src/ui/widgets/MixedValueSpinBox.cpp b/qtfred/src/ui/widgets/MixedValueSpinBox.cpp new file mode 100644 index 00000000000..8c4df860a92 --- /dev/null +++ b/qtfred/src/ui/widgets/MixedValueSpinBox.cpp @@ -0,0 +1,54 @@ +#include "MixedValueSpinBox.h" + +#include +#include + +namespace fso::fred { + +MixedValueSpinBox::MixedValueSpinBox(QWidget* parent) : QSpinBox(parent) {} + +void MixedValueSpinBox::setMixed() +{ + if (!_mixed) { + _realMinimum = minimum(); + _mixed = true; + } + setSpecialValueText(QStringLiteral("-")); + setMinimum(std::numeric_limits::min()); + setValue(minimum()); +} + +void MixedValueSpinBox::setSingleValue(int value) +{ + leaveMixedState(); + setValue(value); +} + +void MixedValueSpinBox::leaveMixedState() +{ + if (!_mixed) + return; + + _mixed = false; + setSpecialValueText(QString()); + // Qt moves a value below the new minimum up to the minimum. + setMinimum(_realMinimum); +} + +void MixedValueSpinBox::stepBy(int steps) +{ + // From "-", the first step shows the lowest real value. + const bool wasBlank = _mixed && value() == minimum(); + leaveMixedState(); + if (!wasBlank) + QSpinBox::stepBy(steps); +} + +int MixedValueSpinBox::valueFromText(const QString& text) const +{ + const int value = QSpinBox::valueFromText(text); + // In the mixed state, the minimum is below the real range. A typed value must stay in the real range. + return _mixed ? std::clamp(value, _realMinimum, maximum()) : value; +} + +} // namespace fso::fred diff --git a/qtfred/src/ui/widgets/MixedValueSpinBox.h b/qtfred/src/ui/widgets/MixedValueSpinBox.h new file mode 100644 index 00000000000..a0293b09805 --- /dev/null +++ b/qtfred/src/ui/widgets/MixedValueSpinBox.h @@ -0,0 +1,38 @@ +#pragma once + +#include + +namespace fso::fred { + +/** + * @brief A spin box that edits one field of several objects at the same time. + * + * When the objects have different values, setMixed() shows "-". A spin box shows its special value text only + * at its minimum, so the mixed state moves the minimum below each real value. Thus each value that the user + * enters, also the real minimum, is a change and gives valueChanged(). The values that the user enters always + * stay in the real range. + */ +class MixedValueSpinBox : public QSpinBox { + Q_OBJECT + + public: + explicit MixedValueSpinBox(QWidget* parent = nullptr); + + // Shows "-" until the user enters a value. + void setMixed(); + + // Shows one value for all objects. This ends the mixed state. + void setSingleValue(int value); + + protected: + void stepBy(int steps) override; + int valueFromText(const QString& text) const override; + + private: + void leaveMixedState(); + + bool _mixed = false; + int _realMinimum = 0; +}; + +} // namespace fso::fred diff --git a/qtfred/ui/ReinforcementsDialog.ui b/qtfred/ui/ReinforcementsDialog.ui index 54d12475602..00c0fc5604a 100644 --- a/qtfred/ui/ReinforcementsDialog.ui +++ b/qtfred/ui/ReinforcementsDialog.ui @@ -323,7 +323,7 @@ - + 16777215 @@ -337,7 +337,7 @@ - + 16777215 @@ -376,6 +376,13 @@ + + + fso::fred::MixedValueSpinBox + QSpinBox +
ui/widgets/MixedValueSpinBox.h
+
+
possibleShipsList actionAddShip diff --git a/qtfred/ui/ShipInitialStatus.ui b/qtfred/ui/ShipInitialStatus.ui index 5973114839b..362cfddd4fe 100644 --- a/qtfred/ui/ShipInitialStatus.ui +++ b/qtfred/ui/ShipInitialStatus.ui @@ -20,7 +20,7 @@ - + 70 @@ -49,7 +49,7 @@ - + 70 @@ -134,7 +134,7 @@ - + @@ -172,7 +172,7 @@ - + 70 @@ -457,6 +457,11 @@ QCheckBox
ui/widgets/ShipFlagCheckbox.h
+ + fso::fred::MixedValueSpinBox + QSpinBox +
ui/widgets/MixedValueSpinBox.h
+
velocitySpinBox From 5583eaefb0887b302bb7e39987b69e919af4ecd1 Mon Sep 17 00:00:00 2001 From: the-e Date: Wed, 11 Nov 2026 19:48:13 +0100 Subject: [PATCH 05/26] QtFRED: fix Initial Status with several marked ships With several ships marked, OK in the Initial Status dialog damaged the ships: - The code checked the velocity flag three times and never used the shield and hull flags. So mixed values did not show blank, and OK wrote 101 (the blank marker) to the ships. - OK gave the guardian threshold and the team color of one ship to all marked ships. - OK could crash, because the dock update ran in multi-edit mode, where the dock data was never set up. Now a field with different values shows blank, and OK keeps the value of each ship for a blank field. This includes the guardian threshold and the team color. The team color goes only to ships that use team colors. The dock update runs only when the dialog edits one ship. The multi-edit loop uses one ship reference and one merge function for the check boxes. Co-Authored-By: Claude Opus 5.5 --- .../ShipInitialStatusDialogModel.cpp | 163 +++++++----------- .../ShipEditor/ShipInitialStatusDialogModel.h | 2 +- 2 files changed, 62 insertions(+), 103 deletions(-) diff --git a/qtfred/src/mission/dialogs/ShipEditor/ShipInitialStatusDialogModel.cpp b/qtfred/src/mission/dialogs/ShipEditor/ShipInitialStatusDialogModel.cpp index 13aaadde5a9..7e712190115 100644 --- a/qtfred/src/mission/dialogs/ShipEditor/ShipInitialStatusDialogModel.cpp +++ b/qtfred/src/mission/dialogs/ShipEditor/ShipInitialStatusDialogModel.cpp @@ -109,7 +109,6 @@ ShipInitialStatusDialogModel::ShipInitialStatusDialogModel(QObject* parent, Edit void ShipInitialStatusDialogModel::initializeData(bool multi) { _multiEdit = multi; - int vflag, sflag, hflag; object* objp = nullptr; _ship = _editor->cur_ship; if (_ship == -1) { @@ -137,7 +136,6 @@ void ShipInitialStatusDialogModel::initializeData(bool multi) } } } - vflag = sflag = hflag = 0; _velocity = static_cast(Objects[_editor->currentObject].phys_info.speed); _shields = static_cast(Objects[_editor->currentObject].shield_quadrant[0]); _hull = static_cast(Objects[_editor->currentObject].hull_strength); @@ -187,107 +185,60 @@ void ShipInitialStatusDialogModel::initializeData(bool multi) _afterburnerLocked = Qt::Unchecked; } - if (_multiEdit) { - objp = GET_FIRST(&obj_used_list); - while (objp != END_OF_LIST(&obj_used_list)) { - if (((objp->type == OBJ_SHIP) || (objp->type == OBJ_START)) && - (objp->flags[Object::Object_Flags::Marked])) { - if (objp->phys_info.speed != _velocity) - vflag = 1; - if (static_cast(objp->shield_quadrant[0]) != _shields) - sflag = 1; - if (static_cast(objp->hull_strength) != _hull) - hflag = 1; - if (objp->flags[Object::Object_Flags::No_shields]) { - if (_hasShields) - _hasShields = Qt::PartiallyChecked; - - } else { - if (!_hasShields) - _hasShields = Qt::PartiallyChecked; - } - - Assert((objp->type == OBJ_SHIP) || (objp->type == OBJ_START)); - - if (Ships[get_ship_from_obj(objp)].flags[Ship::Ship_Flags::Force_shields_on]) { - if (!_forceShields) - _forceShields = Qt::PartiallyChecked; - - } else { - if (_forceShields) - _forceShields = Qt::PartiallyChecked; - } - - if (Ships[get_ship_from_obj(objp)].flags[Ship::Ship_Flags::Ship_locked]) { - if (!_shipLocked) - _shipLocked = Qt::PartiallyChecked; - - } else { - if (_shipLocked) - _shipLocked = Qt::PartiallyChecked; - } - - if (Ships[get_ship_from_obj(objp)].flags[Ship::Ship_Flags::Weapons_locked]) { - if (!_weaponsLocked) - _weaponsLocked = Qt::PartiallyChecked; - - } else { - if (_weaponsLocked) - _weaponsLocked = Qt::PartiallyChecked; - } - - if (Ships[get_ship_from_obj(objp)].flags[Ship::Ship_Flags::Primaries_locked]) { - if (!_primariesLocked) - _primariesLocked = Qt::PartiallyChecked; - } else { - if (_primariesLocked) - _primariesLocked = Qt::PartiallyChecked; - } - - if (Ships[get_ship_from_obj(objp)].flags[Ship::Ship_Flags::Secondaries_locked]) { - if (!_secondariesLocked) - _secondariesLocked = Qt::PartiallyChecked; - } else { - if (_secondariesLocked) - _secondariesLocked = Qt::PartiallyChecked; - } - - if (Ships[get_ship_from_obj(objp)].flags[Ship::Ship_Flags::Lock_all_turrets_initially]) { - if (!_turretsLocked) - _turretsLocked = Qt::PartiallyChecked; - } else { - if (_turretsLocked) - _turretsLocked = Qt::PartiallyChecked; - } + if (Ship_info[Ships[_ship].ship_info_index].uses_team_colors) { + _useTeams = true; + _teamColorSetting = Ships[_ship].team_name; + } - if (Ships[get_ship_from_obj(objp)].flags[Ship::Ship_Flags::Afterburner_locked]) { - if (!_afterburnerLocked) - _afterburnerLocked = Qt::PartiallyChecked; - } else { - if (_afterburnerLocked) - _afterburnerLocked = Qt::PartiallyChecked; - } + if (_multiEdit) { + // Merges the flag of one more ship into a check box state: a difference gives PartiallyChecked. + auto mergeFlag = [](int& state, bool set) { + if (state != (set ? Qt::Checked : Qt::Unchecked)) + state = Qt::PartiallyChecked; + }; + + // A field that has different values on the marked ships shows blank. The apply step keeps the + // values of the ships for a blank field. Compare with the values of the current ship. + const int refVelocity = _velocity; + const int refShields = _shields; + const int refHull = _hull; + const int refGuardian = _guardianThreshold; + const SCP_string refTeamColor = _teamColorSetting; + + for (objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp)) { + if (((objp->type != OBJ_SHIP) && (objp->type != OBJ_START)) || + !(objp->flags[Object::Object_Flags::Marked])) { + continue; } - objp = GET_NEXT(objp); + const ship& other = Ships[get_ship_from_obj(objp)]; + + if (static_cast(objp->phys_info.speed) != refVelocity) + _velocity = BLANKFIELD; + if (static_cast(objp->shield_quadrant[0]) != refShields) + _shields = BLANKFIELD; + if (static_cast(objp->hull_strength) != refHull) + _hull = BLANKFIELD; + if (other.ship_guardian_threshold != refGuardian) + _guardianThreshold = BLANKFIELD; + // Only ships that use team colors take part in the team color comparison. + if (_useTeams && Ship_info[other.ship_info_index].uses_team_colors && + !lcase_equal(other.team_name, refTeamColor)) + _teamColorSetting.clear(); + + mergeFlag(_hasShields, !objp->flags[Object::Object_Flags::No_shields]); + mergeFlag(_forceShields, other.flags[Ship::Ship_Flags::Force_shields_on]); + mergeFlag(_shipLocked, other.flags[Ship::Ship_Flags::Ship_locked]); + mergeFlag(_weaponsLocked, other.flags[Ship::Ship_Flags::Weapons_locked]); + mergeFlag(_primariesLocked, other.flags[Ship::Ship_Flags::Primaries_locked]); + mergeFlag(_secondariesLocked, other.flags[Ship::Ship_Flags::Secondaries_locked]); + mergeFlag(_turretsLocked, other.flags[Ship::Ship_Flags::Lock_all_turrets_initially]); + mergeFlag(_afterburnerLocked, other.flags[Ship::Ship_Flags::Afterburner_locked]); } } - if (Ship_info[Ships[_ship].ship_info_index].uses_team_colors) { - _useTeams = true; - _teamColorSetting = Ships[_ship].team_name; - } changeSubsys(0); - if (vflag) { - _velocity = BLANKFIELD; - } - if (vflag) { - _velocity = BLANKFIELD; - } - if (vflag) { - _velocity = BLANKFIELD; - } _modified = false; modelChanged(); _modified = false; @@ -587,11 +538,14 @@ bool ShipInitialStatusDialogModel::apply() while (objp != END_OF_LIST(&obj_used_list)) { if (((objp->type == OBJ_SHIP) || (objp->type == OBJ_START)) && (objp->flags[Object::Object_Flags::Marked])) { - modify(objp->phys_info.speed, (float)_velocity); + if (_velocity != BLANKFIELD) + modify(objp->phys_info.speed, (float)_velocity); - modify(objp->shield_quadrant[0], (float)_shields); + if (_shields != BLANKFIELD) + modify(objp->shield_quadrant[0], (float)_shields); - modify(objp->hull_strength, (float)_hull); + if (_hull != BLANKFIELD) + modify(objp->hull_strength, (float)_hull); if (_hasShields == Qt::Checked) { objp->flags.remove(Object::Object_Flags::No_shields); @@ -599,7 +553,8 @@ bool ShipInitialStatusDialogModel::apply() objp->flags.set(Object::Object_Flags::No_shields); } auto shipp = &Ships[get_ship_from_obj(objp)]; - shipp->ship_guardian_threshold = _guardianThreshold; + if (_guardianThreshold != BLANKFIELD) + shipp->ship_guardian_threshold = _guardianThreshold; // We need to ensure that we handle the inconsistent "boolean" value correctly handle_inconsistent_flag(shipp->flags, Ship::Ship_Flags::Force_shields_on, _forceShields); handle_inconsistent_flag(shipp->flags, Ship::Ship_Flags::Ship_locked, _shipLocked); @@ -608,7 +563,8 @@ bool ShipInitialStatusDialogModel::apply() handle_inconsistent_flag(shipp->flags, Ship::Ship_Flags::Secondaries_locked, _secondariesLocked); handle_inconsistent_flag(shipp->flags, Ship::Ship_Flags::Lock_all_turrets_initially, _turretsLocked); handle_inconsistent_flag(shipp->flags, Ship::Ship_Flags::Afterburner_locked, _afterburnerLocked); - shipp->team_name = _teamColorSetting; + if (!_teamColorSetting.empty() && Ship_info[shipp->ship_info_index].uses_team_colors) + shipp->team_name = _teamColorSetting; } objp = GET_NEXT(objp); @@ -630,9 +586,12 @@ bool ShipInitialStatusDialogModel::apply() handle_inconsistent_flag(Ships[_ship].flags, Ship::Ship_Flags::Secondaries_locked, _secondariesLocked); handle_inconsistent_flag(Ships[_ship].flags, Ship::Ship_Flags::Lock_all_turrets_initially, _turretsLocked); handle_inconsistent_flag(Ships[_ship].flags, Ship::Ship_Flags::Afterburner_locked, _afterburnerLocked); - Ships[_ship].team_name = _teamColorSetting; + if (_useTeams) + Ships[_ship].team_name = _teamColorSetting; + + // Dockpoint data exists only when the dialog edits one ship. + updateDockingInfo(); } - updateDockingInfo(); _editor->missionChanged(); return true; } diff --git a/qtfred/src/mission/dialogs/ShipEditor/ShipInitialStatusDialogModel.h b/qtfred/src/mission/dialogs/ShipEditor/ShipInitialStatusDialogModel.h index a911ca5b864..181e80c1275 100644 --- a/qtfred/src/mission/dialogs/ShipEditor/ShipInitialStatusDialogModel.h +++ b/qtfred/src/mission/dialogs/ShipEditor/ShipInitialStatusDialogModel.h @@ -127,7 +127,7 @@ class ShipInitialStatusDialogModel : public AbstractDialogModel { int _afterburnerLocked; SCP_string _teamColorSetting; int _shipHasScannableSubsystems; - int _numDockPoints; + int _numDockPoints = 0; std::unique_ptr _dockpointArray; bool _multiEdit; bool _useTeams = false; From 147d9fd5c04129d0db63448028d9ee51fdea1091 Mon Sep 17 00:00:00 2001 From: the-e Date: Wed, 11 Nov 2026 19:48:20 +0100 Subject: [PATCH 06/26] AI: free Lua AI goal arguments before the Lua state closes The goals of Lua AI modes keep Lua values (the extra SEXP arguments) in Ai_info and Wings. Script_system.Clear() closes the Lua state, but these values stayed. Their destructors ran later, for example at program exit, and released references in the closed Lua state. The new ai_lua_init() in ailua.cpp registers an OnStateDestroy handler that frees these arguments while the Lua state still exists. ai_init() calls it once. This applies to the game and to the editors. Co-Authored-By: Claude Opus 5.5 --- code/ai/aicode.cpp | 2 ++ code/ai/ailua.cpp | 22 ++++++++++++++++++++++ code/ai/ailua.h | 3 +++ 3 files changed, 27 insertions(+) diff --git a/code/ai/aicode.cpp b/code/ai/aicode.cpp index 047f677dd16..0807353c332 100644 --- a/code/ai/aicode.cpp +++ b/code/ai/aicode.cpp @@ -978,6 +978,8 @@ LOCAL int ai_inited = 0; void ai_init() { if ( !ai_inited ) { + ai_lua_init(); + // Do the first time initialization stuff here Ai_classes.clear(); Ai_class_names.clear(); diff --git a/code/ai/ailua.cpp b/code/ai/ailua.cpp index 6f4203c4b18..5a01ed96c59 100644 --- a/code/ai/ailua.cpp +++ b/code/ai/ailua.cpp @@ -13,6 +13,28 @@ static std::unordered_map Lua_ai_modes; static std::unordered_map Lua_player_orders; +// The goals of Lua AI modes keep Lua values. Free them while the Lua state still exists. Otherwise their +// destructors run later (for example at program exit) and release references in a closed Lua state. +static void ai_lua_free_goal_values(lua_State*) +{ + // Only the arguments are Lua values. The target is plain data. + for (int i = 0; i < MAX_AI_INFO; ++i) { + Ai_info[i].lua_ai_target.arguments.clear(); + for (auto& goal : Ai_info[i].goals) + goal.lua_ai_target.arguments.clear(); + } + + for (auto& wingp : Wings) { + for (auto& goal : wingp.ai_goals) + goal.lua_ai_target.arguments.clear(); + } +} + +void ai_lua_init() +{ + Script_system.OnStateDestroy.add(ai_lua_free_goal_values); +} + void ai_lua_add_mode(int sexp_op, const ai_mode_lua& mode) { Lua_ai_modes.emplace(sexp_op, mode); } diff --git a/code/ai/ailua.h b/code/ai/ailua.h index f4424ce3ab5..54732870dbd 100644 --- a/code/ai/ailua.h +++ b/code/ai/ailua.h @@ -28,6 +28,9 @@ struct player_order_lua { }; +// One-time setup of the Lua AI code. ai_init() calls it. +void ai_lua_init(); + void ai_lua_add_mode(int sexp_op, const ai_mode_lua& mode); bool ai_lua_add_order(int sexp_op, player_order_lua order); bool ai_lua_has_mode(int sexp_op); From 66e6ca851242145ad9ca041133b30f24418cbe37 Mon Sep 17 00:00:00 2001 From: the-e Date: Wed, 11 Nov 2026 19:48:31 +0100 Subject: [PATCH 07/26] Editors: fix crashes at exit and the shutdown order QtFRED freed the mission and SEXP data while editor windows still used it, because WA_DeleteOnClose deletes a window only after shutdown(). QtFRED and FRED2 also never closed the Lua scripting system. Closing the campaign editor could trigger the Qt assert "Called object is not of the correct type", because the graph scene sent selectionChanged to the half-destroyed graph. On exit, QtFRED now closes the editor windows first, so each one can ask about its own changes. After the mission prompt, it deletes them, then it shuts down the engine. The new shared editor_shutdown() frees the engine and SEXP data, closes the Lua state (in the same order as game_shutdown()), then sound, then graphics. QtFRED and FRED2 both use it, and FRED2 no longer closes sound in CFREDView::OnDestroy. The campaign editor and its graph disconnect their child signals in their destructors. Co-Authored-By: Claude Opus 5.5 --- code/missioneditor/common.cpp | 27 ++++++++++++++++++- code/missioneditor/common.h | 8 +++--- fred2/fredview.cpp | 4 +-- fred2/management.cpp | 6 +---- qtfred/src/mission/management.cpp | 9 +------ qtfred/src/ui/FredView.cpp | 27 +++++++++++++++++++ qtfred/src/ui/FredView.h | 2 ++ .../src/ui/dialogs/CampaignEditorDialog.cpp | 8 +++++- 8 files changed, 70 insertions(+), 21 deletions(-) diff --git a/code/missioneditor/common.cpp b/code/missioneditor/common.cpp index ed4b73a514f..21b11c4ba63 100644 --- a/code/missioneditor/common.cpp +++ b/code/missioneditor/common.cpp @@ -17,6 +17,11 @@ #include "parse/sexp.h" #include "prop/prop.h" #include "render/batching.h" +#include "scripting/scripting.h" +#include "sound/audiostr.h" +#include "sound/sound.h" +#include "graphics/2d.h" +#include "osapi/osapi.h" #include "ship/ship.h" #include "weapon/weapon.h" @@ -388,7 +393,9 @@ SCP_string check_name_conflict(const char *entity_type, const char *name, int ex return ""; // no error } -void editor_free_engine_data() +// Free the engine data that the editors keep for their whole session. Call it while the graphics system is +// still up, because models own GPU buffers and cursors own bitmaps. +static void editor_free_engine_data() { // models, model instances, and collision trees; done before ship_close() because model_unload() walks Ship_info model_free_all(); @@ -406,6 +413,11 @@ void editor_free_engine_data() fhash_flush(); control_config_common_close(); sexp_shutdown(); + + // Use the same order as game_shutdown(). The SEXP data (Lua SEXPs) holds Lua references, so free it first. + // After this call, scripting is not available. + Script_system.Clear(); + batching_shutdown(); // the cursors hold bitmaps, so this must happen before the graphics system shuts down @@ -418,6 +430,19 @@ void editor_free_engine_data() } } +void editor_shutdown() +{ + // Lua objects can hold sound handles, so free the Lua state before the sound system. + editor_free_engine_data(); + + audiostream_close(); + snd_close(); + + gr_close(); + + os_cleanup(); +} + int load_and_find_campaign_mission(const char *mission_filename) { if (!mission_filename || !mission_filename[0]) diff --git a/code/missioneditor/common.h b/code/missioneditor/common.h index bff0c669493..8984adb2a82 100644 --- a/code/missioneditor/common.h +++ b/code/missioneditor/common.h @@ -86,9 +86,11 @@ bool set_single_player_start(int objnum); // against the entity currently being renamed. SCP_string check_name_conflict(const char *entity_type, const char *name, int exclude_ship = -1, int exclude_wing = -1, int exclude_waypoint_list = -1, int exclude_jump_node = -1); -// Free the engine data that the editors keep for their whole session. Call at shutdown, while the graphics -// system is still up, since models own GPU buffers and cursors own bitmaps. -void editor_free_engine_data(); + +// The shutdown of the engine systems, for FRED2 and QtFRED. The order is the same as in game_shutdown(): +// first the engine data, the SEXP data, and the Lua state, then sound, then graphics. +// Call it after you close the editor windows, because they can use mission and SEXP data. +void editor_shutdown(); // Bounding-box midpoint of all (or only marked) objects and the farthest distance from it; false if there are none. bool get_object_bounds(bool marked_only, vec3d* center, float* radius); diff --git a/fred2/fredview.cpp b/fred2/fredview.cpp index b47dfcbdb78..a1c08e23647 100644 --- a/fred2/fredview.cpp +++ b/fred2/fredview.cpp @@ -5082,9 +5082,7 @@ void CFREDView::OnEditorsFiction() void CFREDView::OnDestroy() { - audiostream_close(); - snd_close(); - + // fred_shutdown() closes the sound system after the Lua state, the same as QtFRED and the game. CView::OnDestroy(); } diff --git a/fred2/management.cpp b/fred2/management.cpp index 1c7f7ff0800..815ebea5820 100644 --- a/fred2/management.cpp +++ b/fred2/management.cpp @@ -480,11 +480,7 @@ bool fred_init(std::unique_ptr&& graphicsOps) // called when FRED closes, after the document has been closed void fred_shutdown() { - editor_free_engine_data(); - - gr_close(); - - os_cleanup(); + editor_shutdown(); } void set_physics_controls() diff --git a/qtfred/src/mission/management.cpp b/qtfred/src/mission/management.cpp index d54b69b51a5..321a35dbab8 100644 --- a/qtfred/src/mission/management.cpp +++ b/qtfred/src/mission/management.cpp @@ -318,14 +318,7 @@ initialize(const std::string& cfilepath, int argc, char* argv[], Editor* editor, } void shutdown() { - audiostream_close(); - snd_close(); - - editor_free_engine_data(); - - gr_close(); - - os_cleanup(); + editor_shutdown(); if (LoggingEnabled) { outwnd_close(); diff --git a/qtfred/src/ui/FredView.cpp b/qtfred/src/ui/FredView.cpp index 687339b7743..5d4961fbb95 100644 --- a/qtfred/src/ui/FredView.cpp +++ b/qtfred/src/ui/FredView.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -2261,6 +2262,17 @@ void FredView::changeEvent(QEvent* event) { menuBar()->update(); } } +QList FredView::editorWindows() const { + // Only dialogs and the campaign editor (a QMainWindow) are editor windows. Menus and floating dock + // widgets are also top-level children, but this window owns them until it is destroyed. + QList windows; + for (auto* child : findChildren(QString(), Qt::FindDirectChildrenOnly)) { + if (child->isWindow() && (qobject_cast(child) != nullptr || qobject_cast(child) != nullptr)) + windows.append(child); + } + return windows; +} + void FredView::closeEvent(QCloseEvent* event) { QSettings settings; settings.setValue("FredView/mainWindowState", saveState()); @@ -2269,6 +2281,17 @@ void FredView::closeEvent(QCloseEvent* event) { settings.setValue("FredView/transformLocalRotate", _tbLocalRotate); // Camera speeds are persisted on change in onUpdateViewSpeeds(), so no need to save them here. + // Close the editor windows before the mission prompt. A window can ask about its own unsaved changes. + // If the user keeps the changes, they go into the mission, and the mission prompt then includes them. + // A cancel in a window stops the exit. A window that closed before the cancel stays closed, because + // the user already answered its prompt, and its model is not usable again after apply() or reject(). + for (auto* window : editorWindows()) { + if (window->isVisible() && !window->close()) { + event->ignore(); + return; + } + } + if (!maybePromptToSaveMissionChanges(tr("closing QtFRED"))) { event->ignore(); return; @@ -2276,6 +2299,10 @@ void FredView::closeEvent(QCloseEvent* event) { disconnect(); QMainWindow::closeEvent(event); + // The editor windows hold SEXP trees and pointers into mission data. WA_DeleteOnClose only schedules a + // deferred delete, which runs after shutdown() frees that data. Delete them now. + qDeleteAll(editorWindows()); + // gr_close() destroys this window, so this must be the last thing we do here shutdown(); } diff --git a/qtfred/src/ui/FredView.h b/qtfred/src/ui/FredView.h index 6f738721ed1..d0ef4460af0 100644 --- a/qtfred/src/ui/FredView.h +++ b/qtfred/src/ui/FredView.h @@ -230,6 +230,8 @@ class FredView: public QMainWindow, public IDialogProvider { void on_actionControlModeCurrentShip_triggered(bool enabled); void addToRecentFiles(const QString& path); + // The editor dialogs and the campaign editor that are open as children of this window. + QList editorWindows() const; void updateRecentFileList(); void recentFileOpened(); diff --git a/qtfred/src/ui/dialogs/CampaignEditorDialog.cpp b/qtfred/src/ui/dialogs/CampaignEditorDialog.cpp index 14a227d3b50..5347384e506 100644 --- a/qtfred/src/ui/dialogs/CampaignEditorDialog.cpp +++ b/qtfred/src/ui/dialogs/CampaignEditorDialog.cpp @@ -162,7 +162,13 @@ CampaignEditorDialog::CampaignEditorDialog(QWidget* parent, EditorViewport* view initializeUi(); updateUi(); } -CampaignEditorDialog::~CampaignEditorDialog() = default; +CampaignEditorDialog::~CampaignEditorDialog() +{ + // ~QWidget deletes the child widgets after this destructor, and after _model. Disconnect the SEXP tree + // now, so that a signal from its destruction cannot reach this dialog or the deleted model. The graph + // disconnects its own scene in ~CampaignMissionGraph. + ui->sxtBranches->disconnect(this); +} SCP_vector CampaignEditorDialog::getMissionNames() { From 82babca78e691e4b1e25304578595fb7ec2c031b Mon Sep 17 00:00:00 2001 From: the-e Date: Wed, 11 Nov 2026 19:48:36 +0100 Subject: [PATCH 08/26] QtFRED: fix the action leak in the recent-files menu Each update of the recent-files menu created up to 8 new menu actions with the main window as parent. QMenu::clear() did not delete them, so they leaked. The menu now owns its actions. The update removes the old actions and deletes them later, because a recent-file action can start the update while it sends its own triggered() signal. Co-Authored-By: Claude Opus 5.5 --- qtfred/src/ui/FredView.cpp | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/qtfred/src/ui/FredView.cpp b/qtfred/src/ui/FredView.cpp index 5d4961fbb95..9d8fd11acb5 100644 --- a/qtfred/src/ui/FredView.cpp +++ b/qtfred/src/ui/FredView.cpp @@ -906,22 +906,20 @@ void FredView::updateRecentFileList() { QSettings settings; auto recentFiles = settings.value("FredView/recentFiles").toStringList(); - if (recentFiles.empty()) { - // If there are no files, clear the menu and disable it - ui->menuRe_cent_Files->clear(); - ui->menuRe_cent_Files->setEnabled(false); - } else { - // Reset the menu in case there was something there before and enable it - ui->menuRe_cent_Files->clear(); - ui->menuRe_cent_Files->setEnabled(true); + // Remove the old actions. A recent-file action can call this function while it sends its own triggered() + // signal, so use a deferred delete. Before, the actions had this window as parent, and each update leaked them. + for (auto* action : ui->menuRe_cent_Files->actions()) { + ui->menuRe_cent_Files->removeAction(action); + action->deleteLater(); + } + ui->menuRe_cent_Files->setEnabled(!recentFiles.empty()); - // Now add the individual files as actions - for (auto& path : recentFiles) { - auto action = new QAction(path, this); - connect(action, &QAction::triggered, this, &FredView::recentFileOpened); + // Now add the individual files as actions + for (auto& path : recentFiles) { + auto action = new QAction(path, ui->menuRe_cent_Files); + connect(action, &QAction::triggered, this, &FredView::recentFileOpened); - ui->menuRe_cent_Files->addAction(action); - } + ui->menuRe_cent_Files->addAction(action); } } From 36a4912d586345d2bd6e52af8760baed2d3140a4 Mon Sep 17 00:00:00 2001 From: the-e Date: Wed, 11 Nov 2026 19:52:30 +0100 Subject: [PATCH 09/26] QtFRED: fix the save path after Save As and template loads Three defects in the save path: - After Save As, the window title still showed the old file name. - A cancelled Save As cleared the current file name, because the dialog result went directly into the member. - A template load kept the save path of the mission that was open before, so Save wrote over that mission. A .fst file opened from the recent-files list or with -start_mission loaded as a plain mission, so Save wrote over the template. Editor now holds the save path. Editor::loadMission() makes each .fst file a template and gives a template no save path. FredView::saveName is removed; FredView reads Editor::currentMissionPath(). Save As uses a local variable, sets the new path only after the save, and updates the title and the recent-files list. Co-Authored-By: Claude Opus 5.5 --- qtfred/src/mission/Editor.cpp | 16 +++++++- qtfred/src/mission/Editor.h | 16 +++++++- qtfred/src/ui/FredView.cpp | 71 +++++++++++++++++------------------ qtfred/src/ui/FredView.h | 3 +- 4 files changed, 65 insertions(+), 41 deletions(-) diff --git a/qtfred/src/mission/Editor.cpp b/qtfred/src/mission/Editor.cpp index aa6b37a05be..c13330ef8ed 100644 --- a/qtfred/src/mission/Editor.cpp +++ b/qtfred/src/mission/Editor.cpp @@ -187,7 +187,7 @@ void Editor::stopAutosaveTimer() { } void Editor::setCurrentMissionPath(const QString& path) { - _currentMissionPath = path; + _currentMissionPath = QDir::toNativeSeparators(path); } void Editor::performTimedAutosave() { @@ -208,6 +208,11 @@ bool Editor::loadMission(const std::string& mission_name, int flags) { // activate the localizer hash table fhash_flush(); + // A .fst file is always a template, from each caller (recent files, -start_mission). Without the template + // flag, Save writes a plain mission over the template file. + if (QString::fromStdString(mission_name).endsWith(".fst", Qt::CaseInsensitive)) + flags |= MPF_IS_TEMPLATE; + clearMission(flags & MPF_FAST_RELOAD); std::string filepath = mission_name; @@ -417,7 +422,13 @@ bool Editor::loadMission(const std::string& mission_name, int flags) { stars_post_level_init(); - missionLoaded(filepath); + // The path that Save writes to. A template has no such file: the user must give a name with Save As. + if (flags & MPF_IS_TEMPLATE) + setCurrentMissionPath({}); + else + setCurrentMissionPath(QString::fromStdString(filepath)); + + missionLoaded(_currentMissionPath.toStdString()); // This hook will allow for scripts to know when a mission has been loaded // which will then allow them to update any LuaEnums that may be related to sexps @@ -830,6 +841,7 @@ void Editor::createNewMission() { create_player(&vmd_zero_vector, &vmd_identity_matrix); stars_post_level_init(); // TODO(Phase 3): _undoStack->clear() + setCurrentMissionPath({}); missionLoaded(""); } void Editor::hideMarkedObjects() { diff --git a/qtfred/src/mission/Editor.h b/qtfred/src/mission/Editor.h index be5c65ca992..7cc37ac6b6c 100644 --- a/qtfred/src/mission/Editor.h +++ b/qtfred/src/mission/Editor.h @@ -71,10 +71,21 @@ class Editor : public QObject { void startAutosaveTimer(int intervalSeconds); void stopAutosaveTimer(); + /** + * @brief The file that Save writes to. It is empty for a new mission, a template, and an FS1 import. + * @details loadMission() and createNewMission() set it. Save As sets it with setCurrentMissionPath(). + */ + const QString& currentMissionPath() const { return _currentMissionPath; } void setCurrentMissionPath(const QString& path); const QString& autosaveDirectory() const { return _autosaveDirectory; } - /*! Load a mission. */ + /** + * @brief Loads a mission. + * @param filepath The file to load. + * @param flags The MPF_* parse flags. A file with the .fst extension always loads as a template. + * @details On success, currentMissionPath() is the file that Save writes to, and missionLoaded() sends it. + * @return true if the mission loaded. On failure, the editor shows an error and creates a new mission. + */ bool loadMission(const std::string& filepath, int flags = 0); void markObject(int objId); @@ -140,6 +151,9 @@ class Editor : public QObject { * @brief Signal for when a new mission has been loaded * @param filepath The path of the mission file, empty if new mission */ + /** + * @param filepath The value of currentMissionPath(). + */ void missionLoaded(const std::string& filepath); /** diff --git a/qtfred/src/ui/FredView.cpp b/qtfred/src/ui/FredView.cpp index 9d8fd11acb5..92a4b385716 100644 --- a/qtfred/src/ui/FredView.cpp +++ b/qtfred/src/ui/FredView.cpp @@ -319,7 +319,7 @@ void FredView::setEditor(Editor* editor, EditorViewport* viewport) { &FredView::viewIdle, this, [this]() { ui->actionRestore_Camera_Pos->setEnabled(_viewport->camera.hasSavedPosition()); }); - connect(this, &FredView::viewIdle, this, [this]() { ui->actionRevert->setEnabled(!saveName.isEmpty()); }); + connect(this, &FredView::viewIdle, this, [this]() { ui->actionRevert->setEnabled(!fred->currentMissionPath().isEmpty()); }); // Scene Browser dock panel _browserPanel = new SceneBrowserPanel(this, _viewport); addDockWidget(Qt::LeftDockWidgetArea, _browserPanel); @@ -482,7 +482,8 @@ bool FredView::performPreSaveCheck(int* outFixCount) { } bool FredView::saveMissionToCurrentPath() { - if (saveName.isEmpty()) + const QString path = fred->currentMissionPath(); + if (path.isEmpty()) return saveMissionAs(); int fixCount = -1; @@ -498,7 +499,7 @@ bool FredView::saveMissionToCurrentPath() { save.set_fred_alt_names(Fred_alt_names); save.set_fred_callsigns(Fred_callsigns); - save.save_mission_file(saveName.replace('/', DIR_SEPARATOR_CHAR).toUtf8().constData()); + save.save_mission_file(path.toUtf8().constData()); _missionModified = false; setLastSaved(QDateTime::currentDateTime()); @@ -524,11 +525,13 @@ bool FredView::saveMissionAs() { return false; const QString lastDir = fso::fred::util::getLastDir("missions/saveMission", CF_TYPE_MISSIONS); - saveName = QFileDialog::getSaveFileName(this, tr("Save mission"), lastDir, tr("FS2 missions (*.fs2)")); - if (saveName.isEmpty()) + // Use a local variable, so that a cancelled dialog does not clear the current file name. + QString newSaveName = QFileDialog::getSaveFileName(this, tr("Save mission"), lastDir, tr("FS2 missions (*.fs2)")); + if (newSaveName.isEmpty()) return false; - fso::fred::util::saveLastDir("missions/saveMission", saveName); + fso::fred::util::saveLastDir("missions/saveMission", newSaveName); + newSaveName.replace('/', DIR_SEPARATOR_CHAR); Fred_mission_save save; save.set_save_format(_missionSaveFormat); @@ -539,7 +542,7 @@ bool FredView::saveMissionAs() { save.set_fred_alt_names(Fred_alt_names); save.set_fred_callsigns(Fred_callsigns); - save.save_mission_file(saveName.replace('/', DIR_SEPARATOR_CHAR).toUtf8().constData()); + save.save_mission_file(newSaveName.toUtf8().constData()); _missionModified = false; setLastSaved(QDateTime::currentDateTime()); @@ -554,8 +557,9 @@ bool FredView::saveMissionAs() { if (_errorCheckerDialog && _errorCheckerDialog->isVisible()) _errorCheckerDialog->runCheck(); - fred->setCurrentMissionPath(saveName); - restartAutosaveTimer(); + fred->setCurrentMissionPath(newSaveName); + showCurrentMissionFile(); + addToRecentFiles(newSaveName); return true; } @@ -646,7 +650,9 @@ void FredView::on_actionSave_As_Template_triggered(bool) { } void FredView::on_actionRevert_triggered(bool) { - if (saveName.isEmpty()) { + // A copy, because the load changes the current mission path. + const QString path = fred->currentMissionPath(); + if (path.isEmpty()) { QMessageBox::information(this, tr("Revert"), tr("Mission has not been saved yet.")); return; } @@ -658,7 +664,7 @@ void FredView::on_actionRevert_triggered(bool) { return; // Clear modified flag so loadMissionFile doesn't prompt to save again _missionModified = false; - loadMissionFile(saveName); + loadMissionFile(path); } void FredView::on_actionFS2_Open_triggered(bool) { @@ -827,32 +833,10 @@ void FredView::on_mission_loaded(const std::string& filepath) { _tbLayerComboDirty = true; } - QString filename = "Untitled"; - if (!filepath.empty()) { - filename = QFileInfo(QString::fromStdString(filepath)).fileName(); - } - - // The "[*]" is the placeholder for showing the modified state of the window - auto title = tr("%1[*]").arg(filename); - - setWindowTitle(title); - // This will add some additional features on platforms that make use of this information - setWindowFilePath(QString::fromStdString(filepath)); - - if (!filepath.empty()) { - auto qpath = QString::fromStdString(filepath); - // Templates are loaded to edit, not saved back to their original path - if (!qpath.endsWith(".fst", Qt::CaseInsensitive)) { - saveName = qpath; - } - addToRecentFiles(qpath); - } else { - saveName = QString(); - } - - // Update autosave path and start/stop timer based on whether we have a named file. - fred->setCurrentMissionPath(saveName); - restartAutosaveTimer(); + // filepath is Editor::currentMissionPath(). It is empty for a new mission and a template. + showCurrentMissionFile(); + if (!filepath.empty()) + addToRecentFiles(QString::fromStdString(filepath)); _missionModified = false; @@ -863,6 +847,19 @@ void FredView::on_mission_loaded(const std::string& filepath) { } } +void FredView::showCurrentMissionFile() { + const QString& path = fred->currentMissionPath(); + const QString filename = path.isEmpty() ? QStringLiteral("Untitled") : QFileInfo(path).fileName(); + + // The "[*]" is the placeholder for showing the modified state of the window + setWindowTitle(tr("%1[*]").arg(filename)); + // This will add some additional features on platforms that make use of this information + setWindowFilePath(path); + + // The autosave file name depends on the mission path, so start the interval again. + restartAutosaveTimer(); +} + QSurface* FredView::getRenderSurface() { return ui->centralWidget->getRenderSurface(); } diff --git a/qtfred/src/ui/FredView.h b/qtfred/src/ui/FredView.h index d0ef4460af0..65d5ec75a79 100644 --- a/qtfred/src/ui/FredView.h +++ b/qtfred/src/ui/FredView.h @@ -230,6 +230,8 @@ class FredView: public QMainWindow, public IDialogProvider { void on_actionControlModeCurrentShip_triggered(bool enabled); void addToRecentFiles(const QString& path); + // Shows the current mission file (Editor::currentMissionPath()) in the window title. + void showCurrentMissionFile(); // The editor dialogs and the campaign editor that are open as children of this window. QList editorWindows() const; void updateRecentFileList(); @@ -285,7 +287,6 @@ class FredView: public QMainWindow, public IDialogProvider { QAction* _controlModeCamera = nullptr; QAction* _controlModeCurrentShip = nullptr; - QString saveName = nullptr; MissionFormat _missionSaveFormat = MissionFormat::STANDARD; std::unique_ptr ui; From 9b71d97c788ae59496320a0f450540e6d6e0ba19 Mon Sep 17 00:00:00 2001 From: the-e Date: Wed, 11 Nov 2026 19:52:39 +0100 Subject: [PATCH 10/26] QtFRED: do not make the FS1 source file the save target The FS1 import loads the .fsm file and then saves it as an FS2 mission. The load made the .fsm file the save path. If the conversion save failed, the mission stayed loaded, and Save wrote FS2 data over the FS1 source file. An FS1 import now gives an untitled mission. After a successful conversion, the import loads the converted file as before. Co-Authored-By: Claude Opus 5.5 --- qtfred/src/mission/Editor.cpp | 5 +++-- qtfred/src/ui/FredView.cpp | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/qtfred/src/mission/Editor.cpp b/qtfred/src/mission/Editor.cpp index c13330ef8ed..4e9a733000e 100644 --- a/qtfred/src/mission/Editor.cpp +++ b/qtfred/src/mission/Editor.cpp @@ -422,8 +422,9 @@ bool Editor::loadMission(const std::string& mission_name, int flags) { stars_post_level_init(); - // The path that Save writes to. A template has no such file: the user must give a name with Save As. - if (flags & MPF_IS_TEMPLATE) + // The path that Save writes to. A template and an FS1 import have no such file: the user must give a + // name with Save As. + if (flags & (MPF_IS_TEMPLATE | MPF_IMPORT_FSM)) setCurrentMissionPath({}); else setCurrentMissionPath(QString::fromStdString(filepath)); diff --git a/qtfred/src/ui/FredView.cpp b/qtfred/src/ui/FredView.cpp index 92a4b385716..bff3b36c4d9 100644 --- a/qtfred/src/ui/FredView.cpp +++ b/qtfred/src/ui/FredView.cpp @@ -833,7 +833,7 @@ void FredView::on_mission_loaded(const std::string& filepath) { _tbLayerComboDirty = true; } - // filepath is Editor::currentMissionPath(). It is empty for a new mission and a template. + // filepath is Editor::currentMissionPath(). It is empty for a new mission, a template, and an FS1 import. showCurrentMissionFile(); if (!filepath.empty()) addToRecentFiles(QString::fromStdString(filepath)); From 77defb7744001bc24b6f745f4919b6de37833402 Mon Sep 17 00:00:00 2001 From: the-e Date: Wed, 11 Nov 2026 19:54:25 +0100 Subject: [PATCH 11/26] QtFRED: fix autosave recovery Several defects in the autosave recovery: - After a recovery, the save path pointed to the file in the autosave folder, so Save wrote there. On Windows, the '/' separators from QStandardPaths could trigger the CFile assert "We have full path, but no separator!?". - Two missions with the same file name in different folders shared one autosave, so the recovery could load the wrong mission. - The timer wrote an autosave also without unsaved changes. The next load then offered a recovery of content that was already in the file, and Revert could bring back the changes that the user had just discarded. Editor::loadMission() now owns the recovery. It asks about a newer autosave, loads it with native separators, and keeps the original mission path as the save path. missionLoaded() tells FredView that the content is not saved yet, so the mission shows as modified. A failed load gives an untitled mission. The autosave name contains a hash of the full mission path. The timer writes an autosave only for unsaved changes, and Revert does not offer a recovery. The dead catch block in loadMissionFile() is removed. Co-Authored-By: Claude Opus 5.5 --- qtfred/src/mission/Editor.cpp | 66 +++++++++++++++++++++-------------- qtfred/src/mission/Editor.h | 20 +++++++++-- qtfred/src/ui/FredView.cpp | 40 ++++++++++----------- qtfred/src/ui/FredView.h | 8 +++-- 4 files changed, 82 insertions(+), 52 deletions(-) diff --git a/qtfred/src/mission/Editor.cpp b/qtfred/src/mission/Editor.cpp index 4e9a733000e..812df83f221 100644 --- a/qtfred/src/mission/Editor.cpp +++ b/qtfred/src/mission/Editor.cpp @@ -39,6 +39,7 @@ #include "ui/QtGraphicsOperations.h" #include +#include #include #include #include @@ -148,22 +149,32 @@ void Editor::update() { } } -void Editor::maybeUseAutosave(std::string& filepath) +QString Editor::autosavePathFor(const QString& missionPath) const { - const QString qpath = QString::fromStdString(filepath); - const QString basename = QFileInfo(qpath).fileName(); - const QString autosavePath = _autosaveDirectory + basename; + if (missionPath.isEmpty()) + return _autosaveDirectory + "untitled_autosave.fs2"; - const QFileInfo autosaveInfo(autosavePath); - if (!autosaveInfo.exists()) - return; + const QFileInfo info(missionPath); + QString key = QDir::cleanPath(info.absoluteFilePath()); +#ifdef _WIN32 + // Windows paths are not case-sensitive. + key = key.toLower(); +#endif + const auto hash = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Md5).toHex().left(8); - const QFileInfo originalInfo(qpath); - if (autosaveInfo.lastModified() <= originalInfo.lastModified()) - return; + return _autosaveDirectory + info.completeBaseName() + "." + QString::fromLatin1(hash) + "." + info.suffix(); +} + +QString Editor::askToUseNewerAutosave(const QString& missionPath) +{ + const QString autosavePath = autosavePathFor(missionPath); + + const QFileInfo autosaveInfo(autosavePath); + if (!autosaveInfo.exists() || autosaveInfo.lastModified() <= QFileInfo(missionPath).lastModified()) + return {}; if (_lastActiveViewport == nullptr || _lastActiveViewport->dialogProvider == nullptr) - return; + return {}; const auto result = _lastActiveViewport->dialogProvider->showButtonDialog( DialogType::Question, @@ -171,9 +182,8 @@ void Editor::maybeUseAutosave(std::string& filepath) "An autosave file for this mission is newer than the original. Load the autosave instead?", { DialogButton::Yes, DialogButton::No }); - if (result == DialogButton::Yes) { - filepath = autosavePath.toStdString(); - } + // QStandardPaths gives '/' separators. CFile expects the native separator in an absolute path. + return result == DialogButton::Yes ? QDir::toNativeSeparators(autosavePath) : QString(); } void Editor::startAutosaveTimer(int intervalSeconds) { @@ -191,16 +201,10 @@ void Editor::setCurrentMissionPath(const QString& path) { } void Editor::performTimedAutosave() { - QString savePath; - if (_currentMissionPath.isEmpty()) { - savePath = _autosaveDirectory + "untitled_autosave.fs2"; - } else { - savePath = _autosaveDirectory + QFileInfo(_currentMissionPath).fileName(); - } - autosaveDue(savePath); + autosaveDue(autosavePathFor(_currentMissionPath)); } -bool Editor::loadMission(const std::string& mission_name, int flags) { +bool Editor::loadMission(const std::string& mission_name, int flags, bool offerAutosaveRecovery) { char name[512], * old_name; int i, j, ob; object* objp; @@ -213,9 +217,15 @@ bool Editor::loadMission(const std::string& mission_name, int flags) { if (QString::fromStdString(mission_name).endsWith(".fst", Qt::CaseInsensitive)) flags |= MPF_IS_TEMPLATE; + // A template is not a mission file that the user edits, so it has no autosave. + QString autosavePath; + if (offerAutosaveRecovery && !(flags & MPF_IS_TEMPLATE)) + autosavePath = askToUseNewerAutosave(QString::fromStdString(mission_name)); + const bool recovered = !autosavePath.isEmpty(); + clearMission(flags & MPF_FAST_RELOAD); - std::string filepath = mission_name; + std::string filepath = recovered ? autosavePath.toStdString() : mission_name; auto res = cf_find_file_location(filepath.c_str(), CF_TYPE_MISSIONS); if (res.found) { // We found this file in the CFile system @@ -423,13 +433,15 @@ bool Editor::loadMission(const std::string& mission_name, int flags) { stars_post_level_init(); // The path that Save writes to. A template and an FS1 import have no such file: the user must give a - // name with Save As. - if (flags & (MPF_IS_TEMPLATE | MPF_IMPORT_FSM)) + // name with Save As. An autosave belongs to the mission file that it came from. + if (recovered) + setCurrentMissionPath(QString::fromStdString(mission_name)); + else if (flags & (MPF_IS_TEMPLATE | MPF_IMPORT_FSM)) setCurrentMissionPath({}); else setCurrentMissionPath(QString::fromStdString(filepath)); - missionLoaded(_currentMissionPath.toStdString()); + missionLoaded(_currentMissionPath.toStdString(), recovered); // This hook will allow for scripts to know when a mission has been loaded // which will then allow them to update any LuaEnums that may be related to sexps @@ -843,7 +855,7 @@ void Editor::createNewMission() { stars_post_level_init(); // TODO(Phase 3): _undoStack->clear() setCurrentMissionPath({}); - missionLoaded(""); + missionLoaded("", false); } void Editor::hideMarkedObjects() { object* ptr; diff --git a/qtfred/src/mission/Editor.h b/qtfred/src/mission/Editor.h index 7cc37ac6b6c..af468acfa27 100644 --- a/qtfred/src/mission/Editor.h +++ b/qtfred/src/mission/Editor.h @@ -67,7 +67,12 @@ class Editor : public QObject { void createNewMission(); - void maybeUseAutosave(std::string& filepath); + /** + * @brief Returns the autosave file for a mission path, or the untitled autosave file for an empty path. + * @details The name contains a hash of the full path. Thus two missions with the same file name in + * different folders do not share an autosave. + */ + QString autosavePathFor(const QString& missionPath) const; void startAutosaveTimer(int intervalSeconds); void stopAutosaveTimer(); @@ -83,10 +88,12 @@ class Editor : public QObject { * @brief Loads a mission. * @param filepath The file to load. * @param flags The MPF_* parse flags. A file with the .fst extension always loads as a template. + * @param offerAutosaveRecovery If true and a newer autosave exists, ask the user to load the autosave. * @details On success, currentMissionPath() is the file that Save writes to, and missionLoaded() sends it. + * A recovered autosave belongs to filepath, and its content is not saved yet. * @return true if the mission loaded. On failure, the editor shows an error and creates a new mission. */ - bool loadMission(const std::string& filepath, int flags = 0); + bool loadMission(const std::string& filepath, int flags = 0, bool offerAutosaveRecovery = false); void markObject(int objId); void unmarkObject(int objId); @@ -153,8 +160,9 @@ class Editor : public QObject { */ /** * @param filepath The value of currentMissionPath(). + * @param hasUnsavedContent true if the mission content is not in that file (a recovered autosave). */ - void missionLoaded(const std::string& filepath); + void missionLoaded(const std::string& filepath, bool hasUnsavedContent); /** * @brief A signal emitted when the mission has changed somehow @@ -279,6 +287,12 @@ class Editor : public QObject { private slots: void performTimedAutosave(); + /** + * @brief Asks the user to load the autosave of a mission if the autosave is newer than the mission file. + * @return The autosave path with native separators, or an empty string if the mission file stays. + */ + QString askToUseNewerAutosave(const QString& missionPath); + private: // NOLINT(readability-redundant-access-specifiers) QTimer* _autosaveTimer = nullptr; QString _autosaveDirectory; diff --git a/qtfred/src/ui/FredView.cpp b/qtfred/src/ui/FredView.cpp index bff3b36c4d9..9e5c1b86177 100644 --- a/qtfred/src/ui/FredView.cpp +++ b/qtfred/src/ui/FredView.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include @@ -282,6 +283,11 @@ void FredView::setEditor(Editor* editor, EditorViewport* viewport) { connect(fred, &Editor::missionLoaded, this, &FredView::on_mission_loaded); connect(fred, &Editor::missionChanged, this, [this]() { _missionModified = true; }); connect(fred, &Editor::autosaveDue, this, [this](const QString& savePath) { + // Write an autosave only for unsaved changes. Otherwise the autosave is newer than the mission + // file, and the next load offers a recovery of content that is already in the file. + if (!_missionModified) + return; + Fred_mission_save save; save.set_save_format(_missionSaveFormat); save.set_always_save_display_names(_viewport->Always_save_display_names); @@ -294,7 +300,7 @@ void FredView::setEditor(Editor* editor, EditorViewport* viewport) { connect(fred, &Editor::layerListChanged, this, [this]() { _tbLayerComboDirty = true; }); // Sets the initial window title - on_mission_loaded(""); + on_mission_loaded("", false); syncViewOptions(); @@ -362,30 +368,22 @@ void FredView::setEditor(Editor* editor, EditorViewport* viewport) { _contextToolBar->setFixedHeight(qMax(28, ui->toolBar->sizeHint().height())); } -void FredView::loadMissionFile(const QString& pathName, int flags) { +void FredView::loadMissionFile(const QString& pathName, int flags, bool offerAutosaveRecovery) { if (!maybePromptToSaveMissionChanges(tr("loading another mission"))) { return; } statusBar()->showMessage(tr("Loading mission %1").arg(pathName)); - try { - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - - // probably good to clear selections in qtFRED too - fred->clean_up_selections(); - - auto pathToLoad = pathName.toStdString(); - if (!(flags & MPF_IS_TEMPLATE) && _viewport->Offer_autosave_recovery) - fred->maybeUseAutosave(pathToLoad); + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + auto restoreCursor = ::util::finally([] { QApplication::restoreOverrideCursor(); }); - fred->loadMission(pathToLoad, flags); + // probably good to clear selections in qtFRED too + fred->clean_up_selections(); - QApplication::restoreOverrideCursor(); + // On failure, loadMission() shows the error and creates a new, untitled mission. + if (fred->loadMission(pathName.toStdString(), flags, offerAutosaveRecovery && _viewport->Offer_autosave_recovery)) { autoRunErrorChecker(); - } catch (const fso::fred::mission_load_error&) { - QApplication::restoreOverrideCursor(); - - QMessageBox::critical(this, tr("Failed loading mission."), tr("Could not parse the mission.")); + } else { statusBar()->clearMessage(); } } @@ -664,7 +662,8 @@ void FredView::on_actionRevert_triggered(bool) { return; // Clear modified flag so loadMissionFile doesn't prompt to save again _missionModified = false; - loadMissionFile(path); + // Revert discards the changes. Do not offer the autosave, because it can contain those changes. + loadMissionFile(path, 0, false); } void FredView::on_actionFS2_Open_triggered(bool) { @@ -817,7 +816,7 @@ void FredView::on_actionRun_FreeSpace_2_Open_triggered(bool) { } } -void FredView::on_mission_loaded(const std::string& filepath) { +void FredView::on_mission_loaded(const std::string& filepath, bool hasUnsavedContent) { // Clear browsed head ANIs so the new mission's message scan starts fresh. fso::fred::dialogs::MissionEventsDialogModel::clearBrowsedHeadAnis(); @@ -838,7 +837,8 @@ void FredView::on_mission_loaded(const std::string& filepath) { if (!filepath.empty()) addToRecentFiles(QString::fromStdString(filepath)); - _missionModified = false; + // A recovered autosave is not in the mission file yet. + _missionModified = hasUnsavedContent; if (filepath.empty()) { statusBar()->showMessage(tr("Every great mission starts here. No pressure.")); diff --git a/qtfred/src/ui/FredView.h b/qtfred/src/ui/FredView.h index 65d5ec75a79..8606d56d4e4 100644 --- a/qtfred/src/ui/FredView.h +++ b/qtfred/src/ui/FredView.h @@ -50,7 +50,11 @@ class FredView: public QMainWindow, public IDialogProvider { ~FredView() override; void setEditor(Editor* editor, EditorViewport* viewport); - void loadMissionFile(const QString& pathName, int flags = 0); + /** + * @brief Loads a mission file after the prompt to save the current mission. + * @param offerAutosaveRecovery false if the load must not offer a newer autosave (for example Revert). + */ + void loadMissionFile(const QString& pathName, int flags = 0, bool offerAutosaveRecovery = true); QSurface* getRenderSurface(); RenderWidget* getRenderWidget(); @@ -221,7 +225,7 @@ class FredView: public QMainWindow, public IDialogProvider { bool maybePromptToSaveMissionChanges(const QString& actionDescription); bool isMissionModified() const; - void on_mission_loaded(const std::string& filepath); + void on_mission_loaded(const std::string& filepath, bool hasUnsavedContent); void connectActionToViewSetting(QAction* option, bool* destination); void connectActionToViewSetting(QAction* option, std::vector* vector, size_t idx); From 50e5816f09b9dfc8633280a06cee22b1e4d1a0ec Mon Sep 17 00:00:00 2001 From: the-e Date: Wed, 11 Nov 2026 19:54:37 +0100 Subject: [PATCH 12/26] QtFRED: report a failed mission save save_mission_file() only writes to the log when it fails. Save and Save As ignored its result: they cleared the modified flag and set the last-saved time also after a failure. The user saw no message, and QtFRED then closed without a prompt, so the edits were lost. The new writeMissionFile() checks the result. On failure, it shows an error and keeps the modified flag. Save As then also keeps the old file name. configureMissionSave() now sets the save options in one place for Save, the autosave, and the FS1 import, and reportPreSaveFixes() shows the pre-save check result for Save and Save As. Co-Authored-By: Claude Opus 5.5 --- qtfred/src/ui/FredView.cpp | 83 +++++++++++++++++--------------------- qtfred/src/ui/FredView.h | 4 ++ 2 files changed, 40 insertions(+), 47 deletions(-) diff --git a/qtfred/src/ui/FredView.cpp b/qtfred/src/ui/FredView.cpp index 9e5c1b86177..cffddffd5d0 100644 --- a/qtfred/src/ui/FredView.cpp +++ b/qtfred/src/ui/FredView.cpp @@ -289,12 +289,7 @@ void FredView::setEditor(Editor* editor, EditorViewport* viewport) { return; Fred_mission_save save; - save.set_save_format(_missionSaveFormat); - save.set_always_save_display_names(_viewport->Always_save_display_names); - save.set_view_pos(_viewport->camera.view_pos); - save.set_view_orient(_viewport->camera.view_orient); - save.set_fred_alt_names(Fred_alt_names); - save.set_fred_callsigns(Fred_callsigns); + configureMissionSave(save); save.save_autosave_file(savePath.toUtf8().constData()); }); connect(fred, &Editor::layerListChanged, this, [this]() { _tbLayerComboDirty = true; }); @@ -479,16 +474,7 @@ bool FredView::performPreSaveCheck(int* outFixCount) { } } -bool FredView::saveMissionToCurrentPath() { - const QString path = fred->currentMissionPath(); - if (path.isEmpty()) - return saveMissionAs(); - - int fixCount = -1; - if (!performPreSaveCheck(&fixCount)) - return false; - - Fred_mission_save save; +void FredView::configureMissionSave(Fred_mission_save& save) const { save.set_save_format(_missionSaveFormat); save.set_always_save_display_names(_viewport->Always_save_display_names); save.set_create_bak_file(_viewport->Create_bak_on_save); @@ -496,11 +482,25 @@ bool FredView::saveMissionToCurrentPath() { save.set_view_orient(_viewport->camera.view_orient); save.set_fred_alt_names(Fred_alt_names); save.set_fred_callsigns(Fred_callsigns); +} + +bool FredView::writeMissionFile(const QString& path) { + Fred_mission_save save; + configureMissionSave(save); + + // save_mission_file() returns 0 on success. On failure it only writes to the log, so tell the user here. + if (save.save_mission_file(path.toUtf8().constData()) != 0) { + QMessageBox::critical(this, tr("Save Failed"), + tr("QtFRED could not write the mission to\n%1\n\nThe mission is not saved.").arg(path)); + return false; + } - save.save_mission_file(path.toUtf8().constData()); _missionModified = false; setLastSaved(QDateTime::currentDateTime()); + return true; +} +void FredView::reportPreSaveFixes(int fixCount) { if (fixCount > 0) QMessageBox::information(this, tr("Auto-corrections Applied"), tr("%n issue(s) were automatically corrected before saving.", "", fixCount)); @@ -511,7 +511,21 @@ bool FredView::saveMissionToCurrentPath() { // Keep the persistent error checker in sync if it is already open. if (_errorCheckerDialog && _errorCheckerDialog->isVisible()) _errorCheckerDialog->runCheck(); +} +bool FredView::saveMissionToCurrentPath() { + const QString path = fred->currentMissionPath(); + if (path.isEmpty()) + return saveMissionAs(); + + int fixCount = -1; + if (!performPreSaveCheck(&fixCount)) + return false; + + if (!writeMissionFile(path)) + return false; + + reportPreSaveFixes(fixCount); return true; } @@ -531,30 +545,11 @@ bool FredView::saveMissionAs() { fso::fred::util::saveLastDir("missions/saveMission", newSaveName); newSaveName.replace('/', DIR_SEPARATOR_CHAR); - Fred_mission_save save; - save.set_save_format(_missionSaveFormat); - save.set_always_save_display_names(_viewport->Always_save_display_names); - save.set_create_bak_file(_viewport->Create_bak_on_save); - save.set_view_pos(_viewport->camera.view_pos); - save.set_view_orient(_viewport->camera.view_orient); - save.set_fred_alt_names(Fred_alt_names); - save.set_fred_callsigns(Fred_callsigns); - - save.save_mission_file(newSaveName.toUtf8().constData()); - _missionModified = false; - setLastSaved(QDateTime::currentDateTime()); - - if (fixCount > 0) - QMessageBox::information(this, tr("Auto-corrections Applied"), - tr("%n issue(s) were automatically corrected before saving.", "", fixCount)); - else if (fixCount == 0) - QMessageBox::information(this, tr("No Auto-corrections Applied"), - tr("No issues could be automatically corrected. The mission was saved with existing errors.")); - - // Keep the persistent error checker in sync if it is already open. - if (_errorCheckerDialog && _errorCheckerDialog->isVisible()) - _errorCheckerDialog->runCheck(); + // On failure, keep the old file name and the modified flag. + if (!writeMissionFile(newSaveName)) + return false; + reportPreSaveFixes(fixCount); fred->setCurrentMissionPath(newSaveName); showCurrentMissionFile(); addToRecentFiles(newSaveName); @@ -729,13 +724,7 @@ void FredView::on_actionFS1_Mission_triggered(bool) { destPath += filename; Fred_mission_save fileSave; - fileSave.set_save_format(_missionSaveFormat); - fileSave.set_always_save_display_names(_viewport->Always_save_display_names); - fileSave.set_create_bak_file(_viewport->Create_bak_on_save); - fileSave.set_view_pos(_viewport->camera.view_pos); - fileSave.set_view_orient(_viewport->camera.view_orient); - fileSave.set_fred_alt_names(Fred_alt_names); - fileSave.set_fred_callsigns(Fred_callsigns); + configureMissionSave(fileSave); if (fileSave.save_mission_file(destPath.c_str()) == 0) { ++successes; diff --git a/qtfred/src/ui/FredView.h b/qtfred/src/ui/FredView.h index 8606d56d4e4..07963fe4750 100644 --- a/qtfred/src/ui/FredView.h +++ b/qtfred/src/ui/FredView.h @@ -238,6 +238,10 @@ class FredView: public QMainWindow, public IDialogProvider { void showCurrentMissionFile(); // The editor dialogs and the campaign editor that are open as children of this window. QList editorWindows() const; + // Sets the save options from the user preferences. Mission saves, autosaves, and FS1 imports use it. + void configureMissionSave(Fred_mission_save& save) const; + bool writeMissionFile(const QString& path); + void reportPreSaveFixes(int fixCount); void updateRecentFileList(); void recentFileOpened(); From 4f2dfc2cd400fb9ccd9aa772b6b0fdb72d04d620 Mon Sep 17 00:00:00 2001 From: the-e Date: Sat, 14 Nov 2026 15:33:27 +0100 Subject: [PATCH 13/26] QtFRED: make setSpinBoxValueOrBlank static The function does not use this. The clang-tidy job reports it as readability-convert-member-functions-to-static. Co-Authored-By: Claude Sonnet 5.5 --- qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.h b/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.h index 991c092e2cb..03c5a24fcfb 100644 --- a/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.h +++ b/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.h @@ -55,7 +55,7 @@ class ShipInitialStatusDialog : public QDialog { EditorViewport* _viewport; void updateUi(); - void setSpinBoxValueOrBlank(MixedValueSpinBox* spinBox, int value); + static void setSpinBoxValueOrBlank(MixedValueSpinBox* spinBox, int value); void updateFlags(); void updateDocks(); void updateDockee(); From 6fa834befd53350a8400c40f057fcacd57d4f816 Mon Sep 17 00:00:00 2001 From: the-e Date: Sat, 14 Nov 2026 15:33:27 +0100 Subject: [PATCH 14/26] FRED2: use arrival_min_distance in the ship editor The ship editor used the radius of the arriving ship and accepted a distance of 0 for a special anchor. The wing editors and QtFRED use the radius of the target. Use the shared rule so the editors agree. Co-Authored-By: Claude Sonnet 5.5 --- fred2/shipeditordlg.cpp | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/fred2/shipeditordlg.cpp b/fred2/shipeditordlg.cpp index 6c70de2ea8b..71c93fffce5 100644 --- a/fred2/shipeditordlg.cpp +++ b/fred2/shipeditordlg.cpp @@ -1285,23 +1285,22 @@ int CShipEditorDlg::update_ship(int ship) z = (int)((CComboBox *) GetDlgItem(IDC_ARRIVAL_TARGET))->GetItemData(m_arrival_target); MODIFY(Ships[ship].arrival_anchor, target_to_anchor(z)); - // if the arrival is not hyperspace or docking bay -- force arrival distance to be - // greater than 2*radius of target. - if (((m_arrival_location != static_cast(ArrivalLocation::FROM_DOCK_BAY)) && (m_arrival_location != static_cast(ArrivalLocation::AT_LOCATION))) && (z >= 0) && !(z & ANCHOR_SPECIAL_ARRIVAL)) { - d = int(std::min(500.0f, 2.0f * Objects[Ships[ship].objnum].radius)); - if ((Ships[ship].arrival_distance < d) && (Ships[ship].arrival_distance > -d)) { + // Force the arrival distance to be at least the minimum for the arrival location and target. + // This is the same rule as the wing editor and QtFRED. + d = arrival_min_distance(static_cast(m_arrival_location), target_to_anchor(z)); + if ((d > 0) && (Ships[ship].arrival_distance < d) && (Ships[ship].arrival_distance > -d)) { + // A minimum of 1 only prevents an invalid distance, so it needs no warning. + if (d > 1) { str.Format("Ship must arrive at least %d meters away from target.\n" - "Value has been reset to this. Use with caution!\r\n" - "Recommended distance is %d meters.\r\n", d, (int)(2.0f * Objects[Ships[ship].objnum].radius) ); - + "Value has been reset to this. Use with caution!\r\n", d); MessageBox(str); - if (Ships[ship].arrival_distance < 0) - Ships[ship].arrival_distance = -d; - else - Ships[ship].arrival_distance = d; - - m_arrival_dist.fix(Ships[ship].arrival_distance); } + if (Ships[ship].arrival_distance < 0) + Ships[ship].arrival_distance = -d; + else + Ships[ship].arrival_distance = d; + + m_arrival_dist.fix(Ships[ship].arrival_distance); } } if (m_departure_target >= 0) { From a0eced8bcf9882d7a3ebb8a0dc8b9b2a8ce4519b Mon Sep 17 00:00:00 2001 From: the-e Date: Mon, 16 Nov 2026 18:13:50 +0100 Subject: [PATCH 15/26] QtFRED: write the autosave at each interval again The autosave gate needed the modified flag. The Reinforcements, Mission Specs, Variables, Briefing, and Asteroid editors do not set it, so an edit in only these editors got no autosave. The gate also kept a stale autosave after Revert or Discard, and the next load offered the discarded changes again. Write the autosave at each interval, the same as before. A successful save, Revert, and Discard now delete the autosave of the mission. Save As also deletes the autosave of the old path. After a save, the interval starts again. askToUseNewerAutosave() is no longer a slot. Co-Authored-By: Claude Opus 5.5 --- qtfred/src/mission/Editor.cpp | 6 ++++++ qtfred/src/mission/Editor.h | 9 ++++++++- qtfred/src/ui/FredView.cpp | 19 +++++++++++++------ 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/qtfred/src/mission/Editor.cpp b/qtfred/src/mission/Editor.cpp index 812df83f221..17f33faa5da 100644 --- a/qtfred/src/mission/Editor.cpp +++ b/qtfred/src/mission/Editor.cpp @@ -41,6 +41,7 @@ #include #include #include +#include #include #include @@ -165,6 +166,11 @@ QString Editor::autosavePathFor(const QString& missionPath) const return _autosaveDirectory + info.completeBaseName() + "." + QString::fromLatin1(hash) + "." + info.suffix(); } +void Editor::removeAutosave(const QString& missionPath) const +{ + QFile::remove(autosavePathFor(missionPath)); +} + QString Editor::askToUseNewerAutosave(const QString& missionPath) { const QString autosavePath = autosavePathFor(missionPath); diff --git a/qtfred/src/mission/Editor.h b/qtfred/src/mission/Editor.h index af468acfa27..4ebecb161cc 100644 --- a/qtfred/src/mission/Editor.h +++ b/qtfred/src/mission/Editor.h @@ -74,6 +74,13 @@ class Editor : public QObject { */ QString autosavePathFor(const QString& missionPath) const; + /** + * @brief Deletes the autosave of a mission path, if it exists. + * @details Call it when the autosave content is not necessary: after a save, a revert, or a discard. + * Otherwise, the next load offers changes that are saved or that the user discarded. + */ + void removeAutosave(const QString& missionPath) const; + void startAutosaveTimer(int intervalSeconds); void stopAutosaveTimer(); /** @@ -287,13 +294,13 @@ class Editor : public QObject { private slots: void performTimedAutosave(); + private: // NOLINT(readability-redundant-access-specifiers) /** * @brief Asks the user to load the autosave of a mission if the autosave is newer than the mission file. * @return The autosave path with native separators, or an empty string if the mission file stays. */ QString askToUseNewerAutosave(const QString& missionPath); - private: // NOLINT(readability-redundant-access-specifiers) QTimer* _autosaveTimer = nullptr; QString _autosaveDirectory; QString _currentMissionPath; diff --git a/qtfred/src/ui/FredView.cpp b/qtfred/src/ui/FredView.cpp index cffddffd5d0..ef489ad4600 100644 --- a/qtfred/src/ui/FredView.cpp +++ b/qtfred/src/ui/FredView.cpp @@ -283,11 +283,8 @@ void FredView::setEditor(Editor* editor, EditorViewport* viewport) { connect(fred, &Editor::missionLoaded, this, &FredView::on_mission_loaded); connect(fred, &Editor::missionChanged, this, [this]() { _missionModified = true; }); connect(fred, &Editor::autosaveDue, this, [this](const QString& savePath) { - // Write an autosave only for unsaved changes. Otherwise the autosave is newer than the mission - // file, and the next load offers a recovery of content that is already in the file. - if (!_missionModified) - return; - + // Write the autosave at each interval. Some editor dialogs do not set the modified flag, so the flag + // cannot tell if the mission has changes. A save, a revert, or a discard deletes the autosave. Fred_mission_save save; configureMissionSave(save); save.save_autosave_file(savePath.toUtf8().constData()); @@ -497,6 +494,11 @@ bool FredView::writeMissionFile(const QString& path) { _missionModified = false; setLastSaved(QDateTime::currentDateTime()); + + // The file now contains the changes, so the autosave is not necessary. For Save As, also delete the + // autosave of the old path (or of the untitled mission). + fred->removeAutosave(path); + fred->removeAutosave(fred->currentMissionPath()); return true; } @@ -525,6 +527,8 @@ bool FredView::saveMissionToCurrentPath() { if (!writeMissionFile(path)) return false; + // Start the interval again. Thus the next autosave comes one full interval after the save. + restartAutosaveTimer(); reportPreSaveFixes(fixCount); return true; } @@ -657,7 +661,8 @@ void FredView::on_actionRevert_triggered(bool) { return; // Clear modified flag so loadMissionFile doesn't prompt to save again _missionModified = false; - // Revert discards the changes. Do not offer the autosave, because it can contain those changes. + // Revert discards the changes. Delete the autosave, because it can contain those changes. + fred->removeAutosave(path); loadMissionFile(path, 0, false); } @@ -1711,6 +1716,8 @@ bool FredView::maybePromptToSaveMissionChanges(const QString& actionDescription) case QMessageBox::Save: return saveMissionToCurrentPath(); case QMessageBox::Discard: + // The user discards the changes, so the next load must not offer them from the autosave. + fred->removeAutosave(fred->currentMissionPath()); return true; case QMessageBox::Cancel: default: From 78ad15819026030ea2b8c112fab97a14006c2721 Mon Sep 17 00:00:00 2001 From: the-e Date: Mon, 16 Nov 2026 18:13:50 +0100 Subject: [PATCH 16/26] QtFRED: keep the mixed state of a spin box on Enter In the mixed state, the value of the spin box is a sentinel below the real range. Enter on an untouched "-" field went through valueFromText(), which clamped "-" to the real minimum. The slots then gave that value to the model, so each marked ship got it. valueFromText() now keeps "-" as the sentinel. The new isBlank() tells the Initial Status and Reinforcements slots to ignore the sentinel, so each ship keeps its own value. Co-Authored-By: Claude Opus 5.5 --- qtfred/src/ui/dialogs/ReinforcementsEditorDialog.cpp | 6 ++++-- .../dialogs/ShipEditor/ShipInitialStatusDialog.cpp | 12 ++++++++++++ qtfred/src/ui/widgets/MixedValueSpinBox.cpp | 11 ++++++++++- qtfred/src/ui/widgets/MixedValueSpinBox.h | 6 +++++- 4 files changed, 31 insertions(+), 4 deletions(-) diff --git a/qtfred/src/ui/dialogs/ReinforcementsEditorDialog.cpp b/qtfred/src/ui/dialogs/ReinforcementsEditorDialog.cpp index 87ba7a42c15..b550e1833ba 100644 --- a/qtfred/src/ui/dialogs/ReinforcementsEditorDialog.cpp +++ b/qtfred/src/ui/dialogs/ReinforcementsEditorDialog.cpp @@ -204,7 +204,8 @@ void ReinforcementsDialog::on_moveSelectionDown_clicked() void ReinforcementsDialog::on_useSpinBox_valueChanged(int val) { // need to check that it's not empty so as not to pass nonsense values back to the model. - if (ui->chosenShipsList->selectedItems().count() > 0) { + // "-" keeps the value of each selected reinforcement. + if (ui->chosenShipsList->selectedItems().count() > 0 && !ui->useSpinBox->isBlank()) { // MixedValueSpinBox keeps each value that the user enters in the real range (0 or more). _model->setUseCount(val); } @@ -213,7 +214,8 @@ void ReinforcementsDialog::on_useSpinBox_valueChanged(int val) void ReinforcementsDialog::on_delaySpinBox_valueChanged(int val) { // need to check that it's not empty so as not to pass nonsense values back to the model. - if (ui->chosenShipsList->selectedItems().count() > 0) { + // "-" keeps the value of each selected reinforcement. + if (ui->chosenShipsList->selectedItems().count() > 0 && !ui->delaySpinBox->isBlank()) { // MixedValueSpinBox keeps each value that the user enters in the real range (0 or more). _model->setBeforeArrivalDelay(val); } diff --git a/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.cpp b/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.cpp index 02f011e7842..66a364539aa 100644 --- a/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.cpp +++ b/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.cpp @@ -67,6 +67,9 @@ void ShipInitialStatusDialog::closeEvent(QCloseEvent* e) } void ShipInitialStatusDialog::on_velocitySpinBox_valueChanged(int value) { + // "-" keeps the value of each marked ship. + if (ui->velocitySpinBox->isBlank()) + return; _model->setVelocity(value); } void ShipInitialStatusDialog::on_dockpointList_currentItemChanged(QListWidgetItem* current) @@ -95,6 +98,9 @@ void ShipInitialStatusDialog::on_dockeePointComboBox_currentIndexChanged(int ind } void ShipInitialStatusDialog::on_hullSpinBox_valueChanged(int value) { + // "-" keeps the value of each marked ship. + if (ui->hullSpinBox->isBlank()) + return; _model->setHull(value); } void ShipInitialStatusDialog::on_hasShieldCheckBox_stateChanged(int state) @@ -103,6 +109,9 @@ void ShipInitialStatusDialog::on_hasShieldCheckBox_stateChanged(int state) } void ShipInitialStatusDialog::on_shieldHullSpinBox_valueChanged(int value) { + // "-" keeps the value of each marked ship. + if (ui->shieldHullSpinBox->isBlank()) + return; _model->setShieldHull(value); } void ShipInitialStatusDialog::on_forceShieldsCheckBox_stateChanged(int state) @@ -165,6 +174,9 @@ void ShipInitialStatusDialog::on_cancelPushButton_clicked() { } void ShipInitialStatusDialog::on_guardianSpinBox_valueChanged(int value) { + // "-" keeps the value of each marked ship. + if (ui->guardianSpinBox->isBlank()) + return; _model->setGuardian(value); } void ShipInitialStatusDialog::on_moveShipsCheckBox_toggled(bool value) diff --git a/qtfred/src/ui/widgets/MixedValueSpinBox.cpp b/qtfred/src/ui/widgets/MixedValueSpinBox.cpp index 8c4df860a92..60eaffb1c32 100644 --- a/qtfred/src/ui/widgets/MixedValueSpinBox.cpp +++ b/qtfred/src/ui/widgets/MixedValueSpinBox.cpp @@ -24,6 +24,11 @@ void MixedValueSpinBox::setSingleValue(int value) setValue(value); } +bool MixedValueSpinBox::isBlank() const +{ + return _mixed && value() == minimum(); +} + void MixedValueSpinBox::leaveMixedState() { if (!_mixed) @@ -38,7 +43,7 @@ void MixedValueSpinBox::leaveMixedState() void MixedValueSpinBox::stepBy(int steps) { // From "-", the first step shows the lowest real value. - const bool wasBlank = _mixed && value() == minimum(); + const bool wasBlank = isBlank(); leaveMixedState(); if (!wasBlank) QSpinBox::stepBy(steps); @@ -46,6 +51,10 @@ void MixedValueSpinBox::stepBy(int steps) int MixedValueSpinBox::valueFromText(const QString& text) const { + // Enter on an untouched "-" field keeps the mixed state. The clamp below must not make it a real value. + if (_mixed && text == specialValueText()) + return minimum(); + const int value = QSpinBox::valueFromText(text); // In the mixed state, the minimum is below the real range. A typed value must stay in the real range. return _mixed ? std::clamp(value, _realMinimum, maximum()) : value; diff --git a/qtfred/src/ui/widgets/MixedValueSpinBox.h b/qtfred/src/ui/widgets/MixedValueSpinBox.h index a0293b09805..2f2d7ae9ad7 100644 --- a/qtfred/src/ui/widgets/MixedValueSpinBox.h +++ b/qtfred/src/ui/widgets/MixedValueSpinBox.h @@ -24,8 +24,12 @@ class MixedValueSpinBox : public QSpinBox { // Shows one value for all objects. This ends the mixed state. void setSingleValue(int value); - protected: + // True while the spin box shows "-". Then value() is not a real value, so do not give it to a model. + bool isBlank() const; + void stepBy(int steps) override; + + protected: int valueFromText(const QString& text) const override; private: From d2ab216897ac3d7b0d9c62def1faa6c9fdd3a45d Mon Sep 17 00:00:00 2001 From: the-e Date: Mon, 16 Nov 2026 18:13:50 +0100 Subject: [PATCH 17/26] Editors: apply the arrival distance minimum to each ship The QtFRED ship editor examined only the distance of the last marked ship, and then wrote its minimum to each marked ship. It also examined the target before it wrote the new target to the ships. FRED2's ship editor used the dialog's arrival location, which is -1 when the marked ships have different locations, so it did no check. FRED2's wing editor still used the old rule. Each ship and wing now gets the minimum for its own location and target, and a ship with a sufficient distance keeps it. A negative distance goes up to the minimum, because the parser changes a value of 0 or less to 1. In multi-edit mode, FRED2 does not write the minimum of one ship into the field, because save() copies the field to each ship. Co-Authored-By: Claude Opus 5.5 --- fred2/shipeditordlg.cpp | 32 +++++++------- fred2/wing_editor.cpp | 31 ++++++------- .../ShipEditor/ShipEditorDialogModel.cpp | 43 +++++++++++-------- .../ShipEditor/ShipEditorDialogModel.h | 4 +- 4 files changed, 58 insertions(+), 52 deletions(-) diff --git a/fred2/shipeditordlg.cpp b/fred2/shipeditordlg.cpp index 71c93fffce5..be9887df183 100644 --- a/fred2/shipeditordlg.cpp +++ b/fred2/shipeditordlg.cpp @@ -1284,25 +1284,27 @@ int CShipEditorDlg::update_ship(int ship) if (m_arrival_target >= 0) { z = (int)((CComboBox *) GetDlgItem(IDC_ARRIVAL_TARGET))->GetItemData(m_arrival_target); MODIFY(Ships[ship].arrival_anchor, target_to_anchor(z)); + } - // Force the arrival distance to be at least the minimum for the arrival location and target. - // This is the same rule as the wing editor and QtFRED. - d = arrival_min_distance(static_cast(m_arrival_location), target_to_anchor(z)); - if ((d > 0) && (Ships[ship].arrival_distance < d) && (Ships[ship].arrival_distance > -d)) { - // A minimum of 1 only prevents an invalid distance, so it needs no warning. - if (d > 1) { - str.Format("Ship must arrive at least %d meters away from target.\n" - "Value has been reset to this. Use with caution!\r\n", d); - MessageBox(str); - } - if (Ships[ship].arrival_distance < 0) - Ships[ship].arrival_distance = -d; - else - Ships[ship].arrival_distance = d; + // Force the arrival distance to be at least the minimum for the arrival location and target. + // This is the same rule as the wing editor and QtFRED. In multi-edit mode, the marked ships can have + // different locations and targets, so use the values of this ship. + d = arrival_min_distance(Ships[ship].arrival_location, Ships[ship].arrival_anchor); + if (Ships[ship].arrival_distance < d) { + // A minimum of 1 only prevents an invalid distance, so it needs no warning. + if (d > 1) { + str.Format("Ship must arrive at least %d meters away from target.\n" + "Value has been reset to this. Use with caution!\r\n", d); + MessageBox(str); + } + Ships[ship].arrival_distance = d; + // In multi-edit mode, save() copies the field to each marked ship. The field must not get the + // minimum of one ship, because the minimum of each ship can be different. + if (!multi_edit) m_arrival_dist.fix(Ships[ship].arrival_distance); - } } + if (m_departure_target >= 0) { z = (int)((CComboBox *) GetDlgItem(IDC_DEPARTURE_TARGET))->GetItemData(m_departure_target); MODIFY(Ships[ship].departure_anchor, target_to_anchor(z)); diff --git a/fred2/wing_editor.cpp b/fred2/wing_editor.cpp index 21f1005f30a..8d936364c20 100644 --- a/fred2/wing_editor.cpp +++ b/fred2/wing_editor.cpp @@ -729,25 +729,20 @@ void wing_editor::update_data_safe() i = (int)((CComboBox *) GetDlgItem(IDC_ARRIVAL_TARGET))->GetItemData(m_arrival_target); MODIFY(Wings[cur_wing].arrival_anchor, target_to_anchor(i)); - // when arriving near or in front of a ship, be sure that we are far enough away from it!!! - if (((m_arrival_location != static_cast(ArrivalLocation::AT_LOCATION)) && (m_arrival_location != static_cast(ArrivalLocation::FROM_DOCK_BAY))) && (i >= 0) && !(i & ANCHOR_SPECIAL_ARRIVAL)) { - d = int(std::min(MIN_TARGET_ARRIVAL_DISTANCE, MIN_TARGET_ARRIVAL_MULTIPLIER * Objects[Ships[i].objnum].radius)); - if ((Wings[cur_wing].arrival_distance < d) && (Wings[cur_wing].arrival_distance > -d)) { - if (!bypass_errors) { - sprintf(buf, "Ship must arrive at least %d meters away from target.\n" - "Value has been reset to this. Use with caution!\r\n" - "Recommended distance is %d meters.\r\n", d, (int)(MIN_TARGET_ARRIVAL_MULTIPLIER * Objects[Ships[i].objnum].radius) ); - - MessageBox(buf); - } - - if (Wings[cur_wing].arrival_distance < 0) - Wings[cur_wing].arrival_distance = -d; - else - Wings[cur_wing].arrival_distance = d; - - m_arrival_dist = Wings[cur_wing].arrival_distance; + // Force the arrival distance to be at least the minimum for the arrival location and target. + // This is the same rule as the ship editor and QtFRED. + d = arrival_min_distance(Wings[cur_wing].arrival_location, Wings[cur_wing].arrival_anchor); + if (Wings[cur_wing].arrival_distance < d) { + // A minimum of 1 only prevents an invalid distance, so it needs no warning. + if (!bypass_errors && (d > 1)) { + sprintf(buf, "Ship must arrive at least %d meters away from target.\n" + "Value has been reset to this. Use with caution!\r\n", d); + + MessageBox(buf); } + + Wings[cur_wing].arrival_distance = d; + m_arrival_dist = Wings[cur_wing].arrival_distance; } } if (m_departure_target >= 0) { diff --git a/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.cpp b/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.cpp index 303fbb6d2ff..855b1548f2d 100644 --- a/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.cpp +++ b/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.cpp @@ -24,6 +24,8 @@ #include +#include + namespace fso::fred::dialogs { ShipEditorDialogModel::ShipEditorDialogModel(QObject* parent, EditorViewport* viewport) : AbstractDialogModel(parent, viewport) @@ -1193,12 +1195,6 @@ bool ShipEditorDialogModel::arrivalNeedsDistance() const return arrival_location_uses_distance(getArrivalLocation()); } -int ShipEditorDialogModel::computeArrivalMinDist() const -{ - // The same rule as the wing editor and FRED2: the radius of the target ship sets the minimum. - return arrival_min_distance(getArrivalLocation(), target_to_anchor(_arrivalTarget)); -} - void ShipEditorDialogModel::writeArrivalDistance(int value) { _arrivalDist = value; @@ -1213,19 +1209,33 @@ void ShipEditorDialogModel::writeArrivalDistance(int value) void ShipEditorDialogModel::enforceArrivalMinDist() { - const int min_dist = computeArrivalMinDist(); - if (min_dist <= 0 || _arrivalDist >= min_dist) - return; + // The marked ships can have different arrival locations and targets, so use the values of each ship. + // The same rule as the wing editor and FRED2: the radius of the target ship sets the minimum. + int largest_raise = 0; + for (auto* ptr = GET_FIRST(&obj_used_list); ptr != END_OF_LIST(&obj_used_list); ptr = GET_NEXT(ptr)) { + if (((ptr->type == OBJ_SHIP) || (ptr->type == OBJ_START)) && (ptr->flags[Object::Object_Flags::Marked])) { + auto& shipp = Ships[ptr->instance]; + if (shipp.wingnum >= 0) + continue; + + const int min_dist = arrival_min_distance(shipp.arrival_location, shipp.arrival_anchor); + if (shipp.arrival_distance < min_dist) { + shipp.arrival_distance = min_dist; + largest_raise = std::max(largest_raise, min_dist); + } + // The dialog shows the distance of the last marked ship, the same as initializeData(). + _arrivalDist = shipp.arrival_distance; + } + } // A minimum of 1 only prevents an invalid distance, so it needs no warning. - if (min_dist > 1) { + if (largest_raise > 1) { QMessageBox::warning(nullptr, tr("Arrival Distance"), tr("Ship must arrive at least %1 meters away from target.\n" "Value has been reset to this. Use with caution!") - .arg(min_dist)); + .arg(largest_raise)); } - writeArrivalDistance(min_dist); } void ShipEditorDialogModel::setArrivalTarget(const int value) @@ -1234,11 +1244,6 @@ void ShipEditorDialogModel::setArrivalTarget(const int value) return; _arrivalTarget = value; - // Re-validate the existing arrival distance now that the target has changed. - // A target change from a special anchor to a real ship can make a previously - // acceptable distance too close. - enforceArrivalMinDist(); - for (auto* ptr = GET_FIRST(&obj_used_list); ptr != END_OF_LIST(&obj_used_list); ptr = GET_NEXT(ptr)) { if (((ptr->type == OBJ_SHIP) || (ptr->type == OBJ_START)) && (ptr->flags[Object::Object_Flags::Marked])) { if (Ships[ptr->instance].wingnum < 0 && value >= 0) { @@ -1246,6 +1251,10 @@ void ShipEditorDialogModel::setArrivalTarget(const int value) } } } + + // Examine the arrival distance again with the new target. A change from a special anchor to a real ship + // can make a distance too small. The ships must have the new anchor before this call. + enforceArrivalMinDist(); setModified(); _editor->missionChanged(); modelChanged(); diff --git a/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.h b/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.h index 3dcceeab7de..b9eaf007dd7 100644 --- a/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.h +++ b/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.h @@ -166,10 +166,10 @@ class ShipEditorDialogModel : public AbstractDialogModel { void shipAltNameClose(int baseShip); void shipCallsignClose(int baseShip); static int makeShipList(int* arr); - int computeArrivalMinDist() const; // Writes the arrival distance to the dialog and to each marked ship that is not in a wing. void writeArrivalDistance(int value); - // Raises the arrival distance to computeArrivalMinDist() if it is smaller. + // For each marked ship that is not in a wing, raises the arrival distance to the minimum for the arrival + // location and target of that ship. A ship with a sufficient distance keeps it. void enforceArrivalMinDist(); int _noDepartureWarp; From e9f96b91aa175c6e6ddb5f7ea18813d8228e3ee1 Mon Sep 17 00:00:00 2001 From: the-e Date: Mon, 16 Nov 2026 18:14:04 +0100 Subject: [PATCH 18/26] Editors: give -1 to a ship that leaves its last group A ship stayed at group 0 after its last group bit was removed, and the mission save then wrote "+Group: 0". Set it back to -1 ("in no group"). QtFRED's Set Group also marks the mission as changed now. Co-Authored-By: Claude Opus 5.5 --- code/missioneditor/common.cpp | 4 +++- qtfred/src/ui/FredView.cpp | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/code/missioneditor/common.cpp b/code/missioneditor/common.cpp index 21b11c4ba63..2a7f35958e9 100644 --- a/code/missioneditor/common.cpp +++ b/code/missioneditor/common.cpp @@ -143,8 +143,10 @@ void ship_set_editor_group(ship& shipp, int group_bit, bool in_group) if (in_group) { shipp.group = (shipp.group < 0 ? 0 : shipp.group) | group_bit; } else if (shipp.group >= 0) { - // A ship in no group keeps -1, so that the mission save writes no group data for it. shipp.group &= ~group_bit; + // A ship in no group has -1, so that the mission save writes no group data for it. + if (shipp.group == 0) + shipp.group = -1; } } diff --git a/qtfred/src/ui/FredView.cpp b/qtfred/src/ui/FredView.cpp index ef489ad4600..7f246ab64f4 100644 --- a/qtfred/src/ui/FredView.cpp +++ b/qtfred/src/ui/FredView.cpp @@ -2982,7 +2982,8 @@ void FredView::onSetGroup(int group) { "These illegal objects you marked were not placed in the group", { DialogButton::Ok }); } - fred->updateAllViewports(); + // The mission file contains the groups. missionChanged() also updates the viewports. + fred->missionChanged(); } void FredView::on_actionControl_Object_triggered(bool) { _viewport->camera.toggleControlMode(); From 44ebebf6548c05d3883b9e8edaf400377ad4a334 Mon Sep 17 00:00:00 2001 From: the-e Date: Mon, 16 Nov 2026 18:14:04 +0100 Subject: [PATCH 19/26] Tests: add tests for the editor rules and the Lua goal cleanup The new editor tests examine the group bits and arrival_min_distance(). The Lua test puts Lua values into the AI goal arguments, calls Script_system.Clear(), and makes sure that the arguments are empty. Co-Authored-By: Claude Opus 5.5 --- test/src/ai/test_ailua.cpp | 50 +++++++ test/src/missioneditor/test_editor_rules.cpp | 130 +++++++++++++++++++ test/src/source_groups.cmake | 5 + 3 files changed, 185 insertions(+) create mode 100644 test/src/ai/test_ailua.cpp create mode 100644 test/src/missioneditor/test_editor_rules.cpp diff --git a/test/src/ai/test_ailua.cpp b/test/src/ai/test_ailua.cpp new file mode 100644 index 00000000000..c05e2b6655b --- /dev/null +++ b/test/src/ai/test_ailua.cpp @@ -0,0 +1,50 @@ +#include "ai/ai.h" +#include "ai/ailua.h" +#include "scripting/lua/LuaValue.h" +#include "scripting/scripting.h" +#include "ship/ship.h" + +#include "util/FSTestFixture.h" + +namespace { + +// The goals of Lua AI modes keep Lua values. The values must be freed before the Lua state closes. +class AiLuaGoalTest : public test::FSTestFixture { + public: + AiLuaGoalTest() : test::FSTestFixture(INIT_CFILE) {} + + protected: + void SetUp() override { + test::FSTestFixture::SetUp(); + + ai_lua_init(); + Script_system.CreateLuaState(); + } + + void TearDown() override { + // Do not keep a value of a closed state, if a check failed before Clear(). + Ai_info[0].lua_ai_target.arguments.clear(); + Ai_info[0].goals[0].lua_ai_target.arguments.clear(); + Wings[0].ai_goals[0].lua_ai_target.arguments.clear(); + Script_system.Clear(); + + test::FSTestFixture::TearDown(); + } +}; + +} // namespace + +TEST_F(AiLuaGoalTest, clear_frees_goal_arguments) { + lua_State* L = Script_system.GetLuaSession(); + ASSERT_NE(L, nullptr); + + Ai_info[0].lua_ai_target.arguments.push_back(luacpp::LuaValue::createValue(L, 1)); + Ai_info[0].goals[0].lua_ai_target.arguments.push_back(luacpp::LuaValue::createValue(L, "goal")); + Wings[0].ai_goals[0].lua_ai_target.arguments.push_back(luacpp::LuaValue::createValue(L, 2.0)); + + Script_system.Clear(); + + EXPECT_TRUE(Ai_info[0].lua_ai_target.arguments.empty()); + EXPECT_TRUE(Ai_info[0].goals[0].lua_ai_target.arguments.empty()); + EXPECT_TRUE(Wings[0].ai_goals[0].lua_ai_target.arguments.empty()); +} diff --git a/test/src/missioneditor/test_editor_rules.cpp b/test/src/missioneditor/test_editor_rules.cpp new file mode 100644 index 00000000000..b38e4c5037b --- /dev/null +++ b/test/src/missioneditor/test_editor_rules.cpp @@ -0,0 +1,130 @@ +#include + +#include "mission/missionparse.h" +#include "missioneditor/common.h" +#include "object/object.h" +#include "ship/ship.h" + +// The selection groups of FRED2 and QtFRED. Each group is one bit, and -1 is "in no group". +TEST(EditorGroups, no_group_matches_no_group) { + ship shipp; + shipp.group = -1; + + for (int bit = 1; bit <= (1 << 8); bit <<= 1) + EXPECT_FALSE(ship_in_editor_group(shipp, bit)); +} + +TEST(EditorGroups, groups_do_not_overlap) { + ship shipp; + shipp.group = -1; + + // Group 3 is bit 4. It must not match groups 1 and 2. + ship_set_editor_group(shipp, 4, true); + EXPECT_EQ(shipp.group, 4); + EXPECT_TRUE(ship_in_editor_group(shipp, 4)); + EXPECT_FALSE(ship_in_editor_group(shipp, 1)); + EXPECT_FALSE(ship_in_editor_group(shipp, 2)); + + ship_set_editor_group(shipp, 1, true); + EXPECT_EQ(shipp.group, 5); + EXPECT_TRUE(ship_in_editor_group(shipp, 1)); + EXPECT_TRUE(ship_in_editor_group(shipp, 4)); +} + +TEST(EditorGroups, last_group_removed_gives_no_group) { + ship shipp; + shipp.group = -1; + ship_set_editor_group(shipp, 2, true); + ship_set_editor_group(shipp, 8, true); + + ship_set_editor_group(shipp, 2, false); + EXPECT_EQ(shipp.group, 8); + + // The mission save writes +Group for 0, so the ship must go back to -1. + ship_set_editor_group(shipp, 8, false); + EXPECT_EQ(shipp.group, -1); +} + +TEST(EditorGroups, remove_from_no_group_keeps_no_group) { + ship shipp; + shipp.group = -1; + + ship_set_editor_group(shipp, 2, false); + EXPECT_EQ(shipp.group, -1); +} + +namespace { + +// The minimum arrival distance that FRED2 and QtFRED share. +class ArrivalMinDistanceTest : public ::testing::Test { + protected: + static constexpr int SHIPNUM = 3; + static constexpr int OBJNUM = 5; + + void SetUp() override { + Ship_registry.clear(); + Ship_registry_map.clear(); + + ship_registry_entry entry("Target"); + entry.shipnum = SHIPNUM; + entry.objnum = OBJNUM; + Ship_registry.push_back(entry); + Ship_registry_map[entry.name] = 0; + + _oldObjnum = Ships[SHIPNUM].objnum; + _oldRadius = Objects[OBJNUM].radius; + Ships[SHIPNUM].objnum = OBJNUM; + } + + void TearDown() override { + Ships[SHIPNUM].objnum = _oldObjnum; + Objects[OBJNUM].radius = _oldRadius; + + Ship_registry.clear(); + Ship_registry_map.clear(); + } + + static anchor_t targetAnchor() { return anchor_t(0); } + + int _oldObjnum = -1; + float _oldRadius = 0.0f; +}; + +} // namespace + +TEST_F(ArrivalMinDistanceTest, location_without_distance) { + Objects[OBJNUM].radius = 100.0f; + + EXPECT_EQ(arrival_min_distance(ArrivalLocation::AT_LOCATION, targetAnchor()), 0); + EXPECT_EQ(arrival_min_distance(ArrivalLocation::FROM_DOCK_BAY, targetAnchor()), 0); +} + +TEST_F(ArrivalMinDistanceTest, special_or_invalid_anchor) { + EXPECT_EQ(arrival_min_distance(ArrivalLocation::NEAR_SHIP, anchor_t(ANCHOR_SPECIAL_ARRIVAL)), 1); + EXPECT_EQ(arrival_min_distance(ArrivalLocation::NEAR_SHIP, anchor_t(ANCHOR_SPECIAL_ARRIVAL | ANCHOR_SPECIAL_ARRIVAL_PLAYER)), 1); + EXPECT_EQ(arrival_min_distance(ArrivalLocation::IN_FRONT_OF_SHIP, anchor_t::invalid()), 1); +} + +TEST_F(ArrivalMinDistanceTest, twice_the_target_radius) { + Objects[OBJNUM].radius = 100.0f; + EXPECT_EQ(arrival_min_distance(ArrivalLocation::NEAR_SHIP, targetAnchor()), 200); + + // The value is rounded, not truncated. + Objects[OBJNUM].radius = 100.3f; + EXPECT_EQ(arrival_min_distance(ArrivalLocation::ABOVE_SHIP, targetAnchor()), 201); +} + +TEST_F(ArrivalMinDistanceTest, limit_of_500) { + Objects[OBJNUM].radius = 1000.0f; + EXPECT_EQ(arrival_min_distance(ArrivalLocation::BELOW_SHIP, targetAnchor()), 500); +} + +TEST_F(ArrivalMinDistanceTest, at_least_1) { + Objects[OBJNUM].radius = 0.1f; + EXPECT_EQ(arrival_min_distance(ArrivalLocation::TO_LEFT_OF_SHIP, targetAnchor()), 1); +} + +TEST_F(ArrivalMinDistanceTest, target_without_object) { + Ships[SHIPNUM].objnum = -1; + EXPECT_EQ(arrival_min_distance(ArrivalLocation::NEAR_SHIP, targetAnchor()), 1); +} diff --git a/test/src/source_groups.cmake b/test/src/source_groups.cmake index 5fd968b8dc8..0f73e542f12 100644 --- a/test/src/source_groups.cmake +++ b/test/src/source_groups.cmake @@ -13,6 +13,10 @@ add_file_folder("Actions\\\\Expression" actions/expression/test_ExpressionParser.cpp ) +add_file_folder("AI" + ai/test_ailua.cpp +) + add_file_folder("Bmpman" bmpman/test_eff.cpp ) @@ -60,6 +64,7 @@ add_file_folder("menuui" add_file_folder("missioneditor" missioneditor/test_object_bounds.cpp + missioneditor/test_editor_rules.cpp ) add_file_folder("mod" From e4a2baed0ea9ae4e0a0030d87f891c4bf5b9b34b Mon Sep 17 00:00:00 2001 From: the-e Date: Mon, 16 Nov 2026 18:14:04 +0100 Subject: [PATCH 20/26] Apply the smaller review notes Move the doc comment of get_special_anchor() back to its function. Remove the unused mission_load_error. Mention Cancel at the mission prompt in the exit comment. Make the recent-files loop variable const, for misc-const-correctness. Co-Authored-By: Claude Opus 5.5 --- code/mission/missionparse.cpp | 6 +++--- qtfred/src/mission/management.cpp | 3 --- qtfred/src/mission/management.h | 4 ---- qtfred/src/ui/FredView.cpp | 3 ++- 4 files changed, 5 insertions(+), 11 deletions(-) diff --git a/code/mission/missionparse.cpp b/code/mission/missionparse.cpp index b34397b42e7..24ccf240bb7 100644 --- a/code/mission/missionparse.cpp +++ b/code/mission/missionparse.cpp @@ -8972,9 +8972,6 @@ int add_path_restriction() return index; } -/** - * Look for \, \, etc. - */ bool arrival_location_uses_distance(ArrivalLocation location) { switch (location) { @@ -8993,6 +8990,9 @@ bool arrival_location_uses_distance(ArrivalLocation location) return false; } +/** + * Look for \, \, etc. + */ anchor_t get_special_anchor(const char *name) { char tmp[NAME_LENGTH + 15]; diff --git a/qtfred/src/mission/management.cpp b/qtfred/src/mission/management.cpp index 321a35dbab8..00b12cb6692 100644 --- a/qtfred/src/mission/management.cpp +++ b/qtfred/src/mission/management.cpp @@ -326,8 +326,5 @@ void shutdown() { } -mission_load_error::mission_load_error(const char* msg) : std::runtime_error{ msg } { -} - } } diff --git a/qtfred/src/mission/management.h b/qtfred/src/mission/management.h index 088c07a3e0d..67be1eb4f78 100644 --- a/qtfred/src/mission/management.h +++ b/qtfred/src/mission/management.h @@ -91,10 +91,6 @@ bool initialize(const std::string& cfilepath, void shutdown(); -struct mission_load_error: public std::runtime_error { - mission_load_error(const char* msg); -}; - } } diff --git a/qtfred/src/ui/FredView.cpp b/qtfred/src/ui/FredView.cpp index 7f246ab64f4..f110019228c 100644 --- a/qtfred/src/ui/FredView.cpp +++ b/qtfred/src/ui/FredView.cpp @@ -906,7 +906,7 @@ void FredView::updateRecentFileList() { ui->menuRe_cent_Files->setEnabled(!recentFiles.empty()); // Now add the individual files as actions - for (auto& path : recentFiles) { + for (const auto& path : recentFiles) { auto action = new QAction(path, ui->menuRe_cent_Files); connect(action, &QAction::triggered, this, &FredView::recentFileOpened); @@ -2276,6 +2276,7 @@ void FredView::closeEvent(QCloseEvent* event) { // If the user keeps the changes, they go into the mission, and the mission prompt then includes them. // A cancel in a window stops the exit. A window that closed before the cancel stays closed, because // the user already answered its prompt, and its model is not usable again after apply() or reject(). + // A cancel at the mission prompt also stops the exit. The windows that closed before it also stay closed. for (auto* window : editorWindows()) { if (window->isVisible() && !window->close()) { event->ignore(); From f6ac060e69e700f4305d630d0b803657ac10a5a1 Mon Sep 17 00:00:00 2001 From: the-e Date: Tue, 17 Nov 2026 18:57:20 +0100 Subject: [PATCH 21/26] Editors: report a failed rename at the end of a mission save The mission save ignored the result of the last rename. On Windows with backups off, rename() does not replace a file that exists, so the save did not change the mission file. Delete the old file first on Windows, and return an error if the rename fails. Co-Authored-By: Claude Opus 5.5 --- code/missioneditor/missionsave.cpp | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/code/missioneditor/missionsave.cpp b/code/missioneditor/missionsave.cpp index 41e3ef0b2ae..6353cb433ff 100644 --- a/code/missioneditor/missionsave.cpp +++ b/code/missioneditor/missionsave.cpp @@ -2454,10 +2454,21 @@ int Fred_mission_save::save_mission_file(const char* pathname) cf_attrib(pathname, 0, FILE_ATTRIBUTE_READONLY, CF_TYPE_MISSIONS); #endif cf_delete(backup_name, CF_TYPE_MISSIONS); + // This rename fails if the mission file does not exist yet. That is correct for a new file. cf_rename(pathname, backup_name, CF_TYPE_MISSIONS); - cf_rename(savepath, pathname, CF_TYPE_MISSIONS); - } else { - cf_rename(savepath, pathname, CF_TYPE_MISSIONS); + } +#ifdef _WIN32 + else { + // rename() on Windows does not replace a file that exists. Delete the old mission file first. + cf_attrib(pathname, 0, FILE_ATTRIBUTE_READONLY, CF_TYPE_MISSIONS); + cf_delete(pathname, CF_TYPE_MISSIONS); + } +#endif + + // If the rename fails, the new content is only in the temporary file. Report an error. + if (cf_rename(savepath, pathname, CF_TYPE_MISSIONS) != CF_RENAME_SUCCESS) { + mprintf(("Could not rename '%s' to '%s'. The mission is not saved.\n", savepath, pathname)); + err = -19; } } From 881ca587cdcaf21023200a09ac0d4d3b7ceb2529 Mon Sep 17 00:00:00 2001 From: the-e Date: Tue, 17 Nov 2026 18:57:20 +0100 Subject: [PATCH 22/26] QtFRED: stop the autosave timer after Revert and Discard The timer could write the discarded changes again while a dialog stayed open. The next load starts the timer again. A plain Save now deletes the autosave one time only. The untitled autosave is deleted when another mission loads. A recovered autosave now uses the absolute mission path, the same as a normal load. Co-Authored-By: Claude Opus 5.5 --- qtfred/src/mission/Editor.cpp | 32 +++++++++++++++++--------------- qtfred/src/ui/FredView.cpp | 21 ++++++++++++++++----- 2 files changed, 33 insertions(+), 20 deletions(-) diff --git a/qtfred/src/mission/Editor.cpp b/qtfred/src/mission/Editor.cpp index 17f33faa5da..2d23f8385ed 100644 --- a/qtfred/src/mission/Editor.cpp +++ b/qtfred/src/mission/Editor.cpp @@ -223,24 +223,24 @@ bool Editor::loadMission(const std::string& mission_name, int flags, bool offerA if (QString::fromStdString(mission_name).endsWith(".fst", Qt::CaseInsensitive)) flags |= MPF_IS_TEMPLATE; + // Find the mission file in the CFile system. If it is a "real" file (not in a VP), use its absolute path. + // Then the "recent mission" menu has correct file names, Save writes to that file, and the autosave + // path is the same for each name of the file. + std::string missionPath = mission_name; + auto res = cf_find_file_location(missionPath.c_str(), CF_TYPE_MISSIONS); + if (res.found && res.offset == 0) + missionPath = res.full_name; + // A template is not a mission file that the user edits, so it has no autosave. QString autosavePath; if (offerAutosaveRecovery && !(flags & MPF_IS_TEMPLATE)) - autosavePath = askToUseNewerAutosave(QString::fromStdString(mission_name)); + autosavePath = askToUseNewerAutosave(QString::fromStdString(missionPath)); const bool recovered = !autosavePath.isEmpty(); clearMission(flags & MPF_FAST_RELOAD); - std::string filepath = recovered ? autosavePath.toStdString() : mission_name; - auto res = cf_find_file_location(filepath.c_str(), CF_TYPE_MISSIONS); - if (res.found) { - // We found this file in the CFile system - if (res.offset == 0) { - // This is a "real" file. Since we now have an absolute path we can use that to make sure we only deal with - // absolute paths which makes sure that the "recent mission" menu has correct file names - filepath = res.full_name; - } - } + // The autosave path is already absolute. + const std::string filepath = recovered ? autosavePath.toStdString() : missionPath; // message 1: required version if (!parse_main(filepath.c_str(), flags)) { @@ -440,12 +440,14 @@ bool Editor::loadMission(const std::string& mission_name, int flags, bool offerA // The path that Save writes to. A template and an FS1 import have no such file: the user must give a // name with Save As. An autosave belongs to the mission file that it came from. - if (recovered) - setCurrentMissionPath(QString::fromStdString(mission_name)); - else if (flags & (MPF_IS_TEMPLATE | MPF_IMPORT_FSM)) + // An untitled mission has no recovery offer, so its autosave is not necessary after the user leaves it. + if (_currentMissionPath.isEmpty()) + removeAutosave({}); + + if (flags & (MPF_IS_TEMPLATE | MPF_IMPORT_FSM)) setCurrentMissionPath({}); else - setCurrentMissionPath(QString::fromStdString(filepath)); + setCurrentMissionPath(QString::fromStdString(missionPath)); missionLoaded(_currentMissionPath.toStdString(), recovered); diff --git a/qtfred/src/ui/FredView.cpp b/qtfred/src/ui/FredView.cpp index f110019228c..dad186ad913 100644 --- a/qtfred/src/ui/FredView.cpp +++ b/qtfred/src/ui/FredView.cpp @@ -498,7 +498,8 @@ bool FredView::writeMissionFile(const QString& path) { // The file now contains the changes, so the autosave is not necessary. For Save As, also delete the // autosave of the old path (or of the untitled mission). fred->removeAutosave(path); - fred->removeAutosave(fred->currentMissionPath()); + if (fred->currentMissionPath() != path) + fred->removeAutosave(fred->currentMissionPath()); return true; } @@ -661,7 +662,9 @@ void FredView::on_actionRevert_triggered(bool) { return; // Clear modified flag so loadMissionFile doesn't prompt to save again _missionModified = false; - // Revert discards the changes. Delete the autosave, because it can contain those changes. + // Revert discards the changes. Delete the autosave, because it can contain those changes. Stop the timer, + // so that it does not write the changes again while the recovery question is open. The load starts it again. + fred->stopAutosaveTimer(); fred->removeAutosave(path); loadMissionFile(path, 0, false); } @@ -690,8 +693,11 @@ void FredView::on_actionFS1_Mission_triggered(bool) { fso::fred::util::getLastDir("missions/importFS1Source", QDir::homePath()), tr("FreeSpace Missions (*.fsm)")); - if (srcPaths.isEmpty()) + // A discard at the prompt stopped the autosave timer. If the user cancels here, the mission stays open. + if (srcPaths.isEmpty()) { + restartAutosaveTimer(); return; + } fso::fred::util::saveLastDir("missions/importFS1Source", srcPaths.first()); @@ -699,8 +705,10 @@ void FredView::on_actionFS1_Mission_triggered(bool) { tr("Select destination folder for converted missions"), fso::fred::util::getLastDir("missions/importFS1Dest", CF_TYPE_MISSIONS)); - if (destDir.isEmpty()) + if (destDir.isEmpty()) { + restartAutosaveTimer(); return; + } fso::fred::util::saveLastDir("missions/importFS1Dest", destDir); @@ -1716,7 +1724,10 @@ bool FredView::maybePromptToSaveMissionChanges(const QString& actionDescription) case QMessageBox::Save: return saveMissionToCurrentPath(); case QMessageBox::Discard: - // The user discards the changes, so the next load must not offer them from the autosave. + // The user discards the changes, so the next load must not offer them from the autosave. Stop the + // timer, so that it does not write the changes again while a file dialog or a question is open. The + // next load or new mission starts it again. A caller that stops after a discard must start it again. + fred->stopAutosaveTimer(); fred->removeAutosave(fred->currentMissionPath()); return true; case QMessageBox::Cancel: From 92e33fd17e121fea9646b6bc4124017cc4c9407c Mon Sep 17 00:00:00 2001 From: the-e Date: Tue, 17 Nov 2026 18:57:20 +0100 Subject: [PATCH 23/26] Editors: apply the arrival distance notes from the third review - QtFRED ship editor: the distance field shows "-" when the marked ships have different distances, and its maximum is no longer 99. - QtFRED wing editor: with no targets, the distance gets the minimum. - FRED2 wing editor: the minimum check also runs with no target. - FRED2 ship editor: one warning after all the ships, and only when bypass_errors is not set. - Correct the comment of MIN_TARGET_ARRIVAL_DISTANCE. It is the largest minimum, not a lower limit. Co-Authored-By: Claude Opus 5.5 --- code/mission/missionparse.h | 2 +- code/missioneditor/common.cpp | 2 ++ fred2/shipeditordlg.cpp | 18 ++++++++----- fred2/shipeditordlg.h | 2 ++ fred2/wing_editor.cpp | 26 +++++++++---------- .../ShipEditor/ShipEditorDialogModel.cpp | 24 +++++++++++++++-- .../ShipEditor/ShipEditorDialogModel.h | 3 +++ .../mission/dialogs/WingEditorDialogModel.cpp | 5 ++-- .../dialogs/ShipEditor/ShipEditorDialog.cpp | 10 +++++-- qtfred/ui/ShipEditorDialog.ui | 10 ++++++- 10 files changed, 75 insertions(+), 27 deletions(-) diff --git a/code/mission/missionparse.h b/code/mission/missionparse.h index 9751c9386cf..75ec37c7140 100644 --- a/code/mission/missionparse.h +++ b/code/mission/missionparse.h @@ -44,7 +44,7 @@ enum class DepartureLocation; #define DEFAULT_AMBIENT_LIGHT_LEVEL 0x00787878 #define MIN_TARGET_ARRIVAL_DISTANCE 500.0f // float because that's how FRED does the math -#define MIN_TARGET_ARRIVAL_MULTIPLIER 2.0f // minimum distance is 2 * target radius, but at least 500 +#define MIN_TARGET_ARRIVAL_MULTIPLIER 2.0f // minimum distance is 2 * target radius, but not more than MIN_TARGET_ARRIVAL_DISTANCE anchor_t get_special_anchor(const char *name); void check_anchor_for_hangar_bay(SCP_string &message, SCP_set &anchors_checked, anchor_t anchor, const char *other_name, bool other_is_ship, bool is_arrival); diff --git a/code/missioneditor/common.cpp b/code/missioneditor/common.cpp index 2a7f35958e9..16b442718da 100644 --- a/code/missioneditor/common.cpp +++ b/code/missioneditor/common.cpp @@ -128,6 +128,8 @@ int arrival_min_distance(ArrivalLocation location, anchor_t anchor) if (shipnum < 0 || shipnum >= MAX_SHIPS || Ships[shipnum].objnum < 0) return 1; + // The minimum is 2 * the target radius, but not more than MIN_TARGET_ARRIVAL_DISTANCE. Thus that constant + // is the largest minimum, not a lower limit. A large target does not need an arrival distance above it. const float radius_distance = std::round(MIN_TARGET_ARRIVAL_MULTIPLIER * Objects[Ships[shipnum].objnum].radius); return std::max(1, static_cast(std::min(MIN_TARGET_ARRIVAL_DISTANCE, radius_distance))); } diff --git a/fred2/shipeditordlg.cpp b/fred2/shipeditordlg.cpp index be9887df183..d195c3e0e2b 100644 --- a/fred2/shipeditordlg.cpp +++ b/fred2/shipeditordlg.cpp @@ -1077,6 +1077,7 @@ int CShipEditorDlg::update_data(int redraw) UpdateData(TRUE); UpdateData(TRUE); Wing_editor_dialog.update_data_safe(); + largest_arrival_raise = 0; if (multi_edit) { // editing multiple ships (ships and/or players) ptr = GET_FIRST(&obj_used_list); while (ptr != END_OF_LIST(&obj_used_list)) { @@ -1145,6 +1146,15 @@ int CShipEditorDlg::update_data(int redraw) } } + // One warning for all the ships, the same as the wing editor and QtFRED. A minimum of 1 only prevents an + // invalid distance, so it needs no warning. + if (!bypass_errors && (largest_arrival_raise > 1)) { + CString str; + str.Format("Ship must arrive at least %d meters away from target.\n" + "Value has been reset to this. Use with caution!\r\n", largest_arrival_raise); + MessageBox(str); + } + ensure_valid_player_start_shipnum(); // may need a new single player start if (modified) @@ -1291,12 +1301,8 @@ int CShipEditorDlg::update_ship(int ship) // different locations and targets, so use the values of this ship. d = arrival_min_distance(Ships[ship].arrival_location, Ships[ship].arrival_anchor); if (Ships[ship].arrival_distance < d) { - // A minimum of 1 only prevents an invalid distance, so it needs no warning. - if (d > 1) { - str.Format("Ship must arrive at least %d meters away from target.\n" - "Value has been reset to this. Use with caution!\r\n", d); - MessageBox(str); - } + // update_data() shows the warning after it updates all the ships. + largest_arrival_raise = std::max(largest_arrival_raise, d); Ships[ship].arrival_distance = d; // In multi-edit mode, save() copies the field to each marked ship. The field must not get the diff --git a/fred2/shipeditordlg.h b/fred2/shipeditordlg.h index a86db751eb3..0350a38f6b1 100644 --- a/fred2/shipeditordlg.h +++ b/fred2/shipeditordlg.h @@ -44,6 +44,8 @@ class CShipEditorDlg : public CDialog private: int make_ship_list(int *arr); int update_ship(int ship); + // The largest arrival distance that update_ship() raised a ship to. update_data() shows one warning for it. + int largest_arrival_raise = 0; int initialized; int multi_edit; int always_on_top; diff --git a/fred2/wing_editor.cpp b/fred2/wing_editor.cpp index 8d936364c20..d9361fa5f2c 100644 --- a/fred2/wing_editor.cpp +++ b/fred2/wing_editor.cpp @@ -728,22 +728,22 @@ void wing_editor::update_data_safe() if (m_arrival_target >= 0) { i = (int)((CComboBox *) GetDlgItem(IDC_ARRIVAL_TARGET))->GetItemData(m_arrival_target); MODIFY(Wings[cur_wing].arrival_anchor, target_to_anchor(i)); + } - // Force the arrival distance to be at least the minimum for the arrival location and target. - // This is the same rule as the ship editor and QtFRED. - d = arrival_min_distance(Wings[cur_wing].arrival_location, Wings[cur_wing].arrival_anchor); - if (Wings[cur_wing].arrival_distance < d) { - // A minimum of 1 only prevents an invalid distance, so it needs no warning. - if (!bypass_errors && (d > 1)) { - sprintf(buf, "Ship must arrive at least %d meters away from target.\n" - "Value has been reset to this. Use with caution!\r\n", d); - - MessageBox(buf); - } + // Force the arrival distance to be at least the minimum for the arrival location and target. + // This is the same rule as the ship editor and QtFRED. A wing with no target also gets the minimum. + d = arrival_min_distance(Wings[cur_wing].arrival_location, Wings[cur_wing].arrival_anchor); + if (Wings[cur_wing].arrival_distance < d) { + // A minimum of 1 only prevents an invalid distance, so it needs no warning. + if (!bypass_errors && (d > 1)) { + sprintf(buf, "Ship must arrive at least %d meters away from target.\n" + "Value has been reset to this. Use with caution!\r\n", d); - Wings[cur_wing].arrival_distance = d; - m_arrival_dist = Wings[cur_wing].arrival_distance; + MessageBox(buf); } + + Wings[cur_wing].arrival_distance = d; + m_arrival_dist = Wings[cur_wing].arrival_distance; } if (m_departure_target >= 0) { i = (int)((CComboBox *) GetDlgItem(IDC_DEPARTURE_TARGET))->GetItemData(m_departure_target); diff --git a/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.cpp b/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.cpp index 855b1548f2d..6d898737836 100644 --- a/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.cpp +++ b/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.cpp @@ -289,6 +289,7 @@ void ShipEditorDialogModel::initializeData() _arrivalTreeFormula = _departureTreeFormula = -1; _arrivalLocation = -1; _arrivalDist = -1; + _arrivalDistMixed = false; _arrivalTarget = -1; _arrivalDelay = -1; _departureLocation = -1; @@ -372,6 +373,9 @@ void ShipEditorDialogModel::initializeData() _departureLocation = -1; } + if (Ships[i].arrival_distance != _arrivalDist) { + _arrivalDistMixed = true; + } _arrivalDist = Ships[i].arrival_distance; _arrivalDelay = Ships[i].arrival_delay; _departureDelay = Ships[i].departure_delay; @@ -548,6 +552,7 @@ void ShipEditorDialogModel::initializeData() _arrivalDelay = 0; _departureDelay = 0; _arrivalDist = 0; + _arrivalDistMixed = false; _arrivalTarget = -1; _departureTarget = -1; _noArrivalWarp = false; @@ -1198,6 +1203,7 @@ bool ShipEditorDialogModel::arrivalNeedsDistance() const void ShipEditorDialogModel::writeArrivalDistance(int value) { _arrivalDist = value; + _arrivalDistMixed = false; for (auto* ptr = GET_FIRST(&obj_used_list); ptr != END_OF_LIST(&obj_used_list); ptr = GET_NEXT(ptr)) { if (((ptr->type == OBJ_SHIP) || (ptr->type == OBJ_START)) && (ptr->flags[Object::Object_Flags::Marked])) { if (Ships[ptr->instance].wingnum < 0) { @@ -1212,6 +1218,7 @@ void ShipEditorDialogModel::enforceArrivalMinDist() // The marked ships can have different arrival locations and targets, so use the values of each ship. // The same rule as the wing editor and FRED2: the radius of the target ship sets the minimum. int largest_raise = 0; + bool first = true; for (auto* ptr = GET_FIRST(&obj_used_list); ptr != END_OF_LIST(&obj_used_list); ptr = GET_NEXT(ptr)) { if (((ptr->type == OBJ_SHIP) || (ptr->type == OBJ_START)) && (ptr->flags[Object::Object_Flags::Marked])) { auto& shipp = Ships[ptr->instance]; @@ -1223,7 +1230,14 @@ void ShipEditorDialogModel::enforceArrivalMinDist() shipp.arrival_distance = min_dist; largest_raise = std::max(largest_raise, min_dist); } - // The dialog shows the distance of the last marked ship, the same as initializeData(). + // The ships can now have different distances. Then the dialog shows the mixed state, the same as + // initializeData(), and a value that the user enters goes to each ship. + if (first) { + _arrivalDistMixed = false; + first = false; + } else if (shipp.arrival_distance != _arrivalDist) { + _arrivalDistMixed = true; + } _arrivalDist = shipp.arrival_distance; } } @@ -1267,7 +1281,8 @@ int ShipEditorDialogModel::getArrivalTarget() const void ShipEditorDialogModel::setArrivalDistance(const int value) { - if (_arrivalDist == value) + // In the mixed state, the same value as _arrivalDist is a change for the other ships. + if (!_arrivalDistMixed && _arrivalDist == value) return; writeArrivalDistance(value); @@ -1282,6 +1297,11 @@ int ShipEditorDialogModel::getArrivalDistance() const return _arrivalDist; } +bool ShipEditorDialogModel::getArrivalDistanceMixed() const +{ + return _arrivalDistMixed; +} + void ShipEditorDialogModel::setArrivalDelay(const int value) { if (_arrivalDelay == value) diff --git a/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.h b/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.h index b9eaf007dd7..5597a07a8ea 100644 --- a/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.h +++ b/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.h @@ -79,6 +79,8 @@ class ShipEditorDialogModel : public AbstractDialogModel { void setArrivalDistance(int distance); int getArrivalDistance() const; + // True if the marked ships have different arrival distances. Then getArrivalDistance() is not a real value. + bool getArrivalDistanceMixed() const; void setArrivalDelay(int delay); int getArrivalDelay() const; @@ -199,6 +201,7 @@ class ShipEditorDialogModel : public AbstractDialogModel { int _score; int _assistScore; int _arrivalDist; + bool _arrivalDistMixed = false; int _arrivalTarget; int _departureTarget; int _persona; diff --git a/qtfred/src/mission/dialogs/WingEditorDialogModel.cpp b/qtfred/src/mission/dialogs/WingEditorDialogModel.cpp index a2b985dafd1..ed85a0bf1e1 100644 --- a/qtfred/src/mission/dialogs/WingEditorDialogModel.cpp +++ b/qtfred/src/mission/dialogs/WingEditorDialogModel.cpp @@ -827,9 +827,10 @@ void WingEditorDialogModel::setArrivalType(ArrivalLocation newArrivalType) const auto& targets = getArrivalTargetList(); if (targets.empty()) { - // No targets available, set to -1 + // No targets available, set to -1. The distance gets the minimum without a target, the same as the + // ship editor. modify(w->arrival_anchor, anchor_t::invalid()); - modify(w->arrival_distance, 0); + modify(w->arrival_distance, getMinArrivalDistance()); return; } diff --git a/qtfred/src/ui/dialogs/ShipEditor/ShipEditorDialog.cpp b/qtfred/src/ui/dialogs/ShipEditor/ShipEditorDialog.cpp index 0f649313f4c..0c20571492d 100644 --- a/qtfred/src/ui/dialogs/ShipEditor/ShipEditorDialog.cpp +++ b/qtfred/src/ui/dialogs/ShipEditor/ShipEditorDialog.cpp @@ -333,8 +333,11 @@ void ShipEditorDialog::updateUi() } ui->arrivalLocationCombo->setCurrentIndex(ui->arrivalLocationCombo->findData(arrivalLocation)); - ui->arrivalDistanceEdit->clear(); - ui->arrivalDistanceEdit->setValue(_model->getArrivalDistance()); + if (_model->getArrivalDistanceMixed()) { + ui->arrivalDistanceEdit->setMixed(); + } else { + ui->arrivalDistanceEdit->setSingleValue(_model->getArrivalDistance()); + } ui->arrivalDelaySpinBox->setValue(_model->getArrivalDelay()); ui->updateArrivalCueCheckBox->setChecked(_model->getArrivalCue()); @@ -844,6 +847,9 @@ void ShipEditorDialog::on_arrivalTargetCombo_currentIndexChanged(int index) } void ShipEditorDialog::on_arrivalDistanceEdit_valueChanged(int value) { + // "-" is not a real value. Each ship keeps its own distance. + if (ui->arrivalDistanceEdit->isBlank()) + return; _model->setArrivalDistance(value); } void ShipEditorDialog::on_arrivalDelaySpinBox_valueChanged(int value) diff --git a/qtfred/ui/ShipEditorDialog.ui b/qtfred/ui/ShipEditorDialog.ui index a3257997355..ae5cc608b75 100644 --- a/qtfred/ui/ShipEditorDialog.ui +++ b/qtfred/ui/ShipEditorDialog.ui @@ -610,13 +610,16 @@ - + <html><head/><body><p>Distance from target</p></body></html> QAbstractSpinBox::NoButtons + + 16777215 + @@ -940,6 +943,11 @@
+ + fso::fred::MixedValueSpinBox + QSpinBox +
ui/widgets/MixedValueSpinBox.h
+
fso::fred::ShipFlagCheckbox QCheckBox From 32d51e31e275293aa99c64268315c287b11607b7 Mon Sep 17 00:00:00 2001 From: the-e Date: Tue, 17 Nov 2026 18:57:20 +0100 Subject: [PATCH 24/26] Tests: add a rounding case and add the Lua AI handler one time A radius of 100.2 tells round from ceil. ai_lua_init() adds a handler to the global Script_system, so call it only one time. Co-Authored-By: Claude Opus 5.5 --- test/src/ai/test_ailua.cpp | 8 +++++++- test/src/missioneditor/test_editor_rules.cpp | 4 ++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/test/src/ai/test_ailua.cpp b/test/src/ai/test_ailua.cpp index c05e2b6655b..45c16b0cf64 100644 --- a/test/src/ai/test_ailua.cpp +++ b/test/src/ai/test_ailua.cpp @@ -17,7 +17,13 @@ class AiLuaGoalTest : public test::FSTestFixture { void SetUp() override { test::FSTestFixture::SetUp(); - ai_lua_init(); + // ai_lua_init() adds a handler to the global Script_system, and nothing removes it. Add it only one + // time, so that more tests or --gtest_repeat do not add more handlers. + static bool lua_ai_initialized = false; + if (!lua_ai_initialized) { + ai_lua_init(); + lua_ai_initialized = true; + } Script_system.CreateLuaState(); } diff --git a/test/src/missioneditor/test_editor_rules.cpp b/test/src/missioneditor/test_editor_rules.cpp index b38e4c5037b..c489b1f6295 100644 --- a/test/src/missioneditor/test_editor_rules.cpp +++ b/test/src/missioneditor/test_editor_rules.cpp @@ -112,6 +112,10 @@ TEST_F(ArrivalMinDistanceTest, twice_the_target_radius) { // The value is rounded, not truncated. Objects[OBJNUM].radius = 100.3f; EXPECT_EQ(arrival_min_distance(ArrivalLocation::ABOVE_SHIP, targetAnchor()), 201); + + // The value is rounded down when the fraction is small. The ceiling gives 201. + Objects[OBJNUM].radius = 100.2f; + EXPECT_EQ(arrival_min_distance(ArrivalLocation::ABOVE_SHIP, targetAnchor()), 200); } TEST_F(ArrivalMinDistanceTest, limit_of_500) { From f81ec0e212e131937cb089b8b78b83f71a3b5c48 Mon Sep 17 00:00:00 2001 From: the-e Date: Wed, 18 Nov 2026 17:09:55 +0100 Subject: [PATCH 25/26] QtFRED: refresh the ship editor distance field after a change The distance field got its value only when the dialog opened or the marking changed. When a target or location change raised a ship to its minimum, or left the marked ships with different distances, the field kept the old number. The saved values were correct. The dialog now refreshes the distance field after each model change. It changes the field only when the field shows a different value. The field also sends its value only on Enter or focus loss. Before, each key press sent a value, so the minimum check could raise a part of a typed number. Co-Authored-By: Claude Opus 5.5 --- .../dialogs/ShipEditor/ShipEditorDialog.cpp | 25 ++++++++++++++----- .../ui/dialogs/ShipEditor/ShipEditorDialog.h | 1 + qtfred/ui/ShipEditorDialog.ui | 3 +++ 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/qtfred/src/ui/dialogs/ShipEditor/ShipEditorDialog.cpp b/qtfred/src/ui/dialogs/ShipEditor/ShipEditorDialog.cpp index 0c20571492d..e3fabda4737 100644 --- a/qtfred/src/ui/dialogs/ShipEditor/ShipEditorDialog.cpp +++ b/qtfred/src/ui/dialogs/ShipEditor/ShipEditorDialog.cpp @@ -15,6 +15,7 @@ #include #include #include +#include namespace fso::fred::dialogs { @@ -54,7 +55,11 @@ ShipEditorDialog::ShipEditorDialog(FredView* parent, EditorViewport* viewport) initializeUi(); updateUi(); - connect(_model.get(), &AbstractDialogModel::modelChanged, this, [this] { initializeUi(); }); + connect(_model.get(), &AbstractDialogModel::modelChanged, this, [this] { + initializeUi(); + // The model can raise the distances to the minimum, or the marked ships can now have different distances. + updateArrivalDistanceField(); + }); connect(_model.get(), &ShipEditorDialogModel::shipMarkingChanged, this, [this] { initializeUi(); updateUi(); @@ -333,11 +338,7 @@ void ShipEditorDialog::updateUi() } ui->arrivalLocationCombo->setCurrentIndex(ui->arrivalLocationCombo->findData(arrivalLocation)); - if (_model->getArrivalDistanceMixed()) { - ui->arrivalDistanceEdit->setMixed(); - } else { - ui->arrivalDistanceEdit->setSingleValue(_model->getArrivalDistance()); - } + updateArrivalDistanceField(); ui->arrivalDelaySpinBox->setValue(_model->getArrivalDelay()); ui->updateArrivalCueCheckBox->setChecked(_model->getArrivalCue()); @@ -845,6 +846,18 @@ void ShipEditorDialog::on_arrivalTargetCombo_currentIndexChanged(int index) auto arrivalLocationIdx = ui->arrivalTargetCombo->itemData(index).toInt(); _model->setArrivalTarget(arrivalLocationIdx); } +// Shows the arrival distance of the model. If the field already shows that value, the field does not change. +void ShipEditorDialog::updateArrivalDistanceField() +{ + QSignalBlocker blocker(ui->arrivalDistanceEdit); + auto* field = ui->arrivalDistanceEdit; + if (_model->getArrivalDistanceMixed()) { + if (!field->isBlank()) + field->setMixed(); + } else if (field->isBlank() || field->value() != _model->getArrivalDistance()) { + field->setSingleValue(_model->getArrivalDistance()); + } +} void ShipEditorDialog::on_arrivalDistanceEdit_valueChanged(int value) { // "-" is not a real value. Each ship keeps its own distance. diff --git a/qtfred/src/ui/dialogs/ShipEditor/ShipEditorDialog.h b/qtfred/src/ui/dialogs/ShipEditor/ShipEditorDialog.h index ada6a90e992..885b453c789 100644 --- a/qtfred/src/ui/dialogs/ShipEditor/ShipEditorDialog.h +++ b/qtfred/src/ui/dialogs/ShipEditor/ShipEditorDialog.h @@ -102,6 +102,7 @@ class ShipEditorDialog : public QDialog, public SexpTreeEditorInterface { void initializeUi(); void updateUi(); + void updateArrivalDistanceField(); void enableDisable(); // column one diff --git a/qtfred/ui/ShipEditorDialog.ui b/qtfred/ui/ShipEditorDialog.ui index ae5cc608b75..6eab329c665 100644 --- a/qtfred/ui/ShipEditorDialog.ui +++ b/qtfred/ui/ShipEditorDialog.ui @@ -617,6 +617,9 @@ QAbstractSpinBox::NoButtons + + false + 16777215 From 179b098ee9eea0f5e67a1e9c317eee576d9421d9 Mon Sep 17 00:00:00 2001 From: the-e Date: Wed, 18 Nov 2026 17:09:55 +0100 Subject: [PATCH 26/26] Editors: replace the mission file in one step on save On Windows with backups off, the save deleted the old mission file and then renamed the temporary file. If that rename failed, the mission file was missing until the next save. cf_rename() has a new replace_existing parameter. On Windows it uses MoveFileExA() with MOVEFILE_REPLACE_EXISTING. POSIX rename() already replaces a file. The mission save uses it, so a failed rename keeps the old mission file. Co-Authored-By: Claude Opus 5.5 --- code/cfile/cfile.cpp | 16 +++++++++++++++- code/cfile/cfile.h | 4 +++- code/missioneditor/missionsave.cpp | 8 ++++---- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/code/cfile/cfile.cpp b/code/cfile/cfile.cpp index 6fac45be3c0..038e2c91f12 100644 --- a/code/cfile/cfile.cpp +++ b/code/cfile/cfile.cpp @@ -544,7 +544,7 @@ void cf_attrib(const char *filename, int set, int clear, int dir_type) } #endif -int cf_rename(const char *old_name, const char *name, int dir_type) +int cf_rename(const char *old_name, const char *name, int dir_type, bool replace_existing) { Assert( CF_TYPE_SPECIFIED(dir_type) ); @@ -555,6 +555,20 @@ int cf_rename(const char *old_name, const char *name, int dir_type) cf_create_default_path_string(old_longname, dir_type, old_name); cf_create_default_path_string(new_longname, dir_type, name); +#ifdef _WIN32 + if (replace_existing) { + if (MoveFileExA(old_longname.c_str(), new_longname.c_str(), MOVEFILE_REPLACE_EXISTING)) { + return CF_RENAME_SUCCESS; + } + const auto error = GetLastError(); + return (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) ? CF_RENAME_FAIL_EXIST + : CF_RENAME_FAIL_ACCESS; + } +#else + // POSIX rename() always replaces a file that exists. + SCP_UNUSED(replace_existing); +#endif + ret_code = rename(old_longname.c_str(), new_longname.c_str()); if(ret_code != 0){ switch(errno){ diff --git a/code/cfile/cfile.h b/code/cfile/cfile.h index f5e99d8960b..6ef9e5d9c8f 100644 --- a/code/cfile/cfile.h +++ b/code/cfile/cfile.h @@ -288,7 +288,9 @@ uint cf_add_chksum_long(uint seed, ubyte *buffer, size_t size); #define CF_RENAME_SUCCESS 0 // successfully renamed the file #define CF_RENAME_FAIL_ACCESS 1 // new name could not be created #define CF_RENAME_FAIL_EXIST 2 // old name does not exist -int cf_rename(const char *old_name, const char *name, int type = CF_TYPE_ANY ); +// If replace_existing is true and the new name already exists, the rename replaces that file in one step. Without +// it, rename() on Windows fails when the new name exists, but POSIX rename() replaces the file. +int cf_rename(const char *old_name, const char *name, int type = CF_TYPE_ANY, bool replace_existing = false); // Creates the directory path if it doesn't exist. Even creates all its // parent paths. diff --git a/code/missioneditor/missionsave.cpp b/code/missioneditor/missionsave.cpp index 6353cb433ff..8c0ff9d77d7 100644 --- a/code/missioneditor/missionsave.cpp +++ b/code/missioneditor/missionsave.cpp @@ -2459,14 +2459,14 @@ int Fred_mission_save::save_mission_file(const char* pathname) } #ifdef _WIN32 else { - // rename() on Windows does not replace a file that exists. Delete the old mission file first. + // A replace fails on a read-only file. cf_attrib(pathname, 0, FILE_ATTRIBUTE_READONLY, CF_TYPE_MISSIONS); - cf_delete(pathname, CF_TYPE_MISSIONS); } #endif - // If the rename fails, the new content is only in the temporary file. Report an error. - if (cf_rename(savepath, pathname, CF_TYPE_MISSIONS) != CF_RENAME_SUCCESS) { + // Replace the old mission file in one step. If the rename fails, the old file stays and the new content is + // only in the temporary file. Report an error. + if (cf_rename(savepath, pathname, CF_TYPE_MISSIONS, true) != CF_RENAME_SUCCESS) { mprintf(("Could not rename '%s' to '%s'. The mission is not saved.\n", savepath, pathname)); err = -19; }