1 // Copyright (c) 2013- PPSSPP Project.
2 
3 // This program is free software: you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License as published by
5 // the Free Software Foundation, version 2.0 or later versions.
6 
7 // This program is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10 // GNU General Public License 2.0 for more details.
11 
12 // A copy of the GPL 2.0 should have been included with the program.
13 // If not, see http://www.gnu.org/licenses/
14 
15 // Official git repository and contact information can be found at
16 // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
17 
18 #include <algorithm>
19 #include <vector>
20 
21 #include "Common/Data/Color/RGBAUtil.h"
22 #include "Common/Render/DrawBuffer.h"
23 #include "Common/Data/Text/I18n.h"
24 #include "Common/Math/math_util.h"
25 #include "Common/UI/Context.h"
26 
27 #include "Common/Common.h"
28 #include "Common/Log.h"
29 #include "Core/Config.h"
30 #include "Core/System.h"
31 #include "UI/GamepadEmu.h"
32 #include "UI/TouchControlLayoutScreen.h"
33 #include "UI/TouchControlVisibilityScreen.h"
34 
35 static float layoutAreaScale = 1.0f;
36 
GetButtonColor()37 static u32 GetButtonColor() {
38 	return g_Config.iTouchButtonStyle != 0 ? 0xFFFFFF : 0xc0b080;
39 }
40 
41 class DragDropButton : public MultiTouchButton {
42 public:
DragDropButton(ConfigTouchPos & pos,const char * key,ImageID bgImg,ImageID img,const Bounds & screenBounds)43 	DragDropButton(ConfigTouchPos &pos, const char *key, ImageID bgImg, ImageID img, const Bounds &screenBounds)
44 	: MultiTouchButton(key, bgImg, bgImg, img, pos.scale, new UI::AnchorLayoutParams(pos.x * screenBounds.w, pos.y * screenBounds.h, UI::NONE, UI::NONE, true)),
45 		x_(pos.x), y_(pos.y), theScale_(pos.scale), screenBounds_(screenBounds) {
46 		scale_ = theScale_;
47 	}
48 
IsDown()49 	bool IsDown() override {
50 		// Don't want the button to enlarge and throw the user's perspective
51 		// of button size off whack.
52 		return false;
53 	};
54 
Draw(UIContext & dc)55 	void Draw(UIContext &dc) override {
56 		scale_ = theScale_*layoutAreaScale; // Scale down just for rendering
57 		dc.PushScissor(screenBounds_);
58 		MultiTouchButton::Draw(dc);
59 		dc.PopScissor();
60 		scale_ = theScale_/layoutAreaScale; // is this is needed?
61 	}
62 
SavePosition()63 	virtual void SavePosition() {
64 		x_ = (bounds_.centerX() - screenBounds_.x) / screenBounds_.w;
65 		y_ = (bounds_.centerY() - screenBounds_.y) / screenBounds_.h;
66 		scale_ = theScale_;
67 	}
68 
GetScale() const69 	virtual float GetScale() const { return theScale_; }
SetScale(float s)70 	virtual void SetScale(float s) { theScale_ = s; scale_ = s; }
71 
GetSpacing() const72 	virtual float GetSpacing() const { return 1.0f; }
SetSpacing(float s)73 	virtual void SetSpacing(float s) { }
74 
Contains(float x,float y)75 	virtual bool Contains(float x, float y) {
76 		const float thresholdFactor = 0.25f;
77 		const float thresholdW = thresholdFactor * bounds_.w;
78 		const float thresholdH = thresholdFactor * bounds_.h;
79 
80 		Bounds tolerantBounds(bounds_.x - thresholdW * 0.5, bounds_.y - thresholdH * 0.5 , bounds_.w + thresholdW, bounds_.h + thresholdH);
81 		return tolerantBounds.Contains(x, y);
82 	}
83 
84 protected:
GetButtonOpacity()85 	float GetButtonOpacity() override {
86 		float opacity = g_Config.iTouchButtonOpacity / 100.0f;
87 		return std::max(0.5f, opacity);
88 	}
89 	const Bounds &screenBounds_;
90 	float &theScale_;
91 	float &x_, &y_;
92 };
93 
94 class PSPActionButtons : public DragDropButton {
95 public:
PSPActionButtons(ConfigTouchPos & pos,const char * key,float & spacing,const Bounds & screenBounds)96 	PSPActionButtons(ConfigTouchPos &pos, const char *key, float &spacing, const Bounds &screenBounds)
97 		: DragDropButton(pos, key, ImageID::invalid(), ImageID::invalid(), screenBounds), spacing_(spacing) {
98 		using namespace UI;
99 		roundId_ = g_Config.iTouchButtonStyle ? ImageID("I_ROUND_LINE") : ImageID("I_ROUND");
100 	};
101 
setCircleVisibility(bool visible)102 	void setCircleVisibility(bool visible) {
103 		circleVisible_ = visible;
104 	}
105 
setCrossVisibility(bool visible)106 	void setCrossVisibility(bool visible) {
107 		crossVisible_ = visible;
108 	}
109 
setTriangleVisibility(bool visible)110 	void setTriangleVisibility(bool visible) {
111 		triangleVisible_ = visible;
112 	}
113 
setSquareVisibility(bool visible)114 	void setSquareVisibility(bool visible) {
115 		squareVisible_ = visible;
116 	}
117 
Draw(UIContext & dc)118 	void Draw(UIContext &dc) override {
119 		scale_ = theScale_*layoutAreaScale;
120 		dc.PushScissor(screenBounds_);
121 		uint32_t colorBg = colorAlpha(GetButtonColor(), GetButtonOpacity());
122 		uint32_t color = colorAlpha(0xFFFFFF, GetButtonOpacity());
123 
124 		int centerX = bounds_.centerX();
125 		int centerY = bounds_.centerY();
126 
127 		float spacing = spacing_ * baseActionButtonSpacing * layoutAreaScale;
128 		if (circleVisible_) {
129 			dc.Draw()->DrawImageRotated(roundId_, centerX + spacing, centerY, scale_, 0, colorBg, false);
130 			dc.Draw()->DrawImageRotated(circleId_,  centerX + spacing, centerY, scale_, 0, color, false);
131 		}
132 
133 		if (crossVisible_) {
134 			dc.Draw()->DrawImageRotated(roundId_, centerX, centerY + spacing, scale_, 0, colorBg, false);
135 			dc.Draw()->DrawImageRotated(crossId_, centerX, centerY + spacing, scale_, 0, color, false);
136 		}
137 
138 		if (triangleVisible_) {
139 			float y = centerY - spacing;
140 			y -= 2.8f * scale_;
141 			dc.Draw()->DrawImageRotated(roundId_, centerX, centerY - spacing, scale_, 0, colorBg, false);
142 			dc.Draw()->DrawImageRotated(triangleId_, centerX, y, scale_, 0, color, false);
143 		}
144 
145 		if (squareVisible_) {
146 			dc.Draw()->DrawImageRotated(roundId_, centerX - spacing, centerY, scale_, 0, colorBg, false);
147 			dc.Draw()->DrawImageRotated(squareId_, centerX - spacing, centerY, scale_, 0, color, false);
148 		}
149 		dc.PopScissor();
150 		scale_ = theScale_/layoutAreaScale;
151 	};
152 
GetContentDimensions(const UIContext & dc,float & w,float & h) const153 	void GetContentDimensions(const UIContext &dc, float &w, float &h) const override {
154 		const AtlasImage *image = dc.Draw()->GetAtlas()->getImage(roundId_);
155 
156 		w = (2.0f * baseActionButtonSpacing * spacing_) + image->w * scale_;
157 		h = (2.0f * baseActionButtonSpacing * spacing_) + image->h * scale_;
158 	}
159 
GetSpacing() const160 	float GetSpacing() const override { return spacing_; }
SetSpacing(float s)161 	void SetSpacing(float s) override { spacing_ = s; }
162 
Contains(float x,float y)163 	bool Contains(float x, float y) override {
164 		float xFac = 0.0f;
165 		float wFac = 0.0f;
166 		float yFac = 0.0f;
167 		float hFac = 0.0f;
168 
169 		// Many cases sadly...
170 		if (circleVisible_ && !squareVisible_) {
171 			if (crossVisible_ || triangleVisible_) {
172 				xFac = 1.0f;
173 				wFac = -1.0f;
174 			} else {
175 				xFac = 2.0f;
176 				wFac = -2.0f;
177 				yFac = 1.0f;
178 				hFac = -2.0f;
179 			}
180 		} else if (!circleVisible_ && squareVisible_) {
181 			if (crossVisible_ || triangleVisible_) {
182 				wFac = -1.0f;
183 			} else {
184 				wFac = -2.0f;
185 				yFac = 1.0f;
186 				hFac = -2.0f;
187 			}
188 		} else if (circleVisible_ && squareVisible_ && !crossVisible_ && !triangleVisible_) {
189 			yFac = 1.0f;
190 			hFac = -2.0f;
191 		}
192 
193 		// No else here is intentional
194 		if (crossVisible_ && !triangleVisible_) {
195 			if (circleVisible_ || squareVisible_) {
196 				yFac = 1.0f;
197 				hFac = -1.0f;
198 			} else {
199 				yFac = 2.0f;
200 				hFac = -2.0f;
201 				xFac = 1.0f;
202 				wFac = -2.0f;
203 			}
204 		} else if (!crossVisible_ && triangleVisible_) {
205 			if (circleVisible_ || squareVisible_) {
206 				hFac = -1.0f;
207 			} else {
208 				hFac = -2.0f;
209 				xFac = 1.0f;
210 				wFac = -2.0f;
211 			}
212 		} else if (!circleVisible_ && !squareVisible_ && crossVisible_ && triangleVisible_) {
213 			xFac = 1.0f;
214 			wFac = -2.0f;
215 		}
216 
217 		const float thresholdFactor = 0.25f;
218 		const float thresholdW = thresholdFactor * bounds_.w;
219 		const float thresholdH = thresholdFactor * bounds_.h;
220 
221 		float tolerantX = bounds_.x - thresholdW*0.5 + xFac*baseActionButtonSpacing*spacing_;
222 		float tolerantY = bounds_.y - thresholdH*0.5 + yFac*baseActionButtonSpacing*spacing_;
223 		float tolerantW = bounds_.w + thresholdW + wFac*baseActionButtonSpacing*spacing_;
224 		float tolerantH = bounds_.h + thresholdH + hFac*baseActionButtonSpacing*spacing_;
225 
226 		Bounds tolerantBounds(tolerantX, tolerantY, tolerantW, tolerantH);
227 		return tolerantBounds.Contains(x, y);
228 	}
229 
230 private:
231 	bool circleVisible_ = true, crossVisible_ = true, triangleVisible_ = true, squareVisible_ = true;
232 
233 	ImageID roundId_ = ImageID::invalid();
234 	ImageID circleId_ = ImageID("I_CIRCLE");
235 	ImageID crossId_ = ImageID("I_CROSS");
236 	ImageID triangleId_ = ImageID("I_TRIANGLE");
237 	ImageID squareId_ = ImageID("I_SQUARE");
238 
239 	float &spacing_;
240 };
241 
242 class PSPDPadButtons : public DragDropButton {
243 public:
PSPDPadButtons(ConfigTouchPos & pos,const char * key,float & spacing,const Bounds & screenBounds)244 	PSPDPadButtons(ConfigTouchPos &pos, const char *key, float &spacing, const Bounds &screenBounds)
245 		: DragDropButton(pos, key, ImageID::invalid(), ImageID::invalid(), screenBounds), spacing_(spacing) {
246 	}
247 
Draw(UIContext & dc)248 	void Draw(UIContext &dc) override {
249 		scale_ = theScale_*layoutAreaScale;
250 		dc.PushScissor(screenBounds_);
251 		uint32_t colorBg = colorAlpha(GetButtonColor(), GetButtonOpacity());
252 		uint32_t color = colorAlpha(0xFFFFFF, GetButtonOpacity());
253 
254 		static const float xoff[4] = {1, 0, -1, 0};
255 		static const float yoff[4] = {0, 1, 0, -1};
256 
257 		ImageID dirImage = g_Config.iTouchButtonStyle ? ImageID("I_DIR_LINE") : ImageID("I_DIR");
258 
259 		for (int i = 0; i < 4; i++) {
260 			float r = D_pad_Radius * spacing_ * layoutAreaScale;
261 			float x = bounds_.centerX() + xoff[i] * r;
262 			float y = bounds_.centerY() + yoff[i] * r;
263 			float x2 = bounds_.centerX() + xoff[i] * (r + 10.f * scale_);
264 			float y2 = bounds_.centerY() + yoff[i] * (r + 10.f * scale_);
265 			float angle = i * M_PI / 2;
266 
267 			dc.Draw()->DrawImageRotated(dirImage, x, y, scale_, angle + PI, colorBg, false);
268 			dc.Draw()->DrawImageRotated(ImageID("I_ARROW"), x2, y2, scale_, angle + PI, color);
269 		}
270 		dc.PopScissor();
271 		scale_ = theScale_/layoutAreaScale;
272 	}
273 
GetContentDimensions(const UIContext & dc,float & w,float & h) const274 	void GetContentDimensions(const UIContext &dc, float &w, float &h) const override {
275 		const AtlasImage *image = dc.Draw()->GetAtlas()->getImage(ImageID("I_DIR"));
276 		w = 2 * D_pad_Radius * spacing_ + image->w * scale_;
277 		h = 2 * D_pad_Radius * spacing_ + image->h * scale_;
278 	};
279 
GetSpacing() const280 	float GetSpacing() const override { return spacing_; }
SetSpacing(float s)281 	void SetSpacing(float s) override { spacing_ = s; }
282 
283 private:
284 	float &spacing_;
285 };
286 
287 class PSPStickDragDrop : public DragDropButton {
288 public:
PSPStickDragDrop(ConfigTouchPos & pos,const char * key,ImageID bgImg,ImageID img,const Bounds & screenBounds,float & spacing)289 	PSPStickDragDrop(ConfigTouchPos &pos, const char *key, ImageID bgImg, ImageID img, const Bounds &screenBounds, float &spacing)
290 		: DragDropButton(pos, key, bgImg, img, screenBounds), spacing_(spacing) {
291 	}
292 
Draw(UIContext & dc)293 	void Draw(UIContext &dc) override {
294 		uint32_t colorBg = colorAlpha(GetButtonColor(), GetButtonOpacity());
295 		uint32_t downBg = colorAlpha(0x00FFFFFF, GetButtonOpacity() * 0.5f);
296 
297 		const ImageID stickImage = g_Config.iTouchButtonStyle ? ImageID("I_STICK_LINE") : ImageID("I_STICK");
298 		const ImageID stickBg = g_Config.iTouchButtonStyle ? ImageID("I_STICK_BG_LINE") : ImageID("I_STICK_BG");
299 
300 		dc.Draw()->DrawImage(stickBg, bounds_.centerX(), bounds_.centerY(), scale_, colorBg, ALIGN_CENTER);
301 		dc.Draw()->DrawImage(stickImage, bounds_.centerX(), bounds_.centerY(), scale_ * spacing_, colorBg, ALIGN_CENTER);
302 	}
303 
GetSpacing() const304 	float GetSpacing() const override { return spacing_; }
SetSpacing(float s)305 	void SetSpacing(float s) override {
306 		// In mapping spacing is clamped between 0.5 and 3.0 and passed to this method
307 		spacing_ = s/3;
308 	}
309 
310 private:
311 	float &spacing_;
312 };
313 
314 class SnapGrid : public UI::View {
315 public:
SnapGrid(int leftMargin,int rightMargin,int topMargin,int bottomMargin,u32 color)316 	SnapGrid(int leftMargin, int rightMargin, int topMargin, int bottomMargin, u32 color) {
317 		x1 = leftMargin;
318 		x2 = rightMargin;
319 		y1 = topMargin;
320 		y2 = bottomMargin;
321 		col = color;
322 	}
323 
Draw(UIContext & dc)324 	void Draw(UIContext &dc) override {
325 		if (g_Config.bTouchSnapToGrid) {
326 			dc.Flush();
327 			dc.BeginNoTex();
328 			float xOffset = bounds_.x;
329 			float yOffset = bounds_.y;
330 			for (int x = x1; x < x2; x += g_Config.iTouchSnapGridSize)
331 				dc.Draw()->vLine(x + xOffset, y1 + yOffset, y2 + yOffset, col);
332 			for (int y = y1; y < y2; y += g_Config.iTouchSnapGridSize)
333 				dc.Draw()->hLine(x1 + xOffset, y + yOffset, x2 + xOffset, col);
334 			dc.Flush();
335 			dc.Begin();
336 		}
337 	}
338 
DescribeText() const339 	std::string DescribeText() const override {
340 		return "";
341 	}
342 
343 private:
344 	int x1, x2, y1, y2;
345 	u32 col;
346 };
347 
348 class DragDropButton;
349 
350 class ControlLayoutView : public UI::AnchorLayout {
351 public:
ControlLayoutView(UI::LayoutParams * layoutParams)352 	explicit ControlLayoutView(UI::LayoutParams *layoutParams)
353 		: UI::AnchorLayout(layoutParams) {
354 	}
355 
356 	void Touch(const TouchInput &input) override;
357 	void CreateViews();
HasCreatedViews() const358 	bool HasCreatedViews() const {
359 		return !controls_.empty();
360 	}
361 
362 	DragDropButton *pickedControl_ = nullptr;
363 	DragDropButton *getPickedControl(const int x, const int y);
364 	std::vector<DragDropButton *> controls_;
365 
366 	// Touch down state for dragging
367 	float startObjectX_ = -1.0f;
368 	float startObjectY_ = -1.0f;
369 	float startDragX_ = -1.0f;
370 	float startDragY_ = -1.0f;
371 	float startScale_ = -1.0f;
372 	float startSpacing_ = -1.0f;
373 
374 	int mode_ = 0;
375 };
376 
ClampTo(const Point & p,const Bounds & b)377 static Point ClampTo(const Point &p, const Bounds &b) {
378 	return Point(clamp_value(p.x, b.x, b.x + b.w), clamp_value(p.y, b.y, b.y + b.h));
379 }
380 
Touch(const TouchInput & touch)381 void ControlLayoutView::Touch(const TouchInput &touch) {
382 	using namespace UI;
383 
384 	if ((touch.flags & TOUCH_MOVE) && pickedControl_ != nullptr) {
385 		if (mode_ == 0) {
386 			const Bounds &controlBounds = pickedControl_->GetBounds();
387 
388 			// Allow placing the control halfway outside the play area.
389 			Bounds validRange = this->GetBounds();
390 			// Control coordinates are relative inside the bounds.
391 			validRange.x = 0.0f;
392 			validRange.y = 0.0f;
393 
394 			// This make cure the controll is all inside the screen (commended out only half)
395 			//validRange.x += controlBounds.w * 0.5f;
396 			//validRange.w -= controlBounds.w;
397 			//validRange.y += controlBounds.h * 0.5f;
398 			//validRange.h -= controlBounds.h;
399 
400 			Point newPos;
401 			newPos.x = startObjectX_ + (touch.x - startDragX_);
402 			newPos.y = startObjectY_ + (touch.y - startDragY_);
403 			if (g_Config.bTouchSnapToGrid) {
404 				newPos.x -= fmod(newPos.x - controlBounds.w, g_Config.iTouchSnapGridSize);
405 				newPos.y -= fmod(newPos.y - controlBounds.h, g_Config.iTouchSnapGridSize);
406 			}
407 
408 			newPos = ClampTo(newPos, validRange);
409 			pickedControl_->ReplaceLayoutParams(new AnchorLayoutParams(newPos.x, newPos.y, NONE, NONE, true));
410 		} else if (mode_ == 1) {
411 			// Resize. Vertical = scaling, horizontal = spacing;
412 			// Up should be bigger so let's negate in that direction
413 			float diffX = (touch.x - startDragX_);
414 			float diffY = -(touch.y - startDragY_);
415 
416 			// Snap to grid
417 			if (g_Config.bTouchSnapToGrid) {
418 				diffX -= fmod(touch.x - startDragX_, g_Config.iTouchSnapGridSize/2);
419 				diffY += fmod(touch.y - startDragY_, g_Config.iTouchSnapGridSize/2);
420 			}
421 			float movementScale = 0.02f;
422 			float newScale = startScale_ + diffY * movementScale;
423 			float newSpacing = startSpacing_ + diffX * movementScale;
424 			if (newScale > 3.0f) newScale = 3.0f;
425 			if (newScale < 0.5f) newScale = 0.5f;
426 			if (newSpacing > 3.0f) newSpacing = 3.0f;
427 			if (newSpacing < 0.5f) newSpacing = 0.5f;
428 			pickedControl_->SetSpacing(newSpacing);
429 			pickedControl_->SetScale(newScale);
430 		}
431 	}
432 	if ((touch.flags & TOUCH_DOWN) && pickedControl_ == 0) {
433 		pickedControl_ = getPickedControl(touch.x, touch.y);
434 		if (pickedControl_) {
435 			startDragX_ = touch.x;
436 			startDragY_ = touch.y;
437 			const auto &prevParams = pickedControl_->GetLayoutParams()->As<AnchorLayoutParams>();
438 			startObjectX_ = prevParams->left;
439 			startObjectY_ = prevParams->top;
440 
441 			startSpacing_ = pickedControl_->GetSpacing();
442 			startScale_ = pickedControl_->GetScale();
443 		}
444 	}
445 	if ((touch.flags & TOUCH_UP) && pickedControl_ != 0) {
446 		pickedControl_->SavePosition();
447 		pickedControl_ = 0;
448 	}
449 }
450 
CreateViews()451 void ControlLayoutView::CreateViews() {
452 	using namespace CustomKey;
453 	const Bounds &bounds = GetBounds();
454 	if (bounds.w == 0.0f || bounds.h == 0.0f) {
455 		// Layout hasn't happened yet, return.
456 		// See comment in TouchControlLayoutScreen::update().
457 		return;
458 	}
459 
460 	// Create all the views.
461 
462 	if (g_Config.bShowTouchCircle || g_Config.bShowTouchCross || g_Config.bShowTouchTriangle || g_Config.bShowTouchSquare) {
463 		PSPActionButtons *actionButtons = new PSPActionButtons(g_Config.touchActionButtonCenter, "Action buttons", g_Config.fActionButtonSpacing, bounds);
464 		actionButtons->setCircleVisibility(g_Config.bShowTouchCircle);
465 		actionButtons->setCrossVisibility(g_Config.bShowTouchCross);
466 		actionButtons->setTriangleVisibility(g_Config.bShowTouchTriangle);
467 		actionButtons->setSquareVisibility(g_Config.bShowTouchSquare);
468 		controls_.push_back(actionButtons);
469 	}
470 
471 	ImageID rectImage = g_Config.iTouchButtonStyle ? ImageID("I_RECT_LINE") : ImageID("I_RECT");
472 	ImageID shoulderImage = g_Config.iTouchButtonStyle ? ImageID("I_SHOULDER_LINE") : ImageID("I_SHOULDER");
473 	ImageID stickImage = g_Config.iTouchButtonStyle ? ImageID("I_STICK_LINE") : ImageID("I_STICK");
474 	ImageID stickBg = g_Config.iTouchButtonStyle ? ImageID("I_STICK_BG_LINE") : ImageID("I_STICK_BG");
475 	ImageID roundImage = g_Config.iTouchButtonStyle ? ImageID("I_ROUND_LINE") : ImageID("I_ROUND");
476 
477 	auto addDragDropButton = [&](ConfigTouchPos &pos, const char *key, ImageID bgImg, ImageID img) {
478 		DragDropButton *b = nullptr;
479 		if (pos.show) {
480 			b = new DragDropButton(pos, key, bgImg, img, bounds);
481 			controls_.push_back(b);
482 		}
483 		return b;
484 	};
485 
486 	if (g_Config.touchDpad.show) {
487 		controls_.push_back(new PSPDPadButtons(g_Config.touchDpad, "D-pad", g_Config.fDpadSpacing, bounds));
488 	}
489 
490 	addDragDropButton(g_Config.touchSelectKey, "Select button", rectImage, ImageID("I_SELECT"));
491 	addDragDropButton(g_Config.touchStartKey, "Start button", rectImage, ImageID("I_START"));
492 
493 	if (auto *fastForward = addDragDropButton(g_Config.touchFastForwardKey, "Fast-forward button", rectImage, ImageID("I_ARROW"))) {
494 		fastForward->SetAngle(180.0f);
495 	}
496 	addDragDropButton(g_Config.touchLKey, "Left shoulder button", shoulderImage, ImageID("I_L"));
497 	if (auto *rbutton = addDragDropButton(g_Config.touchRKey, "Right shoulder button", shoulderImage, ImageID("I_R"))) {
498 		rbutton->FlipImageH(true);
499 	}
500 
501 	if (g_Config.touchAnalogStick.show) {
502 		controls_.push_back(new PSPStickDragDrop(g_Config.touchAnalogStick, "Left analog stick", stickBg, stickImage, bounds, g_Config.fLeftStickHeadScale));
503 	}
504 	if (g_Config.touchRightAnalogStick.show) {
505 		controls_.push_back(new PSPStickDragDrop(g_Config.touchRightAnalogStick, "Right analog stick", stickBg, stickImage, bounds, g_Config.fRightStickHeadScale));
506 	}
507 
508 	auto addDragComboKey = [&](ConfigTouchPos &pos, const char *key, const ConfigCustomButton& cfg) {
509 		DragDropButton *b = nullptr;
510 		if (pos.show) {
511 			b = new DragDropButton(pos, key, g_Config.iTouchButtonStyle == 0 ? comboKeyShapes[cfg.shape].i : comboKeyShapes[cfg.shape].l, comboKeyImages[cfg.image].i, bounds);
512 			b->FlipImageH(comboKeyShapes[cfg.shape].f);
513 			b->SetAngle(comboKeyImages[cfg.image].r, comboKeyShapes[cfg.shape].r);
514 			controls_.push_back(b);
515 		}
516 		return b;
517 	};
518 	addDragComboKey(g_Config.touchCombo0, "Custom 1 button", g_Config.CustomKey0);
519 	addDragComboKey(g_Config.touchCombo1, "Custom 2 button", g_Config.CustomKey1);
520 	addDragComboKey(g_Config.touchCombo2, "Custom 3 button", g_Config.CustomKey2);
521 	addDragComboKey(g_Config.touchCombo3, "Custom 4 button", g_Config.CustomKey3);
522 	addDragComboKey(g_Config.touchCombo4, "Custom 5 button", g_Config.CustomKey4);
523 	addDragComboKey(g_Config.touchCombo5, "Custom 6 button", g_Config.CustomKey5);
524 	addDragComboKey(g_Config.touchCombo6, "Custom 7 button", g_Config.CustomKey6);
525 	addDragComboKey(g_Config.touchCombo7, "Custom 8 button", g_Config.CustomKey7);
526 	addDragComboKey(g_Config.touchCombo8, "Custom 9 button", g_Config.CustomKey8);
527 	addDragComboKey(g_Config.touchCombo9, "Custom 10 button", g_Config.CustomKey9);
528 
529 	for (size_t i = 0; i < controls_.size(); i++) {
530 		Add(controls_[i]);
531 	}
532 
533 	Add(new SnapGrid(0, bounds.w, 0, bounds.h, 0x3FFFFFFF));
534 }
535 
536 // return the control which was picked up by the touchEvent. If a control
537 // was already picked up, then it's being dragged around, so just return that instead
getPickedControl(const int x,const int y)538 DragDropButton *ControlLayoutView::getPickedControl(const int x, const int y) {
539 	if (pickedControl_ != 0) {
540 		return pickedControl_;
541 	}
542 
543 	DragDropButton *bestMatch = nullptr;
544 	float bestDistance;
545 	for (size_t i = 0; i < controls_.size(); i++) {
546 		DragDropButton *control = controls_[i];
547 		if (control->Contains(x, y)) {
548 			const Bounds &bounds = control->GetBounds();
549 			float distance = (bounds.centerX()-x)*(bounds.centerX()-x)+(bounds.centerY()-y)*(bounds.centerY()-y);
550 			if (!bestMatch || distance < bestDistance) {
551 				bestDistance = distance;
552 				bestMatch = control;
553 			}
554 		}
555 	}
556 
557 	return bestMatch;
558 }
559 
TouchControlLayoutScreen()560 TouchControlLayoutScreen::TouchControlLayoutScreen() {}
561 
resized()562 void TouchControlLayoutScreen::resized() {
563 	RecreateViews();
564 }
565 
onFinish(DialogResult reason)566 void TouchControlLayoutScreen::onFinish(DialogResult reason) {
567 	g_Config.Save("TouchControlLayoutScreen::onFinish");
568 }
569 
OnVisibility(UI::EventParams & e)570 UI::EventReturn TouchControlLayoutScreen::OnVisibility(UI::EventParams &e) {
571 	screenManager()->push(new TouchControlVisibilityScreen());
572 	return UI::EVENT_DONE;
573 }
574 
OnReset(UI::EventParams & e)575 UI::EventReturn TouchControlLayoutScreen::OnReset(UI::EventParams &e) {
576 	INFO_LOG(G3D, "Resetting touch control layout");
577 	g_Config.ResetControlLayout();
578 	const Bounds &bounds = screenManager()->getUIContext()->GetBounds();
579 	InitPadLayout(bounds.w, bounds.h);
580 	RecreateViews();
581 	return UI::EVENT_DONE;
582 };
583 
dialogFinished(const Screen * dialog,DialogResult result)584 void TouchControlLayoutScreen::dialogFinished(const Screen *dialog, DialogResult result) {
585 	RecreateViews();
586 }
587 
OnMode(UI::EventParams & e)588 UI::EventReturn TouchControlLayoutScreen::OnMode(UI::EventParams &e) {
589 	int mode = mode_->GetSelection();
590 	if (layoutView_) {
591 		layoutView_->mode_ = mode;
592 	}
593 	return UI::EVENT_DONE;
594 }
595 
update()596 void TouchControlLayoutScreen::update() {
597 	UIDialogScreenWithBackground::update();
598 
599 	// TODO: We really, really need a cleaner solution for creating sub-views
600 	// of custom compound controls.
601 	if (layoutView_) {
602 		if (!layoutView_->HasCreatedViews()) {
603 			layoutView_->CreateViews();
604 		}
605 	}
606 }
607 
CreateViews()608 void TouchControlLayoutScreen::CreateViews() {
609 	using namespace UI;
610 
611 	// setup g_Config for button layout
612 	const Bounds &bounds = screenManager()->getUIContext()->GetBounds();
613 	InitPadLayout(bounds.w, bounds.h);
614 
615 	const float leftColumnWidth = 170.0f;
616 	layoutAreaScale = 1.0-(leftColumnWidth+10)/bounds.w;
617 
618 	auto co = GetI18NCategory("Controls");
619 	auto di = GetI18NCategory("Dialog");
620 
621 	root_ = new AnchorLayout(new LayoutParams(FILL_PARENT, FILL_PARENT));
622 
623 	ScrollView *leftColumnScroll = root_->Add(new ScrollView(ORIENT_VERTICAL, new AnchorLayoutParams(leftColumnWidth, WRAP_CONTENT, 10, NONE, NONE, 10)));
624 	LinearLayout *leftColumn = leftColumnScroll->Add(new LinearLayout(ORIENT_VERTICAL));
625 
626 	mode_ = new ChoiceStrip(ORIENT_VERTICAL);
627 	mode_->AddChoice(di->T("Move"));
628 	mode_->AddChoice(di->T("Resize"));
629 	mode_->SetSelection(0, false);
630 	mode_->OnChoice.Handle(this, &TouchControlLayoutScreen::OnMode);
631 
632 	CheckBox *snap = new CheckBox(&g_Config.bTouchSnapToGrid, di->T("Snap"));
633 	PopupSliderChoice *gridSize = new PopupSliderChoice(&g_Config.iTouchSnapGridSize, 2, 256, di->T("Grid"), screenManager(), "", new AnchorLayoutParams(leftColumnWidth, WRAP_CONTENT, 10, NONE, NONE, 158));
634 	gridSize->SetEnabledPtr(&g_Config.bTouchSnapToGrid);
635 
636 	leftColumn->Add(mode_);
637 	leftColumn->Add(new Choice(co->T("Customize")))->OnClick.Handle(this, &TouchControlLayoutScreen::OnVisibility);
638 	leftColumn->Add(snap);
639 	leftColumn->Add(gridSize);
640 	leftColumn->Add(new Choice(di->T("Reset")))->OnClick.Handle(this, &TouchControlLayoutScreen::OnReset);
641 	leftColumn->Add(new Choice(di->T("Back")))->OnClick.Handle<UIScreen>(this, &UIScreen::OnBack);
642 
643 	root_->Add(new BorderView(BORDER_BOTTOM, BorderStyle::ITEM_DOWN_BG, 4.0f, new AnchorLayoutParams(leftColumnWidth + 10, bounds.h * (1.0f - layoutAreaScale), 0.0f, NONE, false)));
644 	root_->Add(new BorderView(BORDER_RIGHT, BorderStyle::ITEM_DOWN_BG, 4.0f, new AnchorLayoutParams(leftColumnWidth + 10, 0.0f, NONE, 0.0f, false)));
645 	layoutView_ = root_->Add(new ControlLayoutView(new AnchorLayoutParams(leftColumnWidth + 10, bounds.h * (1.0 - layoutAreaScale), 0.0f, 0.0f, false)));
646 }
647