Files
fs2open.github.com/code/osapi/dialogs.cpp
T
1fa6e00f39 Controls 4 and 5 - Multi-joy and Preset Files (#2958)
* Updates the AxisInverted hooks to use the new CC_bind.  Currently assumes only Joy0, so this may need further tweaking or replacement

* * Add ability to claim up to 4 joysticks for player use, using the launcher (via registry or fs2_open.ini) or the new menu system
* Hack into existing control polling system to get the new primary/secondary binding schema to work.  This should be reworked into a reverse-lookup system.
* Finally break the mouse loose from overlapping with Joystick binidngs
* Fix bug where joy button wouldn't register on search function
* Fix bug with mousewheel not always decaying as it should.
* Fix rebase conflict with selecting item during search mode

* Fix bug where mouse buttons were incorrectly labeled.

* Move some enums around

* Fix bug with joy axis labels being displayed as buttons.
* Fix possible bug where Other conflict axis wouldn't clear
* Updated default joystick axis text. A new strings.tbl will need to be supplied for localization support

* Deprecate nAxisInverted ADE functions and replace with AxisInverted(int, int, bool)

* Merge Axis mappings into Control_config
* More utility functions for CC_bind and CCB
* Adds another ADE function for inverting the axis action, instead of individual bindings
* Hacks to get plr file to compile.  Currently slices out many of the new features like secondary axis and the mouse axis, and the additional joystick bindings (joy1, joy2, joy3)

* Fix bug with uncontrollable spin (slopily)
* Fix some warnings
* Add flags for Hats and Balls for future implementation

* Fix bug where inverting an axis would trigger an assert

* Fix bug where joy wasn't detected as present

* Most axis actions should be relative, instead of absolute
* Hopefully optimize joy_get_unscaled_reading
* Properly break out of double-for search function for search and bind modes in config menu
* Refactor control_get_axes_readings to provide more consistent behavior
* Use JOY_REL_THROTTLE instead of Action::REL_THROTTLE when indexing into Control_config

* Bank axis has a default binding, Throttle does not.

* Fix bug where conflicts weren't being detected.
Fix bug where default presets weren't being detectd

* Elegantly break out of double fors with goto.
Fix bug with bind mode not detecting axis

* Save new binding scheme to playerfile
* Add cid_assign() to standardize cid assignment with shorts
* Add write and read handlers for int8_t

* Remove saving controls to csg.  This will be replaced by presets.

* Fix bug with reading pilotfile

* Use "Joy-n" instead of "joystick n" to match default identifiers in config menu

* Fix bug with CC_TYPE_TRIGGER controls always marked as used, if not bound with a key.
Fix bug with Joy-0 btn 1 triggering multiple controls that are not bound to it.

* Improve readibility of the joy info output to log
* Message when a joystick connects and using legacy system.
* Fix bug where system joystick 0 was mapped in pJoystick that should've been nullptr

* Fix bug where *not* having a joystick will cause bind mode in the config menu to immediately cancel.

* Add reverse lookup functions for actions.  mActionToVal[] does string -> int, mValToAction() does int -> string

* Add the foundation for writing the presets files.
* Adds a bunch of reverse lookup functions to get the stringified version of various enums, etc.
* presets.h and presets.cpp are in something of a barebones at this point

* Add new subdir for preset files 'player/presets'
* add utility for finding the distance of a bitfield/bitmask.  Used to translate mouse button masks into mouse button id's
* Write PresetFileHandler as standalone, instead of a subclass.  Still mostly a copy of JSONFileHandler
* Make functions to map and reverse-map the bindings for use with the preset files and ultimately the ControlConfigDefaults.tbl as well

* Check presets from file to see if they are duplicate with an existing preset.

* Check for uniqueness of presets fron controlconfigdefaults.tbl before adding them, and warn the user if there are duplicates.

* Rename the test functions into proper load/save.
* save function has some standard checks
* load function is called on init
* make finding duplicates its own function outside of the preset label rendering function
* Initial draft of saving presets in-game

* Fix bug where all loaded presets were thought to be duplicate of defaults.

* Fix bug where preset cycling would get stuck on the first preset other than default

* Fix bug where saving a mouse button saves the wrong textified string.

* Prevent preset names from being too long.
* Crash still occurs if the name is too long, as if set outside of FSO
* Workaround text running off the popups in 640x480.  Doesn't look as nice, sadly

* CSG's now track preset names instead of containing bindings
* remake control_config_reset_defaults() into control_config_use_preset()
* provide a function to get the currently selected preset.

* Do PLR backward compatibility, hopefully.

* PLR now tracks presets instead of saving the bindings.

* On Loading pre PLR3 or CSG6 data, create a new preset.

* Strip off file extension before saving preset files. Jason.json.json just looks dumb

* Add "-joy_info" commandline option.  Will output SDL joystick info of all detected joysticks to stdout

* Fix non-standard behavior with registry_read_string().
* Returning NULL instead of the default value, or an empty string, will trigger an access violation with SCP_string and other string copy functions.

* Modify io::joystick::init() to take an optional param, no_register, to use with -joy_info

* Address CI complaints

* Address CI issues 2.

* Supress preset duplicate warning if in unit tests.

* Address scripting unittest failure due to incorrect argument type. (Ints don't technically exist in LUA)

* Use Mouse enums instead of Joy enums or magic numbers

* More signed/unsigned madness

* Address CI issues 3

* Address gcc-5 issues. (No auto in lambdas)
* Fix bug with bit_distance()

* Address gcc-5 issues 2

* Address clang issues

* Address clang-tidy issues

* Address clang-tidy issues in undosys.  May need to be cherry picked to Controls2.

* Address clang-tidy issues

* Improve logic of preset name prompt.

* Fix bug with selected presets not being saved

* No, a cstr is not a std::string.
* Can't use i there because its already defined.

* Fix bug where CSG's wouldn't save selected preset
* Fix bug where presets wouldn't be loaded correctly from player files
* Fix bug where loaded preset files would not update the preset cycle position correctly

* Some QoL changes for the preset name prompt

* Address Appveyor issues.

* Add forward compatibility for player file.  This is required because currently any "missing" data in the pilotfile will trigger an Error, and crash FSO.

* Fix bug where mouse X axis was unusable.
Apparently stating that MOUSE_Z_AXIS IS MOUSE_Z_AXIS doesn't get the point across.

* Address CI issues.

* Address CI issues.
* sel default assigned to -1
* static_cast enum to an int

* Assimilate -joy_info int -get_flags, replacing the existing method that launchers use to get joystick information.

* Add '\n' to PST log messages.

* Change logic of checking joystick .ini keys:  Should the multi-joy key not be found, try legacy joy key.

* Add some more missing '\n' to mprintf messages.

* Notify the player when converting to the new multi-joy system. (Using ReleaseWarning for now...)
* Warn the player if a preset defined in their .PLR could not be found.

* Actually disable control items without a valid tab, instead of relying on the fact that they're disabled  by default.

* Add CC_preset::is_duplicate_of() method to make checking for preset uniqueness less of a brain teaser.
* Doxy the first_override param of control_config_common_read_section

* Adds the os::dialogs::Information() method, which displays an information-only dialog in similar format to Warning and Error dialogs.  Does not throw Warning nor Error exceptions
* load_player now uses os::dialogs::Information() instead of ::ReleaseWarning, thus not halting unit tests.

* Breaks retail localization support for Joystick and Mice labels - This is because the new multi-joy axis end up very confusing "Joy-0 Joystick/Mouse X Axis"
* Renames Joy_axis_text to Axis_text, intended to be used both by joysticks and the mouse.
* Moves mouse axis and button labels into an array to ease future XSTR support
* Adds asserts to ensure indices are within the array sizes of label arrays
* Adds XSTR indices for Axis labels, mouse buttons, and mouse wheels.

* Seperates conflict check comparisons from equality comparisons.
*  Conflict checks can ignore certain combinations of CC_bind::flag's; i.e. an Axis bound to a different control but is inverted or relative will still cause a conflict with another control that has the same axis
*  Equality comparisons is exact equality, allowing presets to check if binds have the same binding and flag configurations.

* More UI string changes and localization
* Tweaks positioning of top button labels in CC menu
* Adds the following XSTR's:
1659 "Preset: %s"
1660 "Preset: custom"
1661 "Next Preset"

* Fix bug where mouse axis turned into mouse button when inverting control by its control name.
* Fix bug with the new conflict checking subroutine not working with non-axis controls

* Address CI issues.

* Don't trigger modal popups while in unit tests.

* Address clang tidy issues
* use nullptr
* be consistent with conditional style
* use booleans to stuff debug states, methods with just Assertions in it will trigger a false positive on clang tidy
* use string::empty() instead of checking for "".

* Remove dead code of -joy_info.  Functionality has been merged with -get_flags

* Address clang-tidy [readability-simplify-boolean-expr]
--z64 says "I don't like it!"

* fix axis check

* Implement revised axis action virtvars for scripting. Also protect against a control mismatch in the CSG file due to a script-inverted control

* Encapsulate CC_bind properly
* Add mouse and joystick cid's to AxisInverted description

* Update translate_key() and its user to correctly translate multijoy bindings for training messages.

* Prompt user trying to escape from config menu when they have changes.
* Remove dead function.

* Fix crash during training missions due to key translation that would overflow internal buffer.
* Went back with cstring as return value instead of SCP string, because caller would need a significant refactor
* Update doxy of the textify functions

* Unify textify_scancode() and textify_scancode_universal() to ensure common code path.

* Add "Multijoy" entry to json caps. (For Knossos)

* Make CI happy.
* Remove unused lambda captures.

* Instead of overwrite during plr2 => plr3 conversion, try to use the existing preset file.

* Fix conditional for checking if file exists within presets::save_preset_file()

* Revert Majority of PR#3739
* PLR and CSG versions are incremented past versions set by 3739
* Forward compatibility feature of #3739 (Only save sexp containers into the CSG if they are used) is removed

* Remove forward compatibilty of PLR file when going in between pre- and post-Controls5 FSO versions
* Add missing startSection() and endSection() for csg_write_controls()

* Fix clang-tidy error #1

* Fix clang-tidy error #2

* fix clandy tidy error #1 part 2/2

* Fix clang tidy error 3

Co-authored-by: Goober5000 <[email protected]>
Co-authored-by: Tyler Blount <[email protected]>
Co-authored-by: wookieejedi <[email protected]>
Co-authored-by: BMagnu <[email protected]>
2022-01-04 12:01:32 -06:00

541 lines
13 KiB
C++

#include "osapi/dialogs.h"
#include "osapi/osapi.h"
#include "parse/parselo.h"
#include "cmdline/cmdline.h"
#include "graphics/2d.h"
#include "scripting/ade.h"
#include <SDL_messagebox.h>
#include <SDL_clipboard.h>
#include <string>
#include <algorithm>
extern "C" {
#include <lauxlib.h>
#include <lualib.h>
}
namespace
{
const char* Separator = "------------------------------------------------------------------\n";
const int Messagebox_lines = 30;
template<typename Stream>
void LuaDebugPrint(Stream& stream, lua_Debug &ar)
{
if (ar.name == nullptr)
{
// Invalid lua_Debug struct
return;
}
stream << "Name:\t\t" << ar.name << "\n";
stream << "Name of:\t" << ar.namewhat << "\n";
stream << "Function type:\t" << ar.what << "\n";
stream << "Defined on:\t" << ar.linedefined << "\n";
stream << "Upvalues:\t" << ar.nups << "\n";
stream << "\n";
stream << "Source:\t\t" << ar.source << "\n";
stream << "Short source:\t" << ar.short_src << "\n";
stream << "Current line:\t" << ar.currentline << "\n";
stream << "- Function line:\t" << (ar.linedefined ? (1 + ar.currentline - ar.linedefined) : 0) << "\n";
}
SCP_string truncateLines(SCP_stringstream& s, int maxLines)
{
SCP_stringstream outStream;
s.seekp(0, std::ios::beg);
for (SCP_string line; std::getline(s, line);)
{
outStream << line << "\n";
--maxLines;
if (maxLines <= 0)
{
outStream << "[...]";
break;
}
}
return outStream.str();
}
const char* clean_filename(const char* filename)
{
auto separator = strrchr(filename, DIR_SEPARATOR_CHAR);
if (separator != nullptr)
{
filename = separator + 1;
}
return filename;
}
void set_clipboard_text(const char* text)
{
// Make sure video is enabled
if (!SDL_InitSubSystem(SDL_INIT_VIDEO))
{
SDL_SetClipboardText(text);
}
}
}
int Global_warning_count = 0;
int Global_error_count = 0;
namespace os
{
namespace dialogs
{
//This function is a helper function to determine if the dialogs should have a parent window
//Normally, this should always be FSO's window, but there is an issue with this in fullscreen
//where occasionally (when knossos is on the same screen as FSO in a multi-monitor setup on
//windows) this results in the dialog losing focus, unable to regain it, thus rendering the
//buttons not clickable. So as a hotfix, the dialog has no blocking parent in that case and
//is instead rendered as it's own window
SDL_Window* getDialogParent() {
return !(Cmdline_fullscreen_window || Cmdline_window) ? NULL : os::getSDLMainWindow();
}
void AssertMessage(const char * text, const char * filename, int linenum, const char * format, ...)
{
// We only want to display the file name
filename = clean_filename(filename);
SCP_stringstream msgStream;
msgStream << "Assert: \"" << text << "\"\n";
msgStream << "File: " << filename << "\n";
msgStream << "Line: " << linenum << "\n";
if (format != nullptr)
{
SCP_string buffer;
va_list args;
va_start(args, format);
vsprintf(buffer, format, args);
va_end(args);
msgStream << buffer << "\n";
mprintf(("ASSERTION: \"%s\" at %s:%d\n %s\n", text, filename, linenum, buffer.c_str()));
}
else
{
// No additional message
mprintf(("ASSERTION: \"%s\" at %s:%d\n", text, filename, linenum));
}
if (running_unittests) {
throw AssertException(msgStream.str());
}
msgStream << "\n";
msgStream << dump_stacktrace();
SCP_string messageText = msgStream.str();
set_clipboard_text(messageText.c_str());
messageText = truncateLines(msgStream, Messagebox_lines);
messageText += "\n[ This info is in the clipboard so you can paste it somewhere now ]\n";
messageText += "\n\nUse Debug to break into Debugger, Exit will close the application.\n";
Error(messageText.c_str());
}
void LuaError(lua_State * L, const char * format, ...)
{
SCP_stringstream msgStream;
//WMC - if format is set to NULL, assume this is acting as an
//error handler for Lua.
if (format == NULL)
{
msgStream << "LUA ERROR: " << lua_tostring(L, -1);
lua_pop(L, -1);
}
else
{
SCP_string formatText;
va_list args;
va_start(args, format);
vsprintf(formatText, format, args);
va_end(args);
msgStream << formatText;
}
msgStream << "\n";
msgStream << "\n";
msgStream << Separator;
// Get the stack via the debug.traceback() function
lua_getglobal(L, LUA_DBLIBNAME);
if (!lua_isnil(L, -1))
{
msgStream << "\n";
lua_getfield(L, -1, "traceback");
lua_remove(L, -2);
if (lua_pcall(L, 0, 1, 0) != 0)
msgStream << "Error while retrieving stack: " << lua_tostring(L, -1);
else
msgStream << lua_tostring(L, -1);
lua_pop(L, 1);
}
msgStream << "\n";
msgStream << Separator;
char stackText[1024];
stackText[0] = '\0';
scripting::ade_stackdump(L, stackText);
msgStream << stackText;
msgStream << "\n";
msgStream << Separator;
mprintf(("Lua Error: %s\n", msgStream.str().c_str()));
if (Cmdline_noninteractive) {
abort();
return;
}
if (running_unittests) {
throw LuaErrorException(msgStream.str());
}
set_clipboard_text(msgStream.str().c_str());
// truncate text
auto truncatedText = truncateLines(msgStream, Messagebox_lines);
SCP_stringstream boxTextStream;
boxTextStream << truncatedText << "\n";
boxTextStream << "\n[ This info is in the clipboard so you can paste it somewhere now ]\n";
auto boxText = boxTextStream.str();
const SDL_MessageBoxButtonData buttons[] = {
{ SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, 2, "Exit" },
{ SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, 1, "Continue" },
{ /* .flags, .buttonid, .text */ 0, 0, "Debug" },
};
SDL_MessageBoxData boxData;
memset(&boxData, 0, sizeof(boxData));
boxData.buttons = buttons;
boxData.numbuttons = 3;
boxData.colorScheme = nullptr;
boxData.flags = SDL_MESSAGEBOX_ERROR;
boxData.message = boxText.c_str();
boxData.title = "Error!";
boxData.window = getDialogParent();
gr_activate(0);
int buttonId;
if (SDL_ShowMessageBox(&boxData, &buttonId) < 0)
{
// Call failed
buttonId = 1; // No action
}
switch (buttonId)
{
case 2:
abort();
case 0:
Int3();
break;
default:
break;
}
gr_activate(1);
}
void Error(const char * filename, int line, const char * format, ...)
{
SCP_string formatText;
filename = clean_filename(filename);
va_list args;
va_start(args, format);
vsprintf(formatText, format, args);
va_end(args);
SCP_stringstream messageStream;
messageStream << "Error: " << formatText << "\n";
messageStream << "File: " << filename << "\n";
messageStream << "Line: " << line << "\n";
Error(messageStream.str().c_str());
}
void Error(const char* text)
{
mprintf(("\n%s\n", text));
if (Cmdline_noninteractive) {
abort();
return;
}
if (running_unittests) {
throw ErrorException(text);
}
SCP_stringstream messageStream;
messageStream << text << "\n";
messageStream << dump_stacktrace();
SCP_string fullText = messageStream.str();
set_clipboard_text(fullText.c_str());
fullText = truncateLines(messageStream, Messagebox_lines);
fullText += "\n[ This info is in the clipboard so you can paste it somewhere now ]\n";
fullText += "\n\nUse Debug to break into Debugger, Exit will close the application.\n";
const SDL_MessageBoxButtonData buttons[] = {
{ SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, 1, "Exit" },
{ /* .flags, .buttonid, .text */ 0, 0, "Debug" },
};
SDL_MessageBoxData boxData;
memset(&boxData, 0, sizeof(boxData));
boxData.buttons = buttons;
boxData.numbuttons = 2;
boxData.colorScheme = nullptr;
boxData.flags = SDL_MESSAGEBOX_ERROR;
boxData.message = text;
boxData.title = "Error!";
boxData.window = getDialogParent();
gr_activate(0);
int buttonId;
if (SDL_ShowMessageBox(&boxData, &buttonId) < 0)
{
// Call failed
abort();
}
switch (buttonId)
{
case 1:
abort();
default:
Int3();
break;
}
gr_activate(1);
}
// Actual implementation of the warning function. Used by the various warning functions
void WarningImpl(const char* filename, int line, const SCP_string& text)
{
filename = clean_filename(filename);
// output to the debug log before anything else (so that we have a complete record)
mprintf(("WARNING: \"%s\" at %s:%d\n", text.c_str(), filename, line));
// now go for the additional popup window, if we want it ...
if (Cmdline_noninteractive) {
return;
}
if (running_unittests) {
throw WarningException(text);
}
SCP_stringstream boxMsgStream;
boxMsgStream << "Warning: " << text << "\n";
boxMsgStream << "File: " << filename << "\n";
boxMsgStream << "Line: " << line << "\n";
set_clipboard_text(boxMsgStream.str().c_str());
boxMsgStream << "\n";
SCP_string boxMessage = truncateLines(boxMsgStream, Messagebox_lines);
boxMessage += "\n[ This info is in the clipboard so you can paste it somewhere now ]\n";
boxMessage += "\n\nUse Debug to break into Debugger\n";
const SDL_MessageBoxButtonData buttons[] = {
{ SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, 2, "Exit" },
{ SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, 1, "Continue" },
{ /* .flags, .buttonid, .text */ 0, 0, "Debug" },
};
SDL_MessageBoxData boxData;
memset(&boxData, 0, sizeof(boxData));
boxData.buttons = buttons;
boxData.numbuttons = 3;
boxData.colorScheme = nullptr;
boxData.flags = SDL_MESSAGEBOX_WARNING;
boxData.message = boxMessage.c_str();
boxData.title = "Warning!";
boxData.window = getDialogParent();
gr_activate(0);
int buttonId;
if (SDL_ShowMessageBox(&boxData, &buttonId) < 0)
{
// Call failed
buttonId = 1; // No action
}
switch (buttonId)
{
case 2:
abort();
case 0:
Int3();
break;
default:
break;
}
gr_activate(1);
}
void ReleaseWarning(const char* filename, int line, const char* format, ...) {
Global_warning_count++;
SCP_string msg;
va_list args;
va_start(args, format);
vsprintf(msg, format, args);
va_end(args);
WarningImpl(filename, line, msg);
}
void Warning(const char* filename, int line, const char* format, ...)
{
Global_warning_count++;
#ifndef NDEBUG
SCP_string msg;
va_list args;
va_start(args, format);
vsprintf(msg, format, args);
va_end(args);
WarningImpl(filename, line, msg);
#endif
}
void WarningEx(const char* filename, int line, const char* format, ...)
{
#ifndef NDEBUG
if (Cmdline_extra_warn) {
SCP_string msg;
va_list args;
va_start(args, format);
vsprintf(msg, format, args);
va_end(args);
Warning(filename, line, "%s", msg.c_str());
}
#endif
}
void Information(const char* filename, int line, const char* format, ...) {
SCP_string msg;
va_list args;
va_start(args, format);
vsprintf(msg, format, args);
va_end(args);
// Below is essentially a stripped down copy pasta of WarningImpl
filename = clean_filename(filename);
// output to the debug log before anything else (so that we have a complete record)
mprintf(("INFO: \"%s\" at %s:%d\n", msg.c_str(), filename, line));
// now go for the additional popup window, if we want it ...
if (Cmdline_noninteractive || running_unittests) {
return;
}
SCP_stringstream boxMsgStream;
boxMsgStream << "Information: " << msg << "\n";
boxMsgStream << "File: " << filename << "\n";
boxMsgStream << "Line: " << line << "\n";
set_clipboard_text(boxMsgStream.str().c_str());
boxMsgStream << "\n";
SCP_string boxMessage = truncateLines(boxMsgStream, Messagebox_lines);
boxMessage += "\n[ This info is in the clipboard so you can paste it somewhere now ]\n";
gr_activate(0);
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Information", boxMessage.c_str(), getDialogParent());
gr_activate(1);
}
void Message(MessageType type, const char* message, const char* title)
{
if (running_unittests) {
throw WarningException(message);
}
int flags = 1;
switch (type)
{
case MESSAGEBOX_ERROR:
flags = SDL_MESSAGEBOX_ERROR;
if (title == NULL)
title = "Error";
break;
case MESSAGEBOX_INFORMATION:
flags = SDL_MESSAGEBOX_INFORMATION;
if (title == NULL)
title = "Information";
break;
case MESSAGEBOX_WARNING:
flags = SDL_MESSAGEBOX_WARNING;
if (title == NULL)
title = "Warning";
break;
default:
Int3();
title = ""; // Remove warning about unitialized variable
break;
}
SDL_ShowSimpleMessageBox(flags, title, message, getDialogParent());
}
}
}