Index: ps/trunk/source/gui/CGUIText.cpp
===================================================================
--- ps/trunk/source/gui/CGUIText.cpp (revision 25352)
+++ ps/trunk/source/gui/CGUIText.cpp (revision 25353)
@@ -1,470 +1,478 @@
/* Copyright (C) 2021 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. 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 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. 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 0 A.D. If not, see .
*/
#include "precompiled.h"
#include "CGUIText.h"
#include "graphics/FontMetrics.h"
#include "graphics/ShaderManager.h"
#include "graphics/TextRenderer.h"
#include "gui/CGUI.h"
#include "gui/ObjectBases/IGUIObject.h"
#include "gui/SettingTypes/CGUIString.h"
#include "renderer/Renderer.h"
#include
extern int g_xres, g_yres;
extern float g_GuiScale;
// TODO Gee: CRect => CPoint ?
void SGenerateTextImage::SetupSpriteCall(
const bool Left, CGUIText::SSpriteCall& SpriteCall, const float width, const float y,
const CSize2D& Size, const CStr& TextureName, const float BufferZone)
{
// TODO Gee: Temp hardcoded values
SpriteCall.m_Area.top = y + BufferZone;
SpriteCall.m_Area.bottom = y + BufferZone + Size.Height;
if (Left)
{
SpriteCall.m_Area.left = BufferZone;
SpriteCall.m_Area.right = Size.Width + BufferZone;
}
else
{
SpriteCall.m_Area.left = width-BufferZone - Size.Width;
SpriteCall.m_Area.right = width-BufferZone;
}
SpriteCall.m_Sprite = TextureName;
m_YFrom = SpriteCall.m_Area.top - BufferZone;
m_YTo = SpriteCall.m_Area.bottom + BufferZone;
m_Indentation = Size.Width + BufferZone * 2;
}
CGUIText::CGUIText(const CGUI& pGUI, const CGUIString& string, const CStrW& FontW, const float Width, const float BufferZone, const IGUIObject* pObject)
{
if (string.m_Words.empty())
return;
CStrIntern Font(FontW.ToUTF8());
float x = BufferZone, y = BufferZone; // drawing pointer
int from = 0;
bool FirstLine = true; // Necessary because text in the first line is shorter
// (it doesn't count the line spacing)
// Images on the left or the right side.
SGenerateTextImages Images;
int pos_last_img = -1; // Position in the string where last img (either left or right) were encountered.
// in order to avoid duplicate processing.
// get the alignment type for the control we are computing the text for since
// we are computing the horizontal alignment in this method in order to not have
// to run through the TextCalls a second time in the CalculateTextPosition method again
EAlign align = EAlign::LEFT;
if (pObject->SettingExists("text_align"))
align = pObject->GetSetting("text_align");
// Go through string word by word
for (int i = 0; i < static_cast(string.m_Words.size()) - 1; ++i)
{
// Pre-process each line one time, so we know which floating images
// will be added for that line.
// Generated stuff is stored in Feedback.
CGUIString::SFeedback Feedback;
// Preliminary line height, used for word-wrapping with floating images.
float prelim_line_height = 0.f;
// Width and height of all text calls generated.
string.GenerateTextCall(pGUI, Feedback, Font, string.m_Words[i], string.m_Words[i+1], FirstLine);
SetupSpriteCalls(pGUI, Feedback.m_Images, y, Width, BufferZone, i, pos_last_img, Images);
pos_last_img = std::max(pos_last_img, i);
x += Feedback.m_Size.Width;
prelim_line_height = std::max(prelim_line_height, Feedback.m_Size.Height);
// If Width is 0, then there's no word-wrapping, disable NewLine.
if (((Width != 0 && (x > Width - BufferZone || Feedback.m_NewLine)) || i == static_cast(string.m_Words.size()) - 2) &&
ProcessLine(pGUI, string, Font, pObject, Images, align, prelim_line_height, Width, BufferZone, FirstLine, x, y, i, from))
return;
}
}
// Loop through our images queues, to see if images have been added.
void CGUIText::SetupSpriteCalls(
const CGUI& pGUI,
const std::array, 2>& FeedbackImages,
const float y,
const float Width,
const float BufferZone,
const int i,
const int pos_last_img,
SGenerateTextImages& Images)
{
// Check if this has already been processed.
// Also, floating images are only applicable if Word-Wrapping is on
if (Width == 0 || i <= pos_last_img)
return;
// Loop left/right
for (int j = 0; j < 2; ++j)
for (const CStr& imgname : FeedbackImages[j])
{
SSpriteCall SpriteCall;
SGenerateTextImage Image;
// Y is if no other floating images is above, y. Else it is placed
// after the last image, like a stack downwards.
float _y;
if (!Images[j].empty())
_y = std::max(y, Images[j].back().m_YTo);
else
_y = y;
const SGUIIcon& icon = pGUI.GetIcon(imgname);
Image.SetupSpriteCall(j == CGUIString::SFeedback::Left, SpriteCall, Width, _y, icon.m_Size, icon.m_SpriteName, BufferZone);
// Check if image is the lowest thing.
m_Size.Height = std::max(m_Size.Height, Image.m_YTo);
Images[j].emplace_back(Image);
m_SpriteCalls.emplace_back(std::move(SpriteCall));
}
}
// Now we'll do another loop to figure out the height and width of
// the line (the height of the largest character and the width is
// the sum of all of the individual widths). This
// couldn't be determined in the first loop (main loop)
// because it didn't regard images, so we don't know
// if all characters processed, will actually be involved
// in that line.
void CGUIText::ComputeLineSize(
const CGUI& pGUI,
const CGUIString& string,
const CStrIntern& Font,
const bool FirstLine,
const float Width,
const float width_range_to,
const int i,
const int temp_from,
float& x,
CSize2D& line_size) const
{
for (int j = temp_from; j <= i; ++j)
{
// We don't want to use Feedback now, so we'll have to use another one.
CGUIString::SFeedback Feedback2;
// Don't attach object, it'll suppress the errors
// we want them to be reported in the final GenerateTextCall()
// so that we don't get duplicates.
string.GenerateTextCall(pGUI, Feedback2, Font, string.m_Words[j], string.m_Words[j+1], FirstLine);
// Append X value.
x += Feedback2.m_Size.Width;
if (Width != 0 && x > width_range_to && j != temp_from && !Feedback2.m_NewLine)
{
// The calculated width of each word includes the space between the current
// word and the next. When we're wrapping, we need subtract the width of the
// space after the last word on the line before the wrap.
CFontMetrics currentFont(Font);
line_size.Width -= currentFont.GetCharacterWidth(*L" ");
break;
}
// Let line_size.cy be the maximum m_Height we encounter.
line_size.Height = std::max(line_size.Height, Feedback2.m_Size.Height);
// If the current word is an explicit new line ("\n"),
// break now before adding the width of this character.
// ("\n" doesn't have a glyph, thus is given the same width as
// the "missing glyph" character by CFont::GetCharacterWidth().)
if (Width != 0 && Feedback2.m_NewLine)
break;
line_size.Width += Feedback2.m_Size.Width;
}
}
bool CGUIText::ProcessLine(
const CGUI& pGUI,
const CGUIString& string,
const CStrIntern& Font,
const IGUIObject* pObject,
const SGenerateTextImages& Images,
const EAlign align,
const float prelim_line_height,
const float Width,
const float BufferZone,
bool& FirstLine,
float& x,
float& y,
int& i,
int& from)
{
// Change 'from' to 'i', but first keep a copy of its value.
int temp_from = from;
from = i;
float width_range_from = BufferZone;
float width_range_to = Width - BufferZone;
ComputeLineRange(Images, y, Width, prelim_line_height, width_range_from, width_range_to);
// Reset X for the next loop
x = width_range_from;
CSize2D line_size;
ComputeLineSize(pGUI, string, Font, FirstLine, Width, width_range_to, i, temp_from, x, line_size);
// Reset x once more
x = width_range_from;
// Move down, because font drawing starts from the baseline
y += line_size.Height;
const float dx = GetLineOffset(align, width_range_from, width_range_to, line_size);
// Do the real processing now
const bool done = AssembleCalls(pGUI, string, Font, pObject, FirstLine, Width, width_range_to, dx, y, temp_from, i, x, from);
// Reset X
x = BufferZone;
// Update dimensions
m_Size.Width = std::max(m_Size.Width, line_size.Width + BufferZone * 2);
m_Size.Height = std::max(m_Size.Height, y + BufferZone);
FirstLine = false;
// Now if we entered as from = i, then we want
// i being one minus that, so that it will become
// the same i in the next loop. The difference is that
// we're on a new line now.
i = from - 1;
return done;
}
// Decide width of the line. We need to iterate our floating images.
// this won't be exact because we're assuming the line_size.cy
// will be as our preliminary calculation said. But that may change,
// although we'd have to add a couple of more loops to try straightening
// this problem out, and it is very unlikely to happen noticeably if one
// structures his text in a stylistically pure fashion. Even if not, it
// is still quite unlikely it will happen.
// Loop through left and right side, from and to.
void CGUIText::ComputeLineRange(
const SGenerateTextImages& Images,
const float y,
const float Width,
const float prelim_line_height,
float& width_range_from,
float& width_range_to) const
{
// Floating images are only applicable if word-wrapping is enabled.
if (Width == 0)
return;
for (int j = 0; j < 2; ++j)
for (const SGenerateTextImage& img : Images[j])
{
// We're working with two intervals here, the image's and the line height's.
// let's find the union of these two.
float union_from, union_to;
union_from = std::max(y, img.m_YFrom);
union_to = std::min(y + prelim_line_height, img.m_YTo);
// The union is not empty
if (union_to > union_from)
{
if (j == 0)
width_range_from = std::max(width_range_from, img.m_Indentation);
else
width_range_to = std::min(width_range_to, Width - img.m_Indentation);
}
}
}
// compute offset based on what kind of alignment
float CGUIText::GetLineOffset(
const EAlign align,
const float width_range_from,
const float width_range_to,
const CSize2D& line_size) const
{
switch (align)
{
case EAlign::LEFT:
// don't add an offset
return 0.f;
case EAlign::CENTER:
return ((width_range_to - width_range_from) - line_size.Width) / 2;
case EAlign::RIGHT:
return width_range_to - line_size.Width;
default:
debug_warn(L"Broken EAlign in CGUIText()");
return 0.f;
}
}
bool CGUIText::AssembleCalls(
const CGUI& pGUI,
const CGUIString& string,
const CStrIntern& Font,
const IGUIObject* pObject,
const bool FirstLine,
const float Width,
const float width_range_to,
const float dx,
const float y,
const int temp_from,
const int i,
float& x,
int& from)
{
bool done = false;
for (int j = temp_from; j <= i; ++j)
{
// We don't want to use Feedback now, so we'll have to use another one.
CGUIString::SFeedback Feedback2;
// Defaults
string.GenerateTextCall(pGUI, Feedback2, Font, string.m_Words[j], string.m_Words[j+1], FirstLine, pObject);
// Iterate all and set X/Y values
// Since X values are not set, we need to make an internal
// iteration with an increment that will append the internal
// x, that is what x_pointer is for.
float x_pointer = 0.f;
for (STextCall& tc : Feedback2.m_TextCalls)
{
tc.m_Pos = CVector2D(dx + x + x_pointer, y);
x_pointer += tc.m_Size.Width;
if (tc.m_pSpriteCall)
tc.m_pSpriteCall->m_Area += tc.m_Pos - CSize2D(0, tc.m_pSpriteCall->m_Area.GetHeight());
}
// Append X value.
x += Feedback2.m_Size.Width;
// The first word overrides the width limit, what we
// do, in those cases, are just drawing that word even
// though it'll extend the object.
if (Width != 0) // only if word-wrapping is applicable
{
if (Feedback2.m_NewLine)
{
from = j + 1;
// Sprite call can exist within only a newline segment,
// therefore we need this.
- m_SpriteCalls.insert(
- m_SpriteCalls.end(),
- std::make_move_iterator(Feedback2.m_SpriteCalls.begin()),
- std::make_move_iterator(Feedback2.m_SpriteCalls.end()));
+ if (!Feedback2.m_SpriteCalls.empty())
+ {
+ auto newEnd = std::remove_if(Feedback2.m_TextCalls.begin(), Feedback2.m_TextCalls.end(), [](const STextCall& call) { return !call.m_pSpriteCall; });
+ m_TextCalls.insert(
+ m_TextCalls.end(),
+ std::make_move_iterator(Feedback2.m_TextCalls.begin()),
+ std::make_move_iterator(newEnd));
+ m_SpriteCalls.insert(
+ m_SpriteCalls.end(),
+ std::make_move_iterator(Feedback2.m_SpriteCalls.begin()),
+ std::make_move_iterator(Feedback2.m_SpriteCalls.end()));
+ }
break;
}
else if (x > width_range_to && j == temp_from)
{
from = j+1;
// do not break, since we want it to be added to m_TextCalls
}
else if (x > width_range_to)
{
from = j;
break;
}
}
// Add the whole Feedback2.m_TextCalls to our m_TextCalls.
m_TextCalls.insert(
m_TextCalls.end(),
std::make_move_iterator(Feedback2.m_TextCalls.begin()),
std::make_move_iterator(Feedback2.m_TextCalls.end()));
m_SpriteCalls.insert(
m_SpriteCalls.end(),
std::make_move_iterator(Feedback2.m_SpriteCalls.begin()),
std::make_move_iterator(Feedback2.m_SpriteCalls.end()));
if (j == static_cast(string.m_Words.size()) - 2)
done = true;
}
return done;
}
void CGUIText::Draw(CGUI& pGUI, const CGUIColor& DefaultColor, const CVector2D& pos, const float z, const CRect& clipping) const
{
CShaderTechniquePtr tech = g_Renderer.GetShaderManager().LoadEffect(str_gui_text);
tech->BeginPass();
bool isClipped = clipping != CRect();
if (isClipped)
{
glEnable(GL_SCISSOR_TEST);
glScissor(
clipping.left * g_GuiScale,
g_yres - clipping.bottom * g_GuiScale,
clipping.GetWidth() * g_GuiScale,
clipping.GetHeight() * g_GuiScale);
}
CTextRenderer textRenderer(tech->GetShader());
textRenderer.SetClippingRect(clipping);
textRenderer.Translate(0.0f, 0.0f, z);
for (const STextCall& tc : m_TextCalls)
{
// If this is just a placeholder for a sprite call, continue
if (tc.m_pSpriteCall)
continue;
textRenderer.Color(tc.m_UseCustomColor ? tc.m_Color : DefaultColor);
textRenderer.Font(tc.m_Font);
textRenderer.Put(floorf(pos.X + tc.m_Pos.X), floorf(pos.Y + tc.m_Pos.Y), &tc.m_String);
}
textRenderer.Render();
for (const SSpriteCall& sc : m_SpriteCalls)
pGUI.DrawSprite(sc.m_Sprite, z, sc.m_Area + pos);
if (isClipped)
glDisable(GL_SCISSOR_TEST);
tech->EndPass();
}
Index: ps/trunk/source/gui/CGUIText.h
===================================================================
--- ps/trunk/source/gui/CGUIText.h (revision 25352)
+++ ps/trunk/source/gui/CGUIText.h (revision 25353)
@@ -1,285 +1,280 @@
/* Copyright (C) 2021 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. 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 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. 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 0 A.D. If not, see .
*/
#ifndef INCLUDED_GUITEXT
#define INCLUDED_GUITEXT
#include "gui/CGUISprite.h"
#include "gui/SettingTypes/CGUIColor.h"
#include "gui/SettingTypes/EAlign.h"
#include "maths/Rect.h"
#include "maths/Size2D.h"
#include "maths/Vector2D.h"
#include "ps/CStrIntern.h"
#include
#include
#include
class CGUI;
class CGUIString;
class IGUIObject;
struct SGenerateTextImage;
using SGenerateTextImages = std::array, 2>;
/**
* An CGUIText object is a parsed string, divided into
* text-rendering components. Each component, being a
* call to the Renderer. For instance, if you by tags
* change the color, then the GUI will have to make
* individual calls saying it want that color on the
* text.
*
* For instance:
* "Hello [b]there[/b] bunny!"
*
* That without word-wrapping would mean 3 components.
* i.e. 3 calls to CRenderer. One drawing "Hello",
* one drawing "there" in bold, and one drawing "bunny!".
*/
class CGUIText
{
public:
/**
* A sprite call to the CRenderer
*/
struct SSpriteCall
{
// The CGUISpriteInstance makes this uncopyable to avoid invalidating its draw cache
NONCOPYABLE(SSpriteCall);
MOVABLE(SSpriteCall);
SSpriteCall() {}
/**
* Size and position of sprite
*/
CRect m_Area;
/**
* Sprite from global GUI sprite database.
*/
CGUISpriteInstance m_Sprite;
-
- /**
- * Tooltip text
- */
- CStrW m_Tooltip;
-
- /**
- * Tooltip style
- */
- CStrW m_TooltipStyle;
};
/**
* A text call to the CRenderer
*/
struct STextCall
{
NONCOPYABLE(STextCall);
MOVABLE(STextCall);
STextCall() :
m_UseCustomColor(false),
m_Bold(false), m_Italic(false), m_Underlined(false),
m_pSpriteCall(nullptr) {}
/**
* Position
*/
CVector2D m_Pos;
/**
* Size
*/
CSize2D m_Size;
/**
* The string that is suppose to be rendered.
*/
CStrW m_String;
/**
* Use custom color? If true then m_Color is used,
* else the color inputted will be used.
*/
bool m_UseCustomColor;
/**
* Color setup
*/
CGUIColor m_Color;
/**
* Font name
*/
CStrIntern m_Font;
/**
* Settings
*/
bool m_Bold, m_Italic, m_Underlined;
/**
+ * Tooltip text
+ */
+ CStrW m_Tooltip;
+
+ /**
* *IF* an icon, then this is not nullptr.
*/
std::list::pointer m_pSpriteCall;
};
// The SSpriteCall CGUISpriteInstance makes this uncopyable to avoid invalidating its draw cache.
// Also take advantage of exchanging the containers directly with move semantics.
NONCOPYABLE(CGUIText);
MOVABLE(CGUIText);
/**
* Generates empty text.
*/
CGUIText() = default;
/**
* Generate a CGUIText object from the inputted string.
* The function will break down the string and its
* tags to calculate exactly which rendering queries
* will be sent to the Renderer. Also, horizontal alignment
* is taken into acount in this method but NOT vertical alignment.
*
* @param Text Text to generate CGUIText object from
* @param Font Default font, notice both Default color and default font
* can be changed by tags.
* @param Width Width, 0 if no word-wrapping.
* @param BufferZone space between text and edge, and space between text and images.
* @param pObject Optional parameter for error output. Used *only* if error parsing fails,
* and we need to be able to output which object the error occurred in to aid the user.
*/
CGUIText(const CGUI& pGUI, const CGUIString& string, const CStrW& FontW, const float Width, const float BufferZone, const IGUIObject* pObject);
/**
* Draw this CGUIText object
*/
void Draw(CGUI& pGUI, const CGUIColor& DefaultColor, const CVector2D& pos, const float z, const CRect& clipping) const;
const CSize2D& GetSize() const { return m_Size; }
const std::list& GetSpriteCalls() const { return m_SpriteCalls; }
const std::vector& GetTextCalls() const { return m_TextCalls; }
// Helper functions of the constructor
bool ProcessLine(
const CGUI& pGUI,
const CGUIString& string,
const CStrIntern& Font,
const IGUIObject* pObject,
const SGenerateTextImages& Images,
const EAlign align,
const float prelim_line_height,
const float Width,
const float BufferZone,
bool& FirstLine,
float& x,
float& y,
int& i,
int& from);
void SetupSpriteCalls(
const CGUI& pGUI,
const std::array, 2>& FeedbackImages,
const float y,
const float Width,
const float BufferZone,
const int i,
const int pos_last_img,
SGenerateTextImages& Images);
float GetLineOffset(
const EAlign align,
const float width_range_from,
const float width_range_to,
const CSize2D& line_size) const;
void ComputeLineRange(
const SGenerateTextImages& Images,
const float y,
const float Width,
const float prelim_line_height,
float& width_range_from,
float& width_range_to) const;
void ComputeLineSize(
const CGUI& pGUI,
const CGUIString& string,
const CStrIntern& Font,
const bool FirstLine,
const float Width,
const float width_range_to,
const int i,
const int temp_from,
float& x,
CSize2D& line_size) const;
bool AssembleCalls(
const CGUI& pGUI,
const CGUIString& string,
const CStrIntern& Font,
const IGUIObject* pObject,
const bool FirstLine,
const float Width,
const float width_range_to,
const float dx,
const float y,
const int temp_from,
const int i,
float& x,
int& from);
/**
* List of TextCalls, for instance "Hello", "there!"
*/
std::vector m_TextCalls;
/**
* List of sprites, or "icons" that should be rendered
* along with the text.
*/
std::list m_SpriteCalls; // list for consistent mem addresses
// so that we can point to elements.
/**
* Width and height of the whole output, used when setting up
* scrollbars and such.
*/
CSize2D m_Size;
};
struct SGenerateTextImage
{
// The image's starting location in Y
float m_YFrom;
// The image's end location in Y
float m_YTo;
// The image width in other words
float m_Indentation;
void SetupSpriteCall(
const bool Left, CGUIText::SSpriteCall& SpriteCall, const float width, const float y,
const CSize2D& Size, const CStr& TextureName, const float BufferZone);
};
#endif // INCLUDED_GUITEXT
Index: ps/trunk/source/gui/GUITooltip.cpp
===================================================================
--- ps/trunk/source/gui/GUITooltip.cpp (revision 25352)
+++ ps/trunk/source/gui/GUITooltip.cpp (revision 25353)
@@ -1,344 +1,331 @@
/* Copyright (C) 2021 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. 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 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. 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 0 A.D. If not, see .
*/
#include "precompiled.h"
#include "GUITooltip.h"
#include "gui/CGUI.h"
#include "gui/ObjectBases/IGUIObject.h"
#include "lib/timer.h"
#include "ps/CLogger.h"
/*
Tooltips:
When holding the mouse stationary over an object for some amount of time,
the tooltip is displayed. If the mouse moves off that object, the tooltip
disappears. If the mouse re-enters an object within a short time, the new
tooltip is displayed immediately. (This lets you run the mouse across a
series of buttons, without waiting ages for the text to pop up every time.)
See Visual Studio's toolbar buttons for an example.
Implemented as a state machine:
(where "*" lines are checked constantly, and "<" lines are handled
on entry to that state)
IN MOTION
* If the mouse stops, check whether it should have a tooltip and move to
'STATIONARY, NO TOOLTIP' or 'STATIONARY, TOOLIP'
* If the mouse enters an object with a tooltip delay of 0, switch to 'SHOWING'
STATIONARY, NO TOOLTIP
* If the mouse moves, switch to 'IN MOTION'
STATIONARY, TOOLTIP
< Set target time = now + tooltip time
* If the mouse moves, switch to 'IN MOTION'
* If now > target time, switch to 'SHOWING'
SHOWING
< Start displaying the tooltip
* If the mouse leaves the object, check whether the new object has a tooltip
and switch to 'SHOWING' or 'COOLING'
COOLING (since I can't think of a better name)
< Stop displaying the tooltip
< Set target time = now + cooldown time
* If the mouse has moved and is over a tooltipped object, switch to 'SHOWING'
* If now > target time, switch to 'STATIONARY, NO TOOLTIP'
*/
enum
{
ST_IN_MOTION,
ST_STATIONARY_NO_TOOLTIP,
ST_STATIONARY_TOOLTIP,
ST_SHOWING,
ST_COOLING
};
GUITooltip::GUITooltip()
: m_State(ST_IN_MOTION), m_PreviousObject(nullptr), m_PreviousTooltipName()
{
}
const double CooldownTime = 0.25; // TODO: Don't hard-code this value
bool GUITooltip::GetTooltip(IGUIObject* obj, CStr& style)
{
- if (obj && obj->SettingExists("_icon_tooltip_style") && obj->MouseOverIcon())
- {
- style = obj->GetSetting("_icon_tooltip_style");
- if (!obj->GetSetting("_icon_tooltip").empty())
- {
- if (style.empty())
- style = "default";
- m_IsIconTooltip = true;
- return true;
- }
- }
+ if (!obj)
+ return false;
- if (obj && obj->SettingExists("tooltip_style"))
- {
- style = obj->GetSetting("tooltip_style");
- if (!obj->GetSetting("tooltip").empty())
- {
- if (style.empty())
- style = "default";
- m_IsIconTooltip = false;
- return true;
- }
- }
+ if (obj->GetTooltipText().empty())
+ return false;
- return false;
+ style = obj->GetTooltipStyle();
+ if (style.empty())
+ style = "default";
+ return true;
}
void GUITooltip::ShowTooltip(IGUIObject* obj, const CVector2D& pos, const CStr& style, CGUI& pGUI)
{
ENSURE(obj);
if (style.empty())
return;
// Must be a CTooltip*
IGUIObject* tooltipobj = pGUI.FindObjectByName("__tooltip_" + style);
if (!tooltipobj || !tooltipobj->SettingExists("use_object"))
{
LOGERROR("Cannot find tooltip named '%s'", style.c_str());
return;
}
IGUIObject* usedobj; // object actually used to display the tooltip in
const CStr& usedObjectName = tooltipobj->GetSetting("use_object");
if (usedObjectName.empty())
{
usedobj = tooltipobj;
if (usedobj->SettingExists("_mousepos"))
{
usedobj->SetSetting("_mousepos", pos, true);
}
else
{
LOGERROR("Object '%s' used by tooltip '%s' isn't a tooltip object!", usedObjectName.c_str(), style.c_str());
return;
}
}
else
{
usedobj = pGUI.FindObjectByName(usedObjectName);
if (!usedobj)
{
LOGERROR("Cannot find object named '%s' used by tooltip '%s'", usedObjectName.c_str(), style.c_str());
return;
}
}
if (usedobj->SettingExists("caption"))
{
- const CStrW& text = obj->GetSetting(m_IsIconTooltip ? "_icon_tooltip" : "tooltip");
+ const CStrW& text = obj->GetTooltipText();
usedobj->SetSettingFromString("caption", text, true);
}
else
{
LOGERROR("Object '%s' used by tooltip '%s' must have a caption setting!", usedobj->GetPresentableName().c_str(), style.c_str());
return;
}
// Every IGUIObject has a "hidden" setting
usedobj->SetSetting("hidden", false, true);
}
void GUITooltip::HideTooltip(const CStr& style, CGUI& pGUI)
{
if (style.empty())
return;
// Must be a CTooltip*
IGUIObject* tooltipobj = pGUI.FindObjectByName("__tooltip_" + style);
if (!tooltipobj || !tooltipobj->SettingExists("use_object") || !tooltipobj->SettingExists("hide_object"))
{
LOGERROR("Cannot find tooltip named '%s' or it is not a tooltip", style.c_str());
return;
}
const CStr& usedObjectName = tooltipobj->GetSetting("use_object");
if (!usedObjectName.empty())
{
IGUIObject* usedobj = pGUI.FindObjectByName(usedObjectName);
if (usedobj && usedobj->SettingExists("caption"))
{
usedobj->SetSettingFromString("caption", L"", true);
}
else
{
LOGERROR("Object named '%s' used by tooltip '%s' does not exist or does not have a caption setting!", usedObjectName.c_str(), style.c_str());
return;
}
if (tooltipobj->GetSetting("hide_object"))
// Every IGUIObject has a "hidden" setting
usedobj->SetSetting("hidden", true, true);
}
else
tooltipobj->SetSetting("hidden", true, true);
}
static i32 GetTooltipDelay(const CStr& style, CGUI& pGUI)
{
// Must be a CTooltip*
IGUIObject* tooltipobj = pGUI.FindObjectByName("__tooltip_" + style);
if (!tooltipobj)
{
LOGERROR("Cannot find tooltip object named '%s'", style.c_str());
return 500;
}
return tooltipobj->GetSetting("delay");
}
void GUITooltip::Update(IGUIObject* Nearest, const CVector2D& MousePos, CGUI& GUI)
{
// Called once per frame, so efficiency isn't vital
double now = timer_Time();
CStr style;
int nextstate = -1;
switch (m_State)
{
case ST_IN_MOTION:
if (MousePos == m_PreviousMousePos)
{
if (GetTooltip(Nearest, style))
nextstate = ST_STATIONARY_TOOLTIP;
else
nextstate = ST_STATIONARY_NO_TOOLTIP;
}
else
{
// Check for movement onto a zero-delayed tooltip
if (GetTooltip(Nearest, style) && GetTooltipDelay(style, GUI)==0)
{
// Reset any previous tooltips completely
//m_Time = now + (double)GetTooltipDelay(style, GUI) / 1000.;
HideTooltip(m_PreviousTooltipName, GUI);
nextstate = ST_SHOWING;
}
}
break;
case ST_STATIONARY_NO_TOOLTIP:
if (MousePos != m_PreviousMousePos)
nextstate = ST_IN_MOTION;
break;
case ST_STATIONARY_TOOLTIP:
if (MousePos != m_PreviousMousePos)
nextstate = ST_IN_MOTION;
else if (now >= m_Time)
{
// Make sure the tooltip still exists
if (GetTooltip(Nearest, style))
nextstate = ST_SHOWING;
else
{
// Failed to retrieve style - the object has probably been
// altered, so just restart the process
nextstate = ST_IN_MOTION;
}
}
break;
case ST_SHOWING:
- // Handle special case of icon tooltips
- if (Nearest == m_PreviousObject && (!m_IsIconTooltip || Nearest->MouseOverIcon()))
+ // Handle sub-object tooltips.
+ if (Nearest == m_PreviousObject)
{
// Still showing the same object's tooltip, but the text might have changed
if (GetTooltip(Nearest, style))
ShowTooltip(Nearest, MousePos, style, GUI);
+ else
+ nextstate = ST_COOLING;
}
else
{
// Mouse moved onto a new object
if (GetTooltip(Nearest, style))
{
CStr style_old;
// If we're displaying a tooltip with no delay, then we want to
// reset so that other object that should have delay can't
// "ride this tail", it have to wait.
// Notice that this doesn't apply to when you go from one delay=0
// to another delay=0
if (GetTooltip(m_PreviousObject, style_old) && GetTooltipDelay(style_old, GUI) == 0 &&
GetTooltipDelay(style, GUI) != 0)
{
HideTooltip(m_PreviousTooltipName, GUI);
nextstate = ST_IN_MOTION;
}
else
{
// Hide old scrollbar
HideTooltip(m_PreviousTooltipName, GUI);
nextstate = ST_SHOWING;
}
}
else
nextstate = ST_COOLING;
}
break;
case ST_COOLING:
if (GetTooltip(Nearest, style))
nextstate = ST_SHOWING;
else if (now >= m_Time)
nextstate = ST_IN_MOTION;
break;
}
// Handle state-entry code:
if (nextstate != -1)
{
switch (nextstate)
{
case ST_STATIONARY_TOOLTIP:
m_Time = now + (double)GetTooltipDelay(style, GUI) / 1000.;
break;
case ST_SHOWING:
ShowTooltip(Nearest, MousePos, style, GUI);
m_PreviousTooltipName = style;
break;
case ST_COOLING:
HideTooltip(m_PreviousTooltipName, GUI);
m_Time = now + CooldownTime;
break;
}
m_State = nextstate;
}
m_PreviousMousePos = MousePos;
m_PreviousObject = Nearest;
}
Index: ps/trunk/source/gui/GUITooltip.h
===================================================================
--- ps/trunk/source/gui/GUITooltip.h (revision 25352)
+++ ps/trunk/source/gui/GUITooltip.h (revision 25353)
@@ -1,50 +1,49 @@
/* Copyright (C) 2021 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. 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 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. 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 0 A.D. If not, see .
*/
#ifndef INCLUDED_GUITOOLTIP
#define INCLUDED_GUITOOLTIP
class IGUIObject;
class CGUI;
#include "maths/Vector2D.h"
#include "ps/CStr.h"
class GUITooltip
{
public:
NONCOPYABLE(GUITooltip);
GUITooltip();
void Update(IGUIObject* Nearest, const CVector2D& MousePos, CGUI& GUI);
private:
void ShowTooltip(IGUIObject* obj, const CVector2D& pos, const CStr& style, CGUI& pGUI);
void HideTooltip(const CStr& style, CGUI& pGUI);
bool GetTooltip(IGUIObject* obj, CStr& style);
int m_State;
IGUIObject* m_PreviousObject;
CStr m_PreviousTooltipName;
CVector2D m_PreviousMousePos;
double m_Time;
- bool m_IsIconTooltip;
};
#endif // INCLUDED_GUITOOLTIP
Index: ps/trunk/source/gui/ObjectBases/IGUIObject.cpp
===================================================================
--- ps/trunk/source/gui/ObjectBases/IGUIObject.cpp (revision 25352)
+++ ps/trunk/source/gui/ObjectBases/IGUIObject.cpp (revision 25353)
@@ -1,565 +1,560 @@
/* Copyright (C) 2021 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. 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 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. 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 0 A.D. If not, see .
*/
#include "precompiled.h"
#include "IGUIObject.h"
#include "gui/CGUI.h"
#include "gui/CGUISetting.h"
#include "gui/Scripting/JSInterface_GUIProxy.h"
#include "js/Conversions.h"
#include "ps/CLogger.h"
#include "ps/GameSetup/Config.h"
#include "ps/Profile.h"
#include "scriptinterface/ScriptContext.h"
#include "scriptinterface/ScriptExtraHeaders.h"
#include "scriptinterface/ScriptInterface.h"
#include "soundmanager/ISoundManager.h"
#include
#include
const CStr IGUIObject::EventNameMouseEnter = "MouseEnter";
const CStr IGUIObject::EventNameMouseMove = "MouseMove";
const CStr IGUIObject::EventNameMouseLeave = "MouseLeave";
IGUIObject::IGUIObject(CGUI& pGUI)
: m_pGUI(pGUI),
m_pParent(),
m_MouseHovering(),
m_LastClickTime(),
m_Enabled(),
m_Hidden(),
m_Size(),
m_Style(),
m_Hotkey(),
m_Z(),
m_Absolute(),
m_Ghost(),
m_AspectRatio(),
m_Tooltip(),
m_TooltipStyle()
{
RegisterSetting("enabled", m_Enabled);
RegisterSetting("hidden", m_Hidden);
RegisterSetting("size", m_Size);
RegisterSetting("style", m_Style);
RegisterSetting("hotkey", m_Hotkey);
RegisterSetting("z", m_Z);
RegisterSetting("absolute", m_Absolute);
RegisterSetting("ghost", m_Ghost);
RegisterSetting("aspectratio", m_AspectRatio);
RegisterSetting("tooltip", m_Tooltip);
RegisterSetting("tooltip_style", m_TooltipStyle);
// Setup important defaults
// TODO: Should be in the default style?
SetSetting("hidden", false, true);
SetSetting("ghost", false, true);
SetSetting("enabled", true, true);
SetSetting("absolute", true, true);
}
IGUIObject::~IGUIObject()
{
for (const std::pair& p : m_Settings)
delete p.second;
if (!m_ScriptHandlers.empty())
JS_RemoveExtraGCRootsTracer(m_pGUI.GetScriptInterface()->GetGeneralJSContext(), Trace, this);
// m_Children is deleted along all other GUI Objects in the CGUI destructor
}
void IGUIObject::AddChild(IGUIObject& pChild)
{
pChild.SetParent(this);
m_Children.push_back(&pChild);
}
template
void IGUIObject::RegisterSetting(const CStr& Name, T& Value)
{
if (SettingExists(Name))
LOGERROR("The setting '%s' already exists on the object '%s'!", Name.c_str(), GetPresentableName().c_str());
else
m_Settings.emplace(Name, new CGUISetting(*this, Name, Value));
}
bool IGUIObject::SettingExists(const CStr& Setting) const
{
return m_Settings.find(Setting) != m_Settings.end();
}
template
T& IGUIObject::GetSetting(const CStr& Setting)
{
return static_cast* >(m_Settings.at(Setting))->m_pSetting;
}
template
const T& IGUIObject::GetSetting(const CStr& Setting) const
{
return static_cast* >(m_Settings.at(Setting))->m_pSetting;
}
bool IGUIObject::SetSettingFromString(const CStr& Setting, const CStrW& Value, const bool SendMessage)
{
const std::map::iterator it = m_Settings.find(Setting);
if (it == m_Settings.end())
{
LOGERROR("GUI object '%s' has no property called '%s', can't set parse and set value '%s'", GetPresentableName().c_str(), Setting.c_str(), Value.ToUTF8().c_str());
return false;
}
return it->second->FromString(Value, SendMessage);
}
template
void IGUIObject::SetSetting(const CStr& Setting, T& Value, const bool SendMessage)
{
PreSettingChange(Setting);
static_cast* >(m_Settings.at(Setting))->m_pSetting = std::move(Value);
SettingChanged(Setting, SendMessage);
}
template
void IGUIObject::SetSetting(const CStr& Setting, const T& Value, const bool SendMessage)
{
PreSettingChange(Setting);
static_cast* >(m_Settings.at(Setting))->m_pSetting = Value;
SettingChanged(Setting, SendMessage);
}
void IGUIObject::PreSettingChange(const CStr& Setting)
{
if (Setting == "hotkey")
m_pGUI.UnsetObjectHotkey(this, GetSetting(Setting));
}
void IGUIObject::SettingChanged(const CStr& Setting, const bool SendMessage)
{
if (Setting == "size")
{
// If setting was "size", we need to re-cache itself and all children
RecurseObject(nullptr, &IGUIObject::UpdateCachedSize);
}
else if (Setting == "hidden")
{
// Hiding an object requires us to reset it and all children
if (m_Hidden)
RecurseObject(nullptr, &IGUIObject::ResetStates);
}
else if (Setting == "hotkey")
m_pGUI.SetObjectHotkey(this, GetSetting(Setting));
else if (Setting == "style")
m_pGUI.SetObjectStyle(this, GetSetting(Setting));
if (SendMessage)
{
SGUIMessage msg(GUIM_SETTINGS_UPDATED, Setting);
HandleMessage(msg);
}
}
bool IGUIObject::IsMouseOver() const
{
return m_CachedActualSize.PointInside(m_pGUI.GetMousePos());
}
-bool IGUIObject::MouseOverIcon()
-{
- return false;
-}
-
void IGUIObject::UpdateMouseOver(IGUIObject* const& pMouseOver)
{
if (pMouseOver == this)
{
if (!m_MouseHovering)
SendMouseEvent(GUIM_MOUSE_ENTER,EventNameMouseEnter);
m_MouseHovering = true;
SendMouseEvent(GUIM_MOUSE_OVER, EventNameMouseMove);
}
else
{
if (m_MouseHovering)
{
m_MouseHovering = false;
SendMouseEvent(GUIM_MOUSE_LEAVE, EventNameMouseLeave);
}
}
}
void IGUIObject::ChooseMouseOverAndClosest(IGUIObject*& pObject)
{
if (!IsMouseOver())
return;
// Check if we've got competition at all
if (pObject == nullptr)
{
pObject = this;
return;
}
// Or if it's closer
if (GetBufferedZ() >= pObject->GetBufferedZ())
{
pObject = this;
return;
}
}
IGUIObject* IGUIObject::GetParent() const
{
// Important, we're not using GetParent() for these
// checks, that could screw it up
if (m_pParent && m_pParent->m_pParent == nullptr)
return nullptr;
return m_pParent;
}
void IGUIObject::ResetStates()
{
// Notify the gui that we aren't hovered anymore
UpdateMouseOver(nullptr);
}
void IGUIObject::UpdateCachedSize()
{
// If absolute="false" and the object has got a parent,
// use its cached size instead of the screen. Notice
// it must have just been cached for it to work.
if (!m_Absolute && m_pParent && !IsRootObject())
m_CachedActualSize = m_Size.GetSize(m_pParent->m_CachedActualSize);
else
m_CachedActualSize = m_Size.GetSize(CRect(0.f, 0.f, g_xres / g_GuiScale, g_yres / g_GuiScale));
// In a few cases, GUI objects have to resize to fill the screen
// but maintain a constant aspect ratio.
// Adjust the size to be the max possible, centered in the original size:
if (m_AspectRatio)
{
if (m_CachedActualSize.GetWidth() > m_CachedActualSize.GetHeight() * m_AspectRatio)
{
float delta = m_CachedActualSize.GetWidth() - m_CachedActualSize.GetHeight() * m_AspectRatio;
m_CachedActualSize.left += delta/2.f;
m_CachedActualSize.right -= delta/2.f;
}
else
{
float delta = m_CachedActualSize.GetHeight() - m_CachedActualSize.GetWidth() / m_AspectRatio;
m_CachedActualSize.bottom -= delta/2.f;
m_CachedActualSize.top += delta/2.f;
}
}
}
CRect IGUIObject::GetComputedSize()
{
UpdateCachedSize();
return m_CachedActualSize;
}
bool IGUIObject::ApplyStyle(const CStr& StyleName)
{
if (!m_pGUI.HasStyle(StyleName))
{
LOGERROR("IGUIObject: Trying to use style '%s' that doesn't exist.", StyleName.c_str());
return false;
}
// The default style may specify settings for any GUI object.
// Other styles are reported if they specify a Setting that does not exist,
// so that the XML author is informed and can correct the style.
for (const std::pair& p : m_pGUI.GetStyle(StyleName).m_SettingsDefaults)
{
if (SettingExists(p.first))
SetSettingFromString(p.first, p.second, true);
else if (StyleName != "default")
LOGWARNING("GUI object has no setting \"%s\", but the style \"%s\" defines it", p.first, StyleName.c_str());
}
return true;
}
float IGUIObject::GetBufferedZ() const
{
if (m_Absolute)
return m_Z;
if (GetParent())
return GetParent()->GetBufferedZ() + m_Z;
// In philosophy, a parentless object shouldn't be able to have a relative sizing,
// but we'll accept it so that absolute can be used as default without a complaint.
// Also, you could consider those objects children to the screen resolution.
return m_Z;
}
void IGUIObject::RegisterScriptHandler(const CStr& eventName, const CStr& Code, CGUI& pGUI)
{
ScriptRequest rq(pGUI.GetScriptInterface());
const int paramCount = 1;
const char* paramNames[paramCount] = { "mouse" };
// Location to report errors from
CStr CodeName = GetName() + " " + eventName;
// Generate a unique name
static int x = 0;
char buf[64];
sprintf_s(buf, ARRAY_SIZE(buf), "__eventhandler%d (%s)", x++, eventName.c_str());
// TODO: this is essentially the same code as ScriptInterface::LoadScript (with a tweak for the argument).
JS::CompileOptions options(rq.cx);
options.setFileAndLine(CodeName.c_str(), 0);
options.setIsRunOnce(false);
JS::SourceText src;
ENSURE(src.init(rq.cx, Code.c_str(), Code.length(), JS::SourceOwnership::Borrowed));
JS::RootedObjectVector emptyScopeChain(rq.cx);
JS::RootedFunction func(rq.cx, JS::CompileFunction(rq.cx, emptyScopeChain, options, buf, paramCount, paramNames, src));
if (func == nullptr)
{
LOGERROR("RegisterScriptHandler: Failed to compile the script for %s", eventName.c_str());
return;
}
JS::RootedObject funcObj(rq.cx, JS_GetFunctionObject(func));
SetScriptHandler(eventName, funcObj);
}
void IGUIObject::SetScriptHandler(const CStr& eventName, JS::HandleObject Function)
{
if (m_ScriptHandlers.empty())
JS_AddExtraGCRootsTracer(m_pGUI.GetScriptInterface()->GetGeneralJSContext(), Trace, this);
m_ScriptHandlers[eventName] = JS::Heap(Function);
if (std::find(m_pGUI.m_EventObjects[eventName].begin(), m_pGUI.m_EventObjects[eventName].end(), this) == m_pGUI.m_EventObjects[eventName].end())
m_pGUI.m_EventObjects[eventName].emplace_back(this);
}
void IGUIObject::UnsetScriptHandler(const CStr& eventName)
{
std::map >::iterator it = m_ScriptHandlers.find(eventName);
if (it == m_ScriptHandlers.end())
return;
m_ScriptHandlers.erase(it);
if (m_ScriptHandlers.empty())
JS_RemoveExtraGCRootsTracer(m_pGUI.GetScriptInterface()->GetGeneralJSContext(), Trace, this);
std::unordered_map>::iterator it2 = m_pGUI.m_EventObjects.find(eventName);
if (it2 == m_pGUI.m_EventObjects.end())
return;
std::vector& handlers = it2->second;
handlers.erase(std::remove(handlers.begin(), handlers.end(), this), handlers.end());
if (handlers.empty())
m_pGUI.m_EventObjects.erase(it2);
}
InReaction IGUIObject::SendEvent(EGUIMessageType type, const CStr& eventName)
{
PROFILE2_EVENT("gui event");
PROFILE2_ATTR("type: %s", eventName.c_str());
PROFILE2_ATTR("object: %s", m_Name.c_str());
SGUIMessage msg(type);
HandleMessage(msg);
ScriptEvent(eventName);
return msg.skipped ? IN_PASS : IN_HANDLED;
}
InReaction IGUIObject::SendMouseEvent(EGUIMessageType type, const CStr& eventName)
{
PROFILE2_EVENT("gui mouse event");
PROFILE2_ATTR("type: %s", eventName.c_str());
PROFILE2_ATTR("object: %s", m_Name.c_str());
SGUIMessage msg(type);
HandleMessage(msg);
ScriptRequest rq(m_pGUI.GetScriptInterface());
// Set up the 'mouse' parameter
JS::RootedValue mouse(rq.cx);
const CVector2D& mousePos = m_pGUI.GetMousePos();
ScriptInterface::CreateObject(
rq,
&mouse,
"x", mousePos.X,
"y", mousePos.Y,
"buttons", m_pGUI.GetMouseButtons());
JS::RootedValueVector paramData(rq.cx);
ignore_result(paramData.append(mouse));
ScriptEvent(eventName, paramData);
return msg.skipped ? IN_PASS : IN_HANDLED;
}
void IGUIObject::ScriptEvent(const CStr& eventName)
{
ScriptEventWithReturn(eventName);
}
bool IGUIObject::ScriptEventWithReturn(const CStr& eventName)
{
if (m_ScriptHandlers.find(eventName) == m_ScriptHandlers.end())
return false;
ScriptRequest rq(m_pGUI.GetScriptInterface());
JS::RootedValueVector paramData(rq.cx);
return ScriptEventWithReturn(eventName, paramData);
}
void IGUIObject::ScriptEvent(const CStr& eventName, const JS::HandleValueArray& paramData)
{
ScriptEventWithReturn(eventName, paramData);
}
bool IGUIObject::ScriptEventWithReturn(const CStr& eventName, const JS::HandleValueArray& paramData)
{
std::map >::iterator it = m_ScriptHandlers.find(eventName);
if (it == m_ScriptHandlers.end())
return false;
ScriptRequest rq(m_pGUI.GetScriptInterface());
JS::RootedObject obj(rq.cx, GetJSObject());
JS::RootedValue handlerVal(rq.cx, JS::ObjectValue(*it->second));
JS::RootedValue result(rq.cx);
if (!JS_CallFunctionValue(rq.cx, obj, handlerVal, paramData, &result))
{
LOGERROR("Errors executing script event \"%s\"", eventName.c_str());
ScriptException::CatchPending(rq);
return false;
}
return JS::ToBoolean(result);
}
JSObject* IGUIObject::GetJSObject()
{
// Cache the object when somebody first asks for it, because otherwise
// we end up doing far too much object allocation.
if (!m_JSObject)
CreateJSObject();
return m_JSObject->Get();
}
bool IGUIObject::IsEnabled() const
{
return m_Enabled;
}
bool IGUIObject::IsHidden() const
{
return m_Hidden;
}
bool IGUIObject::IsHiddenOrGhost() const
{
return m_Hidden || m_Ghost;
}
void IGUIObject::PlaySound(const CStrW& soundPath) const
{
if (g_SoundManager && !soundPath.empty())
g_SoundManager->PlayAsUI(soundPath.c_str(), false);
}
CStr IGUIObject::GetPresentableName() const
{
// __internal(), must be at least 13 letters to be able to be
// an internal name
if (m_Name.length() <= 12)
return m_Name;
if (m_Name.substr(0, 10) == "__internal")
return CStr("[unnamed object]");
else
return m_Name;
}
void IGUIObject::SetFocus()
{
m_pGUI.SetFocusedObject(this);
}
void IGUIObject::ReleaseFocus()
{
m_pGUI.SetFocusedObject(nullptr);
}
bool IGUIObject::IsFocused() const
{
return m_pGUI.GetFocusedObject() == this;
}
bool IGUIObject::IsBaseObject() const
{
return this == m_pGUI.GetBaseObject();
}
bool IGUIObject::IsRootObject() const
{
return m_pParent == m_pGUI.GetBaseObject();
}
void IGUIObject::TraceMember(JSTracer* trc)
{
// Please ensure to adapt the Tracer enabling and disabling in accordance with the GC things traced!
for (std::pair>& handler : m_ScriptHandlers)
JS::TraceEdge(trc, &handler.second, "IGUIObject::m_ScriptHandlers");
}
// Instantiate templated functions:
// These functions avoid copies by working with a reference and move semantics.
#define TYPE(T) \
template void IGUIObject::RegisterSetting(const CStr& Name, T& Value); \
template T& IGUIObject::GetSetting(const CStr& Setting); \
template const T& IGUIObject::GetSetting(const CStr& Setting) const; \
template void IGUIObject::SetSetting(const CStr& Setting, T& Value, const bool SendMessage); \
#include "gui/GUISettingTypes.h"
#undef TYPE
// Copying functions - discouraged except for primitives.
#define TYPE(T) \
template void IGUIObject::SetSetting(const CStr& Setting, const T& Value, const bool SendMessage); \
#define GUITYPE_IGNORE_NONCOPYABLE
#include "gui/GUISettingTypes.h"
#undef GUITYPE_IGNORE_NONCOPYABLE
#undef TYPE
Index: ps/trunk/source/gui/ObjectBases/IGUIObject.h
===================================================================
--- ps/trunk/source/gui/ObjectBases/IGUIObject.h (revision 25352)
+++ ps/trunk/source/gui/ObjectBases/IGUIObject.h (revision 25353)
@@ -1,560 +1,558 @@
/* Copyright (C) 2021 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. 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 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. 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 0 A.D. If not, see .
*/
/*
* The base class of an object.
* All objects are derived from this class.
* It's an abstract data type, so it can't be used per se.
* Also contains a Dummy object which is used for completely blank objects.
*/
#ifndef INCLUDED_IGUIOBJECT
#define INCLUDED_IGUIOBJECT
#include "gui/SettingTypes/CGUISize.h"
#include "gui/SGUIMessage.h"
#include "lib/input.h" // just for IN_PASS
#include "ps/XML/Xeromyces.h"
#include "scriptinterface/ScriptTypes.h"
#include