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

View File

@@ -0,0 +1,653 @@
/* 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 "backends/imgui/IconsMaterialSymbols.h"
#include "graphics/macgui/mactext.h"
#include "image/png.h"
#include "director/director.h"
#include "director/lingo/lingodec/context.h"
#include "director/lingo/lingodec/script.h"
#include "director/cast.h"
#include "director/castmember/bitmap.h"
#include "director/castmember/shape.h"
#include "director/castmember/text.h"
#include "director/debugger.h"
#include "director/movie.h"
#include "director/window.h"
#include "director/score.h"
#include "director/channel.h"
#include "director/picture.h"
#include "director/debugger/debugtools.h"
#include "director/debugger/dt-internal.h"
namespace Director {
namespace DT {
ImGuiState *_state = nullptr;
const LingoDec::Handler *getHandler(const Cast *cast, CastMemberID id, const Common::String &handlerId) {
if (!cast)
return nullptr;
const ScriptContext *ctx = cast->_lingoArchive->findScriptContext(id.member);
if (!ctx || !ctx->_functionHandlers.contains(handlerId))
return nullptr;
// for the moment it's happening with Director version < 4
if (!cast->_lingodec)
return nullptr;
for (auto p : cast->_lingodec->scripts) {
if (cast->getCastIdByScriptId(p.first) != id.member)
continue;
for (const LingoDec::Handler &handler : p.second->handlers) {
if (handler.name == handlerId) {
return &handler;
}
}
for (const LingoDec::Script *factoryScript : p.second->factories) {
for (const LingoDec::Handler &handler : factoryScript->handlers) {
if (handler.name == handlerId) {
return &handler;
}
}
}
}
return nullptr;
}
const LingoDec::Handler *getHandler(CastMemberID id, const Common::String &handlerId) {
const Director::Movie *movie = g_director->getCurrentMovie();
const Cast *cast = movie->getCasts()->getVal(id.castLib);
const LingoDec::Handler *handler = getHandler(cast, id, handlerId);
if (handler)
return handler;
return getHandler(movie->getSharedCast(), id, handlerId);
}
ImGuiScript toImGuiScript(ScriptType scriptType, CastMemberID id, const Common::String &handlerId) {
ImGuiScript result;
result.id = id;
result.handlerId = handlerId;
result.type = scriptType;
const LingoDec::Handler *handler = getHandler(id, handlerId);
if (!handler) {
const ScriptContext *ctx;
if (id.castLib == SHARED_CAST_LIB) {
ctx = g_director->getCurrentMovie()->getSharedCast()->_lingoArchive->getScriptContext(scriptType, id.member);
} else {
ctx = g_director->getCurrentMovie()->getScriptContext(scriptType, id);
}
if (!ctx) return result;
result.oldAst = ctx->_assemblyAST;
return result;
}
result.bytecodeArray = handler->bytecodeArray;
result.root = handler->ast.root;
result.isGenericEvent = handler->isGenericEvent;
result.argumentNames = handler->argumentNames;
result.propertyNames = handler->script->propertyNames;
result.globalNames = handler->globalNames;
LingoDec::Script *script = handler->script;
if (!script)
return result;
result.isMethod = script->isFactory();
return result;
}
ScriptContext *getScriptContext(CastMemberID id) {
const Director::Movie *movie = g_director->getCurrentMovie();;
const Cast *cast = movie->getCasts()->getVal(id.castLib);
if (!cast) {
return nullptr;
}
ScriptContext *ctx = cast->_lingoArchive->findScriptContext(id.member);
return ctx;
}
ScriptContext *getScriptContext(uint32 nameIndex, CastMemberID id, Common::String handlerName) {
Movie *movie = g_director->getCurrentMovie();
Cast *cast = movie->getCasts()->getVal(id.castLib);
// If the name at nameIndex is not the same as handler name, means its a local script (in the same Lscr resource)
if (cast && cast->_lingoArchive->names[nameIndex] != handlerName) {
return cast->_lingoArchive->findScriptContext(id.member);
}
for (auto it : cast->_lingoArchive->scriptContexts[kMovieScript]) {
if (it._value->_functionHandlers.contains(handlerName)) {
return it._value;
}
}
return nullptr;
}
Director::Breakpoint *getBreakpoint(const Common::String &handlerName, uint16 scriptId, uint pc) {
auto &bps = g_lingo->getBreakpoints();
for (uint i = 0; i < bps.size(); i++) {
if (bps[i].type == kBreakpointFunction && bps[i].scriptId == scriptId && bps[i].funcName == handlerName && bps[i].funcOffset == pc) {
return &bps[i];
}
}
return nullptr;
}
ImGuiImage getImageID(CastMember *castMember) {
if (castMember->_type != CastType::kCastBitmap) {
return {};
}
BitmapCastMember *bmpMember = (BitmapCastMember *)castMember;
if (_state->_cast._textures.contains(bmpMember)) {
return _state->_cast._textures[bmpMember];
}
bmpMember->load();
Picture *pic = bmpMember->_picture;
if (!pic)
return {};
ImTextureID textureID = (ImTextureID)(intptr_t)g_system->getImGuiTexture(pic->_surface, pic->_palette, pic->_paletteColors);
_state->_cast._textures[bmpMember] = {textureID, pic->_surface.w, pic->_surface.h};
return _state->_cast._textures[bmpMember];
}
static void setToolTipImage(const ImGuiImage &image, const char *name) {
if (ImGui::IsItemHovered() && ImGui::BeginTooltip()) {
ImGui::Text("%s", name);
ImGui::Image(image.id, ImVec2(image.width, image.height), ImVec2(0, 0), ImVec2(1, 1), ImVec4(1, 1, 1, 1), ImVec4(1, 1, 1, 1));
ImGui::EndTooltip();
}
}
void showImage(const ImGuiImage &image, const char *name, float thumbnailSize) {
ImVec2 size;
if (image.width > image.height) {
size = {thumbnailSize - 2, (thumbnailSize - 2) * image.height / image.width};
} else {
size = {(thumbnailSize - 2) * image.width / image.height, thumbnailSize - 2};
}
ImGui::BeginGroup();
ImVec2 screenPos = ImGui::GetCursorScreenPos();
ImGui::GetWindowDrawList()->AddRect(screenPos, screenPos + ImVec2(thumbnailSize, thumbnailSize), 0xFFFFFFFF);
ImVec2 pos = ImGui::GetCursorPos();
// Reserve the space of area thumbnailSize * thumbnailSize to make sure the column stretches properly
ImGui::Dummy(ImVec2(thumbnailSize, thumbnailSize));
ImVec2 imgPos = pos + ImVec2(1 + (thumbnailSize - 2 - size.x) * 0.5f, 1 + (thumbnailSize - 2 - size.y) * 0.5f);
ImGui::SetCursorPos(imgPos);
ImGui::Image(image.id, size);
ImGui::EndGroup();
setToolTipImage(image, name);
}
ImGuiImage getShapeID(CastMember *castMember) {
if (castMember->_type != CastType::kCastShape) {
return {};
}
if (_state->_cast._textures.contains(castMember)) {
return _state->_cast._textures[castMember];
}
ShapeCastMember *shapeMember = (ShapeCastMember *)castMember;
// Make a temporary Sprite
Sprite *sprite = new Sprite();
sprite->_movie = g_director->getCurrentMovie();
sprite->setCast(CastMemberID(castMember->getID(), castMember->getCast()->_castLibID));
sprite->_ink = shapeMember->_ink;
sprite->_backColor = shapeMember->getBackColor();
sprite->_foreColor = shapeMember->getForeColor();
sprite->_pattern = shapeMember->_pattern;
sprite->_thickness = shapeMember->_lineThickness;
// Make a temporary channel to blit the shape from
Channel *channel = new Channel(nullptr, sprite);
Common::Rect bbox(castMember->getBbox());
// Manually set the bbox of the channel to the bbox of cast member
// Even though the BBox of the channel and cast member are the same, the channel's bbox is offset to a non zero origin
// Depending upon the position of the sprite in the window
channel->setBbox(bbox.left, bbox.top, bbox.right, bbox.bottom);
Graphics::ManagedSurface *managedSurface = new Graphics::ManagedSurface(bbox.width(), bbox.height(), g_director->_pixelformat);
Window::inkBlitFrom(channel, bbox, managedSurface);
Graphics::Surface surface = managedSurface->rawSurface();
if (debugChannelSet(8, kDebugImages)) {
Common::String prepend = "shape";
Common::String filename = Common::String::format("./dumps/%s-%s-%d.png", g_director->getCurrentMovie()->getMacName().c_str(), encodePathForDump(prepend).c_str(), castMember->getID());
Common::DumpFile bitmapFile;
bitmapFile.open(Common::Path(filename), true);
Image::writePNG(bitmapFile, surface, g_director->getPalette());
bitmapFile.close();
}
ImTextureID textureID = (ImTextureID)(intptr_t)g_system->getImGuiTexture(surface, g_director->getPalette(), g_director->getPaletteColorCount());
delete managedSurface;
delete sprite;
delete channel;
int16 width = surface.w, height = surface.h;
_state->_cast._textures[castMember] = {textureID, width, height};
return _state->_cast._textures[castMember];
}
ImGuiImage getTextID(CastMember *castMember) {
if (castMember->_type != CastType::kCastText && castMember->_type != CastType::kCastButton && castMember->_type != CastType::kCastRichText) {
return {};
}
if (_state->_cast._textures.contains(castMember)) {
return _state->_cast._textures[castMember];
}
Common::Rect bbox(castMember->getBbox());
// Make a temporary Sprite
Sprite *sprite = new Sprite();
sprite->_spriteType = kTextSprite;
sprite->_movie = g_director->getCurrentMovie();
sprite->setCast(CastMemberID(castMember->getID(), castMember->getCast()->_castLibID));
sprite->_backColor = castMember->getBackColor();
sprite->_foreColor = castMember->getForeColor();
sprite->_editable = false;
// Make a temporary channel to blit the shape from
Channel *channel = new Channel(nullptr, sprite);
Graphics::MacWidget *widget = castMember->createWidget(bbox, channel, kTextSprite);
Graphics::Surface surface;
surface.copyFrom(*widget->getSurface());
if (debugChannelSet(8, kDebugImages)) {
Common::String prepend = "text";
Common::String filename = Common::String::format("./dumps/%s-%s-%d.png", g_director->getCurrentMovie()->getMacName().c_str(), encodePathForDump(prepend).c_str(), castMember->getID());
Common::DumpFile bitmapFile;
bitmapFile.open(Common::Path(filename), true);
Image::writePNG(bitmapFile, surface, g_director->getPalette());
bitmapFile.close();
}
ImTextureID textureID = (ImTextureID)(intptr_t)g_system->getImGuiTexture(surface, g_director->getPalette(), g_director->getPaletteColorCount());
int16 width = surface.w, height = surface.h;
surface.free();
delete widget;
delete sprite;
delete channel;
_state->_cast._textures[castMember] = {textureID, width, height};
return _state->_cast._textures[castMember];
}
void displayVariable(const Common::String &name, bool changed, bool outOfScope) {
ImU32 var_color = ImGui::GetColorU32(_state->_colors._var_ref);
ImU32 color;
color = ImGui::GetColorU32(_state->_colors._bp_color_disabled);
if (_state->_variables.contains(name))
color = ImGui::GetColorU32(_state->_colors._bp_color_enabled);
ImDrawList *dl = ImGui::GetWindowDrawList();
ImVec2 pos = ImGui::GetCursorScreenPos();
ImVec2 eyeSize = ImGui::CalcTextSize(ICON_MS_VISIBILITY " ");
ImVec2 textSize = ImGui::CalcTextSize(name.c_str());
ImGui::InvisibleButton("Line", ImVec2(textSize.x + eyeSize.x, textSize.y));
if (ImGui::IsItemClicked(0)) {
if (color == ImGui::GetColorU32(_state->_colors._bp_color_enabled)) {
_state->_variables.erase(name);
color = ImGui::GetColorU32(_state->_colors._bp_color_disabled);
} else {
_state->_variables[name] = true;
color = ImGui::GetColorU32(_state->_colors._bp_color_enabled);
}
}
if (changed) {
var_color = ImGui::GetColorU32(_state->_colors._var_ref_changed);
} else if (outOfScope) {
var_color = ImGui::GetColorU32(_state->_colors._var_ref_out_of_scope);
}
if (color == ImGui::GetColorU32(_state->_colors._bp_color_disabled) && ImGui::IsItemHovered()) {
color = ImGui::GetColorU32(_state->_colors._bp_color_hover);
}
dl->AddText(pos, color, ICON_MS_VISIBILITY " ");
dl->AddText(ImVec2(pos.x + eyeSize.x, pos.y), var_color, name.c_str());
}
ImVec4 convertColor(uint32 color) {
if (g_director->_colorDepth <= 8) {
float r = g_director->getPalette()[color * 3 + 0] * 1.0 / 255.0;
float g = g_director->getPalette()[color * 3 + 1] * 1.0 / 255.0;
float b = g_director->getPalette()[color * 3 + 2] * 1.0 / 255.0;
return ImVec4(r, g, b, 1.0);
}
return ImGui::ColorConvertU32ToFloat4(color);
}
static void addScriptCastToDisplay(CastMemberID &id) {
_state->_scriptCasts.remove(id);
_state->_scriptCasts.push_back(id);
}
void setScriptToDisplay(const ImGuiScript &script) {
ScriptData *scriptData = &_state->_functions._windowScriptData.getOrCreateVal(g_director->getCurrentWindow());
uint index = scriptData->_scripts.size();
if (index && scriptData->_scripts[index - 1] == script) {
scriptData->_showScript = true;
return;
}
scriptData->_scripts.push_back(script);
scriptData->_current = index;
scriptData->_showScript = true;
_state->_dbg._scrollToPC = true;
}
void displayScriptRef(CastMemberID &scriptId) {
if (scriptId.member) {
ImGui::TextColored(_state->_colors._script_ref, "%d", scriptId.member);
ImGui::SetItemTooltip(scriptId.asString().c_str());
if (ImGui::IsItemClicked(0))
addScriptCastToDisplay(scriptId);
} else {
ImGui::Selectable(" ");
}
}
ImColor brightenColor(const ImColor& color, float factor) {
ImVec4 col = color.Value;
col.x = CLIP<float>(col.x * factor, 0.0f, 1.0f);
col.y = CLIP<float>(col.y * factor, 0.0f, 1.0f);
col.z = CLIP<float>(col.z * factor, 0.0f, 1.0f);
return ImColor(col);
}
Window *windowListCombo(Common::String *target) {
const Common::Array<Window *> *windowList = g_director->getWindowList();
const Common::String selWin = *target;
Window *res = nullptr;
Common::String stage = g_director->getStage()->getCurrentMovie()->getMacName();
// Check if the relevant window is gone
bool found = false;
for (auto window : (*windowList)) {
if (window->getCurrentMovie()->getMacName() == selWin) {
// Found the selected window
found = true;
res = window;
break;
}
}
// Our default is Stage
if (selWin.empty() || windowList->empty() || !found) {
*target = stage;
res = g_director->getStage();
}
ImGui::Text("Window:");
ImGui::SameLine();
if (ImGui::BeginCombo("##window", selWin.c_str())) {
bool selected = (*target == stage);
if (ImGui::Selectable(stage.c_str(), selected))
*target = stage;
if (selected) {
ImGui::SetItemDefaultFocus();
res = g_director->getStage();
}
for (auto window : (*windowList)) {
Common::String winName = window->getCurrentMovie()->getMacName();
selected = (*target == winName);
if (ImGui::Selectable(winName.c_str(), selected)) {
*target = winName;
res = window;
}
if (selected) {
ImGui::SetItemDefaultFocus();
res = window;
}
}
ImGui::EndCombo();
}
return res;
}
static void showSettings() {
if (!_state->_w.settings)
return;
ImGui::SetNextWindowPos(ImVec2(20, 20), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(480, 240), ImGuiCond_FirstUseEver);
if (ImGui::Begin("Settings", &_state->_w.settings)) {
ImGui::ColorEdit4("Breakpoint disabled", &_state->_colors._bp_color_disabled.x);
ImGui::ColorEdit4("Breakpoint enabled", &_state->_colors._bp_color_enabled.x);
ImGui::ColorEdit4("Breakpoint hover", &_state->_colors._bp_color_hover.x);
ImGui::ColorEdit4("Channel toggle", &_state->_colors._channel_toggle.x);
ImGui::SeparatorText("Lingo syntax");
ImGui::ColorEdit4("Line", &_state->_colors._line_color.x);
ImGui::ColorEdit4("Call", &_state->_colors._call_color.x);
ImGui::ColorEdit4("Builtin", &_state->_colors._builtin_color.x);
ImGui::ColorEdit4("Variable", &_state->_colors._var_color.x);
ImGui::ColorEdit4("Literal", &_state->_colors._literal_color.x);
ImGui::ColorEdit4("Comment", &_state->_colors._comment_color.x);
ImGui::ColorEdit4("Type", &_state->_colors._type_color.x);
ImGui::ColorEdit4("Keyword", &_state->_colors._keyword_color.x);
ImGui::ColorEdit4("The entity", &_state->_colors._the_color.x);
ImGui::SeparatorText("References");
ImGui::ColorEdit4("Script", &_state->_colors._script_ref.x);
ImGui::ColorEdit4("Variable", &_state->_colors._var_ref.x);
ImGui::ColorEdit4("Variable changed", &_state->_colors._var_ref_changed.x);
_state->_logger->drawColorOptions();
}
ImGui::End();
}
void onLog(LogMessageType::Type type, int level, uint32 debugChannel, const char *message) {
switch (type) {
case LogMessageType::kError:
_state->_logger->addLog("[error]%s", message);
break;
case LogMessageType::kWarning:
_state->_logger->addLog("[warn]%s", message);
break;
case LogMessageType::kInfo:
_state->_logger->addLog("%s", message);
break;
case LogMessageType::kDebug:
_state->_logger->addLog("[debug]%s", message);
break;
}
}
void onImGuiInit() {
ImGuiIO &io = ImGui::GetIO();
io.Fonts->AddFontDefault();
ImFontConfig icons_config;
icons_config.MergeMode = true;
icons_config.PixelSnapH = false;
icons_config.OversampleH = 3;
icons_config.OversampleV = 3;
icons_config.GlyphOffset = {0, 4};
static const ImWchar icons_ranges[] = {ICON_MIN_MS, ICON_MAX_MS, 0};
io.FontDefault = ImGui::addTTFFontFromArchive("MaterialSymbolsSharp.ttf", 16.f, &icons_config, icons_ranges);
_state = new ImGuiState();
_state->_tinyFont = ImGui::addTTFFontFromArchive("LiberationSans-Regular.ttf", 10.0f, nullptr, nullptr);
_state->_archive.memEdit.ReadOnly = true;
_state->_logger = new ImGuiEx::ImGuiLogger;
Common::setLogWatcher(onLog);
}
void onImGuiRender() {
if (!debugChannelSet(-1, kDebugImGui)) {
ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange | ImGuiConfigFlags_NoMouse;
return;
}
if (!_state)
return;
ImGuiIO &io = ImGui::GetIO();
io.ConfigFlags &= ~(ImGuiConfigFlags_NoMouseCursorChange | ImGuiConfigFlags_NoMouse);
ImGui::DockSpaceOverViewport(0, ImGui::GetMainViewport(), ImGuiDockNodeFlags_PassthruCentralNode);
if (ImGui::BeginMainMenuBar()) {
if (ImGui::BeginMenu("View")) {
ImGui::SeparatorText("Windows");
if (ImGui::MenuItem("View All")) {
if (_state->_wasHidden)
_state->_w = _state->_savedW;
_state->_wasHidden = false;
}
if (ImGui::MenuItem("Hide All")) {
if (!_state->_wasHidden) {
_state->_savedW = _state->_w;
memset((void *)&_state->_w, 0, sizeof(_state->_w));
}
_state->_wasHidden = true;
}
ImGui::MenuItem("Control Panel", NULL, &_state->_w.controlPanel);
ImGui::MenuItem("Score", NULL, &_state->_w.score);
ImGui::MenuItem("Functions", NULL, &_state->_w.funcList);
ImGui::MenuItem("Cast", NULL, &_state->_w.cast);
ImGui::MenuItem("Channels", NULL, &_state->_w.channels);
ImGui::MenuItem("Breakpoints", NULL, &_state->_w.bpList);
ImGui::MenuItem("Vars", NULL, &_state->_w.vars);
ImGui::MenuItem("Watched Vars", NULL, &_state->_w.watchedVars);
ImGui::MenuItem("Logger", NULL, &_state->_w.logger);
ImGui::MenuItem("Archive", NULL, &_state->_w.archive);
ImGui::MenuItem("Execution Context", NULL, &_state->_w.executionContext);
ImGui::SeparatorText("Misc");
if (ImGui::MenuItem("Save state")) {
saveCurrentState();
}
if (ImGui::MenuItem("Load state")) {
loadSavedState();
}
ImGui::Separator();
ImGui::MenuItem("Settings", NULL, &_state->_w.settings);
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
showScriptCasts();
showExecutionContext();
showHandlers();
showControlPanel();
showVars();
showChannels();
showCast();
showFuncList();
showScore();
showBreakpointList();
showSettings();
showArchive();
showWatchedVars();
_state->_logger->draw("Logger", &_state->_w.logger);
}
void onImGuiCleanup() {
Common::setLogWatcher(nullptr);
if (_state) {
free(_state->_archive.data);
delete _state->_logger;
}
delete _state;
_state = nullptr;
}
int getSelectedChannel(){
return _state ? _state->_selectedChannel : -1;
}
Common::String formatHandlerName(int scriptId, int castId, Common::String handlerName, ScriptType scriptType, bool childScript) {
Common::String formatted = Common::String();
// Naming convention: <script id> (<cast id/cast id of parent script>): name of handler: script type
if (childScript) {
formatted = Common::String::format("%d (p<%d>):%s :%s", scriptId, castId, handlerName.size() ? handlerName.c_str() : "<unnamed>", scriptType2str(scriptType));
} else {
formatted = Common::String::format("%d (%d) :%s :%s", scriptId, castId, handlerName.size() ? handlerName.c_str() : "<unnamed>", scriptType2str(scriptType));
}
return formatted;
}
} // namespace DT
} // namespace Director

View File

@@ -0,0 +1,34 @@
/* 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 DIRECTOR_DEBUGTOOLS_H
#define DIRECTOR_DEBUGTOOLS_H
namespace Director {
namespace DT {
void onImGuiInit();
void onImGuiRender();
void onImGuiCleanup();
int getSelectedChannel();
} // namespace DT
} // namespace Director
#endif

View File

@@ -0,0 +1,339 @@
/* 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 "backends/imgui/IconsMaterialSymbols.h"
#include "backends/imgui/imgui_utils.h"
#include "director/director.h"
#include "director/debugger/dt-internal.h"
#include "director/cast.h"
#include "director/castmember/bitmap.h"
#include "director/castmember/text.h"
#include "director/castmember/shape.h"
#include "director/castmember/richtext.h"
#include "director/castmember/script.h"
#include "director/movie.h"
#include "director/types.h"
#include "director/window.h"
namespace Director {
namespace DT {
static const char *toString(ScriptType scriptType) {
static const char *scriptTypes[] = {
"Score",
"Cast",
"Movie",
"Event",
"Test",
"???",
"???",
"Parent",
};
if (scriptType < 0 || scriptType > kMaxScriptType)
return "???";
return scriptTypes[(int)scriptType];
}
static const char *toIcon(CastType castType) {
static const char *castTypes[] = {
"", // Empty
ICON_MS_BACKGROUND_DOT_LARGE, // Bitmap
ICON_MS_THEATERS, // FilmLoop
ICON_MS_MATCH_CASE, // Text
ICON_MS_PALETTE, // Palette
ICON_MS_IMAGESMODE, // Picture
ICON_MS_VOLUME_UP, // Sound
ICON_MS_SLAB_SERIF, // Button
ICON_MS_SHAPES, // Shape
ICON_MS_MOVIE, // Movie
ICON_MS_ANIMATED_IMAGES, // DigitalVideo
ICON_MS_FORMS_APPS_SCRIPT, // Script
ICON_MS_BRAND_FAMILY, // RTE
"?", // ???
ICON_MS_TRANSITION_FADE}; // Transition
if (castType < 0 || castType > kCastTransition)
return "";
return castTypes[(int)castType];
}
const char *toString(CastType castType) {
static const char *castTypes[] = {
"Empty",
"Bitmap",
"FilmLoop",
"Text",
"Palette",
"Picture",
"Sound",
"Button",
"Shape",
"Movie",
"DigitalVideo",
"Script",
"RTE",
"???",
"Transition"};
if (castType < 0 || castType > kCastTransition)
return "???";
return castTypes[(int)castType];
}
Common::String getDisplayName(CastMember *castMember) {
const CastMemberInfo *castMemberInfo = castMember->getInfo();
Common::String name(castMemberInfo ? castMemberInfo->name : "");
if (!name.empty())
return name;
if (castMember->_type == kCastText) {
TextCastMember *textCastMember = (TextCastMember *)castMember;
return textCastMember->getText();
}
return Common::String::format("%u", castMember->getID());
}
void showCast() {
if (!_state->_w.cast)
return;
ImGui::SetNextWindowPos(ImVec2(20, 160), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(480, 480), ImGuiCond_FirstUseEver);
if (ImGui::Begin("Cast", &_state->_w.cast)) {
Window *selectedWindow = windowListCombo(&_state->_castWindow);
// display a toolbar with: grid/list/filters buttons + name filter
ImGuiEx::toggleButton(ICON_MS_LIST, &_state->_cast._listView);
ImGui::SetItemTooltip("List");
ImGui::SameLine();
ImGuiEx::toggleButton(ICON_MS_GRID_VIEW, &_state->_cast._listView, true);
ImGui::SetItemTooltip("Grid");
ImGui::SameLine();
if (ImGui::Button(ICON_MS_FILTER_ALT)) {
ImGui::OpenPopup("filters_popup");
}
ImGui::SameLine();
if (ImGui::BeginPopup("filters_popup")) {
ImGui::CheckboxFlags("All", &_state->_cast._typeFilter, 0x7FFF);
ImGui::Separator();
for (int i = 0; i <= 14; i++) {
ImGui::PushID(i);
Common::String option(Common::String::format("%s %s", toIcon((CastType)i), toString((CastType)i)));
ImGui::CheckboxFlags(option.c_str(), &_state->_cast._typeFilter, 1 << i);
ImGui::PopID();
}
ImGui::EndPopup();
}
_state->_cast._nameFilter.Draw();
ImGui::Separator();
// display a list or a grid
const float sliderHeight = _state->_cast._listView ? 0.f : 38.f;
const ImVec2 childsize = ImGui::GetContentRegionAvail();
Movie *movie = selectedWindow->getCurrentMovie();
ImGui::BeginChild("##cast", ImVec2(childsize.x, childsize.y - sliderHeight));
if (_state->_cast._listView) {
if (ImGui::BeginTable("Resources", 5, ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg)) {
ImGui::TableSetupColumn("Name", 0, 120.f);
ImGui::TableSetupColumn("#", 0, 20.f);
ImGui::TableSetupColumn("Script", 0, 80.f);
ImGui::TableSetupColumn("Type", 0, 80.f);
ImGui::TableSetupColumn("Preview", ImGuiTableColumnFlags_WidthStretch, 50.f);
ImGui::TableHeadersRow();
for (auto it : *movie->getCasts()) {
Cast *cast = it._value;
if (!cast->_loadedCast)
continue;
for (auto castMember : *cast->_loadedCast) {
if (!castMember._value->isLoaded())
continue;
Common::String name(getDisplayName(castMember._value));
if (!_state->_cast._nameFilter.PassFilter(name.c_str()))
continue;
if ((castMember._value->_type != kCastTypeAny) && !(_state->_cast._typeFilter & (1 << (int)castMember._value->_type)))
continue;
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::Text("%s %s", toIcon(castMember._value->_type), name.c_str());
ImGui::TableNextColumn();
ImGui::Text("%d", castMember._key);
ImGui::TableNextColumn();
if (castMember._value->_type == CastType::kCastLingoScript) {
ScriptCastMember *scriptMember = (ScriptCastMember *)castMember._value;
ImGui::Text("%s", toString(scriptMember->_scriptType));
}
ImGui::TableNextColumn();
ImGui::Text("%s", toString(castMember._value->_type));
ImGui::TableNextColumn();
float columnWidth = ImGui::GetColumnWidth();
ImGuiImage imgID = {};
switch (castMember._value->_type) {
case kCastBitmap:
{
imgID = getImageID(castMember._value);
if (imgID.id) {
float offsetX = (columnWidth - 32.f) * 0.5f;
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + offsetX);
showImage(imgID, name.c_str(), 32.f);
}
}
break;
case kCastText:
case kCastRichText:
case kCastButton:
{
imgID = getTextID(castMember._value);
if (imgID.id) {
float offsetX = (columnWidth - 32.f) * 0.5f;
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + offsetX);
showImage(imgID, name.c_str(), 32.f);
}
}
break;
case kCastShape:
{
imgID = getShapeID(castMember._value);
if (imgID.id) {
float offsetX = (columnWidth - 32.f) * 0.5f;
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + offsetX);
showImage(imgID, name.c_str(), 32.f);
}
}
break;
default:
break;
}
}
}
ImGui::EndTable();
}
} else {
const float thumbnailSize = (float)_state->_cast._thumbnailSize;
const float contentWidth = ImGui::GetContentRegionAvail().x;
int columns = contentWidth / (thumbnailSize + 8.f);
columns = columns < 1 ? 1 : columns;
if (ImGui::BeginTable("Cast", columns)) {
for (auto it : *movie->getCasts()) {
const Cast *cast = it._value;
if (!cast->_loadedCast)
continue;
for (auto castMember : *cast->_loadedCast) {
if (!castMember._value->isLoaded())
continue;
Common::String name(getDisplayName(castMember._value));
if (!_state->_cast._nameFilter.PassFilter(name.c_str()))
continue;
if ((castMember._value->_type != kCastTypeAny) && !(_state->_cast._typeFilter & (1 << (int)castMember._value->_type)))
continue;
ImGui::TableNextColumn();
ImGui::BeginGroup();
const ImVec2 textSize = ImGui::CalcTextSize(name.c_str());
float textWidth = textSize.x;
float textHeight = textSize.y;
if (textWidth > thumbnailSize) {
textWidth = thumbnailSize;
textHeight *= (textSize.x / textWidth);
}
ImGuiImage imgID = {};
switch (castMember._value->_type) {
case kCastBitmap:
{
imgID = getImageID(castMember._value);
if (imgID.id) {
showImage(imgID, name.c_str(), thumbnailSize);
}
}
break;
case kCastText:
case kCastRichText:
case kCastButton:
{
imgID = getTextID(castMember._value);
if (imgID.id) {
showImage(imgID, name.c_str(), thumbnailSize);
}
}
break;
case kCastShape:
{
imgID = getShapeID(castMember._value);
if (imgID.id) {
showImage(imgID, name.c_str(), thumbnailSize);
}
}
break;
default:
break;
}
if (!imgID.id) {
ImGui::PushID(castMember._key);
ImGui::InvisibleButton("##canvas", ImVec2(thumbnailSize, thumbnailSize));
ImGui::PopID();
const ImVec2 p0 = ImGui::GetItemRectMin();
const ImVec2 p1 = ImGui::GetItemRectMax();
ImGui::PushClipRect(p0, p1, true);
ImDrawList *draw_list = ImGui::GetWindowDrawList();
draw_list->AddRect(p0, p1, IM_COL32_WHITE);
const ImVec2 pos = p0 + ImVec2((thumbnailSize - textWidth) * 0.5f, (thumbnailSize - textHeight) * 0.5f);
draw_list->AddText(nullptr, 0.f, pos, IM_COL32_WHITE, name.c_str(), 0, thumbnailSize);
draw_list->AddText(nullptr, 0.f, p1 - ImVec2(16, 16), IM_COL32_WHITE, toIcon(castMember._value->_type));
ImGui::PopClipRect();
}
ImGui::EndGroup();
}
}
ImGui::EndTable();
}
}
ImGui::EndChild();
// in the footer display a slider for the grid view: thumbnail size
if (!_state->_cast._listView) {
ImGui::Spacing();
ImGui::Separator();
ImGui::Spacing();
ImGui::SliderInt("Thumbnail Size", &_state->_cast._thumbnailSize, 32, 256);
}
}
ImGui::End();
}
} // namespace DT
} // namespace Director

View File

@@ -0,0 +1,356 @@
/* 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 "director/director.h"
#include "director/debugger/dt-internal.h"
#include "director/archive.h"
#include "director/movie.h"
#include "director/window.h"
#include "director/score.h"
namespace Director {
namespace DT {
static uint32 getLineFromPC() {
ScriptData *scriptData = &_state->_functions._windowScriptData.getOrCreateVal(g_director->getCurrentWindow());
const uint pc = g_lingo->_state->pc;
if (scriptData->_scripts.empty())
return 0;
const Common::Array<uint> &offsets = scriptData->_scripts[scriptData->_current].startOffsets;
for (uint i = 0; i < offsets.size(); i++) {
if (pc <= offsets[i])
return i;
}
return 0;
}
static bool stepOverShouldPauseDebugger() {
const uint32 line = getLineFromPC();
// we stop when we are :
// - in the same callstack level and the statement line is different
// - OR we go up in the callstack
if (((g_lingo->_state->callstack.size() == _state->_dbg._callstackSize) && (line != _state->_dbg._lastLinePC)) ||
(g_lingo->_state->callstack.size() < _state->_dbg._callstackSize)) {
_state->_dbg._lastLinePC = line;
_state->_dbg._isScriptDirty = true;
return true;
}
return false;
}
static bool stepInShouldPauseDebugger() {
const uint32 line = getLineFromPC();
// we stop when:
// - the statement line is different
// - OR when the callstack level change
if ((g_lingo->_state->callstack.size() != _state->_dbg._callstackSize) || (_state->_dbg._lastLinePC != line)) {
_state->_dbg._lastLinePC = line;
_state->_dbg._isScriptDirty = true;
return true;
}
return false;
}
static bool stepOutShouldPause() {
const uint32 line = getLineFromPC();
// we stop when:
// - OR we go up in the callstack
if (g_lingo->_state->callstack.size() < _state->_dbg._callstackSize) {
_state->_dbg._lastLinePC = line;
_state->_dbg._isScriptDirty = true;
return true;
}
return false;
}
static void dgbStop() {
g_lingo->_exec._state = kPause;
g_lingo->_exec._shouldPause = nullptr;
_state->_dbg._isScriptDirty = true;
}
static void dbgStepOver() {
g_lingo->_exec._state = kRunning;
_state->_dbg._lastLinePC = getLineFromPC();
_state->_dbg._callstackSize = g_lingo->_state->callstack.size();
g_lingo->_exec._shouldPause = stepOverShouldPauseDebugger;
_state->_dbg._isScriptDirty = true;
}
static void dbgStepInto() {
g_lingo->_exec._state = kRunning;
_state->_dbg._lastLinePC = getLineFromPC();
_state->_dbg._callstackSize = g_lingo->_state->callstack.size();
g_lingo->_exec._shouldPause = stepInShouldPauseDebugger;
_state->_dbg._isScriptDirty = true;
}
static void dbgStepOut() {
g_lingo->_exec._state = kRunning;
_state->_dbg._lastLinePC = getLineFromPC();
_state->_dbg._callstackSize = g_lingo->_state->callstack.size();
g_lingo->_exec._shouldPause = stepOutShouldPause;
_state->_dbg._isScriptDirty = true;
}
void showControlPanel() {
if (!_state->_w.controlPanel)
return;
ImVec2 vp(ImGui::GetMainViewport()->Size);
ImGui::SetNextWindowPos(ImVec2(vp.x - 220.0f, 20.0f), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(200, 103), ImGuiCond_FirstUseEver);
if (ImGui::Begin("Control Panel", &_state->_w.controlPanel, ImGuiWindowFlags_NoDocking)) {
Movie *movie = g_director->getCurrentMovie();
Score *score = movie->getScore();
ImDrawList *dl = ImGui::GetWindowDrawList();
ImU32 color = ImGui::GetColorU32(ImVec4(0.8f, 0.8f, 0.8f, 1.0f));
ImU32 color_red = ImGui::GetColorU32(ImVec4(1.0f, 0.6f, 0.6f, 1.0f));
ImU32 active_color = ImGui::GetColorU32(ImVec4(1.0f, 1.0f, 0.4f, 1.0f));
ImU32 bgcolor = ImGui::GetColorU32(ImVec4(0.2f, 0.2f, 1.0f, 1.0f));
ImVec2 p = ImGui::GetCursorScreenPos();
ImVec2 buttonSize(20, 14);
float bgX1 = -4.0f, bgX2 = 21.0f;
int frameNum = score->getCurrentFrameNum();
if (_state->_prevFrame != -1 && _state->_prevFrame != frameNum) {
score->_playState = kPlayPaused;
_state->_prevFrame = -1;
}
{ // Rewind
ImGui::InvisibleButton("Rewind", buttonSize);
if (ImGui::IsItemClicked(0)) {
score->_playState = kPlayStarted;
score->setCurrentFrame(1);
}
if (ImGui::IsItemHovered())
dl->AddRectFilled(ImVec2(p.x + bgX1, p.y + bgX1), ImVec2(p.x + bgX2, p.y + bgX2), bgcolor, 3.0f, ImDrawFlags_RoundCornersAll);
dl->AddTriangleFilled(ImVec2(p.x, p.y + 8), ImVec2(p.x + 8, p.y), ImVec2(p.x + 8, p.y + 16), color);
dl->AddTriangleFilled(ImVec2(p.x + 8, p.y + 8), ImVec2(p.x + 16, p.y), ImVec2(p.x + 16, p.y + 16), color);
ImGui::SetItemTooltip("Rewind");
ImGui::SameLine();
}
{ // Step Back
p = ImGui::GetCursorScreenPos();
ImGui::InvisibleButton("Step Back", ImVec2(18, 16));
if (ImGui::IsItemClicked(0)) {
score->_playState = kPlayStarted;
score->setCurrentFrame(frameNum - 1);
_state->_prevFrame = frameNum;
}
if (ImGui::IsItemHovered())
dl->AddRectFilled(ImVec2(p.x + bgX1, p.y + bgX1), ImVec2(p.x + bgX2, p.y + bgX2), bgcolor, 3.0f, ImDrawFlags_RoundCornersAll);
dl->AddTriangleFilled(ImVec2(p.x, p.y + 8), ImVec2(p.x + 9, p.y), ImVec2(p.x + 9, p.y + 16), color);
dl->AddRectFilled(ImVec2(p.x + 11, p.y), ImVec2(p.x + 17, p.y + 16), color);
ImGui::SetItemTooltip("Step Back");
ImGui::SameLine();
}
{ // Stop
p = ImGui::GetCursorScreenPos();
ImGui::InvisibleButton("Stop", buttonSize);
if (ImGui::IsItemClicked(0)) {
score->_playState = kPlayPaused;
g_lingo->_exec._state = kPause;
g_lingo->_exec._shouldPause = nullptr;
_state->_dbg._isScriptDirty = true;
g_system->displayMessageOnOSD(Common::U32String("Paused"));
}
if (ImGui::IsItemHovered())
dl->AddRectFilled(ImVec2(p.x + bgX1, p.y + bgX1), ImVec2(p.x + bgX2, p.y + bgX2), bgcolor, 3.0f, ImDrawFlags_RoundCornersAll);
ImU32 stopColor = (score->_playState == kPlayPaused || score->_playState == kPlayPausedAfterLoading) ? active_color : color;
dl->AddRectFilled(ImVec2(p.x, p.y), ImVec2(p.x + 16, p.y + 16), stopColor);
ImGui::SetItemTooltip("Stop");
ImGui::SameLine();
}
{ // Step
p = ImGui::GetCursorScreenPos();
ImGui::InvisibleButton("Step", buttonSize);
if (ImGui::IsItemClicked(0)) {
score->_playState = kPlayStarted;
score->setCurrentFrame(frameNum + 1);
_state->_prevFrame = frameNum;
}
if (ImGui::IsItemHovered())
dl->AddRectFilled(ImVec2(p.x + bgX1, p.y + bgX1), ImVec2(p.x + bgX2, p.y + bgX2), bgcolor, 3.0f, ImDrawFlags_RoundCornersAll);
dl->AddRectFilled(ImVec2(p.x, p.y), ImVec2(p.x + 6, p.y + 16), color);
dl->AddTriangleFilled(ImVec2(p.x + 8, p.y + 2), ImVec2(p.x + 8, p.y + 14), ImVec2(p.x + 16, p.y + 8), color);
ImGui::SetItemTooltip("Step");
ImGui::SameLine();
}
{ // Play
p = ImGui::GetCursorScreenPos();
ImGui::InvisibleButton("Play", buttonSize);
if (ImGui::IsItemClicked(0)) {
if (score->_playState == kPlayPausedAfterLoading)
score->_playState = kPlayLoaded;
else
score->_playState = kPlayStarted;
g_lingo->_exec._state = kRunning;
g_lingo->_exec._shouldPause = nullptr;
}
if (ImGui::IsItemHovered())
dl->AddRectFilled(ImVec2(p.x + bgX1, p.y + bgX1), ImVec2(p.x + bgX2, p.y + bgX2), bgcolor, 3.0f, ImDrawFlags_RoundCornersAll);
if (score->_playState == kPlayStarted)
color = ImGui::GetColorU32(ImVec4(0.3f, 0.3f, 1.0f, 1.0f));
dl->AddTriangleFilled(ImVec2(p.x, p.y), ImVec2(p.x, p.y + 16), ImVec2(p.x + 14, p.y + 8), color);
ImGui::SetItemTooltip("Play");
ImGui::SameLine();
}
char buf[6];
snprintf(buf, 6, "%d", score->getCurrentFrameNum());
ImGui::SetNextItemWidth(35);
ImGui::InputText("##frame", buf, 5, ImGuiInputTextFlags_CharsDecimal);
ImGui::SetItemTooltip("Frame");
{
ImGui::Separator();
ImGui::TextColored(ImVec4(0.9f, 0.8f, 0.5f, 1.0f), movie->getArchive()->getPathName().toString().c_str());
ImGui::SetItemTooltip(movie->getArchive()->getPathName().toString().c_str());
}
ImGui::Separator();
ImGui::Separator();
ImGui::Text("Lingo:");
ImGui::SameLine();
{ // Step over
p = ImGui::GetCursorScreenPos();
ImGui::InvisibleButton("Step Over", buttonSize);
if (ImGui::IsItemClicked(0)) {
score->_playState = kPlayStarted;
if (g_lingo->_exec._state == kRunning) {
dgbStop();
} else {
dbgStepOver();
}
}
if (ImGui::IsItemHovered())
dl->AddRectFilled(ImVec2(p.x + bgX1, p.y + bgX1), ImVec2(p.x + bgX2, p.y + bgX2), bgcolor, 3.0f, ImDrawFlags_RoundCornersAll);
dl->PathArcToFast(ImVec2(p.x + 9, p.y + 15), 10.0f, 7, 11);
dl->PathStroke(color_red, 0, 2);
dl->AddLine(ImVec2(p.x + 18, p.y + 5), ImVec2(p.x + 18, p.y + 10), color_red, 2);
dl->AddLine(ImVec2(p.x + 14, p.y + 10), ImVec2(p.x + 18, p.y + 10), color_red, 2);
dl->AddCircleFilled(ImVec2(p.x + 9, p.y + 15), 2.0f, color);
ImGui::SetItemTooltip("Step Over");
ImGui::SameLine();
}
{ // Step into
p = ImGui::GetCursorScreenPos();
ImGui::InvisibleButton("Step Into", buttonSize);
if (ImGui::IsItemClicked(0)) {
score->_playState = kPlayStarted;
if (g_lingo->_exec._state == kRunning) {
dgbStop();
} else {
dbgStepInto();
}
}
if (ImGui::IsItemHovered())
dl->AddRectFilled(ImVec2(p.x + bgX1, p.y + bgX1), ImVec2(p.x + bgX2, p.y + bgX2), bgcolor, 3.0f, ImDrawFlags_RoundCornersAll);
dl->AddLine(ImVec2(p.x + 8.5f, p.y + 1), ImVec2(p.x + 8.5f, p.y + 10), color_red, 2);
dl->AddLine(ImVec2(p.x + 5.5f, p.y + 6), ImVec2(p.x + 8.5f, p.y + 9), color_red, 2);
dl->AddLine(ImVec2(p.x + 12, p.y + 6), ImVec2(p.x + 8.5f, p.y + 9), color_red, 2);
dl->AddCircleFilled(ImVec2(p.x + 9, p.y + 15), 2.0f, color);
ImGui::SetItemTooltip("Step Into");
ImGui::SameLine();
}
{ // Step out
p = ImGui::GetCursorScreenPos();
ImGui::InvisibleButton("Step Out", buttonSize);
if (ImGui::IsItemClicked(0)) {
score->_playState = kPlayStarted;
if (g_lingo->_exec._state == kRunning) {
dgbStop();
} else {
dbgStepOut();
}
}
if (ImGui::IsItemHovered())
dl->AddRectFilled(ImVec2(p.x + bgX1, p.y + bgX1), ImVec2(p.x + bgX2, p.y + bgX2), bgcolor, 3.0f, ImDrawFlags_RoundCornersAll);
dl->AddLine(ImVec2(p.x + 8.5f, p.y + 1), ImVec2(p.x + 8.5f, p.y + 10), color_red, 2);
dl->AddLine(ImVec2(p.x + 5.5f, p.y + 5), ImVec2(p.x + 8.5f, p.y + 1), color_red, 2);
dl->AddLine(ImVec2(p.x + 12, p.y + 5), ImVec2(p.x + 8.5f, p.y + 1), color_red, 2);
dl->AddCircleFilled(ImVec2(p.x + 9, p.y + 15), 2.0f, color);
ImGui::SetItemTooltip("Step Out");
}
}
ImGui::End();
}
} // namespace DT
} // namespace Director

View File

@@ -0,0 +1,284 @@
/* 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 DIRECTOR_DEBUGER_DT_INTERNAL_H
#define DIRECTOR_DEBUGER_DT_INTERNAL_H
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "graphics/surface.h"
#include "backends/imgui/imgui.h"
#include "backends/imgui/imgui_fonts.h"
#include "backends/imgui/components/imgui_logger.h"
#include "director/debugger/imgui_memory_editor.h"
#include "director/types.h"
#include "director/lingo/lingo.h"
#include "director/lingo/lingodec/ast.h"
#include "director/lingo/lingodec/handler.h"
namespace Director {
namespace DT {
#define kMaxColumnsInTable 512
typedef struct ImGuiImage {
ImTextureID id;
int16 width;
int16 height;
} ImGuiImage;
typedef struct ImGuiScriptCodeLine {
uint32 pc;
Common::String codeLine;
} ImGuiScriptCodeLine;
typedef struct ImGuiScript {
bool score = false;
CastMemberID id;
ScriptType type;
Common::String handlerId;
Common::String handlerName;
Common::String moviePath;
Common::Array<uint32> byteOffsets;
uint pc = 0;
bool isMethod = false;
bool isGenericEvent = false;
Common::StringArray argumentNames;
Common::StringArray propertyNames;
Common::StringArray globalNames;
Common::SharedPtr<LingoDec::HandlerNode> root;
Common::Array<LingoDec::Bytecode> bytecodeArray;
Common::Array<uint> startOffsets;
Common::SharedPtr<Node> oldAst;
bool operator==(const ImGuiScript &c) const {
return moviePath == c.moviePath && score == c.score && id == c.id && handlerId == c.handlerId;
}
bool operator!=(const ImGuiScript &c) const {
return !(*this == c);
}
} ImGuiScript;
typedef struct ImGuiWindows {
bool controlPanel = true;
bool vars = false;
bool channels = false;
bool cast = false;
bool funcList = false;
bool score = false;
bool bpList = false;
bool settings = false;
bool logger = false;
bool archive = false;
bool watchedVars = false;
bool executionContext = false;
} ImGuiWindows;
typedef struct ScriptData {
Common::Array<ImGuiScript> _scripts;
uint _current = 0;
bool _showByteCode = false;
bool _showScript = false;
} ScriptData;
typedef struct WindowFlag {
const char *name;
bool *flag;
} WindowFlag;
typedef struct ImGuiState {
struct {
Common::HashMap<CastMember *, ImGuiImage> _textures;
bool _listView = true;
int _thumbnailSize = 64;
ImGuiTextFilter _nameFilter;
int _typeFilter = 0x7FFF;
} _cast;
struct {
ImGuiTextFilter _nameFilter;
bool _showScriptContexts = true;
Common::HashMap<Window *, ScriptData> _windowScriptData;
} _functions;
struct {
bool _isScriptDirty = false; // indicates whether or not we have to display the script corresponding to the current stackframe
bool _goToDefinition = false;
bool _scrollToPC = false;
uint _lastLinePC = 0;
uint _callstackSize = 0;
} _dbg;
struct {
ImVec4 _bp_color_disabled = ImVec4(0.9f, 0.08f, 0.0f, 0.0f);
ImVec4 _bp_color_enabled = ImVec4(0.9f, 0.08f, 0.0f, 1.0f);
ImVec4 _bp_color_hover = ImVec4(0.42f, 0.17f, 0.13f, 1.0f);
ImVec4 _channel_toggle = ImColor(IM_COL32(0x30, 0x30, 0xFF, 0xFF));
ImVec4 _current_statement = ImColor(IM_COL32(0xFF, 0xFF, 0x00, 0xFF));
ImVec4 _line_color = ImVec4(0.44f, 0.44f, 0.44f, 1.0f);
ImVec4 _call_color = ImColor(IM_COL32(0xFF, 0xC5, 0x5C, 0xFF));
ImVec4 _builtin_color = ImColor(IM_COL32(0x60, 0x7C, 0xFF, 0xFF));
ImVec4 _var_color = ImColor(IM_COL32(0x4B, 0xCD, 0x5E, 0xFF));
ImVec4 _literal_color = ImColor(IM_COL32(0xFF, 0x9F, 0xDA, 0x9E));
ImVec4 _comment_color = ImColor(IM_COL32(0xFF, 0xA5, 0x9D, 0x95));
ImVec4 _type_color = ImColor(IM_COL32(0x13, 0xC5, 0xF9, 0xFF));
ImVec4 _keyword_color = ImColor(IM_COL32(0xC1, 0xC1, 0xC1, 0xFF));
ImVec4 _the_color = ImColor(IM_COL32(0xFF, 0x49, 0xEF, 0xFF));
ImVec4 _script_ref = ImColor(IM_COL32(0x7f, 0x7f, 0xff, 0xfff));
ImVec4 _var_ref = ImColor(IM_COL32(0xe6, 0xe6, 0x00, 0xff));
ImVec4 _var_ref_changed = ImColor(IM_COL32(0xFF, 0x00, 0x00, 0xFF));
ImVec4 _var_ref_out_of_scope = ImColor(IM_COL32(0xFF, 0x00, 0xFF, 0xFF));
// Colors to show continuation data
// They come from the Authoring tool
ImColor _contColors[6] = {
ImColor(IM_COL32(0xce, 0xce, 0xff, 0x80)), // 0xceceff,
ImColor(IM_COL32(0xff, 0xff, 0xce, 0x80)), // 0xffffce,
ImColor(IM_COL32(0xce, 0xff, 0xce, 0x80)), // 0xceffce,
ImColor(IM_COL32(0xce, 0xff, 0xff, 0x80)), // 0xceffff,
ImColor(IM_COL32(0xff, 0xce, 0xff, 0x80)), // 0xffceff,
ImColor(IM_COL32(0xff, 0xce, 0x9c, 0x80)), // 0xffce9c,
};
ImColor _channel_selected_col = ImColor(IM_COL32(0x94, 0x00, 0xD3, 0xFF));
ImColor _channel_hovered_col = ImColor(IM_COL32(0xFF, 0xFF, 0, 0x3C));
int _contColorIndex = 0;
} _colors;
struct {
DatumHash _locals;
DatumHash _globals;
DatumHash _prevLocals;
DatumHash _prevGlobals;
uint32 _lastTimeRefreshed = 0;
} _vars;
ImGuiWindows _w;
ImGuiWindows _savedW;
bool _wasHidden = false;
Common::List<CastMemberID> _scriptCasts;
Common::HashMap<int, ImGuiScript> _openHandlers;
bool _showCompleteScript = true;
Common::HashMap<Common::String, bool, Common::IgnoreCase_Hash, Common::IgnoreCase_EqualTo> _variables;
int _prevFrame = -1;
struct {
int frame = -1;
int channel = -1;
} _selectedScoreCast;
struct {
int frame = -1;
int channel = -1;
} _hoveredScoreCast;
Common::Array<Common::Array<Common::Pair<uint, uint>>> _continuationData;
Common::String _loadedContinuationData;
Common::String _scoreWindow;
Common::String _channelsWindow;
Common::String _castWindow;
int _scoreMode = 0;
int _scoreFrameOffset = 1;
int _scorePageSlider = 0;
int _selectedChannel = -1;
ImFont *_tinyFont = nullptr;
struct {
Common::Path path;
uint32 resType = 0;
uint32 resId = 0;
byte *data = nullptr;
uint32 dataSize = 0;
MemoryEditor memEdit;
} _archive;
ImGuiEx::ImGuiLogger *_logger = nullptr;
} ImGuiState;
// debugtools.cpp
ImGuiScript toImGuiScript(ScriptType scriptType, CastMemberID id, const Common::String &handlerId);
ScriptContext *getScriptContext(CastMemberID id);
ScriptContext *getScriptContext(uint32 nameIndex, CastMemberID castId, Common::String handler);
void setScriptToDisplay(const ImGuiScript &script);
Director::Breakpoint *getBreakpoint(const Common::String &handlerName, uint16 scriptId, uint pc);
void displayScriptRef(CastMemberID &scriptId);
ImGuiImage getImageID(CastMember *castMember);
ImGuiImage getShapeID(CastMember *castMember);
ImGuiImage getTextID(CastMember *castMember);
Common::String getDisplayName(CastMember *castMember);
void showImage(const ImGuiImage &image, const char *name, float thumbnailSize);
ImVec4 convertColor(uint32 color);
void displayVariable(const Common::String &name, bool changed, bool outOfScope = false);
ImColor brightenColor(const ImColor &color, float factor);
Window *windowListCombo(Common::String *target);
Common::String formatHandlerName(int scriptId, int castId, Common::String handlerName, ScriptType scriptType, bool childScript);
void showCast(); // dt-cast.cpp
void showControlPanel(); // dt-controlpanel.cpp
// dt-lists.cpp
void showVars();
void showWatchedVars();
void showBreakpointList();
void showArchive();
// dt-score.cpp
void showScore();
void showChannels();
void renderOldScriptAST(ImGuiScript &script, bool showByteCode, bool scrollTo); // dt-script-d2.cpp
void renderScriptAST(ImGuiScript &script, bool showByteCode, bool scrollTo); // dt-script-d4.cpp
// dt-scripts.cpp
void showFuncList();
void showScriptCasts();
void showExecutionContext();
void showHandlers();
// dt-save-state.cpp
void saveCurrentState();
void loadSavedState();
Common::Array<WindowFlag> getWindowFlags();
extern ImGuiState *_state;
} // End of namespace DT
} // End of namespace Director
#endif

View File

@@ -0,0 +1,340 @@
/* 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 "director/director.h"
#include "director/archive.h"
#include "director/debugger.h"
#include "director/debugger/dt-internal.h"
#include "director/lingo/lingo-object.h"
namespace Director {
namespace DT {
static void cacheVars() {
// take a snapshot of the variables every 500 ms
if ((g_director->getTotalPlayTime() - _state->_vars._lastTimeRefreshed) > 500) {
_state->_vars._prevLocals = _state->_vars._locals;
if (g_lingo->_state->localVars) {
_state->_vars._locals = *g_lingo->_state->localVars;
} else {
_state->_vars._locals.clear();
}
_state->_vars._prevGlobals = _state->_vars._globals;
_state->_vars._globals = g_lingo->_globalvars;
_state->_vars._lastTimeRefreshed = g_director->getTotalPlayTime();
}
}
void showVars() {
if (!_state->_w.vars)
return;
cacheVars();
Director::Lingo *lingo = g_director->getLingo();
ImGui::SetNextWindowPos(ImVec2(20, 20), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(300, 250), ImGuiCond_FirstUseEver);
if (ImGui::Begin("Vars", &_state->_w.vars)) {
Common::Array<Common::String> keyBuffer;
if (ImGui::CollapsingHeader("Global vars:", ImGuiTreeNodeFlags_DefaultOpen)) {
for (auto &it : _state->_vars._globals) {
keyBuffer.push_back(it._key);
}
Common::sort(keyBuffer.begin(), keyBuffer.end());
uint32 id = 0;
for (auto &i : keyBuffer) {
ImGui::PushID(id);
Datum &val = _state->_vars._globals.getVal(i);
bool changed = !_state->_vars._prevGlobals.contains(i) || !(_state->_vars._globals.getVal(i) == _state->_vars._prevGlobals.getVal(i));
displayVariable(i, changed);
ImGui::SameLine();
ImGui::Text(" - [%s] %s", val.type2str(), formatStringForDump(val.asString(true)).c_str());
ImGui::PopID();
id += 1;
}
keyBuffer.clear();
}
if (ImGui::CollapsingHeader("Local vars:", ImGuiTreeNodeFlags_None)) {
if (!_state->_vars._locals.empty()) {
for (auto &it : _state->_vars._locals) {
keyBuffer.push_back(it._key);
}
Common::sort(keyBuffer.begin(), keyBuffer.end());
uint32 id = 0;
for (auto &i : keyBuffer) {
ImGui::PushID(id);
Datum &val = _state->_vars._locals.getVal(i);
bool changed = !_state->_vars._prevLocals.contains(i) || !(_state->_vars._locals.getVal(i) == _state->_vars._prevLocals.getVal(i));
displayVariable(i, changed);
ImGui::SameLine();
ImGui::Text(" - [%s] %s", val.type2str(), formatStringForDump(val.asString(true)).c_str());
ImGui::PopID();
id += 1;
}
keyBuffer.clear();
} else {
ImGui::Text(" (no local vars)");
}
}
if (ImGui::CollapsingHeader("Instance/property vars:", ImGuiTreeNodeFlags_None)) {
if (lingo->_state->me.type == OBJECT && lingo->_state->me.u.obj->getObjType() & (kFactoryObj | kScriptObj)) {
ScriptContext *script = static_cast<ScriptContext *>(lingo->_state->me.u.obj);
for (uint32 i = 1; i <= script->getPropCount(); i++) {
keyBuffer.push_back(script->getPropAt(i));
}
Common::sort(keyBuffer.begin(), keyBuffer.end());
uint32 id = 0;
for (auto &i : keyBuffer) {
ImGui::PushID(id);
Datum val = script->getProp(i);
displayVariable(i, false);
ImGui::SameLine();
ImGui::Text(" - [%s] %s", val.type2str(), formatStringForDump(val.asString(true)).c_str());
ImGui::PopID();
id += 1;
}
keyBuffer.clear();
} else {
ImGui::Text(" (no instance or property)");
}
}
}
ImGui::End();
}
void showWatchedVars() {
if (!_state->_w.watchedVars)
return;
cacheVars();
ImGui::SetNextWindowPos(ImVec2(20, 20), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(300, 250), ImGuiCond_FirstUseEver);
if (ImGui::Begin("Watched Vars", &_state->_w.watchedVars)) {
int id = -1;
for (auto &v : _state->_variables) {
Datum name(v._key);
name.type = VARREF;
Datum val = g_lingo->varFetch(name, true);
bool outOfScope = false;
if (val.type == VOID) {
outOfScope = true;
}
id += 1;
ImGui::PushID(id);
displayVariable(v._key, false, outOfScope);
ImGui::PopID();
ImGui::SameLine();
ImGui::Text(" - [%s] %s", val.type2str(), formatStringForDump(val.asString(true)).c_str());
}
if (_state->_variables.empty())
ImGui::Text("(no watched variables)");
}
ImGui::End();
}
// Make the UI compact because there are so many fields
static void PushStyleCompact() {
ImGuiStyle &style = ImGui::GetStyle();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(style.FramePadding.x, (float)(int)(style.FramePadding.y * 0.60f)));
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x, (float)(int)(style.ItemSpacing.y * 0.60f)));
}
static void PopStyleCompact() {
ImGui::PopStyleVar(2);
}
void showBreakpointList() {
if (!_state->_w.bpList)
return;
ImGui::SetNextWindowPos(ImVec2(20, 20), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(480, 240), ImGuiCond_FirstUseEver);
if (ImGui::Begin("Breakpoints", &_state->_w.bpList)) {
auto &bps = g_lingo->getBreakpoints();
if (ImGui::BeginTable("BreakpointsTable", 5, ImGuiTableFlags_SizingFixedFit)) {
for (uint i = 0; i < 5; i++)
ImGui::TableSetupColumn(NULL, i == 2 ? ImGuiTableColumnFlags_WidthStretch : ImGuiTableColumnFlags_NoHeaderWidth);
for (uint i = 0; i < bps.size(); i++) {
if (bps[i].type != kBreakpointFunction)
continue;
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImDrawList *dl = ImGui::GetWindowDrawList();
ImVec2 pos = ImGui::GetCursorScreenPos();
const ImVec2 mid(pos.x + 7, pos.y + 7);
ImVec4 color = bps[i].enabled ? _state->_colors._bp_color_enabled : _state->_colors._bp_color_disabled;
ImGui::InvisibleButton("Line", ImVec2(16, ImGui::GetFontSize()));
if (ImGui::IsItemClicked(0)) {
if (bps[i].enabled) {
bps[i].enabled = false;
color = _state->_colors._bp_color_disabled;
} else {
bps[i].enabled = true;
color = _state->_colors._bp_color_enabled;
}
}
if (!bps[i].enabled && ImGui::IsItemHovered()) {
color = _state->_colors._bp_color_hover;
}
if (bps[i].enabled)
dl->AddCircleFilled(mid, 4.0f, ImColor(color));
else
dl->AddCircle(mid, 4.0f, ImColor(_state->_colors._line_color));
// enabled column
ImGui::TableNextColumn();
PushStyleCompact();
ImGui::PushID(i);
ImGui::Checkbox("", &bps[i].enabled);
PopStyleCompact();
// description
ImGui::TableNextColumn();
Common::String desc;
if (bps[i].scriptId)
desc = Common::String::format("%d: %s", bps[i].scriptId, bps[i].funcName.c_str());
else
desc = bps[i].funcName;
ImGui::Text("%s", desc.c_str());
// remove bp
ImGui::TableNextColumn();
pos = ImGui::GetCursorScreenPos();
const bool del = ImGui::InvisibleButton("DelBp", ImVec2(16, ImGui::GetFontSize()));
const bool hovered = ImGui::IsItemHovered();
const float fontSize = ImGui::GetFontSize();
const float cross_extent = ImGui::GetFontSize() * 0.5f * 0.7071f - 1.0f;
const ImU32 cross_col = ImGui::GetColorU32(ImGuiCol_Text);
const ImVec2 center = pos + ImVec2(0.5f + fontSize * 0.5f, 1.0f + fontSize * 0.5f);
if (hovered)
dl->AddCircleFilled(center, MAX(2.0f, fontSize * 0.5f + 1.0f), ImGui::GetColorU32(ImGuiCol_ButtonActive));
dl->AddLine(center + ImVec2(+cross_extent, +cross_extent), center + ImVec2(-cross_extent, -cross_extent), cross_col, 1.0f);
dl->AddLine(center + ImVec2(+cross_extent, -cross_extent), center + ImVec2(-cross_extent, +cross_extent), cross_col, 1.0f);
// offset
ImGui::TableNextColumn();
ImGui::Text("%d", bps[i].funcOffset);
ImGui::PopID();
if (del) {
g_lingo->delBreakpoint(bps[i].id);
break;
}
}
ImGui::EndTable();
}
}
ImGui::End();
}
void showArchive() {
if (!_state->_w.archive)
return;
ImVec2 pos(40, 40);
ImGui::SetNextWindowPos(pos, ImGuiCond_FirstUseEver);
ImVec2 windowSize = ImGui::GetMainViewport()->Size * 0.8f;
ImGui::SetNextWindowSize(windowSize, ImGuiCond_FirstUseEver);
if (ImGui::Begin("Archive", &_state->_w.archive)) {
{ // Left pane
ImGui::BeginChild("ChildL", ImVec2(ImGui::GetContentRegionAvail().x * 0.3f, ImGui::GetContentRegionAvail().y), ImGuiChildFlags_None);
for (auto &it : g_director->_allSeenResFiles) {
Archive *archive = it._value;
if (ImGui::TreeNode(archive->getPathName().toString().c_str())) {
Common::Array<uint32> typeList = archive->getResourceTypeList();
Common::sort(typeList.begin(), typeList.end());
for (auto tag : typeList) {
if (ImGui::TreeNode((void*)(intptr_t)tag, "%s", tag2str(tag))) {
Common::Array<uint16> resList = archive->getResourceIDList(tag);
Common::sort(resList.begin(), resList.end());
for (auto id : resList) {
if (ImGui::Selectable(Common::String::format("%d", id).c_str())) {
_state->_archive.path = it._key;
_state->_archive.resType = tag;
_state->_archive.resId = id;
free(_state->_archive.data);
Common::SeekableReadStreamEndian *res = archive->getResource(tag, id);
_state->_archive.data = (byte *)malloc(res->size());
res->read(_state->_archive.data, res->size());
_state->_archive.dataSize = res->size();
delete res;
}
}
ImGui::TreePop();
}
}
ImGui::TreePop();
}
}
ImGui::EndChild();
}
ImGui::SameLine();
{ // Right pane
ImGui::BeginChild("ChildR", ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y), ImGuiChildFlags_Borders);
ImGui::Text("Resource %s %d (%d bytes)", tag2str(_state->_archive.resType), _state->_archive.resId, _state->_archive.dataSize);
ImGui::Separator();
if (!_state->_archive.path.empty())
_state->_archive.memEdit.DrawContents(_state->_archive.data, _state->_archive.dataSize);
ImGui::EndChild();
}
}
ImGui::End();
}
} // namespace DT
} // namespace Director

View File

@@ -0,0 +1,187 @@
/* 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 "backends/imgui/imgui_utils.h"
#include "common/formats/json.h"
#include "common/memstream.h"
#include "common/savefile.h"
#include "common/file.h"
#include "director/director.h"
#include "director/movie.h"
#include "director/score.h"
#include "director/debugger/dt-internal.h"
namespace Director {
namespace DT {
const char *savedStateFileName = "ImGuiSaveState.json";
Common::Array<WindowFlag> getWindowFlags() {
return {
{ "Archive", &_state->_w.archive },
{ "Breakpoints", &_state->_w.bpList },
{ "Cast", &_state->_w.cast },
{ "Channels", &_state->_w.channels },
{ "Control Panel", &_state->_w.controlPanel },
{ "Execution Context", &_state->_w.executionContext },
{ "Functions", &_state->_w.funcList },
{ "Log", &_state->_w.logger },
{ "Score", &_state->_w.score },
{ "Settings", &_state->_w.settings },
{ "Vars", &_state->_w.vars },
{ "Watched Vars", &_state->_w.watchedVars },
};
}
// What are the things that need saving?
// 1) Window Positions
// 2) Score frame number
// 3) Windows that are open/closed
// 4) Watched Variables
void saveCurrentState() {
Common::JSONObject json = Common::JSONObject();
// Whether windows are open or not
Common::Array<WindowFlag> windows = getWindowFlags();
uint index = 0;
int64 openFlags = 0;
for (const WindowFlag &it : windows) {
openFlags += (*it.flag) ? 1 << index : 0;
index += 1;
}
if (debugChannelSet(7, kDebugImGui)) {
debugC(7, kDebugImGui, "Window flags: ");
for (auto it : windows) {
debug("%s: %s", it.name, *it.flag ? "open" : "closed");
}
}
json["Windows"] = new Common::JSONValue((long long int)openFlags);
// Window Settings
const char *windowSettings = ImGui::SaveIniSettingsToMemory();
json["Window Settings"] = new Common::JSONValue(windowSettings);
// Current Log
ImVector<char *> currentLog = _state->_logger->getItems();
Common::JSONArray log;
for (auto iter : currentLog) {
log.push_back(new Common::JSONValue(iter));
}
json["Log"] = new Common::JSONValue(log);
// Other settings
json["ScoreWindow"] = new Common::JSONValue(_state->_scoreWindow);
json["ChannelsWindow"] = new Common::JSONValue(_state->_channelsWindow);
json["CastWindow"] = new Common::JSONValue(_state->_castWindow);
// Save the JSON
Common::JSONValue save(json);
debugC(7, kDebugImGui, "ImGui::Saved state: %s", save.stringify().c_str());
Common::OutSaveFile *stream = g_engine->getSaveFileManager()->openForSaving(savedStateFileName);
if (stream) {
stream->writeString(save.stringify());
stream->finalize();
debug("ImGui::SaveCurrentState: Saved the current ImGui State @%s", savedStateFileName);
} else {
debug("ImGui::SaveCurrentState: Failed to open the file %s for saving", savedStateFileName);
}
// Clean up everything
delete stream;
}
void loadSavedState() {
Common::InSaveFile *savedState = g_engine->getSaveFileManager()->openForLoading(savedStateFileName);
if (!savedState || savedState->size() == 0) {
debug("ImGui::loadSavedState(): Failed to open saved state file: %s", savedStateFileName);
return;
}
// ASAN throws an error if the data is exactly equal to savedState->size() in JSON::parse()
// Probably because JSON::parse() expects a NULL terminated data
char *data = (char *)malloc(savedState->size() + 1);
data[savedState->size()] = '\0';
savedState->read(data, savedState->size());
Common::JSONValue *saved = Common::JSON::parse(data);
if (!saved) {
debug("ImGui:: Bad JSON: Failed to parse the Saved state");
free(data);
return;
}
debugC(7, kDebugImGui, "ImGui::loaded state: %s", saved->stringify(true).c_str());
// Load open/closed window flags
int64 openFlags = saved->asObject()["Windows"]->asIntegerNumber();
Common::Array<WindowFlag> windows = getWindowFlags();
uint index = 0;
for (WindowFlag it : windows) {
*it.flag = (openFlags & 1 << index) ? true : false;
index += 1;
}
_state->_w.archive = (openFlags & 1) ? true : false;
if (debugChannelSet(7, kDebugImGui)) {
debugC(7, kDebugImGui, "Window flags: ");
for (auto it : windows) {
debug("%s: %s", it.name, *it.flag ? "open" : "closed");
}
}
// Load window settings
const char *windowSettings = saved->asObject()["Window Settings"]->asString().c_str();
ImGui::LoadIniSettingsFromMemory(windowSettings);
// Load the log
Common::JSONArray log = saved->asObject()["Log"]->asArray();
if (debugChannelSet(7, kDebugImGui)) {
debugC(7, kDebugImGui, "Loading log: \n");
for (auto iter : log) {
debugC(7, kDebugImGui, "%s", iter->asString().c_str());
}
}
_state->_logger->clear();
for (auto iter : log) {
_state->_logger->addLog(iter->asString().c_str());
}
// Load other settings
_state->_scoreWindow = saved->asObject()["ScoreWindow"]->asString();
_state->_channelsWindow = saved->asObject()["ChannelsWindow"]->asString();
_state->_castWindow = saved->asObject()["CastWindow"]->asString();
free(data);
delete saved;
delete savedState;
}
} // End of namespace DT
} // End of namespace Director

View File

@@ -0,0 +1,955 @@
/* 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/memstream.h"
#include "backends/imgui/IconsMaterialSymbols.h"
#include "director/director.h"
#include "director/debugger/dt-internal.h"
#include "director/cast.h"
#include "director/castmember/castmember.h"
#include "director/channel.h"
#include "director/frame.h"
#include "director/movie.h"
#include "director/score.h"
#include "director/sprite.h"
#include "director/window.h"
namespace Director {
namespace DT {
enum { kModeMember, kModeBehavior, kModeLocation, kModeInk, kModeBlend, kModeExtended,
kChTempo, kChPalette, kChTransition, kChSound1, kChSound2, kChScript };
const char *modes[] = { "Member", "Behavior", "Location", "Ink", "Blend", "Extended" };
const char *modes2[] = {
ICON_MS_TIMER, "Tempo", // timer
ICON_MS_PALETTE, "Palette", // palette
ICON_MS_TRANSITION_FADE, "Transition", // transition_fade
ICON_MS_VOLUME_UP,"Sound 1", // volume_up
ICON_MS_VOLUME_DOWN,"Sound 2", // volume_up
ICON_MS_FORMS_APPS_SCRIPT, "Script", // forms_apps_script
};
#define FRAME_PAGE_SIZE 100
static void buildContinuationData(Window *window) {
if (_state->_loadedContinuationData == window->getCurrentMovie()->getMacName()) {
return;
}
_state->_scorePageSlider = 0;
_state->_continuationData.clear();
Score *score = window->getCurrentMovie()->getScore();
uint numFrames = score->_scoreCache.size();
uint numChannels = score->_scoreCache[0]->_sprites.size();
_state->_continuationData.resize(numChannels);
for (int ch = 0; ch < (int)numChannels; ch++) {
_state->_continuationData[ch].resize(numFrames);
uint currentContinuation = 1;
for (int f = 0; f < (int)numFrames; f++) {
const Frame &frame = *score->_scoreCache[f];
Sprite &sprite = *frame._sprites[ch];
const Frame *prevFrame = (f == 0) ? nullptr : score->_scoreCache[f - 1];
Sprite *prevSprite = (prevFrame) ? prevFrame->_sprites[ch] : nullptr;
if (prevSprite) {
if (!(*prevSprite == sprite)) {
currentContinuation = f;
}
} else {
currentContinuation = f;
}
_state->_continuationData[ch][f].first = currentContinuation;
#if 0
if (ch == 3 && prevSprite && f >= 20 && f < 49) {
warning("%02d: st: %d cid: %d sp: %d w: %d h: %d i: %d f: %d b: %d bl: %d in: %d t: %d",
f,
prevSprite->_spriteType == sprite._spriteType,
prevSprite->_castId == sprite._castId,
prevSprite->_startPoint == sprite._startPoint,
prevSprite->_width == sprite._width,
prevSprite->_height == sprite._height,
prevSprite->_ink == sprite._ink,
prevSprite->_foreColor == sprite._foreColor,
prevSprite->_backColor == sprite._backColor,
prevSprite->_blendAmount == sprite._blendAmount,
prevSprite->_ink == sprite._ink,
prevSprite->_thickness == sprite._thickness
);
}
#endif
}
currentContinuation = 1;
for (int f = (int)numFrames - 1; f >= 0; f--) {
const Frame &frame = *score->_scoreCache[f];
Sprite &sprite = *frame._sprites[ch];
const Frame *nextFrame = (f == (int)numFrames - 1) ? nullptr : score->_scoreCache[f + 1];
Sprite *nextSprite = (nextFrame) ? nextFrame->_sprites[ch] : nullptr;
if (nextSprite) {
if (!(*nextSprite == sprite)) {
currentContinuation = f;
}
} else {
currentContinuation = f;
}
_state->_continuationData[ch][f].second = currentContinuation;
}
}
_state->_loadedContinuationData = window->getCurrentMovie()->getMacName();
}
static void displayScoreChannel(int ch, int mode, int modeSel, Window *window) {
Score *score = window->getCurrentMovie()->getScore();
uint numFrames = score->_scoreCache.size();
const uint currentFrameNum = score->getCurrentFrameNum();
const ImU32 cell_bg_color = ImGui::GetColorU32(ImVec4(0.7f, 0.7f, 0.0f, 0.65f));
ImGui::TableNextRow();
ImGui::PushFont(_state->_tinyFont);
if (modeSel == kModeExtended && mode == kModeExtended)
ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0, ImGui::GetColorU32(ImGuiCol_TableRowBgAlt));
{ // Playback toggle
ImGui::TableNextColumn();
ImGui::PushID(ch + 20000 - mode);
ImDrawList *dl = ImGui::GetWindowDrawList();
const ImVec2 pos = ImGui::GetCursorScreenPos();
const ImVec2 mid(pos.x + 7, pos.y + 7);
ImGui::InvisibleButton("Line", ImVec2(16, ImGui::GetFontSize()));
ImGui::SetItemTooltip("Playback toggle");
if (ImGui::IsItemClicked(0)) {
if (mode == kModeMember) {
score->_channels[ch]->_visible = !score->_channels[ch]->_visible;
window->render(true);
}
}
if (mode != kModeMember || score->_channels[ch]->_visible)
dl->AddCircleFilled(mid, 4.0f, ImColor(_state->_colors._channel_toggle));
else
dl->AddCircle(mid, 4.0f, ImColor(_state->_colors._channel_toggle));
ImGui::PopID();
}
{ // Channel name / number
ImGui::TableNextColumn();
float indentSize = 17.0f;
if (mode < kChTempo && modeSel == kModeExtended)
indentSize = 10.0f;
if (modeSel == kModeExtended && mode == kModeExtended)
indentSize = 0.1f;
ImGui::Indent(indentSize);
if (mode >= kChTempo) {
ImGui::PushFont(ImGui::GetIO().FontDefault);
ImGui::Text(modes2[(mode - kChTempo) * 2]);
ImGui::SetItemTooltip(modes2[(mode - kChTempo) * 2 + 1]);
ImGui::PopFont();
} else if (modeSel != kModeExtended || mode == kModeExtended) {
ImGui::Text("%3d", ch);
} else {
ImGui::Text(modes[mode]);
}
if (ch == _state->_selectedScoreCast.channel)
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, ImGui::GetColorU32(ImVec4(0.5f, 0.5f, 0.5f, 0.6f)));
else
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, ImGui::GetColorU32(ImGuiCol_TableHeaderBg));
ImGui::Unindent(indentSize);
}
numFrames -= _state->_scoreFrameOffset - 1;
numFrames = MIN<uint>(numFrames, kMaxColumnsInTable - 2);
for (int f = 0; f < (int)numFrames; f++) {
int rf = f + _state->_scoreFrameOffset - 1;
Frame &frame = *score->_scoreCache[rf];
Sprite &sprite = *frame._sprites[ch];
_state->_colors._contColorIndex = frame._sprites[ch]->_colorcode & 0x07;
if (_state->_colors._contColorIndex > 5)
_state->_colors._contColorIndex = 0;
ImGui::TableNextColumn();
int startCont = _state->_continuationData[ch][rf].first;
int endCont = _state->_continuationData[ch][rf].second;
if (!(startCont == endCont) && (sprite._castId.member || sprite.isQDShape())) {
if (_state->_selectedScoreCast.frame + _state->_scoreFrameOffset - 1 >= startCont &&
_state->_selectedScoreCast.frame + _state->_scoreFrameOffset - 1 <= endCont &&
ch == _state->_selectedScoreCast.channel &&
mode <= kModeExtended) {
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, _state->_colors._channel_selected_col);
} else if (_state->_hoveredScoreCast.frame >= startCont &&
_state->_hoveredScoreCast.frame <= endCont &&
ch == _state->_hoveredScoreCast.channel) {
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, _state->_colors._channel_hovered_col);
} else {
if (mode == modeSel)
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, _state->_colors._contColors[_state->_colors._contColorIndex]);
else
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, brightenColor(_state->_colors._contColors[_state->_colors._contColorIndex], 1.5));
}
}
if (rf + 1 == (int)currentFrameNum)
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, cell_bg_color);
if (f == _state->_selectedScoreCast.frame + _state->_scoreFrameOffset - 1 &&
ch == _state->_selectedScoreCast.channel && mode <= kModeExtended)
ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, ImGui::GetColorU32(ImVec4(1.0f, 0.3f, 0.3f, 0.6f)));
int mode1 = mode;
ImGui::PushID((ch * 20 + mode) * 10000 + f);
// If the frame is not the start, then don't render any text
if (mode == kModeMember) {
if (rf != startCont || !(sprite._castId.member || sprite.isQDShape())) {
if (rf == endCont && sprite._castId.member && mode == _state->_scoreMode) {
ImGui::PushFont(ImGui::GetIO().FontDefault);
ImGui::TextUnformatted("\uf819");
ImGui::PopFont();
} else {
if (sprite._castId.member) {
ImGui::Selectable("");
} else {
ImGui::Selectable(" ");
}
}
mode1 = -1; // Skip cell data rendering
}
}
switch (mode1) {
case -1:
break;
case kModeMember:
if (sprite._castId.member)
ImGui::Selectable(Common::String::format("%d", sprite._castId.member).c_str());
else if (sprite.isQDShape())
ImGui::Selectable("Q");
else
ImGui::Selectable(" ");
break;
case kModeInk:
ImGui::Selectable(Common::String::format("%s", inkType2str(sprite._ink)).c_str());
break;
case kModeLocation:
ImGui::Selectable(Common::String::format("%d, %d", sprite._startPoint.x, sprite._startPoint.y).c_str());
break;
case kModeBlend:
ImGui::Selectable(Common::String::format("%d", sprite._blendAmount).c_str());
break;
case kModeBehavior:
displayScriptRef(sprite._scriptId);
break;
case kChTempo:
if (frame._mainChannels.tempo)
ImGui::Selectable(Common::String::format("%d", frame._mainChannels.tempo).c_str());
break;
case kChPalette:
if (frame._mainChannels.palette.paletteId.member)
ImGui::Selectable(Common::String::format("%d", frame._mainChannels.palette.paletteId.member).c_str());
break;
case kChTransition:
if (frame._mainChannels.transType)
ImGui::Selectable(Common::String::format("%d", frame._mainChannels.transType).c_str());
break;
case kChSound1:
if (frame._mainChannels.sound1.member)
ImGui::Selectable(Common::String::format("%d", frame._mainChannels.sound1.member).c_str());
break;
case kChSound2:
if (frame._mainChannels.sound2.member)
ImGui::Selectable(Common::String::format("%d", frame._mainChannels.sound2.member).c_str());
break;
case kChScript:
displayScriptRef(frame._mainChannels.actionId);
break;
case kModeExtended: // Render empty row
default:
ImGui::Selectable(" ");
}
ImGui::PopID();
if (ImGui::IsItemClicked(ImGuiMouseButton_Left)) {
_state->_selectedScoreCast.frame = f + _state->_scoreFrameOffset - 1;
_state->_selectedScoreCast.channel = ch;
if (f + _state->_scoreFrameOffset == (int)currentFrameNum) {
if (_state->_selectedChannel == ch)
_state->_selectedChannel = -1;
else
_state->_selectedChannel = ch;
window->render(true);
}
}
if (ImGui::IsItemHovered()) {
_state->_hoveredScoreCast.frame = f;
_state->_hoveredScoreCast.channel = ch;
}
}
ImGui::PopFont();
}
void showScore() {
if (!_state->_w.score)
return;
ImVec2 pos(40, 40);
ImGui::SetNextWindowPos(pos, ImGuiCond_FirstUseEver);
ImVec2 windowSize = ImGui::GetMainViewport()->Size - pos - pos;
ImGui::SetNextWindowSize(windowSize, ImGuiCond_FirstUseEver);
if (ImGui::Begin("Score", &_state->_w.score)) {
Window *selectedWindow = windowListCombo(&_state->_scoreWindow);
buildContinuationData(selectedWindow);
Score *score = selectedWindow->getCurrentMovie()->getScore();
uint numFrames = score->_scoreCache.size();
Cast *cast = selectedWindow->getCurrentMovie()->getCast();
if (!numFrames) {
ImGui::Text("No frames");
ImGui::End();
return;
}
if (_state->_selectedScoreCast.frame >= (int)numFrames)
_state->_selectedScoreCast.frame = 0;
if (!numFrames || _state->_selectedScoreCast.channel >= (int)score->_scoreCache[0]->_sprites.size())
_state->_selectedScoreCast.channel = 0;
if (_state->_scoreFrameOffset >= (int)numFrames)
_state->_scoreFrameOffset = 1;
{ // Render sprite details
Sprite *sprite = nullptr;
CastMember *castMember = nullptr;
bool shape = false;
if (_state->_selectedScoreCast.frame != -1)
sprite = score->_scoreCache[_state->_selectedScoreCast.frame]->_sprites[_state->_selectedScoreCast.channel];
if (sprite) {
castMember = cast->getCastMember(sprite->_castId.member, true);
shape = sprite->isQDShape();
}
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg));
ImGui::BeginChild("Image", ImVec2(200.0f, 70.0f));
if (castMember || shape) {
ImGuiImage imgID = {};
if (castMember) {
switch (castMember->_type) {
case kCastBitmap:
imgID = getImageID(castMember);
break;
case kCastShape:
imgID = getShapeID(castMember);
break;
case kCastText:
case kCastButton:
case kCastRichText:
imgID = getTextID(castMember);
break;
default:
break;
}
}
if (castMember && imgID.id) {
Common::String name(getDisplayName(castMember));
showImage(imgID, name.c_str(), 32.f);
} else {
ImGui::InvisibleButton("##canvas", ImVec2(32.f, 32.f));
}
ImGui::SameLine();
ImGui::Text("%s", sprite->_castId.asString().c_str());
ImGui::Text("%s", spriteType2str(sprite->_spriteType));
}
ImGui::PopStyleColor();
ImGui::EndChild();
ImGui::SameLine();
ImGui::BeginChild("Details", ImVec2(500.0f, 70.0f));
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg));
ImGui::BeginChild("Ink", ImVec2(150.0f, 20.0f));
if (castMember || shape) {
ImGui::Text("%s", inkType2str(sprite->_ink));
ImGui::SameLine(70);
ImGui::SetItemTooltip("Ink");
ImGui::Text("|");
ImGui::SameLine();
ImGui::Text("%d", sprite->_blendAmount);
ImGui::SameLine();
ImGui::SetItemTooltip("Blend");
}
ImGui::PopStyleColor();
ImGui::EndChild();
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg));
ImGui::BeginChild("Range", ImVec2(100.0f, 20.0f));
if (castMember || shape) {
ImGui::TextUnformatted("\uf816"); ImGui::SameLine(); // line_start_circle
// the continuation data is 0-indexed but the frames are 1-indexed
ImGui::Text("%4d", _state->_continuationData[_state->_selectedScoreCast.channel][_state->_selectedScoreCast.frame].first + 1); ImGui::SameLine(50);
ImGui::SetItemTooltip("Start Frame");
ImGui::TextUnformatted("\uf819"); ImGui::SameLine(); // line_end_square
// the continuation data is 0-indexed but the frames are 1-indexed
ImGui::Text("%4d", _state->_continuationData[_state->_selectedScoreCast.channel][_state->_selectedScoreCast.frame].second + 1); ImGui::SameLine();
ImGui::SetItemTooltip("End Frame");
}
ImGui::PopStyleColor();
ImGui::EndChild();
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg));
ImGui::BeginChild("Flags", ImVec2(200.0f, 20.0f));
if (castMember || shape) {
ImGui::Checkbox(ICON_MS_LOCK, &sprite->_enabled); ImGui::SameLine();
ImGui::SetItemTooltip("enabled");
ImGui::Checkbox(ICON_MS_EDIT_NOTE, &sprite->_editable); ImGui::SameLine();
ImGui::SetItemTooltip("editable");
ImGui::Checkbox(ICON_MS_MOVE_SELECTION_RIGHT, &sprite->_moveable); ImGui::SameLine();
ImGui::SetItemTooltip("moveable");
ImGui::Checkbox(ICON_MS_DYNAMIC_FEED, &sprite->_trails);
ImGui::SetItemTooltip("trails");
}
ImGui::PopStyleColor();
ImGui::EndChild();
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg));
ImGui::BeginChild("Colors", ImVec2(150.0f, 50.0f));
if (castMember || shape) {
ImVec4 fg = convertColor(sprite->_foreColor);
ImGui::ColorButton("foreColor", fg);
ImGui::SameLine();
ImGui::Text("#%02x%02x%02x", (int)(fg.x * 255), (int)(fg.y * 255), (int)(fg.z * 255));
ImGui::SetItemTooltip("Foreground Color");
ImVec4 bg = convertColor(sprite->_backColor);
ImGui::ColorButton("backColor", bg);
ImGui::SameLine();
ImGui::Text("#%02x%02x%02x", (int)(bg.x * 255), (int)(bg.y * 255), (int)(bg.z * 255));
ImGui::SameLine();
ImGui::SetItemTooltip("Background Color");
}
ImGui::PopStyleColor();
ImGui::EndChild();
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg));
ImGui::BeginChild("Coordinates", ImVec2(150.0f, 50.0f));
if (castMember || shape) {
ImGui::Text("X:"); ImGui::SameLine();
ImGui::Text("%d", sprite->_startPoint.x); ImGui::SameLine(75);
ImGui::SetItemTooltip("Reg Point Horizontal");
ImGui::Text("W:"); ImGui::SameLine();
ImGui::Text("%d", sprite->getWidth());
ImGui::SetItemTooltip("Width");
ImGui::Text("Y:"); ImGui::SameLine();
ImGui::Text("%d", sprite->_startPoint.y); ImGui::SameLine(75);
ImGui::SetItemTooltip("Reg Point Vertical");
ImGui::Text("H:"); ImGui::SameLine();
ImGui::Text("%d", sprite->getHeight()); ImGui::SameLine();
ImGui::SetItemTooltip("Height");
}
ImGui::PopStyleColor();
ImGui::EndChild();
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg));
ImGui::BeginChild("Bbox", ImVec2(150.0f, 50.0f));
if (castMember || shape) {
const Common::Rect &box = sprite->getBbox(true);
ImGui::Text("l:"); ImGui::SameLine();
ImGui::Text("%d", box.left); ImGui::SameLine(75);
ImGui::SetItemTooltip("Left");
ImGui::Text("r:"); ImGui::SameLine();
ImGui::Text("%d", box.right);
ImGui::SetItemTooltip("Right");
ImGui::Text("t:"); ImGui::SameLine();
ImGui::Text("%d", box.top); ImGui::SameLine(75);
ImGui::SetItemTooltip("Top");
ImGui::Text("b:"); ImGui::SameLine();
ImGui::Text("%d", box.bottom);
ImGui::SetItemTooltip("Bottom");
}
ImGui::PopStyleColor();
ImGui::EndChild();
ImGui::EndChild();
}
uint numChannels = MIN<int>(score->_scoreCache[0]->_sprites.size(), score->_maxChannelsUsed + 10);
uint tableColumns = MAX(numFrames + 5, 25U); // Set minimal table width to 25
if (tableColumns > kMaxColumnsInTable - 3) // Current restriction of ImGui
tableColumns = kMaxColumnsInTable - 3;
ImGuiTableFlags addonFlags = _state->_scoreMode == kModeExtended ? 0 : ImGuiTableFlags_RowBg;
ImGui::BeginChild("Score table", ImVec2(0, -20));
if (ImGui::BeginTable("Score", tableColumns + 2,
ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY |
addonFlags)) {
ImGuiTableFlags flags = ImGuiTableColumnFlags_WidthFixed;
ImGui::TableSetupScrollFreeze(2, 2);
ImGui::PushFont(_state->_tinyFont);
ImGui::TableSetupColumn("##disable", flags); // disable button
ImGui::TableSetupColumn("##", flags); // Number
for (uint i = 0; i < tableColumns; i++) {
Common::String label = Common::String::format("%-2d", i + _state->_scoreFrameOffset);
label += Common::String::format("##l%d", i);
ImGui::TableSetupColumn(label.c_str(), flags);
}
ImGui::TableNextRow(ImGuiTableRowFlags_Headers);
ImGui::TableNextRow(0);
ImGui::TableSetColumnIndex(0);
ImGui::SetNextItemWidth(20);
ImGui::TableSetColumnIndex(1);
ImGui::PushID(0);
ImGui::SetNextItemWidth(50);
const char *selMode = modes[_state->_scoreMode];
if (ImGui::BeginCombo("##mode", selMode)) {
for (int n = 0; n < ARRAYSIZE(modes); n++) {
const bool selected = (_state->_scoreMode == n);
if (ImGui::Selectable(modes[n], selected))
_state->_scoreMode = n;
if (selected)
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
ImGui::TableHeader("##");
}
ImGui::PopID();
for (uint i = 0; i < tableColumns; i++) {
ImGui::TableSetColumnIndex(i + 2);
const char *column_name = ImGui::TableGetColumnName(i + 2);
ImGui::SetNextItemWidth(20);
ImGui::TableHeader(column_name);
}
ImGui::TableNextRow();
ImGui::TableNextColumn(); // Enable/Disable switch
ImGui::TableNextColumn(); // Label column
float indentSize = 10.0;
ImGui::Indent(indentSize);
ImGui::Text("Labels");
ImGui::Unindent(indentSize);
ImGui::PopFont();
if (score->_labels && score->_labels->size()) {
auto labels = *score->_labels;
auto it = labels.begin();
for (uint f = 0; f < tableColumns; f++) {
ImGui::TableNextColumn();
while (it != labels.end() && (*it)->number < f + _state->_scoreFrameOffset)
it++;
if (it == labels.end())
continue;
if ((*it)->number == f + _state->_scoreFrameOffset) {
ImGui::Text(ICON_MS_BEENHERE);
ImGui::SetItemTooltip((*it)->name.c_str());
}
}
}
{
displayScoreChannel(0, kChTempo, 0, selectedWindow);
displayScoreChannel(0, kChPalette, 0, selectedWindow);
displayScoreChannel(0, kChTransition, 0, selectedWindow);
displayScoreChannel(0, kChSound1, 0, selectedWindow);
displayScoreChannel(0, kChSound2, 0, selectedWindow);
displayScoreChannel(0, kChScript, 0, selectedWindow);
}
ImGui::TableNextRow();
int mode = _state->_scoreMode;
for (int ch = 0; ch < (int)numChannels - 1; ch++) {
if (mode == kModeExtended) // This will render empty row
displayScoreChannel(ch + 1, kModeExtended, _state->_scoreMode, selectedWindow);
if (mode == kModeMember || mode == kModeExtended)
displayScoreChannel(ch + 1, kModeMember, _state->_scoreMode, selectedWindow);
if (mode == kModeBehavior || mode == kModeExtended)
displayScoreChannel(ch + 1, kModeBehavior, _state->_scoreMode, selectedWindow);
if (mode == kModeInk || mode == kModeExtended)
displayScoreChannel(ch + 1, kModeInk, _state->_scoreMode, selectedWindow);
if (mode == kModeBlend || mode == kModeExtended)
displayScoreChannel(ch + 1, kModeBlend, _state->_scoreMode, selectedWindow);
if (mode == kModeLocation || mode == kModeExtended)
displayScoreChannel(ch + 1, kModeLocation, _state->_scoreMode, selectedWindow);
}
ImGui::EndTable();
}
ImGui::EndChild();
{ // Render pagination
ImGui::BeginDisabled(numFrames <= FRAME_PAGE_SIZE);
ImGui::Text(" Jump to frame:");
ImGui::SameLine();
ImGui::SliderInt("##scorepage", &_state->_scorePageSlider, 0, numFrames / FRAME_PAGE_SIZE, "%d00");
_state->_scoreFrameOffset = _state->_scorePageSlider * FRAME_PAGE_SIZE + 1;
ImGui::EndDisabled();
ImGui::SameLine();
ImGui::Button(ICON_MS_ALIGN_JUSTIFY_CENTER, ImVec2(20, 20));
ImGui::SetItemTooltip("Center View");
}
}
ImGui::End();
}
void showChannels() {
if (!_state->_w.channels)
return;
ImVec2 pos(40, 40);
ImGui::SetNextWindowPos(pos, ImGuiCond_FirstUseEver);
ImVec2 windowSize = ImGui::GetMainViewport()->Size - pos - pos;
ImGui::SetNextWindowSize(windowSize, ImGuiCond_FirstUseEver);
if (ImGui::Begin("Channels", &_state->_w.channels)) {
Window *selectedWindow = windowListCombo(&_state->_scoreWindow);
Score *score = selectedWindow->getCurrentMovie()->getScore();
const Frame &frame = *score->_currentFrame;
CastMemberID defaultPalette = selectedWindow->getCurrentMovie()->_defaultPalette;
ImGui::Text("TMPO: tempo: %d, skipFrameFlag: %d, blend: %d, currentFPS: %d",
frame._mainChannels.tempo, frame._mainChannels.skipFrameFlag, frame._mainChannels.blend, score->_currentFrameRate);
if (!frame._mainChannels.palette.paletteId.isNull()) {
ImGui::Text("PAL: paletteId: %s, firstColor: %d, lastColor: %d, flags: %d, cycleCount: %d, speed: %d, frameCount: %d, fade: %d, delay: %d, style: %d, currentId: %s, defaultId: %s",
frame._mainChannels.palette.paletteId.asString().c_str(), frame._mainChannels.palette.firstColor, frame._mainChannels.palette.lastColor, frame._mainChannels.palette.flags,
frame._mainChannels.palette.cycleCount, frame._mainChannels.palette.speed, frame._mainChannels.palette.frameCount,
frame._mainChannels.palette.fade, frame._mainChannels.palette.delay, frame._mainChannels.palette.style, g_director->_lastPalette.asString().c_str(), defaultPalette.asString().c_str());
} else {
ImGui::Text("PAL: paletteId: 000, currentId: %s, defaultId: %s\n", g_director->_lastPalette.asString().c_str(), defaultPalette.asString().c_str());
}
ImGui::Text("TRAN: transType: %d, transDuration: %d, transChunkSize: %d",
frame._mainChannels.transType, frame._mainChannels.transDuration, frame._mainChannels.transChunkSize);
ImGui::Text("SND: 1 sound1: %d, soundType1: %d", frame._mainChannels.sound1.member, frame._mainChannels.soundType1);
ImGui::Text("SND: 2 sound2: %d, soundType2: %d", frame._mainChannels.sound2.member, frame._mainChannels.soundType2);
ImGui::Text("LSCR: actionId: %s", frame._mainChannels.actionId.asString().c_str());
int columns = 22;
if (score->_version >= kFileVer600) {
columns += 1; // sprite name
}
if (ImGui::BeginTable("Channels", columns, ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg)) {
ImGuiTableFlags flags = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_AngledHeader;
ImGui::TableSetupColumn("##toggle", flags);
ImGui::TableSetupColumn("CH", flags);
ImGui::TableSetupColumn("castId", flags);
ImGui::TableSetupColumn("vis", flags);
ImGui::TableSetupColumn("inkData", flags);
ImGui::TableSetupColumn("ink", flags);
ImGui::TableSetupColumn("trails", flags);
ImGui::TableSetupColumn("stretch", flags);
ImGui::TableSetupColumn("line", flags);
ImGui::TableSetupColumn("dims", flags);
ImGui::TableSetupColumn("type", flags);
ImGui::TableSetupColumn("fg", flags);
ImGui::TableSetupColumn("bg", flags);
if (score->_version >= kFileVer600) {
ImGui::TableSetupColumn("behaviors", flags);
} else {
ImGui::TableSetupColumn("script", flags);
}
if (score->_version >= kFileVer600)
ImGui::TableSetupColumn("name", flags);
ImGui::TableSetupColumn("colorcode", flags);
ImGui::TableSetupColumn("blendAmount", flags);
ImGui::TableSetupColumn("unk3", flags);
ImGui::TableSetupColumn("constraint", flags);
ImGui::TableSetupColumn("puppet", flags);
ImGui::TableSetupColumn("moveable", flags);
ImGui::TableSetupColumn("movieRate", flags);
ImGui::TableSetupColumn("movieTime", flags);
ImGui::TableAngledHeadersRow();
for (int i = 0; i < MIN<int>(frame._numChannels, score->_maxChannelsUsed + 10); i++) {
Channel &channel = *score->_channels[i + 1];
Sprite &sprite = *channel._sprite;
ImGui::TableNextRow();
{ // Playback toggle
ImGui::TableNextColumn();
ImGui::PushID(i + 20000);
ImDrawList *dl = ImGui::GetWindowDrawList();
const ImVec2 pos1 = ImGui::GetCursorScreenPos();
const ImVec2 mid(pos1.x + 7, pos1.y + 7);
ImGui::InvisibleButton("Line", ImVec2(16, ImGui::GetFontSize()));
ImGui::SetItemTooltip("Playback toggle");
if (ImGui::IsItemClicked(0)) {
score->_channels[i]->_visible = !score->_channels[i]->_visible;
selectedWindow->render(true);
}
if (score->_channels[i]->_visible)
dl->AddCircleFilled(mid, 4.0f, ImColor(_state->_colors._channel_toggle));
else
dl->AddCircle(mid, 4.0f, ImColor(_state->_colors._channel_toggle));
ImGui::PopID();
}
ImGui::TableNextColumn();
bool isSelected = (_state->_selectedChannel == i + 1);
if (ImGui::Selectable(Common::String::format("%-3d", i + 1).c_str(), isSelected, ImGuiSelectableFlags_SpanAllColumns)) {
if (isSelected) {
_state->_selectedChannel = -1;
} else {
_state->_selectedChannel = i + 1;
}
selectedWindow->render(true);
}
ImGui::TableNextColumn();
if (sprite._castId.member) {
Common::String chNum = Common::String::format("%d", i);
Common::String colN;
Common::Point position = channel.getPosition();
ImGui::Text("%s", sprite._castId.asString().c_str());
ImGui::TableNextColumn();
colN = "##vis" + chNum;
ImGui::Checkbox(colN.c_str(), &channel._visible);
ImGui::TableNextColumn();
ImGui::Text("0x%02x", sprite._inkData);
ImGui::TableNextColumn();
ImGui::Text("%d (%s)", sprite._ink, inkType2str(sprite._ink));
ImGui::TableNextColumn();
colN = "##trails" + chNum;
ImGui::Checkbox(colN.c_str(), &sprite._trails);
ImGui::TableNextColumn();
colN = "##stretch" + chNum;
ImGui::Checkbox(colN.c_str(), &sprite._stretch);
ImGui::TableNextColumn();
ImGui::Text("%d", sprite._thickness);
ImGui::TableNextColumn();
ImGui::Text("%dx%d@%d,%d", channel.getWidth(), channel.getHeight(), position.x, position.y);
ImGui::TableNextColumn();
ImGui::Text("%d (%s)", sprite._spriteType, spriteType2str(sprite._spriteType));
ImGui::TableNextColumn();
ImGui::PushID(i + 1);
ImGui::Text("%3d", sprite._foreColor); ImGui::SameLine();
ImGui::ColorButton("foreColor", convertColor(sprite._foreColor));
ImGui::PopID();
ImGui::TableNextColumn();
ImGui::PushID(i + 1);
ImGui::Text("%3d", sprite._backColor); ImGui::SameLine();
ImGui::ColorButton("backColor", convertColor(sprite._backColor));
ImGui::PopID();
ImGui::TableNextColumn();
if (score->_version >= kFileVer600) {
if (sprite._behaviors.size() > 0) {
for (uint j = 0; j < sprite._behaviors.size(); j++) {
displayScriptRef(sprite._behaviors[j].memberID);
ImGui::SameLine();
if (sprite._behaviors[j].initializerIndex) {
ImGui::Text("(%s)", sprite._behaviors[j].initializerParams.c_str());
} else {
ImGui::Text("(\"\")");
}
}
} else {
ImGui::PushID(i + 1);
ImGui::TextUnformatted(" ");
ImGui::PopID();
}
} else {
// Check early for non integer script ids
if (sprite._scriptId.member) {
displayScriptRef(sprite._scriptId);
} else {
ImGui::PushID(i + 1);
ImGui::TextUnformatted(" ");
ImGui::PopID();
}
}
if (score->_version >= kFileVer600) {
ImGui::TableNextColumn();
if (sprite._spriteListIdx) {
Common::MemoryReadStreamEndian *stream = score->getSpriteDetailsStream(sprite._spriteListIdx + 2);
Common::String name;
if (stream)
name = stream->readPascalString();
ImGui::Text("%s", name.c_str());
} else {
ImGui::Text(" ");
}
}
ImGui::TableNextColumn();
ImGui::Text("0x%x", sprite._colorcode);
ImGui::TableNextColumn();
ImGui::Text("0x%x", sprite._blendAmount);
ImGui::TableNextColumn();
ImGui::Text("0x%x", sprite._unk3);
ImGui::TableNextColumn();
ImGui::Text("%d", channel._constraint);
ImGui::TableNextColumn();
colN = "##puppet" + chNum;
ImGui::Checkbox(colN.c_str(), &sprite._puppet);
ImGui::TableNextColumn();
colN = "##moveable" + chNum;
ImGui::Checkbox(colN.c_str(), &sprite._moveable);
ImGui::TableNextColumn();
if (channel._movieRate)
ImGui::Text("%f", channel._movieRate);
else
ImGui::Text("0");
ImGui::TableNextColumn();
if (channel._movieRate)
ImGui::Text("%d (%f)", channel._movieTime, (float)(channel._movieTime/60.0f));
else
ImGui::Text("0");
} else {
ImGui::Text("000");
}
}
ImGui::EndTable();
}
}
ImGui::End();
}
} // namespace DT
} // namespace Director

View File

@@ -0,0 +1,880 @@
/* 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 "director/director.h"
#include "director/movie.h"
#include "director/cast.h"
#include "director/debugger/dt-internal.h"
#include "director/debugger.h"
#include "director/lingo/lingo-ast.h"
#include "director/lingo/lingo-code.h"
#include "director/lingo/lingo-object.h"
#include "director/lingo/lingo-the.h"
namespace Director {
namespace DT {
class RenderOldScriptVisitor : public NodeVisitor {
private:
ImGuiScript &_script;
int _indent = 0;
bool _isScriptInDebug = false;
bool _currentStatementDisplayed = false;
bool _scrollTo = false;
bool _scrollDone = true;
public:
explicit RenderOldScriptVisitor(ImGuiScript &script, bool scrollTo) : _script(script), _scrollTo(scrollTo) {
Common::Array<CFrame *> &callstack = g_lingo->_state->callstack;
if (!callstack.empty()) {
CFrame *head = callstack[callstack.size() - 1];
_isScriptInDebug = (head->sp.ctx->_id == script.id.member) && (*head->sp.name == script.handlerId);
}
_script.startOffsets.clear();
}
virtual bool visitHandlerNode(HandlerNode *node) {
ImGui::Text("on ");
ImGui::SameLine();
ImGui::TextColored(_state->_colors._call_color, "%s", node->name->c_str());
if (!node->args->empty()) {
ImGui::SameLine();
ImGui::Text(" ");
ImGui::SameLine();
for (uint i = 0; i < node->args->size(); i++) {
Common::String *arg = (*node->args)[i];
ImGui::Text("%s", arg->c_str());
ImGui::SameLine();
if (i != (node->args->size() - 1)) {
ImGui::Text(", ");
ImGui::SameLine();
}
}
ImGui::NewLine();
}
if (_state->_dbg._goToDefinition && _scrollTo) {
ImGui::SetScrollHereY(0.5f);
_state->_dbg._goToDefinition = false;
}
indent();
for (uint i = 0; i < node->stmts->size(); i++) {
Node *stmt = (*node->stmts)[i];
renderLine(stmt->startOffset);
stmt->accept(this);
ImGui::NewLine();
}
unindent();
renderLine(node->endOffset);
ImGui::TextColored(_state->_colors._keyword_color, "end");
return true;
}
virtual bool visitScriptNode(ScriptNode *node) {
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2());
for (Node *child : *node->children) {
if (child->type == kHandlerNode && *((HandlerNode *)child)->name != _script.handlerId)
continue;
renderLine(child->startOffset);
child->accept(this);
}
ImGui::PopStyleVar();
return true;
}
virtual bool visitFactoryNode(FactoryNode *node) {
ImGui::Text("factory %s", node->name->c_str());
ImGui::NewLine();
indent();
for (uint i = 0; i < node->methods->size(); i++) {
Node *method = (*node->methods)[i];
renderLine(method->startOffset);
method->accept(this);
ImGui::NewLine();
}
unindent();
return true;
}
virtual bool visitCmdNode(CmdNode *node) {
ImGui::Text("%s ", node->name->c_str());
ImGui::SameLine();
if (*node->name == "go") {
ImGui::TextColored(_state->_colors._keyword_color, "to ");
ImGui::SameLine();
}
for (uint i = 0; i < node->args->size(); i++) {
Node *arg = (*node->args)[i];
if ((i != 0) || (node->args->size() < 2) || ((*node->args)[1]->type != kMovieNode)) {
arg->accept(this);
ImGui::SameLine();
if (i != (node->args->size() - 1)) {
ImGui::Text(", ");
ImGui::SameLine();
}
}
}
return true;
}
virtual bool visitPutIntoNode(PutIntoNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "put ");
ImGui::SameLine();
node->val->accept(this);
ImGui::TextColored(_state->_colors._keyword_color, " into ");
ImGui::SameLine();
node->var->accept(this);
return true;
}
virtual bool visitPutAfterNode(PutAfterNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "put ");
ImGui::SameLine();
node->val->accept(this);
ImGui::TextColored(_state->_colors._keyword_color, " after ");
ImGui::SameLine();
node->var->accept(this);
return true;
}
virtual bool visitPutBeforeNode(PutBeforeNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "put ");
ImGui::SameLine();
node->val->accept(this);
ImGui::TextColored(_state->_colors._keyword_color, " before ");
ImGui::SameLine();
node->var->accept(this);
return true;
}
virtual bool visitSetNode(SetNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "set ");
ImGui::SameLine();
node->val->accept(this);
ImGui::TextColored(_state->_colors._keyword_color, " to ");
ImGui::SameLine();
node->var->accept(this);
return true;
}
void displayDefineVar(const char *name, IDList *names) {
ImGui::Text("%s ", name);
ImGui::SameLine();
for (uint i = 0; i < names->size(); i++) {
Common::String *arg = (*names)[i];
ImGui::Text("%s", arg->c_str());
ImGui::SameLine();
if (i != (names->size() - 1)) {
ImGui::Text(" ");
ImGui::SameLine();
}
}
}
virtual bool visitGlobalNode(GlobalNode *node) {
displayDefineVar("global", node->names);
return true;
}
virtual bool visitPropertyNode(PropertyNode *node) {
displayDefineVar("property", node->names);
return true;
}
virtual bool visitInstanceNode(InstanceNode *node) {
displayDefineVar("instance", node->names);
return true;
}
virtual bool visitIfStmtNode(IfStmtNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "if ");
ImGui::SameLine();
node->cond->accept(this);
ImGui::TextColored(_state->_colors._keyword_color, " then ");
if (node->stmts->size() == 1) {
ImGui::SameLine();
(*node->stmts)[0]->accept(this);
} else {
indent();
for (uint i = 0; i < node->stmts->size(); i++) {
Node *stmt = (*node->stmts)[i];
renderLine(stmt->startOffset);
stmt->accept(this);
ImGui::NewLine();
}
unindent();
renderLine(node->endOffset);
ImGui::TextColored(_state->_colors._keyword_color, "endif");
ImGui::SameLine();
}
return true;
}
virtual bool visitIfElseStmtNode(IfElseStmtNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "if ");
ImGui::SameLine();
node->cond->accept(this);
ImGui::TextColored(_state->_colors._keyword_color, " then ");
if (node->stmts1->size() == 1) {
ImGui::SameLine();
(*node->stmts1)[0]->accept(this);
ImGui::Text(" ");
ImGui::SameLine();
} else {
uint offset = node->cond->endOffset;
indent();
for (uint i = 0; i < node->stmts1->size(); i++) {
Node *stmt = (*node->stmts1)[i];
renderLine(stmt->startOffset);
stmt->accept(this);
ImGui::NewLine();
offset = stmt->endOffset;
}
unindent();
renderLine(offset);
}
ImGui::TextColored(_state->_colors._keyword_color, "else ");
if (node->stmts2->size() == 1) {
ImGui::SameLine();
(*node->stmts2)[0]->accept(this);
} else {
uint offset = node->cond->endOffset;
indent();
for (uint i = 0; i < node->stmts2->size(); i++) {
Node *stmt = (*node->stmts2)[i];
renderLine(stmt->startOffset);
stmt->accept(this);
ImGui::NewLine();
offset = stmt->endOffset;
}
unindent();
renderLine(offset);
ImGui::TextColored(_state->_colors._keyword_color, "endif");
ImGui::SameLine();
}
return true;
}
virtual bool visitRepeatWhileNode(RepeatWhileNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "repeat while ");
ImGui::SameLine();
node->cond->accept(this);
ImGui::NewLine();
indent();
uint offset = node->cond->endOffset;
for (uint i = 0; i < node->stmts->size(); i++) {
Node *stmt = (*node->stmts)[i];
renderLine(stmt->startOffset);
stmt->accept(this);
ImGui::NewLine();
offset = stmt->endOffset;
}
unindent();
renderLine(offset);
ImGui::TextColored(_state->_colors._keyword_color, "endrepeat");
return true;
}
virtual bool visitRepeatWithToNode(RepeatWithToNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "repeat with ");
ImGui::SameLine();
ImGui::Text("%s = ", node->var->c_str());
ImGui::SameLine();
node->start->accept(this);
ImGui::TextColored(_state->_colors._keyword_color, " %s ", node->down ? "down to" : "to");
node->end->accept(this);
ImGui::NewLine();
indent();
for (uint i = 0; i < node->stmts->size(); i++) {
Node *stmt = (*node->stmts)[i];
renderLine(stmt->startOffset);
stmt->accept(this);
ImGui::NewLine();
}
unindent();
renderLine(node->endOffset);
ImGui::TextColored(_state->_colors._keyword_color, "endrepeat");
return true;
}
virtual bool visitRepeatWithInNode(RepeatWithInNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "repeat with ");
ImGui::SameLine();
ImGui::Text("%s in ", node->var->c_str());
ImGui::SameLine();
node->list->accept(this);
ImGui::NewLine();
indent();
for (uint i = 0; i < node->stmts->size(); i++) {
Node *stmt = (*node->stmts)[i];
renderLine(stmt->startOffset);
stmt->accept(this);
ImGui::NewLine();
}
unindent();
renderLine(node->endOffset);
ImGui::TextColored(_state->_colors._keyword_color, "endrepeat");
return true;
}
virtual bool visitNextRepeatNode(NextRepeatNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "next repeat");
return true;
}
virtual bool visitExitRepeatNode(ExitRepeatNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "exit repeat");
return true;
}
virtual bool visitExitNode(ExitNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "exit");
return true;
}
virtual bool visitReturnNode(ReturnNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "return");
if (node->expr) {
ImGui::Text(" ");
ImGui::SameLine();
node->expr->accept(this);
ImGui::NewLine();
}
return true;
}
virtual bool visitTellNode(TellNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "tell ");
node->target->accept(this);
if (node->stmts->size() == 1) {
ImGui::SameLine();
ImGui::TextColored(_state->_colors._keyword_color, " to ");
ImGui::SameLine();
(*node->stmts)[0]->accept(this);
} else {
indent();
for (uint i = 0; i < node->stmts->size(); i++) {
Node *stmt = (*node->stmts)[i];
renderLine(stmt->startOffset);
stmt->accept(this);
ImGui::NewLine();
}
unindent();
renderLine(node->endOffset);
ImGui::TextColored(_state->_colors._keyword_color, "endtell");
}
return true;
}
virtual bool visitWhenNode(WhenNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "when ");
ImGui::SameLine();
ImGui::Text("%s", node->event->c_str());
ImGui::SameLine();
ImGui::TextColored(_state->_colors._keyword_color, " then ");
ImGui::SameLine();
ImGui::Text("%s", node->code->c_str());
ImGui::SameLine();
return true;
}
virtual bool visitDeleteNode(DeleteNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "delete ");
ImGui::SameLine();
node->chunk->accept(this);
return true;
}
virtual bool visitHiliteNode(HiliteNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "hilite ");
ImGui::SameLine();
node->chunk->accept(this);
return true;
}
virtual bool visitAssertErrorNode(AssertErrorNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "scummvmAssertError ");
ImGui::SameLine();
node->stmt->accept(this);
return true;
}
virtual bool visitIntNode(IntNode *node) {
ImGui::TextColored(_state->_colors._literal_color, "%d", node->val);
ImGui::SameLine();
return true;
}
virtual bool visitFloatNode(FloatNode *node) {
ImGui::TextColored(_state->_colors._literal_color, "%g", node->val);
ImGui::SameLine();
return true;
}
virtual bool visitSymbolNode(SymbolNode *node) {
ImGui::TextColored(_state->_colors._literal_color, "%s", node->val->c_str());
ImGui::SameLine();
return true;
}
virtual bool visitStringNode(StringNode *node) {
ImGui::TextColored(_state->_colors._literal_color, "\"%s\"", node->val->c_str());
ImGui::SameLine();
return true;
}
virtual bool visitListNode(ListNode *node) {
ImGui::Text("[");
ImGui::SameLine();
for (uint i = 0; i < node->items->size(); i++) {
Node *prop = (*node->items)[i];
prop->accept(this);
if (i != (node->items->size() - 1)) {
ImGui::Text(",");
ImGui::SameLine();
}
}
ImGui::Text("]");
ImGui::SameLine();
return true;
}
virtual bool visitPropListNode(PropListNode *node) {
ImGui::Text("[");
ImGui::SameLine();
if (node->items->empty()) {
ImGui::Text(":");
ImGui::SameLine();
} else {
for (uint i = 0; i < node->items->size(); i++) {
Node *prop = (*node->items)[i];
prop->accept(this);
if (i != (node->items->size() - 1)) {
ImGui::Text(",");
ImGui::SameLine();
}
}
}
ImGui::Text("]");
ImGui::SameLine();
return true;
}
virtual bool visitPropPairNode(PropPairNode *node) {
node->key->accept(this);
ImGui::Text(":");
ImGui::SameLine();
node->val->accept(this);
return true;
}
virtual bool visitFuncNode(FuncNode *node) {
const bool isBuiltin = g_lingo->_builtinCmds.contains(*node->name);
const ImVec4 color = (ImVec4)ImColor(isBuiltin ? _state->_colors._builtin_color : _state->_colors._call_color);
ImGui::TextColored(color, "%s(", node->name->c_str());
if (!isBuiltin && ImGui::IsItemHovered() && ImGui::BeginTooltip()) {
ImGui::Text("Go to definition");
ImGui::EndTooltip();
}
if (!isBuiltin && ImGui::IsItemClicked()) {
int obj = 0;
for (uint i = 0; i < _script.bytecodeArray.size(); i++) {
if (node->startOffset == _script.bytecodeArray[i].pos) {
obj = _script.bytecodeArray[i].obj;
break;
}
}
ScriptContext *context = getScriptContext(obj, _script.id, *node->name);
if (context) {
ImGuiScript script = toImGuiScript(_script.type, CastMemberID(context->_id, _script.id.castLib), *node->name);
const Director::Movie *movie = g_director->getCurrentMovie();
int castId = context->_id;
bool childScript = false;
if (castId == -1) {
castId = movie->getCast()->getCastIdByScriptId(context->_parentNumber);
childScript = true;
}
script.byteOffsets = context->_functionByteOffsets[script.handlerId];
script.moviePath = _script.moviePath;
script.handlerName = formatHandlerName(context->_scriptId, castId, script.handlerId, context->_scriptType, childScript);
setScriptToDisplay(script);
_state->_dbg._goToDefinition = true;
}
}
ImGui::SameLine();
for (uint i = 0; i < node->args->size(); i++) {
Node *arg = (*node->args)[i];
arg->accept(this);
if (i != (node->args->size() - 1)) {
ImGui::Text(",");
ImGui::SameLine();
}
}
ImGui::Text(")");
ImGui::SameLine();
return true;
}
virtual bool visitVarNode(VarNode *node) {
ImGui::TextColored(_state->_colors._var_color, "%s", node->name->c_str());
if (ImGui::IsItemHovered() && g_lingo->_globalvars.contains(*node->name)) {
const Datum &val = g_lingo->_globalvars.getVal(*node->name);
ImGui::BeginTooltip();
ImGui::Text("Click to add to watches.");
Common::String s = val.asString(true);
s.wordWrap(150);
if (s.size() > 4000) {
uint chop = s.size() - 4000;
s.chop(s.size() - 4000);
s += Common::String::format("... [chopped %d chars]", chop);
}
ImGui::Text("= %s", s.c_str());
ImGui::EndTooltip();
}
if (ImGui::IsItemClicked()) {
_state->_variables[*node->name] = true;
}
ImGui::SameLine();
return true;
}
virtual bool visitParensNode(ParensNode *node) {
ImGui::Text("(");
ImGui::SameLine();
node->expr->accept(this);
ImGui::Text(")");
ImGui::SameLine();
return true;
}
virtual bool visitUnaryOpNode(UnaryOpNode *node) {
char op = '?';
if (node->op == LC::c_negate) {
op = '-';
} else if (node->op == LC::c_not) {
op = '!';
}
ImGui::Text("%c", op);
ImGui::SameLine();
node->arg->accept(this);
return true;
}
virtual bool visitBinaryOpNode(BinaryOpNode *node) {
node->a->accept(this);
static struct {
inst op;
const char *name;
} ops[] = {
{LC::c_add, "+"},
{LC::c_sub, "-"},
{LC::c_mul, "*"},
{LC::c_div, "/"},
{LC::c_mod, "mod"},
{LC::c_gt, ">"},
{LC::c_lt, "<"},
{LC::c_eq, "="},
{LC::c_neq, "<>"},
{LC::c_ge, ">="},
{LC::c_le, "<="},
{LC::c_and, "and"},
{LC::c_or, "or"},
{LC::c_ampersand, "&"},
{LC::c_concat, "&&"},
{LC::c_contains, "contains"},
{LC::c_starts, "starts"},
};
for (auto &op : ops) {
if (op.op == node->op) {
ImGui::Text(" %s ", op.name);
ImGui::SameLine();
break;
}
}
node->b->accept(this);
return true;
}
virtual bool visitFrameNode(FrameNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "frame ");
ImGui::SameLine();
node->arg->accept(this);
return true;
}
virtual bool visitMovieNode(MovieNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "movie ");
ImGui::SameLine();
node->arg->accept(this);
return true;
}
virtual bool visitIntersectsNode(IntersectsNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "sprite ");
ImGui::SameLine();
node->sprite1->accept(this);
ImGui::TextColored(_state->_colors._keyword_color, "intersects ");
node->sprite2->accept(this);
return true;
}
virtual bool visitWithinNode(WithinNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "sprite ");
ImGui::SameLine();
node->sprite1->accept(this);
ImGui::TextColored(_state->_colors._keyword_color, "within ");
node->sprite2->accept(this);
return true;
}
virtual bool visitTheNode(TheNode *node) {
ImGui::TextColored(_state->_colors._the_color, "the %s", node->prop->c_str());
ImGui::SameLine();
return true;
}
virtual bool visitTheOfNode(TheOfNode *node) {
ImGui::TextColored(_state->_colors._the_color, "the %s of ", node->prop->c_str());
ImGui::SameLine();
node->obj->accept(this);
return true;
}
virtual bool visitTheNumberOfNode(TheNumberOfNode *node) {
ImGui::TextColored(_state->_colors._the_color, "the number of ");
ImGui::SameLine();
node->arg->accept(this);
return true;
}
virtual bool visitTheLastNode(TheLastNode *node) {
// TODO: change the node to know if it's 'in' or 'of'
ImGui::TextColored(_state->_colors._the_color, "the last %s in/of ", toString(node->type).c_str());
ImGui::SameLine();
node->arg->accept(this);
return true;
}
virtual bool visitTheDateTimeNode(TheDateTimeNode *node) {
const char *key1 = "";
switch (node->field) {
case kTheAbbr:
key1 = "abbreviated";
break;
case kTheLong:
key1 = "long";
break;
case kTheShort:
key1 = "short";
break;
}
const char *key2 = node->entity == kTheDate ? "date" : "time";
ImGui::TextColored(_state->_colors._the_color, "the %s %s", key1, key2);
ImGui::SameLine();
return true;
}
virtual bool visitMenuNode(MenuNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "menu ");
ImGui::SameLine();
node->arg->accept(this);
return true;
}
virtual bool visitMenuItemNode(MenuItemNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "menuitem ");
ImGui::SameLine();
node->arg1->accept(this);
ImGui::TextColored(_state->_colors._keyword_color, "of menu ");
ImGui::SameLine();
node->arg2->accept(this);
return true;
}
virtual bool visitSoundNode(SoundNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "sound ");
ImGui::SameLine();
node->arg->accept(this);
return true;
}
virtual bool visitSpriteNode(SpriteNode *node) {
ImGui::TextColored(_state->_colors._keyword_color, "sprite ");
ImGui::SameLine();
node->arg->accept(this);
return true;
}
virtual bool visitChunkExprNode(ChunkExprNode *node) {
const char *key1 = "";
switch (node->type) {
case kChunkChar:
key1 = "char";
break;
case kChunkWord:
key1 = "word";
break;
case kChunkItem:
key1 = "item";
break;
case kChunkLine:
key1 = "line";
break;
}
ImGui::Text("%s", key1);
ImGui::SameLine();
node->start->accept(this);
if (node->end) {
ImGui::TextColored(_state->_colors._keyword_color, " to ");
ImGui::SameLine();
node->end->accept(this);
}
ImGui::TextColored(_state->_colors._keyword_color, " of ");
ImGui::SameLine();
node->src->accept(this);
return true;
}
private:
static Common::String toString(ChunkType chunkType) {
// TODO: this method could be used in ChunkExprNode
switch (chunkType) {
case kChunkChar:
return "char";
case kChunkWord:
return "word";
case kChunkItem:
return "item";
case kChunkLine:
return "line";
}
return "<unknown>";
}
void indent() {
_indent++;
}
void unindent() {
if (_indent > 0)
_indent--;
}
void renderIndentation() const {
for (int i = 0; i < _indent; i++) {
ImGui::Text(" ");
ImGui::SameLine();
}
}
void renderLine(uint32 pc) {
bool showCurrentStatement = false;
_script.startOffsets.push_back(pc);
if (_script.pc != 0 && pc >= _script.pc) {
if (!_currentStatementDisplayed) {
showCurrentStatement = true;
_currentStatementDisplayed = true;
}
} else if (_isScriptInDebug && g_lingo->_exec._state == kPause) {
// check current statement
if (!_currentStatementDisplayed) {
if (g_lingo->_state->pc <= pc) {
showCurrentStatement = true;
_currentStatementDisplayed = true;
}
}
}
ImDrawList *dl = ImGui::GetWindowDrawList();
const ImVec2 pos = ImGui::GetCursorScreenPos();
const float width = ImGui::GetContentRegionAvail().x;
const ImVec2 mid(pos.x + 7, pos.y + 7);
ImVec4 color = _state->_colors._bp_color_disabled;
const Director::Breakpoint *bp = getBreakpoint(_script.handlerId, _script.id.member, pc);
if (bp)
color = _state->_colors._bp_color_enabled;
ImGui::InvisibleButton("Line", ImVec2(16, ImGui::GetFontSize()));
// click on breakpoint column?
if (ImGui::IsItemClicked(0)) {
if (color == _state->_colors._bp_color_enabled) {
g_lingo->delBreakpoint(bp->id);
color = _state->_colors._bp_color_disabled;
} else {
Director::Breakpoint newBp;
newBp.type = kBreakpointFunction;
newBp.scriptId = _script.id.member;
newBp.funcName = _script.handlerId;
newBp.funcOffset = pc;
g_lingo->addBreakpoint(newBp);
color = _state->_colors._bp_color_enabled;
}
}
if (color == _state->_colors._bp_color_disabled && ImGui::IsItemHovered()) {
color = _state->_colors._bp_color_hover;
}
// draw breakpoint
if (!bp || bp->enabled)
dl->AddCircleFilled(mid, 4.0f, ImColor(color));
else
dl->AddCircle(mid, 4.0f, ImColor(_state->_colors._line_color));
// draw current statement
if (showCurrentStatement) {
dl->AddQuadFilled(ImVec2(pos.x, pos.y + 4.f), ImVec2(pos.x + 9.f, pos.y + 4.f), ImVec2(pos.x + 9.f, pos.y + 10.f), ImVec2(pos.x, pos.y + 10.f), ImColor(_state->_colors._current_statement));
dl->AddTriangleFilled(ImVec2(pos.x + 8.f, pos.y), ImVec2(pos.x + 14.f, pos.y + 7.f), ImVec2(pos.x + 8.f, pos.y + 14.f), ImColor(_state->_colors._current_statement));
if (!_scrollDone && _scrollTo && g_lingo->_state->callstack.size() != _state->_dbg._callstackSize) {
ImGui::SetScrollHereY(0.5f);
_scrollDone = true;
}
dl->AddRectFilled(ImVec2(pos.x + 16.f, pos.y), ImVec2(pos.x + width, pos.y + 16.f), ImColor(IM_COL32(0xFF, 0xFF, 0x00, 0x20)), 0.4f);
}
// draw separator
dl->AddLine(ImVec2(pos.x + 16.0f, pos.y), ImVec2(pos.x + 16.0f, pos.y + 17), ImColor(_state->_colors._line_color));
ImGui::SetItemTooltip("Click to add a breakpoint");
ImGui::SameLine();
// draw offset
ImGui::Text("[%5d] ", pc == 0xFFFFFFFF ? -1 : pc);
ImGui::SameLine();
renderIndentation();
}
};
void renderOldScriptAST(ImGuiScript &script, bool showByteCode, bool scrollTo) {
RenderOldScriptVisitor oldVisitor(script, scrollTo);
script.oldAst->accept(&oldVisitor);
}
} // namespace DT
} // namespace Director

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,791 @@
/* 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 "backends/imgui/IconsMaterialSymbols.h"
#include "backends/imgui/imgui_utils.h"
#include "director/director.h"
#include "director/debugger/dt-internal.h"
#include "director/archive.h"
#include "director/window.h"
#include "director/cast.h"
#include "director/debugger.h"
#include "director/movie.h"
#include "director/castmember/castmember.h"
#include "director/lingo/lingo-object.h"
namespace Director {
namespace DT {
static void renderCastScript(Symbol &sym) {
if (sym.type != HANDLER)
return;
Director::Lingo *lingo = g_director->getLingo();
Common::String handlerName;
if (sym.ctx && sym.ctx->_id)
handlerName = Common::String::format("%d:", sym.ctx->_id);
handlerName += lingo->formatFunctionName(sym);
ImGui::Text("%s", handlerName.c_str());
ImDrawList *dl = ImGui::GetWindowDrawList();
ImVec4 color;
uint pc = 0;
while (pc < sym.u.defn->size()) {
ImVec2 pos = ImGui::GetCursorScreenPos();
const ImVec2 mid(pos.x + 7, pos.y + 7);
Common::String bpName = Common::String::format("%s-%d", handlerName.c_str(), pc);
color = _state->_colors._bp_color_disabled;
Director::Breakpoint *bp = getBreakpoint(handlerName, sym.ctx->_id, pc);
if (bp)
color = _state->_colors._bp_color_enabled;
ImGui::PushID(pc);
ImGui::InvisibleButton("Line", ImVec2(16, ImGui::GetFontSize()));
if (ImGui::IsItemClicked(0)) {
if (bp) {
g_lingo->delBreakpoint(bp->id);
color = _state->_colors._bp_color_disabled;
} else {
Director::Breakpoint newBp;
newBp.type = kBreakpointFunction;
newBp.funcName = handlerName;
newBp.funcOffset = pc;
g_lingo->addBreakpoint(newBp);
color = _state->_colors._bp_color_enabled;
}
}
if (color == _state->_colors._bp_color_disabled && ImGui::IsItemHovered()) {
color = _state->_colors._bp_color_hover;
}
dl->AddCircleFilled(mid, 4.0f, ImColor(color));
dl->AddLine(ImVec2(pos.x + 16.0f, pos.y), ImVec2(pos.x + 16.0f, pos.y + 17), ImColor(_state->_colors._line_color));
ImGui::SetItemTooltip("Click to add a breakpoint");
ImGui::SameLine();
ImGui::Text("[%5d] ", pc);
ImGui::SameLine();
ImGui::Text("%s", lingo->decodeInstruction(sym.u.defn, pc, &pc).c_str());
ImGui::PopID();
}
}
static void renderScript(ImGuiScript &script, bool showByteCode, bool scrollTo) {
if (script.oldAst) {
renderOldScriptAST(script, showByteCode, scrollTo);
return;
}
if (!script.root)
return;
renderScriptAST(script, showByteCode, scrollTo);
}
static void renderCallStack(uint pc) {
Common::Array<CFrame *> callstack = g_lingo->_state->callstack;
if (callstack.size() == 0) {
ImGui::Text("End of execution\n");
return;
}
const Movie *movie = g_director->getCurrentMovie();
ImGui::Text("Call stack:\n");
for (int i = 0; i < (int)callstack.size(); i++) {
Common::String stackFrame;
CFrame *frame = callstack[callstack.size() - i - 1];
uint framePc = pc;
if (i > 0)
framePc = callstack[callstack.size() - i]->retPC;
if (frame->sp.type != VOIDSYM) {
stackFrame = Common::String::format("#%d ", i);
stackFrame += Common::String::format("%d ", frame->sp.ctx->_scriptId);
if (frame->sp.ctx && frame->sp.ctx->_id != -1) {
stackFrame += Common::String::format("(%d): ", frame->sp.ctx->_id);
} else if (frame->sp.ctx) {
stackFrame += Common::String::format("(<p%d>): ", movie->getCast()->getCastIdByScriptId(frame->sp.ctx->_parentNumber));
}
if (frame->sp.ctx && frame->sp.ctx->isFactory()) {
stackFrame += Common::String::format("%s:", frame->sp.ctx->getName().c_str());
}
stackFrame += Common::String::format("%s at [%5d]\n",
frame->sp.name->c_str(),
framePc
);
} else {
stackFrame = Common::String::format("#%d [unknown] at [%5d]\n",
i,
framePc
);
}
if (ImGui::Selectable(stackFrame.c_str())) {
CFrame *head = callstack[callstack.size() - i - 1];
ScriptContext *scriptContext = head->sp.ctx;
int castLibID = movie->getCast()->_castLibID;
int castId = head->sp.ctx->_id;
bool childScript = false;
if (castId == -1) {
castId = movie->getCast()->getCastIdByScriptId(head->sp.ctx->_parentNumber);
childScript = true;
}
ImGuiScript script = toImGuiScript(scriptContext->_scriptType, CastMemberID(castId, castLibID), *head->sp.name);
script.byteOffsets = head->sp.ctx->_functionByteOffsets[script.handlerId];
script.moviePath = movie->getArchive()->getPathName().toString();
script.handlerName = formatHandlerName(head->sp.ctx->_scriptId, castId, script.handlerName, head->sp.ctx->_scriptType, childScript);
script.pc = framePc;
setScriptToDisplay(script);
}
}
}
static bool showScriptCast(CastMemberID &id) {
Common::String wName("Script ");
wName += id.asString();
ImGui::SetNextWindowPos(ImVec2(20, 160), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(240, 240), ImGuiCond_FirstUseEver);
bool closed = true;
if (ImGui::Begin(wName.c_str(), &closed)) {
Cast *cast = g_director->getCurrentMovie()->getCasts()->getVal(id.castLib);
ScriptContext *ctx = g_director->getCurrentMovie()->getScriptContext(kScoreScript, id);
if (ctx) {
for (auto &handler : ctx->_functionHandlers)
renderCastScript(handler._value);
} else if (cast->_lingoArchive->factoryContexts.contains(id.member)) {
for (auto &it : *cast->_lingoArchive->factoryContexts.getVal(id.member)) {
for (auto &handler : it._value->_functionHandlers)
renderCastScript(handler._value);
}
} else {
ImGui::Text("[Nothing]");
}
}
ImGui::End();
if (!closed)
return false;
return true;
}
/**
* Display all open scripts
*/
void showScriptCasts() {
if (_state->_scriptCasts.empty())
return;
for (Common::List<CastMemberID>::iterator scr = _state->_scriptCasts.begin(); scr != _state->_scriptCasts.end();) {
if (!showScriptCast(*scr))
scr = _state->_scriptCasts.erase(scr);
else
scr++;
}
}
static void addToOpenHandlers(ImGuiScript handler) {
_state->_openHandlers.erase(handler.id.member);
_state->_openHandlers[handler.id.member] = handler;
}
static bool showHandler(ImGuiScript handler) {
ScriptContext *ctx = getScriptContext(handler.id);
Common::String wName;
if (ctx) {
wName = Common::String(ctx->asString());
}
ImGui::SetNextWindowPos(ImVec2(20, 160), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(480, 540), ImGuiCond_FirstUseEver);
bool closed = true;
if (ImGui::Begin(wName.c_str(), &closed)) {
ImGuiEx::toggleButton(ICON_MS_PACKAGE_2, &_state->_showCompleteScript, true); // Lingo
ImGui::SetItemTooltip("Show Handler");
ImGui::SameLine();
ImGuiEx::toggleButton(ICON_MS_STACKS, &_state->_showCompleteScript); // Bytecode
ImGui::SetItemTooltip("Show Script Context");
if (!ctx || ctx->_functionHandlers.size() <= 1 || !_state->_showCompleteScript) {
renderScript(handler, false, true);
} else {
for (auto &functionHandler : ctx->_functionHandlers) {
ImGuiScript script = toImGuiScript(ctx->_scriptType, handler.id, functionHandler._key);
script.byteOffsets = ctx->_functionByteOffsets[script.handlerId];
if (script == handler) {
_state->_dbg._goToDefinition = true;
}
renderScript(script, false, script == handler);
ImGui::NewLine();
}
}
}
ImGui::End();
if (!closed)
return false;
return true;
}
/**
* Display all open handlers
*/
void showHandlers() {
if (_state->_openHandlers.empty()) {
return;
}
for (auto handler : _state->_openHandlers) {
if (!showHandler(handler._value)) {
_state->_openHandlers.erase(handler._value.id.member);
}
}
}
static void updateCurrentScript() {
if ((g_lingo->_exec._state != kPause) || !_state->_dbg._isScriptDirty)
return;
Common::Array<CFrame *> &callstack = g_lingo->_state->callstack;
if (callstack.empty())
return;
// show current script of the current stack frame
CFrame *head = callstack[callstack.size() - 1];
const Director::Movie *movie = g_director->getCurrentMovie();
ScriptContext *scriptContext = head->sp.ctx;
int castLibID = movie->getCast()->_castLibID;
int castId = head->sp.ctx->_id;
bool childScript = false;
if (castId == -1) {
castId = movie->getCast()->getCastIdByScriptId(head->sp.ctx->_parentNumber);
childScript = true;
}
ImGuiScript script = toImGuiScript(scriptContext->_scriptType, CastMemberID(castId, castLibID), *head->sp.name);
script.byteOffsets = scriptContext->_functionByteOffsets[script.handlerId];
script.moviePath = movie->getArchive()->getPathName().toString();
script.handlerName = formatHandlerName(head->sp.ctx->_scriptId, castId, script.handlerName, head->sp.ctx->_scriptType, childScript);
script.pc = 0;
setScriptToDisplay(script);
}
static Common::String getHandlerName(Symbol &sym) {
Common::String handlerName;
if (sym.ctx && sym.ctx->_id)
handlerName = Common::String::format("%d:", sym.ctx->_id);
handlerName += g_lingo->formatFunctionName(sym);
return handlerName;
}
void showFuncList() {
if (!_state->_w.funcList)
return;
ImGui::SetNextWindowPos(ImVec2(20, 20), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(480, 640), ImGuiCond_FirstUseEver);
if (ImGui::Begin("Functions", &_state->_w.funcList)) {
_state->_functions._nameFilter.Draw();
ImGui::Separator();
// Show a script context wise handlers
ImGuiEx::toggleButton(ICON_MS_PACKAGE_2, &_state->_functions._showScriptContexts);
ImGui::SetItemTooltip("Script Contexts");
ImGui::SameLine();
// Show a list of all handlers
ImGuiEx::toggleButton(ICON_MS_STACKS, &_state->_functions._showScriptContexts, true);
ImGui::SetItemTooltip("All Handlers");
const ImVec2 childSize = ImGui::GetContentRegionAvail();
ImGui::BeginChild("##functions", ImVec2(childSize.x, childSize.y));
const Movie *movie = g_director->getCurrentMovie();
if (_state->_functions._showScriptContexts) {
for (auto cast : *movie->getCasts()) {
Common::String castName = Common::String::format("%d", cast._key);
if (cast._value->getCastName().size()) {
castName += Common::String::format(": %s ", cast._value->getCastName().c_str());
}
if (ImGui::TreeNodeEx(castName.c_str(), ImGuiTreeNodeFlags_DefaultOpen)) {
for (auto context : cast._value->_lingoArchive->lctxContexts) {
CastMemberInfo *cmi = cast._value->getCastMemberInfo(context._value->_id);
Common::String contextName = Common::String::format("%d", context._value->_id);
if (cmi && cmi->name.size()) {
contextName += Common::String::format(": %s", cmi->name.c_str());
}
contextName += Common::String::format(": %s", scriptType2str(context._value->_scriptType));
if (!context._value || !context._value->_functionHandlers.size() || !_state->_functions._nameFilter.PassFilter(contextName.c_str())) {
continue;
}
ImGui::PushID(context._key);
if (ImGui::TreeNode(contextName.c_str())) {
if (ImGui::BeginTable("Functions", 1, ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg)) {
ImGui::TableSetupColumn("Function", ImGuiTableColumnFlags_WidthStretch, 240.f);
int castId = context._value->_id;
bool childScript = false;
if (castId == -1) {
castId = movie->getCast()->getCastIdByScriptId(context._value->_parentNumber);
childScript = true;
}
for (auto &functionHandler : context._value->_functionHandlers) {
Common::String function = Common::String::format("%s", g_lingo->formatFunctionName(functionHandler._value).c_str());
ImGui::TableNextRow();
ImGui::TableNextColumn();
if (ImGui::Selectable(function.c_str())) {
CastMemberID memberID(cast._value->getCastIdByScriptId(context._key), cast._key);
ImGuiScript script = toImGuiScript(context._value->_scriptType, memberID, functionHandler._key);
script.byteOffsets = context._value->_functionByteOffsets[script.handlerId];
script.moviePath = movie->getArchive()->getPathName().toString();
script.handlerName = formatHandlerName(context._value->_scriptId, castId, script.handlerId, context._value->_scriptType, childScript);
addToOpenHandlers(script);
}
}
ImGui::EndTable();
}
ImGui::TreePop();
}
ImGui::PopID();
}
ImGui::TreePop();
}
}
Cast *sharedCast = movie->getSharedCast();
if (sharedCast && sharedCast->_lingoArchive) {
Common::String castName = Common::String::format("%s", "SHARED");
if (sharedCast->getCastName().size()) {
castName += Common::String::format(": %s ", sharedCast->getCastName().c_str());
}
if (ImGui::TreeNode(castName.c_str())) {
for (auto context : sharedCast->_lingoArchive->lctxContexts) {
CastMemberInfo *cmi = sharedCast->getCastMemberInfo(context._value->_id);
Common::String contextName = Common::String::format("%d", context._value->_id);
if (cmi && cmi->name.size()) {
contextName += Common::String::format(": %s", cmi->name.c_str());
}
contextName += Common::String::format(": %s", scriptType2str(context._value->_scriptType));
if (!context._value || !context._value->_functionHandlers.size() || !_state->_functions._nameFilter.PassFilter(contextName.c_str())) {
continue;
}
ImGui::PushID(context._key);
if (ImGui::TreeNode(contextName.c_str())) {
if (ImGui::BeginTable("Functions", 1, ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg)) {
ImGui::TableSetupColumn("Function", ImGuiTableColumnFlags_WidthStretch, 240.f);
int castId = context._value->_id;
bool childScript = false;
if (castId == -1) {
castId = movie->getCast()->getCastIdByScriptId(context._value->_parentNumber);
childScript = true;
}
for (auto &functionHandler : context._value->_functionHandlers) {
Common::String function = Common::String::format("%s", g_lingo->formatFunctionName(functionHandler._value).c_str());
ImGui::TableNextRow();
ImGui::TableNextColumn();
if (ImGui::Selectable(function.c_str())) {
CastMemberID memberID(sharedCast->getCastIdByScriptId(context._key), SHARED_CAST_LIB);
ImGuiScript script = toImGuiScript(context._value->_scriptType, memberID, functionHandler._key);
script.byteOffsets = context._value->_functionByteOffsets[script.handlerId];
script.moviePath = movie->getArchive()->getPathName().toString();
script.handlerName = formatHandlerName(context._value->_scriptId, castId, script.handlerName, context._value->_scriptType, childScript);
addToOpenHandlers(script);
}
}
ImGui::EndTable();
}
ImGui::TreePop();
}
ImGui::PopID();
}
ImGui::TreePop();
}
}
} else {
if (ImGui::BeginTable("Functions", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg)) {
ImGui::TableSetupColumn("Function", 0, 240.f);
ImGui::TableSetupColumn("Cast Name", ImGuiTableColumnFlags_WidthStretch, 240.f);
ImGui::TableHeadersRow();
for (auto &cast : *movie->getCasts()) {
for (int i = 0; i <= kMaxScriptType; i++) {
if (cast._value->_lingoArchive->scriptContexts[i].empty())
continue;
Common::String scriptType(scriptType2str((ScriptType)i));
for (auto &scriptContext : cast._value->_lingoArchive->scriptContexts[i]) {
Common::String name = Common::String::format("%d", scriptContext._key);
CastMemberInfo *cmi = cast._value->getCastMemberInfo(scriptContext._key);
CastMember *castMember = cast._value->getCastMember(scriptContext._key);
for (auto &functionHandler : scriptContext._value->_functionHandlers) {
Common::String function = Common::String::format("%s-%s (%d lib %d)",
castMember ? castType2str(castMember->_type) : "any", g_lingo->formatFunctionName(functionHandler._value).c_str(),
scriptContext._key, cast._key
);
if (!_state->_functions._nameFilter.PassFilter(function.c_str()))
continue;
ImGui::TableNextRow();
ImGui::TableNextColumn();
if (ImGui::Selectable(function.c_str())) {
CastMemberID memberID(scriptContext._key, cast._key);
ImGuiScript script = toImGuiScript(scriptContext._value->_scriptType, memberID, functionHandler._key);
script.byteOffsets = scriptContext._value->_functionByteOffsets[script.handlerId];
script.moviePath = movie->getArchive()->getPathName().toString();
script.handlerName = getHandlerName(functionHandler._value);
addToOpenHandlers(script);
}
ImGui::TableNextColumn();
ImGui::Text("%s", (cmi && cmi->name.size()) ? cmi->name.c_str() : "unnamed");
}
}
}
}
Cast *sharedCast = movie->getSharedCast();
if (sharedCast && sharedCast->_lingoArchive) {
for (int i = 0; i <= kMaxScriptType; i++) {
if (sharedCast->_lingoArchive->scriptContexts[i].empty())
continue;
Common::String scriptType(scriptType2str((ScriptType)i));
for (auto &scriptContext : sharedCast->_lingoArchive->scriptContexts[i]) {
Common::String name = Common::String::format("%d", scriptContext._key);
CastMemberInfo *cmi = sharedCast->getCastMemberInfo(scriptContext._key);
CastMember *castMember = sharedCast->getCastMember(scriptContext._key);
for (auto &functionHandler : scriptContext._value->_functionHandlers) {
Common::String function = Common::String::format("%s-%s (%d lib %d)",
castMember ? castType2str(castMember->_type) : "any", g_lingo->formatFunctionName(functionHandler._value).c_str(),
scriptContext._key, SHARED_CAST_LIB
);
if (!_state->_functions._nameFilter.PassFilter(function.c_str()))
continue;
ImGui::TableNextRow();
ImGui::TableNextColumn();
if (ImGui::Selectable(function.c_str())) {
CastMemberID memberID(scriptContext._key, SHARED_CAST_LIB);
ImGuiScript script = toImGuiScript(scriptContext._value->_scriptType, memberID, functionHandler._key);
script.byteOffsets = scriptContext._value->_functionByteOffsets[script.handlerId];
script.moviePath = movie->getArchive()->getPathName().toString();
script.handlerName = getHandlerName(functionHandler._value);
addToOpenHandlers(script);
}
ImGui::TableNextColumn();
ImGui::Text("%s", (cmi && cmi->name.size()) ? cmi->name.c_str() : "unnamed");
}
}
}
}
ImGui::EndTable();
}
}
ImGui::EndChild();
}
ImGui::End();
}
void showExecutionContext() {
if (!_state->_w.executionContext)
return;
ImGui::SetNextWindowPos(ImVec2(20, 160), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(500, 750), ImGuiCond_FirstUseEver);
Director::Lingo *lingo = g_director->getLingo();
const Movie *movie = g_director->getCurrentMovie();
Window *currentWindow = g_director->getCurrentWindow();
bool scriptsRendered = false;
if (ImGui::Begin("Execution Context", &_state->_w.executionContext, ImGuiWindowFlags_AlwaysAutoResize)) {
Window *stage = g_director->getStage();
g_director->setCurrentWindow(stage);
g_lingo->switchStateFromWindow();
int windowID = 0;
ImGui::PushID(windowID);
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg));
ImGui::BeginChild("Window##", ImVec2(500.0f, 700.0f));
ImGui::Text("%s", stage->asString().c_str());
ImGui::Text("%s", stage->getCurrentMovie()->getMacName().c_str());
ImGui::SeparatorText("Backtrace");
ImVec2 childSize = ImGui::GetContentRegionAvail();
childSize.y /= 3;
ImGui::BeginChild("##backtrace", childSize);
renderCallStack(lingo->_state->pc);
ImGui::EndChild();
ImGui::SeparatorText("Scripts");
ScriptData *scriptData = &_state->_functions._windowScriptData.getOrCreateVal(stage);
updateCurrentScript();
if (scriptData->_showScript) {
ImGuiScript &current = scriptData->_scripts[scriptData->_current];
// Get all the handlers from the script
ScriptContext* context = getScriptContext(current.id);
if (context) {
ImGui::Text("%d:%s type:%s", context->_id, context->getName().c_str(), scriptType2str(context->_scriptType));
}
ImGui::BeginDisabled(scriptData->_scripts.empty() || scriptData->_current == 0);
if (ImGui::Button(ICON_MS_ARROW_BACK)) {
scriptData->_current--;
}
ImGui::EndDisabled();
ImGui::SetItemTooltip("Backward");
ImGui::SameLine();
ImGui::BeginDisabled(scriptData->_current >= scriptData->_scripts.size() - 1);
if (ImGui::Button(ICON_MS_ARROW_FORWARD)) {
scriptData->_current++;
}
ImGui::EndDisabled();
ImGui::SetItemTooltip("Forward");
ImGui::SameLine();
const char *currentScript = nullptr;
if (scriptData->_current < scriptData->_scripts.size()) {
currentScript = scriptData->_scripts[scriptData->_current].handlerName.c_str();
}
if (ImGui::BeginCombo("##handlers", currentScript)) {
for (uint i = 0; i < scriptData->_scripts.size(); i++) {
auto &script = scriptData->_scripts[i];
bool selected = i == scriptData->_current;
if (ImGui::Selectable(script.handlerName.c_str(), &selected)) {
scriptData->_current = i;
}
}
ImGui::EndCombo();
}
if (!scriptData->_scripts[scriptData->_current].oldAst) {
ImGui::SameLine(0, 20);
ImGuiEx::toggleButton(ICON_MS_PACKAGE_2, &scriptData->_showByteCode, true); // Lingo
ImGui::SetItemTooltip("Lingo");
ImGui::SameLine();
ImGuiEx::toggleButton(ICON_MS_STACKS, &scriptData->_showByteCode); // Bytecode
ImGui::SetItemTooltip("Bytecode");
}
ImGui::Separator();
childSize = ImGui::GetContentRegionAvail();
ImGui::BeginChild("##script", childSize);
if (!context || context->_functionHandlers.size() == 1) {
renderScript(current, scriptData->_showByteCode, true);
} else {
for (auto &functionHandler : context->_functionHandlers) {
if (current.handlerId == functionHandler._key) {
renderScript(current, scriptData->_showByteCode, true);
} else {
ImGuiScript script = toImGuiScript(context->_scriptType, current.id, functionHandler._key);
script.byteOffsets = context->_functionByteOffsets[script.handlerId];
script.moviePath = movie->getArchive()->getPathName().toString();
script.handlerName = getHandlerName(functionHandler._value);
// Need to pass by reference in case of the current handler
renderScript(script, scriptData->_showByteCode, false);
}
ImGui::NewLine();
}
}
scriptsRendered = true;
ImGui::EndChild();
}
ImGui::EndChild();
ImGui::PopStyleColor();
ImGui::PopID();
ImGui::SameLine();
const Common::Array<Window *> *windowList = g_director->getWindowList();
for (auto window : (*windowList)) {
g_director->setCurrentWindow(window);
g_lingo->switchStateFromWindow();
windowID += 1;
ImGui::PushID(windowID);
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyleColorVec4(ImGuiCol_FrameBg));
ImGui::BeginChild("Window##", ImVec2(500.0f, 700.0f), ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY);
ImGui::Text("%s", window->asString().c_str());
ImGui::Text("%s", window->getCurrentMovie()->getMacName().c_str());
ImGui::SeparatorText("Backtrace");
childSize = ImGui::GetContentRegionAvail();
childSize.y /= 3;
ImGui::BeginChild("##backtrace", childSize);
renderCallStack(lingo->_state->pc);
ImGui::EndChild();
ImGui::SeparatorText("Scripts");
scriptData = &_state->_functions._windowScriptData.getOrCreateVal(window);
updateCurrentScript();
if (scriptData->_showScript) {
ImGuiScript &current = scriptData->_scripts[scriptData->_current];
// Get all the handlers from the script
ScriptContext* context = getScriptContext(current.id);
if (context) {
int castId = context->_id;
if (castId == -1) {
castId = movie->getCast()->getCastIdByScriptId(context->_parentNumber);
}
Common::String scriptInfo = Common::String::format("%d:%s type:%s", castId, context->getName().c_str(), scriptType2str(context->_scriptType));
ImGui::Text("%s", scriptInfo.c_str());
}
ImGui::BeginDisabled(scriptData->_scripts.empty() || scriptData->_current == 0);
if (ImGui::Button(ICON_MS_ARROW_BACK)) {
scriptData->_current--;
}
ImGui::EndDisabled();
ImGui::SetItemTooltip("Backward");
ImGui::SameLine();
ImGui::BeginDisabled(scriptData->_current >= scriptData->_scripts.size() - 1);
if (ImGui::Button(ICON_MS_ARROW_FORWARD)) {
scriptData->_current++;
}
ImGui::EndDisabled();
ImGui::SetItemTooltip("Forward");
ImGui::SameLine();
const char *currentScript = nullptr;
if (scriptData->_current < scriptData->_scripts.size()) {
currentScript = scriptData->_scripts[scriptData->_current].handlerName.c_str();
}
if (ImGui::BeginCombo("##handlers", currentScript)) {
for (uint i = 0; i < scriptData->_scripts.size(); i++) {
auto &script = scriptData->_scripts[i];
bool selected = i == scriptData->_current;
if (ImGui::Selectable(script.handlerName.c_str(), &selected)) {
scriptData->_current = i;
}
}
ImGui::EndCombo();
}
if (!scriptData->_scripts[scriptData->_current].oldAst) {
ImGui::SameLine(0, 20);
ImGuiEx::toggleButton(ICON_MS_PACKAGE_2, &scriptData->_showByteCode, true); // Lingo
ImGui::SetItemTooltip("Lingo");
ImGui::SameLine();
ImGuiEx::toggleButton(ICON_MS_STACKS, &scriptData->_showByteCode); // Bytecode
ImGui::SetItemTooltip("Bytecode");
}
ImGui::Separator();
childSize = ImGui::GetContentRegionAvail();
ImGui::BeginChild("##script", childSize);
if (!context || context->_functionHandlers.size() == 1) {
renderScript(current, scriptData->_showByteCode, true);
} else {
for (auto &functionHandler : context->_functionHandlers) {
if (current.handlerId == functionHandler._key) {
renderScript(current, scriptData->_showByteCode, true);
} else {
ImGuiScript script = toImGuiScript(context->_scriptType, current.id, functionHandler._key);
script.byteOffsets = context->_functionByteOffsets[script.handlerId];
script.moviePath = movie->getArchive()->getPathName().toString();
script.handlerName = getHandlerName(functionHandler._value);
// Need to pass by reference in case of the current handler
renderScript(script, scriptData->_showByteCode, false);
}
ImGui::NewLine();
}
}
scriptsRendered = true;
ImGui::EndChild();
}
ImGui::EndChild();
ImGui::PopStyleColor();
ImGui::PopID();
}
// Mark the scripts not dirty after all the handlers have been rendered
_state->_dbg._isScriptDirty = !scriptsRendered;
g_director->setCurrentWindow(currentWindow);
g_lingo->switchStateFromWindow();
}
ImGui::End();
}
} // namespace DT
} // namespace Director

