Initial commit

This commit is contained in:
2026-02-02 04:50:13 +01:00
commit 5b11698731
22592 changed files with 7677434 additions and 0 deletions

2365
base/commandLine.cpp Normal file

File diff suppressed because it is too large Load Diff

59
base/commandLine.h Normal file
View File

@@ -0,0 +1,59 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef COMMON_COMMAND_LINE_H
#define COMMON_COMMAND_LINE_H
#include "common/hash-str.h"
namespace Common {
class Error;
class String;
}
namespace Base {
/**
* Register various defaults with the ConfigManager.
*/
void registerDefaults();
/**
* Parse the command line for options and a command; the options
* are stored in the map 'settings, the command (if any) is returned.
*/
Common::String parseCommandLine(Common::StringMap &settings, int argc, const char * const *argv);
/**
* Process the command line options and arguments.
* Returns true if everything was handled and ScummVM should quit
* (e.g. because "--help" was specified, and handled).
*
* @param[in] command the command as returned by parseCommandLine
* @param[in] settings the settings as returned by parseCommandLine
* @param[out] err indicates whether any error occurred, and which
* @return true if the command was completely processed and ScummVM should quit, false otherwise
*/
bool processSettings(Common::String &command, Common::StringMap &settings, Common::Error &err);
} // End of namespace Base
#endif

View File

