Get rid of tiny callback classes, round No.1

I say round No.1 because I'm not sure if there are any left.
Hopefully there aren't.
This commit is contained in:
Tamás Bálint Misius 2019-12-16 20:59:46 +01:00
parent 131b965af2
commit 7629c98f22
No known key found for this signature in database
GPG Key ID: 5B472A12F6ECA9F2
81 changed files with 1126 additions and 2955 deletions

View File

@ -1,14 +1,6 @@
#ifndef CONTROLLER_H_
#define CONTROLLER_H_
class ControllerCallback
{
public:
ControllerCallback() {}
virtual void ControllerExit() {}
virtual ~ControllerCallback() {}
};
class Controller
{
private:

View File

@ -10,64 +10,55 @@
#include "Misc.h"
ColourPickerActivity::ColourPickerActivity(ui::Colour initialColour, ColourPickedCallback * callback) :
ColourPickerActivity::ColourPickerActivity(ui::Colour initialColour, OnPicked onPicked_) :
WindowActivity(ui::Point(-1, -1), ui::Point(266, 175)),
currentHue(0),
currentSaturation(0),
currentValue(0),
mouseDown(false),
valueMouseDown(false),
callback(callback)
onPicked(onPicked_)
{
auto colourChange = [this] {
int r, g, b, alpha;
r = rValue->GetText().ToNumber<int>(true);
g = gValue->GetText().ToNumber<int>(true);
b = bValue->GetText().ToNumber<int>(true);
alpha = aValue->GetText().ToNumber<int>(true);
if (r > 255)
r = 255;
if (g > 255)
g = 255;
if (b > 255)
b = 255;
if (alpha > 255)
alpha = 255;
class ColourChange : public ui::TextboxAction
{
ColourPickerActivity * a;
public:
ColourChange(ColourPickerActivity * a) : a(a) {}
void TextChangedCallback(ui::Textbox * sender) override
{
int r, g, b, alpha;
r = a->rValue->GetText().ToNumber<int>(true);
g = a->gValue->GetText().ToNumber<int>(true);
b = a->bValue->GetText().ToNumber<int>(true);
alpha = a->aValue->GetText().ToNumber<int>(true);
if (r > 255)
r = 255;
if (g > 255)
g = 255;
if (b > 255)
b = 255;
if (alpha > 255)
alpha = 255;
RGB_to_HSV(r, g, b, &a->currentHue, &a->currentSaturation, &a->currentValue);
a->currentAlpha = alpha;
a->UpdateTextboxes(r, g, b, alpha);
}
RGB_to_HSV(r, g, b, &currentHue, &currentSaturation, &currentValue);
currentAlpha = alpha;
UpdateTextboxes(r, g, b, alpha);
};
rValue = new ui::Textbox(ui::Point(5, Size.Y-23), ui::Point(30, 17), "255");
rValue->SetActionCallback(new ColourChange(this));
rValue->SetActionCallback({ colourChange });
rValue->SetLimit(3);
rValue->SetInputType(ui::Textbox::Number);
AddComponent(rValue);
gValue = new ui::Textbox(ui::Point(40, Size.Y-23), ui::Point(30, 17), "255");
gValue->SetActionCallback(new ColourChange(this));
gValue->SetActionCallback({ colourChange });
gValue->SetLimit(3);
gValue->SetInputType(ui::Textbox::Number);
AddComponent(gValue);
bValue = new ui::Textbox(ui::Point(75, Size.Y-23), ui::Point(30, 17), "255");
bValue->SetActionCallback(new ColourChange(this));
bValue->SetActionCallback({ colourChange });
bValue->SetLimit(3);
bValue->SetInputType(ui::Textbox::Number);
AddComponent(bValue);
aValue = new ui::Textbox(ui::Point(110, Size.Y-23), ui::Point(30, 17), "255");
aValue->SetActionCallback(new ColourChange(this));
aValue->SetActionCallback({ colourChange });
aValue->SetLimit(3);
aValue->SetInputType(ui::Textbox::Number);
AddComponent(aValue);
@ -75,26 +66,17 @@ ColourPickerActivity::ColourPickerActivity(ui::Colour initialColour, ColourPicke
hexValue = new::ui::Label(ui::Point(150, Size.Y-23), ui::Point(53, 17), "0xFFFFFFFF");
AddComponent(hexValue);
class OkayAction: public ui::ButtonAction
{
ColourPickerActivity * a;
public:
OkayAction(ColourPickerActivity * a) : a(a) { }
void ActionCallback(ui::Button * sender) override
{
int Red, Green, Blue;
Red = a->rValue->GetText().ToNumber<int>(true);
Green = a->gValue->GetText().ToNumber<int>(true);
Blue = a->bValue->GetText().ToNumber<int>(true);
ui::Colour col(Red, Green, Blue, a->currentAlpha);
if(a->callback)
a->callback->ColourPicked(col);
a->Exit();
}
};
ui::Button * doneButton = new ui::Button(ui::Point(Size.X-45, Size.Y-23), ui::Point(40, 17), "Done");
doneButton->SetActionCallback(new OkayAction(this));
doneButton->SetActionCallback({ [this] {
int Red, Green, Blue;
Red = rValue->GetText().ToNumber<int>(true);
Green = gValue->GetText().ToNumber<int>(true);
Blue = bValue->GetText().ToNumber<int>(true);
ui::Colour col(Red, Green, Blue, currentAlpha);
if (onPicked)
onPicked(col);
Exit();
} });
AddComponent(doneButton);
SetOkayButton(doneButton);
@ -316,8 +298,3 @@ void ColourPickerActivity::OnDraw()
g->xor_line(offsetX+currentValueX, offsetY+4+128, offsetX+currentValueX, offsetY+13+128);
g->xor_line(offsetX+currentValueX+1, offsetY+4+128, offsetX+currentValueX+1, offsetY+13+128);
}
ColourPickerActivity::~ColourPickerActivity() {
delete callback;
}

View File

@ -4,21 +4,18 @@
#include "Activity.h"
#include "gui/interface/Colour.h"
#include <functional>
namespace ui
{
class Textbox;
class Label;
}
class ColourPickedCallback
class ColourPickerActivity : public WindowActivity
{
public:
ColourPickedCallback() {}
virtual ~ColourPickedCallback() {}
virtual void ColourPicked(ui::Colour colour) {}
};
using OnPicked = std::function<void (ui::Colour)>;
class ColourPickerActivity: public WindowActivity {
int currentHue;
int currentSaturation;
int currentValue;
@ -33,16 +30,17 @@ class ColourPickerActivity: public WindowActivity {
ui::Textbox * aValue;
ui::Label * hexValue;
ColourPickedCallback * callback;
OnPicked onPicked;
void UpdateTextboxes(int r, int g, int b, int a);
public:
ColourPickerActivity(ui::Colour initialColour, OnPicked onPicked = nullptr);
virtual ~ColourPickerActivity() = default;
void OnMouseMove(int x, int y, int dx, int dy) override;
void OnMouseDown(int x, int y, unsigned button) override;
void OnMouseUp(int x, int y, unsigned button) override;
void OnKeyPress(int key, int scan, bool repeat, bool shift, bool ctrl, bool alt) override;
void OnTryExit(ExitMethod method) override;
ColourPickerActivity(ui::Colour initialColour, ColourPickedCallback * callback = NULL);
virtual ~ColourPickerActivity();
void OnDraw() override;
};

View File

@ -7,7 +7,7 @@
#include "lua/CommandInterface.h"
ConsoleController::ConsoleController(ControllerCallback * callback, CommandInterface * commandInterface):
ConsoleController::ConsoleController(std::function<void ()> onDone, CommandInterface * commandInterface):
HasDone(false)
{
consoleModel = new ConsoleModel();
@ -15,7 +15,7 @@ ConsoleController::ConsoleController(ControllerCallback * callback, CommandInter
consoleView->AttachController(this);
consoleModel->AddObserver(consoleView);
this->callback = callback;
this->onDone = onDone;
this->commandInterface = commandInterface;
}
@ -59,8 +59,8 @@ void ConsoleController::PreviousCommand()
void ConsoleController::Exit()
{
consoleView->CloseActiveWindow();
if (callback)
callback->ControllerExit();
if (onDone)
onDone();
HasDone = true;
}
@ -72,7 +72,6 @@ ConsoleView * ConsoleController::GetView()
ConsoleController::~ConsoleController()
{
consoleView->CloseActiveWindow();
delete callback;
delete consoleModel;
delete consoleView;
}

View File

@ -3,19 +3,20 @@
#include "common/String.h"
#include <functional>
class CommandInterface;
class ConsoleModel;
class ConsoleView;
class ControllerCallback;
class ConsoleController
{
ControllerCallback * callback;
ConsoleView * consoleView;
ConsoleModel * consoleModel;
CommandInterface * commandInterface;
std::function<void ()> onDone;
public:
bool HasDone;
ConsoleController(ControllerCallback * callback, CommandInterface * commandInterface);
ConsoleController(std::function<void ()> onDone, CommandInterface * commandInterface);
String FormatCommand(String command);
void EvaluateCommand(String command);
void NextCommand();

View File

@ -19,20 +19,10 @@ ConsoleView::ConsoleView():
ui::Window(ui::Point(0, 0), ui::Point(WINDOWW, 150)),
commandField(NULL)
{
class CommandHighlighter: public ui::TextboxAction
{
ConsoleView * v;
public:
CommandHighlighter(ConsoleView * v_) { v = v_; }
void TextChangedCallback(ui::Textbox * sender) override
{
sender->SetDisplayText(v->c->FormatCommand(sender->GetText()));
}
};
commandField = new ui::Textbox(ui::Point(0, Size.Y-16), ui::Point(Size.X, 16), "");
commandField->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
commandField->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
commandField->SetActionCallback(new CommandHighlighter(this));
commandField->SetActionCallback({ [this] { commandField->SetDisplayText(c->FormatCommand(commandField->GetText())); } });
AddComponent(commandField);
FocusComponent(commandField);
commandField->SetBorder(false);

View File

@ -11,69 +11,7 @@
#include "graphics/Graphics.h"
ConfirmPrompt::ConfirmPrompt(String title, String message, ConfirmDialogueCallback * callback_):
ui::Window(ui::Point(-1, -1), ui::Point(250, 35)),
callback(callback_)
{
ui::Label * titleLabel = new ui::Label(ui::Point(4, 5), ui::Point(Size.X-8, 15), title);
titleLabel->SetTextColour(style::Colour::WarningTitle);
titleLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
titleLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
AddComponent(titleLabel);
ui::ScrollPanel *messagePanel = new ui::ScrollPanel(ui::Point(4, 24), ui::Point(Size.X-8, 206));
AddComponent(messagePanel);
ui::Label * messageLabel = new ui::Label(ui::Point(4, 0), ui::Point(Size.X-28, -1), message);
messageLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
messageLabel->Appearance.VerticalAlign = ui::Appearance::AlignTop;
messageLabel->SetMultiline(true);
messagePanel->AddChild(messageLabel);
messagePanel->InnerSize = ui::Point(messagePanel->Size.X, messageLabel->Size.Y+4);
if (messageLabel->Size.Y < messagePanel->Size.Y)
messagePanel->Size.Y = messageLabel->Size.Y+4;
Size.Y += messagePanel->Size.Y+12;
Position.Y = (ui::Engine::Ref().GetHeight()-Size.Y)/2;
class CloseAction: public ui::ButtonAction
{
public:
ConfirmPrompt * prompt;
DialogueResult result;
CloseAction(ConfirmPrompt * prompt_, DialogueResult result_) { prompt = prompt_; result = result_; }
void ActionCallback(ui::Button * sender) override
{
prompt->CloseActiveWindow();
if(prompt->callback)
prompt->callback->ConfirmCallback(result);
prompt->SelfDestruct();
}
};
ui::Button * cancelButton = new ui::Button(ui::Point(0, Size.Y-16), ui::Point(Size.X-75, 16), "Cancel");
cancelButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
cancelButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
cancelButton->Appearance.BorderInactive = ui::Colour(200, 200, 200);
cancelButton->SetActionCallback(new CloseAction(this, ResultCancel));
AddComponent(cancelButton);
SetCancelButton(cancelButton);
ui::Button * okayButton = new ui::Button(ui::Point(Size.X-76, Size.Y-16), ui::Point(76, 16), "Continue");
okayButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
okayButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
okayButton->Appearance.TextInactive = style::Colour::WarningTitle;
okayButton->SetActionCallback(new CloseAction(this, ResultOkay));
AddComponent(okayButton);
SetOkayButton(okayButton);
MakeActiveWindow();
}
ConfirmPrompt::ConfirmPrompt(String title, String message, String buttonText, ConfirmDialogueCallback * callback_):
ConfirmPrompt::ConfirmPrompt(String title, String message, ResultCallback callback_, String buttonText):
ui::Window(ui::Point(-1, -1), ui::Point(250, 50)),
callback(callback_)
{
@ -100,27 +38,16 @@ ConfirmPrompt::ConfirmPrompt(String title, String message, String buttonText, Co
Size.Y += messagePanel->Size.Y+12;
Position.Y = (ui::Engine::Ref().GetHeight()-Size.Y)/2;
class CloseAction: public ui::ButtonAction
{
public:
ConfirmPrompt * prompt;
DialogueResult result;
CloseAction(ConfirmPrompt * prompt_, DialogueResult result_) { prompt = prompt_; result = result_; }
void ActionCallback(ui::Button * sender) override
{
prompt->CloseActiveWindow();
if(prompt->callback)
prompt->callback->ConfirmCallback(result);
prompt->SelfDestruct();
}
};
ui::Button * cancelButton = new ui::Button(ui::Point(0, Size.Y-16), ui::Point(Size.X-75, 16), "Cancel");
cancelButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
cancelButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
cancelButton->Appearance.BorderInactive = ui::Colour(200, 200, 200);
cancelButton->SetActionCallback(new CloseAction(this, ResultCancel));
cancelButton->SetActionCallback({ [this] {
CloseActiveWindow();
if (callback.cancel)
callback.cancel();
SelfDestruct();
} });
AddComponent(cancelButton);
SetCancelButton(cancelButton);
@ -128,7 +55,12 @@ ConfirmPrompt::ConfirmPrompt(String title, String message, String buttonText, Co
okayButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
okayButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
okayButton->Appearance.TextInactive = style::Colour::WarningTitle;
okayButton->SetActionCallback(new CloseAction(this, ResultOkay));
okayButton->SetActionCallback({ [this] {
CloseActiveWindow();
if (callback.okay)
callback.okay();
SelfDestruct();
} });
AddComponent(okayButton);
SetOkayButton(okayButton);
@ -137,23 +69,13 @@ ConfirmPrompt::ConfirmPrompt(String title, String message, String buttonText, Co
bool ConfirmPrompt::Blocking(String title, String message, String buttonText)
{
class BlockingPromptCallback: public ConfirmDialogueCallback {
public:
bool & outputResult;
BlockingPromptCallback(bool & output): outputResult(output) {}
void ConfirmCallback(ConfirmPrompt::DialogueResult result) override {
if (result == ConfirmPrompt::ResultOkay)
outputResult = true;
else
outputResult = false;
ui::Engine::Ref().Break();
}
virtual ~BlockingPromptCallback() { }
};
bool result;
new ConfirmPrompt(title, message, buttonText, new BlockingPromptCallback(result));
bool outputResult;
new ConfirmPrompt(title, message, {
[&outputResult] { outputResult = true; ui::Engine::Ref().Break(); },
[&outputResult] { outputResult = false; ui::Engine::Ref().Break(); },
}, buttonText);
EngineProcess();
return result;
return outputResult;
}
void ConfirmPrompt::OnDraw()
@ -163,8 +85,3 @@ void ConfirmPrompt::OnDraw()
g->clearrect(Position.X-2, Position.Y-2, Size.X+3, Size.Y+3);
g->drawrect(Position.X, Position.Y, Size.X, Size.Y, 200, 200, 200, 255);
}
ConfirmPrompt::~ConfirmPrompt() {
delete callback;
}

View File

@ -3,23 +3,23 @@
#include "gui/interface/Window.h"
class ConfirmDialogueCallback;
class ConfirmPrompt: public ui::Window {
#include <functional>
class ConfirmPrompt : public ui::Window
{
struct ResultCallback
{
std::function<void ()> okay, cancel;
};
ResultCallback callback;
public:
enum DialogueResult { ResultCancel, ResultOkay };
ConfirmPrompt(String title, String message, ConfirmDialogueCallback * callback_ = NULL);
ConfirmPrompt(String title, String message, String buttonText, ConfirmDialogueCallback * callback_ = NULL);
ConfirmPrompt(String title, String message, ResultCallback callback_ = {}, String buttonText = String("Confirm"));
virtual ~ConfirmPrompt() = default;
static bool Blocking(String title, String message, String buttonText = String("Confirm"));
void OnDraw() override;
virtual ~ConfirmPrompt();
ConfirmDialogueCallback * callback;
};
class ConfirmDialogueCallback
{
public:
virtual void ConfirmCallback(ConfirmPrompt::DialogueResult result) {}
virtual ~ConfirmDialogueCallback() {}
};
#endif /* CONFIRMPROMPT_H_ */

View File

@ -10,7 +10,7 @@
#include "graphics/Graphics.h"
ErrorMessage::ErrorMessage(String title, String message, ErrorMessageCallback * callback_):
ErrorMessage::ErrorMessage(String title, String message, DismissCallback callback_):
ui::Window(ui::Point(-1, -1), ui::Point(200, 35)),
callback(callback_)
{
@ -29,25 +29,16 @@ ErrorMessage::ErrorMessage(String title, String message, ErrorMessageCallback *
Size.Y += messageLabel->Size.Y+12;
Position.Y = (ui::Engine::Ref().GetHeight()-Size.Y)/2;
class DismissAction: public ui::ButtonAction
{
ErrorMessage * message;
public:
DismissAction(ErrorMessage * message_) { message = message_; }
void ActionCallback(ui::Button * sender) override
{
message->CloseActiveWindow();
if(message->callback)
message->callback->DismissCallback();
message->SelfDestruct();
}
};
ui::Button * okayButton = new ui::Button(ui::Point(0, Size.Y-16), ui::Point(Size.X, 16), "Dismiss");
okayButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
okayButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
okayButton->Appearance.BorderInactive = ui::Colour(200, 200, 200);
okayButton->SetActionCallback(new DismissAction(this));
okayButton->SetActionCallback({ [this] {
CloseActiveWindow();
if (callback.dismiss)
callback.dismiss();
SelfDestruct();
} });
AddComponent(okayButton);
SetOkayButton(okayButton);
SetCancelButton(okayButton);
@ -57,15 +48,9 @@ ErrorMessage::ErrorMessage(String title, String message, ErrorMessageCallback *
void ErrorMessage::Blocking(String title, String message)
{
class BlockingDismissCallback: public ErrorMessageCallback {
public:
BlockingDismissCallback() {}
void DismissCallback() override {
ui::Engine::Ref().Break();
}
virtual ~BlockingDismissCallback() { }
};
new ErrorMessage(title, message, new BlockingDismissCallback());
new ErrorMessage(title, message, { [] {
ui::Engine::Ref().Break();
} });
EngineProcess();
}
@ -76,8 +61,3 @@ void ErrorMessage::OnDraw()
g->clearrect(Position.X-2, Position.Y-2, Size.X+3, Size.Y+3);
g->drawrect(Position.X, Position.Y, Size.X, Size.Y, 200, 200, 200, 255);
}
ErrorMessage::~ErrorMessage() {
delete callback;
}

View File

@ -3,21 +3,23 @@
#include "gui/interface/Window.h"
class ErrorMessageCallback;
class ErrorMessage: public ui::Window {
ErrorMessageCallback * callback;
#include <functional>
class ErrorMessage : public ui::Window
{
struct DismissCallback
{
std::function<void ()> dismiss;
};
DismissCallback callback;
public:
ErrorMessage(String title, String message, ErrorMessageCallback * callback_ = NULL);
ErrorMessage(String title, String message, DismissCallback callback_ = {});
virtual ~ErrorMessage() = default;
static void Blocking(String title, String message);
void OnDraw() override;
virtual ~ErrorMessage();
};
class ErrorMessageCallback
{
public:
virtual void DismissCallback() {}
virtual ~ErrorMessageCallback() {}
};
#endif /* ERRORMESSAGE_H_ */

View File

@ -55,23 +55,14 @@ InformationMessage::InformationMessage(String title, String message, bool large)
titleLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
AddComponent(titleLabel);
class DismissAction: public ui::ButtonAction
{
InformationMessage * message;
public:
DismissAction(InformationMessage * message_) { message = message_; }
void ActionCallback(ui::Button * sender) override
{
message->CloseActiveWindow();
message->SelfDestruct(); //TODO: Fix component disposal
}
};
ui::Button * okayButton = new ui::Button(ui::Point(0, Size.Y-16), ui::Point(Size.X, 16), "Dismiss");
okayButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
okayButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
okayButton->Appearance.BorderInactive = ui::Colour(200, 200, 200);
okayButton->SetActionCallback(new DismissAction(this));
okayButton->SetActionCallback({ [this] {
CloseActiveWindow();
SelfDestruct(); //TODO: Fix component disposal
} });
AddComponent(okayButton);
SetOkayButton(okayButton);
SetCancelButton(okayButton);
@ -86,7 +77,3 @@ void InformationMessage::OnDraw()
g->clearrect(Position.X-2, Position.Y-2, Size.X+3, Size.Y+3);
g->drawrect(Position.X, Position.Y, Size.X, Size.Y, 200, 200, 200, 255);
}
InformationMessage::~InformationMessage() {
}

View File

@ -3,11 +3,13 @@
#include "gui/interface/Window.h"
class InformationMessage: public ui::Window {
class InformationMessage : public ui::Window
{
public:
InformationMessage(String title, String message, bool large);
virtual ~InformationMessage() = default;
void OnDraw() override;
virtual ~InformationMessage();
};
#endif /* INFORMATIONMESSAGE_H_ */

View File

@ -36,22 +36,13 @@ SaveIDMessage::SaveIDMessage(int id):
ui::CopyTextButton * copyTextButton = new ui::CopyTextButton(ui::Point((Size.X-textWidth-10)/2, 50), ui::Point(textWidth+10, 18), String::Build(id), copyTextLabel);
AddComponent(copyTextButton);
class DismissAction: public ui::ButtonAction
{
SaveIDMessage * message;
public:
DismissAction(SaveIDMessage * message_) { message = message_; }
void ActionCallback(ui::Button * sender) override
{
message->CloseActiveWindow();
message->SelfDestruct();
}
};
ui::Button * okayButton = new ui::Button(ui::Point(0, Size.Y-16), ui::Point(Size.X, 16), "OK");
okayButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
okayButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
okayButton->SetActionCallback(new DismissAction(this));
okayButton->SetActionCallback({ [this] {
CloseActiveWindow();
SelfDestruct();
} });
AddComponent(okayButton);
// This button has multiple personalities
SetOkayButton(okayButton);
@ -73,9 +64,3 @@ void SaveIDMessage::OnTryExit(ExitMethod method)
CloseActiveWindow();
SelfDestruct();
}
SaveIDMessage::~SaveIDMessage()
{
}

View File

@ -3,12 +3,14 @@
#include "gui/interface/Window.h"
class SaveIDMessage: public ui::Window {
class SaveIDMessage : public ui::Window
{
public:
SaveIDMessage(int id);
virtual ~SaveIDMessage() = default;
void OnDraw() override;
void OnTryExit(ExitMethod method) override;
virtual ~SaveIDMessage();
};
#endif /* SAVEIDMESSAGE_H */

View File

@ -10,22 +10,7 @@
#include "graphics/Graphics.h"
class CloseAction: public ui::ButtonAction
{
public:
TextPrompt * prompt;
TextPrompt::DialogueResult result;
CloseAction(TextPrompt * prompt_, TextPrompt::DialogueResult result_) { prompt = prompt_; result = result_; }
void ActionCallback(ui::Button * sender) override
{
prompt->CloseActiveWindow();
if(prompt->callback)
prompt->callback->TextCallback(result, prompt->textField->GetText());
prompt->SelfDestruct(); //TODO: Fix component disposal
}
};
TextPrompt::TextPrompt(String title, String message, String text, String placeholder, bool multiline, TextDialogueCallback * callback_):
TextPrompt::TextPrompt(String title, String message, String text, String placeholder, bool multiline, TextDialogueCallback callback_):
ui::Window(ui::Point(-1, -1), ui::Point(200, 65)),
callback(callback_)
{
@ -66,7 +51,12 @@ TextPrompt::TextPrompt(String title, String message, String text, String placeho
cancelButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
cancelButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
cancelButton->Appearance.BorderInactive = ui::Colour(200, 200, 200);
cancelButton->SetActionCallback(new CloseAction(this, ResultCancel));
cancelButton->SetActionCallback({ [this] {
CloseActiveWindow();
if (callback.cancel)
callback.cancel();
SelfDestruct();
} });
AddComponent(cancelButton);
SetCancelButton(cancelButton);
@ -74,7 +64,12 @@ TextPrompt::TextPrompt(String title, String message, String text, String placeho
okayButton->Appearance.HorizontalAlign = ui::Appearance::AlignRight;
okayButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
okayButton->Appearance.TextInactive = style::Colour::WarningTitle;
okayButton->SetActionCallback(new CloseAction(this, ResultOkay));
okayButton->SetActionCallback({ [this] {
CloseActiveWindow();
if (callback.text)
callback.text(textField->GetText());
SelfDestruct();
} });
AddComponent(okayButton);
SetOkayButton(okayButton);
@ -83,25 +78,12 @@ TextPrompt::TextPrompt(String title, String message, String text, String placeho
String TextPrompt::Blocking(String title, String message, String text, String placeholder, bool multiline)
{
String returnString = "";
class BlockingTextCallback: public TextDialogueCallback {
String & outputString;
public:
BlockingTextCallback(String & output) : outputString(output) {}
void TextCallback(TextPrompt::DialogueResult result, String resultText) override {
if(result == ResultOkay)
outputString = resultText;
else
outputString = "";
ui::Engine::Ref().Break();
}
virtual ~BlockingTextCallback() { }
};
new TextPrompt(title, message, text, placeholder, multiline, new BlockingTextCallback(returnString));
String outputString;
new TextPrompt(title, message, text, placeholder, multiline, { [&outputString](String const &resultText) {
outputString = resultText;
} });
EngineProcess();
return returnString;
return outputString;
}
void TextPrompt::OnDraw()
@ -111,8 +93,3 @@ void TextPrompt::OnDraw()
g->clearrect(Position.X-2, Position.Y-2, Size.X+3, Size.Y+3);
g->drawrect(Position.X, Position.Y, Size.X, Size.Y, 200, 200, 200, 255);
}
TextPrompt::~TextPrompt() {
delete callback;
}

View File

@ -3,31 +3,32 @@
#include "gui/interface/Window.h"
#include <functional>
namespace ui
{
class Textbox;
}
class TextDialogueCallback;
class TextPrompt: public ui::Window
class TextPrompt : public ui::Window
{
struct TextDialogueCallback
{
std::function<void (String const &)> text;
std::function<void ()> cancel;
};
TextDialogueCallback callback;
protected:
ui::Textbox * textField;
public:
friend class CloseAction;
enum DialogueResult { ResultCancel, ResultOkay };
TextPrompt(String title, String message, String text, String placeholder, bool multiline, TextDialogueCallback * callback_);
TextPrompt(String title, String message, String text, String placeholder, bool multiline, TextDialogueCallback callback_ = {});
virtual ~TextPrompt() = default;
static String Blocking(String title, String message, String text, String placeholder, bool multiline);
void OnDraw() override;
virtual ~TextPrompt();
TextDialogueCallback * callback;
};
class TextDialogueCallback
{
public:
virtual void TextCallback(TextPrompt::DialogueResult result, String resultText) {}
virtual ~TextDialogueCallback() {}
};
#endif /* TEXTPROMPT_H_ */

View File

@ -15,20 +15,6 @@
#include "graphics/Graphics.h"
class ElementSearchActivity::ToolAction: public ui::ButtonAction
{
ElementSearchActivity * a;
public:
Tool * tool;
ToolAction(ElementSearchActivity * a, Tool * tool) : a(a), tool(tool) { }
void ActionCallback(ui::Button * sender_) override
{
ToolButton *sender = (ToolButton*)sender_;
if(sender->GetSelectionState() >= 0 && sender->GetSelectionState() <= 2)
a->SetActiveTool(sender->GetSelectionState(), tool);
}
};
ElementSearchActivity::ElementSearchActivity(GameController * gameController, std::vector<Tool*> tools) :
WindowActivity(ui::Point(-1, -1), ui::Point(236, 302)),
firstResult(NULL),
@ -47,50 +33,19 @@ ElementSearchActivity::ElementSearchActivity(GameController * gameController, st
title->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
AddComponent(title);
class SearchAction : public ui::TextboxAction
{
private:
ElementSearchActivity * a;
public:
SearchAction(ElementSearchActivity * a) : a(a) {}
void TextChangedCallback(ui::Textbox * sender) override {
a->searchTools(sender->GetText());
}
};
searchField = new ui::Textbox(ui::Point(8, 23), ui::Point(Size.X-16, 17), "");
searchField->SetActionCallback(new SearchAction(this));
searchField->SetActionCallback({ [this] { searchTools(searchField->GetText()); } });
searchField->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
AddComponent(searchField);
FocusComponent(searchField);
class CloseAction: public ui::ButtonAction
{
ElementSearchActivity * a;
public:
CloseAction(ElementSearchActivity * a) : a(a) { }
void ActionCallback(ui::Button * sender_) override
{
a->exit = true;
}
};
class OKAction: public ui::ButtonAction
{
ElementSearchActivity * a;
public:
OKAction(ElementSearchActivity * a) : a(a) { }
void ActionCallback(ui::Button * sender_) override
{
if(a->GetFirstResult())
a->SetActiveTool(0, a->GetFirstResult());
}
};
ui::Button * closeButton = new ui::Button(ui::Point(0, Size.Y-15), ui::Point((Size.X/2)+1, 15), "Close");
closeButton->SetActionCallback(new CloseAction(this));
closeButton->SetActionCallback({ [this] { exit = true; } });
ui::Button * okButton = new ui::Button(ui::Point(Size.X/2, Size.Y-15), ui::Point(Size.X/2, 15), "OK");
okButton->SetActionCallback(new OKAction(this));
okButton->SetActionCallback({ [this] {
if (GetFirstResult())
SetActiveTool(0, GetFirstResult());
} });
AddComponent(okButton);
AddComponent(closeButton);
@ -194,7 +149,10 @@ void ElementSearchActivity::searchTools(String query)
tempButton->Appearance.SetTexture(tempTexture);
tempButton->Appearance.BackgroundInactive = ui::Colour(tool->colRed, tool->colGreen, tool->colBlue);
tempButton->SetActionCallback(new ToolAction(this, tool));
tempButton->SetActionCallback({ [this, tempButton, tool] {
if (tempButton->GetSelectionState() >= 0 && tempButton->GetSelectionState() <= 2)
SetActiveTool(tempButton->GetSelectionState(), tool);
} });
if(gameController->GetActiveTool(0) == tool)
{

View File

@ -31,7 +31,6 @@ class ElementSearchActivity: public WindowActivity
void searchTools(String query);
public:
class ToolAction;
bool exit;
Tool * GetFirstResult() { return firstResult; }
ElementSearchActivity(GameController * gameController, std::vector<Tool*> tools);

View File

@ -21,25 +21,6 @@
#include "graphics/Graphics.h"
class SaveSelectedAction: public ui::SaveButtonAction
{
FileBrowserActivity * a;
public:
SaveSelectedAction(FileBrowserActivity * _a) { a = _a; }
void ActionCallback(ui::SaveButton * sender) override
{
a->SelectSave(sender->GetSaveFile());
}
void AltActionCallback(ui::SaveButton * sender) override
{
a->RenameSave(sender->GetSaveFile());
}
void AltActionCallback2(ui::SaveButton * sender) override
{
a->DeleteSave(sender->GetSaveFile());
}
};
//Currently, reading is done on another thread, we can't render outside the main thread due to some bullshit with OpenGL
class LoadFilesTask: public Task
{
@ -99,19 +80,9 @@ public:
}
};
class FileBrowserActivity::SearchAction: public ui::TextboxAction
{
public:
FileBrowserActivity * a;
SearchAction(FileBrowserActivity * a) : a(a) {}
void TextChangedCallback(ui::Textbox * sender) override {
a->DoSearch(sender->GetText().ToUtf8());
}
};
FileBrowserActivity::FileBrowserActivity(ByteString directory, FileSelectedCallback * callback):
FileBrowserActivity::FileBrowserActivity(ByteString directory, OnSelected onSelected_):
WindowActivity(ui::Point(-1, -1), ui::Point(500, 350)),
callback(callback),
onSelected(onSelected_),
directory(directory),
totalFiles(0)
{
@ -125,7 +96,7 @@ FileBrowserActivity::FileBrowserActivity(ByteString directory, FileSelectedCallb
ui::Textbox * textField = new ui::Textbox(ui::Point(8, 25), ui::Point(Size.X-16, 16), "", "[search]");
textField->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
textField->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
textField->SetActionCallback(new SearchAction(this));
textField->SetActionCallback({ [this, textField] { DoSearch(textField->GetText().ToUtf8()); } });
AddComponent(textField);
FocusComponent(textField);
@ -165,8 +136,8 @@ void FileBrowserActivity::DoSearch(ByteString search)
void FileBrowserActivity::SelectSave(SaveFile * file)
{
if(callback)
callback->FileSelected(new SaveFile(*file));
if (onSelected)
onSelected(std::unique_ptr<SaveFile>(new SaveFile(*file)));
Exit();
}
@ -303,7 +274,12 @@ void FileBrowserActivity::OnTick(float dt)
saveFile);
saveButton->AddContextMenu(1);
saveButton->Tick(dt);
saveButton->SetActionCallback(new SaveSelectedAction(this));
saveButton->SetActionCallback({
[this, saveButton] { SelectSave(saveButton->GetSaveFile()); },
[this, saveButton] { RenameSave(saveButton->GetSaveFile()); },
[this, saveButton] { DeleteSave(saveButton->GetSaveFile()); }
});
progressBar->SetStatus("Rendering thumbnails");
progressBar->SetProgress((float(totalFiles-files.size())/float(totalFiles))*100.0f);
componentsQueue.push_back(saveButton);
@ -334,6 +310,5 @@ void FileBrowserActivity::OnDraw()
FileBrowserActivity::~FileBrowserActivity()
{
delete callback;
cleanup();
}

View File

@ -1,18 +1,14 @@
#pragma once
#include <vector>
#include "common/String.h"
#include "Activity.h"
#include "tasks/TaskListener.h"
#include <vector>
#include <functional>
#include <memory>
class SaveFile;
class FileSelectedCallback
{
public:
FileSelectedCallback() {}
virtual ~FileSelectedCallback() {}
virtual void FileSelected(SaveFile* file) {}
};
namespace ui
{
@ -24,8 +20,10 @@ namespace ui
class LoadFilesTask;
class FileBrowserActivity: public TaskListener, public WindowActivity
{
using OnSelected = std::function<void (std::unique_ptr<SaveFile>)>;
LoadFilesTask * loadFiles;
FileSelectedCallback * callback;
OnSelected onSelected;
ui::ScrollPanel * itemList;
ui::Label * infoText;
std::vector<SaveFile*> files;
@ -40,12 +38,12 @@ class FileBrowserActivity: public TaskListener, public WindowActivity
int fileX, fileY;
int buttonWidth, buttonHeight, buttonAreaWidth, buttonAreaHeight, buttonXOffset, buttonYOffset;
class SearchAction;
void populateList();
void cleanup();
public:
FileBrowserActivity(ByteString directory, FileSelectedCallback * callback);
FileBrowserActivity(ByteString directory, OnSelected onSelected = nullptr);
virtual ~FileBrowserActivity();
void OnDraw() override;
void OnTick(float dt) override;
void OnTryExit(ExitMethod method) override;
@ -55,7 +53,6 @@ public:
void DeleteSave(SaveFile * file);
void RenameSave(SaveFile * file);
void DoSearch(ByteString search);
virtual ~FileBrowserActivity();
void NotifyDone(Task * task) override;
void NotifyError(Task * task) override;

View File

@ -272,204 +272,105 @@ FontEditor::FontEditor(ByteString _header):
int baseline = 8 + FONT_H * FONT_SCALE + 4 + FONT_H + 4 + 1;
int currentX = 1;
class PrevCharAction : public ui::ButtonAction
{
FontEditor *v;
public:
PrevCharAction(FontEditor *_v): v(_v) {}
void ActionCallback(ui::Button *)
{
v->PrevChar();
}
};
ui::Button *prev = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), 0xE016);
currentX += 18;
prev->SetActionCallback(new PrevCharAction(this));
prev->SetActionCallback({ [this] { PrevChar(); } });
AddComponent(prev);
class CharNumberAction : public ui::TextboxAction
{
FontEditor *v;
public:
CharNumberAction(FontEditor *_v): v(_v) {}
void TextChangedCallback(ui::Textbox *)
{
unsigned int number = v->currentCharTextbox->GetText().ToNumber<unsigned int>(Format::Hex(), true);
if(number <= 0x10FFFF)
v->currentChar = number;
}
};
currentCharTextbox = new ui::Textbox(ui::Point(currentX, baseline), ui::Point(31, 17));
currentX += 32;
currentCharTextbox->SetActionCallback(new CharNumberAction(this));
currentCharTextbox->SetActionCallback({ [this] {
unsigned int number = currentCharTextbox->GetText().ToNumber<unsigned int>(Format::Hex(), true);
if(number <= 0x10FFFF)
currentChar = number;
} });
UpdateCharNumber();
AddComponent(currentCharTextbox);
class NextCharAction : public ui::ButtonAction
{
FontEditor *v;
public:
NextCharAction(FontEditor *_v): v(_v) {}
void ActionCallback(ui::Button *)
{
v->NextChar();
}
};
ui::Button *next = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), 0xE015);
currentX += 18;
next->SetActionCallback(new NextCharAction(this));
next->SetActionCallback({ [this] { NextChar(); } });
AddComponent(next);
class ShrinkCharAction : public ui::ButtonAction
{
FontEditor *v;
public:
ShrinkCharAction(FontEditor *_v): v(_v) {}
void ActionCallback(ui::Button *)
{
v->ShrinkChar();
}
};
ui::Button *shrink = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), "><");
currentX += 18;
shrink->SetActionCallback(new ShrinkCharAction(this));
shrink->SetActionCallback({ [this] { ShrinkChar(); } });
AddComponent(shrink);
class GrowCharAction : public ui::ButtonAction
{
FontEditor *v;
public:
GrowCharAction(FontEditor *_v): v(_v) {}
void ActionCallback(ui::Button *)
{
v->GrowChar();
}
};
ui::Button *grow = new ui::Button(ui::Point(currentX, baseline), ui::Point(17, 17), "<>");
currentX += 18;
grow->SetActionCallback(new GrowCharAction(this));
grow->SetActionCallback({ [this] { GrowChar(); } });
AddComponent(grow);
class AddCharAction : public ui::ButtonAction
{
FontEditor *v;
public:
AddCharAction(FontEditor *_v): v(_v) {}
void ActionCallback(ui::Button *)
{
if(v->fontWidths.find(v->currentChar) == v->fontWidths.end())
{
v->savedButton->SetToggleState(false);
v->fontWidths[v->currentChar] = 5;
v->fontPixels[v->currentChar];
}
}
};
ui::Button *add = new ui::Button(ui::Point(currentX, baseline), ui::Point(36, 17), "Add");
currentX += 37;
add->SetActionCallback(new AddCharAction(this));
add->SetActionCallback({ [this] {
if (fontWidths.find(currentChar) == fontWidths.end())
{
savedButton->SetToggleState(false);
fontWidths[currentChar] = 5;
fontPixels[currentChar];
}
} });
AddComponent(add);
class RemoveCharAction : public ui::ButtonAction
{
FontEditor *v;
public:
RemoveCharAction(FontEditor *_v): v(_v) {}
void ActionCallback(ui::Button *)
{
if(v->fontWidths.find(v->currentChar) != v->fontWidths.end())
{
v->savedButton->SetToggleState(false);
v->fontWidths.erase(v->currentChar);
v->fontPixels.erase(v->currentChar);
}
}
};
ui::Button *remove = new ui::Button(ui::Point(currentX, baseline), ui::Point(36, 17), "Remove");
currentX += 37;
remove->SetActionCallback(new RemoveCharAction(this));
remove->SetActionCallback({ [this] {
if (fontWidths.find(currentChar) != fontWidths.end())
{
savedButton->SetToggleState(false);
fontWidths.erase(currentChar);
fontPixels.erase(currentChar);
}
} });
AddComponent(remove);
class ToggleAction : public ui::ButtonAction
{
int &toggle;
public:
ToggleAction(int &_toggle): toggle(_toggle) {}
void ActionCallback(ui::Button *button)
{
toggle = button->GetToggleState();
}
};
ui::Button *showGrid = new ui::Button(ui::Point(currentX, baseline), ui::Point(32, 17), "Grid");
currentX += 33;
showGrid->SetTogglable(true);
showGrid->SetToggleState(grid);
showGrid->SetActionCallback(new ToggleAction(grid));
showGrid->SetActionCallback({ [this, showGrid] {
grid = showGrid->GetToggleState();
} });
AddComponent(showGrid);
ui::Button *showRulers = new ui::Button(ui::Point(currentX, baseline), ui::Point(32, 17), "Rulers");
currentX += 33;
showRulers->SetTogglable(true);
showRulers->SetToggleState(grid);
showRulers->SetActionCallback(new ToggleAction(rulers));
showRulers->SetToggleState(rulers);
showRulers->SetActionCallback({ [this, showGrid] {
rulers = showGrid->GetToggleState();
} });
AddComponent(showRulers);
baseline += 18;
currentX = 1;
class ColorComponentAction : public ui::TextboxAction
{
int &color;
public:
ColorComponentAction(int &_color): color(_color) {}
void TextChangedCallback(ui::Textbox *box)
{
color = box->GetText().ToNumber<int>(true);
}
};
int *refs[6] = {&fgR, &fgG, &fgB, &bgR, &bgG, &bgB};
for(int i = 0; i < 6; i++)
{
ui::Textbox *colorComponent = new ui::Textbox(ui::Point(currentX, baseline), ui::Point(27, 17), String::Build(*refs[i]));
currentX += 28;
colorComponent->SetActionCallback(new ColorComponentAction(*refs[i]));
colorComponent->SetActionCallback({ [colorComponent, refs, i] {
*refs[i] = colorComponent->GetText().ToNumber<int>(true);
} });
AddComponent(colorComponent);
}
baseline += 18;
currentX = 1;
class RenderAction : public ui::ButtonAction
{
FontEditor *v;
public:
RenderAction(FontEditor *_v): v(_v) {}
void ActionCallback(ui::Button *)
{
v->Render();
}
};
ui::Button *render = new ui::Button(ui::Point(currentX, baseline), ui::Point(50, 17), "Render");
currentX += 51;
render->SetActionCallback(new RenderAction(this));
render->SetActionCallback({ [this] { Render(); } });
AddComponent(render);
class SaveAction : public ui::ButtonAction
{
FontEditor *v;
public:
SaveAction(FontEditor *_v): v(_v) {}
void ActionCallback(ui::Button *)
{
v->Save();
}
};
savedButton = new ui::Button(ui::Point(currentX, baseline), ui::Point(50, 17), "Save");
currentX += 51;
savedButton->SetTogglable(true);
savedButton->SetToggleState(true);
savedButton->SetActionCallback(new SaveAction(this));
savedButton->SetActionCallback({ [this] { Save(); } });
AddComponent(savedButton);
baseline += 18;
@ -480,41 +381,34 @@ FontEditor::FontEditor(ByteString _header):
outputPreview->Appearance.VerticalAlign = ui::Appearance::AlignTop;
AddComponent(outputPreview);
class PreviewAction : public ui::TextboxAction
{
FontEditor *v;
public:
PreviewAction(FontEditor *_v): v(_v) {}
void TextChangedCallback(ui::Textbox *box)
{
String str = box->GetText();
size_t at = 0;
StringBuilder text;
while(at < str.size())
{
unsigned int ch;
if(str[at] != ' ')
if(String::Split split = str.SplitNumber(ch, Format::Hex(), at))
{
text << String::value_type(ch);
at = split.PositionAfter();
}
else
{
text << str[at++];
}
else
at++;
}
v->outputPreview->SetText(text.Build());
}
};
ui::Textbox *inputPreview = new ui::Textbox(ui::Point(0, baseline), ui::Point(Size.X, (Size.Y - baseline) * 3 / 5));
inputPreview->SetMultiline(true);
inputPreview->SetInputType(ui::Textbox::Multiline);
inputPreview->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
inputPreview->Appearance.VerticalAlign = ui::Appearance::AlignTop;
inputPreview->SetActionCallback(new PreviewAction(this));
auto textChangedCallback = [this, inputPreview] {
String str = inputPreview->GetText();
size_t at = 0;
StringBuilder text;
while(at < str.size())
{
unsigned int ch;
if(str[at] != ' ')
if(String::Split split = str.SplitNumber(ch, Format::Hex(), at))
{
text << String::value_type(ch);
at = split.PositionAfter();
}
else
{
text << str[at++];
}
else
at++;
}
outputPreview->SetText(text.Build());
};
inputPreview->SetActionCallback({ textChangedCallback });
StringBuilder input;
input << Format::Hex() << Format::Width(2);
@ -525,7 +419,7 @@ FontEditor::FontEditor(ByteString _header):
input << ch << " ";
}
inputPreview->SetText(input.Build());
PreviewAction(this).TextChangedCallback(inputPreview);
textChangedCallback();
AddComponent(inputPreview);
}

View File

@ -78,94 +78,6 @@
# undef GetUserName // dammit windows
#endif
class GameController::SearchCallback: public ControllerCallback
{
GameController * cc;
public:
SearchCallback(GameController * cc_) { cc = cc_; }
void ControllerExit() override
{
if(cc->search->GetLoadedSave())
{
try
{
cc->HistorySnapshot();
cc->gameModel->SetSave(cc->search->GetLoadedSave(), cc->gameView->ShiftBehaviour());
cc->search->ReleaseLoadedSave();
}
catch(GameModelException & ex)
{
new ErrorMessage("Cannot open save", ByteString(ex.what()).FromUtf8());
}
}
}
};
class GameController::SaveOpenCallback: public ControllerCallback
{
GameController * cc;
public:
SaveOpenCallback(GameController * cc_) { cc = cc_; }
void ControllerExit() override
{
if(cc->activePreview->GetDoOpen() && cc->activePreview->GetSaveInfo())
{
try
{
cc->HistorySnapshot();
cc->LoadSave(cc->activePreview->GetSaveInfo());
}
catch(GameModelException & ex)
{
new ErrorMessage("Cannot open save", ByteString(ex.what()).FromUtf8());
}
}
}
};
class GameController::OptionsCallback: public ControllerCallback
{
GameController * cc;
public:
OptionsCallback(GameController * cc_) { cc = cc_; }
void ControllerExit() override
{
cc->gameModel->UpdateQuickOptions();
Client::Ref().WritePrefs();
}
};
class GameController::TagsCallback: public ControllerCallback
{
GameController * cc;
public:
TagsCallback(GameController * cc_) { cc = cc_; }
void ControllerExit() override
{
cc->gameView->NotifySaveChanged(cc->gameModel);
}
};
class GameController::StampsCallback: public ControllerCallback
{
GameController * cc;
public:
StampsCallback(GameController * cc_) { cc = cc_; }
void ControllerExit() override
{
SaveFile *file = cc->localBrowser->GetSave();
if (file)
{
if (file->GetError().length())
new ErrorMessage("Error loading stamp", file->GetError());
else if (cc->localBrowser->GetMoveToFront())
Client::Ref().MoveStampToFront(file->GetDisplayName().ToUtf8());
cc->LoadStamp(file->GetGameSave());
}
}
};
GameController::GameController():
firstTick(true),
foundSignID(-1),
@ -385,26 +297,16 @@ void GameController::Install()
#if defined(MACOSX)
new InformationMessage("No installation necessary", "You don't need to install The Powder Toy on OS X", false);
#elif defined(WIN) || defined(LIN)
class InstallConfirmation: public ConfirmDialogueCallback {
public:
GameController * c;
InstallConfirmation(GameController * c_) { c = c_; }
void ConfirmCallback(ConfirmPrompt::DialogueResult result) override {
if (result == ConfirmPrompt::ResultOkay)
{
if(Client::Ref().DoInstallation())
{
new InformationMessage("Success", "Installation completed", false);
}
else
{
new ErrorMessage("Could not install", "The installation did not complete due to an error");
}
}
new ConfirmPrompt("Install The Powder Toy", "Do you wish to install The Powder Toy on this computer?\nThis allows you to open save files and saves directly from the website.", { [this] {
if (Client::Ref().DoInstallation())
{
new InformationMessage("Success", "Installation completed", false);
}
virtual ~InstallConfirmation() { }
};
new ConfirmPrompt("Install The Powder Toy", "Do you wish to install The Powder Toy on this computer?\nThis allows you to open save files and saves directly from the website.", new InstallConfirmation(this));
else
{
new ErrorMessage("Could not install", "The installation did not complete due to an error");
}
} });
#else
new ErrorMessage("Cannot install", "You cannot install The Powder Toy on this platform");
#endif
@ -1250,7 +1152,21 @@ void GameController::SetReplaceModeFlags(int flags)
void GameController::OpenSearch(String searchText)
{
if(!search)
search = new SearchController(new SearchCallback(this));
search = new SearchController([this] {
if (search->GetLoadedSave())
{
try
{
HistorySnapshot();
gameModel->SetSave(search->GetLoadedSave(), gameView->ShiftBehaviour());
search->ReleaseLoadedSave();
}
catch(GameModelException & ex)
{
new ErrorMessage("Cannot open save", ByteString(ex.what()).FromUtf8());
}
}
});
if (searchText.length())
search->DoSearch2(searchText);
ui::Engine::Ref().ShowWindow(search->GetView());
@ -1278,19 +1194,9 @@ void GameController::OpenLocalSaveWindow(bool asCurrent)
if (!asCurrent || !gameModel->GetSaveFile())
{
class LocalSaveCallback: public FileSavedCallback
{
GameController * c;
public:
LocalSaveCallback(GameController * _c): c(_c) {}
virtual ~LocalSaveCallback() {}
void FileSaved(SaveFile* file) override
{
c->gameModel->SetSaveFile(file, c->gameView->ShiftBehaviour());
}
};
new LocalSaveActivity(tempSave, new LocalSaveCallback(this));
new LocalSaveActivity(tempSave, [this](SaveFile *file) {
gameModel->SetSaveFile(file, gameView->ShiftBehaviour());
});
}
else if (gameModel->GetSaveFile())
{
@ -1326,9 +1232,25 @@ void GameController::LoadSave(SaveInfo * save)
gameModel->SetSave(save, gameView->ShiftBehaviour());
}
void GameController::OpenSaveDone()
{
if (activePreview->GetDoOpen() && activePreview->GetSaveInfo())
{
try
{
HistorySnapshot();
LoadSave(activePreview->GetSaveInfo());
}
catch(GameModelException & ex)
{
new ErrorMessage("Cannot open save", ByteString(ex.what()).FromUtf8());
}
}
}
void GameController::OpenSavePreview(int saveID, int saveDate, bool instant)
{
activePreview = new PreviewController(saveID, saveDate, instant, new SaveOpenCallback(this));
activePreview = new PreviewController(saveID, saveDate, instant, [this] { OpenSaveDone(); });
ui::Engine::Ref().ShowWindow(activePreview->GetView());
}
@ -1336,27 +1258,17 @@ void GameController::OpenSavePreview()
{
if(gameModel->GetSave())
{
activePreview = new PreviewController(gameModel->GetSave()->GetID(), false, new SaveOpenCallback(this));
activePreview = new PreviewController(gameModel->GetSave()->GetID(), 0, false, [this] { OpenSaveDone(); });
ui::Engine::Ref().ShowWindow(activePreview->GetView());
}
}
void GameController::OpenLocalBrowse()
{
class LocalSaveOpenCallback: public FileSelectedCallback
{
GameController * c;
public:
LocalSaveOpenCallback(GameController * _c): c(_c) {}
virtual ~LocalSaveOpenCallback() {};
void FileSelected(SaveFile* file) override
{
c->HistorySnapshot();
c->LoadSaveFile(file);
delete file;
}
};
new FileBrowserActivity(LOCAL_SAVE_DIR PATH_SEP, new LocalSaveOpenCallback(this));
new FileBrowserActivity(LOCAL_SAVE_DIR PATH_SEP, [this](std::unique_ptr<SaveFile> file) {
HistorySnapshot();
LoadSaveFile(file.get());
});
}
void GameController::OpenLogin()
@ -1398,18 +1310,9 @@ void GameController::OpenElementSearch()
void GameController::OpenColourPicker()
{
class ColourPickerCallback: public ColourPickedCallback
{
GameController * c;
public:
ColourPickerCallback(GameController * _c): c(_c) {}
virtual ~ColourPickerCallback() {}
void ColourPicked(ui::Colour colour) override
{
c->SetColour(colour);
}
};
new ColourPickerActivity(gameModel->GetColourSelectorColour(), new ColourPickerCallback(this));
new ColourPickerActivity(gameModel->GetColourSelectorColour(), [this](ui::Colour colour) {
SetColour(colour);
});
}
void GameController::OpenTags()
@ -1417,7 +1320,7 @@ void GameController::OpenTags()
if(gameModel->GetSave() && gameModel->GetSave()->GetID())
{
delete tagsWindow;
tagsWindow = new TagsController(new TagsCallback(this), gameModel->GetSave());
tagsWindow = new TagsController([this] { gameView->NotifySaveChanged(gameModel); }, gameModel->GetSave());
ui::Engine::Ref().ShowWindow(tagsWindow->GetView());
}
else
@ -1428,13 +1331,26 @@ void GameController::OpenTags()
void GameController::OpenStamps()
{
localBrowser = new LocalBrowserController(new StampsCallback(this));
localBrowser = new LocalBrowserController([this] {
SaveFile *file = localBrowser->GetSave();
if (file)
{
if (file->GetError().length())
new ErrorMessage("Error loading stamp", file->GetError());
else if (localBrowser->GetMoveToFront())
Client::Ref().MoveStampToFront(file->GetDisplayName().ToUtf8());
LoadStamp(file->GetGameSave());
}
});
ui::Engine::Ref().ShowWindow(localBrowser->GetView());
}
void GameController::OpenOptions()
{
options = new OptionsController(gameModel, new OptionsCallback(this));
options = new OptionsController(gameModel, [this] {
gameModel->UpdateQuickOptions();
Client::Ref().WritePrefs();
});
ui::Engine::Ref().ShowWindow(options->GetView());
}
@ -1462,19 +1378,6 @@ void GameController::OpenRenderOptions()
void GameController::OpenSaveWindow()
{
class SaveUploadedCallback: public ServerSaveActivity::SaveUploadedCallback
{
GameController * c;
public:
SaveUploadedCallback(GameController * _c): c(_c) {}
virtual ~SaveUploadedCallback() {}
void SaveUploaded(SaveInfo save) override
{
save.SetVote(1);
save.SetVotesUp(1);
c->LoadSave(&save);
}
};
if(gameModel->GetUser().UserID)
{
Simulation * sim = gameModel->GetSimulation();
@ -1491,13 +1394,21 @@ void GameController::OpenSaveWindow()
{
SaveInfo tempSave(*gameModel->GetSave());
tempSave.SetGameSave(gameSave);
new ServerSaveActivity(tempSave, new SaveUploadedCallback(this));
new ServerSaveActivity(tempSave, [this](SaveInfo &save) {
save.SetVote(1);
save.SetVotesUp(1);
LoadSave(&save);
});
}
else
{
SaveInfo tempSave(0, 0, 0, 0, 0, gameModel->GetUser().Username, "");
tempSave.SetGameSave(gameSave);
new ServerSaveActivity(tempSave, new SaveUploadedCallback(this));
new ServerSaveActivity(tempSave, [this](SaveInfo &save) {
save.SetVote(1);
save.SetVotesUp(1);
LoadSave(&save);
});
}
}
}
@ -1509,19 +1420,6 @@ void GameController::OpenSaveWindow()
void GameController::SaveAsCurrent()
{
class SaveUploadedCallback: public ServerSaveActivity::SaveUploadedCallback
{
GameController * c;
public:
SaveUploadedCallback(GameController * _c): c(_c) {}
virtual ~SaveUploadedCallback() {}
void SaveUploaded(SaveInfo save) override
{
c->LoadSave(&save);
}
};
if(gameModel->GetSave() && gameModel->GetUser().UserID && gameModel->GetUser().Username == gameModel->GetSave()->GetUserName())
{
Simulation * sim = gameModel->GetSimulation();
@ -1538,13 +1436,13 @@ void GameController::SaveAsCurrent()
{
SaveInfo tempSave(*gameModel->GetSave());
tempSave.SetGameSave(gameSave);
new ServerSaveActivity(tempSave, true, new SaveUploadedCallback(this));
new ServerSaveActivity(tempSave, true, [this](SaveInfo &save) { LoadSave(&save); });
}
else
{
SaveInfo tempSave(0, 0, 0, 0, 0, gameModel->GetUser().Username, "");
tempSave.SetGameSave(gameSave);
new ServerSaveActivity(tempSave, true, new SaveUploadedCallback(this));
new ServerSaveActivity(tempSave, true, [this](SaveInfo &save) { LoadSave(&save); });
}
}
}
@ -1673,19 +1571,6 @@ void GameController::NotifyNewNotification(Client * sender, std::pair<String, By
void GameController::NotifyUpdateAvailable(Client * sender)
{
class UpdateConfirmation: public ConfirmDialogueCallback {
public:
GameController * c;
UpdateConfirmation(GameController * c_) { c = c_; }
void ConfirmCallback(ConfirmPrompt::DialogueResult result) override {
if (result == ConfirmPrompt::ResultOkay)
{
c->RunUpdater();
}
}
virtual ~UpdateConfirmation() { }
};
class UpdateNotification : public Notification
{
GameController * c;
@ -1728,7 +1613,7 @@ void GameController::NotifyUpdateAvailable(Client * sender)
if (info.Changelog.length())
updateMessage << "\n\nChangelog:\n" << info.Changelog;
new ConfirmPrompt("Run Updater", updateMessage.Build(), new UpdateConfirmation(c));
new ConfirmPrompt("Run Updater", updateMessage.Build(), { [this] { c->RunUpdater(); } });
}
};

View File

@ -51,15 +51,10 @@ private:
CommandInterface * commandInterface;
std::vector<DebugInfo*> debugInfo;
unsigned int debugFlags;
void OpenSaveDone();
public:
bool HasDone;
class SearchCallback;
class SSaveCallback;
class TagsCallback;
class StampsCallback;
class OptionsCallback;
class SaveOpenCallback;
friend class SaveOpenCallback;
GameController();
~GameController();
GameView * GetView();

View File

@ -14,6 +14,7 @@
#include "QuickOptions.h"
#include "DecorationTool.h"
#include "ToolButton.h"
#include "MenuButton.h"
#include "Menu.h"
#include "client/SaveInfo.h"
@ -41,38 +42,36 @@
# undef GetUserName // dammit windows
#endif
class SplitButton;
class SplitButtonAction
{
public:
virtual void ActionCallbackLeft(ui::Button * sender) {}
virtual void ActionCallbackRight(ui::Button * sender) {}
virtual ~SplitButtonAction() {}
};
class SplitButton : public ui::Button
{
private:
bool rightDown;
bool leftDown;
bool showSplit;
int splitPosition;
String toolTip2;
SplitButtonAction * splitActionCallback;
struct SplitButtonAction
{
std::function<void ()> left, right;
};
SplitButtonAction actionCallback;
public:
SplitButton(ui::Point position, ui::Point size, String buttonText, String toolTip, String toolTip2, int split) :
Button(position, size, buttonText, toolTip),
showSplit(true),
splitPosition(split),
toolTip2(toolTip2),
splitActionCallback(NULL)
toolTip2(toolTip2)
{
}
virtual ~SplitButton() = default;
void SetRightToolTip(String tooltip) { toolTip2 = tooltip; }
bool GetShowSplit() { return showSplit; }
void SetShowSplit(bool split) { showSplit = split; }
SplitButtonAction * GetSplitActionCallback() { return splitActionCallback; }
void SetSplitActionCallback(SplitButtonAction * newAction) { splitActionCallback = newAction; }
inline SplitButtonAction const &GetSplitActionCallback() { return actionCallback; }
inline void SetSplitActionCallback(SplitButtonAction const &action) { actionCallback = action; }
void SetToolTip(int x, int y)
{
if(x >= splitPosition || !showSplit)
@ -137,15 +136,15 @@ public:
{
if(!Enabled)
return;
if(splitActionCallback)
splitActionCallback->ActionCallbackRight(this);
if (actionCallback.right)
actionCallback.right();
}
void DoLeftAction()
{
if(!Enabled)
return;
if(splitActionCallback)
splitActionCallback->ActionCallbackLeft(this);
if (actionCallback.left)
actionCallback.left();
}
void Draw(const ui::Point& screenPos) override
{
@ -156,10 +155,6 @@ public:
if(showSplit)
g->draw_line(splitPosition+screenPos.X, screenPos.Y+1, splitPosition+screenPos.X, screenPos.Y+Size.Y-2, 180, 180, 180, 255);
}
virtual ~SplitButton()
{
delete splitActionCallback;
}
};
@ -221,19 +216,6 @@ GameView::GameView():
int currentX = 1;
//Set up UI
class SearchAction : public ui::ButtonAction
{
GameView * v;
public:
SearchAction(GameView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
if(v->CtrlBehaviour())
v->c->OpenLocalBrowse();
else
v->c->OpenSearch("");
}
};
scrollBar = new ui::Button(ui::Point(0,YRES+21), ui::Point(XRES, 2), "");
scrollBar->Appearance.BorderHover = ui::Colour(200, 200, 200);
@ -246,222 +228,105 @@ GameView::GameView():
searchButton->SetIcon(IconOpen);
currentX+=18;
searchButton->SetTogglable(false);
searchButton->SetActionCallback(new SearchAction(this));
searchButton->SetActionCallback({ [this] {
if (CtrlBehaviour())
c->OpenLocalBrowse();
else
c->OpenSearch("");
} });
AddComponent(searchButton);
class ReloadAction : public ui::ButtonAction
{
GameView * v;
public:
ReloadAction(GameView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->ReloadSim();
}
void AltActionCallback(ui::Button * sender) override
{
v->c->OpenSavePreview();
}
};
reloadButton = new ui::Button(ui::Point(currentX, Size.Y-16), ui::Point(17, 15), "", "Reload the simulation");
reloadButton->SetIcon(IconReload);
reloadButton->Appearance.Margin.Left+=2;
currentX+=18;
reloadButton->SetActionCallback(new ReloadAction(this));
reloadButton->SetActionCallback({ [this] { c->ReloadSim(); }, [this] { c->OpenSavePreview(); } });
AddComponent(reloadButton);
class SaveSimulationAction : public SplitButtonAction
{
GameView * v;
public:
SaveSimulationAction(GameView * _v) { v = _v; }
void ActionCallbackRight(ui::Button * sender) override
{
if(v->CtrlBehaviour() || !Client::Ref().GetAuthUser().UserID)
v->c->OpenLocalSaveWindow(false);
else
v->c->OpenSaveWindow();
}
void ActionCallbackLeft(ui::Button * sender) override
{
if(v->CtrlBehaviour() || !Client::Ref().GetAuthUser().UserID)
v->c->OpenLocalSaveWindow(true);
else
v->c->SaveAsCurrent();
}
};
saveSimulationButton = new SplitButton(ui::Point(currentX, Size.Y-16), ui::Point(150, 15), "[untitled simulation]", "", "", 19);
saveSimulationButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
saveSimulationButton->SetIcon(IconSave);
currentX+=151;
((SplitButton*)saveSimulationButton)->SetSplitActionCallback(new SaveSimulationAction(this));
saveSimulationButton->SetSplitActionCallback({
[this] {
if (CtrlBehaviour() || !Client::Ref().GetAuthUser().UserID)
c->OpenLocalSaveWindow(true);
else
c->SaveAsCurrent();
},
[this] {
if (CtrlBehaviour() || !Client::Ref().GetAuthUser().UserID)
c->OpenLocalSaveWindow(false);
else
c->OpenSaveWindow();
}
});
SetSaveButtonTooltips();
AddComponent(saveSimulationButton);
class UpVoteAction : public ui::ButtonAction
{
GameView * v;
public:
UpVoteAction(GameView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->Vote(1);
}
};
upVoteButton = new ui::Button(ui::Point(currentX, Size.Y-16), ui::Point(39, 15), "", "Like this save");
upVoteButton->SetIcon(IconVoteUp);
upVoteButton->Appearance.Margin.Top+=2;
upVoteButton->Appearance.Margin.Left+=2;
currentX+=38;
upVoteButton->SetActionCallback(new UpVoteAction(this));
upVoteButton->SetActionCallback({ [this] { c->Vote(1); } });
AddComponent(upVoteButton);
class DownVoteAction : public ui::ButtonAction
{
GameView * v;
public:
DownVoteAction(GameView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->Vote(-1);
}
};
downVoteButton = new ui::Button(ui::Point(currentX, Size.Y-16), ui::Point(15, 15), "", "Dislike this save");
downVoteButton->SetIcon(IconVoteDown);
downVoteButton->Appearance.Margin.Bottom+=2;
downVoteButton->Appearance.Margin.Left+=2;
currentX+=16;
downVoteButton->SetActionCallback(new DownVoteAction(this));
downVoteButton->SetActionCallback({ [this] { c->Vote(-1); } });
AddComponent(downVoteButton);
class TagSimulationAction : public ui::ButtonAction
{
GameView * v;
public:
TagSimulationAction(GameView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->OpenTags();
}
};
tagSimulationButton = new ui::Button(ui::Point(currentX, Size.Y-16), ui::Point(227, 15), "[no tags set]", "Add simulation tags");
tagSimulationButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
tagSimulationButton->SetIcon(IconTag);
//currentX+=252;
tagSimulationButton->SetActionCallback(new TagSimulationAction(this));
tagSimulationButton->SetActionCallback({ [this] { c->OpenTags(); } });
AddComponent(tagSimulationButton);
class ClearSimAction : public ui::ButtonAction
{
GameView * v;
public:
ClearSimAction(GameView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->ClearSim();
}
};
clearSimButton = new ui::Button(ui::Point(Size.X-159, Size.Y-16), ui::Point(17, 15), "", "Erase everything");
clearSimButton->SetIcon(IconNew);
clearSimButton->Appearance.Margin.Left+=2;
clearSimButton->SetActionCallback(new ClearSimAction(this));
clearSimButton->SetActionCallback({ [this] { c->ClearSim(); } });
AddComponent(clearSimButton);
class LoginAction : public SplitButtonAction
{
GameView * v;
public:
LoginAction(GameView * _v) { v = _v; }
void ActionCallbackLeft(ui::Button * sender) override
{
v->c->OpenLogin();
}
void ActionCallbackRight(ui::Button * sender) override
{
v->c->OpenProfile();
}
};
loginButton = new SplitButton(ui::Point(Size.X-141, Size.Y-16), ui::Point(92, 15), "[sign in]", "Sign into simulation server", "Edit Profile", 19);
loginButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
loginButton->SetIcon(IconLogin);
((SplitButton*)loginButton)->SetSplitActionCallback(new LoginAction(this));
loginButton->SetSplitActionCallback({
[this] { c->OpenLogin(); },
[this] { c->OpenProfile(); }
});
AddComponent(loginButton);
class SimulationOptionAction : public ui::ButtonAction
{
GameView * v;
public:
SimulationOptionAction(GameView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->OpenOptions();
}
};
simulationOptionButton = new ui::Button(ui::Point(Size.X-48, Size.Y-16), ui::Point(15, 15), "", "Simulation options");
simulationOptionButton->SetIcon(IconSimulationSettings);
simulationOptionButton->Appearance.Margin.Left+=2;
simulationOptionButton->SetActionCallback(new SimulationOptionAction(this));
simulationOptionButton->SetActionCallback({ [this] { c->OpenOptions(); } });
AddComponent(simulationOptionButton);
class DisplayModeAction : public ui::ButtonAction
{
GameView * v;
public:
DisplayModeAction(GameView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->OpenRenderOptions();
}
};
displayModeButton = new ui::Button(ui::Point(Size.X-32, Size.Y-16), ui::Point(15, 15), "", "Renderer options");
displayModeButton->SetIcon(IconRenderSettings);
displayModeButton->Appearance.Margin.Left+=2;
displayModeButton->SetActionCallback(new DisplayModeAction(this));
displayModeButton->SetActionCallback({ [this] { c->OpenRenderOptions(); } });
AddComponent(displayModeButton);
class PauseAction : public ui::ButtonAction
{
GameView * v;
public:
PauseAction(GameView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->SetPaused(sender->GetToggleState());
}
};
pauseButton = new ui::Button(ui::Point(Size.X-16, Size.Y-16), ui::Point(15, 15), "", "Pause/Resume the simulation"); //Pause
pauseButton->SetIcon(IconPause);
pauseButton->SetTogglable(true);
pauseButton->SetActionCallback(new PauseAction(this));
pauseButton->SetActionCallback({ [this] { c->SetPaused(pauseButton->GetToggleState()); } });
AddComponent(pauseButton);
class ElementSearchAction : public ui::ButtonAction
{
GameView * v;
public:
ElementSearchAction(GameView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->OpenElementSearch();
}
};
ui::Button * tempButton = new ui::Button(ui::Point(WINDOWW-16, WINDOWH-32), ui::Point(15, 15), 0xE065, "Search for elements");
tempButton->Appearance.Margin = ui::Border(0, 2, 3, 2);
tempButton->SetActionCallback(new ElementSearchAction(this));
tempButton->SetActionCallback({ [this] { c->OpenElementSearch(); } });
AddComponent(tempButton);
class ColourPickerAction : public ui::ButtonAction
{
GameView * v;
public:
ColourPickerAction(GameView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->OpenColourPicker();
}
};
colourPicker = new ui::Button(ui::Point((XRES/2)-8, YRES+1), ui::Point(16, 16), "", "Pick Colour");
colourPicker->SetActionCallback(new ColourPickerAction(this));
colourPicker->SetActionCallback({ [this] { c->OpenColourPicker(); } });
}
GameView::~GameView()
@ -482,49 +347,6 @@ GameView::~GameView()
delete placeSaveThumb;
}
class GameView::MenuAction: public ui::ButtonAction
{
GameView * v;
public:
int menuID;
bool needsClick;
MenuAction(GameView * _v, int menuID_)
{
v = _v;
menuID = menuID_;
if (menuID == SC_DECO)
needsClick = true;
else
needsClick = false;
}
void MouseEnterCallback(ui::Button * sender) override
{
// don't immediately change the active menu, the actual set is done inside GameView::OnMouseMove
// if we change it here it causes components to be removed, which causes the window to stop sending events
// and then the previous menusection button never gets sent the OnMouseLeave event and is never unhighlighted
if(!(needsClick || v->c->GetMouseClickRequired()) && !v->GetMouseDown())
v->SetActiveMenuDelayed(menuID);
}
void ActionCallback(ui::Button * sender) override
{
if (needsClick || v->c->GetMouseClickRequired())
v->c->SetActiveMenu(menuID);
else
MouseEnterCallback(sender);
}
};
class GameView::OptionAction: public ui::ButtonAction
{
QuickOption * option;
public:
OptionAction(QuickOption * _option) { option = _option; }
void ActionCallback(ui::Button * sender) override
{
option->Perform();
}
};
class GameView::OptionListener: public QuickOptionListener
{
ui::Button * button;
@ -544,51 +366,6 @@ public:
}
};
class GameView::ToolAction: public ui::ButtonAction
{
GameView * v;
public:
Tool * tool;
ToolAction(GameView * _v, Tool * tool_) { v = _v; tool = tool_; }
void ActionCallback(ui::Button * sender_) override
{
ToolButton *sender = (ToolButton*)sender_;
if (v->ShiftBehaviour() && v->CtrlBehaviour() && !v->AltBehaviour())
{
if (sender->GetSelectionState() == 0)
{
if (Favorite::Ref().IsFavorite(tool->GetIdentifier()))
{
Favorite::Ref().RemoveFavorite(tool->GetIdentifier());
}
else
{
Favorite::Ref().AddFavorite(tool->GetIdentifier());
}
v->c->RebuildFavoritesMenu();
}
else if (sender->GetSelectionState() == 1)
{
Favorite::Ref().RemoveFavorite(tool->GetIdentifier());
v->c->RebuildFavoritesMenu();
}
}
else
{
if (v->CtrlBehaviour() && v->AltBehaviour() && !v->ShiftBehaviour())
{
if (tool->GetIdentifier().Contains("_PT_"))
{
sender->SetSelectionState(3);
}
}
if (sender->GetSelectionState() >= 0 && sender->GetSelectionState() <= 3)
v->c->SetActiveTool(sender->GetSelectionState(), tool);
}
}
};
void GameView::NotifyQuickOptionsChanged(GameModel * sender)
{
for (size_t i = 0; i < quickOptionButtons.size(); i++)
@ -604,7 +381,9 @@ void GameView::NotifyQuickOptionsChanged(GameModel * sender)
ui::Button * tempButton = new ui::Button(ui::Point(WINDOWW-16, currentY), ui::Point(15, 15), option->GetIcon(), option->GetDescription());
//tempButton->Appearance.Margin = ui::Border(0, 2, 3, 2);
tempButton->SetTogglable(true);
tempButton->SetActionCallback(new OptionAction(option));
tempButton->SetActionCallback({ [option] {
option->Perform();
} });
option->AddListener(new OptionListener(tempButton));
AddComponent(tempButton);
@ -638,10 +417,25 @@ void GameView::NotifyMenuListChanged(GameModel * sender)
String description = menuList[i]->GetDescription();
if (i == SC_FAVORITES && !Favorite::Ref().AnyFavorites())
description += " (Use ctrl+shift+click to toggle the favorite status of an element)";
ui::Button * tempButton = new ui::Button(ui::Point(WINDOWW-16, currentY), ui::Point(15, 15), tempString, description);
auto *tempButton = new MenuButton(ui::Point(WINDOWW-16, currentY), ui::Point(15, 15), tempString, description);
tempButton->Appearance.Margin = ui::Border(0, 2, 3, 2);
tempButton->menuID = i;
tempButton->needsClick = i == SC_DECO;
tempButton->SetTogglable(true);
tempButton->SetActionCallback(new MenuAction(this, i));
auto mouseEnterCallback = [this, tempButton] {
// don't immediately change the active menu, the actual set is done inside GameView::OnMouseMove
// if we change it here it causes components to be removed, which causes the window to stop sending events
// and then the previous menusection button never gets sent the OnMouseLeave event and is never unhighlighted
if(!(tempButton->needsClick || c->GetMouseClickRequired()) && !GetMouseDown())
SetActiveMenuDelayed(tempButton->menuID);
};
auto actionCallback = [this, tempButton, mouseEnterCallback] {
if (tempButton->needsClick || c->GetMouseClickRequired())
c->SetActiveMenu(tempButton->menuID);
else
mouseEnterCallback();
};
tempButton->SetActionCallback({ actionCallback, nullptr, mouseEnterCallback });
currentY-=16;
AddComponent(tempButton);
menuButtons.push_back(tempButton);
@ -696,7 +490,7 @@ void GameView::NotifyActiveToolsChanged(GameModel * sender)
decoBrush = false;
for (size_t i = 0; i < toolButtons.size(); i++)
{
Tool * tool = ((ToolAction*)toolButtons[i]->GetActionCallback())->tool;
auto *tool = toolButtons[i]->tool;
if(sender->GetActiveTool(0) == tool)
{
toolButtons[i]->SetSelectionState(0); //Primary
@ -748,7 +542,7 @@ void GameView::NotifyToolListChanged(GameModel * sender)
{
for (size_t i = 0; i < menuButtons.size(); i++)
{
if (((MenuAction*)menuButtons[i]->GetActionCallback())->menuID==sender->GetActiveMenu())
if (menuButtons[i]->menuID==sender->GetActiveMenu())
{
menuButtons[i]->SetToggleState(true);
}
@ -767,21 +561,58 @@ void GameView::NotifyToolListChanged(GameModel * sender)
int currentX = 0;
for (size_t i = 0; i < toolList.size(); i++)
{
VideoBuffer * tempTexture = toolList[i]->GetTexture(26, 14);
auto *tool = toolList[i];
VideoBuffer * tempTexture = tool->GetTexture(26, 14);
ToolButton * tempButton;
//get decotool texture manually, since it changes depending on it's own color
if (sender->GetActiveMenu() == SC_DECO)
tempTexture = ((DecorationTool*)toolList[i])->GetIcon(toolList[i]->GetToolID(), 26, 14);
tempTexture = ((DecorationTool*)tool)->GetIcon(tool->GetToolID(), 26, 14);
if(tempTexture)
tempButton = new ToolButton(ui::Point(currentX, YRES+1), ui::Point(30, 18), "", toolList[i]->GetIdentifier(), toolList[i]->GetDescription());
tempButton = new ToolButton(ui::Point(currentX, YRES+1), ui::Point(30, 18), "", tool->GetIdentifier(), tool->GetDescription());
else
tempButton = new ToolButton(ui::Point(currentX, YRES+1), ui::Point(30, 18), toolList[i]->GetName(), toolList[i]->GetIdentifier(), toolList[i]->GetDescription());
tempButton = new ToolButton(ui::Point(currentX, YRES+1), ui::Point(30, 18), tool->GetName(), tool->GetIdentifier(), tool->GetDescription());
//currentY -= 17;
currentX -= 31;
tempButton->SetActionCallback(new ToolAction(this, toolList[i]));
tempButton->tool = tool;
tempButton->SetActionCallback({ [this, tempButton] {
auto *tool = tempButton->tool;
if (ShiftBehaviour() && CtrlBehaviour() && !AltBehaviour())
{
if (tempButton->GetSelectionState() == 0)
{
if (Favorite::Ref().IsFavorite(tool->GetIdentifier()))
{
Favorite::Ref().RemoveFavorite(tool->GetIdentifier());
}
else
{
Favorite::Ref().AddFavorite(tool->GetIdentifier());
}
c->RebuildFavoritesMenu();
}
else if (tempButton->GetSelectionState() == 1)
{
Favorite::Ref().RemoveFavorite(tool->GetIdentifier());
c->RebuildFavoritesMenu();
}
}
else
{
if (CtrlBehaviour() && AltBehaviour() && !ShiftBehaviour())
{
if (tool->GetIdentifier().Contains("_PT_"))
{
tempButton->SetSelectionState(3);
}
}
if (tempButton->GetSelectionState() >= 0 && tempButton->GetSelectionState() <= 3)
c->SetActiveTool(tempButton->GetSelectionState(), tool);
}
} });
tempButton->Appearance.SetTexture(tempTexture);
delete tempTexture;
@ -842,23 +673,8 @@ void GameView::NotifyColourSelectorVisibilityChanged(GameModel * sender)
void GameView::NotifyColourPresetsChanged(GameModel * sender)
{
class ColourPresetAction: public ui::ButtonAction
for (auto *button : colourPresets)
{
GameView * v;
public:
int preset;
ColourPresetAction(GameView * _v, int preset) : preset(preset) { v = _v; }
void ActionCallback(ui::Button * sender_) override
{
v->c->SetActiveColourPreset(preset);
v->c->SetColour(sender_->Appearance.BackgroundInactive);
}
};
for(std::vector<ToolButton*>::iterator iter = colourPresets.begin(), end = colourPresets.end(); iter != end; ++iter)
{
ToolButton * button = *iter;
RemoveComponent(button);
delete button;
}
@ -871,7 +687,10 @@ void GameView::NotifyColourPresetsChanged(GameModel * sender)
{
ToolButton * tempButton = new ToolButton(ui::Point(currentX, YRES+1), ui::Point(30, 18), "", "", "Decoration Presets.");
tempButton->Appearance.BackgroundInactive = *iter;
tempButton->SetActionCallback(new ColourPresetAction(this, i));
tempButton->SetActionCallback({ [this, i, tempButton] {
c->SetActiveColourPreset(i);
c->SetColour(tempButton->Appearance.BackgroundInactive);
} });
currentX += 31;
@ -920,14 +739,14 @@ void GameView::NotifyUserChanged(GameModel * sender)
if(!sender->GetUser().UserID)
{
loginButton->SetText("[sign in]");
((SplitButton*)loginButton)->SetShowSplit(false);
((SplitButton*)loginButton)->SetRightToolTip("Sign in to simulation server");
loginButton->SetShowSplit(false);
loginButton->SetRightToolTip("Sign in to simulation server");
}
else
{
loginButton->SetText(sender->GetUser().Username.FromUtf8());
((SplitButton*)loginButton)->SetShowSplit(true);
((SplitButton*)loginButton)->SetRightToolTip("Edit profile");
loginButton->SetShowSplit(true);
loginButton->SetRightToolTip("Edit profile");
}
// saveSimulationButtonEnabled = sender->GetUser().ID;
saveSimulationButtonEnabled = true;
@ -961,9 +780,9 @@ void GameView::NotifySaveChanged(GameModel * sender)
saveSimulationButton->SetText(sender->GetSave()->GetName());
if (sender->GetSave()->GetUserName() == sender->GetUser().Username)
((SplitButton*)saveSimulationButton)->SetShowSplit(true);
saveSimulationButton->SetShowSplit(true);
else
((SplitButton*)saveSimulationButton)->SetShowSplit(false);
saveSimulationButton->SetShowSplit(false);
reloadButton->Enabled = true;
upVoteButton->Enabled = (sender->GetSave()->GetID() && sender->GetUser().UserID && sender->GetSave()->GetVote()==0);
if(sender->GetSave()->GetID() && sender->GetUser().UserID && sender->GetSave()->GetVote()==1)
@ -1020,9 +839,9 @@ void GameView::NotifySaveChanged(GameModel * sender)
else if (sender->GetSaveFile())
{
if (ctrlBehaviour)
((SplitButton*)saveSimulationButton)->SetShowSplit(true);
saveSimulationButton->SetShowSplit(true);
else
((SplitButton*)saveSimulationButton)->SetShowSplit(false);
saveSimulationButton->SetShowSplit(false);
saveSimulationButton->SetText(sender->GetSaveFile()->GetDisplayName());
reloadButton->Enabled = true;
upVoteButton->Enabled = false;
@ -1037,7 +856,7 @@ void GameView::NotifySaveChanged(GameModel * sender)
}
else
{
((SplitButton*)saveSimulationButton)->SetShowSplit(false);
saveSimulationButton->SetShowSplit(false);
saveSimulationButton->SetText("[untitled simulation]");
reloadButton->Enabled = false;
upVoteButton->Enabled = false;
@ -1904,48 +1723,23 @@ void GameView::DoDraw()
void GameView::NotifyNotificationsChanged(GameModel * sender)
{
class NotificationButtonAction : public ui::ButtonAction
for (auto *notificationComponent : notificationComponents)
{
Notification * notification;
public:
NotificationButtonAction(Notification * notification) : notification(notification) { }
void ActionCallback(ui::Button * sender) override
{
notification->Action();
//v->c->RemoveNotification(notification);
}
};
class CloseNotificationButtonAction : public ui::ButtonAction
{
GameView * v;
Notification * notification;
public:
CloseNotificationButtonAction(GameView * v, Notification * notification) : v(v), notification(notification) { }
void ActionCallback(ui::Button * sender) override
{
v->c->RemoveNotification(notification);
}
void AltActionCallback(ui::Button * sender) override
{
v->c->RemoveNotification(notification);
}
};
for(std::vector<ui::Component*>::const_iterator iter = notificationComponents.begin(), end = notificationComponents.end(); iter != end; ++iter) {
ui::Component * cNotification = *iter;
RemoveComponent(cNotification);
delete cNotification;
RemoveComponent(notificationComponent);
delete notificationComponent;
}
notificationComponents.clear();
std::vector<Notification*> notifications = sender->GetNotifications();
int currentY = YRES-23;
for(std::vector<Notification*>::iterator iter = notifications.begin(), end = notifications.end(); iter != end; ++iter)
for (auto *notification : notifications)
{
int width = (Graphics::textwidth((*iter)->Message))+8;
ui::Button * tempButton = new ui::Button(ui::Point(XRES-width-22, currentY), ui::Point(width, 15), (*iter)->Message);
tempButton->SetActionCallback(new NotificationButtonAction(*iter));
int width = (Graphics::textwidth(notification->Message))+8;
ui::Button * tempButton = new ui::Button(ui::Point(XRES-width-22, currentY), ui::Point(width, 15), notification->Message);
tempButton->SetActionCallback({ [notification] {
notification->Action();
} });
tempButton->Appearance.BorderInactive = style::Colour::WarningTitle;
tempButton->Appearance.TextInactive = style::Colour::WarningTitle;
tempButton->Appearance.BorderHover = ui::Colour(255, 175, 0);
@ -1955,7 +1749,10 @@ void GameView::NotifyNotificationsChanged(GameModel * sender)
tempButton = new ui::Button(ui::Point(XRES-20, currentY), ui::Point(15, 15), 0xE02A);
//tempButton->SetIcon(IconClose);
tempButton->SetActionCallback(new CloseNotificationButtonAction(this, *iter));
auto closeNotification = [this, notification] {
c->RemoveNotification(notification);
};
tempButton->SetActionCallback({ closeNotification, closeNotification });
tempButton->Appearance.Margin.Left -= 1;
tempButton->Appearance.Margin.Top -= 1;
tempButton->Appearance.BorderInactive = style::Colour::WarningTitle;
@ -2060,7 +1857,7 @@ void GameView::enableCtrlBehaviour()
searchButton->SetToolTip("Open a simulation from your hard drive.");
if (currentSaveType == 2)
((SplitButton*)saveSimulationButton)->SetShowSplit(true);
saveSimulationButton->SetShowSplit(true);
}
}
@ -2084,7 +1881,7 @@ void GameView::disableCtrlBehaviour()
searchButton->Appearance.TextInactive = searchButton->Appearance.TextHover = ui::Colour(255, 255, 255);
searchButton->SetToolTip("Find & open a simulation. Hold Ctrl to load offline saves.");
if (currentSaveType == 2)
((SplitButton*)saveSimulationButton)->SetShowSplit(false);
saveSimulationButton->SetShowSplit(false);
}
}
@ -2118,13 +1915,13 @@ void GameView::UpdateToolStrength()
void GameView::SetSaveButtonTooltips()
{
if (!Client::Ref().GetAuthUser().UserID)
((SplitButton*)saveSimulationButton)->SetToolTips("Overwrite the open simulation on your hard drive.", "Save the simulation to your hard drive. Login to save online.");
saveSimulationButton->SetToolTips("Overwrite the open simulation on your hard drive.", "Save the simulation to your hard drive. Login to save online.");
else if (ctrlBehaviour)
((SplitButton*)saveSimulationButton)->SetToolTips("Overwrite the open simulation on your hard drive.", "Save the simulation to your hard drive.");
else if (((SplitButton*)saveSimulationButton)->GetShowSplit())
((SplitButton*)saveSimulationButton)->SetToolTips("Re-upload the current simulation", "Modify simulation properties");
saveSimulationButton->SetToolTips("Overwrite the open simulation on your hard drive.", "Save the simulation to your hard drive.");
else if (saveSimulationButton->GetShowSplit())
saveSimulationButton->SetToolTips("Re-upload the current simulation", "Modify simulation properties");
else
((SplitButton*)saveSimulationButton)->SetToolTips("Re-upload the current simulation", "Upload a new simulation. Hold Ctrl to save offline.");
saveSimulationButton->SetToolTips("Re-upload the current simulation", "Upload a new simulation. Hold Ctrl to save offline.");
}
void GameView::OnDraw()

View File

@ -24,6 +24,9 @@ namespace ui
class Textbox;
}
class SplitButton;
class MenuButton;
class Renderer;
class VideoBuffer;
class ToolButton;
@ -76,21 +79,23 @@ private:
Brush * activeBrush;
//UI Elements
std::vector<ui::Button*> quickOptionButtons;
std::vector<ui::Button*> menuButtons;
std::vector<MenuButton*> menuButtons;
std::vector<ToolButton*> toolButtons;
std::vector<ui::Component*> notificationComponents;
std::deque<std::pair<String, int> > logEntries;
ui::Button * scrollBar;
ui::Button * searchButton;
ui::Button * reloadButton;
ui::Button * saveSimulationButton;
SplitButton * saveSimulationButton;
bool saveSimulationButtonEnabled;
bool saveReuploadAllowed;
ui::Button * downVoteButton;
ui::Button * upVoteButton;
ui::Button * tagSimulationButton;
ui::Button * clearSimButton;
ui::Button * loginButton;
SplitButton * loginButton;
ui::Button * simulationOptionButton;
ui::Button * displayModeButton;
ui::Button * pauseButton;
@ -208,9 +213,6 @@ public:
void DoKeyPress(int key, int scan, bool repeat, bool shift, bool ctrl, bool alt) override;
void DoKeyRelease(int key, int scan, bool repeat, bool shift, bool ctrl, bool alt) override;
class MenuAction;
class ToolAction;
class OptionAction;
class OptionListener;
};

14
src/gui/game/MenuButton.h Normal file
View File

@ -0,0 +1,14 @@
#ifndef MENUBUTTON_H_
#define MENUBUTTON_H_
#include "gui/interface/Button.h"
class MenuButton : public ui::Button
{
public:
using ui::Button::Button;
int menuID;
bool needsClick;
};
#endif /* MENUBUTTON_H_ */

View File

@ -32,20 +32,6 @@ public:
void OnKeyPress(int key, int scan, bool repeat, bool shift, bool ctrl, bool alt) override;
void OnTryExit(ExitMethod method) override;
virtual ~PropertyWindow() {}
class OkayAction: public ui::ButtonAction
{
public:
PropertyWindow * prompt;
OkayAction(PropertyWindow * prompt_) { prompt = prompt_; }
void ActionCallback(ui::Button * sender) override
{
prompt->CloseActiveWindow();
if(prompt->textField->GetText().length())
prompt->SetProperty();
prompt->SelfDestruct();
return;
}
};
};
PropertyWindow::PropertyWindow(PropertyTool * tool_, Simulation *sim_):
@ -65,22 +51,17 @@ sim(sim_)
okayButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
okayButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
okayButton->Appearance.BorderInactive = ui::Colour(200, 200, 200);
okayButton->SetActionCallback(new OkayAction(this));
okayButton->SetActionCallback({ [this] {
CloseActiveWindow();
if (textField->GetText().length())
SetProperty();
SelfDestruct();
} });
AddComponent(okayButton);
SetOkayButton(okayButton);
class PropertyChanged: public ui::DropDownAction
{
PropertyWindow * w;
public:
PropertyChanged(PropertyWindow * w): w(w) { }
void OptionChanged(ui::DropDown * sender, std::pair<String, int> option) override
{
w->FocusComponent(w->textField);
}
};
property = new ui::DropDown(ui::Point(8, 25), ui::Point(Size.X-16, 16));
property->SetActionCallback(new PropertyChanged(this));
property->SetActionCallback({ [this] { FocusComponent(textField); } });
AddComponent(property);
for (size_t i = 0; i < properties.size(); i++)
{

View File

@ -50,71 +50,6 @@ public:
}
virtual ~SignWindow() {}
void OnTryExit(ui::Window::ExitMethod method) override;
class OkayAction: public ui::ButtonAction
{
public:
SignWindow * prompt;
OkayAction(SignWindow * prompt_) { prompt = prompt_; }
void ActionCallback(ui::Button * sender) override
{
prompt->CloseActiveWindow();
if(prompt->signID==-1 && prompt->textField->GetText().length())
{
prompt->sim->signs.push_back(sign(prompt->textField->GetText(), prompt->signPosition.X, prompt->signPosition.Y, (sign::Justification)prompt->justification->GetOption().second));
}
else if(prompt->signID!=-1 && prompt->textField->GetText().length())
{
prompt->sim->signs[prompt->signID] = sign(sign(prompt->textField->GetText(), prompt->signPosition.X, prompt->signPosition.Y, (sign::Justification)prompt->justification->GetOption().second));
}
prompt->SelfDestruct();
}
};
class DeleteAction: public ui::ButtonAction
{
public:
SignWindow * prompt;
DeleteAction(SignWindow * prompt_) { prompt = prompt_; }
void ActionCallback(ui::Button * sender) override
{
prompt->CloseActiveWindow();
if(prompt->signID!=-1)
{
prompt->sim->signs.erase(prompt->sim->signs.begin()+prompt->signID);
}
prompt->SelfDestruct();
}
};
class SignTextAction: public ui::TextboxAction
{
public:
SignWindow * prompt;
SignTextAction(SignWindow * prompt_) { prompt = prompt_; }
void TextChangedCallback(ui::Textbox * sender) override
{
if(prompt->signID!=-1)
{
prompt->sim->signs[prompt->signID].text = sender->GetText();
prompt->sim->signs[prompt->signID].ju = (sign::Justification)prompt->justification->GetOption().second;
}
}
};
class MoveAction: public ui::ButtonAction
{
public:
SignWindow * prompt;
MoveAction(SignWindow * prompt_) { prompt = prompt_; }
void ActionCallback(ui::Button * sender) override
{
if(prompt->signID!=-1)
{
prompt->movingSign = &prompt->sim->signs[prompt->signID];
prompt->sim->signs[prompt->signID].ju = (sign::Justification)prompt->justification->GetOption().second;
prompt->signMoving = true;
}
}
};
};
SignWindow::SignWindow(SignTool * tool_, Simulation * sim_, int signID_, ui::Point position_):
@ -136,7 +71,18 @@ SignWindow::SignWindow(SignTool * tool_, Simulation * sim_, int signID_, ui::Poi
okayButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
okayButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
okayButton->Appearance.BorderInactive = (ui::Colour(200, 200, 200));
okayButton->SetActionCallback(new OkayAction(this));
okayButton->SetActionCallback({ [this] {
CloseActiveWindow();
if(signID==-1 && textField->GetText().length())
{
sim->signs.push_back(sign(textField->GetText(), signPosition.X, signPosition.Y, (sign::Justification)justification->GetOption().second));
}
else if(signID!=-1 && textField->GetText().length())
{
sim->signs[signID] = sign(sign(textField->GetText(), signPosition.X, signPosition.Y, (sign::Justification)justification->GetOption().second));
}
SelfDestruct();
} });
AddComponent(okayButton);
SetOkayButton(okayButton);
@ -158,7 +104,13 @@ SignWindow::SignWindow(SignTool * tool_, Simulation * sim_, int signID_, ui::Poi
textField->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
textField->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
textField->SetLimit(45);
textField->SetActionCallback(new SignTextAction(this));
textField->SetActionCallback({ [this] {
if (signID!=-1)
{
sim->signs[signID].text = textField->GetText();
sim->signs[signID].ju = (sign::Justification)justification->GetOption().second;
}
} });
AddComponent(textField);
FocusComponent(textField);
@ -171,13 +123,27 @@ SignWindow::SignWindow(SignTool * tool_, Simulation * sim_, int signID_, ui::Poi
ui::Point position = ui::Point(justification->Position.X+justification->Size.X+3, 48);
ui::Button * moveButton = new ui::Button(position, ui::Point(((Size.X-position.X-8)/2)-2, 16), "Move");
moveButton->SetActionCallback(new MoveAction(this));
moveButton->SetActionCallback({ [this] {
if (signID!=-1)
{
movingSign = &sim->signs[signID];
sim->signs[signID].ju = (sign::Justification)justification->GetOption().second;
signMoving = true;
}
} });
AddComponent(moveButton);
position = ui::Point(justification->Position.X+justification->Size.X+3, 48)+ui::Point(moveButton->Size.X+3, 0);
ui::Button * deleteButton = new ui::Button(position, ui::Point((Size.X-position.X-8)-1, 16), "Delete");
//deleteButton->SetIcon(IconDelete);
deleteButton->SetActionCallback(new DeleteAction(this));
deleteButton->SetActionCallback({ [this] {
CloseActiveWindow();
if (signID!=-1)
{
sim->signs.erase(sim->signs.begin() + signID);
}
SelfDestruct();
} });
signPosition.X = sim->signs[signID].x;
signPosition.Y = sim->signs[signID].y;

View File

@ -110,7 +110,3 @@ int ToolButton::GetSelectionState()
{
return currentSelection;
}
ToolButton::~ToolButton() {
}

View File

@ -3,6 +3,8 @@
#include "gui/interface/Button.h"
class Tool;
class ToolButton: public ui::Button
{
int currentSelection;
@ -15,7 +17,7 @@ public:
void Draw(const ui::Point& screenPos) override;
void SetSelectionState(int state);
int GetSelectionState();
virtual ~ToolButton();
Tool *tool;
};
#endif /* TOOLBUTTON_H_ */

View File

@ -15,17 +15,11 @@ namespace ui {
AvatarButton::AvatarButton(Point position, Point size, ByteString username):
Component(position, size),
name(username),
tried(false),
actionCallback(NULL)
tried(false)
{
}
AvatarButton::~AvatarButton()
{
delete actionCallback;
}
void AvatarButton::OnResponse(std::unique_ptr<VideoBuffer> Avatar)
{
avatar = std::move(Avatar);
@ -97,13 +91,8 @@ void AvatarButton::OnMouseLeave(int x, int y)
void AvatarButton::DoAction()
{
if(actionCallback)
actionCallback->ActionCallback(this);
}
void AvatarButton::SetActionCallback(AvatarButtonAction * action)
{
actionCallback = action;
if( actionCallback.action)
actionCallback.action();
}
} /* namespace ui */

View File

@ -10,25 +10,25 @@
#include "client/http/RequestMonitor.h"
#include <memory>
#include <functional>
namespace ui
{
class AvatarButton;
class AvatarButtonAction
{
public:
virtual void ActionCallback(ui::AvatarButton * sender) {}
virtual ~AvatarButtonAction() {}
};
class AvatarButton : public Component, public http::RequestMonitor<http::AvatarRequest>
{
std::unique_ptr<VideoBuffer> avatar;
ByteString name;
bool tried;
struct AvatarButtonAction
{
std::function<void ()> action;
};
AvatarButtonAction actionCallback;
public:
AvatarButton(Point position, Point size, ByteString username);
virtual ~AvatarButton();
virtual ~AvatarButton() = default;
void OnMouseClick(int x, int y, unsigned int button) override;
void OnMouseUnclick(int x, int y, unsigned int button) override;
@ -47,10 +47,9 @@ public:
void SetUsername(ByteString username) { name = username; }
ByteString GetUsername() { return name; }
void SetActionCallback(AvatarButtonAction * action);
inline void SetActionCallback(AvatarButtonAction const &action) { actionCallback = action; };
protected:
bool isMouseInside, isButtonDown;
AvatarButtonAction * actionCallback;
};
}
#endif /* AVATARBUTTON_H_ */

View File

@ -15,8 +15,7 @@ Button::Button(Point position, Point size, String buttonText, String toolTip):
isButtonDown(false),
isMouseInside(false),
isTogglable(false),
toggle(false),
actionCallback(NULL)
toggle(false)
{
TextPosition(ButtonText);
}
@ -191,8 +190,8 @@ void Button::OnMouseEnter(int x, int y)
isMouseInside = true;
if(!Enabled)
return;
if(actionCallback)
actionCallback->MouseEnterCallback(this);
if (actionCallback.mouseEnter)
actionCallback.mouseEnter();
}
void Button::OnMouseHover(int x, int y)
@ -213,27 +212,16 @@ void Button::DoAction()
{
if(!Enabled)
return;
if(actionCallback)
actionCallback->ActionCallback(this);
if (actionCallback.action)
actionCallback.action();
}
void Button::DoAltAction()
{
if(!Enabled)
return;
if(actionCallback)
actionCallback->AltActionCallback(this);
}
void Button::SetActionCallback(ButtonAction * action)
{
delete actionCallback;
actionCallback = action;
}
Button::~Button()
{
delete actionCallback;
if (actionCallback.altAction)
actionCallback.altAction();
}
} /* namespace ui */

View File

@ -4,23 +4,21 @@
#include "common/String.h"
#include "Component.h"
#include <functional>
namespace ui
{
class Button;
class ButtonAction
{
public:
virtual void ActionCallback(ui::Button * sender) {}
virtual void AltActionCallback(ui::Button * sender) {}
virtual void MouseEnterCallback(ui::Button * sender) {}
virtual ~ButtonAction() {}
};
class Button : public Component
{
struct ButtonAction
{
std::function<void ()> action, altAction, mouseEnter;
};
public:
Button(Point position = Point(0, 0), Point size = Point(0, 0), String buttonText = String(), String toolTip = String());
virtual ~Button();
virtual ~Button() = default;
void OnMouseClick(int x, int y, unsigned int button) override;
void OnMouseUnclick(int x, int y, unsigned int button) override;
@ -40,21 +38,20 @@ public:
bool GetTogglable();
bool GetToggleState();
void SetToggleState(bool state);
void SetActionCallback(ButtonAction * action);
ButtonAction * GetActionCallback() { return actionCallback; }
inline void SetActionCallback(ButtonAction const &action) { actionCallback = action; }
// inline ButtonAction const &GetActionCallback() const { return actionCallback; }
void SetText(String buttonText);
void SetIcon(Icon icon);
inline String GetText() { return ButtonText; }
void SetToolTip(String newToolTip) { toolTip = newToolTip; }
protected:
protected:
String ButtonText;
String toolTip;
String buttonDisplayText;
bool isButtonDown, isAltButtonDown, state, isMouseInside, isTogglable, toggle;
ButtonAction * actionCallback;
ButtonAction actionCallback;
};
}
#endif /* BUTTON_H_ */

View File

@ -11,8 +11,7 @@ Checkbox::Checkbox(ui::Point position, ui::Point size, String text, String toolT
text(text),
toolTip(toolTip),
checked(false),
isMouseOver(false),
actionCallback(NULL)
isMouseOver(false)
{
}
@ -44,8 +43,8 @@ void Checkbox::OnMouseClick(int x, int y, unsigned int button)
{
checked = true;
}
if(actionCallback)
actionCallback->ActionCallback(this);
if (actionCallback.action)
actionCallback.action();
}
void Checkbox::OnMouseUp(int x, int y, unsigned int button)
@ -97,14 +96,3 @@ void Checkbox::Draw(const Point& screenPos)
g->draw_icon(screenPos.X+iconPosition.X, screenPos.Y+iconPosition.Y, Appearance.icon, 200);
}
}
void Checkbox::SetActionCallback(CheckboxAction * action)
{
delete actionCallback;
actionCallback = action;
}
Checkbox::~Checkbox() {
delete actionCallback;
}

View File

@ -3,23 +3,26 @@
#include "common/String.h"
#include "Component.h"
#include <functional>
namespace ui
{
class Checkbox;
class CheckboxAction
{
public:
virtual void ActionCallback(ui::Checkbox * sender) {}
virtual ~CheckboxAction() {}
};
class Checkbox: public ui::Component {
String text;
String toolTip;
bool checked;
bool isMouseOver;
CheckboxAction * actionCallback;
struct CheckboxAction
{
std::function<void ()> action;
};
CheckboxAction actionCallback;
public:
Checkbox(ui::Point position, ui::Point size, String text, String toolTip);
virtual ~Checkbox() = default;
void SetText(String text);
String GetText();
void SetIcon(Icon icon);
@ -29,11 +32,10 @@ public:
void OnMouseLeave(int x, int y) override;
void OnMouseClick(int x, int y, unsigned int button) override;
void OnMouseUp(int x, int y, unsigned int button) override;
void SetActionCallback(CheckboxAction * action);
CheckboxAction * GetActionCallback() { return actionCallback; }
inline void SetActionCallback(CheckboxAction const &action) { actionCallback = action; }
inline CheckboxAction const &GetActionCallback() const { return actionCallback; }
bool GetChecked() { return checked; }
void SetChecked(bool checked_) { checked = checked_; }
virtual ~Checkbox();
};
}

View File

@ -6,18 +6,6 @@
using namespace ui;
class ContextMenu::ItemSelectedAction: public ButtonAction
{
ContextMenu * window;
int item;
public:
ItemSelectedAction(ContextMenu * window, int itemID): window(window), item(itemID) { }
void ActionCallback(ui::Button *sender) override
{
window->ActionCallbackItem(sender, item);
}
};
ContextMenu::ContextMenu(Component * source):
Window(ui::Point(0, 0), ui::Point(0, 0)),
source(source),
@ -49,7 +37,10 @@ void ContextMenu::Show(ui::Point position)
Button * tempButton = new Button(Point(1, currentY), Point(Size.X-2, 16), items[i].Text);
tempButton->Appearance = Appearance;
tempButton->Enabled = items[i].Enabled;
tempButton->SetActionCallback(new ItemSelectedAction(this, items[i].ID));
auto item = items[i].ID;
tempButton->SetActionCallback({ [this, item, tempButton] {
ActionCallbackItem(tempButton, item);
} });
buttons.push_back(tempButton);
AddComponent(tempButton);
currentY += 15;

View File

@ -18,14 +18,15 @@ public:
ContextMenuItem(String text, int id, bool enabled) : ID(id), Text(text), Enabled(enabled) {}
};
class ContextMenu: public ui::Window, public ButtonAction {
class ContextMenu: public ui::Window {
std::vector<Button*> buttons;
std::vector<ContextMenuItem> items;
ui::Component * source;
public:
ui::Appearance Appearance;
class ItemSelectedAction;
ContextMenu(Component * source);
virtual ~ContextMenu() = default;
void ActionCallbackItem(ui::Button *sender, int item);
void AddItem(ContextMenuItem item);
void RemoveItem(int id);
@ -33,7 +34,6 @@ public:
void Show(ui::Point position);
void OnDraw() override;
void OnMouseDown(int x, int y, unsigned button) override;
virtual ~ContextMenu() {}
};
}

View File

@ -7,27 +7,14 @@
namespace ui {
class ItemSelectedAction;
class DropDownWindow: public ui::Window {
friend class ItemSelectedAction;
class DropDownWindow : public ui::Window
{
DropDown * dropDown;
Appearance appearance;
std::vector<Button> buttons;
bool isMouseInside;
public:
class ItemSelectedAction: public ButtonAction
{
DropDownWindow * window;
String option;
public:
ItemSelectedAction(DropDownWindow * window, String option): window(window), option(option) { }
void ActionCallback(ui::Button *sender) override
{
window->CloseActiveWindow();
window->setOption(option);
window->SelfDestruct();
}
};
DropDownWindow(DropDown * dropDown):
Window(dropDown->GetScreenPos() + ui::Point(-1, -1 - dropDown->optionIndex * 16), ui::Point(dropDown->Size.X+2, 1+dropDown->options.size()*16)),
dropDown(dropDown),
@ -40,7 +27,12 @@ public:
tempButton->Appearance = appearance;
if (i)
tempButton->Appearance.Border = ui::Border(0, 1, 1, 1);
tempButton->SetActionCallback(new ItemSelectedAction(this, dropDown->options[i].first));
auto option = dropDown->options[i].first;
tempButton->SetActionCallback({ [this, option] {
CloseActiveWindow();
setOption(option);
SelfDestruct();
} });
AddComponent(tempButton);
currentY += 16;
}
@ -53,15 +45,9 @@ public:
void setOption(String option)
{
dropDown->SetOption(option);
if (dropDown->callback)
if (dropDown->actionCallback.change)
{
size_t optionIndex = 0;
for (optionIndex = 0; optionIndex < dropDown->options.size(); optionIndex++)
{
if(option == dropDown->options[optionIndex].first)
break;
}
dropDown->callback->OptionChanged(dropDown, dropDown->options[optionIndex]);
dropDown->actionCallback.change();
}
}
void OnTryExit(ExitMethod method) override
@ -75,8 +61,7 @@ public:
DropDown::DropDown(Point position, Point size):
Component(position, size),
isMouseInside(false),
optionIndex(-1),
callback(NULL)
optionIndex(-1)
{
}
@ -129,70 +114,70 @@ void DropDown::OnMouseLeave(int x, int y)
{
isMouseInside = false;
}
std::pair<String, int> DropDown::GetOption()
{
if(optionIndex!=-1)
{
return options[optionIndex];
}
return std::pair<String, int>("", -1);
}
void DropDown::SetOption(String option)
std::pair<String, int> DropDown::GetOption()
{
if(optionIndex!=-1)
{
for (size_t i = 0; i < options.size(); i++)
{
if (options[i].first == option)
{
optionIndex = i;
TextPosition(options[optionIndex].first);
return;
}
}
}
void DropDown::SetOption(int option)
{
for (size_t i = 0; i < options.size(); i++)
{
if (options[i].second == option)
{
optionIndex = i;
TextPosition(options[optionIndex].first);
return;
}
}
}
void DropDown::AddOption(std::pair<String, int> option)
{
for (size_t i = 0; i < options.size(); i++)
{
if (options[i] == option)
return;
}
options.push_back(option);
}
void DropDown::RemoveOption(String option)
{
start:
for (size_t i = 0; i < options.size(); i++)
{
if (options[i].first == option)
{
if ((int)i == optionIndex)
optionIndex = -1;
options.erase(options.begin()+i);
goto start;
}
}
}
void DropDown::SetOptions(std::vector<std::pair<String, int> > options)
{
this->options = options;
return options[optionIndex];
}
return std::pair<String, int>("", -1);
}
void DropDown::SetOption(String option)
{
for (size_t i = 0; i < options.size(); i++)
{
if (options[i].first == option)
{
optionIndex = i;
TextPosition(options[optionIndex].first);
return;
}
}
}
DropDown::~DropDown() {
delete callback;
void DropDown::SetOption(int option)
{
for (size_t i = 0; i < options.size(); i++)
{
if (options[i].second == option)
{
optionIndex = i;
TextPosition(options[optionIndex].first);
return;
}
}
}
void DropDown::AddOption(std::pair<String, int> option)
{
for (size_t i = 0; i < options.size(); i++)
{
if (options[i] == option)
return;
}
options.push_back(option);
}
void DropDown::RemoveOption(String option)
{
start:
for (size_t i = 0; i < options.size(); i++)
{
if (options[i].first == option)
{
if ((int)i == optionIndex)
optionIndex = -1;
options.erase(options.begin()+i);
goto start;
}
}
}
void DropDown::SetOptions(std::vector<std::pair<String, int> > options)
{
this->options = options;
}
} /* namespace ui */

View File

@ -4,36 +4,41 @@
#include <utility>
#include "Component.h"
#include <functional>
namespace ui {
class DropDown;
class DropDownWindow;
class DropDownAction
class DropDown : public ui::Component
{
public:
virtual void OptionChanged(DropDown * sender, std::pair<String, int> newOption) {}
virtual ~DropDownAction() {}
};
class DropDown: public ui::Component {
friend class DropDownWindow;
bool isMouseInside;
int optionIndex;
DropDownAction * callback;
struct DropDownAction
{
std::function<void ()> change;
};
DropDownAction actionCallback;
std::vector<std::pair<String, int> > options;
public:
DropDown(Point position, Point size);
virtual ~DropDown() = default;
std::pair<String, int> GetOption();
void SetOption(int option);
void SetOption(String option);
void AddOption(std::pair<String, int> option);
void RemoveOption(String option);
void SetOptions(std::vector<std::pair<String, int> > options);
void SetActionCallback(DropDownAction * action) { callback = action;}
inline void SetActionCallback(DropDownAction action) { actionCallback = action; }
void Draw(const Point& screenPos) override;
void OnMouseClick(int x, int y, unsigned int button) override;
void OnMouseEnter(int x, int y) override;
void OnMouseLeave(int x, int y) override;
virtual ~DropDown();
};
} /* namespace ui */

View File

@ -77,18 +77,9 @@ void Engine::Exit()
void Engine::ConfirmExit()
{
class ExitConfirmation: public ConfirmDialogueCallback {
public:
ExitConfirmation() {}
void ConfirmCallback(ConfirmPrompt::DialogueResult result) override {
if (result == ConfirmPrompt::ResultOkay)
{
ui::Engine::Ref().Exit();
}
}
virtual ~ExitConfirmation() { }
};
new ConfirmPrompt("You are about to quit", "Are you sure you want to exit the game?", new ExitConfirmation());
new ConfirmPrompt("You are about to quit", "Are you sure you want to exit the game?", { [] {
ui::Engine::Ref().Exit();
} });
}
void Engine::ShowWindow(Window * window)

View File

@ -14,10 +14,11 @@
namespace ui {
SaveButton::SaveButton(Point position, Point size, SaveInfo * save):
SaveButton::SaveButton(Point position, Point size) :
Component(position, size),
file(NULL),
save(save),
file(nullptr),
save(nullptr),
wantsDraw(false),
triedThumbnail(false),
isMouseInsideAuthor(false),
isMouseInsideHistory(false),
@ -26,9 +27,13 @@ SaveButton::SaveButton(Point position, Point size, SaveInfo * save):
isButtonDown(false),
isMouseInside(false),
selected(false),
selectable(false),
actionCallback(NULL)
selectable(false)
{
}
SaveButton::SaveButton(Point position, Point size, SaveInfo * save_) : SaveButton(position, size)
{
save = save_;
if(save)
{
name = save->name;
@ -87,22 +92,9 @@ SaveButton::SaveButton(Point position, Point size, SaveInfo * save):
}
}
SaveButton::SaveButton(Point position, Point size, SaveFile * file):
Component(position, size),
file(file),
save(NULL),
wantsDraw(false),
triedThumbnail(false),
isMouseInsideAuthor(false),
isMouseInsideHistory(false),
showVotes(false),
thumbnailRenderer(nullptr),
isButtonDown(false),
isMouseInside(false),
selected(false),
selectable(false),
actionCallback(NULL)
SaveButton::SaveButton(Point position, Point size, SaveFile * file_) : SaveButton(position, size)
{
file = file_;
if(file)
{
name = file->GetDisplayName();
@ -121,7 +113,6 @@ SaveButton::~SaveButton()
{
thumbnailRenderer->Abandon();
}
delete actionCallback;
delete save;
delete file;
}
@ -407,20 +398,20 @@ void SaveButton::OnMouseLeave(int x, int y)
void SaveButton::DoAltAction()
{
if(actionCallback)
actionCallback->AltActionCallback(this);
if (actionCallback.altAction)
actionCallback.altAction();
}
void SaveButton::DoAltAction2()
{
if(actionCallback)
actionCallback->AltActionCallback2(this);
if (actionCallback.altAltAction)
actionCallback.altAltAction();
}
void SaveButton::DoAction()
{
if(actionCallback)
actionCallback->ActionCallback(this);
if (actionCallback.action)
actionCallback.action();
}
void SaveButton::DoSelection()
@ -432,13 +423,8 @@ void SaveButton::DoSelection()
else
menu->SetItem(1, "Select");
}
if(selectable && actionCallback)
actionCallback->SelectedCallback(this);
}
void SaveButton::SetActionCallback(SaveButtonAction * action)
{
actionCallback = action;
if (selectable && actionCallback.selected)
actionCallback.selected();
}
} /* namespace ui */

View File

@ -8,6 +8,7 @@
#include "client/http/RequestMonitor.h"
#include <memory>
#include <functional>
class VideoBuffer;
class SaveFile;
@ -15,17 +16,6 @@ class SaveInfo;
class ThumbnailRendererTask;
namespace ui
{
class SaveButton;
class SaveButtonAction
{
public:
virtual void ActionCallback(ui::SaveButton * sender) {}
virtual void AltActionCallback(ui::SaveButton * sender) {}
virtual void AltActionCallback2(ui::SaveButton * sender) {}
virtual void SelectedCallback(ui::SaveButton * sender) {}
virtual ~SaveButtonAction() {}
};
class SaveButton : public Component, public http::RequestMonitor<http::ThumbnailRequest>
{
SaveFile * file;
@ -44,6 +34,15 @@ class SaveButton : public Component, public http::RequestMonitor<http::Thumbnail
bool isMouseInsideHistory;
bool showVotes;
ThumbnailRendererTask *thumbnailRenderer;
struct SaveButtonAction
{
std::function<void ()> action, altAction, altAltAction, selected;
};
SaveButtonAction actionCallback;
SaveButton(Point position, Point size);
public:
SaveButton(Point position, Point size, SaveInfo * save);
SaveButton(Point position, Point size, SaveFile * file);
@ -78,10 +77,9 @@ public:
void DoAltAction();
void DoAltAction2();
void DoSelection();
void SetActionCallback(SaveButtonAction * action);
inline void SetActionCallback(SaveButtonAction action) { actionCallback = action; }
protected:
bool isButtonDown, state, isMouseInside, selected, selectable;
SaveButtonAction * actionCallback;
};
}
#endif /* BUTTON_H_ */

View File

@ -35,9 +35,9 @@ void Slider::updatePosition(int position)
sliderPosition = newSliderPosition;
if(actionCallback)
if (actionCallback.change)
{
actionCallback->ValueChangedCallback(this);
actionCallback.change();
}
}
@ -132,8 +132,4 @@ void Slider::Draw(const Point& screenPos)
g->drawrect(screenPos.X+sliderX-2, screenPos.Y+1, 4, Size.Y-2, 200, 200, 200, 255);
}
Slider::~Slider()
{
}
} /* namespace ui */

View File

@ -4,36 +4,38 @@
#include "Component.h"
#include "Colour.h"
#include <functional>
namespace ui {
class Slider;
class SliderAction
class Slider : public ui::Component
{
public:
virtual void ValueChangedCallback(ui::Slider * sender) {}
virtual ~SliderAction() {}
};
class Slider: public ui::Component {
friend class SliderAction;
int sliderSteps;
int sliderPosition;
bool isMouseDown;
unsigned char * bgGradient;
SliderAction * actionCallback;
struct SliderAction
{
std::function<void ()> change;
};
SliderAction actionCallback;
Colour col1, col2;
void updatePosition(int position);
public:
Slider(Point position, Point size, int steps);
virtual ~Slider() = default;
void OnMouseMoved(int x, int y, int dx, int dy) override;
void OnMouseClick(int x, int y, unsigned button) override;
void OnMouseUp(int x, int y, unsigned button) override;
void Draw(const Point& screenPos) override;
void SetColour(Colour col1, Colour col2);
void SetActionCallback(SliderAction * action) { actionCallback = action; }
inline void SetActionCallback(SliderAction action) { actionCallback = action; }
int GetValue();
void SetValue(int value);
int GetSteps();
void SetSteps(int steps);
virtual ~Slider();
};
} /* namespace ui */

View File

@ -24,8 +24,7 @@ Textbox::Textbox(Point position, Point size, String textboxText, String textboxP
characterDown(0),
mouseDown(false),
masked(false),
border(true),
actionCallback(NULL)
border(true)
{
placeHolder = textboxPlaceholder;
@ -38,11 +37,6 @@ Textbox::Textbox(Point position, Point size, String textboxText, String textboxP
menu->AddItem(ContextMenuItem("Paste", 2, true));
}
Textbox::~Textbox()
{
delete actionCallback;
}
void Textbox::SetHidden(bool hidden)
{
menu->RemoveItem(0);
@ -181,8 +175,8 @@ void Textbox::cutSelection()
{
cursorPositionY = cursorPositionX = 0;
}
if(actionCallback)
actionCallback->TextChangedCallback(this);
if (actionCallback.change)
actionCallback.change();
}
void Textbox::pasteIntoSelection()
@ -251,8 +245,8 @@ void Textbox::pasteIntoSelection()
{
cursorPositionY = cursorPositionX = 0;
}
if(actionCallback)
actionCallback->TextChangedCallback(this);
if (actionCallback.change)
actionCallback.change();
}
bool Textbox::CharacterValid(int character)
@ -469,8 +463,8 @@ void Textbox::AfterTextChange(bool changed)
{
cursorPositionY = cursorPositionX = 0;
}
if (changed && actionCallback)
actionCallback->TextChangedCallback(this);
if (changed && actionCallback.change)
actionCallback.change();
}
void Textbox::OnTextInput(String text)

View File

@ -3,27 +3,24 @@
#include "Label.h"
#include <functional>
namespace ui
{
class Textbox;
class TextboxAction
struct TextboxAction
{
public:
virtual void TextChangedCallback(ui::Textbox * sender) {}
virtual ~TextboxAction() {}
std::function<void ()> change;
};
class Textbox : public Label
{
friend class TextboxAction;
void AfterTextChange(bool changed);
public:
bool ReadOnly;
enum ValidInput { All, Multiline, Numeric, Number }; // Numeric doesn't delete trailing 0's
Textbox(Point position, Point size, String textboxText = String(), String textboxPlaceholder = String());
virtual ~Textbox();
virtual ~Textbox() = default;
void SetText(String text) override;
String GetText() override;
@ -33,7 +30,7 @@ public:
void SetBorder(bool border) { this->border = border; }
void SetHidden(bool hidden);
bool GetHidden() { return masked; }
void SetActionCallback(TextboxAction * action) { actionCallback = action; }
void SetActionCallback(TextboxAction action) { actionCallback = action; }
void SetLimit(size_t limit);
size_t GetLimit();
@ -67,7 +64,7 @@ protected:
bool mouseDown;
bool masked, border;
int cursor, cursorPositionX, cursorPositionY;
TextboxAction *actionCallback;
TextboxAction actionCallback;
String backingText;
String placeHolder;

View File

@ -12,7 +12,7 @@
#include "common/tpt-minmax.h"
LocalBrowserController::LocalBrowserController(ControllerCallback * callback):
LocalBrowserController::LocalBrowserController(std::function<void ()> onDone_):
HasDone(false)
{
browserModel = new LocalBrowserModel();
@ -20,7 +20,7 @@ LocalBrowserController::LocalBrowserController(ControllerCallback * callback):
browserView->AttachController(this);
browserModel->AddObserver(browserView);
this->callback = callback;
onDone = onDone_;
browserModel->UpdateSavesList(1);
}
@ -37,23 +37,12 @@ SaveFile * LocalBrowserController::GetSave()
void LocalBrowserController::RemoveSelected()
{
class RemoveSelectedConfirmation: public ConfirmDialogueCallback {
public:
LocalBrowserController * c;
RemoveSelectedConfirmation(LocalBrowserController * c_) { c = c_; }
void ConfirmCallback(ConfirmPrompt::DialogueResult result) override {
if (result == ConfirmPrompt::ResultOkay)
c->removeSelectedC();
}
virtual ~RemoveSelectedConfirmation() { }
};
StringBuilder desc;
desc << "Are you sure you want to delete " << browserModel->GetSelected().size() << " stamp";
if(browserModel->GetSelected().size()>1)
desc << "s";
desc << "?";
new ConfirmPrompt("Delete stamps", desc.Build(), new RemoveSelectedConfirmation(this));
new ConfirmPrompt("Delete stamps", desc.Build(), { [this] { removeSelectedC(); } });
}
void LocalBrowserController::removeSelectedC()
@ -87,19 +76,7 @@ void LocalBrowserController::removeSelectedC()
void LocalBrowserController::RescanStamps()
{
class RescanConfirmation: public ConfirmDialogueCallback {
public:
LocalBrowserController * c;
RescanConfirmation(LocalBrowserController * c_) { c = c_; }
void ConfirmCallback(ConfirmPrompt::DialogueResult result) override {
if (result == ConfirmPrompt::ResultOkay)
c->rescanStampsC();
}
virtual ~RescanConfirmation() { }
};
String desc = "Rescanning the stamps folder can find stamps added to the stamps folder or recover stamps when the stamps.def file has been lost or damaged. However, be warned that this will mess up the current sorting order";
new ConfirmPrompt("Rescan", desc, new RescanConfirmation(this));
new ConfirmPrompt("Rescan", "Rescanning the stamps folder can find stamps added to the stamps folder or recover stamps when the stamps.def file has been lost or damaged. However, be warned that this will mess up the current sorting order", { [this] { rescanStampsC(); } });
}
void LocalBrowserController::rescanStampsC()
@ -161,15 +138,14 @@ void LocalBrowserController::SetMoveToFront(bool move)
void LocalBrowserController::Exit()
{
browserView->CloseActiveWindow();
if(callback)
callback->ControllerExit();
if (onDone)
onDone();
HasDone = true;
}
LocalBrowserController::~LocalBrowserController()
{
browserView->CloseActiveWindow();
delete callback;
delete browserModel;
delete browserView;
}

View File

@ -3,17 +3,18 @@
#include "common/String.h"
class ControllerCallback;
#include <functional>
class SaveFile;
class LocalBrowserView;
class LocalBrowserModel;
class LocalBrowserController {
ControllerCallback * callback;
LocalBrowserView * browserView;
LocalBrowserModel * browserModel;
std::function<void ()> onDone;
public:
bool HasDone;
LocalBrowserController(ControllerCallback * callback);
LocalBrowserController(std::function<void ()> onDone = nullptr);
LocalBrowserView * GetView() {return browserView;}
SaveFile * GetSave();
void RemoveSelected();

View File

@ -29,18 +29,8 @@ LocalBrowserView::LocalBrowserView():
AddComponent(previousButton);
AddComponent(undeleteButton);
class PageNumAction : public ui::TextboxAction
{
LocalBrowserView * v;
public:
PageNumAction(LocalBrowserView * _v) { v = _v; }
void TextChangedCallback(ui::Textbox * sender) override
{
v->textChanged();
}
};
pageTextbox = new ui::Textbox(ui::Point(283, WINDOWH-18), ui::Point(41, 16), "");
pageTextbox->SetActionCallback(new PageNumAction(this));
pageTextbox->SetActionCallback({ [this] { textChanged(); } });
pageTextbox->SetInputType(ui::Textbox::Number);
pageLabel = new ui::Label(ui::Point(0, WINDOWH-18), ui::Point(30, 16), "Page"); //page [TEXTBOX] of y
pageLabel->Appearance.HorizontalAlign = ui::Appearance::AlignRight;
@ -50,51 +40,19 @@ LocalBrowserView::LocalBrowserView():
AddComponent(pageCountLabel);
AddComponent(pageTextbox);
class RelativePageAction : public ui::ButtonAction
{
LocalBrowserView * v;
int offset;
public:
RelativePageAction(LocalBrowserView * _v, int _offset): v(_v), offset(_offset) {}
void ActionCallback(ui::Button * sender) override
{
v->c->SetPageRelative(offset);
}
};
nextButton->SetActionCallback(new RelativePageAction(this, 1));
nextButton->SetActionCallback({ [this] { c->SetPageRelative(1); } });
nextButton->Appearance.HorizontalAlign = ui::Appearance::AlignRight;
nextButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
previousButton->SetActionCallback(new RelativePageAction(this, -1));
previousButton->SetActionCallback({ [this] { c->SetPageRelative(-1); } });
previousButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
previousButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
class UndeleteAction : public ui::ButtonAction
{
LocalBrowserView * v;
public:
UndeleteAction(LocalBrowserView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->RescanStamps();
}
};
undeleteButton->SetActionCallback(new UndeleteAction(this));
class RemoveSelectedAction : public ui::ButtonAction
{
LocalBrowserView * v;
public:
RemoveSelectedAction(LocalBrowserView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->RemoveSelected();
}
};
undeleteButton->SetActionCallback({ [this] { c->RescanStamps(); } });
removeSelected = new ui::Button(ui::Point(((WINDOWW-100)/2), WINDOWH-18), ui::Point(100, 16), "Delete");
removeSelected->Visible = false;
removeSelected->SetActionCallback(new RemoveSelectedAction(this));
removeSelected->SetActionCallback({ [this] { c->RemoveSelected(); } });
AddComponent(removeSelected);
}
@ -178,22 +136,6 @@ void LocalBrowserView::NotifySavesListChanged(LocalBrowserModel * sender)
buttonAreaHeight = Size.Y - buttonYOffset - 18;
buttonWidth = (buttonAreaWidth/savesX) - buttonPadding*2;
buttonHeight = (buttonAreaHeight/savesY) - buttonPadding*2;
class SaveOpenAction: public ui::SaveButtonAction
{
LocalBrowserView * v;
public:
SaveOpenAction(LocalBrowserView * _v) { v = _v; }
void ActionCallback(ui::SaveButton * sender) override
{
if(sender->GetSaveFile())
v->c->OpenSave(sender->GetSaveFile());
}
void SelectedCallback(ui::SaveButton * sender) override
{
if(sender->GetSaveFile())
v->c->Selected(sender->GetSaveFile()->GetDisplayName().ToUtf8(), sender->GetSelected());
}
};
for (size_t i = 0; i < saves.size(); i++)
{
if(saveX == savesX)
@ -212,7 +154,18 @@ void LocalBrowserView::NotifySavesListChanged(LocalBrowserModel * sender)
ui::Point(buttonWidth, buttonHeight),
saves[i]);
saveButton->SetSelectable(true);
saveButton->SetActionCallback(new SaveOpenAction(this));
saveButton->SetActionCallback({
[this, saveButton] {
if (saveButton->GetSaveFile())
c->OpenSave(saveButton->GetSaveFile());
},
nullptr,
nullptr,
[this, saveButton] {
if (saveButton->GetSaveFile())
c->Selected(saveButton->GetSaveFile()->GetDisplayName().ToUtf8(), saveButton->GetSelected());
}
});
stampButtons.push_back(saveButton);
AddComponent(saveButton);
saveX++;

View File

@ -6,7 +6,7 @@
#include "LoginModel.h"
#include "Controller.h"
LoginController::LoginController(ControllerCallback * callback):
LoginController::LoginController(std::function<void ()> onDone_):
HasExited(false)
{
loginView = new LoginView();
@ -15,8 +15,7 @@ LoginController::LoginController(ControllerCallback * callback):
loginView->AttachController(this);
loginModel->AddObserver(loginView);
this->callback = callback;
onDone = onDone_;
}
void LoginController::Login(ByteString username, ByteString password)
@ -33,8 +32,8 @@ void LoginController::Exit()
{
loginView->CloseActiveWindow();
Client::Ref().SetAuthUser(loginModel->GetUser());
if(callback)
callback->ControllerExit();
if (onDone)
onDone();
HasExited = true;
}

View File

@ -4,17 +4,18 @@
#include "common/String.h"
#include "client/User.h"
#include <functional>
class LoginView;
class LoginModel;
class ControllerCallback;
class LoginController
{
LoginView * loginView;
LoginModel * loginModel;
ControllerCallback * callback;
std::function<void ()> onDone;
public:
bool HasExited;
LoginController(ControllerCallback * callback = NULL);
LoginController(std::function<void ()> onDone = nullptr);
void Login(ByteString username, ByteString password);
void Exit();
LoginView * GetView() { return loginView; }

View File

@ -14,28 +14,6 @@
#include "Misc.h"
class LoginView::LoginAction : public ui::ButtonAction
{
LoginView * v;
public:
LoginAction(LoginView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->Login(v->usernameField->GetText().ToUtf8(), v->passwordField->GetText().ToUtf8());
}
};
class LoginView::CancelAction : public ui::ButtonAction
{
LoginView * v;
public:
CancelAction(LoginView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->Exit();
}
};
LoginView::LoginView():
ui::Window(ui::Point(-1, -1), ui::Point(200, 87)),
loginButton(new ui::Button(ui::Point(200-100, 87-17), ui::Point(100, 17), "Sign in")),
@ -60,11 +38,11 @@ LoginView::LoginView():
loginButton->Appearance.HorizontalAlign = ui::Appearance::AlignRight;
loginButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
loginButton->Appearance.TextInactive = style::Colour::ConfirmButton;
loginButton->SetActionCallback(new LoginAction(this));
loginButton->SetActionCallback({ [this] { c->Login(usernameField->GetText().ToUtf8(), passwordField->GetText().ToUtf8()); } });
AddComponent(cancelButton);
cancelButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
cancelButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
cancelButton->SetActionCallback(new CancelAction(this));
cancelButton->SetActionCallback({ [this] { c->Exit(); } });
AddComponent(titleLabel);
titleLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
titleLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;

View File

@ -23,8 +23,6 @@ class LoginView: public ui::Window
ui::Textbox * passwordField;
ui::Point targetSize;
public:
class LoginAction;
class CancelAction;
LoginView();
void OnKeyPress(int key, int scan, bool repeat, bool shift, bool ctrl, bool alt) override;
void OnTryExit(ExitMethod method) override;

View File

@ -5,9 +5,9 @@
#include "Controller.h"
OptionsController::OptionsController(GameModel * gModel_, ControllerCallback * callback_):
OptionsController::OptionsController(GameModel * gModel_, std::function<void ()> onDone_):
gModel(gModel_),
callback(callback_),
onDone(onDone_),
HasExited(false)
{
view = new OptionsView();
@ -111,8 +111,8 @@ void OptionsController::Exit()
{
view->CloseActiveWindow();
if (callback)
callback->ControllerExit();
if (onDone)
onDone();
HasExited = true;
}
@ -122,6 +122,5 @@ OptionsController::~OptionsController()
view->CloseActiveWindow();
delete model;
delete view;
delete callback;
}

View File

@ -1,7 +1,8 @@
#ifndef OPTIONSCONTROLLER_H_
#define OPTIONSCONTROLLER_H_
class ControllerCallback;
#include <functional>
class GameModel;
class OptionsModel;
class OptionsView;
@ -10,10 +11,10 @@ class OptionsController
GameModel * gModel;
OptionsView * view;
OptionsModel * model;
ControllerCallback * callback;
std::function<void ()> onDone;
public:
bool HasExited;
OptionsController(GameModel * gModel_, ControllerCallback * callback_);
OptionsController(GameModel * gModel_, std::function<void ()> onDone = nullptr);
void SetHeatSimulation(bool state);
void SetAmbientHeatSimulation(bool state);
void SetNewtonianGravity(bool state);

View File

@ -55,19 +55,9 @@ OptionsView::OptionsView():
AddComponent(scrollPanel);
class HeatSimulationAction: public ui::CheckboxAction
{
OptionsView * v;
public:
HeatSimulationAction(OptionsView * v_){ v = v_; }
void ActionCallback(ui::Checkbox * sender) override {
v->c->SetHeatSimulation(sender->GetChecked());
}
};
heatSimulation = new ui::Checkbox(ui::Point(8, currentY), ui::Point(1, 16), "Heat simulation \bgIntroduced in version 34", "");
autowidth(heatSimulation);
heatSimulation->SetActionCallback(new HeatSimulationAction(this));
heatSimulation->SetActionCallback({ [this] { c->SetHeatSimulation(heatSimulation->GetChecked()); } });
scrollPanel->AddChild(heatSimulation);
currentY+=14;
tempLabel = new ui::Label(ui::Point(24, currentY), ui::Point(1, 16), "\bgCan cause odd behaviour when disabled");
@ -76,20 +66,10 @@ OptionsView::OptionsView():
tempLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
scrollPanel->AddChild(tempLabel);
class AmbientHeatSimulationAction: public ui::CheckboxAction
{
OptionsView * v;
public:
AmbientHeatSimulationAction(OptionsView * v_){ v = v_; }
void ActionCallback(ui::Checkbox * sender) override {
v->c->SetAmbientHeatSimulation(sender->GetChecked());
}
};
currentY+=16;
ambientHeatSimulation = new ui::Checkbox(ui::Point(8, currentY), ui::Point(1, 16), "Ambient heat simulation \bgIntroduced in version 50", "");
autowidth(ambientHeatSimulation);
ambientHeatSimulation->SetActionCallback(new AmbientHeatSimulationAction(this));
ambientHeatSimulation->SetActionCallback({ [this] { c->SetAmbientHeatSimulation(ambientHeatSimulation->GetChecked()); } });
scrollPanel->AddChild(ambientHeatSimulation);
currentY+=14;
tempLabel = new ui::Label(ui::Point(24, currentY), ui::Point(1, 16), "\bgCan cause odd / broken behaviour with many saves");
@ -98,20 +78,10 @@ OptionsView::OptionsView():
tempLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
scrollPanel->AddChild(tempLabel);
class NewtonianGravityAction: public ui::CheckboxAction
{
OptionsView * v;
public:
NewtonianGravityAction(OptionsView * v_){ v = v_; }
void ActionCallback(ui::Checkbox * sender) override {
v->c->SetNewtonianGravity(sender->GetChecked());
}
};
currentY+=16;
newtonianGravity = new ui::Checkbox(ui::Point(8, currentY), ui::Point(1, 16), "Newtonian gravity \bgIntroduced in version 48", "");
autowidth(newtonianGravity);
newtonianGravity->SetActionCallback(new NewtonianGravityAction(this));
newtonianGravity->SetActionCallback({ [this] { c->SetNewtonianGravity(newtonianGravity->GetChecked()); } });
scrollPanel->AddChild(newtonianGravity);
currentY+=14;
tempLabel = new ui::Label(ui::Point(24, currentY), ui::Point(1, 16), "\bgMay cause poor performance on older computers");
@ -120,20 +90,10 @@ OptionsView::OptionsView():
tempLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
scrollPanel->AddChild(tempLabel);
class WaterEqualisationAction: public ui::CheckboxAction
{
OptionsView * v;
public:
WaterEqualisationAction(OptionsView * v_){ v = v_; }
void ActionCallback(ui::Checkbox * sender) override {
v->c->SetWaterEqualisation(sender->GetChecked());
}
};
currentY+=16;
waterEqualisation = new ui::Checkbox(ui::Point(8, currentY), ui::Point(1, 16), "Water equalisation \bgIntroduced in version 61", "");
autowidth(waterEqualisation);
waterEqualisation->SetActionCallback(new WaterEqualisationAction(this));
waterEqualisation->SetActionCallback({ [this] { c->SetWaterEqualisation(waterEqualisation->GetChecked()); } });
scrollPanel->AddChild(waterEqualisation);
currentY+=14;
tempLabel = new ui::Label(ui::Point(24, currentY), ui::Point(1, 16), "\bgMay cause poor performance with a lot of water");
@ -142,15 +102,6 @@ OptionsView::OptionsView():
tempLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
scrollPanel->AddChild(tempLabel);
class AirModeChanged: public ui::DropDownAction
{
OptionsView * v;
public:
AirModeChanged(OptionsView * v): v(v) { }
void OptionChanged(ui::DropDown * sender, std::pair<String, int> option) override {
v->c->SetAirMode(option.second);
}
};
currentY+=19;
airMode = new ui::DropDown(ui::Point(Size.X-95, currentY), ui::Point(80, 16));
scrollPanel->AddChild(airMode);
@ -159,52 +110,33 @@ OptionsView::OptionsView():
airMode->AddOption(std::pair<String, int>("Velocity off", 2));
airMode->AddOption(std::pair<String, int>("Off", 3));
airMode->AddOption(std::pair<String, int>("No Update", 4));
airMode->SetActionCallback(new AirModeChanged(this));
airMode->SetActionCallback({ [this] { c->SetAirMode(airMode->GetOption().second); } });
tempLabel = new ui::Label(ui::Point(8, currentY), ui::Point(Size.X-96, 16), "Air Simulation Mode");
tempLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
tempLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
scrollPanel->AddChild(tempLabel);
class GravityModeChanged: public ui::DropDownAction
{
OptionsView * v;
public:
GravityModeChanged(OptionsView * v): v(v) { }
void OptionChanged(ui::DropDown * sender, std::pair<String, int> option) override {
v->c->SetGravityMode(option.second);
}
};
currentY+=20;
gravityMode = new ui::DropDown(ui::Point(Size.X-95, currentY), ui::Point(80, 16));
scrollPanel->AddChild(gravityMode);
gravityMode->AddOption(std::pair<String, int>("Vertical", 0));
gravityMode->AddOption(std::pair<String, int>("Off", 1));
gravityMode->AddOption(std::pair<String, int>("Radial", 2));
gravityMode->SetActionCallback(new GravityModeChanged(this));
gravityMode->SetActionCallback({ [this] { c->SetGravityMode(gravityMode->GetOption().second); } });
tempLabel = new ui::Label(ui::Point(8, currentY), ui::Point(Size.X-96, 16), "Gravity Simulation Mode");
tempLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
tempLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
scrollPanel->AddChild(tempLabel);
class EdgeModeChanged: public ui::DropDownAction
{
OptionsView * v;
public:
EdgeModeChanged(OptionsView * v): v(v) { }
void OptionChanged(ui::DropDown * sender, std::pair<String, int> option) override {
v->c->SetEdgeMode(option.second);
}
};
currentY+=20;
edgeMode = new ui::DropDown(ui::Point(Size.X-95, currentY), ui::Point(80, 16));
scrollPanel->AddChild(edgeMode);
edgeMode->AddOption(std::pair<String, int>("Void", 0));
edgeMode->AddOption(std::pair<String, int>("Solid", 1));
edgeMode->AddOption(std::pair<String, int>("Loop", 2));
edgeMode->SetActionCallback(new EdgeModeChanged(this));
edgeMode->SetActionCallback({ [this] { c->SetEdgeMode(edgeMode->GetOption().second); } });
tempLabel = new ui::Label(ui::Point(8, currentY), ui::Point(Size.X-96, 16), "Edge Mode");
tempLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
@ -215,15 +147,6 @@ OptionsView::OptionsView():
tmpSeparator = new Separator(ui::Point(0, currentY), ui::Point(Size.X, 1));
scrollPanel->AddChild(tmpSeparator);
class ScaleAction: public ui::DropDownAction
{
OptionsView * v;
public:
ScaleAction(OptionsView * v): v(v) { }
void OptionChanged(ui::DropDown * sender, std::pair<String, int> option) override {
v->c->SetScale(option.second);
}
};
currentY+=4;
scale = new ui::DropDown(ui::Point(8, currentY), ui::Point(40, 16));
{
@ -241,7 +164,7 @@ OptionsView::OptionsView():
if (!current_scale_valid)
scale->AddOption(std::pair<String, int>("current", current_scale));
}
scale->SetActionCallback(new ScaleAction(this));
scale->SetActionCallback({ [this] { c->SetScale(scale->GetOption().second); } });
scrollPanel->AddChild(scale);
tempLabel = new ui::Label(ui::Point(scale->Position.X+scale->Size.X+3, currentY), ui::Point(Size.X-40, 16), "\bg- Window scale factor for larger screens");
@ -249,21 +172,10 @@ OptionsView::OptionsView():
tempLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
scrollPanel->AddChild(tempLabel);
class ResizableAction: public ui::CheckboxAction
{
OptionsView * v;
public:
ResizableAction(OptionsView * v_){ v = v_; }
void ActionCallback(ui::Checkbox * sender) override
{
v->c->SetResizable(sender->GetChecked());
}
};
currentY+=20;
resizable = new ui::Checkbox(ui::Point(8, currentY), ui::Point(1, 16), "Resizable", "");
autowidth(resizable);
resizable->SetActionCallback(new ResizableAction(this));
resizable->SetActionCallback({ [this] { c->SetResizable(resizable->GetChecked()); } });
tempLabel = new ui::Label(ui::Point(resizable->Position.X+Graphics::textwidth(resizable->GetText())+20, currentY), ui::Point(1, 16), "\bg- Allow resizing and maximizing window");
autowidth(tempLabel);
tempLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
@ -271,21 +183,10 @@ OptionsView::OptionsView():
scrollPanel->AddChild(tempLabel);
scrollPanel->AddChild(resizable);
class FullscreenAction: public ui::CheckboxAction
{
OptionsView * v;
public:
FullscreenAction(OptionsView * v_){ v = v_; }
void ActionCallback(ui::Checkbox * sender) override
{
v->c->SetFullscreen(sender->GetChecked());
}
};
currentY+=20;
fullscreen = new ui::Checkbox(ui::Point(8, currentY), ui::Point(1, 16), "Fullscreen", "");
autowidth(fullscreen);
fullscreen->SetActionCallback(new FullscreenAction(this));
fullscreen->SetActionCallback({ [this] { c->SetFullscreen(fullscreen->GetChecked()); } });
tempLabel = new ui::Label(ui::Point(fullscreen->Position.X+Graphics::textwidth(fullscreen->GetText())+20, currentY), ui::Point(1, 16), "\bg- Fill the entire screen");
autowidth(tempLabel);
tempLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
@ -293,20 +194,10 @@ OptionsView::OptionsView():
scrollPanel->AddChild(tempLabel);
scrollPanel->AddChild(fullscreen);
class AltFullscreenAction: public ui::CheckboxAction
{
OptionsView * v;
public:
AltFullscreenAction(OptionsView * v_){ v = v_; }
void ActionCallback(ui::Checkbox * sender) override
{
v->c->SetAltFullscreen(sender->GetChecked());
}
};
currentY+=20;
altFullscreen = new ui::Checkbox(ui::Point(23, currentY), ui::Point(1, 16), "Change Resolution", "");
autowidth(altFullscreen);
altFullscreen->SetActionCallback(new AltFullscreenAction(this));
altFullscreen->SetActionCallback({ [this] { c->SetAltFullscreen(altFullscreen->GetChecked()); } });
tempLabel = new ui::Label(ui::Point(altFullscreen->Position.X+Graphics::textwidth(altFullscreen->GetText())+20, currentY), ui::Point(1, 16), "\bg- Set optimial screen resolution");
autowidth(tempLabel);
tempLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
@ -314,21 +205,10 @@ OptionsView::OptionsView():
scrollPanel->AddChild(tempLabel);
scrollPanel->AddChild(altFullscreen);
class ForceIntegerScalingAction: public ui::CheckboxAction
{
OptionsView * v;
public:
ForceIntegerScalingAction(OptionsView * v_) { v = v_; }
void ActionCallback(ui::Checkbox * sender) override
{
v->c->SetForceIntegerScaling(sender->GetChecked());
}
};
currentY+=20;
forceIntegerScaling = new ui::Checkbox(ui::Point(23, currentY), ui::Point(1, 16), "Force Integer Scaling", "");
autowidth(forceIntegerScaling);
forceIntegerScaling->SetActionCallback(new ForceIntegerScalingAction(this));
forceIntegerScaling->SetActionCallback({ [this] { c->SetForceIntegerScaling(forceIntegerScaling->GetChecked()); } });
tempLabel = new ui::Label(ui::Point(altFullscreen->Position.X+Graphics::textwidth(forceIntegerScaling->GetText())+20, currentY), ui::Point(1, 16), "\bg- Less blurry");
autowidth(tempLabel);
tempLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
@ -336,20 +216,10 @@ OptionsView::OptionsView():
scrollPanel->AddChild(tempLabel);
scrollPanel->AddChild(forceIntegerScaling);
class FastQuitAction: public ui::CheckboxAction
{
OptionsView * v;
public:
FastQuitAction(OptionsView * v_){ v = v_; }
void ActionCallback(ui::Checkbox * sender) override {
v->c->SetFastQuit(sender->GetChecked());
}
};
currentY+=20;
fastquit = new ui::Checkbox(ui::Point(8, currentY), ui::Point(1, 16), "Fast Quit", "");
autowidth(fastquit);
fastquit->SetActionCallback(new FastQuitAction(this));
fastquit->SetActionCallback({ [this] { c->SetFastQuit(fastquit->GetChecked()); } });
tempLabel = new ui::Label(ui::Point(fastquit->Position.X+Graphics::textwidth(fastquit->GetText())+20, currentY), ui::Point(1, 16), "\bg- Always exit completely when hitting close");
autowidth(tempLabel);
tempLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
@ -357,19 +227,10 @@ OptionsView::OptionsView():
scrollPanel->AddChild(tempLabel);
scrollPanel->AddChild(fastquit);
class ShowAvatarsAction: public ui::CheckboxAction
{
OptionsView * v;
public:
ShowAvatarsAction(OptionsView * v_){ v = v_; }
void ActionCallback(ui::Checkbox * sender) override {
v->c->SetShowAvatars(sender->GetChecked());
}
};
currentY+=20;
showAvatars = new ui::Checkbox(ui::Point(8, currentY), ui::Point(1, 16), "Show Avatars", "");
autowidth(showAvatars);
showAvatars->SetActionCallback(new ShowAvatarsAction(this));
showAvatars->SetActionCallback({ [this] { c->SetShowAvatars(showAvatars->GetChecked()); } });
tempLabel = new ui::Label(ui::Point(showAvatars->Position.X+Graphics::textwidth(showAvatars->GetText())+20, currentY), ui::Point(1, 16), "\bg- Disable if you have a slow connection");
autowidth(tempLabel);
tempLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
@ -377,19 +238,10 @@ OptionsView::OptionsView():
scrollPanel->AddChild(tempLabel);
scrollPanel->AddChild(showAvatars);
class MouseClickRequiredAction: public ui::CheckboxAction
{
OptionsView * v;
public:
MouseClickRequiredAction(OptionsView * v_){ v = v_; }
void ActionCallback(ui::Checkbox * sender) override {
v->c->SetMouseClickrequired(sender->GetChecked());
}
};
currentY+=20;
mouseClickRequired = new ui::Checkbox(ui::Point(8, currentY), ui::Point(1, 16), "Sticky Categories", "");
autowidth(mouseClickRequired);
mouseClickRequired->SetActionCallback(new MouseClickRequiredAction(this));
mouseClickRequired->SetActionCallback({ [this] { c->SetMouseClickrequired(mouseClickRequired->GetChecked()); } });
tempLabel = new ui::Label(ui::Point(mouseClickRequired->Position.X+Graphics::textwidth(mouseClickRequired->GetText())+20, currentY), ui::Point(1, 16), "\bg- Switch between categories by clicking");
autowidth(tempLabel);
tempLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
@ -397,19 +249,10 @@ OptionsView::OptionsView():
scrollPanel->AddChild(tempLabel);
scrollPanel->AddChild(mouseClickRequired);
class IncludePressureAction: public ui::CheckboxAction
{
OptionsView * v;
public:
IncludePressureAction(OptionsView * v_){ v = v_; }
void ActionCallback(ui::Checkbox * sender) override {
v->c->SetIncludePressure(sender->GetChecked());
}
};
currentY+=20;
includePressure = new ui::Checkbox(ui::Point(8, currentY), ui::Point(1, 16), "Include Pressure", "");
autowidth(includePressure);
includePressure->SetActionCallback(new IncludePressureAction(this));
includePressure->SetActionCallback({ [this] { c->SetIncludePressure(includePressure->GetChecked()); } });
tempLabel = new ui::Label(ui::Point(includePressure->Position.X+Graphics::textwidth(includePressure->GetText())+20, currentY), ui::Point(1, 16), "\bg- When saving, copying, stamping, etc.");
autowidth(tempLabel);
tempLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
@ -417,18 +260,9 @@ OptionsView::OptionsView():
scrollPanel->AddChild(tempLabel);
scrollPanel->AddChild(includePressure);
class DecoSpaceAction: public ui::DropDownAction
{
OptionsView * v;
public:
DecoSpaceAction(OptionsView * v): v(v) { }
void OptionChanged(ui::DropDown * sender, std::pair<String, int> option) override {
v->c->SetDecoSpace(option.second);
}
};
currentY+=20;
decoSpace = new ui::DropDown(ui::Point(8, currentY), ui::Point(60, 16));
decoSpace->SetActionCallback(new DecoSpaceAction(this));
decoSpace->SetActionCallback({ [this] { c->SetDecoSpace(decoSpace->GetOption().second); } });
scrollPanel->AddChild(decoSpace);
decoSpace->AddOption(std::pair<String, int>("sRGB", 0));
decoSpace->AddOption(std::pair<String, int>("Linear", 1));
@ -440,30 +274,23 @@ OptionsView::OptionsView():
tempLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
scrollPanel->AddChild(tempLabel);
class DataFolderAction: public ui::ButtonAction
{
public:
DataFolderAction() { }
void ActionCallback(ui::Button * sender) override
{
//one of these should always be defined
#ifdef WIN
const char* openCommand = "explorer ";
#elif MACOSX
const char* openCommand = "open ";
//#elif LIN
#else
const char* openCommand = "xdg-open ";
#endif
char* workingDirectory = new char[FILENAME_MAX+strlen(openCommand)];
sprintf(workingDirectory, "%s\"%s\"", openCommand, getcwd(NULL, 0));
system(workingDirectory);
delete[] workingDirectory;
}
};
currentY+=20;
ui::Button * dataFolderButton = new ui::Button(ui::Point(8, currentY), ui::Point(90, 16), "Open Data Folder");
dataFolderButton->SetActionCallback(new DataFolderAction());
dataFolderButton->SetActionCallback({ [] {
//one of these should always be defined
#ifdef WIN
const char* openCommand = "explorer ";
#elif MACOSX
const char* openCommand = "open ";
//#elif LIN
#else
const char* openCommand = "xdg-open ";
#endif
char* workingDirectory = new char[FILENAME_MAX+strlen(openCommand)];
sprintf(workingDirectory, "%s\"%s\"", openCommand, getcwd(NULL, 0));
system(workingDirectory);
delete[] workingDirectory;
} });
scrollPanel->AddChild(dataFolderButton);
tempLabel = new ui::Label(ui::Point(dataFolderButton->Position.X+dataFolderButton->Size.X+3, currentY), ui::Point(1, 16), "\bg- Open the data and preferences folder");
@ -472,19 +299,8 @@ OptionsView::OptionsView():
tempLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
scrollPanel->AddChild(tempLabel);
class CloseAction: public ui::ButtonAction
{
public:
OptionsView * v;
CloseAction(OptionsView * v_) { v = v_; }
void ActionCallback(ui::Button * sender) override
{
v->c->Exit();
}
};
ui::Button * tempButton = new ui::Button(ui::Point(0, Size.Y-16), ui::Point(Size.X, 16), "OK");
tempButton->SetActionCallback(new CloseAction(this));
tempButton->SetActionCallback({ [this] { c->Exit(); } });
AddComponent(tempButton);
SetCancelButton(tempButton);
SetOkayButton(tempButton);

View File

@ -17,9 +17,8 @@
#include "Platform.h"
#include "Config.h"
PreviewController::PreviewController(int saveID, int saveDate, bool instant, ControllerCallback * callback):
PreviewController::PreviewController(int saveID, int saveDate, bool instant, std::function<void ()> onDone_):
saveId(saveID),
saveDate(saveDate),
loginWindow(NULL),
HasExited(false)
{
@ -38,32 +37,7 @@ PreviewController::PreviewController(int saveID, int saveDate, bool instant, Con
Client::Ref().AddListener(this);
this->callback = callback;
(void)saveDate; //pretend this is used
}
PreviewController::PreviewController(int saveID, bool instant, ControllerCallback * callback):
saveId(saveID),
saveDate(0),
loginWindow(NULL),
HasExited(false)
{
previewModel = new PreviewModel();
previewView = new PreviewView();
previewModel->AddObserver(previewView);
previewView->AttachController(this);
previewModel->UpdateSave(saveID, 0);
if(Client::Ref().GetAuthUser().UserID)
{
previewModel->SetCommentBoxEnabled(true);
}
Client::Ref().AddListener(this);
this->callback = callback;
(void)saveDate; //pretend this is used
onDone = onDone_;
}
void PreviewController::Update()
@ -189,8 +163,8 @@ void PreviewController::Exit()
{
previewView->CloseActiveWindow();
HasExited = true;
if(callback)
callback->ControllerExit();
if (onDone)
onDone();
}
PreviewController::~PreviewController()
@ -199,5 +173,4 @@ PreviewController::~PreviewController()
Client::Ref().RemoveListener(this);
delete previewModel;
delete previewView;
delete callback;
}

View File

@ -3,25 +3,24 @@
#include "client/ClientListener.h"
#include <functional>
class SaveInfo;
class ControllerCallback;
class LoginController;
class PreviewModel;
class PreviewView;
class PreviewController: public ClientListener {
int saveId;
int saveDate;
PreviewModel * previewModel;
PreviewView * previewView;
LoginController * loginWindow;
ControllerCallback * callback;
std::function<void ()> onDone;
public:
void NotifyAuthUserChanged(Client * sender) override;
inline int SaveID() { return saveId; }
bool HasExited;
PreviewController(int saveID, bool instant, ControllerCallback * callback);
PreviewController(int saveID, int saveDate, bool instant, ControllerCallback * callback);
PreviewController(int saveID, int saveDate, bool instant, std::function<void ()> onDone = nullptr);
void Exit();
void DoOpen();
void OpenInBrowser();

View File

@ -30,53 +30,6 @@
# undef GetUserName // dammit windows
#endif
class PreviewView::LoginAction: public ui::ButtonAction
{
PreviewView * v;
public:
LoginAction(PreviewView * v_){ v = v_; }
void ActionCallback(ui::Button * sender) override
{
v->c->ShowLogin();
}
};
class PreviewView::SubmitCommentAction: public ui::ButtonAction
{
PreviewView * v;
public:
SubmitCommentAction(PreviewView * v_){ v = v_; }
void ActionCallback(ui::Button * sender) override
{
v->submitComment();
}
};
class PreviewView::AutoCommentSizeAction: public ui::TextboxAction
{
PreviewView * v;
public:
AutoCommentSizeAction(PreviewView * v): v(v) {}
void TextChangedCallback(ui::Textbox * sender) override {
v->CheckComment();
v->commentBoxAutoHeight();
}
};
class PreviewView::AvatarAction: public ui::AvatarButtonAction
{
PreviewView * v;
public:
AvatarAction(PreviewView * v_){ v = v_; }
void ActionCallback(ui::AvatarButton * sender) override
{
if(sender->GetUsername().size() > 0)
{
new ProfileActivity(sender->GetUsername());
}
}
};
PreviewView::PreviewView():
ui::Window(ui::Point(-1, -1), ui::Point((XRES/2)+210, (YRES/2)+150)),
savePreview(NULL),
@ -92,85 +45,40 @@ PreviewView::PreviewView():
commentBoxHeight(20),
commentHelpText(false)
{
class FavAction: public ui::ButtonAction
{
PreviewView * v;
public:
FavAction(PreviewView * v_){ v = v_; }
void ActionCallback(ui::Button * sender) override
{
v->c->FavouriteSave();
}
};
showAvatars = Client::Ref().GetPrefBool("ShowAvatars", true);
favButton = new ui::Button(ui::Point(50, Size.Y-19), ui::Point(51, 19), "Fav");
favButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; favButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
favButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
favButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
favButton->SetIcon(IconFavourite);
favButton->SetActionCallback(new FavAction(this));
favButton->SetActionCallback({ [this] { c->FavouriteSave(); } });
favButton->Enabled = Client::Ref().GetAuthUser().UserID?true:false;
AddComponent(favButton);
class ReportPromptCallback: public TextDialogueCallback {
public:
PreviewView * v;
ReportPromptCallback(PreviewView * v_) { v = v_; }
void TextCallback(TextPrompt::DialogueResult result, String resultText) override {
if (result == TextPrompt::ResultOkay)
v->c->Report(resultText);
}
virtual ~ReportPromptCallback() { }
};
class ReportAction: public ui::ButtonAction
{
PreviewView * v;
public:
ReportAction(PreviewView * v_){ v = v_; }
void ActionCallback(ui::Button * sender) override
{
new TextPrompt("Report Save", "Things to consider when reporting:\n\bw1)\bg When reporting stolen saves, please include the ID of the original save.\n\bw2)\bg Do not ask for saves to be removed from front page unless they break the rules.\n\bw3)\bg You may report saves for comments or tags too (including your own saves)", "", "[reason]", true, new ReportPromptCallback(v));
}
};
reportButton = new ui::Button(ui::Point(100, Size.Y-19), ui::Point(51, 19), "Report");
reportButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; reportButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
reportButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
reportButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
reportButton->SetIcon(IconReport);
reportButton->SetActionCallback(new ReportAction(this));
reportButton->SetActionCallback({ [this] {
new TextPrompt("Report Save", "Things to consider when reporting:\n\bw1)\bg When reporting stolen saves, please include the ID of the original save.\n\bw2)\bg Do not ask for saves to be removed from front page unless they break the rules.\n\bw3)\bg You may report saves for comments or tags too (including your own saves)", "", "[reason]", true, { [this](String const &resultText) {
c->Report(resultText);
} });
} });
reportButton->Enabled = Client::Ref().GetAuthUser().UserID?true:false;
AddComponent(reportButton);
class OpenAction: public ui::ButtonAction
{
PreviewView * v;
public:
OpenAction(PreviewView * v_){ v = v_; }
void ActionCallback(ui::Button * sender) override
{
v->c->DoOpen();
}
};
openButton = new ui::Button(ui::Point(0, Size.Y-19), ui::Point(51, 19), "Open");
openButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; openButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
openButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
openButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
openButton->SetIcon(IconOpen);
openButton->SetActionCallback(new OpenAction(this));
openButton->SetActionCallback({ [this] { c->DoOpen(); } });
AddComponent(openButton);
class BrowserOpenAction: public ui::ButtonAction
{
PreviewView * v;
public:
BrowserOpenAction(PreviewView * v_){ v = v_; }
void ActionCallback(ui::Button * sender) override
{
v->c->OpenInBrowser();
}
};
browserOpenButton = new ui::Button(ui::Point((XRES/2)-107, Size.Y-19), ui::Point(108, 19), "Open in browser");
browserOpenButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; browserOpenButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
browserOpenButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
browserOpenButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
browserOpenButton->SetIcon(IconOpen);
browserOpenButton->SetActionCallback(new BrowserOpenAction(this));
browserOpenButton->SetActionCallback({ [this] { c->OpenInBrowser(); } });
AddComponent(browserOpenButton);
if(showAvatars)
@ -202,7 +110,12 @@ PreviewView::PreviewView():
if(showAvatars)
{
avatarButton = new ui::AvatarButton(ui::Point(4, (YRES/2)+4), ui::Point(34, 34), "");
avatarButton->SetActionCallback(new AvatarAction(this));
avatarButton->SetActionCallback({ [this] {
if (avatarButton->GetUsername().size() > 0)
{
new ProfileActivity(avatarButton->GetUsername());
}
} });
AddComponent(avatarButton);
}
@ -620,12 +533,15 @@ void PreviewView::NotifyCommentBoxEnabledChanged(PreviewModel * sender)
commentBoxSizeY = 17;
addCommentBox = new ui::Textbox(ui::Point((XRES/2)+4, Size.Y-19), ui::Point(Size.X-(XRES/2)-48, 17), "", "Add Comment");
addCommentBox->SetActionCallback(new AutoCommentSizeAction(this));
addCommentBox->SetActionCallback({ [this] {
CheckComment();
commentBoxAutoHeight();
} });
addCommentBox->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
addCommentBox->SetMultiline(true);
AddComponent(addCommentBox);
submitCommentButton = new ui::Button(ui::Point(Size.X-40, Size.Y-19), ui::Point(40, 19), "Submit");
submitCommentButton->SetActionCallback(new SubmitCommentAction(this));
submitCommentButton->SetActionCallback({ [this] { submitComment(); } });
//submitCommentButton->Enabled = false;
AddComponent(submitCommentButton);
@ -638,7 +554,7 @@ void PreviewView::NotifyCommentBoxEnabledChanged(PreviewModel * sender)
else
{
submitCommentButton = new ui::Button(ui::Point(XRES/2, Size.Y-19), ui::Point(Size.X-(XRES/2), 19), "Login to comment");
submitCommentButton->SetActionCallback(new LoginAction(this));
submitCommentButton->SetActionCallback({ [this] { c->ShowLogin(); } });
AddComponent(submitCommentButton);
}
}
@ -686,7 +602,12 @@ void PreviewView::NotifyCommentsChanged(PreviewModel * sender)
if (showAvatars)
{
tempAvatar = new ui::AvatarButton(ui::Point(2, currentY+7), ui::Point(26, 26), comments->at(i)->authorName);
tempAvatar->SetActionCallback(new AvatarAction(this));
tempAvatar->SetActionCallback({ [this, tempAvatar] {
if (tempAvatar->GetUsername().size() > 0)
{
new ProfileActivity(tempAvatar->GetUsername());
}
} });
commentComponents.push_back(tempAvatar);
commentsPanel->AddChild(tempAvatar);
}

View File

@ -21,10 +21,6 @@ class PreviewModel;
class PreviewController;
class PreviewView: public ui::Window
{
class SubmitCommentAction;
class LoginAction;
class AutoCommentSizeAction;
class AvatarAction;
PreviewController * c;
VideoBuffer * savePreview;
ui::Button * openButton;

View File

@ -21,47 +21,27 @@ ProfileActivity::ProfileActivity(ByteString username) :
{
editable = Client::Ref().GetAuthUser().UserID && Client::Ref().GetAuthUser().Username == username;
class CloseAction: public ui::ButtonAction
{
ProfileActivity * a;
public:
CloseAction(ProfileActivity * a) : a(a) { }
void ActionCallback(ui::Button * sender_) override
{
a->Exit();
}
};
class SaveAction: public ui::ButtonAction
{
ProfileActivity * a;
public:
SaveAction(ProfileActivity * a) : a(a) { }
void ActionCallback(ui::Button * sender_) override
{
if (!a->loading && !a->saving && a->editable)
{
sender_->Enabled = false;
sender_->SetText("Saving...");
a->saving = true;
a->info.location = ((ui::Textbox*)a->location)->GetText();
a->info.biography = ((ui::Textbox*)a->bio)->GetText();
a->SaveUserInfoRequestMonitor::RequestSetup(a->info);
a->SaveUserInfoRequestMonitor::RequestStart();
}
}
};
ui::Button * closeButton = new ui::Button(ui::Point(0, Size.Y-15), ui::Point(Size.X, 15), "Close");
closeButton->SetActionCallback(new CloseAction(this));
closeButton->SetActionCallback({ [this] {
Exit();
} });
if(editable)
{
closeButton->Size.X = (Size.X/2)+1;
ui::Button * saveButton = new ui::Button(ui::Point(Size.X/2, Size.Y-15), ui::Point(Size.X/2, 15), "Save");
saveButton->SetActionCallback(new SaveAction(this));
saveButton->SetActionCallback({ [this, saveButton] {
if (!loading && !saving && editable)
{
saveButton->Enabled = false;
saveButton->SetText("Saving...");
saving = true;
info.location = location->GetText();
info.biography = bio->GetText();
SaveUserInfoRequestMonitor::RequestSetup(info);
SaveUserInfoRequestMonitor::RequestStart();
}
} });
AddComponent(saveButton);
}
@ -75,15 +55,6 @@ ProfileActivity::ProfileActivity(ByteString username) :
void ProfileActivity::setUserInfo(UserInfo newInfo)
{
class EditAvatarAction: public ui::ButtonAction
{
public:
void ActionCallback(ui::Button * sender_) override
{
Platform::OpenURI(SCHEME SERVER "/Profile/Avatar.html");
}
};
info = newInfo;
if (!info.biography.length() && !editable)
@ -111,7 +82,9 @@ void ProfileActivity::setUserInfo(UserInfo newInfo)
if (editable)
{
ui::Button * editAvatar = new ui::Button(ui::Point(Size.X - (40 + 16 + 75), currentY), ui::Point(75, 15), "Edit Avatar");
editAvatar->SetActionCallback(new EditAvatarAction());
editAvatar->SetActionCallback({ [] {
Platform::OpenURI(SCHEME SERVER "/Profile/Avatar.html");
} });
scrollPanel->AddChild(editAvatar);
}
currentY += 23;
@ -200,22 +173,11 @@ void ProfileActivity::setUserInfo(UserInfo newInfo)
scrollPanel->AddChild(bioTitle);
currentY += 17;
class BioChangedAction: public ui::TextboxAction
{
public:
ProfileActivity * profileActivity;
BioChangedAction(ProfileActivity * profileActivity_) { profileActivity = profileActivity_; }
void TextChangedCallback(ui::Textbox * sender) override
{
profileActivity->ResizeArea();
}
};
if (editable)
{
bio = new ui::Textbox(ui::Point(4, currentY), ui::Point(Size.X-12, -1), info.biography);
((ui::Textbox*)bio)->SetInputType(ui::Textbox::Multiline);
((ui::Textbox*)bio)->SetActionCallback(new BioChangedAction(this));
((ui::Textbox*)bio)->SetActionCallback({ [this] { ResizeArea(); } });
((ui::Textbox*)bio)->SetLimit(20000);
}
else

View File

@ -5,7 +5,7 @@
#include "Controller.h"
RenderController::RenderController(Renderer * ren, ControllerCallback * callback):
RenderController::RenderController(Renderer * ren, std::function<void ()> onDone_):
HasExited(false)
{
renderView = new RenderView();
@ -15,7 +15,7 @@ RenderController::RenderController(Renderer * ren, ControllerCallback * callback
renderModel->AddObserver(renderView);
renderModel->SetRenderer(ren);
this->callback = callback;
onDone = onDone_;
}
void RenderController::SetRenderMode(unsigned int renderMode)
@ -51,15 +51,14 @@ void RenderController::LoadRenderPreset(int presetNum)
void RenderController::Exit()
{
renderView->CloseActiveWindow();
if(callback)
callback->ControllerExit();
if (onDone)
onDone();
HasExited = true;
}
RenderController::~RenderController()
{
renderView->CloseActiveWindow();
delete callback;
delete renderModel;
delete renderView;
}

View File

@ -1,7 +1,8 @@
#ifndef RENDERCONTROLLER_H_
#define RENDERCONTROLLER_H_
class ControllerCallback;
#include <functional>
class RenderView;
class RenderModel;
class Renderer;
@ -9,10 +10,10 @@ class RenderController
{
RenderView * renderView;
RenderModel * renderModel;
ControllerCallback * callback;
std::function<void ()> onDone;
public:
bool HasExited;
RenderController(Renderer * ren, ControllerCallback * callback = nullptr);
RenderController(Renderer * ren, std::function<void ()> onDone = nullptr);
void Exit();
RenderView * GetView() { return renderView; }
virtual ~RenderController();

View File

@ -11,77 +11,11 @@
#include "gui/interface/Checkbox.h"
#include "gui/interface/Button.h"
class RenderView::RenderModeAction: public ui::CheckboxAction
class ModeCheckbox : public ui::Checkbox
{
RenderView * v;
public:
unsigned int renderMode;
RenderModeAction(RenderView * v_, unsigned int renderMode_)
{
v = v_;
renderMode = renderMode_;
}
void ActionCallback(ui::Checkbox * sender) override
{
if(sender->GetChecked())
v->c->SetRenderMode(renderMode);
else
v->c->UnsetRenderMode(renderMode);
}
};
class RenderView::DisplayModeAction: public ui::CheckboxAction
{
RenderView * v;
public:
unsigned int displayMode;
DisplayModeAction(RenderView * v_, unsigned int displayMode_)
{
v = v_;
displayMode = displayMode_;
}
void ActionCallback(ui::Checkbox * sender) override
{
if(sender->GetChecked())
v->c->SetDisplayMode(displayMode);
else
v->c->UnsetDisplayMode(displayMode);
}
};
class RenderView::ColourModeAction: public ui::CheckboxAction
{
RenderView * v;
public:
unsigned int colourMode;
ColourModeAction(RenderView * v_, unsigned int colourMode_)
{
v = v_;
colourMode = colourMode_;
}
void ActionCallback(ui::Checkbox * sender) override
{
if(sender->GetChecked())
v->c->SetColourMode(colourMode);
else
v->c->SetColourMode(0);
}
};
class RenderView::RenderPresetAction: public ui::ButtonAction
{
RenderView * v;
public:
int renderPreset;
RenderPresetAction(RenderView * v_, int renderPreset_)
{
v = v_;
renderPreset = renderPreset_;
}
void ActionCallback(ui::Button * sender) override
{
v->c->LoadRenderPreset(renderPreset);
}
using ui::Checkbox::Checkbox;
unsigned int mode;
};
RenderView::RenderView():
@ -91,210 +25,93 @@ RenderView::RenderView():
toolTipPresence(0),
isToolTipFadingIn(false)
{
ui::Button * presetButton;
int presetButtonOffset = 375;
int checkboxOffset = 1;
int cSpace = 32;
int sSpace = 38;
auto addPresetButton = [this](int index, Icon icon, ui::Point offset, String tooltip) {
auto *presetButton = new ui::Button(ui::Point(XRES, YRES) + offset, ui::Point(30, 13), "", tooltip);
presetButton->SetIcon(icon);
presetButton->SetActionCallback({ [this, index] { c->LoadRenderPreset(index); } });
AddComponent(presetButton);
};
addPresetButton( 1, IconVelocity , ui::Point( -37, 6), "Velocity display mode preset");
addPresetButton( 2, IconPressure , ui::Point( -37, 24), "Pressure display mode preset");
addPresetButton( 3, IconPersistant, ui::Point( -76, 6), "Persistent display mode preset");
addPresetButton( 4, IconFire , ui::Point( -76, 24), "Fire display mode preset");
addPresetButton( 5, IconBlob , ui::Point(-115, 6), "Blob display mode preset");
addPresetButton( 6, IconHeat , ui::Point(-115, 24), "Heat display mode preset");
addPresetButton( 7, IconBlur , ui::Point(-154, 6), "Fancy display mode preset");
addPresetButton( 8, IconBasic , ui::Point(-154, 24), "Nothing display mode preset");
addPresetButton( 9, IconGradient , ui::Point(-193, 6), "Heat gradient display mode preset");
addPresetButton( 0, IconAltAir , ui::Point(-193, 24), "Alternative Velocity display mode preset");
addPresetButton(10, IconLife , ui::Point(-232, 6), "Life display mode preset");
presetButton = new ui::Button(ui::Point(presetButtonOffset+200, YRES+6), ui::Point(30, 13), "", "Velocity display mode preset");
presetButton->SetIcon(IconVelocity);
presetButton->SetActionCallback(new RenderPresetAction(this, 1));
AddComponent(presetButton);
presetButton = new ui::Button(ui::Point(presetButtonOffset+200, YRES+6+18), ui::Point(30, 13), "", "Pressure display mode preset");
presetButton->SetIcon(IconPressure);
presetButton->SetActionCallback(new RenderPresetAction(this, 2));
AddComponent(presetButton);
presetButton = new ui::Button(ui::Point(presetButtonOffset+161, YRES+6), ui::Point(30, 13), "", "Persistent display mode preset");
presetButton->SetIcon(IconPersistant);
presetButton->SetActionCallback(new RenderPresetAction(this, 3));
AddComponent(presetButton);
presetButton = new ui::Button(ui::Point(presetButtonOffset+161, YRES+6+18), ui::Point(30, 13), "", "Fire display mode preset");
presetButton->SetIcon(IconFire);
presetButton->SetActionCallback(new RenderPresetAction(this, 4));
AddComponent(presetButton);
presetButton = new ui::Button(ui::Point(presetButtonOffset+122, YRES+6), ui::Point(30, 13), "", "Blob display mode preset");
presetButton->SetIcon(IconBlob);
presetButton->SetActionCallback(new RenderPresetAction(this, 5));
AddComponent(presetButton);
presetButton = new ui::Button(ui::Point(presetButtonOffset+122, YRES+6+18), ui::Point(30, 13), "", "Heat display mode preset");
presetButton->SetIcon(IconHeat);
presetButton->SetActionCallback(new RenderPresetAction(this, 6));
AddComponent(presetButton);
presetButton = new ui::Button(ui::Point(presetButtonOffset+83, YRES+6), ui::Point(30, 13), "", "Fancy display mode preset");
presetButton->SetIcon(IconBlur);
presetButton->SetActionCallback(new RenderPresetAction(this, 7));
AddComponent(presetButton);
presetButton = new ui::Button(ui::Point(presetButtonOffset+83, YRES+6+18), ui::Point(30, 13), "", "Nothing display mode preset");
presetButton->SetIcon(IconBasic);
presetButton->SetActionCallback(new RenderPresetAction(this, 8));
AddComponent(presetButton);
presetButton = new ui::Button(ui::Point(presetButtonOffset+44, YRES+6), ui::Point(30, 13), "", "Heat gradient display mode preset");
presetButton->SetIcon(IconGradient);
presetButton->SetActionCallback(new RenderPresetAction(this, 9));
AddComponent(presetButton);
presetButton = new ui::Button(ui::Point(presetButtonOffset+44, YRES+6+18), ui::Point(30, 13), "", "Alternative Velocity display mode preset");
presetButton->SetIcon(IconAltAir);
presetButton->SetActionCallback(new RenderPresetAction(this, 0));
AddComponent(presetButton);
presetButton = new ui::Button(ui::Point(presetButtonOffset+5, YRES+6), ui::Point(30, 13), "", "Life display mode preset");
presetButton->SetIcon(IconLife);
presetButton->SetActionCallback(new RenderPresetAction(this, 10));
AddComponent(presetButton);
ui::Checkbox * tCheckbox;
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4), ui::Point(30, 16), "Effects", "Adds Special flare effects to some elements");
renderModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconEffect);
tCheckbox->SetActionCallback(new RenderModeAction(this, RENDER_EFFE));
AddComponent(tCheckbox);
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4+18), ui::Point(30, 16), "Fire", "Fire effect for gasses");
renderModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconFire);
tCheckbox->SetActionCallback(new RenderModeAction(this, RENDER_FIRE));
AddComponent(tCheckbox);
checkboxOffset += cSpace;
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4), ui::Point(30, 16), "Glow", "Glow effect on some elements");
renderModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconGlow);
tCheckbox->SetActionCallback(new RenderModeAction(this, RENDER_GLOW));
AddComponent(tCheckbox);
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4+18), ui::Point(30, 16), "Blur", "Blur effect for liquids");
renderModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconBlur);
tCheckbox->SetActionCallback(new RenderModeAction(this, RENDER_BLUR));
AddComponent(tCheckbox);
checkboxOffset += cSpace;
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4), ui::Point(30, 16), "Blob", "Makes everything be drawn like a blob");
renderModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconBlob);
tCheckbox->SetActionCallback(new RenderModeAction(this, RENDER_BLOB));
AddComponent(tCheckbox);
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4+18), ui::Point(30, 16), "Point", "Basic rendering, without this, most things will be invisible");
renderModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconBasic);
tCheckbox->SetActionCallback(new RenderModeAction(this, RENDER_BASC));
AddComponent(tCheckbox);
checkboxOffset += cSpace;
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4), ui::Point(30, 16), "Spark", "Glow effect on sparks");
renderModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconEffect);
tCheckbox->SetActionCallback(new RenderModeAction(this, RENDER_SPRK));
AddComponent(tCheckbox);
checkboxOffset += sSpace;
line1 = checkboxOffset-5;
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4), ui::Point(30, 16), "Alt. Air", "Displays pressure as red and blue, and velocity as white");
displayModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconAltAir);
tCheckbox->SetActionCallback(new DisplayModeAction(this, DISPLAY_AIRC));
AddComponent(tCheckbox);
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4+18), ui::Point(30, 16), "Pressure", "Displays pressure, red is positive and blue is negative");
displayModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconPressure);
tCheckbox->SetActionCallback(new DisplayModeAction(this, DISPLAY_AIRP));
AddComponent(tCheckbox);
checkboxOffset += cSpace;
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4), ui::Point(30, 16), "Velocity", "Displays velocity and positive pressure: up/down adds blue, right/left adds red, still pressure adds green");
displayModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconVelocity);
tCheckbox->SetActionCallback(new DisplayModeAction(this, DISPLAY_AIRV));
AddComponent(tCheckbox);
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4+18), ui::Point(30, 16), "Air-heat", "Displays the temperature of the air like heat display does");
displayModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconHeat);
tCheckbox->SetActionCallback(new DisplayModeAction(this, DISPLAY_AIRH));
AddComponent(tCheckbox);
/*tCheckbox = new ui::Checkbox(ui::Point(216, YRES+4), ui::Point(30, 16), "Air", "");
displayModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconAltAir);
tCheckbox->SetActionCallback(new DisplayModeAction(this, DISPLAY_AIR));
AddComponent(tCheckbox);*/
checkboxOffset += sSpace;
line2 = checkboxOffset-5;
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4+18), ui::Point(30, 16), "Warp", "Gravity lensing, Newtonian Gravity bends light with this on");
displayModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconWarp);
tCheckbox->SetActionCallback(new DisplayModeAction(this, DISPLAY_WARP));
AddComponent(tCheckbox);
auto addRenderModeCheckbox = [this](unsigned int mode, Icon icon, ui::Point offset, String tooltip) {
auto *renderModeCheckbox = new ModeCheckbox(ui::Point(0, YRES) + offset, ui::Point(30, 16), "", tooltip);
renderModes.push_back(renderModeCheckbox);
renderModeCheckbox->mode = mode;
renderModeCheckbox->SetIcon(icon);
renderModeCheckbox->SetActionCallback({ [this, mode, renderModeCheckbox] {
if (renderModeCheckbox->GetChecked())
c->SetRenderMode(renderModeCheckbox->mode);
else
c->UnsetRenderMode(renderModeCheckbox->mode);
} });
AddComponent(renderModeCheckbox);
};
addRenderModeCheckbox(RENDER_EFFE, IconEffect, ui::Point( 1, 4), "Adds Special flare effects to some elements");
addRenderModeCheckbox(RENDER_FIRE, IconFire , ui::Point( 1, 22), "Fire effect for gasses");
addRenderModeCheckbox(RENDER_GLOW, IconGlow , ui::Point(33, 4), "Glow effect on some elements");
addRenderModeCheckbox(RENDER_BLUR, IconBlur , ui::Point(33, 22), "Blur effect for liquids");
addRenderModeCheckbox(RENDER_BLOB, IconBlob , ui::Point(65, 4), "Makes everything be drawn like a blob");
addRenderModeCheckbox(RENDER_BASC, IconBasic , ui::Point(65, 22), "Basic rendering, without this, most things will be invisible");
addRenderModeCheckbox(RENDER_SPRK, IconEffect, ui::Point(97, 4), "Glow effect on sparks");
auto addDisplayModeCheckbox = [this](unsigned int mode, Icon icon, ui::Point offset, String tooltip) {
auto *displayModeCheckbox = new ModeCheckbox(ui::Point(0, YRES) + offset, ui::Point(30, 16), "", tooltip);
displayModes.push_back(displayModeCheckbox);
displayModeCheckbox->mode = mode;
displayModeCheckbox->SetIcon(icon);
displayModeCheckbox->SetActionCallback({ [this, mode, displayModeCheckbox] {
if (displayModeCheckbox->GetChecked())
c->SetDisplayMode(displayModeCheckbox->mode);
else
c->UnsetDisplayMode(displayModeCheckbox->mode);
} });
AddComponent(displayModeCheckbox);
};
line1 = 130;
addDisplayModeCheckbox(DISPLAY_AIRC, IconAltAir , ui::Point(135, 4), "Displays pressure as red and blue, and velocity as white");
addDisplayModeCheckbox(DISPLAY_AIRP, IconPressure , ui::Point(135, 22), "Displays pressure, red is positive and blue is negative");
addDisplayModeCheckbox(DISPLAY_AIRV, IconVelocity , ui::Point(167, 4), "Displays velocity and positive pressure: up/down adds blue, right/left adds red, still pressure adds green");
addDisplayModeCheckbox(DISPLAY_AIRH, IconHeat , ui::Point(167, 22), "Displays the temperature of the air like heat display does");
line2 = 200;
addDisplayModeCheckbox(DISPLAY_WARP, IconWarp , ui::Point(205, 22), "Gravity lensing, Newtonian Gravity bends light with this on");
#ifdef OGLR
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4), ui::Point(30, 16), "Effect", "Some type of OpenGL effect ... maybe"); //I would remove the whole checkbox, but then there's a large empty space
# define TOOLTIP "Some type of OpenGL effect ... maybe"
#else
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4), ui::Point(30, 16), "Effect", "Enables moving solids, stickmen guns, and premium(tm) graphics");
# define TOOLTIP "Enables moving solids, stickmen guns, and premium(tm) graphics"
#endif
displayModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconEffect);
tCheckbox->SetActionCallback(new DisplayModeAction(this, DISPLAY_EFFE));
AddComponent(tCheckbox);
addDisplayModeCheckbox(DISPLAY_EFFE, IconEffect , ui::Point(205, 4), TOOLTIP);
#undef TOOLTIP
addDisplayModeCheckbox(DISPLAY_PERS, IconPersistant, ui::Point(237, 4), "Element paths persist on the screen for a while");
line3 = 270;
checkboxOffset += cSpace;
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4), ui::Point(30, 16), "Persistent", "Element paths persist on the screen for a while");
displayModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconPersistant);
tCheckbox->SetActionCallback(new DisplayModeAction(this, DISPLAY_PERS));
AddComponent(tCheckbox);
checkboxOffset += sSpace;
line3 = checkboxOffset-5;
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4), ui::Point(30, 16), "Heat", "Displays temperatures of the elements, dark blue is coldest, pink is hottest");
colourModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconHeat);
tCheckbox->SetActionCallback(new ColourModeAction(this, COLOUR_HEAT));
AddComponent(tCheckbox);
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4+18), ui::Point(30, 16), "Life", "Displays the life value of elements in greyscale gradients");
colourModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconLife);
tCheckbox->SetActionCallback(new ColourModeAction(this, COLOUR_LIFE));
AddComponent(tCheckbox);
checkboxOffset += cSpace;
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4+18), ui::Point(30, 16), "H-Gradient", "Changes colors of elements slightly to show heat diffusing through them");
colourModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconGradient);
tCheckbox->SetActionCallback(new ColourModeAction(this, COLOUR_GRAD));
AddComponent(tCheckbox);
tCheckbox = new ui::Checkbox(ui::Point(checkboxOffset, YRES+4), ui::Point(30, 16), "Basic", "No special effects at all for anything, overrides all other options and deco");
colourModes.push_back(tCheckbox);
tCheckbox->SetIcon(IconBasic);
tCheckbox->SetActionCallback(new ColourModeAction(this, COLOUR_BASC));
AddComponent(tCheckbox);
checkboxOffset += sSpace;
line4 = checkboxOffset-5;
auto addColourModeCheckbox = [this](unsigned int mode, Icon icon, ui::Point offset, String tooltip) {
auto *colourModeCheckbox = new ModeCheckbox(ui::Point(0, YRES) + offset, ui::Point(30, 16), "", tooltip);
colourModes.push_back(colourModeCheckbox);
colourModeCheckbox->mode = mode;
colourModeCheckbox->SetIcon(icon);
colourModeCheckbox->SetActionCallback({ [this, mode, colourModeCheckbox] {
if(colourModeCheckbox->GetChecked())
c->SetColourMode(colourModeCheckbox->mode);
else
c->SetColourMode(0);
} });
AddComponent(colourModeCheckbox);
};
addColourModeCheckbox(COLOUR_HEAT, IconHeat , ui::Point(275, 4), "Displays temperatures of the elements, dark blue is coldest, pink is hottest");
addColourModeCheckbox(COLOUR_LIFE, IconLife , ui::Point(275, 22), "Displays the life value of elements in greyscale gradients");
addColourModeCheckbox(COLOUR_GRAD, IconGradient, ui::Point(307, 22), "Changes colors of elements slightly to show heat diffusing through them");
addColourModeCheckbox(COLOUR_BASC, IconBasic , ui::Point(307, 4), "No special effects at all for anything, overrides all other options and deco");
line4 = 340;
}
void RenderView::OnMouseDown(int x, int y, unsigned button)
@ -317,19 +134,9 @@ void RenderView::NotifyRenderChanged(RenderModel * sender)
{
for (size_t i = 0; i < renderModes.size(); i++)
{
if (renderModes[i]->GetActionCallback())
{
//Compares bitmasks at the moment, this means that "Point" is always on when other options that depend on it are, this might confuse some users, TODO: get the full list and compare that?
RenderModeAction * action = (RenderModeAction *)(renderModes[i]->GetActionCallback());
if (action->renderMode == (sender->GetRenderMode() & action->renderMode))
{
renderModes[i]->SetChecked(true);
}
else
{
renderModes[i]->SetChecked(false);
}
}
//Compares bitmasks at the moment, this means that "Point" is always on when other options that depend on it are, this might confuse some users, TODO: get the full list and compare that?
auto renderMode = renderModes[i]->mode;
renderModes[i]->SetChecked(renderMode == (sender->GetRenderMode() & renderMode));
}
}
@ -337,18 +144,8 @@ void RenderView::NotifyDisplayChanged(RenderModel * sender)
{
for (size_t i = 0; i < displayModes.size(); i++)
{
if( displayModes[i]->GetActionCallback())
{
DisplayModeAction * action = (DisplayModeAction *)(displayModes[i]->GetActionCallback());
if (action->displayMode == (sender->GetDisplayMode() & action->displayMode))
{
displayModes[i]->SetChecked(true);
}
else
{
displayModes[i]->SetChecked(false);
}
}
auto displayMode = displayModes[i]->mode;
displayModes[i]->SetChecked(displayMode == (sender->GetDisplayMode() & displayMode));
}
}
@ -356,18 +153,8 @@ void RenderView::NotifyColourChanged(RenderModel * sender)
{
for (size_t i = 0; i < colourModes.size(); i++)
{
if (colourModes[i]->GetActionCallback())
{
ColourModeAction * action = (ColourModeAction *)(colourModes[i]->GetActionCallback());
if (action->colourMode == sender->GetColourMode())
{
colourModes[i]->SetChecked(true);
}
else
{
colourModes[i]->SetChecked(false);
}
}
auto colourMode = colourModes[i]->mode;
colourModes[i]->SetChecked(colourMode == sender->GetColourMode());
}
}

