Page MenuHomePhabricator (Chris)

No OneTemporary

Authored By
Unknown
Size
132 KB
Referenced Files
None
Subscribers
None
diff --git a/src/GUIListBox.cpp b/src/GUIListBox.cpp
index ce2d7a5..f5b18e1 100644
--- a/src/GUIListBox.cpp
+++ b/src/GUIListBox.cpp
@@ -1,578 +1,585 @@
/*
* Copyright (C) 2011-2012 Me and My Shadow
*
* This file is part of Me and My Shadow.
*
* Me and My Shadow is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Me and My Shadow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Me and My Shadow. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Functions.h"
#include "GUIListBox.h"
#include "ThemeManager.h"
using namespace std;
namespace {
inline int tHeight(const SharedTexture& t) {
if(t) {
return rectFromTexture(*t).h;
} else {
return 0;
}
}
inline int tWidth(const SharedTexture& t) {
if(t) {
return rectFromTexture(*t).w;
} else {
return 0;
}
}
}
GUIListBox::GUIListBox(ImageManager& imageManager, SDL_Renderer& renderer,int left,int top,int width,int height,bool enabled,bool visible,int gravity):
GUIObject(imageManager,renderer,left,top,width,height,NULL,-1,enabled,visible,gravity),selectable(true),clickEvents(false){
//Set the state -1.
state=-1;
//Create the scrollbar and add it to the children.
scrollBar=new GUIScrollBar(imageManager,renderer,width-16,0,16,height,1,0,0,0,1,1,true,true);
childControls.push_back(scrollBar);
}
GUIListBox::~GUIListBox(){
//Remove all items and cache.
clearItems();
//We need to delete every child we have.
for(unsigned int i=0;i<childControls.size();i++){
delete childControls[i];
}
//Deleted the childs now empty the childControls vector.
childControls.clear();
}
void GUIListBox::scrollScrollbar(int dy) {
if (scrollBar->enabled && dy) {
scrollBar->value = clamp(scrollBar->value + dy, 0, scrollBar->maxValue);
}
}
void GUIListBox::onResize() {
scrollBar->left = width - 16;
scrollBar->height = height;
updateScrollbar = true;
}
bool GUIListBox::handleEvents(SDL_Renderer& renderer,int x,int y,bool enabled,bool visible,bool processed){
//Boolean if the event is processed.
bool b=processed;
//The GUIObject is only enabled when he and his parent are enabled.
enabled=enabled && this->enabled;
//The GUIObject is only enabled when he and his parent are enabled.
visible=visible && this->visible;
//Get the absolute position.
x+=left;
y+=top;
//Update the scrollbar.
if(scrollBar->visible)
b=b||scrollBar->handleEvents(renderer,x,y,enabled,visible,b);
//Set state negative.
state=-1;
//Check if the GUIListBox is visible, enabled and no event has been processed before.
if(enabled&&visible&&!b){
//The mouse location (x=i, y=j) and the mouse button (k).
int i,j;
SDL_GetMouseState(&i,&j);
//Convert the mouse location to a relative location.
i-=x;
j-=y;
//Check if the mouse is inside the GUIListBox.
if(i>=0&&i<width-4&&j>=0&&j<height-4){
//Calculate selected item.
int idx=-1;
int yPos=-firstItemY;
int i=scrollBar->value;
if(yPos!=0) i--;
for(;i<images.size();++i){
const SharedTexture& tex = images.at(i);
if(tex){
yPos+=tHeight(tex);
}
if(j<yPos){
idx=i;
break;
}
}
//If the entry isn't above the max we have an event.
if (idx >= 0 && idx < (int)item.size() && selectable && itemSelectable[idx]) {
state=idx;
//Check if the left mouse button is pressed.
if(event.type==SDL_MOUSEBUTTONDOWN && event.button.button==SDL_BUTTON_LEFT){
//Check if the slected item changed.
if(value!=idx){
value=idx;
//If event callback is configured then add an event to the queue.
if(eventCallback){
GUIEvent e={eventCallback,name,this,GUIEventChange};
GUIEventQueue.push_back(e);
}
}
//After possibly a change event, there will always be a click event.
if(eventCallback && clickEvents){
GUIEvent e={eventCallback,name,this,GUIEventClick};
GUIEventQueue.push_back(e);
}
}
}
//Check for mouse wheel scrolling.
if (event.type == SDL_MOUSEWHEEL && event.wheel.y && scrollBar->enabled) {
scrollScrollbar(event.wheel.y < 0 ? 1 : -1);
}
}
}
//Process child controls event except for the scrollbar.
- //That's why i starts at one.
- for(unsigned int i=1;i<childControls.size();i++){
- bool b1=childControls[i]->handleEvents(renderer,x,y,enabled,visible,b);
+ //That's why i ends at 1.
+ for (int i = childControls.size() - 1; i >= 1; i--) {
+ bool b1 = childControls[i]->handleEvents(renderer, x, y, enabled, visible, b);
//The event is processed when either our or the childs is true (or both).
b=b||b1;
}
return b;
}
void GUIListBox::render(SDL_Renderer& renderer, int x,int y,bool draw){
if(updateScrollbar){
//Calculate the height of the content.
int maxY=0;
for(const SharedTexture& t: images){
if(t){
maxY+=textureHeight(*t);
} else {
std::cerr << "WARNING: Null texture in GUIListBox!" << std::endl;
}
}
//Check if we need to show the scrollbar for many entries.
if(maxY<height){
scrollBar->maxValue=0;
scrollBar->value=0;
scrollBar->visible=false;
}else{
scrollBar->visible=true;
scrollBar->maxValue=item.size();
int yy=0;
for(int i=images.size()-1;i>0;i--){
yy+=textureHeight(*images.at(i));
if(yy>height)
break;
else
scrollBar->maxValue--;
}
scrollBar->largeChange=item.size()/4;
}
updateScrollbar=false;
}
//Rectangle the size of the GUIObject, used to draw borders.
//SDL_Rect r; //Unused local variable :/
//There's no need drawing the GUIObject when it's invisible.
if(!visible||!draw)
return;
//Get the absolute x and y location.
x+=left;
y+=top;
//Draw the background box.
const SDL_Rect r={x,y,width,height};
SDL_SetRenderDrawColor(&renderer,255,255,255,220);
SDL_RenderFillRect(&renderer, &r);
firstItemY=0;
//Loop through the entries and draw them.
if(scrollBar->value==scrollBar->maxValue&&scrollBar->visible){
int lowNumber=height;
int currentItem=images.size()-1;
while(lowNumber>=0&&currentItem>=0){
const SharedTexture& currentTexture = images.at(currentItem);
lowNumber-=tHeight(currentTexture);//->h;
if(lowNumber>0){
if(selectable){
//Check if the mouse is hovering on current entry. If so draw borders around it.
if(state==currentItem)
drawGUIBox(x,y+lowNumber-1,width,tHeight(currentTexture)+1,renderer,0x00000000);
//Check if the current entry is selected. If so draw a gray background.
if(value==currentItem)
drawGUIBox(x,y+lowNumber-1,width,tHeight(currentTexture)+1,renderer,0xDDDDDDFF);
}
applyTexture(x,y+lowNumber,*currentTexture,renderer);
}else{
// This is the top item that is partially obscured.
if(selectable){
//Check if the mouse is hovering on current entry. If so draw borders around it.
if(state==currentItem)
drawGUIBox(x,y,width,tHeight(currentTexture)+lowNumber+1,renderer,0x00000000);
//Check if the current entry is selected. If so draw a gray background.
if(value==currentItem)
drawGUIBox(x,y,width,tHeight(currentTexture)+lowNumber+1,renderer,0xDDDDDDFF);
}
firstItemY=-lowNumber;
const SDL_Rect clip{ 0, -lowNumber, textureWidth(*currentTexture), textureHeight(*currentTexture) + lowNumber };
const SDL_Rect dstRect{x, y, clip.w, clip.h};
if (clip.w > 0 && clip.h > 0) SDL_RenderCopy(&renderer, currentTexture.get(), &clip, &dstRect);
break;
}
currentItem--;
}
}else{
for(int i=scrollBar->value,j=y+1;i<(int)item.size();i++){
//Check if the current item is out side of the widget.
int yOver=tHeight(images[i]);
if(j+yOver>y+height)
yOver=y+height-j;
if (yOver > 0){
if (selectable){
//Check if the mouse is hovering on current entry. If so draw borders around it.
if (state == i)
drawGUIBox(x, j - 1, width, yOver + 1, renderer, 0x00000000);
//Check if the current entry is selected. If so draw a gray background.
if (value == i)
drawGUIBox(x, j - 1, width, yOver + 1, renderer, 0xDDDDDDFF);
}
//Draw the image.
const SDL_Rect clip{ 0, 0, tWidth(images[i]), yOver };
const SDL_Rect dstRect{ x, j, clip.w, clip.h };
SDL_RenderCopy(&renderer, images[i].get(), &clip, &dstRect);
} else if (yOver<0) {
break;
}
j+=tHeight(images[i]);
}
}
//Draw borders around the whole thing.
drawGUIBox(x,y,width,height,renderer,0x00000000);
//We now need to draw all the children of the GUIObject.
for(unsigned int i=0;i<childControls.size();i++){
childControls[i]->render(renderer,x,y,draw);
}
}
void GUIListBox::clearItems(){
item.clear();
images.clear();
itemSelectable.clear();
}
void GUIListBox::addItem(SDL_Renderer &renderer, const std::string& name, SharedTexture texture, bool selectable) {
if(texture){
images.push_back(texture);
}else if(!texture&&!name.empty()){
auto tex=SharedTexture(textureFromText(renderer, *fontText, name.c_str(), objThemes.getTextColor(true)));
// Make sure we don't create any empty textures.
if(!tex) {
std::cerr << "WARNING: Failed to create texture from text: \"" << name << "\"" << std::endl;
return;
}
images.push_back(tex);
} else {
// If nothing was added, ignore it.
return;
}
item.push_back(name);
itemSelectable.push_back(selectable);
updateScrollbar=true;
}
void GUIListBox::updateItem(SDL_Renderer &renderer, int index, const string& newText, SharedTexture newTexture) {
updateItem(renderer, index, newText, newTexture, itemSelectable[index]);
}
void GUIListBox::updateItem(SDL_Renderer &renderer, int index, const string& newText, SharedTexture newTexture, bool selectable) {
if(newTexture) {
images.at(index) = newTexture;
} else if (!newTexture&&!newText.empty()) {
auto tex=SharedTexture(textureFromText(renderer, *fontText, newText.c_str(), objThemes.getTextColor(true)));
// Make sure we don't create any empty textures.
if(!tex) {
std::cerr << "WARNING: Failed to update texture at index" << index << " \"" << newText << "\"" << std::endl;
return;
}
images.at(index)=tex;
} else {
return;
}
item.at(index)=newText;
itemSelectable.at(index) = selectable;
updateScrollbar=true;
}
std::string GUIListBox::getItem(int index){
return item.at(index);
}
GUISingleLineListBox::GUISingleLineListBox(ImageManager& imageManager, SDL_Renderer& renderer, int left, int top, int width, int height, bool enabled, bool visible, int gravity):
GUIObject(imageManager,renderer,left,top,width,height,NULL,-1,enabled,visible,gravity),animation(0){}
void GUISingleLineListBox::addItem(string name,string label){
//Check if the label is set, if not use the name.
if(label.size()==0)
label=name;
item.push_back(pair<string,string>(name,label));
}
void GUISingleLineListBox::addItems(vector<pair<string,string> > items){
vector<pair<string,string> >::iterator it;
for(it=items.begin();it!=items.end();++it){
addItem(it->first,it->second);
}
}
void GUISingleLineListBox::addItems(vector<string> items){
vector<string>::iterator it;
for(it=items.begin();it!=items.end();++it){
addItem(*it);
}
}
string GUISingleLineListBox::getName(unsigned int index){
if(index==-1)
index=value;
if(index<0||index>item.size())
return "";
return item[index].first;
}
bool GUISingleLineListBox::handleEvents(SDL_Renderer&,int x,int y,bool enabled,bool visible,bool processed){
//Boolean if the event is processed.
bool b=processed;
//The GUIObject is only enabled when he and his parent(s) are enabled.
enabled=enabled && this->enabled;
//The GUIObject is only enabled when he and his parent(s) are enabled.
visible=visible && this->visible;
//Get the absolute position.
x+=left-gravityX;
y+=top;
state&=~0xF;
- if(enabled&&visible){
+ if(enabled && visible && !b){
//Only process mouse event when not in keyboard only mode
if (!isKeyboardOnly) {
//The mouse location (x=i, y=j) and the mouse button (k).
int i, j, k;
k = SDL_GetMouseState(&i, &j);
//Convert the mouse location to a relative location.
i -= x;
j -= y;
//The selected button.
//0=nothing 1=left 2=right.
int idx = 0;
//Check which button the mouse is above.
if (i >= 0 && i < width&&j >= 0 && j < height){
if (i < 26 && i < width / 2){
//The left arrow.
idx = 1;
} else if (i >= width - 26){
//The right arrow.
idx = 2;
}
+
+ //Event has been processed as long as this is a mouse event and the mouse is inside the widget.
+ if ((event.type == SDL_MOUSEMOTION && event.motion.state == 0)
+ || event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEWHEEL)
+ {
+ b = true;
+ }
}
//If idx is 0 it means the mous doesn't hover any arrow so reset animation.
if (idx == 0)
animation = 0;
//Check if there's a mouse button press or not.
if (k&SDL_BUTTON(1)){
if (((state >> 4) & 0xF) == idx)
state |= idx;
} else{
state |= idx;
}
//Check if there's a mouse press.
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT && idx){
state = idx | (idx << 4);
} else if (event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT && idx && ((state >> 4) & 0xF) == idx){
int m = (int)item.size();
if (m > 0){
if (idx == 2){
idx = value + 1;
if (idx < 0 || idx >= m) idx = 0;
if (idx != value){
value = idx;
//If there is an event callback then call it.
if (eventCallback){
GUIEvent e = { eventCallback, name, this, GUIEventClick };
GUIEventQueue.push_back(e);
}
}
} else if (idx == 1){
idx = value - 1;
if (idx < 0 || idx >= m) idx = m - 1;
if (idx != value){
value = idx;
//If there is an event callback then call it.
if (eventCallback){
GUIEvent e = { eventCallback, name, this, GUIEventClick };
GUIEventQueue.push_back(e);
}
}
}
}
}
if (event.type == SDL_MOUSEBUTTONUP) state &= 0xF;
}
}else{
//Set state zero.
state=0;
}
return b;
}
void GUISingleLineListBox::render(SDL_Renderer& renderer, int x,int y,bool draw){
//Rectangle the size of the GUIObject, used to draw borders.
SDL_Rect r;
//There's no need drawing the GUIObject when it's invisible.
if(!visible)
return;
//NOTE: logic in the render method since it's the only part that gets called every frame.
if (!isKeyboardOnly) {
if ((state & 0xF) == 0x1 || (state & 0xF) == 0x2){
animation++;
if (animation > 20)
animation = -20;
}
}
//Get the absolute x and y location.
x+=left;
y+=top;
gravityX = 0;
if(gravity==GUIGravityCenter)
gravityX=int(width/2);
else if(gravity==GUIGravityRight)
gravityX=width;
x-=gravityX;
if (isKeyboardOnly && state && draw) {
drawGUIBox(x, y, width, height, renderer, 0xFFFFFF40);
}
//Check if the enabled state changed or the caption, if so we need to clear the (old) cache.
if(enabled!=cachedEnabled || item[value].second.compare(cachedCaption)!=0){
//Free the cache.
cacheTex.reset(nullptr);
//And cache the new values.
cachedEnabled=enabled;
cachedCaption=item[value].second;
}
//Draw the text.
if(value>=0 && value<(int)item.size()){
//Get the text.
const std::string& lp=item[value].second;
//Check if the text is empty or not.
if(!lp.empty()){
if(!cacheTex){
SDL_Color color = objThemes.getTextColor(inDialog);
cacheTex=textureFromText(renderer, *fontGUI, lp.c_str(), color);
//If the text is too wide then we change to smaller font (?)
//NOTE: The width is 32px smaller (2x16px for the arrows).
if(rectFromTexture(*cacheTex).w>width-32){
cacheTex=textureFromText(renderer, *fontGUISmall,lp.c_str(),color);
}
}
if(draw){
//Center the text both vertically as horizontally.
const SDL_Rect textureSize = rectFromTexture(*cacheTex);
r.x=x+(width-textureSize.w)/2;
r.y=y+(height-textureSize.h)/2-GUI_FONT_RAISE;
//Draw the text.
applyTexture(r.x, r.y, cacheTex, renderer);
}
}
}
if(draw){
//Draw the arrows.
r.x=x;
if (!isKeyboardOnly) {
if ((state & 0xF) == 0x1)
r.x += abs(animation / 2);
}
r.y=y+4;
if(inDialog)
applyTexture(r.x,r.y,*arrowLeft2,renderer);
else
applyTexture(r.x,r.y,*arrowLeft1,renderer);
r.x=x+width-16;
if (!isKeyboardOnly) {
if ((state & 0xF) == 0x2)
r.x -= abs(animation / 2);
}
if(inDialog)
applyTexture(r.x,r.y,*arrowRight2,renderer);
else
applyTexture(r.x,r.y,*arrowRight1,renderer);
}
}
diff --git a/src/GUIObject.cpp b/src/GUIObject.cpp
index 17bf5dd..6910405 100644
--- a/src/GUIObject.cpp
+++ b/src/GUIObject.cpp
@@ -1,1235 +1,1258 @@
/*
* Copyright (C) 2011-2012 Me and My Shadow
*
* This file is part of Me and My Shadow.
*
* Me and My Shadow is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Me and My Shadow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Me and My Shadow. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Functions.h"
#include "UTF8Functions.h"
#include "GUIObject.h"
#include "ThemeManager.h"
#include "InputManager.h"
#include "GUIListBox.h"
#include "GUISlider.h"
#include <algorithm>
#include <iostream>
#include <list>
#include <SDL_ttf_fontfallback.h>
#include "Render.h"
using namespace std;
//Set the GUIObjectRoot to NULL.
GUIObject* GUIObjectRoot=NULL;
//Initialise the event queue.
list<GUIEvent> GUIEventQueue;
//A boolean variable used to skip next mouse up event for GUI (temporary workaround).
bool GUISkipNextMouseUpEvent = false;
void GUIObjectHandleEvents(ImageManager& imageManager, SDL_Renderer& renderer, bool kill){
//Check if we need to reset the skip variable.
if (event.type == SDL_MOUSEBUTTONDOWN) {
GUISkipNextMouseUpEvent = false;
}
//Check if we need to skip event.
if (event.type == SDL_MOUSEBUTTONUP && GUISkipNextMouseUpEvent) {
GUISkipNextMouseUpEvent = false;
} else {
//Make sure that GUIObjectRoot isn't null.
if (GUIObjectRoot)
GUIObjectRoot->handleEvents(renderer);
}
//Check for SDL_QUIT.
if(event.type==SDL_QUIT && kill){
//We get a quit event so enter the exit state.
setNextState(STATE_EXIT);
delete GUIObjectRoot;
GUIObjectRoot=NULL;
return;
}
//Keep calling events until there are none left.
while(!GUIEventQueue.empty()){
//Get one event and remove it from the queue.
GUIEvent e=GUIEventQueue.front();
GUIEventQueue.pop_front();
//If an eventCallback exist call it.
if(e.eventCallback){
e.eventCallback->GUIEventCallback_OnEvent(imageManager,renderer,e.name,e.obj,e.eventType);
}
}
//We empty the event queue just to be sure.
GUIEventQueue.clear();
}
GUIObject::GUIObject(ImageManager& imageManager, SDL_Renderer& renderer, int left, int top, int width, int height,
const char* caption, int value,
bool enabled, bool visible, int gravity) :
left(left), top(top), width(width), height(height),
gravity(gravity), value(value),
enabled(enabled), visible(visible),
eventCallback(NULL), state(0),
cachedEnabled(enabled), gravityX(0),
gravityLeft(0), gravityTop(0), gravityRight(0), gravityBottom(0)
{
//Make sure that caption isn't NULL before setting it.
if (caption){
GUIObject::caption = caption;
//And set the cached caption.
cachedCaption = caption;
}
if (width <= 0)
autoWidth = true;
else
autoWidth = false;
inDialog = false;
//Load the gui images.
bmGuiTex = imageManager.loadTexture(getDataPath() + "gfx/gui.png", renderer);
}
GUIObject::~GUIObject(){
//We need to delete every child we have.
for(unsigned int i=0;i<childControls.size();i++){
delete childControls[i];
}
//Deleted the childs now empty the childControls vector.
childControls.clear();
}
void GUIObject::addChild(GUIObject* obj){
//Add widget add a child
childControls.push_back(obj);
//Copy inDialog boolean from parent.
obj->inDialog = inDialog;
}
GUIObject* GUIObject::getChild(const std::string& name){
//Look for a child with the name.
for (unsigned int i = 0; i<childControls.size(); i++)
if (childControls[i]->name == name)
return childControls[i];
//Not found so return NULL.
return NULL;
}
bool GUIObject::handleEvents(SDL_Renderer& renderer,int x,int y,bool enabled,bool visible,bool processed){
//Boolean if the event is processed.
bool b=processed;
//The GUIObject is only enabled when its parent are enabled.
enabled=enabled && this->enabled;
//The GUIObject is only enabled when its parent are enabled.
visible=visible && this->visible;
//Get the absolute position.
x+=left-gravityX;
y+=top;
//Also let the children handle their events.
- for(unsigned int i=0;i<childControls.size();i++){
- bool b1=childControls[i]->handleEvents(renderer,x,y,enabled,visible,b);
+ for (int i = childControls.size() - 1; i >= 0; i--) {
+ bool b1 = childControls[i]->handleEvents(renderer, x, y, enabled, visible, b);
//The event is processed when either our or the childs is true (or both).
b=b||b1;
}
+
return b;
}
void GUIObject::render(SDL_Renderer& renderer, int x,int y,bool draw){
//There's no need drawing the GUIObject when it's invisible.
if(!visible)
return;
//Get the absolute x and y location.
x+=left;
y+=top;
//We now need to draw all the children of the GUIObject.
for(unsigned int i=0;i<childControls.size();i++){
childControls[i]->render(renderer,x,y,draw);
}
}
void GUIObject::onResize() {
}
void GUIObject::refreshCache(bool enabled) {
//Check if the enabled state changed or the caption, if so we need to clear the (old) cache.
if(enabled!=cachedEnabled || caption.compare(cachedCaption)!=0 || width<=0){
//TODO: Only change alpha if only enabled changes.
//Free the cache.
cacheTex.reset(nullptr);
//And cache the new values.
cachedEnabled=enabled;
cachedCaption=caption;
//Finally resize the widget
if(autoWidth)
width=-1;
}
}
int GUIObject::getSelectedControl() {
for (int i = 0; i < (int)childControls.size(); i++) {
GUIObject *obj = childControls[i];
if (obj && obj->visible && obj->enabled && obj->state) {
if (dynamic_cast<GUITextBox*>(obj) && obj->state == 2) {
return i;
} else if (dynamic_cast<GUIButton*>(obj) || dynamic_cast<GUICheckBox*>(obj)
|| dynamic_cast<GUISingleLineListBox*>(obj)
|| dynamic_cast<GUISlider*>(obj)
)
{
return i;
}
}
}
return -1;
}
void GUIObject::setSelectedControl(int index) {
for (int i = 0; i < (int)childControls.size(); i++) {
GUIObject *obj = childControls[i];
if (obj && obj->visible && obj->enabled) {
if (dynamic_cast<GUIButton*>(obj) || dynamic_cast<GUICheckBox*>(obj)) {
//It's a button.
obj->state = (i == index) ? 1 : 0;
} else if (dynamic_cast<GUITextBox*>(obj)) {
//It's a text box (or a spin box).
if(i == index) {
obj->state = 2;
} else {
dynamic_cast<GUITextBox*>(obj)->blur();
}
} else if (dynamic_cast<GUISingleLineListBox*>(obj)) {
//It's a single line list box.
obj->state = (i == index) ? 0x100 : 0;
} else if (dynamic_cast<GUISlider*>(obj)) {
//It's a slider.
obj->state = (i == index) ? 0x10000 : 0;
}
}
}
}
int GUIObject::selectNextControl(int direction, int selected) {
//Get the index of currently selected control.
if (selected == 0x80000000) {
selected = getSelectedControl();
}
//Find the next control.
for (int i = 0; i < (int)childControls.size(); i++) {
if (selected < 0) {
selected = 0;
} else {
selected += direction;
if (selected >= (int)childControls.size()) {
selected -= childControls.size();
} else if (selected < 0) {
selected += childControls.size();
}
}
GUIObject *obj = childControls[selected];
if (obj && obj->visible && obj->enabled) {
if (dynamic_cast<GUIButton*>(obj) || dynamic_cast<GUICheckBox*>(obj)
|| dynamic_cast<GUITextBox*>(obj)
|| dynamic_cast<GUISingleLineListBox*>(obj)
|| dynamic_cast<GUISlider*>(obj)
)
{
setSelectedControl(selected);
return selected;
}
}
}
return -1;
}
bool GUIObject::handleKeyboardNavigationEvents(ImageManager& imageManager, SDL_Renderer& renderer, int keyboardNavigationMode) {
if (keyboardNavigationMode == 0) return false;
//Check operation on focused control. These have higher priority.
if (isKeyboardOnly) {
//Check enter key.
if ((keyboardNavigationMode & ReturnControls) != 0 && inputMgr.isKeyDownEvent(INPUTMGR_SELECT)) {
int index = getSelectedControl();
if (index >= 0) {
GUIObject *obj = childControls[index];
if (dynamic_cast<GUIButton*>(obj)) {
//It's a button.
if (obj->eventCallback) {
obj->eventCallback->GUIEventCallback_OnEvent(imageManager, renderer, obj->name, obj, GUIEventClick);
}
return true;
}
if (dynamic_cast<GUICheckBox*>(obj)) {
//It's a check box.
obj->value = obj->value ? 0 : 1;
if (obj->eventCallback) {
obj->eventCallback->GUIEventCallback_OnEvent(imageManager, renderer, obj->name, obj, GUIEventClick);
}
return true;
}
}
}
//Check left/right key.
if ((keyboardNavigationMode & LeftRightControls) != 0 && (inputMgr.isKeyDownEvent(INPUTMGR_LEFT) || inputMgr.isKeyDownEvent(INPUTMGR_RIGHT))) {
int index = getSelectedControl();
if (index >= 0) {
GUIObject *obj = childControls[index];
auto sllb = dynamic_cast<GUISingleLineListBox*>(obj);
if (sllb) {
//It's a single line list box.
int newValue = sllb->value + (inputMgr.isKeyDownEvent(INPUTMGR_RIGHT) ? 1 : -1);
if (newValue >= (int)sllb->item.size()) {
newValue -= sllb->item.size();
} else if (newValue < 0) {
newValue += sllb->item.size();
}
if (sllb->value != newValue) {
sllb->value = newValue;
if (obj->eventCallback) {
obj->eventCallback->GUIEventCallback_OnEvent(imageManager, renderer, obj->name, obj, GUIEventClick);
}
}
return true;
}
auto slider = dynamic_cast<GUISlider*>(obj);
if (slider) {
//It's a slider.
int newValue = slider->value + (inputMgr.isKeyDownEvent(INPUTMGR_RIGHT) ? slider->largeChange : -slider->largeChange);
newValue = clamp(newValue, slider->minValue, slider->maxValue);
if (slider->value != newValue) {
slider->value = newValue;
if (obj->eventCallback) {
obj->eventCallback->GUIEventCallback_OnEvent(imageManager, renderer, obj->name, obj, GUIEventChange);
}
}
return true;
}
}
}
}
//Check if we need to exclude printable characters
bool excludePrintable = false;
{
int index = getSelectedControl();
if (index >= 0) {
GUIObject *obj = childControls[index];
if (dynamic_cast<GUITextBox*>(obj)) {
excludePrintable = true;
}
}
}
//Check focus movement
int m = SDL_GetModState();
if (((keyboardNavigationMode & LeftRightFocus) != 0 && inputMgr.isKeyDownEvent(INPUTMGR_RIGHT, excludePrintable))
|| ((keyboardNavigationMode & UpDownFocus) != 0 && inputMgr.isKeyDownEvent(INPUTMGR_DOWN, excludePrintable))
|| ((keyboardNavigationMode & TabFocus) != 0 && inputMgr.isKeyDownEvent(INPUTMGR_TAB, excludePrintable) && (m & KMOD_SHIFT) == 0)
)
{
isKeyboardOnly = true;
selectNextControl(1);
return true;
} else if (((keyboardNavigationMode & LeftRightFocus) != 0 && inputMgr.isKeyDownEvent(INPUTMGR_LEFT, excludePrintable))
|| ((keyboardNavigationMode & UpDownFocus) != 0 && inputMgr.isKeyDownEvent(INPUTMGR_UP, excludePrintable))
|| ((keyboardNavigationMode & TabFocus) != 0 && inputMgr.isKeyDownEvent(INPUTMGR_TAB, excludePrintable) && (m & KMOD_SHIFT) != 0)
)
{
isKeyboardOnly = true;
selectNextControl(-1);
return true;
}
return false;
}
//////////////GUIButton///////////////////////////////////////////////////////////////////
bool GUIButton::handleEvents(SDL_Renderer& renderer,int x,int y,bool enabled,bool visible,bool processed){
//Boolean if the event is processed.
bool b=processed;
//The widget is only enabled when its parent are enabled.
enabled=enabled && this->enabled;
//The widget is only enabled when its parent are enabled.
visible=visible && this->visible;
//Get the absolute position.
x+=left-gravityX;
y+=top;
//We don't update button state under keyboard only mode.
if (!isKeyboardOnly) {
//Set state to 0.
state = 0;
- //Only check for events when the object is both enabled and visible.
- if (enabled && visible) {
+ //Only check for events when the object is both enabled and visible and the event hasn't been already processed.
+ if (enabled && visible && !b) {
//The mouse location (x=i, y=j) and the mouse button (k).
int i, j, k;
k = SDL_GetMouseState(&i, &j);
//Check if the mouse is inside the widget.
if (i >= x && i < x + width && j >= y && j < y + height) {
//We have hover so set state to one.
state = 1;
//Check for a mouse button press.
if (k&SDL_BUTTON(1))
state = 2;
- //Check if there's a mouse press and the event hasn't been already processed.
- if (event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT && !b) {
+ //Check if there's a mouse press.
+ if (event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT) {
//If event callback is configured then add an event to the queue.
if (eventCallback) {
GUIEvent e = { eventCallback, name, this, GUIEventClick };
GUIEventQueue.push_back(e);
}
+ }
- //Event has been processed.
+ //Event has been processed as long as this is a mouse event and the mouse is inside the widget.
+ if ((event.type == SDL_MOUSEMOTION && event.motion.state == 0)
+ || event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEWHEEL)
+ {
b = true;
}
}
}
}
-
- //Also let the children handle their events.
- for(unsigned int i=0;i<childControls.size();i++){
- bool b1=childControls[i]->handleEvents(renderer,x,y,enabled,visible,b);
-
- //The event is processed when either our or the childs is true (or both).
- b=b||b1;
- }
+
return b;
}
void GUIButton::render(SDL_Renderer& renderer, int x,int y,bool draw){
//There's no need drawing the widget when it's invisible.
if(!visible)
return;
//Get the absolute x and y location.
x+=left;
y+=top;
refreshCache(enabled);
//Get the text and make sure it isn't empty.
const char* lp=caption.c_str();
if(lp!=NULL && lp[0]){
//Update cache if needed.
if(!cacheTex){
SDL_Color color = objThemes.getTextColor(inDialog);
if(!smallFont) {
cacheTex = textureFromText(renderer, *fontGUI, lp, color);
} else {
cacheTex = textureFromText(renderer, *fontGUISmall, lp, color);
}
//Make the widget transparent if it's disabled.
if(!enabled) {
SDL_SetTextureAlphaMod(cacheTex.get(), 128);
}
//Calculate proper size for the widget.
if(width<=0){
width=textureWidth(*cacheTex)+50;
if(gravity==GUIGravityCenter){
gravityX=int(width/2);
}else if(gravity==GUIGravityRight){
gravityX=width;
}else{
gravityX=0;
}
}
}
if(draw){
//Center the text both vertically as horizontally.
const SDL_Rect size = rectFromTexture(*cacheTex);
const int drawX=x-gravityX+(width-size.w)/2;
const int drawY=y+(height-size.h)/2-GUI_FONT_RAISE;
//Check if the arrows don't fall of.
if(size.w+32<=width){
if(state==1){
if(inDialog){
applyTexture(x-gravityX+(width-size.w)/2+4+size.w+5,y+2,*arrowLeft2,renderer);
applyTexture(x-gravityX+(width-size.w)/2-25,y+2,*arrowRight2,renderer);
}else{
applyTexture(x-gravityX+(width-size.w)/2+4+size.w+5,y+2,*arrowLeft1,renderer);
applyTexture(x-gravityX+(width-size.w)/2-25,y+2,*arrowRight1,renderer);
}
}else if(state==2){
if(inDialog){
applyTexture(x-gravityX+(width-size.w)/2+4+size.w,y+2,*arrowLeft2,renderer);
applyTexture(x-gravityX+(width-size.w)/2-20,y+2,*arrowRight2,renderer);
}else{
applyTexture(x-gravityX+(width-size.w)/2+4+size.w,y+2,*arrowLeft1,renderer);
applyTexture(x-gravityX+(width-size.w)/2-20,y+2,arrowRight1,renderer);
}
}
}
//Draw the text.
applyTexture(drawX, drawY, *cacheTex, renderer);
}
}
}
//////////////GUICheckBox///////////////////////////////////////////////////////////////////
bool GUICheckBox::handleEvents(SDL_Renderer&,int x,int y,bool enabled,bool visible,bool processed){
//Boolean if the event is processed.
bool b=processed;
//The widget is only enabled when its parent are enabled.
enabled=enabled && this->enabled;
//The widget is only enabled when its parent are enabled.
visible=visible && this->visible;
//Get the absolute position.
x+=left-gravityX;
y+=top;
//We don't update state under keyboard only mode.
if (!isKeyboardOnly) {
//Set state to 0.
state = 0;
- //Only check for events when the object is both enabled and visible.
- if (enabled&&visible){
+ //Only check for events when the object is both enabled and visible and the event hasn't been already processed.
+ if (enabled && visible && !b) {
//The mouse location (x=i, y=j) and the mouse button (k).
int i, j, k;
k = SDL_GetMouseState(&i, &j);
//Check if the mouse is inside the widget.
if (i >= x && i < x + width && j >= y && j < y + height){
//We have hover so set state to one.
state = 1;
//Check for a mouse button press.
if (k&SDL_BUTTON(1))
state = 2;
//Check if there's a mouse press and the event hasn't been already processed.
- if (event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT && !b){
+ if (event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT){
//It's a checkbox so toggle the value.
value = value ? 0 : 1;
//If event callback is configured then add an event to the queue.
if (eventCallback){
GUIEvent e = { eventCallback, name, this, GUIEventClick };
GUIEventQueue.push_back(e);
}
+ }
- //Event has been processed.
+ //Event has been processed as long as this is a mouse event and the mouse is inside the widget.
+ if ((event.type == SDL_MOUSEMOTION && event.motion.state == 0)
+ || event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEWHEEL)
+ {
b = true;
}
}
}
}
return b;
}
void GUICheckBox::render(SDL_Renderer& renderer, int x,int y,bool draw){
//There's no need drawing the widget when it's invisible.
if(!visible)
return;
//Get the absolute x and y location.
x+=left;
y+=top;
refreshCache(enabled);
//Draw the highlight in keyboard only mode.
if (isKeyboardOnly && state && draw) {
drawGUIBox(x, y, width, height, renderer, 0xFFFFFF40);
}
//Get the text.
const char* lp=caption.c_str();
//Make sure it isn't empty.
if(lp!=NULL && lp[0]){
//Update the cache if needed.
if(!cacheTex){
SDL_Color color = objThemes.getTextColor(inDialog);
cacheTex=textureFromText(renderer,*fontText,lp,color);
}
if(draw){
//Calculate the location, center it vertically.
const int drawX=x;
const int drawY=y+(height - textureHeight(*cacheTex))/2;
//Draw the text
applyTexture(drawX, drawY, *cacheTex, renderer);
}
}
if(draw){
//Draw the check (or not).
//value*16 determines where in the gui textures we draw from.
//if(value==1||value==2)
// r1.x=value*16;
const SDL_Rect srcRect={value*16,0,16,16};
const SDL_Rect dstRect={x+width-20, y+(height-16)/2, 16, 16};
//Get the right image depending on the state of the object.
SDL_RenderCopy(&renderer, bmGuiTex.get(), &srcRect, &dstRect);
}
}
//////////////GUILabel///////////////////////////////////////////////////////////////////
bool GUILabel::handleEvents(SDL_Renderer&,int ,int ,bool ,bool ,bool processed){
return processed;
}
void GUILabel::render(SDL_Renderer& renderer, int x,int y,bool draw){
//There's no need drawing the widget when it's invisible.
if(!visible)
return;
//Check if the enabled state changed or the caption, if so we need to clear the (old) cache.
refreshCache(enabled);
//Get the absolute x and y location.
x+=left;
y+=top;
//Rectangle the size of the widget.
SDL_Rect r;
r.x=x;
r.y=y;
r.w=width;
r.h=height;
//Get the caption and make sure it isn't empty.
const char* lp=caption.c_str();
if(lp!=NULL && lp[0]){
//Update cache if needed.
if(!cacheTex){
SDL_Color color = objThemes.getTextColor(inDialog);
cacheTex=textureFromText(renderer, *fontText, lp, color);
if(width<=0)
width=textureWidth(*cacheTex);
}
//Align the text properly and draw it.
if(draw){
const SDL_Rect size = rectFromTexture(*cacheTex);
if(gravity==GUIGravityCenter)
gravityX=(width-size.w)/2;
else if(gravity==GUIGravityRight)
gravityX=width-size.w;
else
gravityX=0;
r.y=y+(height - size.h)/2;
r.x+=gravityX;
applyTexture(r.x, r.y, cacheTex, renderer);
}
}
}
//////////////GUITextBox///////////////////////////////////////////////////////////////////
void GUITextBox::backspaceChar(){
//We need to remove a character so first make sure that there is text.
if(caption.length()>0){
if(highlightStart==highlightEnd&&highlightStart>0){
int advance = 0;
// this is proper UTF-8 support
int ch = utf8ReadBackward(caption.c_str(), highlightStart); // we obtain new highlightStart from this
if (ch > 0) TTF_GlyphMetrics(fontText, ch, NULL, NULL, NULL, NULL, &advance);
highlightEndX = highlightStartX = highlightEndX - advance;
caption.erase(highlightStart, highlightEnd - highlightStart);
highlightEnd = highlightStart;
} else if (highlightStart<highlightEnd){
caption.erase(highlightStart,highlightEnd-highlightStart);
highlightEnd=highlightStart;
highlightEndX=highlightStartX;
}else{
caption.erase(highlightEnd,highlightStart-highlightEnd);
highlightStart=highlightEnd;
highlightStartX=highlightEndX;
}
//If there is an event callback then call it.
if(eventCallback){
GUIEvent e={eventCallback,name,this,GUIEventChange};
GUIEventQueue.push_back(e);
}
}
}
void GUITextBox::deleteChar(){
//We need to remove a character so first make sure that there is text.
if(caption.length()>0){
if(highlightStart==highlightEnd){
// this is proper utf8 support
int i = highlightEnd;
utf8ReadForward(caption.c_str(), i);
if (i > highlightEnd) caption.erase(highlightEnd, i - highlightEnd);
highlightStart=highlightEnd;
highlightStartX=highlightEndX;
}else if(highlightStart<highlightEnd){
caption.erase(highlightStart,highlightEnd-highlightStart);
highlightEnd=highlightStart;
highlightEndX=highlightStartX;
}else{
caption.erase(highlightEnd,highlightStart-highlightEnd);
highlightStart=highlightEnd;
highlightStartX=highlightEndX;
}
//If there is an event callback then call it.
if(eventCallback){
GUIEvent e={eventCallback,name,this,GUIEventChange};
GUIEventQueue.push_back(e);
}
}
}
void GUITextBox::moveCarrotLeft(){
if(highlightEnd>0){
int advance = 0;
// this is proper UTF-8 support
int ch = utf8ReadBackward(caption.c_str(), highlightEnd); // we obtain new highlightEnd from this
if (ch > 0) TTF_GlyphMetrics(fontText, ch, NULL, NULL, NULL, NULL, &advance);
if(SDL_GetModState() & KMOD_SHIFT){
highlightEndX-=advance;
}else{
highlightStart=highlightEnd;
highlightStartX=highlightEndX=highlightEndX-advance;
}
}else{
if((SDL_GetModState() & KMOD_SHIFT)==0){
highlightStart=highlightEnd;
highlightStartX=highlightEndX;
}
}
tick=15;
}
void GUITextBox::moveCarrotRight(){
if(highlightEnd<caption.length()){
int advance = 0;
// this is proper UTF-8 support
int ch = utf8ReadForward(caption.c_str(), highlightEnd); // we obtain new highlightEnd from this
if (ch > 0) TTF_GlyphMetrics(fontText, ch, NULL, NULL, NULL, NULL, &advance);
if(SDL_GetModState() & KMOD_SHIFT){
highlightEndX+=advance;
}else{
highlightStartX=highlightEndX=highlightEndX+advance;
highlightStart=highlightEnd;
}
}else{
if((SDL_GetModState() & KMOD_SHIFT)==0){
highlightStart=highlightEnd;
highlightStartX=highlightEndX;
}
}
tick=15;
}
void GUITextBox::updateText(const std::string& text) {
caption = text;
updateSelection(0, 0);
}
void GUITextBox::updateSelection(int start, int end) {
start = clamp(start, 0, caption.size());
end = clamp(end, 0, caption.size());
highlightStart = start;
highlightStartX = 0;
highlightEnd = end;
highlightEndX = 0;
if (start > 0) {
TTF_SizeUTF8(fontText, caption.substr(0, start).c_str(), &highlightStartX, NULL);
}
if (end > 0) {
TTF_SizeUTF8(fontText, caption.substr(0, end).c_str(), &highlightEndX, NULL);
}
}
void GUITextBox::inputText(const char* s) {
int m = strlen(s);
if (m > 0){
if (highlightStart == highlightEnd) {
caption.insert((size_t)highlightStart, s);
highlightStart += m;
highlightEnd = highlightStart;
} else if (highlightStart < highlightEnd) {
caption.erase(highlightStart, highlightEnd - highlightStart);
caption.insert((size_t)highlightStart, s);
highlightStart += m;
highlightEnd = highlightStart;
highlightEndX = highlightStartX;
} else {
caption.erase(highlightEnd, highlightStart - highlightEnd);
caption.insert((size_t)highlightEnd, s);
highlightEnd += m;
highlightStart = highlightEnd;
highlightStartX = highlightEndX;
}
int advance = 0;
for (int i = 0;;) {
int a = 0;
int ch = utf8ReadForward(s, i);
if (ch <= 0) break;
TTF_GlyphMetrics(fontText, ch, NULL, NULL, NULL, NULL, &a);
advance += a;
}
highlightStartX = highlightEndX = highlightStartX + advance;
//If there is an event callback then call it.
if (eventCallback){
GUIEvent e = { eventCallback, name, this, GUIEventChange };
GUIEventQueue.push_back(e);
}
}
}
void GUITextBox::blur(){
state = 0;
highlightStart=highlightStartX=0;
highlightEnd=highlightEndX=0;
}
bool GUITextBox::handleEvents(SDL_Renderer&,int x,int y,bool enabled,bool visible,bool processed){
//Boolean if the event is processed.
bool b=processed;
//The widget is only enabled when its parent are enabled.
enabled=enabled && this->enabled;
//The widget is only enabled when its parent are enabled.
visible=visible && this->visible;
//Get the absolute position.
x+=left-gravityX;
y+=top;
//NOTE: We don't reset the state to have a "focus" effect.
//Only check for events when the object is both enabled and visible.
if(enabled&&visible){
//Check if there's a key press and the event hasn't been already processed.
if(state==2 && event.type==SDL_KEYDOWN && !b){
//Get the keycode.
SDL_Keycode key=event.key.keysym.sym;
if ((event.key.keysym.mod & KMOD_CTRL) == 0) {
//Check if the key is supported.
if (event.key.keysym.sym == SDLK_BACKSPACE){
backspaceChar();
} else if (event.key.keysym.sym == SDLK_DELETE){
deleteChar();
} else if (event.key.keysym.sym == SDLK_RIGHT){
moveCarrotRight();
} else if (event.key.keysym.sym == SDLK_LEFT){
moveCarrotLeft();
}
} else {
//Check hotkey.
if (event.key.keysym.sym == SDLK_a) {
//Select all.
highlightStart = 0;
highlightStartX = 0;
highlightEnd = caption.size();
highlightEndX = 0;
if (highlightEnd > 0) {
TTF_SizeUTF8(fontText, caption.c_str(), &highlightEndX, NULL);
}
} else if (event.key.keysym.sym == SDLK_x || event.key.keysym.sym == SDLK_c) {
//Cut or copy.
int start = highlightStart, end = highlightEnd;
if (start > end) std::swap(start, end);
if (start < end) {
SDL_SetClipboardText(caption.substr(start, end - start).c_str());
if (event.key.keysym.sym == SDLK_x) {
//Cut.
backspaceChar();
}
}
} else if (event.key.keysym.sym == SDLK_v) {
//Paste.
if (SDL_HasClipboardText()) {
char *s = SDL_GetClipboardText();
inputText(s);
SDL_free(s);
}
}
}
//The event has been processed.
b = true;
} else if (state == 2 && event.type == SDL_TEXTINPUT && !b){
inputText(event.text.text);
//The event has been processed.
b = true;
} else if (state == 2 && event.type == SDL_TEXTEDITING && !b){
// TODO: process SDL_TEXTEDITING event
}
//Only process mouse event when not in keyboard only mode
- if (!isKeyboardOnly) {
+ if (!isKeyboardOnly &&
+ (event.type == SDL_MOUSEMOTION || event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEWHEEL))
+ {
//The mouse location (x=i, y=j) and the mouse button (k).
int i, j, k;
k = SDL_GetMouseState(&i, &j);
- //Check if the mouse is inside the widget.
- if (i >= x && i < x + width && j >= y && j < y + height){
+ //Check if the mouse is inside the widget and the event hasn't been processed.
+ if (i >= x && i < x + width && j >= y && j < y + height && !b) {
//We can only increase our state. (nothing->hover->focus).
if (state != 2){
state = 1;
}
//Also update the cursor type.
currentCursor = CURSOR_CARROT;
//Move carrot and highlightning according to mouse input.
int clickX = i - x - 2;
int finalPos = 0;
int finalX = 0;
if (cacheTex&&!caption.empty()){
finalPos = caption.length();
for (int i = 0;;){
int advance = 0;
// this is proper UTF-8 support
int i0 = i;
int ch = utf8ReadForward(caption.c_str(), i);
if (ch <= 0) break;
TTF_GlyphMetrics(fontText, ch, NULL, NULL, NULL, NULL, &advance);
finalX += advance;
if (clickX < finalX - advance / 2){
finalPos = i0;
finalX -= advance;
break;
}
}
}
if (event.type == SDL_MOUSEBUTTONUP && state == 2){
state = 2;
highlightEnd = finalPos;
highlightEndX = finalX;
} else if (event.type == SDL_MOUSEBUTTONDOWN){
state = 2;
highlightStart = highlightEnd = finalPos;
highlightStartX = highlightEndX = finalX;
} else if (event.type == SDL_MOUSEMOTION && (k&SDL_BUTTON(1)) && state == 2){
state = 2;
highlightEnd = finalPos;
highlightEndX = finalX;
}
+
+ //Event has been processed as long as this is a mouse event and the mouse is inside the widget.
+ b = true;
} else{
//The mouse is outside the TextBox.
//If we don't have focus but only hover we lose it.
if (state == 1){
state = 0;
}
//If it's a click event outside the textbox then we blur.
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT){
blur();
}
}
}
}
return b;
}
void GUITextBox::render(SDL_Renderer& renderer, int x,int y,bool draw){
//There's no need drawing the widget when it's invisible.
if(!visible)
return;
//Get the absolute x and y location.
x+=left;
y+=top;
//Check if the enabled state changed or the caption, if so we need to clear the (old) cache.
refreshCache(enabled);
if(draw){
//Default background opacity
int clr=50;
//If hovering or focused make background more visible.
if(state==1)
clr=128;
else if (state==2)
clr=100;
//Draw the box.
Uint32 color=0xFFFFFF00|clr;
drawGUIBox(x,y,width,height,renderer,color);
}
//Rectangle used for drawing.
SDL_Rect r{0,0,0,0};
//Get the text and make sure it isn't empty.
const char* lp=caption.c_str();
if(lp!=NULL && lp[0]){
if(!cacheTex) {
//Draw the text.
cacheTex=textureFromText(renderer,*fontText,lp,objThemes.getTextColor(true));
}
if(draw){
//Only draw the carrot and highlight when focus.
if(state==2){
//Place the highlighted area.
r.x=x+4;
r.y=y+3;
r.h=height-6;
if(highlightStart<highlightEnd){
r.x+=highlightStartX;
r.w=highlightEndX-highlightStartX;
}else{
r.x+=highlightEndX;
r.w=highlightStartX-highlightEndX;
}
//Draw the area.
//SDL_FillRect(screen,&r,SDL_MapRGB(screen->format,128,128,128));
SDL_SetRenderDrawColor(&renderer, 128,128,128,255);
SDL_RenderFillRect(&renderer, &r);
//Ticking carrot.
if(tick<16){
//Show carrot: 15->0.
r.x=x+highlightEndX+2;
r.y=y+3;
r.h=height-6;
r.w=2;
//SDL_FillRect(screen,&r,SDL_MapRGB(screen->format,0,0,0));
SDL_SetRenderDrawColor(&renderer,0,0,0,255);
SDL_RenderFillRect(&renderer, &r);
//Reset: 32 or count down.
if(tick<=0)
tick=32;
else
tick--;
}else{
//Hide carrot: 32->16.
tick--;
}
}
//Calculate the location, center it vertically.
SDL_Rect dstRect=rectFromTexture(*cacheTex);
dstRect.x=x+4;
dstRect.y=y+(height-dstRect.h)/2;
dstRect.w=std::min(width-2, dstRect.w);
//Draw the text.
const SDL_Rect srcRect={0,0,width-2,25};
SDL_RenderCopy(&renderer, cacheTex.get(), &srcRect, &dstRect);
}
}else{
//Only draw the carrot when focus.
if(state==2&&draw){
//Ticking carrot.
if (tick<16){
//Show carrot: 15->0.
r.x = x + 4;
r.y = y + 4;
r.w = 2;
r.h = height - 8;
//SDL_FillRect(screen,&r,SDL_MapRGB(screen->format,0,0,0));
SDL_SetRenderDrawColor(&renderer, 0, 0, 0, 255);
SDL_RenderFillRect(&renderer, &r);
//Reset: 32 or count down.
if (tick <= 0)
tick = 32;
else
tick--;
} else{
//Hide carrot: 32->16.
tick--;
}
}
}
}
//////////////GUIFrame///////////////////////////////////////////////////////////////////
bool GUIFrame::handleEvents(SDL_Renderer& renderer,int x,int y,bool enabled,bool visible,bool processed){
//Boolean if the event is processed.
bool b=processed;
//The widget is only enabled when its parent are enabled.
enabled=enabled && this->enabled;
//The widget is only enabled when its parent are enabled.
visible=visible && this->visible;
//Get the absolute position.
x+=left;
y+=top;
//Also let the children handle their events.
- for(unsigned int i=0;i<childControls.size();i++){
- bool b1=childControls[i]->handleEvents(renderer,x,y,enabled,visible,b);
+ for (int i = childControls.size() - 1; i >= 0; i--) {
+ bool b1 = childControls[i]->handleEvents(renderer, x, y, enabled, visible, b);
//The event is processed when either our or the childs is true (or both).
b=b||b1;
}
+
+ //If we are visible, the event is a mouse event, and the mouse is inside the widget, we mark this event as processed.
+ if (visible &&
+ ((event.type == SDL_MOUSEMOTION && event.motion.state == 0)
+ || event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEWHEEL))
+ {
+ //The mouse location (x=i, y=j) and the mouse button (k).
+ int i, j, k;
+ k = SDL_GetMouseState(&i, &j);
+
+ //Check if the mouse is inside the widget.
+ if (i >= x && i < x + width && j >= y && j < y + height) {
+ b = true;
+ }
+ }
+
return b;
}
void GUIFrame::render(SDL_Renderer& renderer, int x,int y,bool draw){
//There's no need drawing this widget when it's invisible.
if(!visible)
return;
//Get the absolute x and y location.
x+=left;
y+=top;
//Check if the enabled state changed or the caption, if so we need to clear the (old) cache.
if(enabled!=cachedEnabled || caption.compare(cachedCaption)!=0 || width<=0){
//Free the cache.
cacheTex.reset(nullptr);
//And cache the new values.
cachedEnabled=enabled;
cachedCaption=caption;
//Finally resize the widget.
if(autoWidth)
width=-1;
}
//Draw fill and borders.
if(draw){
Uint32 color=0xDDDDDDFF;
drawGUIBox(x,y,width,height,renderer,color);
}
//Get the title text and make sure it isn't empty.
const char* lp=caption.c_str();
if(lp!=NULL && lp[0]){
//Update cache if needed.
if(!cacheTex) {
cacheTex = textureFromText(renderer, *fontGUI, lp, objThemes.getTextColor(true));
}
//Draw the text.
if(draw) {
applyTexture(x+(width-textureWidth(*cacheTex))/2, y+6-GUI_FONT_RAISE, *cacheTex, renderer);
}
}
//We now need to draw all the children.
for(unsigned int i=0;i<childControls.size();i++){
childControls[i]->render(renderer,x,y,draw);
}
}
//////////////GUIImage///////////////////////////////////////////////////////////////////
GUIImage::~GUIImage(){
}
bool GUIImage::handleEvents(SDL_Renderer&,int ,int ,bool ,bool ,bool processed){
return processed;
}
void GUIImage::fitToImage(){
const SDL_Rect imageSize = rectFromTexture(*image);
//Increase or decrease the width and height to fully show the image.
if(clip.w!=0) {
width=clip.w;
} else {
width=imageSize.w;
}
if(clip.h!=0) {
height=clip.h;
} else {
height=imageSize.h;
}
}
void GUIImage::render(SDL_Renderer& renderer, int x,int y,bool draw){
//There's no need drawing the widget when it's invisible.
//Also make sure the image isn't null.
if(!visible || !image)
return;
//Get the absolute x and y location.
x+=left;
y+=top;
//Create a clip rectangle.
SDL_Rect r=clip;
//The width and height are capped by the GUIImage itself.
if(r.w>width || r.w==0) {
r.w=width;
}
if(r.h>height || r.h==0) {
r.h=height;
}
const SDL_Rect dstRect={x,y,r.w,r.h};
SDL_RenderCopy(&renderer, image.get(), &r, &dstRect);
}
diff --git a/src/GUIScrollBar.cpp b/src/GUIScrollBar.cpp
index c87fad0..93d395b 100644
--- a/src/GUIScrollBar.cpp
+++ b/src/GUIScrollBar.cpp
@@ -1,391 +1,408 @@
/*
* Copyright (C) 2011-2012 Me and My Shadow
*
* This file is part of Me and My Shadow.
*
* Me and My Shadow is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Me and My Shadow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Me and My Shadow. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Functions.h"
#include "GUIScrollBar.h"
namespace {
const int SCROLLBAR_IMAGE_WIDTH = 16;
const int SCROLLBAR_IMAGE_HEIGHT = 16;
}
using namespace std;
void GUIScrollBar::calcPos(){
//Floats ...
float f,f2;
//The value can't be below the minimum value or above the maximum.
if(value<minValue)
value=minValue;
else if(value>maxValue)
value=maxValue;
//
if(orientation){
f=(float)(top+16);
f2=(float)(height-32);
}else{
f=(float)(left+16);
f2=(float)(width-32);
}
if(largeChange<=0) f2=-1;
if(f2>0){
float f1=0.0f;
valuePerPixel = (maxValue - minValue + largeChange) / f2;
if(valuePerPixel > 0.0001f) f1 = largeChange / valuePerPixel;
if(f1 < 4 && f2 > 4){
valuePerPixel = (maxValue - minValue) / (f2 - 4);
f1 = 4;
}
thumbStart = f + (value - minValue) / valuePerPixel;
thumbEnd = thumbStart + f1;
}else{
valuePerPixel = -1;
thumbStart = f;
thumbEnd = f - 1;
}
}
bool GUIScrollBar::handleEvents(SDL_Renderer&,int x,int y,bool enabled,bool visible,bool processed){
//Boolean if the event is processed.
bool b=processed;
//The GUIObject is only enabled when he and his parent are enabled.
enabled=enabled && this->enabled;
//The GUIObject is only enabled when he and his parent are enabled.
visible=visible && this->visible;
//Check if the mouse button is released.
- if(event.type==SDL_MOUSEBUTTONUP || !(enabled&&visible)){
+ if(event.type==SDL_MOUSEBUTTONUP || !(enabled&&visible) || b){
//It so we have lost any focus at all.
state=0;
}else if(event.type==SDL_MOUSEMOTION || event.type==SDL_MOUSEBUTTONDOWN){
//The mouse button is down and it's moving
int i,j,k,f,f1;
state&=~0xFF;
k=SDL_GetMouseState(&i,&j);
i-=x;
j-=y;
bool bInControl_0;
if(orientation){
f=top;
f1=f+height;
bInControl_0=(i>=left&&i<left+width);
i=j;
}else{
f=left;
f1=f+width;
bInControl_0=(j>=top&&j<top+height);
}
//===
if((state&0x0000FF00)==0x300&&(k&SDL_BUTTON(1))&&event.type==SDL_MOUSEMOTION&&valuePerPixel>0){
//drag thumb
state|=3;
int val = criticalValue + (int)(((float)i - startDragPos) * valuePerPixel + 0.5f);
if(val<minValue) val=minValue;
else if(val>maxValue) val=maxValue;
if(value!=val){
value=val;
changed=true;
}
b=true;
}else if(bInControl_0){
int f2,f3;
if(valuePerPixel > 0){
f2=f+16;
f3=f1-16;
}else{
f2=f3=(f+f1)/2;
}
if(i<f){ //do nothing
}else if(i<f2){ //-smallchange
state=(state&~0xFF)|1;
if(event.type==SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) state=(state&~0x0000FF00)|((state&0xFF)<<8);
else if((state&0x0000FF00)&&((state&0xFF)!=((state>>8)&0xFF))) state&=~0xFF;
if(event.type==SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT){
int val=value-smallChange;
if(val<minValue) val=minValue;
if(value!=val){
value=val;
changed=true;
}
timer=8;
}
b=true;
}else if(i>=f3 && i<f1){ //+smallchange
state=(state&~0xFF)|5;
if(event.type==SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) state=(state&~0x0000FF00)|((state&0xFF)<<8);
else if((state&0x0000FF00)&&((state&0xFF)!=((state>>8)&0xFF))) state&=~0xFF;
if(event.type==SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT){
int val=value+smallChange;
if(val>maxValue) val=maxValue;
if(value!=val){
value=val;
changed=true;
}
timer=8;
}
b=true;
}else if(valuePerPixel<=0){ //do nothing
}else if(i<(int)thumbStart){ //-largechange
state=(state&~0xFF)|2;
if(event.type==SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) state=(state&~0x0000FF00)|((state&0xFF)<<8);
else if((state&0x0000FF00)&&((state&0xFF)!=((state>>8)&0xFF))) state&=~0xFF;
if(event.type==SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT){
int val=value-largeChange;
if(val<minValue) val=minValue;
if(value!=val){
value=val;
changed=true;
}
timer=8;
}
if(state&0xFF) criticalValue = minValue + (int)(float(i - f2) * valuePerPixel + 0.5f);
b=true;
}else if(i<(int)thumbEnd){ //start drag
state=(state&~0xFF)|3;
if(event.type==SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) state=(state&~0x0000FF00)|((state&0xFF)<<8);
else if((state&0x0000FF00)&&((state&0xFF)!=((state>>8)&0xFF))) state&=~0xFF;
if(event.type==SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT){
criticalValue=value;
startDragPos = (float)i;
}
b=true;
}else if(i<f3){ //+largechange
state=(state&~0xFF)|4;
if(event.type==SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) state=(state&~0x0000FF00)|((state&0xFF)<<8);
else if((state&0x0000FF00)&&((state&0xFF)!=((state>>8)&0xFF))) state&=~0xFF;
if(event.type==SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT){
int val=value+largeChange;
if(val>maxValue) val=maxValue;
if(value!=val){
value=val;
changed=true;
}
timer=8;
}
if(state&0xFF) criticalValue = minValue - largeChange + (int)(float(i - f2) * valuePerPixel + 0.5f);
b=true;
}
}
}
-
+
+ //If we are visible, the event is a mouse event, and the mouse is inside the widget, we mark this event as processed.
+ if (visible &&
+ ((event.type == SDL_MOUSEMOTION && event.motion.state == 0)
+ || event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEWHEEL))
+ {
+ //The mouse location (x=i, y=j) and the mouse button (k).
+ int i, j, k;
+ k = SDL_GetMouseState(&i, &j);
+ i -= left;
+ j -= top;
+
+ //Check if the mouse is inside the widget.
+ if (i >= x && i < x + width && j >= y && j < y + height) {
+ b = true;
+ }
+ }
+
return b;
}
void GUIScrollBar::renderScrollBarButton(SDL_Renderer& renderer, int index,int x1,int y1,int x2,int y2,int srcleft,int srctop){
//Make sure the button isn't inverted.
if(x2<=x1||y2<=y1)
return;
{
//The color.
int clr=-1;
//Rectangle the size of the button.
const SDL_Rect r={x1,y1,x2-x1,y2-y1};
//Check
if((state&0xFF)==index){
if(((state>>8)&0xFF)==index){
//Set the color gray.
clr=0xDDDDDDFF;
}else{
//Set the color to lightgray.
clr=0xFFFFFFFF;
}
}
//Draw a box.
drawGUIBox(r.x,r.y,r.w,r.h,renderer,clr);
}
//Boolean if there should be an image on the button.
bool b;
//The check depends on the orientation.
if(orientation)
b=(y2-y1>=14);
else
b=(x2-x1>=14);
//Check if the image can be drawn.
if(b&&srcleft>=0&&srctop>=0){
//It can thus draw it.
const SDL_Rect srcRect={
srcleft,
srctop,
SCROLLBAR_IMAGE_WIDTH,
SCROLLBAR_IMAGE_HEIGHT
};
const SDL_Rect dstRect={
(x1+x2)/2-8,
(y1+y2)/2-8,
SCROLLBAR_IMAGE_WIDTH,
SCROLLBAR_IMAGE_HEIGHT
};
SDL_RenderCopy(&renderer, bmGuiTex.get(), &srcRect, &dstRect);
}
}
void GUIScrollBar::render(SDL_Renderer &renderer, int x, int y, bool draw){
//There's no use in rendering the scrollbar when invisible.
if(!visible)
return;
//Check if the scrollbar is enabled.
if(enabled){
//Check if the state is right.
if((state&0xFF)==((state>>8)&0xFF)){
//Switch the state (change)/
switch(state&0xFF){
case 1:
//It's a small negative change.
//Check if it's time.
if((--timer)<=0){
//Reduce the value.
int val=value-smallChange;
//Make sure it doesn't go too low.
if(val<minValue)
val=minValue;
if(value!=val){
value=val;
changed=true;
}
//Set the time to two.
timer=2;
}
break;
case 2:
//It's a lager negative change.
//Check if it's time.
if((--timer)<=0){
if(value<criticalValue)
state&=~0xFF;
else{
//Reduce the value.
int val=value-largeChange;
//Make sure it doesn't go too low.
if(val<minValue)
val=minValue;
if(value!=val){
value=val;
changed=true;
}
//Set the time to two.
timer=2;
}
}
break;
case 4:
//It's a lager positive change.
//Check if it's time.
if((--timer)<=0){
if(value>criticalValue)
state&=~0xFF;
else{
//Increase the value.
int val=value+largeChange;
//Make sure it doesn't go too high.
if(val>maxValue)
val=maxValue;
if(value!=val){
value=val;
changed=true;
}
//Set the time to two.
timer=2;
}
}
break;
case 5:
//It's a small positive change.
//Check if it's time.
if((--timer)<=0){
//Increase the value.
int val=value+smallChange;
//Make sure ti doesn't go too high.
if(val>maxValue)
val=maxValue;
if(value!=val){
value=val;
changed=true;
}
//Set the time to two.
timer=2;
}
break;
}
}
}
//If the scrollbar changed then invoke a GUIEvent.
if(changed){
if(eventCallback){
GUIEvent e={eventCallback,name,this,GUIEventChange};
GUIEventQueue.push_back(e);
}
changed=false;
}
//We calculate the position since it could have changed.
calcPos();
//Now the actual drawing begins.
if (draw) {
if (orientation){
//The scrollbar is vertically orientated.
if (valuePerPixel > 0){
//There are five buttons so draw them.
renderScrollBarButton(renderer, 1, x + left, y + top, x + left + width, y + top + 16, 80, 0);
renderScrollBarButton(renderer, 2, x + left, y + top + 15, x + left + width, y + (int)thumbStart, -1, -1);
renderScrollBarButton(renderer, 3, x + left, y - 1 + (int)thumbStart, x + left + width, y + 1 + (int)thumbEnd, 0, 16);
renderScrollBarButton(renderer, 4, x + left, y + (int)thumbEnd, x + left + width, y + top + height - 15, -1, -1);
renderScrollBarButton(renderer, 5, x + left, y + top + height - 16, x + left + width, y + top + height, 96, 0);
} else{
//There are two buttons so draw them.
int f = top + height / 2;
renderScrollBarButton(renderer, 1, x + left, y + top, x + left + width, y + 1 + f, 80, 0);
renderScrollBarButton(renderer, 5, x + left, y + f, x + left + width, y + top + height, 96, 0);
}
} else{
//The scrollbar is horizontally orientated.
if (valuePerPixel > 0){
//There are five buttons so draw them.
renderScrollBarButton(renderer, 1, x + left, y + top, x + left + 16, y + top + height, 80, 16);
renderScrollBarButton(renderer, 2, x + left + 15, y + top, x + (int)thumbStart, y + top + height, -1, -1);
renderScrollBarButton(renderer, 3, x - 1 + (int)thumbStart, y + top, x + 1 + (int)thumbEnd, y + top + height, 16, 16);
renderScrollBarButton(renderer, 4, x + (int)thumbEnd, y + top, x + left + width - 15, y + top + height, -1, -1);
renderScrollBarButton(renderer, 5, x + left + width - 16, y + top, x + left + width, y + top + height, 96, 16);
} else{
//There are two buttons so draw them.
int f = left + width / 2;
renderScrollBarButton(renderer, 1, x + left, y + top, x + 1 + f, y + top + height, 80, 16);
renderScrollBarButton(renderer, 5, x + f, y + top, x + left + width, y + top + height, 96, 16);
}
}
}
}
diff --git a/src/GUISlider.cpp b/src/GUISlider.cpp
index 8548f62..6bef17e 100644
--- a/src/GUISlider.cpp
+++ b/src/GUISlider.cpp
@@ -1,276 +1,293 @@
/*
* Copyright (C) 2012 Me and My Shadow
*
* This file is part of Me and My Shadow.
*
* Me and My Shadow is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Me and My Shadow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Me and My Shadow. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Functions.h"
#include "GUISlider.h"
using namespace std;
void GUISlider::calcPos(){
//Floats ...
float f,f2;
//The value can't be below the minimum value or above the maximum.
if(value<minValue)
value=minValue;
else if(value>maxValue)
value=maxValue;
//
f=(float)(left+1);
f2=(float)(width-2);
if(largeChange<=0) f2=-1;
if(f2>0){
float f1=0.0f;
valuePerPixel = (maxValue - minValue + largeChange) / f2;
if(valuePerPixel > 0.0001f) f1 = largeChange / valuePerPixel;
if(f1 < 4 && f2 > 4){
valuePerPixel = (maxValue - minValue) / (f2 - 4);
f1 = 4;
}
thumbStart = f + (value - minValue) / valuePerPixel;
thumbEnd = thumbStart + f1;
}else{
valuePerPixel = -1;
thumbStart = f;
thumbEnd = f - 1;
}
}
bool GUISlider::handleEvents(SDL_Renderer&,int x,int y,bool enabled,bool visible,bool processed){
//Boolean if the event is processed.
bool b=processed;
//The GUIObject is only enabled when he and his parent are enabled.
enabled=enabled && this->enabled;
//The GUIObject is only enabled when he and his parent are enabled.
visible=visible && this->visible;
//Check enabled and visible.
- if (!(enabled && visible)) {
+ if (!(enabled && visible) || b) {
state = 0;
} else if (isKeyboardOnly) {
//Do nothing on keyboard only mode.
} else {
//Check if the mouse button is released.
if (event.type == SDL_MOUSEBUTTONUP){
//It so we have lost any focus at all.
state = 0;
} else if (event.type == SDL_MOUSEMOTION || event.type == SDL_MOUSEBUTTONDOWN){
//The mouse button is down and it's moving
int i, j, k, f, f1;
state &= ~0xFF;
k = SDL_GetMouseState(&i, &j);
i -= x;
j -= y;
bool bInControl_0;
f = left;
f1 = f + width;
bInControl_0 = (j >= top&&j < top + height);
//===
if ((state & 0x0000FF00) == 0x300 && (k&SDL_BUTTON(1)) && event.type == SDL_MOUSEMOTION && valuePerPixel>0){
//drag thumb
state |= 3;
int val = criticalValue + (int)(((float)i - startDragPos) * valuePerPixel + 0.5f);
if (val<minValue) val = minValue;
else if (val>maxValue) val = maxValue;
if (value != val){
value = val;
changed = true;
}
b = true;
} else if (bInControl_0){
if (i < f){ //do nothing
} else if (valuePerPixel <= 0){ //do nothing
} else if (i < (int)thumbStart){ //-largechange
state = (state&~0xFF) | 2;
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) state = (state&~0x0000FF00) | ((state & 0xFF) << 8);
else if ((state & 0x0000FF00) && ((state & 0xFF) != ((state >> 8) & 0xFF))) state &= ~0xFF;
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT){
int val = value - largeChange;
if (val < minValue) val = minValue;
if (value != val){
value = val;
changed = true;
}
timer = 8;
}
if (state & 0xFF) criticalValue = minValue + (int)(float(i - f) * valuePerPixel + 0.5f);
b = true;
} else if (i < (int)thumbEnd){ //start drag
state = (state&~0xFF) | 3;
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) state = (state&~0x0000FF00) | ((state & 0xFF) << 8);
else if ((state & 0x0000FF00) && ((state & 0xFF) != ((state >> 8) & 0xFF))) state &= ~0xFF;
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT){
criticalValue = value;
startDragPos = (float)i;
}
b = true;
} else if (i < f1){ //+largechange
state = (state&~0xFF) | 4;
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) state = (state&~0x0000FF00) | ((state & 0xFF) << 8);
else if ((state & 0x0000FF00) && ((state & 0xFF) != ((state >> 8) & 0xFF))) state &= ~0xFF;
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT){
int val = value + largeChange;
if (val > maxValue) val = maxValue;
if (value != val){
value = val;
changed = true;
}
timer = 8;
}
if (state & 0xFF) criticalValue = minValue - largeChange + (int)(float(i - f) * valuePerPixel + 0.5f);
b = true;
}
}
}
}
-
+
+ //If we are visible, the event is a mouse event, and the mouse is inside the widget, we mark this event as processed.
+ if (visible &&
+ ((event.type == SDL_MOUSEMOTION && event.motion.state == 0)
+ || event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEWHEEL))
+ {
+ //The mouse location (x=i, y=j) and the mouse button (k).
+ int i, j, k;
+ k = SDL_GetMouseState(&i, &j);
+ i -= left;
+ j -= top;
+
+ //Check if the mouse is inside the widget.
+ if (i >= x && i < x + width && j >= y && j < y + height) {
+ b = true;
+ }
+ }
+
return b;
}
void GUISlider::renderScrollBarButton(SDL_Renderer &renderer, int index, int x1, int y1, int x2, int y2, int srcleft, int srctop){
//Make sure the button isn't inverted.
if(x2<=x1||y2<=y1)
return;
//The color.
int clr=-1;
//Rectangle the size of the button.
SDL_Rect r={x1,y1,x2-x1,y2-y1};
//Check
if((state&0xFF)==index){
if(((state>>8)&0xFF)==index){
//Set the color gray.
clr=0xDDDDDDFF;
}else{
//Set the color to lightgray.
clr=0xFFFFFFFF;
}
}
//Draw a box.
drawGUIBox(r.x,r.y,r.w,r.h,renderer,clr);
//Boolean if there should be an image on the button.
const bool b = (x2-x1>=14);
//Check if the image can be drawn.
if(b&&srcleft>=0&&srctop>=0){
//It can thus draw it.
const SDL_Rect srcRect={srcleft,srctop,16,16};
const SDL_Rect dstRect={(x1+x2)/2-8, (y1+y2)/2-8, srcRect.w, srcRect.h};
SDL_RenderCopy(&renderer, bmGuiTex.get(), &srcRect, &dstRect);
}
}
void GUISlider::render(SDL_Renderer &renderer, int x, int y, bool draw){
//There's no use in rendering the scrollbar when invisible.
if(!visible||!draw)
return;
//Draw highlight on keyboard only mode.
if (isKeyboardOnly && state) {
drawGUIBox(x + left, y + top, width, height, renderer, 0xFFFFFF40);
}
//Check if the scrollbar is enabled.
if(enabled){
//Check if the state is right.
if((state&0xFF)==((state>>8)&0xFF)){
//Switch the state (change)/
switch(state&0xFF){
case 2:
//It's a lager negative change.
//Check if it's time.
if((--timer)<=0){
if(value<criticalValue)
state&=~0xFF;
else{
//Reduce the value.
int val=value-largeChange;
//Make sure it doesn't go too low.
if(val<minValue)
val=minValue;
if(value!=val){
value=val;
changed=true;
}
//Set the time to two.
timer=2;
}
}
break;
case 4:
//It's a lager positive change.
//Check if it's time.
if((--timer)<=0){
if(value>criticalValue)
state&=~0xFF;
else{
//Increase the value.
int val=value+largeChange;
//Make sure it doesn't go too high.
if(val>maxValue)
val=maxValue;
if(value!=val){
value=val;
changed=true;
}
//Set the time to two.
timer=2;
}
}
break;
}
}
}
//If the scrollbar changed then invoke a GUIEvent.
if(changed){
if(eventCallback){
GUIEvent e={eventCallback,name,this,GUIEventChange};
GUIEventQueue.push_back(e);
}
changed=false;
}
//We calculate the position since it could have changed.
calcPos();
//Now the actual drawing begins.
if(valuePerPixel>0){
//Draw the line the slider moves along.
drawGUIBox(x+left,y+top+(height-4)/2,width,4,renderer,0);
renderScrollBarButton(renderer,3,x-1+(int)thumbStart,y+top+(height/4),x+1+(int)thumbEnd,y+top+(height/4)*3,16,16);
}else{
//There are two buttons so draw them.
int f=left+width/2;
renderScrollBarButton(renderer,1,x+left,y+top,x+1+f,y+top+height,48,0);
renderScrollBarButton(renderer,5,x+f,y+top,x+left+width,y+top+height,64,0);
}
}
diff --git a/src/GUISpinBox.cpp b/src/GUISpinBox.cpp
index 664125b..bbc185c 100644
--- a/src/GUISpinBox.cpp
+++ b/src/GUISpinBox.cpp
@@ -1,203 +1,208 @@
/*
* Copyright (C) 2011-2012 Me and My Shadow
*
* This file is part of Me and My Shadow.
*
* Me and My Shadow is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Me and My Shadow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Me and My Shadow. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Functions.h"
#include "GUISpinBox.h"
#include "ThemeManager.h"
#include <algorithm>
bool GUISpinBox::handleEvents(SDL_Renderer& renderer,int x,int y,bool enabled,bool visible,bool processed){
//Backup the old state.
int oldState = state;
//First we call the GUITextBox::handleEvents().
bool b0 = GUITextBox::handleEvents(renderer, x, y, enabled, visible, processed);
//Boolean if the event is processed.
bool b=processed;
//The GUIObject is only enabled when he and his parent are enabled.
enabled=enabled && this->enabled;
//The GUIObject is only enabled when he and his parent are enabled.
visible=visible && this->visible;
//Get the absolute position.
x+=left-gravityX;
y+=top;
//Reset "key" to stop contant update of "number" in render().
//If the mouse is still on the button, the "key" will be reassigned later.
key=-1;
//Only check for events when the object is both enabled and visible.
if (enabled&&visible){
//Check if there's a key press and the event hasn't been already processed.
if (state == 2 && event.type == SDL_KEYDOWN && !b) {
if (event.key.keysym.sym == SDLK_UP) {
updateValue(true);
b = true;
} else if (event.key.keysym.sym == SDLK_DOWN) {
updateValue(false);
b = true;
}
}
//Only process mouse event when not in keyboard only mode
- if (!isKeyboardOnly) {
+ if (!isKeyboardOnly &&
+ (event.type == SDL_MOUSEMOTION || event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEWHEEL))
+ {
//The mouse location (x=i, y=j) and the mouse button (k).
int i, j, k;
k = SDL_GetMouseState(&i, &j);
- //Check if the mouse is inside the text box.
- if (i >= x && i < x + width && j >= y && j < y + height){
+ //Check if the mouse is inside the widget and the event hasn't been processed.
+ if (i >= x && i < x + width && j >= y && j < y + height && !b) {
//Check if the mouse is inside the up/down button.
if (i >= x + width - 16) {
//Reset the cursor back to normal.
currentCursor = CURSOR_POINTER;
//Check for a mouse button press.
if (k&SDL_BUTTON(1)){
if (j < y + 17){
//Set the key values correct.
this->key = SDLK_UP;
keyHoldTime = 0;
keyTime = getKeyboardRepeatDelay();
//Update once to prevent a lag.
updateValue(true);
} else{
//Set the key values correct.
this->key = SDLK_DOWN;
keyHoldTime = 0;
keyTime = getKeyboardRepeatDelay();
//Update once to prevent a lag.
updateValue(false);
}
}
}
//Allow mouse wheel to change value.
if (event.type == SDL_MOUSEWHEEL){
if (event.wheel.y > 0){
updateValue(true);
b = true;
} else if (event.wheel.y < 0){
updateValue(false);
b = true;
}
}
+
+ //Event has been processed as long as this is a mouse event and the mouse is inside the widget.
+ b = true;
}
}
//Validate the input when we lost focus.
if (oldState == 2 && state == 0){
update();
}
}
return b || b0;
}
void GUISpinBox::render(SDL_Renderer &renderer, int x, int y, bool draw){
//Call the GUITextBox::render().
GUITextBox::render(renderer, x, y, draw);
//FIXME: Logic in the render method since that is update constant.
if(key!=-1){
//Increase the key time.
keyHoldTime++;
//Make sure the deletionTime isn't to short.
if(keyHoldTime>=keyTime){
keyHoldTime=0;
keyTime = getKeyboardRepeatInterval();
//Now check the which key it was.
switch(key){
case SDLK_UP:
{
updateValue(true);
break;
}
case SDLK_DOWN:
{
updateValue(false);
break;
}
}
}
}
//There's no need drawing when it's invisible.
if(!visible || !draw)
return;
//Get the absolute x and y location.
x+=left;
y+=top;
//Draw arrow buttons.
SDL_Rect srcRect = { 80, 0, 16, 16 };
SDL_Rect dstRect = { x + width - 18, y + 1, srcRect.w, srcRect.h };
SDL_RenderCopy(&renderer, bmGuiTex.get(), &srcRect, &dstRect);
srcRect.x = 96;
dstRect.y += 16;
SDL_RenderCopy(&renderer, bmGuiTex.get(), &srcRect, &dstRect);
}
void GUISpinBox::update(){
//Read number from the caption string.
double number=atof(caption.c_str());
//Stay in the limits.
if(number>limitMax){
number=limitMax;
}else if(number<limitMin){
number=limitMin;
}
//Write the number to the caption string.
char str[128];
sprintf(str,format.c_str(),number);
updateText(str);
}
void GUISpinBox::updateValue(bool positive){
//Read number from the caption string.
double number=atof(caption.c_str());
//Apply change.
if(positive)
number+=change;
else
number-=change;
//Stay in the limits.
if(number>limitMax){
number=limitMax;
}else if(number<limitMin){
number=limitMin;
}
//Write the number to the caption string.
char str[128];
sprintf(str,format.c_str(),number);
updateText(str);
}
diff --git a/src/GUITextArea.cpp b/src/GUITextArea.cpp
index b1b5755..4074325 100644
--- a/src/GUITextArea.cpp
+++ b/src/GUITextArea.cpp
@@ -1,1069 +1,1075 @@
/*
* Copyright (C) 2011-2012 Me and My Shadow
*
* This file is part of Me and My Shadow.
*
* Me and My Shadow is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Me and My Shadow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Me and My Shadow. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Functions.h"
#include "UTF8Functions.h"
#include "GUITextArea.h"
#include "ThemeManager.h"
#include "WordWrapper.h"
#include <cmath>
#include <algorithm>
#include <assert.h>
#include <ctype.h>
#include <SDL_ttf_fontfallback.h>
using namespace std;
#define SPACE_PER_TAB 2
GUITextArea::GUITextArea(ImageManager& imageManager, SDL_Renderer& renderer,int left,int top,int width,int height,bool enabled,bool visible):
GUIObject(imageManager,renderer,left,top,width,height,NULL,-1,enabled,visible),editable(true){
//Set some default values.
state=0;
setFont(fontText);
highlightLineStart=highlightLineEnd=0;
highlightStartX=highlightEndX=0;
highlightStart=highlightEnd=0;
//Add empty text.
lines.push_back("");
linesCache.push_back(nullptr);
//Create scrollbar widget.
scrollBar=new GUIScrollBar(imageManager,renderer,width-16,0,16,height,1,0,0,0);
childControls.push_back(scrollBar);
scrollBarH=new GUIScrollBar(imageManager,renderer,0,height-16,width-16,16,0,0,0,0,100,500,true,false);
childControls.push_back(scrollBarH);
}
void GUITextArea::setFont(TTF_Font* font){
//NOTE: This fuction shouldn't be called after adding items, so no need to update the whole cache.
widgetFont=font;
fontHeight=TTF_FontHeight(font)+1;
}
void GUITextArea::inputText(SDL_Renderer &renderer, const char* s) {
if (s && s[0]) {
//Split into lines.
vector<string> newLines;
newLines.push_back(std::string());
for (int i = 0; s[i]; i++) {
if (s[i] == '\r') continue;
if (s[i] == '\n') {
newLines.push_back(std::string());
continue;
}
if (s[i] == '\t') {
// Replace tabs by spaces.
newLines.back() += std::string(SPACE_PER_TAB, ' ');
continue;
}
newLines.back().push_back(s[i]);
}
const int m = newLines.size();
if (m == 1 && newLines[0].empty()) return;
//Remove selected text.
removeHighlight(renderer);
//Calculate the width of the last line.
int advance = 0;
{
const char* lastLine = newLines[m - 1].c_str();
for (int i = 0;;) {
int a = 0;
int ch = utf8ReadForward(lastLine, i);
if (ch <= 0) break;
TTF_GlyphMetrics(widgetFont, ch, NULL, NULL, NULL, NULL, &a);
advance += a;
}
}
if (m > 1) {
//Multiple lines.
highlightEnd = newLines[m - 1].size();
highlightStartX = highlightEndX = advance;
newLines[m - 1] += lines[highlightLineStart].substr(highlightStart);
lines[highlightLineStart] = lines[highlightLineStart].substr(0, highlightStart) + newLines[0];
lines.insert(lines.begin() + (highlightLineStart + 1), newLines.begin() + 1, newLines.end());
for (int i = 0; i < m - 1; i++) {
linesCache.insert(linesCache.begin() + (highlightLineStart + 1), nullptr);
}
highlightStart = highlightEnd;
} else {
//Single line.
highlightEnd = highlightStart + newLines[0].size();
lines[highlightLineStart].insert(highlightStart, newLines[0]);
highlightStart = highlightEnd;
highlightStartX = highlightEndX = highlightStartX + advance;
}
//Update cache.
highlightLineEnd = highlightLineStart + m - 1;
for (int i = highlightLineStart; i <= highlightLineEnd; i++) {
linesCache[i] = textureFromText(renderer, *widgetFont, lines[i].c_str(), objThemes.getTextColor(true));
}
highlightLineStart = highlightLineEnd;
//Update view if needed.
adjustView();
//If there is an event callback then call it.
if (eventCallback){
GUIEvent e = { eventCallback, name, this, GUIEventChange };
GUIEventQueue.push_back(e);
}
}
}
void GUITextArea::scrollScrollbar(int dx, int dy) {
if (dx && scrollBarH->visible){
scrollBarH->value = clamp(scrollBarH->value + dx, 0, scrollBarH->maxValue);
}
if (dy) {
scrollBar->value = clamp(scrollBar->value + dy, 0, scrollBar->maxValue);
}
}
bool GUITextArea::handleEvents(SDL_Renderer& renderer,int x,int y,bool enabled,bool visible,bool processed){
//Boolean if the event is processed.
bool b=processed;
//The GUIObject is only enabled when he and his parent are enabled.
enabled=enabled && this->enabled;
//The GUIObject is only enabled when he and his parent are enabled.
visible=visible && this->visible;
//Get the absolute position.
x+=left;
y+=top;
- //Update the vertical scrollbar.
- b=b||scrollBar->handleEvents(renderer,x,y,enabled,visible,b);
-
+ //Update the scrollbars.
+ b = b || scrollBar->handleEvents(renderer, x, y, enabled, visible, b);
+ b = b || scrollBarH->handleEvents(renderer, x, y, enabled, visible, b);
+
//NOTE: We don't reset the state to have a "focus" effect.
//Only check for events when the object is both enabled and visible.
if(enabled&&visible){
//Check if there's a key press and the event hasn't been already processed.
if(state==2 && event.type==SDL_KEYDOWN && !b && editable){
if ((event.key.keysym.mod & KMOD_CTRL) == 0) {
//Check if the key is supported.
if (event.key.keysym.sym == SDLK_BACKSPACE){
//Delete one character direct to prevent a lag.
backspaceChar(renderer);
} else if (event.key.keysym.sym == SDLK_DELETE){
//Delete one character direct to prevent a lag.
deleteChar(renderer);
} else if (event.key.keysym.sym == SDLK_RETURN){
removeHighlight(renderer);
//Split the current line and update.
string str2 = lines.at(highlightLineEnd).substr(highlightStart);
lines.at(highlightLineStart) = lines.at(highlightLineStart).substr(0, highlightStart);
linesCache.at(highlightLineStart) =
textureFromText(renderer, *widgetFont, lines.at(highlightLineStart).c_str(), objThemes.getTextColor(true));
//Calculate indentation.
int indent = 0;
for (int i = 0; i < (int)lines.at(highlightLineStart).length(); i++){
if (isspace(lines.at(highlightLineStart)[i]))
indent++;
else
break;
}
str2.insert(0, indent, ' ');
//Add the rest in a new line.
highlightLineStart++;
highlightStart = indent;
highlightEnd = highlightStart;
highlightLineEnd++;
highlightStartX = 0;
for (int i = 0; i < indent; i++){
int advance;
TTF_GlyphMetrics(widgetFont, str2.at(i), NULL, NULL, NULL, NULL, &advance);
highlightStartX += advance;
}
highlightEndX = highlightStartX;
lines.insert(lines.begin() + highlightLineStart, str2);
auto tex = textureFromText(renderer, *widgetFont, str2.c_str(), objThemes.getTextColor(true));
linesCache.insert(linesCache.begin() + highlightLineStart, std::move(tex));
adjustView();
//If there is an event callback then call it.
if (eventCallback){
GUIEvent e = { eventCallback, name, this, GUIEventChange };
GUIEventQueue.push_back(e);
}
} else if (event.key.keysym.sym == SDLK_TAB){
//Calculate the width of a space.
int advance;
TTF_GlyphMetrics(widgetFont, ' ', NULL, NULL, NULL, NULL, &advance);
int start = highlightLineStart, end = highlightLineEnd;
if (start > end) std::swap(start, end);
for (int line = start; line <= end; line++) {
int count = 0;
std::string &s = lines[line];
if (event.key.keysym.mod & KMOD_SHIFT) {
// remove spaces
for (; count < SPACE_PER_TAB; count++) {
if (s.c_str()[count] != ' ') break;
}
if (count > 0) {
s.erase(0, count);
count = -count;
}
} else {
// add spaces
count = SPACE_PER_TAB;
s.insert(0, count, ' ');
}
//Update cache.
if (count) {
linesCache.at(line) = textureFromText(renderer, *widgetFont, s.c_str(), objThemes.getTextColor(true));
}
//Update selection.
if (line == highlightLineStart) {
highlightStart += count;
highlightStartX += count*advance;
if (highlightStart <= 0) {
highlightStart = 0;
highlightStartX = 0;
}
}
if (line == highlightLineEnd) {
highlightEnd += count;
highlightEndX += count*advance;
if (highlightEnd <= 0) {
highlightEnd = 0;
highlightEndX = 0;
}
}
}
adjustView();
} else if (event.key.keysym.sym == SDLK_RIGHT){
//Move the carrot once to prevent a lag.
moveCarrotRight();
} else if (event.key.keysym.sym == SDLK_LEFT){
//Move the carrot once to prevent a lag.
moveCarrotLeft();
} else if (event.key.keysym.sym == SDLK_DOWN){
//Move the carrot once to prevent a lag.
moveCarrotDown();
} else if (event.key.keysym.sym == SDLK_UP){
//Move the carrot once to prevent a lag.
moveCarrotUp();
}
} else {
//Check hotkey.
if (event.key.keysym.sym == SDLK_a) {
//Select all.
highlightLineStart = 0;
highlightStart = 0;
highlightStartX = 0;
highlightLineEnd = lines.size() - 1;
highlightEnd = lines.back().size();
highlightEndX = 0;
if (highlightEnd > 0) {
TTF_SizeUTF8(widgetFont, lines.back().c_str(), &highlightEndX, NULL);
}
} else if (event.key.keysym.sym == SDLK_x || event.key.keysym.sym == SDLK_c) {
//Cut or copy.
int startLine = highlightLineStart, endLine = highlightLineEnd;
int start = highlightStart, end = highlightEnd;
if (startLine > endLine || (startLine == endLine && start > end)) {
std::swap(startLine, endLine);
std::swap(start, end);
}
std::string s;
if (startLine < endLine) {
//Multiple lines.
s = lines[startLine].substr(start);
s.push_back('\n');
for (int i = startLine + 1; i < endLine; i++) {
s += lines[i];
s.push_back('\n');
}
s += lines[endLine].substr(0, end);
} else {
//Single line.
s = lines[startLine].substr(start, end - start);
}
if (!s.empty()) {
SDL_SetClipboardText(s.c_str());
if (event.key.keysym.sym == SDLK_x) {
//Cut.
removeHighlight(renderer);
//If there is an event callback then call it.
if (eventCallback){
GUIEvent e = { eventCallback, name, this, GUIEventChange };
GUIEventQueue.push_back(e);
}
}
}
} else if (event.key.keysym.sym == SDLK_v) {
//Paste.
if (SDL_HasClipboardText()) {
char *s = SDL_GetClipboardText();
inputText(renderer, s);
SDL_free(s);
}
}
}
//The event has been processed.
b=true;
} else if (state == 2 && event.type == SDL_TEXTINPUT && !b && editable){
inputText(renderer, event.text.text);
} else if (state == 2 && event.type == SDL_TEXTEDITING && !b && editable){
// TODO: process SDL_TEXTEDITING event
}
- //The mouse location (x=i, y=j) and the mouse button (k).
- int i,j,k;
- k=SDL_GetMouseState(&i,&j);
-
- //Check if the mouse is inside the GUIObject.
- if(i>=x&&i<x+width&&j>=y&&j<y+height){
- //We can only increase our state. (nothing->hover->focus).
- if(state!=2){
- state=1;
- }
-
- //Check for mouse wheel scrolling.
- //Scroll horizontally if mouse is over the horizontal scrollbar.
- //Otherwise scroll vertically.
- if(event.type==SDL_MOUSEWHEEL && event.wheel.y) {
- if(j>=y+height-16&&scrollBarH->visible){
- scrollScrollbar(event.wheel.y < 0 ? 20 : -20, 0);
- }else{
- scrollScrollbar(0, event.wheel.y < 0 ? 1 : -1);
- }
- }
-
- //When mouse is not over the scrollbar.
- if(i<x+width-16&&j<(scrollBarH->visible?y+height-16:y+height)){
- if (editable) {
- //Update the cursor type.
- currentCursor = CURSOR_CARROT;
-
- if (((event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEBUTTONDOWN) && event.button.button == 1)
- || (event.type == SDL_MOUSEMOTION && (k & SDL_BUTTON(1))))
- {
- //Move carrot to the place clicked.
- const int mouseLine = clamp((int)floor(float(j - y) / float(fontHeight)) + scrollBar->value, 0, lines.size() - 1);
-
- string* str = &lines.at(mouseLine);
- value = str->length();
-
- const int clickX = i - x + scrollBarH->value;
- int finalX = 0;
- int finalPos = str->length();
-
- for (int i = 0;;){
- int advance = 0;
-
- int i0 = i;
- int ch = utf8ReadForward(str->c_str(), i);
- if (ch <= 0) break;
- TTF_GlyphMetrics(widgetFont, ch, NULL, NULL, NULL, NULL, &advance);
- finalX += advance;
-
- if (clickX < finalX - advance / 2){
- finalPos = i0;
- finalX -= advance;
- break;
+ if (event.type == SDL_MOUSEMOTION || event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEWHEEL) {
+ //The mouse location (x=i, y=j) and the mouse button (k).
+ int i, j, k;
+ k = SDL_GetMouseState(&i, &j);
+
+ //Check if the mouse is inside the GUIObject.
+ if (i >= x && i < x + width && j >= y && j < y + height && !b){
+ //We can only increase our state. (nothing->hover->focus).
+ if (state != 2){
+ state = 1;
+ }
+
+ //Check for mouse wheel scrolling.
+ //Scroll horizontally if mouse is over the horizontal scrollbar.
+ //Otherwise scroll vertically.
+ if (event.type == SDL_MOUSEWHEEL && event.wheel.y) {
+ if (j >= y + height - 16 && scrollBarH->visible){
+ scrollScrollbar(event.wheel.y < 0 ? 20 : -20, 0);
+ } else{
+ scrollScrollbar(0, event.wheel.y < 0 ? 1 : -1);
+ }
+ }
+
+ //When mouse is not over the scrollbar.
+ if (i < x + width - 16 && j < (scrollBarH->visible ? y + height - 16 : y + height)){
+ if (editable) {
+ //Update the cursor type.
+ currentCursor = CURSOR_CARROT;
+
+ if (((event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEBUTTONDOWN) && event.button.button == 1)
+ || (event.type == SDL_MOUSEMOTION && (k & SDL_BUTTON(1))))
+ {
+ //Move carrot to the place clicked.
+ const int mouseLine = clamp((int)floor(float(j - y) / float(fontHeight)) + scrollBar->value, 0, lines.size() - 1);
+
+ string* str = &lines.at(mouseLine);
+ value = str->length();
+
+ const int clickX = i - x + scrollBarH->value;
+ int finalX = 0;
+ int finalPos = str->length();
+
+ for (int i = 0;;){
+ int advance = 0;
+
+ int i0 = i;
+ int ch = utf8ReadForward(str->c_str(), i);
+ if (ch <= 0) break;
+ TTF_GlyphMetrics(widgetFont, ch, NULL, NULL, NULL, NULL, &advance);
+ finalX += advance;
+
+ if (clickX < finalX - advance / 2){
+ finalPos = i0;
+ finalX -= advance;
+ break;
+ }
}
- }
- if (event.type == SDL_MOUSEBUTTONUP){
- state = 2;
- highlightEnd = finalPos;
- highlightEndX = finalX;
- highlightLineEnd = mouseLine;
- } else if (event.type == SDL_MOUSEBUTTONDOWN){
- state = 2;
- highlightStart = highlightEnd = finalPos;
- highlightStartX = highlightEndX = finalX;
- highlightLineStart = highlightLineEnd = mouseLine;
- } else if (event.type == SDL_MOUSEMOTION){
- state = 2;
- highlightEnd = finalPos;
- highlightEndX = finalX;
- highlightLineEnd = mouseLine;
+ if (event.type == SDL_MOUSEBUTTONUP){
+ state = 2;
+ highlightEnd = finalPos;
+ highlightEndX = finalX;
+ highlightLineEnd = mouseLine;
+ } else if (event.type == SDL_MOUSEBUTTONDOWN){
+ state = 2;
+ highlightStart = highlightEnd = finalPos;
+ highlightStartX = highlightEndX = finalX;
+ highlightLineStart = highlightLineEnd = mouseLine;
+ } else if (event.type == SDL_MOUSEMOTION){
+ state = 2;
+ highlightEnd = finalPos;
+ highlightEndX = finalX;
+ highlightLineEnd = mouseLine;
+ }
}
- }
- } else {
- const int mouseLine = (int)floor(float(j - y) / float(fontHeight)) + scrollBar->value;
- if (mouseLine >= 0 && mouseLine < (int)hyperlinks.size()) {
- const int clickX = i - x + scrollBarH->value;
- for (const Hyperlink& lnk : hyperlinks[mouseLine]) {
- if (clickX >= lnk.startX && clickX < lnk.endX) {
- currentCursor = CURSOR_POINTING_HAND;
- if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == 1) {
- openWebsite(lnk.url);
+ } else {
+ const int mouseLine = (int)floor(float(j - y) / float(fontHeight)) + scrollBar->value;
+ if (mouseLine >= 0 && mouseLine < (int)hyperlinks.size()) {
+ const int clickX = i - x + scrollBarH->value;
+ for (const Hyperlink& lnk : hyperlinks[mouseLine]) {
+ if (clickX >= lnk.startX && clickX < lnk.endX) {
+ currentCursor = CURSOR_POINTING_HAND;
+ if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == 1) {
+ openWebsite(lnk.url);
+ }
+ break;
}
- break;
}
}
}
}
- }
- }else{
- //The mouse is outside the TextBox.
- //If we don't have focus but only hover we lose it.
- if(state==1){
- state=0;
- }
-
- //If it's a click event outside the textbox then we blur.
- if(event.type==SDL_MOUSEBUTTONUP && event.button.button==SDL_BUTTON_LEFT){
- //Set state to 0.
- state=0;
+
+ //Event has been processed as long as this is a mouse event and the mouse is inside the widget.
+ b = true;
+ } else{
+ //The mouse is outside the TextBox.
+ //If we don't have focus but only hover we lose it.
+ if (state == 1){
+ state = 0;
+ }
+
+ //If it's a click event outside the textbox then we blur.
+ if (event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT){
+ //Set state to 0.
+ state = 0;
+ }
}
}
}
if(!editable)
highlightLineStart=scrollBar->value;
- //Process child controls event except for the scrollbar.
- //That's why i starts at one.
- for(unsigned int i=1;i<childControls.size();i++){
- bool b1=childControls[i]->handleEvents(renderer,x,y,enabled,visible,b);
+ //Process child controls event except for the scrollbars.
+ //That's why i ends at 2.
+ for (int i = childControls.size() - 1; i >= 2; i--) {
+ bool b1 = childControls[i]->handleEvents(renderer, x, y, enabled, visible, b);
//The event is processed when either our or the childs is true (or both).
b=b||b1;
}
return b;
}
void GUITextArea::removeHighlight(SDL_Renderer& renderer){
if (highlightLineStart==highlightLineEnd) {
if (highlightStart == highlightEnd) return;
int start=highlightStart, end=highlightEnd, startx=highlightStartX;
if(highlightStart>highlightEnd){
start=highlightEnd;
end=highlightStart;
startx=highlightEndX;
}
std::string& str=lines.at(highlightLineStart);
str.erase(start,end-start);
highlightStart=highlightEnd=start;
highlightStartX=highlightEndX=startx;
// Update cache.
linesCache.at(highlightLineStart) = textureFromText(renderer,*widgetFont,str.c_str(),objThemes.getTextColor(true));
}else{
int startLine=highlightLineStart, endLine=highlightLineEnd,
start=highlightStart, end=highlightEnd, startx=highlightStartX;
if(startLine>endLine){
startLine=highlightLineEnd;
endLine=highlightLineStart;
start=highlightEnd;
end=highlightStart;
startx=highlightEndX;
}
lines[startLine] = lines[startLine].substr(0, start) + lines[endLine].substr(end);
lines.erase(lines.begin() + startLine + 1, lines.begin() + endLine + 1);
linesCache.erase(linesCache.begin() + startLine + 1, linesCache.begin() + endLine + 1);
highlightLineStart=highlightLineEnd=startLine;
highlightStart=highlightEnd=start;
highlightStartX=highlightEndX=startx;
// Update cache.
linesCache.at(startLine) = textureFromText(renderer, *widgetFont, lines[startLine].c_str(), objThemes.getTextColor(true));
}
adjustView();
}
void GUITextArea::deleteChar(SDL_Renderer& renderer){
if (highlightLineStart==highlightLineEnd && highlightStart==highlightEnd){
if(highlightEnd>=(int)lines.at(highlightLineEnd).length()){
if(highlightLineEnd<(int)lines.size()-1){
highlightLineEnd++;
highlightEnd=0;
}
} else {
utf8ReadForward(lines.at(highlightLineEnd).c_str(), highlightEnd);
}
}
removeHighlight(renderer);
//If there is an event callback.
if(eventCallback){
GUIEvent e={eventCallback,name,this,GUIEventChange};
GUIEventQueue.push_back(e);
}
}
void GUITextArea::backspaceChar(SDL_Renderer& renderer){
if(highlightLineStart==highlightLineEnd && highlightStart==highlightEnd){
if(highlightStart<=0){
if(highlightLineStart==0){
highlightStart=0;
}else{
highlightLineStart--;
highlightStart=lines.at(highlightLineStart).length();
highlightStartX=0;
if (highlightStart > 0) {
TexturePtr& t = linesCache.at(highlightLineStart);
if (t) highlightStartX = textureWidth(*t);
}
}
}else{
int advance = 0;
int ch = utf8ReadBackward(lines.at(highlightLineStart).c_str(), highlightStart);
if (ch > 0) TTF_GlyphMetrics(widgetFont, ch, NULL, NULL, NULL, NULL, &advance);
highlightStartX -= advance;
}
}
removeHighlight(renderer);
//If there is an event callback.
if(eventCallback){
GUIEvent e={eventCallback,name,this,GUIEventChange};
GUIEventQueue.push_back(e);
}
}
void GUITextArea::moveCarrotRight(){
if (highlightEnd>=(int)lines.at(highlightLineEnd).length()){
if (highlightLineEnd<(int)lines.size()-1){
highlightEnd=0;
highlightEndX=0;
highlightLineEnd++;
}
}else{
int advance = 0;
int ch = utf8ReadForward(lines.at(highlightLineEnd).c_str(), highlightEnd);
if (ch > 0) TTF_GlyphMetrics(widgetFont, ch, NULL, NULL, NULL, NULL, &advance);
highlightEndX += advance;
}
if((SDL_GetModState()&KMOD_SHIFT)==0){
highlightLineStart=highlightLineEnd;
highlightStart=highlightEnd;
highlightStartX=highlightEndX;
}
adjustView();
}
void GUITextArea::moveCarrotLeft(){
if (highlightEnd<=0){
if (highlightLineEnd==0){
highlightEnd=0;
}else{
highlightLineEnd--;
highlightEnd=lines.at(highlightLineEnd).length();
highlightEndX=0;
if (highlightEnd > 0) {
TexturePtr& t = linesCache.at(highlightLineEnd);
if (t) highlightEndX = textureWidth(*t);
}
}
}else{
int advance = 0;
int ch = utf8ReadBackward(lines.at(highlightLineEnd).c_str(), highlightEnd);
if (ch > 0) TTF_GlyphMetrics(widgetFont, ch, NULL, NULL, NULL, NULL, &advance);
highlightEndX -= advance;
}
if((SDL_GetModState()&KMOD_SHIFT)==0){
highlightLineStart=highlightLineEnd;
highlightStart=highlightEnd;
highlightStartX=highlightEndX;
}
adjustView();
}
void GUITextArea::moveCarrotUp(){
if(highlightLineEnd==0){
highlightEnd=0;
highlightEndX=0;
}else{
highlightLineEnd--;
const std::string& str=lines.at(highlightLineEnd);
//Find out closest match.
int xPos=0;
int i=0;
for (;;){
int advance = 0;
int i0 = i;
int ch = utf8ReadForward(str.c_str(), i);
if (ch <= 0) break;
TTF_GlyphMetrics(widgetFont, ch, NULL, NULL, NULL, NULL, &advance);
xPos += advance;
if(highlightEndX<xPos-advance/2){
highlightEnd=i=i0;
highlightEndX=xPos-advance;
break;
}
}
if (i == 0) {
highlightEnd = highlightEndX = 0;
} else if (i == str.length()){
highlightEnd=str.length();
highlightEndX=0;
if (highlightEnd > 0) {
TexturePtr& t = linesCache.at(highlightLineEnd);
if (t) highlightEndX = textureWidth(*t);
}
}
}
if((SDL_GetModState()&KMOD_SHIFT)==0){
highlightStart=highlightEnd;
highlightStartX=highlightEndX;
highlightLineStart=highlightLineEnd;
}
adjustView();
}
void GUITextArea::moveCarrotDown(){
if(highlightLineEnd==lines.size()-1){
highlightEnd=lines.at(highlightLineEnd).length();
highlightEndX=0;
if (highlightEnd > 0) {
TexturePtr& t = linesCache.at(highlightLineEnd);
if (t) highlightEndX = textureWidth(*t);
}
}else{
highlightLineEnd++;
string* str=&lines.at(highlightLineEnd);
//Find out closest match.
int xPos=0;
int i = 0;
for (;;){
int advance = 0;
int i0 = i;
int ch = utf8ReadForward(str->c_str(), i);
if (ch <= 0) break;
TTF_GlyphMetrics(widgetFont, ch, NULL, NULL, NULL, NULL, &advance);
xPos += advance;
if (highlightEndX<xPos - advance / 2){
highlightEnd = i = i0;
highlightEndX = xPos - advance;
break;
}
}
if (i == 0) {
highlightEnd = highlightEndX = 0;
} else if (i == str->length()){
highlightEnd=str->length();
highlightEndX=0;
TexturePtr& t = linesCache.at(highlightLineEnd);
if(t) highlightEndX=textureWidth(*t);
}
}
if((SDL_GetModState()&KMOD_SHIFT)==0){
highlightStart=highlightEnd;
highlightStartX=highlightEndX;
highlightLineStart=highlightLineEnd;
}
adjustView();
}
void GUITextArea::adjustView(){
//Adjust view to current line.
if(fontHeight*(highlightLineEnd-scrollBar->value)+4>height-4)
scrollBar->value=highlightLineEnd-3;
else if(highlightLineEnd-scrollBar->value<0)
scrollBar->value=highlightLineEnd;
//Find out the lenght of the longest line.
int maxWidth=0;
for(const TexturePtr& tex: linesCache){
if(tex) {
const int texWidth = textureWidth(*tex.get());
if(texWidth>width-16&&texWidth>maxWidth)
maxWidth=texWidth;
}
}
//We need the horizontal scrollbar if any line is too long.
if(maxWidth>0){
scrollBar->height=height-16;
scrollBarH->visible=true;
scrollBarH->maxValue=maxWidth-width+24;
}else{
scrollBar->height=height;
scrollBarH->visible=false;
scrollBarH->value=0;
scrollBarH->maxValue=0;
}
//Adjust the horizontal view.
int carrotX=0;
for(int n=0;n<highlightEnd;){
int advance = 0;
int ch = utf8ReadForward(lines.at(highlightLineEnd).c_str(), n);
if (ch <= 0) break;
TTF_GlyphMetrics(widgetFont, ch, NULL, NULL, NULL, NULL, &advance);
carrotX += advance;
}
if(carrotX>width-24)
scrollBarH->value=scrollBarH->maxValue;
else
scrollBarH->value=0;
//Update vertical scrollbar.
int rh=height-(scrollBarH->visible?16:0);
int m=lines.size(),n=(int)floor((float)rh/(float)fontHeight);
if(m>n){
scrollBar->maxValue=m-n;
scrollBar->smallChange=1;
scrollBar->largeChange=n;
}else{
scrollBar->value=0;
scrollBar->maxValue=0;
}
}
void GUITextArea::drawHighlight(SDL_Renderer& renderer, int x,int y,SDL_Rect r,SDL_Color color){
if(r.x<x) {
int tmp_w = r.w - x + r.x;
if(tmp_w<=0) return;
r.w = tmp_w;
r.x = x;
}
if(r.x+r.w > x+width){
int tmp_w=width-r.x+x;
if(tmp_w<=0) return;
r.w=tmp_w;
}
if(r.y<y){
int tmp_h=r.h - y + r.y;
if(tmp_h<=0) return;
r.h=tmp_h;
r.y = y;
}
if(r.y+r.h > y+height){
int tmp_h=height-r.y+y;
if(tmp_h<=0) return;
r.h=tmp_h;
}
SDL_SetRenderDrawColor(&renderer, color.r, color.g, color.b, color.a);
SDL_RenderFillRect(&renderer, &r);
}
void GUITextArea::render(SDL_Renderer& renderer, int x,int y,bool draw){
//There's no need drawing the GUIObject when it's invisible.
if(!visible||!draw)
return;
//Get the absolute x and y location.
x+=left;
y+=top;
{
//Draw the box.
const Uint32 color=0xFFFFFFFF;
drawGUIBox(x,y,width,height,renderer,color);
}
//Place the highlighted area.
SDL_Rect r;
const SDL_Color color{128,128,128,255};
if (editable) {
if (highlightLineStart == highlightLineEnd){
r.x = x - scrollBarH->value;
r.y = y + ((highlightLineStart - scrollBar->value)*fontHeight);
r.h = fontHeight;
if (highlightStart < highlightEnd){
r.x += highlightStartX;
r.w = highlightEndX - highlightStartX;
} else{
r.x += highlightEndX;
r.w = highlightStartX - highlightEndX;
}
drawHighlight(renderer, x, y, r, color);
} else if (highlightLineStart < highlightLineEnd){
int lnc = highlightLineEnd - highlightLineStart;
for (int i = 0; i <= lnc; i++){
r.x = x - scrollBarH->value;
r.y = y + ((i + highlightLineStart - scrollBar->value)*fontHeight);
r.w = width + scrollBarH->maxValue;
r.h = fontHeight;
if (i == 0){
r.x += highlightStartX;
r.w -= highlightStartX;
} else if (i == lnc){
r.w = highlightEndX;
}
if (lines.at(i + highlightLineStart).empty()){
r.w = fontHeight / 4;
}
drawHighlight(renderer, x, y, r, color);
}
} else{
int lnc = highlightLineStart - highlightLineEnd;
for (int i = 0; i <= lnc; i++){
r.x = x - scrollBarH->value;
r.y = y + ((i + highlightLineEnd - scrollBar->value)*fontHeight);
r.w = width + scrollBarH->maxValue;
r.h = fontHeight;
if (i == 0){
r.x += highlightEndX;
r.w -= highlightEndX;
} else if (i == lnc){
r.w = highlightStartX;
}
if (lines.at(i + highlightLineEnd).empty()){
r.w = fontHeight / 4;
}
drawHighlight(renderer, x, y, r, color);
}
}
}
//Draw text.
int lineY=0;
for(int line=scrollBar->value;line<(int)linesCache.size();line++){
TexturePtr& it = linesCache[line];
if(it){
if(lineY<height){
SDL_Rect r = { scrollBarH->value, 0, std::min(width - 17, textureWidth(*it.get()) - scrollBarH->value), textureHeight(*it.get()) };
int over=-height+lineY+fontHeight;
if(over>0) r.h-=over;
const SDL_Rect dstRect={x+1,y+1+lineY,r.w,r.h};
if(r.w>0 && r.h>0) SDL_RenderCopy(&renderer,it.get(),&r,&dstRect);
// draw hyperlinks
if (!editable && line<(int)hyperlinks.size()) {
r.y = lineY + fontHeight - 1;
if (r.y < height){
r.y += y + 1;
r.h = 1;
for (const Hyperlink& lnk : hyperlinks[line]) {
r.x = clamp(lnk.startX - scrollBarH->value, 0, width - 17);
r.w = clamp(lnk.endX - scrollBarH->value, 0, width - 17);
if (r.w > r.x) {
r.w -= r.x;
r.x += x + 1;
SDL_SetRenderDrawColor(&renderer, 0, 0, 0, 255);
SDL_RenderFillRect(&renderer, &r);
}
}
}
}
}else{
break;
}
}
lineY+=fontHeight;
}
//Only draw the carrot when focus.
if(state==2&&editable){
r.x=x-scrollBarH->value+highlightEndX;
r.y=y+4+fontHeight*(highlightLineEnd-scrollBar->value);
r.w=2;
r.h=fontHeight-4;
//Make sure that the carrot is inside the textbox.
if((r.y<y+height-4)&&(r.y>y)&&(r.x>x-1)&&(r.x<x+width-16)){
drawHighlight(renderer,x,y,r,SDL_Color{0,0,0,127});
}
}
//We now need to draw all the children of the GUIObject.
for(unsigned int i=0;i<childControls.size();i++){
childControls[i]->render(renderer,x,y,draw);
}
}
void GUITextArea::setString(SDL_Renderer& renderer, const std::string& input, bool wordWrap) {
WordWrapper wrapper;
wrapper.wordWrap = wordWrap;
setString(renderer, input, wrapper);
}
void GUITextArea::setString(SDL_Renderer& renderer, const std::string& input, WordWrapper& wrapper) {
//Clear previous content if any.
//Delete every line.
lines.clear();
linesCache.clear();
//Copy values.
wrapper.maxWidth = width - 16;
wrapper.font = widgetFont;
wrapper.addString(lines, input);
//Render and cache text.
for (const std::string& s : lines) {
linesCache.push_back(textureFromText(renderer, *widgetFont, s.c_str(), objThemes.getTextColor(true)));
}
adjustView();
}
void GUITextArea::setStringArray(SDL_Renderer& renderer, const std::vector<std::string>& input, bool wordWrap) {
WordWrapper wrapper;
wrapper.wordWrap = wordWrap;
setStringArray(renderer, input, wrapper);
}
void GUITextArea::setStringArray(SDL_Renderer& renderer, const std::vector<std::string>& input, WordWrapper& wrapper) {
//Free cached images.
linesCache.clear();
lines.clear();
//Copy values.
wrapper.maxWidth = width - 16;
wrapper.font = widgetFont;
wrapper.addLines(lines, input);
//Render and cache text.
for(const std::string& s: lines) {
linesCache.push_back(textureFromText(renderer,*widgetFont,s.c_str(),objThemes.getTextColor(true)));
}
adjustView();
}
void GUITextArea::setStringArray(SDL_Renderer &renderer, std::vector<SurfacePtr>& surfaces) {
//Free cached images.
linesCache.clear();
lines.clear();
//Copy values.
lines.resize(surfaces.size());
for (SurfacePtr& surface : surfaces) {
linesCache.emplace_back(SDL_CreateTextureFromSurface(&renderer, surface.get()));
}
adjustView();
}
void GUITextArea::extractHyperlinks() {
const int lm = lines.size();
hyperlinks.clear();
if (lm <= 0) return;
hyperlinks.resize(lm);
for (int l = 0; l < lm; l++) {
const char* s = lines[l].c_str();
for (int i = 0, m = lines[l].size(); i < m; i++) {
const int lps = i;
std::string url;
// we only support http or https
if ((s[i] == 'H' || s[i] == 'h')
&& (s[i + 1] == 'T' || s[i + 1] == 't')
&& (s[i + 2] == 'T' || s[i + 2] == 't')
&& (s[i + 3] == 'P' || s[i + 3] == 'p'))
{
if (s[i + 4] == ':' && s[i + 5] == '/' && s[i + 6] == '/') {
// http
i += 7;
url = "http://";
} else if ((s[i + 4] == 'S' || s[i + 4] == 's') && s[i + 5] == ':' && s[i + 6] == '/' && s[i + 7] == '/') {
// https
i += 8;
url = "https://";
} else {
continue;
}
for (; i < m; i++) {
char c = s[i];
// url ends with following character
if (c == '\0' || c == ' ' || c == ')' || c == ']' || c == '}' || c == '>' || c == '\r' || c == '\n' || c == '\t') {
break;
}
url.push_back(c);
}
} else {
continue;
}
const int lpe = i;
Hyperlink hyperlink = {};
TTF_SizeUTF8(widgetFont, lines[l].substr(0, lps).c_str(), &hyperlink.startX, NULL);
TTF_SizeUTF8(widgetFont, lines[l].substr(0, lpe).c_str(), &hyperlink.endX, NULL);
hyperlink.url = lines[l].substr(lps, lpe - lps);
hyperlinks[l].push_back(hyperlink);
}
}
}
string GUITextArea::getString(){
string tmp;
for(vector<string>::iterator it=lines.begin();it!=lines.end();++it){
//Append a newline only if not the first line.
if(it!=lines.begin())
tmp.append(1,'\n');
//Append the line.
tmp.append(*it);
}
return tmp;
}
void GUITextArea::onResize(){
scrollBar->left=width-16;
scrollBar->height=height;
if(scrollBarH->visible)
scrollBar->height-=16;
scrollBarH->top=height-16;
scrollBarH->width=width-16;
adjustView();
}
diff --git a/src/GUIWindow.cpp b/src/GUIWindow.cpp
index e74a26f..85552fc 100644
--- a/src/GUIWindow.cpp
+++ b/src/GUIWindow.cpp
@@ -1,340 +1,356 @@
/*
* Copyright (C) 2012 Me and My Shadow
*
* This file is part of Me and My Shadow.
*
* Me and My Shadow is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Me and My Shadow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Me and My Shadow. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Functions.h"
#include "GUIWindow.h"
#include "ThemeManager.h"
using namespace std;
GUIWindow::GUIWindow(ImageManager& imageManager,SDL_Renderer& renderer,int left,int top,int width,int height,bool enabled,bool visible,const char* caption):
GUIObject(imageManager,renderer,left,top,width,height,caption,-1,enabled,visible){
//Set some default values.
inDialog = true;
dragging=false;
resizing=false;
minWidth=minHeight=0;
maxWidth=maxHeight=0;
this->caption = textureFromText(renderer, *fontGUI, caption, objThemes.getTextColor(true));
}
bool GUIWindow::handleEvents(SDL_Renderer& renderer,int x,int y,bool enabled,bool visible,bool processed){
//Boolean if the event is processed.
bool b=processed;
//The GUIObject is only enabled when he and his parent are enabled.
enabled=enabled && this->enabled;
//The GUIObject is only enabled when he and his parent are enabled.
visible=visible && this->visible;
//Get the absolute position.
x+=left;
y+=top;
//NOTE: We don't reset the state to have a "focus" effect.
//Only check for events when the object is both enabled and visible.
- if(enabled&&visible){
+ if(enabled && visible && !b){
//Check if the titlebar is hit.
bool clicked=(event.type==SDL_MOUSEBUTTONDOWN && event.button.button==SDL_BUTTON_LEFT);
//Check if the mouse is inside the window.
SDL_Rect mouse={event.button.x,event.button.y,0,0};
SDL_Rect titlebar={x,y+5,width,43}; //We have a resize edge at the top five pixels.
//FIXME: Only set the cursor to POINTER when moving away from the GUIWindow?
if(clicked && pointOnRect(mouse,titlebar)){
//Mouse pressed inside the window,so assume dragging
dragging=true;
}
//Check for resizing.
SDL_Rect edge={x,y,width,5};
//Check each edge only if not resizing.
//NOTE: This is done to preserve the resize cursor type when off the edge.
bool topEdge=resizing?(resizeDirection==GUIResizeTop || resizeDirection==GUIResizeTopLeft || resizeDirection==GUIResizeTopRight):pointOnRect(mouse,edge);
edge.x=x+width-5;
edge.w=5;
edge.h=height;
bool rightEdge=resizing?(resizeDirection==GUIResizeRight || resizeDirection==GUIResizeTopRight || resizeDirection==GUIResizeBottomRight):pointOnRect(mouse,edge);
edge.x=x;
edge.y=y+height-5;
edge.w=width;
edge.h=5;
bool bottomEdge=resizing?(resizeDirection==GUIResizeBottom || resizeDirection==GUIResizeBottomLeft || resizeDirection==GUIResizeBottomRight):pointOnRect(mouse,edge);
edge.y=y;
edge.w=5;
edge.h=height;
bool leftEdge=resizing?(resizeDirection==GUIResizeLeft || resizeDirection==GUIResizeTopLeft || resizeDirection==GUIResizeBottomLeft):pointOnRect(mouse,edge);
//Set resizing true when resizing previously of clicking on a edge.
if(topEdge || rightEdge || bottomEdge || leftEdge)
resizing=resizing?true:clicked;
//Determine the resize direction.
if(topEdge){
resizeDirection=GUIResizeTop;
currentCursor=CURSOR_SIZE_VER;
//Check if there's an additional horizontal edge (corner).
if(leftEdge){
currentCursor=CURSOR_SIZE_FDIAG;
resizeDirection=GUIResizeTopLeft;
}else if(rightEdge){
currentCursor=CURSOR_SIZE_BDIAG;
resizeDirection=GUIResizeTopRight;
}
}else if(bottomEdge){
resizeDirection=GUIResizeBottom;
currentCursor=CURSOR_SIZE_VER;
//Check if there's an additional horizontal edge (corner).
if(leftEdge){
currentCursor=CURSOR_SIZE_BDIAG;
resizeDirection=GUIResizeBottomLeft;
}else if(rightEdge){
currentCursor=CURSOR_SIZE_FDIAG;
resizeDirection=GUIResizeBottomRight;
}
}else if(leftEdge){
resizeDirection=GUIResizeLeft;
currentCursor=CURSOR_SIZE_HOR;
}else if(rightEdge){
resizeDirection=GUIResizeRight;
currentCursor=CURSOR_SIZE_HOR;
}
if(event.type==SDL_MOUSEBUTTONUP && event.button.button==SDL_BUTTON_LEFT){
//Stop dragging
dragging=false;
SDL_Rect mouse={event.button.x,event.button.y,0,0};
//Check if close button clicked
{
SDL_Rect r={left+width-36,top+12,24,24};
if(pointOnRect(mouse,r)){
this->visible=false;
//And we add a close event to the queue.
GUIEvent e={eventCallback,name,this,GUIEventClick};
GUIEventQueue.push_back(e);
}
}
}else if(event.type==SDL_MOUSEMOTION){
if((event.motion.state & SDL_BUTTON_LMASK)==0){
//Stop dragging or resizing.
dragging=false;
resizing=false;
}else if(dragging){
move(left+event.motion.xrel,top+event.motion.yrel);
}else if(resizing){
//Check what the resize direction is.
switch(resizeDirection){
case GUIResizeTop:
resize(left,top+event.motion.yrel,width,height-event.motion.yrel);
break;
case GUIResizeTopRight:
resize(left,top+event.motion.yrel,width+event.motion.xrel,height-event.motion.yrel);
break;
case GUIResizeRight:
resize(left,top,width+event.motion.xrel,height);
break;
case GUIResizeBottomRight:
resize(left,top,width+event.motion.xrel,height+event.motion.yrel);
break;
case GUIResizeBottom:
resize(left,top,width,height+event.motion.yrel);
break;
case GUIResizeBottomLeft:
resize(left+event.motion.xrel,top,width-event.motion.xrel,height+event.motion.yrel);
break;
case GUIResizeLeft:
resize(left+event.motion.xrel,top,width-event.motion.xrel,height);
break;
case GUIResizeTopLeft:
resize(left+event.motion.xrel,top+event.motion.yrel,width-event.motion.xrel,height-event.motion.yrel);
break;
}
}
}
//Also update the cursor type accordingly.
if(dragging)
currentCursor=CURSOR_DRAG;
}
//Process child controls event.
- for(unsigned int i=0;i<childControls.size();i++){
- bool b1=childControls[i]->handleEvents(renderer,x,y,enabled,visible,b);
+ for (int i = childControls.size() - 1; i >= 0; i--) {
+ bool b1 = childControls[i]->handleEvents(renderer, x, y, enabled, visible, b);
//The event is processed when either our or the childs is true (or both).
b=b||b1;
}
+
+ //If we are visible, the event is a mouse event, and the mouse is inside the widget, we mark this event as processed.
+ if (visible &&
+ ((event.type == SDL_MOUSEMOTION && event.motion.state == 0)
+ || event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEWHEEL))
+ {
+ //The mouse location (x=i, y=j) and the mouse button (k).
+ int i, j, k;
+ k = SDL_GetMouseState(&i, &j);
+
+ //Check if the mouse is inside the widget.
+ if (i >= x && i < x + width && j >= y && j < y + height) {
+ b = true;
+ }
+ }
+
return b;
}
void GUIWindow::move(int x,int y){
//Check the horizontal bounds.
if(x>SCREEN_WIDTH-width)
x=SCREEN_WIDTH-width;
else if(x<0)
x=0;
//Check the vertical bounds.
if(y>SCREEN_HEIGHT-height)
y=SCREEN_HEIGHT-height;
else if(y<0)
y=0;
//And set the new position.
left=x;
top=y;
}
static inline int resizeBorder(int coord, int oldWidth, int newWidth, int gravity) {
switch (gravity) {
default:
return coord;
break;
case GUIGravityCenter:
return coord + newWidth / 2 - oldWidth / 2;
break;
case GUIGravityRight:
return coord + newWidth - oldWidth;
break;
}
}
void GUIWindow::resize(int x,int y,int width,int height){
//FIXME: In case of resizing to the left or top the window moves when the maximum size has been reached.
//Check for the minimum width.
if(minWidth){
if(width<minWidth)
width=minWidth;
}
//Check for the minimum height.
if(minHeight){
if(height<minHeight)
height=minHeight;
}
//Check for maximum width.
if(maxWidth){
if(width>maxWidth)
width=maxWidth;
}
//Check for maximum height.
if(maxHeight){
if(height>maxHeight)
height=maxHeight;
}
//Resize child widgets.
for (auto obj : childControls) {
int widgetLeft = obj->left;
int widgetTop = obj->top;
int widgetRight = widgetLeft + obj->width;
int widgetBottom = widgetTop + obj->height;
widgetLeft = resizeBorder(widgetLeft, this->width, width, obj->gravityLeft);
widgetTop = resizeBorder(widgetTop, this->height, height, obj->gravityTop);
widgetRight = resizeBorder(widgetRight, this->width, width, obj->gravityRight);
widgetBottom = resizeBorder(widgetBottom, this->height, height, obj->gravityBottom);
obj->left = widgetLeft;
obj->top = widgetTop;
int newWidth = widgetRight - widgetLeft;
int newHeight = widgetBottom - widgetTop;
if (newWidth != obj->width || newHeight != obj->height) {
obj->width = newWidth;
obj->height = newHeight;
obj->onResize();
}
}
//Now set the values.
this->left=x;
this->top=y;
this->width=width;
this->height=height;
//And we add a resize event to the queue.
GUIEvent e={eventCallback,name,this,GUIEventChange};
GUIEventQueue.push_back(e);
}
void GUIWindow::render(SDL_Renderer& renderer,int x,int y,bool draw){
//Rectangle the size of the GUIObject, used to draw borders.
//SDL_Rect r; //Unused local variable :/
//There's no need drawing the GUIObject when it's invisible.
if(!visible||!draw)
return;
//Get the absolute x and y location.
x+=left;
y+=top;
//Draw the frame.
Uint32 color=0xFFFFFFFF;
drawGUIBox(x,y,width,height,renderer,color);
//Draw the titlebar.
color=0x00000033;
drawGUIBox(x,y,width,48,renderer,color);
//Get the mouse position.
int mouseX,mouseY;
SDL_GetMouseState(&mouseX,&mouseY);
SDL_Rect mouse={mouseX,mouseY,0,0};
//Draw the close button.
{
//check highlight
const SDL_Rect r={left+width-36,top+12,24,24};
if(pointOnRect(mouse,r)){
drawGUIBox(r.x,r.y,r.w,r.h,renderer,0x999999FFU);
}
const SDL_Rect srcRect={112,0,16,16};
const SDL_Rect dstRect={left+width-32, top+16, 16, 16};
SDL_RenderCopy(&renderer, bmGuiTex.get(), &srcRect, &dstRect);
}
//Draw the caption.
{
const SDL_Rect captionSize = rectFromTexture(*caption);
const SDL_Rect captionRect={6,8,width-16,32};
applyTexture(x+captionRect.x+(captionRect.w-captionSize.w)/2,
y+captionRect.y+(captionRect.h-captionSize.h)/2,
caption,
renderer);
}
//We now need to draw all the children of the GUIObject.
for(unsigned int i=0;i<childControls.size();i++){
childControls[i]->render(renderer,x,y,draw);
}
}
void GUIWindow::GUIEventCallback_OnEvent(ImageManager& imageManager,SDL_Renderer& renderer,string name,GUIObject* obj,int eventType){
//Check if we have a eventCallback.
if(eventCallback){
//We call the onEvent method of the callback, but change the GUIObject pointer to ourself.
eventCallback->GUIEventCallback_OnEvent(imageManager,renderer,name,this,eventType);
}
}

File Metadata

Mime Type
text/x-diff
Expires
Mon, May 11, 2:55 PM (5 d, 10 m ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
62774
Default Alt Text
(132 KB)

Event Timeline