@@ -0,0 +1,55 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef DETECTION_STATIC
#include "base/plugins.h"
#include "base/detection/detection.h"
#include "engines/metaengine.h"
#include "engines/advancedDetector.h"
class DetectionDynamic : public Detection {
public:
DetectionDynamic() {}
~DetectionDynamic() {}
const char *getName() const override {
return "detection";
}
PluginList getPlugins() const override {
PluginList pl;
#define LINK_PLUGIN(ID) \
extern const PluginType g_##ID##_type; \
extern PluginObject *g_##ID##_getObject(); \
pl.push_back(new StaticPlugin(g_##ID##_getObject(), g_##ID##_type));
#include "engines/detection_table.h"
return pl;
}
};
REGISTER_PLUGIN_DYNAMIC(DETECTION_DYNAMIC, PLUGIN_TYPE_DETECTION, DetectionDynamic);
#endif // !DETECTION_STATIC

View File

@@ -0,0 +1,31 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "base/plugins.h"
class Detection : public PluginObject {
public:
Detection() {}
virtual ~Detection() {}
virtual const char *getName() const = 0;
virtual PluginList getPlugins() const = 0;
};

15
base/detection/module.mk Normal file
View File

@@ -0,0 +1,15 @@
MODULE := base/detection
DETECT_OBJS_DYNAMIC=$(addprefix ../../,$(DETECT_OBJS))
MODULE_OBJS := \
detection.o \
$(DETECT_OBJS_DYNAMIC)
# Reset detect objects, so none of them build into the executable.
DETECT_OBJS :=
PLUGIN := 1
# Include common rules
include $(srcdir)/rules.mk

21
base/internal_plugins.h Normal file
View File

@@ -0,0 +1,21 @@
#if !defined(INCLUDED_FROM_BASE_PLUGINS_H) && !defined(RC_INVOKED)
#error This file may only be included by base/plugins.h or dists/scummvm.rc
#endif
// plugin macros are defined in this simple internal header so that scummvm.rc
// can include them without causing problems for Windows resource compilers.
#define STATIC_PLUGIN 1
#define DYNAMIC_PLUGIN 2
#define PLUGIN_ENABLED_STATIC(ID) \
(ENABLE_##ID && !PLUGIN_ENABLED_DYNAMIC(ID))
#ifdef DYNAMIC_MODULES
#define PLUGIN_ENABLED_DYNAMIC(ID) \
(ENABLE_##ID && (ENABLE_##ID == DYNAMIC_PLUGIN))
#else
#define PLUGIN_ENABLED_DYNAMIC(ID) 0
#endif
#define PLUGIN_ENABLED(ID) (ENABLE_##ID)

View File

@@ -0,0 +1,6 @@
#ifndef SCUMMVM_INTERNAL_REVISION_H
#define SCUMMVM_INTERNAL_REVISION_H
#define SCUMMVM_REVISION "@REVISION@"
#endif

23
base/internal_version.h Normal file
View File

@@ -0,0 +1,23 @@
#if !defined(INCLUDED_FROM_BASE_VERSION_CPP) && !defined(RC_INVOKED)
#error This file may only be included by base/version.cpp or dists/scummvm.rc
#endif
// Reads revision number from file
// (this is used when building with Visual Studio)
#ifdef SCUMMVM_INTERNAL_REVISION
#include "internal_revision.h"
#endif
#ifdef RELEASE_BUILD
#undef SCUMMVM_REVISION
#endif
#ifndef SCUMMVM_REVISION
#define SCUMMVM_REVISION
#endif
#define SCUMMVM_VERSION "2026.1.1git"
#define SCUMMVM_VER_MAJOR 2026
#define SCUMMVM_VER_MINOR 1
#define SCUMMVM_VER_PATCH 1

View File

@@ -0,0 +1,23 @@
#if !defined(INCLUDED_FROM_BASE_VERSION_CPP) && !defined(RC_INVOKED)
#error This file may only be included by base/version.cpp or dists/scummvm.rc
#endif
// Reads revision number from file
// (this is used when building with Visual Studio)
#ifdef SCUMMVM_INTERNAL_REVISION
#include "internal_revision.h"
#endif
#ifdef RELEASE_BUILD
#undef SCUMMVM_REVISION
#endif
#ifndef SCUMMVM_REVISION
#define SCUMMVM_REVISION
#endif
#define SCUMMVM_VERSION "@VERSION@"
#define SCUMMVM_VER_MAJOR @VER_MAJOR@
#define SCUMMVM_VER_MINOR @VER_MINOR@
#define SCUMMVM_VER_PATCH @VER_PATCH@

925
base/main.cpp Normal file
View File

@@ -0,0 +1,925 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*! \mainpage %ScummVM Source Reference
*
* These pages contain a cross referenced documentation for the %ScummVM source code,
* generated with Doxygen (https://www.doxygen.nl) directly from the source.
* Currently not much is actually properly documented, but at least you can get an overview
* of almost all the classes, methods and variables, and how they interact.
*/
// FIXME: Avoid using printf
#define FORBIDDEN_SYMBOL_EXCEPTION_printf
#include "engines/engine.h"
#include "engines/metaengine.h"
#include "base/commandLine.h"
#include "base/plugins.h"
#include "base/version.h"
#include "common/archive.h"
#include "common/config-manager.h"
#include "common/debug.h"
#include "common/debug-channels.h" /* for debug manager */
#include "common/events.h"
#include "gui/EventRecorder.h"
#include "common/fs.h"
#ifdef ENABLE_EVENTRECORDER
#include "common/recorderfile.h"
#endif
#include "common/system.h"
#include "common/textconsole.h"
#include "common/tokenizer.h"
#include "common/translation.h"
#include "common/text-to-speech.h"
#include "common/osd_message_queue.h"
#include "gui/gui-manager.h"
#include "gui/error.h"
#include "gui/message.h"
#include "audio/mididrv.h"
#include "audio/musicplugin.h" /* for music manager */
#include "graphics/cursorman.h"
#include "graphics/fontman.h"
#include "graphics/yuv_to_rgb.h"
#ifdef USE_FREETYPE2
#include "graphics/fonts/ttf.h"
#endif
#include "graphics/scalerplugin.h"
#include "backends/keymapper/action.h"
#include "backends/keymapper/keymap.h"
#include "backends/keymapper/keymapper.h"
#ifdef USE_CLOUD
#include "backends/cloud/cloudmanager.h"
#include "backends/networking/http/connectionmanager.h"
#endif
#ifdef USE_SDL_NET
#include "backends/networking/sdl_net/localwebserver.h"
#endif
#if defined(__DC__)
#include "backends/platform/dc/DCLauncherDialog.h"
#else
#include "gui/launcher.h"
#endif
#ifdef USE_UPDATES
#include "gui/updates-dialog.h"
#endif
#ifdef ANDROID_BACKEND
#include "backends/fs/android/android-fs-factory.h"
#endif
#include "gui/dump-all-dialogs.h"
static bool launcherDialog() {
// Discard any command line options. Those that affect the graphics
// mode and the others (like bootparam etc.) should not
// blindly be passed to the first game launched from the launcher.
ConfMan.getDomain(Common::ConfigManager::kTransientDomain)->clear();
// If the backend does not allow quitting, loop on the launcher until a game is started
bool noQuit = g_system->hasFeature(OSystem::kFeatureNoQuit);
bool status = true;
do {
#if defined(__DC__)
DCLauncherDialog dlg;
#else
GUI::LauncherChooser dlg;
dlg.selectLauncher();
#endif
status = (dlg.runModal() != -1);
} while (noQuit && nullptr == ConfMan.getActiveDomain());
return status;
}
static Common::Error identifyGame(const Common::String &debugLevels, const Plugin **detectionPlugin, DetectedGame &game, const void **descriptor) {
assert(detectionPlugin);
// Figure out the engine ID and game ID
Common::String engineId = ConfMan.get("engineid");
Common::String gameId = ConfMan.get("gameid");
// Print text saying what's going on
printf("User picked target '%s' (engine ID '%s', game ID '%s')...\n", ConfMan.getActiveDomainName().c_str(), engineId.c_str(), gameId.c_str());
// At this point the engine ID and game ID must be known
if (engineId.empty()) {
warning("The engine ID is not set for target '%s'", ConfMan.getActiveDomainName().c_str());
return Common::kUnknownError;
}
if (gameId.empty()) {
warning("The game ID is not set for target '%s'", ConfMan.getActiveDomainName().c_str());
return Common::kUnknownError;
}
*detectionPlugin = EngineMan.findDetectionPlugin(engineId);
if (!*detectionPlugin) {
warning("'%s' is an invalid engine ID. Use the --list-engines command to list supported engine IDs", engineId.c_str());
return Common::kMetaEnginePluginNotFound;
}
// Query the plugin for the game descriptor
MetaEngineDetection &metaEngine = (*detectionPlugin)->get<MetaEngineDetection>();
// before doing anything, we register the debug channels of the (Meta)Engine(Detection)
DebugMan.addAllDebugChannels(metaEngine.getDebugChannels());
// Setup now the debug channels
Common::StringTokenizer tokenizer(debugLevels, " ,");
while (!tokenizer.empty()) {
Common::String token = tokenizer.nextToken();
if (token.equalsIgnoreCase("all"))
DebugMan.enableAllDebugChannels();
else if (!DebugMan.enableDebugChannel(token))
warning("Engine does not support debug level '%s'", token.c_str());
}
Common::Error result = metaEngine.identifyGame(game, descriptor);
if (result.getCode() != Common::kNoError) {
warning("Couldn't identify game '%s' for the engine '%s'.", gameId.c_str(), engineId.c_str());
}
return result;
}
void saveLastLaunchedTarget(const Common::String &target) {
if (ConfMan.hasGameDomain(target)) {
// Set the last selected game, so the game will be highlighted next time the user
// returns to the launcher.
ConfMan.set("lastselectedgame", target, Common::ConfigManager::kApplicationDomain);
ConfMan.flushToDisk();
}
}
// TODO: specify the possible return values here
static Common::Error runGame(const Plugin *enginePlugin, OSystem &system, const DetectedGame &game, const void *meDescriptor) {
assert(enginePlugin);
// Determine the game data path, for validation and error messages
Common::FSNode dir(ConfMan.getPath("path"));
Common::String target = ConfMan.getActiveDomainName();
Common::Error err = Common::kNoError;
Engine *engine = nullptr;
#if defined(SDL_BACKEND) && defined(USE_OPENGL) && defined(USE_RGB_COLOR)
// HACK: We set up the requested graphics mode setting here to allow the
// backend to switch from Surface SDL to OpenGL if necessary. This is
// needed because otherwise the g_system->getSupportedFormats might return
// bad values.
g_system->beginGFXTransaction();
g_system->setGraphicsMode(ConfMan.get("gfx_mode").c_str());
if (g_system->endGFXTransaction() != OSystem::kTransactionSuccess) {
warning("Switching graphics mode to '%s' failed", ConfMan.get("gfx_mode").c_str());
return Common::kUnknownError;
}
#endif
// Verify that the game path refers to an actual directory
if (!dir.exists()) {
err = Common::kPathDoesNotExist;
} else if (!dir.isDirectory()) {
err = Common::kPathNotDirectory;
}
// Create the game's MetaEngine.
MetaEngine &metaEngine = enginePlugin->get<MetaEngine>();
if (err.getCode() == Common::kNoError) {
// Set default values for all of the custom engine options
// Apparently some engines query them in their constructor, thus we
// need to set this up before instance creation.
metaEngine.registerDefaultSettings(target);
err = metaEngine.createInstance(&system, &engine, game, meDescriptor);
}
if (err.getCode() == Common::kNoError) {
// Update add-on targets
if (engine != nullptr && engine->gameTypeHasAddOns())
err = engine->updateAddOns(&metaEngine);
}
// Check for errors
if (!engine || err.getCode() != Common::kNoError) {
// Print a warning; note that scummvm_main will also
// display an error dialog, so we don't have to do this here.
warning("%s failed to instantiate engine: %s (target '%s', path '%s')",
game.engineId.c_str(),
err.getDesc().c_str(),
target.c_str(),
dir.getPath().toString(Common::Path::kNativeSeparator).c_str()
);
// If a temporary target failed to launch, remove it from the configuration manager
// so it not visible in the launcher.
// Temporary targets are created when starting games from the command line using the game id.
if (ConfMan.hasKey("id_came_from_command_line")) {
ConfMan.removeGameDomain(target.c_str());
}
metaEngine.deleteInstance(engine, game, meDescriptor);
return err;
}
// Set up the metaengine
engine->setMetaEngine(&metaEngine);
// Set the window caption to the game name
Common::String caption(ConfMan.get("description"));
if (caption.empty())
caption = game.description;
if (caption.empty())
caption = target;
if (!caption.empty()) {
system.setWindowCaption(caption.decode());
}
//
// Setup various paths in the SearchManager
//
// Add the game path to the directory search list
engine->initializePath(dir);
// Add extrapath (if any) to the directory search list
if (ConfMan.hasKey("extrapath")) {
dir = Common::FSNode(ConfMan.getPath("extrapath"));
SearchMan.addDirectory(dir);
}
// If a second extrapath is specified on the app domain level, add that as well.
// However, since the default hasKey() and get() check the app domain level,
// verify that it's not already there before adding it. The search manager will
// check for that too, so this check is mostly to avoid a warning message.
if (ConfMan.hasKey("extrapath", Common::ConfigManager::kApplicationDomain)) {
Common::Path extraPath = ConfMan.getPath("extrapath", Common::ConfigManager::kApplicationDomain);
dir = Common::FSNode(extraPath);
if (!SearchMan.hasArchive(dir.getPath().toString())) {
SearchMan.addDirectory(dir);
}
}
#ifdef USE_TRANSLATION
Common::String previousLanguage = TransMan.getCurrentLanguage();
if (ConfMan.hasKey("gui_use_game_language")
&& ConfMan.getBool("gui_use_game_language")
&& ConfMan.hasKey("language")) {
TransMan.setLanguage(ConfMan.get("language"));
Common::TextToSpeechManager *ttsMan;
if ((ttsMan = g_system->getTextToSpeechManager()) != nullptr) {
ttsMan->setLanguage(ConfMan.get("language"));
}
}
#endif // USE_TRANSLATION
// Initialize any game-specific keymaps
Common::KeymapArray gameKeymaps = metaEngine.initKeymaps(target.c_str());
Common::Keymapper *keymapper = system.getEventManager()->getKeymapper();
for (auto &gameKeymap : gameKeymaps) {
keymapper->addGameKeymap(gameKeymap);
}
system.applyBackendSettings();
// Inform backend that the engine is about to be run
system.engineInit();
// Purge queued input events that may remain from the GUI (such as key-up)
system.getEventManager()->purgeKeyboardEvents();
system.getEventManager()->purgeMouseEvents();
// Run the engine
Common::Error result = engine->run();
// Make sure we do not return to the launcher if this is not possible.
if (!engine->hasFeature(Engine::kSupportsReturnToLauncher))
ConfMan.setBool("gui_return_to_launcher_at_exit", false, Common::ConfigManager::kTransientDomain);
// Inform backend that the engine finished
system.engineDone();
// Clean up any game-specific keymaps
keymapper->cleanupGameKeymaps();
// Free up memory
metaEngine.deleteInstance(engine, game, meDescriptor);
// Reset the file/directory mappings
SearchMan.clear();
#ifdef USE_TRANSLATION
TransMan.setLanguage(previousLanguage);
Common::TextToSpeechManager *ttsMan;
if ((ttsMan = g_system->getTextToSpeechManager()) != nullptr) {
ttsMan->setLanguage(ConfMan.get("language"));
}
#endif // USE_TRANSLATION
// Return result (== 0 means no error)
return result;
}
static void setupGraphics(OSystem &system) {
system.beginGFXTransaction();
// Set the user specified graphics mode (if any).
system.setGraphicsMode(ConfMan.get("gfx_mode").c_str());
system.setStretchMode(ConfMan.get("stretch_mode").c_str());
system.setScaler(ConfMan.get("scaler").c_str(), ConfMan.getInt("scale_factor"));
system.setShader(ConfMan.getPath("shader"));
system.setRotationMode(ConfMan.getInt("rotation_mode"));
#if defined(OPENDINGUX) || defined(MIYOO) || defined(MIYOOMINI) || defined(ATARI)
// 0, 0 means "autodetect" but currently only SDL supports
// it and really useful only on Opendingux. When more platforms
// support it we will switch to it.
system.initSize(0, 0);
#else
system.initSize(320, 200);
#endif
// Parse graphics configuration, implicit fallback to defaults set with RegisterDefaults()
system.setFeatureState(OSystem::kFeatureAspectRatioCorrection, ConfMan.getBool("aspect_ratio"));
system.setFeatureState(OSystem::kFeatureFullscreenMode, ConfMan.getBool("fullscreen"));
system.setFeatureState(OSystem::kFeatureFilteringMode, ConfMan.getBool("filtering"));
system.setFeatureState(OSystem::kFeatureVSync, ConfMan.getBool("vsync"));
system.endGFXTransaction();
system.applyBackendSettings();
// Set initial window caption
system.setWindowCaption(Common::U32String(gScummVMFullVersion));
// Clear the main screen
system.fillScreen(0);
}
static void setupKeymapper(OSystem &system) {
using namespace Common;
Keymapper *mapper = system.getEventManager()->getKeymapper();
mapper->clear();
// Query the backend for hardware keys and default bindings and register them
HardwareInputSet *inputSet = system.getHardwareInputSet();
KeymapperDefaultBindings *backendDefaultBindings = system.getKeymapperDefaultBindings();
mapper->registerHardwareInputSet(inputSet, backendDefaultBindings);
Keymap *primaryGlobalKeymap = system.getEventManager()->getGlobalKeymap();
if (primaryGlobalKeymap) {
mapper->addGlobalKeymap(primaryGlobalKeymap);
}
// Get the platform-specific global keymap (if it exists)
KeymapArray platformKeymaps = system.getGlobalKeymaps();
for (auto &platformKeymap : platformKeymaps) {
mapper->addGlobalKeymap(platformKeymap);
}
}
extern "C" int scummvm_main(int argc, const char * const argv[]) {
Common::String specialDebug;
Common::String command;
// Verify that the backend has been initialized (i.e. g_system has been set).
assert(g_system);
OSystem &system = *g_system;
// Register config manager defaults
Base::registerDefaults();
system.registerDefaultSettings(Common::ConfigManager::kApplicationDomain);
// Parse the command line
Common::StringMap settings;
command = Base::parseCommandLine(settings, argc, argv);
// Check for backend start settings
Common::String executable;
if (argc && argv && argv[0]) {
const char *s = strrchr(argv[0], '/');
if (!s)
s = strrchr(argv[0], '\\');
executable = s ? (s + 1) : argv[0];
}
Common::StringArray additionalArgs;
system.updateStartSettings(executable, command, settings, additionalArgs);
if (!additionalArgs.empty()) {
// Parse those additional command line arguments.
additionalArgs.insert_at(0, executable);
uint argumentsSize = additionalArgs.size();
char **arguments = (char **)malloc(argumentsSize * sizeof(char *));
for (uint i = 0; i < argumentsSize; i++) {
arguments[i] = (char *)malloc(additionalArgs[i].size() + 1);
Common::strlcpy(arguments[i], additionalArgs[i].c_str(), additionalArgs[i].size() + 1);
}
Common::StringMap additionalSettings;
Common::String additionalCommand = Base::parseCommandLine(additionalSettings, argumentsSize, arguments);
for (uint i = 0; i < argumentsSize; i++)
free(arguments[i]);
free(arguments);
// Merge additional settings and command with command line. Command line has priority.
if (command.empty())
command = additionalCommand;
for (const auto &additionalSetting : additionalSettings) {
if (!settings.contains(additionalSetting._key))
settings[additionalSetting._key] = additionalSetting._value;
}
}
// Load the config file (possibly overridden via command line):
Common::Path initConfigFilename;
if (settings.contains("initial-cfg"))
initConfigFilename = Common::Path(settings["initial-cfg"], Common::Path::kNativeSeparator);
bool configLoadStatus;
if (settings.contains("config")) {
configLoadStatus = ConfMan.loadConfigFile(
Common::Path(settings["config"], Common::Path::kNativeSeparator), initConfigFilename);
} else {
configLoadStatus = ConfMan.loadDefaultConfigFile(initConfigFilename);
}
// Update the config file
ConfMan.set("versioninfo", gScummVMVersion, Common::ConfigManager::kApplicationDomain);
// Load and setup the debuglevel and the debug flags. We do this at the
// soonest possible moment to ensure debug output starts early on, if
// requested.
if (settings.contains("debuglevel")) {
gDebugLevel = (int)strtol(settings["debuglevel"].c_str(), nullptr, 10);
printf("Debuglevel (from command line): %d\n", gDebugLevel);
settings.erase("debuglevel"); // This option should not be passed to ConfMan.
} else if (ConfMan.hasKey("debuglevel"))
gDebugLevel = ConfMan.getInt("debuglevel");
if (settings.contains("debugflags")) {
specialDebug = settings["debugflags"];
settings.erase("debugflags");
} else if (ConfMan.hasKey("debugflags"))
specialDebug = ConfMan.get("debugflags");
if (settings.contains("debug-channels-only"))
gDebugChannelsOnly = true;
// Now we want to enable global flags if any
Common::StringTokenizer tokenizer(specialDebug, " ,");
while (!tokenizer.empty()) {
Common::String token = tokenizer.nextToken();
if (token.equalsIgnoreCase("all"))
DebugMan.enableAllDebugChannels();
else
DebugMan.enableDebugChannel(token);
}
ConfMan.registerDefault("always_run_fallback_detection_extern", true);
PluginManager::instance().init();
PluginManager::instance().loadAllPlugins(); // load plugins for cached plugin manager
PluginManager::instance().loadDetectionPlugin(); // load detection plugin for uncached plugin manager
// If we received an invalid music parameter via command line we check this here.
// We can't check this before loading the music plugins.
// On the other hand we cannot load the plugins before we know the file paths (in case of external plugins).
if (settings.contains("music-driver")) {
if (MidiDriver::getMusicType(MidiDriver::getDeviceHandle(settings["music-driver"])) == MT_INVALID) {
warning("Unrecognized music driver '%s'. Switching to default device", settings["music-driver"].c_str());
settings["music-driver"] = "auto";
}
}
// Process the remaining command line settings. Must be done after the
// config file and the plugins have been loaded.
Common::Error res;
// TODO: deal with settings that require plugins to be loaded
if (Base::processSettings(command, settings, res)) {
if (res.getCode() != Common::kNoError)
warning("%s", res.getDesc().c_str());
PluginManager::destroy();
return res.getCode();
}
if (settings.contains("dump-midi")) {
// Store this command line setting in ConfMan, since all transient settings are destroyed
ConfMan.registerDefault("dump_midi", true);
}
#ifdef USE_OPENGL
if (settings.contains("last_window_width")) {
ConfMan.setInt("last_window_width", atoi(settings["last_window_width"].c_str()), Common::ConfigManager::kApplicationDomain);
ConfMan.setInt("last_window_height", atoi(settings["last_window_height"].c_str()), Common::ConfigManager::kApplicationDomain);
}
#endif
// If we received an old style graphics mode parameter via command line
// override it to default at this stage, so that the backend init won't
// pass it onto updateOldSettings(). If it happened to be a valid new
// graphics mode, we'll put it back after initBackend().
Common::String gfxModeSetting;
if (settings.contains("gfx-mode")) {
gfxModeSetting = settings["gfx-mode"];
if (ScalerMan.isOldGraphicsSetting(gfxModeSetting)) {
settings["gfx-mode"] = "default";
ConfMan.set("gfx_mode", settings["gfx-mode"], Common::ConfigManager::kSessionDomain);
}
}
// Init the backend. Must take place after all config data (including
// the command line params) was read.
system.initBackend();
// If we received an invalid graphics mode parameter via command line
// we check this here. We can't do it until after the backend is inited,
// or there won't be a graphics manager to ask for the supported modes.
if (!gfxModeSetting.empty()) {
const OSystem::GraphicsMode *gm = g_system->getSupportedGraphicsModes();
bool isValid = false;
while (gm->name && !isValid) {
isValid = !scumm_stricmp(gm->name, gfxModeSetting.c_str());
gm++;
}
if (!isValid) {
// We will actually already have switched to default, but couldn't be sure that it was right until now.
warning("Unrecognized graphics mode '%s'. Switching to default mode", gfxModeSetting.c_str());
} else {
settings["gfx-mode"] = gfxModeSetting;
system.beginGFXTransaction();
system.setGraphicsMode(gfxModeSetting.c_str());
system.endGFXTransaction();
}
ConfMan.set("gfx_mode", gfxModeSetting, Common::ConfigManager::kSessionDomain);
}
#ifdef ENABLE_EVENTRECORDER
if (settings.contains("disable-display")) {
ConfMan.setInt("disable_display", 1, Common::ConfigManager::kTransientDomain);
}
#endif
setupGraphics(system);
if (!configLoadStatus) {
GUI::MessageDialog alert(_("Bad config file format. overwrite?"), _("Yes"), _("Cancel"));
if (alert.runModal() != GUI::kMessageOK)
return 0;
}
// Init the different managers that are used by the engines.
// Do it here to prevent fragmentation later
system.getAudioCDManager();
MusicManager::instance();
Common::DebugManager::instance();
// Init the event manager. As the virtual keyboard is loaded here, it must
// take place after the backend is initiated and the screen has been setup
system.getEventManager()->init();
#ifdef ENABLE_EVENTRECORDER
// Directly after initializing the event manager, we will initialize our
// event recorder.
//
// TODO: This is just to match the current behavior, when we further extend
// our event recorder, we might do this at another place. Or even change
// the whole API for that ;-).
g_eventRec.RegisterEventSource();
#endif
Common::OSDMessageQueue::instance().registerEventSource();
// Now as the event manager is created, setup the keymapper
setupKeymapper(system);
#ifdef USE_UPDATES
if (!ConfMan.hasKey("updates_check") && g_system->getUpdateManager()) {
GUI::UpdatesDialog dlg;
dlg.runModal();
}
#endif
#ifdef ANDROID_BACKEND
// This early popup message for Android, informing the users about important
// changes to file access, needs to be *after* language for the GUI has been selected.
// Hence, we instantiate GUI Manager here, to take care of this.
GUI::GuiManager::instance();
if (AndroidFilesystemFactory::instance().hasSAF()
&& !ConfMan.hasKey("android_saf_dialog_shown")) {
bool cancelled = false;
if (!ConfMan.getGameDomains().empty()) {
GUI::MessageDialog alert(_(
// I18N: <Add a new folder> must match the translation done in backends/fs/android/android-saf-fs.h
"In this new version of ScummVM for Android, significant changes were made to "
"the file access system to allow support for modern versions of the Android "
"Operating System.\n"
"If you find that your existing added games or custom paths no longer work, "
"please edit those paths:"
"\n"
" 1. From the Launcher, go to **Game Options > Paths**."
" Select **Game Path** or **Extra Path**, as appropriate. \n"
" 2. Inside the ScummVM file browser, select **Go Up** until you reach the root folder "
"which has the **<Add a new folder>** option.\n"
" 3. Double-tap **<Add a new folder>**. In your device's file browser, navigate to the folder "
"containing all your game folders. For example, **SD Card > ScummVMgames** \n"
" 4. Select **Use this folder**. \n"
" 5. Select **Allow** to give ScummVM permission to access the folder. \n"
" 6. In the ScummVM file browser, double-tap to browse through your added folder. "
"Select the folder containing the game's files, then tap **Choose**. \n"
"\n"
"Repeat steps 1 and 6 for each game."
), _("OK"),
// I18N: A button caption to dismiss a message and read it later
_("Read Later"), Graphics::kTextAlignLeft);
if (alert.runModal() != GUI::kMessageOK)
cancelled = true;
} else {
GUI::MessageDialog alert(_(
// I18N: <Add a new folder> must match the translation done in backends/fs/android/android-saf-fs.h
"In this new version of ScummVM for Android, significant changes were made to "
"the file access system to allow support for modern versions of the Android "
"Operating System.\n"
"To add a game:\n"
"\n"
" 1. Select **Add Game...** from the launcher. \n"
" 2. Inside the ScummVM file browser, select **Go Up** until you reach the root folder "
"which has the **<Add a new folder>** option.\n"
" 3. Double-tap **<Add a new folder>**. In your device's file browser, navigate to the folder "
"containing all your game folders. For example, **SD Card > ScummVMgames** \n"
" 4. Select **Use this folder**. \n"
" 5. Select **Allow** to give ScummVM permission to access the folder. \n"
" 6. In the ScummVM file browser, double-tap to browse through your added folder. "
"Select the sub-folder containing the game's files, then tap **Choose**."
"\n"
"Repeat steps 1 and 6 for each game."
), _("OK"),
// I18N: A button caption to dismiss a message and read it later
_("Read Later"), Graphics::kTextAlignLeft);
if (alert.runModal() != GUI::kMessageOK)
cancelled = true;
}
if (!cancelled)
ConfMan.setBool("android_saf_dialog_shown", true);
}
#endif
#ifdef USE_CLOUD
CloudMan.init();
CloudMan.syncSaves();
#endif
#if 0
GUI::dumpAllDialogs();
#endif
// Print out CPU extension info
// Separate block to keep the stack clean
{
Common::String extensionSupportString[3] = { "not supported", "disabled", "enabled" };
byte sse2Support = 0;
byte avx2Support = 0;
byte neonSupport = 0;
#ifdef SCUMMVM_SSE2
++sse2Support;
if (g_system->hasFeature(OSystem::kFeatureCpuSSE2))
++sse2Support;
#endif
#ifdef SCUMMVM_AVX2
++avx2Support;
if (g_system->hasFeature(OSystem::kFeatureCpuAVX2))
++avx2Support;
#endif
#ifdef SCUMMVM_NEON
++neonSupport;
if (g_system->hasFeature(OSystem::kFeatureCpuNEON))
++neonSupport;
#endif
debug(0, "CPU extensions:");
debug(0, "SSE2(%s) AVX2(%s) NEON(%s)",
extensionSupportString[sse2Support].c_str(),
extensionSupportString[avx2Support].c_str(),
extensionSupportString[neonSupport].c_str());
}
// Unless a game was specified, show the launcher dialog
if (nullptr == ConfMan.getActiveDomain())
launcherDialog();
// FIXME: We're now looping the launcher. This, of course, doesn't
// work as well as it should. In theory everything should be destroyed
// cleanly, so this is now enabled to encourage people to fix bits :)
while (nullptr != ConfMan.getActiveDomain()) {
saveLastLaunchedTarget(ConfMan.getActiveDomainName());
EngineMan.upgradeTargetIfNecessary(ConfMan.getActiveDomainName());
// Try to find a MetaEnginePlugin which feels responsible for the specified game.
const Plugin *enginePlugin = nullptr;
const Plugin *plugin = nullptr;
DetectedGame game;
const void *meDescriptor = nullptr;
Common::Error result = identifyGame(specialDebug, &plugin, game, &meDescriptor);
if (result.getCode() == Common::kNoError) {
Common::String engineId = plugin->getName();
#if defined(UNCACHED_PLUGINS) && defined(DYNAMIC_MODULES) && !defined(DETECTION_STATIC)
// Unload all MetaEnginesDetection if we're using uncached plugins to save extra memory.
PluginManager::instance().unloadDetectionPlugin();
#endif
// Then, get the relevant Engine plugin from MetaEngine.
enginePlugin = PluginMan.findEnginePlugin(engineId);
if (enginePlugin == nullptr) {
result = Common::kEnginePluginNotFound;
}
}
if (result.getCode() == Common::kNoError) {
// Unload all plugins not needed for this game, to save memory
// Right now, we have a MetaEngine plugin, and we want to unload all except Engine.
// Pass in the pointer to enginePlugin, with the matching type, so our function behaves as-is.
PluginManager::instance().unloadPluginsExcept(PLUGIN_TYPE_ENGINE, enginePlugin);
#ifdef ENABLE_EVENTRECORDER
Common::String recordMode = ConfMan.get("record_mode");
Common::String recordFileName = ConfMan.get("record_file_name");
if (recordMode == "record") {
Common::String targetFileName = ConfMan.hasKey("record_file_name") ? recordFileName : g_eventRec.generateRecordFileName(ConfMan.getActiveDomainName());
g_eventRec.init(targetFileName, GUI::EventRecorder::kRecorderRecord);
} else if (recordMode == "update") {
g_eventRec.init(recordFileName, GUI::EventRecorder::kRecorderUpdate);
} else if (recordMode == "playback") {
g_eventRec.init(recordFileName, GUI::EventRecorder::kRecorderPlayback);
} else if (recordMode == "fast_playback") {
g_eventRec.init(recordFileName, GUI::EventRecorder::kRecorderPlayback);
g_eventRec.setFastPlayback(true);
} else if ((recordMode == "info") && (!recordFileName.empty())) {
Common::PlaybackFile record;
record.openRead(recordFileName);
debug("info:author=%s name=%s description=%s", record.getHeader().author.c_str(), record.getHeader().name.c_str(), record.getHeader().description.c_str());
DebugMan.removeAllDebugChannels();
break;
}
#endif
Common::TextToSpeechManager *ttsMan = g_system->getTextToSpeechManager();
if (ttsMan != nullptr) {
ttsMan->pushState();
}
// Try to run the game
result = runGame(enginePlugin, system, game, meDescriptor);
if (ttsMan != nullptr) {
ttsMan->popState();
}
DebugMan.removeAllDebugChannels();
#ifdef ENABLE_EVENTRECORDER
// Flush Event recorder file. The recorder does not get reinitialized for next game
// which is intentional. Only single game per session is allowed.
g_eventRec.deinit();
#endif
#if defined(UNCACHED_PLUGINS) && defined(DYNAMIC_MODULES)
// do our best to prevent fragmentation by unloading as soon as we can
PluginManager::instance().unloadPluginsExcept(PLUGIN_TYPE_ENGINE, NULL, false);
PluginManager::instance().unloadDetectionPlugin();
// reallocate the config manager to get rid of any fragmentation
ConfMan.defragment();
// The keymapper keeps pointers to the configuration domains. It needs to be reinitialized.
setupKeymapper(system);
#endif
// Did an error occur ?
if (result.getCode() != Common::kNoError && result.getCode() != Common::kUserCanceled) {
// Shows an informative error dialog if starting the selected game failed.
GUI::displayErrorDialog(result, _("Error running game:"));
}
// Quit unless an error occurred, or Return to launcher was requested
if (result.getCode() == Common::kNoError && !g_system->getEventManager()->shouldReturnToLauncher() &&
!g_system->hasFeature(OSystem::kFeatureNoQuit) && !ConfMan.getBool("gui_return_to_launcher_at_exit"))
break;
// Reset the return to launcher and quit flags in case we want to load another engine
g_system->getEventManager()->resetReturnToLauncher();
g_system->getEventManager()->resetQuit();
#ifdef ENABLE_EVENTRECORDER
if (g_eventRec.checkForContinueGame()) {
continue;
}
#endif
// At this point, we usually return to the launcher. However, the
// game may have requested that one or more other games be "chained"
// to the current one, with optional save slots to start the games
// at. At the time of writing, this is used for the Maniac Mansion
// easter egg in Day of the Tentacle.
Common::String chainedGame;
int saveSlot = -1;
ChainedGamesMan.pop(chainedGame, saveSlot);
// Discard any command line options. It's unlikely that the user
// wanted to apply them to *all* games ever launched.
ConfMan.getDomain(Common::ConfigManager::kTransientDomain)->clear();
if (!chainedGame.empty()) {
if (saveSlot != -1) {
ConfMan.setInt("save_slot", saveSlot, Common::ConfigManager::kTransientDomain);
}
// Start the chained game
ConfMan.setActiveDomain(chainedGame);
} else {
// Clear the active config domain
ConfMan.setActiveDomain("");
}
PluginManager::instance().loadAllPluginsOfType(PLUGIN_TYPE_ENGINE); // only for cached manager
PluginManager::instance().loadDetectionPlugin(); // only for uncached manager
} else {
DebugMan.removeAllDebugChannels();
GUI::displayErrorDialog(result, _("Error running game:"));
// Clear the active domain
ConfMan.setActiveDomain("");
}
// reset the graphics to default
setupGraphics(system);
if (nullptr == ConfMan.getActiveDomain()) {
launcherDialog();
}
}
#ifdef USE_SDL_NET
Networking::LocalWebserver::destroy();
#endif
#ifdef USE_CLOUD
Networking::ConnectionManager::destroy();
//I think it's important to destroy it after ConnectionManager
Cloud::CloudManager::destroy();
#endif
PluginManager::destroy();
GUI::GuiManager::destroy();
Common::ConfigManager::destroy();
Common::DebugManager::destroy();
Common::OSDMessageQueue::destroy();
#ifdef ENABLE_EVENTRECORDER
GUI::EventRecorder::destroy();
#endif
Common::SearchManager::destroy();
#ifdef USE_TRANSLATION
Common::MainTranslationManager::destroy();
#endif
MusicManager::destroy();
Graphics::CursorManager::destroy();
Graphics::FontManager::destroy();
#ifdef USE_FREETYPE2
Graphics::shutdownTTF();
#endif
EngineManager::destroy();
Graphics::YUVToRGBManager::destroy();
return 0;
}

32
base/main.h Normal file
View File

@@ -0,0 +1,32 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef BASE_MAIN_H
#define BASE_MAIN_H
#include "common/scummsys.h"
//
// The scummvm main entry point, to be invoked by ports
//
extern "C" int scummvm_main(int argc, const char * const argv[]);
#endif

11
base/module.mk Normal file
View File

@@ -0,0 +1,11 @@
MODULE := base
MODULE_OBJS := \
test_new_standards.o \
main.o \
commandLine.o \
plugins.o \
version.o
# Include common rules
include $(srcdir)/rules.mk

1080
base/plugins.cpp Normal file

File diff suppressed because it is too large Load Diff

368
base/plugins.h Normal file
View File

@@ -0,0 +1,368 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef BASE_PLUGINS_H
#define BASE_PLUGINS_H
#include "common/array.h"
#include "common/fs.h"
#include "common/str.h"
#include "backends/plugins/elf/version.h"
#define INCLUDED_FROM_BASE_PLUGINS_H
#include "base/internal_plugins.h"
#undef INCLUDED_FROM_BASE_PLUGINS_H
// Plugin versioning
/** Global Plugin API version */
#define PLUGIN_VERSION 1
enum PluginType {
PLUGIN_TYPE_ENGINE_DETECTION = 0,
PLUGIN_TYPE_ENGINE,
PLUGIN_TYPE_MUSIC,
PLUGIN_TYPE_DETECTION,
PLUGIN_TYPE_SCALER,
PLUGIN_TYPE_MAX
};
// TODO: Make the engine API version depend on ScummVM's version
// because of the back linking (possibly from the checkout revision)
#define PLUGIN_TYPE_ENGINE_DETECTION_VERSION 1
#define PLUGIN_TYPE_ENGINE_VERSION 2
#define PLUGIN_TYPE_MUSIC_VERSION 1
#define PLUGIN_TYPE_DETECTION_VERSION 1
#define PLUGIN_TYPE_SCALER_VERSION 1
extern const int pluginTypeVersions[PLUGIN_TYPE_MAX];
// Plugin linking
// see comments in backends/plugins/elf/elf-provider.cpp
#if defined(USE_ELF_LOADER) && defined(ELF_LOADER_CXA_ATEXIT)
#define PLUGIN_DYNAMIC_DSO_HANDLE \
uint32 __dso_handle __attribute__((visibility("hidden"))) = 0;
#else
#define PLUGIN_DYNAMIC_DSO_HANDLE
#endif
#ifdef USE_ELF_LOADER
#define PLUGIN_DYNAMIC_BUILD_DATE \
PLUGIN_EXPORT const char *PLUGIN_getBuildDate() { return gScummVMPluginBuildDate; }
#else
#define PLUGIN_DYNAMIC_BUILD_DATE
#endif
/**
* REGISTER_PLUGIN_STATIC is a convenience macro which is used to declare
* the plugin interface for static plugins. Code (such as game engines)
* which needs to implement a static plugin can simply invoke this macro
* with a plugin ID, plugin type and PluginObject subclass, and the correct
* wrapper code will be inserted.
*
* @see REGISTER_PLUGIN_DYNAMIC
*/
#define REGISTER_PLUGIN_STATIC(ID,TYPE,PLUGINCLASS) \
extern const PluginType g_##ID##_type; \
const PluginType g_##ID##_type = TYPE; \
PluginObject *g_##ID##_getObject() { \
return new PLUGINCLASS(); \
} \
void dummyFuncToAllowTrailingSemicolon_##ID##_()
#ifdef DYNAMIC_MODULES
/**
* REGISTER_PLUGIN_DYNAMIC is a convenience macro which is used to declare
* the plugin interface for dynamically loadable plugins. Code (such as game engines)
* which needs to implement a dynamic plugin can simply invoke this macro
* with a plugin ID, plugin type and PluginObject subclass, and the correct
* wrapper code will be inserted.
*
* @see REGISTER_PLUGIN_STATIC
*/
#define REGISTER_PLUGIN_DYNAMIC(ID,TYPE,PLUGINCLASS) \
extern "C" { \
PLUGIN_DYNAMIC_DSO_HANDLE \
PLUGIN_DYNAMIC_BUILD_DATE \
PLUGIN_EXPORT int32 PLUGIN_getVersion() { return PLUGIN_VERSION; } \
PLUGIN_EXPORT int32 PLUGIN_getType() { return TYPE; } \
PLUGIN_EXPORT int32 PLUGIN_getTypeVersion() { return TYPE##_VERSION; } \
PLUGIN_EXPORT PluginObject *PLUGIN_getObject() { \
return new PLUGINCLASS(); \
} \
} \
void dummyFuncToAllowTrailingSemicolon_##ID##_()
#endif // DYNAMIC_MODULES
// Abstract plugins
/**
* Abstract base class for the plugin objects which handle plugins
* instantiation. Subclasses for this may be used for engine plugins and other
* types of plugins. An existing PluginObject refers to an executable file
* loaded in memory and ready to run. The plugin, on the other hand, is just
* a handle to the file/object, whether it's loaded in memory or not.
*/
class PluginObject {
public:
virtual ~PluginObject() {}
/** Returns the name of the plugin. */
virtual const char *getName() const = 0;
};
/**
* Abstract base class for the plugin system.
* Subclasses for this can be used to wrap both static and dynamic
* plugins. This class refers to a plugin which may or may not be loaded in
* memory.
*/
class Plugin {
protected:
PluginObject *_pluginObject;
PluginType _type;
public:
Plugin() : _pluginObject(0), _type(PLUGIN_TYPE_MAX) {}
virtual ~Plugin() {
//if (isLoaded())
//unloadPlugin();
}
// virtual bool isLoaded() const = 0; // TODO
virtual bool loadPlugin() = 0; // TODO: Rename to load() ?
virtual void unloadPlugin() = 0; // TODO: Rename to unload() ?
/**
* The following functions query information from the plugin object once
* it's loaded into memory.
**/
PluginType getType() const;
const char *getName() const;
template <class T>
T &get() const {
T *pluginObject = dynamic_cast<T *>(_pluginObject);
if (!pluginObject) {
error("Invalid cast of plugin %s", getName());
}
return *pluginObject;
}
/**
* The getFileName() function gets the name of the plugin file for those
* plugins that have files (ie. not static). It doesn't require the plugin
* object to be loaded into memory, unlike getName()
**/
virtual Common::Path getFileName() const { return Common::Path(); }
};
class StaticPlugin : public Plugin {
public:
StaticPlugin(PluginObject *pluginobject, PluginType type);
~StaticPlugin();
virtual bool loadPlugin();
virtual void unloadPlugin();
};
/** List of Plugin instances. */
typedef Common::Array<Plugin *> PluginList;
/**
* Abstract base class for Plugin factories. Subclasses of this
* are responsible for creating plugin objects, e.g. by loading
* loadable modules from storage media; by creating "fake" plugins
* from static code; or whatever other means.
*/
class PluginProvider {
public:
virtual ~PluginProvider() {}
/**
* Return a list of Plugin objects. The caller is responsible for actually
* loading/unloading them (by invoking the appropriate Plugin methods).
* Furthermore, the caller is responsible for deleting these objects
* eventually.
*
* @return a list of Plugin instances
*/
virtual PluginList getPlugins() = 0;
/**
* @return whether or not object is a FilePluginProvider.
*/
virtual bool isFilePluginProvider() { return false; }
};
#ifdef DYNAMIC_MODULES
/**
* Abstract base class for Plugin factories which load binary code from files.
* Subclasses only have to implement the createPlugin() method, and optionally
* can overload the other protected methods to achieve custom behavior.
*/
class FilePluginProvider : public PluginProvider {
public:
/**
* Return a list of Plugin objects loaded via createPlugin from disk.
* For this, a list of directories is searched for plugin objects:
* The current dir and its "plugins" subdirectory (if present), a list
* of custom search dirs (see addCustomDirectories) and finally the
* directory specified via the "pluginspath" config variable (if any).
*
* @return a list of Plugin instances
*/
virtual PluginList getPlugins();
/**
* @return whether or not object is a FilePluginProvider.
*/
bool isFilePluginProvider() { return true; }
protected:
/**
* Create a Plugin instance from a loadable code module with the specified name.
* Subclasses of FilePluginProvider have to at least overload this method.
* If the file is not found, or does not contain loadable code, 0 is returned instead.
*
* @param node the FSNode of the loadable code module
* @return a pointer to a Plugin instance, or 0 if an error occurred.
*/
virtual Plugin *createPlugin(const Common::FSNode &node) const = 0;
/**
* Check if the supplied file corresponds to a loadable plugin file in
* the current platform. Usually, this will just check the file name.
*
* @param node the FSNode of the file to check
* @return true if the filename corresponds to a plugin, false otherwise
*/
virtual bool isPluginFilename(const Common::FSNode &node) const;
/**
* Optionally add to the list of directories to be searched for
* plugins by getPlugins().
*
* @param dirs the reference to the list of directories to be used when
* searching for plugins.
*/
virtual void addCustomDirectories(Common::FSList &dirs) const;
};
#endif // DYNAMIC_MODULES
#define PluginMan PluginManager::instance()
/**
* Singleton class which manages all plugins, including loading them,
* managing all Plugin class instances, and unloading them.
*/
class PluginManager {
protected:
typedef Common::Array<PluginProvider *> ProviderList;
PluginList _pluginsInMem[PLUGIN_TYPE_MAX];
ProviderList _providers;
bool tryLoadPlugin(Plugin *plugin);
void addToPluginsInMemList(Plugin *plugin);
const Plugin *findLoadedPlugin(const Common::String &engineId);
static PluginManager *_instance;
PluginManager();
void unloadAllPlugins();
public:
virtual ~PluginManager();
static void destroy() { delete _instance; _instance = 0; }
static PluginManager &instance();
void addPluginProvider(PluginProvider *pp);
/**
* A method which finds the METAENGINE plugin for the provided engineId
*
* @param engineId The engine ID
*
* @return A plugin of type METAENGINE.
*/
const Plugin *findEnginePlugin(const Common::String &engineId);
// Functions used by the uncached PluginManager
virtual void init() {}
virtual void loadFirstPlugin() {}
virtual bool loadNextPlugin() { return false; }
virtual bool loadPluginFromEngineId(const Common::String &engineId) { return false; }
virtual void updateConfigWithFileName(const Common::String &engineId) {}
virtual void loadDetectionPlugin() {}
virtual void unloadDetectionPlugin() {}
// Functions used only by the cached PluginManager
virtual void loadAllPlugins();
virtual void loadAllPluginsOfType(PluginType type);
void unloadPluginsExcept(PluginType type, const Plugin *plugin, bool deletePlugin = true);
const PluginList &getPlugins(PluginType t) { return _pluginsInMem[t]; }
};
/**
* Uncached version of plugin manager
* Keeps only one dynamic plugin in memory at a time
**/
class PluginManagerUncached : public PluginManager {
protected:
friend class PluginManager;
PluginList _allEnginePlugins;
Plugin *_detectionPlugin;
PluginList::iterator _currentPlugin;
bool _isDetectionLoaded;
PluginManagerUncached() : _detectionPlugin(nullptr), _currentPlugin(nullptr), _isDetectionLoaded(false) {}
bool loadPluginByFileName(const Common::Path &filename);
public:
virtual ~PluginManagerUncached();
void init() override;
void loadFirstPlugin() override;
bool loadNextPlugin() override;
bool loadPluginFromEngineId(const Common::String &engineId) override;
void updateConfigWithFileName(const Common::String &engineId) override;
#ifndef DETECTION_STATIC
void loadDetectionPlugin() override;
void unloadDetectionPlugin() override;
#endif
void loadAllPlugins() override {} // we don't allow these
void loadAllPluginsOfType(PluginType type) override {}
};
#endif

336
base/test_new_standards.cpp Normal file
View File

@@ -0,0 +1,336 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
// This file does nothing functional!
// It test support for main C++11 features
// In the future, it might be extended to test also C++14, C++17, C++20 and any future standard
//
// In order to enable the tests, we have to `define ENABLE_TEST_CPP_11` (and of course, compile this file)
// Then it should print "Testing C++11" *during compilation*
// If the message is printed, and there are no compilation errors - great, C++11 is supported on this platform
// If there are errors, each one of the tests can be disabled, by defining the relevant DONT_TEST_*
// It's important to disable failing tests, because we might decide to support only specific subset of C++11
//
// Note: there are 3 warnings in my GCC run, they have no signficance
#if defined(NONSTANDARD_PORT)
#include "portdefs.h"
#endif
#if defined(HAVE_CONFIG_H)
#include "config.h"
#endif
#ifdef ENABLE_TEST_CPP_11
#pragma message("Testing C++11")
// The tests are based on https://blog.petrzemek.net/2014/12/07/improving-cpp98-code-with-cpp11/
// See there for further links and explanations
//
// We're not testing `nullptr` and `override`, since they're defined in common/c++11-compat.h
#include "common/array.h"
#include "common/hashmap.h"
#include "common/hash-str.h"
#include "common/rect.h"
#ifndef DONT_TEST_UNICODE_STRING_LITERAL
const char16_t *u16str = u"\u00DAnicode string";
const char32_t *u32str = U"\u00DAnicode string";
#endif
#ifndef DONT_TEST_INITIALIZIER_LIST1
#ifndef USE_INITIALIZIER_LIST_REPLACEMENT
#include <initializer_list>
#else
namespace std {
template<class T> class initializer_list {
public:
typedef T value_type;
typedef const T& reference;
typedef const T& const_reference;
typedef size_t size_type;
typedef const T* iterator;
typedef const T* const_iterator;
constexpr initializer_list() noexcept = default;
constexpr size_t size() const noexcept { return m_size; };
constexpr const T* begin() const noexcept { return m_begin; };
constexpr const T* end() const noexcept { return m_begin + m_size; }
private:
// Note: begin has to be first or the compiler gets very upset
const T* m_begin = { nullptr };
size_t m_size = { 0 };
// The compiler is allowed to call this constructor
constexpr initializer_list(const T* t, size_t s) noexcept : m_begin(t) , m_size(s) {}
};
template<class T> constexpr const T* begin(initializer_list<T> il) noexcept {
return il.begin();
}
template<class T> constexpr const T* end(initializer_list<T> il) noexcept {
return il.end();
}
} // end namespace std
#endif
#endif
#ifndef DONT_TEST_CLASS_ENUM
// ----------------------------------
// Scoped/Strongly Typed Enumerations
// ----------------------------------
enum class MyEnum {
VAL1,
VAL2,
VAL3
};
#endif
#ifndef DONT_TEST_FINAL_CLASS
// ----------------------------------
// Non-Inheritable Classes (final)
// ----------------------------------
// C++11
class TestNewStandards final {
#else
class TestNewStandards {
#endif
private:
void do_nothing(const int &i) {
// don't do anything with i
};
#ifndef DONT_TEST_STRING_LITERAL_INIT
// ----------------------------------
// Char arrays initialized by a string literal
// * note - not properly implemented before GCC 5.1 (GCC Bug #43453)
// ----------------------------------
char _emptyMsg[1] = "";
#else
char _emptyMsg[1] = { '\0' };
#endif
#ifndef DONT_TEST_FINAL_FUNCTION
// ----------------------------------
// Non-Overridable Member Functions (final)
// ----------------------------------
virtual void f() final {}
#endif
#ifndef DONT_TEST_VARIADIC_TEMPLATES
// ------------------------
// Variadic Templates
// ------------------------
template <typename T>
void variadic_function(const T &value) {
do_nothing(value);
}
template <typename U, typename... T>
void variadic_function(const U &head, const T &... tail) {
do_nothing(head);
variadic_function(tail...);
}
#endif
#ifndef DONT_TEST_TYPE_ALIASES
// ------------------------
// Type Aliases
// * note - this test has another bunch of code below
// ------------------------
// C++98
template<typename T>
struct Dictionary_98 {
typedef Common::HashMap<Common::String, T, Common::IgnoreCase_Hash, Common::IgnoreCase_EqualTo> type;
};
// Usage:
Dictionary_98<int>::type d98;
// C++11
template <typename T>
using Dictionary_11 = Common::HashMap<Common::String, T, Common::IgnoreCase_Hash, Common::IgnoreCase_EqualTo>;
// Usage:
Dictionary_11<int> d11;
#endif
#ifndef DONT_TEST_INITIALIZIER_LIST1
// Array with C++11 initialization list
template<class T> class ArrayCpp11 : public Common::Array<T> {
public:
ArrayCpp11(std::initializer_list<T> list) {
if (list.size()) {
this->allocCapacity(list.size());
Common::uninitialized_copy(list.begin(), list.end(), this->_storage);
}
}
};
#endif
void test_cpp11() {
#ifdef DONT_TEST_INITIALIZIER_LIST1
// ------------------------
// Initializer list
// ------------------------
// C++98
Common::Array<int> arr;
arr.push_back(1);
arr.push_back(2);
arr.push_back(3);
#else
// C++11
ArrayCpp11<int> arr = {1, 2, 3};
#endif
#ifndef DONT_TEST_INITIALIZIER_LIST2
// C++11
Common::Point arr3[] = {{0, 0}, {1, 1}};
#endif
#ifndef DONT_TEST_AUTO_TYPE_INFERENCE
// ------------------------
// Automatic Type Inference
// ------------------------
// C++98
for (Common::Array<int>::iterator i = arr.begin(), e = arr.end(); i != e; ++i)
;
// C++11
for (auto i = arr.begin(), e = arr.end(); i != e; ++i)
;
#endif
#ifndef DONT_TEST_RANGE_BASED_FOR_LOOP
// ------------------------
// Range based for loop
// ------------------------
// C++98
for (Common::Array<int>::iterator i = arr.begin(), e = arr.end(); i != e; ++i)
do_nothing(*i);
// C++11
for (int &i : arr)
do_nothing(i);
#endif
#ifndef DONT_TEST_LAMBDA_FUNCTIONS
// ------------------------
// Lambda functions
// ------------------------
// C++98
// the following isn't working in VS, but it's not really important to debug...
// Common::for_each(arr.begin(), arr.end(), do_nothing);
// C++11
Common::for_each(arr.begin(), arr.end(),
[](int i) {
// don't do anything with i
}
);
#endif
#ifndef DONT_TEST_VARIADIC_TEMPLATES
variadic_function(1, 1, 2, 3, 5, 8, 13, 21, 34);
#endif
#ifndef DONT_TEST_GET_RID_OF_SPACE_IN_NESTED_TEMPLATES
// ------------------------
// No Need For an Extra Space In Nested Template Declarations
// ------------------------
// C++98
Common::Array<Common::Array<int> > v_98;
// C++11
Common::Array<Common::Array<int>> v_11;
#endif
#ifndef DONT_TEST_TYPE_ALIASES
// ------------------------
// Type Aliases
// * note - this test has another bunch of code above
// ------------------------
// C++98
typedef void (*fp_98)(int, int);
// C++11
using fp_11 = void (*)(int, int);
#endif
};
#ifndef DONT_TEST_ALT_FUNCTION_SYNTAX
// ------------------------
// Alternative Function Syntax
// ------------------------
// C++98
int f_98(int x, int y) {return x;}
// C++11
auto f_11(int x, int y) -> int {return x;}
#endif
#ifndef DONT_TEST_NON_STATIC_INIT
// ------------------------
// Non-Static Data Member Initializers
// ------------------------
int j = 3;
Common::String s = "non static init";
#endif
#ifndef DONT_TEST_EXPLICIT
// ------------------------
// Explicit Conversion Operators
// ------------------------
explicit operator bool() const {return true;}
#endif
public:
TestNewStandards() {
test_cpp11();
}
#ifndef DONT_TEST_MOVE_SEMANTICS
// ------------------------
// Move semantics
// Note: this test hasn't been taken from the aforementioned web page
// ------------------------
TestNewStandards(TestNewStandards&& t) {
// I'm not convinced that it's a good example of move sematics, it's a complicated topic. But just checking the syntax.
}
#endif
#ifndef DONT_TEST_DELETED_FUNCTIONS
// ------------------------
// Explicitly Deleted Functions
// (useful for non copyable classes,
// particularly for our Singleton class)
// ------------------------
TestNewStandards &operator=(const TestNewStandards &) = delete;
#endif
};
static TestNewStandards test = TestNewStandards();
#endif

245
base/version.cpp Normal file
View File

@@ -0,0 +1,245 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common/scummsys.h"
#include "base/version.h"
#define INCLUDED_FROM_BASE_VERSION_CPP
#include "base/internal_version.h"
/*
* Version string and build date string. These can be used by anything that
* wants to display this information to the user (e.g. about dialog).
*
* Note: it would be very nice if we could instead of (or in addition to) the
* build date present a date which corresponds to the date our source files
* were last changed. To understand the difference, imagine that a user
* makes a checkout on January 1, then after a week compiles it
* (e.g. after doing a 'make clean'). The build date then will say January 8
* even though the files were last changed on January 1.
*
* Another problem is that __DATE__/__TIME__ depend on the local time zone.
*
* It's clear that such a "last changed" date would be much more useful to us
* for feedback purposes. After all, when somebody files a bug report, we
* don't care about the build date, we want to know which date their checkout
* was made.
*
* So, how could we implement this? At least on unix systems, a special script
* could do it. Basically, that script could parse the output of "svn info" or
* "svnversion" to determine the revision of the checkout, and insert that
* information somehow into the build process (e.g. by generating a tiny
* header file, analog to internal_version.h, maybe called svn_rev.h or so.)
*
* Drawback: This only works on systems which can run suitable scripts as part
* of the build process (so I guess Visual C++ would be out of the game here?
* I don't know VC enough to be sure). And of course it must be robust enough
* to properly work in exports (i.e. release tar balls etc.).
*/
const char gScummVMVersion[] = SCUMMVM_VERSION SCUMMVM_REVISION;
#if defined(__amigaos4__) || defined(__MORPHOS__)
static const char *version_cookie __attribute__((used)) = "$VER: ScummVM " SCUMMVM_VERSION SCUMMVM_REVISION " (" AMIGA_DATE ")";
#endif
const char gScummVMBuildDate[] = __DATE__ " " __TIME__;
const char gScummVMVersionDate[] = SCUMMVM_VERSION SCUMMVM_REVISION " (" __DATE__ " " __TIME__ ")";
const char gScummVMCompiler[] = ""
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
#if defined(_MSC_VER)
"MSVC " STR(_MSC_FULL_VER)
#elif defined(__INTEL_COMPILER)
"ICC " STR(__INTEL_COMPILER) "." STR(__INTEL_COMPILER_UPDATE)
#elif defined(__clang__)
"Clang " STR(__clang_major__) "." STR(__clang_minor__) "." STR(__clang_patchlevel__)
#elif defined(__GNUC__)
"GCC " STR(__GNUC__) "." STR(__GNUC_MINOR__) "." STR(__GNUC_PATCHLEVEL__)
#else
"unknown compiler"
#endif
#undef STR
#undef STR_HELPER
;
const char gScummVMFullVersion[] = "ScummVM " SCUMMVM_VERSION SCUMMVM_REVISION " (" __DATE__ " " __TIME__ ")";
const char gScummVMFeatures[] = ""
#ifdef TAINTED_BUILD
// TAINTED means the build contains engines/subengines not enabled by default
"TAINTED "
#endif
#ifdef USE_TREMOR
"Tremor "
#elif defined(USE_VORBIS)
"Vorbis "
#endif
#ifdef USE_FLAC
"FLAC "
#endif
#ifdef USE_MAD
"MP3 "
#endif
#ifdef USE_ALSA
"ALSA "
#endif
#ifdef USE_SEQ_MIDI
"SEQ "
#endif
#ifdef USE_SNDIO
"sndio "
#endif
#ifdef USE_TIMIDITY
"TiMidity "
#endif
#ifdef USE_RGB_COLOR
"RGB "
#endif
#ifdef USE_ZLIB
"zLib "
#endif
#ifdef USE_MPEG2
"MPEG2 "
#endif
#ifdef USE_FLUIDLITE
"FluidLite "
#elif defined(USE_FLUIDSYNTH)
"FluidSynth "
#endif
#ifdef USE_SONIVOX
"EAS "
#endif
#ifdef USE_MIKMOD
"MikMod "
#endif
#ifdef USE_OPENMPT
"OpenMPT "
#endif
#ifdef USE_THEORADEC
"Theora "
#endif
#ifdef USE_VPX
"VPX "
#endif
#ifdef USE_FAAD
"AAC "
#endif
#ifdef USE_A52
"A/52 "
#endif
#ifdef USE_FREETYPE2
"FreeType2 "
#endif
#ifdef USE_FRIBIDI
"FriBiDi "
#endif
#ifdef USE_JPEG
"JPEG "
#endif
#ifdef USE_PNG
"PNG "
#endif
#ifdef USE_GIF
"GIF "
#endif
#ifdef ENABLE_VKEYBD
"VirtualKeyboard "
#endif
#ifdef ENABLE_EVENTRECORDER
"EventRecorder "
#endif
#ifdef USE_TASKBAR
"taskbar "
#endif
#ifdef USE_TTS
"TTS "
#endif
#ifdef USE_CLOUD
"cloud "
#endif
#ifdef USE_LIBCURL
"libcurl "
#endif
#ifdef USE_SDL_NET
"SDL_net "
#endif
#ifdef USE_ENET
"ENet "
#endif
#ifdef SDL_BACKEND
# ifdef USE_SDL2
"SDL2 "
# else
"SDL1.2 "
# endif
#endif
#ifdef USE_TINYGL
"TinyGL "
#endif
#ifdef USE_OPENGL
"OpenGL "
# ifdef USE_OPENGL_SHADERS
"(with shaders) "
# endif
#endif
#ifdef USE_GLES_MODE
# if USE_GLES_MODE == 0
"OpenGL desktop only "
# elif USE_GLES_MODE == 1
"OpenGL ES 1 only "
# elif USE_GLES_MODE == 2
"OpenGL ES 2 only "
# endif
#endif
#ifdef USE_RETROWAVE
"RetroWave "
#endif
;

32
base/version.h Normal file
View File

@@ -0,0 +1,32 @@
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef BASE_VERSION_H
#define BASE_VERSION_H
extern const char gScummVMVersion[]; // e.g. "0.4.1"
extern const char gScummVMBuildDate[]; // e.g. "2003-06-24"
extern const char gScummVMVersionDate[]; // e.g. "0.4.1 (2003-06-24)"
extern const char gScummVMCompiler[]; // e.g. "GCC 11.2.0"
extern const char gScummVMFullVersion[]; // e.g. "ScummVM 0.4.1 (2003-06-24)"
extern const char gScummVMFeatures[]; // e.g. "ALSA MPEG2 zLib"
#endif