View File

@ -4,10 +4,7 @@
#include <vector>
#include "gui/interface/Window.h"
namespace ui
{
class Checkbox;
}
class ModeCheckbox;
class Renderer;
class RenderController;
@ -15,18 +12,14 @@ class RenderModel;
class RenderView: public ui::Window {
RenderController * c;
Renderer * ren;
std::vector<ui::Checkbox*> renderModes;
std::vector<ui::Checkbox*> displayModes;
std::vector<ui::Checkbox*> colourModes;
std::vector<ModeCheckbox *> renderModes;
std::vector<ModeCheckbox *> displayModes;
std::vector<ModeCheckbox *> colourModes;
String toolTip;
int toolTipPresence;
bool isToolTipFadingIn;
int line1, line2, line3, line4;
public:
class RenderModeAction;
class DisplayModeAction;
class ColourModeAction;
class RenderPresetAction;
RenderView();
void NotifyRendererChanged(RenderModel * sender);
void NotifyRenderChanged(RenderModel * sender);

View File

@ -16,34 +16,11 @@
#include "gui/interface/Label.h"
#include "gui/interface/Textbox.h"
class LocalSaveActivity::CancelAction: public ui::ButtonAction
{
LocalSaveActivity * a;
public:
CancelAction(LocalSaveActivity * a) : a(a) {}
void ActionCallback(ui::Button * sender) override
{
a->Exit();
}
};
class LocalSaveActivity::SaveAction: public ui::ButtonAction
{
LocalSaveActivity * a;
public:
SaveAction(LocalSaveActivity * a) : a(a) {}
void ActionCallback(ui::Button * sender) override
{
a->Save();
}
};
LocalSaveActivity::LocalSaveActivity(SaveFile save, FileSavedCallback * callback) :
LocalSaveActivity::LocalSaveActivity(SaveFile save, OnSaved onSaved_) :
WindowActivity(ui::Point(-1, -1), ui::Point(220, 200)),
save(save),
thumbnailRenderer(nullptr),
callback(callback)
onSaved(onSaved_)
{
ui::Label * titleLabel = new ui::Label(ui::Point(4, 5), ui::Point(Size.X-8, 16), "Save to computer:");
titleLabel->SetTextColour(style::Colour::InformationTitle);
@ -61,7 +38,9 @@ LocalSaveActivity::LocalSaveActivity(SaveFile save, FileSavedCallback * callback
cancelButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
cancelButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
cancelButton->Appearance.BorderInactive = ui::Colour(200, 200, 200);
cancelButton->SetActionCallback(new CancelAction(this));
cancelButton->SetActionCallback({ [this] {
Exit();
} });
AddComponent(cancelButton);
SetCancelButton(cancelButton);
@ -69,7 +48,9 @@ LocalSaveActivity::LocalSaveActivity(SaveFile save, FileSavedCallback * callback
okayButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
okayButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
okayButton->Appearance.TextInactive = style::Colour::InformationTitle;
okayButton->SetActionCallback(new SaveAction(this));
okayButton->SetActionCallback({ [this] {
Save();
} });
AddComponent(okayButton);
SetOkayButton(okayButton);
@ -95,20 +76,6 @@ void LocalSaveActivity::OnTick(float dt)
void LocalSaveActivity::Save()
{
class FileOverwriteConfirmation: public ConfirmDialogueCallback {
public:
LocalSaveActivity * a;
ByteString filename;
FileOverwriteConfirmation(LocalSaveActivity * a, ByteString finalFilename) : a(a), filename(finalFilename) {}
void ConfirmCallback(ConfirmPrompt::DialogueResult result) override {
if (result == ConfirmPrompt::ResultOkay)
{
a->saveWrite(filename);
}
}
virtual ~FileOverwriteConfirmation() { }
};
if (filenameField->GetText().Contains('/') || filenameField->GetText().BeginsWith("."))
{
new ErrorMessage("Error", "Invalid filename.");
@ -120,7 +87,9 @@ void LocalSaveActivity::Save()
save.SetFileName(finalFilename);
if(Client::Ref().FileExists(finalFilename))
{
new ConfirmPrompt("Overwrite file", "Are you sure you wish to overwrite\n"+finalFilename.FromUtf8(), new FileOverwriteConfirmation(this, finalFilename));
new ConfirmPrompt("Overwrite file", "Are you sure you wish to overwrite\n"+finalFilename.FromUtf8(), { [this, &finalFilename] {
saveWrite(finalFilename);
} });
}
else
{
@ -151,7 +120,10 @@ void LocalSaveActivity::saveWrite(ByteString finalFilename)
new ErrorMessage("Error", "Unable to write save file.");
else
{
callback->FileSaved(&save);
if (onSaved)
{
onSaved(&save);
}
Exit();
}
}
@ -176,5 +148,4 @@ LocalSaveActivity::~LocalSaveActivity()
{
thumbnailRenderer->Abandon();
}
delete callback;
}

View File

@ -3,7 +3,7 @@
#include "Activity.h"
#include "client/SaveFile.h"
#include <memory>
#include <functional>
namespace ui
{
@ -13,27 +13,19 @@ namespace ui
class VideoBuffer;
class ThumbnailRendererTask;
class FileSavedCallback
{
public:
FileSavedCallback() {}
virtual ~FileSavedCallback() {}
virtual void FileSaved(SaveFile * file) {}
};
class LocalSaveActivity: public WindowActivity
{
using OnSaved = std::function<void (SaveFile *)>;
SaveFile save;
ThumbnailRendererTask *thumbnailRenderer;
std::unique_ptr<VideoBuffer> thumbnail;
ui::Textbox * filenameField;
class CancelAction;
class SaveAction;
friend class CancelAction;
friend class SaveAction;
FileSavedCallback * callback;
OnSaved onSaved;
public:
LocalSaveActivity(SaveFile save, FileSavedCallback * callback);
LocalSaveActivity(SaveFile save, OnSaved onSaved = nullptr);
void saveWrite(ByteString finalFilename);
void Save();
void OnDraw() override;

View File

@ -21,60 +21,6 @@
#include "images.h"
class ServerSaveActivity::CancelAction: public ui::ButtonAction
{
ServerSaveActivity * a;
public:
CancelAction(ServerSaveActivity * a) : a(a) {}
void ActionCallback(ui::Button * sender) override
{
a->Exit();
}
};
class ServerSaveActivity::SaveAction: public ui::ButtonAction
{
ServerSaveActivity * a;
public:
SaveAction(ServerSaveActivity * a) : a(a) {}
void ActionCallback(ui::Button * sender) override
{
a->Save();
}
};
class ServerSaveActivity::PublishingAction: public ui::ButtonAction
{
ServerSaveActivity * a;
public:
PublishingAction(ServerSaveActivity * a) : a(a) {}
void ActionCallback(ui::Button * sender) override
{
a->ShowPublishingInfo();
}
};
class ServerSaveActivity::RulesAction: public ui::ButtonAction
{
ServerSaveActivity * a;
public:
RulesAction(ServerSaveActivity * a) : a(a) {}
void ActionCallback(ui::Button * sender) override
{
a->ShowRules();
}
};
class ServerSaveActivity::NameChangedAction: public ui::TextboxAction
{
public:
ServerSaveActivity * a;
NameChangedAction(ServerSaveActivity * a) : a(a) {}
void TextChangedCallback(ui::Textbox * sender) override {
a->CheckName(sender->GetText());
}
};
class SaveUploadTask: public Task
{
SaveInfo save;
@ -108,11 +54,11 @@ public:
}
};
ServerSaveActivity::ServerSaveActivity(SaveInfo save, ServerSaveActivity::SaveUploadedCallback * callback) :
ServerSaveActivity::ServerSaveActivity(SaveInfo save, OnUploaded onUploaded_) :
WindowActivity(ui::Point(-1, -1), ui::Point(440, 200)),
thumbnailRenderer(nullptr),
save(save),
callback(callback),
onUploaded(onUploaded_),
saveUploadTask(NULL)
{
titleLabel = new ui::Label(ui::Point(4, 5), ui::Point((Size.X/2)-8, 16), "");
@ -131,7 +77,7 @@ ServerSaveActivity::ServerSaveActivity(SaveInfo save, ServerSaveActivity::SaveUp
nameField = new ui::Textbox(ui::Point(8, 25), ui::Point((Size.X/2)-16, 16), save.GetName(), "[save name]");
nameField->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
nameField->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
nameField->SetActionCallback(new NameChangedAction(this));
nameField->SetActionCallback({ [this] { CheckName(nameField->GetText()); } });
AddComponent(nameField);
FocusComponent(nameField);
@ -163,7 +109,9 @@ ServerSaveActivity::ServerSaveActivity(SaveInfo save, ServerSaveActivity::SaveUp
cancelButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
cancelButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
cancelButton->Appearance.BorderInactive = ui::Colour(200, 200, 200);
cancelButton->SetActionCallback(new CancelAction(this));
cancelButton->SetActionCallback({ [this] {
Exit();
} });
AddComponent(cancelButton);
SetCancelButton(cancelButton);
@ -171,7 +119,9 @@ ServerSaveActivity::ServerSaveActivity(SaveInfo save, ServerSaveActivity::SaveUp
okayButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
okayButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
okayButton->Appearance.TextInactive = style::Colour::InformationTitle;
okayButton->SetActionCallback(new SaveAction(this));
okayButton->SetActionCallback({ [this] {
Save();
} });
AddComponent(okayButton);
SetOkayButton(okayButton);
@ -179,14 +129,18 @@ ServerSaveActivity::ServerSaveActivity(SaveInfo save, ServerSaveActivity::SaveUp
PublishingInfoButton->Appearance.HorizontalAlign = ui::Appearance::AlignCentre;
PublishingInfoButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
PublishingInfoButton->Appearance.TextInactive = style::Colour::InformationTitle;
PublishingInfoButton->SetActionCallback(new PublishingAction(this));
PublishingInfoButton->SetActionCallback({ [this] {
ShowPublishingInfo();
} });
AddComponent(PublishingInfoButton);
ui::Button * RulesButton = new ui::Button(ui::Point((Size.X*3/4)-75, Size.Y-22), ui::Point(150, 16), "Save Uploading Rules");
RulesButton->Appearance.HorizontalAlign = ui::Appearance::AlignCentre;
RulesButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
RulesButton->Appearance.TextInactive = style::Colour::InformationTitle;
RulesButton->SetActionCallback(new RulesAction(this));
RulesButton->SetActionCallback({ [this] {
ShowRules();
} });
AddComponent(RulesButton);
if (save.GetGameSave())
@ -196,11 +150,11 @@ ServerSaveActivity::ServerSaveActivity(SaveInfo save, ServerSaveActivity::SaveUp
}
}
ServerSaveActivity::ServerSaveActivity(SaveInfo save, bool saveNow, ServerSaveActivity::SaveUploadedCallback * callback) :
ServerSaveActivity::ServerSaveActivity(SaveInfo save, bool saveNow, OnUploaded onUploaded_) :
WindowActivity(ui::Point(-1, -1), ui::Point(200, 50)),
thumbnailRenderer(nullptr),
save(save),
callback(callback),
onUploaded(onUploaded_),
saveUploadTask(NULL)
{
ui::Label * titleLabel = new ui::Label(ui::Point(0, 0), Size, "Saving to server...");
@ -225,9 +179,9 @@ void ServerSaveActivity::NotifyDone(Task * task)
}
else
{
if(callback)
if (onUploaded)
{
callback->SaveUploaded(save);
onUploaded(save);
}
Exit();
}
@ -235,25 +189,14 @@ void ServerSaveActivity::NotifyDone(Task * task)
void ServerSaveActivity::Save()
{
class PublishConfirmation: public ConfirmDialogueCallback {
public:
ServerSaveActivity * a;
PublishConfirmation(ServerSaveActivity * a) : a(a) {}
void ConfirmCallback(ConfirmPrompt::DialogueResult result) override {
if (result == ConfirmPrompt::ResultOkay)
{
a->Exit();
a->saveUpload();
}
}
virtual ~PublishConfirmation() { }
};
if(nameField->GetText().length())
{
if(Client::Ref().GetAuthUser().Username != save.GetUserName() && publishedCheckbox->GetChecked())
{
new ConfirmPrompt("Publish", "This save was created by " + save.GetUserName().FromUtf8() + ", you're about to publish this under your own name; If you haven't been given permission by the author to do so, please uncheck the publish box, otherwise continue", new PublishConfirmation(this));
new ConfirmPrompt("Publish", "This save was created by " + save.GetUserName().FromUtf8() + ", you're about to publish this under your own name; If you haven't been given permission by the author to do so, please uncheck the publish box, otherwise continue", { [this] {
Exit();
saveUpload();
} });
}
else
{
@ -295,10 +238,10 @@ void ServerSaveActivity::saveUpload()
{
new ErrorMessage("Error", "Upload failed with error:\n"+Client::Ref().GetLastError());
}
else if(callback)
else if (onUploaded)
{
new SaveIDMessage(save.GetID());
callback->SaveUploaded(save);
onUploaded(save);
}
}
@ -448,5 +391,4 @@ ServerSaveActivity::~ServerSaveActivity()
thumbnailRenderer->Abandon();
}
delete saveUploadTask;
delete callback;
}

View File

@ -5,6 +5,7 @@
#include "tasks/TaskListener.h"
#include <memory>
#include <functional>
namespace ui
{
@ -18,16 +19,12 @@ class Task;
class VideoBuffer;
class ServerSaveActivity: public WindowActivity, public TaskListener
{
using OnUploaded = std::function<void (SaveInfo &)>;
public:
class SaveUploadedCallback
{
public:
SaveUploadedCallback() {}
virtual ~SaveUploadedCallback() {}
virtual void SaveUploaded(SaveInfo save) {}
};
ServerSaveActivity(SaveInfo save, SaveUploadedCallback * callback);
ServerSaveActivity(SaveInfo save, bool saveNow, SaveUploadedCallback * callback);
ServerSaveActivity(SaveInfo save, OnUploaded onUploaded);
ServerSaveActivity(SaveInfo save, bool saveNow, OnUploaded onUploaded);
void saveUpload();
void Save();
virtual void Exit() override;
@ -43,16 +40,13 @@ protected:
ThumbnailRendererTask *thumbnailRenderer;
std::unique_ptr<VideoBuffer> thumbnail;
SaveInfo save;
SaveUploadedCallback * callback;
private:
OnUploaded onUploaded;
protected:
Task * saveUploadTask;
ui::Label * titleLabel;
ui::Textbox * nameField;
ui::Textbox * descriptionField;
ui::Checkbox * publishedCheckbox;
ui::Checkbox * pausedCheckbox;
class CancelAction;
class SaveAction;
class PublishingAction;
class RulesAction;
class NameChangedAction;
};

View File

@ -19,26 +19,7 @@
#include "common/tpt-minmax.h"
class SearchController::OpenCallback: public ControllerCallback
{
SearchController * cc;
public:
OpenCallback(SearchController * cc_) { cc = cc_; }
void ControllerExit() override
{
if(cc->activePreview->GetDoOpen() && cc->activePreview->GetSaveInfo())
{
cc->searchModel->SetLoadedSave(cc->activePreview->GetSaveInfo());
}
else
{
cc->searchModel->SetLoadedSave(NULL);
}
}
};
SearchController::SearchController(ControllerCallback * callback):
SearchController::SearchController(std::function<void ()> onDone_):
activePreview(NULL),
nextQueryTime(0.0f),
nextQueryDone(true),
@ -53,7 +34,7 @@ SearchController::SearchController(ControllerCallback * callback):
searchModel->UpdateSaveList(1, "");
this->callback = callback;
onDone = onDone;
}
SaveInfo * SearchController::GetLoadedSave()
@ -97,8 +78,8 @@ void SearchController::Exit()
{
InstantOpen(false);
searchView->CloseActiveWindow();
if(callback)
callback->ControllerExit();
if (onDone)
onDone();
//HasExited = true;
}
@ -108,7 +89,6 @@ SearchController::~SearchController()
searchView->CloseActiveWindow();
delete searchModel;
delete searchView;
delete callback;
}
void SearchController::DoSearch(String query, bool now)
@ -202,12 +182,24 @@ void SearchController::InstantOpen(bool instant)
instantOpen = instant;
}
void SearchController::OpenSaveDone()
{
if (activePreview->GetDoOpen() && activePreview->GetSaveInfo())
{
searchModel->SetLoadedSave(activePreview->GetSaveInfo());
}
else
{
searchModel->SetLoadedSave(NULL);
}
}
void SearchController::OpenSave(int saveID)
{
delete activePreview;
Graphics * g = searchView->GetGraphics();
g->fillrect(XRES/3, WINDOWH-20, XRES/3, 20, 0, 0, 0, 150); //dim the "Page X of Y" a little to make the CopyTextButton more noticeable
activePreview = new PreviewController(saveID, instantOpen, new OpenCallback(this));
activePreview = new PreviewController(saveID, 0, instantOpen, [this] { OpenSaveDone(); });
activePreview->GetView()->MakeActiveWindow();
}
@ -216,7 +208,7 @@ void SearchController::OpenSave(int saveID, int saveDate)
delete activePreview;
Graphics * g = searchView->GetGraphics();
g->fillrect(XRES/3, WINDOWH-20, XRES/3, 20, 0, 0, 0, 150); //dim the "Page X of Y" a little to make the CopyTextButton more noticeable
activePreview = new PreviewController(saveID, saveDate, instantOpen, new OpenCallback(this));
activePreview = new PreviewController(saveID, saveDate, instantOpen, [this] { OpenSaveDone(); });
activePreview->GetView()->MakeActiveWindow();
}
@ -227,23 +219,14 @@ void SearchController::ClearSelection()
void SearchController::RemoveSelected()
{
class RemoveSelectedConfirmation: public ConfirmDialogueCallback {
public:
SearchController * c;
RemoveSelectedConfirmation(SearchController * c_) { c = c_; }
void ConfirmCallback(ConfirmPrompt::DialogueResult result) override {
if (result == ConfirmPrompt::ResultOkay)
c->removeSelectedC();
}
virtual ~RemoveSelectedConfirmation() { }
};
StringBuilder desc;
desc << "Are you sure you want to delete " << searchModel->GetSelected().size() << " save";
if(searchModel->GetSelected().size()>1)
desc << "s";
desc << "?";
new ConfirmPrompt("Delete saves", desc.Build(), new RemoveSelectedConfirmation(this));
new ConfirmPrompt("Delete saves", desc.Build(), { [this] {
removeSelectedC();
} });
}
void SearchController::removeSelectedC()
@ -280,24 +263,14 @@ void SearchController::removeSelectedC()
void SearchController::UnpublishSelected(bool publish)
{
class UnpublishSelectedConfirmation: public ConfirmDialogueCallback {
public:
SearchController * c;
bool publish;
UnpublishSelectedConfirmation(SearchController * c_, bool publish_) { c = c_; publish = publish_; }
void ConfirmCallback(ConfirmPrompt::DialogueResult result) override {
if (result == ConfirmPrompt::ResultOkay)
c->unpublishSelectedC(publish);
}
virtual ~UnpublishSelectedConfirmation() { }
};
StringBuilder desc;
desc << "Are you sure you want to " << (publish ? String("publish ") : String("unpublish ")) << searchModel->GetSelected().size() << " save";
if (searchModel->GetSelected().size() > 1)
desc << "s";
desc << "?";
new ConfirmPrompt(publish ? String("Publish Saves") : String("Unpublish Saves"), desc.Build(), new UnpublishSelectedConfirmation(this, publish));
new ConfirmPrompt(publish ? String("Publish Saves") : String("Unpublish Saves"), desc.Build(), { [this, publish] {
unpublishSelectedC(publish);
} });
}
void SearchController::unpublishSelectedC(bool publish)

View File

@ -3,7 +3,8 @@
#include "common/String.h"
class ControllerCallback;
#include <functional>
class SaveInfo;
class PreviewController;
class PreviewController;
@ -15,7 +16,7 @@ private:
SearchModel * searchModel;
SearchView * searchView;
PreviewController * activePreview;
ControllerCallback * callback;
std::function<void ()> onDone;
double nextQueryTime;
String nextQuery;
@ -24,10 +25,11 @@ private:
bool doRefresh;
void removeSelectedC();
void unpublishSelectedC(bool publish);
void OpenSaveDone();
public:
class OpenCallback;
bool HasExited;
SearchController(ControllerCallback * callback = NULL);
SearchController(std::function<void ()> onDone = nullptr);
~SearchController();
SearchView * GetView() { return searchView; }
void Exit();

View File

@ -45,18 +45,8 @@ SearchView::SearchView():
}
catch (std::exception & e) { }
class PageNumAction : public ui::TextboxAction
{
SearchView * v;
public:
PageNumAction(SearchView * _v) { v = _v; }
void TextChangedCallback(ui::Textbox * sender) override
{
v->textChanged();
}
};
pageTextbox = new ui::Textbox(ui::Point(283, WINDOWH-18), ui::Point(41, 16), "");
pageTextbox->SetActionCallback(new PageNumAction(this));
pageTextbox->SetActionCallback({ [this] { textChanged(); } });
pageTextbox->SetInputType(ui::Textbox::Number);
pageLabel = new ui::Label(ui::Point(0, WINDOWH-18), ui::Point(30, 16), "Page"); //page [TEXTBOX] of y
pageLabel->Appearance.HorizontalAlign = ui::Appearance::AlignRight;
@ -66,93 +56,42 @@ SearchView::SearchView():
AddComponent(pageCountLabel);
AddComponent(pageTextbox);
class SearchAction : public ui::TextboxAction
{
SearchView * v;
public:
SearchAction(SearchView * _v) { v = _v; }
void TextChangedCallback(ui::Textbox * sender) override
{
v->doSearch();
}
};
searchField = new ui::Textbox(ui::Point(60, 10), ui::Point(WINDOWW-238, 17), "", "[search]");
searchField->Appearance.icon = IconSearch;
searchField->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
searchField->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
searchField->SetActionCallback(new SearchAction(this));
searchField->SetActionCallback({ [this] { doSearch(); } });
FocusComponent(searchField);
class SortAction : public ui::ButtonAction
{
SearchView * v;
public:
SortAction(SearchView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->ChangeSort();
}
};
sortButton = new ui::Button(ui::Point(WINDOWW-140, 10), ui::Point(61, 17), "Sort");
sortButton->SetIcon(IconVoteSort);
sortButton->SetTogglable(true);
sortButton->SetActionCallback(new SortAction(this));
sortButton->SetActionCallback({ [this] { c->ChangeSort(); } });
sortButton->Appearance.HorizontalAlign = ui::Appearance::AlignCentre;
sortButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
AddComponent(sortButton);
class MyOwnAction : public ui::ButtonAction
{
SearchView * v;
public:
MyOwnAction(SearchView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->ShowOwn(sender->GetToggleState());
}
};
ownButton = new ui::Button(ui::Point(WINDOWW-70, 10), ui::Point(61, 17), "My Own");
ownButton->SetIcon(IconMyOwn);
ownButton->SetTogglable(true);
ownButton->SetActionCallback(new MyOwnAction(this));
ownButton->SetActionCallback({ [this] { c->ShowOwn(ownButton->GetToggleState()); } });
ownButton->Appearance.HorizontalAlign = ui::Appearance::AlignCentre;
ownButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
AddComponent(ownButton);
class FavAction : public ui::ButtonAction
{
SearchView * v;
public:
FavAction(SearchView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->ShowFavourite(sender->GetToggleState());
}
};
favButton = new ui::Button(searchField->Position+ui::Point(searchField->Size.X+15, 0), ui::Point(17, 17), "");
favButton->SetIcon(IconFavourite);
favButton->SetTogglable(true);
favButton->Appearance.Margin.Left+=2;
favButton->SetActionCallback(new FavAction(this));
favButton->SetActionCallback({ [this] { c->ShowFavourite(favButton->GetToggleState()); } });
favButton->Appearance.HorizontalAlign = ui::Appearance::AlignCentre;
favButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
favButton->Appearance.BorderInactive = ui::Colour(170,170,170);
AddComponent(favButton);
class ClearSearchAction : public ui::ButtonAction
{
SearchView * v;
public:
ClearSearchAction(SearchView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->clearSearch();
}
};
ui::Button * clearSearchButton = new ui::Button(searchField->Position+ui::Point(searchField->Size.X-1, 0), ui::Point(17, 17), "");
clearSearchButton->SetIcon(IconClose);
clearSearchButton->SetActionCallback(new ClearSearchAction(this));
clearSearchButton->SetActionCallback({ [this] { clearSearch(); } });
clearSearchButton->Appearance.Margin.Left+=2;
clearSearchButton->Appearance.Margin.Top+=2;
clearSearchButton->Appearance.HorizontalAlign = ui::Appearance::AlignCentre;
@ -160,22 +99,11 @@ SearchView::SearchView():
clearSearchButton->Appearance.BorderInactive = ui::Colour(170,170,170);
AddComponent(clearSearchButton);
class RelativePageAction : public ui::ButtonAction
{
SearchView * v;
int offset;
public:
RelativePageAction(SearchView * _v, int _offset): v(_v), offset(_offset) {}
void ActionCallback(ui::Button * sender) override
{
v->c->SetPageRelative(offset);
}
};
nextButton->SetActionCallback(new RelativePageAction(this, 1));
nextButton->SetActionCallback({ [this] { c->SetPageRelative(1); } });
nextButton->Appearance.HorizontalAlign = ui::Appearance::AlignRight;
nextButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
nextButton->Visible = false;
previousButton->SetActionCallback(new RelativePageAction(this, -1));
previousButton->SetActionCallback({ [this] { c->SetPageRelative(-1); } });
previousButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
previousButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
previousButton->Visible = false;
@ -191,68 +119,24 @@ SearchView::SearchView():
searchPrompt->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
AddComponent(searchPrompt);
class RemoveSelectedAction : public ui::ButtonAction
{
SearchView * v;
public:
RemoveSelectedAction(SearchView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->RemoveSelected();
}
};
class UnpublishSelectedAction : public ui::ButtonAction
{
SearchView * v;
public:
UnpublishSelectedAction(SearchView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->UnpublishSelected(v->publishButtonShown);
}
};
class FavouriteSelectedAction : public ui::ButtonAction
{
SearchView * v;
public:
FavouriteSelectedAction(SearchView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->FavouriteSelected();
}
};
class ClearSelectionAction : public ui::ButtonAction
{
SearchView * v;
public:
ClearSelectionAction(SearchView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->ClearSelection();
}
};
removeSelected = new ui::Button(ui::Point(((WINDOWW-415)/2), WINDOWH-18), ui::Point(100, 16), "Delete");
removeSelected->Visible = false;
removeSelected->SetActionCallback(new RemoveSelectedAction(this));
removeSelected->SetActionCallback({ [this] { c->RemoveSelected(); } });
AddComponent(removeSelected);
unpublishSelected = new ui::Button(ui::Point(((WINDOWW-415)/2)+105, WINDOWH-18), ui::Point(100, 16), "Unpublish");
unpublishSelected->Visible = false;
unpublishSelected->SetActionCallback(new UnpublishSelectedAction(this));
unpublishSelected->SetActionCallback({ [this] { c->UnpublishSelected(publishButtonShown); } });
AddComponent(unpublishSelected);
favouriteSelected = new ui::Button(ui::Point(((WINDOWW-415)/2)+210, WINDOWH-18), ui::Point(100, 16), "Favourite");
favouriteSelected->Visible = false;
favouriteSelected->SetActionCallback(new FavouriteSelectedAction(this));
favouriteSelected->SetActionCallback({ [this] { c->FavouriteSelected(); } });
AddComponent(favouriteSelected);
clearSelection = new ui::Button(ui::Point(((WINDOWW-415)/2)+315, WINDOWH-18), ui::Point(100, 16), "Clear selection");
clearSelection->Visible = false;
clearSelection->SetActionCallback(new ClearSelectionAction(this));
clearSelection->SetActionCallback({ [this] { c->ClearSelection(); } });
AddComponent(clearSelection);
CheckAccess();
@ -525,17 +409,6 @@ void SearchView::NotifyTagListChanged(SearchModel * sender)
}
}
class TagAction: public ui::ButtonAction
{
SearchView * v;
ByteString tag;
public:
TagAction(SearchView * v, ByteString tag) : v(v), tag(tag) {}
void ActionCallback(ui::Button * sender) override
{
v->Search(tag.FromUtf8());
}
};
if (sender->GetShowTags())
{
for (size_t i = 0; i < tags.size(); i++)
@ -565,7 +438,9 @@ void SearchView::NotifyTagListChanged(SearchModel * sender)
ui::Point(tagWidth, tagHeight),
tag.first.FromUtf8()
);
tagButton->SetActionCallback(new TagAction(this, tag.first));
tagButton->SetActionCallback({ [this, &tag] {
Search(tag.first.FromUtf8());
} });
tagButton->Appearance.BorderInactive = ui::Colour(0, 0, 0);
tagButton->Appearance.BorderHover = ui::Colour(0, 0, 0);
tagButton->Appearance.BorderActive = ui::Colour(0, 0, 0);
@ -673,30 +548,6 @@ void SearchView::NotifySaveListChanged(SearchModel * sender)
buttonWidth = (buttonAreaWidth/savesX) - buttonPadding*2;
buttonHeight = (buttonAreaHeight/savesY) - buttonPadding*2;
class SaveOpenAction: public ui::SaveButtonAction
{
SearchView * v;
public:
SaveOpenAction(SearchView * _v) { v = _v; }
void ActionCallback(ui::SaveButton * sender) override
{
v->c->OpenSave(sender->GetSave()->GetID(), sender->GetSave()->GetVersion());
}
void SelectedCallback(ui::SaveButton * sender) override
{
v->c->Selected(sender->GetSave()->GetID(), sender->GetSelected());
}
void AltActionCallback(ui::SaveButton * sender) override
{
v->Search(String::Build("history:", sender->GetSave()->GetID()));
}
void AltActionCallback2(ui::SaveButton * sender) override
{
v->Search(String::Build("user:", sender->GetSave()->GetUserName().FromUtf8()));
}
};
for (size_t i = 0; i < saves.size(); i++)
{
if (saveX == savesX)
@ -715,7 +566,12 @@ void SearchView::NotifySaveListChanged(SearchModel * sender)
ui::Point(buttonWidth, buttonHeight),
saves[i]);
saveButton->AddContextMenu(0);
saveButton->SetActionCallback(new SaveOpenAction(this));
saveButton->SetActionCallback({
[this, saveButton] { c->OpenSave(saveButton->GetSave()->GetID(), saveButton->GetSave()->GetVersion()); },
[this, saveButton] { Search(String::Build("history:", saveButton->GetSave()->GetID())); },
[this, saveButton] { Search(String::Build("user:", saveButton->GetSave()->GetUserName().FromUtf8())); },
[this, saveButton] { c->Selected(saveButton->GetSave()->GetID(), saveButton->GetSelected()); }
});
if(Client::Ref().GetAuthUser().UserID)
saveButton->SetSelectable(true);
if (saves[i]->GetUserName() == Client::Ref().GetAuthUser().Username || Client::Ref().GetAuthUser().UserElevation == User::ElevationAdmin || Client::Ref().GetAuthUser().UserElevation == User::ElevationModerator)

View File

@ -7,7 +7,7 @@
#include "client/SaveInfo.h"
#include "Controller.h"
TagsController::TagsController(ControllerCallback * callback, SaveInfo * save):
TagsController::TagsController(std::function<void ()> onDone_, SaveInfo * save):
HasDone(false)
{
tagsModel = new TagsModel();
@ -17,7 +17,7 @@ TagsController::TagsController(ControllerCallback * callback, SaveInfo * save):
tagsModel->SetSave(save);
this->callback = callback;
onDone = onDone_;
}
SaveInfo * TagsController::GetSave()
@ -39,8 +39,8 @@ void TagsController::AddTag(ByteString tag)
void TagsController::Exit()
{
tagsView->CloseActiveWindow();
if(callback)
callback->ControllerExit();
if (onDone)
onDone();
HasDone = true;
}
@ -49,6 +49,5 @@ TagsController::~TagsController()
tagsView->CloseActiveWindow();
delete tagsModel;
delete tagsView;
delete callback;
}

View File

@ -3,18 +3,19 @@
#include "common/String.h"
class ControllerCallback;
#include <functional>
class SaveInfo;
class TagsView;
class TagsModel;
class TagsController
{
ControllerCallback * callback;
std::function<void ()> onDone;
TagsView * tagsView;
TagsModel * tagsModel;
public:
bool HasDone;
TagsController(ControllerCallback * callback, SaveInfo * save);
TagsController(std::function<void ()> onDone, SaveInfo * save);
TagsView * GetView() {return tagsView;}
SaveInfo * GetSave();
void RemoveTag(ByteString tag);

View File

@ -18,46 +18,24 @@
TagsView::TagsView():
ui::Window(ui::Point(-1, -1), ui::Point(195, 250))
{
class CloseAction : public ui::ButtonAction
{
TagsView * v;
public:
CloseAction(TagsView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->c->Exit();
}
};
closeButton = new ui::Button(ui::Point(0, Size.Y-16), ui::Point(195, 16), "Close");
closeButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
closeButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
closeButton->SetActionCallback(new CloseAction(this));
closeButton->SetActionCallback({ [this] { c->Exit(); } });
AddComponent(closeButton);
SetCancelButton(closeButton);
tagInput = new ui::Textbox(ui::Point(8, Size.Y-40), ui::Point(Size.X-60, 16), "", "[new tag]");
tagInput->Appearance.icon = IconTag;
tagInput->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
tagInput->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
AddComponent(tagInput);
class AddTagAction : public ui::ButtonAction
{
TagsView * v;
public:
AddTagAction(TagsView * _v) { v = _v; }
void ActionCallback(ui::Button * sender) override
{
v->addTag();
}
};
addButton = new ui::Button(ui::Point(tagInput->Position.X+tagInput->Size.X+4, tagInput->Position.Y), ui::Point(40, 16), "Add");
addButton->Appearance.icon = IconAdd;
addButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
addButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
addButton->SetActionCallback(new AddTagAction(this));
addButton->SetActionCallback({ [this] { addTag(); } });
AddComponent(addButton);
if (!Client::Ref().GetAuthUser().UserID)
@ -85,34 +63,14 @@ void TagsView::NotifyTagsChanged(TagsModel * sender)
delete tags[i];
}
tags.clear();
class DeleteTagAction : public ui::ButtonAction
{
TagsView * v;
ByteString tag;
public:
DeleteTagAction(TagsView * _v, ByteString tag) { v = _v; this->tag = tag; }
void ActionCallback(ui::Button * sender) override
{
try
{
v->c->RemoveTag(tag);
}
catch(TagsModelException & ex)
{
new ErrorMessage("Could not remove tag", ByteString(ex.what()).FromUtf8());
}
}
};
if(sender->GetSave())
{
std::list<ByteString> Tags = sender->GetSave()->GetTags();
int i = 0;
for(std::list<ByteString>::const_iterator iter = Tags.begin(), end = Tags.end(); iter != end; iter++)
for (auto &tag : Tags)
{
ui::Label * tempLabel = new ui::Label(ui::Point(35, 35+(16*i)), ui::Point(120, 16), (*iter).FromUtf8());
ui::Label * tempLabel = new ui::Label(ui::Point(35, 35+(16*i)), ui::Point(120, 16), tag.FromUtf8());
tempLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; tempLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
tags.push_back(tempLabel);
AddComponent(tempLabel);
@ -125,7 +83,7 @@ void TagsView::NotifyTagsChanged(TagsModel * sender)
tempButton->Appearance.Margin.Top += 2;
tempButton->Appearance.HorizontalAlign = ui::Appearance::AlignCentre;
tempButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
tempButton->SetActionCallback(new DeleteTagAction(this, *iter));
tempButton->SetActionCallback({ [this, &tag] { c->RemoveTag(tag); } });
tags.push_back(tempButton);
AddComponent(tempButton);
}

View File

@ -146,27 +146,18 @@ void UpdateActivity::Exit()
void UpdateActivity::NotifyError(Task * sender)
{
class ErrorMessageCallback: public ConfirmDialogueCallback
{
UpdateActivity * a;
public:
ErrorMessageCallback(UpdateActivity * a_) { a = a_; }
void ConfirmCallback(ConfirmPrompt::DialogueResult result) override {
if (result == ConfirmPrompt::ResultOkay)
{
#ifndef UPDATESERVER
Platform::OpenURI(SCHEME "powdertoy.co.uk/Download.html");
#endif
}
a->Exit();
}
virtual ~ErrorMessageCallback() { }
};
#ifdef UPDATESERVER
new ConfirmPrompt("Autoupdate failed", "Please go online to manually download a newer version.\nError: " + sender->GetError(), new ErrorMessageCallback(this));
# define FIRST_LINE "Please go online to manually download a newer version.\n"
#else
new ConfirmPrompt("Autoupdate failed", "Please visit the website to download a newer version.\nError: " + sender->GetError(), new ErrorMessageCallback(this));
# define FIRST_LINE "Please visit the website to download a newer version.\n"
#endif
new ConfirmPrompt("Autoupdate failed", FIRST_LINE "Error: " + sender->GetError(), { [this] {
#ifndef UPDATESERVER
Platform::OpenURI(SCHEME "powdertoy.co.uk/Download.html");
#endif
Exit();
}, [this] { Exit(); } });
#undef FIRST_LINE
}

View File

@ -32,17 +32,7 @@ LuaButton::LuaButton(lua_State * l) :
button = new ui::Button(ui::Point(posX, posY), ui::Point(sizeX, sizeY), text, toolTip);
component = button;
class ClickAction : public ui::ButtonAction
{
LuaButton * luaButton;
public:
ClickAction(LuaButton * luaButton) : luaButton(luaButton) {}
void ActionCallback(ui::Button * sender) override
{
luaButton->triggerAction();
}
};
button->SetActionCallback(new ClickAction(this));
button->SetActionCallback({ [this] { triggerAction(); } });
}
int LuaButton::enabled(lua_State * l)

View File

@ -31,17 +31,7 @@ LuaCheckbox::LuaCheckbox(lua_State * l) :
checkbox = new ui::Checkbox(ui::Point(posX, posY), ui::Point(sizeX, sizeY), text, "");
component = checkbox;
class ClickAction : public ui::CheckboxAction
{
LuaCheckbox * luaCheckbox;
public:
ClickAction(LuaCheckbox * luaCheckbox) : luaCheckbox(luaCheckbox) {}
void ActionCallback(ui::Checkbox * sender) override
{
luaCheckbox->triggerAction();
}
};
checkbox->SetActionCallback(new ClickAction(this));
checkbox->SetActionCallback({ [this] { triggerAction(); } });
}
int LuaCheckbox::checked(lua_State * l)

View File

@ -31,17 +31,7 @@ LuaSlider::LuaSlider(lua_State * l) :
slider = new ui::Slider(ui::Point(posX, posY), ui::Point(sizeX, sizeY), steps);
component = slider;
class ValueAction : public ui::SliderAction
{
LuaSlider * luaSlider;
public:
ValueAction(LuaSlider * luaSlider) : luaSlider(luaSlider) {}
void ValueChangedCallback(ui::Slider * sender) override
{
luaSlider->triggerOnValueChanged();
}
};
slider->SetActionCallback(new ValueAction(this));
slider->SetActionCallback({ [this] { triggerOnValueChanged(); } });
}
int LuaSlider::steps(lua_State * l)

View File

@ -33,17 +33,7 @@ LuaTextbox::LuaTextbox(lua_State * l) :
textbox = new ui::Textbox(ui::Point(posX, posY), ui::Point(sizeX, sizeY), text, placeholder);
textbox->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
class TextChangedAction : public ui::TextboxAction
{
LuaTextbox * t;
public:
TextChangedAction(LuaTextbox * t) : t(t) {}
void TextChangedCallback(ui::Textbox * sender) override
{
t->triggerOnTextChanged();
}
};
textbox->SetActionCallback(new TextChangedAction(this));
textbox->SetActionCallback({ [this] { triggerOnTextChanged(); } });
component = textbox;
}