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); 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/mission/missionparse.cpp b/code/mission/missionparse.cpp index 848af7bc8e0..24ccf240bb7 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; @@ -8980,6 +8972,24 @@ int add_path_restriction() return index; } +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; +} + /** * Look for \, \, etc. */ diff --git a/code/mission/missionparse.h b/code/mission/missionparse.h index aa3236cc49f..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); @@ -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 8642c9a941a..16b442718da 100644 --- a/code/missioneditor/common.cpp +++ b/code/missioneditor/common.cpp @@ -17,10 +17,16 @@ #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" #include +#include // to keep track of data char Voice_abbrev_briefing[NAME_LENGTH]; @@ -110,6 +116,42 @@ 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; + + // 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))); +} + +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) { + 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; + } +} + void update_custom_wing_indexes() { int i; @@ -355,7 +397,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(); @@ -373,6 +417,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 @@ -385,6 +434,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 698f4d88b68..8984adb2a82 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,17 @@ 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; +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(); @@ -73,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/code/missioneditor/missionsave.cpp b/code/missioneditor/missionsave.cpp index 41e3ef0b2ae..8c0ff9d77d7 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 { + // A replace fails on a read-only file. + cf_attrib(pathname, 0, FILE_ATTRIBUTE_READONLY, CF_TYPE_MISSIONS); + } +#endif + + // 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; } } diff --git a/fred2/fredview.cpp b/fred2/fredview.cpp index 15b7f251aff..a1c08e23647 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; @@ -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/fred2/shipeditordlg.cpp b/fred2/shipeditordlg.cpp index 6c70de2ea8b..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) @@ -1284,26 +1294,23 @@ 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)); + } - // 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)) { - 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) ); - - 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); - } - } + // 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) { + // 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 + // 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/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 21f1005f30a..d9361fa5f2c 100644 --- a/fred2/wing_editor.cpp +++ b/fred2/wing_editor.cpp @@ -728,27 +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)); + } - // 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; + // 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); - 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/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/mission/Editor.cpp b/qtfred/src/mission/Editor.cpp index aa6b37a05be..2d23f8385ed 100644 --- a/qtfred/src/mission/Editor.cpp +++ b/qtfred/src/mission/Editor.cpp @@ -39,7 +39,9 @@ #include "ui/QtGraphicsOperations.h" #include +#include #include +#include #include #include @@ -148,22 +150,37 @@ 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(); +} + +void Editor::removeAutosave(const QString& missionPath) const +{ + QFile::remove(autosavePathFor(missionPath)); +} + +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 +188,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) { @@ -187,20 +203,14 @@ void Editor::stopAutosaveTimer() { } void Editor::setCurrentMissionPath(const QString& path) { - _currentMissionPath = path; + _currentMissionPath = QDir::toNativeSeparators(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; @@ -208,18 +218,29 @@ 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; + + // 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(missionPath)); + const bool recovered = !autosavePath.isEmpty(); + clearMission(flags & MPF_FAST_RELOAD); - std::string filepath = 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)) { @@ -417,7 +438,18 @@ bool Editor::loadMission(const std::string& mission_name, int flags) { stars_post_level_init(); - missionLoaded(filepath); + // 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. + // 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(missionPath)); + + 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 @@ -830,7 +862,8 @@ void Editor::createNewMission() { create_player(&vmd_zero_vector, &vmd_identity_matrix); stars_post_level_init(); // TODO(Phase 3): _undoStack->clear() - missionLoaded(""); + setCurrentMissionPath({}); + missionLoaded("", false); } void Editor::hideMarkedObjects() { object* ptr; diff --git a/qtfred/src/mission/Editor.h b/qtfred/src/mission/Editor.h index be5c65ca992..4ebecb161cc 100644 --- a/qtfred/src/mission/Editor.h +++ b/qtfred/src/mission/Editor.h @@ -67,15 +67,40 @@ 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; + + /** + * @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(); + /** + * @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. */ - bool loadMission(const std::string& filepath, int flags = 0); + /** + * @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 offerAutosaveRecovery = false); void markObject(int objId); void unmarkObject(int objId); @@ -140,7 +165,11 @@ 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 */ - void missionLoaded(const std::string& filepath); + /** + * @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, bool hasUnsavedContent); /** * @brief A signal emitted when the mission has changed somehow @@ -266,6 +295,12 @@ class Editor : public QObject { 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); + QTimer* _autosaveTimer = nullptr; QString _autosaveDirectory; QString _currentMissionPath; diff --git a/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.cpp b/qtfred/src/mission/dialogs/ShipEditor/ShipEditorDialogModel.cpp index a0765e8ff5d..6d898737836 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) @@ -287,6 +289,7 @@ void ShipEditorDialogModel::initializeData() _arrivalTreeFormula = _departureTreeFormula = -1; _arrivalLocation = -1; _arrivalDist = -1; + _arrivalDistMixed = false; _arrivalTarget = -1; _arrivalDelay = -1; _departureLocation = -1; @@ -370,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; @@ -546,6 +552,7 @@ void ShipEditorDialogModel::initializeData() _arrivalDelay = 0; _departureDelay = 0; _arrivalDist = 0; + _arrivalDistMixed = false; _arrivalTarget = -1; _departureTarget = -1; _noArrivalWarp = false; @@ -1161,6 +1168,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 +1197,66 @@ 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 +void ShipEditorDialogModel::writeArrivalDistance(int value) { - // 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; - - // Compute the most restrictive minimum distance across all marked arriving ships - int max_d = 0; + _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] && - 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) - return; - _arrivalTarget = value; + // 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]; + 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 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; + } + } - // 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 (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)); - _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; - } - } + .arg(largest_raise)); } +} + +void ShipEditorDialogModel::setArrivalTarget(const int value) +{ + if (_arrivalTarget == value) + return; + _arrivalTarget = 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])) { @@ -1257,6 +1265,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(); @@ -1269,28 +1281,12 @@ 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; - 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(); @@ -1301,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 b69ab2034d1..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; @@ -166,7 +168,11 @@ 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); + // 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; int _noArrivalWarp; @@ -195,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/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; diff --git a/qtfred/src/mission/dialogs/WingEditorDialogModel.cpp b/qtfred/src/mission/dialogs/WingEditorDialogModel.cpp index 38ab3537d58..ed85a0bf1e1 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 @@ -866,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; } @@ -1007,10 +969,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); @@ -1035,9 +997,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/mission/management.cpp b/qtfred/src/mission/management.cpp index d54b69b51a5..00b12cb6692 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(); @@ -333,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 a17fef0d342..dad186ad913 100644 --- a/qtfred/src/ui/FredView.cpp +++ b/qtfred/src/ui/FredView.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -20,6 +21,8 @@ #include #include +#include +#include #include #include @@ -280,19 +283,16 @@ 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 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; - 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; }); // Sets the initial window title - on_mission_loaded(""); + on_mission_loaded("", false); syncViewOptions(); @@ -317,7 +317,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); @@ -360,30 +360,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(); } } @@ -479,15 +471,7 @@ bool FredView::performPreSaveCheck(int* outFixCount) { } } -bool FredView::saveMissionToCurrentPath() { - if (saveName.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); @@ -495,11 +479,31 @@ 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(saveName.replace('/', DIR_SEPARATOR_CHAR).toUtf8().constData()); _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); + if (fred->currentMissionPath() != path) + fred->removeAutosave(fred->currentMissionPath()); + 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)); @@ -510,7 +514,23 @@ 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; + + // Start the interval again. Thus the next autosave comes one full interval after the save. + restartAutosaveTimer(); + reportPreSaveFixes(fixCount); return true; } @@ -522,38 +542,22 @@ 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); - - 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(saveName.replace('/', DIR_SEPARATOR_CHAR).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.")); + fso::fred::util::saveLastDir("missions/saveMission", newSaveName); + newSaveName.replace('/', DIR_SEPARATOR_CHAR); - // 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; - fred->setCurrentMissionPath(saveName); - restartAutosaveTimer(); + reportPreSaveFixes(fixCount); + fred->setCurrentMissionPath(newSaveName); + showCurrentMissionFile(); + addToRecentFiles(newSaveName); return true; } @@ -644,7 +648,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; } @@ -656,7 +662,11 @@ void FredView::on_actionRevert_triggered(bool) { return; // Clear modified flag so loadMissionFile doesn't prompt to save again _missionModified = false; - loadMissionFile(saveName); + // 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); } void FredView::on_actionFS2_Open_triggered(bool) { @@ -683,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()); @@ -692,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); @@ -722,13 +737,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; @@ -809,7 +818,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(); @@ -825,34 +834,13 @@ 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, a template, and an FS1 import. + showCurrentMissionFile(); + 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.")); @@ -861,6 +849,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(); } @@ -904,22 +905,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 (const 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); } } @@ -1725,6 +1724,11 @@ 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. 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: default: @@ -2260,6 +2264,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()); @@ -2268,6 +2283,18 @@ 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(). + // 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(); + return; + } + } + if (!maybePromptToSaveMissionChanges(tr("closing QtFRED"))) { event->ignore(); return; @@ -2275,6 +2302,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(); } @@ -2910,34 +2941,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 +2971,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; @@ -2971,7 +2994,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(); diff --git a/qtfred/src/ui/FredView.h b/qtfred/src/ui/FredView.h index 6f738721ed1..07963fe4750 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); @@ -230,6 +234,14 @@ 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; + // 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(); @@ -283,7 +295,6 @@ class FredView: public QMainWindow, public IDialogProvider { QAction* _controlModeCamera = nullptr; QAction* _controlModeCurrentShip = nullptr; - QString saveName = nullptr; MissionFormat _missionSaveFormat = MissionFormat::STANDARD; std::unique_ptr ui; 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() { diff --git a/qtfred/src/ui/dialogs/ReinforcementsEditorDialog.cpp b/qtfred/src/ui/dialogs/ReinforcementsEditorDialog.cpp index 5493ac3c8e5..b550e1833ba 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); } } @@ -218,13 +204,9 @@ 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) { - if (val < 0) { - val = 0; - - util::SignalBlockers blockers(this); - ui->useSpinBox->setValue(val); - } + // "-" 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); } } @@ -232,13 +214,9 @@ 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) { - if (val < 0) { - val = 0; - - util::SignalBlockers blockers(this); - ui->delaySpinBox->setValue(val); - } + // "-" 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/ShipEditorDialog.cpp b/qtfred/src/ui/dialogs/ShipEditor/ShipEditorDialog.cpp index 0f649313f4c..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,8 +338,7 @@ void ShipEditorDialog::updateUi() } ui->arrivalLocationCombo->setCurrentIndex(ui->arrivalLocationCombo->findData(arrivalLocation)); - ui->arrivalDistanceEdit->clear(); - ui->arrivalDistanceEdit->setValue(_model->getArrivalDistance()); + updateArrivalDistanceField(); ui->arrivalDelaySpinBox->setValue(_model->getArrivalDelay()); ui->updateArrivalCueCheckBox->setChecked(_model->getArrivalCue()); @@ -842,8 +846,23 @@ 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. + if (ui->arrivalDistanceEdit->isBlank()) + return; _model->setArrivalDistance(value); } void ShipEditorDialog::on_arrivalDelaySpinBox_valueChanged(int value) 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/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.cpp b/qtfred/src/ui/dialogs/ShipEditor/ShipInitialStatusDialog.cpp index 1d28b170af9..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,41 +174,38 @@ 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) { _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); - } else { - ui->velocitySpinBox->setSpecialValueText("-"); - } - value = _model->getHull(); - if (value != BLANKFIELD) { - ui->hullSpinBox->setValue(value); + if (value == BLANKFIELD) { + spinBox->setMixed(); } else { - ui->hullSpinBox->setSpecialValueText("-"); + spinBox->setSingleValue(value); } - 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..03c5a24fcfb 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(); + static void setSpinBoxValueOrBlank(MixedValueSpinBox* spinBox, int value); void updateFlags(); void updateDocks(); void updateDockee(); 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); } diff --git a/qtfred/src/ui/widgets/MixedValueSpinBox.cpp b/qtfred/src/ui/widgets/MixedValueSpinBox.cpp new file mode 100644 index 00000000000..60eaffb1c32 --- /dev/null +++ b/qtfred/src/ui/widgets/MixedValueSpinBox.cpp @@ -0,0 +1,63 @@ +#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); +} + +bool MixedValueSpinBox::isBlank() const +{ + return _mixed && value() == minimum(); +} + +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 = isBlank(); + leaveMixedState(); + if (!wasBlank) + QSpinBox::stepBy(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; +} + +} // 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..2f2d7ae9ad7 --- /dev/null +++ b/qtfred/src/ui/widgets/MixedValueSpinBox.h @@ -0,0 +1,42 @@ +#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); + + // 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: + 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/ShipEditorDialog.ui b/qtfred/ui/ShipEditorDialog.ui index a3257997355..6eab329c665 100644 --- a/qtfred/ui/ShipEditorDialog.ui +++ b/qtfred/ui/ShipEditorDialog.ui @@ -610,13 +610,19 @@ - + <html><head/><body><p>Distance from target</p></body></html> QAbstractSpinBox::NoButtons + + false + + + 16777215 + @@ -940,6 +946,11 @@ + + fso::fred::MixedValueSpinBox + QSpinBox +
ui/widgets/MixedValueSpinBox.h
+
fso::fred::ShipFlagCheckbox QCheckBox 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 diff --git a/test/src/ai/test_ailua.cpp b/test/src/ai/test_ailua.cpp new file mode 100644 index 00000000000..45c16b0cf64 --- /dev/null +++ b/test/src/ai/test_ailua.cpp @@ -0,0 +1,56 @@ +#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() 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(); + } + + 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..c489b1f6295 --- /dev/null +++ b/test/src/missioneditor/test_editor_rules.cpp @@ -0,0 +1,134 @@ +#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); + + // 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) { + 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"