View File

@@ -0,0 +1,738 @@
// Mini memory editor for Dear ImGui (to embed in your game/tools)
// Get latest version at http://www.github.com/ocornut/imgui_club
//
// Right-click anywhere to access the Options menu!
// You can adjust the keyboard repeat delay/rate in ImGuiIO.
// The code assume a mono-space font for simplicity!
// If you don't use the default font, use ImGui::PushFont()/PopFont() to switch to a mono-space font before calling this.
//
// Usage:
// // Create a window and draw memory editor inside it:
// static MemoryEditor mem_edit_1;
// static char data[0x10000];
// size_t data_size = 0x10000;
// mem_edit_1.DrawWindow("Memory Editor", data, data_size);
//
// Usage:
// // If you already have a window, use DrawContents() instead:
// static MemoryEditor mem_edit_2;
// ImGui::Begin("MyWindow")
// mem_edit_2.DrawContents(this, sizeof(*this), (size_t)this);
// ImGui::End();
//
// Changelog:
// - v0.10: initial version
// - v0.23 (2017/08/17): added to github. fixed right-arrow triggering a byte write.
// - v0.24 (2018/06/02): changed DragInt("Rows" to use a %d data format (which is desirable since imgui 1.61).
// - v0.25 (2018/07/11): fixed wording: all occurrences of "Rows" renamed to "Columns".
// - v0.26 (2018/08/02): fixed clicking on hex region
// - v0.30 (2018/08/02): added data preview for common data types
// - v0.31 (2018/10/10): added OptUpperCaseHex option to select lower/upper casing display [@samhocevar]
// - v0.32 (2018/10/10): changed signatures to use void* instead of unsigned char*
// - v0.33 (2018/10/10): added OptShowOptions option to hide all the interactive option setting.
// - v0.34 (2019/05/07): binary preview now applies endianness setting [@nicolasnoble]
// - v0.35 (2020/01/29): using ImGuiDataType available since Dear ImGui 1.69.
// - v0.36 (2020/05/05): minor tweaks, minor refactor.
// - v0.40 (2020/10/04): fix misuse of ImGuiListClipper API, broke with Dear ImGui 1.79. made cursor position appears on left-side of edit box. option popup appears on mouse release. fix MSVC warnings where _CRT_SECURE_NO_WARNINGS wasn't working in recent versions.
// - v0.41 (2020/10/05): fix when using with keyboard/gamepad navigation enabled.
// - v0.42 (2020/10/14): fix for . character in ASCII view always being greyed out.
// - v0.43 (2021/03/12): added OptFooterExtraHeight to allow for custom drawing at the bottom of the editor [@leiradel]
// - v0.44 (2021/03/12): use ImGuiInputTextFlags_AlwaysOverwrite in 1.82 + fix hardcoded width.
// - v0.50 (2021/11/12): various fixes for recent dear imgui versions (fixed misuse of clipper, relying on SetKeyboardFocusHere() handling scrolling from 1.85). added default size.
// - v0.51 (2024/02/22): fix for layout change in 1.89 when using IMGUI_DISABLE_OBSOLETE_FUNCTIONS. (#34)
// - v0.52 (2024/03/08): removed unnecessary GetKeyIndex() calls, they are a no-op since 1.87.
//
// Todo/Bugs:
// - This is generally old/crappy code, it should work but isn't very good.. to be rewritten some day.
// - PageUp/PageDown are not supported because we use _NoNav. This is a good test scenario for working out idioms of how to mix natural nav and our own...
// - Arrows are being sent to the InputText() about to disappear which for LeftArrow makes the text cursor appear at position 1 for one frame.
// - Using InputText() is awkward and maybe overkill here, consider implementing something custom.
#pragma once
#include <stdio.h> // sprintf, scanf
#include <stdint.h> // uint8_t, etc.
#ifdef _MSC_VER
#define ImSnprintf _snprintf
#else
#define ImSnprintf snprintf
#endif
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable: 4996) // warning C4996: 'sprintf': This function or variable may be unsafe.
#endif
struct MemoryEditor
{
enum DataFormat
{
DataFormat_Bin = 0,
DataFormat_Dec = 1,
DataFormat_Hex = 2,
DataFormat_COUNT
};
// Settings
bool Open; // = true // set to false when DrawWindow() was closed. ignore if not using DrawWindow().
bool ReadOnly; // = false // disable any editing.
int Cols; // = 16 // number of columns to display.
bool OptShowOptions; // = true // display options button/context menu. when disabled, options will be locked unless you provide your own UI for them.
bool OptShowDataPreview; // = false // display a footer previewing the decimal/binary/hex/float representation of the currently selected bytes.
bool OptShowHexII; // = false // display values in HexII representation instead of regular hexadecimal: hide null/zero bytes, ascii values as ".X".
bool OptShowAscii; // = true // display ASCII representation on the right side.
bool OptGreyOutZeroes; // = true // display null/zero bytes using the TextDisabled color.
bool OptUpperCaseHex; // = true // display hexadecimal values as "FF" instead of "ff".
int OptMidColsCount; // = 8 // set to 0 to disable extra spacing between every mid-cols.
int OptAddrDigitsCount; // = 0 // number of addr digits to display (default calculated based on maximum displayed addr).
float OptFooterExtraHeight; // = 0 // space to reserve at the bottom of the widget to add custom widgets
ImU32 HighlightColor; // // background color of highlighted bytes.
ImU8 (*ReadFn)(const ImU8* data, size_t off); // = 0 // optional handler to read bytes.
void (*WriteFn)(ImU8* data, size_t off, ImU8 d); // = 0 // optional handler to write bytes.
bool (*HighlightFn)(const ImU8* data, size_t off);//= 0 // optional handler to return Highlight property (to support non-contiguous highlighting).
// [Internal State]
bool ContentsWidthChanged;
size_t DataPreviewAddr;
size_t DataEditingAddr;
bool DataEditingTakeFocus;
char DataInputBuf[32];
char AddrInputBuf[32];
size_t GotoAddr;
size_t HighlightMin, HighlightMax;
int PreviewEndianness;
ImGuiDataType PreviewDataType;
MemoryEditor()
{
// Settings
Open = true;
ReadOnly = false;
Cols = 16;
OptShowOptions = true;
OptShowDataPreview = false;
OptShowHexII = false;
OptShowAscii = true;
OptGreyOutZeroes = true;
OptUpperCaseHex = true;
OptMidColsCount = 8;
OptAddrDigitsCount = 0;
OptFooterExtraHeight = 0.0f;
HighlightColor = IM_COL32(255, 255, 255, 50);
ReadFn = NULL;
WriteFn = NULL;
HighlightFn = NULL;
// State/Internals
ContentsWidthChanged = false;
DataPreviewAddr = DataEditingAddr = (size_t)-1;
DataEditingTakeFocus = false;
memset(DataInputBuf, 0, sizeof(DataInputBuf));
memset(AddrInputBuf, 0, sizeof(AddrInputBuf));
GotoAddr = (size_t)-1;
HighlightMin = HighlightMax = (size_t)-1;
PreviewEndianness = 0;
PreviewDataType = ImGuiDataType_S32;
}
void GotoAddrAndHighlight(size_t addr_min, size_t addr_max)
{
GotoAddr = addr_min;
HighlightMin = addr_min;
HighlightMax = addr_max;
}
struct Sizes
{
int AddrDigitsCount;
float LineHeight;
float GlyphWidth;
float HexCellWidth;
float SpacingBetweenMidCols;
float PosHexStart;
float PosHexEnd;
float PosAsciiStart;
float PosAsciiEnd;
float WindowWidth;
Sizes() { memset(this, 0, sizeof(*this)); }
};
void CalcSizes(Sizes& s, size_t mem_size, size_t base_display_addr)
{
ImGuiStyle& style = ImGui::GetStyle();
s.AddrDigitsCount = OptAddrDigitsCount;
if (s.AddrDigitsCount == 0)
for (size_t n = base_display_addr + mem_size - 1; n > 0; n >>= 4)
s.AddrDigitsCount++;
s.LineHeight = ImGui::GetTextLineHeight();
s.GlyphWidth = ImGui::CalcTextSize("F").x + 1; // We assume the font is mono-space
s.HexCellWidth = (float)(int)(s.GlyphWidth * 2.5f); // "FF " we include trailing space in the width to easily catch clicks everywhere
s.SpacingBetweenMidCols = (float)(int)(s.HexCellWidth * 0.25f); // Every OptMidColsCount columns we add a bit of extra spacing
s.PosHexStart = (s.AddrDigitsCount + 2) * s.GlyphWidth;
s.PosHexEnd = s.PosHexStart + (s.HexCellWidth * Cols);
s.PosAsciiStart = s.PosAsciiEnd = s.PosHexEnd;
if (OptShowAscii)
{
s.PosAsciiStart = s.PosHexEnd + s.GlyphWidth * 1;
if (OptMidColsCount > 0)
s.PosAsciiStart += (float)((Cols + OptMidColsCount - 1) / OptMidColsCount) * s.SpacingBetweenMidCols;
s.PosAsciiEnd = s.PosAsciiStart + Cols * s.GlyphWidth;
}
s.WindowWidth = s.PosAsciiEnd + style.ScrollbarSize + style.WindowPadding.x * 2 + s.GlyphWidth;
}
// Standalone Memory Editor window
void DrawWindow(const char* title, void* mem_data, size_t mem_size, size_t base_display_addr = 0x0000)
{
Sizes s;
CalcSizes(s, mem_size, base_display_addr);
ImGui::SetNextWindowSize(ImVec2(s.WindowWidth, s.WindowWidth * 0.60f), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, 0.0f), ImVec2(s.WindowWidth, FLT_MAX));
Open = true;
if (ImGui::Begin(title, &Open, ImGuiWindowFlags_NoScrollbar))
{
if (ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows) && ImGui::IsMouseReleased(ImGuiMouseButton_Right))
ImGui::OpenPopup("context");
DrawContents(mem_data, mem_size, base_display_addr);
if (ContentsWidthChanged)
{
CalcSizes(s, mem_size, base_display_addr);
ImGui::SetWindowSize(ImVec2(s.WindowWidth, ImGui::GetWindowSize().y));
}
}
ImGui::End();
}
// Memory Editor contents only
void DrawContents(void* mem_data_void, size_t mem_size, size_t base_display_addr = 0x0000)
{
if (Cols < 1)
Cols = 1;
ImU8* mem_data = (ImU8*)mem_data_void;
Sizes s;
CalcSizes(s, mem_size, base_display_addr);
ImGuiStyle& style = ImGui::GetStyle();
// We begin into our scrolling region with the 'ImGuiWindowFlags_NoMove' in order to prevent click from moving the window.
// This is used as a facility since our main click detection code doesn't assign an ActiveId so the click would normally be caught as a window-move.
const float height_separator = style.ItemSpacing.y;
float footer_height = OptFooterExtraHeight;
if (OptShowOptions)
footer_height += height_separator + ImGui::GetFrameHeightWithSpacing() * 1;
if (OptShowDataPreview)
footer_height += height_separator + ImGui::GetFrameHeightWithSpacing() * 1 + ImGui::GetTextLineHeightWithSpacing() * 3;
ImGui::BeginChild("##scrolling", ImVec2(0, -footer_height), false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNav);
ImDrawList* draw_list = ImGui::GetWindowDrawList();
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
// We are not really using the clipper API correctly here, because we rely on visible_start_addr/visible_end_addr for our scrolling function.
const int line_total_count = (int)((mem_size + Cols - 1) / Cols);
ImGuiListClipper clipper;
clipper.Begin(line_total_count, s.LineHeight);
bool data_next = false;
if (ReadOnly || DataEditingAddr >= mem_size)
DataEditingAddr = (size_t)-1;
if (DataPreviewAddr >= mem_size)
DataPreviewAddr = (size_t)-1;
size_t preview_data_type_size = OptShowDataPreview ? DataTypeGetSize(PreviewDataType) : 0;
size_t data_editing_addr_next = (size_t)-1;
if (DataEditingAddr != (size_t)-1)
{
// Move cursor but only apply on next frame so scrolling with be synchronized (because currently we can't change the scrolling while the window is being rendered)
if (ImGui::IsKeyPressed(ImGuiKey_UpArrow) && (ptrdiff_t)DataEditingAddr >= (ptrdiff_t)Cols) { data_editing_addr_next = DataEditingAddr - Cols; }
else if (ImGui::IsKeyPressed(ImGuiKey_DownArrow) && (ptrdiff_t)DataEditingAddr < (ptrdiff_t)mem_size - Cols){ data_editing_addr_next = DataEditingAddr + Cols; }
else if (ImGui::IsKeyPressed(ImGuiKey_LeftArrow) && (ptrdiff_t)DataEditingAddr > (ptrdiff_t)0) { data_editing_addr_next = DataEditingAddr - 1; }
else if (ImGui::IsKeyPressed(ImGuiKey_RightArrow) && (ptrdiff_t)DataEditingAddr < (ptrdiff_t)mem_size - 1) { data_editing_addr_next = DataEditingAddr + 1; }
}
// Draw vertical separator
ImVec2 window_pos = ImGui::GetWindowPos();
if (OptShowAscii)
draw_list->AddLine(ImVec2(window_pos.x + s.PosAsciiStart - s.GlyphWidth, window_pos.y), ImVec2(window_pos.x + s.PosAsciiStart - s.GlyphWidth, window_pos.y + 9999), ImGui::GetColorU32(ImGuiCol_Border));
const ImU32 color_text = ImGui::GetColorU32(ImGuiCol_Text);
const ImU32 color_disabled = OptGreyOutZeroes ? ImGui::GetColorU32(ImGuiCol_TextDisabled) : color_text;
const char* format_address = OptUpperCaseHex ? "%0*zX: " : "%0*zx: ";
const char* format_data = OptUpperCaseHex ? "%0*zX" : "%0*zx";
const char* format_byte = OptUpperCaseHex ? "%02X" : "%02x";
const char* format_byte_space = OptUpperCaseHex ? "%02X " : "%02x ";
while (clipper.Step())
for (int line_i = clipper.DisplayStart; line_i < clipper.DisplayEnd; line_i++) // display only visible lines
{
size_t addr = (size_t)(line_i * Cols);
ImGui::Text(format_address, s.AddrDigitsCount, base_display_addr + addr);
// Draw Hexadecimal
for (int n = 0; n < Cols && addr < mem_size; n++, addr++)
{
float byte_pos_x = s.PosHexStart + s.HexCellWidth * n;
if (OptMidColsCount > 0)
byte_pos_x += (float)(n / OptMidColsCount) * s.SpacingBetweenMidCols;
ImGui::SameLine(byte_pos_x);
// Draw highlight
bool is_highlight_from_user_range = (addr >= HighlightMin && addr < HighlightMax);
bool is_highlight_from_user_func = (HighlightFn && HighlightFn(mem_data, addr));
bool is_highlight_from_preview = (addr >= DataPreviewAddr && addr < DataPreviewAddr + preview_data_type_size);
if (is_highlight_from_user_range || is_highlight_from_user_func || is_highlight_from_preview)
{
ImVec2 pos = ImGui::GetCursorScreenPos();
float highlight_width = s.GlyphWidth * 2;
bool is_next_byte_highlighted = (addr + 1 < mem_size) && ((HighlightMax != (size_t)-1 && addr + 1 < HighlightMax) || (HighlightFn && HighlightFn(mem_data, addr + 1)));
if (is_next_byte_highlighted || (n + 1 == Cols))
{
highlight_width = s.HexCellWidth;
if (OptMidColsCount > 0 && n > 0 && (n + 1) < Cols && ((n + 1) % OptMidColsCount) == 0)
highlight_width += s.SpacingBetweenMidCols;
}
draw_list->AddRectFilled(pos, ImVec2(pos.x + highlight_width, pos.y + s.LineHeight), HighlightColor);
}
if (DataEditingAddr == addr)
{
// Display text input on current byte
bool data_write = false;
ImGui::PushID((void*)addr);
if (DataEditingTakeFocus)
{
ImGui::SetKeyboardFocusHere(0);
snprintf(AddrInputBuf, 32, format_data, s.AddrDigitsCount, base_display_addr + addr);
snprintf(DataInputBuf, 32, format_byte, ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]);
}
struct UserData
{
// FIXME: We should have a way to retrieve the text edit cursor position more easily in the API, this is rather tedious. This is such a ugly mess we may be better off not using InputText() at all here.
static int Callback(ImGuiInputTextCallbackData* data)
{
UserData* user_data = (UserData*)data->UserData;
if (!data->HasSelection())
user_data->CursorPos = data->CursorPos;
if (data->SelectionStart == 0 && data->SelectionEnd == data->BufTextLen)
{
// When not editing a byte, always refresh its InputText content pulled from underlying memory data
// (this is a bit tricky, since InputText technically "owns" the master copy of the buffer we edit it in there)
data->DeleteChars(0, data->BufTextLen);
data->InsertChars(0, user_data->CurrentBufOverwrite);
data->SelectionStart = 0;
data->SelectionEnd = 2;
data->CursorPos = 0;
}
return 0;
}
char CurrentBufOverwrite[3]; // Input
int CursorPos; // Output
};
UserData user_data;
user_data.CursorPos = -1;
snprintf(user_data.CurrentBufOverwrite, 3, format_byte, ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]);
ImGuiInputTextFlags flags = ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoHorizontalScroll | ImGuiInputTextFlags_CallbackAlways;
flags |= ImGuiInputTextFlags_AlwaysOverwrite; // was ImGuiInputTextFlags_AlwaysInsertMode
ImGui::SetNextItemWidth(s.GlyphWidth * 2);
if (ImGui::InputText("##data", DataInputBuf, IM_ARRAYSIZE(DataInputBuf), flags, UserData::Callback, &user_data))
data_write = data_next = true;
else if (!DataEditingTakeFocus && !ImGui::IsItemActive())
DataEditingAddr = data_editing_addr_next = (size_t)-1;
DataEditingTakeFocus = false;
if (user_data.CursorPos >= 2)
data_write = data_next = true;
if (data_editing_addr_next != (size_t)-1)
data_write = data_next = false;
unsigned int data_input_value = 0;
if (data_write && sscanf(DataInputBuf, "%X", &data_input_value) == 1)
{
if (WriteFn)
WriteFn(mem_data, addr, (ImU8)data_input_value);
else
mem_data[addr] = (ImU8)data_input_value;
}
ImGui::PopID();
}
else
{
// NB: The trailing space is not visible but ensure there's no gap that the mouse cannot click on.
ImU8 b = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr];
if (OptShowHexII)
{
if ((b >= 32 && b < 128))
ImGui::Text(".%c ", b);
else if (b == 0xFF && OptGreyOutZeroes)
ImGui::TextDisabled("## ");
else if (b == 0x00)
ImGui::Text(" ");
else
ImGui::Text(format_byte_space, b);
}
else
{
if (b == 0 && OptGreyOutZeroes)
ImGui::TextDisabled("00 ");
else
ImGui::Text(format_byte_space, b);
}
if (!ReadOnly && ImGui::IsItemHovered() && ImGui::IsMouseClicked(0))
{
DataEditingTakeFocus = true;
data_editing_addr_next = addr;
}
}
}
if (OptShowAscii)
{
// Draw ASCII values
ImGui::SameLine(s.PosAsciiStart);
ImVec2 pos = ImGui::GetCursorScreenPos();
addr = line_i * Cols;
ImGui::PushID(line_i);
if (ImGui::InvisibleButton("ascii", ImVec2(s.PosAsciiEnd - s.PosAsciiStart, s.LineHeight)))
{
DataEditingAddr = DataPreviewAddr = addr + (size_t)((ImGui::GetIO().MousePos.x - pos.x) / s.GlyphWidth);
DataEditingTakeFocus = true;
}
ImGui::PopID();
for (int n = 0; n < Cols && addr < mem_size; n++, addr++)
{
if (addr == DataEditingAddr)
{
draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui::GetColorU32(ImGuiCol_FrameBg));
draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui::GetColorU32(ImGuiCol_TextSelectedBg));
}
unsigned char c = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr];
char display_c = (c < 32 || c >= 128) ? '.' : c;
draw_list->AddText(pos, (display_c == c) ? color_text : color_disabled, &display_c, &display_c + 1);
pos.x += s.GlyphWidth;
}
}
}
ImGui::PopStyleVar(2);
ImGui::EndChild();
// Notify the main window of our ideal child content size (FIXME: we are missing an API to get the contents size from the child)
ImGui::SetCursorPosX(s.WindowWidth);
ImGui::Dummy(ImVec2(0.0f, 0.0f));
if (data_next && DataEditingAddr + 1 < mem_size)
{
DataEditingAddr = DataPreviewAddr = DataEditingAddr + 1;
DataEditingTakeFocus = true;
}
else if (data_editing_addr_next != (size_t)-1)
{
DataEditingAddr = DataPreviewAddr = data_editing_addr_next;
DataEditingTakeFocus = true;
}
const bool lock_show_data_preview = OptShowDataPreview;
if (OptShowOptions)
{
ImGui::Separator();
DrawOptionsLine(s, mem_data, mem_size, base_display_addr);
}
if (lock_show_data_preview)
{
ImGui::Separator();
DrawPreviewLine(s, mem_data, mem_size, base_display_addr);
}
}
void DrawOptionsLine(const Sizes& s, void* mem_data, size_t mem_size, size_t base_display_addr)
{
IM_UNUSED(mem_data);
ImGuiStyle& style = ImGui::GetStyle();
const char* format_range = OptUpperCaseHex ? "Range %0*zX..%0*zX" : "Range %0*zx..%0*zx";
// Options menu
if (ImGui::Button("Options"))
ImGui::OpenPopup("context");
if (ImGui::BeginPopup("context"))
{
ImGui::SetNextItemWidth(s.GlyphWidth * 7 + style.FramePadding.x * 2.0f);
if (ImGui::DragInt("##cols", &Cols, 0.2f, 4, 32, "%d cols")) { ContentsWidthChanged = true; if (Cols < 1) Cols = 1; }
ImGui::Checkbox("Show Data Preview", &OptShowDataPreview);
ImGui::Checkbox("Show HexII", &OptShowHexII);
if (ImGui::Checkbox("Show Ascii", &OptShowAscii)) { ContentsWidthChanged = true; }
ImGui::Checkbox("Grey out zeroes", &OptGreyOutZeroes);
ImGui::Checkbox("Uppercase Hex", &OptUpperCaseHex);
ImGui::EndPopup();
}
ImGui::SameLine();
ImGui::Text(format_range, s.AddrDigitsCount, base_display_addr, s.AddrDigitsCount, base_display_addr + mem_size - 1);
ImGui::SameLine();
ImGui::SetNextItemWidth((s.AddrDigitsCount + 1) * s.GlyphWidth + style.FramePadding.x * 2.0f);
if (ImGui::InputText("##addr", AddrInputBuf, IM_ARRAYSIZE(AddrInputBuf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue))
{
size_t goto_addr;
if (sscanf(AddrInputBuf, "%zX", &goto_addr) == 1)
{
GotoAddr = goto_addr - base_display_addr;
HighlightMin = HighlightMax = (size_t)-1;
}
}
if (GotoAddr != (size_t)-1)
{
if (GotoAddr < mem_size)
{
ImGui::BeginChild("##scrolling");
ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + (GotoAddr / Cols) * ImGui::GetTextLineHeight());
ImGui::EndChild();
DataEditingAddr = DataPreviewAddr = GotoAddr;
DataEditingTakeFocus = true;
}
GotoAddr = (size_t)-1;
}
}
void DrawPreviewLine(const Sizes& s, void* mem_data_void, size_t mem_size, size_t base_display_addr)
{
IM_UNUSED(base_display_addr);
ImU8* mem_data = (ImU8*)mem_data_void;
ImGuiStyle& style = ImGui::GetStyle();
ImGui::AlignTextToFramePadding();
ImGui::Text("Preview as:");
ImGui::SameLine();
ImGui::SetNextItemWidth((s.GlyphWidth * 10.0f) + style.FramePadding.x * 2.0f + style.ItemInnerSpacing.x);
if (ImGui::BeginCombo("##combo_type", DataTypeGetDesc(PreviewDataType), ImGuiComboFlags_HeightLargest))
{
for (int n = 0; n < ImGuiDataType_COUNT; n++)
if (ImGui::Selectable(DataTypeGetDesc((ImGuiDataType)n), PreviewDataType == n))
PreviewDataType = (ImGuiDataType)n;
ImGui::EndCombo();
}
ImGui::SameLine();
ImGui::SetNextItemWidth((s.GlyphWidth * 6.0f) + style.FramePadding.x * 2.0f + style.ItemInnerSpacing.x);
ImGui::Combo("##combo_endianness", &PreviewEndianness, "LE\0BE\0\0");
char buf[128] = "";
float x = s.GlyphWidth * 6.0f;
bool has_value = DataPreviewAddr != (size_t)-1;
if (has_value)
DrawPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Dec, buf, (size_t)IM_ARRAYSIZE(buf));
ImGui::Text("Dec"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
if (has_value)
DrawPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Hex, buf, (size_t)IM_ARRAYSIZE(buf));
ImGui::Text("Hex"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
if (has_value)
DrawPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Bin, buf, (size_t)IM_ARRAYSIZE(buf));
buf[IM_ARRAYSIZE(buf) - 1] = 0;
ImGui::Text("Bin"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value ? buf : "N/A");
}
// Utilities for Data Preview
const char* DataTypeGetDesc(ImGuiDataType data_type) const
{
const char* descs[] = { "Int8", "Uint8", "Int16", "Uint16", "Int32", "Uint32", "Int64", "Uint64", "Float", "Double" };
IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
return descs[data_type];
}
size_t DataTypeGetSize(ImGuiDataType data_type) const
{
const size_t sizes[] = { 1, 1, 2, 2, 4, 4, 8, 8, sizeof(float), sizeof(double) };
IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
return sizes[data_type];
}
const char* DataFormatGetDesc(DataFormat data_format) const
{
const char* descs[] = { "Bin", "Dec", "Hex" };
IM_ASSERT(data_format >= 0 && data_format < DataFormat_COUNT);
return descs[data_format];
}
bool IsBigEndian() const
{
uint16_t x = 1;
char c[2];
memcpy(c, &x, 2);
return c[0] != 0;
}
static void* EndiannessCopyBigEndian(void* _dst, void* _src, size_t s, int is_little_endian)
{
if (is_little_endian)
{
uint8_t* dst = (uint8_t*)_dst;
uint8_t* src = (uint8_t*)_src + s - 1;
for (int i = 0, n = (int)s; i < n; ++i)
memcpy(dst++, src--, 1);
return _dst;
}
else
{
return memcpy(_dst, _src, s);
}
}
static void* EndiannessCopyLittleEndian(void* _dst, void* _src, size_t s, int is_little_endian)
{
if (is_little_endian)
{
return memcpy(_dst, _src, s);
}
else
{
uint8_t* dst = (uint8_t*)_dst;
uint8_t* src = (uint8_t*)_src + s - 1;
for (int i = 0, n = (int)s; i < n; ++i)
memcpy(dst++, src--, 1);
return _dst;
}
}
void* EndiannessCopy(void* dst, void* src, size_t size) const
{
static void* (*fp)(void*, void*, size_t, int) = NULL;
if (fp == NULL)
fp = IsBigEndian() ? EndiannessCopyBigEndian : EndiannessCopyLittleEndian;
return fp(dst, src, size, PreviewEndianness);
}
const char* FormatBinary(const uint8_t* buf, int width) const
{
IM_ASSERT(width <= 64);
size_t out_n = 0;
static char out_buf[64 + 8 + 1];
int n = width / 8;
for (int j = n - 1; j >= 0; --j)
{
for (int i = 0; i < 8; ++i)
out_buf[out_n++] = (buf[j] & (1 << (7 - i))) ? '1' : '0';
out_buf[out_n++] = ' ';
}
IM_ASSERT(out_n < IM_ARRAYSIZE(out_buf));
out_buf[out_n] = 0;
return out_buf;
}
// [Internal]
void DrawPreviewData(size_t addr, const ImU8* mem_data, size_t mem_size, ImGuiDataType data_type, DataFormat data_format, char* out_buf, size_t out_buf_size) const
{
uint8_t buf[8];
size_t elem_size = DataTypeGetSize(data_type);
size_t size = addr + elem_size > mem_size ? mem_size - addr : elem_size;
if (ReadFn)
for (int i = 0, n = (int)size; i < n; ++i)
buf[i] = ReadFn(mem_data, addr + i);
else
memcpy(buf, mem_data + addr, size);
if (data_format == DataFormat_Bin)
{
uint8_t binbuf[8];
EndiannessCopy(binbuf, buf, size);
ImSnprintf(out_buf, out_buf_size, "%s", FormatBinary(binbuf, (int)size * 8));
return;
}
out_buf[0] = 0;
switch (data_type)
{
case ImGuiDataType_S8:
{
int8_t int8d = 0;
EndiannessCopy(&int8d, buf, size);
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hhd", int8d); return; }
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%02x", int8d & 0xFF); return; }
break;
}
case ImGuiDataType_U8:
{
uint8_t uint8d = 0;
EndiannessCopy(&uint8d, buf, size);
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hhu", uint8d); return; }
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%02x", uint8d & 0XFF); return; }
break;
}
case ImGuiDataType_S16:
{
int16_t int16d = 0;
EndiannessCopy(&int16d, buf, size);
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hd", int16d); return; }
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%04x", int16d & 0xFFFF); return; }
break;
}
case ImGuiDataType_U16:
{
uint16_t uint16d = 0;
EndiannessCopy(&uint16d, buf, size);
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%hu", uint16d); return; }
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%04x", uint16d & 0xFFFF); return; }
break;
}
case ImGuiDataType_S32:
{
int32_t int32d = 0;
EndiannessCopy(&int32d, buf, size);
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%d", int32d); return; }
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%08x", int32d); return; }
break;
}
case ImGuiDataType_U32:
{
uint32_t uint32d = 0;
EndiannessCopy(&uint32d, buf, size);
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%u", uint32d); return; }
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%08x", uint32d); return; }
break;
}
case ImGuiDataType_S64:
{
int64_t int64d = 0;
EndiannessCopy(&int64d, buf, size);
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%lld", (long long)int64d); return; }
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%016llx", (long long)int64d); return; }
break;
}
case ImGuiDataType_U64:
{
uint64_t uint64d = 0;
EndiannessCopy(&uint64d, buf, size);
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%llu", (long long)uint64d); return; }
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "0x%016llx", (long long)uint64d); return; }
break;
}
case ImGuiDataType_Float:
{
float float32d = 0.0f;
EndiannessCopy(&float32d, buf, size);
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%f", float32d); return; }
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "%a", float32d); return; }
break;
}
case ImGuiDataType_Double:
{
double float64d = 0.0;
EndiannessCopy(&float64d, buf, size);
if (data_format == DataFormat_Dec) { ImSnprintf(out_buf, out_buf_size, "%f", float64d); return; }
if (data_format == DataFormat_Hex) { ImSnprintf(out_buf, out_buf_size, "%a", float64d); return; }
break;
}
case ImGuiDataType_COUNT:
break;
} // Switch
IM_ASSERT(0); // Shouldn't reach
}
};
#undef ImSnprintf
#ifdef _MSC_VER
#pragma warning (pop)
#endif