Browse Source

Merge pull request #523 from AtomicGameEngine/JME-ATOMIC-518

Update TB formatting
JoshEngebretson 10 years ago
parent
commit
421d3479d2
100 changed files with 9865 additions and 9865 deletions
  1. 97 97
      Source/ThirdParty/TurboBadger/animation/tb_animation.cpp
  2. 91 91
      Source/ThirdParty/TurboBadger/animation/tb_animation.h
  3. 130 130
      Source/ThirdParty/TurboBadger/animation/tb_widget_animation.cpp
  4. 57 57
      Source/ThirdParty/TurboBadger/animation/tb_widget_animation.h
  5. 76 76
      Source/ThirdParty/TurboBadger/image/tb_image_manager.cpp
  6. 46 46
      Source/ThirdParty/TurboBadger/image/tb_image_manager.h
  7. 3 3
      Source/ThirdParty/TurboBadger/image/tb_image_widget.cpp
  8. 11 11
      Source/ThirdParty/TurboBadger/image/tb_image_widget.h
  9. 369 369
      Source/ThirdParty/TurboBadger/parser/tb_parser.cpp
  10. 28 28
      Source/ThirdParty/TurboBadger/parser/tb_parser.h
  11. 157 157
      Source/ThirdParty/TurboBadger/renderers/tb_renderer_batcher.cpp
  12. 70 70
      Source/ThirdParty/TurboBadger/renderers/tb_renderer_batcher.h
  13. 21 21
      Source/ThirdParty/TurboBadger/tb_addon.cpp
  14. 23 23
      Source/ThirdParty/TurboBadger/tb_addon.h
  15. 418 418
      Source/ThirdParty/TurboBadger/tb_bitmap_fragment.cpp
  16. 160 160
      Source/ThirdParty/TurboBadger/tb_bitmap_fragment.h
  17. 47 47
      Source/ThirdParty/TurboBadger/tb_clipboard_win.cpp
  18. 11 11
      Source/ThirdParty/TurboBadger/tb_color.cpp
  19. 10 10
      Source/ThirdParty/TurboBadger/tb_color.h
  20. 14 14
      Source/ThirdParty/TurboBadger/tb_config.h
  21. 17 17
      Source/ThirdParty/TurboBadger/tb_core.cpp
  22. 168 168
      Source/ThirdParty/TurboBadger/tb_debug.cpp
  23. 22 22
      Source/ThirdParty/TurboBadger/tb_debug.h
  24. 48 48
      Source/ThirdParty/TurboBadger/tb_dimension.cpp
  25. 38 38
      Source/ThirdParty/TurboBadger/tb_dimension.h
  26. 151 151
      Source/ThirdParty/TurboBadger/tb_editfield.h
  27. 6 6
      Source/ThirdParty/TurboBadger/tb_file_posix.cpp
  28. 40 40
      Source/ThirdParty/TurboBadger/tb_font_desc.h
  29. 349 349
      Source/ThirdParty/TurboBadger/tb_font_renderer.cpp
  30. 157 157
      Source/ThirdParty/TurboBadger/tb_font_renderer.h
  31. 122 122
      Source/ThirdParty/TurboBadger/tb_font_renderer_freetype.cpp
  32. 61 61
      Source/ThirdParty/TurboBadger/tb_font_renderer_stb.cpp
  33. 209 209
      Source/ThirdParty/TurboBadger/tb_font_renderer_tbbf.cpp
  34. 148 148
      Source/ThirdParty/TurboBadger/tb_geometry.cpp
  35. 64 64
      Source/ThirdParty/TurboBadger/tb_geometry.h
  36. 11 11
      Source/ThirdParty/TurboBadger/tb_hash.cpp
  37. 3 3
      Source/ThirdParty/TurboBadger/tb_hash.h
  38. 141 141
      Source/ThirdParty/TurboBadger/tb_hashtable.cpp
  39. 53 53
      Source/ThirdParty/TurboBadger/tb_hashtable.h
  40. 43 43
      Source/ThirdParty/TurboBadger/tb_id.cpp
  41. 17 17
      Source/ThirdParty/TurboBadger/tb_id.h
  42. 48 48
      Source/ThirdParty/TurboBadger/tb_image_loader_stb.cpp
  43. 60 60
      Source/ThirdParty/TurboBadger/tb_inline_select.cpp
  44. 18 18
      Source/ThirdParty/TurboBadger/tb_inline_select.h
  45. 27 27
      Source/ThirdParty/TurboBadger/tb_language.cpp
  46. 19 19
      Source/ThirdParty/TurboBadger/tb_language.h
  47. 382 382
      Source/ThirdParty/TurboBadger/tb_layout.cpp
  48. 99 99
      Source/ThirdParty/TurboBadger/tb_layout.h
  49. 133 133
      Source/ThirdParty/TurboBadger/tb_linklist.cpp
  50. 101 101
      Source/ThirdParty/TurboBadger/tb_linklist.h
  51. 61 61
      Source/ThirdParty/TurboBadger/tb_list.cpp
  52. 74 74
      Source/ThirdParty/TurboBadger/tb_list.h
  53. 29 29
      Source/ThirdParty/TurboBadger/tb_menu_window.cpp
  54. 11 11
      Source/ThirdParty/TurboBadger/tb_menu_window.h
  55. 99 99
      Source/ThirdParty/TurboBadger/tb_message_window.cpp
  56. 27 27
      Source/ThirdParty/TurboBadger/tb_message_window.h
  57. 112 112
      Source/ThirdParty/TurboBadger/tb_msg.cpp
  58. 60 60
      Source/ThirdParty/TurboBadger/tb_msg.h
  59. 122 122
      Source/ThirdParty/TurboBadger/tb_node_ref_tree.cpp
  60. 46 46
      Source/ThirdParty/TurboBadger/tb_node_ref_tree.h
  61. 232 232
      Source/ThirdParty/TurboBadger/tb_node_tree.cpp
  62. 88 88
      Source/ThirdParty/TurboBadger/tb_node_tree.h
  63. 21 21
      Source/ThirdParty/TurboBadger/tb_object.h
  64. 84 84
      Source/ThirdParty/TurboBadger/tb_popup_window.cpp
  65. 51 51
      Source/ThirdParty/TurboBadger/tb_popup_window.h
  66. 6 6
      Source/ThirdParty/TurboBadger/tb_renderer.cpp
  67. 109 109
      Source/ThirdParty/TurboBadger/tb_renderer.h
  68. 221 221
      Source/ThirdParty/TurboBadger/tb_scroll_container.cpp
  69. 52 52
      Source/ThirdParty/TurboBadger/tb_scroll_container.h
  70. 267 267
      Source/ThirdParty/TurboBadger/tb_scroller.cpp
  71. 76 76
      Source/ThirdParty/TurboBadger/tb_scroller.h
  72. 294 294
      Source/ThirdParty/TurboBadger/tb_select.cpp
  73. 109 109
      Source/ThirdParty/TurboBadger/tb_select.h
  74. 124 124
      Source/ThirdParty/TurboBadger/tb_select_item.cpp
  75. 132 132
      Source/ThirdParty/TurboBadger/tb_select_item.h
  76. 629 629
      Source/ThirdParty/TurboBadger/tb_skin.cpp
  77. 289 289
      Source/ThirdParty/TurboBadger/tb_skin.h
  78. 32 32
      Source/ThirdParty/TurboBadger/tb_skin_util.cpp
  79. 4 4
      Source/ThirdParty/TurboBadger/tb_skin_util.h
  80. 8 8
      Source/ThirdParty/TurboBadger/tb_sort.h
  81. 93 93
      Source/ThirdParty/TurboBadger/tb_str.cpp
  82. 31 31
      Source/ThirdParty/TurboBadger/tb_str.h
  83. 458 458
      Source/ThirdParty/TurboBadger/tb_style_edit.cpp
  84. 296 296
      Source/ThirdParty/TurboBadger/tb_style_edit.h
  85. 38 38
      Source/ThirdParty/TurboBadger/tb_style_edit_content.cpp
  86. 29 29
      Source/ThirdParty/TurboBadger/tb_style_edit_content.h
  87. 31 31
      Source/ThirdParty/TurboBadger/tb_system.h
  88. 42 42
      Source/ThirdParty/TurboBadger/tb_system_android.cpp
  89. 9 9
      Source/ThirdParty/TurboBadger/tb_system_linux.cpp
  90. 13 13
      Source/ThirdParty/TurboBadger/tb_system_win.cpp
  91. 80 80
      Source/ThirdParty/TurboBadger/tb_tab_container.cpp
  92. 37 37
      Source/ThirdParty/TurboBadger/tb_tab_container.h
  93. 56 56
      Source/ThirdParty/TurboBadger/tb_tempbuffer.cpp
  94. 50 50
      Source/ThirdParty/TurboBadger/tb_tempbuffer.h
  95. 78 78
      Source/ThirdParty/TurboBadger/tb_toggle_container.cpp
  96. 65 65
      Source/ThirdParty/TurboBadger/tb_toggle_container.h
  97. 14 14
      Source/ThirdParty/TurboBadger/tb_types.h
  98. 221 221
      Source/ThirdParty/TurboBadger/tb_value.cpp
  99. 102 102
      Source/ThirdParty/TurboBadger/tb_value.h
  100. 59 59
      Source/ThirdParty/TurboBadger/tb_widget_skin_condition_context.cpp

+ 97 - 97
Source/ThirdParty/TurboBadger/animation/tb_animation.cpp

@@ -14,44 +14,44 @@ namespace tb {
 
 static float sc(float x)
 {
-	float s = x < 0 ? -1.f : 1.f;
-	x = ABS(x);
-	if (x >= 1)
-		return s;
-	return s * (x < 0 ? x / 0.5f : (x / (1 + x * x)) / 0.5f);
+    float s = x < 0 ? -1.f : 1.f;
+    x = ABS(x);
+    if (x >= 1)
+        return s;
+    return s * (x < 0 ? x / 0.5f : (x / (1 + x * x)) / 0.5f);
 }
 
 static float SmoothCurve(float x, float a)
 {
-	float r = a * x / (2 * a * x - a - x + 1);
-	r = (r - 0.5f) * 2;
-	return sc(r) * 0.5f + 0.5f;
+    float r = a * x / (2 * a * x - a - x + 1);
+    r = (r - 0.5f) * 2;
+    return sc(r) * 0.5f + 0.5f;
 }
 
 // == TBAnimationObject ===============================================
 
 void TBAnimationObject::InvokeOnAnimationStart()
 {
-	TBLinkListOf<TBAnimationListener>::Iterator li = m_listeners.IterateForward();
-	OnAnimationStart();
-	while (TBAnimationListener *listener = li.GetAndStep())
-		listener->OnAnimationStart(this);
+    TBLinkListOf<TBAnimationListener>::Iterator li = m_listeners.IterateForward();
+    OnAnimationStart();
+    while (TBAnimationListener *listener = li.GetAndStep())
+        listener->OnAnimationStart(this);
 }
 
 void TBAnimationObject::InvokeOnAnimationUpdate(float progress)
 {
-	TBLinkListOf<TBAnimationListener>::Iterator li = m_listeners.IterateForward();
-	OnAnimationUpdate(progress);
-	while (TBAnimationListener *listener = li.GetAndStep())
-		listener->OnAnimationUpdate(this, progress);
+    TBLinkListOf<TBAnimationListener>::Iterator li = m_listeners.IterateForward();
+    OnAnimationUpdate(progress);
+    while (TBAnimationListener *listener = li.GetAndStep())
+        listener->OnAnimationUpdate(this, progress);
 }
 
 void TBAnimationObject::InvokeOnAnimationStop(bool aborted)
 {
-	TBLinkListOf<TBAnimationListener>::Iterator li = m_listeners.IterateForward();
-	OnAnimationStop(aborted);
-	while (TBAnimationListener *listener = li.GetAndStep())
-		listener->OnAnimationStop(this, aborted);
+    TBLinkListOf<TBAnimationListener>::Iterator li = m_listeners.IterateForward();
+    OnAnimationStop(aborted);
+    while (TBAnimationListener *listener = li.GetAndStep())
+        listener->OnAnimationStop(this, aborted);
 }
 
 // == TBAnimationManager ==============================================
@@ -62,118 +62,118 @@ static int block_animations_counter = 0;
 //static
 void TBAnimationManager::AbortAllAnimations()
 {
-	while (TBAnimationObject *obj = animating_objects.GetFirst())
-		AbortAnimation(obj, true);
+    while (TBAnimationObject *obj = animating_objects.GetFirst())
+        AbortAnimation(obj, true);
 }
 
 //static
 void TBAnimationManager::Update()
 {
-	double time_now = TBSystem::GetTimeMS();
-
-	TBLinkListOf<TBAnimationObject>::Iterator iter = animating_objects.IterateForward();
-	while (TBAnimationObject *obj = iter.GetAndStep())
-	{
-		// Adjust the start time if it's the first update time for this object.
-		if (obj->adjust_start_time)
-		{
-			obj->animation_start_time = time_now;
-			obj->adjust_start_time = false;
-		}
-
-		// Calculate current progress
-		// If animation_duration is 0, it should just complete immediately.
-		float progress = 1.0f;
-		if (obj->animation_duration != 0)
-		{
-			progress = (float)(time_now - obj->animation_start_time) / (float)obj->animation_duration;
-			progress = MIN(progress, 1.0f);
-		}
-
-		// Apply animation curve
-		float tmp;
-		switch (obj->animation_curve)
-		{
-		case ANIMATION_CURVE_SLOW_DOWN:
-			tmp = 1 - progress;
-			progress = 1 - tmp * tmp * tmp;
-			break;
-		case ANIMATION_CURVE_SPEED_UP:
-			progress = progress * progress * progress;
-			break;
-		case ANIMATION_CURVE_BEZIER:
-			progress = SMOOTHSTEP(progress);
-			break;
-		case ANIMATION_CURVE_SMOOTH:
-			progress = SmoothCurve(progress, 0.6f);
-			break;
-		default: // linear (progress is already linear)
-			break;
-		};
-
-		// Update animation
-		obj->InvokeOnAnimationUpdate(progress);
-
-		// Remove completed animations
-		if (progress == 1.0f)
-		{
-			animating_objects.Remove(obj);
-			obj->InvokeOnAnimationStop(false);
-			delete obj;
-		}
-	}
+    double time_now = TBSystem::GetTimeMS();
+
+    TBLinkListOf<TBAnimationObject>::Iterator iter = animating_objects.IterateForward();
+    while (TBAnimationObject *obj = iter.GetAndStep())
+    {
+        // Adjust the start time if it's the first update time for this object.
+        if (obj->adjust_start_time)
+        {
+            obj->animation_start_time = time_now;
+            obj->adjust_start_time = false;
+        }
+
+        // Calculate current progress
+        // If animation_duration is 0, it should just complete immediately.
+        float progress = 1.0f;
+        if (obj->animation_duration != 0)
+        {
+            progress = (float)(time_now - obj->animation_start_time) / (float)obj->animation_duration;
+            progress = MIN(progress, 1.0f);
+        }
+
+        // Apply animation curve
+        float tmp;
+        switch (obj->animation_curve)
+        {
+        case ANIMATION_CURVE_SLOW_DOWN:
+            tmp = 1 - progress;
+            progress = 1 - tmp * tmp * tmp;
+            break;
+        case ANIMATION_CURVE_SPEED_UP:
+            progress = progress * progress * progress;
+            break;
+        case ANIMATION_CURVE_BEZIER:
+            progress = SMOOTHSTEP(progress);
+            break;
+        case ANIMATION_CURVE_SMOOTH:
+            progress = SmoothCurve(progress, 0.6f);
+            break;
+        default: // linear (progress is already linear)
+            break;
+        };
+
+        // Update animation
+        obj->InvokeOnAnimationUpdate(progress);
+
+        // Remove completed animations
+        if (progress == 1.0f)
+        {
+            animating_objects.Remove(obj);
+            obj->InvokeOnAnimationStop(false);
+            delete obj;
+        }
+    }
 }
 
 //static
 bool TBAnimationManager::HasAnimationsRunning()
 {
-	return animating_objects.HasLinks();
+    return animating_objects.HasLinks();
 }
 
 //static
 void TBAnimationManager::StartAnimation(TBAnimationObject *obj, ANIMATION_CURVE animation_curve, double animation_duration, ANIMATION_TIME animation_time)
 {
-	if (obj->IsAnimating())
-		AbortAnimation(obj, false);
-	if (IsAnimationsBlocked())
-		animation_duration = 0;
-	obj->adjust_start_time = (animation_time == ANIMATION_TIME_FIRST_UPDATE ? true : false);
-	obj->animation_start_time = TBSystem::GetTimeMS();
-	obj->animation_duration = MAX(animation_duration, 0.0);
-	obj->animation_curve = animation_curve;
-	animating_objects.AddLast(obj);
-	obj->InvokeOnAnimationStart();
+    if (obj->IsAnimating())
+        AbortAnimation(obj, false);
+    if (IsAnimationsBlocked())
+        animation_duration = 0;
+    obj->adjust_start_time = (animation_time == ANIMATION_TIME_FIRST_UPDATE ? true : false);
+    obj->animation_start_time = TBSystem::GetTimeMS();
+    obj->animation_duration = MAX(animation_duration, 0.0);
+    obj->animation_curve = animation_curve;
+    animating_objects.AddLast(obj);
+    obj->InvokeOnAnimationStart();
 }
 
 //static
 void TBAnimationManager::AbortAnimation(TBAnimationObject *obj, bool delete_animation)
 {
-	if (obj->IsAnimating())
-	{
-		animating_objects.Remove(obj);
-		obj->InvokeOnAnimationStop(true);
-		if (delete_animation)
-			delete obj;
-	}
+    if (obj->IsAnimating())
+    {
+        animating_objects.Remove(obj);
+        obj->InvokeOnAnimationStop(true);
+        if (delete_animation)
+            delete obj;
+    }
 }
 
 //static
 bool TBAnimationManager::IsAnimationsBlocked()
 {
-	return block_animations_counter > 0;
+    return block_animations_counter > 0;
 }
 
 //static
 void TBAnimationManager::BeginBlockAnimations()
 {
-	block_animations_counter++;
+    block_animations_counter++;
 }
 
 //static
 void TBAnimationManager::EndBlockAnimations()
 {
-	assert(block_animations_counter > 0);
-	block_animations_counter--;
+    assert(block_animations_counter > 0);
+    block_animations_counter--;
 }
 
 }; // namespace tb

+ 91 - 91
Source/ThirdParty/TurboBadger/animation/tb_animation.h

@@ -15,33 +15,33 @@ class TBAnimationObject;
 
 /** Defines how the animation progress value is interpolated. */
 enum ANIMATION_CURVE {
-	ANIMATION_CURVE_LINEAR,		///< Linear
-	ANIMATION_CURVE_SLOW_DOWN,	///< Fast start, slow end
-	ANIMATION_CURVE_SPEED_UP,	///< Slow start, fast end
-	ANIMATION_CURVE_BEZIER,		///< Slow start, slow end. Almost linear.
-	ANIMATION_CURVE_SMOOTH		///< Slow start, slow end. Stronger than ANIMATION_CURVE_BEZIER.
+    ANIMATION_CURVE_LINEAR,		///< Linear
+    ANIMATION_CURVE_SLOW_DOWN,	///< Fast start, slow end
+    ANIMATION_CURVE_SPEED_UP,	///< Slow start, fast end
+    ANIMATION_CURVE_BEZIER,		///< Slow start, slow end. Almost linear.
+    ANIMATION_CURVE_SMOOTH		///< Slow start, slow end. Stronger than ANIMATION_CURVE_BEZIER.
 };
 
 /** Defines what the animation duration time is relative to. */
 enum ANIMATION_TIME {
 
-	/** The start time begins when the animation start in TBAnimationManager::StartAnimation. */
-	ANIMATION_TIME_IMMEDIATELY,
+    /** The start time begins when the animation start in TBAnimationManager::StartAnimation. */
+    ANIMATION_TIME_IMMEDIATELY,
 
-	/** The animation start in StartAnimation just as with ANIMATION_TIME_IMMEDIATELY,
-		but the start time is adjusted to when the animations Update is about to be called
-		the first time since it was started.
+    /** The animation start in StartAnimation just as with ANIMATION_TIME_IMMEDIATELY,
+        but the start time is adjusted to when the animations Update is about to be called
+        the first time since it was started.
 
-		Using this is most often preferable since starting a animation is often accompanied
-		with some extra work that might eat up a considerable time of the total duration (and
-		chop of the beginning of it).
+        Using this is most often preferable since starting a animation is often accompanied
+        with some extra work that might eat up a considerable time of the total duration (and
+        chop of the beginning of it).
 
-		F.ex: Creating a window and starting its appearance animation. During initialization
-		of the window, you might initiate loading of additional resources. When that is done
-		and you finally end up updating animations, most of the animation time might already
-		have passed. If the animation start time is adjusted to the first update, the whole
-		animation will run from 0.0 - 1.0 smoothly when the initialization is done. */
-	ANIMATION_TIME_FIRST_UPDATE
+        F.ex: Creating a window and starting its appearance animation. During initialization
+        of the window, you might initiate loading of additional resources. When that is done
+        and you finally end up updating animations, most of the animation time might already
+        have passed. If the animation start time is adjusted to the first update, the whole
+        animation will run from 0.0 - 1.0 smoothly when the initialization is done. */
+    ANIMATION_TIME_FIRST_UPDATE
 };
 
 #define ANIMATION_DEFAULT_CURVE			ANIMATION_CURVE_SLOW_DOWN
@@ -52,19 +52,19 @@ enum ANIMATION_TIME {
 class TBAnimationListener : public TBLinkOf<TBAnimationListener>
 {
 public:
-	virtual ~TBAnimationListener() {};
+    virtual ~TBAnimationListener() {};
 
-	/** Called after the animation object handled its own OnAnimationStart.
-		See TBAnimationObject::OnAnimationStart for details. */
-	virtual void OnAnimationStart(TBAnimationObject *obj) = 0;
+    /** Called after the animation object handled its own OnAnimationStart.
+        See TBAnimationObject::OnAnimationStart for details. */
+    virtual void OnAnimationStart(TBAnimationObject *obj) = 0;
 
-	/** Called after the animation object handled its own OnAnimationStart.
-		See TBAnimationObject::OnAnimationUpdate for details. */
-	virtual void OnAnimationUpdate(TBAnimationObject *obj, float progress) = 0;
+    /** Called after the animation object handled its own OnAnimationStart.
+        See TBAnimationObject::OnAnimationUpdate for details. */
+    virtual void OnAnimationUpdate(TBAnimationObject *obj, float progress) = 0;
 
-	/** Called after the animation object handled its own OnAnimationStart.
-		See TBAnimationObject::OnAnimationStop for details. */
-	virtual void OnAnimationStop(TBAnimationObject *obj, bool aborted) = 0;
+    /** Called after the animation object handled its own OnAnimationStart.
+        See TBAnimationObject::OnAnimationStop for details. */
+    virtual void OnAnimationStop(TBAnimationObject *obj, bool aborted) = 0;
 };
 
 /** TBAnimationObject - Base class for all animated object */
@@ -72,43 +72,43 @@ public:
 class TBAnimationObject : public TBTypedObject, public TBLinkOf<TBAnimationObject>
 {
 public:
-	ANIMATION_CURVE animation_curve;
-	double animation_start_time;
-	double animation_duration;
-	bool adjust_start_time;
+    ANIMATION_CURVE animation_curve;
+    double animation_start_time;
+    double animation_duration;
+    bool adjust_start_time;
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBAnimationObject, TBTypedObject);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBAnimationObject, TBTypedObject);
 
-	virtual ~TBAnimationObject() {}
+    virtual ~TBAnimationObject() {}
 
-	/** Return true if the object is currently animating. */
-	bool IsAnimating() const { return linklist ? true : false; }
+    /** Return true if the object is currently animating. */
+    bool IsAnimating() const { return linklist ? true : false; }
 
-	/** Called on animation start */
-	virtual void OnAnimationStart() = 0;
+    /** Called on animation start */
+    virtual void OnAnimationStart() = 0;
 
-	/** Called on animation update. progress is current progress from 0 to 1.
-		Note that it isn't called on start, so progress 0 might not happen.
-		It will be called with progress 1 before the animation is completed normally (not aborted) */
-	virtual void OnAnimationUpdate(float progress) = 0;
+    /** Called on animation update. progress is current progress from 0 to 1.
+        Note that it isn't called on start, so progress 0 might not happen.
+        It will be called with progress 1 before the animation is completed normally (not aborted) */
+    virtual void OnAnimationUpdate(float progress) = 0;
 
-	/** Called on animation stop. aborted is true if it was aborted before completion.
-		Note that if a animation is started when it's already running, it will first
-		be aborted and then started again. */
-	virtual void OnAnimationStop(bool aborted) = 0;
+    /** Called on animation stop. aborted is true if it was aborted before completion.
+        Note that if a animation is started when it's already running, it will first
+        be aborted and then started again. */
+    virtual void OnAnimationStop(bool aborted) = 0;
 
-	/** Add an listener to this animation object. */
-	void AddListener(TBAnimationListener *listener) { m_listeners.AddLast(listener); }
+    /** Add an listener to this animation object. */
+    void AddListener(TBAnimationListener *listener) { m_listeners.AddLast(listener); }
 
-	/** Remove an listener from this animation object. */
-	void RemoveListener(TBAnimationListener *listener) { m_listeners.Remove(listener); }
+    /** Remove an listener from this animation object. */
+    void RemoveListener(TBAnimationListener *listener) { m_listeners.Remove(listener); }
 private:
-	friend class TBAnimationManager;
-	TBLinkListOf<TBAnimationListener> m_listeners;
-	void InvokeOnAnimationStart();
-	void InvokeOnAnimationUpdate(float progress);
-	void InvokeOnAnimationStop(bool aborted);
+    friend class TBAnimationManager;
+    TBLinkListOf<TBAnimationListener> m_listeners;
+    void InvokeOnAnimationStart();
+    void InvokeOnAnimationUpdate(float progress);
+    void InvokeOnAnimationStop(bool aborted);
 };
 
 /** TBAnimationManager - System class that manages all animated object */
@@ -116,47 +116,47 @@ private:
 class TBAnimationManager
 {
 private:
-	static TBLinkListOf<TBAnimationObject> animating_objects;
+    static TBLinkListOf<TBAnimationObject> animating_objects;
 public:
-	/** Update all running animations. */
-	static void Update();
-
-	/** Return true if there is running animations. */
-	static bool HasAnimationsRunning();
-
-	static void StartAnimation(TBAnimationObject *obj,
-								ANIMATION_CURVE animation_curve = ANIMATION_DEFAULT_CURVE,
-								double animation_duration = ANIMATION_DEFAULT_DURATION,
-								ANIMATION_TIME animation_time = ANIMATION_TIME_FIRST_UPDATE);
-	/** Abort the animation. If delete_animation is true, the animation will be deleted in
-		this call after running callbacks and listeners callbacks. In rare situations,
-		you might want to keep the animation around and delete it later (or start it
-		again). */
-	static void AbortAnimation(TBAnimationObject *obj, bool delete_animation);
-
-	/** Abort and delete all animations. */
-	static void AbortAllAnimations();
-
-	/** Return true if new animations are blocked. */
-	static bool IsAnimationsBlocked();
-
-	/** Begin a period of blocking new animations. End the period with EndBlockAnimations.
-		If StartAnimation is called during the blocked period, the animation object will
-		finish the next animation update as it completed normally. */
-	static void BeginBlockAnimations();
-
-	/** End a period of blocking new animations that was started with BeginBlockAnimations. */
-	static void EndBlockAnimations();
+    /** Update all running animations. */
+    static void Update();
+
+    /** Return true if there is running animations. */
+    static bool HasAnimationsRunning();
+
+    static void StartAnimation(TBAnimationObject *obj,
+                               ANIMATION_CURVE animation_curve = ANIMATION_DEFAULT_CURVE,
+                               double animation_duration = ANIMATION_DEFAULT_DURATION,
+                               ANIMATION_TIME animation_time = ANIMATION_TIME_FIRST_UPDATE);
+    /** Abort the animation. If delete_animation is true, the animation will be deleted in
+        this call after running callbacks and listeners callbacks. In rare situations,
+        you might want to keep the animation around and delete it later (or start it
+        again). */
+    static void AbortAnimation(TBAnimationObject *obj, bool delete_animation);
+
+    /** Abort and delete all animations. */
+    static void AbortAllAnimations();
+
+    /** Return true if new animations are blocked. */
+    static bool IsAnimationsBlocked();
+
+    /** Begin a period of blocking new animations. End the period with EndBlockAnimations.
+        If StartAnimation is called during the blocked period, the animation object will
+        finish the next animation update as it completed normally. */
+    static void BeginBlockAnimations();
+
+    /** End a period of blocking new animations that was started with BeginBlockAnimations. */
+    static void EndBlockAnimations();
 };
 
 /** TBAnimationBlocker blocks new animations during its lifetime.
-	It's convenient to put on the stack to block new animations
-	within a scope of code. */
+    It's convenient to put on the stack to block new animations
+    within a scope of code. */
 class TBAnimationBlocker
 {
 public:
-	TBAnimationBlocker() { TBAnimationManager::BeginBlockAnimations(); }
-	~TBAnimationBlocker() { TBAnimationManager::EndBlockAnimations(); }
+    TBAnimationBlocker() { TBAnimationManager::BeginBlockAnimations(); }
+    ~TBAnimationBlocker() { TBAnimationManager::EndBlockAnimations(); }
 };
 
 }; // namespace tb

+ 130 - 130
Source/ThirdParty/TurboBadger/animation/tb_widget_animation.cpp

@@ -19,123 +19,123 @@ TBLinkListOf<TBWidgetAnimationObject> widget_animations;
 // == TBWidgetAnimationObject =============================================================
 
 TBWidgetAnimationObject::TBWidgetAnimationObject(TBWidget *widget)
-	: m_widget(widget)
+    : m_widget(widget)
 {
-	widget_animations.AddLast(this);
+    widget_animations.AddLast(this);
 }
 
 TBWidgetAnimationObject::~TBWidgetAnimationObject()
 {
-	widget_animations.Remove(this);
+    widget_animations.Remove(this);
 }
 
 // == TBWidgetAnimationOpacity ============================================================
 
 TBWidgetAnimationOpacity::TBWidgetAnimationOpacity(TBWidget *widget, float src_opacity, float dst_opacity, bool die)
-	: TBWidgetAnimationObject(widget)
-	, m_src_opacity(src_opacity)
-	, m_dst_opacity(dst_opacity)
-	, m_die(die)
+    : TBWidgetAnimationObject(widget)
+    , m_src_opacity(src_opacity)
+    , m_dst_opacity(dst_opacity)
+    , m_die(die)
 {
 }
 
 void TBWidgetAnimationOpacity::OnAnimationStart()
 {
-	// Make sure we don't stay idle if nothing is scheduled (hack).
-	// FIX: fix this properly
-	m_widget->Invalidate();
+    // Make sure we don't stay idle if nothing is scheduled (hack).
+    // FIX: fix this properly
+    m_widget->Invalidate();
 
-	m_widget->SetOpacity(m_src_opacity);
+    m_widget->SetOpacity(m_src_opacity);
 }
 
 void TBWidgetAnimationOpacity::OnAnimationUpdate(float progress)
 {
-	m_widget->SetOpacity(LERP(m_src_opacity, m_dst_opacity, progress));
+    m_widget->SetOpacity(LERP(m_src_opacity, m_dst_opacity, progress));
 }
 
 void TBWidgetAnimationOpacity::OnAnimationStop(bool aborted)
 {
-	// If we're aborted, it may be because the widget is being deleted
-	if (m_die && !aborted)
-	{
-		TBWidgetSafePointer the_widget(m_widget);
-		if (m_widget->GetParent())
-			m_widget->GetParent()->RemoveChild(m_widget);
-		if (the_widget.Get())
-			delete the_widget.Get();
-	}
-	else
-		m_widget->SetOpacity(m_dst_opacity);
+    // If we're aborted, it may be because the widget is being deleted
+    if (m_die && !aborted)
+    {
+        TBWidgetSafePointer the_widget(m_widget);
+        if (m_widget->GetParent())
+            m_widget->GetParent()->RemoveChild(m_widget);
+        if (the_widget.Get())
+            delete the_widget.Get();
+    }
+    else
+        m_widget->SetOpacity(m_dst_opacity);
 }
 
 // == TBWidgetAnimationRect ===============================================================
 
 TBWidgetAnimationRect::TBWidgetAnimationRect(TBWidget *widget, const TBRect &src_rect, const TBRect &dst_rect)
-	: TBWidgetAnimationObject(widget)
-	, m_src_rect(src_rect)
-	, m_dst_rect(dst_rect)
-	, m_mode(MODE_SRC_TO_DST)
+    : TBWidgetAnimationObject(widget)
+    , m_src_rect(src_rect)
+    , m_dst_rect(dst_rect)
+    , m_mode(MODE_SRC_TO_DST)
 {
 }
 
 TBWidgetAnimationRect::TBWidgetAnimationRect(TBWidget *widget, const TBRect &delta_rect, MODE mode)
-	: TBWidgetAnimationObject(widget)
-	, m_delta_rect(delta_rect)
-	, m_mode(mode)
+    : TBWidgetAnimationObject(widget)
+    , m_delta_rect(delta_rect)
+    , m_mode(mode)
 {
-	assert(mode == MODE_DELTA_IN || mode == MODE_DELTA_OUT);
+    assert(mode == MODE_DELTA_IN || mode == MODE_DELTA_OUT);
 }
 
 void TBWidgetAnimationRect::OnAnimationStart()
 {
-	// Make sure we don't stay idle if nothing is scheduled (hack).
-	// FIX: fix this properly
-	m_widget->Invalidate();
+    // Make sure we don't stay idle if nothing is scheduled (hack).
+    // FIX: fix this properly
+    m_widget->Invalidate();
 
-	if (m_mode == MODE_SRC_TO_DST)
-		m_widget->SetRect(m_src_rect);
+    if (m_mode == MODE_SRC_TO_DST)
+        m_widget->SetRect(m_src_rect);
 }
 
 void TBWidgetAnimationRect::OnAnimationUpdate(float progress)
 {
-	if (m_mode == MODE_DELTA_IN || m_mode == MODE_DELTA_OUT)
-	{
-		m_dst_rect = m_src_rect = m_widget->GetRect();
-		if (m_dst_rect.Equals(TBRect()))
-		{
-			// Widget hasn't been laid out yet,
-			// the animation was started too soon.
-			TBAnimationManager::AbortAnimation(this, true);
-			return;
-		}
-		if (m_mode == MODE_DELTA_IN)
-		{
-			m_dst_rect.x += m_delta_rect.x;
-			m_dst_rect.y += m_delta_rect.y;
-			m_dst_rect.w += m_delta_rect.w;
-			m_dst_rect.h += m_delta_rect.h;
-		}
-		else
-		{
-			m_src_rect.x += m_delta_rect.x;
-			m_src_rect.y += m_delta_rect.y;
-			m_src_rect.w += m_delta_rect.w;
-			m_src_rect.h += m_delta_rect.h;
-		}
-		m_mode = MODE_SRC_TO_DST;
-	}
-	TBRect rect;
-	rect.x = (int) LERP(m_src_rect.x, m_dst_rect.x, progress);
-	rect.y = (int) LERP(m_src_rect.y, m_dst_rect.y, progress);
-	rect.w = (int) LERP(m_src_rect.w, m_dst_rect.w, progress);
-	rect.h = (int) LERP(m_src_rect.h, m_dst_rect.h, progress);
-	m_widget->SetRect(rect);
+    if (m_mode == MODE_DELTA_IN || m_mode == MODE_DELTA_OUT)
+    {
+        m_dst_rect = m_src_rect = m_widget->GetRect();
+        if (m_dst_rect.Equals(TBRect()))
+        {
+            // Widget hasn't been laid out yet,
+            // the animation was started too soon.
+            TBAnimationManager::AbortAnimation(this, true);
+            return;
+        }
+        if (m_mode == MODE_DELTA_IN)
+        {
+            m_dst_rect.x += m_delta_rect.x;
+            m_dst_rect.y += m_delta_rect.y;
+            m_dst_rect.w += m_delta_rect.w;
+            m_dst_rect.h += m_delta_rect.h;
+        }
+        else
+        {
+            m_src_rect.x += m_delta_rect.x;
+            m_src_rect.y += m_delta_rect.y;
+            m_src_rect.w += m_delta_rect.w;
+            m_src_rect.h += m_delta_rect.h;
+        }
+        m_mode = MODE_SRC_TO_DST;
+    }
+    TBRect rect;
+    rect.x = (int) LERP(m_src_rect.x, m_dst_rect.x, progress);
+    rect.y = (int) LERP(m_src_rect.y, m_dst_rect.y, progress);
+    rect.w = (int) LERP(m_src_rect.w, m_dst_rect.w, progress);
+    rect.h = (int) LERP(m_src_rect.h, m_dst_rect.h, progress);
+    m_widget->SetRect(rect);
 }
 
 void TBWidgetAnimationRect::OnAnimationStop(bool aborted)
 {
-	if (m_mode == MODE_SRC_TO_DST) // m_dst_rect may still be unset if aborted.
-		m_widget->SetRect(m_dst_rect);
+    if (m_mode == MODE_SRC_TO_DST) // m_dst_rect may still be unset if aborted.
+        m_widget->SetRect(m_dst_rect);
 }
 
 // == TBWidgetsAnimationManager =====================================================
@@ -144,91 +144,91 @@ TBWidgetsAnimationManager widgets_animation_manager;
 
 void TBWidgetsAnimationManager::Init()
 {
-	TBWidgetListener::AddGlobalListener(&widgets_animation_manager);
+    TBWidgetListener::AddGlobalListener(&widgets_animation_manager);
 }
 
 void TBWidgetsAnimationManager::Shutdown()
 {
-	TBWidgetListener::RemoveGlobalListener(&widgets_animation_manager);
+    TBWidgetListener::RemoveGlobalListener(&widgets_animation_manager);
 }
 
 void TBWidgetsAnimationManager::AbortAnimations(TBWidget *widget)
 {
-	AbortAnimations(widget, nullptr);
+    AbortAnimations(widget, nullptr);
 }
 
 void TBWidgetsAnimationManager::AbortAnimations(TBWidget *widget, TB_TYPE_ID type_id)
 {
-	TBLinkListOf<TBWidgetAnimationObject>::Iterator iter = widget_animations.IterateForward();
-	while (TBWidgetAnimationObject *wao = iter.GetAndStep())
-	{
-		if (wao->m_widget == widget)
-		{
-			// Skip this animation if we asked for a specific (and
-			// different) animation type.
-			if (type_id != nullptr && !wao->IsOfTypeId(type_id))
-				continue;
+    TBLinkListOf<TBWidgetAnimationObject>::Iterator iter = widget_animations.IterateForward();
+    while (TBWidgetAnimationObject *wao = iter.GetAndStep())
+    {
+        if (wao->m_widget == widget)
+        {
+            // Skip this animation if we asked for a specific (and
+            // different) animation type.
+            if (type_id != nullptr && !wao->IsOfTypeId(type_id))
+                continue;
 
-			// Abort the animation. This will both autoremove itself
-			// and delete it, so no need to do it here.
-			TBAnimationManager::AbortAnimation(wao, true);
-		}
-	}
+            // Abort the animation. This will both autoremove itself
+            // and delete it, so no need to do it here.
+            TBAnimationManager::AbortAnimation(wao, true);
+        }
+    }
 }
 
 void TBWidgetsAnimationManager::OnWidgetDelete(TBWidget *widget)
 {
-	// Kill and delete all animations running for the widget being deleted.
-	AbortAnimations(widget);
+    // Kill and delete all animations running for the widget being deleted.
+    AbortAnimations(widget);
 }
 
 bool TBWidgetsAnimationManager::OnWidgetDying(TBWidget *widget)
 {
-	bool handled = false;
-	if (TBWindow *window = TBSafeCast<TBWindow>(widget))
-	{
-		// Fade out dying windows
-		if (TBAnimationObject *anim = new TBWidgetAnimationOpacity(window, 1.f, TB_ALMOST_ZERO_OPACITY, true))
-			TBAnimationManager::StartAnimation(anim, ANIMATION_CURVE_BEZIER);
-		handled = true;
-	}
-	if (TBMessageWindow *window = TBSafeCast<TBMessageWindow>(widget))
-	{
-		// Move out dying message windows
-		if (TBAnimationObject *anim = new TBWidgetAnimationRect(window, TBRect(0, 50, 0, 0), TBWidgetAnimationRect::MODE_DELTA_IN))
-			TBAnimationManager::StartAnimation(anim, ANIMATION_CURVE_SPEED_UP);
-		handled = true;
-	}
-	if (TBDimmer *dimmer = TBSafeCast<TBDimmer>(widget))
-	{
-		// Fade out dying dim layers
-		if (TBAnimationObject *anim = new TBWidgetAnimationOpacity(dimmer, 1.f, TB_ALMOST_ZERO_OPACITY, true))
-			TBAnimationManager::StartAnimation(anim, ANIMATION_CURVE_BEZIER);
-		handled = true;
-	}
-	return handled;
+    bool handled = false;
+    if (TBWindow *window = TBSafeCast<TBWindow>(widget))
+    {
+        // Fade out dying windows
+        if (TBAnimationObject *anim = new TBWidgetAnimationOpacity(window, 1.f, TB_ALMOST_ZERO_OPACITY, true))
+            TBAnimationManager::StartAnimation(anim, ANIMATION_CURVE_BEZIER);
+        handled = true;
+    }
+    if (TBMessageWindow *window = TBSafeCast<TBMessageWindow>(widget))
+    {
+        // Move out dying message windows
+        if (TBAnimationObject *anim = new TBWidgetAnimationRect(window, TBRect(0, 50, 0, 0), TBWidgetAnimationRect::MODE_DELTA_IN))
+            TBAnimationManager::StartAnimation(anim, ANIMATION_CURVE_SPEED_UP);
+        handled = true;
+    }
+    if (TBDimmer *dimmer = TBSafeCast<TBDimmer>(widget))
+    {
+        // Fade out dying dim layers
+        if (TBAnimationObject *anim = new TBWidgetAnimationOpacity(dimmer, 1.f, TB_ALMOST_ZERO_OPACITY, true))
+            TBAnimationManager::StartAnimation(anim, ANIMATION_CURVE_BEZIER);
+        handled = true;
+    }
+    return handled;
 }
 
 void TBWidgetsAnimationManager::OnWidgetAdded(TBWidget *parent, TBWidget *widget)
 {
-	if (TBWindow *window = TBSafeCast<TBWindow>(widget))
-	{
-		// Fade in new windows
-		if (TBAnimationObject *anim = new TBWidgetAnimationOpacity(window, TB_ALMOST_ZERO_OPACITY, 1.f, false))
-			TBAnimationManager::StartAnimation(anim, ANIMATION_CURVE_BEZIER);
-	}
-	if (TBMessageWindow *window = TBSafeCast<TBMessageWindow>(widget))
-	{
-		// Move in new message windows
-		if (TBAnimationObject *anim = new TBWidgetAnimationRect(window, TBRect(0, -50, 0, 0), TBWidgetAnimationRect::MODE_DELTA_OUT))
-			TBAnimationManager::StartAnimation(anim);
-	}
-	if (TBDimmer *dimmer = TBSafeCast<TBDimmer>(widget))
-	{
-		// Fade in dim layer
-		if (TBAnimationObject *anim = new TBWidgetAnimationOpacity(dimmer, TB_ALMOST_ZERO_OPACITY, 1.f, false))
-			TBAnimationManager::StartAnimation(anim, ANIMATION_CURVE_BEZIER);
-	}
+    if (TBWindow *window = TBSafeCast<TBWindow>(widget))
+    {
+        // Fade in new windows
+        if (TBAnimationObject *anim = new TBWidgetAnimationOpacity(window, TB_ALMOST_ZERO_OPACITY, 1.f, false))
+            TBAnimationManager::StartAnimation(anim, ANIMATION_CURVE_BEZIER);
+    }
+    if (TBMessageWindow *window = TBSafeCast<TBMessageWindow>(widget))
+    {
+        // Move in new message windows
+        if (TBAnimationObject *anim = new TBWidgetAnimationRect(window, TBRect(0, -50, 0, 0), TBWidgetAnimationRect::MODE_DELTA_OUT))
+            TBAnimationManager::StartAnimation(anim);
+    }
+    if (TBDimmer *dimmer = TBSafeCast<TBDimmer>(widget))
+    {
+        // Fade in dim layer
+        if (TBAnimationObject *anim = new TBWidgetAnimationOpacity(dimmer, TB_ALMOST_ZERO_OPACITY, 1.f, false))
+            TBAnimationManager::StartAnimation(anim, ANIMATION_CURVE_BEZIER);
+    }
 }
 
 void TBWidgetsAnimationManager::OnWidgetRemove(TBWidget *parent, TBWidget *widget)

+ 57 - 57
Source/ThirdParty/TurboBadger/animation/tb_widget_animation.h

@@ -12,96 +12,96 @@
 namespace tb {
 
 /** Don't use 0.0 for opacity animations since that may break focus code.
-	At the moment a window should appear and start fading in from opacity 0,
-	it would also attempt setting the focus to it, but if opacity is 0 it will
-	think focus should not be set in that window and fail. */
+    At the moment a window should appear and start fading in from opacity 0,
+    it would also attempt setting the focus to it, but if opacity is 0 it will
+    think focus should not be set in that window and fail. */
 #define TB_ALMOST_ZERO_OPACITY 0.001f
 
 /** Base class for widget animations. This animation object will
-	be deleted automatically if the widget is deleted. */
+    be deleted automatically if the widget is deleted. */
 class TBWidgetAnimationObject : public TBAnimationObject, public TBLinkOf<TBWidgetAnimationObject>
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBWidgetAnimationObject, TBAnimationObject);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBWidgetAnimationObject, TBAnimationObject);
 
-	TBWidgetAnimationObject(TBWidget *widget);
-	virtual ~TBWidgetAnimationObject();
+    TBWidgetAnimationObject(TBWidget *widget);
+    virtual ~TBWidgetAnimationObject();
 public:
-	TBWidget *m_widget;
+    TBWidget *m_widget;
 };
 
 /** Animate the opacity of the target widget. */
 class TBWidgetAnimationOpacity : public TBWidgetAnimationObject
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBWidgetAnimationOpacity, TBWidgetAnimationObject);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBWidgetAnimationOpacity, TBWidgetAnimationObject);
 
-	TBWidgetAnimationOpacity(TBWidget *widget, float src_opacity, float dst_opacity, bool die);
-	virtual void OnAnimationStart();
-	virtual void OnAnimationUpdate(float progress);
-	virtual void OnAnimationStop(bool aborted);
+    TBWidgetAnimationOpacity(TBWidget *widget, float src_opacity, float dst_opacity, bool die);
+    virtual void OnAnimationStart();
+    virtual void OnAnimationUpdate(float progress);
+    virtual void OnAnimationStop(bool aborted);
 private:
-	float m_src_opacity;
-	float m_dst_opacity;
-	bool m_die;
+    float m_src_opacity;
+    float m_dst_opacity;
+    bool m_die;
 };
 
 /** Animate the rectangle of the target widget. */
 class TBWidgetAnimationRect : public TBWidgetAnimationObject
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBWidgetAnimationRect, TBWidgetAnimationObject);
-
-	enum MODE {
-		/** Animate from source to dest. */
-		MODE_SRC_TO_DST,
-		/** Animate from current + delta to current. */
-		MODE_DELTA_IN,
-		/** Animate from current to current + delta. */
-		MODE_DELTA_OUT
-	};
-	/** Animate the widget between the given source and dest rectangle. */
-	TBWidgetAnimationRect(TBWidget *widget, const TBRect &src_rect, const TBRect &dst_rect);
-	/** Animate the widget between rectangles based on the current widget
-		rectangle and a delta. The reference rectangle will be taken from
-		the target widget on the first OnAnimationUpdate. */
-	TBWidgetAnimationRect(TBWidget *widget, const TBRect &delta_rect, MODE mode);
-	virtual void OnAnimationStart();
-	virtual void OnAnimationUpdate(float progress);
-	virtual void OnAnimationStop(bool aborted);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBWidgetAnimationRect, TBWidgetAnimationObject);
+
+    enum MODE {
+        /** Animate from source to dest. */
+        MODE_SRC_TO_DST,
+        /** Animate from current + delta to current. */
+        MODE_DELTA_IN,
+        /** Animate from current to current + delta. */
+        MODE_DELTA_OUT
+    };
+    /** Animate the widget between the given source and dest rectangle. */
+    TBWidgetAnimationRect(TBWidget *widget, const TBRect &src_rect, const TBRect &dst_rect);
+    /** Animate the widget between rectangles based on the current widget
+        rectangle and a delta. The reference rectangle will be taken from
+        the target widget on the first OnAnimationUpdate. */
+    TBWidgetAnimationRect(TBWidget *widget, const TBRect &delta_rect, MODE mode);
+    virtual void OnAnimationStart();
+    virtual void OnAnimationUpdate(float progress);
+    virtual void OnAnimationStop(bool aborted);
 private:
-	TBRect m_src_rect;
-	TBRect m_dst_rect;
-	TBRect m_delta_rect;
-	MODE m_mode;
+    TBRect m_src_rect;
+    TBRect m_dst_rect;
+    TBRect m_delta_rect;
+    MODE m_mode;
 };
 
 class TBWidgetsAnimationManager : public TBWidgetListener
 {
 public:
-	/** Init the widgets animation manager. */
-	static void Init();
+    /** Init the widgets animation manager. */
+    static void Init();
 
-	/** Shutdown the widgets animation manager. */
-	static void Shutdown();
+    /** Shutdown the widgets animation manager. */
+    static void Shutdown();
 
-	/** Abort all animations that are running for the given widget. */
-	static void AbortAnimations(TBWidget *widget);
+    /** Abort all animations that are running for the given widget. */
+    static void AbortAnimations(TBWidget *widget);
 
-	/** Abort all animations matching the given type that are running for the given widget.
-		This example will abort all opacity animations:
-			AbortAnimations(widget, TBTypedObject::GetTypeId<TBWidgetAnimationOpacity>()) */
-	static void AbortAnimations(TBWidget *widget, TB_TYPE_ID type_id);
+    /** Abort all animations matching the given type that are running for the given widget.
+        This example will abort all opacity animations:
+            AbortAnimations(widget, TBTypedObject::GetTypeId<TBWidgetAnimationOpacity>()) */
+    static void AbortAnimations(TBWidget *widget, TB_TYPE_ID type_id);
 
 private:
-	// == TBWidgetListener ==================
-	virtual void OnWidgetDelete(TBWidget *widget);
-	virtual bool OnWidgetDying(TBWidget *widget);
-	virtual void OnWidgetAdded(TBWidget *parent, TBWidget *child);
-	virtual void OnWidgetRemove(TBWidget *parent, TBWidget *child);
+    // == TBWidgetListener ==================
+    virtual void OnWidgetDelete(TBWidget *widget);
+    virtual bool OnWidgetDying(TBWidget *widget);
+    virtual void OnWidgetAdded(TBWidget *parent, TBWidget *child);
+    virtual void OnWidgetRemove(TBWidget *parent, TBWidget *child);
 };
 
 }; // namespace tb

+ 76 - 76
Source/ThirdParty/TurboBadger/image/tb_image_manager.cpp

@@ -16,84 +16,84 @@ namespace tb {
 // == TBImageRep ========================================================================
 
 TBImageRep::TBImageRep(TBImageManager *image_manager, TBBitmapFragment *fragment, uint32 hash_key)
-	: ref_count(0), hash_key(hash_key), image_manager(image_manager), fragment(fragment)
+    : ref_count(0), hash_key(hash_key), image_manager(image_manager), fragment(fragment)
 {
 }
 
 void TBImageRep::IncRef()
 {
-	ref_count++;
+    ref_count++;
 }
 
 void TBImageRep::DecRef()
 {
-	ref_count--;
-	if (ref_count == 0)
-	{
-		if (image_manager)
-			image_manager->RemoveImageRep(this);
-		delete this;
-	}
+    ref_count--;
+    if (ref_count == 0)
+    {
+        if (image_manager)
+            image_manager->RemoveImageRep(this);
+        delete this;
+    }
 }
 
 // == TBImage ===========================================================================
 
 TBImage::TBImage(TBImageRep *rep)
-	: m_image_rep(rep)
+    : m_image_rep(rep)
 {
-	if (m_image_rep)
-		m_image_rep->IncRef();
+    if (m_image_rep)
+        m_image_rep->IncRef();
 }
 
 TBImage::TBImage(const TBImage &image)
-	: m_image_rep(image.m_image_rep)
+    : m_image_rep(image.m_image_rep)
 {
-	if (m_image_rep)
-		m_image_rep->IncRef();
+    if (m_image_rep)
+        m_image_rep->IncRef();
 }
 
 TBImage::~TBImage()
 {
-	if (m_image_rep)
-		m_image_rep->DecRef();
+    if (m_image_rep)
+        m_image_rep->DecRef();
 }
 
 bool TBImage::IsEmpty() const
 {
-	return m_image_rep && m_image_rep->fragment;
+    return m_image_rep && m_image_rep->fragment;
 }
 
 int TBImage::Width() const
 {
-	if (m_image_rep && m_image_rep->fragment)
-		return m_image_rep->fragment->Width();
-	return 0;
+    if (m_image_rep && m_image_rep->fragment)
+        return m_image_rep->fragment->Width();
+    return 0;
 }
 
 int TBImage::Height() const
 {
-	if (m_image_rep && m_image_rep->fragment)
-		return m_image_rep->fragment->Height();
-	return 0;
+    if (m_image_rep && m_image_rep->fragment)
+        return m_image_rep->fragment->Height();
+    return 0;
 }
 
 TBBitmapFragment *TBImage::GetBitmap() const
 {
-	return m_image_rep ? m_image_rep->fragment : nullptr;
+    return m_image_rep ? m_image_rep->fragment : nullptr;
 }
 
 void TBImage::SetImageRep(TBImageRep *image_rep)
 {
-	if (m_image_rep == image_rep)
-		return;
+    if (m_image_rep == image_rep)
+        return;
 
-	if (m_image_rep)
-		m_image_rep->DecRef();
+    if (m_image_rep)
+        m_image_rep->DecRef();
 
-	m_image_rep = image_rep;
+    m_image_rep = image_rep;
 
-	if (m_image_rep)
-		m_image_rep->IncRef();
+    if (m_image_rep)
+        m_image_rep->IncRef();
 }
 
 // == TBImageManager ====================================================================
@@ -102,73 +102,73 @@ TBImageManager *g_image_manager = nullptr;
 
 TBImageManager::TBImageManager()
 {
-	g_renderer->AddListener(this);
+    g_renderer->AddListener(this);
 }
 
 TBImageManager::~TBImageManager()
 {
-	g_renderer->RemoveListener(this);
+    g_renderer->RemoveListener(this);
 
-	// If there is TBImageRep objects live, we must unset the fragment pointer
-	// since the m_frag_manager is going to be destroyed very soon.
-	TBHashTableIteratorOf<TBImageRep> it(&m_image_rep_hash);
-	while (TBImageRep *image_rep = it.GetNextContent())
-	{
-		image_rep->fragment = nullptr;
-		image_rep->image_manager = nullptr;
-	}
+    // If there is TBImageRep objects live, we must unset the fragment pointer
+    // since the m_frag_manager is going to be destroyed very soon.
+    TBHashTableIteratorOf<TBImageRep> it(&m_image_rep_hash);
+    while (TBImageRep *image_rep = it.GetNextContent())
+    {
+        image_rep->fragment = nullptr;
+        image_rep->image_manager = nullptr;
+    }
 }
 
 TBImage TBImageManager::GetImage(const char *filename)
 {
-	uint32 hash_key = TBGetHash(filename);
-	TBImageRep *image_rep = m_image_rep_hash.Get(hash_key);
-	if (!image_rep)
-	{
-		// Load a fragment. Load a destination DPI bitmap if available.
-		TBBitmapFragment *fragment = nullptr;
-		if (g_tb_skin->GetDimensionConverter()->NeedConversion())
-		{
-			TBTempBuffer filename_dst_DPI;
-			g_tb_skin->GetDimensionConverter()->GetDstDPIFilename(filename, &filename_dst_DPI);
-			fragment = m_frag_manager.GetFragmentFromFile(filename_dst_DPI.GetData(), false);
-		}
-		if (!fragment)
-			fragment = m_frag_manager.GetFragmentFromFile(filename, false);
-
-		image_rep = new TBImageRep(this, fragment, hash_key);
-		if (!image_rep || !fragment || !m_image_rep_hash.Add(hash_key, image_rep))
-		{
-			delete image_rep;
-			m_frag_manager.FreeFragment(fragment);
-			image_rep = nullptr;
-		}
+    uint32 hash_key = TBGetHash(filename);
+    TBImageRep *image_rep = m_image_rep_hash.Get(hash_key);
+    if (!image_rep)
+    {
+        // Load a fragment. Load a destination DPI bitmap if available.
+        TBBitmapFragment *fragment = nullptr;
+        if (g_tb_skin->GetDimensionConverter()->NeedConversion())
+        {
+            TBTempBuffer filename_dst_DPI;
+            g_tb_skin->GetDimensionConverter()->GetDstDPIFilename(filename, &filename_dst_DPI);
+            fragment = m_frag_manager.GetFragmentFromFile(filename_dst_DPI.GetData(), false);
+        }
+        if (!fragment)
+            fragment = m_frag_manager.GetFragmentFromFile(filename, false);
+
+        image_rep = new TBImageRep(this, fragment, hash_key);
+        if (!image_rep || !fragment || !m_image_rep_hash.Add(hash_key, image_rep))
+        {
+            delete image_rep;
+            m_frag_manager.FreeFragment(fragment);
+            image_rep = nullptr;
+        }
         // TBDebugOut(image_rep ? "TBImageManager - Loaded new image.\n" : "TBImageManager - Loading image failed.\n");
-	}
-	return TBImage(image_rep);
+    }
+    return TBImage(image_rep);
 }
 
 void TBImageManager::RemoveImageRep(TBImageRep *image_rep)
 {
-	assert(image_rep->ref_count == 0);
-	if (image_rep->fragment)
-	{
-		m_frag_manager.FreeFragment(image_rep->fragment);
-		image_rep->fragment = nullptr;
-	}
-	m_image_rep_hash.Remove(image_rep->hash_key);
-	image_rep->image_manager = nullptr;
+    assert(image_rep->ref_count == 0);
+    if (image_rep->fragment)
+    {
+        m_frag_manager.FreeFragment(image_rep->fragment);
+        image_rep->fragment = nullptr;
+    }
+    m_image_rep_hash.Remove(image_rep->hash_key);
+    image_rep->image_manager = nullptr;
     //TBDebugOut("TBImageManager - Removed image.\n");
 }
 
 void TBImageManager::OnContextLost()
 {
-	m_frag_manager.DeleteBitmaps();
+    m_frag_manager.DeleteBitmaps();
 }
 
 void TBImageManager::OnContextRestored()
 {
-	// No need to do anything. The bitmaps will be created when drawing.
+    // No need to do anything. The bitmaps will be created when drawing.
 }
 
 }; // namespace tb

+ 46 - 46
Source/ThirdParty/TurboBadger/image/tb_image_manager.h

@@ -23,86 +23,86 @@ class TBImageManager;
 
 class TBImageRep
 {
-	friend class TBImageManager;
-	friend class TBImage;
+    friend class TBImageManager;
+    friend class TBImage;
 
-	TBImageRep(TBImageManager *image_manager, TBBitmapFragment *fragment, uint32 hash_key);
+    TBImageRep(TBImageManager *image_manager, TBBitmapFragment *fragment, uint32 hash_key);
 
-	void IncRef();
-	void DecRef();
+    void IncRef();
+    void DecRef();
 
-	int ref_count;
-	uint32 hash_key;
-	TBImageManager *image_manager;
-	TBBitmapFragment *fragment;
+    int ref_count;
+    uint32 hash_key;
+    TBImageManager *image_manager;
+    TBBitmapFragment *fragment;
 };
 
 /** TBImage is a reference counting object representing a image loaded by TBImageManager.
-	As long as there are TBImage objects for a certain image, it will be kept loaded in memory.
-	It may be empty if the image has not yet been set, or if the TBImageManager is destroyed
-	when the image is still alive.
+    As long as there are TBImage objects for a certain image, it will be kept loaded in memory.
+    It may be empty if the image has not yet been set, or if the TBImageManager is destroyed
+    when the image is still alive.
 */
 
 class TBImage
 {
 public:
-	TBImage() : m_image_rep(nullptr) {}
-	TBImage(TBImageRep *rep);
-	TBImage(const TBImage &image);
-	~TBImage();
+    TBImage() : m_image_rep(nullptr) {}
+    TBImage(TBImageRep *rep);
+    TBImage(const TBImage &image);
+    ~TBImage();
 
-	/** Return true if this image is empty. */
-	bool IsEmpty() const;
+    /** Return true if this image is empty. */
+    bool IsEmpty() const;
 
-	/** Return the width of this image, or 0 if empty. */
-	int Width() const;
+    /** Return the width of this image, or 0 if empty. */
+    int Width() const;
 
-	/** Return the height of this image, or 0 if empty. */
-	int Height() const;
+    /** Return the height of this image, or 0 if empty. */
+    int Height() const;
 
-	/** Return the bitmap fragment for this image, or nullptr if empty. */
-	TBBitmapFragment *GetBitmap() const;
+    /** Return the bitmap fragment for this image, or nullptr if empty. */
+    TBBitmapFragment *GetBitmap() const;
 
-	const TBImage& operator = (const TBImage &image) { SetImageRep(image.m_image_rep); return *this; }
-	bool operator == (const TBImage &image) const { return m_image_rep == image.m_image_rep; }
-	bool operator != (const TBImage &image) const { return m_image_rep != image.m_image_rep; }
+    const TBImage& operator = (const TBImage &image) { SetImageRep(image.m_image_rep); return *this; }
+    bool operator == (const TBImage &image) const { return m_image_rep == image.m_image_rep; }
+    bool operator != (const TBImage &image) const { return m_image_rep != image.m_image_rep; }
 private:
-	void SetImageRep(TBImageRep *image_rep);
-	TBImageRep *m_image_rep;
+    void SetImageRep(TBImageRep *image_rep);
+    TBImageRep *m_image_rep;
 };
 
 /** TBImageManager loads images returned as TBImage objects.
 
-	It internally use a TBBitmapFragmentManager that create fragment maps for loaded images,
-	and keeping track of which images are loaded so they are not loaded several times.
+    It internally use a TBBitmapFragmentManager that create fragment maps for loaded images,
+    and keeping track of which images are loaded so they are not loaded several times.
 
-	Images are forgotten when there are no longer any TBImage objects for a given file.
+    Images are forgotten when there are no longer any TBImage objects for a given file.
 */
 
 class TBImageManager : private TBRendererListener
 {
 public:
-	TBImageManager();
-	~TBImageManager();
+    TBImageManager();
+    ~TBImageManager();
 
-	/** Return a image object for the given filename.
-		If it fails, the returned TBImage object will be empty. */
-	TBImage GetImage(const char *filename);
+    /** Return a image object for the given filename.
+        If it fails, the returned TBImage object will be empty. */
+    TBImage GetImage(const char *filename);
 
 #ifdef TB_RUNTIME_DEBUG_INFO
-	/** Render the skin bitmaps on screen, to analyze fragment positioning. */
-	void Debug() { m_frag_manager.Debug(); }
+    /** Render the skin bitmaps on screen, to analyze fragment positioning. */
+    void Debug() { m_frag_manager.Debug(); }
 #endif
 
-	// Implementing TBRendererListener
-	virtual void OnContextLost();
-	virtual void OnContextRestored();
+    // Implementing TBRendererListener
+    virtual void OnContextLost();
+    virtual void OnContextRestored();
 private:
-	TBBitmapFragmentManager m_frag_manager;
-	TBHashTableOf<TBImageRep> m_image_rep_hash;
+    TBBitmapFragmentManager m_frag_manager;
+    TBHashTableOf<TBImageRep> m_image_rep_hash;
 
-	friend class TBImageRep;
-	void RemoveImageRep(TBImageRep *image_rep);
+    friend class TBImageRep;
+    void RemoveImageRep(TBImageRep *image_rep);
 };
 
 /** The global TBImageManager. */

+ 3 - 3
Source/ThirdParty/TurboBadger/image/tb_image_widget.cpp

@@ -13,13 +13,13 @@ namespace tb {
 
 PreferredSize TBImageWidget::OnCalculatePreferredContentSize(const SizeConstraints &constraints)
 {
-	return PreferredSize(m_image.Width(), m_image.Height());
+    return PreferredSize(m_image.Width(), m_image.Height());
 }
 
 void TBImageWidget::OnPaint(const PaintProps &paint_props)
 {
-	if (TBBitmapFragment *fragment = m_image.GetBitmap())
-		g_renderer->DrawBitmap(GetPaddingRect(), TBRect(0, 0, m_image.Width(), m_image.Height()), fragment);
+    if (TBBitmapFragment *fragment = m_image.GetBitmap())
+        g_renderer->DrawBitmap(GetPaddingRect(), TBRect(0, 0, m_image.Width(), m_image.Height()), fragment);
 }
 
 }; // namespace tb

+ 11 - 11
Source/ThirdParty/TurboBadger/image/tb_image_widget.h

@@ -15,29 +15,29 @@
 namespace tb {
 
 /** TBImageWidget is a widget showing a image loaded by TBImageManager,
-	constrained in size to its skin.
-	If you need to show a image from the skin, you can use TBSkinImage. */
+    constrained in size to its skin.
+    If you need to show a image from the skin, you can use TBSkinImage. */
 
 class TBImageWidget : public TBWidget
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBImageWidget, TBWidget);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBImageWidget, TBWidget);
 
-	TBImageWidget() {}
+    TBImageWidget() {}
 
-	void SetImage(const TBImage &image) { m_image = image; }
-	void SetImage(const char *filename) { m_image = g_image_manager->GetImage(filename); }
+    void SetImage(const TBImage &image) { m_image = image; }
+    void SetImage(const char *filename) { m_image = g_image_manager->GetImage(filename); }
 
     int32 GetImageWidth() { return m_image.Width(); }
     int32 GetImageHeight() { return m_image.Height(); }
 
-	virtual PreferredSize OnCalculatePreferredContentSize(const SizeConstraints &constraints);
+    virtual PreferredSize OnCalculatePreferredContentSize(const SizeConstraints &constraints);
 
-	virtual void OnInflate(const INFLATE_INFO &info);
-	virtual void OnPaint(const PaintProps &paint_props);
+    virtual void OnInflate(const INFLATE_INFO &info);
+    virtual void OnPaint(const PaintProps &paint_props);
 private:
-	TBImage m_image;
+    TBImage m_image;
 };
 
 }; // namespace tb

+ 369 - 369
Source/ThirdParty/TurboBadger/parser/tb_parser.cpp

@@ -15,432 +15,432 @@ namespace tb {
 
 static bool is_hex(char c)
 {
-	return ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));
+    return ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'));
 }
 
 static uint32 parse_hex(char *&src, int max_count)
 {
-	uint32 hex = 0;
-	for (int i = 0; i < max_count; i++)
-	{
-		char c = *src;
-		if (!is_hex(c))
-			break;
-		hex <<= 4;
-		hex |= isdigit(c) ? c - '0' : tolower(c) - 'a' + 10;
-		src++;
-	}
-	return hex;
+    uint32 hex = 0;
+    for (int i = 0; i < max_count; i++)
+    {
+        char c = *src;
+        if (!is_hex(c))
+            break;
+        hex <<= 4;
+        hex |= isdigit(c) ? c - '0' : tolower(c) - 'a' + 10;
+        src++;
+    }
+    return hex;
 }
 
 void UnescapeString(char *str)
 {
-	// fast forward to any escape sequence
-	while (*str && *str != '\\')
-		str++;
-
-	char *dst = str, *src = str;
-	while (*src)
-	{
-		if (*src == '\\')
-		{
-			bool code_found = true;
-			switch (src[1])
-			{
-			case 'a': *dst = '\a'; break;
-			case 'b': *dst = '\b'; break;
-			case 'f': *dst = '\f'; break;
-			case 'n': *dst = '\n'; break;
-			case 'r': *dst = '\r'; break;
-			case 't': *dst = '\t'; break;
-			case 'v': *dst = '\v'; break;
-			case '0': *dst = '\0'; break;
-			case '\"': *dst = '\"'; break;
-			case '\'': *dst = '\''; break;
-			case '\\': *dst = '\\'; break;
-			case 'x': // \xXX
-			case 'u': // \uXXXX
-			{
-				// This should be safe. A utf-8 character can be at most 4 bytes,
-				// and we have 4 bytes to use for \xXX and 6 for \uXXXX.
-				src += 2;
-				if (UCS4 hex = parse_hex(src, src[1] == 'x' ? 2 : 4))
-					dst += utf8::encode(hex, dst);
-				continue;
-			}
-			default:
-				code_found = false;
-			}
-			if (code_found)
-			{
-				src += 2;
-				dst++;
-				continue;
-			}
-		}
-		*dst = *src;
-		dst++;
-		src++;
-	}
-	*dst = 0;
+    // fast forward to any escape sequence
+    while (*str && *str != '\\')
+        str++;
+
+    char *dst = str, *src = str;
+    while (*src)
+    {
+        if (*src == '\\')
+        {
+            bool code_found = true;
+            switch (src[1])
+            {
+            case 'a': *dst = '\a'; break;
+            case 'b': *dst = '\b'; break;
+            case 'f': *dst = '\f'; break;
+            case 'n': *dst = '\n'; break;
+            case 'r': *dst = '\r'; break;
+            case 't': *dst = '\t'; break;
+            case 'v': *dst = '\v'; break;
+            case '0': *dst = '\0'; break;
+            case '\"': *dst = '\"'; break;
+            case '\'': *dst = '\''; break;
+            case '\\': *dst = '\\'; break;
+            case 'x': // \xXX
+            case 'u': // \uXXXX
+            {
+                // This should be safe. A utf-8 character can be at most 4 bytes,
+                // and we have 4 bytes to use for \xXX and 6 for \uXXXX.
+                src += 2;
+                if (UCS4 hex = parse_hex(src, src[1] == 'x' ? 2 : 4))
+                    dst += utf8::encode(hex, dst);
+                continue;
+            }
+            default:
+                code_found = false;
+            }
+            if (code_found)
+            {
+                src += 2;
+                dst++;
+                continue;
+            }
+        }
+        *dst = *src;
+        dst++;
+        src++;
+    }
+    *dst = 0;
 }
 
 bool is_white_space(const char *str)
 {
-	switch (*str)
-	{
-	case ' ':
-	case '\t':
-		return true;
-	default:
-		return false;
-	}
+    switch (*str)
+    {
+    case ' ':
+    case '\t':
+        return true;
+    default:
+        return false;
+    }
 }
 
 /** Return true if the given string starts with a color.
-	Ex: #ffdd00, #fd0 */
+    Ex: #ffdd00, #fd0 */
 bool is_start_of_color(const char *str)
 {
-	if (*str++ != '#')
-		return false;
-	int digit_count = 0;
-	while (is_hex(*str))
-	{
-		str++;
-		digit_count++;
-	}
-	return digit_count == 8 || digit_count == 6 || digit_count == 4 || digit_count == 3;
+    if (*str++ != '#')
+        return false;
+    int digit_count = 0;
+    while (is_hex(*str))
+    {
+        str++;
+        digit_count++;
+    }
+    return digit_count == 8 || digit_count == 6 || digit_count == 4 || digit_count == 3;
 }
 
 /** Return true if the given string may be a node reference, such
-	as language strings or TBNodeRefTree references. */
+    as language strings or TBNodeRefTree references. */
 bool is_start_of_reference(const char *str)
 {
-	if (*str++ != '@')
-		return false;
-	while (*str && *str != ' ')
-	{
-		// If the token ends with colon, it's not a value but a key.
-		if (*str == ':')
-			return false;
-		str++;
-	}
-	return true;
+    if (*str++ != '@')
+        return false;
+    while (*str && *str != ' ')
+    {
+        // If the token ends with colon, it's not a value but a key.
+        if (*str == ':')
+            return false;
+        str++;
+    }
+    return true;
 }
 
 /** Check if the line is a comment or empty space. If it is, consume the leading
-	whitespace from line. */
+    whitespace from line. */
 bool is_space_or_comment(char *&line)
 {
-	char *tmp = line;
-	while (is_white_space(tmp))
-		tmp++;
-	if (*tmp == '#' || *tmp == 0)
-	{
-		line = tmp;
-		return true;
-	}
-	return false;
+    char *tmp = line;
+    while (is_white_space(tmp))
+        tmp++;
+    if (*tmp == '#' || *tmp == 0)
+    {
+        line = tmp;
+        return true;
+    }
+    return false;
 }
 
 bool is_pending_multiline(const char *str)
 {
-	while (is_white_space(str))
-		str++;
-	return str[0] == '\\' && str[1] == 0;
+    while (is_white_space(str))
+        str++;
+    return str[0] == '\\' && str[1] == 0;
 }
 
 bool IsEndQuote(const char *buf_start, const char *buf, const char quote_type)
 {
-	if (*buf != quote_type)
-		return false;
-	int num_backslashes = 0;
-	while (buf_start < buf && *(buf-- - 1) == '\\')
-		num_backslashes++;
-	return !(num_backslashes & 1);
+    if (*buf != quote_type)
+        return false;
+    int num_backslashes = 0;
+    while (buf_start < buf && *(buf-- - 1) == '\\')
+        num_backslashes++;
+    return !(num_backslashes & 1);
 }
 
 // == Parser ============================================================================
 
 TBParser::STATUS TBParser::Read(TBParserStream *stream, TBParserTarget *target)
 {
-	TBTempBuffer line, work;
-	if (!line.Reserve(1024) || !work.Reserve(1024))
-		return STATUS_OUT_OF_MEMORY;
-
-	current_indent = 0;
-	current_line_nr = 1;
-	pending_multiline = false;
-	multi_line_sub_level = 0;
-
-	while (int read_len = stream->GetMoreData((char *)work.GetData(), work.GetCapacity()))
-	{
-		char *buf = work.GetData();
-
-		// Skip BOM (BYTE ORDER MARK) character, often in the beginning of UTF-8 documents.
-		if (current_line_nr == 1 && read_len > 3 &&
-			(uint8)buf[0] == 239 &&
-			(uint8)buf[1] == 187 &&
-			(uint8)buf[2] == 191)
-		{
-			read_len -= 3;
-			buf += 3;
-		}
-
-		int line_pos = 0;
-		while (true)
-		{
-			// Find line end
-			int line_start = line_pos;
-			while (line_pos < read_len && buf[line_pos] != '\n')
-				line_pos++;
-
-			if (line_pos < read_len)
-			{
-				// We have a line
-				// Skip preceding \r (if we have one)
-				int line_len = line_pos - line_start;
-				if (!line.Append(buf + line_start, line_len))
-					return STATUS_OUT_OF_MEMORY;
-
-				// Strip away trailing '\r' if the line has it
-				char *linebuf = line.GetData();
-				int linebuf_len = line.GetAppendPos();
-				if (linebuf_len > 0 && linebuf[linebuf_len - 1] == '\r')
-					linebuf[linebuf_len - 1] = 0;
-
-				// Terminate the line string
-				if (!line.Append("", 1))
-					return STATUS_OUT_OF_MEMORY;
-
-				// Handle line
-				OnLine(line.GetData(), target);
-				current_line_nr++;
-
-				line.ResetAppendPos();
-				line_pos++; // Skip this \n
-				// Find next line
-				continue;
-			}
-			// No more lines here so push the rest and break for more data
-			if (!line.Append(buf + line_start, read_len - line_start))
-				return STATUS_OUT_OF_MEMORY;
-			break;
-		}
-	}
-	if (line.GetAppendPos())
-	{
-		if (!line.Append("", 1))
-			return STATUS_OUT_OF_MEMORY;
-		OnLine(line.GetData(), target);
-		current_line_nr++;
-	}
-	return STATUS_OK;
+    TBTempBuffer line, work;
+    if (!line.Reserve(1024) || !work.Reserve(1024))
+        return STATUS_OUT_OF_MEMORY;
+
+    current_indent = 0;
+    current_line_nr = 1;
+    pending_multiline = false;
+    multi_line_sub_level = 0;
+
+    while (int read_len = stream->GetMoreData((char *)work.GetData(), work.GetCapacity()))
+    {
+        char *buf = work.GetData();
+
+        // Skip BOM (BYTE ORDER MARK) character, often in the beginning of UTF-8 documents.
+        if (current_line_nr == 1 && read_len > 3 &&
+                (uint8)buf[0] == 239 &&
+                (uint8)buf[1] == 187 &&
+                (uint8)buf[2] == 191)
+        {
+            read_len -= 3;
+            buf += 3;
+        }
+
+        int line_pos = 0;
+        while (true)
+        {
+            // Find line end
+            int line_start = line_pos;
+            while (line_pos < read_len && buf[line_pos] != '\n')
+                line_pos++;
+
+            if (line_pos < read_len)
+            {
+                // We have a line
+                // Skip preceding \r (if we have one)
+                int line_len = line_pos - line_start;
+                if (!line.Append(buf + line_start, line_len))
+                    return STATUS_OUT_OF_MEMORY;
+
+                // Strip away trailing '\r' if the line has it
+                char *linebuf = line.GetData();
+                int linebuf_len = line.GetAppendPos();
+                if (linebuf_len > 0 && linebuf[linebuf_len - 1] == '\r')
+                    linebuf[linebuf_len - 1] = 0;
+
+                // Terminate the line string
+                if (!line.Append("", 1))
+                    return STATUS_OUT_OF_MEMORY;
+
+                // Handle line
+                OnLine(line.GetData(), target);
+                current_line_nr++;
+
+                line.ResetAppendPos();
+                line_pos++; // Skip this \n
+                // Find next line
+                continue;
+            }
+            // No more lines here so push the rest and break for more data
+            if (!line.Append(buf + line_start, read_len - line_start))
+                return STATUS_OUT_OF_MEMORY;
+            break;
+        }
+    }
+    if (line.GetAppendPos())
+    {
+        if (!line.Append("", 1))
+            return STATUS_OUT_OF_MEMORY;
+        OnLine(line.GetData(), target);
+        current_line_nr++;
+    }
+    return STATUS_OK;
 }
 
 void TBParser::OnLine(char *line, TBParserTarget *target)
 {
-	if (is_space_or_comment(line))
-	{
-		if (*line == '#')
-			target->OnComment(current_line_nr, line + 1);
-		return;
-	}
-	if (pending_multiline)
-	{
-		OnMultiline(line, target);
-		return;
-	}
-
-	// Check indent
-	int indent = 0;
-	while (line[indent] == '\t' && line[indent] != 0)
-		indent++;
-	line += indent;
-
-	if (indent - current_indent > 1)
-	{
-		target->OnError(current_line_nr, "Indentation error. (Line skipped)");
-		return;
-	}
-
-	if (indent > current_indent)
-	{
-		// FIX: Report indentation error if more than 1 higher!
-		assert(indent - current_indent == 1);
-		target->Enter();
-		current_indent++;
-	}
-	else if (indent < current_indent)
-	{
-		while (indent < current_indent)
-		{
-			target->Leave();
-			current_indent--;
-		}
-	}
-
-	if (*line == 0)
-		return;
-	else
-	{
-		char *token = line;
-		// Read line while consuming it and copy over to token buf
-		while (!is_white_space(line) && *line != 0)
-			line++;
-		int token_len = line - token;
-		// Consume any white space after the token
-		while (is_white_space(line))
-			line++;
-
-		bool is_compact_line = token_len && token[token_len - 1] == ':';
-
-		TBValue value;
-		if (is_compact_line)
-		{
-			token_len--;
-			token[token_len] = 0;
-
-			// Check if the first argument is not a child but the value for this token
-			if (*line == '[' || *line == '\"' || *line == '\'' ||
-				is_start_of_number(line) ||
-				is_start_of_color(line) ||
-				is_start_of_reference(line))
-			{
-				ConsumeValue(value, line);
-
-				if (pending_multiline)
-				{
-					// The value wrapped to the next line, so we should remember the token and continue.
-					multi_line_token.Set(token);
-					return;
-				}
-			}
-		}
-		else if (token[token_len])
-		{
-			token[token_len] = 0;
-			UnescapeString(line);
-			value.SetFromStringAuto(line, TBValue::SET_AS_STATIC);
-		}
-		target->OnToken(current_line_nr, token, value);
-
-		if (is_compact_line)
-			OnCompactLine(line, target);
-	}
+    if (is_space_or_comment(line))
+    {
+        if (*line == '#')
+            target->OnComment(current_line_nr, line + 1);
+        return;
+    }
+    if (pending_multiline)
+    {
+        OnMultiline(line, target);
+        return;
+    }
+
+    // Check indent
+    int indent = 0;
+    while (line[indent] == '\t' && line[indent] != 0)
+        indent++;
+    line += indent;
+
+    if (indent - current_indent > 1)
+    {
+        target->OnError(current_line_nr, "Indentation error. (Line skipped)");
+        return;
+    }
+
+    if (indent > current_indent)
+    {
+        // FIX: Report indentation error if more than 1 higher!
+        assert(indent - current_indent == 1);
+        target->Enter();
+        current_indent++;
+    }
+    else if (indent < current_indent)
+    {
+        while (indent < current_indent)
+        {
+            target->Leave();
+            current_indent--;
+        }
+    }
+
+    if (*line == 0)
+        return;
+    else
+    {
+        char *token = line;
+        // Read line while consuming it and copy over to token buf
+        while (!is_white_space(line) && *line != 0)
+            line++;
+        int token_len = line - token;
+        // Consume any white space after the token
+        while (is_white_space(line))
+            line++;
+
+        bool is_compact_line = token_len && token[token_len - 1] == ':';
+
+        TBValue value;
+        if (is_compact_line)
+        {
+            token_len--;
+            token[token_len] = 0;
+
+            // Check if the first argument is not a child but the value for this token
+            if (*line == '[' || *line == '\"' || *line == '\'' ||
+                    is_start_of_number(line) ||
+                    is_start_of_color(line) ||
+                    is_start_of_reference(line))
+            {
+                ConsumeValue(value, line);
+
+                if (pending_multiline)
+                {
+                    // The value wrapped to the next line, so we should remember the token and continue.
+                    multi_line_token.Set(token);
+                    return;
+                }
+            }
+        }
+        else if (token[token_len])
+        {
+            token[token_len] = 0;
+            UnescapeString(line);
+            value.SetFromStringAuto(line, TBValue::SET_AS_STATIC);
+        }
+        target->OnToken(current_line_nr, token, value);
+
+        if (is_compact_line)
+            OnCompactLine(line, target);
+    }
 }
 
 void TBParser::OnCompactLine(char *line, TBParserTarget *target)
 {
-	target->Enter();
-	while (*line)
-	{
-		// consume any whitespace
-		while (is_white_space(line))
-			line++;
-
-		// Find token
-		char *token = line;
-		while (*line != ':' && *line != 0)
-			line++;
-		if (!*line)
-			break; // Syntax error, expected token
-		*line++ = 0;
-
-		// consume any whitespace
-		while (is_white_space(line))
-			line++;
-
-		TBValue v;
-		ConsumeValue(v, line);
-
-		if (pending_multiline)
-		{
-			// The value wrapped to the next line, so we should remember the token and continue.
-			multi_line_token.Set(token);
-			// Since we need to call target->Leave when the multiline is ready, set multi_line_sub_level.
-			multi_line_sub_level = 1;
-			return;
-		}
-
-		// Ready
-		target->OnToken(current_line_nr, token, v);
-	}
-
-	target->Leave();
+    target->Enter();
+    while (*line)
+    {
+        // consume any whitespace
+        while (is_white_space(line))
+            line++;
+
+        // Find token
+        char *token = line;
+        while (*line != ':' && *line != 0)
+            line++;
+        if (!*line)
+            break; // Syntax error, expected token
+        *line++ = 0;
+
+        // consume any whitespace
+        while (is_white_space(line))
+            line++;
+
+        TBValue v;
+        ConsumeValue(v, line);
+
+        if (pending_multiline)
+        {
+            // The value wrapped to the next line, so we should remember the token and continue.
+            multi_line_token.Set(token);
+            // Since we need to call target->Leave when the multiline is ready, set multi_line_sub_level.
+            multi_line_sub_level = 1;
+            return;
+        }
+
+        // Ready
+        target->OnToken(current_line_nr, token, v);
+    }
+
+    target->Leave();
 }
 
 void TBParser::OnMultiline(char *line, TBParserTarget *target)
 {
-	// consume any whitespace
-	while (is_white_space(line))
-		line++;
-
-	TBValue value;
-	ConsumeValue(value, line);
-
-	if (!pending_multiline)
-	{
-		// Ready with all lines
-		value.SetString(multi_line_value.GetData(), TBValue::SET_AS_STATIC);
-		target->OnToken(current_line_nr, multi_line_token, value);
-
-		if (multi_line_sub_level)
-			target->Leave();
-
-		// Reset
-		multi_line_value.SetAppendPos(0);
-		multi_line_sub_level = 0;
-	}
+    // consume any whitespace
+    while (is_white_space(line))
+        line++;
+
+    TBValue value;
+    ConsumeValue(value, line);
+
+    if (!pending_multiline)
+    {
+        // Ready with all lines
+        value.SetString(multi_line_value.GetData(), TBValue::SET_AS_STATIC);
+        target->OnToken(current_line_nr, multi_line_token, value);
+
+        if (multi_line_sub_level)
+            target->Leave();
+
+        // Reset
+        multi_line_value.SetAppendPos(0);
+        multi_line_sub_level = 0;
+    }
 }
 
 void TBParser::ConsumeValue(TBValue &dst_value, char *&line)
 {
-	// Find value (As quoted string, or as auto)
-	char *value = line;
-	if (*line == '\"' || *line == '\'')
-	{
-		const char quote_type = *line;
-		// Consume starting quote
-		line++;
-		value++;
-		// Find ending quote or end
-		while (!IsEndQuote(value, line, quote_type) && *line != 0)
-			line++;
-		// Terminate away the quote
-		if (*line == quote_type)
-			*line++ = 0;
-
-		// consume any whitespace
-		while (is_white_space(line))
-			line++;
-		// consume any comma
-		if (*line == ',')
-			line++;
-
-		UnescapeString(value);
-		dst_value.SetString(value, TBValue::SET_AS_STATIC);
-	}
-	else
-	{
-		// Find next comma or end
-		while (*line != ',' && *line != 0)
-			line++;
-		// Terminate away the comma
-		if (*line == ',')
-			*line++ = 0;
-
-		UnescapeString(value);
-		dst_value.SetFromStringAuto(value, TBValue::SET_AS_STATIC);
-	}
-
-	// Check if we still have pending value data on the following line and set pending_multiline.
-	bool continuing_multiline = pending_multiline;
-	pending_multiline = is_pending_multiline(line);
-
-	// Append the multi line value to the buffer.
-	if (continuing_multiline || pending_multiline)
-		multi_line_value.AppendString(dst_value.GetString());
+    // Find value (As quoted string, or as auto)
+    char *value = line;
+    if (*line == '\"' || *line == '\'')
+    {
+        const char quote_type = *line;
+        // Consume starting quote
+        line++;
+        value++;
+        // Find ending quote or end
+        while (!IsEndQuote(value, line, quote_type) && *line != 0)
+            line++;
+        // Terminate away the quote
+        if (*line == quote_type)
+            *line++ = 0;
+
+        // consume any whitespace
+        while (is_white_space(line))
+            line++;
+        // consume any comma
+        if (*line == ',')
+            line++;
+
+        UnescapeString(value);
+        dst_value.SetString(value, TBValue::SET_AS_STATIC);
+    }
+    else
+    {
+        // Find next comma or end
+        while (*line != ',' && *line != 0)
+            line++;
+        // Terminate away the comma
+        if (*line == ',')
+            *line++ = 0;
+
+        UnescapeString(value);
+        dst_value.SetFromStringAuto(value, TBValue::SET_AS_STATIC);
+    }
+
+    // Check if we still have pending value data on the following line and set pending_multiline.
+    bool continuing_multiline = pending_multiline;
+    pending_multiline = is_pending_multiline(line);
+
+    // Append the multi line value to the buffer.
+    if (continuing_multiline || pending_multiline)
+        multi_line_value.AppendString(dst_value.GetString());
 }
 
 }; // namespace tb

+ 28 - 28
Source/ThirdParty/TurboBadger/parser/tb_parser.h

@@ -13,53 +13,53 @@
 namespace tb {
 
 /** Unescape backslash codes. This is done in place using the string both as source
-	and destination. */
+    and destination. */
 void UnescapeString(char *str);
 
 /** Check if buf is pointing at a end quote. It may need to iterate
-	buf backwards toward buf_start to check if any preceding backslashes
-	make it a escaped quote (which should not be the end quote) */
+    buf backwards toward buf_start to check if any preceding backslashes
+    make it a escaped quote (which should not be the end quote) */
 bool IsEndQuote(const char *buf_start, const char *buf, const char quote_type);
 
 class TBParserTarget
 {
 public:
-	virtual ~TBParserTarget() {}
-	virtual void OnError(int line_nr, const char *error) = 0;
-	virtual void OnComment(int line_nr, const char *comment) = 0;
-	virtual void OnToken(int line_nr, const char *name, TBValue &value) = 0;
-	virtual void Enter() = 0;
-	virtual void Leave() = 0;
+    virtual ~TBParserTarget() {}
+    virtual void OnError(int line_nr, const char *error) = 0;
+    virtual void OnComment(int line_nr, const char *comment) = 0;
+    virtual void OnToken(int line_nr, const char *name, TBValue &value) = 0;
+    virtual void Enter() = 0;
+    virtual void Leave() = 0;
 };
 
 class TBParserStream
 {
 public:
-	virtual ~TBParserStream() {}
-	virtual int GetMoreData(char *buf, int buf_len) = 0;
+    virtual ~TBParserStream() {}
+    virtual int GetMoreData(char *buf, int buf_len) = 0;
 };
 
 class TBParser
 {
 public:
-	enum STATUS {
-		STATUS_OK,
-		STATUS_OUT_OF_MEMORY,
-		STATUS_PARSE_ERROR
-	};
-	TBParser() {}
-	STATUS Read(TBParserStream *stream, TBParserTarget *target);
+    enum STATUS {
+        STATUS_OK,
+        STATUS_OUT_OF_MEMORY,
+        STATUS_PARSE_ERROR
+    };
+    TBParser() {}
+    STATUS Read(TBParserStream *stream, TBParserTarget *target);
 private:
-	int current_indent;
-	int current_line_nr;
-	TBStr multi_line_token;
-	TBTempBuffer multi_line_value;
-	int multi_line_sub_level;
-	bool pending_multiline;
-	void OnLine(char *line, TBParserTarget *target);
-	void OnCompactLine(char *line, TBParserTarget *target);
-	void OnMultiline(char *line, TBParserTarget *target);
-	void ConsumeValue(TBValue &dst_value, char *&line);
+    int current_indent;
+    int current_line_nr;
+    TBStr multi_line_token;
+    TBTempBuffer multi_line_value;
+    int multi_line_sub_level;
+    bool pending_multiline;
+    void OnLine(char *line, TBParserTarget *target);
+    void OnCompactLine(char *line, TBParserTarget *target);
+    void OnMultiline(char *line, TBParserTarget *target);
+    void ConsumeValue(TBValue &dst_value, char *&line);
 };
 
 }; // namespace tb

+ 157 - 157
Source/ThirdParty/TurboBadger/renderers/tb_renderer_batcher.cpp

@@ -23,65 +23,65 @@ uint32 dbg_frame_triangle_count = 0;
 
 void TBRendererBatcher::Batch::Flush(TBRendererBatcher *batch_renderer)
 {
-	if (!vertex_count || is_flushing)
-		return;
+    if (!vertex_count || is_flushing)
+        return;
 
-	// Prevent re-entrancy. Calling fragment->GetBitmap may end up calling TBBitmap::SetData
-	// which will end up flushing any existing batch with that bitmap.
-	is_flushing = true;
+    // Prevent re-entrancy. Calling fragment->GetBitmap may end up calling TBBitmap::SetData
+    // which will end up flushing any existing batch with that bitmap.
+    is_flushing = true;
 
-	if (fragment)
-	{
-		// Now it's time to ensure the bitmap data is up to date. A call to GetBitmap
-		// with TB_VALIDATE_ALWAYS should guarantee that its data is validated.
-		TBBitmap *frag_bitmap = fragment->GetBitmap(TB_VALIDATE_ALWAYS);
-		((void)frag_bitmap); // silence warning about unused variable
-		assert(frag_bitmap == bitmap);
-	}
+    if (fragment)
+    {
+        // Now it's time to ensure the bitmap data is up to date. A call to GetBitmap
+        // with TB_VALIDATE_ALWAYS should guarantee that its data is validated.
+        TBBitmap *frag_bitmap = fragment->GetBitmap(TB_VALIDATE_ALWAYS);
+        ((void)frag_bitmap); // silence warning about unused variable
+        assert(frag_bitmap == bitmap);
+    }
 
-	batch_renderer->RenderBatch(this);
+    batch_renderer->RenderBatch(this);
 
 #ifdef TB_RUNTIME_DEBUG_INFO
-	if (TB_DEBUG_SETTING(RENDER_BATCHES))
-	{
-		// This assumes we're drawing triangles. Need to modify this
-		// if we start using strips, fans or whatever.
-		dbg_frame_triangle_count += vertex_count / 3;
-
-		// Draw the triangles again using a random color based on the batch
-		// id. This indicates which triangles belong to the same batch.
-		uint32 id = batch_id - dbg_begin_paint_batch_id;
-		uint32 hash = id * (2166136261U ^ id);
-		uint32 color = 0xAA000000 + (hash & 0x00FFFFFF);
-		for (int i = 0; i < vertex_count; i++)
-			vertex[i].col = color;
-		bitmap = nullptr;
-		batch_renderer->RenderBatch(this);
-	}
+    if (TB_DEBUG_SETTING(RENDER_BATCHES))
+    {
+        // This assumes we're drawing triangles. Need to modify this
+        // if we start using strips, fans or whatever.
+        dbg_frame_triangle_count += vertex_count / 3;
+
+        // Draw the triangles again using a random color based on the batch
+        // id. This indicates which triangles belong to the same batch.
+        uint32 id = batch_id - dbg_begin_paint_batch_id;
+        uint32 hash = id * (2166136261U ^ id);
+        uint32 color = 0xAA000000 + (hash & 0x00FFFFFF);
+        for (int i = 0; i < vertex_count; i++)
+            vertex[i].col = color;
+        bitmap = nullptr;
+        batch_renderer->RenderBatch(this);
+    }
 #endif // TB_RUNTIME_DEBUG_INFO
 
-	vertex_count = 0;
+    vertex_count = 0;
 
-	batch_id++; // Will overflow eventually, but that doesn't really matter.
+    batch_id++; // Will overflow eventually, but that doesn't really matter.
 
-	is_flushing = false;
+    is_flushing = false;
 }
 
 TBRendererBatcher::Vertex *TBRendererBatcher::Batch::Reserve(TBRendererBatcher *batch_renderer, int count)
 {
-	assert(count < VERTEX_BATCH_SIZE);
-	if (vertex_count + count > VERTEX_BATCH_SIZE)
-		Flush(batch_renderer);
-	Vertex *ret = &vertex[vertex_count];
-	vertex_count += count;
-	return ret;
+    assert(count < VERTEX_BATCH_SIZE);
+    if (vertex_count + count > VERTEX_BATCH_SIZE)
+        Flush(batch_renderer);
+    Vertex *ret = &vertex[vertex_count];
+    vertex_count += count;
+    return ret;
 }
 
 // == TBRendererBatcher ===================================================================
 
 TBRendererBatcher::TBRendererBatcher()
-	: m_opacity(255), m_translation_x(0), m_translation_y(0)
-	, m_u(0), m_v(0), m_uu(0), m_vv(0)
+    : m_opacity(255), m_translation_x(0), m_translation_y(0)
+    , m_u(0), m_v(0), m_uu(0), m_vv(0)
 {
 }
 
@@ -92,221 +92,221 @@ TBRendererBatcher::~TBRendererBatcher()
 void TBRendererBatcher::BeginPaint(int render_target_w, int render_target_h)
 {
 #ifdef TB_RUNTIME_DEBUG_INFO
-	dbg_begin_paint_batch_id = batch.batch_id;
-	dbg_frame_triangle_count = 0;
+    dbg_begin_paint_batch_id = batch.batch_id;
+    dbg_frame_triangle_count = 0;
 #endif // TB_RUNTIME_DEBUG_INFO
 
-	m_screen_rect.Set(0, 0, render_target_w, render_target_h);
-	m_clip_rect = m_screen_rect;
+    m_screen_rect.Set(0, 0, render_target_w, render_target_h);
+    m_clip_rect = m_screen_rect;
 }
 
 void TBRendererBatcher::EndPaint()
 {
-	FlushAllInternal();
+    FlushAllInternal();
 
 #ifdef TB_RUNTIME_DEBUG_INFO
-	if (TB_DEBUG_SETTING(RENDER_BATCHES))
-		TBDebugPrint("Frame rendered using %d batches and a total of %d triangles.\n",
-						batch.batch_id - dbg_begin_paint_batch_id,
-						dbg_frame_triangle_count);
+    if (TB_DEBUG_SETTING(RENDER_BATCHES))
+        TBDebugPrint("Frame rendered using %d batches and a total of %d triangles.\n",
+                     batch.batch_id - dbg_begin_paint_batch_id,
+                     dbg_frame_triangle_count);
 #endif // TB_RUNTIME_DEBUG_INFO
 }
 
 void TBRendererBatcher::Translate(int dx, int dy)
 {
-	m_translation_x += dx;
-	m_translation_y += dy;
+    m_translation_x += dx;
+    m_translation_y += dy;
 }
 
 void TBRendererBatcher::SetOpacity(float opacity)
 {
-	int8 opacity8 = (uint8) (opacity * 255);
-	if (opacity8 == m_opacity)
-		return;
-	m_opacity = opacity8;
+    int8 opacity8 = (uint8) (opacity * 255);
+    if (opacity8 == m_opacity)
+        return;
+    m_opacity = opacity8;
 }
 
 float TBRendererBatcher::GetOpacity()
 {
-	return m_opacity / 255.f;
+    return m_opacity / 255.f;
 }
 
 TBRect TBRendererBatcher::SetClipRect(const TBRect &rect, bool add_to_current)
 {
-	TBRect old_clip_rect = m_clip_rect;
-	m_clip_rect = rect;
-	m_clip_rect.x += m_translation_x;
-	m_clip_rect.y += m_translation_y;
+    TBRect old_clip_rect = m_clip_rect;
+    m_clip_rect = rect;
+    m_clip_rect.x += m_translation_x;
+    m_clip_rect.y += m_translation_y;
 
-	if (add_to_current)
-		m_clip_rect = m_clip_rect.Clip(old_clip_rect);
+    if (add_to_current)
+        m_clip_rect = m_clip_rect.Clip(old_clip_rect);
 
-	FlushAllInternal();
-	SetClipRect(m_clip_rect);
+    FlushAllInternal();
+    SetClipRect(m_clip_rect);
 
-	old_clip_rect.x -= m_translation_x;
-	old_clip_rect.y -= m_translation_y;
-	return old_clip_rect;
+    old_clip_rect.x -= m_translation_x;
+    old_clip_rect.y -= m_translation_y;
+    return old_clip_rect;
 }
 
 TBRect TBRendererBatcher::GetClipRect()
 {
-	TBRect curr_clip_rect = m_clip_rect;
-	curr_clip_rect.x -= m_translation_x;
-	curr_clip_rect.y -= m_translation_y;
-	return curr_clip_rect;
+    TBRect curr_clip_rect = m_clip_rect;
+    curr_clip_rect.x -= m_translation_x;
+    curr_clip_rect.y -= m_translation_y;
+    return curr_clip_rect;
 }
 
 void TBRendererBatcher::DrawBitmap(const TBRect &dst_rect, const TBRect &src_rect, TBBitmapFragment *bitmap_fragment)
 {
-	if (TBBitmap *bitmap = bitmap_fragment->GetBitmap(TB_VALIDATE_FIRST_TIME))
-		AddQuadInternal(dst_rect.Offset(m_translation_x, m_translation_y),
-						src_rect.Offset(bitmap_fragment->m_rect.x, bitmap_fragment->m_rect.y),
-						VER_COL_OPACITY(m_opacity), bitmap, bitmap_fragment);
+    if (TBBitmap *bitmap = bitmap_fragment->GetBitmap(TB_VALIDATE_FIRST_TIME))
+        AddQuadInternal(dst_rect.Offset(m_translation_x, m_translation_y),
+                        src_rect.Offset(bitmap_fragment->m_rect.x, bitmap_fragment->m_rect.y),
+                        VER_COL_OPACITY(m_opacity), bitmap, bitmap_fragment);
 }
 
 void TBRendererBatcher::DrawBitmap(const TBRect &dst_rect, const TBRect &src_rect, TBBitmap *bitmap)
 {
-	AddQuadInternal(dst_rect.Offset(m_translation_x, m_translation_y), src_rect, VER_COL_OPACITY(m_opacity), bitmap, nullptr);
+    AddQuadInternal(dst_rect.Offset(m_translation_x, m_translation_y), src_rect, VER_COL_OPACITY(m_opacity), bitmap, nullptr);
 }
 
 void TBRendererBatcher::DrawBitmapColored(const TBRect &dst_rect, const TBRect &src_rect, const TBColor &color, TBBitmapFragment *bitmap_fragment)
 {
-	if (TBBitmap *bitmap = bitmap_fragment->GetBitmap(TB_VALIDATE_FIRST_TIME))
-	{
-		uint32 a = (color.a * m_opacity) / 255;
-		AddQuadInternal(dst_rect.Offset(m_translation_x, m_translation_y),
-						src_rect.Offset(bitmap_fragment->m_rect.x, bitmap_fragment->m_rect.y),
-						VER_COL(color.r, color.g, color.b, a), bitmap, bitmap_fragment);
-	}
+    if (TBBitmap *bitmap = bitmap_fragment->GetBitmap(TB_VALIDATE_FIRST_TIME))
+    {
+        uint32 a = (color.a * m_opacity) / 255;
+        AddQuadInternal(dst_rect.Offset(m_translation_x, m_translation_y),
+                        src_rect.Offset(bitmap_fragment->m_rect.x, bitmap_fragment->m_rect.y),
+                        VER_COL(color.r, color.g, color.b, a), bitmap, bitmap_fragment);
+    }
 }
 
 void TBRendererBatcher::DrawBitmapColored(const TBRect &dst_rect, const TBRect &src_rect, const TBColor &color, TBBitmap *bitmap)
 {
-	uint32 a = (color.a * m_opacity) / 255;
-	AddQuadInternal(dst_rect.Offset(m_translation_x, m_translation_y),
-					src_rect, VER_COL(color.r, color.g, color.b, a), bitmap, nullptr);
+    uint32 a = (color.a * m_opacity) / 255;
+    AddQuadInternal(dst_rect.Offset(m_translation_x, m_translation_y),
+                    src_rect, VER_COL(color.r, color.g, color.b, a), bitmap, nullptr);
 }
 
 void TBRendererBatcher::DrawBitmapTile(const TBRect &dst_rect, TBBitmap *bitmap)
 {
-	AddQuadInternal(dst_rect.Offset(m_translation_x, m_translation_y),
-					TBRect(0, 0, dst_rect.w, dst_rect.h),
-					VER_COL_OPACITY(m_opacity), bitmap, nullptr);
+    AddQuadInternal(dst_rect.Offset(m_translation_x, m_translation_y),
+                    TBRect(0, 0, dst_rect.w, dst_rect.h),
+                    VER_COL_OPACITY(m_opacity), bitmap, nullptr);
 }
 
 void TBRendererBatcher::DrawRect(const TBRect &dst_rect, const TBColor &color)
 {
-	if (dst_rect.IsEmpty())
-		return;
-	// Top
-	DrawRectFill(TBRect(dst_rect.x, dst_rect.y, dst_rect.w, 1), color);
-	// Bottom
-	DrawRectFill(TBRect(dst_rect.x, dst_rect.y + dst_rect.h - 1, dst_rect.w, 1), color);
-	// Left
-	DrawRectFill(TBRect(dst_rect.x, dst_rect.y + 1, 1, dst_rect.h - 2), color);
-	// Right
-	DrawRectFill(TBRect(dst_rect.x + dst_rect.w - 1, dst_rect.y + 1, 1, dst_rect.h - 2), color);
+    if (dst_rect.IsEmpty())
+        return;
+    // Top
+    DrawRectFill(TBRect(dst_rect.x, dst_rect.y, dst_rect.w, 1), color);
+    // Bottom
+    DrawRectFill(TBRect(dst_rect.x, dst_rect.y + dst_rect.h - 1, dst_rect.w, 1), color);
+    // Left
+    DrawRectFill(TBRect(dst_rect.x, dst_rect.y + 1, 1, dst_rect.h - 2), color);
+    // Right
+    DrawRectFill(TBRect(dst_rect.x + dst_rect.w - 1, dst_rect.y + 1, 1, dst_rect.h - 2), color);
 }
 
 void TBRendererBatcher::DrawRectFill(const TBRect &dst_rect, const TBColor &color)
 {
-	if (dst_rect.IsEmpty())
-		return;
-	uint32 a = (color.a * m_opacity) / 255;
-	AddQuadInternal(dst_rect.Offset(m_translation_x, m_translation_y),
-					TBRect(), VER_COL(color.r, color.g, color.b, a), nullptr, nullptr);
+    if (dst_rect.IsEmpty())
+        return;
+    uint32 a = (color.a * m_opacity) / 255;
+    AddQuadInternal(dst_rect.Offset(m_translation_x, m_translation_y),
+                    TBRect(), VER_COL(color.r, color.g, color.b, a), nullptr, nullptr);
 }
 
 void TBRendererBatcher::AddQuadInternal(const TBRect &dst_rect, const TBRect &src_rect, uint32 color, TBBitmap *bitmap, TBBitmapFragment *fragment)
 {
-	if (batch.bitmap != bitmap)
-	{
-		batch.Flush(this);
-		batch.bitmap = bitmap;
-	}
-	batch.fragment = fragment;
-	if (bitmap)
-	{
-		int bitmap_w = bitmap->Width();
-		int bitmap_h = bitmap->Height();
-		m_u = (float)src_rect.x / bitmap_w;
-		m_v = (float)src_rect.y / bitmap_h;
-		m_uu = (float)(src_rect.x + src_rect.w) / bitmap_w;
-		m_vv = (float)(src_rect.y + src_rect.h) / bitmap_h;
-	}
+    if (batch.bitmap != bitmap)
+    {
+        batch.Flush(this);
+        batch.bitmap = bitmap;
+    }
+    batch.fragment = fragment;
+    if (bitmap)
+    {
+        int bitmap_w = bitmap->Width();
+        int bitmap_h = bitmap->Height();
+        m_u = (float)src_rect.x / bitmap_w;
+        m_v = (float)src_rect.y / bitmap_h;
+        m_uu = (float)(src_rect.x + src_rect.w) / bitmap_w;
+        m_vv = (float)(src_rect.y + src_rect.h) / bitmap_h;
+    }
 
 #ifdef _MSC_VER
-       //Direct3D9 Adjustment
+    //Direct3D9 Adjustment
 #ifdef ATOMIC_D3D11
-       float posAdjust = 0.0f;
+    float posAdjust = 0.0f;
 #else
-       float posAdjust = 0.5f;
+    float posAdjust = 0.5f;
 #endif
 
 #else
-       float posAdjust = 0.0f;
+    float posAdjust = 0.0f;
 #endif
 
-	Vertex *ver = batch.Reserve(this, 6);
+    Vertex *ver = batch.Reserve(this, 6);
     ver[0].x = (float) dst_rect.x + posAdjust;
     ver[0].y = (float) (dst_rect.y + dst_rect.h) + posAdjust;
-	ver[0].u = m_u;
-	ver[0].v = m_vv;
-	ver[0].col = color;
+    ver[0].u = m_u;
+    ver[0].v = m_vv;
+    ver[0].col = color;
     ver[1].x = (float) (dst_rect.x + dst_rect.w) + posAdjust;
     ver[1].y = (float) (dst_rect.y + dst_rect.h) + posAdjust;
-	ver[1].u = m_uu;
-	ver[1].v = m_vv;
-	ver[1].col = color;
+    ver[1].u = m_uu;
+    ver[1].v = m_vv;
+    ver[1].col = color;
     ver[2].x = (float) dst_rect.x + posAdjust;
     ver[2].y = (float) dst_rect.y + posAdjust;
-	ver[2].u = m_u;
-	ver[2].v = m_v;
-	ver[2].col = color;
+    ver[2].u = m_u;
+    ver[2].v = m_v;
+    ver[2].col = color;
 
     ver[3].x = (float) dst_rect.x + posAdjust;
     ver[3].y = (float) dst_rect.y + posAdjust;
-	ver[3].u = m_u;
-	ver[3].v = m_v;
-	ver[3].col = color;
+    ver[3].u = m_u;
+    ver[3].v = m_v;
+    ver[3].col = color;
     ver[4].x = (float) (dst_rect.x + dst_rect.w) + posAdjust;
     ver[4].y = (float) (dst_rect.y + dst_rect.h) + posAdjust;
-	ver[4].u = m_uu;
-	ver[4].v = m_vv;
-	ver[4].col = color;
+    ver[4].u = m_uu;
+    ver[4].v = m_vv;
+    ver[4].col = color;
     ver[5].x = (float) (dst_rect.x + dst_rect.w) + posAdjust;
     ver[5].y = (float) dst_rect.y + posAdjust;
-	ver[5].u = m_uu;
-	ver[5].v = m_v;
-	ver[5].col = color;
+    ver[5].u = m_uu;
+    ver[5].v = m_v;
+    ver[5].col = color;
 
-	// Update fragments batch id (See FlushBitmapFragment)
-	if (fragment)
-		fragment->m_batch_id = batch.batch_id;
+    // Update fragments batch id (See FlushBitmapFragment)
+    if (fragment)
+        fragment->m_batch_id = batch.batch_id;
 }
 
 void TBRendererBatcher::FlushAllInternal()
 {
-	batch.Flush(this);
+    batch.Flush(this);
 }
 
 void TBRendererBatcher::FlushBitmap(TBBitmap *bitmap)
 {
-	// Flush the batch if it's using this bitmap (that is about to change or be deleted)
-	if (batch.vertex_count && bitmap == batch.bitmap)
-		batch.Flush(this);
+    // Flush the batch if it's using this bitmap (that is about to change or be deleted)
+    if (batch.vertex_count && bitmap == batch.bitmap)
+        batch.Flush(this);
 }
 
 void TBRendererBatcher::FlushBitmapFragment(TBBitmapFragment *bitmap_fragment)
 {
-	// Flush the batch if it is using this fragment (that is about to change or be deleted)
-	// We know if it is in use in the current batch if its batch_id matches the current
-	// batch_id in our (one and only) batch.
-	// If we switch to a more advance batching system with multiple batches, we need to
-	// solve this a bit differently.
-	if (batch.vertex_count && bitmap_fragment->m_batch_id == batch.batch_id)
-		batch.Flush(this);
+    // Flush the batch if it is using this fragment (that is about to change or be deleted)
+    // We know if it is in use in the current batch if its batch_id matches the current
+    // batch_id in our (one and only) batch.
+    // If we switch to a more advance batching system with multiple batches, we need to
+    // solve this a bit differently.
+    if (batch.vertex_count && bitmap_fragment->m_batch_id == batch.batch_id)
+        batch.Flush(this);
 }
 
 }; // namespace tb

+ 70 - 70
Source/ThirdParty/TurboBadger/renderers/tb_renderer_batcher.h

@@ -15,82 +15,82 @@ namespace tb {
 #define VERTEX_BATCH_SIZE 6 * 2048
 
 /** TBRendererBatcher is a helper class that implements batching of draw operations for a TBRenderer.
-	If you do not want to do your own batching you can subclass this class instead of TBRenderer.
-	If overriding any function in this class, make sure to call the base class too. */
+    If you do not want to do your own batching you can subclass this class instead of TBRenderer.
+    If overriding any function in this class, make sure to call the base class too. */
 class TBRendererBatcher : public TBRenderer
 {
 public:
-	/** Vertex stored in a Batch */
-	struct Vertex
-	{
-		float x, y;
-		float u, v;
-		union {
-			struct { unsigned char r, g, b, a; };
-			uint32 col;
-		};
-	};
-	/** A batch which should be rendered. */
-	class Batch
-	{
-	public:
-		Batch() : vertex_count(0), bitmap(nullptr), fragment(nullptr), batch_id(0), is_flushing(false) {}
-		void Flush(TBRendererBatcher *batch_renderer);
-		Vertex *Reserve(TBRendererBatcher *batch_renderer, int count);
-
-		Vertex vertex[VERTEX_BATCH_SIZE];
-		int vertex_count;
-
-		TBBitmap *bitmap;
-		TBBitmapFragment *fragment;
-
-		uint32 batch_id;
-		bool is_flushing;
-	};
-
-	TBRendererBatcher();
-	virtual ~TBRendererBatcher();
-
-	virtual void BeginPaint(int render_target_w, int render_target_h);
-	virtual void EndPaint();
-
-	virtual void Translate(int dx, int dy);
-
-	virtual void SetOpacity(float opacity);
-	virtual float GetOpacity();
-
-	virtual TBRect SetClipRect(const TBRect &rect, bool add_to_current);
-	virtual TBRect GetClipRect();
-
-	virtual void DrawBitmap(const TBRect &dst_rect, const TBRect &src_rect, TBBitmapFragment *bitmap_fragment);
-	virtual void DrawBitmap(const TBRect &dst_rect, const TBRect &src_rect, TBBitmap *bitmap);
-	virtual void DrawBitmapColored(const TBRect &dst_rect, const TBRect &src_rect, const TBColor &color, TBBitmapFragment *bitmap_fragment);
-	virtual void DrawBitmapColored(const TBRect &dst_rect, const TBRect &src_rect, const TBColor &color, TBBitmap *bitmap);
-	virtual void DrawBitmapTile(const TBRect &dst_rect, TBBitmap *bitmap);
-	virtual void DrawRect(const TBRect &dst_rect, const TBColor &color);
-	virtual void DrawRectFill(const TBRect &dst_rect, const TBColor &color);
-	virtual void FlushBitmap(TBBitmap *bitmap);
-	virtual void FlushBitmapFragment(TBBitmapFragment *bitmap_fragment);
-
-	virtual void BeginBatchHint(TBRenderer::BATCH_HINT hint) {}
-	virtual void EndBatchHint() {}
-
-	// == Methods that need implementation in subclasses ================================
-	virtual TBBitmap *CreateBitmap(int width, int height, uint32 *data) = 0;
-	virtual void RenderBatch(Batch *batch) = 0;
-	virtual void SetClipRect(const TBRect &rect) = 0;
+    /** Vertex stored in a Batch */
+    struct Vertex
+    {
+        float x, y;
+        float u, v;
+        union {
+            struct { unsigned char r, g, b, a; };
+            uint32 col;
+        };
+    };
+    /** A batch which should be rendered. */
+    class Batch
+    {
+    public:
+        Batch() : vertex_count(0), bitmap(nullptr), fragment(nullptr), batch_id(0), is_flushing(false) {}
+        void Flush(TBRendererBatcher *batch_renderer);
+        Vertex *Reserve(TBRendererBatcher *batch_renderer, int count);
+
+        Vertex vertex[VERTEX_BATCH_SIZE];
+        int vertex_count;
+
+        TBBitmap *bitmap;
+        TBBitmapFragment *fragment;
+
+        uint32 batch_id;
+        bool is_flushing;
+    };
+
+    TBRendererBatcher();
+    virtual ~TBRendererBatcher();
+
+    virtual void BeginPaint(int render_target_w, int render_target_h);
+    virtual void EndPaint();
+
+    virtual void Translate(int dx, int dy);
+
+    virtual void SetOpacity(float opacity);
+    virtual float GetOpacity();
+
+    virtual TBRect SetClipRect(const TBRect &rect, bool add_to_current);
+    virtual TBRect GetClipRect();
+
+    virtual void DrawBitmap(const TBRect &dst_rect, const TBRect &src_rect, TBBitmapFragment *bitmap_fragment);
+    virtual void DrawBitmap(const TBRect &dst_rect, const TBRect &src_rect, TBBitmap *bitmap);
+    virtual void DrawBitmapColored(const TBRect &dst_rect, const TBRect &src_rect, const TBColor &color, TBBitmapFragment *bitmap_fragment);
+    virtual void DrawBitmapColored(const TBRect &dst_rect, const TBRect &src_rect, const TBColor &color, TBBitmap *bitmap);
+    virtual void DrawBitmapTile(const TBRect &dst_rect, TBBitmap *bitmap);
+    virtual void DrawRect(const TBRect &dst_rect, const TBColor &color);
+    virtual void DrawRectFill(const TBRect &dst_rect, const TBColor &color);
+    virtual void FlushBitmap(TBBitmap *bitmap);
+    virtual void FlushBitmapFragment(TBBitmapFragment *bitmap_fragment);
+
+    virtual void BeginBatchHint(TBRenderer::BATCH_HINT hint) {}
+    virtual void EndBatchHint() {}
+
+    // == Methods that need implementation in subclasses ================================
+    virtual TBBitmap *CreateBitmap(int width, int height, uint32 *data) = 0;
+    virtual void RenderBatch(Batch *batch) = 0;
+    virtual void SetClipRect(const TBRect &rect) = 0;
 protected:
-	uint8 m_opacity;
-	TBRect m_screen_rect;
-	TBRect m_clip_rect;
-	int m_translation_x;
-	int m_translation_y;
+    uint8 m_opacity;
+    TBRect m_screen_rect;
+    TBRect m_clip_rect;
+    int m_translation_x;
+    int m_translation_y;
 
-	float m_u, m_v, m_uu, m_vv; ///< Some temp variables
-	Batch batch; ///< The one and only batch. this should be improved.
+    float m_u, m_v, m_uu, m_vv; ///< Some temp variables
+    Batch batch; ///< The one and only batch. this should be improved.
 
-	void AddQuadInternal(const TBRect &dst_rect, const TBRect &src_rect, uint32 color, TBBitmap *bitmap, TBBitmapFragment *fragment);
-	void FlushAllInternal();
+    void AddQuadInternal(const TBRect &dst_rect, const TBRect &src_rect, uint32 color, TBBitmap *bitmap, TBBitmapFragment *fragment);
+    void FlushAllInternal();
 };
 
 }; // namespace tb

+ 21 - 21
Source/ThirdParty/TurboBadger/tb_addon.cpp

@@ -14,9 +14,9 @@ namespace tb {
 TBAddonFactory *g_registered_addon_factories = nullptr;
 
 TBAddonFactory::TBAddonFactory()
-	: next(g_registered_addon_factories)
+    : next(g_registered_addon_factories)
 {
-	g_registered_addon_factories = this;
+    g_registered_addon_factories = this;
 }
 
 // ======================================================================================
@@ -25,29 +25,29 @@ TBLinkListOf<TBAddon> m_addons;
 
 bool TBInitAddons()
 {
-	TBAddonFactory *f = g_registered_addon_factories;
-	while (f)
-	{
-		TBAddon *addon = f->Create();
-		if (!addon || !addon->Init())
-		{
-			delete addon;
-			TBDebugOut("Failed initiating addon\n");
-			return false;
-		}
-		m_addons.AddLast(addon);
-		f = f->next;
-	}
-	return true;
+    TBAddonFactory *f = g_registered_addon_factories;
+    while (f)
+    {
+        TBAddon *addon = f->Create();
+        if (!addon || !addon->Init())
+        {
+            delete addon;
+            TBDebugOut("Failed initiating addon\n");
+            return false;
+        }
+        m_addons.AddLast(addon);
+        f = f->next;
+    }
+    return true;
 }
 
 void TBShutdownAddons()
 {
-	while (TBAddon *addon = m_addons.GetLast())
-	{
-		addon->Shutdown();
-		m_addons.Delete(addon);
-	}
+    while (TBAddon *addon = m_addons.GetLast())
+    {
+        addon->Shutdown();
+        m_addons.Delete(addon);
+    }
 }
 
 }; // namespace tb

+ 23 - 23
Source/ThirdParty/TurboBadger/tb_addon.h

@@ -12,36 +12,36 @@
 namespace tb {
 
 /** TBAddon provides a simple API with Init/Shutdown callbacks that will
-	be called during tb_core_init and tb_core_shutdown.
+    be called during tb_core_init and tb_core_shutdown.
 
-	THIS CLASS IS DEPRECATED! */
+    THIS CLASS IS DEPRECATED! */
 
 class TBAddon : public TBLinkOf<TBAddon>
 {
 public:
-	/** Called during tb_core_init after turbo badger core has been initiated. */
-	virtual bool Init() = 0;
+    /** Called during tb_core_init after turbo badger core has been initiated. */
+    virtual bool Init() = 0;
 
-	/** Called during tb_core_shutdown before turbo badger core has been shut down. */
-	virtual void Shutdown() = 0;
+    /** Called during tb_core_shutdown before turbo badger core has been shut down. */
+    virtual void Shutdown() = 0;
 
-	virtual ~TBAddon() {}
+    virtual ~TBAddon() {}
 };
 
 /** TBAddonFactory is ment to be subclassed to create a TBAddon, by
-	being declared as a global object. It will then register itself
-	so the addon is created, initiated during tb_core_init and
-	destroyed during tb_core_shutdown.
+    being declared as a global object. It will then register itself
+    so the addon is created, initiated during tb_core_init and
+    destroyed during tb_core_shutdown.
 
-	THIS CLASS IS DEPRECATED! */
+    THIS CLASS IS DEPRECATED! */
 class TBAddonFactory
 {
 public:
-	TBAddonFactory();
+    TBAddonFactory();
 
-	virtual TBAddon *Create() = 0;
+    virtual TBAddon *Create() = 0;
 
-	TBAddonFactory *next;	///< Next registered addon factory.
+    TBAddonFactory *next;	///< Next registered addon factory.
 };
 
 /** Init addons. */
@@ -52,15 +52,15 @@ void TBShutdownAddons();
 
 /** This macro creates a new TBAddonFactory for the given class name. */
 #define TB_ADDON_FACTORY(classname) \
-	class classname##AddonFactory : public TBAddonFactory \
-	{ \
-	public: \
-		virtual TBAddon *Create() \
-		{ \
-			return new classname(); \
-		} \
-	}; \
-	static classname##AddonFactory classname##_af;
+    class classname##AddonFactory : public TBAddonFactory \
+{ \
+    public: \
+    virtual TBAddon *Create() \
+{ \
+    return new classname(); \
+} \
+}; \
+    static classname##AddonFactory classname##_af;
 
 }; // namespace tb
 

+ 418 - 418
Source/ThirdParty/TurboBadger/tb_bitmap_fragment.cpp

@@ -11,547 +11,547 @@ namespace tb {
 
 int TBGetNearestPowerOfTwo(int val)
 {
-	int i;
-	for(i = 31; i >= 0; i--)
-		if ((val - 1) & (1<<i))
-			break;
-	return (1<<(i + 1));
+    int i;
+    for(i = 31; i >= 0; i--)
+        if ((val - 1) & (1<<i))
+            break;
+    return (1<<(i + 1));
 }
 
 // == TBSpaceAllocator ======================================================================================
 
 bool TBSpaceAllocator::HasSpace(int needed_w) const
 {
-	if (needed_w > m_available_space)
-		return false;
-	if (IsAllAvailable())
-		return true;
-	for (Space *fs = m_free_space_list.GetFirst(); fs; fs = fs->GetNext())
-	{
-		if (needed_w <= fs->width)
-			return true;
-	}
-	return false;
+    if (needed_w > m_available_space)
+        return false;
+    if (IsAllAvailable())
+        return true;
+    for (Space *fs = m_free_space_list.GetFirst(); fs; fs = fs->GetNext())
+    {
+        if (needed_w <= fs->width)
+            return true;
+    }
+    return false;
 }
 
 TBSpaceAllocator::Space *TBSpaceAllocator::AllocSpace(int needed_w)
 {
-	if (Space *available_space = GetSmallestAvailableSpace(needed_w))
-	{
-		if (Space *new_space = new Space)
-		{
-			new_space->x = available_space->x;
-			new_space->width = needed_w;
-			m_used_space_list.AddLast(new_space);
-
-			// Consume the used space from the available space
-			available_space->x += needed_w;
-			available_space->width -= needed_w;
-			m_available_space -= needed_w;
-
-			// Remove it if empty
-			if (!available_space->width)
-				m_free_space_list.Delete(available_space);
-			return new_space;
-		}
-	}
-	return nullptr;
+    if (Space *available_space = GetSmallestAvailableSpace(needed_w))
+    {
+        if (Space *new_space = new Space)
+        {
+            new_space->x = available_space->x;
+            new_space->width = needed_w;
+            m_used_space_list.AddLast(new_space);
+
+            // Consume the used space from the available space
+            available_space->x += needed_w;
+            available_space->width -= needed_w;
+            m_available_space -= needed_w;
+
+            // Remove it if empty
+            if (!available_space->width)
+                m_free_space_list.Delete(available_space);
+            return new_space;
+        }
+    }
+    return nullptr;
 }
 
 TBSpaceAllocator::Space *TBSpaceAllocator::GetSmallestAvailableSpace(int needed_w)
 {
-	assert(needed_w > 0);
-
-	// Add free space covering all available space if empty.
-	if (!m_free_space_list.HasLinks() && IsAllAvailable())
-	{
-		if (Space *fs = new Space)
-		{
-			fs->x = 0;
-			fs->width = m_available_space;
-			m_free_space_list.AddLast(fs);
-		}
-	}
-
-	// Check for the smallest space where we fit
-	Space *best_fs = nullptr;
-	for (Space *fs = m_free_space_list.GetFirst(); fs; fs = fs->GetNext())
-	{
-		if (needed_w == fs->width)
-			return fs; // It can't be better than a perfect match!
-		if (needed_w < fs->width)
-			if (!best_fs || fs->width < best_fs->width)
-				best_fs = fs;
-	}
-	return best_fs;
+    assert(needed_w > 0);
+
+    // Add free space covering all available space if empty.
+    if (!m_free_space_list.HasLinks() && IsAllAvailable())
+    {
+        if (Space *fs = new Space)
+        {
+            fs->x = 0;
+            fs->width = m_available_space;
+            m_free_space_list.AddLast(fs);
+        }
+    }
+
+    // Check for the smallest space where we fit
+    Space *best_fs = nullptr;
+    for (Space *fs = m_free_space_list.GetFirst(); fs; fs = fs->GetNext())
+    {
+        if (needed_w == fs->width)
+            return fs; // It can't be better than a perfect match!
+        if (needed_w < fs->width)
+            if (!best_fs || fs->width < best_fs->width)
+                best_fs = fs;
+    }
+    return best_fs;
 }
 
 void TBSpaceAllocator::FreeSpace(Space *space)
 {
-	m_used_space_list.Remove(space);
-	m_available_space += space->width;
-
-	// Find where in m_free_space_list we should insert the space,
-	// or which existing space we can extend.
-	Space *preceeding = nullptr;
-	Space *succeeding = nullptr;
-	for (Space *fs = m_free_space_list.GetFirst(); fs; fs = fs->GetNext())
-	{
-		if (fs->x < space->x)
-			preceeding = fs;
-		if (fs->x > space->x)
-		{
-			succeeding = fs;
-			break;
-		}
-	}
-	if (preceeding && preceeding->x + preceeding->width == space->x)
-	{
-		preceeding->width += space->width;
-		delete space;
-	}
-	else if (succeeding && succeeding->x == space->x + space->width)
-	{
-		succeeding->x -= space->width;
-		succeeding->width += space->width;
-		delete space;
-	}
-	else
-	{
-		if (preceeding)
-			m_free_space_list.AddAfter(space, preceeding);
-		else if (succeeding)
-			m_free_space_list.AddBefore(space, succeeding);
-		else
-		{
-			assert(!m_free_space_list.HasLinks());
-			m_free_space_list.AddLast(space);
-		}
-	}
-	// Merge free spaces
-	Space *fs = m_free_space_list.GetFirst();
-	while (fs)
-	{
-		Space *next_fs = fs->GetNext();
-		if (!next_fs)
-			break;
-		if (fs->x + fs->width == next_fs->x)
-		{
-			fs->width += next_fs->width;
-			m_free_space_list.Delete(next_fs);
-			continue;
-		}
-		fs = next_fs;
-	}
+    m_used_space_list.Remove(space);
+    m_available_space += space->width;
+
+    // Find where in m_free_space_list we should insert the space,
+    // or which existing space we can extend.
+    Space *preceeding = nullptr;
+    Space *succeeding = nullptr;
+    for (Space *fs = m_free_space_list.GetFirst(); fs; fs = fs->GetNext())
+    {
+        if (fs->x < space->x)
+            preceeding = fs;
+        if (fs->x > space->x)
+        {
+            succeeding = fs;
+            break;
+        }
+    }
+    if (preceeding && preceeding->x + preceeding->width == space->x)
+    {
+        preceeding->width += space->width;
+        delete space;
+    }
+    else if (succeeding && succeeding->x == space->x + space->width)
+    {
+        succeeding->x -= space->width;
+        succeeding->width += space->width;
+        delete space;
+    }
+    else
+    {
+        if (preceeding)
+            m_free_space_list.AddAfter(space, preceeding);
+        else if (succeeding)
+            m_free_space_list.AddBefore(space, succeeding);
+        else
+        {
+            assert(!m_free_space_list.HasLinks());
+            m_free_space_list.AddLast(space);
+        }
+    }
+    // Merge free spaces
+    Space *fs = m_free_space_list.GetFirst();
+    while (fs)
+    {
+        Space *next_fs = fs->GetNext();
+        if (!next_fs)
+            break;
+        if (fs->x + fs->width == next_fs->x)
+        {
+            fs->width += next_fs->width;
+            m_free_space_list.Delete(next_fs);
+            continue;
+        }
+        fs = next_fs;
+    }
 
 #ifdef TB_RUNTIME_DEBUG_INFO
-	// Check that free space is in order
-	Space *tmp = m_free_space_list.GetFirst();
-	int x = 0;
-	while (tmp)
-	{
-		assert(tmp->x >= x);
-		x = tmp->x + tmp->width;
-		tmp = tmp->GetNext();
-	}
+    // Check that free space is in order
+    Space *tmp = m_free_space_list.GetFirst();
+    int x = 0;
+    while (tmp)
+    {
+        assert(tmp->x >= x);
+        x = tmp->x + tmp->width;
+        tmp = tmp->GetNext();
+    }
 #endif // TB_RUNTIME_DEBUG_INFO
 }
 
 // == TBBitmapFragmentMap ===================================================================================
 
 TBBitmapFragmentMap::TBBitmapFragmentMap()
-	: m_bitmap_w(0)
-	, m_bitmap_h(0)
-	, m_bitmap_data(nullptr)
-	, m_bitmap(nullptr)
-	, m_need_update(false)
-	, m_allocated_pixels(0)
+    : m_bitmap_w(0)
+    , m_bitmap_h(0)
+    , m_bitmap_data(nullptr)
+    , m_bitmap(nullptr)
+    , m_need_update(false)
+    , m_allocated_pixels(0)
 {
 }
 
 bool TBBitmapFragmentMap::Init(int bitmap_w, int bitmap_h)
 {
-	m_bitmap_data = new uint32[bitmap_w * bitmap_h];
-	m_bitmap_w = bitmap_w;
-	m_bitmap_h = bitmap_h;
+    m_bitmap_data = new uint32[bitmap_w * bitmap_h];
+    m_bitmap_w = bitmap_w;
+    m_bitmap_h = bitmap_h;
 #ifdef TB_RUNTIME_DEBUG_INFO
-	if (m_bitmap_data)
-		memset(m_bitmap_data, 0x88, bitmap_w * bitmap_h * sizeof(uint32));
+    if (m_bitmap_data)
+        memset(m_bitmap_data, 0x88, bitmap_w * bitmap_h * sizeof(uint32));
 #endif
-	return m_bitmap_data ? true : false;
+    return m_bitmap_data ? true : false;
 }
 
 TBBitmapFragmentMap::~TBBitmapFragmentMap()
 {
-	delete m_bitmap;
-	delete [] m_bitmap_data;
+    delete m_bitmap;
+    delete [] m_bitmap_data;
 }
 
 TBBitmapFragment *TBBitmapFragmentMap::CreateNewFragment(int frag_w, int frag_h, int data_stride, uint32 *frag_data, bool add_border)
 {
-	// Finding available space works like this:
-	// The map size is sliced up horizontally in rows (initially just one row covering
-	// the entire map). When adding a new fragment, put it in the row with smallest height.
-	// If the smallest row is empty, it may slice the row to make a even smaller row.
-
-	// When a image is stretched up to a larger size, the filtering will read
-	// pixels closest (but outside) of the src_rect. When we pack images together
-	// those pixels would be read from neighbour images, so we must add border space
-	// around each image to avoid artifacts. We must also fill in that border with
-	// the "clamp" of the image itself so we don't get any filtering artifacts at all.
-	// Allways add border except when we're using the entire map for one fragment.
-	int border = 0;
-	int needed_w = frag_w;
-	int needed_h = frag_h;
-	if (add_border)
-	{
-		if (needed_w != m_bitmap_w || needed_h != m_bitmap_h)
-		{
-			border = 1;
-			needed_w += 2;
-			needed_h += 2;
-		}
-	}
-
-	// Snap the fragments to a certain granularity. This could maybe ease the stress
-	// on the space allocator when allocating & deallocating lots of small fragments.
-	// I'm not sure there is any performance issue though and it would be better to
-	// optimize the algorithm instead (so disabled it for now).
-	//const int granularity = 8;
-	//needed_w = (needed_w + granularity - 1) / granularity * granularity;
-	//needed_h = (needed_h + granularity - 1) / granularity * granularity;
-
-	if (!m_rows.GetNumItems())
-	{
-		// Create a row covering the entire bitmap.
-		TBFragmentSpaceAllocator *row;
-		if (!m_rows.GrowIfNeeded() || !(row = new TBFragmentSpaceAllocator(0, m_bitmap_w, m_bitmap_h)))
-			return nullptr;
-		m_rows.Add(row);
-	}
-	// Get the smallest row where we fit
-	int best_row_index = -1;
-	TBFragmentSpaceAllocator *best_row = nullptr;
-	for (int i = 0; i < m_rows.GetNumItems(); i++)
-	{
-		TBFragmentSpaceAllocator *row = m_rows[i];
-		if (!best_row || row->height < best_row->height)
-		{
-			// This is the best row so far, if we fit
-			if (needed_h <= row->height && row->HasSpace(needed_w))
-			{
-				best_row = row;
-				best_row_index = i;
-				if (needed_h == row->height)
-					break; // We can't find a smaller line, so we're done
-			}
-		}
-	}
-	// Return if we're full
-	if (!best_row)
-		return nullptr;
-	// If the row is unused, create a smaller row to only consume needed height for fragment
-	if (best_row->IsAllAvailable() && needed_h < best_row->height)
-	{
-		TBFragmentSpaceAllocator *row;
-		if (!m_rows.GrowIfNeeded() || !(row = new TBFragmentSpaceAllocator(best_row->y + needed_h, m_bitmap_w, best_row->height - needed_h)))
-			return nullptr;
-		// Keep the rows sorted from top to bottom
-		m_rows.Add(row, best_row_index + 1);
-		best_row->height = needed_h;
-	}
-	// Allocate the fragment and copy the fragment data into the map data.
-	if (TBFragmentSpaceAllocator::Space *space = best_row->AllocSpace(needed_w))
-	{
-		if (TBBitmapFragment *frag = new TBBitmapFragment)
-		{
-			frag->m_map = this;
-			frag->m_row = best_row;
-			frag->m_space = space;
-			frag->m_rect.Set(space->x + border, best_row->y + border, frag_w, frag_h);
-			frag->m_row_height = best_row->height;
-			frag->m_batch_id = 0xffffffff;
-			CopyData(frag, data_stride, frag_data, border);
-			m_need_update = true;
-			m_allocated_pixels += frag->m_space->width * frag->m_row->height;
-			return frag;
-		}
-		else
-			best_row->FreeSpace(space);
-	}
-	return nullptr;
+    // Finding available space works like this:
+    // The map size is sliced up horizontally in rows (initially just one row covering
+    // the entire map). When adding a new fragment, put it in the row with smallest height.
+    // If the smallest row is empty, it may slice the row to make a even smaller row.
+
+    // When a image is stretched up to a larger size, the filtering will read
+    // pixels closest (but outside) of the src_rect. When we pack images together
+    // those pixels would be read from neighbour images, so we must add border space
+    // around each image to avoid artifacts. We must also fill in that border with
+    // the "clamp" of the image itself so we don't get any filtering artifacts at all.
+    // Allways add border except when we're using the entire map for one fragment.
+    int border = 0;
+    int needed_w = frag_w;
+    int needed_h = frag_h;
+    if (add_border)
+    {
+        if (needed_w != m_bitmap_w || needed_h != m_bitmap_h)
+        {
+            border = 1;
+            needed_w += 2;
+            needed_h += 2;
+        }
+    }
+
+    // Snap the fragments to a certain granularity. This could maybe ease the stress
+    // on the space allocator when allocating & deallocating lots of small fragments.
+    // I'm not sure there is any performance issue though and it would be better to
+    // optimize the algorithm instead (so disabled it for now).
+    //const int granularity = 8;
+    //needed_w = (needed_w + granularity - 1) / granularity * granularity;
+    //needed_h = (needed_h + granularity - 1) / granularity * granularity;
+
+    if (!m_rows.GetNumItems())
+    {
+        // Create a row covering the entire bitmap.
+        TBFragmentSpaceAllocator *row;
+        if (!m_rows.GrowIfNeeded() || !(row = new TBFragmentSpaceAllocator(0, m_bitmap_w, m_bitmap_h)))
+            return nullptr;
+        m_rows.Add(row);
+    }
+    // Get the smallest row where we fit
+    int best_row_index = -1;
+    TBFragmentSpaceAllocator *best_row = nullptr;
+    for (int i = 0; i < m_rows.GetNumItems(); i++)
+    {
+        TBFragmentSpaceAllocator *row = m_rows[i];
+        if (!best_row || row->height < best_row->height)
+        {
+            // This is the best row so far, if we fit
+            if (needed_h <= row->height && row->HasSpace(needed_w))
+            {
+                best_row = row;
+                best_row_index = i;
+                if (needed_h == row->height)
+                    break; // We can't find a smaller line, so we're done
+            }
+        }
+    }
+    // Return if we're full
+    if (!best_row)
+        return nullptr;
+    // If the row is unused, create a smaller row to only consume needed height for fragment
+    if (best_row->IsAllAvailable() && needed_h < best_row->height)
+    {
+        TBFragmentSpaceAllocator *row;
+        if (!m_rows.GrowIfNeeded() || !(row = new TBFragmentSpaceAllocator(best_row->y + needed_h, m_bitmap_w, best_row->height - needed_h)))
+            return nullptr;
+        // Keep the rows sorted from top to bottom
+        m_rows.Add(row, best_row_index + 1);
+        best_row->height = needed_h;
+    }
+    // Allocate the fragment and copy the fragment data into the map data.
+    if (TBFragmentSpaceAllocator::Space *space = best_row->AllocSpace(needed_w))
+    {
+        if (TBBitmapFragment *frag = new TBBitmapFragment)
+        {
+            frag->m_map = this;
+            frag->m_row = best_row;
+            frag->m_space = space;
+            frag->m_rect.Set(space->x + border, best_row->y + border, frag_w, frag_h);
+            frag->m_row_height = best_row->height;
+            frag->m_batch_id = 0xffffffff;
+            CopyData(frag, data_stride, frag_data, border);
+            m_need_update = true;
+            m_allocated_pixels += frag->m_space->width * frag->m_row->height;
+            return frag;
+        }
+        else
+            best_row->FreeSpace(space);
+    }
+    return nullptr;
 }
 
 void TBBitmapFragmentMap::FreeFragmentSpace(TBBitmapFragment *frag)
 {
-	if (!frag)
-		return;
-	assert(frag->m_map == this);
+    if (!frag)
+        return;
+    assert(frag->m_map == this);
 
 #ifdef TB_RUNTIME_DEBUG_INFO
-	// Debug code to clear the area in debug builds so it's easier to
-	// see & debug the allocation & deallocation of fragments in maps.
-	if (uint32 *data32 = new uint32[frag->m_space->width * frag->m_row->height])
-	{
-		static int c = 0;
-		memset(data32, (c++) * 32, sizeof(uint32) * frag->m_space->width * frag->m_row->height);
-		CopyData(frag, frag->m_space->width, data32, false);
-		m_need_update = true;
-		delete [] data32;
-	}
+    // Debug code to clear the area in debug builds so it's easier to
+    // see & debug the allocation & deallocation of fragments in maps.
+    if (uint32 *data32 = new uint32[frag->m_space->width * frag->m_row->height])
+    {
+        static int c = 0;
+        memset(data32, (c++) * 32, sizeof(uint32) * frag->m_space->width * frag->m_row->height);
+        CopyData(frag, frag->m_space->width, data32, false);
+        m_need_update = true;
+        delete [] data32;
+    }
 #endif // TB_RUNTIME_DEBUG_INFO
 
-	m_allocated_pixels -= frag->m_space->width * frag->m_row->height;
-	frag->m_row->FreeSpace(frag->m_space);
-	frag->m_space = nullptr;
-	frag->m_row_height = 0;
-
-	// If the row is now empty, merge empty rows so larger fragments
-	// have a chance of allocating the space.
-	if (frag->m_row->IsAllAvailable())
-	{
-		for (int i = 0; i < m_rows.GetNumItems() - 1; i++)
-		{
-			assert(i >= 0);
-			assert(i < m_rows.GetNumItems() - 1);
-			TBFragmentSpaceAllocator *row = m_rows.Get(i);
-			TBFragmentSpaceAllocator *next_row = m_rows.Get(i + 1);
-			if (row->IsAllAvailable() && next_row->IsAllAvailable())
-			{
-				row->height += next_row->height;
-				m_rows.Delete(i + 1);
-				i--;
-			}
-		}
-	}
+    m_allocated_pixels -= frag->m_space->width * frag->m_row->height;
+    frag->m_row->FreeSpace(frag->m_space);
+    frag->m_space = nullptr;
+    frag->m_row_height = 0;
+
+    // If the row is now empty, merge empty rows so larger fragments
+    // have a chance of allocating the space.
+    if (frag->m_row->IsAllAvailable())
+    {
+        for (int i = 0; i < m_rows.GetNumItems() - 1; i++)
+        {
+            assert(i >= 0);
+            assert(i < m_rows.GetNumItems() - 1);
+            TBFragmentSpaceAllocator *row = m_rows.Get(i);
+            TBFragmentSpaceAllocator *next_row = m_rows.Get(i + 1);
+            if (row->IsAllAvailable() && next_row->IsAllAvailable())
+            {
+                row->height += next_row->height;
+                m_rows.Delete(i + 1);
+                i--;
+            }
+        }
+    }
 }
 
 void TBBitmapFragmentMap::CopyData(TBBitmapFragment *frag, int data_stride, uint32 *frag_data, int border)
 {
-	// Copy the bitmap data
-	uint32 *dst = m_bitmap_data + frag->m_rect.x + frag->m_rect.y * m_bitmap_w;
-	uint32 *src = frag_data;
-	for (int i = 0; i < frag->m_rect.h; i++)
-	{
-		memcpy(dst, src, frag->m_rect.w * sizeof(uint32));
-		dst += m_bitmap_w;
-		src += data_stride;
-	}
-	// Copy the bitmap data to the border around the fragment
-	if (border)
-	{
-		TBRect rect = frag->m_rect.Expand(border, border);
-		// Copy vertical edges
-		dst = m_bitmap_data + rect.x + (rect.y + 1) * m_bitmap_w;
-		src = frag_data;
-		for (int i = 0; i < frag->m_rect.h; i++)
-		{
-			dst[0] = src[0] & 0x00ffffff;
-			dst[rect.w - 1] = src[frag->m_rect.w - 1] & 0x00ffffff;
-			dst += m_bitmap_w;
-			src += data_stride;
-		}
-		// Copy horizontal edges
-		dst = m_bitmap_data + rect.x + 1 + rect.y * m_bitmap_w;
-		src = frag_data;
-		for (int i = 0; i < frag->m_rect.w; i++)
-			dst[i] = src[i] & 0x00ffffff;
-		dst = m_bitmap_data + rect.x + 1 + (rect.y + rect.h - 1) * m_bitmap_w;
-		src = frag_data + (frag->m_rect.h - 1) * data_stride;
-		for (int i = 0; i < frag->m_rect.w; i++)
-			dst[i] = src[i] & 0x00ffffff;
-	}
+    // Copy the bitmap data
+    uint32 *dst = m_bitmap_data + frag->m_rect.x + frag->m_rect.y * m_bitmap_w;
+    uint32 *src = frag_data;
+    for (int i = 0; i < frag->m_rect.h; i++)
+    {
+        memcpy(dst, src, frag->m_rect.w * sizeof(uint32));
+        dst += m_bitmap_w;
+        src += data_stride;
+    }
+    // Copy the bitmap data to the border around the fragment
+    if (border)
+    {
+        TBRect rect = frag->m_rect.Expand(border, border);
+        // Copy vertical edges
+        dst = m_bitmap_data + rect.x + (rect.y + 1) * m_bitmap_w;
+        src = frag_data;
+        for (int i = 0; i < frag->m_rect.h; i++)
+        {
+            dst[0] = src[0] & 0x00ffffff;
+            dst[rect.w - 1] = src[frag->m_rect.w - 1] & 0x00ffffff;
+            dst += m_bitmap_w;
+            src += data_stride;
+        }
+        // Copy horizontal edges
+        dst = m_bitmap_data + rect.x + 1 + rect.y * m_bitmap_w;
+        src = frag_data;
+        for (int i = 0; i < frag->m_rect.w; i++)
+            dst[i] = src[i] & 0x00ffffff;
+        dst = m_bitmap_data + rect.x + 1 + (rect.y + rect.h - 1) * m_bitmap_w;
+        src = frag_data + (frag->m_rect.h - 1) * data_stride;
+        for (int i = 0; i < frag->m_rect.w; i++)
+            dst[i] = src[i] & 0x00ffffff;
+    }
 }
 
 TBBitmap *TBBitmapFragmentMap::GetBitmap(TB_VALIDATE_TYPE validate_type)
 {
-	if (m_bitmap && validate_type == TB_VALIDATE_FIRST_TIME)
-		return m_bitmap;
-	ValidateBitmap();
-	return m_bitmap;
+    if (m_bitmap && validate_type == TB_VALIDATE_FIRST_TIME)
+        return m_bitmap;
+    ValidateBitmap();
+    return m_bitmap;
 }
 
 bool TBBitmapFragmentMap::ValidateBitmap()
 {
-	if (m_need_update)
-	{
-		if (m_bitmap)
-			m_bitmap->SetData(m_bitmap_data);
-		else
-			m_bitmap = g_renderer->CreateBitmap(m_bitmap_w, m_bitmap_h, m_bitmap_data);
-		m_need_update = false;
-	}
-	return m_bitmap ? true : false;
+    if (m_need_update)
+    {
+        if (m_bitmap)
+            m_bitmap->SetData(m_bitmap_data);
+        else
+            m_bitmap = g_renderer->CreateBitmap(m_bitmap_w, m_bitmap_h, m_bitmap_data);
+        m_need_update = false;
+    }
+    return m_bitmap ? true : false;
 }
 
 void TBBitmapFragmentMap::DeleteBitmap()
 {
-	delete m_bitmap;
-	m_bitmap = nullptr;
-	m_need_update = true;
+    delete m_bitmap;
+    m_bitmap = nullptr;
+    m_need_update = true;
 }
 
 // == TBBitmapFragmentManager =============================================================================
 
 TBBitmapFragmentManager::TBBitmapFragmentManager()
-	: m_num_maps_limit(0)
-	, m_add_border(false)
-	, m_default_map_w(512)
-	, m_default_map_h(512)
+    : m_num_maps_limit(0)
+    , m_add_border(false)
+    , m_default_map_w(512)
+    , m_default_map_h(512)
 {
 }
 
 TBBitmapFragmentManager::~TBBitmapFragmentManager()
 {
-	Clear();
+    Clear();
 }
 
 TBBitmapFragment *TBBitmapFragmentManager::GetFragmentFromFile(const char *filename, bool dedicated_map)
 {
-	TBID id(filename);
+    TBID id(filename);
 
-	// If we already have a fragment for this filename, return that
-	TBBitmapFragment *frag = m_fragments.Get(id);
-	if (frag)
-		return frag;
+    // If we already have a fragment for this filename, return that
+    TBBitmapFragment *frag = m_fragments.Get(id);
+    if (frag)
+        return frag;
 
-	// Load the file
-	TBImageLoader *img = TBImageLoader::CreateFromFile(filename);
-	if (!img)
-		return nullptr;
+    // Load the file
+    TBImageLoader *img = TBImageLoader::CreateFromFile(filename);
+    if (!img)
+        return nullptr;
 
-	frag = CreateNewFragment(id, dedicated_map, img->Width(), img->Height(), img->Width(), img->Data());
-	delete img;
-	return frag;
+    frag = CreateNewFragment(id, dedicated_map, img->Width(), img->Height(), img->Width(), img->Data());
+    delete img;
+    return frag;
 }
 
 TBBitmapFragment *TBBitmapFragmentManager::CreateNewFragment(const TBID &id, bool dedicated_map,
-															 int data_w, int data_h, int data_stride,
-															 uint32 *data)
+                                                             int data_w, int data_h, int data_stride,
+                                                             uint32 *data)
 {
-	assert(!GetFragment(id));
-
-	TBBitmapFragment *frag = nullptr;
-
-	// Create a fragment in any of the fragment maps. Doing it in the reverse order
-	// would be faster since it's most likely to succeed, but we want to maximize
-	// the amount of fragments per map, so do it in the creation order.
-	if (!dedicated_map)
-	{
-		for (int i = 0; i < m_fragment_maps.GetNumItems(); i++)
-		{
-			if ((frag = m_fragment_maps[i]->CreateNewFragment(data_w, data_h, data_stride, data, m_add_border)))
-				break;
-		}
-	}
-	// If we couldn't create the fragment in any map, create a new map where we know it will fit.
-	bool allow_another_map = (m_num_maps_limit == 0 || m_fragment_maps.GetNumItems() < m_num_maps_limit);
-	if (!frag && allow_another_map && m_fragment_maps.GrowIfNeeded())
-	{
-		int po2w = TBGetNearestPowerOfTwo(MAX(data_w, m_default_map_w));
-		int po2h = TBGetNearestPowerOfTwo(MAX(data_h, m_default_map_h));
-		if (dedicated_map)
-		{
-			po2w = TBGetNearestPowerOfTwo(data_w);
-			po2h = TBGetNearestPowerOfTwo(data_h);
-		}
-		TBBitmapFragmentMap *fm = new TBBitmapFragmentMap();
-		if (fm && fm->Init(po2w, po2h))
-		{
-			m_fragment_maps.Add(fm);
-			frag = fm->CreateNewFragment(data_w, data_h, data_stride, data, m_add_border);
-		}
-		else
-			delete fm;
-	}
-	// Finally, add the new fragment to the hash.
-	if (frag && m_fragments.Add(id, frag))
-	{
-		frag->m_id = id;
-		return frag;
-	}
-	delete frag;
-	return nullptr;
+    assert(!GetFragment(id));
+
+    TBBitmapFragment *frag = nullptr;
+
+    // Create a fragment in any of the fragment maps. Doing it in the reverse order
+    // would be faster since it's most likely to succeed, but we want to maximize
+    // the amount of fragments per map, so do it in the creation order.
+    if (!dedicated_map)
+    {
+        for (int i = 0; i < m_fragment_maps.GetNumItems(); i++)
+        {
+            if ((frag = m_fragment_maps[i]->CreateNewFragment(data_w, data_h, data_stride, data, m_add_border)))
+                break;
+        }
+    }
+    // If we couldn't create the fragment in any map, create a new map where we know it will fit.
+    bool allow_another_map = (m_num_maps_limit == 0 || m_fragment_maps.GetNumItems() < m_num_maps_limit);
+    if (!frag && allow_another_map && m_fragment_maps.GrowIfNeeded())
+    {
+        int po2w = TBGetNearestPowerOfTwo(MAX(data_w, m_default_map_w));
+        int po2h = TBGetNearestPowerOfTwo(MAX(data_h, m_default_map_h));
+        if (dedicated_map)
+        {
+            po2w = TBGetNearestPowerOfTwo(data_w);
+            po2h = TBGetNearestPowerOfTwo(data_h);
+        }
+        TBBitmapFragmentMap *fm = new TBBitmapFragmentMap();
+        if (fm && fm->Init(po2w, po2h))
+        {
+            m_fragment_maps.Add(fm);
+            frag = fm->CreateNewFragment(data_w, data_h, data_stride, data, m_add_border);
+        }
+        else
+            delete fm;
+    }
+    // Finally, add the new fragment to the hash.
+    if (frag && m_fragments.Add(id, frag))
+    {
+        frag->m_id = id;
+        return frag;
+    }
+    delete frag;
+    return nullptr;
 }
 
 void TBBitmapFragmentManager::FreeFragment(TBBitmapFragment *frag)
 {
-	if (frag)
-	{
-		g_renderer->FlushBitmapFragment(frag);
-
-		TBBitmapFragmentMap *map = frag->m_map;
-		frag->m_map->FreeFragmentSpace(frag);
-		m_fragments.Delete(frag->m_id);
-
-		// If the map is now empty, delete it.
-		if (map->m_allocated_pixels == 0)
-			m_fragment_maps.Delete(m_fragment_maps.Find(map));
-	}
+    if (frag)
+    {
+        g_renderer->FlushBitmapFragment(frag);
+
+        TBBitmapFragmentMap *map = frag->m_map;
+        frag->m_map->FreeFragmentSpace(frag);
+        m_fragments.Delete(frag->m_id);
+
+        // If the map is now empty, delete it.
+        if (map->m_allocated_pixels == 0)
+            m_fragment_maps.Delete(m_fragment_maps.Find(map));
+    }
 }
 
 TBBitmapFragment *TBBitmapFragmentManager::GetFragment(const TBID &id) const
 {
-	return m_fragments.Get(id);
+    return m_fragments.Get(id);
 }
 
 void TBBitmapFragmentManager::Clear()
 {
-	m_fragment_maps.DeleteAll();
-	m_fragments.DeleteAll();
+    m_fragment_maps.DeleteAll();
+    m_fragments.DeleteAll();
 }
 
 bool TBBitmapFragmentManager::ValidateBitmaps()
 {
-	bool success = true;
-	for (int i = 0; i < m_fragment_maps.GetNumItems(); i++)
-		if (!m_fragment_maps[i]->ValidateBitmap())
-			success = false;
-	return success;
+    bool success = true;
+    for (int i = 0; i < m_fragment_maps.GetNumItems(); i++)
+        if (!m_fragment_maps[i]->ValidateBitmap())
+            success = false;
+    return success;
 }
 
 void TBBitmapFragmentManager::DeleteBitmaps()
 {
-	for (int i = 0; i < m_fragment_maps.GetNumItems(); i++)
-		m_fragment_maps[i]->DeleteBitmap();
+    for (int i = 0; i < m_fragment_maps.GetNumItems(); i++)
+        m_fragment_maps[i]->DeleteBitmap();
 }
 
 void TBBitmapFragmentManager::SetNumMapsLimit(int num_maps_limit)
 {
-	m_num_maps_limit = num_maps_limit;
+    m_num_maps_limit = num_maps_limit;
 }
 
 void TBBitmapFragmentManager::SetDefaultMapSize(int w, int h)
 {
-	assert(TBGetNearestPowerOfTwo(w) == w);
-	assert(TBGetNearestPowerOfTwo(h) == h);
-	m_default_map_w = w;
-	m_default_map_h = h;
+    assert(TBGetNearestPowerOfTwo(w) == w);
+    assert(TBGetNearestPowerOfTwo(h) == h);
+    m_default_map_w = w;
+    m_default_map_h = h;
 }
 
 int TBBitmapFragmentManager::GetUseRatio() const
 {
-	int used = 0;
-	int total = 0;
-	for (int i = 0; i < m_fragment_maps.GetNumItems(); i++)
-	{
-		used += m_fragment_maps[i]->m_allocated_pixels;
-		total += m_fragment_maps[i]->m_bitmap_w * m_fragment_maps[i]->m_bitmap_h;
-	}
-	return total ? (used * 100) / total : 0;
+    int used = 0;
+    int total = 0;
+    for (int i = 0; i < m_fragment_maps.GetNumItems(); i++)
+    {
+        used += m_fragment_maps[i]->m_allocated_pixels;
+        total += m_fragment_maps[i]->m_bitmap_w * m_fragment_maps[i]->m_bitmap_h;
+    }
+    return total ? (used * 100) / total : 0;
 }
 
 #ifdef TB_RUNTIME_DEBUG_INFO
 void TBBitmapFragmentManager::Debug()
 {
-	int x = 0;
-	for (int i = 0; i < m_fragment_maps.GetNumItems(); i++)
-	{
-		TBBitmapFragmentMap *fm = m_fragment_maps[i];
-		if (TBBitmap *bitmap = fm->GetBitmap())
-			g_renderer->DrawBitmap(TBRect(x, 0, fm->m_bitmap_w, fm->m_bitmap_h), TBRect(0, 0, fm->m_bitmap_w, fm->m_bitmap_h), bitmap);
-		x += fm->m_bitmap_w + 5;
-	}
+    int x = 0;
+    for (int i = 0; i < m_fragment_maps.GetNumItems(); i++)
+    {
+        TBBitmapFragmentMap *fm = m_fragment_maps[i];
+        if (TBBitmap *bitmap = fm->GetBitmap())
+            g_renderer->DrawBitmap(TBRect(x, 0, fm->m_bitmap_w, fm->m_bitmap_h), TBRect(0, 0, fm->m_bitmap_w, fm->m_bitmap_h), bitmap);
+        x += fm->m_bitmap_w + 5;
+    }
 }
 #endif // TB_RUNTIME_DEBUG_INFO
 

+ 160 - 160
Source/ThirdParty/TurboBadger/tb_bitmap_fragment.h

@@ -19,232 +19,232 @@ class TBBitmapFragment;
 class TBBitmap;
 
 /** Return the nearest power of two from val.
-	F.ex 110 -> 128, 256->256, 257->512 etc. */
+    F.ex 110 -> 128, 256->256, 257->512 etc. */
 int TBGetNearestPowerOfTwo(int val);
 
 /** TBImageloader is a class used to load skin images. It can be implemented
-	in any way the system wants, but the system has to provide a image loader
-	capable of handling all image formats used in the skin. */
+    in any way the system wants, but the system has to provide a image loader
+    capable of handling all image formats used in the skin. */
 class TBImageLoader
 {
 public:
-	/** Static method used to create an image loader. The system must implement this
-		function and create an implementation of the TBImageLoader interface. */
-	static TBImageLoader *CreateFromFile(const char *filename);
+    /** Static method used to create an image loader. The system must implement this
+        function and create an implementation of the TBImageLoader interface. */
+    static TBImageLoader *CreateFromFile(const char *filename);
 
-	virtual ~TBImageLoader() {}
+    virtual ~TBImageLoader() {}
 
-	/** Return the width of the loaded bitmap. */
-	virtual int Width() = 0;
+    /** Return the width of the loaded bitmap. */
+    virtual int Width() = 0;
 
-	/** Return the height of the loaded bitmap. */
-	virtual int Height() = 0;
+    /** Return the height of the loaded bitmap. */
+    virtual int Height() = 0;
 
-	/** Return the data of the loaded bitmap.
-		This data should always be in 32bit RGBA format. */
-	virtual uint32 *Data() = 0;
+    /** Return the data of the loaded bitmap.
+        This data should always be in 32bit RGBA format. */
+    virtual uint32 *Data() = 0;
 };
 
 /** Allocator of space out of a given available space. */
 class TBSpaceAllocator
 {
 public:
-	/** A chunk of space */
-	class Space : public TBLinkOf<Space>
-	{
-	public:
-		int x, width;
-	};
+    /** A chunk of space */
+    class Space : public TBLinkOf<Space>
+    {
+    public:
+        int x, width;
+    };
 
-	TBSpaceAllocator(int available_space)
-		: m_available_space(available_space) { }
+    TBSpaceAllocator(int available_space)
+        : m_available_space(available_space) { }
 
-	/** Return true if no allocations are currently live using this allocator. */
-	bool IsAllAvailable() const { return !m_used_space_list.HasLinks(); }
+    /** Return true if no allocations are currently live using this allocator. */
+    bool IsAllAvailable() const { return !m_used_space_list.HasLinks(); }
 
-	/** Return true if the given width is currently available. */
-	bool HasSpace(int needed_w) const;
+    /** Return true if the given width is currently available. */
+    bool HasSpace(int needed_w) const;
 
-	/** Allocate the given space and return the Space, or nullptr on error. */
-	Space *AllocSpace(int needed_w);
+    /** Allocate the given space and return the Space, or nullptr on error. */
+    Space *AllocSpace(int needed_w);
 
-	/** Free the given space so it is available for new allocations. */
-	void FreeSpace(Space *space);
+    /** Free the given space so it is available for new allocations. */
+    void FreeSpace(Space *space);
 private:
-	Space *GetSmallestAvailableSpace(int needed_w);
-	int m_available_space;
-	TBLinkListAutoDeleteOf<Space> m_free_space_list;
-	TBLinkListAutoDeleteOf<Space> m_used_space_list;
+    Space *GetSmallestAvailableSpace(int needed_w);
+    int m_available_space;
+    TBLinkListAutoDeleteOf<Space> m_free_space_list;
+    TBLinkListAutoDeleteOf<Space> m_used_space_list;
 };
 
 /** Allocates space for TBBitmapFragment in a row (used in TBBitmapFragmentMap). */
 class TBFragmentSpaceAllocator : public TBSpaceAllocator
 {
 public:
-	TBFragmentSpaceAllocator(int y, int width, int height)
-		: TBSpaceAllocator(width), y(y), height(height) {}
+    TBFragmentSpaceAllocator(int y, int width, int height)
+        : TBSpaceAllocator(width), y(y), height(height) {}
 
-	int y, height;
+    int y, height;
 };
 
 /** Specify when the bitmap should be validated when calling TBBitmapFragmentMap::GetBitmap. */
 enum TB_VALIDATE_TYPE {
 
-	/** Always validate the bitmap (The bitmap is updated if needed) */
-	TB_VALIDATE_ALWAYS,
+    /** Always validate the bitmap (The bitmap is updated if needed) */
+    TB_VALIDATE_ALWAYS,
 
-	/** Only validate if the bitmap does not yet exist (Make sure there is
-		a valid bitmap pointer, but the data is not necessarily updated) */
-	TB_VALIDATE_FIRST_TIME
+    /** Only validate if the bitmap does not yet exist (Make sure there is
+        a valid bitmap pointer, but the data is not necessarily updated) */
+    TB_VALIDATE_FIRST_TIME
 };
 
 /** TBBitmapFragmentMap is used to pack multiple bitmaps into a single TBBitmap.
-	When initialized (in a size suitable for a TBBitmap) is also creates a software buffer
-	that will make up the TBBitmap when all fragments have been added. */
+    When initialized (in a size suitable for a TBBitmap) is also creates a software buffer
+    that will make up the TBBitmap when all fragments have been added. */
 class TBBitmapFragmentMap
 {
 public:
-	TBBitmapFragmentMap();
-	~TBBitmapFragmentMap();
+    TBBitmapFragmentMap();
+    ~TBBitmapFragmentMap();
 
-	/** Initialize the map with the given size. The size should be a power of two since
-		it will be used to create a TBBitmap (texture memory). */
-	bool Init(int bitmap_w, int bitmap_h);
+    /** Initialize the map with the given size. The size should be a power of two since
+        it will be used to create a TBBitmap (texture memory). */
+    bool Init(int bitmap_w, int bitmap_h);
 
-	/** Create a new fragment with the given size and data in this map.
-		Returns nullptr if there is not enough room in this map or on any other fail. */
-	TBBitmapFragment *CreateNewFragment(int frag_w, int frag_h, int data_stride, uint32 *frag_data, bool add_border);
+    /** Create a new fragment with the given size and data in this map.
+        Returns nullptr if there is not enough room in this map or on any other fail. */
+    TBBitmapFragment *CreateNewFragment(int frag_w, int frag_h, int data_stride, uint32 *frag_data, bool add_border);
 
-	/** Free up the space used by the given fragment, so that other fragments can take its place. */
-	void FreeFragmentSpace(TBBitmapFragment *frag);
+    /** Free up the space used by the given fragment, so that other fragments can take its place. */
+    void FreeFragmentSpace(TBBitmapFragment *frag);
 
-	/** Return the bitmap for this map.
-		By default, the bitmap is validated if needed before returning (See TB_VALIDATE_TYPE) */
-	TBBitmap *GetBitmap(TB_VALIDATE_TYPE validate_type = TB_VALIDATE_ALWAYS);
+    /** Return the bitmap for this map.
+        By default, the bitmap is validated if needed before returning (See TB_VALIDATE_TYPE) */
+    TBBitmap *GetBitmap(TB_VALIDATE_TYPE validate_type = TB_VALIDATE_ALWAYS);
 private:
-	friend class TBBitmapFragmentManager;
-	bool ValidateBitmap();
-	void DeleteBitmap();
-	void CopyData(TBBitmapFragment *frag, int data_stride, uint32 *frag_data, int border);
-	TBListAutoDeleteOf<TBFragmentSpaceAllocator> m_rows;
-	int m_bitmap_w, m_bitmap_h;
-	uint32 *m_bitmap_data;
-	TBBitmap *m_bitmap;
-	bool m_need_update;
-	int m_allocated_pixels;
+    friend class TBBitmapFragmentManager;
+    bool ValidateBitmap();
+    void DeleteBitmap();
+    void CopyData(TBBitmapFragment *frag, int data_stride, uint32 *frag_data, int border);
+    TBListAutoDeleteOf<TBFragmentSpaceAllocator> m_rows;
+    int m_bitmap_w, m_bitmap_h;
+    uint32 *m_bitmap_data;
+    TBBitmap *m_bitmap;
+    bool m_need_update;
+    int m_allocated_pixels;
 };
 
 /** TBBitmapFragment represents a sub part of a TBBitmap.
-	It's owned by TBBitmapFragmentManager which pack multiple
-	TBBitmapFragment within TBBitmaps to reduce texture switching. */
+    It's owned by TBBitmapFragmentManager which pack multiple
+    TBBitmapFragment within TBBitmaps to reduce texture switching. */
 class TBBitmapFragment
 {
 public:
-	/** Return the width of the bitmap fragment. */
-	int Width() const { return m_rect.w; }
+    /** Return the width of the bitmap fragment. */
+    int Width() const { return m_rect.w; }
 
-	/** Return the height of the bitmap fragment. */
-	int Height() const { return m_rect.h; }
+    /** Return the height of the bitmap fragment. */
+    int Height() const { return m_rect.h; }
 
-	/** Return the bitmap for this fragment.
-		By default, the bitmap is validated if needed before returning (See TB_VALIDATE_TYPE) */
-	TBBitmap *GetBitmap(TB_VALIDATE_TYPE validate_type = TB_VALIDATE_ALWAYS) { return m_map->GetBitmap(validate_type); }
+    /** Return the bitmap for this fragment.
+        By default, the bitmap is validated if needed before returning (See TB_VALIDATE_TYPE) */
+    TBBitmap *GetBitmap(TB_VALIDATE_TYPE validate_type = TB_VALIDATE_ALWAYS) { return m_map->GetBitmap(validate_type); }
 
-	/** Return the height allocated to this fragment. This may be larger than Height() depending
-		of the internal allocation of fragments in a map. It should rarely be used. */
-	int GetAllocatedHeight() const { return m_row_height; }
+    /** Return the height allocated to this fragment. This may be larger than Height() depending
+        of the internal allocation of fragments in a map. It should rarely be used. */
+    int GetAllocatedHeight() const { return m_row_height; }
 public:
-	TBBitmapFragmentMap *m_map;
-	TBRect m_rect;
-	TBFragmentSpaceAllocator *m_row;
-	TBFragmentSpaceAllocator::Space *m_space;
-	TBID m_id;
-	int m_row_height;
-
-	/** This uint32 is reserved for batching renderer backends. It's not used
-		internally, but always initialized to 0xffffffff for all new fragments. */
-	uint32 m_batch_id;
+    TBBitmapFragmentMap *m_map;
+    TBRect m_rect;
+    TBFragmentSpaceAllocator *m_row;
+    TBFragmentSpaceAllocator::Space *m_space;
+    TBID m_id;
+    int m_row_height;
+
+    /** This uint32 is reserved for batching renderer backends. It's not used
+        internally, but always initialized to 0xffffffff for all new fragments. */
+    uint32 m_batch_id;
 };
 
 /** TBBitmapFragmentManager manages loading bitmaps of arbitrary size,
-	pack as many of them into as few TBBitmap as possible.
+    pack as many of them into as few TBBitmap as possible.
 
-	It also makes sure that only one instance of each file is loaded,
-	so f.ex loading "foo.png" many times still load and allocate one
-	TBBitmapFragment. */
+    It also makes sure that only one instance of each file is loaded,
+    so f.ex loading "foo.png" many times still load and allocate one
+    TBBitmapFragment. */
 class TBBitmapFragmentManager
 {
 public:
-	TBBitmapFragmentManager();
-	~TBBitmapFragmentManager();
-
-	/** Set to true if a 1px border should be added to new fragments so stretched
-		drawing won't get filtering artifacts at the edges (default is disabled). */
-	void SetAddBorder(bool add_border) { m_add_border = add_border; }
-	bool GetAddBorder() const { return m_add_border; }
-
-	/** Get the fragment with the given image filename. If it's not already loaded,
-		it will be loaded into a new fragment with the filename as id.
-		returns nullptr on fail. */
-	TBBitmapFragment *GetFragmentFromFile(const char *filename, bool dedicated_map);
-
-	/** Get the fragment with the given id, or nullptr if it doesn't exist. */
-	TBBitmapFragment *GetFragment(const TBID &id) const;
-
-	/** Create a new fragment from the given data.
-		@param id The id that should be used to identify the fragment.
-		@param dedicated_map if true, it will get a dedicated map.
-		@param data_w the width of the data.
-		@param data_h the height of the data.
-		@param data_stride the number of pixels in a row of the input data.
-		@param data pointer to the data in BGRA32 format. */
-	TBBitmapFragment *CreateNewFragment(const TBID &id, bool dedicated_map,
-										int data_w, int data_h, int data_stride,
-										uint32 *data);
-
-	/** Delete the given fragment and free the space it used in its map,
-		so that other fragments can take its place. */
-	void FreeFragment(TBBitmapFragment *frag);
-
-	/** Clear all loaded bitmaps and all created bitmap fragments and maps.
-		After this call, do not keep any pointers to any TBBitmapFragment created
-		by this fragment manager. */
-	void Clear();
-
-	/** Validate bitmaps on fragment maps that has changed. */
-	bool ValidateBitmaps();
-
-	/** Delete all bitmaps in all fragment maps in this manager.
-		The bitmaps will be recreated automatically when needed, or when
-		calling ValidateBitmaps. You do not need to call this, except when
-		the context is lost and all bitmaps must be forgotten. */
-	void DeleteBitmaps();
-
-	/** Get number of fragment maps that is currently used. */
-	int GetNumMaps() const { return m_fragment_maps.GetNumItems(); }
-
-	/** Set the number of maps (TBBitmaps) this manager should be allowed to create.
-		If a new fragment can't fit into any existing bitmap and the limit is reached,
-		the fragment creation will fail. Set to 0 for unlimited (default). */
-	void SetNumMapsLimit(int num_maps_limit);
-
-	/** Set the default size of new fragment maps. These must be power of two. */
-	void SetDefaultMapSize(int w, int h);
-
-	/** Get the amount (in percent) of space that is currently occupied by all maps
-		in this fragment manager. */
-	int GetUseRatio() const;
+    TBBitmapFragmentManager();
+    ~TBBitmapFragmentManager();
+
+    /** Set to true if a 1px border should be added to new fragments so stretched
+        drawing won't get filtering artifacts at the edges (default is disabled). */
+    void SetAddBorder(bool add_border) { m_add_border = add_border; }
+    bool GetAddBorder() const { return m_add_border; }
+
+    /** Get the fragment with the given image filename. If it's not already loaded,
+        it will be loaded into a new fragment with the filename as id.
+        returns nullptr on fail. */
+    TBBitmapFragment *GetFragmentFromFile(const char *filename, bool dedicated_map);
+
+    /** Get the fragment with the given id, or nullptr if it doesn't exist. */
+    TBBitmapFragment *GetFragment(const TBID &id) const;
+
+    /** Create a new fragment from the given data.
+        @param id The id that should be used to identify the fragment.
+        @param dedicated_map if true, it will get a dedicated map.
+        @param data_w the width of the data.
+        @param data_h the height of the data.
+        @param data_stride the number of pixels in a row of the input data.
+        @param data pointer to the data in BGRA32 format. */
+    TBBitmapFragment *CreateNewFragment(const TBID &id, bool dedicated_map,
+                                        int data_w, int data_h, int data_stride,
+                                        uint32 *data);
+
+    /** Delete the given fragment and free the space it used in its map,
+        so that other fragments can take its place. */
+    void FreeFragment(TBBitmapFragment *frag);
+
+    /** Clear all loaded bitmaps and all created bitmap fragments and maps.
+        After this call, do not keep any pointers to any TBBitmapFragment created
+        by this fragment manager. */
+    void Clear();
+
+    /** Validate bitmaps on fragment maps that has changed. */
+    bool ValidateBitmaps();
+
+    /** Delete all bitmaps in all fragment maps in this manager.
+        The bitmaps will be recreated automatically when needed, or when
+        calling ValidateBitmaps. You do not need to call this, except when
+        the context is lost and all bitmaps must be forgotten. */
+    void DeleteBitmaps();
+
+    /** Get number of fragment maps that is currently used. */
+    int GetNumMaps() const { return m_fragment_maps.GetNumItems(); }
+
+    /** Set the number of maps (TBBitmaps) this manager should be allowed to create.
+        If a new fragment can't fit into any existing bitmap and the limit is reached,
+        the fragment creation will fail. Set to 0 for unlimited (default). */
+    void SetNumMapsLimit(int num_maps_limit);
+
+    /** Set the default size of new fragment maps. These must be power of two. */
+    void SetDefaultMapSize(int w, int h);
+
+    /** Get the amount (in percent) of space that is currently occupied by all maps
+        in this fragment manager. */
+    int GetUseRatio() const;
 #ifdef TB_RUNTIME_DEBUG_INFO
-	/** Render the maps on screen, to analyze fragment positioning. */
-	void Debug();
+    /** Render the maps on screen, to analyze fragment positioning. */
+    void Debug();
 #endif
 private:
-	TBListOf<TBBitmapFragmentMap> m_fragment_maps;
-	TBHashTableOf<TBBitmapFragment> m_fragments;
-	int m_num_maps_limit;
-	bool m_add_border;
-	int m_default_map_w;
-	int m_default_map_h;
+    TBListOf<TBBitmapFragmentMap> m_fragment_maps;
+    TBHashTableOf<TBBitmapFragment> m_fragments;
+    int m_num_maps_limit;
+    bool m_add_border;
+    int m_default_map_w;
+    int m_default_map_h;
 };
 
 }; // namespace tb

+ 47 - 47
Source/ThirdParty/TurboBadger/tb_clipboard_win.cpp

@@ -16,67 +16,67 @@ namespace tb {
 
 void TBClipboard::Empty()
 {
-	if (OpenClipboard(NULL))
-	{
-		EmptyClipboard();
-		CloseClipboard();
-	}
+    if (OpenClipboard(NULL))
+    {
+        EmptyClipboard();
+        CloseClipboard();
+    }
 }
 
 bool TBClipboard::HasText()
 {
-	bool has_text = false;
-	if (OpenClipboard(NULL))
-	{
-		has_text =	IsClipboardFormatAvailable(CF_TEXT) ||
-					IsClipboardFormatAvailable(CF_OEMTEXT) ||
-					IsClipboardFormatAvailable(CF_UNICODETEXT);
-		CloseClipboard();
-	}
-	return has_text;
+    bool has_text = false;
+    if (OpenClipboard(NULL))
+    {
+        has_text =	IsClipboardFormatAvailable(CF_TEXT) ||
+                IsClipboardFormatAvailable(CF_OEMTEXT) ||
+                IsClipboardFormatAvailable(CF_UNICODETEXT);
+        CloseClipboard();
+    }
+    return has_text;
 }
 
 bool TBClipboard::SetText(const char *text)
 {
-	if (OpenClipboard(NULL))
-	{
-		int num_wide_chars_needed = MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
-		if (HGLOBAL hClipboardData = GlobalAlloc(GMEM_DDESHARE, num_wide_chars_needed * sizeof(wchar_t)))
-		{
-			LPWSTR pchData = (LPWSTR) GlobalLock(hClipboardData);
-			MultiByteToWideChar(CP_UTF8, 0, text, -1, pchData, num_wide_chars_needed);
-			GlobalUnlock(hClipboardData);
+    if (OpenClipboard(NULL))
+    {
+        int num_wide_chars_needed = MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
+        if (HGLOBAL hClipboardData = GlobalAlloc(GMEM_DDESHARE, num_wide_chars_needed * sizeof(wchar_t)))
+        {
+            LPWSTR pchData = (LPWSTR) GlobalLock(hClipboardData);
+            MultiByteToWideChar(CP_UTF8, 0, text, -1, pchData, num_wide_chars_needed);
+            GlobalUnlock(hClipboardData);
 
-			EmptyClipboard();
-			SetClipboardData(CF_UNICODETEXT, hClipboardData);
-		}
+            EmptyClipboard();
+            SetClipboardData(CF_UNICODETEXT, hClipboardData);
+        }
 
-		CloseClipboard();
-		return true;
-	}
-	return false;
+        CloseClipboard();
+        return true;
+    }
+    return false;
 }
 
 bool TBClipboard::GetText(TBStr &text)
 {
-	bool success = false;
-	if (HasText() && OpenClipboard(NULL))
-	{
-		if (HANDLE hClipboardData = GetClipboardData(CF_UNICODETEXT))
-		{
-			wchar_t *pchData = (wchar_t*) GlobalLock(hClipboardData);
-			int len = WideCharToMultiByte(CP_UTF8, 0, pchData, -1, NULL, 0, NULL, NULL);
-			if (char *utf8 = new char[len])
-			{
-				WideCharToMultiByte(CP_UTF8, 0, pchData, -1, utf8, len, NULL, NULL);
-				success = text.Set(utf8);
-				delete [] utf8;
-			}
-			GlobalUnlock(hClipboardData);
-		}
-		CloseClipboard();
-	}
-	return success;
+    bool success = false;
+    if (HasText() && OpenClipboard(NULL))
+    {
+        if (HANDLE hClipboardData = GetClipboardData(CF_UNICODETEXT))
+        {
+            wchar_t *pchData = (wchar_t*) GlobalLock(hClipboardData);
+            int len = WideCharToMultiByte(CP_UTF8, 0, pchData, -1, NULL, 0, NULL, NULL);
+            if (char *utf8 = new char[len])
+            {
+                WideCharToMultiByte(CP_UTF8, 0, pchData, -1, utf8, len, NULL, NULL);
+                success = text.Set(utf8);
+                delete [] utf8;
+            }
+            GlobalUnlock(hClipboardData);
+        }
+        CloseClipboard();
+    }
+    return success;
 }
 
 }; // namespace tb

+ 11 - 11
Source/ThirdParty/TurboBadger/tb_color.cpp

@@ -12,17 +12,17 @@ namespace tb {
 
 void TBColor::SetFromString(const char *str, int len)
 {
-	int r, g, b, a;
-	if (len == 9 && sscanf(str, "#%2x%2x%2x%2x", &r, &g, &b, &a) == 4)			// rrggbbaa
-		Set(TBColor(r, g, b, a));
-	else if (len == 7 && sscanf(str, "#%2x%2x%2x", &r, &g, &b) == 3)			// rrggbb
-		Set(TBColor(r, g, b));
-	else if (len == 5 && sscanf(str, "#%1x%1x%1x%1x", &r, &g, &b, &a) == 4)		// rgba
-		Set(TBColor(r + (r << 4), g + (g << 4), b + (b << 4), a + (a << 4)));
-	else if (len == 4 && sscanf(str, "#%1x%1x%1x", &r, &g, &b) == 3)			// rgb
-		Set(TBColor(r + (r << 4), g + (g << 4), b + (b << 4)));
-	else
-		Set(TBColor());
+    int r, g, b, a;
+    if (len == 9 && sscanf(str, "#%2x%2x%2x%2x", &r, &g, &b, &a) == 4)			// rrggbbaa
+        Set(TBColor(r, g, b, a));
+    else if (len == 7 && sscanf(str, "#%2x%2x%2x", &r, &g, &b) == 3)			// rrggbb
+        Set(TBColor(r, g, b));
+    else if (len == 5 && sscanf(str, "#%1x%1x%1x%1x", &r, &g, &b, &a) == 4)		// rgba
+        Set(TBColor(r + (r << 4), g + (g << 4), b + (b << 4), a + (a << 4)));
+    else if (len == 4 && sscanf(str, "#%1x%1x%1x", &r, &g, &b) == 3)			// rgb
+        Set(TBColor(r + (r << 4), g + (g << 4), b + (b << 4)));
+    else
+        Set(TBColor());
 }
 
 }; // namespace tb

+ 10 - 10
Source/ThirdParty/TurboBadger/tb_color.h

@@ -15,20 +15,20 @@ namespace tb {
 class TBColor
 {
 public:
-	TBColor() : b(0), g(0), r(0), a(255) {}
-	TBColor(int r, int g, int b, int a = 255) : b(b), g(g), r(r), a(a) {}
+    TBColor() : b(0), g(0), r(0), a(255) {}
+    TBColor(int r, int g, int b, int a = 255) : b(b), g(g), r(r), a(a) {}
 
-	uint8 b, g, r, a;
+    uint8 b, g, r, a;
 
-	void Set(const TBColor &color) { *this = color; }
+    void Set(const TBColor &color) { *this = color; }
 
-	/** Set the color from string in any of the following formats:
-		"#rrggbbaa", "#rrggbb", "#rgba", "#rgb" */
-	void SetFromString(const char *str, int len);
+    /** Set the color from string in any of the following formats:
+        "#rrggbbaa", "#rrggbb", "#rgba", "#rgb" */
+    void SetFromString(const char *str, int len);
 
-	operator uint32 () const		{ return *((uint32*)this); }
-	bool operator == (const TBColor &c) const { return *this == (uint32)c; }
-	bool operator != (const TBColor &c) const { return !(*this == c); }
+    operator uint32 () const		{ return *((uint32*)this); }
+    bool operator == (const TBColor &c) const { return *this == (uint32)c; }
+    bool operator != (const TBColor &c) const { return !(*this == c); }
 };
 
 }; // namespace tb

+ 14 - 14
Source/ThirdParty/TurboBadger/tb_config.h

@@ -12,8 +12,8 @@
 #define TB_CONFIG_H
 
 /** Enable for some handy runtime debugging, enabled by modifying
-	the various settings in g_tb_debug. A settings window can be
-	shown by calling ShowDebugInfoSettingsWindow. */
+    the various settings in g_tb_debug. A settings window can be
+    shown by calling ShowDebugInfoSettingsWindow. */
 #ifndef NDEBUG
 #define TB_RUNTIME_DEBUG_INFO
 #endif
@@ -24,11 +24,11 @@
 #endif
 
 /** Enable if the focus state should automatically be set on edit fields even
-	when using the pointer. It is normally set only while moving focus by keyboard. */
+    when using the pointer. It is normally set only while moving focus by keyboard. */
 //#define TB_ALWAYS_SHOW_EDIT_FOCUS
 
 /** Enable to use premultiplied alpha. Warning: This is not handled everywhere in
-	the default backends, so consider it an experimental and unfinished feature! */
+    the default backends, so consider it an experimental and unfinished feature! */
 //#define TB_PREMULTIPLIED_ALPHA
 
 /** Enable to support TBBF fonts (Turbo Badger Bitmap Fonts) */
@@ -38,28 +38,28 @@
 //#define TB_FONT_RENDERER_FREETYPE
 
 /** Enable to support truetype fonts using stb_truetype.h (http://nothings.org/).
-	It's a *very unsafe* font library. Use only with fonts distributed with your
-	app, that you know work! Freetype generates much prettier glyphs (using
-	hinting) but is a lot larger. This implementation is kept here as alternative
-	as long as it compiles. */
+    It's a *very unsafe* font library. Use only with fonts distributed with your
+    app, that you know work! Freetype generates much prettier glyphs (using
+    hinting) but is a lot larger. This implementation is kept here as alternative
+    as long as it compiles. */
 // #define TB_FONT_RENDERER_STB
 
 /** Enable to support image loading using stb_image.c (http://nothings.org/).
-	It's a *very unsafe* image library. Use only with images distributed with
-	your app, that you know work! */
+    It's a *very unsafe* image library. Use only with images distributed with
+    your app, that you know work! */
 #define TB_IMAGE_LOADER_STB
 
 /** Enable to get TBRendererBatcher, an helper class for renderers that
-	implements batching of draw operations. Subclasses of TBRendererBatcher
-	can be done super easily, and still do batching. */
+    implements batching of draw operations. Subclasses of TBRendererBatcher
+    can be done super easily, and still do batching. */
 #define TB_RENDERER_BATCHER
 
 /** Enable renderer using OpenGL. This renderer depends on TB_RENDERER_BATCHER.
-	It is using GL version 1.1, */
+    It is using GL version 1.1, */
 #define TB_RENDERER_GL
 
 /** Enable renderer using OpenGL ES. This renderer depends on TB_RENDERER_GL.
-	It is using GL ES version 1. */
+    It is using GL ES version 1. */
 //#define TB_RENDERER_GLES_1
 
 /** The width of the font glyph cache. Must be a power of two. */

+ 17 - 17
Source/ThirdParty/TurboBadger/tb_core.cpp

@@ -23,35 +23,35 @@ TBFontManager *g_font_manager = nullptr;
 
 bool tb_core_init(TBRenderer *renderer, const char *lng_file)
 {
-	TBDebugPrint("Initiating Turbo Badger - version %s\n", TB_VERSION_STR);
-	g_renderer = renderer;
-	g_tb_lng = new TBLanguage;
-	g_tb_lng->Load(lng_file);
-	g_font_manager = new TBFontManager();
-	g_tb_skin = new TBSkin();
-	g_widgets_reader = TBWidgetsReader::Create();
+    TBDebugPrint("Initiating Turbo Badger - version %s\n", TB_VERSION_STR);
+    g_renderer = renderer;
+    g_tb_lng = new TBLanguage;
+    g_tb_lng->Load(lng_file);
+    g_font_manager = new TBFontManager();
+    g_tb_skin = new TBSkin();
+    g_widgets_reader = TBWidgetsReader::Create();
 #ifdef TB_IMAGE
-	g_image_manager = new TBImageManager();
+    g_image_manager = new TBImageManager();
 #endif
-	return TBInitAddons();
+    return TBInitAddons();
 }
 
 void tb_core_shutdown()
 {
-	TBAnimationManager::AbortAllAnimations();
-	TBShutdownAddons();
+    TBAnimationManager::AbortAllAnimations();
+    TBShutdownAddons();
 #ifdef TB_IMAGE
-	delete g_image_manager;
+    delete g_image_manager;
 #endif
-	delete g_widgets_reader;
-	delete g_tb_skin;
-	delete g_font_manager;
-	delete g_tb_lng;
+    delete g_widgets_reader;
+    delete g_tb_skin;
+    delete g_font_manager;
+    delete g_tb_lng;
 }
 
 bool tb_core_is_initialized()
 {
-	return g_widgets_reader ? true : false;
+    return g_widgets_reader ? true : false;
 }
 
 }; // namespace tb

+ 168 - 168
Source/ThirdParty/TurboBadger/tb_debug.cpp

@@ -19,189 +19,189 @@ TBDebugInfo g_tb_debug;
 
 TBDebugInfo::TBDebugInfo()
 {
-	memset(settings, 0, sizeof(int) * NUM_SETTINGS);
+    memset(settings, 0, sizeof(int) * NUM_SETTINGS);
 }
 
 /** Window showing runtime debug settings. */
 class DebugSettingsWindow : public TBWindow, public TBWidgetListener
 {
 public:
-	TBEditField *output;
-
-	TBOBJECT_SUBCLASS(DebugSettingsWindow, TBWindow);
-
-	DebugSettingsWindow(TBWidget *root)
-	{
-		SetText("Debug settings");
-		g_widgets_reader->LoadData(this,
-			"TBLayout: axis: y, distribution: available, position: left\n"
-			"	TBLayout: id: 'container', axis: y, size: available\n"
-			"	TBTextField: text: 'Event output:'\n"
-			"	TBEditField: id: 'output', gravity: all, multiline: 1, wrap: 0\n"
-			"		lp: pref-height: 100dp");
-
-		AddCheckbox(TBDebugInfo::LAYOUT_BOUNDS, "Layout bounds");
-		AddCheckbox(TBDebugInfo::LAYOUT_CLIPPING, "Layout clipping");
-		AddCheckbox(TBDebugInfo::LAYOUT_PS_DEBUGGING, "Layout size calculation");
-		AddCheckbox(TBDebugInfo::RENDER_BATCHES, "Render batches");
-		AddCheckbox(TBDebugInfo::RENDER_SKIN_BITMAP_FRAGMENTS, "Render skin bitmap fragments");
-		AddCheckbox(TBDebugInfo::RENDER_FONT_BITMAP_FRAGMENTS, "Render font bitmap fragments");
-
-		output = GetWidgetByIDAndType<TBEditField>(TBIDC("output"));
-
-		TBRect bounds(0, 0, root->GetRect().w, root->GetRect().h);
-		SetRect(GetResizeToFitContentRect().CenterIn(bounds).MoveIn(bounds).Clip(bounds));
-
-		root->AddChild(this);
-
-		TBWidgetListener::AddGlobalListener(this);
-	}
-
-	~DebugSettingsWindow()
-	{
-		TBWidgetListener::RemoveGlobalListener(this);
-	}
-
-	void AddCheckbox(TBDebugInfo::SETTING setting, const char *str)
-	{
-		TBCheckBox *check = new TBCheckBox();
-		check->SetValue(g_tb_debug.settings[setting]);
-		check->data.SetInt(setting);
-		check->SetID(TBIDC("check"));
-
-		TBClickLabel *label = new TBClickLabel();
-		label->SetText(str);
-		label->GetContentRoot()->AddChild(check, WIDGET_Z_BOTTOM);
-
-		GetWidgetByID(TBIDC("container"))->AddChild(label);
-	}
-
-	virtual bool OnEvent(const TBWidgetEvent &ev)
-	{
-		if (ev.type == EVENT_TYPE_CLICK && ev.target->GetID() == TBIDC("check"))
-		{
-			// Update setting and invalidate
-			g_tb_debug.settings[ev.target->data.GetInt()] = ev.target->GetValue();
-			GetParentRoot()->Invalidate();
-			return true;
-		}
-		return TBWindow::OnEvent(ev);
-	}
-
-	virtual void OnPaint(const PaintProps &paint_props)
-	{
-		// Draw stuff to the right of the debug window
-		g_renderer->Translate(GetRect().w, 0);
-
-		// Draw skin bitmap fragments
-		if (TB_DEBUG_SETTING(RENDER_SKIN_BITMAP_FRAGMENTS))
-			g_tb_skin->Debug();
-
-		// Draw font glyph fragments (the font of the hovered widget)
-		if (TB_DEBUG_SETTING(RENDER_FONT_BITMAP_FRAGMENTS))
-		{
-			TBWidget *widget = TBWidget::hovered_widget ? TBWidget::hovered_widget : TBWidget::focused_widget;
-			g_font_manager->GetFontFace(widget ?
-										widget->GetCalculatedFontDescription() :
-										g_font_manager->GetDefaultFontDescription())->Debug();
-		}
-
-		g_renderer->Translate(-GetRect().w, 0);
-	}
-
-	TBStr GetIDString(const TBID &id)
-	{
-		TBStr str;
+    TBEditField *output;
+
+    TBOBJECT_SUBCLASS(DebugSettingsWindow, TBWindow);
+
+    DebugSettingsWindow(TBWidget *root)
+    {
+        SetText("Debug settings");
+        g_widgets_reader->LoadData(this,
+                                   "TBLayout: axis: y, distribution: available, position: left\n"
+                                   "	TBLayout: id: 'container', axis: y, size: available\n"
+                                   "	TBTextField: text: 'Event output:'\n"
+                                   "	TBEditField: id: 'output', gravity: all, multiline: 1, wrap: 0\n"
+                                   "		lp: pref-height: 100dp");
+
+        AddCheckbox(TBDebugInfo::LAYOUT_BOUNDS, "Layout bounds");
+        AddCheckbox(TBDebugInfo::LAYOUT_CLIPPING, "Layout clipping");
+        AddCheckbox(TBDebugInfo::LAYOUT_PS_DEBUGGING, "Layout size calculation");
+        AddCheckbox(TBDebugInfo::RENDER_BATCHES, "Render batches");
+        AddCheckbox(TBDebugInfo::RENDER_SKIN_BITMAP_FRAGMENTS, "Render skin bitmap fragments");
+        AddCheckbox(TBDebugInfo::RENDER_FONT_BITMAP_FRAGMENTS, "Render font bitmap fragments");
+
+        output = GetWidgetByIDAndType<TBEditField>(TBIDC("output"));
+
+        TBRect bounds(0, 0, root->GetRect().w, root->GetRect().h);
+        SetRect(GetResizeToFitContentRect().CenterIn(bounds).MoveIn(bounds).Clip(bounds));
+
+        root->AddChild(this);
+
+        TBWidgetListener::AddGlobalListener(this);
+    }
+
+    ~DebugSettingsWindow()
+    {
+        TBWidgetListener::RemoveGlobalListener(this);
+    }
+
+    void AddCheckbox(TBDebugInfo::SETTING setting, const char *str)
+    {
+        TBCheckBox *check = new TBCheckBox();
+        check->SetValue(g_tb_debug.settings[setting]);
+        check->data.SetInt(setting);
+        check->SetID(TBIDC("check"));
+
+        TBClickLabel *label = new TBClickLabel();
+        label->SetText(str);
+        label->GetContentRoot()->AddChild(check, WIDGET_Z_BOTTOM);
+
+        GetWidgetByID(TBIDC("container"))->AddChild(label);
+    }
+
+    virtual bool OnEvent(const TBWidgetEvent &ev)
+    {
+        if (ev.type == EVENT_TYPE_CLICK && ev.target->GetID() == TBIDC("check"))
+        {
+            // Update setting and invalidate
+            g_tb_debug.settings[ev.target->data.GetInt()] = ev.target->GetValue();
+            GetParentRoot()->Invalidate();
+            return true;
+        }
+        return TBWindow::OnEvent(ev);
+    }
+
+    virtual void OnPaint(const PaintProps &paint_props)
+    {
+        // Draw stuff to the right of the debug window
+        g_renderer->Translate(GetRect().w, 0);
+
+        // Draw skin bitmap fragments
+        if (TB_DEBUG_SETTING(RENDER_SKIN_BITMAP_FRAGMENTS))
+            g_tb_skin->Debug();
+
+        // Draw font glyph fragments (the font of the hovered widget)
+        if (TB_DEBUG_SETTING(RENDER_FONT_BITMAP_FRAGMENTS))
+        {
+            TBWidget *widget = TBWidget::hovered_widget ? TBWidget::hovered_widget : TBWidget::focused_widget;
+            g_font_manager->GetFontFace(widget ?
+                                            widget->GetCalculatedFontDescription() :
+                                            g_font_manager->GetDefaultFontDescription())->Debug();
+        }
+
+        g_renderer->Translate(-GetRect().w, 0);
+    }
+
+    TBStr GetIDString(const TBID &id)
+    {
+        TBStr str;
 #ifdef TB_RUNTIME_DEBUG_INFO
-		str.Append("\"");
-		str.Append(id.debug_string);
-		str.Append("\"");
+        str.Append("\"");
+        str.Append(id.debug_string);
+        str.Append("\"");
 #else
-		str.SetFormatted("%u", (uint32)id);
+        str.SetFormatted("%u", (uint32)id);
 #endif
-		return str;
-	}
-
-	// TBWidgetListener
-	virtual bool OnWidgetInvokeEvent(TBWidget *widget, const TBWidgetEvent &ev)
-	{
-		// Skip these events for now
-		if (ev.IsPointerEvent())
-			return false;
-
-		// Always ignore activity in this window (or we might get endless recursion)
-		if (TBWindow *window = widget->GetParentWindow())
-			if (TBSafeCast<DebugSettingsWindow>(window))
-				return false;
-
-		TBTempBuffer buf;
-		buf.AppendString(GetEventTypeStr(ev.type));
-		buf.AppendString(" (");
-		buf.AppendString(widget->GetClassName());
-		buf.AppendString(")");
-
-		buf.AppendString(" id: ");
-		buf.AppendString(GetIDString(ev.target->GetID()));
-
-		if (ev.ref_id)
-		{
-			buf.AppendString(", ref_id: ");
-			buf.AppendString(GetIDString(ev.ref_id));
-		}
-
-		if (ev.type == EVENT_TYPE_CHANGED)
-		{
-			TBStr extra, text;
-			if (ev.target->GetText(text) && text.Length() > 24)
-				sprintf(text.CStr() + 20, "...");
-			extra.SetFormatted(", value: %.2f (\"%s\")", ev.target->GetValueDouble(), text.CStr());
-			buf.AppendString(extra);
-		}
-		buf.AppendString("\n");
-
-		// Append the line to the output textfield
-		TBStyleEdit *se = output->GetStyleEdit();
-		se->selection.SelectNothing();
-		se->AppendText(buf.GetData(), TB_ALL_TO_TERMINATION, true);
-		se->ScrollIfNeeded(false, true);
-
-		// Remove lines from the top if we exceed the height limit.
-		const int height_limit = 2000;
-		int current_height = se->GetContentHeight();
-		if (current_height > height_limit)
-		{
-			se->caret.Place(TBPoint(0, current_height - height_limit));
-			se->selection.SelectToCaret(se->blocks.GetFirst(), 0);
-			se->Delete();
-		}
-		return false;
-	}
-
-	const char *GetEventTypeStr(EVENT_TYPE type) const
-	{
-		switch (type)
-		{
-		case EVENT_TYPE_CLICK:			return "CLICK";
-		case EVENT_TYPE_LONG_CLICK:		return "LONG_CLICK";
-		case EVENT_TYPE_POINTER_DOWN:	return "POINTER_DOWN";
-		case EVENT_TYPE_POINTER_UP:		return "POINTER_UP";
-		case EVENT_TYPE_POINTER_MOVE:	return "POINTER_MOVE";
+        return str;
+    }
+
+    // TBWidgetListener
+    virtual bool OnWidgetInvokeEvent(TBWidget *widget, const TBWidgetEvent &ev)
+    {
+        // Skip these events for now
+        if (ev.IsPointerEvent())
+            return false;
+
+        // Always ignore activity in this window (or we might get endless recursion)
+        if (TBWindow *window = widget->GetParentWindow())
+            if (TBSafeCast<DebugSettingsWindow>(window))
+                return false;
+
+        TBTempBuffer buf;
+        buf.AppendString(GetEventTypeStr(ev.type));
+        buf.AppendString(" (");
+        buf.AppendString(widget->GetClassName());
+        buf.AppendString(")");
+
+        buf.AppendString(" id: ");
+        buf.AppendString(GetIDString(ev.target->GetID()));
+
+        if (ev.ref_id)
+        {
+            buf.AppendString(", ref_id: ");
+            buf.AppendString(GetIDString(ev.ref_id));
+        }
+
+        if (ev.type == EVENT_TYPE_CHANGED)
+        {
+            TBStr extra, text;
+            if (ev.target->GetText(text) && text.Length() > 24)
+                sprintf(text.CStr() + 20, "...");
+            extra.SetFormatted(", value: %.2f (\"%s\")", ev.target->GetValueDouble(), text.CStr());
+            buf.AppendString(extra);
+        }
+        buf.AppendString("\n");
+
+        // Append the line to the output textfield
+        TBStyleEdit *se = output->GetStyleEdit();
+        se->selection.SelectNothing();
+        se->AppendText(buf.GetData(), TB_ALL_TO_TERMINATION, true);
+        se->ScrollIfNeeded(false, true);
+
+        // Remove lines from the top if we exceed the height limit.
+        const int height_limit = 2000;
+        int current_height = se->GetContentHeight();
+        if (current_height > height_limit)
+        {
+            se->caret.Place(TBPoint(0, current_height - height_limit));
+            se->selection.SelectToCaret(se->blocks.GetFirst(), 0);
+            se->Delete();
+        }
+        return false;
+    }
+
+    const char *GetEventTypeStr(EVENT_TYPE type) const
+    {
+        switch (type)
+        {
+        case EVENT_TYPE_CLICK:			return "CLICK";
+        case EVENT_TYPE_LONG_CLICK:		return "LONG_CLICK";
+        case EVENT_TYPE_POINTER_DOWN:	return "POINTER_DOWN";
+        case EVENT_TYPE_POINTER_UP:		return "POINTER_UP";
+        case EVENT_TYPE_POINTER_MOVE:	return "POINTER_MOVE";
         case EVENT_TYPE_RIGHT_POINTER_UP: return "RIGHT_POINTER_UP";
         case EVENT_TYPE_RIGHT_POINTER_DOWN:	return "RIGHT_POINTER_DOWN";
-		case EVENT_TYPE_WHEEL:			return "WHEEL";
-		case EVENT_TYPE_CHANGED:		return "CHANGED";
-		case EVENT_TYPE_KEY_DOWN:		return "KEY_DOWN";
-		case EVENT_TYPE_KEY_UP:			return "KEY_UP";
-		case EVENT_TYPE_SHORTCUT:		return "SHORT_CUT";
-		case EVENT_TYPE_CONTEXT_MENU:	return "CONTEXT_MENU";
-		default: return "[UNKNOWN]";
-		};
-	}
+        case EVENT_TYPE_WHEEL:			return "WHEEL";
+        case EVENT_TYPE_CHANGED:		return "CHANGED";
+        case EVENT_TYPE_KEY_DOWN:		return "KEY_DOWN";
+        case EVENT_TYPE_KEY_UP:			return "KEY_UP";
+        case EVENT_TYPE_SHORTCUT:		return "SHORT_CUT";
+        case EVENT_TYPE_CONTEXT_MENU:	return "CONTEXT_MENU";
+        default: return "[UNKNOWN]";
+        };
+    }
 };
 
 void ShowDebugInfoSettingsWindow(TBWidget *root)
 {
-	new DebugSettingsWindow(root);
+    new DebugSettingsWindow(root);
 }
 
 #endif // TB_RUNTIME_DEBUG_INFO

+ 22 - 22
Source/ThirdParty/TurboBadger/tb_debug.h

@@ -21,28 +21,28 @@ namespace tb {
 class TBDebugInfo
 {
 public:
-	TBDebugInfo();
-
-	enum SETTING {
-		/** Show widgets bounds */
-		LAYOUT_BOUNDS,
-		/** Show child widget clipping set by some widgets. */
-		LAYOUT_CLIPPING,
-		/** Show highlights on widgets that recalculate their preferred
-			size, and those who recalculate their layout. */
-		LAYOUT_PS_DEBUGGING,
-		/** Show render batch info and log batch info in the debug
-			output. It depends on the renderer backend if this is available. */
-		RENDER_BATCHES,
-		/** Render the bitmap fragments of the skin. */
-		RENDER_SKIN_BITMAP_FRAGMENTS,
-		/** Render the bitmap fragments of the font that's set on the hovered
-			or focused widget. */
-		RENDER_FONT_BITMAP_FRAGMENTS,
-
-		NUM_SETTINGS
-	};
-	int settings[NUM_SETTINGS];
+    TBDebugInfo();
+
+    enum SETTING {
+        /** Show widgets bounds */
+        LAYOUT_BOUNDS,
+        /** Show child widget clipping set by some widgets. */
+        LAYOUT_CLIPPING,
+        /** Show highlights on widgets that recalculate their preferred
+            size, and those who recalculate their layout. */
+        LAYOUT_PS_DEBUGGING,
+        /** Show render batch info and log batch info in the debug
+            output. It depends on the renderer backend if this is available. */
+        RENDER_BATCHES,
+        /** Render the bitmap fragments of the skin. */
+        RENDER_SKIN_BITMAP_FRAGMENTS,
+        /** Render the bitmap fragments of the font that's set on the hovered
+            or focused widget. */
+        RENDER_FONT_BITMAP_FRAGMENTS,
+
+        NUM_SETTINGS
+    };
+    int settings[NUM_SETTINGS];
 };
 
 extern TBDebugInfo g_tb_debug;

+ 48 - 48
Source/ThirdParty/TurboBadger/tb_dimension.cpp

@@ -17,75 +17,75 @@ namespace tb {
 
 void TBDimensionConverter::SetDPI(int src_dpi, int dst_dpi)
 {
-	m_src_dpi = src_dpi;
-	m_dst_dpi = dst_dpi;
-	m_dst_dpi_str.Clear();
-	if (NeedConversion())
-		m_dst_dpi_str.SetFormatted("@%d", m_dst_dpi);
+    m_src_dpi = src_dpi;
+    m_dst_dpi = dst_dpi;
+    m_dst_dpi_str.Clear();
+    if (NeedConversion())
+        m_dst_dpi_str.SetFormatted("@%d", m_dst_dpi);
 }
 
 void TBDimensionConverter::GetDstDPIFilename(const char *filename, TBTempBuffer *tempbuf) const
 {
-	int dot_pos = 0;
-	for (dot_pos = strlen(filename) - 1; dot_pos > 0; dot_pos--)
-		if (filename[dot_pos] == '.')
-			break;
-	tempbuf->ResetAppendPos();
-	tempbuf->Append(filename, dot_pos);
-	tempbuf->AppendString(GetDstDPIStr());
-	tempbuf->AppendString(filename + dot_pos);
+    int dot_pos = 0;
+    for (dot_pos = strlen(filename) - 1; dot_pos > 0; dot_pos--)
+        if (filename[dot_pos] == '.')
+            break;
+    tempbuf->ResetAppendPos();
+    tempbuf->Append(filename, dot_pos);
+    tempbuf->AppendString(GetDstDPIStr());
+    tempbuf->AppendString(filename + dot_pos);
 }
 
 int TBDimensionConverter::DpToPx(int dp) const
 {
-	if (dp <= TB_INVALID_DIMENSION || dp == 0 || !NeedConversion())
-		return dp;
-	if (dp > 0)
-	{
-		dp = dp * m_dst_dpi / m_src_dpi;
-		return MAX(dp, 1);
-	}
-	else
-	{
-		dp = dp * m_dst_dpi / m_src_dpi;
-		return MIN(dp, -1);
-	}
+    if (dp <= TB_INVALID_DIMENSION || dp == 0 || !NeedConversion())
+        return dp;
+    if (dp > 0)
+    {
+        dp = dp * m_dst_dpi / m_src_dpi;
+        return MAX(dp, 1);
+    }
+    else
+    {
+        dp = dp * m_dst_dpi / m_src_dpi;
+        return MIN(dp, -1);
+    }
 }
 
 int TBDimensionConverter::MmToPx(int mm) const
 {
-	if (mm <= TB_INVALID_DIMENSION || mm == 0)
-		return mm;
+    if (mm <= TB_INVALID_DIMENSION || mm == 0)
+        return mm;
 
-	return (int) (mm * TBSystem::GetDPI() / 25.4f + 0.5f);
+    return (int) (mm * TBSystem::GetDPI() / 25.4f + 0.5f);
 }
 
 int TBDimensionConverter::GetPxFromString(const char *str, int def_value) const
 {
-	if (!str || !is_start_of_number(str))
-		return def_value;
-	int len = strlen(str);
-	int val = atoi(str);
-	// "dp" and unspecified unit is dp.
-	if ((len > 0 && isdigit(str[len - 1])) ||
-		(len > 2 && strcmp(str + len - 2, "dp") == 0))
-		return DpToPx(val);
-	else if (len > 2 && strcmp(str + len - 2, "mm") == 0)
-		return MmToPx(val);
-	else
-		return val;
+    if (!str || !is_start_of_number(str))
+        return def_value;
+    int len = strlen(str);
+    int val = atoi(str);
+    // "dp" and unspecified unit is dp.
+    if ((len > 0 && isdigit(str[len - 1])) ||
+            (len > 2 && strcmp(str + len - 2, "dp") == 0))
+        return DpToPx(val);
+    else if (len > 2 && strcmp(str + len - 2, "mm") == 0)
+        return MmToPx(val);
+    else
+        return val;
 }
 
 int TBDimensionConverter::GetPxFromValue(TBValue *value, int def_value) const
 {
-	if (!value)
-		return def_value;
-	if (value->GetType() == TBValue::TYPE_INT)
-		return DpToPx(value->GetInt());
-	else if (value->GetType() == TBValue::TYPE_FLOAT)
-		// FIX: We might want float versions of all dimension functions.
-		return DpToPx((int)value->GetFloat());
-	return GetPxFromString(value->GetString(), def_value);
+    if (!value)
+        return def_value;
+    if (value->GetType() == TBValue::TYPE_INT)
+        return DpToPx(value->GetInt());
+    else if (value->GetType() == TBValue::TYPE_FLOAT)
+        // FIX: We might want float versions of all dimension functions.
+        return DpToPx((int)value->GetFloat());
+    return GetPxFromString(value->GetString(), def_value);
 }
 
 }; // namespace tb

+ 38 - 38
Source/ThirdParty/TurboBadger/tb_dimension.h

@@ -13,65 +13,65 @@
 namespace tb {
 
 /** Dimensions <= this value will be untouched by conversion in TBDimensionConverter.
-	To preserve special constants, those must be <= this value. */
+    To preserve special constants, those must be <= this value. */
 #define TB_INVALID_DIMENSION -5555
 
 class TBTempBuffer;
 class TBValue;
 
 /** TBDimensionConverter converts device independant points
-	to pixels, based on two DPI values.
-	Dimensions in Turbo Badger are normally in pixels (if not specified differently)
-	and conversion normally take place when loading skin. */
+    to pixels, based on two DPI values.
+    Dimensions in Turbo Badger are normally in pixels (if not specified differently)
+    and conversion normally take place when loading skin. */
 class TBDimensionConverter
 {
-	int m_src_dpi; ///< The source DPI (Normally the base_dpi from skin).
-	int m_dst_dpi; ///< The destination DPI (Normally the supported skin DPI nearest to TBSystem::GetDPI).
-	TBStr m_dst_dpi_str; ///< The file suffix that should be used to load bitmaps in destinatin DPI.
+    int m_src_dpi; ///< The source DPI (Normally the base_dpi from skin).
+    int m_dst_dpi; ///< The destination DPI (Normally the supported skin DPI nearest to TBSystem::GetDPI).
+    TBStr m_dst_dpi_str; ///< The file suffix that should be used to load bitmaps in destinatin DPI.
 public:
-	TBDimensionConverter() : m_src_dpi(100), m_dst_dpi(100) {}
+    TBDimensionConverter() : m_src_dpi(100), m_dst_dpi(100) {}
 
-	/** Set the source and destination DPI that will affect the conversion. */
-	void SetDPI(int src_dpi, int dst_dpi);
+    /** Set the source and destination DPI that will affect the conversion. */
+    void SetDPI(int src_dpi, int dst_dpi);
 
-	/** Get the source DPI. */
-	int GetSrcDPI() const { return m_src_dpi; }
+    /** Get the source DPI. */
+    int GetSrcDPI() const { return m_src_dpi; }
 
-	/** Get the destination DPI. */
-	int GetDstDPI() const { return m_dst_dpi; }
+    /** Get the destination DPI. */
+    int GetDstDPI() const { return m_dst_dpi; }
 
-	/** Get the file name suffix that should be used to load bitmaps in the destination DPI.
-		Examples: "@96", "@196" */
-	const char *GetDstDPIStr() const { return m_dst_dpi_str; }
+    /** Get the file name suffix that should be used to load bitmaps in the destination DPI.
+        Examples: "@96", "@196" */
+    const char *GetDstDPIStr() const { return m_dst_dpi_str; }
 
-	/** Get the file name with destination DPI suffix (F.ex "foo.png" becomes "[email protected]").
-		The temp buffer will contain the resulting file name. */
-	void GetDstDPIFilename(const char *filename, TBTempBuffer *tempbuf) const;
+    /** Get the file name with destination DPI suffix (F.ex "foo.png" becomes "[email protected]").
+        The temp buffer will contain the resulting file name. */
+    void GetDstDPIFilename(const char *filename, TBTempBuffer *tempbuf) const;
 
-	/** Return true if the source and destinatin DPI are different. */
-	bool NeedConversion() const { return m_src_dpi != m_dst_dpi; }
+    /** Return true if the source and destinatin DPI are different. */
+    bool NeedConversion() const { return m_src_dpi != m_dst_dpi; }
 
-	/** Convert device independant point to pixel. */
-	int DpToPx(int dp) const;
+    /** Convert device independant point to pixel. */
+    int DpToPx(int dp) const;
 
-	/** Convert millimeter to pixel. */
-	int MmToPx(int mm) const;
+    /** Convert millimeter to pixel. */
+    int MmToPx(int mm) const;
 
-	/** Get a pixel value from string in any of the following formats:
-		str may be nullptr. def_value is returned on fail.
+    /** Get a pixel value from string in any of the following formats:
+        str may be nullptr. def_value is returned on fail.
 
-		Device independent point:		"1", "1dp"
-		Pixel value:					"1px"
-		*/
-	int GetPxFromString(const char *str, int def_value) const;
+        Device independent point:		"1", "1dp"
+        Pixel value:					"1px"
+        */
+    int GetPxFromString(const char *str, int def_value) const;
 
-	/** Get a pixel value from TBValue.
-		value may be nullptr. def_value is returned on fail.
+    /** Get a pixel value from TBValue.
+        value may be nullptr. def_value is returned on fail.
 
-		Number formats are treated as dp.
-		String format is treated like for GetPxFromString.
-		*/
-	int GetPxFromValue(TBValue *value, int def_value) const;
+        Number formats are treated as dp.
+        String format is treated like for GetPxFromString.
+        */
+    int GetPxFromValue(TBValue *value, int def_value) const;
 };
 
 }; // namespace tb

+ 151 - 151
Source/ThirdParty/TurboBadger/tb_editfield.h

@@ -13,199 +13,199 @@
 namespace tb {
 
 /** EDIT_TYPE - These types does not restrict input (may change in the future).
-	They are just hints for virtual keyboard, so it can show special keys. */
+    They are just hints for virtual keyboard, so it can show special keys. */
 enum EDIT_TYPE {
-	EDIT_TYPE_TEXT,
-	EDIT_TYPE_SEARCH,
-	EDIT_TYPE_PASSWORD,
-	EDIT_TYPE_EMAIL,
-	EDIT_TYPE_PHONE,
-	EDIT_TYPE_URL,
-	EDIT_TYPE_NUMBER
+    EDIT_TYPE_TEXT,
+    EDIT_TYPE_SEARCH,
+    EDIT_TYPE_PASSWORD,
+    EDIT_TYPE_EMAIL,
+    EDIT_TYPE_PHONE,
+    EDIT_TYPE_URL,
+    EDIT_TYPE_NUMBER
 };
 
 /** The default content factory for embedded content in TBEditField with styling enabled.
 
-	Creates all that TBTextFragmentContentFactory creates by default,
-	and any type of widget from a inline resource string.
+    Creates all that TBTextFragmentContentFactory creates by default,
+    and any type of widget from a inline resource string.
 
-	Syntax: <widget xxx> Where xxx is parsed by TBWidgetsReader.
+    Syntax: <widget xxx> Where xxx is parsed by TBWidgetsReader.
 
-	Example - Create a button with id "hello":
+    Example - Create a button with id "hello":
 
-		<widget TBButton: text: "Hello world!" id: "hello">
+        <widget TBButton: text: "Hello world!" id: "hello">
 
-	Example - Create a image from skin element "Icon48":
+    Example - Create a image from skin element "Icon48":
 
-		<widget TBSkinImage: skin: "Icon48">
+        <widget TBSkinImage: skin: "Icon48">
 */
 
 class TBEditFieldContentFactory : public TBTextFragmentContentFactory
 {
 public:
-	class TBEditField *editfield;
-	virtual int GetContent(const char *text);
-	virtual TBTextFragmentContent *CreateFragmentContent(const char *text, int text_len);
+    class TBEditField *editfield;
+    virtual int GetContent(const char *text);
+    virtual TBTextFragmentContent *CreateFragmentContent(const char *text, int text_len);
 };
 
 /** TBEditFieldScrollRoot - Internal for TBEditField.
-	Acts as a scrollable container for any widget created as embedded content. */
+    Acts as a scrollable container for any widget created as embedded content. */
 
 class TBEditFieldScrollRoot : public TBWidget
 {
 private: // May only be used by TBEditField.
-	friend class TBEditField;
-	TBEditFieldScrollRoot() {}
+    friend class TBEditField;
+    TBEditFieldScrollRoot() {}
 public:
-	virtual void OnPaintChildren(const PaintProps &paint_props);
-	virtual void GetChildTranslation(int &x, int &y) const;
-	virtual WIDGET_HIT_STATUS GetHitStatus(int x, int y);
+    virtual void OnPaintChildren(const PaintProps &paint_props);
+    virtual void GetChildTranslation(int &x, int &y) const;
+    virtual WIDGET_HIT_STATUS GetHitStatus(int x, int y);
 };
 
 /** TBEditField is a one line or multi line textfield that is editable or
-	read-only. It can also be a passwordfield by calling
-	SetEditType(EDIT_TYPE_PASSWORD).
+    read-only. It can also be a passwordfield by calling
+    SetEditType(EDIT_TYPE_PASSWORD).
 
-	It may perform styling of text and contain custom embedded content,
-	if enabled by SetStyling(true). Disabled by default.
+    It may perform styling of text and contain custom embedded content,
+    if enabled by SetStyling(true). Disabled by default.
 */
 
 class TBEditField : public TBWidget, private TBStyleEditListener, public TBMessageHandler
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBEditField, TBWidget);
-
-	TBEditField();
-	~TBEditField();
-
-	/** Get the visible rect (the GetPaddingRect() minus any scrollbars) */
-	TBRect GetVisibleRect();
-
-	/** Set if multiple lines should be allowed or not.
-		Will also set wrapping (to true if multiline, and false if not). */
-	void SetMultiline(bool multiline);
-	bool GetMultiline() const { return m_style_edit.packed.multiline_on; }
-
-	/** Set if styling should be enabled or not. Default is disabled. */
-	void SetStyling(bool styling);
-	bool GetStyling() const { return m_style_edit.packed.styling_on; }
-
-	/** Set if read only mode should be enabled. Default is disabled.
-		In read only mode, editing is disabled and caret is hidden.
-		The user is still able to focus, select and copy text. */
-	void SetReadOnly(bool readonly);
-	bool GetReadOnly() const { return m_style_edit.packed.read_only; }
-
-	/** Set to true if the text should wrap if multi line is enabled (See SetMultiline). */
-	void SetWrapping(bool wrapping);
-	bool GetWrapping() const { return m_style_edit.packed.wrapping; }
-
-	/** Set to true if the preferred size of this editfield should adapt to the
-		size of the content (disabled by default).
-		If wrapping is enabled, the result is partly dependant on the virtual
-		width (See SetVirtualWidth). */
-	void SetAdaptToContentSize(bool adapt);
-	bool GetAdaptToContentSize() const { return m_adapt_to_content_size; }
-
-	/** The virtual width is only used if the size is adapting to content size
-		(See SetAdaptToContentSize) and wrapping is enabled.
-		The virtual width will be used to layout the text and see which resulting
-		width and height it takes up. The width that is actually used depends on
-		the content. It is also up to the the layouter to decide if the size
-		should be respected or not. The default is 250. */
-	void SetVirtualWidth(int virtual_width);
-	int GetVirtualWidth() const { return m_virtual_width; }
-
-	/** Get the TBStyleEdit object that contains more functions and settings. */
-	TBStyleEdit *GetStyleEdit() { return &m_style_edit; }
-
-	/** Set the edit type that is a hint for virtual keyboards about what the
-		content should be. */
-	void SetEditType(EDIT_TYPE type);
-	EDIT_TYPE GetEditType() { return m_edit_type; }
-
-	/** Support custom skin condition properties. Currently supported properties are:
-		"edit-type", matching those of EDIT_TYPE.
-		"multiline", matching 1 if multiline mode is enabled.
-		"readonly", matching 1 if readonly mode is enabled. */
-	virtual bool GetCustomSkinCondition(const TBSkinCondition::CONDITION_INFO &info);
-
-	/** Set which alignment the text should have if the space
-		given when painting is larger than the text.
-		This changes the default for new blocks, as wel as the currently selected blocks or the block
-		of the current caret position if nothing is selected. */
-	void SetTextAlign(TB_TEXT_ALIGN align) { m_style_edit.SetAlign(align); }
-	TB_TEXT_ALIGN GetTextAlign() { return m_style_edit.align; }
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBEditField, TBWidget);
+
+    TBEditField();
+    ~TBEditField();
+
+    /** Get the visible rect (the GetPaddingRect() minus any scrollbars) */
+    TBRect GetVisibleRect();
+
+    /** Set if multiple lines should be allowed or not.
+        Will also set wrapping (to true if multiline, and false if not). */
+    void SetMultiline(bool multiline);
+    bool GetMultiline() const { return m_style_edit.packed.multiline_on; }
+
+    /** Set if styling should be enabled or not. Default is disabled. */
+    void SetStyling(bool styling);
+    bool GetStyling() const { return m_style_edit.packed.styling_on; }
+
+    /** Set if read only mode should be enabled. Default is disabled.
+        In read only mode, editing is disabled and caret is hidden.
+        The user is still able to focus, select and copy text. */
+    void SetReadOnly(bool readonly);
+    bool GetReadOnly() const { return m_style_edit.packed.read_only; }
+
+    /** Set to true if the text should wrap if multi line is enabled (See SetMultiline). */
+    void SetWrapping(bool wrapping);
+    bool GetWrapping() const { return m_style_edit.packed.wrapping; }
+
+    /** Set to true if the preferred size of this editfield should adapt to the
+        size of the content (disabled by default).
+        If wrapping is enabled, the result is partly dependant on the virtual
+        width (See SetVirtualWidth). */
+    void SetAdaptToContentSize(bool adapt);
+    bool GetAdaptToContentSize() const { return m_adapt_to_content_size; }
+
+    /** The virtual width is only used if the size is adapting to content size
+        (See SetAdaptToContentSize) and wrapping is enabled.
+        The virtual width will be used to layout the text and see which resulting
+        width and height it takes up. The width that is actually used depends on
+        the content. It is also up to the the layouter to decide if the size
+        should be respected or not. The default is 250. */
+    void SetVirtualWidth(int virtual_width);
+    int GetVirtualWidth() const { return m_virtual_width; }
+
+    /** Get the TBStyleEdit object that contains more functions and settings. */
+    TBStyleEdit *GetStyleEdit() { return &m_style_edit; }
+
+    /** Set the edit type that is a hint for virtual keyboards about what the
+        content should be. */
+    void SetEditType(EDIT_TYPE type);
+    EDIT_TYPE GetEditType() { return m_edit_type; }
+
+    /** Support custom skin condition properties. Currently supported properties are:
+        "edit-type", matching those of EDIT_TYPE.
+        "multiline", matching 1 if multiline mode is enabled.
+        "readonly", matching 1 if readonly mode is enabled. */
+    virtual bool GetCustomSkinCondition(const TBSkinCondition::CONDITION_INFO &info);
+
+    /** Set which alignment the text should have if the space
+        given when painting is larger than the text.
+        This changes the default for new blocks, as wel as the currently selected blocks or the block
+        of the current caret position if nothing is selected. */
+    void SetTextAlign(TB_TEXT_ALIGN align) { m_style_edit.SetAlign(align); }
+    TB_TEXT_ALIGN GetTextAlign() { return m_style_edit.align; }
 
     void AppendText(const char *text, int32 len = TB_ALL_TO_TERMINATION, bool clear_undo_redo = false) { m_style_edit.AppendText(text, len, clear_undo_redo); }
 
-	virtual bool SetText(const char *text) { return m_style_edit.SetText(text, TB_CARET_POS_BEGINNING); }
-	virtual bool GetText(TBStr &text) { return m_style_edit.GetText(text); }
-	using TBWidget::GetText; ///< Make all versions in base class available.
-
-	using TBWidget::Invalidate; ///< Make Invalidate in base class available.
-
-	/** Set the text and also specify if the caret should be positioned at the beginning
-		or end of the text. */
-	bool SetText(const char *text, TB_CARET_POS pos)
-											{ return m_style_edit.SetText(text, pos); }
-	/** Set the text of the given length and also specify if the caret should be positioned
-		at the beginning or end of the text. */
-	bool SetText(const char *text, int text_len, TB_CARET_POS pos = TB_CARET_POS_BEGINNING)
-											{ return m_style_edit.SetText(text, text_len, pos); }
-
-	/** Set the placeholder text. It will be visible only when the textfield is empty. */
-	virtual bool SetPlaceholderText(const char *text) { return m_placeholder.SetText(text); }
-	virtual bool GetPlaceholderText(TBStr &text) { return m_placeholder.GetText(text); }
-
-	virtual void ScrollTo(int x, int y);
-	virtual TBWidget::ScrollInfo GetScrollInfo();
-	virtual TBWidget *GetScrollRoot() { return &m_root; }
-
-	virtual bool OnEvent(const TBWidgetEvent &ev);
-	virtual void OnPaint(const PaintProps &paint_props);
-	virtual void OnPaintChildren(const PaintProps &paint_props);
-	virtual void OnInflate(const INFLATE_INFO &info);
-	virtual void OnAdded();
-	virtual void OnFontChanged();
-	virtual void OnFocusChanged(bool focused);
-	virtual void OnResized(int old_w, int old_h);
-	virtual TBWidget *GetContentRoot() { return &m_root; }
-
-	virtual PreferredSize OnCalculatePreferredContentSize(const SizeConstraints &constraints);
+    virtual bool SetText(const char *text) { return m_style_edit.SetText(text, TB_CARET_POS_BEGINNING); }
+    virtual bool GetText(TBStr &text) { return m_style_edit.GetText(text); }
+    using TBWidget::GetText; ///< Make all versions in base class available.
+
+    using TBWidget::Invalidate; ///< Make Invalidate in base class available.
+
+    /** Set the text and also specify if the caret should be positioned at the beginning
+        or end of the text. */
+    bool SetText(const char *text, TB_CARET_POS pos)
+    { return m_style_edit.SetText(text, pos); }
+    /** Set the text of the given length and also specify if the caret should be positioned
+        at the beginning or end of the text. */
+    bool SetText(const char *text, int text_len, TB_CARET_POS pos = TB_CARET_POS_BEGINNING)
+    { return m_style_edit.SetText(text, text_len, pos); }
+
+    /** Set the placeholder text. It will be visible only when the textfield is empty. */
+    virtual bool SetPlaceholderText(const char *text) { return m_placeholder.SetText(text); }
+    virtual bool GetPlaceholderText(TBStr &text) { return m_placeholder.GetText(text); }
+
+    virtual void ScrollTo(int x, int y);
+    virtual TBWidget::ScrollInfo GetScrollInfo();
+    virtual TBWidget *GetScrollRoot() { return &m_root; }
+
+    virtual bool OnEvent(const TBWidgetEvent &ev);
+    virtual void OnPaint(const PaintProps &paint_props);
+    virtual void OnPaintChildren(const PaintProps &paint_props);
+    virtual void OnInflate(const INFLATE_INFO &info);
+    virtual void OnAdded();
+    virtual void OnFontChanged();
+    virtual void OnFocusChanged(bool focused);
+    virtual void OnResized(int old_w, int old_h);
+    virtual TBWidget *GetContentRoot() { return &m_root; }
+
+    virtual PreferredSize OnCalculatePreferredContentSize(const SizeConstraints &constraints);
 
     void Reformat(bool update_fragments) { m_style_edit.Reformat(update_fragments); }
 
-	virtual void OnMessageReceived(TBMessage *msg);
+    virtual void OnMessageReceived(TBMessage *msg);
 private:
-	TBScrollBar m_scrollbar_x;
-	TBScrollBar m_scrollbar_y;
-	TBWidgetString m_placeholder;
-	EDIT_TYPE m_edit_type;
-	TBEditFieldScrollRoot m_root;
-	TBEditFieldContentFactory m_content_factory;
-	TBStyleEdit m_style_edit;
-	bool m_adapt_to_content_size;
-	int m_virtual_width;
-	void UpdateScrollbarVisibility(bool multiline);
+    TBScrollBar m_scrollbar_x;
+    TBScrollBar m_scrollbar_y;
+    TBWidgetString m_placeholder;
+    EDIT_TYPE m_edit_type;
+    TBEditFieldScrollRoot m_root;
+    TBEditFieldContentFactory m_content_factory;
+    TBStyleEdit m_style_edit;
+    bool m_adapt_to_content_size;
+    int m_virtual_width;
+    void UpdateScrollbarVisibility(bool multiline);
 
     TBStr m_initial_edit_text;
 
-	// == TBStyleEditListener =======================
-	virtual void OnChange();
-	virtual bool OnEnter();
-	virtual void Invalidate(const TBRect &rect);
-	virtual void DrawString(int32 x, int32 y, TBFontFace *font, const TBColor &color, const char *str, int32 len);
-	virtual void DrawRect(const TBRect &rect, const TBColor &color);
-	virtual void DrawRectFill(const TBRect &rect, const TBColor &color);
-	virtual void DrawTextSelectionBg(const TBRect &rect);
-	virtual void DrawContentSelectionFg(const TBRect &rect);
-	virtual void DrawCaret(const TBRect &rect);
-	virtual void Scroll(int32 dx, int32 dy);
-	virtual void UpdateScrollbars();
-	virtual void CaretBlinkStart();
-	virtual void CaretBlinkStop();
+    // == TBStyleEditListener =======================
+    virtual void OnChange();
+    virtual bool OnEnter();
+    virtual void Invalidate(const TBRect &rect);
+    virtual void DrawString(int32 x, int32 y, TBFontFace *font, const TBColor &color, const char *str, int32 len);
+    virtual void DrawRect(const TBRect &rect, const TBColor &color);
+    virtual void DrawRectFill(const TBRect &rect, const TBColor &color);
+    virtual void DrawTextSelectionBg(const TBRect &rect);
+    virtual void DrawContentSelectionFg(const TBRect &rect);
+    virtual void DrawCaret(const TBRect &rect);
+    virtual void Scroll(int32 dx, int32 dy);
+    virtual void UpdateScrollbars();
+    virtual void CaretBlinkStart();
+    virtual void CaretBlinkStop();
 };
 
 }; // namespace tb

+ 6 - 6
Source/ThirdParty/TurboBadger/tb_file_posix.cpp

@@ -32,12 +32,12 @@ public:
             free(data);
     }
 
-	virtual long Size()
-	{
+    virtual long Size()
+    {
         return (long) size;
-	}
-	virtual size_t Read(void *buf, size_t elemSize, size_t count)
-	{
+    }
+    virtual size_t Read(void *buf, size_t elemSize, size_t count)
+    {
         size_t totalRead = elemSize * count;
 
         if (currentPos + totalRead > size)
@@ -56,7 +56,7 @@ public:
 
         return totalRead;
 
-	}
+    }
 private:
     void* data;
     size_t size;

+ 40 - 40
Source/ThirdParty/TurboBadger/tb_font_desc.h

@@ -12,59 +12,59 @@
 namespace tb {
 
 /** TBFontDescription describes a font.
-	By default when nothing is set, the font is unspecified and means it should be inherited
-	from a parent widget that specifies a font, or use the default font if no parent does. */
+    By default when nothing is set, the font is unspecified and means it should be inherited
+    from a parent widget that specifies a font, or use the default font if no parent does. */
 
 class TBFontDescription
 {
 public:
-	/** Set the font ID of the font to use.
-		This ID maps to the font names in TBFontInfo, which is managed from
-		TBFontManager::AddFontInfo, TBFontManager::GetFontInfo.
+    /** Set the font ID of the font to use.
+        This ID maps to the font names in TBFontInfo, which is managed from
+        TBFontManager::AddFontInfo, TBFontManager::GetFontInfo.
 
-		Example:
-		If a font was added to the font manager with the name "Vera", you can
-		do font_description.SetID(TBIDC("Vera")).
-		*/
-	void SetID(const TBID &id)											{ m_id = id; }
+        Example:
+        If a font was added to the font manager with the name "Vera", you can
+        do font_description.SetID(TBIDC("Vera")).
+        */
+    void SetID(const TBID &id)											{ m_id = id; }
 
-	/** Get the TBID for the font name (See SetID). */
-	TBID GetID() const { return m_id; }
+    /** Get the TBID for the font name (See SetID). */
+    TBID GetID() const { return m_id; }
 
-	/** Get the TBID for the TBFontFace that matches this font description.
-		This is a ID combining both the font file, and variation (such as size and style),
-		and should be used to identify a certain font face.
+    /** Get the TBID for the TBFontFace that matches this font description.
+        This is a ID combining both the font file, and variation (such as size and style),
+        and should be used to identify a certain font face.
 
-		If this is 0, the font description is unspecified. For a widget, that means that the font
-		should be inherited from the parent widget. */
-	TBID GetFontFaceID() const { return m_id + m_packed_init; }
+        If this is 0, the font description is unspecified. For a widget, that means that the font
+        should be inherited from the parent widget. */
+    TBID GetFontFaceID() const { return m_id + m_packed_init; }
 
-	void SetSize(uint32 size)											{ m_packed.size = MIN(size, 0x8000u); }
-	uint32 GetSize() const												{ return m_packed.size; }
+    void SetSize(uint32 size)											{ m_packed.size = MIN(size, 0x8000u); }
+    uint32 GetSize() const												{ return m_packed.size; }
 
-	//not connected to anything yet
-	//void SetBold(bool bold)											{ m_packed.bold = bold; }
-	//bool GetBold() const												{ return m_packed.bold; }
+    //not connected to anything yet
+    //void SetBold(bool bold)											{ m_packed.bold = bold; }
+    //bool GetBold() const												{ return m_packed.bold; }
 
-	//not connected to anything yet
-	//void SetItalic(bool italic)										{ m_packed.italic = italic; }
-	//bool GetItalic() const											{ return m_packed.italic; }
+    //not connected to anything yet
+    //void SetItalic(bool italic)										{ m_packed.italic = italic; }
+    //bool GetItalic() const											{ return m_packed.italic; }
 
-	TBFontDescription() : m_packed_init(0) {}
-	TBFontDescription(const TBFontDescription &src)						{ m_packed_init = src.m_packed_init; m_id = src.m_id; }
-	const TBFontDescription& operator = (const TBFontDescription &src)	{ m_packed_init = src.m_packed_init; m_id = src.m_id; return *this; }
-	bool operator == (const TBFontDescription &fd) const { return m_packed_init == fd.m_packed_init && m_id == fd.m_id; }
-	bool operator != (const TBFontDescription &fd) const { return !(*this == fd); }
+    TBFontDescription() : m_packed_init(0) {}
+    TBFontDescription(const TBFontDescription &src)						{ m_packed_init = src.m_packed_init; m_id = src.m_id; }
+    const TBFontDescription& operator = (const TBFontDescription &src)	{ m_packed_init = src.m_packed_init; m_id = src.m_id; return *this; }
+    bool operator == (const TBFontDescription &fd) const { return m_packed_init == fd.m_packed_init && m_id == fd.m_id; }
+    bool operator != (const TBFontDescription &fd) const { return !(*this == fd); }
 private:
-	TBID m_id;
-	union {
-		struct {
-			uint32 size : 15;
-			uint32 italic : 1;
-			uint32 bold : 1;
-		} m_packed;
-		uint32 m_packed_init;
-	};
+    TBID m_id;
+    union {
+        struct {
+            uint32 size : 15;
+            uint32 italic : 1;
+            uint32 bold : 1;
+        } m_packed;
+        uint32 m_packed_init;
+    };
 };
 
 }; // namespace tb

+ 349 - 349
Source/ThirdParty/TurboBadger/tb_font_renderer.cpp

@@ -14,121 +14,121 @@ namespace tb {
 
 static void blurGlyph(unsigned char* src, int srcw, int srch, int srcStride, unsigned char* dst, int dstw, int dsth, int dstStride, float* temp, float* kernel, int kernelRadius)
 {
-	for (int y = 0; y < srch; y++)
-	{
-		for (int x = 0; x < dstw; x++)
-		{
-			float val = 0;
-			for (int k_ofs = -kernelRadius; k_ofs <= kernelRadius; k_ofs++)
-			{
-				if (x - kernelRadius + k_ofs >= 0 && x - kernelRadius + k_ofs < srcw)
-					val += src[y * srcStride + x - kernelRadius + k_ofs] * kernel[k_ofs + kernelRadius];
-			}
-			temp[y * dstw + x] = val;
-		}
-	}
-	for (int y = 0; y < dsth; y++)
-	{
-		for (int x = 0; x < dstw; x++)
-		{
-			float val = 0;
-			for (int k_ofs = -kernelRadius; k_ofs <= kernelRadius; k_ofs++)
-			{
-				if (y - kernelRadius + k_ofs >= 0 && y - kernelRadius + k_ofs < srch)
-					val += temp[(y - kernelRadius + k_ofs) * dstw + x] * kernel[k_ofs + kernelRadius];
-			}
-			dst[y * dstStride + x] = (unsigned char)(val + 0.5f);
-		}
-	}
+    for (int y = 0; y < srch; y++)
+    {
+        for (int x = 0; x < dstw; x++)
+        {
+            float val = 0;
+            for (int k_ofs = -kernelRadius; k_ofs <= kernelRadius; k_ofs++)
+            {
+                if (x - kernelRadius + k_ofs >= 0 && x - kernelRadius + k_ofs < srcw)
+                    val += src[y * srcStride + x - kernelRadius + k_ofs] * kernel[k_ofs + kernelRadius];
+            }
+            temp[y * dstw + x] = val;
+        }
+    }
+    for (int y = 0; y < dsth; y++)
+    {
+        for (int x = 0; x < dstw; x++)
+        {
+            float val = 0;
+            for (int k_ofs = -kernelRadius; k_ofs <= kernelRadius; k_ofs++)
+            {
+                if (y - kernelRadius + k_ofs >= 0 && y - kernelRadius + k_ofs < srch)
+                    val += temp[(y - kernelRadius + k_ofs) * dstw + x] * kernel[k_ofs + kernelRadius];
+            }
+            dst[y * dstStride + x] = (unsigned char)(val + 0.5f);
+        }
+    }
 }
 
 // ================================================================================================
 
 TBFontEffect::TBFontEffect()
-	: m_blur_radius(0)
-	, m_tempBuffer(nullptr)
-	, m_kernel(nullptr)
+    : m_blur_radius(0)
+    , m_tempBuffer(nullptr)
+    , m_kernel(nullptr)
 {
 }
 
 TBFontEffect::~TBFontEffect()
 {
-	delete [] m_tempBuffer;
-	delete [] m_kernel;
+    delete [] m_tempBuffer;
+    delete [] m_kernel;
 }
 
 void TBFontEffect::SetBlurRadius(int blur_radius)
 {
-	assert(blur_radius >= 0);
-	if (m_blur_radius == blur_radius)
-		return;
-	m_blur_radius = blur_radius;
-	if (m_blur_radius > 0)
-	{
-		delete [] m_kernel;
-		m_kernel = new float[m_blur_radius * 2 + 1];
-		if (!m_kernel)
-		{
-			m_blur_radius = 0;
-			return;
-		}
-		float stdDevSq2 = (float)m_blur_radius / 2.f;
-		stdDevSq2 = 2.f * stdDevSq2 * stdDevSq2;
-		float scale = 1.f / sqrt(3.1415f * stdDevSq2);
-		float sum = 0;
-		for (int k = 0; k < 2 * m_blur_radius + 1; k++)
-		{
-			float x = (float)(k - m_blur_radius);
-			float kval = scale * exp(-(x * x / stdDevSq2));
-			m_kernel[k] = kval;
-			sum += kval;
-		}
-		for (int k = 0; k < 2 * m_blur_radius + 1; k++)
-			m_kernel[k] /= sum;
-	}
+    assert(blur_radius >= 0);
+    if (m_blur_radius == blur_radius)
+        return;
+    m_blur_radius = blur_radius;
+    if (m_blur_radius > 0)
+    {
+        delete [] m_kernel;
+        m_kernel = new float[m_blur_radius * 2 + 1];
+        if (!m_kernel)
+        {
+            m_blur_radius = 0;
+            return;
+        }
+        float stdDevSq2 = (float)m_blur_radius / 2.f;
+        stdDevSq2 = 2.f * stdDevSq2 * stdDevSq2;
+        float scale = 1.f / sqrt(3.1415f * stdDevSq2);
+        float sum = 0;
+        for (int k = 0; k < 2 * m_blur_radius + 1; k++)
+        {
+            float x = (float)(k - m_blur_radius);
+            float kval = scale * exp(-(x * x / stdDevSq2));
+            m_kernel[k] = kval;
+            sum += kval;
+        }
+        for (int k = 0; k < 2 * m_blur_radius + 1; k++)
+            m_kernel[k] /= sum;
+    }
 }
 
 TBFontGlyphData *TBFontEffect::Render(TBGlyphMetrics *metrics, const TBFontGlyphData *src)
 {
-	TBFontGlyphData *effect_glyph_data = nullptr;
-	if (m_blur_radius > 0 && src->data8)
-	{
-		// Create a new TBFontGlyphData for the blurred glyph
-		effect_glyph_data = new TBFontGlyphData;
-		if (!effect_glyph_data)
-			return nullptr;
-		effect_glyph_data->w = src->w + m_blur_radius * 2;
-		effect_glyph_data->h = src->h + m_blur_radius * 2;
-		effect_glyph_data->stride = effect_glyph_data->w;
-		effect_glyph_data->data8 = new unsigned char[effect_glyph_data->w * effect_glyph_data->h];
-
-		// Reserve memory needed for blurring.
-		if (!effect_glyph_data->data8 ||
-			!m_blur_temp.Reserve(effect_glyph_data->w * effect_glyph_data->h * sizeof(float)))
-		{
-			delete effect_glyph_data;
-			return nullptr;
-		}
-
-		// Blur!
-		blurGlyph(src->data8, src->w, src->h, src->stride,
-					effect_glyph_data->data8, effect_glyph_data->w, effect_glyph_data->h, effect_glyph_data->w,
-					(float *)m_blur_temp.GetData(), m_kernel, m_blur_radius);
-
-		// Adjust glyph position to compensate for larger size.
-		metrics->x -= m_blur_radius;
-		metrics->y -= m_blur_radius;
-	}
-	return effect_glyph_data;
+    TBFontGlyphData *effect_glyph_data = nullptr;
+    if (m_blur_radius > 0 && src->data8)
+    {
+        // Create a new TBFontGlyphData for the blurred glyph
+        effect_glyph_data = new TBFontGlyphData;
+        if (!effect_glyph_data)
+            return nullptr;
+        effect_glyph_data->w = src->w + m_blur_radius * 2;
+        effect_glyph_data->h = src->h + m_blur_radius * 2;
+        effect_glyph_data->stride = effect_glyph_data->w;
+        effect_glyph_data->data8 = new unsigned char[effect_glyph_data->w * effect_glyph_data->h];
+
+        // Reserve memory needed for blurring.
+        if (!effect_glyph_data->data8 ||
+                !m_blur_temp.Reserve(effect_glyph_data->w * effect_glyph_data->h * sizeof(float)))
+        {
+            delete effect_glyph_data;
+            return nullptr;
+        }
+
+        // Blur!
+        blurGlyph(src->data8, src->w, src->h, src->stride,
+                  effect_glyph_data->data8, effect_glyph_data->w, effect_glyph_data->h, effect_glyph_data->w,
+                  (float *)m_blur_temp.GetData(), m_kernel, m_blur_radius);
+
+        // Adjust glyph position to compensate for larger size.
+        metrics->x -= m_blur_radius;
+        metrics->y -= m_blur_radius;
+    }
+    return effect_glyph_data;
 }
 
 // == TBFontGlyph =================================================================================
 
 TBFontGlyph::TBFontGlyph(const TBID &hash_id, UCS4 cp)
-	: hash_id(hash_id)
-	, cp(cp)
-	, frag(nullptr)
-	, has_rgb(false)
+    : hash_id(hash_id)
+    , cp(cp)
+    , frag(nullptr)
+    , has_rgb(false)
 {
 }
 
@@ -136,305 +136,305 @@ TBFontGlyph::TBFontGlyph(const TBID &hash_id, UCS4 cp)
 
 TBFontGlyphCache::TBFontGlyphCache()
 {
-	// Only use one map for the font face. The glyph cache will start forgetting
-	// glyphs that haven't been used for a while if the map gets full.
-	m_frag_manager.SetNumMapsLimit(1);
-	m_frag_manager.SetDefaultMapSize(TB_GLYPH_CACHE_WIDTH, TB_GLYPH_CACHE_HEIGHT);
+    // Only use one map for the font face. The glyph cache will start forgetting
+    // glyphs that haven't been used for a while if the map gets full.
+    m_frag_manager.SetNumMapsLimit(1);
+    m_frag_manager.SetDefaultMapSize(TB_GLYPH_CACHE_WIDTH, TB_GLYPH_CACHE_HEIGHT);
 
-	g_renderer->AddListener(this);
+    g_renderer->AddListener(this);
 }
 
 TBFontGlyphCache::~TBFontGlyphCache()
 {
-	g_renderer->RemoveListener(this);
+    g_renderer->RemoveListener(this);
 }
 
 TBFontGlyph *TBFontGlyphCache::GetGlyph(const TBID &hash_id, UCS4 cp)
 {
-	if (TBFontGlyph *glyph = m_glyphs.Get(hash_id))
-	{
-		// Move the glyph to the end of m_all_rendered_glyphs so we maintain LRU (oldest first)
-		if (m_all_rendered_glyphs.ContainsLink(glyph))
-		{
-			m_all_rendered_glyphs.Remove(glyph);
-			m_all_rendered_glyphs.AddLast(glyph);
-		}
-		return glyph;
-	}
-	return nullptr;
+    if (TBFontGlyph *glyph = m_glyphs.Get(hash_id))
+    {
+        // Move the glyph to the end of m_all_rendered_glyphs so we maintain LRU (oldest first)
+        if (m_all_rendered_glyphs.ContainsLink(glyph))
+        {
+            m_all_rendered_glyphs.Remove(glyph);
+            m_all_rendered_glyphs.AddLast(glyph);
+        }
+        return glyph;
+    }
+    return nullptr;
 }
 
 TBFontGlyph *TBFontGlyphCache::CreateAndCacheGlyph(const TBID &hash_id, UCS4 cp)
 {
-	assert(!GetGlyph(hash_id, cp));
-	TBFontGlyph *glyph = new TBFontGlyph(hash_id, cp);
-	if (glyph && m_glyphs.Add(glyph->hash_id, glyph))
-		return glyph;
-	delete glyph;
-	return nullptr;
+    assert(!GetGlyph(hash_id, cp));
+    TBFontGlyph *glyph = new TBFontGlyph(hash_id, cp);
+    if (glyph && m_glyphs.Add(glyph->hash_id, glyph))
+        return glyph;
+    delete glyph;
+    return nullptr;
 }
 
 TBBitmapFragment *TBFontGlyphCache::CreateFragment(TBFontGlyph *glyph, int w, int h, int stride, uint32 *data)
 {
-	assert(GetGlyph(glyph->hash_id, glyph->cp));
-	// Don't bother if the requested glyph is too large.
-	if (w > TB_GLYPH_CACHE_WIDTH || h > TB_GLYPH_CACHE_HEIGHT)
-		return nullptr;
-
-	bool try_drop_largest = true;
-	bool dropped_large_enough_glyph = false;
-	do
-	{
-		// Attempt creating a fragment for the rendered glyph data
-		if (TBBitmapFragment *frag = m_frag_manager.CreateNewFragment(glyph->hash_id, false, w, h, stride, data))
-		{
-			glyph->frag = frag;
-			m_all_rendered_glyphs.AddLast(glyph);
-			return frag;
-		}
-		// Drop the oldest glyph that's large enough to free up the space we need.
-		if (try_drop_largest)
-		{
-			const int check_limit = 20;
-			int check_count = 0;
-			for (TBFontGlyph *oldest = m_all_rendered_glyphs.GetFirst(); oldest && check_count < check_limit; oldest = oldest->GetNext())
-			{
-				if (oldest->frag->Width() >= w && oldest->frag->GetAllocatedHeight() >= h)
-				{
-					DropGlyphFragment(oldest);
-					dropped_large_enough_glyph = true;
-					break;
-				}
-				check_count++;
-			}
-			try_drop_largest = false;
-		}
-		// We had no large enough glyph so just drop the oldest one. We will likely
-		// spin around the loop, fail and drop again a few times before we succeed.
-		if (!dropped_large_enough_glyph)
-		{
-			if (TBFontGlyph *oldest = m_all_rendered_glyphs.GetFirst())
-				DropGlyphFragment(oldest);
-			else
-				break;
-		}
-	} while (true);
-	return nullptr;
+    assert(GetGlyph(glyph->hash_id, glyph->cp));
+    // Don't bother if the requested glyph is too large.
+    if (w > TB_GLYPH_CACHE_WIDTH || h > TB_GLYPH_CACHE_HEIGHT)
+        return nullptr;
+
+    bool try_drop_largest = true;
+    bool dropped_large_enough_glyph = false;
+    do
+    {
+        // Attempt creating a fragment for the rendered glyph data
+        if (TBBitmapFragment *frag = m_frag_manager.CreateNewFragment(glyph->hash_id, false, w, h, stride, data))
+        {
+            glyph->frag = frag;
+            m_all_rendered_glyphs.AddLast(glyph);
+            return frag;
+        }
+        // Drop the oldest glyph that's large enough to free up the space we need.
+        if (try_drop_largest)
+        {
+            const int check_limit = 20;
+            int check_count = 0;
+            for (TBFontGlyph *oldest = m_all_rendered_glyphs.GetFirst(); oldest && check_count < check_limit; oldest = oldest->GetNext())
+            {
+                if (oldest->frag->Width() >= w && oldest->frag->GetAllocatedHeight() >= h)
+                {
+                    DropGlyphFragment(oldest);
+                    dropped_large_enough_glyph = true;
+                    break;
+                }
+                check_count++;
+            }
+            try_drop_largest = false;
+        }
+        // We had no large enough glyph so just drop the oldest one. We will likely
+        // spin around the loop, fail and drop again a few times before we succeed.
+        if (!dropped_large_enough_glyph)
+        {
+            if (TBFontGlyph *oldest = m_all_rendered_glyphs.GetFirst())
+                DropGlyphFragment(oldest);
+            else
+                break;
+        }
+    } while (true);
+    return nullptr;
 }
 
 void TBFontGlyphCache::DropGlyphFragment(TBFontGlyph *glyph)
 {
-	assert(glyph->frag);
-	m_frag_manager.FreeFragment(glyph->frag);
-	glyph->frag = nullptr;
-	m_all_rendered_glyphs.Remove(glyph);
+    assert(glyph->frag);
+    m_frag_manager.FreeFragment(glyph->frag);
+    glyph->frag = nullptr;
+    m_all_rendered_glyphs.Remove(glyph);
 }
 
 #ifdef TB_RUNTIME_DEBUG_INFO
 void TBFontGlyphCache::Debug()
 {
-	m_frag_manager.Debug();
+    m_frag_manager.Debug();
 }
 #endif // TB_RUNTIME_DEBUG_INFO
 
 void TBFontGlyphCache::OnContextLost()
 {
-	m_frag_manager.DeleteBitmaps();
+    m_frag_manager.DeleteBitmaps();
 }
 
 void TBFontGlyphCache::OnContextRestored()
 {
-	// No need to do anything. The bitmaps will be created when drawing.
+    // No need to do anything. The bitmaps will be created when drawing.
 }
 
 // ================================================================================================
 
 TBFontFace::TBFontFace(TBFontGlyphCache *glyph_cache, TBFontRenderer *renderer, const TBFontDescription &font_desc)
-	: m_glyph_cache(glyph_cache), m_font_renderer(renderer), m_font_desc(font_desc), m_bgFont(nullptr), m_bgX(0), m_bgY(0)
+    : m_glyph_cache(glyph_cache), m_font_renderer(renderer), m_font_desc(font_desc), m_bgFont(nullptr), m_bgX(0), m_bgY(0)
 {
-	if (m_font_renderer)
-		m_metrics = m_font_renderer->GetMetrics();
-	else
-	{
-		// Invent some metrics for the test font
-		int size = m_font_desc.GetSize();
-		m_metrics.ascent = size - size / 4;
-		m_metrics.descent = size / 4;
-		m_metrics.height = size;
-	}
+    if (m_font_renderer)
+        m_metrics = m_font_renderer->GetMetrics();
+    else
+    {
+        // Invent some metrics for the test font
+        int size = m_font_desc.GetSize();
+        m_metrics.ascent = size - size / 4;
+        m_metrics.descent = size / 4;
+        m_metrics.height = size;
+    }
 }
 
 TBFontFace::~TBFontFace()
 {
-	// It would be nice to drop all glyphs we have live for this font face.
-	// Now they only die when they get old and kicked out of the cache.
-	// We currently don't drop any font faces either though (except on shutdown)
-	delete m_font_renderer;
+    // It would be nice to drop all glyphs we have live for this font face.
+    // Now they only die when they get old and kicked out of the cache.
+    // We currently don't drop any font faces either though (except on shutdown)
+    delete m_font_renderer;
 }
 
 void TBFontFace::SetBackgroundFont(TBFontFace *font, const TBColor &col, int xofs, int yofs)
 {
-	m_bgFont = font;
-	m_bgX = xofs;
-	m_bgY = yofs;
-	m_bgColor = col;
+    m_bgFont = font;
+    m_bgX = xofs;
+    m_bgY = yofs;
+    m_bgColor = col;
 }
 
 bool TBFontFace::RenderGlyphs(const char *glyph_str, int glyph_str_len)
 {
-	if (!m_font_renderer)
-		return true; // This is the test font
+    if (!m_font_renderer)
+        return true; // This is the test font
 
-	if (glyph_str_len == TB_ALL_TO_TERMINATION)
-		glyph_str_len = strlen(glyph_str);
+    if (glyph_str_len == TB_ALL_TO_TERMINATION)
+        glyph_str_len = strlen(glyph_str);
 
-	bool has_all_glyphs = true;
-	int i = 0;
-	while (glyph_str[i] && i < glyph_str_len)
-	{
-		UCS4 cp = utf8::decode_next(glyph_str, &i, glyph_str_len);
-		if (!GetGlyph(cp, true))
-			has_all_glyphs = false;
-	}
-	return has_all_glyphs;
+    bool has_all_glyphs = true;
+    int i = 0;
+    while (glyph_str[i] && i < glyph_str_len)
+    {
+        UCS4 cp = utf8::decode_next(glyph_str, &i, glyph_str_len);
+        if (!GetGlyph(cp, true))
+            has_all_glyphs = false;
+    }
+    return has_all_glyphs;
 }
 
 TBFontGlyph *TBFontFace::CreateAndCacheGlyph(UCS4 cp)
 {
-	if (!m_font_renderer)
-		return nullptr; // This is the test font
+    if (!m_font_renderer)
+        return nullptr; // This is the test font
 
-	// Create the new glyph
-	TBFontGlyph *glyph = m_glyph_cache->CreateAndCacheGlyph(GetHashId(cp), cp);
-	if (glyph)
-		m_font_renderer->GetGlyphMetrics(&glyph->metrics, cp);
-	return glyph;
+    // Create the new glyph
+    TBFontGlyph *glyph = m_glyph_cache->CreateAndCacheGlyph(GetHashId(cp), cp);
+    if (glyph)
+        m_font_renderer->GetGlyphMetrics(&glyph->metrics, cp);
+    return glyph;
 }
 
 void TBFontFace::RenderGlyph(TBFontGlyph *glyph)
 {
-	assert(!glyph->frag);
-	TBFontGlyphData glyph_data;
-	if (m_font_renderer->RenderGlyph(&glyph_data, glyph->cp))
-	{
-		TBFontGlyphData *effect_glyph_data = m_effect.Render(&glyph->metrics, &glyph_data);
-		TBFontGlyphData *result_glyph_data = effect_glyph_data ? effect_glyph_data : &glyph_data;
-
-		// The glyph data may be in uint8 format, which we have to convert since we always
-		// create fragments (and TBBitmap) in 32bit format.
-		uint32 *glyph_dsta_src = result_glyph_data->data32;
-		if (!glyph_dsta_src && result_glyph_data->data8)
-		{
-			if (m_temp_buffer.Reserve(result_glyph_data->w * result_glyph_data->h * sizeof(uint32)))
-			{
-				glyph_dsta_src = (uint32 *) m_temp_buffer.GetData();
-				for (int y = 0; y < result_glyph_data->h; y++)
-					for (int x = 0; x < result_glyph_data->w; x++)
-					{
+    assert(!glyph->frag);
+    TBFontGlyphData glyph_data;
+    if (m_font_renderer->RenderGlyph(&glyph_data, glyph->cp))
+    {
+        TBFontGlyphData *effect_glyph_data = m_effect.Render(&glyph->metrics, &glyph_data);
+        TBFontGlyphData *result_glyph_data = effect_glyph_data ? effect_glyph_data : &glyph_data;
+
+        // The glyph data may be in uint8 format, which we have to convert since we always
+        // create fragments (and TBBitmap) in 32bit format.
+        uint32 *glyph_dsta_src = result_glyph_data->data32;
+        if (!glyph_dsta_src && result_glyph_data->data8)
+        {
+            if (m_temp_buffer.Reserve(result_glyph_data->w * result_glyph_data->h * sizeof(uint32)))
+            {
+                glyph_dsta_src = (uint32 *) m_temp_buffer.GetData();
+                for (int y = 0; y < result_glyph_data->h; y++)
+                    for (int x = 0; x < result_glyph_data->w; x++)
+                    {
 #ifdef TB_PREMULTIPLIED_ALPHA
-						uint8 opacity = result_glyph_data->data8[x + y * result_glyph_data->stride];
-						glyph_dsta_src[x + y * result_glyph_data->w] = TBColor(opacity, opacity, opacity, opacity);
+                        uint8 opacity = result_glyph_data->data8[x + y * result_glyph_data->stride];
+                        glyph_dsta_src[x + y * result_glyph_data->w] = TBColor(opacity, opacity, opacity, opacity);
 #else
-						glyph_dsta_src[x + y * result_glyph_data->w] = TBColor(255, 255, 255, result_glyph_data->data8[x + y * result_glyph_data->stride]);
+                        glyph_dsta_src[x + y * result_glyph_data->w] = TBColor(255, 255, 255, result_glyph_data->data8[x + y * result_glyph_data->stride]);
 #endif
-					}
-			}
-		}
-
-		// Finally, the glyph data is ready and we can create a bitmap fragment.
-		if (glyph_dsta_src)
-		{
-			glyph->has_rgb = result_glyph_data->rgb;
-			m_glyph_cache->CreateFragment(glyph, result_glyph_data->w, result_glyph_data->h,
-										result_glyph_data->stride, glyph_dsta_src);
-		}
-
-		delete effect_glyph_data;
-	}
+                    }
+            }
+        }
+
+        // Finally, the glyph data is ready and we can create a bitmap fragment.
+        if (glyph_dsta_src)
+        {
+            glyph->has_rgb = result_glyph_data->rgb;
+            m_glyph_cache->CreateFragment(glyph, result_glyph_data->w, result_glyph_data->h,
+                                          result_glyph_data->stride, glyph_dsta_src);
+        }
+
+        delete effect_glyph_data;
+    }
 #ifdef TB_RUNTIME_DEBUG_INFO
-	//char glyph_str[9];
-	//int len = utf8::encode(cp, glyph_str);
-	//glyph_str[len] = 0;
-	//TBStr info;
-	//info.SetFormatted("Created glyph %d (\"%s\"). Cache contains %d glyphs (%d%% full) using %d bitmaps.\n", cp, glyph_str, m_all_glyphs.CountLinks(), m_frag_manager.GetUseRatio(), m_frag_manager.GetNumMaps());
-	//TBDebugOut(info);
+    //char glyph_str[9];
+    //int len = utf8::encode(cp, glyph_str);
+    //glyph_str[len] = 0;
+    //TBStr info;
+    //info.SetFormatted("Created glyph %d (\"%s\"). Cache contains %d glyphs (%d%% full) using %d bitmaps.\n", cp, glyph_str, m_all_glyphs.CountLinks(), m_frag_manager.GetUseRatio(), m_frag_manager.GetNumMaps());
+    //TBDebugOut(info);
 #endif
 }
 
 TBID TBFontFace::GetHashId(UCS4 cp) const
 {
-	return cp * 31 + m_font_desc.GetFontFaceID();
+    return cp * 31 + m_font_desc.GetFontFaceID();
 }
 
 TBFontGlyph *TBFontFace::GetGlyph(UCS4 cp, bool render_if_needed)
 {
-	TBFontGlyph *glyph = m_glyph_cache->GetGlyph(GetHashId(cp), cp);
-	if (!glyph)
-		glyph = CreateAndCacheGlyph(cp);
-	if (glyph && !glyph->frag && render_if_needed)
-		RenderGlyph(glyph);
-	return glyph;
+    TBFontGlyph *glyph = m_glyph_cache->GetGlyph(GetHashId(cp), cp);
+    if (!glyph)
+        glyph = CreateAndCacheGlyph(cp);
+    if (glyph && !glyph->frag && render_if_needed)
+        RenderGlyph(glyph);
+    return glyph;
 }
 
 void TBFontFace::DrawString(int x, int y, const TBColor &color, const char *str, int len)
 {
-	if (m_bgFont)
-		m_bgFont->DrawString(x+m_bgX, y+m_bgY, m_bgColor, str, len);
-
-	if (m_font_renderer)
-		g_renderer->BeginBatchHint(TBRenderer::BATCH_HINT_DRAW_BITMAP_FRAGMENT);
-
-	int i = 0;
-	while (str[i] && i < len)
-	{
-		UCS4 cp = utf8::decode_next(str, &i, len);
-		if (cp == 0xFFFF)
-			continue;
-		if (TBFontGlyph *glyph = GetGlyph(cp, true))
-		{
-			if (glyph->frag)
-			{
-				TBRect dst_rect(x + glyph->metrics.x, y + glyph->metrics.y + GetAscent(), glyph->frag->Width(), glyph->frag->Height());
-				TBRect src_rect(0, 0, glyph->frag->Width(), glyph->frag->Height());
-				if (glyph->has_rgb)
-					g_renderer->DrawBitmap(dst_rect, src_rect, glyph->frag);
-				else
-					g_renderer->DrawBitmapColored(dst_rect, src_rect, color, glyph->frag);
-			}
-			x += glyph->metrics.advance;
-		}
-		else if (!m_font_renderer) // This is the test font. Use same glyph width as height and draw square.
-		{
-			g_renderer->DrawRect(TBRect(x, y, m_metrics.height / 3, m_metrics.height), color);
-			x += m_metrics.height / 3 + 1;
-		}
-	}
-
-	if (m_font_renderer)
-		g_renderer->EndBatchHint();
+    if (m_bgFont)
+        m_bgFont->DrawString(x+m_bgX, y+m_bgY, m_bgColor, str, len);
+
+    if (m_font_renderer)
+        g_renderer->BeginBatchHint(TBRenderer::BATCH_HINT_DRAW_BITMAP_FRAGMENT);
+
+    int i = 0;
+    while (str[i] && i < len)
+    {
+        UCS4 cp = utf8::decode_next(str, &i, len);
+        if (cp == 0xFFFF)
+            continue;
+        if (TBFontGlyph *glyph = GetGlyph(cp, true))
+        {
+            if (glyph->frag)
+            {
+                TBRect dst_rect(x + glyph->metrics.x, y + glyph->metrics.y + GetAscent(), glyph->frag->Width(), glyph->frag->Height());
+                TBRect src_rect(0, 0, glyph->frag->Width(), glyph->frag->Height());
+                if (glyph->has_rgb)
+                    g_renderer->DrawBitmap(dst_rect, src_rect, glyph->frag);
+                else
+                    g_renderer->DrawBitmapColored(dst_rect, src_rect, color, glyph->frag);
+            }
+            x += glyph->metrics.advance;
+        }
+        else if (!m_font_renderer) // This is the test font. Use same glyph width as height and draw square.
+        {
+            g_renderer->DrawRect(TBRect(x, y, m_metrics.height / 3, m_metrics.height), color);
+            x += m_metrics.height / 3 + 1;
+        }
+    }
+
+    if (m_font_renderer)
+        g_renderer->EndBatchHint();
 }
 
 int TBFontFace::GetStringWidth(const char *str, int len)
 {
-	int width = 0;
-	int i = 0;
-	while (str[i] && i < len)
-	{
-		UCS4 cp = utf8::decode_next(str, &i, len);
-		if (cp == 0xFFFF)
-			continue;
-		if (!m_font_renderer) // This is the test font. Use same glyph width as height.
-			width += m_metrics.height / 3 + 1;
-		else if (TBFontGlyph *glyph = GetGlyph(cp, false))
-			width += glyph->metrics.advance;
-	}
-	return width;
+    int width = 0;
+    int i = 0;
+    while (str[i] && i < len)
+    {
+        UCS4 cp = utf8::decode_next(str, &i, len);
+        if (cp == 0xFFFF)
+            continue;
+        if (!m_font_renderer) // This is the test font. Use same glyph width as height.
+            width += m_metrics.height / 3 + 1;
+        else if (TBFontGlyph *glyph = GetGlyph(cp, false))
+            width += glyph->metrics.advance;
+    }
+    return width;
 }
 
 #ifdef TB_RUNTIME_DEBUG_INFO
 void TBFontFace::Debug()
 {
-	m_glyph_cache->Debug();
+    m_glyph_cache->Debug();
 }
 #endif // TB_RUNTIME_DEBUG_INFO
 
@@ -442,13 +442,13 @@ void TBFontFace::Debug()
 
 TBFontManager::TBFontManager()
 {
-	// Add the test dummy font with empty name (Equals to ID 0)
-	AddFontInfo("-test-font-dummy-", "");
-	m_test_font_desc.SetSize(16);
-	CreateFontFace(m_test_font_desc);
+    // Add the test dummy font with empty name (Equals to ID 0)
+    AddFontInfo("-test-font-dummy-", "");
+    m_test_font_desc.SetSize(16);
+    CreateFontFace(m_test_font_desc);
 
-	// Use the test dummy font as default by default
-	m_default_font_desc = m_test_font_desc;
+    // Use the test dummy font as default by default
+    m_default_font_desc = m_test_font_desc;
 }
 
 TBFontManager::~TBFontManager()
@@ -457,64 +457,64 @@ TBFontManager::~TBFontManager()
 
 TBFontInfo *TBFontManager::AddFontInfo(const char *filename, const char *name)
 {
-	if (TBFontInfo *fi = new TBFontInfo(filename, name))
-	{
-		if (m_font_info.Add(fi->GetID(), fi))
-			return fi;
-		delete fi;
-	}
-	return nullptr;
+    if (TBFontInfo *fi = new TBFontInfo(filename, name))
+    {
+        if (m_font_info.Add(fi->GetID(), fi))
+            return fi;
+        delete fi;
+    }
+    return nullptr;
 }
 
 TBFontInfo *TBFontManager::GetFontInfo(const TBID &id) const
 {
-	return m_font_info.Get(id);
+    return m_font_info.Get(id);
 }
 
 bool TBFontManager::HasFontFace(const TBFontDescription &font_desc) const
 {
-	return m_fonts.Get(font_desc.GetFontFaceID()) ? true : false;
+    return m_fonts.Get(font_desc.GetFontFaceID()) ? true : false;
 }
 
 TBFontFace *TBFontManager::GetFontFace(const TBFontDescription &font_desc)
 {
-	if (TBFontFace *font = m_fonts.Get(font_desc.GetFontFaceID()))
-		return font;
-	if (TBFontFace *font = m_fonts.Get(GetDefaultFontDescription().GetFontFaceID()))
-		return font;
-	return m_fonts.Get(m_test_font_desc.GetFontFaceID());
+    if (TBFontFace *font = m_fonts.Get(font_desc.GetFontFaceID()))
+        return font;
+    if (TBFontFace *font = m_fonts.Get(GetDefaultFontDescription().GetFontFaceID()))
+        return font;
+    return m_fonts.Get(m_test_font_desc.GetFontFaceID());
 }
 
 TBFontFace *TBFontManager::CreateFontFace(const TBFontDescription &font_desc)
 {
-	assert(!HasFontFace(font_desc)); // There is already a font added with this description!
-
-	TBFontInfo *fi = GetFontInfo(font_desc.GetID());
-	if (!fi)
-		return nullptr;
-
-	if (fi->GetID() == 0) // Is this the test dummy font
-	{
-		if (TBFontFace *font = new TBFontFace(&m_glyph_cache, nullptr, font_desc))
-		{
-			if (m_fonts.Add(font_desc.GetFontFaceID(), font))
-				return font;
-			delete font;
-		}
-		return nullptr;
-	}
-
-	// Iterate through font renderers until we find one capable of creating a font for this file.
-	for (TBFontRenderer *fr = m_font_renderers.GetFirst(); fr; fr = fr->GetNext())
-	{
-		if (TBFontFace *font = fr->Create(this, fi->GetFilename(), font_desc))
-		{
-			if (m_fonts.Add(font_desc.GetFontFaceID(), font))
-				return font;
-			delete font;
-		}
-	}
-	return nullptr;
+    assert(!HasFontFace(font_desc)); // There is already a font added with this description!
+
+    TBFontInfo *fi = GetFontInfo(font_desc.GetID());
+    if (!fi)
+        return nullptr;
+
+    if (fi->GetID() == 0) // Is this the test dummy font
+    {
+        if (TBFontFace *font = new TBFontFace(&m_glyph_cache, nullptr, font_desc))
+        {
+            if (m_fonts.Add(font_desc.GetFontFaceID(), font))
+                return font;
+            delete font;
+        }
+        return nullptr;
+    }
+
+    // Iterate through font renderers until we find one capable of creating a font for this file.
+    for (TBFontRenderer *fr = m_font_renderers.GetFirst(); fr; fr = fr->GetNext())
+    {
+        if (TBFontFace *font = fr->Create(this, fi->GetFilename(), font_desc))
+        {
+            if (m_fonts.Add(font_desc.GetFontFaceID(), font))
+                return font;
+            delete font;
+        }
+    }
+    return nullptr;
 }
 
 }; // namespace tb

+ 157 - 157
Source/ThirdParty/TurboBadger/tb_font_renderer.h

@@ -20,264 +20,264 @@ class TBBitmap;
 class TBFontFace;
 
 /** TBFontGlyphData is rendering info used during glyph rendering by TBFontRenderer.
-	It does not own the data pointers. */
+    It does not own the data pointers. */
 class TBFontGlyphData
 {
 public:
-	TBFontGlyphData() : data8(nullptr), data32(nullptr), w(0), h(0), stride(0), rgb(false) {}
-	~TBFontGlyphData() {}
+    TBFontGlyphData() : data8(nullptr), data32(nullptr), w(0), h(0), stride(0), rgb(false) {}
+    ~TBFontGlyphData() {}
 
-	uint8 *data8;
-	uint32 *data32;
-	int w, h, stride;
-	bool rgb;
+    uint8 *data8;
+    uint32 *data32;
+    int w, h, stride;
+    bool rgb;
 };
 
 /** TBGlyphMetrics contains metrics for a font glyph. */
 class TBGlyphMetrics
 {
 public:
-	TBGlyphMetrics() : advance(0), x(0), y(0) {}
-	int16 advance, x, y;
+    TBGlyphMetrics() : advance(0), x(0), y(0) {}
+    int16 advance, x, y;
 };
 
 /** TBFontMetrics contains metrics for a font face. */
 class TBFontMetrics
 {
 public:
-	TBFontMetrics() : ascent(0), descent(0), height(0) {}
-	int16 ascent;	///< Ascent. See TBFontFace::GetAscent()
-	int16 descent;	///< Descent. See TBFontFace::GetDescent()
-	int16 height;	///< Height. See TBFontFace::GetHeight()
+    TBFontMetrics() : ascent(0), descent(0), height(0) {}
+    int16 ascent;	///< Ascent. See TBFontFace::GetAscent()
+    int16 descent;	///< Descent. See TBFontFace::GetDescent()
+    int16 height;	///< Height. See TBFontFace::GetHeight()
 };
 
 /** TBFontRenderer renders glyphs from a font file. */
 class TBFontRenderer : public TBLinkOf<TBFontRenderer>
 {
 public:
-	virtual ~TBFontRenderer() {}
+    virtual ~TBFontRenderer() {}
 
-	/** Open the given font file with this renderer and return a new TBFontFace with it.
-		return nullptr if the file can't be opened by this renderer. */
-	virtual TBFontFace *Create(TBFontManager *font_manager, const char *filename,
-								const TBFontDescription &font_desc) = 0;
+    /** Open the given font file with this renderer and return a new TBFontFace with it.
+        return nullptr if the file can't be opened by this renderer. */
+    virtual TBFontFace *Create(TBFontManager *font_manager, const char *filename,
+                               const TBFontDescription &font_desc) = 0;
 
-	virtual bool RenderGlyph(TBFontGlyphData *data, UCS4 cp) = 0;
-	virtual void GetGlyphMetrics(TBGlyphMetrics *metrics, UCS4 cp) = 0;
-	virtual TBFontMetrics GetMetrics() = 0;
-	//virtual int GetKernAdvance(UCS4 cp1, UCS4 cp2) = 0;
+    virtual bool RenderGlyph(TBFontGlyphData *data, UCS4 cp) = 0;
+    virtual void GetGlyphMetrics(TBGlyphMetrics *metrics, UCS4 cp) = 0;
+    virtual TBFontMetrics GetMetrics() = 0;
+    //virtual int GetKernAdvance(UCS4 cp1, UCS4 cp2) = 0;
 };
 
 /** TBFontGlyph holds glyph metrics and bitmap fragment.
-	There's one of these for all rendered (both successful
-	and missing) glyphs in TBFontFace. */
+    There's one of these for all rendered (both successful
+    and missing) glyphs in TBFontFace. */
 class TBFontGlyph : public TBLinkOf<TBFontGlyph>
 {
 public:
-	TBFontGlyph(const TBID &hash_id, UCS4 cp);
-	TBID hash_id;
-	UCS4 cp;
-	TBGlyphMetrics metrics;		///< The glyph metrics.
-	TBBitmapFragment *frag;		///< The bitmap fragment, or nullptr if missing.
-	bool has_rgb;				///< if true, drawing should ignore text color.
+    TBFontGlyph(const TBID &hash_id, UCS4 cp);
+    TBID hash_id;
+    UCS4 cp;
+    TBGlyphMetrics metrics;		///< The glyph metrics.
+    TBBitmapFragment *frag;		///< The bitmap fragment, or nullptr if missing.
+    bool has_rgb;				///< if true, drawing should ignore text color.
 };
 
 /** TBFontGlyphCache caches glyphs for font faces.
-	Rendered glyphs use bitmap fragments from its fragment manager. */
+    Rendered glyphs use bitmap fragments from its fragment manager. */
 class TBFontGlyphCache : private TBRendererListener
 {
 public:
-	TBFontGlyphCache();
-	~TBFontGlyphCache();
+    TBFontGlyphCache();
+    ~TBFontGlyphCache();
 
-	/** Get the glyph or nullptr if it is not in the cache. */
-	TBFontGlyph *GetGlyph(const TBID &hash_id, UCS4 cp);
+    /** Get the glyph or nullptr if it is not in the cache. */
+    TBFontGlyph *GetGlyph(const TBID &hash_id, UCS4 cp);
 
-	/** Create the glyph and put it in the cache. Returns the glyph, or nullptr on fail. */
-	TBFontGlyph *CreateAndCacheGlyph(const TBID &hash_id, UCS4 cp);
+    /** Create the glyph and put it in the cache. Returns the glyph, or nullptr on fail. */
+    TBFontGlyph *CreateAndCacheGlyph(const TBID &hash_id, UCS4 cp);
 
-	/** Create a bitmap fragment for the given glyph and render data. This may drop other
-		rendered glyphs from the fragment map. Returns the fragment, or nullptr on fail. */
-	TBBitmapFragment *CreateFragment(TBFontGlyph *glyph, int w, int h, int stride, uint32 *data);
+    /** Create a bitmap fragment for the given glyph and render data. This may drop other
+        rendered glyphs from the fragment map. Returns the fragment, or nullptr on fail. */
+    TBBitmapFragment *CreateFragment(TBFontGlyph *glyph, int w, int h, int stride, uint32 *data);
 
 #ifdef TB_RUNTIME_DEBUG_INFO
-	/** Render the glyph bitmaps on screen, to analyze fragment positioning. */
-	void Debug();
+    /** Render the glyph bitmaps on screen, to analyze fragment positioning. */
+    void Debug();
 #endif
 
-	// Implementing TBRendererListener
-	virtual void OnContextLost();
-	virtual void OnContextRestored();
+    // Implementing TBRendererListener
+    virtual void OnContextLost();
+    virtual void OnContextRestored();
 private:
-	void DropGlyphFragment(TBFontGlyph *glyph);
-	TBBitmapFragmentManager m_frag_manager;
-	TBHashTableAutoDeleteOf<TBFontGlyph> m_glyphs;
-	TBLinkListOf<TBFontGlyph> m_all_rendered_glyphs;
+    void DropGlyphFragment(TBFontGlyph *glyph);
+    TBBitmapFragmentManager m_frag_manager;
+    TBHashTableAutoDeleteOf<TBFontGlyph> m_glyphs;
+    TBLinkListOf<TBFontGlyph> m_all_rendered_glyphs;
 };
 
 /** TBFontEffect applies an effect on each glyph that is rendered in a TBFontFace. */
 class TBFontEffect
 {
 public:
-	TBFontEffect();
-	~TBFontEffect();
+    TBFontEffect();
+    ~TBFontEffect();
 
-	/** Set blur radius. 0 means no blur. */
-	void SetBlurRadius(int blur_radius);
+    /** Set blur radius. 0 means no blur. */
+    void SetBlurRadius(int blur_radius);
 
-	/** Returns true if the result is in RGB and should not be painted using the color parameter
-		given to DrawString. In other words: It's a color glyph. */
-	bool RendersInRGB() const { return false; }
+    /** Returns true if the result is in RGB and should not be painted using the color parameter
+        given to DrawString. In other words: It's a color glyph. */
+    bool RendersInRGB() const { return false; }
 
-	TBFontGlyphData *Render(TBGlyphMetrics *metrics, const TBFontGlyphData *src);
+    TBFontGlyphData *Render(TBGlyphMetrics *metrics, const TBFontGlyphData *src);
 private:
-	// Blur data
-	int m_blur_radius;
-	float *m_tempBuffer;
-	float *m_kernel;
-	TBTempBuffer m_blur_temp;
+    // Blur data
+    int m_blur_radius;
+    float *m_tempBuffer;
+    float *m_kernel;
+    TBTempBuffer m_blur_temp;
 };
 
 /** TBFontFace represents a loaded font that can measure and render strings. */
 class TBFontFace
 {
 public:
-	TBFontFace(TBFontGlyphCache *glyph_cache, TBFontRenderer *renderer, const TBFontDescription &font_desc);
-	~TBFontFace();
+    TBFontFace(TBFontGlyphCache *glyph_cache, TBFontRenderer *renderer, const TBFontDescription &font_desc);
+    ~TBFontFace();
 
-	/** Render all glyphs needed to display the string. */
-	bool RenderGlyphs(const char *glyph_str, int glyph_str_len = TB_ALL_TO_TERMINATION);
+    /** Render all glyphs needed to display the string. */
+    bool RenderGlyphs(const char *glyph_str, int glyph_str_len = TB_ALL_TO_TERMINATION);
 
-	/** Get the vertical distance (positive) from the horizontal baseline to the highest character coordinate
-		in a font face. */
-	int GetAscent() const { return m_metrics.ascent; }
+    /** Get the vertical distance (positive) from the horizontal baseline to the highest character coordinate
+        in a font face. */
+    int GetAscent() const { return m_metrics.ascent; }
 
-	/** Get the vertical distance (positive) from the horizontal baseline to the lowest character coordinate
-		in the font face. */
-	int GetDescent() const { return m_metrics.descent; }
+    /** Get the vertical distance (positive) from the horizontal baseline to the lowest character coordinate
+        in the font face. */
+    int GetDescent() const { return m_metrics.descent; }
 
-	/** Get height of the font in pixels. */
-	int GetHeight() const { return m_metrics.height; }
+    /** Get height of the font in pixels. */
+    int GetHeight() const { return m_metrics.height; }
 
-	/** Get the font description that was used to create this font. */
-	TBFontDescription GetFontDescription() const { return m_font_desc; }
+    /** Get the font description that was used to create this font. */
+    TBFontDescription GetFontDescription() const { return m_font_desc; }
 
-	/** Get the effect object, so the effect can be changed.
-		Note: No glyphs are re-rendered. Only new glyphs are affected. */
-	TBFontEffect *GetEffect() { return &m_effect; }
+    /** Get the effect object, so the effect can be changed.
+        Note: No glyphs are re-rendered. Only new glyphs are affected. */
+    TBFontEffect *GetEffect() { return &m_effect; }
 
-	/** Draw string at position x, y (marks the upper left corner of the text). */
-	void DrawString(int x, int y, const TBColor &color, const char *str, int len = TB_ALL_TO_TERMINATION);
+    /** Draw string at position x, y (marks the upper left corner of the text). */
+    void DrawString(int x, int y, const TBColor &color, const char *str, int len = TB_ALL_TO_TERMINATION);
 
-	/** Measure the width of the given string. Should measure len characters or to the null
-		termination (whatever comes first). */
-	int GetStringWidth(const char *str, int len = TB_ALL_TO_TERMINATION);
+    /** Measure the width of the given string. Should measure len characters or to the null
+        termination (whatever comes first). */
+    int GetStringWidth(const char *str, int len = TB_ALL_TO_TERMINATION);
 
 #ifdef TB_RUNTIME_DEBUG_INFO
-	/** Render the glyph bitmaps on screen, to analyze fragment positioning. */
-	void Debug();
+    /** Render the glyph bitmaps on screen, to analyze fragment positioning. */
+    void Debug();
 #endif
 
-	/** Set a background font which will always be rendered behind this one
-	    when calling DrawString. Very usefull to add a shadow effect to a font. */
-	void SetBackgroundFont(TBFontFace *font, const TBColor &col, int xofs, int yofs);
+    /** Set a background font which will always be rendered behind this one
+        when calling DrawString. Very usefull to add a shadow effect to a font. */
+    void SetBackgroundFont(TBFontFace *font, const TBColor &col, int xofs, int yofs);
 private:
-	TBID GetHashId(UCS4 cp) const;
-	TBFontGlyph *GetGlyph(UCS4 cp, bool render_if_needed);
-	TBFontGlyph *CreateAndCacheGlyph(UCS4 cp);
-	void RenderGlyph(TBFontGlyph *glyph);
-	TBFontGlyphCache *m_glyph_cache;
-	TBFontRenderer *m_font_renderer;
-	TBFontDescription m_font_desc;
-	TBFontMetrics m_metrics;
-	TBFontEffect m_effect;
-	TBTempBuffer m_temp_buffer;
-
-	TBFontFace *m_bgFont;
-	int m_bgX;
-	int m_bgY;
-	TBColor m_bgColor;
+    TBID GetHashId(UCS4 cp) const;
+    TBFontGlyph *GetGlyph(UCS4 cp, bool render_if_needed);
+    TBFontGlyph *CreateAndCacheGlyph(UCS4 cp);
+    void RenderGlyph(TBFontGlyph *glyph);
+    TBFontGlyphCache *m_glyph_cache;
+    TBFontRenderer *m_font_renderer;
+    TBFontDescription m_font_desc;
+    TBFontMetrics m_metrics;
+    TBFontEffect m_effect;
+    TBTempBuffer m_temp_buffer;
+
+    TBFontFace *m_bgFont;
+    int m_bgX;
+    int m_bgY;
+    TBColor m_bgColor;
 };
 
 /** TBFontInfo provides information about a font file associated with a font id. */
 class TBFontInfo
 {
 public:
-	/** Get the font filename. */
-	const char *GetFilename() const { return m_filename; }
+    /** Get the font filename. */
+    const char *GetFilename() const { return m_filename; }
 
-	/** Get the font name. */
-	const char *GetName() const { return m_name; }
+    /** Get the font name. */
+    const char *GetName() const { return m_name; }
 
-	/** Get the font ID that can be used to create this font from a
-		TBFontDescription (See TBFontDescription::SetID) */
-	TBID GetID() const { return m_id; }
+    /** Get the font ID that can be used to create this font from a
+        TBFontDescription (See TBFontDescription::SetID) */
+    TBID GetID() const { return m_id; }
 
 private:
-	friend class TBFontManager;
-	TBFontInfo(const char *filename, const char *name) : m_filename(filename), m_name(name), m_id(name) {}
-	TBStr m_filename;
-	TBStr m_name;
-	TBID m_id;
+    friend class TBFontManager;
+    TBFontInfo(const char *filename, const char *name) : m_filename(filename), m_name(name), m_id(name) {}
+    TBStr m_filename;
+    TBStr m_name;
+    TBID m_id;
 };
 
 /** TBFontManager creates and owns font faces (TBFontFace) which are looked up from
-	TBFontDescription using GetFontFace.
+    TBFontDescription using GetFontFace.
 
-	The fonts it can return must first have their file added and indexed (AddFontInfo),
-	and then created CreateFontFace. Otherwise when asking for a font and it doesn't
-	exist, it will use the default font.
+    The fonts it can return must first have their file added and indexed (AddFontInfo),
+    and then created CreateFontFace. Otherwise when asking for a font and it doesn't
+    exist, it will use the default font.
 
-	Font ID 0 is always populated with a dummy font that draws squares. This font is
-	generally not used for other things than unit testing or as fallback when there is
-	no font backend implemented yet. Since there is always at least the test font, no
-	nullptr checks are needed.
+    Font ID 0 is always populated with a dummy font that draws squares. This font is
+    generally not used for other things than unit testing or as fallback when there is
+    no font backend implemented yet. Since there is always at least the test font, no
+    nullptr checks are needed.
 */
 class TBFontManager
 {
 public:
-	TBFontManager();
-	~TBFontManager();
+    TBFontManager();
+    ~TBFontManager();
 
-	/** Add a renderer so fonts supported by the renderer can be created. Ownership of the
-		renderer is taken, until calling RemoveRenderer. */
-	void AddRenderer(TBFontRenderer *renderer) { m_font_renderers.AddLast(renderer); }
-	void RemoveRenderer(TBFontRenderer *renderer) { m_font_renderers.Remove(renderer); }
+    /** Add a renderer so fonts supported by the renderer can be created. Ownership of the
+        renderer is taken, until calling RemoveRenderer. */
+    void AddRenderer(TBFontRenderer *renderer) { m_font_renderers.AddLast(renderer); }
+    void RemoveRenderer(TBFontRenderer *renderer) { m_font_renderers.Remove(renderer); }
 
-	/** Add TBFontInfo for the given font filename, so it can be loaded and identified
-		using the font id in a TBFontDescription. */
-	TBFontInfo *AddFontInfo(const char *filename, const char *name);
+    /** Add TBFontInfo for the given font filename, so it can be loaded and identified
+        using the font id in a TBFontDescription. */
+    TBFontInfo *AddFontInfo(const char *filename, const char *name);
 
-	/** Get TBFontInfo for the given font id, or nullptr if there is no match. */
-	TBFontInfo *GetFontInfo(const TBID &id) const;
+    /** Get TBFontInfo for the given font id, or nullptr if there is no match. */
+    TBFontInfo *GetFontInfo(const TBID &id) const;
 
-	/** Return true if there is a font loaded that match the given font description. */
-	bool HasFontFace(const TBFontDescription &font_desc) const;
+    /** Return true if there is a font loaded that match the given font description. */
+    bool HasFontFace(const TBFontDescription &font_desc) const;
 
-	/** Get a loaded font matching the description, or the default font if there is no exact match.
-		If there is not even any default font loaded, it will return the test dummy font (rendering
-		only squares). */
-	TBFontFace *GetFontFace(const TBFontDescription &font_desc);
+    /** Get a loaded font matching the description, or the default font if there is no exact match.
+        If there is not even any default font loaded, it will return the test dummy font (rendering
+        only squares). */
+    TBFontFace *GetFontFace(const TBFontDescription &font_desc);
 
-	/** Create and add a font with the given description. Returns the created font face, or
-		nullptr on fail. The font is owned by this TBFontManager, and can be recieved from
-		GetFontFace using the same TBFontDescription. */
-	TBFontFace *CreateFontFace(const TBFontDescription &font_desc);
+    /** Create and add a font with the given description. Returns the created font face, or
+        nullptr on fail. The font is owned by this TBFontManager, and can be recieved from
+        GetFontFace using the same TBFontDescription. */
+    TBFontFace *CreateFontFace(const TBFontDescription &font_desc);
 
-	/** Set the default font description. This is the font description that will be used by default
-		for widgets. By default, the default description is using the test dummy font. */
-	void SetDefaultFontDescription(const TBFontDescription &font_desc) { m_default_font_desc = font_desc; }
-	TBFontDescription GetDefaultFontDescription() const { return m_default_font_desc; }
+    /** Set the default font description. This is the font description that will be used by default
+        for widgets. By default, the default description is using the test dummy font. */
+    void SetDefaultFontDescription(const TBFontDescription &font_desc) { m_default_font_desc = font_desc; }
+    TBFontDescription GetDefaultFontDescription() const { return m_default_font_desc; }
 
-	/** Return the glyph cache used for fonts created by this font manager. */
-	TBFontGlyphCache *GetGlyphCache() { return &m_glyph_cache; }
+    /** Return the glyph cache used for fonts created by this font manager. */
+    TBFontGlyphCache *GetGlyphCache() { return &m_glyph_cache; }
 private:
-	TBHashTableAutoDeleteOf<TBFontInfo> m_font_info;
-	TBHashTableAutoDeleteOf<TBFontFace> m_fonts;
-	TBLinkListAutoDeleteOf<TBFontRenderer> m_font_renderers;
-	TBFontGlyphCache m_glyph_cache;
-	TBFontDescription m_default_font_desc;
-	TBFontDescription m_test_font_desc;
+    TBHashTableAutoDeleteOf<TBFontInfo> m_font_info;
+    TBHashTableAutoDeleteOf<TBFontFace> m_fonts;
+    TBLinkListAutoDeleteOf<TBFontRenderer> m_font_renderers;
+    TBFontGlyphCache m_glyph_cache;
+    TBFontDescription m_default_font_desc;
+    TBFontDescription m_test_font_desc;
 };
 
 }; // namespace tb

+ 122 - 122
Source/ThirdParty/TurboBadger/tb_font_renderer_freetype.cpp

@@ -27,25 +27,25 @@ static TBHashTableOf<FreetypeFace> ft_face_cache;
 class FreetypeFace
 {
 public:
-	FreetypeFace() : hashID(0), ttf_buffer(nullptr), m_face(0), refCount(1) { }
-	~FreetypeFace()
-	{
-		if (hashID)
-			ft_face_cache.Remove(hashID);
-		FT_Done_Face(m_face);
-		delete [] ttf_buffer;
-	}
-	void Release()
-	{
-		--refCount;
-		if (!refCount)
-			delete this;
-	}
-
-	uint32 hashID;
-	unsigned char *ttf_buffer;
-	FT_Face m_face;
-	unsigned int refCount;
+    FreetypeFace() : hashID(0), ttf_buffer(nullptr), m_face(0), refCount(1) { }
+    ~FreetypeFace()
+    {
+        if (hashID)
+            ft_face_cache.Remove(hashID);
+        FT_Done_Face(m_face);
+        delete [] ttf_buffer;
+    }
+    void Release()
+    {
+        --refCount;
+        if (!refCount)
+            delete this;
+    }
+
+    uint32 hashID;
+    unsigned char *ttf_buffer;
+    FT_Face m_face;
+    unsigned int refCount;
 };
 
 
@@ -53,149 +53,149 @@ public:
 class FreetypeFontRenderer : public TBFontRenderer
 {
 public:
-	FreetypeFontRenderer();
-	~FreetypeFontRenderer();
+    FreetypeFontRenderer();
+    ~FreetypeFontRenderer();
 
-	virtual TBFontFace *Create(TBFontManager *font_manager, const char *filename,
-								const TBFontDescription &font_desc);
+    virtual TBFontFace *Create(TBFontManager *font_manager, const char *filename,
+                               const TBFontDescription &font_desc);
 
-	virtual TBFontMetrics GetMetrics();
-	virtual bool RenderGlyph(TBFontGlyphData *dst_bitmap, UCS4 cp);
-	virtual void GetGlyphMetrics(TBGlyphMetrics *metrics, UCS4 cp);
+    virtual TBFontMetrics GetMetrics();
+    virtual bool RenderGlyph(TBFontGlyphData *dst_bitmap, UCS4 cp);
+    virtual void GetGlyphMetrics(TBGlyphMetrics *metrics, UCS4 cp);
 private:
-	bool Load(FreetypeFace *face, int size);
-	bool Load(const char *filename, int size);
+    bool Load(FreetypeFace *face, int size);
+    bool Load(const char *filename, int size);
 
-	FT_Size m_size;
-	FreetypeFace *m_face;
+    FT_Size m_size;
+    FreetypeFace *m_face;
 };
 
 FreetypeFontRenderer::FreetypeFontRenderer()
-	: m_size(nullptr)
-	, m_face(nullptr)
+    : m_size(nullptr)
+    , m_face(nullptr)
 {
-	num_fonts++;
+    num_fonts++;
 }
 
 FreetypeFontRenderer::~FreetypeFontRenderer()
 {
-	FT_Done_Size(m_size);
-	if (m_face)
-		m_face->Release();
-
-	num_fonts--;
-	if (num_fonts == 0 && ft_initialized)
-	{
-		FT_Done_FreeType(g_freetype);
-		ft_initialized = false;
-	}
+    FT_Done_Size(m_size);
+    if (m_face)
+        m_face->Release();
+
+    num_fonts--;
+    if (num_fonts == 0 && ft_initialized)
+    {
+        FT_Done_FreeType(g_freetype);
+        ft_initialized = false;
+    }
 }
 
 TBFontMetrics FreetypeFontRenderer::GetMetrics()
 {
-	TBFontMetrics metrics;
-	metrics.ascent = (int16) (m_size->metrics.ascender >> 6);
-	metrics.descent = (int16) -(m_size->metrics.descender >> 6);
-	metrics.height = (int16) (m_size->metrics.height >> 6);
-	return metrics;
+    TBFontMetrics metrics;
+    metrics.ascent = (int16) (m_size->metrics.ascender >> 6);
+    metrics.descent = (int16) -(m_size->metrics.descender >> 6);
+    metrics.height = (int16) (m_size->metrics.height >> 6);
+    return metrics;
 }
 
 bool FreetypeFontRenderer::RenderGlyph(TBFontGlyphData *data, UCS4 cp)
 {
-	FT_Activate_Size(m_size);
-	FT_GlyphSlot slot = m_face->m_face->glyph;
-	if (FT_Load_Char(m_face->m_face, cp, FT_LOAD_RENDER) ||
-		slot->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
-		return false;
-	data->w = slot->bitmap.width;
-	data->h = slot->bitmap.rows;
-	data->stride = slot->bitmap.pitch;
-	data->data8 = slot->bitmap.buffer;
-	return data->data8 ? true : false;
+    FT_Activate_Size(m_size);
+    FT_GlyphSlot slot = m_face->m_face->glyph;
+    if (FT_Load_Char(m_face->m_face, cp, FT_LOAD_RENDER) ||
+            slot->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
+        return false;
+    data->w = slot->bitmap.width;
+    data->h = slot->bitmap.rows;
+    data->stride = slot->bitmap.pitch;
+    data->data8 = slot->bitmap.buffer;
+    return data->data8 ? true : false;
 }
 
 void FreetypeFontRenderer::GetGlyphMetrics(TBGlyphMetrics *metrics, UCS4 cp)
 {
-	FT_Activate_Size(m_size);
-	FT_GlyphSlot slot = m_face->m_face->glyph;
-	if (FT_Load_Char(m_face->m_face, cp, FT_LOAD_RENDER))
-		return;
-	metrics->advance = (int16) (slot->advance.x >> 6);
-	metrics->x = slot->bitmap_left;
-	metrics->y = - slot->bitmap_top;
+    FT_Activate_Size(m_size);
+    FT_GlyphSlot slot = m_face->m_face->glyph;
+    if (FT_Load_Char(m_face->m_face, cp, FT_LOAD_RENDER))
+        return;
+    metrics->advance = (int16) (slot->advance.x >> 6);
+    metrics->x = slot->bitmap_left;
+    metrics->y = - slot->bitmap_top;
 }
 
 bool FreetypeFontRenderer::Load(FreetypeFace *face, int size)
 {
-	// Should not be possible to have a face if freetype is not initialized
-	assert(ft_initialized);
-	m_face = face;
-	if (FT_New_Size(m_face->m_face, &m_size) ||
-		FT_Activate_Size(m_size) ||
-		FT_Set_Pixel_Sizes(m_face->m_face, 0, size))
-		return false;
-	return true;
+    // Should not be possible to have a face if freetype is not initialized
+    assert(ft_initialized);
+    m_face = face;
+    if (FT_New_Size(m_face->m_face, &m_size) ||
+            FT_Activate_Size(m_size) ||
+            FT_Set_Pixel_Sizes(m_face->m_face, 0, size))
+        return false;
+    return true;
 }
 
 bool FreetypeFontRenderer::Load(const char *filename, int size)
 {
-	if (!ft_initialized)
-		ft_initialized = !FT_Init_FreeType(&g_freetype);
-	if (!ft_initialized)
-		return false;
-
-	m_face = new FreetypeFace();
-	if (!m_face)
-		return false;
-
-	TBFile *f = TBFile::Open(filename, TBFile::MODE_READ);
-	if (!f)
-		return false;
-
-	size_t ttf_buf_size = f->Size();
-	m_face->ttf_buffer = new unsigned char[ttf_buf_size];
-	if (m_face->ttf_buffer)
-		ttf_buf_size = f->Read(m_face->ttf_buffer, 1, ttf_buf_size);
-	delete f;
-
-	if (!m_face->ttf_buffer)
-		return false;
-
-	if (FT_New_Memory_Face(g_freetype, m_face->ttf_buffer, ttf_buf_size, 0, &m_face->m_face))
-		return false;
-	return Load(m_face, size);
+    if (!ft_initialized)
+        ft_initialized = !FT_Init_FreeType(&g_freetype);
+    if (!ft_initialized)
+        return false;
+
+    m_face = new FreetypeFace();
+    if (!m_face)
+        return false;
+
+    TBFile *f = TBFile::Open(filename, TBFile::MODE_READ);
+    if (!f)
+        return false;
+
+    size_t ttf_buf_size = f->Size();
+    m_face->ttf_buffer = new unsigned char[ttf_buf_size];
+    if (m_face->ttf_buffer)
+        ttf_buf_size = f->Read(m_face->ttf_buffer, 1, ttf_buf_size);
+    delete f;
+
+    if (!m_face->ttf_buffer)
+        return false;
+
+    if (FT_New_Memory_Face(g_freetype, m_face->ttf_buffer, ttf_buf_size, 0, &m_face->m_face))
+        return false;
+    return Load(m_face, size);
 }
 
 TBFontFace *FreetypeFontRenderer::Create(TBFontManager *font_manager, const char *filename, const TBFontDescription &font_desc)
 {
-	if (FreetypeFontRenderer *fr = new FreetypeFontRenderer())
-	{
-		TBID face_cache_id(filename);
-		FreetypeFace *f = ft_face_cache.Get(face_cache_id);
-		if (f)
-		{
-			++f->refCount;
-			if (fr->Load(f, (int) font_desc.GetSize()))
-				if (TBFontFace *font = new TBFontFace(font_manager->GetGlyphCache(), fr, font_desc))
-					return font;
-		}
-		else if (fr->Load(filename, (int) font_desc.GetSize()))
-		{
-			if (ft_face_cache.Add(face_cache_id, fr->m_face))
-				fr->m_face->hashID = face_cache_id;
-			if (TBFontFace *font = new TBFontFace(font_manager->GetGlyphCache(), fr, font_desc))
-				return font;
-		}
-
-		delete fr;
-	}
-	return nullptr;
+    if (FreetypeFontRenderer *fr = new FreetypeFontRenderer())
+    {
+        TBID face_cache_id(filename);
+        FreetypeFace *f = ft_face_cache.Get(face_cache_id);
+        if (f)
+        {
+            ++f->refCount;
+            if (fr->Load(f, (int) font_desc.GetSize()))
+                if (TBFontFace *font = new TBFontFace(font_manager->GetGlyphCache(), fr, font_desc))
+                    return font;
+        }
+        else if (fr->Load(filename, (int) font_desc.GetSize()))
+        {
+            if (ft_face_cache.Add(face_cache_id, fr->m_face))
+                fr->m_face->hashID = face_cache_id;
+            if (TBFontFace *font = new TBFontFace(font_manager->GetGlyphCache(), fr, font_desc))
+                return font;
+        }
+
+        delete fr;
+    }
+    return nullptr;
 }
 
 void register_freetype_font_renderer()
 {
-	if (FreetypeFontRenderer *fr = new FreetypeFontRenderer)
-		g_font_manager->AddRenderer(fr);
+    if (FreetypeFontRenderer *fr = new FreetypeFontRenderer)
+        g_font_manager->AddRenderer(fr);
 }
 
 #endif // TB_FONT_RENDERER_FREETYPE

+ 61 - 61
Source/ThirdParty/TurboBadger/tb_font_renderer_stb.cpp

@@ -19,107 +19,107 @@ using namespace tb;
 class STBFontRenderer : public TBFontRenderer
 {
 public:
-	STBFontRenderer();
-	~STBFontRenderer();
+    STBFontRenderer();
+    ~STBFontRenderer();
 
-	bool Load(const char *filename, int size);
+    bool Load(const char *filename, int size);
 
-	virtual TBFontFace *Create(TBFontManager *font_manager, const char *filename,
-								const TBFontDescription &font_desc);
+    virtual TBFontFace *Create(TBFontManager *font_manager, const char *filename,
+                               const TBFontDescription &font_desc);
 
-	virtual TBFontMetrics GetMetrics();
-	virtual bool RenderGlyph(TBFontGlyphData *dst_bitmap, UCS4 cp);
-	virtual void GetGlyphMetrics(TBGlyphMetrics *metrics, UCS4 cp);
+    virtual TBFontMetrics GetMetrics();
+    virtual bool RenderGlyph(TBFontGlyphData *dst_bitmap, UCS4 cp);
+    virtual void GetGlyphMetrics(TBGlyphMetrics *metrics, UCS4 cp);
 private:
-	stbtt_fontinfo font;
-	unsigned char *ttf_buffer;
-	unsigned char *render_data;
-	int font_size;
-	float scale;
+    stbtt_fontinfo font;
+    unsigned char *ttf_buffer;
+    unsigned char *render_data;
+    int font_size;
+    float scale;
 };
 
 STBFontRenderer::STBFontRenderer()
-	: ttf_buffer(nullptr)
-	, render_data(nullptr)
+    : ttf_buffer(nullptr)
+    , render_data(nullptr)
 {
 }
 
 STBFontRenderer::~STBFontRenderer()
 {
-	delete [] ttf_buffer;
-	delete [] render_data;
+    delete [] ttf_buffer;
+    delete [] render_data;
 }
 
 TBFontMetrics STBFontRenderer::GetMetrics()
 {
-	TBFontMetrics metrics;
-	int ascent, descent, lineGap;
-	stbtt_GetFontVMetrics(&font, &ascent, &descent, &lineGap);
-	metrics.ascent = (int) (ascent * scale + 0.5f);
-	metrics.descent = (int) ((-descent) * scale + 0.5f);
-	metrics.height = (int) ((ascent - descent + lineGap) * scale + 0.5f);
-	return metrics;
+    TBFontMetrics metrics;
+    int ascent, descent, lineGap;
+    stbtt_GetFontVMetrics(&font, &ascent, &descent, &lineGap);
+    metrics.ascent = (int) (ascent * scale + 0.5f);
+    metrics.descent = (int) ((-descent) * scale + 0.5f);
+    metrics.height = (int) ((ascent - descent + lineGap) * scale + 0.5f);
+    return metrics;
 }
 
 bool STBFontRenderer::RenderGlyph(TBFontGlyphData *data, UCS4 cp)
 {
-	delete [] render_data;
-	render_data = stbtt_GetCodepointBitmap(&font, 0, scale, cp, &data->w, &data->h, 0, 0);
-	data->data8 = render_data;
-	data->stride = data->w;
-	data->rgb = false;
-	return data->data8 ? true : false;
+    delete [] render_data;
+    render_data = stbtt_GetCodepointBitmap(&font, 0, scale, cp, &data->w, &data->h, 0, 0);
+    data->data8 = render_data;
+    data->stride = data->w;
+    data->rgb = false;
+    return data->data8 ? true : false;
 }
 
 void STBFontRenderer::GetGlyphMetrics(TBGlyphMetrics *metrics, UCS4 cp)
 {
-	int advanceWidth, leftSideBearing;
-	stbtt_GetCodepointHMetrics(&font, cp, &advanceWidth, &leftSideBearing);
-	metrics->advance = (int) (advanceWidth * scale + 0.5f);
-	int ix0, iy0, ix1, iy1;
-	stbtt_GetCodepointBitmapBox(&font, cp, 0, scale, &ix0, &iy0, &ix1, &iy1);
-	metrics->x = ix0;
-	metrics->y = iy0;
+    int advanceWidth, leftSideBearing;
+    stbtt_GetCodepointHMetrics(&font, cp, &advanceWidth, &leftSideBearing);
+    metrics->advance = (int) (advanceWidth * scale + 0.5f);
+    int ix0, iy0, ix1, iy1;
+    stbtt_GetCodepointBitmapBox(&font, cp, 0, scale, &ix0, &iy0, &ix1, &iy1);
+    metrics->x = ix0;
+    metrics->y = iy0;
 }
 
 bool STBFontRenderer::Load(const char *filename, int size)
 {
-	TBFile *f = TBFile::Open(filename, TBFile::MODE_READ);
-	if (!f)
-		return false;
+    TBFile *f = TBFile::Open(filename, TBFile::MODE_READ);
+    if (!f)
+        return false;
 
-	size_t ttf_buf_size = f->Size();
-	ttf_buffer = new unsigned char[ttf_buf_size];
-	if (ttf_buffer)
-		ttf_buf_size = f->Read(ttf_buffer, 1, ttf_buf_size);
-	delete f;
+    size_t ttf_buf_size = f->Size();
+    ttf_buffer = new unsigned char[ttf_buf_size];
+    if (ttf_buffer)
+        ttf_buf_size = f->Read(ttf_buffer, 1, ttf_buf_size);
+    delete f;
 
-	if (!ttf_buffer)
-		return false;
+    if (!ttf_buffer)
+        return false;
 
-	stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer, 0));
+    stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer, 0));
 
-	font_size = (int) (size * 1.3f); // FIX: Constant taken out of thin air because fonts get too small.
-	scale = stbtt_ScaleForPixelHeight(&font, (float)font_size);
-	return true;
+    font_size = (int) (size * 1.3f); // FIX: Constant taken out of thin air because fonts get too small.
+    scale = stbtt_ScaleForPixelHeight(&font, (float)font_size);
+    return true;
 }
 
 TBFontFace *STBFontRenderer::Create(TBFontManager *font_manager, const char *filename, const TBFontDescription &font_desc)
 {
-	if (STBFontRenderer *fr = new STBFontRenderer())
-	{
-		if (fr->Load(filename, (int) font_desc.GetSize()))
-			if (TBFontFace *font = new TBFontFace(font_manager->GetGlyphCache(), fr, font_desc))
-				return font;
-		delete fr;
-	}
-	return nullptr;
+    if (STBFontRenderer *fr = new STBFontRenderer())
+    {
+        if (fr->Load(filename, (int) font_desc.GetSize()))
+            if (TBFontFace *font = new TBFontFace(font_manager->GetGlyphCache(), fr, font_desc))
+                return font;
+        delete fr;
+    }
+    return nullptr;
 }
 
 void register_stb_font_renderer()
 {
-	if (STBFontRenderer *fr = new STBFontRenderer)
-		g_font_manager->AddRenderer(fr);
+    if (STBFontRenderer *fr = new STBFontRenderer)
+        g_font_manager->AddRenderer(fr);
 }
 
 #endif // TB_FONT_RENDERER_STB

+ 209 - 209
Source/ThirdParty/TurboBadger/tb_font_renderer_tbbf.cpp

@@ -15,271 +15,271 @@
 using namespace tb;
 
 struct GLYPH {
-	int x, w;
+    int x, w;
 };
 
 /** TBBFRenderer renders a bitmap font.
 
-	A font is loaded from a text file and at least one image that contains
-	glyphs for a given size. The number of glyphs that the font contains is
-	defined by the glyph string defined in the text file.
-
-	Text file format (in tb.txt format parsed by parser/tb_parser.h):
-
-		- info>glyph_str			Should specify which characters the image
-								file contains.
-		- info>rgb				Set to 1 for color fonts that should never
-								care about the text color when drawing.
-								Set to 0 to let drawing blend using the text
-								color. Default 0.
-		- size xx				Specify font size xx. Should contain the
-								following nodes:
-			- bitmap				The image file name (in the same folder).
-			- ascent				The ascent. Default 0.
-			- descent			The descent. Default 0.
-			- x_ofs				The x offset for all glyph. This can be
-								used in combination with advance_delta to
-								compensate for f.ex glow that extend
-								around the glyph.  Default 0.
-			- advance_delta		The advance delta for all glyphs. This can
-								be used to compensate for f.ex shadow that
-								should not add to each glyphs horizontal
-								advance. Default 0.
-			- space_advance		The advance for the space character.
-
-	Image file format
-
-		Should contain the characters specified in the glyph_str.
-
-		All characters should be placed on one long line. Each glyph will be
-		found, measured and cropped automatically. In order for this to work,
-		each glyph must touch pixels somewhere from the left to the right edge.
-		So if you f.ex have a quotation mark, you will have to make sure there
-		is pixels with alpha > 0 between the two dots, otherwise the dots will
-		be identified as different glyphs.
+    A font is loaded from a text file and at least one image that contains
+    glyphs for a given size. The number of glyphs that the font contains is
+    defined by the glyph string defined in the text file.
+
+    Text file format (in tb.txt format parsed by parser/tb_parser.h):
+
+        - info>glyph_str			Should specify which characters the image
+                                file contains.
+        - info>rgb				Set to 1 for color fonts that should never
+                                care about the text color when drawing.
+                                Set to 0 to let drawing blend using the text
+                                color. Default 0.
+        - size xx				Specify font size xx. Should contain the
+                                following nodes:
+            - bitmap				The image file name (in the same folder).
+            - ascent				The ascent. Default 0.
+            - descent			The descent. Default 0.
+            - x_ofs				The x offset for all glyph. This can be
+                                used in combination with advance_delta to
+                                compensate for f.ex glow that extend
+                                around the glyph.  Default 0.
+            - advance_delta		The advance delta for all glyphs. This can
+                                be used to compensate for f.ex shadow that
+                                should not add to each glyphs horizontal
+                                advance. Default 0.
+            - space_advance		The advance for the space character.
+
+    Image file format
+
+        Should contain the characters specified in the glyph_str.
+
+        All characters should be placed on one long line. Each glyph will be
+        found, measured and cropped automatically. In order for this to work,
+        each glyph must touch pixels somewhere from the left to the right edge.
+        So if you f.ex have a quotation mark, you will have to make sure there
+        is pixels with alpha > 0 between the two dots, otherwise the dots will
+        be identified as different glyphs.
 */
 class TBBFRenderer : public TBFontRenderer
 {
 public:
-	TBBFRenderer();
-	~TBBFRenderer();
+    TBBFRenderer();
+    ~TBBFRenderer();
 
-	bool Load(const char *filename, int size);
-	bool FindGlyphs();
-	GLYPH *FindNext(UCS4 cp, int x);
+    bool Load(const char *filename, int size);
+    bool FindGlyphs();
+    GLYPH *FindNext(UCS4 cp, int x);
 
-	virtual TBFontFace *Create(TBFontManager *font_manager, const char *filename,
-								const TBFontDescription &font_desc);
+    virtual TBFontFace *Create(TBFontManager *font_manager, const char *filename,
+                               const TBFontDescription &font_desc);
 
-	virtual TBFontMetrics GetMetrics();
-	virtual bool RenderGlyph(TBFontGlyphData *dst_bitmap, UCS4 cp);
-	virtual void GetGlyphMetrics(TBGlyphMetrics *metrics, UCS4 cp);
+    virtual TBFontMetrics GetMetrics();
+    virtual bool RenderGlyph(TBFontGlyphData *dst_bitmap, UCS4 cp);
+    virtual void GetGlyphMetrics(TBGlyphMetrics *metrics, UCS4 cp);
 private:
-	TBNode m_node;
-	TBFontMetrics m_metrics;
-	TBImageLoader *m_img;
-	int m_size;
-	int m_x_ofs;
-	int m_advance_delta;
-	int m_space_advance;
-	int m_rgb;
-	TBHashTableAutoDeleteOf<GLYPH> m_glyph_table;
+    TBNode m_node;
+    TBFontMetrics m_metrics;
+    TBImageLoader *m_img;
+    int m_size;
+    int m_x_ofs;
+    int m_advance_delta;
+    int m_space_advance;
+    int m_rgb;
+    TBHashTableAutoDeleteOf<GLYPH> m_glyph_table;
 };
 
 TBBFRenderer::TBBFRenderer()
-	: m_img(nullptr)
-	, m_size(0)
-	, m_x_ofs(0)
-	, m_advance_delta(0)
-	, m_space_advance(0)
-	, m_rgb(0)
+    : m_img(nullptr)
+    , m_size(0)
+    , m_x_ofs(0)
+    , m_advance_delta(0)
+    , m_space_advance(0)
+    , m_rgb(0)
 {
 }
 
 TBBFRenderer::~TBBFRenderer()
 {
-	delete m_img;
+    delete m_img;
 }
 
 TBFontMetrics TBBFRenderer::GetMetrics()
 {
-	return m_metrics;
+    return m_metrics;
 }
 
 bool TBBFRenderer::RenderGlyph(TBFontGlyphData *data, UCS4 cp)
 {
-	if (cp == ' ')
-		return false;
-	GLYPH *glyph;
-	if ((glyph = m_glyph_table.Get(cp)) ||
-		(glyph = m_glyph_table.Get('?')))
-	{
-		data->w = glyph->w;
-		data->h = m_img->Height();
-		data->stride = m_img->Width();
-		data->data32 = m_img->Data() + glyph->x;
-		data->rgb = m_rgb ? true : false;
-		return true;
-	}
-	return false;
+    if (cp == ' ')
+        return false;
+    GLYPH *glyph;
+    if ((glyph = m_glyph_table.Get(cp)) ||
+            (glyph = m_glyph_table.Get('?')))
+    {
+        data->w = glyph->w;
+        data->h = m_img->Height();
+        data->stride = m_img->Width();
+        data->data32 = m_img->Data() + glyph->x;
+        data->rgb = m_rgb ? true : false;
+        return true;
+    }
+    return false;
 }
 
 void TBBFRenderer::GetGlyphMetrics(TBGlyphMetrics *metrics, UCS4 cp)
 {
-	metrics->x = m_x_ofs;
-	metrics->y = -m_metrics.ascent;
-	if (cp == ' ')
-		metrics->advance = m_space_advance;
-	else if (GLYPH *glyph = m_glyph_table.Get(cp))
-		metrics->advance = glyph->w + m_advance_delta;
-	else if (GLYPH *glyph = m_glyph_table.Get('?'))
-		metrics->advance = glyph->w + m_advance_delta;
+    metrics->x = m_x_ofs;
+    metrics->y = -m_metrics.ascent;
+    if (cp == ' ')
+        metrics->advance = m_space_advance;
+    else if (GLYPH *glyph = m_glyph_table.Get(cp))
+        metrics->advance = glyph->w + m_advance_delta;
+    else if (GLYPH *glyph = m_glyph_table.Get('?'))
+        metrics->advance = glyph->w + m_advance_delta;
 }
 
 bool TBBFRenderer::Load(const char *filename, int size)
 {
-	m_size = size;
-	if (!m_node.ReadFile(filename))
-		return false;
-
-	// Check for size nodes and get the one closest to the size we want.
-	TBNode *size_node = nullptr;
-	for (TBNode *n = m_node.GetFirstChild(); n; n = n->GetNext())
-	{
-		if (strcmp(n->GetName(), "size") == 0)
-		{
-			if (!size_node || ABS(m_size - n->GetValue().GetInt()) < ABS(m_size - size_node->GetValue().GetInt()))
-				size_node = n;
-		}
-	}
-	if (!size_node)
-		return false;
-
-	// Metrics
-	m_metrics.ascent = size_node->GetValueInt("ascent", 0);
-	m_metrics.descent = size_node->GetValueInt("descent", 0);
-	m_metrics.height = m_metrics.ascent + m_metrics.descent;
-
-	// Other data
-	m_advance_delta = size_node->GetValueInt("advance_delta", 0);
-	m_space_advance = size_node->GetValueInt("space_advance", 0);
-	m_x_ofs = size_node->GetValueInt("x_ofs", 0);
-
-	// Info
-	m_rgb = m_node.GetValueInt("info>rgb", 0);
-
-	// Get the path for the bitmap file.
-	TBTempBuffer bitmap_filename;
-	if (!bitmap_filename.AppendPath(filename))
-		return false;
-
-	// Append the bitmap filename for the given size.
-	bitmap_filename.AppendString(size_node->GetValueString("bitmap", ""));
-
-	m_img = TBImageLoader::CreateFromFile(bitmap_filename.GetData());
-
-	return FindGlyphs();
+    m_size = size;
+    if (!m_node.ReadFile(filename))
+        return false;
+
+    // Check for size nodes and get the one closest to the size we want.
+    TBNode *size_node = nullptr;
+    for (TBNode *n = m_node.GetFirstChild(); n; n = n->GetNext())
+    {
+        if (strcmp(n->GetName(), "size") == 0)
+        {
+            if (!size_node || ABS(m_size - n->GetValue().GetInt()) < ABS(m_size - size_node->GetValue().GetInt()))
+                size_node = n;
+        }
+    }
+    if (!size_node)
+        return false;
+
+    // Metrics
+    m_metrics.ascent = size_node->GetValueInt("ascent", 0);
+    m_metrics.descent = size_node->GetValueInt("descent", 0);
+    m_metrics.height = m_metrics.ascent + m_metrics.descent;
+
+    // Other data
+    m_advance_delta = size_node->GetValueInt("advance_delta", 0);
+    m_space_advance = size_node->GetValueInt("space_advance", 0);
+    m_x_ofs = size_node->GetValueInt("x_ofs", 0);
+
+    // Info
+    m_rgb = m_node.GetValueInt("info>rgb", 0);
+
+    // Get the path for the bitmap file.
+    TBTempBuffer bitmap_filename;
+    if (!bitmap_filename.AppendPath(filename))
+        return false;
+
+    // Append the bitmap filename for the given size.
+    bitmap_filename.AppendString(size_node->GetValueString("bitmap", ""));
+
+    m_img = TBImageLoader::CreateFromFile(bitmap_filename.GetData());
+
+    return FindGlyphs();
 }
 
 inline unsigned char GetAlpha(uint32 color)
 {
-	return (color & 0xff000000) >> 24;
+    return (color & 0xff000000) >> 24;
 }
 
 bool TBBFRenderer::FindGlyphs()
 {
-	if (!m_img)
-		return false;
-
-	const char *glyph_str = m_node.GetValueString("info>glyph_str", nullptr);
-	if (!glyph_str)
-		return false;
-
-	int glyph_str_len = strlen(glyph_str);
-	int i = 0;
-	int x = 0;
-	while (UCS4 uc = utf8::decode_next(glyph_str, &i, glyph_str_len))
-	{
-		if (GLYPH *glyph = FindNext(uc, x))
-		{
-			m_glyph_table.Add(uc, glyph); // OOM!
-			x = glyph->x + glyph->w + 1;
-		}
-		else
-			break;
-	}
-	return true;
+    if (!m_img)
+        return false;
+
+    const char *glyph_str = m_node.GetValueString("info>glyph_str", nullptr);
+    if (!glyph_str)
+        return false;
+
+    int glyph_str_len = strlen(glyph_str);
+    int i = 0;
+    int x = 0;
+    while (UCS4 uc = utf8::decode_next(glyph_str, &i, glyph_str_len))
+    {
+        if (GLYPH *glyph = FindNext(uc, x))
+        {
+            m_glyph_table.Add(uc, glyph); // OOM!
+            x = glyph->x + glyph->w + 1;
+        }
+        else
+            break;
+    }
+    return true;
 }
 
 GLYPH *TBBFRenderer::FindNext(UCS4 cp, int x)
 {
-	int width = m_img->Width();
-	int height = m_img->Height();
-	uint32 *data32 = m_img->Data();
-
-	if (x >= width)
-		return nullptr;
-
-	GLYPH *glyph = new GLYPH;
-	if (!glyph)
-		return nullptr;
-
-	glyph->x = -1;
-	glyph->w = -1;
-
-	// Find the left edge of the glyph
-	for (int i = x; i < width && glyph->x == -1; i++)
-	{
-		for (int j = 0; j < height; j++)
-			if (GetAlpha(data32[i + j * width]))
-			{
-				glyph->x = x = i;
-				break;
-			}
-	}
-
-	// Find the right edge of the glyph
-	for (int i = x; i < width; i++)
-	{
-		int j;
-		for (j = 0; j < height; j++)
-		{
-			if (GetAlpha(data32[i + j * width]))
-				break;
-		}
-		if (j == height) // The whole col was clear, so we found the edge
-		{
-			glyph->w = i - glyph->x;
-			break;
-		}
-	}
-
-	if (glyph->x == -1 || glyph->w == -1)
-	{
-		delete glyph;
-		return nullptr;
-	}
-	return glyph;
+    int width = m_img->Width();
+    int height = m_img->Height();
+    uint32 *data32 = m_img->Data();
+
+    if (x >= width)
+        return nullptr;
+
+    GLYPH *glyph = new GLYPH;
+    if (!glyph)
+        return nullptr;
+
+    glyph->x = -1;
+    glyph->w = -1;
+
+    // Find the left edge of the glyph
+    for (int i = x; i < width && glyph->x == -1; i++)
+    {
+        for (int j = 0; j < height; j++)
+            if (GetAlpha(data32[i + j * width]))
+            {
+                glyph->x = x = i;
+                break;
+            }
+    }
+
+    // Find the right edge of the glyph
+    for (int i = x; i < width; i++)
+    {
+        int j;
+        for (j = 0; j < height; j++)
+        {
+            if (GetAlpha(data32[i + j * width]))
+                break;
+        }
+        if (j == height) // The whole col was clear, so we found the edge
+        {
+            glyph->w = i - glyph->x;
+            break;
+        }
+    }
+
+    if (glyph->x == -1 || glyph->w == -1)
+    {
+        delete glyph;
+        return nullptr;
+    }
+    return glyph;
 }
 
 TBFontFace *TBBFRenderer::Create(TBFontManager *font_manager, const char *filename, const TBFontDescription &font_desc)
 {
-	if (!strstr(filename, ".tb.txt"))
-		return nullptr;
-	if (TBBFRenderer *fr = new TBBFRenderer())
-	{
-		if (fr->Load(filename, (int) font_desc.GetSize()))
-			if (TBFontFace *font = new TBFontFace(font_manager->GetGlyphCache(), fr, font_desc))
-				return font;
-		delete fr;
-	}
-	return nullptr;
+    if (!strstr(filename, ".tb.txt"))
+        return nullptr;
+    if (TBBFRenderer *fr = new TBBFRenderer())
+    {
+        if (fr->Load(filename, (int) font_desc.GetSize()))
+            if (TBFontFace *font = new TBFontFace(font_manager->GetGlyphCache(), fr, font_desc))
+                return font;
+        delete fr;
+    }
+    return nullptr;
 }
 
 void register_tbbf_font_renderer()
 {
-	if (TBBFRenderer *fr = new TBBFRenderer)
-		g_font_manager->AddRenderer(fr);
+    if (TBBFRenderer *fr = new TBBFRenderer)
+        g_font_manager->AddRenderer(fr);
 }
 
 #endif // TB_FONT_RENDERER_TBBF

+ 148 - 148
Source/ThirdParty/TurboBadger/tb_geometry.cpp

@@ -12,223 +12,223 @@ namespace tb {
 
 bool TBRect::Intersects(const TBRect &rect) const
 {
-	if (IsEmpty() || rect.IsEmpty())
-		return false;
-	if (x + w > rect.x && x < rect.x + rect.w &&
-		y + h > rect.y && y < rect.y + rect.h)
-		return true;
-	return false;
+    if (IsEmpty() || rect.IsEmpty())
+        return false;
+    if (x + w > rect.x && x < rect.x + rect.w &&
+            y + h > rect.y && y < rect.y + rect.h)
+        return true;
+    return false;
 }
 
 TBRect TBRect::MoveIn(const TBRect &bounding_rect) const
 {
-	return TBRect(ClampClipMax(x, bounding_rect.x, bounding_rect.x + bounding_rect.w - w),
-				ClampClipMax(y, bounding_rect.y, bounding_rect.y + bounding_rect.h - h),
-				w, h);
+    return TBRect(ClampClipMax(x, bounding_rect.x, bounding_rect.x + bounding_rect.w - w),
+                  ClampClipMax(y, bounding_rect.y, bounding_rect.y + bounding_rect.h - h),
+                  w, h);
 }
 
 TBRect TBRect::CenterIn(const TBRect &bounding_rect) const
 {
-	return TBRect((bounding_rect.w - w) / 2, (bounding_rect.h - h) / 2, w, h);
+    return TBRect((bounding_rect.w - w) / 2, (bounding_rect.h - h) / 2, w, h);
 }
 
 TBRect TBRect::Union(const TBRect &rect) const
 {
-	assert(!IsInsideOut());
-	assert(!rect.IsInsideOut());
+    assert(!IsInsideOut());
+    assert(!rect.IsInsideOut());
 
-	if (IsEmpty())
-		return rect;
-	if (rect.IsEmpty())
-		return *this;
+    if (IsEmpty())
+        return rect;
+    if (rect.IsEmpty())
+        return *this;
 
-	int minx = MIN(x, rect.x);
-	int miny = MIN(y, rect.y);
-	int maxx = x + w > rect.x + rect.w ?
-				x + w : rect.x + rect.w;
-	int maxy = y + h > rect.y + rect.h ?
-				y + h : rect.y + rect.h;
-	return TBRect(minx, miny, maxx - minx, maxy - miny);
+    int minx = MIN(x, rect.x);
+    int miny = MIN(y, rect.y);
+    int maxx = x + w > rect.x + rect.w ?
+                x + w : rect.x + rect.w;
+    int maxy = y + h > rect.y + rect.h ?
+                y + h : rect.y + rect.h;
+    return TBRect(minx, miny, maxx - minx, maxy - miny);
 }
 
 TBRect TBRect::Clip(const TBRect &clip_rect) const
 {
-	assert(!clip_rect.IsInsideOut());
-	TBRect tmp;
-	if (!Intersects(clip_rect))
-		return tmp;
-	tmp.x = MAX(x, clip_rect.x);
-	tmp.y = MAX(y, clip_rect.y);
-	tmp.w = MIN(x + w, clip_rect.x + clip_rect.w) - tmp.x;
-	tmp.h = MIN(y + h, clip_rect.y + clip_rect.h) - tmp.y;
-	return tmp;
+    assert(!clip_rect.IsInsideOut());
+    TBRect tmp;
+    if (!Intersects(clip_rect))
+        return tmp;
+    tmp.x = MAX(x, clip_rect.x);
+    tmp.y = MAX(y, clip_rect.y);
+    tmp.w = MIN(x + w, clip_rect.x + clip_rect.w) - tmp.x;
+    tmp.h = MIN(y + h, clip_rect.y + clip_rect.h) - tmp.y;
+    return tmp;
 }
 
 // == TBRegion ==========================================================================
 
 TBRegion::TBRegion()
-	: m_rects(nullptr)
-	, m_num_rects(0)
-	, m_capacity(0)
+    : m_rects(nullptr)
+    , m_num_rects(0)
+    , m_capacity(0)
 {
 }
 
 TBRegion::~TBRegion()
 {
-	RemoveAll(true);
+    RemoveAll(true);
 }
 
 void TBRegion::RemoveRect(int index)
 {
-	assert(index >= 0 && index < m_num_rects);
-	for (int i = index; i < m_num_rects - 1; i++)
-		m_rects[i] = m_rects[i + 1];
-	m_num_rects--;
+    assert(index >= 0 && index < m_num_rects);
+    for (int i = index; i < m_num_rects - 1; i++)
+        m_rects[i] = m_rects[i + 1];
+    m_num_rects--;
 }
 
 void TBRegion::RemoveRectFast(int index)
 {
-	assert(index >= 0 && index < m_num_rects);
-	m_rects[index] = m_rects[--m_num_rects];
+    assert(index >= 0 && index < m_num_rects);
+    m_rects[index] = m_rects[--m_num_rects];
 }
 
 void TBRegion::RemoveAll(bool free_memory)
 {
-	m_num_rects = 0;
-	if (free_memory)
-	{
-		delete [] m_rects;
-		m_rects = nullptr;
-		m_capacity = 0;
-	}
+    m_num_rects = 0;
+    if (free_memory)
+    {
+        delete [] m_rects;
+        m_rects = nullptr;
+        m_capacity = 0;
+    }
 }
 
 bool TBRegion::Set(const TBRect &rect)
 {
-	RemoveAll();
-	return AddRect(rect, false);
+    RemoveAll();
+    return AddRect(rect, false);
 }
 
 bool TBRegion::GrowIfNeeded()
 {
-	if (m_num_rects == m_capacity)
-	{
-		int new_m_capacity = CLAMP(4, m_capacity * 2, 1024);
-		TBRect *new_rects = new TBRect[new_m_capacity];
-		if (!new_rects)
-			return false;
-		if (m_rects)
-			memmove(new_rects, m_rects, sizeof(TBRect) * m_capacity);
-		delete [] m_rects;
-		m_rects = new_rects;
-		m_capacity = new_m_capacity;
-	}
-	return true;
+    if (m_num_rects == m_capacity)
+    {
+        int new_m_capacity = CLAMP(4, m_capacity * 2, 1024);
+        TBRect *new_rects = new TBRect[new_m_capacity];
+        if (!new_rects)
+            return false;
+        if (m_rects)
+            memmove(new_rects, m_rects, sizeof(TBRect) * m_capacity);
+        delete [] m_rects;
+        m_rects = new_rects;
+        m_capacity = new_m_capacity;
+    }
+    return true;
 }
 
 bool TBRegion::AddRect(const TBRect &rect, bool coalesce)
 {
-	if (coalesce)
-	{
-		// If the rect can coalesce with any existing rect,
-		// just replace it with the union of both, doing coalesce
-		// check again recursively.
-		// Searching backwards is most likely to give a hit quicker
-		// in many usage scenarios.
-		for (int i = m_num_rects - 1; i >= 0; i--)
-		{
-			if ( // Can coalesce vertically
-				(rect.x == m_rects[i].x && rect.w == m_rects[i].w &&
-				(rect.y == m_rects[i].y + m_rects[i].h || rect.y + rect.h == m_rects[i].y))
-				|| // Can coalesce horizontally
-				(rect.y == m_rects[i].y && rect.h == m_rects[i].h &&
-				(rect.x == m_rects[i].x + m_rects[i].w || rect.x + rect.w == m_rects[i].x))
-				)
-			{
-				TBRect union_rect = m_rects[i].Union(rect);
-				RemoveRectFast(i);
-				return AddRect(union_rect, true);
-			}
-		}
-	}
-
-	if (!GrowIfNeeded())
-		return false;
-	m_rects[m_num_rects++] = rect;
-	return true;
+    if (coalesce)
+    {
+        // If the rect can coalesce with any existing rect,
+        // just replace it with the union of both, doing coalesce
+        // check again recursively.
+        // Searching backwards is most likely to give a hit quicker
+        // in many usage scenarios.
+        for (int i = m_num_rects - 1; i >= 0; i--)
+        {
+            if ( // Can coalesce vertically
+                 (rect.x == m_rects[i].x && rect.w == m_rects[i].w &&
+                  (rect.y == m_rects[i].y + m_rects[i].h || rect.y + rect.h == m_rects[i].y))
+                 || // Can coalesce horizontally
+                 (rect.y == m_rects[i].y && rect.h == m_rects[i].h &&
+                  (rect.x == m_rects[i].x + m_rects[i].w || rect.x + rect.w == m_rects[i].x))
+                 )
+            {
+                TBRect union_rect = m_rects[i].Union(rect);
+                RemoveRectFast(i);
+                return AddRect(union_rect, true);
+            }
+        }
+    }
+
+    if (!GrowIfNeeded())
+        return false;
+    m_rects[m_num_rects++] = rect;
+    return true;
 }
 
 bool TBRegion::IncludeRect(const TBRect &include_rect)
 {
-	for (int i = 0; i < m_num_rects; i++)
-	{
-		if (include_rect.Intersects(m_rects[i]))
-		{
-			// Make a region containing the non intersecting parts and then include
-			// those recursively (they might still intersect some other part of the region).
-			TBRegion inclusion_region;
-			if (!inclusion_region.AddExcludingRects(include_rect, m_rects[i], false))
-				return false;
-			for (int j = 0; j < inclusion_region.m_num_rects; j++)
-			{
-				if (!IncludeRect(inclusion_region.m_rects[j]))
-					return false;
-			}
-			return true;
-		}
-	}
-	// Now we know that the rect can be added without overlap.
-	// Add it with coalesce checking to keep the number of rects down.
-	return AddRect(include_rect, true);
+    for (int i = 0; i < m_num_rects; i++)
+    {
+        if (include_rect.Intersects(m_rects[i]))
+        {
+            // Make a region containing the non intersecting parts and then include
+            // those recursively (they might still intersect some other part of the region).
+            TBRegion inclusion_region;
+            if (!inclusion_region.AddExcludingRects(include_rect, m_rects[i], false))
+                return false;
+            for (int j = 0; j < inclusion_region.m_num_rects; j++)
+            {
+                if (!IncludeRect(inclusion_region.m_rects[j]))
+                    return false;
+            }
+            return true;
+        }
+    }
+    // Now we know that the rect can be added without overlap.
+    // Add it with coalesce checking to keep the number of rects down.
+    return AddRect(include_rect, true);
 }
 
 bool TBRegion::ExcludeRect(const TBRect &exclude_rect)
 {
-	int num_rects_to_check = m_num_rects;
-	for (int i = 0; i < num_rects_to_check; i++)
-	{
-		if (m_rects[i].Intersects(exclude_rect))
-		{
-			// Remove the existing rectangle we found we intersect
-			// and add the pieces we don't intersect. New rects
-			// will be added at the end of the list, so we can decrease
-			// num_rects_to_check.
-			TBRect rect = m_rects[i];
-			RemoveRect(i);
-			num_rects_to_check--;
-			i--;
-
-			if (!AddExcludingRects(rect, exclude_rect, true))
-				return false;
-		}
-	}
-	return true;
+    int num_rects_to_check = m_num_rects;
+    for (int i = 0; i < num_rects_to_check; i++)
+    {
+        if (m_rects[i].Intersects(exclude_rect))
+        {
+            // Remove the existing rectangle we found we intersect
+            // and add the pieces we don't intersect. New rects
+            // will be added at the end of the list, so we can decrease
+            // num_rects_to_check.
+            TBRect rect = m_rects[i];
+            RemoveRect(i);
+            num_rects_to_check--;
+            i--;
+
+            if (!AddExcludingRects(rect, exclude_rect, true))
+                return false;
+        }
+    }
+    return true;
 }
 
 bool TBRegion::AddExcludingRects(const TBRect &rect, const TBRect &exclude_rect, bool coalesce)
 {
-	assert(rect.Intersects(exclude_rect));
-	TBRect remove = exclude_rect.Clip(rect);
+    assert(rect.Intersects(exclude_rect));
+    TBRect remove = exclude_rect.Clip(rect);
 
-	if (remove.y > rect.y)
-		if (!AddRect(TBRect(rect.x, rect.y, rect.w, remove.y - rect.y), coalesce))
-			return false;
-	if (remove.x > rect.x)
-		if (!AddRect(TBRect(rect.x, remove.y, remove.x - rect.x, remove.h), coalesce))
-			return false;
-	if (remove.x + remove.w < rect.x + rect.w)
-		if (!AddRect(TBRect(remove.x + remove.w, remove.y, rect.x + rect.w - (remove.x + remove.w), remove.h), coalesce))
-			return false;
-	if (remove.y + remove.h < rect.y + rect.h)
-		if (!AddRect(TBRect(rect.x, remove.y + remove.h, rect.w, rect.y + rect.h - (remove.y + remove.h)), coalesce))
-			return false;
-	return true;
+    if (remove.y > rect.y)
+        if (!AddRect(TBRect(rect.x, rect.y, rect.w, remove.y - rect.y), coalesce))
+            return false;
+    if (remove.x > rect.x)
+        if (!AddRect(TBRect(rect.x, remove.y, remove.x - rect.x, remove.h), coalesce))
+            return false;
+    if (remove.x + remove.w < rect.x + rect.w)
+        if (!AddRect(TBRect(remove.x + remove.w, remove.y, rect.x + rect.w - (remove.x + remove.w), remove.h), coalesce))
+            return false;
+    if (remove.y + remove.h < rect.y + rect.h)
+        if (!AddRect(TBRect(rect.x, remove.y + remove.h, rect.w, rect.y + rect.h - (remove.y + remove.h)), coalesce))
+            return false;
+    return true;
 }
 
 const TBRect &TBRegion::GetRect(int index) const
 {
-	assert(index >= 0 && index < m_num_rects);
-	return m_rects[index];
+    assert(index >= 0 && index < m_num_rects);
+    return m_rects[index];
 }
 
 }; // namespace tb

+ 64 - 64
Source/ThirdParty/TurboBadger/tb_geometry.h

@@ -15,9 +15,9 @@ namespace tb {
 class TBPoint
 {
 public:
-	int x, y;
-	TBPoint() : x(0), y(0) {}
-	TBPoint(int x, int y) : x(x), y(y) {}
+    int x, y;
+    TBPoint() : x(0), y(0) {}
+    TBPoint(int x, int y) : x(x), y(y) {}
 };
 
 /** Simple rectangle class. */
@@ -25,34 +25,34 @@ public:
 class TBRect
 {
 public:
-	int x, y, w, h;
-	TBRect() : x(0), y(0), w(0), h(0) {}
-	TBRect(int x, int y, int w, int h) : x(x), y(y), w(w), h(h) {}
-
-	inline bool IsEmpty() const						{ return w <= 0 || h <= 0; }
-	inline bool IsInsideOut() const					{ return w < 0 || h < 0; }
-	inline bool Equals(const TBRect &rect) const	{ return rect.x == x && rect.y == y && rect.w == w && rect.h == h; }
-	bool Intersects(const TBRect &rect) const;
-	bool Contains(const TBPoint &p) const			{ return p.x >= x && p.y >= y && p.x < x + w && p.y < y + h; }
-
-	inline void Reset()								{ x = y = w = h = 0; }
-	inline void Set(int x, int y, int w, int h)		{ this->x = x; this->y = y; this->w = w; this->h = h; }
-
-	inline TBRect Shrink(int left, int top, int right, int bottom) const	{ return TBRect(x + left, y + top, w - left - right, h - top - bottom); }
-	inline TBRect Expand(int left, int top, int right, int bottom) const	{ return Shrink(-left, -top, -right, -bottom); }
-	inline TBRect Shrink(int tx, int ty) const		{ return TBRect(x + tx, y + ty, w - tx * 2, h - ty * 2); }
-	inline TBRect Expand(int tx, int ty) const		{ return Shrink(-tx, -ty); }
-	inline TBRect Offset(int dx, int dy) const		{ return TBRect(x + dx, y + dy, w, h); }
-
-	/** Return a rect moved inside bounding_rect. If the rect doesn't fit inside
-		bounding_rect, it will be placed so the x and/or y matches bounding_rect. */
-	TBRect MoveIn(const TBRect &bounding_rect) const;
-
-	/** Return a rect centered in bounding_rect. */
-	TBRect CenterIn(const TBRect &bounding_rect) const;
-
-	TBRect Union(const TBRect &rect) const;
-	TBRect Clip(const TBRect &clip_rect) const;
+    int x, y, w, h;
+    TBRect() : x(0), y(0), w(0), h(0) {}
+    TBRect(int x, int y, int w, int h) : x(x), y(y), w(w), h(h) {}
+
+    inline bool IsEmpty() const						{ return w <= 0 || h <= 0; }
+    inline bool IsInsideOut() const					{ return w < 0 || h < 0; }
+    inline bool Equals(const TBRect &rect) const	{ return rect.x == x && rect.y == y && rect.w == w && rect.h == h; }
+    bool Intersects(const TBRect &rect) const;
+    bool Contains(const TBPoint &p) const			{ return p.x >= x && p.y >= y && p.x < x + w && p.y < y + h; }
+
+    inline void Reset()								{ x = y = w = h = 0; }
+    inline void Set(int x, int y, int w, int h)		{ this->x = x; this->y = y; this->w = w; this->h = h; }
+
+    inline TBRect Shrink(int left, int top, int right, int bottom) const	{ return TBRect(x + left, y + top, w - left - right, h - top - bottom); }
+    inline TBRect Expand(int left, int top, int right, int bottom) const	{ return Shrink(-left, -top, -right, -bottom); }
+    inline TBRect Shrink(int tx, int ty) const		{ return TBRect(x + tx, y + ty, w - tx * 2, h - ty * 2); }
+    inline TBRect Expand(int tx, int ty) const		{ return Shrink(-tx, -ty); }
+    inline TBRect Offset(int dx, int dy) const		{ return TBRect(x + dx, y + dy, w, h); }
+
+    /** Return a rect moved inside bounding_rect. If the rect doesn't fit inside
+        bounding_rect, it will be placed so the x and/or y matches bounding_rect. */
+    TBRect MoveIn(const TBRect &bounding_rect) const;
+
+    /** Return a rect centered in bounding_rect. */
+    TBRect CenterIn(const TBRect &bounding_rect) const;
+
+    TBRect Union(const TBRect &rect) const;
+    TBRect Clip(const TBRect &clip_rect) const;
 };
 
 /** TBRegion does calculations on regions represented by a list of rectangles. */
@@ -60,49 +60,49 @@ public:
 class TBRegion
 {
 public:
-	TBRegion();
-	~TBRegion();
+    TBRegion();
+    ~TBRegion();
 
-	/** Remove the rect at the given index. */
-	void RemoveRect(int index);
+    /** Remove the rect at the given index. */
+    void RemoveRect(int index);
 
-	/** Remove the rect at the given index.
-		This method will change the order of rectangles after index. */
-	void RemoveRectFast(int index);
+    /** Remove the rect at the given index.
+        This method will change the order of rectangles after index. */
+    void RemoveRectFast(int index);
 
-	/** Remove all rectangles so the region becomes empty.
-		If free_memory is false, the internal buffers will be reused
-		if more rectangles are added again under its life time. */
-	void RemoveAll(bool free_memory = true);
+    /** Remove all rectangles so the region becomes empty.
+        If free_memory is false, the internal buffers will be reused
+        if more rectangles are added again under its life time. */
+    void RemoveAll(bool free_memory = true);
 
-	/** Set the region to the given rect. */
-	bool Set(const TBRect &rect);
+    /** Set the region to the given rect. */
+    bool Set(const TBRect &rect);
 
-	/** Add the rect without doing any overlap check.
-		If coalesce is true, it will coalesce the rectangle
-		with existing rectangles if possible (until there's
-		nothing more to coalesce it with). */
-	bool AddRect(const TBRect &rect, bool coalesce);
+    /** Add the rect without doing any overlap check.
+        If coalesce is true, it will coalesce the rectangle
+        with existing rectangles if possible (until there's
+        nothing more to coalesce it with). */
+    bool AddRect(const TBRect &rect, bool coalesce);
 
-	/** Include the rect in the region.
-		This will add only the parts that's not already in the region so the result doesn't
-		contain overlap parts. This assumes there's no overlap in the region already! */
-	bool IncludeRect(const TBRect &include_rect);
+    /** Include the rect in the region.
+        This will add only the parts that's not already in the region so the result doesn't
+        contain overlap parts. This assumes there's no overlap in the region already! */
+    bool IncludeRect(const TBRect &include_rect);
 
-	/** Exclude the rect from the region. */
-	bool ExcludeRect(const TBRect &exclude_rect);
+    /** Exclude the rect from the region. */
+    bool ExcludeRect(const TBRect &exclude_rect);
 
-	/** Add the rectangles that's left of rect after excluding exclude_rect. */
-	bool AddExcludingRects(const TBRect &rect, const TBRect &exclude_rect, bool coalesce);
+    /** Add the rectangles that's left of rect after excluding exclude_rect. */
+    bool AddExcludingRects(const TBRect &rect, const TBRect &exclude_rect, bool coalesce);
 
-	bool IsEmpty() const							{ return m_num_rects == 0; }
-	int GetNumRects() const							{ return m_num_rects; }
-	const TBRect &GetRect(int index) const;
+    bool IsEmpty() const							{ return m_num_rects == 0; }
+    int GetNumRects() const							{ return m_num_rects; }
+    const TBRect &GetRect(int index) const;
 private:
-	TBRect *m_rects;
-	int m_num_rects;
-	int m_capacity;
-	bool GrowIfNeeded();
+    TBRect *m_rects;
+    int m_num_rects;
+    int m_capacity;
+    bool GrowIfNeeded();
 };
 
 }; // namespace tb

+ 11 - 11
Source/ThirdParty/TurboBadger/tb_hash.cpp

@@ -11,17 +11,17 @@ namespace tb {
 
 uint32 TBGetHash(const char *str)
 {
-	if (!str || !*str)
-		return 0;
-	// FNV hash
-	uint32 hash = 2166136261U;
-	int i = 0;
-	while (str[i])
-	{
-		char c = str[i++];
-		hash = (16777619U * hash) ^ c;
-	}
-	return hash;
+    if (!str || !*str)
+        return 0;
+    // FNV hash
+    uint32 hash = 2166136261U;
+    int i = 0;
+    while (str[i])
+    {
+        char c = str[i++];
+        hash = (16777619U * hash) ^ c;
+    }
+    return hash;
 }
 
 #endif // !TB_SUPPORT_CONSTEXPR

+ 3 - 3
Source/ThirdParty/TurboBadger/tb_hash.h

@@ -32,14 +32,14 @@ static constexpr uint32 prime = 16777619U;
 // compile-time hash helper function
 constexpr uint32 TBGetHash_one(char c, const char* remain, uint32 value)
 {
-	return c == 0 ? value : TBGetHash_one(remain[0], remain + 1, (value ^ c) * prime);
+    return c == 0 ? value : TBGetHash_one(remain[0], remain + 1, (value ^ c) * prime);
 }
 
 // compile-time hash
 constexpr uint32 TBGetHash(const char* str)
 {
-	return (str && *str) ? TBGetHash_one(str[0], str + 1, basis) : 0;
-}
+    return (str && *str) ? TBGetHash_one(str[0], str + 1, basis) : 0;
+    }
 
 #define TBIDC(str) TBGetHash(str)
 

+ 141 - 141
Source/ThirdParty/TurboBadger/tb_hashtable.cpp

@@ -16,170 +16,170 @@ namespace tb {
 // == TBHashTable =======================================================================
 
 TBHashTable::TBHashTable()
-	: m_buckets(0)
-	, m_num_buckets(0)
-	, m_num_items(0)
+    : m_buckets(0)
+    , m_num_buckets(0)
+    , m_num_items(0)
 {
 }
 
 TBHashTable::~TBHashTable()
 {
-	RemoveAll();
+    RemoveAll();
 }
 
 void TBHashTable::RemoveAll(bool delete_content)
 {
 #ifdef TB_RUNTIME_DEBUG_INFO
-	//Debug();
+    //Debug();
 #endif
-	for (uint32 i = 0; i < m_num_buckets; i++)
-	{
-		ITEM *item = m_buckets[i];
-		while (item)
-		{
-			ITEM *item_next = item->next;
-			if (delete_content)
-				DeleteContent(item->content);
-			delete item;
-			item = item_next;
-		}
-	}
-	delete [] m_buckets;
-	m_buckets = nullptr;
-	m_num_buckets = m_num_items = 0;
+    for (uint32 i = 0; i < m_num_buckets; i++)
+    {
+        ITEM *item = m_buckets[i];
+        while (item)
+        {
+            ITEM *item_next = item->next;
+            if (delete_content)
+                DeleteContent(item->content);
+            delete item;
+            item = item_next;
+        }
+    }
+    delete [] m_buckets;
+    m_buckets = nullptr;
+    m_num_buckets = m_num_items = 0;
 }
 
 bool TBHashTable::Rehash(uint32 new_num_buckets)
 {
-	if (new_num_buckets == m_num_buckets)
-		return true;
-	if (ITEM **new_buckets = new ITEM*[new_num_buckets])
-	{
-		memset(new_buckets, 0, sizeof(ITEM*) * new_num_buckets);
-		// Rehash all items into the new buckets
-		for (uint32 i = 0; i < m_num_buckets; i++)
-		{
-			ITEM *item = m_buckets[i];
-			while (item)
-			{
-				ITEM *item_next = item->next;
-				// Add it to new_buckets
-				uint32 bucket = item->key & (new_num_buckets - 1);
-				item->next = new_buckets[bucket];
-				new_buckets[bucket] = item;
-				item = item_next;
-			}
-		}
-		// Delete old buckets and update
-		delete [] m_buckets;
-		m_buckets = new_buckets;
-		m_num_buckets = new_num_buckets;
-		return true;
-	}
-	return false;
+    if (new_num_buckets == m_num_buckets)
+        return true;
+    if (ITEM **new_buckets = new ITEM*[new_num_buckets])
+    {
+        memset(new_buckets, 0, sizeof(ITEM*) * new_num_buckets);
+        // Rehash all items into the new buckets
+        for (uint32 i = 0; i < m_num_buckets; i++)
+        {
+            ITEM *item = m_buckets[i];
+            while (item)
+            {
+                ITEM *item_next = item->next;
+                // Add it to new_buckets
+                uint32 bucket = item->key & (new_num_buckets - 1);
+                item->next = new_buckets[bucket];
+                new_buckets[bucket] = item;
+                item = item_next;
+            }
+        }
+        // Delete old buckets and update
+        delete [] m_buckets;
+        m_buckets = new_buckets;
+        m_num_buckets = new_num_buckets;
+        return true;
+    }
+    return false;
 }
 
 bool TBHashTable::NeedRehash() const
 {
-	// Grow if more items than buckets
-	return !m_num_buckets || m_num_items >= m_num_buckets;
+    // Grow if more items than buckets
+    return !m_num_buckets || m_num_items >= m_num_buckets;
 }
 
 uint32 TBHashTable::GetSuitableBucketsCount() const
 {
-	// As long as we use FNV for TBID (in TBGetHash), power of two hash sizes are the best.
-	if (!m_num_items)
-		return 16;
-	return m_num_items * 2;
+    // As long as we use FNV for TBID (in TBGetHash), power of two hash sizes are the best.
+    if (!m_num_items)
+        return 16;
+    return m_num_items * 2;
 }
 
 void *TBHashTable::Get(uint32 key) const
 {
-	if (!m_num_buckets)
-		return nullptr;
-	uint32 bucket = key & (m_num_buckets - 1);
-	ITEM *item = m_buckets[bucket];
-	while (item)
-	{
-		if (item->key == key)
-			return item->content;
-		item = item->next;
-	}
-	return nullptr;
+    if (!m_num_buckets)
+        return nullptr;
+    uint32 bucket = key & (m_num_buckets - 1);
+    ITEM *item = m_buckets[bucket];
+    while (item)
+    {
+        if (item->key == key)
+            return item->content;
+        item = item->next;
+    }
+    return nullptr;
 }
 
 bool TBHashTable::Add(uint32 key, void *content)
 {
-	if (NeedRehash() && !Rehash(GetSuitableBucketsCount()))
-		return false;
-	assert(!Get(key));
-	if (ITEM *item = new ITEM)
-	{
-		uint32 bucket = key & (m_num_buckets - 1);
-		item->key = key;
-		item->content = content;
-		item->next = m_buckets[bucket];
-		m_buckets[bucket] = item;
-		m_num_items++;
-		return true;
-	}
-	return false;
+    if (NeedRehash() && !Rehash(GetSuitableBucketsCount()))
+        return false;
+    assert(!Get(key));
+    if (ITEM *item = new ITEM)
+    {
+        uint32 bucket = key & (m_num_buckets - 1);
+        item->key = key;
+        item->content = content;
+        item->next = m_buckets[bucket];
+        m_buckets[bucket] = item;
+        m_num_items++;
+        return true;
+    }
+    return false;
 }
 
 void *TBHashTable::Remove(uint32 key)
 {
-	if (!m_num_buckets)
-		return nullptr;
-	uint32 bucket = key & (m_num_buckets - 1);
-	ITEM *item = m_buckets[bucket];
-	ITEM *prev_item = nullptr;
-	while (item)
-	{
-		if (item->key == key)
-		{
-			if (prev_item)
-				prev_item->next = item->next;
-			else
-				m_buckets[bucket] = item->next;
-			void *content = item->content;
-			delete item;
-			return content;
-		}
-		prev_item = item;
-		item = item->next;
-	}
-	assert(!"This hash table didn't contain the given key!");
-	return nullptr;
+    if (!m_num_buckets)
+        return nullptr;
+    uint32 bucket = key & (m_num_buckets - 1);
+    ITEM *item = m_buckets[bucket];
+    ITEM *prev_item = nullptr;
+    while (item)
+    {
+        if (item->key == key)
+        {
+            if (prev_item)
+                prev_item->next = item->next;
+            else
+                m_buckets[bucket] = item->next;
+            void *content = item->content;
+            delete item;
+            return content;
+        }
+        prev_item = item;
+        item = item->next;
+    }
+    assert(!"This hash table didn't contain the given key!");
+    return nullptr;
 }
 
 void TBHashTable::Delete(uint32 key)
 {
-	DeleteContent(Remove(key));
+    DeleteContent(Remove(key));
 }
 
 #ifdef TB_RUNTIME_DEBUG_INFO
 
 void TBHashTable::Debug()
 {
-	TBTempBuffer line;
-	line.AppendString("Hash table: ");
-	int total_count = 0;
-	for (uint32 i = 0; i < m_num_buckets; i++)
-	{
-		int count = 0;
-		ITEM *item = m_buckets[i];
-		while (item)
-		{
-			count++;
-			item = item->next;
-		}
-		TBStr tmp; tmp.SetFormatted("%d ", count);
-		line.AppendString(tmp);
-		total_count += count;
-	}
-	TBStr tmp; tmp.SetFormatted(" (total: %d of %d buckets)\n", total_count, m_num_buckets);
-	line.AppendString(tmp);
-	TBDebugOut(line.GetData());
+    TBTempBuffer line;
+    line.AppendString("Hash table: ");
+    int total_count = 0;
+    for (uint32 i = 0; i < m_num_buckets; i++)
+    {
+        int count = 0;
+        ITEM *item = m_buckets[i];
+        while (item)
+        {
+            count++;
+            item = item->next;
+        }
+        TBStr tmp; tmp.SetFormatted("%d ", count);
+        line.AppendString(tmp);
+        total_count += count;
+    }
+    TBStr tmp; tmp.SetFormatted(" (total: %d of %d buckets)\n", total_count, m_num_buckets);
+    line.AppendString(tmp);
+    TBDebugOut(line.GetData());
 }
 
 #endif // TB_RUNTIME_DEBUG_INFO
@@ -187,33 +187,33 @@ void TBHashTable::Debug()
 // == TBHashTableIterator ===============================================================
 
 TBHashTableIterator::TBHashTableIterator(TBHashTable *hash_table)
-	: m_hash_table(hash_table)
-	, m_current_bucket(0)
-	, m_current_item(nullptr)
+    : m_hash_table(hash_table)
+    , m_current_bucket(0)
+    , m_current_item(nullptr)
 {
 }
 
 void *TBHashTableIterator::GetNextContent()
 {
-	if (m_current_bucket == m_hash_table->m_num_buckets)
-		return nullptr;
-	if (m_current_item && m_current_item->next)
-		m_current_item = m_current_item->next;
-	else
-	{
-		if (m_current_item)
-			m_current_bucket++;
-		if (m_current_bucket == m_hash_table->m_num_buckets)
-			return nullptr;
-		while (m_current_bucket < m_hash_table->m_num_buckets)
-		{
-			m_current_item = m_hash_table->m_buckets[m_current_bucket];
-			if (m_current_item)
-				break;
-			m_current_bucket++;
-		}
-	}
-	return m_current_item ? m_current_item->content : nullptr;
+    if (m_current_bucket == m_hash_table->m_num_buckets)
+        return nullptr;
+    if (m_current_item && m_current_item->next)
+        m_current_item = m_current_item->next;
+    else
+    {
+        if (m_current_item)
+            m_current_bucket++;
+        if (m_current_bucket == m_hash_table->m_num_buckets)
+            return nullptr;
+        while (m_current_bucket < m_hash_table->m_num_buckets)
+        {
+            m_current_item = m_hash_table->m_buckets[m_current_bucket];
+            if (m_current_item)
+                break;
+            m_current_bucket++;
+        }
+    }
+    return m_current_item ? m_current_item->content : nullptr;
 }
 
 }; // namespace tb

+ 53 - 53
Source/ThirdParty/TurboBadger/tb_hashtable.h

@@ -16,60 +16,60 @@ namespace tb {
 class TBHashTable
 {
 public:
-	TBHashTable();
-	virtual ~TBHashTable();
+    TBHashTable();
+    virtual ~TBHashTable();
 
-	/** Remove all items without deleting the content. */
-	void RemoveAll() { RemoveAll(false); }
+    /** Remove all items without deleting the content. */
+    void RemoveAll() { RemoveAll(false); }
 
-	/** Remove all items and delete the content.
-		This requires TBHashTable to be subclassed and implementing DeleteContent.
-		You would typically do this by using TBHashTableOf or TBHashTableAutoDeleteOf. */
-	void DeleteAll() { RemoveAll(true); }
+    /** Remove all items and delete the content.
+        This requires TBHashTable to be subclassed and implementing DeleteContent.
+        You would typically do this by using TBHashTableOf or TBHashTableAutoDeleteOf. */
+    void DeleteAll() { RemoveAll(true); }
 
-	/** Get the content for the given key, or nullptr if not found. */
-	void *Get(uint32 key) const;
+    /** Get the content for the given key, or nullptr if not found. */
+    void *Get(uint32 key) const;
 
-	/** Add content with the given key.
-		Returns false if out of memory. */
-	bool Add(uint32 key, void *content);
+    /** Add content with the given key.
+        Returns false if out of memory. */
+    bool Add(uint32 key, void *content);
 
-	/** Remove the content with the given key. */
-	void *Remove(uint32 key);
+    /** Remove the content with the given key. */
+    void *Remove(uint32 key);
 
-	/** Delete the content with the given key. */
-	void Delete(uint32 key);
+    /** Delete the content with the given key. */
+    void Delete(uint32 key);
 
-	/** Rehash the table so use the given number of buckets.
-		Returns false if out of memory. */
-	bool Rehash(uint32 num_buckets);
+    /** Rehash the table so use the given number of buckets.
+        Returns false if out of memory. */
+    bool Rehash(uint32 num_buckets);
 
-	/** Return true if the hashtable itself think it's time to rehash. */
-	bool NeedRehash() const;
+    /** Return true if the hashtable itself think it's time to rehash. */
+    bool NeedRehash() const;
 
-	/** Get the number of buckets the hashtable itself thinks is suitable for
-		the current number of items. */
-	uint32 GetSuitableBucketsCount() const;
+    /** Get the number of buckets the hashtable itself thinks is suitable for
+        the current number of items. */
+    uint32 GetSuitableBucketsCount() const;
 
 #ifdef TB_RUNTIME_DEBUG_INFO
-	/** Print out some debug info about the hash table. */
-	void Debug();
+    /** Print out some debug info about the hash table. */
+    void Debug();
 #endif
 
 protected:
-	/** Delete the content of a item. This is called if calling DeleteAll, and must be
-		implemented in a subclass that knows about the content type. */
-	virtual void DeleteContent(void *content) { assert(!"You need to subclass and implement!"); }
+    /** Delete the content of a item. This is called if calling DeleteAll, and must be
+        implemented in a subclass that knows about the content type. */
+    virtual void DeleteContent(void *content) { assert(!"You need to subclass and implement!"); }
 private:
-	friend class TBHashTableIterator;
-	void RemoveAll(bool delete_content);
-	struct ITEM {
-		uint32 key;
-		ITEM *next;
-		void *content;
-	} **m_buckets;
-	uint32 m_num_buckets;
-	uint32 m_num_items;
+    friend class TBHashTableIterator;
+    void RemoveAll(bool delete_content);
+    struct ITEM {
+        uint32 key;
+        ITEM *next;
+        void *content;
+    } **m_buckets;
+    uint32 m_num_buckets;
+    uint32 m_num_items;
 };
 
 /** TBHashTableIterator is a iterator for stepping through all content stored in a TBHashTable. */
@@ -77,12 +77,12 @@ private:
 class TBHashTableIterator
 {
 public:
-	TBHashTableIterator(TBHashTable *hash_table);
-	void *GetNextContent();
+    TBHashTableIterator(TBHashTable *hash_table);
+    void *GetNextContent();
 private:
-	TBHashTable *m_hash_table;
-	uint32 m_current_bucket;
-	TBHashTable::ITEM *m_current_item;
+    TBHashTable *m_hash_table;
+    uint32 m_current_bucket;
+    TBHashTable::ITEM *m_current_item;
 };
 
 /** TBHashTableIteratorOf is a TBHashTableIterator which auto cast to the class type. */
@@ -90,34 +90,34 @@ template<class T>
 class TBHashTableIteratorOf : private TBHashTableIterator
 {
 public:
-	TBHashTableIteratorOf(TBHashTable *hash_table) : TBHashTableIterator(hash_table) {}
-	T *GetNextContent() { return (T*) TBHashTableIterator::GetNextContent(); }
+    TBHashTableIteratorOf(TBHashTable *hash_table) : TBHashTableIterator(hash_table) {}
+    T *GetNextContent() { return (T*) TBHashTableIterator::GetNextContent(); }
 };
 
 /** TBHashTableOf is a TBHashTable with the given class type as content. */
 template<class T>
 class TBHashTableOf : public TBHashTable
 {
-// FIX: Don't do public inheritance! Either inherit privately and forward, or use a private member backend!
+    // FIX: Don't do public inheritance! Either inherit privately and forward, or use a private member backend!
 public:
-	T *Get(uint32 key) const { return (T*) TBHashTable::Get(key); }
+    T *Get(uint32 key) const { return (T*) TBHashTable::Get(key); }
 
 protected:
-	virtual void DeleteContent(void *content) { delete (T*) content; }
+    virtual void DeleteContent(void *content) { delete (T*) content; }
 };
 
 /** TBHashTableOf is a TBHashTable with the given class type as content.
-	It will delete all content automaticallt on destruction. */
+    It will delete all content automaticallt on destruction. */
 template<class T>
 class TBHashTableAutoDeleteOf : public TBHashTable
 {
 public:
-	~TBHashTableAutoDeleteOf() { DeleteAll(); }
+    ~TBHashTableAutoDeleteOf() { DeleteAll(); }
 
-	T *Get(uint32 key) const { return (T*) TBHashTable::Get(key); }
+    T *Get(uint32 key) const { return (T*) TBHashTable::Get(key); }
 
 protected:
-	virtual void DeleteContent(void *content) { delete (T*) content; }
+    virtual void DeleteContent(void *content) { delete (T*) content; }
 };
 
 }; // namespace tb

+ 43 - 43
Source/ThirdParty/TurboBadger/tb_id.cpp

@@ -21,59 +21,59 @@ static bool is_adding = false;
 
 void TBID::Set(uint32 newid)
 {
-	id = newid;
-	debug_string.Clear();
-	if (!is_adding && tb_core_is_initialized())
-	{
-		if (!all_id_hash.Get(id))
-		{
-			is_adding = true;
-			all_id_hash.Add(id, new TBID(*this));
-			is_adding = false;
-		}
-	}
+    id = newid;
+    debug_string.Clear();
+    if (!is_adding && tb_core_is_initialized())
+    {
+        if (!all_id_hash.Get(id))
+        {
+            is_adding = true;
+            all_id_hash.Add(id, new TBID(*this));
+            is_adding = false;
+        }
+    }
 }
 
 void TBID::Set(const TBID &newid)
 {
-	id = newid;
-	TB_IF_DEBUG(debug_string.Set(newid.debug_string));
-	if (!is_adding && tb_core_is_initialized())
-	{
-		if (TBID *other_id = all_id_hash.Get(id))
-		{
-			// If this happens, 2 different strings result in the same hash.
-			// It might be a good idea to change one of them, but it might not matter.
-			assert(other_id->debug_string.Equals(debug_string));
-		}
-		else
-		{
-			is_adding = true;
-			all_id_hash.Add(id, new TBID(*this));
-			is_adding = false;
-		}
-	}
+    id = newid;
+    TB_IF_DEBUG(debug_string.Set(newid.debug_string));
+    if (!is_adding && tb_core_is_initialized())
+    {
+        if (TBID *other_id = all_id_hash.Get(id))
+        {
+            // If this happens, 2 different strings result in the same hash.
+            // It might be a good idea to change one of them, but it might not matter.
+            assert(other_id->debug_string.Equals(debug_string));
+        }
+        else
+        {
+            is_adding = true;
+            all_id_hash.Add(id, new TBID(*this));
+            is_adding = false;
+        }
+    }
 }
 
 void TBID::Set(const char *string)
 {
-	id = TBGetHash(string);
-	TB_IF_DEBUG(debug_string.Set(string));
-	if (!is_adding && tb_core_is_initialized())
-	{
-		if (TBID *other_id = all_id_hash.Get(id))
-		{
-			assert(other_id->debug_string.Equals(debug_string));
-		}
-		else
-		{
-			is_adding = true;
-			all_id_hash.Add(id, new TBID(*this));
+    id = TBGetHash(string);
+    TB_IF_DEBUG(debug_string.Set(string));
+    if (!is_adding && tb_core_is_initialized())
+    {
+        if (TBID *other_id = all_id_hash.Get(id))
+        {
+            assert(other_id->debug_string.Equals(debug_string));
+        }
+        else
+        {
+            is_adding = true;
+            all_id_hash.Add(id, new TBID(*this));
             if (tbidRegisterCallback)
                 tbidRegisterCallback(id, string);
-			is_adding = false;
-		}
-	}
+            is_adding = false;
+        }
+    }
 }
 
 #endif // TB_RUNTIME_DEBUG_INFO

+ 17 - 17
Source/ThirdParty/TurboBadger/tb_id.h

@@ -15,35 +15,35 @@ namespace tb {
 typedef void (*TBIDRegisterStringCallback) (uint32 id, const char* string);
 
 /** TBID is a wrapper for a uint32 to be used as ID.
-	The uint32 can be set directly to any uint32, or it can be
-	set from a string which will be hashed into the uint32. */
+    The uint32 can be set directly to any uint32, or it can be
+    set from a string which will be hashed into the uint32. */
 class TBID
 {
 public:
-	TBID(uint32 id = 0)				{ Set(id); }
-	TBID(const char *string)		{ Set(string); }
-	TBID(const TBID &id)			{ Set(id); }
+    TBID(uint32 id = 0)				{ Set(id); }
+    TBID(const char *string)		{ Set(string); }
+    TBID(const TBID &id)			{ Set(id); }
 
 #ifdef TB_RUNTIME_DEBUG_INFO
-	void Set(uint32 newid);
-	void Set(const TBID &newid);
-	void Set(const char *string);
+    void Set(uint32 newid);
+    void Set(const TBID &newid);
+    void Set(const char *string);
 #else
-	void Set(uint32 newid)			{ id = newid; }
-	void Set(const TBID &newid)		{ id = newid; }
+    void Set(uint32 newid)			{ id = newid; }
+    void Set(const TBID &newid)		{ id = newid; }
     void Set(const char *string)	{ id = TBGetHash(string); if (tbidRegisterCallback) tbidRegisterCallback(id, string); }
 #endif
 
-	operator uint32 () const		{ return id; }
-	const TBID& operator = (const TBID &id) { Set(id); return *this; }
+    operator uint32 () const		{ return id; }
+    const TBID& operator = (const TBID &id) { Set(id); return *this; }
 private:
-	uint32 id;
+    uint32 id;
 public:
-	/** This string is here to aid debugging (Only in debug builds!)
-		It should not to be used in your code! */
+    /** This string is here to aid debugging (Only in debug builds!)
+        It should not to be used in your code! */
 #ifdef TB_RUNTIME_DEBUG_INFO
-	friend class TBLanguage;
-	TBStr debug_string;
+    friend class TBLanguage;
+    TBStr debug_string;
 #endif
 
     static TBIDRegisterStringCallback tbidRegisterCallback;

+ 48 - 48
Source/ThirdParty/TurboBadger/tb_image_loader_stb.cpp

@@ -33,62 +33,62 @@ namespace tb {
 class STBI_Loader : public TBImageLoader
 {
 public:
-	int width, height;
-	unsigned char *data;
+    int width, height;
+    unsigned char *data;
 
-	STBI_Loader() : width(0), height(0), data(nullptr) {}
-	~STBI_Loader() { stbi_image_free(data); }
+    STBI_Loader() : width(0), height(0), data(nullptr) {}
+    ~STBI_Loader() { stbi_image_free(data); }
 
-	virtual int Width() { return width; }
-	virtual int Height() { return height; }
-	virtual uint32 *Data() { return (uint32*)data; }
+    virtual int Width() { return width; }
+    virtual int Height() { return height; }
+    virtual uint32 *Data() { return (uint32*)data; }
 };
 
 TBImageLoader *TBImageLoader::CreateFromFile(const char *filename)
 {
-	// Load directly from file
-	/*int w, h, comp;
-	if (unsigned char *data = stbi_load(filename, &w, &h, &comp, 4))
-	{
-		if (STBI_Loader *img = new STBI_Loader())
-		{
-			img->width = w;
-			img->height = h;
-			img->data = data;
-			return img;
-		}
-		else
-			stbi_image_free(data);
-	}
-	return nullptr;*/
-	if (TBFile *file = TBFile::Open(filename, TBFile::MODE_READ))
-	{
-		long size = file->Size();
-		if (unsigned char *data = new unsigned char[size])
-		{
-			size = file->Read(data, 1, size);
+    // Load directly from file
+    /*int w, h, comp;
+    if (unsigned char *data = stbi_load(filename, &w, &h, &comp, 4))
+    {
+        if (STBI_Loader *img = new STBI_Loader())
+        {
+            img->width = w;
+            img->height = h;
+            img->data = data;
+            return img;
+        }
+        else
+            stbi_image_free(data);
+    }
+    return nullptr;*/
+    if (TBFile *file = TBFile::Open(filename, TBFile::MODE_READ))
+    {
+        long size = file->Size();
+        if (unsigned char *data = new unsigned char[size])
+        {
+            size = file->Read(data, 1, size);
 
-			int w, h, comp;
-			if (unsigned char *img_data = stbi_load_from_memory(data, size, &w, &h, &comp, 4))
-			{
-				if (STBI_Loader *img = new STBI_Loader())
-				{
-					img->width = w;
-					img->height = h;
-					img->data = img_data;
-					delete [] data;
-					delete file;
-					return img;
-				}
-				else
-					stbi_image_free(img_data);
-			}
+            int w, h, comp;
+            if (unsigned char *img_data = stbi_load_from_memory(data, size, &w, &h, &comp, 4))
+            {
+                if (STBI_Loader *img = new STBI_Loader())
+                {
+                    img->width = w;
+                    img->height = h;
+                    img->data = img_data;
+                    delete [] data;
+                    delete file;
+                    return img;
+                }
+                else
+                    stbi_image_free(img_data);
+            }
 
-			delete data;
-		}
-		delete file;
-	}
-	return nullptr;
+            delete data;
+        }
+        delete file;
+    }
+    return nullptr;
 }
 
 }; // namespace tb

+ 60 - 60
Source/ThirdParty/TurboBadger/tb_inline_select.cpp

@@ -16,33 +16,33 @@ namespace tb {
 // == TBInlineSelect ========================================================================================
 
 TBInlineSelect::TBInlineSelect()
-	: m_value(0)
-	, m_min(0)
+    : m_value(0)
+    , m_min(0)
     , m_max(100)
     , m_modified(false)
 {
-	SetSkinBg(TBIDC("TBInlineSelect"));
-	AddChild(&m_layout);
-	m_layout.AddChild(&m_buttons[0]);
-	m_layout.AddChild(&m_editfield);
-	m_layout.AddChild(&m_buttons[1]);
-	m_layout.SetRect(GetPaddingRect());
-	m_layout.SetGravity(WIDGET_GRAVITY_ALL);
-	m_layout.SetSpacing(0);
-	m_buttons[0].SetSkinBg(TBIDC("TBButton.flat"));
-	m_buttons[1].SetSkinBg(TBIDC("TBButton.flat"));
+    SetSkinBg(TBIDC("TBInlineSelect"));
+    AddChild(&m_layout);
+    m_layout.AddChild(&m_buttons[0]);
+    m_layout.AddChild(&m_editfield);
+    m_layout.AddChild(&m_buttons[1]);
+    m_layout.SetRect(GetPaddingRect());
+    m_layout.SetGravity(WIDGET_GRAVITY_ALL);
+    m_layout.SetSpacing(0);
+    m_buttons[0].SetSkinBg(TBIDC("TBButton.flat"));
+    m_buttons[1].SetSkinBg(TBIDC("TBButton.flat"));
     m_buttons[0].GetContentRoot()->AddChild(new TBSkinImage(TBIDC("arrowdark.left")));
     m_buttons[1].GetContentRoot()->AddChild(new TBSkinImage(TBIDC("arrowdark.right")));
-	m_buttons[0].SetIsFocusable(false);
-	m_buttons[1].SetIsFocusable(false);
-	m_buttons[0].SetID(TBIDC("dec"));
-	m_buttons[1].SetID(TBIDC("inc"));
-	m_buttons[0].SetAutoRepeat(true);
-	m_buttons[1].SetAutoRepeat(true);
+    m_buttons[0].SetIsFocusable(false);
+    m_buttons[1].SetIsFocusable(false);
+    m_buttons[0].SetID(TBIDC("dec"));
+    m_buttons[1].SetID(TBIDC("inc"));
+    m_buttons[0].SetAutoRepeat(true);
+    m_buttons[1].SetAutoRepeat(true);
     m_editfield.SetID(TBIDC("edit"));
     m_editfield.SetTextAlign(TB_TEXT_ALIGN_CENTER);
-	m_editfield.SetEditType(EDIT_TYPE_NUMBER);
-	m_editfield.SetText("0");
+    m_editfield.SetEditType(EDIT_TYPE_NUMBER);
+    m_editfield.SetText("0");
 
     m_editfield.AddListener(this);
 
@@ -52,10 +52,10 @@ TBInlineSelect::~TBInlineSelect()
 {
     m_editfield.RemoveListener(this);
 
-	m_layout.RemoveChild(&m_buttons[1]);
-	m_layout.RemoveChild(&m_editfield);
-	m_layout.RemoveChild(&m_buttons[0]);
-	RemoveChild(&m_layout);
+    m_layout.RemoveChild(&m_buttons[1]);
+    m_layout.RemoveChild(&m_editfield);
+    m_layout.RemoveChild(&m_buttons[0]);
+    RemoveChild(&m_layout);
 }
 
 void TBInlineSelect::SetEditFieldLayoutParams(LayoutParams& lp)
@@ -65,22 +65,22 @@ void TBInlineSelect::SetEditFieldLayoutParams(LayoutParams& lp)
 
 void TBInlineSelect::SetLimits(double min, double max)
 {
-	assert(min <= max);
-	m_min = min;
-	m_max = max;
+    assert(min <= max);
+    m_min = min;
+    m_max = max;
     SetValueDouble(m_value);
 }
 
 void TBInlineSelect::SetValueInternal(double value, bool update_text)
 {
-	value = CLAMP(value, m_min, m_max);
-	if (value == m_value)
-		return;
-	m_value = value;
+    value = CLAMP(value, m_min, m_max);
+    if (value == m_value)
+        return;
+    m_value = value;
 
-	if (update_text)
-	{        
-		TBStr strval;
+    if (update_text)
+    {
+        TBStr strval;
 
         double prec = m_value - floor(m_value);
         if (prec < .001)
@@ -91,44 +91,44 @@ void TBInlineSelect::SetValueInternal(double value, bool update_text)
             strval.SetFormatted("%.2f", m_value);
 
 
-		m_editfield.SetText(strval);
-	}
+        m_editfield.SetText(strval);
+    }
 
     TBWidgetEvent ev(EVENT_TYPE_CHANGED);
     InvokeEvent(ev);
 
-	// Warning: Do nothing here since the event might have deleted us.
-	//          If needed, check if we are alive using a safe pointer first.
+    // Warning: Do nothing here since the event might have deleted us.
+    //          If needed, check if we are alive using a safe pointer first.
 }
 
 void TBInlineSelect::OnSkinChanged()
 {
-	m_layout.SetRect(GetPaddingRect());
+    m_layout.SetRect(GetPaddingRect());
 }
 
 bool TBInlineSelect::OnEvent(const TBWidgetEvent &ev)
 {
-	if (ev.type == EVENT_TYPE_KEY_DOWN)
-	{
-		if (ev.special_key == TB_KEY_UP || ev.special_key == TB_KEY_DOWN)
-		{
+    if (ev.type == EVENT_TYPE_KEY_DOWN)
+    {
+        if (ev.special_key == TB_KEY_UP || ev.special_key == TB_KEY_DOWN)
+        {
             double dv = ev.special_key == TB_KEY_UP ? 1 : -1;
             SetValueDouble(GetValueDouble() + dv);
-			return true;
-		}
-	}
-	else if (ev.type == EVENT_TYPE_CLICK && ev.target->GetID() == TBIDC("dec"))
-	{
+            return true;
+        }
+    }
+    else if (ev.type == EVENT_TYPE_CLICK && ev.target->GetID() == TBIDC("dec"))
+    {
         SetValueDouble(GetValueDouble() - 1);
         if (!ev.target->IsCaptured()) {
 
             InvokeModifiedEvent();
 
         }
-		return true;
-	}
-	else if (ev.type == EVENT_TYPE_CLICK && ev.target->GetID() == TBIDC("inc"))
-	{
+        return true;
+    }
+    else if (ev.type == EVENT_TYPE_CLICK && ev.target->GetID() == TBIDC("inc"))
+    {
         SetValueDouble(GetValueDouble() + 1);
 
         if (!ev.target->IsCaptured()) {
@@ -137,20 +137,20 @@ bool TBInlineSelect::OnEvent(const TBWidgetEvent &ev)
 
         }
 
-		return true;
-	}
-	else if (ev.type == EVENT_TYPE_CHANGED && ev.target == &m_editfield)
-	{
-		TBStr text;
-		m_editfield.GetText(text);
+        return true;
+    }
+    else if (ev.type == EVENT_TYPE_CHANGED && ev.target == &m_editfield)
+    {
+        TBStr text;
+        m_editfield.GetText(text);
         SetValueInternal((double) atof(text), false);
-	}
+    }
     else if (ev.type == EVENT_TYPE_CHANGED && ev.target == this)
     {
         return TBWidget::OnEvent(ev);
     }
 
-	return false;
+    return false;
 }
 
 void TBInlineSelect::InvokeModifiedEvent()

+ 18 - 18
Source/ThirdParty/TurboBadger/tb_inline_select.h

@@ -13,24 +13,24 @@
 namespace tb {
 
 /** TBSelectList is a select widget with no popups. Instead it has two
-	arrow buttons that cycle between the choices.
-	By default it is a number widget.
+    arrow buttons that cycle between the choices.
+    By default it is a number widget.
 
-	FIX: Should also be possible to set a list of strings that will be
-		shown instead of numbers.
+    FIX: Should also be possible to set a list of strings that will be
+        shown instead of numbers.
 */
 class TBInlineSelect : public TBWidget, private TBWidgetListener
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBInlineSelect, TBWidget);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBInlineSelect, TBWidget);
 
-	TBInlineSelect();
-	~TBInlineSelect();
+    TBInlineSelect();
+    ~TBInlineSelect();
 
-	/** Set along which axis the content should layouted. */
-	virtual void SetAxis(AXIS axis) { m_layout.SetAxis(axis); }
-	virtual AXIS GetAxis() const { return m_layout.GetAxis(); }
+    /** Set along which axis the content should layouted. */
+    virtual void SetAxis(AXIS axis) { m_layout.SetAxis(axis); }
+    virtual AXIS GetAxis() const { return m_layout.GetAxis(); }
 
     void SetLimits(double min, double max);
     double GetMinValue() const { return m_min; }
@@ -39,18 +39,18 @@ public:
     virtual void SetValueDouble(double value) { SetValueInternal(value, true); }
     virtual double GetValueDouble() { return m_value; }
 
-	virtual void SetValue(int value) { SetValueInternal(value, true); }
+    virtual void SetValue(int value) { SetValueInternal(value, true); }
     virtual int GetValue() { return m_value; }
 
     void SetEditFieldLayoutParams(LayoutParams& lp);
 
-	virtual void OnInflate(const INFLATE_INFO &info);
-	virtual void OnSkinChanged();
-	virtual bool OnEvent(const TBWidgetEvent &ev);
+    virtual void OnInflate(const INFLATE_INFO &info);
+    virtual void OnSkinChanged();
+    virtual bool OnEvent(const TBWidgetEvent &ev);
 protected:
-	TBButton m_buttons[2];
-	TBLayout m_layout;
-	TBEditField m_editfield;
+    TBButton m_buttons[2];
+    TBLayout m_layout;
+    TBEditField m_editfield;
     double m_value;
     double m_min, m_max;
     bool m_modified;

+ 27 - 27
Source/ThirdParty/TurboBadger/tb_language.cpp

@@ -11,47 +11,47 @@ namespace tb {
 
 TBLanguage::~TBLanguage()
 {
-	Clear();
+    Clear();
 }
 
 bool TBLanguage::Load(const char *filename)
 {
-	// Read the file into a node tree (even though it's only a flat list)
-	TBNode node;
-	if (!node.ReadFile(filename))
-		return false;
-
-	// Go through all nodes and add to the strings hash table
-	TBNode *n = node.GetFirstChild();
-	while (n)
-	{
-		const char *str = n->GetValue().GetString();
-		TBStr *new_str = new TBStr(str);
-		if (!new_str || !strings.Add(TBID(n->GetName()), new_str))
-		{
-			delete new_str;
-			return false;
-		}
-		n = n->GetNext();
-	}
-	return true;
+    // Read the file into a node tree (even though it's only a flat list)
+    TBNode node;
+    if (!node.ReadFile(filename))
+        return false;
+
+    // Go through all nodes and add to the strings hash table
+    TBNode *n = node.GetFirstChild();
+    while (n)
+    {
+        const char *str = n->GetValue().GetString();
+        TBStr *new_str = new TBStr(str);
+        if (!new_str || !strings.Add(TBID(n->GetName()), new_str))
+        {
+            delete new_str;
+            return false;
+        }
+        n = n->GetNext();
+    }
+    return true;
 }
 
 void TBLanguage::Clear()
 {
-	strings.DeleteAll();
+    strings.DeleteAll();
 }
 
 const char *TBLanguage::GetString(const TBID &id)
 {
-	if (TBStr *str = strings.Get(id))
-		return *str;
+    if (TBStr *str = strings.Get(id))
+        return *str;
 #ifdef TB_RUNTIME_DEBUG_INFO
-	static TBStr tmp;
-	tmp.SetFormatted("<TRANSLATE:%s>", id.debug_string.CStr());
-	return tmp;
+    static TBStr tmp;
+    tmp.SetFormatted("<TRANSLATE:%s>", id.debug_string.CStr());
+    return tmp;
 #else
-	return "<TRANSLATE!>";
+    return "<TRANSLATE!>";
 #endif
 }
 

+ 19 - 19
Source/ThirdParty/TurboBadger/tb_language.h

@@ -13,37 +13,37 @@
 namespace tb {
 
 /** TBLanguage is a basic language string manager.
-	Strings read into it can be looked up from a TBID, so either by a number
-	or the hash number from a string (done by TBID).
+    Strings read into it can be looked up from a TBID, so either by a number
+    or the hash number from a string (done by TBID).
 
-	Ex: GetString(10)      (Get the string with id 10)
-	Ex: GetString("new")   (Get the string with id new)
+    Ex: GetString(10)      (Get the string with id 10)
+    Ex: GetString("new")   (Get the string with id new)
 
-	In UI resources, you can refer to strings from language lookup by preceding a string with @.
+    In UI resources, you can refer to strings from language lookup by preceding a string with @.
 
-	Ex: TBButton: text: @close   (Create a button with text from lookup of "close")
+    Ex: TBButton: text: @close   (Create a button with text from lookup of "close")
 */
 
 class TBLanguage
 {
 public:
-	~TBLanguage();
+    ~TBLanguage();
 
-	/** Load a file into this language manager.
-		Note: This *adds* strings read from the file, without clearing any existing
-		strings first. */
-	bool Load(const char *filename);
+    /** Load a file into this language manager.
+        Note: This *adds* strings read from the file, without clearing any existing
+        strings first. */
+    bool Load(const char *filename);
 
-	/** Clear the list of strings. */
-	void Clear();
+    /** Clear the list of strings. */
+    void Clear();
 
-	/** Return the string with the given id.
-		If there is no string with that id, "<TRANSLATE!>" will be returned
-		in release builds, and "<TRANSLATE:%s>" (populated with the id) will
-		be returned in debug builds. */
-	const char *GetString(const TBID &id);
+    /** Return the string with the given id.
+        If there is no string with that id, "<TRANSLATE!>" will be returned
+        in release builds, and "<TRANSLATE:%s>" (populated with the id) will
+        be returned in debug builds. */
+    const char *GetString(const TBID &id);
 private:
-	TBHashTableOf<TBStr> strings;
+    TBHashTableOf<TBStr> strings;
 };
 
 };

+ 382 - 382
Source/ThirdParty/TurboBadger/tb_layout.cpp

@@ -13,515 +13,515 @@ namespace tb {
 // == TBLayout ==========================================================================
 
 TBLayout::TBLayout(AXIS axis)
-	: m_axis(axis)
-	, m_spacing(SPACING_FROM_SKIN)
-	, m_overflow(0)
-	, m_overflow_scroll(0)
-	, m_packed_init(0)
+    : m_axis(axis)
+    , m_spacing(SPACING_FROM_SKIN)
+    , m_overflow(0)
+    , m_overflow_scroll(0)
+    , m_packed_init(0)
 {
-	m_packed.layout_mode_size = LAYOUT_SIZE_GRAVITY;
-	m_packed.layout_mode_pos = LAYOUT_POSITION_CENTER;
-	m_packed.layout_mode_overflow = LAYOUT_OVERFLOW_CLIP;
-	m_packed.layout_mode_dist = LAYOUT_DISTRIBUTION_PREFERRED;
-	m_packed.layout_mode_dist_pos = LAYOUT_DISTRIBUTION_POSITION_CENTER;
-	m_packed.paint_overflow_fadeout = 1;
+    m_packed.layout_mode_size = LAYOUT_SIZE_GRAVITY;
+    m_packed.layout_mode_pos = LAYOUT_POSITION_CENTER;
+    m_packed.layout_mode_overflow = LAYOUT_OVERFLOW_CLIP;
+    m_packed.layout_mode_dist = LAYOUT_DISTRIBUTION_PREFERRED;
+    m_packed.layout_mode_dist_pos = LAYOUT_DISTRIBUTION_POSITION_CENTER;
+    m_packed.paint_overflow_fadeout = 1;
 }
 
 void TBLayout::SetAxis(AXIS axis)
 {
-	if (axis == m_axis)
-		return;
-	m_axis = axis;
-	InvalidateLayout(INVALIDATE_LAYOUT_RECURSIVE);
-	InvalidateSkinStates();
+    if (axis == m_axis)
+        return;
+    m_axis = axis;
+    InvalidateLayout(INVALIDATE_LAYOUT_RECURSIVE);
+    InvalidateSkinStates();
 }
 
 void TBLayout::SetSpacing(int spacing)
 {
-	if (spacing == m_spacing)
-		return;
-	m_spacing = spacing;
-	InvalidateLayout(INVALIDATE_LAYOUT_RECURSIVE);
+    if (spacing == m_spacing)
+        return;
+    m_spacing = spacing;
+    InvalidateLayout(INVALIDATE_LAYOUT_RECURSIVE);
 }
 
 void TBLayout::SetOverflowScroll(int overflow_scroll)
 {
-	overflow_scroll = MIN(overflow_scroll, m_overflow);
-	overflow_scroll = MAX(overflow_scroll, 0);
-	if (overflow_scroll == m_overflow_scroll)
-		return;
-	m_overflow_scroll = overflow_scroll;
-	Invalidate();
-	if (m_axis == AXIS_X)
-		OnScroll(m_overflow_scroll, 0);
-	else
-		OnScroll(0, m_overflow_scroll);
+    overflow_scroll = MIN(overflow_scroll, m_overflow);
+    overflow_scroll = MAX(overflow_scroll, 0);
+    if (overflow_scroll == m_overflow_scroll)
+        return;
+    m_overflow_scroll = overflow_scroll;
+    Invalidate();
+    if (m_axis == AXIS_X)
+        OnScroll(m_overflow_scroll, 0);
+    else
+        OnScroll(0, m_overflow_scroll);
 }
 
 void TBLayout::SetLayoutSize(LAYOUT_SIZE size)
 {
-	if (size == m_packed.layout_mode_size)
-		return;
-	m_packed.layout_mode_size = size;
-	InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
+    if (size == m_packed.layout_mode_size)
+        return;
+    m_packed.layout_mode_size = size;
+    InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
 }
 
 void TBLayout::SetLayoutPosition(LAYOUT_POSITION pos)
 {
-	if (pos == m_packed.layout_mode_pos)
-		return;
-	m_packed.layout_mode_pos = pos;
-	InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
+    if (pos == m_packed.layout_mode_pos)
+        return;
+    m_packed.layout_mode_pos = pos;
+    InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
 }
 
 void TBLayout::SetLayoutOverflow(LAYOUT_OVERFLOW overflow)
 {
-	if (overflow == m_packed.layout_mode_overflow)
-		return;
-	m_packed.layout_mode_overflow = overflow;
-	InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
+    if (overflow == m_packed.layout_mode_overflow)
+        return;
+    m_packed.layout_mode_overflow = overflow;
+    InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
 }
 
 void TBLayout::SetLayoutDistribution(LAYOUT_DISTRIBUTION distribution)
 {
-	if (distribution == m_packed.layout_mode_dist)
-		return;
-	m_packed.layout_mode_dist = distribution;
-	InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
+    if (distribution == m_packed.layout_mode_dist)
+        return;
+    m_packed.layout_mode_dist = distribution;
+    InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
 }
 
 void TBLayout::SetLayoutDistributionPosition(LAYOUT_DISTRIBUTION_POSITION distribution_pos)
 {
-	if (distribution_pos == m_packed.layout_mode_dist_pos)
-		return;
-	m_packed.layout_mode_dist_pos = distribution_pos;
-	InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
+    if (distribution_pos == m_packed.layout_mode_dist_pos)
+        return;
+    m_packed.layout_mode_dist_pos = distribution_pos;
+    InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
 }
 
 void TBLayout::SetLayoutOrder(LAYOUT_ORDER order)
 {
-	bool reversed = (order == LAYOUT_ORDER_TOP_TO_BOTTOM);
-	if (reversed == m_packed.mode_reverse_order)
-		return;
-	m_packed.mode_reverse_order = reversed;
-	InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
+    bool reversed = (order == LAYOUT_ORDER_TOP_TO_BOTTOM);
+    if (reversed == m_packed.mode_reverse_order)
+        return;
+    m_packed.mode_reverse_order = reversed;
+    InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
 }
 
 void TBLayout::InvalidateLayout(INVALIDATE_LAYOUT il)
 {
-	m_packed.layout_is_invalid = 1;
-	// Continue invalidating parents (depending on il)
-	TBWidget::InvalidateLayout(il);
+    m_packed.layout_is_invalid = 1;
+    // Continue invalidating parents (depending on il)
+    TBWidget::InvalidateLayout(il);
 }
 
 PreferredSize RotPreferredSize(const PreferredSize &ps, AXIS axis)
 {
-	if (axis == AXIS_X)
-		return ps;
-	PreferredSize psr;
-	psr.max_w = ps.max_h;
-	psr.max_h = ps.max_w;
-	psr.min_w = ps.min_h;
-	psr.min_h = ps.min_w;
-	psr.pref_w = ps.pref_h;
-	psr.pref_h = ps.pref_w;
-	psr.size_dependency =
-		((ps.size_dependency & SIZE_DEP_WIDTH_DEPEND_ON_HEIGHT) ?
-				SIZE_DEP_HEIGHT_DEPEND_ON_WIDTH : SIZE_DEP_NONE) |
-		((ps.size_dependency & SIZE_DEP_HEIGHT_DEPEND_ON_WIDTH) ?
-				SIZE_DEP_WIDTH_DEPEND_ON_HEIGHT : SIZE_DEP_NONE);
-	return psr;
+    if (axis == AXIS_X)
+        return ps;
+    PreferredSize psr;
+    psr.max_w = ps.max_h;
+    psr.max_h = ps.max_w;
+    psr.min_w = ps.min_h;
+    psr.min_h = ps.min_w;
+    psr.pref_w = ps.pref_h;
+    psr.pref_h = ps.pref_w;
+    psr.size_dependency =
+            ((ps.size_dependency & SIZE_DEP_WIDTH_DEPEND_ON_HEIGHT) ?
+                 SIZE_DEP_HEIGHT_DEPEND_ON_WIDTH : SIZE_DEP_NONE) |
+            ((ps.size_dependency & SIZE_DEP_HEIGHT_DEPEND_ON_WIDTH) ?
+                 SIZE_DEP_WIDTH_DEPEND_ON_HEIGHT : SIZE_DEP_NONE);
+    return psr;
 }
 
 SizeConstraints RotSizeConstraints(const SizeConstraints &sc, AXIS axis)
 {
-	return axis == AXIS_X ? sc : SizeConstraints(sc.available_h, sc.available_w);
+    return axis == AXIS_X ? sc : SizeConstraints(sc.available_h, sc.available_w);
 }
 
 TBRect RotRect(const TBRect &rect, AXIS axis)
 {
-	if (axis == AXIS_X)
-		return rect;
-	return TBRect(rect.y, rect.x, rect.h, rect.w);
+    if (axis == AXIS_X)
+        return rect;
+    return TBRect(rect.y, rect.x, rect.h, rect.w);
 }
 
 WIDGET_GRAVITY RotGravity(WIDGET_GRAVITY gravity, AXIS axis)
 {
-	if (axis == AXIS_X)
-		return gravity;
-	WIDGET_GRAVITY r = WIDGET_GRAVITY_NONE;
-	r |= (gravity & WIDGET_GRAVITY_LEFT) ? WIDGET_GRAVITY_TOP : WIDGET_GRAVITY_NONE;
-	r |= (gravity & WIDGET_GRAVITY_TOP) ? WIDGET_GRAVITY_LEFT : WIDGET_GRAVITY_NONE;
-	r |= (gravity & WIDGET_GRAVITY_RIGHT) ? WIDGET_GRAVITY_BOTTOM : WIDGET_GRAVITY_NONE;
-	r |= (gravity & WIDGET_GRAVITY_BOTTOM) ? WIDGET_GRAVITY_RIGHT : WIDGET_GRAVITY_NONE;
-	return r;
+    if (axis == AXIS_X)
+        return gravity;
+    WIDGET_GRAVITY r = WIDGET_GRAVITY_NONE;
+    r |= (gravity & WIDGET_GRAVITY_LEFT) ? WIDGET_GRAVITY_TOP : WIDGET_GRAVITY_NONE;
+    r |= (gravity & WIDGET_GRAVITY_TOP) ? WIDGET_GRAVITY_LEFT : WIDGET_GRAVITY_NONE;
+    r |= (gravity & WIDGET_GRAVITY_RIGHT) ? WIDGET_GRAVITY_BOTTOM : WIDGET_GRAVITY_NONE;
+    r |= (gravity & WIDGET_GRAVITY_BOTTOM) ? WIDGET_GRAVITY_RIGHT : WIDGET_GRAVITY_NONE;
+    return r;
 }
 
 bool TBLayout::QualifyForExpansion(WIDGET_GRAVITY gravity) const
 {
-	if (m_packed.layout_mode_dist == LAYOUT_DISTRIBUTION_AVAILABLE)
-		return true;
-	if (m_packed.layout_mode_dist == LAYOUT_DISTRIBUTION_GRAVITY &&
-		((gravity & WIDGET_GRAVITY_LEFT) && (gravity & WIDGET_GRAVITY_RIGHT)))
-		return true;
-	return false;
+    if (m_packed.layout_mode_dist == LAYOUT_DISTRIBUTION_AVAILABLE)
+        return true;
+    if (m_packed.layout_mode_dist == LAYOUT_DISTRIBUTION_GRAVITY &&
+            ((gravity & WIDGET_GRAVITY_LEFT) && (gravity & WIDGET_GRAVITY_RIGHT)))
+        return true;
+    return false;
 }
 
 int TBLayout::GetWantedHeight(WIDGET_GRAVITY gravity, const PreferredSize &ps, int available_height) const
 {
-	int height = 0;
-	switch (m_packed.layout_mode_size)
-	{
-	case LAYOUT_SIZE_GRAVITY:
-		height = ((gravity & WIDGET_GRAVITY_TOP) && (gravity & WIDGET_GRAVITY_BOTTOM)) ?
-									available_height : MIN(available_height, ps.pref_h);
-		break;
-	case LAYOUT_SIZE_PREFERRED:
-		height = MIN(available_height, ps.pref_h);
-		break;
-	case LAYOUT_SIZE_AVAILABLE:
-		height = MIN(available_height, ps.max_h);
-		break;
-	};
-	height = MIN(height, ps.max_h);
-	return height;
+    int height = 0;
+    switch (m_packed.layout_mode_size)
+    {
+    case LAYOUT_SIZE_GRAVITY:
+        height = ((gravity & WIDGET_GRAVITY_TOP) && (gravity & WIDGET_GRAVITY_BOTTOM)) ?
+                    available_height : MIN(available_height, ps.pref_h);
+        break;
+    case LAYOUT_SIZE_PREFERRED:
+        height = MIN(available_height, ps.pref_h);
+        break;
+    case LAYOUT_SIZE_AVAILABLE:
+        height = MIN(available_height, ps.max_h);
+        break;
+    };
+    height = MIN(height, ps.max_h);
+    return height;
 }
 
 
 TBWidget *TBLayout::GetNextNonCollapsedWidget(TBWidget *child) const
 {
-	TBWidget *next = GetNextInLayoutOrder(child);
-	while (next && next->GetVisibility() == WIDGET_VISIBILITY_GONE)
-		next = GetNextInLayoutOrder(next);
-	return next;
+    TBWidget *next = GetNextInLayoutOrder(child);
+    while (next && next->GetVisibility() == WIDGET_VISIBILITY_GONE)
+        next = GetNextInLayoutOrder(next);
+    return next;
 }
 
 int TBLayout::GetTrailingSpace(TBWidget *child, int spacing) const
 {
-	if (spacing == 0)
-		return 0;
-	if (!GetNextNonCollapsedWidget(child))
-		return 0;
-	return spacing;
+    if (spacing == 0)
+        return 0;
+    if (!GetNextNonCollapsedWidget(child))
+        return 0;
+    return spacing;
 }
 
 int TBLayout::CalculateSpacing()
 {
-	// Get spacing from skin, if not specified
-	int spacing = m_spacing;
-	if (spacing == SPACING_FROM_SKIN)
-	{
-		if (TBSkinElement *e = GetSkinBgElement())
-			spacing = e->spacing;
+    // Get spacing from skin, if not specified
+    int spacing = m_spacing;
+    if (spacing == SPACING_FROM_SKIN)
+    {
+        if (TBSkinElement *e = GetSkinBgElement())
+            spacing = e->spacing;
 
-		assert(SPACING_FROM_SKIN == SKIN_VALUE_NOT_SPECIFIED);
-		if (spacing == SPACING_FROM_SKIN /*|| spacing == SKIN_VALUE_NOT_SPECIFIED*/)
-			spacing = g_tb_skin->GetDefaultSpacing();
-	}
-	return spacing;
+        assert(SPACING_FROM_SKIN == SKIN_VALUE_NOT_SPECIFIED);
+        if (spacing == SPACING_FROM_SKIN /*|| spacing == SKIN_VALUE_NOT_SPECIFIED*/)
+            spacing = g_tb_skin->GetDefaultSpacing();
+    }
+    return spacing;
 }
 
 TBWidget *TBLayout::GetFirstInLayoutOrder() const
 {
-	return m_packed.mode_reverse_order ? GetLastChild() : GetFirstChild();
+    return m_packed.mode_reverse_order ? GetLastChild() : GetFirstChild();
 }
 
 TBWidget *TBLayout::GetNextInLayoutOrder(TBWidget *child) const
 {
-	return m_packed.mode_reverse_order ? child->GetPrev() : child->GetNext();
+    return m_packed.mode_reverse_order ? child->GetPrev() : child->GetNext();
 }
 
 void TBLayout::ValidateLayout(const SizeConstraints &constraints, PreferredSize *calculate_ps)
 {
-	// Layout notes:
-	// -All layout code is written for AXIS_X layout.
-	//  Instead of duplicating the layout code for both AXIS_X and AXIS_Y, we simply
-	//  rotate the in data (rect, gravity, preferred size) and the outdata (rect).
-
-	if (!calculate_ps)
-	{
-		if (!m_packed.layout_is_invalid)
-			return;
-		m_packed.layout_is_invalid = 0;
-	}
-	else
-	{
-		// Maximum size will grow below depending of the childrens maximum size
-		calculate_ps->max_w = calculate_ps->max_h = 0;
-	}
-
-	const int spacing = CalculateSpacing();
-	const TBRect padding_rect = GetPaddingRect();
-	const TBRect layout_rect = RotRect(padding_rect, m_axis);
-
-	const SizeConstraints inner_sc = constraints.ConstrainByPadding(GetRect().w - padding_rect.w,
-																	GetRect().h - padding_rect.h);
-
-	// Calculate totals for minimum and preferred width that we need for layout.
-	int total_preferred_w = 0;
-	int total_min_pref_diff_w = 0;
-	int total_max_pref_diff_w = 0;
-	for (TBWidget *child = GetFirstInLayoutOrder(); child; child = GetNextInLayoutOrder(child))
-	{
-		if (child->GetVisibility() == WIDGET_VISIBILITY_GONE)
-			continue;
-
-		const int ending_space = GetTrailingSpace(child, spacing);
-		const PreferredSize ps = RotPreferredSize(child->GetPreferredSize(inner_sc), m_axis);
-		const WIDGET_GRAVITY gravity = RotGravity(child->GetGravity(), m_axis);
-
-		total_preferred_w += ps.pref_w + ending_space;
-		total_min_pref_diff_w += ps.pref_w - ps.min_w;
-
-		if (QualifyForExpansion(gravity))
-		{
-			int capped_max_w = MIN(layout_rect.w, ps.max_w);
-			total_max_pref_diff_w += capped_max_w - ps.pref_w;
-		}
-
-		if (calculate_ps)
-		{
-			calculate_ps->min_h = MAX(calculate_ps->min_h, ps.min_h);
-			calculate_ps->pref_h = MAX(calculate_ps->pref_h, ps.pref_h);
-			calculate_ps->min_w += ps.min_w + ending_space;
-			calculate_ps->pref_w += ps.pref_w + ending_space;
-			calculate_ps->max_w += ps.max_w + ending_space;
-
-			// The widget height depends on layout and widget properties, so get what
-			// it would actually use if it was given max_h as available height.
-			// If we just used its max_h, that could increase the whole layout size
-			// even if the widget wouldn't actually use it.
-			int height = GetWantedHeight(gravity, ps, ps.max_h);
-			calculate_ps->max_h = MAX(calculate_ps->max_h, height);
-
-			calculate_ps->size_dependency |= ps.size_dependency;
-		}
-	}
-
-	if (calculate_ps)
-	{
-		// We just wanted to calculate preferred size, so return without layouting.
-		*calculate_ps = RotPreferredSize(*calculate_ps, m_axis);
-		return;
-	}
-
-	TB_IF_DEBUG_SETTING(LAYOUT_PS_DEBUGGING, last_layout_time = TBSystem::GetTimeMS());
-
-	// Pre Layout step (calculate distribution position)
-	int missing_space = MAX(total_preferred_w - layout_rect.w, 0);
-	int extra_space = MAX(layout_rect.w - total_preferred_w, 0);
-
-	int offset = layout_rect.x;
-	if (extra_space && m_packed.layout_mode_dist_pos != LAYOUT_DISTRIBUTION_POSITION_LEFT_TOP)
-	{
-		// To calculate the offset we need to predict the used space. We can do that by checking
-		// the distribution mode and total_max_pref_diff_w. That's how much the widgets could possible
-		// expand in the layout below.
-
-		int used_space = total_preferred_w;
-		if (m_packed.layout_mode_dist != LAYOUT_DISTRIBUTION_PREFERRED)
-			used_space += MIN(extra_space, total_max_pref_diff_w);
-
-		if (m_packed.layout_mode_dist_pos == LAYOUT_DISTRIBUTION_POSITION_CENTER)
-			offset += (layout_rect.w - used_space) / 2;
-		else // LAYOUT_DISTRIBUTION_POSITION_RIGHT_BOTTOM
-			offset += layout_rect.w - used_space;
-	}
-
-	// Layout
-	int used_space = 0;
-	for (TBWidget *child = GetFirstInLayoutOrder(); child; child = GetNextInLayoutOrder(child))
-	{
-		if (child->GetVisibility() == WIDGET_VISIBILITY_GONE)
-			continue;
-
-		const int ending_space = GetTrailingSpace(child, spacing);
-		const PreferredSize ps = RotPreferredSize(child->GetPreferredSize(inner_sc), m_axis);
-		const WIDGET_GRAVITY gravity = RotGravity(child->GetGravity(), m_axis);
-
-		// Calculate width. May shrink if space is missing, or grow if we have extra space.
-		int width = ps.pref_w;
-		if (missing_space && total_min_pref_diff_w)
-		{
-			int diff_w = ps.pref_w - ps.min_w;
-			float factor = (float)diff_w / (float)total_min_pref_diff_w;
-			int removed = (int)(missing_space * factor);
-			removed = MIN(removed, diff_w);
-			width -= removed;
-
-			total_min_pref_diff_w -= diff_w;
-			missing_space -= removed;
-		}
-		else if (extra_space && total_max_pref_diff_w && QualifyForExpansion(gravity))
-		{
-			int capped_max_w = MIN(layout_rect.w, ps.max_w);
-			int diff_w = capped_max_w - ps.pref_w;
-			float factor = (float)diff_w / (float)total_max_pref_diff_w;
-			int added = (int)(extra_space * factor);
-			added = MIN(added, diff_w);
-			width += added;
-
-			total_max_pref_diff_w -= capped_max_w - ps.pref_w;
-			extra_space -= added;
-		}
-
-		// Calculate height
-		int available_height = layout_rect.h;
-		int height = GetWantedHeight(gravity, ps, available_height);
-
-		// Calculate position
-		int pos = layout_rect.y;
-		switch (m_packed.layout_mode_pos)
-		{
-		case LAYOUT_POSITION_CENTER:
-			pos += (available_height - height) / 2;
-			break;
-		case LAYOUT_POSITION_RIGHT_BOTTOM:
-			pos += available_height - height;
-			break;
-		case LAYOUT_POSITION_GRAVITY:
-			if ((gravity & WIDGET_GRAVITY_TOP) && (gravity & WIDGET_GRAVITY_BOTTOM))
-				pos += (available_height - height) / 2;
-			else if (gravity & WIDGET_GRAVITY_BOTTOM)
-				pos += available_height - height;
-			break;
-		default: // LAYOUT_POSITION_LEFT_TOP
-			break;
-		};
-
-		// Done! Set rect and increase used space
-		TBRect rect(used_space + offset, pos, width, height);
-		used_space += width + ending_space;
-
-		child->SetRect(RotRect(rect, m_axis));
-	}
-	// Update overflow and overflow scroll
-	m_overflow = MAX(0, used_space - layout_rect.w);
-	SetOverflowScroll(m_overflow_scroll);
+    // Layout notes:
+    // -All layout code is written for AXIS_X layout.
+    //  Instead of duplicating the layout code for both AXIS_X and AXIS_Y, we simply
+    //  rotate the in data (rect, gravity, preferred size) and the outdata (rect).
+
+    if (!calculate_ps)
+    {
+        if (!m_packed.layout_is_invalid)
+            return;
+        m_packed.layout_is_invalid = 0;
+    }
+    else
+    {
+        // Maximum size will grow below depending of the childrens maximum size
+        calculate_ps->max_w = calculate_ps->max_h = 0;
+    }
+
+    const int spacing = CalculateSpacing();
+    const TBRect padding_rect = GetPaddingRect();
+    const TBRect layout_rect = RotRect(padding_rect, m_axis);
+
+    const SizeConstraints inner_sc = constraints.ConstrainByPadding(GetRect().w - padding_rect.w,
+                                                                    GetRect().h - padding_rect.h);
+
+    // Calculate totals for minimum and preferred width that we need for layout.
+    int total_preferred_w = 0;
+    int total_min_pref_diff_w = 0;
+    int total_max_pref_diff_w = 0;
+    for (TBWidget *child = GetFirstInLayoutOrder(); child; child = GetNextInLayoutOrder(child))
+    {
+        if (child->GetVisibility() == WIDGET_VISIBILITY_GONE)
+            continue;
+
+        const int ending_space = GetTrailingSpace(child, spacing);
+        const PreferredSize ps = RotPreferredSize(child->GetPreferredSize(inner_sc), m_axis);
+        const WIDGET_GRAVITY gravity = RotGravity(child->GetGravity(), m_axis);
+
+        total_preferred_w += ps.pref_w + ending_space;
+        total_min_pref_diff_w += ps.pref_w - ps.min_w;
+
+        if (QualifyForExpansion(gravity))
+        {
+            int capped_max_w = MIN(layout_rect.w, ps.max_w);
+            total_max_pref_diff_w += capped_max_w - ps.pref_w;
+        }
+
+        if (calculate_ps)
+        {
+            calculate_ps->min_h = MAX(calculate_ps->min_h, ps.min_h);
+            calculate_ps->pref_h = MAX(calculate_ps->pref_h, ps.pref_h);
+            calculate_ps->min_w += ps.min_w + ending_space;
+            calculate_ps->pref_w += ps.pref_w + ending_space;
+            calculate_ps->max_w += ps.max_w + ending_space;
+
+            // The widget height depends on layout and widget properties, so get what
+            // it would actually use if it was given max_h as available height.
+            // If we just used its max_h, that could increase the whole layout size
+            // even if the widget wouldn't actually use it.
+            int height = GetWantedHeight(gravity, ps, ps.max_h);
+            calculate_ps->max_h = MAX(calculate_ps->max_h, height);
+
+            calculate_ps->size_dependency |= ps.size_dependency;
+        }
+    }
+
+    if (calculate_ps)
+    {
+        // We just wanted to calculate preferred size, so return without layouting.
+        *calculate_ps = RotPreferredSize(*calculate_ps, m_axis);
+        return;
+    }
+
+    TB_IF_DEBUG_SETTING(LAYOUT_PS_DEBUGGING, last_layout_time = TBSystem::GetTimeMS());
+
+    // Pre Layout step (calculate distribution position)
+    int missing_space = MAX(total_preferred_w - layout_rect.w, 0);
+    int extra_space = MAX(layout_rect.w - total_preferred_w, 0);
+
+    int offset = layout_rect.x;
+    if (extra_space && m_packed.layout_mode_dist_pos != LAYOUT_DISTRIBUTION_POSITION_LEFT_TOP)
+    {
+        // To calculate the offset we need to predict the used space. We can do that by checking
+        // the distribution mode and total_max_pref_diff_w. That's how much the widgets could possible
+        // expand in the layout below.
+
+        int used_space = total_preferred_w;
+        if (m_packed.layout_mode_dist != LAYOUT_DISTRIBUTION_PREFERRED)
+            used_space += MIN(extra_space, total_max_pref_diff_w);
+
+        if (m_packed.layout_mode_dist_pos == LAYOUT_DISTRIBUTION_POSITION_CENTER)
+            offset += (layout_rect.w - used_space) / 2;
+        else // LAYOUT_DISTRIBUTION_POSITION_RIGHT_BOTTOM
+            offset += layout_rect.w - used_space;
+    }
+
+    // Layout
+    int used_space = 0;
+    for (TBWidget *child = GetFirstInLayoutOrder(); child; child = GetNextInLayoutOrder(child))
+    {
+        if (child->GetVisibility() == WIDGET_VISIBILITY_GONE)
+            continue;
+
+        const int ending_space = GetTrailingSpace(child, spacing);
+        const PreferredSize ps = RotPreferredSize(child->GetPreferredSize(inner_sc), m_axis);
+        const WIDGET_GRAVITY gravity = RotGravity(child->GetGravity(), m_axis);
+
+        // Calculate width. May shrink if space is missing, or grow if we have extra space.
+        int width = ps.pref_w;
+        if (missing_space && total_min_pref_diff_w)
+        {
+            int diff_w = ps.pref_w - ps.min_w;
+            float factor = (float)diff_w / (float)total_min_pref_diff_w;
+            int removed = (int)(missing_space * factor);
+            removed = MIN(removed, diff_w);
+            width -= removed;
+
+            total_min_pref_diff_w -= diff_w;
+            missing_space -= removed;
+        }
+        else if (extra_space && total_max_pref_diff_w && QualifyForExpansion(gravity))
+        {
+            int capped_max_w = MIN(layout_rect.w, ps.max_w);
+            int diff_w = capped_max_w - ps.pref_w;
+            float factor = (float)diff_w / (float)total_max_pref_diff_w;
+            int added = (int)(extra_space * factor);
+            added = MIN(added, diff_w);
+            width += added;
+
+            total_max_pref_diff_w -= capped_max_w - ps.pref_w;
+            extra_space -= added;
+        }
+
+        // Calculate height
+        int available_height = layout_rect.h;
+        int height = GetWantedHeight(gravity, ps, available_height);
+
+        // Calculate position
+        int pos = layout_rect.y;
+        switch (m_packed.layout_mode_pos)
+        {
+        case LAYOUT_POSITION_CENTER:
+            pos += (available_height - height) / 2;
+            break;
+        case LAYOUT_POSITION_RIGHT_BOTTOM:
+            pos += available_height - height;
+            break;
+        case LAYOUT_POSITION_GRAVITY:
+            if ((gravity & WIDGET_GRAVITY_TOP) && (gravity & WIDGET_GRAVITY_BOTTOM))
+                pos += (available_height - height) / 2;
+            else if (gravity & WIDGET_GRAVITY_BOTTOM)
+                pos += available_height - height;
+            break;
+        default: // LAYOUT_POSITION_LEFT_TOP
+            break;
+        };
+
+        // Done! Set rect and increase used space
+        TBRect rect(used_space + offset, pos, width, height);
+        used_space += width + ending_space;
+
+        child->SetRect(RotRect(rect, m_axis));
+    }
+    // Update overflow and overflow scroll
+    m_overflow = MAX(0, used_space - layout_rect.w);
+    SetOverflowScroll(m_overflow_scroll);
 }
 
 PreferredSize TBLayout::OnCalculatePreferredContentSize(const SizeConstraints &constraints)
 {
-	// Do a layout pass (without layouting) to check childrens preferences.
-	PreferredSize ps;
-	ValidateLayout(constraints, &ps);
-	return ps;
+    // Do a layout pass (without layouting) to check childrens preferences.
+    PreferredSize ps;
+    ValidateLayout(constraints, &ps);
+    return ps;
 }
 
 bool TBLayout::OnEvent(const TBWidgetEvent &ev)
 {
-	if (ev.type == EVENT_TYPE_WHEEL && ev.modifierkeys == TB_MODIFIER_NONE)
-	{
-		int old_scroll = GetOverflowScroll();
-		SetOverflowScroll(m_overflow_scroll + ev.delta_y * TBSystem::GetPixelsPerLine());
-		return m_overflow_scroll != old_scroll;
-	}
-	return false;
+    if (ev.type == EVENT_TYPE_WHEEL && ev.modifierkeys == TB_MODIFIER_NONE)
+    {
+        int old_scroll = GetOverflowScroll();
+        SetOverflowScroll(m_overflow_scroll + ev.delta_y * TBSystem::GetPixelsPerLine());
+        return m_overflow_scroll != old_scroll;
+    }
+    return false;
 }
 
 void TBLayout::OnPaintChildren(const PaintProps &paint_props)
 {
-	TBRect padding_rect = GetPaddingRect();
-	if (padding_rect.IsEmpty())
-		return;
-
-	// If we overflow the layout, apply clipping when painting children
-	TBRect old_clip_rect;
-	if (m_overflow)
-	{
-		// We only want clipping in one axis (the overflowing one) so we
-		// don't damage any expanded skins on the other axis. Add some fluff.
-		TBRect clip_rect = padding_rect;
-		const int fluff = 100;
-
-		if (m_axis == AXIS_X)
-			clip_rect = clip_rect.Expand(m_overflow_scroll == 0 ? fluff : 0, fluff,
-										m_overflow_scroll == m_overflow ? fluff : 0, fluff);
-		else
-			clip_rect = clip_rect.Expand(fluff, m_overflow_scroll == 0 ? fluff : 0,
-										fluff, m_overflow_scroll == m_overflow ? fluff : 0);
-
-		old_clip_rect = g_renderer->SetClipRect(clip_rect, true);
-
-		TB_IF_DEBUG_SETTING(LAYOUT_CLIPPING, g_renderer->DrawRect(clip_rect, TBColor(255, 0, 0, 200)));
-	}
-
-	// Paint children
-	TBWidget::OnPaintChildren(paint_props);
-
-	// Paint fadeout image over the overflowed edges
-	// to the indicate to used that it's overflowed.
-	if (m_overflow && m_packed.paint_overflow_fadeout)
-	{
-		TBID skin_x, skin_y;
-		if (m_axis == AXIS_X)
-			skin_x = TBIDC("TBLayout.fadeout_x");
-		else
-			skin_y = TBIDC("TBLayout.fadeout_y");
-
-		DrawEdgeFadeout(padding_rect, skin_x, skin_y,
-			m_overflow_scroll,
-			m_overflow_scroll,
-			m_overflow - m_overflow_scroll,
-			m_overflow - m_overflow_scroll);
-	}
-
-	// Restore clipping
-	if (m_overflow)
-		g_renderer->SetClipRect(old_clip_rect, false);
+    TBRect padding_rect = GetPaddingRect();
+    if (padding_rect.IsEmpty())
+        return;
+
+    // If we overflow the layout, apply clipping when painting children
+    TBRect old_clip_rect;
+    if (m_overflow)
+    {
+        // We only want clipping in one axis (the overflowing one) so we
+        // don't damage any expanded skins on the other axis. Add some fluff.
+        TBRect clip_rect = padding_rect;
+        const int fluff = 100;
+
+        if (m_axis == AXIS_X)
+            clip_rect = clip_rect.Expand(m_overflow_scroll == 0 ? fluff : 0, fluff,
+                                         m_overflow_scroll == m_overflow ? fluff : 0, fluff);
+        else
+            clip_rect = clip_rect.Expand(fluff, m_overflow_scroll == 0 ? fluff : 0,
+                                         fluff, m_overflow_scroll == m_overflow ? fluff : 0);
+
+        old_clip_rect = g_renderer->SetClipRect(clip_rect, true);
+
+        TB_IF_DEBUG_SETTING(LAYOUT_CLIPPING, g_renderer->DrawRect(clip_rect, TBColor(255, 0, 0, 200)));
+    }
+
+    // Paint children
+    TBWidget::OnPaintChildren(paint_props);
+
+    // Paint fadeout image over the overflowed edges
+    // to the indicate to used that it's overflowed.
+    if (m_overflow && m_packed.paint_overflow_fadeout)
+    {
+        TBID skin_x, skin_y;
+        if (m_axis == AXIS_X)
+            skin_x = TBIDC("TBLayout.fadeout_x");
+        else
+            skin_y = TBIDC("TBLayout.fadeout_y");
+
+        DrawEdgeFadeout(padding_rect, skin_x, skin_y,
+                        m_overflow_scroll,
+                        m_overflow_scroll,
+                        m_overflow - m_overflow_scroll,
+                        m_overflow - m_overflow_scroll);
+    }
+
+    // Restore clipping
+    if (m_overflow)
+        g_renderer->SetClipRect(old_clip_rect, false);
 }
 
 void TBLayout::OnProcess()
 {
-	SizeConstraints sc(GetRect().w, GetRect().h);
-	ValidateLayout(sc);
+    SizeConstraints sc(GetRect().w, GetRect().h);
+    ValidateLayout(sc);
 }
 
 void TBLayout::OnResized(int old_w, int old_h)
 {
-	InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
-	SizeConstraints sc(GetRect().w, GetRect().h);
-	ValidateLayout(sc);
+    InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
+    SizeConstraints sc(GetRect().w, GetRect().h);
+    ValidateLayout(sc);
 }
 
 void TBLayout::OnInflateChild(TBWidget *child)
 {
-	// Do nothing since we're going to layout the child soon.
+    // Do nothing since we're going to layout the child soon.
 }
 
 void TBLayout::GetChildTranslation(int &x, int &y) const
 {
-	if (m_axis == AXIS_X)
-	{
-		x = -m_overflow_scroll;
-		y = 0;
-	}
-	else
-	{
-		x = 0;
-		y = -m_overflow_scroll;
-	}
+    if (m_axis == AXIS_X)
+    {
+        x = -m_overflow_scroll;
+        y = 0;
+    }
+    else
+    {
+        x = 0;
+        y = -m_overflow_scroll;
+    }
 }
 
 void TBLayout::ScrollTo(int x, int y)
 {
-	SetOverflowScroll(m_axis == AXIS_X ? x : y);
+    SetOverflowScroll(m_axis == AXIS_X ? x : y);
 }
 
 TBWidget::ScrollInfo TBLayout::GetScrollInfo()
 {
-	ScrollInfo info;
-	if (m_axis == AXIS_X)
-	{
-		info.max_x = m_overflow;
-		info.x = m_overflow_scroll;
-	}
-	else
-	{
-		info.max_y = m_overflow;
-		info.y = m_overflow_scroll;
-	}
-	return info;
+    ScrollInfo info;
+    if (m_axis == AXIS_X)
+    {
+        info.max_x = m_overflow;
+        info.x = m_overflow_scroll;
+    }
+    else
+    {
+        info.max_y = m_overflow;
+        info.y = m_overflow_scroll;
+    }
+    return info;
 }
 
 }; // namespace tb

+ 99 - 99
Source/ThirdParty/TurboBadger/tb_layout.h

@@ -14,151 +14,151 @@ namespace tb {
 #define SPACING_FROM_SKIN TB_INVALID_DIMENSION
 
 /** Specifies which height widgets in a AXIS_X layout should have,
-	or which width widgets in a AXIS_Y layout should have.
-	No matter what, it will still prioritize minimum and maximum for each widget. */
+    or which width widgets in a AXIS_Y layout should have.
+    No matter what, it will still prioritize minimum and maximum for each widget. */
 enum LAYOUT_SIZE {
-	LAYOUT_SIZE_GRAVITY,	///< Sizes depend on the gravity for each widget. (If the widget pulls
-							///< towards both directions, it should grow to all available space)
-	LAYOUT_SIZE_PREFERRED,	///< Size will be the preferred so each widget may be sized differently.
-	LAYOUT_SIZE_AVAILABLE	///< Size should grow to all available space
+    LAYOUT_SIZE_GRAVITY,	///< Sizes depend on the gravity for each widget. (If the widget pulls
+    ///< towards both directions, it should grow to all available space)
+    LAYOUT_SIZE_PREFERRED,	///< Size will be the preferred so each widget may be sized differently.
+    LAYOUT_SIZE_AVAILABLE	///< Size should grow to all available space
 };
 
 /** Specifies which y position widgets in a AXIS_X layout should have,
-	or which x position widgets in a AXIS_Y layout should have. */
+    or which x position widgets in a AXIS_Y layout should have. */
 enum LAYOUT_POSITION {
-	LAYOUT_POSITION_CENTER,			///< Position is centered
-	LAYOUT_POSITION_LEFT_TOP,		///< Position is to the left for AXIS_Y layout and top for AXIS_X layout.
-	LAYOUT_POSITION_RIGHT_BOTTOM,	///< Position is to the right for AXIS_Y layout and bottom for AXIS_X layout.
-	LAYOUT_POSITION_GRAVITY,		///< Position depend on the gravity for each widget. (If the widget pulls
-									///< towards both directions, it will be centered)
+    LAYOUT_POSITION_CENTER,			///< Position is centered
+    LAYOUT_POSITION_LEFT_TOP,		///< Position is to the left for AXIS_Y layout and top for AXIS_X layout.
+    LAYOUT_POSITION_RIGHT_BOTTOM,	///< Position is to the right for AXIS_Y layout and bottom for AXIS_X layout.
+    LAYOUT_POSITION_GRAVITY,		///< Position depend on the gravity for each widget. (If the widget pulls
+    ///< towards both directions, it will be centered)
 };
 
 /** Specifies which width widgets in a AXIS_X layout should have,
-	or which height widgets in a AXIS_Y layout should have. */
+    or which height widgets in a AXIS_Y layout should have. */
 enum LAYOUT_DISTRIBUTION {
-	LAYOUT_DISTRIBUTION_PREFERRED,	///< Size will be the preferred so each widget may be sized differently.
-	LAYOUT_DISTRIBUTION_AVAILABLE,	///< Size should grow to all available space
-	LAYOUT_DISTRIBUTION_GRAVITY		///< Sizes depend on the gravity for each widget. (If the widget pulls
-									///< towards both directions, it should grow to all available space)
+    LAYOUT_DISTRIBUTION_PREFERRED,	///< Size will be the preferred so each widget may be sized differently.
+    LAYOUT_DISTRIBUTION_AVAILABLE,	///< Size should grow to all available space
+    LAYOUT_DISTRIBUTION_GRAVITY		///< Sizes depend on the gravity for each widget. (If the widget pulls
+    ///< towards both directions, it should grow to all available space)
 };
 
 /** Specifies how widgets should be moved horizontally in a AXIS_X
-	layout (or vertically in a AXIS_Y layout) if there is extra space
-	available. */
+    layout (or vertically in a AXIS_Y layout) if there is extra space
+    available. */
 enum LAYOUT_DISTRIBUTION_POSITION {
-	LAYOUT_DISTRIBUTION_POSITION_CENTER,
-	LAYOUT_DISTRIBUTION_POSITION_LEFT_TOP,
-	LAYOUT_DISTRIBUTION_POSITION_RIGHT_BOTTOM
+    LAYOUT_DISTRIBUTION_POSITION_CENTER,
+    LAYOUT_DISTRIBUTION_POSITION_LEFT_TOP,
+    LAYOUT_DISTRIBUTION_POSITION_RIGHT_BOTTOM
 };
 
 /** Layout order parameter for TBLayout::SetLayoutOrder. */
 enum LAYOUT_ORDER {
-	LAYOUT_ORDER_BOTTOM_TO_TOP,	///< From bottom to top widget (default creation order).
-	LAYOUT_ORDER_TOP_TO_BOTTOM	///< From top to bottom widget.
+    LAYOUT_ORDER_BOTTOM_TO_TOP,	///< From bottom to top widget (default creation order).
+    LAYOUT_ORDER_TOP_TO_BOTTOM	///< From top to bottom widget.
 };
 
 /** Specifies what happens when there is not enough room for the layout, even
-	when all the children have been shrunk to their minimum size. */
+    when all the children have been shrunk to their minimum size. */
 enum LAYOUT_OVERFLOW {
-	LAYOUT_OVERFLOW_CLIP,
-	LAYOUT_OVERFLOW_SCROLL
-	//LAYOUT_OVERFLOW_WRAP
+    LAYOUT_OVERFLOW_CLIP,
+    LAYOUT_OVERFLOW_SCROLL
+    //LAYOUT_OVERFLOW_WRAP
 };
 
 /** TBLayout layouts its children along the given axis.
 
-	Each widgets size depend on its preferred size (See TBWidget::GetPreferredSize),
-	gravity, and the specified layout settings (See SetLayoutSize, SetLayoutPosition
-	SetLayoutOverflow, SetLayoutDistribution, SetLayoutDistributionPosition), and
-	the available size.
+    Each widgets size depend on its preferred size (See TBWidget::GetPreferredSize),
+    gravity, and the specified layout settings (See SetLayoutSize, SetLayoutPosition
+    SetLayoutOverflow, SetLayoutDistribution, SetLayoutDistributionPosition), and
+    the available size.
 
-	Each widget is also separated by the specified spacing (See SetSpacing).
+    Each widget is also separated by the specified spacing (See SetSpacing).
 */
 
 class TBLayout : public TBWidget
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBLayout, TBWidget);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBLayout, TBWidget);
 
-	TBLayout(AXIS axis = AXIS_X);
+    TBLayout(AXIS axis = AXIS_X);
 
-	/** Set along which axis the content should be layouted */
-	virtual void SetAxis(AXIS axis);
-	virtual AXIS GetAxis() const { return m_axis; }
+    /** Set along which axis the content should be layouted */
+    virtual void SetAxis(AXIS axis);
+    virtual AXIS GetAxis() const { return m_axis; }
 
-	/** Set the spacing between widgets in this layout. Setting the default (SPACING_FROM_SKIN)
-		will make it use the spacing specified in the skin. */
-	void SetSpacing(int spacing);
-	int GetSpacing() const { return m_spacing; }
+    /** Set the spacing between widgets in this layout. Setting the default (SPACING_FROM_SKIN)
+        will make it use the spacing specified in the skin. */
+    void SetSpacing(int spacing);
+    int GetSpacing() const { return m_spacing; }
 
-	/** Set the overflow scroll. If there is not enough room for all children in this layout,
-		it can scroll in the axis it's laid out. It does so automatically by wheel or panning also
-		for other LAYOUT_OVERFLOW than LAYOUT_OVERFLOW_SCROLL. */
-	void SetOverflowScroll(int overflow_scroll);
-	int GetOverflowScroll() const { return m_overflow_scroll; }
+    /** Set the overflow scroll. If there is not enough room for all children in this layout,
+        it can scroll in the axis it's laid out. It does so automatically by wheel or panning also
+        for other LAYOUT_OVERFLOW than LAYOUT_OVERFLOW_SCROLL. */
+    void SetOverflowScroll(int overflow_scroll);
+    int GetOverflowScroll() const { return m_overflow_scroll; }
 
-	/** Set if a fadeout should be painter where the layout overflows or not. */
-	void SetPaintOverflowFadeout(bool paint_fadeout) { m_packed.paint_overflow_fadeout = paint_fadeout; }
+    /** Set if a fadeout should be painter where the layout overflows or not. */
+    void SetPaintOverflowFadeout(bool paint_fadeout) { m_packed.paint_overflow_fadeout = paint_fadeout; }
 
-	/** Set the layout size mode. See LAYOUT_SIZE. */
-	void SetLayoutSize(LAYOUT_SIZE size);
+    /** Set the layout size mode. See LAYOUT_SIZE. */
+    void SetLayoutSize(LAYOUT_SIZE size);
 
-	/** Set the layout position mode. See LAYOUT_POSITION. */
-	void SetLayoutPosition(LAYOUT_POSITION pos);
+    /** Set the layout position mode. See LAYOUT_POSITION. */
+    void SetLayoutPosition(LAYOUT_POSITION pos);
 
-	/** Set the layout size mode. See LAYOUT_OVERFLOW. */
-	void SetLayoutOverflow(LAYOUT_OVERFLOW overflow);
+    /** Set the layout size mode. See LAYOUT_OVERFLOW. */
+    void SetLayoutOverflow(LAYOUT_OVERFLOW overflow);
 
-	/** Set the layout distribution mode. See LAYOUT_DISTRIBUTION. */
-	void SetLayoutDistribution(LAYOUT_DISTRIBUTION distribution);
+    /** Set the layout distribution mode. See LAYOUT_DISTRIBUTION. */
+    void SetLayoutDistribution(LAYOUT_DISTRIBUTION distribution);
 
-	/** Set the layout distribution position mode. See LAYOUT_DISTRIBUTION_POSITION. */
-	void SetLayoutDistributionPosition(LAYOUT_DISTRIBUTION_POSITION distribution_pos);
+    /** Set the layout distribution position mode. See LAYOUT_DISTRIBUTION_POSITION. */
+    void SetLayoutDistributionPosition(LAYOUT_DISTRIBUTION_POSITION distribution_pos);
 
-	/** Set the layout order. The default is LAYOUT_ORDER_BOTTOM_TO_TOP, which begins
-		from bottom to top (default creation order). */
-	void SetLayoutOrder(LAYOUT_ORDER order);
+    /** Set the layout order. The default is LAYOUT_ORDER_BOTTOM_TO_TOP, which begins
+        from bottom to top (default creation order). */
+    void SetLayoutOrder(LAYOUT_ORDER order);
 
-	virtual void InvalidateLayout(INVALIDATE_LAYOUT il);
+    virtual void InvalidateLayout(INVALIDATE_LAYOUT il);
 
-	virtual PreferredSize OnCalculatePreferredContentSize(const SizeConstraints &constraints);
+    virtual PreferredSize OnCalculatePreferredContentSize(const SizeConstraints &constraints);
 
-	virtual void OnInflate(const INFLATE_INFO &info);
-	virtual bool OnEvent(const TBWidgetEvent &ev);
-	virtual void OnPaintChildren(const PaintProps &paint_props);
-	virtual void OnProcess();
-	virtual void OnResized(int old_w, int old_h);
-	virtual void OnInflateChild(TBWidget *child);
-	virtual void GetChildTranslation(int &x, int &y) const;
-	virtual void ScrollTo(int x, int y);
-	virtual TBWidget::ScrollInfo GetScrollInfo();
+    virtual void OnInflate(const INFLATE_INFO &info);
+    virtual bool OnEvent(const TBWidgetEvent &ev);
+    virtual void OnPaintChildren(const PaintProps &paint_props);
+    virtual void OnProcess();
+    virtual void OnResized(int old_w, int old_h);
+    virtual void OnInflateChild(TBWidget *child);
+    virtual void GetChildTranslation(int &x, int &y) const;
+    virtual void ScrollTo(int x, int y);
+    virtual TBWidget::ScrollInfo GetScrollInfo();
 protected:
-	AXIS m_axis;
-	int m_spacing;
-	int m_overflow;
-	int m_overflow_scroll;
-	union {
-		struct {
-			uint32 layout_is_invalid		: 1;
-			uint32 layout_mode_size			: 4;
-			uint32 layout_mode_pos			: 4;
-			uint32 layout_mode_overflow		: 4;
-			uint32 layout_mode_dist			: 4;
-			uint32 layout_mode_dist_pos		: 4;
-			uint32 mode_reverse_order		: 1;
-			uint32 paint_overflow_fadeout	: 1;
-		} m_packed;
-		uint32 m_packed_init;
-	};
-	void ValidateLayout(const SizeConstraints &constraints, PreferredSize *calculate_ps = nullptr);
-	bool QualifyForExpansion(WIDGET_GRAVITY gravity) const;
-	int GetWantedHeight(WIDGET_GRAVITY gravity, const PreferredSize &ps, int available_height) const;
-	TBWidget *GetNextNonCollapsedWidget(TBWidget *child) const;
-	int GetTrailingSpace(TBWidget *child, int spacing) const;
-	int CalculateSpacing();
-	TBWidget *GetFirstInLayoutOrder() const;
-	TBWidget *GetNextInLayoutOrder(TBWidget *child) const;
+    AXIS m_axis;
+    int m_spacing;
+    int m_overflow;
+    int m_overflow_scroll;
+    union {
+        struct {
+            uint32 layout_is_invalid		: 1;
+            uint32 layout_mode_size			: 4;
+            uint32 layout_mode_pos			: 4;
+            uint32 layout_mode_overflow		: 4;
+            uint32 layout_mode_dist			: 4;
+            uint32 layout_mode_dist_pos		: 4;
+            uint32 mode_reverse_order		: 1;
+            uint32 paint_overflow_fadeout	: 1;
+        } m_packed;
+        uint32 m_packed_init;
+    };
+    void ValidateLayout(const SizeConstraints &constraints, PreferredSize *calculate_ps = nullptr);
+    bool QualifyForExpansion(WIDGET_GRAVITY gravity) const;
+    int GetWantedHeight(WIDGET_GRAVITY gravity, const PreferredSize &ps, int available_height) const;
+    TBWidget *GetNextNonCollapsedWidget(TBWidget *child) const;
+    int GetTrailingSpace(TBWidget *child, int spacing) const;
+    int CalculateSpacing();
+    TBWidget *GetFirstInLayoutOrder() const;
+    TBWidget *GetNextInLayoutOrder(TBWidget *child) const;
 };
 
 };

+ 133 - 133
Source/ThirdParty/TurboBadger/tb_linklist.cpp

@@ -10,211 +10,211 @@ namespace tb {
 // == TBLinkListIterator ====================================================================================
 
 TBLinkListIterator::TBLinkListIterator(TBLinkList *linklist, TBLink *current_link, bool forward)
-	: m_linklist(linklist)
-	, m_current_link(current_link)
-	, m_forward(forward)
+    : m_linklist(linklist)
+    , m_current_link(current_link)
+    , m_forward(forward)
 {
-	Register();
+    Register();
 }
 
 TBLinkListIterator::TBLinkListIterator(const TBLinkListIterator &iter)
-	: m_linklist(iter.m_linklist)
-	, m_current_link(iter.m_current_link)
-	, m_forward(iter.m_forward)
+    : m_linklist(iter.m_linklist)
+    , m_current_link(iter.m_current_link)
+    , m_forward(iter.m_forward)
 {
-	Register();
+    Register();
 }
 
 TBLinkListIterator::~TBLinkListIterator()
 {
-	Unregister();
+    Unregister();
 }
 
 void TBLinkListIterator::Register()
 {
-	m_prev = nullptr;
-	m_next = m_linklist->first_iterator;
-	if (m_linklist->first_iterator)
-		m_linklist->first_iterator->m_prev = this;
-	m_linklist->first_iterator = this;
+    m_prev = nullptr;
+    m_next = m_linklist->first_iterator;
+    if (m_linklist->first_iterator)
+        m_linklist->first_iterator->m_prev = this;
+    m_linklist->first_iterator = this;
 }
 
 void TBLinkListIterator::Unregister()
 {
-	if (!m_linklist) // Already unregistered
-		return;
-	if (m_prev)
-		m_prev->m_next = m_next;
-	if (m_next)
-		m_next->m_prev = m_prev;
-	if (m_linklist->first_iterator == this)
-		m_linklist->first_iterator = m_next;
+    if (!m_linklist) // Already unregistered
+        return;
+    if (m_prev)
+        m_prev->m_next = m_next;
+    if (m_next)
+        m_next->m_prev = m_prev;
+    if (m_linklist->first_iterator == this)
+        m_linklist->first_iterator = m_next;
 }
 
 void TBLinkListIterator::UnregisterAndClear()
 {
-	Unregister();
-	m_linklist = nullptr;
-	m_current_link = nullptr;
-	m_prev = nullptr;
-	m_next = nullptr;
+    Unregister();
+    m_linklist = nullptr;
+    m_current_link = nullptr;
+    m_prev = nullptr;
+    m_next = nullptr;
 }
 
 const TBLinkListIterator& TBLinkListIterator::operator = (const TBLinkListIterator &iter)
 {
-	if (m_linklist != iter.m_linklist)
-	{
-		// Change where we are registered if we change linklist.
-		Unregister();
-		m_linklist = iter.m_linklist;
-		Register();
-	}
-	m_linklist = iter.m_linklist;
-	m_current_link = iter.m_current_link;
-	m_forward = iter.m_forward;
-	return *this;
+    if (m_linklist != iter.m_linklist)
+    {
+        // Change where we are registered if we change linklist.
+        Unregister();
+        m_linklist = iter.m_linklist;
+        Register();
+    }
+    m_linklist = iter.m_linklist;
+    m_current_link = iter.m_current_link;
+    m_forward = iter.m_forward;
+    return *this;
 }
 
 void TBLinkListIterator::Reset()
 {
-	if (m_linklist)
-		m_current_link = m_forward ? m_linklist->first : m_linklist->last;
-	else
-		m_current_link  = nullptr;
+    if (m_linklist)
+        m_current_link = m_forward ? m_linklist->first : m_linklist->last;
+    else
+        m_current_link  = nullptr;
 }
 
 TBLink *TBLinkListIterator::GetAndStep()
 {
-	if (!m_current_link)
-		return nullptr;
-	TBLink *current = m_current_link;
-	m_current_link = m_forward ? m_current_link->next : m_current_link->prev;
-	return current;
+    if (!m_current_link)
+        return nullptr;
+    TBLink *current = m_current_link;
+    m_current_link = m_forward ? m_current_link->next : m_current_link->prev;
+    return current;
 }
 
 void TBLinkListIterator::RemoveLink(TBLink *link)
 {
-	// If the current link is being removed, step away from it
-	if (m_current_link == link)
-		GetAndStep();
+    // If the current link is being removed, step away from it
+    if (m_current_link == link)
+        GetAndStep();
 }
 
 // == TBLinkList ============================================================================================
 
 TBLinkList::~TBLinkList()
 {
-	RemoveAll();
+    RemoveAll();
 
-	// Make sure any live iterators for this linklist are cleared!
-	while (first_iterator)
-		first_iterator->UnregisterAndClear();
+    // Make sure any live iterators for this linklist are cleared!
+    while (first_iterator)
+        first_iterator->UnregisterAndClear();
 }
 
 void TBLinkList::AddFirst(TBLink *link)
 {
-	assert(!link->linklist); // Link is already in some list!
-	link->linklist = this;
-	link->next = first;
-	if (first)
-		first->prev = link;
-	first = link;
-	if (!last)
-		last = link;
+    assert(!link->linklist); // Link is already in some list!
+    link->linklist = this;
+    link->next = first;
+    if (first)
+        first->prev = link;
+    first = link;
+    if (!last)
+        last = link;
 }
 
 void TBLinkList::AddLast(TBLink *link)
 {
-	assert(!link->linklist); // Link is already in some list!
-	link->linklist = this;
-	link->prev = last;
-	if (last)
-		last->next = link;
-	last = link;
-	if (!first)
-		first = link;
+    assert(!link->linklist); // Link is already in some list!
+    link->linklist = this;
+    link->prev = last;
+    if (last)
+        last->next = link;
+    last = link;
+    if (!first)
+        first = link;
 }
 
 void TBLinkList::AddBefore(TBLink *link, TBLink *reference)
 {
-	assert(reference->linklist == this); // Reference is not added to this list!
-	link->linklist = this;
-	link->prev = reference->prev;
-	link->next = reference;
-	if (reference->prev)
-		reference->prev->next = link;
-	else
-		first = link;
-	reference->prev = link;
+    assert(reference->linklist == this); // Reference is not added to this list!
+    link->linklist = this;
+    link->prev = reference->prev;
+    link->next = reference;
+    if (reference->prev)
+        reference->prev->next = link;
+    else
+        first = link;
+    reference->prev = link;
 }
 
 void TBLinkList::AddAfter(TBLink *link, TBLink *reference)
 {
-	assert(reference->linklist == this); // Reference is not added to this list!
-	link->linklist = this;
-	link->prev = reference;
-	link->next = reference->next;
-	if (reference->next)
-		reference->next->prev = link;
-	else
-		last = link;
-	reference->next = link;
+    assert(reference->linklist == this); // Reference is not added to this list!
+    link->linklist = this;
+    link->prev = reference;
+    link->next = reference->next;
+    if (reference->next)
+        reference->next->prev = link;
+    else
+        last = link;
+    reference->next = link;
 }
 
 void TBLinkList::Remove(TBLink *link)
 {
-	assert(link->linklist == this); // Link is not added to this list!
-
-	// Go through iterators and make sure there are no pointers
-	// to the link we remove.
-	TBLinkListIterator *iter = first_iterator;
-	while (iter)
-	{
-		iter->RemoveLink(link);
-		iter = iter->m_next;
-	}
-	// Remove the link
-	if (link->next)
-		link->next->prev = link->prev;
-	if (link->prev)
-		link->prev->next = link->next;
-	if (first == link)
-		first = link->next;
-	if (last == link)
-		last = link->prev;
-	link->linklist = nullptr;
-	link->prev = nullptr;
-	link->next = nullptr;
+    assert(link->linklist == this); // Link is not added to this list!
+
+    // Go through iterators and make sure there are no pointers
+    // to the link we remove.
+    TBLinkListIterator *iter = first_iterator;
+    while (iter)
+    {
+        iter->RemoveLink(link);
+        iter = iter->m_next;
+    }
+    // Remove the link
+    if (link->next)
+        link->next->prev = link->prev;
+    if (link->prev)
+        link->prev->next = link->next;
+    if (first == link)
+        first = link->next;
+    if (last == link)
+        last = link->prev;
+    link->linklist = nullptr;
+    link->prev = nullptr;
+    link->next = nullptr;
 }
 
 void TBLinkList::RemoveAll()
 {
-	// Reset all iterators.
-	TBLinkListIterator *iter = first_iterator;
-	while (iter)
-	{
-		iter->m_current_link = nullptr;
-		iter = iter->m_next;
-	}
-	// Remove all links
-	TBLink *link = first;
-	while (link)
-	{
-		TBLink *next = link->next;
-		link->linklist = nullptr;
-		link->prev = nullptr;
-		link->next = nullptr;
-		link = next;
-	}
-	first = nullptr;
-	last = nullptr;
+    // Reset all iterators.
+    TBLinkListIterator *iter = first_iterator;
+    while (iter)
+    {
+        iter->m_current_link = nullptr;
+        iter = iter->m_next;
+    }
+    // Remove all links
+    TBLink *link = first;
+    while (link)
+    {
+        TBLink *next = link->next;
+        link->linklist = nullptr;
+        link->prev = nullptr;
+        link->next = nullptr;
+        link = next;
+    }
+    first = nullptr;
+    last = nullptr;
 }
 
 int TBLinkList::CountLinks() const
 {
-	int count = 0;
-	for (TBLink *link = first; link; link = link->next)
-		count++;
-	return count;
+    int count = 0;
+    for (TBLink *link = first; link; link = link->next)
+        count++;
+    return count;
 }
 
 }; // namespace tb

+ 101 - 101
Source/ThirdParty/TurboBadger/tb_linklist.h

@@ -16,104 +16,104 @@ class TBLink;
 
 /** TBLinkListIterator - The backend class for a safe iteration of a TBLinkList.
 
-	You would normally recieve a typed iterator from a TBLinkListOf::IterateForward
-	or TBLinkListOf::IterateBackward, instead of creating this object directly.
+    You would normally recieve a typed iterator from a TBLinkListOf::IterateForward
+    or TBLinkListOf::IterateBackward, instead of creating this object directly.
 
-	Safe iteration means that if a link is removed from a linked list, _all_ iterators that currently
-	point to that link will automatically step to the next link in the iterators direction. */
+    Safe iteration means that if a link is removed from a linked list, _all_ iterators that currently
+    point to that link will automatically step to the next link in the iterators direction. */
 
 class TBLinkListIterator
 {
 public:
-	TBLinkListIterator(const TBLinkListIterator &iter);
-	TBLinkListIterator(TBLinkList *linklist, TBLink *current_link, bool forward);
-	~TBLinkListIterator();
+    TBLinkListIterator(const TBLinkListIterator &iter);
+    TBLinkListIterator(TBLinkList *linklist, TBLink *current_link, bool forward);
+    ~TBLinkListIterator();
 
-	/** Set the iterator to the first link in we iterate forward,
-		or set it to the last link if we iterate backward.  */
-	void Reset();
+    /** Set the iterator to the first link in we iterate forward,
+        or set it to the last link if we iterate backward.  */
+    void Reset();
 
-	/** Get the current link or nullptr if out of bounds. */
-	TBLink *Get() const { return m_current_link; }
+    /** Get the current link or nullptr if out of bounds. */
+    TBLink *Get() const { return m_current_link; }
 
-	/** Get the current link and step the iterator to the next (forward or backward). */
-	TBLink *GetAndStep();
+    /** Get the current link and step the iterator to the next (forward or backward). */
+    TBLink *GetAndStep();
 
-	operator TBLink *() const { return m_current_link; }
+    operator TBLink *() const { return m_current_link; }
 
-	const TBLinkListIterator& operator = (const TBLinkListIterator &iter);
+    const TBLinkListIterator& operator = (const TBLinkListIterator &iter);
 private:
-	TBLinkList *m_linklist;			///< The linklist we are iterating.
-	TBLink *m_current_link;			///< The current link, or nullptr.
-	bool m_forward;					///< true if we iterate from first to last item.
+    TBLinkList *m_linklist;			///< The linklist we are iterating.
+    TBLink *m_current_link;			///< The current link, or nullptr.
+    bool m_forward;					///< true if we iterate from first to last item.
 
-	TBLinkListIterator *m_prev;		///< Link in list of iterators for m_linklist
-	TBLinkListIterator *m_next;		///< Link in list of iterators for m_linklist
+    TBLinkListIterator *m_prev;		///< Link in list of iterators for m_linklist
+    TBLinkListIterator *m_next;		///< Link in list of iterators for m_linklist
 
-	/** RemoveLink is called when removing/deleting links in the target linklist.
-		This will make sure iterators skip the deleted item. */
-	void RemoveLink(TBLink *link);
-	friend class TBLinkList;
+    /** RemoveLink is called when removing/deleting links in the target linklist.
+        This will make sure iterators skip the deleted item. */
+    void RemoveLink(TBLink *link);
+    friend class TBLinkList;
 
-	/** Add ourself to the chain of iterators in the linklist. */
-	void Register();
+    /** Add ourself to the chain of iterators in the linklist. */
+    void Register();
 
-	/** Unlink ourself from the chain of iterators in the linklist. */
-	void Unregister();
-	void UnregisterAndClear();
+    /** Unlink ourself from the chain of iterators in the linklist. */
+    void Unregister();
+    void UnregisterAndClear();
 };
 
 /** TBLink - The backend class to be inserted in TBLinkList.
-	Use the typed TBLinkOf for object storing! */
+    Use the typed TBLinkOf for object storing! */
 
 class TBLink
 {
 public:
-	TBLink() : prev(nullptr), next(nullptr), linklist(nullptr) {}
+    TBLink() : prev(nullptr), next(nullptr), linklist(nullptr) {}
 
-	/** Return true if the link is currently added to a list. */
-	bool IsInList() const { return linklist ? true : false; }
+    /** Return true if the link is currently added to a list. */
+    bool IsInList() const { return linklist ? true : false; }
 public:
-	TBLink *prev;
-	TBLink *next;
-	TBLinkList *linklist;
+    TBLink *prev;
+    TBLink *next;
+    TBLinkList *linklist;
 };
 
 template<class T>
 class TBLinkOf : public TBLink
 {
 public:
-	inline T *GetPrev() const { return (T *) prev; }
-	inline T *GetNext() const { return (T *) next; }
+    inline T *GetPrev() const { return (T *) prev; }
+    inline T *GetNext() const { return (T *) next; }
 };
 
 /** TBLinkList - This is the backend for TBLinkListOf and TBLinkListAutoDeleteOf.
-	You should use the typed TBLinkListOf or TBLinkListAutoDeleteOf for object storing! */
+    You should use the typed TBLinkListOf or TBLinkListAutoDeleteOf for object storing! */
 
 class TBLinkList
 {
 public:
-	TBLinkList() : first(nullptr), last(nullptr), first_iterator(nullptr) {}
-	~TBLinkList();
+    TBLinkList() : first(nullptr), last(nullptr), first_iterator(nullptr) {}
+    ~TBLinkList();
 
-	void Remove(TBLink *link);
-	void RemoveAll();
+    void Remove(TBLink *link);
+    void RemoveAll();
 
-	void AddFirst(TBLink *link);
-	void AddLast(TBLink *link);
+    void AddFirst(TBLink *link);
+    void AddLast(TBLink *link);
 
-	void AddBefore(TBLink *link, TBLink *reference);
-	void AddAfter(TBLink *link, TBLink *reference);
+    void AddBefore(TBLink *link, TBLink *reference);
+    void AddAfter(TBLink *link, TBLink *reference);
 
-	bool ContainsLink(TBLink *link) const { return link->linklist == this; }
+    bool ContainsLink(TBLink *link) const { return link->linklist == this; }
 
-	bool HasLinks() const { return first ? true : false; }
+    bool HasLinks() const { return first ? true : false; }
 
-	int CountLinks() const;
+    int CountLinks() const;
 public:
-	TBLink *first;
-	TBLink *last;
-	TBLinkListIterator *first_iterator;
+    TBLink *first;
+    TBLink *last;
+    TBLinkListIterator *first_iterator;
 };
 
 /** TBLinkListOf is a double linked linklist. */
@@ -122,70 +122,70 @@ template<class T>
 class TBLinkListOf
 {
 public:
-	/** Remove link from this linklist. */
-	void Remove(T *link)			{ m_linklist.Remove(static_cast<TBLinkOf<T>*>(link)); }
+    /** Remove link from this linklist. */
+    void Remove(T *link)			{ m_linklist.Remove(static_cast<TBLinkOf<T>*>(link)); }
 
-	/** Remove link from this linklist and delete it. */
-	void Delete(T *link)			{ m_linklist.Remove(static_cast<TBLinkOf<T>*>(link)); delete link; }
+    /** Remove link from this linklist and delete it. */
+    void Delete(T *link)			{ m_linklist.Remove(static_cast<TBLinkOf<T>*>(link)); delete link; }
 
-	/** Remove all links without deleting them. */
-	void RemoveAll()				{ m_linklist.RemoveAll(); }
+    /** Remove all links without deleting them. */
+    void RemoveAll()				{ m_linklist.RemoveAll(); }
 
-	/** Delete all links in this linklist. */
-	void DeleteAll()				{ while (T *t = GetFirst()) Delete(t); }
+    /** Delete all links in this linklist. */
+    void DeleteAll()				{ while (T *t = GetFirst()) Delete(t); }
 
-	/** Add link first in this linklist. */
-	void AddFirst(T *link)			{ m_linklist.AddFirst(static_cast<TBLinkOf<T>*>(link)); }
+    /** Add link first in this linklist. */
+    void AddFirst(T *link)			{ m_linklist.AddFirst(static_cast<TBLinkOf<T>*>(link)); }
 
-	/** Add link last in this linklist. */
-	void AddLast(T *link)			{ m_linklist.AddLast(static_cast<TBLinkOf<T>*>(link)); }
+    /** Add link last in this linklist. */
+    void AddLast(T *link)			{ m_linklist.AddLast(static_cast<TBLinkOf<T>*>(link)); }
 
-	/** Add link before the reference link (which must be added to this linklist). */
-	void AddBefore(T *link, T *reference) { m_linklist.AddBefore(static_cast<TBLinkOf<T>*>(link), reference); }
+    /** Add link before the reference link (which must be added to this linklist). */
+    void AddBefore(T *link, T *reference) { m_linklist.AddBefore(static_cast<TBLinkOf<T>*>(link), reference); }
 
-	/** Add link after the reference link (which must be added to this linklist). */
-	void AddAfter(T *link, T *reference) { m_linklist.AddAfter(static_cast<TBLinkOf<T>*>(link), reference); }
+    /** Add link after the reference link (which must be added to this linklist). */
+    void AddAfter(T *link, T *reference) { m_linklist.AddAfter(static_cast<TBLinkOf<T>*>(link), reference); }
 
-	/** Return true if the link is currently added to this linklist. */
-	bool ContainsLink(T *link) const { return m_linklist.ContainsLink(static_cast<TBLinkOf<T>*>(link)); }
+    /** Return true if the link is currently added to this linklist. */
+    bool ContainsLink(T *link) const { return m_linklist.ContainsLink(static_cast<TBLinkOf<T>*>(link)); }
 
-	/** Get the first link, or nullptr. */
-	T *GetFirst() const { return (T *) static_cast<TBLinkOf<T>*>(m_linklist.first); }
+    /** Get the first link, or nullptr. */
+    T *GetFirst() const { return (T *) static_cast<TBLinkOf<T>*>(m_linklist.first); }
 
-	/** Get the last link, or nullptr. */
-	T *GetLast() const { return (T *) static_cast<TBLinkOf<T>*>(m_linklist.last); }
+    /** Get the last link, or nullptr. */
+    T *GetLast() const { return (T *) static_cast<TBLinkOf<T>*>(m_linklist.last); }
 
-	/** Return true if this linklist contains any links. */
-	bool HasLinks() const { return m_linklist.HasLinks(); }
+    /** Return true if this linklist contains any links. */
+    bool HasLinks() const { return m_linklist.HasLinks(); }
 
-	/** Count the number of links in this list by iterating through all links. */
-	int CountLinks() const { return m_linklist.CountLinks(); }
+    /** Count the number of links in this list by iterating through all links. */
+    int CountLinks() const { return m_linklist.CountLinks(); }
 
-	/** Typed iterator for safe iteration. For more info, see TBLinkListIterator. */
-	class Iterator : public TBLinkListIterator
-	{
-	public:
-		Iterator(TBLinkListOf<T> *linklistof, bool forward)
-			: TBLinkListIterator(&linklistof->m_linklist, forward ? linklistof->m_linklist.first : linklistof->m_linklist.last, forward) {}
-		Iterator(TBLinkListOf<T> *linklistof, T *link, bool forward) : TBLinkListIterator(&linklistof->m_linklist, link, forward) {}
-		inline T *Get() const { return (T *) static_cast<TBLinkOf<T>*>(TBLinkListIterator::Get()); }
-		inline T *GetAndStep() { return (T *) static_cast<TBLinkOf<T>*>(TBLinkListIterator::GetAndStep()); }
-		inline operator T *() const { return (T *) static_cast<TBLinkOf<T>*>(Get()); }
-	};
+    /** Typed iterator for safe iteration. For more info, see TBLinkListIterator. */
+    class Iterator : public TBLinkListIterator
+    {
+    public:
+        Iterator(TBLinkListOf<T> *linklistof, bool forward)
+            : TBLinkListIterator(&linklistof->m_linklist, forward ? linklistof->m_linklist.first : linklistof->m_linklist.last, forward) {}
+        Iterator(TBLinkListOf<T> *linklistof, T *link, bool forward) : TBLinkListIterator(&linklistof->m_linklist, link, forward) {}
+        inline T *Get() const { return (T *) static_cast<TBLinkOf<T>*>(TBLinkListIterator::Get()); }
+        inline T *GetAndStep() { return (T *) static_cast<TBLinkOf<T>*>(TBLinkListIterator::GetAndStep()); }
+        inline operator T *() const { return (T *) static_cast<TBLinkOf<T>*>(Get()); }
+    };
 
-	/** Get a forward iterator that starts with the first link. */
-	Iterator IterateForward() { return Iterator(this, true); }
+    /** Get a forward iterator that starts with the first link. */
+    Iterator IterateForward() { return Iterator(this, true); }
 
-	/** Get a forward iterator that starts with the given link. */
-	Iterator IterateForward(T *link) { return Iterator(this, link, true); }
+    /** Get a forward iterator that starts with the given link. */
+    Iterator IterateForward(T *link) { return Iterator(this, link, true); }
 
-	/** Get a backward iterator that starts with the last link. */
-	Iterator IterateBackward() { return Iterator(this, false); }
+    /** Get a backward iterator that starts with the last link. */
+    Iterator IterateBackward() { return Iterator(this, false); }
 
-	/** Get a backward iterator that starts with the given link. */
-	Iterator IterateBackward(T *link) { return Iterator(this, link, false); }
+    /** Get a backward iterator that starts with the given link. */
+    Iterator IterateBackward(T *link) { return Iterator(this, link, false); }
 private:
-	TBLinkList m_linklist;
+    TBLinkList m_linklist;
 };
 
 /** TBLinkListAutoDeleteOf is a double linked linklist that deletes all links on destruction. */
@@ -194,7 +194,7 @@ template<class T>
 class TBLinkListAutoDeleteOf : public TBLinkListOf<T>
 {
 public:
-	~TBLinkListAutoDeleteOf() { TBLinkListOf<T>::DeleteAll(); }
+    ~TBLinkListAutoDeleteOf() { TBLinkListOf<T>::DeleteAll(); }
 };
 
 }; // namespace tb

+ 61 - 61
Source/ThirdParty/TurboBadger/tb_list.cpp

@@ -13,107 +13,107 @@ namespace tb {
 
 bool TBListBackend::Add(void *data)
 {
-	if (!GrowIfNeeded())
-		return false;
-	m_data->list[m_data->num] = data;
-	m_data->num++;
-	return true;
+    if (!GrowIfNeeded())
+        return false;
+    m_data->list[m_data->num] = data;
+    m_data->num++;
+    return true;
 }
 
 bool TBListBackend::Add(void *data, int index)
 {
-	assert(index >= 0 && index <= GetNumItems());
-	if (!GrowIfNeeded())
-		return false;
-	if (index < m_data->num)
-		memmove(&m_data->list[index + 1], &m_data->list[index], (m_data->num - index) * sizeof(void*));
-	m_data->list[index] = data;
-	m_data->num++;
-	return true;
+    assert(index >= 0 && index <= GetNumItems());
+    if (!GrowIfNeeded())
+        return false;
+    if (index < m_data->num)
+        memmove(&m_data->list[index + 1], &m_data->list[index], (m_data->num - index) * sizeof(void*));
+    m_data->list[index] = data;
+    m_data->num++;
+    return true;
 }
 
 void TBListBackend::Set(void *data, int index)
 {
-	assert(index >= 0 && index < GetNumItems());
-	m_data->list[index] = data;
+    assert(index >= 0 && index < GetNumItems());
+    m_data->list[index] = data;
 }
 
 void *TBListBackend::RemoveFast(int index)
 {
-	assert(index >= 0 && index < GetNumItems());
-	void *data = m_data->list[index];
-	m_data->list[index] = m_data->list[m_data->num - 1];
-	m_data->num--;
-	return data;
+    assert(index >= 0 && index < GetNumItems());
+    void *data = m_data->list[index];
+    m_data->list[index] = m_data->list[m_data->num - 1];
+    m_data->num--;
+    return data;
 }
 
 void *TBListBackend::Remove(int index)
 {
-	assert(index >= 0 && index < GetNumItems());
-	void *data = m_data->list[index];
-	if(index < m_data->num - 1)
-		memmove(&m_data->list[index], &m_data->list[index + 1], (m_data->num - index - 1) * sizeof(void*));
-	m_data->num--;
-	return data;
+    assert(index >= 0 && index < GetNumItems());
+    void *data = m_data->list[index];
+    if(index < m_data->num - 1)
+        memmove(&m_data->list[index], &m_data->list[index + 1], (m_data->num - index - 1) * sizeof(void*));
+    m_data->num--;
+    return data;
 }
 
 void TBListBackend::RemoveAll()
 {
-	free(m_data);
-	m_data = nullptr;
+    free(m_data);
+    m_data = nullptr;
 }
 
 void TBListBackend::Swap(int index1, int index2)
 {
-	assert(index1 >= 0 && index1 < GetNumItems());
-	assert(index2 >= 0 && index2 < GetNumItems());
-	void *tmp = m_data->list[index1];
-	m_data->list[index1] = m_data->list[index2];
-	m_data->list[index2] = tmp;
+    assert(index1 >= 0 && index1 < GetNumItems());
+    assert(index2 >= 0 && index2 < GetNumItems());
+    void *tmp = m_data->list[index1];
+    m_data->list[index1] = m_data->list[index2];
+    m_data->list[index2] = tmp;
 }
 
 int TBListBackend::Find(void *data) const
 {
-	int num = GetNumItems();
-	for(int i = 0; i < num; i++)
-	{
-		if (Get(i) == data)
-			return i;
-	}
-	return -1;
+    int num = GetNumItems();
+    for(int i = 0; i < num; i++)
+    {
+        if (Get(i) == data)
+            return i;
+    }
+    return -1;
 }
 
 void *TBListBackend::Get(int index) const
 {
-	assert(index >= 0 && index < GetNumItems());
-	return m_data->list[index];
+    assert(index >= 0 && index < GetNumItems());
+    return m_data->list[index];
 }
 
 bool TBListBackend::Reserve(int new_capacity)
 {
-	assert(new_capacity > 0);
-	if (new_capacity > GetCapacity())
-	{
-		int num = GetNumItems();
-		if (char *new_data = (char *) realloc(m_data, sizeof(TBLIST_DATA) + sizeof(void *) * (new_capacity)))
-		{
-			m_data = (TBLIST_DATA *) new_data;
-			m_data->num = num;
-			m_data->capacity = new_capacity;
-			m_data->list = (void**) (new_data + sizeof(TBLIST_DATA));
-			return true;
-		}
-		return false;
-	}
-	return true;
+    assert(new_capacity > 0);
+    if (new_capacity > GetCapacity())
+    {
+        int num = GetNumItems();
+        if (char *new_data = (char *) realloc(m_data, sizeof(TBLIST_DATA) + sizeof(void *) * (new_capacity)))
+        {
+            m_data = (TBLIST_DATA *) new_data;
+            m_data->num = num;
+            m_data->capacity = new_capacity;
+            m_data->list = (void**) (new_data + sizeof(TBLIST_DATA));
+            return true;
+        }
+        return false;
+    }
+    return true;
 }
 
 bool TBListBackend::GrowIfNeeded()
 {
-	int capacity = GetCapacity();
-	if (GetNumItems() == capacity)
-		return Reserve(CLAMP(4, capacity * 2, 1024));
-	return true;
+    int capacity = GetCapacity();
+    if (GetNumItems() == capacity)
+        return Reserve(CLAMP(4, capacity * 2, 1024));
+    return true;
 }
 
 }; // namespace tb

+ 74 - 74
Source/ThirdParty/TurboBadger/tb_list.h

@@ -10,115 +10,115 @@
 namespace tb {
 
 /** TBList is a list (array) of pointers to any kind of objects.
-	This is the backend for TBListOf and TBListAutoDeleteOf.
-	You should use the typed TBListOf or TBListAutoDeleteOf for object storing! */
+    This is the backend for TBListOf and TBListAutoDeleteOf.
+    You should use the typed TBListOf or TBListAutoDeleteOf for object storing! */
 class TBListBackend
 {
 public:
-	TBListBackend() : m_data(nullptr) {}
-	~TBListBackend() { RemoveAll(); }
-	bool Reserve(int num);
-	bool GrowIfNeeded();
-	bool Add(void *data);
-	bool Add(void *data, int index);
-	void Set(void *data, int index);
-	void *Get(int index) const;
-	void *operator [] (int index) const { return Get(index); }
-	void *RemoveFast(int index);
-	void *Remove(int index);
-	void RemoveAll();
-	void Swap(int index1, int index2);
-	int Find(void *data) const;
-	int GetNumItems() const { return m_data ? m_data->num : 0; }
-	int GetCapacity() const { return m_data ? m_data->capacity : 0; }
+    TBListBackend() : m_data(nullptr) {}
+    ~TBListBackend() { RemoveAll(); }
+    bool Reserve(int num);
+    bool GrowIfNeeded();
+    bool Add(void *data);
+    bool Add(void *data, int index);
+    void Set(void *data, int index);
+    void *Get(int index) const;
+    void *operator [] (int index) const { return Get(index); }
+    void *RemoveFast(int index);
+    void *Remove(int index);
+    void RemoveAll();
+    void Swap(int index1, int index2);
+    int Find(void *data) const;
+    int GetNumItems() const { return m_data ? m_data->num : 0; }
+    int GetCapacity() const { return m_data ? m_data->capacity : 0; }
 private:
-	struct TBLIST_DATA {
-		int num;
-		int capacity;
-		void **list;
-	};
-	TBLIST_DATA *m_data;
+    struct TBLIST_DATA {
+        int num;
+        int capacity;
+        void **list;
+    };
+    TBLIST_DATA *m_data;
 };
 
 /** TBListOf is a list (array) of pointers to the specified object type.
-	Note: The objects won't be deleted automatically. If you want that,
-	use TBListAutoDeleteOf! */
+    Note: The objects won't be deleted automatically. If you want that,
+    use TBListAutoDeleteOf! */
 template<class T>
 class TBListOf
 {
 public:
-	/** Make sure there is space for at least num items in the list. Returns false on OOM failure. */
-	bool Reserve(int num)					{ return m_list.Reserve(num); }
+    /** Make sure there is space for at least num items in the list. Returns false on OOM failure. */
+    bool Reserve(int num)					{ return m_list.Reserve(num); }
 
-	/** Make sure there is space for at least one more item in the list. Returns false on OOM failure.
-		There's no need to call this, but it can make OOM handling easier in some situations since you
-		can guarantee there is space is in a list *before* you allocate an object to insert into it. */
-	bool GrowIfNeeded()						{ return m_list.GrowIfNeeded(); }
+    /** Make sure there is space for at least one more item in the list. Returns false on OOM failure.
+        There's no need to call this, but it can make OOM handling easier in some situations since you
+        can guarantee there is space is in a list *before* you allocate an object to insert into it. */
+    bool GrowIfNeeded()						{ return m_list.GrowIfNeeded(); }
 
-	/** Add data at the end of the list. Returns false on OOM failure. */
-	bool Add(T *data)						{ return m_list.Add(data); }
+    /** Add data at the end of the list. Returns false on OOM failure. */
+    bool Add(T *data)						{ return m_list.Add(data); }
 
-	/** Add data at the given index in the list. Returns false on OOM failure. */
-	bool Add(T *data, int index)			{ return m_list.Add(data, index); }
+    /** Add data at the given index in the list. Returns false on OOM failure. */
+    bool Add(T *data, int index)			{ return m_list.Add(data, index); }
 
-	/** Replace the item at the index with the new data */
-	void Set(T *data, int index)			{ m_list.Set(data, index); }
+    /** Replace the item at the index with the new data */
+    void Set(T *data, int index)			{ m_list.Set(data, index); }
 
-	/** Returns the content at position index. */
-	T *Get(int index) const					{ return (T *) m_list.Get(index); }
+    /** Returns the content at position index. */
+    T *Get(int index) const					{ return (T *) m_list.Get(index); }
 
-	/** Returns the content at position index. */
-	T *operator [] (int index) const		{ return (T *) m_list.Get(index); }
+    /** Returns the content at position index. */
+    T *operator [] (int index) const		{ return (T *) m_list.Get(index); }
 
-	/** Remove the item at position index from the list and returns the pointer.
-		This method should only be used when the order of the list is not important.
-		If the order is important, use Remove() */
-	T *RemoveFast(int index)				{ return (T *) m_list.RemoveFast(index); }
+    /** Remove the item at position index from the list and returns the pointer.
+        This method should only be used when the order of the list is not important.
+        If the order is important, use Remove() */
+    T *RemoveFast(int index)				{ return (T *) m_list.RemoveFast(index); }
 
-	/** Remove the item at position index from the list and returns the pointer. */
-	T *Remove(int index)					{ return (T *) m_list.Remove(index); }
+    /** Remove the item at position index from the list and returns the pointer. */
+    T *Remove(int index)					{ return (T *) m_list.Remove(index); }
 
-	/** Deletes the item at position index after removing it from the list.
-		This method should only be used when the order of the list is not important.
-		If the order is important, use Delete() */
-	void DeleteFast(int index)				{ delete (T *) m_list.RemoveFast(index); }
+    /** Deletes the item at position index after removing it from the list.
+        This method should only be used when the order of the list is not important.
+        If the order is important, use Delete() */
+    void DeleteFast(int index)				{ delete (T *) m_list.RemoveFast(index); }
 
-	/** Deletes the item at position index after removing it from the list. */
-	void Delete(int index)					{ delete (T *) m_list.Remove(index); }
+    /** Deletes the item at position index after removing it from the list. */
+    void Delete(int index)					{ delete (T *) m_list.Remove(index); }
 
-	/** Remove all items without deleding them. */
-	void RemoveAll()						{ m_list.RemoveAll(); }
+    /** Remove all items without deleding them. */
+    void RemoveAll()						{ m_list.RemoveAll(); }
 
-	/** Remove and delete all items from the list. */
-	void DeleteAll()
-	{
-		for (int i = 0; i < GetNumItems(); i++)
-			delete (T *) Get(i);
-		m_list.RemoveAll();
-	}
+    /** Remove and delete all items from the list. */
+    void DeleteAll()
+    {
+        for (int i = 0; i < GetNumItems(); i++)
+            delete (T *) Get(i);
+        m_list.RemoveAll();
+    }
 
-	/** Swap the items at index1 and index2 */
-	void Swap(int index1, int index2)		{ m_list.Swap(index1, index2); }
+    /** Swap the items at index1 and index2 */
+    void Swap(int index1, int index2)		{ m_list.Swap(index1, index2); }
 
-	/** Search for the item with the given data and return the found index, or -1 if not found. */
-	int Find(T *data) const					{ return m_list.Find(data); }
+    /** Search for the item with the given data and return the found index, or -1 if not found. */
+    int Find(T *data) const					{ return m_list.Find(data); }
 
-	/** Get the number of items in the list. */
-	int GetNumItems() const					{ return m_list.GetNumItems(); }
+    /** Get the number of items in the list. */
+    int GetNumItems() const					{ return m_list.GetNumItems(); }
 
-	/** Get the capacity of the list number of items it can hold without allocating more memory) */
-	int GetCapacity() const					{ return m_list.GetCapacity(); }
+    /** Get the capacity of the list number of items it can hold without allocating more memory) */
+    int GetCapacity() const					{ return m_list.GetCapacity(); }
 private:
-	TBListBackend m_list;
+    TBListBackend m_list;
 };
 
 /** TBListAutoDeleteOf is a list (array) of pointers to the specified object type.
-	The objects will be deleted automatically on destruction. */
+    The objects will be deleted automatically on destruction. */
 template<class T>
 class TBListAutoDeleteOf : public TBListOf<T>
 {
 public:
-	~TBListAutoDeleteOf() { TBListOf<T>::DeleteAll(); }
+    ~TBListAutoDeleteOf() { TBListOf<T>::DeleteAll(); }
 };
 
 }; // namespace tb

+ 29 - 29
Source/ThirdParty/TurboBadger/tb_menu_window.cpp

@@ -11,49 +11,49 @@ namespace tb {
 // == TBMenuWindow ==========================================
 
 TBMenuWindow::TBMenuWindow(TBWidget *target, TBID id)
-	: TBPopupWindow(target)
+    : TBPopupWindow(target)
 {
-	SetID(id);
-	SetSkinBg(TBIDC("TBMenuWindow"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
-	m_select_list.GetScrollContainer()->SetAdaptToContentSize(true);
-	m_select_list.SetIsFocusable(false); ///< Avoid it autoclosing its window on click
-	m_select_list.SetSkinBg("");
-	m_select_list.SetRect(GetPaddingRect());
-	m_select_list.SetGravity(WIDGET_GRAVITY_ALL);
-	AddChild(&m_select_list);
+    SetID(id);
+    SetSkinBg(TBIDC("TBMenuWindow"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
+    m_select_list.GetScrollContainer()->SetAdaptToContentSize(true);
+    m_select_list.SetIsFocusable(false); ///< Avoid it autoclosing its window on click
+    m_select_list.SetSkinBg("");
+    m_select_list.SetRect(GetPaddingRect());
+    m_select_list.SetGravity(WIDGET_GRAVITY_ALL);
+    AddChild(&m_select_list);
 }
 
 TBMenuWindow::~TBMenuWindow()
 {
-	RemoveChild(&m_select_list);
+    RemoveChild(&m_select_list);
 }
 
 bool TBMenuWindow::Show(TBSelectItemSource *source, const TBPopupAlignment &alignment, int initial_value)
 {
-	m_select_list.SetValue(initial_value);
-	m_select_list.SetSource(source);
-	m_select_list.ValidateList();
+    m_select_list.SetValue(initial_value);
+    m_select_list.SetSource(source);
+    m_select_list.ValidateList();
 
-	return TBPopupWindow::Show(alignment);
+    return TBPopupWindow::Show(alignment);
 }
 
 bool TBMenuWindow::OnEvent(const TBWidgetEvent &ev)
 {
-	if (ev.type == EVENT_TYPE_CLICK && &m_select_list == ev.target)
-	{
-		TBWidgetSafePointer this_widget(this);
-
-		// Invoke the click on the target
-		TBWidgetEvent target_ev(EVENT_TYPE_CLICK);
-		target_ev.ref_id = ev.ref_id;
-		InvokeEvent(target_ev);
-
-		// If target got deleted, close
-		if (this_widget.Get())
-			Close();
-		return true;
-	}
-	return TBPopupWindow::OnEvent(ev);
+    if (ev.type == EVENT_TYPE_CLICK && &m_select_list == ev.target)
+    {
+        TBWidgetSafePointer this_widget(this);
+
+        // Invoke the click on the target
+        TBWidgetEvent target_ev(EVENT_TYPE_CLICK);
+        target_ev.ref_id = ev.ref_id;
+        InvokeEvent(target_ev);
+
+        // If target got deleted, close
+        if (this_widget.Get())
+            Close();
+        return true;
+    }
+    return TBPopupWindow::OnEvent(ev);
 }
 
 }; // namespace tb

+ 11 - 11
Source/ThirdParty/TurboBadger/tb_menu_window.h

@@ -13,27 +13,27 @@ namespace tb {
 
 /** TBMenuWindow is a popup window that shows a list of items (TBSelectList).
 
-	When selected it will invoke a click with the id given to the menu,
-	and the id of the clicked item as ref_id, and then close itself.
+    When selected it will invoke a click with the id given to the menu,
+    and the id of the clicked item as ref_id, and then close itself.
 
-	It may open sub items as new windows at the same time as this window is open.*/
+    It may open sub items as new windows at the same time as this window is open.*/
 
 class TBMenuWindow : public TBPopupWindow
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBMenuWindow, TBPopupWindow);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBMenuWindow, TBPopupWindow);
 
-	TBMenuWindow(TBWidget *target, TBID id);
-	~TBMenuWindow();
+    TBMenuWindow(TBWidget *target, TBID id);
+    ~TBMenuWindow();
 
-	bool Show(TBSelectItemSource *source, const TBPopupAlignment &alignment, int initial_value = -1);
+    bool Show(TBSelectItemSource *source, const TBPopupAlignment &alignment, int initial_value = -1);
 
-	TBSelectList *GetList() { return &m_select_list; }
+    TBSelectList *GetList() { return &m_select_list; }
 
-	virtual bool OnEvent(const TBWidgetEvent &ev);
+    virtual bool OnEvent(const TBWidgetEvent &ev);
 private:
-	TBSelectList m_select_list;
+    TBSelectList m_select_list;
 };
 
 }; // namespace tb

+ 99 - 99
Source/ThirdParty/TurboBadger/tb_message_window.cpp

@@ -14,33 +14,33 @@ namespace tb {
 // == TBMessageWindow =======================================================================================
 
 TBMessageWindow::TBMessageWindow(TBWidget *target, TBID id)
-	: m_target(target)
+    : m_target(target)
 {
-	TBWidgetListener::AddGlobalListener(this);
-	SetID(id);
+    TBWidgetListener::AddGlobalListener(this);
+    SetID(id);
 }
 
 TBMessageWindow::~TBMessageWindow()
 {
-	TBWidgetListener::RemoveGlobalListener(this);
-	if (TBWidget *dimmer = m_dimmer.Get())
-	{
-		dimmer->GetParent()->RemoveChild(dimmer);
-		delete dimmer;
-	}
+    TBWidgetListener::RemoveGlobalListener(this);
+    if (TBWidget *dimmer = m_dimmer.Get())
+    {
+        dimmer->GetParent()->RemoveChild(dimmer);
+        delete dimmer;
+    }
 }
 
 bool TBMessageWindow::Show(const char *title, const char *message, TBMessageWindowSettings *settings, int width, int height)
 {
-	TBWidget *target = m_target.Get();
-	if (!target)
-		return false;
+    TBWidget *target = m_target.Get();
+    if (!target)
+        return false;
 
-	TBMessageWindowSettings default_settings;
-	if (!settings)
-		settings = &default_settings;
+    TBMessageWindowSettings default_settings;
+    if (!settings)
+        settings = &default_settings;
 
-	TBWidget *root = target->GetParentRoot();
+    TBWidget *root = target->GetParentRoot();
 
     const char *source =    "TBLayout: axis: y, distribution: available\n"
                             "	TBLayout: distribution: available, size: available\n"
@@ -50,36 +50,36 @@ bool TBMessageWindow::Show(const char *title, const char *message, TBMessageWind
                             "		TBLayout: distribution-position: left top, id: 5\n"
                             "		TBLayout: distribution-position: right bottom, id: 3\n";
 
-	if (!g_widgets_reader->LoadData(GetContentRoot(), source))
-		return false;
-
-	SetText(title);
-
-	GetWidgetByIDAndType<TBSkinImage>(2)->SetSkinBg(settings->icon_skin);
-
-	TBEditField *editfield = GetWidgetByIDAndType<TBEditField>(1);
-	editfield->SetStyling(settings->styling);
-	editfield->SetText(message);
-	editfield->SetSkinBg("");
-
-	// Create buttons
-	if (settings->msg == TB_MSG_OK)
-	{
-		AddButton("TBMessageWindow.ok", true);
-	}
-	else if (settings->msg == TB_MSG_OK_CANCEL)
-	{
-		AddButton("TBMessageWindow.ok", true);
-		AddButton("TBMessageWindow.cancel", false);
-	}
-	else if (settings->msg == TB_MSG_YES_NO)
-	{
-		AddButton("TBMessageWindow.yes", true);
-		AddButton("TBMessageWindow.no", false);
-	}
+    if (!g_widgets_reader->LoadData(GetContentRoot(), source))
+        return false;
+
+    SetText(title);
+
+    GetWidgetByIDAndType<TBSkinImage>(2)->SetSkinBg(settings->icon_skin);
+
+    TBEditField *editfield = GetWidgetByIDAndType<TBEditField>(1);
+    editfield->SetStyling(settings->styling);
+    editfield->SetText(message);
+    editfield->SetSkinBg("");
+
+    // Create buttons
+    if (settings->msg == TB_MSG_OK)
+    {
+        AddButton("TBMessageWindow.ok", true);
+    }
+    else if (settings->msg == TB_MSG_OK_CANCEL)
+    {
+        AddButton("TBMessageWindow.ok", true);
+        AddButton("TBMessageWindow.cancel", false);
+    }
+    else if (settings->msg == TB_MSG_YES_NO)
+    {
+        AddButton("TBMessageWindow.yes", true);
+        AddButton("TBMessageWindow.no", false);
+    }
     TBRect rect;
 
-	// Size to fit content. This will use the default size of the textfield.
+    // Size to fit content. This will use the default size of the textfield.
     if (width == 0 || height == 0)
     {
         ResizeToFitContent();
@@ -99,21 +99,21 @@ bool TBMessageWindow::Show(const char *title, const char *message, TBMessageWind
 
 
 
-	// Create background dimmer
-	if (settings->dimmer)
-	{
-		if (TBDimmer *dimmer = new TBDimmer)
-		{
-			root->AddChild(dimmer);
-			m_dimmer.Set(dimmer);
-		}
-	}
+    // Create background dimmer
+    if (settings->dimmer)
+    {
+        if (TBDimmer *dimmer = new TBDimmer)
+        {
+            root->AddChild(dimmer);
+            m_dimmer.Set(dimmer);
+        }
+    }
 
-	// Center and size to the new height
+    // Center and size to the new height
     TBRect bounds(0, 0, root->GetRect().w,  root->GetRect().h);
-	SetRect(rect.CenterIn(bounds).MoveIn(bounds).Clip(bounds));
-	root->AddChild(this);
-	return true;
+    SetRect(rect.CenterIn(bounds).MoveIn(bounds).Clip(bounds));
+    root->AddChild(this);
+    return true;
 }
 
 void TBMessageWindow::AddButtonLeft(TBID id, bool focused)
@@ -123,66 +123,66 @@ void TBMessageWindow::AddButtonLeft(TBID id, bool focused)
 
 void TBMessageWindow::AddButton(TBID id, bool focused, TBLayout *layout)
 {
-    if (!layout) 
-	    layout = GetWidgetByIDAndType<TBLayout>(3);
+    if (!layout)
+        layout = GetWidgetByIDAndType<TBLayout>(3);
+
+    if (!layout)
+        return;
 
-	if (!layout)
-		return;
-	
     if (TBButton *btn = new TBButton)
-	{
-		btn->SetID(id);
-		btn->SetText(g_tb_lng->GetString(btn->GetID()));
-		layout->AddChild(btn);
-		if (focused)
-			btn->SetFocus(WIDGET_FOCUS_REASON_UNKNOWN);
-	}
+    {
+        btn->SetID(id);
+        btn->SetText(g_tb_lng->GetString(btn->GetID()));
+        layout->AddChild(btn);
+        if (focused)
+            btn->SetFocus(WIDGET_FOCUS_REASON_UNKNOWN);
+    }
 }
 
 bool TBMessageWindow::OnEvent(const TBWidgetEvent &ev)
 {
-	if (ev.type == EVENT_TYPE_CLICK && ev.target->IsOfType<TBButton>())
-	{
-		TBWidgetSafePointer this_widget(this);
-
-		// Invoke the click on the target
-		TBWidgetEvent target_ev(EVENT_TYPE_CLICK);
-		target_ev.ref_id = ev.target->GetID();
-		InvokeEvent(target_ev);
-
-		// If target got deleted, close
-		if (this_widget.Get())
-			Close();
-		return true;
-	}
-	else if (ev.type == EVENT_TYPE_KEY_DOWN && ev.special_key == TB_KEY_ESC)
-	{
-		TBWidgetEvent click_ev(EVENT_TYPE_CLICK);
-		m_close_button.InvokeEvent(click_ev);
-		return true;
-	}
-	return TBWindow::OnEvent(ev);
+    if (ev.type == EVENT_TYPE_CLICK && ev.target->IsOfType<TBButton>())
+    {
+        TBWidgetSafePointer this_widget(this);
+
+        // Invoke the click on the target
+        TBWidgetEvent target_ev(EVENT_TYPE_CLICK);
+        target_ev.ref_id = ev.target->GetID();
+        InvokeEvent(target_ev);
+
+        // If target got deleted, close
+        if (this_widget.Get())
+            Close();
+        return true;
+    }
+    else if (ev.type == EVENT_TYPE_KEY_DOWN && ev.special_key == TB_KEY_ESC)
+    {
+        TBWidgetEvent click_ev(EVENT_TYPE_CLICK);
+        m_close_button.InvokeEvent(click_ev);
+        return true;
+    }
+    return TBWindow::OnEvent(ev);
 }
 
 void TBMessageWindow::OnDie()
 {
-	if (TBWidget *dimmer = m_dimmer.Get())
-		dimmer->Die();
+    if (TBWidget *dimmer = m_dimmer.Get())
+        dimmer->Die();
 }
 
 void TBMessageWindow::OnWidgetDelete(TBWidget *widget)
 {
-	// If the target widget is deleted, close!
-	if (!m_target.Get())
-		Close();
+    // If the target widget is deleted, close!
+    if (!m_target.Get())
+        Close();
 }
 
 bool TBMessageWindow::OnWidgetDying(TBWidget *widget)
 {
-	// If the target widget or an ancestor of it is dying, close!
-	if (widget == m_target.Get() || widget->IsAncestorOf(m_target.Get()))
-		Close();
-	return false;
+    // If the target widget or an ancestor of it is dying, close!
+    if (widget == m_target.Get() || widget->IsAncestorOf(m_target.Get()))
+        Close();
+    return false;
 }
 
 }; // namespace tb

+ 27 - 27
Source/ThirdParty/TurboBadger/tb_message_window.h

@@ -13,58 +13,58 @@ namespace tb {
 
 enum TB_MSG {
     TB_MSG_NONE,
-	TB_MSG_OK,
-	TB_MSG_OK_CANCEL,
-	TB_MSG_YES_NO
+    TB_MSG_OK,
+    TB_MSG_OK_CANCEL,
+    TB_MSG_YES_NO
 };
 
 /** TBMessageWindowSettings contains additional settings for TBMessageWindow. */
 class TBMessageWindowSettings
 {
 public:
-	TBMessageWindowSettings() : msg(TB_MSG_OK), dimmer(false), styling(false) {}
-	TBMessageWindowSettings(TB_MSG msg, TBID icon_skin) : msg(msg), icon_skin(icon_skin), dimmer(false), styling(false) {}
+    TBMessageWindowSettings() : msg(TB_MSG_OK), dimmer(false), styling(false) {}
+    TBMessageWindowSettings(TB_MSG msg, TBID icon_skin) : msg(msg), icon_skin(icon_skin), dimmer(false), styling(false) {}
 public:
-	TB_MSG msg;			///< The type of response for the message.
-	TBID icon_skin;		///< The icon skin (0 for no icon)
-	bool dimmer;		///< Set to true to dim background widgets by a TBDimmer.
-	bool styling;		///< Enable styling in the textfield.
+    TB_MSG msg;			///< The type of response for the message.
+    TBID icon_skin;		///< The icon skin (0 for no icon)
+    bool dimmer;		///< Set to true to dim background widgets by a TBDimmer.
+    bool styling;		///< Enable styling in the textfield.
 };
 
 /** TBMessageWindow is a window for showing simple messages.
-	Events invoked in this window will travel up through the target widget.
+    Events invoked in this window will travel up through the target widget.
 
-	When the user click any of its buttons, it will invoke a click event
-	(with the window ID), with the clicked buttons id as ref_id.
-	Then it will delete itself.
+    When the user click any of its buttons, it will invoke a click event
+    (with the window ID), with the clicked buttons id as ref_id.
+    Then it will delete itself.
 
-	If the target widget is deleted while this window is alive, the
-	window will delete itself. */
+    If the target widget is deleted while this window is alive, the
+    window will delete itself. */
 class TBMessageWindow : public TBWindow, private TBWidgetListener
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBMessageWindow, TBWindow);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBMessageWindow, TBWindow);
 
-	TBMessageWindow(TBWidget *target, TBID id);
-	virtual ~TBMessageWindow();
+    TBMessageWindow(TBWidget *target, TBID id);
+    virtual ~TBMessageWindow();
 
     bool Show(const char *title, const char *message, TBMessageWindowSettings *settings = nullptr, int width = 0, int height = 0);
 
-	virtual TBWidget *GetEventDestination() { return m_target.Get(); }
+    virtual TBWidget *GetEventDestination() { return m_target.Get(); }
 
-	virtual bool OnEvent(const TBWidgetEvent &ev);
-	virtual void OnDie();
+    virtual bool OnEvent(const TBWidgetEvent &ev);
+    virtual void OnDie();
 
     void AddButton(TBID id, bool focused, TBLayout *layout = nullptr);
     void AddButtonLeft(TBID id, bool focused);
 
 private:
-	// TBWidgetListener
-	virtual void OnWidgetDelete(TBWidget *widget);
-	virtual bool OnWidgetDying(TBWidget *widget);
-	TBWidgetSafePointer m_dimmer;
-	TBWidgetSafePointer m_target;
+    // TBWidgetListener
+    virtual void OnWidgetDelete(TBWidget *widget);
+    virtual bool OnWidgetDying(TBWidget *widget);
+    TBWidgetSafePointer m_dimmer;
+    TBWidgetSafePointer m_target;
 };
 
 }; // namespace tb

+ 112 - 112
Source/ThirdParty/TurboBadger/tb_msg.cpp

@@ -18,13 +18,13 @@ TBLinkListOf<TBMessageLink> g_all_normal_messages;
 // == TBMessage =========================================================================
 
 TBMessage::TBMessage(TBID message, TBMessageData *data, double fire_time_ms, TBMessageHandler *mh)
-	: message(message), data(data), fire_time_ms(fire_time_ms), mh(mh)
+    : message(message), data(data), fire_time_ms(fire_time_ms), mh(mh)
 {
 }
 
 TBMessage::~TBMessage()
 {
-	delete data;
+    delete data;
 }
 
 // == TBMessageHandler ==================================================================
@@ -35,156 +35,156 @@ TBMessageHandler::TBMessageHandler()
 
 TBMessageHandler::~TBMessageHandler()
 {
-	DeleteAllMessages();
+    DeleteAllMessages();
 }
 
 bool TBMessageHandler::PostMessageDelayed(TBID message, TBMessageData *data, uint32 delay_in_ms)
 {
-	return PostMessageOnTime(message, data, TBSystem::GetTimeMS() + (double)delay_in_ms);
+    return PostMessageOnTime(message, data, TBSystem::GetTimeMS() + (double)delay_in_ms);
 }
 
 bool TBMessageHandler::PostMessageOnTime(TBID message, TBMessageData *data, double fire_time)
 {
-	if (TBMessage *msg = new TBMessage(message, data, fire_time, this))
-	{
-		// Find the message that is already in the list that should fire later, so we can
-		// insert msg just before that. (Always keep the list ordered after fire time)
-
-		// NOTE: If another message is added during OnMessageReceived, it might or might not be fired
-		// in the right order compared to other delayed messages, depending on if it's inserted before or
-		// after the message being processed!
-
-		TBMessage *later_msg = nullptr;
-		TBMessageLink *link = g_all_delayed_messages.GetFirst();
-		while (link)
-		{
-			TBMessage *msg_in_list = static_cast<TBMessage*>(link);
-			if (msg_in_list->fire_time_ms > msg->fire_time_ms)
-			{
-				later_msg = msg_in_list;
-				break;
-			}
-			link = link->GetNext();
-		}
-
-		// Add it to the global list in the right order.
-		if (later_msg)
-			g_all_delayed_messages.AddBefore(msg, later_msg);
-		else
-			g_all_delayed_messages.AddLast(msg);
-
-		// Add it to the list in messagehandler.
-		m_messages.AddLast(msg);
-
-		// If we added it first and there's no normal messages, the next fire time has
-		// changed and we have to reschedule the timer.
-		if (!g_all_normal_messages.GetFirst() && g_all_delayed_messages.GetFirst() == msg)
-			TBSystem::RescheduleTimer(msg->fire_time_ms);
-		return true;
-	}
-	return false;
+    if (TBMessage *msg = new TBMessage(message, data, fire_time, this))
+    {
+        // Find the message that is already in the list that should fire later, so we can
+        // insert msg just before that. (Always keep the list ordered after fire time)
+
+        // NOTE: If another message is added during OnMessageReceived, it might or might not be fired
+        // in the right order compared to other delayed messages, depending on if it's inserted before or
+        // after the message being processed!
+
+        TBMessage *later_msg = nullptr;
+        TBMessageLink *link = g_all_delayed_messages.GetFirst();
+        while (link)
+        {
+            TBMessage *msg_in_list = static_cast<TBMessage*>(link);
+            if (msg_in_list->fire_time_ms > msg->fire_time_ms)
+            {
+                later_msg = msg_in_list;
+                break;
+            }
+            link = link->GetNext();
+        }
+
+        // Add it to the global list in the right order.
+        if (later_msg)
+            g_all_delayed_messages.AddBefore(msg, later_msg);
+        else
+            g_all_delayed_messages.AddLast(msg);
+
+        // Add it to the list in messagehandler.
+        m_messages.AddLast(msg);
+
+        // If we added it first and there's no normal messages, the next fire time has
+        // changed and we have to reschedule the timer.
+        if (!g_all_normal_messages.GetFirst() && g_all_delayed_messages.GetFirst() == msg)
+            TBSystem::RescheduleTimer(msg->fire_time_ms);
+        return true;
+    }
+    return false;
 }
 
 bool TBMessageHandler::PostMessage(TBID message, TBMessageData *data)
 {
-	if (TBMessage *msg = new TBMessage(message, data, 0, this))
-	{
-		g_all_normal_messages.AddLast(msg);
-		m_messages.AddLast(msg);
-
-		// If we added it and there was no messages, the next fire time has
-		// changed and we have to rescedule the timer.
-		if (g_all_normal_messages.GetFirst() == msg)
-			TBSystem::RescheduleTimer(0);
-		return true;
-	}
-	return false;
+    if (TBMessage *msg = new TBMessage(message, data, 0, this))
+    {
+        g_all_normal_messages.AddLast(msg);
+        m_messages.AddLast(msg);
+
+        // If we added it and there was no messages, the next fire time has
+        // changed and we have to rescedule the timer.
+        if (g_all_normal_messages.GetFirst() == msg)
+            TBSystem::RescheduleTimer(0);
+        return true;
+    }
+    return false;
 }
 
 TBMessage *TBMessageHandler::GetMessageByID(TBID message)
 {
-	TBLinkListOf<TBMessage>::Iterator iter = m_messages.IterateForward();
-	while (TBMessage *msg = iter.GetAndStep())
-		if (msg->message == message)
-			return msg;
-	return nullptr;
+    TBLinkListOf<TBMessage>::Iterator iter = m_messages.IterateForward();
+    while (TBMessage *msg = iter.GetAndStep())
+        if (msg->message == message)
+            return msg;
+    return nullptr;
 }
 
 void TBMessageHandler::DeleteMessage(TBMessage *msg)
 {
-	assert(msg->mh == this); // This is not the message handler owning the message!
+    assert(msg->mh == this); // This is not the message handler owning the message!
 
-	// Remove from global list (g_all_delayed_messages or g_all_normal_messages)
-	if (g_all_delayed_messages.ContainsLink(msg))
-		g_all_delayed_messages.Remove(msg);
-	else if (g_all_normal_messages.ContainsLink(msg))
-		g_all_normal_messages.Remove(msg);
+    // Remove from global list (g_all_delayed_messages or g_all_normal_messages)
+    if (g_all_delayed_messages.ContainsLink(msg))
+        g_all_delayed_messages.Remove(msg);
+    else if (g_all_normal_messages.ContainsLink(msg))
+        g_all_normal_messages.Remove(msg);
 
-	// Remove from local list
-	m_messages.Remove(msg);
+    // Remove from local list
+    m_messages.Remove(msg);
 
-	delete msg;
+    delete msg;
 
-	// Note: We could call TBSystem::RescheduleTimer if we think that deleting
-	// this message changed the time for the next message.
+    // Note: We could call TBSystem::RescheduleTimer if we think that deleting
+    // this message changed the time for the next message.
 }
 
 void TBMessageHandler::DeleteAllMessages()
 {
-	while (TBMessage *msg = m_messages.GetFirst())
-		DeleteMessage(msg);
+    while (TBMessage *msg = m_messages.GetFirst())
+        DeleteMessage(msg);
 }
 
 //static
 void TBMessageHandler::ProcessMessages()
 {
-	// Handle delayed messages
-	TBLinkListOf<TBMessageLink>::Iterator iter = g_all_delayed_messages.IterateForward();
-	while (TBMessage *msg = static_cast<TBMessage*>(iter.GetAndStep()))
-	{
-		if (TBSystem::GetTimeMS() >= msg->fire_time_ms)
-		{
-			// Remove from global list
-			g_all_delayed_messages.Remove(msg);
-			// Remove from local list
-			msg->mh->m_messages.Remove(msg);
-
-			msg->mh->OnMessageReceived(msg);
-
-			delete msg;
-		}
-		else
-			break; // Since the list is sorted, all remaining messages should fire later
-	}
-
-	// Handle normal messages
-	iter = g_all_normal_messages.IterateForward();
-	while (TBMessage *msg = static_cast<TBMessage*>(iter.GetAndStep()))
-	{
-		// Remove from global list
-		g_all_normal_messages.Remove(msg);
-		// Remove from local list
-		msg->mh->m_messages.Remove(msg);
-
-		msg->mh->OnMessageReceived(msg);
-
-		delete msg;
-	}
+    // Handle delayed messages
+    TBLinkListOf<TBMessageLink>::Iterator iter = g_all_delayed_messages.IterateForward();
+    while (TBMessage *msg = static_cast<TBMessage*>(iter.GetAndStep()))
+    {
+        if (TBSystem::GetTimeMS() >= msg->fire_time_ms)
+        {
+            // Remove from global list
+            g_all_delayed_messages.Remove(msg);
+            // Remove from local list
+            msg->mh->m_messages.Remove(msg);
+
+            msg->mh->OnMessageReceived(msg);
+
+            delete msg;
+        }
+        else
+            break; // Since the list is sorted, all remaining messages should fire later
+    }
+
+    // Handle normal messages
+    iter = g_all_normal_messages.IterateForward();
+    while (TBMessage *msg = static_cast<TBMessage*>(iter.GetAndStep()))
+    {
+        // Remove from global list
+        g_all_normal_messages.Remove(msg);
+        // Remove from local list
+        msg->mh->m_messages.Remove(msg);
+
+        msg->mh->OnMessageReceived(msg);
+
+        delete msg;
+    }
 }
 
 //static
 double TBMessageHandler::GetNextMessageFireTime()
 {
-	if (g_all_normal_messages.GetFirst())
-		return 0;
+    if (g_all_normal_messages.GetFirst())
+        return 0;
 
-	if (g_all_delayed_messages.GetFirst())
-	{
-		TBMessage *first_delayed_msg = static_cast<TBMessage*>(g_all_delayed_messages.GetFirst());
-		return first_delayed_msg->fire_time_ms;
-	}
+    if (g_all_delayed_messages.GetFirst())
+    {
+        TBMessage *first_delayed_msg = static_cast<TBMessage*>(g_all_delayed_messages.GetFirst());
+        return first_delayed_msg->fire_time_ms;
+    }
 
-	return TB_NOT_SOON;
+    return TB_NOT_SOON;
 }
 
 }; // namespace tb

+ 60 - 60
Source/ThirdParty/TurboBadger/tb_msg.h

@@ -17,7 +17,7 @@ namespace tb {
 class TBMessageHandler;
 
 /** TB_NOT_SOON is returned from TBMessageHandler::GetNextMessageFireTime
-	and means that there is currently no more messages to process. */
+    and means that there is currently no more messages to process. */
 #define TB_NOT_SOON 0xffffffff
 
 /** TBMessageData holds custom data to send with a posted message. */
@@ -25,100 +25,100 @@ class TBMessageHandler;
 class TBMessageData : public TBTypedObject
 {
 public:
-	TBMessageData() {}
-	TBMessageData(int v1, int v2) : v1(v1), v2(v2) {}
-	virtual ~TBMessageData() {}
+    TBMessageData() {}
+    TBMessageData(int v1, int v2) : v1(v1), v2(v2) {}
+    virtual ~TBMessageData() {}
 public:
-	TBValue v1; ///< Use for anything
-	TBValue v2; ///< Use for anything
-	TBID id1;	///< Use for anything
-	TBID id2;	///< Use for anything
+    TBValue v1; ///< Use for anything
+    TBValue v2; ///< Use for anything
+    TBID id1;	///< Use for anything
+    TBID id2;	///< Use for anything
 };
 
 /** TBMessageLink should never be created or subclassed anywhere except in TBMessage.
-	It's only purpose is to add a extra typed link for TBMessage, since it needs to be
-	added in multiple lists. */
+    It's only purpose is to add a extra typed link for TBMessage, since it needs to be
+    added in multiple lists. */
 class TBMessageLink : public TBLinkOf<TBMessageLink> { };
 
 /** TBMessage is a message created and owned by TBMessageHandler.
-	It carries a message id, and may also carry a TBMessageData with
-	additional parameters. */
+    It carries a message id, and may also carry a TBMessageData with
+    additional parameters. */
 
 class TBMessage : public TBLinkOf<TBMessage>, public TBMessageLink
 {
 private:
-	TBMessage(TBID message, TBMessageData *data, double fire_time_ms, TBMessageHandler *mh);
-	~TBMessage();
+    TBMessage(TBID message, TBMessageData *data, double fire_time_ms, TBMessageHandler *mh);
+    ~TBMessage();
 
 public:
-	TBID message;			///< The message id
-	TBMessageData *data;	///< The message data, or nullptr if no data is set
+    TBID message;			///< The message id
+    TBMessageData *data;	///< The message data, or nullptr if no data is set
 
-	/** The time which a delayed message should have fired (0 for non delayed messages) */
-	double GetFireTime() { return fire_time_ms; }
+    /** The time which a delayed message should have fired (0 for non delayed messages) */
+    double GetFireTime() { return fire_time_ms; }
 
 private:
-	friend class TBMessageHandler;
-	double fire_time_ms;
-	TBMessageHandler *mh;
+    friend class TBMessageHandler;
+    double fire_time_ms;
+    TBMessageHandler *mh;
 };
 
 /** TBMessageHandler handles a list of pending messages posted to itself.
-	Messages can be delivered immediately or after a delay.
-	Delayed message are delivered as close as possible to the time they should fire.
-	Immediate messages are put on a queue and delivered as soon as possible, after any delayed
-	messages that has passed their delivery time. This queue is global (among all TBMessageHandlers) */
+    Messages can be delivered immediately or after a delay.
+    Delayed message are delivered as close as possible to the time they should fire.
+    Immediate messages are put on a queue and delivered as soon as possible, after any delayed
+    messages that has passed their delivery time. This queue is global (among all TBMessageHandlers) */
 
 class TBMessageHandler
 {
 public:
-	TBMessageHandler();
-	virtual ~TBMessageHandler();
+    TBMessageHandler();
+    virtual ~TBMessageHandler();
 
-	/** Posts a message to the target after a delay.
-		data may be nullptr if no extra data need to be sent. It will be deleted
-		automatically when the message is deleted. */
-	bool PostMessageDelayed(TBID message, TBMessageData *data, uint32 delay_in_ms);
+    /** Posts a message to the target after a delay.
+        data may be nullptr if no extra data need to be sent. It will be deleted
+        automatically when the message is deleted. */
+    bool PostMessageDelayed(TBID message, TBMessageData *data, uint32 delay_in_ms);
 
-	/** Posts a message to the target at the given time (relative to TBSystem::GetTimeMS()).
-		data may be nullptr if no extra data need to be sent. It will be deleted
-		automatically when the message is deleted. */
-	bool PostMessageOnTime(TBID message, TBMessageData *data, double fire_time);
+    /** Posts a message to the target at the given time (relative to TBSystem::GetTimeMS()).
+        data may be nullptr if no extra data need to be sent. It will be deleted
+        automatically when the message is deleted. */
+    bool PostMessageOnTime(TBID message, TBMessageData *data, double fire_time);
 
-	/** Posts a message to the target.
-		data may be nullptr if no extra data need to be sent. It will be deleted
-		automatically when the message is deleted. */
-	bool PostMessage(TBID message, TBMessageData *data);
+    /** Posts a message to the target.
+        data may be nullptr if no extra data need to be sent. It will be deleted
+        automatically when the message is deleted. */
+    bool PostMessage(TBID message, TBMessageData *data);
 
-	/** Check if this messagehandler has a pending message with the given id.
-		Returns the message if found, or nullptr.
-		If you want to delete the message, call DeleteMessage. */
-	TBMessage *GetMessageByID(TBID message);
+    /** Check if this messagehandler has a pending message with the given id.
+        Returns the message if found, or nullptr.
+        If you want to delete the message, call DeleteMessage. */
+    TBMessage *GetMessageByID(TBID message);
 
-	/** Delete the message from this message handler. */
-	void DeleteMessage(TBMessage *msg);
+    /** Delete the message from this message handler. */
+    void DeleteMessage(TBMessage *msg);
 
-	/** Delete all messages from this message handler. */
-	void DeleteAllMessages();
+    /** Delete all messages from this message handler. */
+    void DeleteAllMessages();
 
-	/** Called when a message is delivered.
+    /** Called when a message is delivered.
 
-		This message won't be found using GetMessageByID. It is already removed from the list.
-		You should not call DeleteMessage on this message. That is done automatically after this method exit. */
-	virtual void OnMessageReceived(TBMessage *msg) {}
+        This message won't be found using GetMessageByID. It is already removed from the list.
+        You should not call DeleteMessage on this message. That is done automatically after this method exit. */
+    virtual void OnMessageReceived(TBMessage *msg) {}
 
-	// == static methods to handle the queue of messages ====================================================
+    // == static methods to handle the queue of messages ====================================================
 
-	/** Process any messages in queue. */
-	static void ProcessMessages();
+    /** Process any messages in queue. */
+    static void ProcessMessages();
 
-	/** Get when the time when ProcessMessages needs to be called again.
-		Always returns 0 if there is nondelayed messages to process, which means it needs to be called asap.
-		If there's only delayed messages to process, it returns the time that the earliest delayed message should be fired.
-		If there's no more messages to process at the moment, it returns TB_NOT_SOON (No call to ProcessMessages is needed). */
-	static double GetNextMessageFireTime();
+    /** Get when the time when ProcessMessages needs to be called again.
+        Always returns 0 if there is nondelayed messages to process, which means it needs to be called asap.
+        If there's only delayed messages to process, it returns the time that the earliest delayed message should be fired.
+        If there's no more messages to process at the moment, it returns TB_NOT_SOON (No call to ProcessMessages is needed). */
+    static double GetNextMessageFireTime();
 private:
-	TBLinkListOf<TBMessage> m_messages;
+    TBLinkListOf<TBMessage> m_messages;
 };
 
 }; // namespace tb

+ 122 - 122
Source/ThirdParty/TurboBadger/tb_node_ref_tree.cpp

@@ -16,164 +16,164 @@ TBLinkListOf<TBNodeRefTree> TBNodeRefTree::s_ref_trees;
 
 TBNodeRefTree::TBNodeRefTree(const char *name) : m_name(name), m_name_id(name)
 {
-	s_ref_trees.AddLast(this);
+    s_ref_trees.AddLast(this);
 }
 
 TBNodeRefTree::~TBNodeRefTree()
 {
-	s_ref_trees.Remove(this);
+    s_ref_trees.Remove(this);
 }
 
 TBValue &TBNodeRefTree::GetValue(const char *request)
 {
-	if (TBNode *node = m_node.GetNodeFollowRef(request))
-		return node->GetValue();
-	TBDebugPrint("TBNodeRefTree::GetValue - Request not found: %s\n", request);
-	static TBValue nullval;
-	return nullval;
+    if (TBNode *node = m_node.GetNodeFollowRef(request))
+        return node->GetValue();
+    TBDebugPrint("TBNodeRefTree::GetValue - Request not found: %s\n", request);
+    static TBValue nullval;
+    return nullval;
 }
 
 //static
 TBValue &TBNodeRefTree::GetValueFromTree(const char *request)
 {
-	assert(*request == '@');
-	TBNode tmp;
-	tmp.GetValue().SetString(request, TBValue::SET_AS_STATIC);
-	TBNode *node = TBNodeRefTree::FollowNodeRef(&tmp);
-	if (node != &tmp)
-		return node->GetValue();
-	static TBValue nullval;
-	return nullval;
+    assert(*request == '@');
+    TBNode tmp;
+    tmp.GetValue().SetString(request, TBValue::SET_AS_STATIC);
+    TBNode *node = TBNodeRefTree::FollowNodeRef(&tmp);
+    if (node != &tmp)
+        return node->GetValue();
+    static TBValue nullval;
+    return nullval;
 }
 
 void TBNodeRefTree::SetValue(const char *request, const TBValue &value)
 {
-	if (TBNode *node = m_node.GetNode(request, TBNode::GET_MISS_POLICY_CREATE))
-	{
-		// FIX: Only invoke the listener if it really changed.
-		node->GetValue().Copy(value);
-		InvokeChangeListenersInternal(request);
-	}
+    if (TBNode *node = m_node.GetNode(request, TBNode::GET_MISS_POLICY_CREATE))
+    {
+        // FIX: Only invoke the listener if it really changed.
+        node->GetValue().Copy(value);
+        InvokeChangeListenersInternal(request);
+    }
 }
 
 void TBNodeRefTree::InvokeChangeListenersInternal(const char *request)
 {
-	TBLinkListOf<TBNodeRefTreeListener>::Iterator iter = m_listeners.IterateForward();
-	while (TBNodeRefTreeListener *listener = iter.GetAndStep())
-		listener->OnDataChanged(this, request);
+    TBLinkListOf<TBNodeRefTreeListener>::Iterator iter = m_listeners.IterateForward();
+    while (TBNodeRefTreeListener *listener = iter.GetAndStep())
+        listener->OnDataChanged(this, request);
 }
 
 //static
 TBNodeRefTree *TBNodeRefTree::GetRefTree(const char *name, int name_len)
 {
-	for (TBNodeRefTree *rt = s_ref_trees.GetFirst(); rt; rt = rt->GetNext())
-		if (strncmp(rt->GetName(), name, name_len) == 0)
-			return rt;
-	return nullptr;
+    for (TBNodeRefTree *rt = s_ref_trees.GetFirst(); rt; rt = rt->GetNext())
+        if (strncmp(rt->GetName(), name, name_len) == 0)
+            return rt;
+    return nullptr;
 }
 
 //static
 TBNode *TBNodeRefTree::FollowNodeRef(TBNode *node)
 {
-	// Detect circular loops by letting this call get a unique id.
-	// Update the id on each visited node and if it's already set,
-	// there's a loop. This cost the storage of id in each TBNode,
-	// and assumes the look up doesn't cause other lookups
-	// recursively.
-	// FIX: Switch to hare and teleporting tortouise?
-	static uint32 s_cycle_id = 0;
-	uint32 cycle_id = ++s_cycle_id;
-	TBNode *start_node = node;
-
-	while (node->GetValue().IsString())
-	{
-		// If not a reference at all, we're done.
-		const char *node_str = node->GetValue().GetString();
-		if (*node_str != '@')
-			break;
-
-		// If there's no tree name and request, we're done. It's probably a language string.
-		const char *name_start = node_str + 1;
-		const char *name_end = TBNode::GetNextNodeSeparator(name_start);
-		if (*name_end == 0)
-			break;
-
-		// We have a "@treename>noderequest" string. Go ahead and look it up.
-		if (TBNodeRefTree *rt = TBNodeRefTree::GetRefTree(name_start, name_end - name_start))
-		{
-			TBNode *next_node = rt->m_node.GetNode(name_end + 1, TBNode::GET_MISS_POLICY_NULL);
-
-			if (!next_node)
-			{
-				TBDebugPrint("TBNodeRefTree::ResolveNode - Node not found on request \"%s\"\n", node_str);
-				break;
-			}
-			node = next_node;
-
-			// Detect circular reference loop.
-			if (node->m_cycle_id != cycle_id)
-				node->m_cycle_id = cycle_id;
-			else
-			{
-				TBDebugPrint("TBNodeRefTree::ResolveNode - Reference loop detected on request \"%s\" from node \"%s\"\n",
-							 node_str, node->GetValue().GetString());
-				return start_node;
-			}
-		}
-		else
-		{
-			TBDebugPrint("TBNodeRefTree::ResolveNode - No tree found for request \"%s\" from node \"%s\"\n",
-						 node_str, node->GetValue().GetString());
-			break;
-		}
-	}
-	return node;
+    // Detect circular loops by letting this call get a unique id.
+    // Update the id on each visited node and if it's already set,
+    // there's a loop. This cost the storage of id in each TBNode,
+    // and assumes the look up doesn't cause other lookups
+    // recursively.
+    // FIX: Switch to hare and teleporting tortouise?
+    static uint32 s_cycle_id = 0;
+    uint32 cycle_id = ++s_cycle_id;
+    TBNode *start_node = node;
+
+    while (node->GetValue().IsString())
+    {
+        // If not a reference at all, we're done.
+        const char *node_str = node->GetValue().GetString();
+        if (*node_str != '@')
+            break;
+
+        // If there's no tree name and request, we're done. It's probably a language string.
+        const char *name_start = node_str + 1;
+        const char *name_end = TBNode::GetNextNodeSeparator(name_start);
+        if (*name_end == 0)
+            break;
+
+        // We have a "@treename>noderequest" string. Go ahead and look it up.
+        if (TBNodeRefTree *rt = TBNodeRefTree::GetRefTree(name_start, name_end - name_start))
+        {
+            TBNode *next_node = rt->m_node.GetNode(name_end + 1, TBNode::GET_MISS_POLICY_NULL);
+
+            if (!next_node)
+            {
+                TBDebugPrint("TBNodeRefTree::ResolveNode - Node not found on request \"%s\"\n", node_str);
+                break;
+            }
+            node = next_node;
+
+            // Detect circular reference loop.
+            if (node->m_cycle_id != cycle_id)
+                node->m_cycle_id = cycle_id;
+            else
+            {
+                TBDebugPrint("TBNodeRefTree::ResolveNode - Reference loop detected on request \"%s\" from node \"%s\"\n",
+                             node_str, node->GetValue().GetString());
+                return start_node;
+            }
+        }
+        else
+        {
+            TBDebugPrint("TBNodeRefTree::ResolveNode - No tree found for request \"%s\" from node \"%s\"\n",
+                         node_str, node->GetValue().GetString());
+            break;
+        }
+    }
+    return node;
 }
 
 //static
 void TBNodeRefTree::ResolveConditions(TBNode *parent_node)
 {
-	bool condition_ret = false;
-	TBNode *node = parent_node->GetFirstChild();
-	while (node)
-	{
-		bool delete_node = false;
-		bool move_children = false;
-		if (strcmp(node->GetName(), "@if") == 0)
-		{
-			condition_ret = node->GetValueFollowRef().GetInt() ? true : false;
-			if (condition_ret)
-				move_children = true;
-			delete_node = true;
-		}
-		else if (strcmp(node->GetName(), "@else") == 0)
-		{
-			condition_ret = !condition_ret;
-			if (condition_ret)
-				move_children = true;
-			delete_node = true;
-		}
-
-		// Make sure we'll skip any nodes added from a conditional branch.
-		TBNode *node_next = node->GetNext();
-
-		if (move_children)
-		{
-			// Resolve the branch first, since we'll skip it.
-			ResolveConditions(node);
-			while (TBNode *content = node->GetLastChild())
-			{
-				node->Remove(content);
-				parent_node->AddAfter(content, node);
-			}
-		}
-
-		if (delete_node)
-			parent_node->Delete(node);
-		else
-			ResolveConditions(node);
-		node = node_next;
-	}
+    bool condition_ret = false;
+    TBNode *node = parent_node->GetFirstChild();
+    while (node)
+    {
+        bool delete_node = false;
+        bool move_children = false;
+        if (strcmp(node->GetName(), "@if") == 0)
+        {
+            condition_ret = node->GetValueFollowRef().GetInt() ? true : false;
+            if (condition_ret)
+                move_children = true;
+            delete_node = true;
+        }
+        else if (strcmp(node->GetName(), "@else") == 0)
+        {
+            condition_ret = !condition_ret;
+            if (condition_ret)
+                move_children = true;
+            delete_node = true;
+        }
+
+        // Make sure we'll skip any nodes added from a conditional branch.
+        TBNode *node_next = node->GetNext();
+
+        if (move_children)
+        {
+            // Resolve the branch first, since we'll skip it.
+            ResolveConditions(node);
+            while (TBNode *content = node->GetLastChild())
+            {
+                node->Remove(content);
+                parent_node->AddAfter(content, node);
+            }
+        }
+
+        if (delete_node)
+            parent_node->Delete(node);
+        else
+            ResolveConditions(node);
+        node = node_next;
+    }
 }
 
 }; // namespace tb

+ 46 - 46
Source/ThirdParty/TurboBadger/tb_node_ref_tree.h

@@ -16,71 +16,71 @@ class TBNode;
 class TBNodeRefTreeListener;
 
 /** TBNodeRefTree is a named TBNode.
-	Nodes under this node may be referenced from other nodes, either when
-	requesting a value (TBNode::GetValueFollowRef), or while parsing the
-	node tree. While parsing, the values can be used for branch conditions
-	or branches of nodes can be included. */
+    Nodes under this node may be referenced from other nodes, either when
+    requesting a value (TBNode::GetValueFollowRef), or while parsing the
+    node tree. While parsing, the values can be used for branch conditions
+    or branches of nodes can be included. */
 class TBNodeRefTree : public TBLinkOf<TBNodeRefTree>
 {
 public:
-	TBNodeRefTree(const char *name);
-	virtual ~TBNodeRefTree();
+    TBNodeRefTree(const char *name);
+    virtual ~TBNodeRefTree();
 
-	const char *GetName() const { return m_name; }
-	const TBID &GetNameID() const { return m_name_id; }
+    const char *GetName() const { return m_name; }
+    const TBID &GetNameID() const { return m_name_id; }
 
-	/** Read the data file. This will *not* invoke any change listener! */
-	bool ReadFile(const char *filename) { return m_node.ReadFile(filename); }
-	void ReadData(const char *data) { m_node.ReadData(data); }
+    /** Read the data file. This will *not* invoke any change listener! */
+    bool ReadFile(const char *filename) { return m_node.ReadFile(filename); }
+    void ReadData(const char *data) { m_node.ReadData(data); }
 
-	/** Add a listener that is invoked on changes in this tree. */
-	void AddListener(TBNodeRefTreeListener *listener) { m_listeners.AddLast(listener); }
+    /** Add a listener that is invoked on changes in this tree. */
+    void AddListener(TBNodeRefTreeListener *listener) { m_listeners.AddLast(listener); }
 
-	/** Remove a change listener from this tree. */
-	void RemoveListener(TBNodeRefTreeListener *listener) { m_listeners.Remove(listener); }
+    /** Remove a change listener from this tree. */
+    void RemoveListener(TBNodeRefTreeListener *listener) { m_listeners.Remove(listener); }
 
-	/** Set the value for the given request and invoke the change listener.
-		Creates the nodes that doesn't exist. */
-	virtual void SetValue(const char *request, const TBValue &value);
+    /** Set the value for the given request and invoke the change listener.
+        Creates the nodes that doesn't exist. */
+    virtual void SetValue(const char *request, const TBValue &value);
 
-	/** Get the value of the given request. Follows references if any.
-		Returns a null value if the request doesn't exist. */
-	virtual TBValue &GetValue(const char *request);
+    /** Get the value of the given request. Follows references if any.
+        Returns a null value if the request doesn't exist. */
+    virtual TBValue &GetValue(const char *request);
 
-	/** Get the value of the given tree name and request (@treename>noderequest).
-		Returns a null value if the given tree or request doesn't exist. */
-	static TBValue &GetValueFromTree(const char *request);
+    /** Get the value of the given tree name and request (@treename>noderequest).
+        Returns a null value if the given tree or request doesn't exist. */
+    static TBValue &GetValueFromTree(const char *request);
 
-	/** Return the tree with the given name, or nullptr if no matching tree exists. */
-	static TBNodeRefTree *GetRefTree(const char *name, int name_len);
+    /** Return the tree with the given name, or nullptr if no matching tree exists. */
+    static TBNodeRefTree *GetRefTree(const char *name, int name_len);
 
-	/** Go through the tree of nodes recursively and include
-		or remove branches depending on any conditions. */
-	static void ResolveConditions(TBNode *parent_node);
+    /** Go through the tree of nodes recursively and include
+        or remove branches depending on any conditions. */
+    static void ResolveConditions(TBNode *parent_node);
 private:
-	friend class TBNode;
-	friend class TBNodeTarget;
-	/** Follow any references to data trees and return the destination node.
-		If there's broken references, the node will be returned. */
-	static TBNode *FollowNodeRef(TBNode *node);
-
-	void InvokeChangeListenersInternal(const char *request);
-	TBNode m_node;
-	TBStr m_name;
-	TBID m_name_id;
-	TBLinkListOf<TBNodeRefTreeListener> m_listeners;
-	static TBLinkListOf<TBNodeRefTree> s_ref_trees;
+    friend class TBNode;
+    friend class TBNodeTarget;
+    /** Follow any references to data trees and return the destination node.
+        If there's broken references, the node will be returned. */
+    static TBNode *FollowNodeRef(TBNode *node);
+
+    void InvokeChangeListenersInternal(const char *request);
+    TBNode m_node;
+    TBStr m_name;
+    TBID m_name_id;
+    TBLinkListOf<TBNodeRefTreeListener> m_listeners;
+    static TBLinkListOf<TBNodeRefTree> s_ref_trees;
 };
 
 /**	TBNodeRefTreeListener receive OnDataChanged when the
-	value of a node in a TBNodeRefTree is changed.
-	FIX: The listener can currently only listen to one tree. */
+    value of a node in a TBNodeRefTree is changed.
+    FIX: The listener can currently only listen to one tree. */
 class TBNodeRefTreeListener : public TBLinkOf<TBNodeRefTreeListener>
 {
 public:
-	/** Called when the value is changed for the given node
-		in the given ref tree. The request is without tree name. */
-	virtual void OnDataChanged(TBNodeRefTree *rt, const char *request) = 0;
+    /** Called when the value is changed for the given node
+        in the given ref tree. The request is without tree name. */
+    virtual void OnDataChanged(TBNodeRefTree *rt, const char *request) = 0;
 };
 
 }; // namespace tb

+ 232 - 232
Source/ThirdParty/TurboBadger/tb_node_tree.cpp

@@ -16,328 +16,328 @@ namespace tb {
 
 TBNode::~TBNode()
 {
-	Clear();
+    Clear();
 }
 
 // static
 TBNode *TBNode::Create(const char *name)
 {
-	TBNode *n = new TBNode;
-	if (!n || !(n->m_name = strdup(name)))
-	{
-		delete n;
-		return nullptr;
-	}
-	return n;
+    TBNode *n = new TBNode;
+    if (!n || !(n->m_name = strdup(name)))
+    {
+        delete n;
+        return nullptr;
+    }
+    return n;
 }
 
 // static
 TBNode *TBNode::Create(const char *name, int name_len)
 {
-	TBNode *n = new TBNode;
-	if (!n || !(n->m_name = (char *) malloc(name_len + 1)))
-	{
-		delete n;
-		return nullptr;
-	}
-	memcpy(n->m_name, name, name_len);
-	n->m_name[name_len] = 0;
-	return n;
+    TBNode *n = new TBNode;
+    if (!n || !(n->m_name = (char *) malloc(name_len + 1)))
+    {
+        delete n;
+        return nullptr;
+    }
+    memcpy(n->m_name, name, name_len);
+    n->m_name[name_len] = 0;
+    return n;
 }
 
 //static
 const char *TBNode::GetNextNodeSeparator(const char *request)
 {
-	while (*request != 0 && *request != '>')
-		request++;
-	return request;
+    while (*request != 0 && *request != '>')
+        request++;
+    return request;
 }
 
 TBNode *TBNode::GetNode(const char *request, GET_MISS_POLICY mp)
 {
-	// Iterate one node deeper for each sub request (non recursive)
-	TBNode *n = this;
-	while (*request && n)
-	{
-		const char *nextend = GetNextNodeSeparator(request);
-		int name_len = nextend - request;
-		TBNode *n_child = n->GetNodeInternal(request, name_len);
-		if (!n_child && mp == GET_MISS_POLICY_CREATE)
-		{
-			n_child = n->Create(request, name_len);
-			if (n_child)
-				n->Add(n_child);
-		}
-		n = n_child;
-		request = *nextend == 0 ? nextend : nextend + 1;
-	}
-	return n;
+    // Iterate one node deeper for each sub request (non recursive)
+    TBNode *n = this;
+    while (*request && n)
+    {
+        const char *nextend = GetNextNodeSeparator(request);
+        int name_len = nextend - request;
+        TBNode *n_child = n->GetNodeInternal(request, name_len);
+        if (!n_child && mp == GET_MISS_POLICY_CREATE)
+        {
+            n_child = n->Create(request, name_len);
+            if (n_child)
+                n->Add(n_child);
+        }
+        n = n_child;
+        request = *nextend == 0 ? nextend : nextend + 1;
+    }
+    return n;
 }
 
 TBNode *TBNode::GetNodeFollowRef(const char *request, GET_MISS_POLICY mp)
 {
-	TBNode *node = GetNode(request, mp);
-	if (node)
-		node = TBNodeRefTree::FollowNodeRef(node);
-	return node;
+    TBNode *node = GetNode(request, mp);
+    if (node)
+        node = TBNodeRefTree::FollowNodeRef(node);
+    return node;
 }
 
 TBNode *TBNode::GetNodeInternal(const char *name, int name_len) const
 {
-	for (TBNode *n = GetFirstChild(); n; n = n->GetNext())
-	{
-		if (strncmp(n->m_name, name, name_len) == 0 && n->m_name[name_len] == 0)
-			return n;
-	}
-	return nullptr;
+    for (TBNode *n = GetFirstChild(); n; n = n->GetNext())
+    {
+        if (strncmp(n->m_name, name, name_len) == 0 && n->m_name[name_len] == 0)
+            return n;
+    }
+    return nullptr;
 }
 
 bool TBNode::CloneChildren(TBNode *source)
 {
-	TBNode *item = source->GetFirstChild();
-	while (item)
-	{
-		TBNode *new_child = Create(item->m_name);
-		if (!new_child)
-			return false;
+    TBNode *item = source->GetFirstChild();
+    while (item)
+    {
+        TBNode *new_child = Create(item->m_name);
+        if (!new_child)
+            return false;
 
-		new_child->m_value.Copy(item->m_value);
-		Add(new_child);
+        new_child->m_value.Copy(item->m_value);
+        Add(new_child);
 
-		if (!new_child->CloneChildren(item))
-			return false;
-		item = item->GetNext();
-	}
-	return true;
+        if (!new_child->CloneChildren(item))
+            return false;
+        item = item->GetNext();
+    }
+    return true;
 }
 
 TBValue &TBNode::GetValueFollowRef()
 {
-	return TBNodeRefTree::FollowNodeRef(this)->GetValue();
+    return TBNodeRefTree::FollowNodeRef(this)->GetValue();
 }
 
 int TBNode::GetValueInt(const char *request, int def)
 {
-	TBNode *n = GetNodeFollowRef(request);
-	return n ? n->m_value.GetInt() : def;
+    TBNode *n = GetNodeFollowRef(request);
+    return n ? n->m_value.GetInt() : def;
 }
 
 float TBNode::GetValueFloat(const char *request, float def)
 {
-	TBNode *n = GetNodeFollowRef(request);
-	return n ? n->m_value.GetFloat() : def;
+    TBNode *n = GetNodeFollowRef(request);
+    return n ? n->m_value.GetFloat() : def;
 }
 
 const char *TBNode::GetValueString(const char *request, const char *def)
 {
-	if (TBNode *node = GetNodeFollowRef(request))
-	{
-		// We might have a language string. Those are not
-		// looked up in GetNode/ResolveNode.
-		if (node->GetValue().IsString())
-		{
-			const char *string = node->GetValue().GetString();
-			if (*string == '@' && *TBNode::GetNextNodeSeparator(string) == 0)
-				string = g_tb_lng->GetString(string + 1);
-			return string;
-		}
-		return node->GetValue().GetString();
-	}
-	return def;
+    if (TBNode *node = GetNodeFollowRef(request))
+    {
+        // We might have a language string. Those are not
+        // looked up in GetNode/ResolveNode.
+        if (node->GetValue().IsString())
+        {
+            const char *string = node->GetValue().GetString();
+            if (*string == '@' && *TBNode::GetNextNodeSeparator(string) == 0)
+                string = g_tb_lng->GetString(string + 1);
+            return string;
+        }
+        return node->GetValue().GetString();
+    }
+    return def;
 }
 
 const char *TBNode::GetValueStringRaw(const char *request, const char *def)
 {
-	TBNode *n = GetNodeFollowRef(request);
-	return n ? n->m_value.GetString() : def;
+    TBNode *n = GetNodeFollowRef(request);
+    return n ? n->m_value.GetString() : def;
 }
 
 class FileParser : public TBParserStream
 {
 public:
-	bool Read(const char *filename, TBParserTarget *target)
-	{
-		f = TBFile::Open(filename, TBFile::MODE_READ);
-		if (!f)
-			return false;
-		TBParser p;
-		TBParser::STATUS status = p.Read(this, target);
-		delete f;
-		return status == TBParser::STATUS_OK ? true : false;
-	}
-	virtual int GetMoreData(char *buf, int buf_len)
-	{
-		return f->Read(buf, 1, buf_len);
-	}
+    bool Read(const char *filename, TBParserTarget *target)
+    {
+        f = TBFile::Open(filename, TBFile::MODE_READ);
+        if (!f)
+            return false;
+        TBParser p;
+        TBParser::STATUS status = p.Read(this, target);
+        delete f;
+        return status == TBParser::STATUS_OK ? true : false;
+    }
+    virtual int GetMoreData(char *buf, int buf_len)
+    {
+        return f->Read(buf, 1, buf_len);
+    }
 private:
-	TBFile *f;
+    TBFile *f;
 };
 
 class DataParser : public TBParserStream
 {
 public:
-	bool Read(const char *data, int data_len, TBParserTarget *target)
-	{
-		m_data = data;
-		m_data_len = data_len;
-		TBParser p;
-		TBParser::STATUS status = p.Read(this, target);
-		return status == TBParser::STATUS_OK ? true : false;
-	}
-	virtual int GetMoreData(char *buf, int buf_len)
-	{
-		int consume = MIN(buf_len, m_data_len);
-		memcpy(buf, m_data, consume);
-		m_data += consume;
-		m_data_len -= consume;
-		return consume;
-	}
+    bool Read(const char *data, int data_len, TBParserTarget *target)
+    {
+        m_data = data;
+        m_data_len = data_len;
+        TBParser p;
+        TBParser::STATUS status = p.Read(this, target);
+        return status == TBParser::STATUS_OK ? true : false;
+    }
+    virtual int GetMoreData(char *buf, int buf_len)
+    {
+        int consume = MIN(buf_len, m_data_len);
+        memcpy(buf, m_data, consume);
+        m_data += consume;
+        m_data_len -= consume;
+        return consume;
+    }
 private:
-	const char *m_data;
-	int m_data_len;
+    const char *m_data;
+    int m_data_len;
 };
 
 class TBNodeTarget : public TBParserTarget
 {
 public:
-	TBNodeTarget(TBNode *root, const char *filename)
-	{
-		m_root_node = m_target_node = root;
-		m_filename = filename;
-	}
-	virtual void OnError(int line_nr, const char *error)
-	{
+    TBNodeTarget(TBNode *root, const char *filename)
+    {
+        m_root_node = m_target_node = root;
+        m_filename = filename;
+    }
+    virtual void OnError(int line_nr, const char *error)
+    {
 #ifdef TB_RUNTIME_DEBUG_INFO
-		TBStr err;
-		err.SetFormatted("%s(%d):Parse error: %s\n", m_filename, line_nr, error);
-		TBDebugOut(err);
+        TBStr err;
+        err.SetFormatted("%s(%d):Parse error: %s\n", m_filename, line_nr, error);
+        TBDebugOut(err);
 #endif // TB_RUNTIME_DEBUG_INFO
-	}
-	virtual void OnComment(int line_nr, const char *comment)
-	{
-	}
-	virtual void OnToken(int line_nr, const char *name, TBValue &value)
-	{
-		if (!m_target_node)
-			return;
-		if (strcmp(name, "@file") == 0)
-			IncludeFile(line_nr, value.GetString());
-		else if (strcmp(name, "@include") == 0)
-			IncludeRef(line_nr, value.GetString());
-		else if (TBNode *n = TBNode::Create(name))
-		{
-			n->m_value.TakeOver(value);
-			m_target_node->Add(n);
-		}
-	}
-	virtual void Enter()
-	{
-		if (m_target_node)
-			m_target_node = m_target_node->GetLastChild();
-	}
-	virtual void Leave()
-	{
-		assert(m_target_node != m_root_node);
-		if (m_target_node)
-			m_target_node = m_target_node->m_parent;
-	}
-	void IncludeFile(int line_nr, const char *filename)
-	{
-		// Read the included file into a new TBNode and then
-		// move all the children to m_target_node.
-		TBTempBuffer include_filename;
-		include_filename.AppendPath(m_filename);
-		include_filename.AppendString(filename);
-		TBNode content;
-		if (content.ReadFile(include_filename.GetData()))
-		{
-			while (TBNode *content_n = content.GetFirstChild())
-			{
-				content.Remove(content_n);
-				m_target_node->Add(content_n);
-			}
-		}
-		else
-		{
-			TBStr err;
-			err.SetFormatted("Referenced file \"%s\" was not found!", include_filename.GetData());
-			OnError(line_nr, err);
-		}
-	}
-	void IncludeRef(int line_nr, const char *refstr)
-	{
-		TBNode *refnode = nullptr;
-		if (*refstr == '@')
-		{
-			TBNode tmp;
-			tmp.GetValue().SetString(refstr, TBValue::SET_AS_STATIC);
-			refnode = TBNodeRefTree::FollowNodeRef(&tmp);
-		}
-		else // Local look-up
-		{
-			// Note: If we read to a target node that already contains
-			//       nodes, we might look up nodes that's already there
-			//       instead of new nodes.
-			refnode = m_root_node->GetNode(refstr, TBNode::GET_MISS_POLICY_NULL);
+    }
+    virtual void OnComment(int line_nr, const char *comment)
+    {
+    }
+    virtual void OnToken(int line_nr, const char *name, TBValue &value)
+    {
+        if (!m_target_node)
+            return;
+        if (strcmp(name, "@file") == 0)
+            IncludeFile(line_nr, value.GetString());
+        else if (strcmp(name, "@include") == 0)
+            IncludeRef(line_nr, value.GetString());
+        else if (TBNode *n = TBNode::Create(name))
+        {
+            n->m_value.TakeOver(value);
+            m_target_node->Add(n);
+        }
+    }
+    virtual void Enter()
+    {
+        if (m_target_node)
+            m_target_node = m_target_node->GetLastChild();
+    }
+    virtual void Leave()
+    {
+        assert(m_target_node != m_root_node);
+        if (m_target_node)
+            m_target_node = m_target_node->m_parent;
+    }
+    void IncludeFile(int line_nr, const char *filename)
+    {
+        // Read the included file into a new TBNode and then
+        // move all the children to m_target_node.
+        TBTempBuffer include_filename;
+        include_filename.AppendPath(m_filename);
+        include_filename.AppendString(filename);
+        TBNode content;
+        if (content.ReadFile(include_filename.GetData()))
+        {
+            while (TBNode *content_n = content.GetFirstChild())
+            {
+                content.Remove(content_n);
+                m_target_node->Add(content_n);
+            }
+        }
+        else
+        {
+            TBStr err;
+            err.SetFormatted("Referenced file \"%s\" was not found!", include_filename.GetData());
+            OnError(line_nr, err);
+        }
+    }
+    void IncludeRef(int line_nr, const char *refstr)
+    {
+        TBNode *refnode = nullptr;
+        if (*refstr == '@')
+        {
+            TBNode tmp;
+            tmp.GetValue().SetString(refstr, TBValue::SET_AS_STATIC);
+            refnode = TBNodeRefTree::FollowNodeRef(&tmp);
+        }
+        else // Local look-up
+        {
+            // Note: If we read to a target node that already contains
+            //       nodes, we might look up nodes that's already there
+            //       instead of new nodes.
+            refnode = m_root_node->GetNode(refstr, TBNode::GET_MISS_POLICY_NULL);
 
-			// Detect cycles
-			TBNode *cycle_detection = m_target_node;
-			while (cycle_detection && refnode)
-			{
-				if (cycle_detection == refnode)
-					refnode = nullptr; // We have a cycle, so just fail the inclusion.
-				cycle_detection = cycle_detection->GetParent();
-			}
-		}
-		if (refnode)
-			m_target_node->CloneChildren(refnode);
-		else
-		{
-			TBStr err;
-			err.SetFormatted("Include \"%s\" was not found!", refstr);
-			OnError(line_nr, err);
-		}
-	}
+            // Detect cycles
+            TBNode *cycle_detection = m_target_node;
+            while (cycle_detection && refnode)
+            {
+                if (cycle_detection == refnode)
+                    refnode = nullptr; // We have a cycle, so just fail the inclusion.
+                cycle_detection = cycle_detection->GetParent();
+            }
+        }
+        if (refnode)
+            m_target_node->CloneChildren(refnode);
+        else
+        {
+            TBStr err;
+            err.SetFormatted("Include \"%s\" was not found!", refstr);
+            OnError(line_nr, err);
+        }
+    }
 private:
-	TBNode *m_root_node;
-	TBNode *m_target_node;
-	const char *m_filename;
+    TBNode *m_root_node;
+    TBNode *m_target_node;
+    const char *m_filename;
 };
 
 bool TBNode::ReadFile(const char *filename, TB_NODE_READ_FLAGS flags)
 {
-	if (!(flags & TB_NODE_READ_FLAGS_APPEND))
-		Clear();
-	FileParser p;
-	TBNodeTarget t(this, filename);
-	if (p.Read(filename, &t))
-	{
-		TBNodeRefTree::ResolveConditions(this);
-		return true;
-	}
-	return false;
+    if (!(flags & TB_NODE_READ_FLAGS_APPEND))
+        Clear();
+    FileParser p;
+    TBNodeTarget t(this, filename);
+    if (p.Read(filename, &t))
+    {
+        TBNodeRefTree::ResolveConditions(this);
+        return true;
+    }
+    return false;
 }
 
 void TBNode::ReadData(const char *data, TB_NODE_READ_FLAGS flags)
 {
-	ReadData(data, strlen(data), flags);
+    ReadData(data, strlen(data), flags);
 }
 
 void TBNode::ReadData(const char *data, int data_len, TB_NODE_READ_FLAGS flags)
 {
-	if (!(flags & TB_NODE_READ_FLAGS_APPEND))
-		Clear();
-	DataParser p;
-	TBNodeTarget t(this, "{data}");
-	p.Read(data, data_len, &t);
-	TBNodeRefTree::ResolveConditions(this);
+    if (!(flags & TB_NODE_READ_FLAGS_APPEND))
+        Clear();
+    DataParser p;
+    TBNodeTarget t(this, "{data}");
+    p.Read(data, data_len, &t);
+    TBNodeRefTree::ResolveConditions(this);
 }
 
 void TBNode::Clear()
 {
-	free(m_name);
-	m_name = nullptr;
-	m_children.DeleteAll();
+    free(m_name);
+    m_name = nullptr;
+    m_children.DeleteAll();
 }
 
 }; // namespace tb

+ 88 - 88
Source/ThirdParty/TurboBadger/tb_node_tree.h

@@ -12,128 +12,128 @@
 namespace tb {
 
 enum TB_NODE_READ_FLAGS {
-	TB_NODE_READ_FLAGS_NONE	= 0,
-	/** Read nodes without clearing first. Can be used to append
-		data from multiple sources, or inject dependencies. */
-	TB_NODE_READ_FLAGS_APPEND = 1,
+    TB_NODE_READ_FLAGS_NONE	= 0,
+    /** Read nodes without clearing first. Can be used to append
+        data from multiple sources, or inject dependencies. */
+    TB_NODE_READ_FLAGS_APPEND = 1,
 };
 MAKE_ENUM_FLAG_COMBO(TB_NODE_READ_FLAGS);
 
 /** TBNode is a tree node with a string name and a value (TBValue).
-	It may have a parent TBNode and child TBNodes.
+    It may have a parent TBNode and child TBNodes.
 
-	Getting the value of this node or any child, may optionally follow
-	references to nodes in any existing TBNodeRefTree (by name).
+    Getting the value of this node or any child, may optionally follow
+    references to nodes in any existing TBNodeRefTree (by name).
 
-	During ReadFile/ReadData, it may also select which branches to include
-	or exclude conditionally by lookup up values in TBNodeRefTree. */
+    During ReadFile/ReadData, it may also select which branches to include
+    or exclude conditionally by lookup up values in TBNodeRefTree. */
 class TBNode : public TBLinkOf<TBNode>
 {
 public:
-	TBNode() : m_name(nullptr), m_parent(nullptr), m_cycle_id(0) {}
-	~TBNode();
+    TBNode() : m_name(nullptr), m_parent(nullptr), m_cycle_id(0) {}
+    ~TBNode();
 
-	/** Create a new node with the given name. */
-	static TBNode *Create(const char *name);
+    /** Create a new node with the given name. */
+    static TBNode *Create(const char *name);
 
-	/** Read a tree of nodes from file into this node. Returns true on success. */
-	bool ReadFile(const char *filename, TB_NODE_READ_FLAGS flags = TB_NODE_READ_FLAGS_NONE);
+    /** Read a tree of nodes from file into this node. Returns true on success. */
+    bool ReadFile(const char *filename, TB_NODE_READ_FLAGS flags = TB_NODE_READ_FLAGS_NONE);
 
-	/** Read a tree of nodes from a null terminated string buffer. */
-	void ReadData(const char *data, TB_NODE_READ_FLAGS flags = TB_NODE_READ_FLAGS_NONE);
+    /** Read a tree of nodes from a null terminated string buffer. */
+    void ReadData(const char *data, TB_NODE_READ_FLAGS flags = TB_NODE_READ_FLAGS_NONE);
 
-	/** Read a tree of nodes from a buffer with a known length. */
-	void ReadData(const char *data, int data_len, TB_NODE_READ_FLAGS flags = TB_NODE_READ_FLAGS_NONE);
+    /** Read a tree of nodes from a buffer with a known length. */
+    void ReadData(const char *data, int data_len, TB_NODE_READ_FLAGS flags = TB_NODE_READ_FLAGS_NONE);
 
-	/** Clear the contens of this node. */
-	void Clear();
+    /** Clear the contens of this node. */
+    void Clear();
 
-	// FIX: Add write support!
-	//bool WriteFile(const char *filename);
+    // FIX: Add write support!
+    //bool WriteFile(const char *filename);
 
-	/** Add node as child to this node. */
-	void Add(TBNode *n) { m_children.AddLast(n); n->m_parent = this; }
+    /** Add node as child to this node. */
+    void Add(TBNode *n) { m_children.AddLast(n); n->m_parent = this; }
 
-	/** Add node before the reference node (which must be a child to this node). */
-	void AddBefore(TBNode *n, TBNode *reference) { m_children.AddBefore(n, reference); n->m_parent = this; }
+    /** Add node before the reference node (which must be a child to this node). */
+    void AddBefore(TBNode *n, TBNode *reference) { m_children.AddBefore(n, reference); n->m_parent = this; }
 
-	/** Add node after the reference node (which must be a child to this node). */
-	void AddAfter(TBNode *n, TBNode *reference) { m_children.AddAfter(n, reference); n->m_parent = this; }
+    /** Add node after the reference node (which must be a child to this node). */
+    void AddAfter(TBNode *n, TBNode *reference) { m_children.AddAfter(n, reference); n->m_parent = this; }
 
-	/** Remove child node n from this node. */
-	void Remove(TBNode *n) { m_children.Remove(n); n->m_parent = nullptr; }
+    /** Remove child node n from this node. */
+    void Remove(TBNode *n) { m_children.Remove(n); n->m_parent = nullptr; }
 
-	/** Remove and delete child node n from this node. */
-	void Delete(TBNode *n) { m_children.Delete(n); }
+    /** Remove and delete child node n from this node. */
+    void Delete(TBNode *n) { m_children.Delete(n); }
 
-	/** Create duplicates of all items in source and add them to this node.
-		Note: Nodes does not replace existing nodes with the same name. Cloned nodes
-		are added after any existing nodes. */
-	bool CloneChildren(TBNode *source);
+    /** Create duplicates of all items in source and add them to this node.
+        Note: Nodes does not replace existing nodes with the same name. Cloned nodes
+        are added after any existing nodes. */
+    bool CloneChildren(TBNode *source);
 
-	enum GET_MISS_POLICY {
-		/** GetNode will return nullptr if the node doesn't exist. */
-		GET_MISS_POLICY_NULL,
-		/** GetNode will create all missing nodes for the request. */
-		GET_MISS_POLICY_CREATE
-	};
+    enum GET_MISS_POLICY {
+        /** GetNode will return nullptr if the node doesn't exist. */
+        GET_MISS_POLICY_NULL,
+        /** GetNode will create all missing nodes for the request. */
+        GET_MISS_POLICY_CREATE
+    };
 
-	/** Get a node from the given request.
-		If the node doesn't exist, it will either return nullptr or create
-		missing nodes, depending on the miss policy.
-		It can find nodes in children as well. Names are separated by a ">".
+    /** Get a node from the given request.
+        If the node doesn't exist, it will either return nullptr or create
+        missing nodes, depending on the miss policy.
+        It can find nodes in children as well. Names are separated by a ">".
 
-		Ex: GetNode("dishes>pizza>special>batman") */
-	TBNode *GetNode(const char *request, GET_MISS_POLICY mp = GET_MISS_POLICY_NULL);
+        Ex: GetNode("dishes>pizza>special>batman") */
+    TBNode *GetNode(const char *request, GET_MISS_POLICY mp = GET_MISS_POLICY_NULL);
 
-	/** Returns the name of this node. */
-	const char *GetName() const { return m_name; }
+    /** Returns the name of this node. */
+    const char *GetName() const { return m_name; }
 
-	/** Returns the value of this node. */
-	TBValue &GetValue() { return m_value; }
+    /** Returns the value of this node. */
+    TBValue &GetValue() { return m_value; }
 
-	/** Returns the value of this node.
-		Will follow eventual references to TBNodeRefTree. */
-	TBValue &GetValueFollowRef();
+    /** Returns the value of this node.
+        Will follow eventual references to TBNodeRefTree. */
+    TBValue &GetValueFollowRef();
 
-	/** Get a value from the given request as an integer.
-		Will follow eventual references to TBNodeRefTree.
-		If the value is not specified, it returns the default value (def). */
-	int GetValueInt(const char *request, int def);
+    /** Get a value from the given request as an integer.
+        Will follow eventual references to TBNodeRefTree.
+        If the value is not specified, it returns the default value (def). */
+    int GetValueInt(const char *request, int def);
 
-	/** Get a value from the given request as an float.
-		Will follow eventual references to TBNodeRefTree.
-		If the value is not specified, it returns the default value (def). */
-	float GetValueFloat(const char *request, float def);
+    /** Get a value from the given request as an float.
+        Will follow eventual references to TBNodeRefTree.
+        If the value is not specified, it returns the default value (def). */
+    float GetValueFloat(const char *request, float def);
 
-	/** Get a value from the given request as an string.
-		Will follow eventual references to TBNodeRefTree.
-		Will also return any referenced language string.
-		If the value is not specified, it returns the default value (def). */
-	const char *GetValueString(const char *request, const char *def);
+    /** Get a value from the given request as an string.
+        Will follow eventual references to TBNodeRefTree.
+        Will also return any referenced language string.
+        If the value is not specified, it returns the default value (def). */
+    const char *GetValueString(const char *request, const char *def);
 
-	/** Same as GetValueString, but won't look up language string references. */
-	const char *GetValueStringRaw(const char *request, const char *def);
+    /** Same as GetValueString, but won't look up language string references. */
+    const char *GetValueStringRaw(const char *request, const char *def);
 
-	/** Get the next position in request that is a sub node separator,
-		or the end of the string. */
-	static const char *GetNextNodeSeparator(const char *request);
+    /** Get the next position in request that is a sub node separator,
+        or the end of the string. */
+    static const char *GetNextNodeSeparator(const char *request);
 
-	inline TBNode *GetParent() const { return m_parent; }
-	inline TBNode *GetFirstChild() const { return m_children.GetFirst(); }
-	inline TBNode *GetLastChild() const { return m_children.GetLast(); }
+    inline TBNode *GetParent() const { return m_parent; }
+    inline TBNode *GetFirstChild() const { return m_children.GetFirst(); }
+    inline TBNode *GetLastChild() const { return m_children.GetLast(); }
 private:
-friend class TBNodeTarget;
-friend class TBNodeRefTree;
-	TBNode *GetNodeFollowRef(const char *request,
-							GET_MISS_POLICY mp = GET_MISS_POLICY_NULL);
-	TBNode *GetNodeInternal(const char *name, int name_len) const;
-	static TBNode *Create(const char *name, int name_len);
-	char *m_name;
-	TBValue m_value;
-	TBLinkListOf<TBNode> m_children;
-	TBNode *m_parent;
-	uint32 m_cycle_id;	///< Used to detect circular references.
+    friend class TBNodeTarget;
+    friend class TBNodeRefTree;
+    TBNode *GetNodeFollowRef(const char *request,
+                             GET_MISS_POLICY mp = GET_MISS_POLICY_NULL);
+    TBNode *GetNodeInternal(const char *name, int name_len) const;
+    static TBNode *Create(const char *name, int name_len);
+    char *m_name;
+    TBValue m_value;
+    TBLinkListOf<TBNode> m_children;
+    TBNode *m_parent;
+    uint32 m_cycle_id;	///< Used to detect circular references.
 };
 
 }; // namespace tb

+ 21 - 21
Source/ThirdParty/TurboBadger/tb_object.h

@@ -14,48 +14,48 @@ namespace tb {
 typedef void* TB_TYPE_ID;
 
 /*  TBTypedObject implements custom RTTI so we can get type safe casts,
-	and the class name at runtime.
+    and the class name at runtime.
 
-	Each subclass is expected to define TBOBJECT_SUBCLASS to get the
-	necessary implementations, instead of implementing those manually. */
+    Each subclass is expected to define TBOBJECT_SUBCLASS to get the
+    necessary implementations, instead of implementing those manually. */
 class TBTypedObject
 {
 public:
-	virtual ~TBTypedObject() {}
+    virtual ~TBTypedObject() {}
 
-	/** A static template method that returns a unique id for each type. */
-	template<class T> static TB_TYPE_ID GetTypeId() { static char type_id; return &type_id; }
+    /** A static template method that returns a unique id for each type. */
+    template<class T> static TB_TYPE_ID GetTypeId() { static char type_id; return &type_id; }
 
-	/** Returns true if the class or the base class matches the type id */
-	virtual bool IsOfTypeId(const TB_TYPE_ID type_id) const { return type_id == GetTypeId<TBTypedObject>(); }
+    /** Returns true if the class or the base class matches the type id */
+    virtual bool IsOfTypeId(const TB_TYPE_ID type_id) const { return type_id == GetTypeId<TBTypedObject>(); }
 
-	/** Returns this object as the given type or nullptr if it's not that type. */
-	template<class T> T *SafeCastTo() const { return (T*) (IsOfTypeId(GetTypeId<T>()) ? this : nullptr); }
+    /** Returns this object as the given type or nullptr if it's not that type. */
+    template<class T> T *SafeCastTo() const { return (T*) (IsOfTypeId(GetTypeId<T>()) ? this : nullptr); }
 
-	/** Return true if this object can safely be casted to the given type. */
-	template<class T> bool IsOfType() const { return SafeCastTo<T>() ? true : false; }
+    /** Return true if this object can safely be casted to the given type. */
+    template<class T> bool IsOfType() const { return SafeCastTo<T>() ? true : false; }
 
-	/** Get the classname of the object. */
-	virtual const char *GetClassName() const { return "TBTypedObject"; }
+    /** Get the classname of the object. */
+    virtual const char *GetClassName() const { return "TBTypedObject"; }
 };
 
 /** Returns the given object as the given type, or nullptr if it's not that type
-	or if the object is nullptr. */
+    or if the object is nullptr. */
 template<class T> T *TBSafeCast(TBTypedObject *obj) {
-	return obj ? obj->SafeCastTo<T>() : nullptr;
+    return obj ? obj->SafeCastTo<T>() : nullptr;
 }
 
 /** Returns the given object as the given type, or nullptr if it's not that type
-	or if the object is nullptr. */
+    or if the object is nullptr. */
 template<class T> const T *TBSafeCast(const TBTypedObject *obj) {
-	return obj ? obj->SafeCastTo<T>() : nullptr;
+    return obj ? obj->SafeCastTo<T>() : nullptr;
 }
 
 /** Implement the methods for safe typecasting without requiring RTTI. */
 #define TBOBJECT_SUBCLASS(clazz, baseclazz) \
-	virtual const char *GetClassName() const { return #clazz; } \
-	virtual bool IsOfTypeId(const TB_TYPE_ID type_id) const \
-		{ return GetTypeId<clazz>() == type_id ? true : baseclazz::IsOfTypeId(type_id); }
+    virtual const char *GetClassName() const { return #clazz; } \
+    virtual bool IsOfTypeId(const TB_TYPE_ID type_id) const \
+{ return GetTypeId<clazz>() == type_id ? true : baseclazz::IsOfTypeId(type_id); }
 
 }; // namespace tb
 

+ 84 - 84
Source/ThirdParty/TurboBadger/tb_popup_window.cpp

@@ -12,103 +12,103 @@ namespace tb {
 
 TBRect TBPopupAlignment::GetAlignedRect(TBWidget *popup, TBWidget *target) const
 {
-	TBWidget *root = target->GetParentRoot();
-
-	SizeConstraints sc(root->GetRect().w, root->GetRect().h);
-
-	PreferredSize ps = popup->GetPreferredSize(sc);
-
-	// Amount of pixels that should be avoided if the target rect needs to be moved.
-	int avoid_w = 0, avoid_h = 0;
-
-	int x = 0, y = 0;
-	int w = MIN(ps.pref_w, root->GetRect().w);
-	int h = MIN(ps.pref_h, root->GetRect().h);
-
-	if (pos_in_root.x != UNSPECIFIED &&
-		pos_in_root.y != UNSPECIFIED)
-	{
-		x = pos_in_root.x;
-		y = pos_in_root.y;
-		avoid_w = pos_offset.x;
-		avoid_h = pos_offset.y;
-		// Make sure it's moved into view horizontally
-		if (align == TB_ALIGN_TOP || align == TB_ALIGN_BOTTOM)
-			x = Clamp(x, 0, root->GetRect().w - w);
-	}
-	else
-	{
-		target->ConvertToRoot(x, y);
-
-		if (align == TB_ALIGN_TOP || align == TB_ALIGN_BOTTOM)
-		{
-			if (expand_to_target_width)
-				w = MAX(w, target->GetRect().w);
-
-			// If the menu is aligned top or bottom, limit its height to the worst case available height.
-			// Being in the center of the root, that is half the root height minus the target rect.
-			h = MIN(h, root->GetRect().h / 2 - target->GetRect().h);
-		}
-		avoid_w = target->GetRect().w;
-		avoid_h = target->GetRect().h;
-	}
-
-	if (align == TB_ALIGN_BOTTOM)
-		y = y + avoid_h + h > root->GetRect().h ? y - h : y + avoid_h;
-	else if (align == TB_ALIGN_TOP)
-		y = y - h < 0 ? y + avoid_h : y - h;
-	else if (align == TB_ALIGN_RIGHT)
-	{
-		x = x + avoid_w + w > root->GetRect().w ? x - w : x + avoid_w;
-		y = MIN(y, root->GetRect().h - h);
-	}
-	else // if (align == TB_ALIGN_LEFT)
-	{
-		x = x - w < 0 ? x + avoid_w : x - w;
-		y = MIN(y, root->GetRect().h - h);
-	}
-	return TBRect(x, y, w, h);
+    TBWidget *root = target->GetParentRoot();
+
+    SizeConstraints sc(root->GetRect().w, root->GetRect().h);
+
+    PreferredSize ps = popup->GetPreferredSize(sc);
+
+    // Amount of pixels that should be avoided if the target rect needs to be moved.
+    int avoid_w = 0, avoid_h = 0;
+
+    int x = 0, y = 0;
+    int w = MIN(ps.pref_w, root->GetRect().w);
+    int h = MIN(ps.pref_h, root->GetRect().h);
+
+    if (pos_in_root.x != UNSPECIFIED &&
+            pos_in_root.y != UNSPECIFIED)
+    {
+        x = pos_in_root.x;
+        y = pos_in_root.y;
+        avoid_w = pos_offset.x;
+        avoid_h = pos_offset.y;
+        // Make sure it's moved into view horizontally
+        if (align == TB_ALIGN_TOP || align == TB_ALIGN_BOTTOM)
+            x = Clamp(x, 0, root->GetRect().w - w);
+    }
+    else
+    {
+        target->ConvertToRoot(x, y);
+
+        if (align == TB_ALIGN_TOP || align == TB_ALIGN_BOTTOM)
+        {
+            if (expand_to_target_width)
+                w = MAX(w, target->GetRect().w);
+
+            // If the menu is aligned top or bottom, limit its height to the worst case available height.
+            // Being in the center of the root, that is half the root height minus the target rect.
+            h = MIN(h, root->GetRect().h / 2 - target->GetRect().h);
+        }
+        avoid_w = target->GetRect().w;
+        avoid_h = target->GetRect().h;
+    }
+
+    if (align == TB_ALIGN_BOTTOM)
+        y = y + avoid_h + h > root->GetRect().h ? y - h : y + avoid_h;
+    else if (align == TB_ALIGN_TOP)
+        y = y - h < 0 ? y + avoid_h : y - h;
+    else if (align == TB_ALIGN_RIGHT)
+    {
+        x = x + avoid_w + w > root->GetRect().w ? x - w : x + avoid_w;
+        y = MIN(y, root->GetRect().h - h);
+    }
+    else // if (align == TB_ALIGN_LEFT)
+    {
+        x = x - w < 0 ? x + avoid_w : x - w;
+        y = MIN(y, root->GetRect().h - h);
+    }
+    return TBRect(x, y, w, h);
 }
 
 // == TBPopupWindow =========================================================================================
 
 TBPopupWindow::TBPopupWindow(TBWidget *target)
-	: m_target(target)
+    : m_target(target)
 {
-	TBWidgetListener::AddGlobalListener(this);
-	SetSkinBg(TBIDC("TBPopupWindow"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
-	SetSettings(WINDOW_SETTINGS_NONE);
+    TBWidgetListener::AddGlobalListener(this);
+    SetSkinBg(TBIDC("TBPopupWindow"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
+    SetSettings(WINDOW_SETTINGS_NONE);
 }
 
 TBPopupWindow::~TBPopupWindow()
 {
-	TBWidgetListener::RemoveGlobalListener(this);
+    TBWidgetListener::RemoveGlobalListener(this);
 }
 
 bool TBPopupWindow::Show(const TBPopupAlignment &alignment)
 {
-	// Calculate and set a good size for the popup window
-	SetRect(alignment.GetAlignedRect(this, m_target.Get()));
+    // Calculate and set a good size for the popup window
+    SetRect(alignment.GetAlignedRect(this, m_target.Get()));
 
-	TBWidget *root = m_target.Get()->GetParentRoot();
-	root->AddChild(this);
-	return true;
+    TBWidget *root = m_target.Get()->GetParentRoot();
+    root->AddChild(this);
+    return true;
 }
 
 bool TBPopupWindow::OnEvent(const TBWidgetEvent &ev)
 {
-	if (ev.type == EVENT_TYPE_KEY_DOWN && ev.special_key == TB_KEY_ESC)
-	{
-		Close();
-		return true;
-	}
-	return TBWindow::OnEvent(ev);
+    if (ev.type == EVENT_TYPE_KEY_DOWN && ev.special_key == TB_KEY_ESC)
+    {
+        Close();
+        return true;
+    }
+    return TBWindow::OnEvent(ev);
 }
 
 void TBPopupWindow::OnWidgetFocusChanged(TBWidget *widget, bool focused)
 {
-	if (focused && !IsEventDestinationFor(widget))
-		Close();
+    if (focused && !IsEventDestinationFor(widget))
+        Close();
 }
 
 bool TBPopupWindow::OnWidgetInvokeEvent(TBWidget *widget, const TBWidgetEvent &ev)
@@ -117,24 +117,24 @@ bool TBPopupWindow::OnWidgetInvokeEvent(TBWidget *widget, const TBWidgetEvent &e
         Close();
 
     if ((ev.type == EVENT_TYPE_POINTER_DOWN || ev.type == EVENT_TYPE_CONTEXT_MENU) &&
-		!IsEventDestinationFor(ev.target))
-		Close();
-	return false;
+            !IsEventDestinationFor(ev.target))
+        Close();
+    return false;
 }
 
 void TBPopupWindow::OnWidgetDelete(TBWidget *widget)
 {
-	// If the target widget is deleted, close!
-	if (!m_target.Get())
-		Close();
+    // If the target widget is deleted, close!
+    if (!m_target.Get())
+        Close();
 }
 
 bool TBPopupWindow::OnWidgetDying(TBWidget *widget)
 {
-	// If the target widget or an ancestor of it is dying, close!
-	if (widget == m_target.Get() || widget->IsAncestorOf(m_target.Get()))
-		Close();
-	return false;
+    // If the target widget or an ancestor of it is dying, close!
+    if (widget == m_target.Get() || widget->IsAncestorOf(m_target.Get()))
+        Close();
+    return false;
 }
 
 }; // namespace tb

+ 51 - 51
Source/ThirdParty/TurboBadger/tb_popup_window.h

@@ -12,73 +12,73 @@
 namespace tb {
 
 /** TBPopupAlignment describes the preferred alignment of a popup
-	relative to a target widget or a given point.
+    relative to a target widget or a given point.
 
-	It calculates the rect to be used to match these preferences
-	for any given popup and target. */
+    It calculates the rect to be used to match these preferences
+    for any given popup and target. */
 class TBPopupAlignment
 {
 public:
-	static const int UNSPECIFIED = TB_INVALID_DIMENSION;
-
-	/** Align relative to the target widget. */
-	TBPopupAlignment(TB_ALIGN align = TB_ALIGN_BOTTOM)
-		: pos_in_root(UNSPECIFIED, UNSPECIFIED)
-		, align(align)
-		, expand_to_target_width(true) {}
-
-	/** Align relative to the given position (coordinates relative to the root widget). */
-	TBPopupAlignment(const TBPoint &pos_in_root, TB_ALIGN align = TB_ALIGN_BOTTOM)
-		: pos_in_root(pos_in_root)
-		, align(align)
-		, expand_to_target_width(true) {}
-
-	/** Align relative to the given position (coordinates relative to the root widget).
-		Applies an additional offset. */
-	TBPopupAlignment(const TBPoint &pos_in_root, const TBPoint &pos_offset)
-		: pos_in_root(pos_in_root)
-		, pos_offset(pos_offset)
-		, align(TB_ALIGN_BOTTOM)
-		, expand_to_target_width(true) {}
-
-	/** Calculate a good rect for the given popup window using its preferred size and
-		the preferred alignment information stored in this class. */
-	TBRect GetAlignedRect(TBWidget *popup, TBWidget *target) const;
-
-	TBPoint pos_in_root;
-	TBPoint pos_offset;
-
-	TB_ALIGN align;
-	/** If true, the width of the popup will be at least the same as the target widget
-		if the alignment is TB_ALIGN_TOP or TB_ALIGN_BOTTOM. */
-	bool expand_to_target_width;
+    static const int UNSPECIFIED = TB_INVALID_DIMENSION;
+
+    /** Align relative to the target widget. */
+    TBPopupAlignment(TB_ALIGN align = TB_ALIGN_BOTTOM)
+        : pos_in_root(UNSPECIFIED, UNSPECIFIED)
+        , align(align)
+        , expand_to_target_width(true) {}
+
+    /** Align relative to the given position (coordinates relative to the root widget). */
+    TBPopupAlignment(const TBPoint &pos_in_root, TB_ALIGN align = TB_ALIGN_BOTTOM)
+        : pos_in_root(pos_in_root)
+        , align(align)
+        , expand_to_target_width(true) {}
+
+    /** Align relative to the given position (coordinates relative to the root widget).
+        Applies an additional offset. */
+    TBPopupAlignment(const TBPoint &pos_in_root, const TBPoint &pos_offset)
+        : pos_in_root(pos_in_root)
+        , pos_offset(pos_offset)
+        , align(TB_ALIGN_BOTTOM)
+        , expand_to_target_width(true) {}
+
+    /** Calculate a good rect for the given popup window using its preferred size and
+        the preferred alignment information stored in this class. */
+    TBRect GetAlignedRect(TBWidget *popup, TBWidget *target) const;
+
+    TBPoint pos_in_root;
+    TBPoint pos_offset;
+
+    TB_ALIGN align;
+    /** If true, the width of the popup will be at least the same as the target widget
+        if the alignment is TB_ALIGN_TOP or TB_ALIGN_BOTTOM. */
+    bool expand_to_target_width;
 };
 
 /** TBPopupWindow is a popup window that redirects any child widgets events
-	through the given target. It will automatically close on click events that
-	are not sent through this popup. */
+    through the given target. It will automatically close on click events that
+    are not sent through this popup. */
 
 class TBPopupWindow : public TBWindow, private TBWidgetListener
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBPopupWindow, TBWindow);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBPopupWindow, TBWindow);
 
-	TBPopupWindow(TBWidget *target);
-	~TBPopupWindow();
+    TBPopupWindow(TBWidget *target);
+    ~TBPopupWindow();
 
-	bool Show(const TBPopupAlignment &alignment);
+    bool Show(const TBPopupAlignment &alignment);
 
-	virtual TBWidget *GetEventDestination() { return m_target.Get(); }
+    virtual TBWidget *GetEventDestination() { return m_target.Get(); }
 
-	virtual bool OnEvent(const TBWidgetEvent &ev);
+    virtual bool OnEvent(const TBWidgetEvent &ev);
 private:
-	TBWidgetSafePointer m_target;
-	// TBWidgetListener
-	virtual void OnWidgetFocusChanged(TBWidget *widget, bool focused);
-	virtual bool OnWidgetInvokeEvent(TBWidget *widget, const TBWidgetEvent &ev);
-	virtual void OnWidgetDelete(TBWidget *widget);
-	virtual bool OnWidgetDying(TBWidget *widget);
+    TBWidgetSafePointer m_target;
+    // TBWidgetListener
+    virtual void OnWidgetFocusChanged(TBWidget *widget, bool focused);
+    virtual bool OnWidgetInvokeEvent(TBWidget *widget, const TBWidgetEvent &ev);
+    virtual void OnWidgetDelete(TBWidget *widget);
+    virtual bool OnWidgetDying(TBWidget *widget);
 };
 
 }; // namespace tb

+ 6 - 6
Source/ThirdParty/TurboBadger/tb_renderer.cpp

@@ -11,16 +11,16 @@ namespace tb {
 
 void TBRenderer::InvokeContextLost()
 {
-	TBLinkListOf<TBRendererListener>::Iterator iter = m_listeners.IterateForward();
-	while (TBRendererListener *listener = iter.GetAndStep())
-		listener->OnContextLost();
+    TBLinkListOf<TBRendererListener>::Iterator iter = m_listeners.IterateForward();
+    while (TBRendererListener *listener = iter.GetAndStep())
+        listener->OnContextLost();
 }
 
 void TBRenderer::InvokeContextRestored()
 {
-	TBLinkListOf<TBRendererListener>::Iterator iter = m_listeners.IterateForward();
-	while (TBRendererListener *listener = iter.GetAndStep())
-		listener->OnContextRestored();
+    TBLinkListOf<TBRendererListener>::Iterator iter = m_listeners.IterateForward();
+    while (TBRendererListener *listener = iter.GetAndStep())
+        listener->OnContextRestored();
 }
 
 }; // namespace tb

+ 109 - 109
Source/ThirdParty/TurboBadger/tb_renderer.h

@@ -19,16 +19,16 @@ class TBBitmapFragment;
 class TBRendererListener : public TBLinkOf<TBRendererListener>
 {
 public:
-	virtual ~TBRendererListener() {}
+    virtual ~TBRendererListener() {}
 
-	/** Called when the context has been lost and all TBBitmaps need to be deleted.
-		NOTE: Only do cleanup here. It's not safe to do work on any bitmap since the
-		context is already lost. */
-	virtual void OnContextLost() = 0;
+    /** Called when the context has been lost and all TBBitmaps need to be deleted.
+        NOTE: Only do cleanup here. It's not safe to do work on any bitmap since the
+        context is already lost. */
+    virtual void OnContextLost() = 0;
 
-	/** Called when the context has been restored again, and new TBBitmaps can be created
-		again. */
-	virtual void OnContextRestored() = 0;
+    /** Called when the context has been restored again, and new TBBitmaps can be created
+        again. */
+    virtual void OnContextRestored() = 0;
 };
 
 /** TBBitmap is a minimal interface for bitmap to be painted by TBRenderer. */
@@ -36,17 +36,17 @@ public:
 class TBBitmap
 {
 public:
-	/** Note: Implementations for batched renderers should call TBRenderer::FlushBitmap
-		to make sure any active batch is being flushed before the bitmap is deleted. */
-	virtual ~TBBitmap() {}
+    /** Note: Implementations for batched renderers should call TBRenderer::FlushBitmap
+        to make sure any active batch is being flushed before the bitmap is deleted. */
+    virtual ~TBBitmap() {}
 
-	virtual int Width() = 0;
-	virtual int Height() = 0;
+    virtual int Width() = 0;
+    virtual int Height() = 0;
 
-	/** Update the bitmap with the given data (in BGRA32 format).
-		Note: Implementations for batched renderers should call TBRenderer::FlushBitmap
-		to make sure any active batch is being flushed before the bitmap is changed. */
-	virtual void SetData(uint32 *data) = 0;
+    /** Update the bitmap with the given data (in BGRA32 format).
+        Note: Implementations for batched renderers should call TBRenderer::FlushBitmap
+        to make sure any active batch is being flushed before the bitmap is changed. */
+    virtual void SetData(uint32 *data) = 0;
 };
 
 /** TBRenderer is a minimal interface for painting strings and bitmaps. */
@@ -54,99 +54,99 @@ public:
 class TBRenderer
 {
 public:
-	virtual ~TBRenderer() {}
-
-	/** Should be called before invoking paint on any widget.
-		render_target_w and render_target_h should be the size of the render target
-		that the renderer renders to. I.e window size, screen size or frame buffer object. */
-	virtual void BeginPaint(int render_target_w, int render_target_h) = 0;
-	virtual void EndPaint() = 0;
-
-	/** Translate all drawing with the given offset */
-	virtual void Translate(int dx, int dy) = 0;
-
-	/** Set the current opacity that should apply to all drawing (0.f-1.f). */
-	virtual void SetOpacity(float opacity) = 0;
-	virtual float GetOpacity() = 0;
-
-	/** Set a clip rect to the renderer. add_to_current should be true when
-		pushing a new cliprect that should clip inside the last clip rect,
-		and false when restoring.
-		It will return the clip rect that was in use before this call. */
-	virtual TBRect SetClipRect(const TBRect &rect, bool add_to_current) = 0;
-
-	/** Get the current clip rect. Note: This may be different from the rect
-		sent to SetClipRect, due to intersecting with the previous cliprect! */
-	virtual TBRect GetClipRect() = 0;
-
-	/** Draw the src_rect part of the fragment stretched to dst_rect.
-		dst_rect or src_rect can have negative width and height to achieve horizontal and vertical flip. */
-	virtual void DrawBitmap(const TBRect &dst_rect, const TBRect &src_rect, TBBitmapFragment *bitmap_fragment) = 0;
-
-	/** Draw the src_rect part of the bitmap stretched to dst_rect.
-		dst_rect or src_rect can have negative width and height to achieve horizontal and vertical flip. */
-	virtual void DrawBitmap(const TBRect &dst_rect, const TBRect &src_rect, TBBitmap *bitmap) = 0;
-
-	/** Draw the src_rect part of the fragment stretched to dst_rect.
-		The bitmap will be used as a mask for the color.
-		dst_rect or src_rect can have negative width and height to achieve horizontal and vertical flip. */
-	virtual void DrawBitmapColored(const TBRect &dst_rect, const TBRect &src_rect, const TBColor &color, TBBitmapFragment *bitmap_fragment) = 0;
-
-	/** Draw the src_rect part of the bitmap stretched to dst_rect.
-		The bitmap will be used as a mask for the color.
-		dst_rect or src_rect can have negative width and height to achieve horizontal and vertical flip. */
-	virtual void DrawBitmapColored(const TBRect &dst_rect, const TBRect &src_rect, const TBColor &color, TBBitmap *bitmap) = 0;
-
-	/** Draw the bitmap tiled into dst_rect. */
-	virtual void DrawBitmapTile(const TBRect &dst_rect, TBBitmap *bitmap) = 0;
-
-	/** Draw a 1px thick rectangle outline. */
-	virtual void DrawRect(const TBRect &dst_rect, const TBColor &color) = 0;
-
-	/** Draw a filled rectangle. */
-	virtual void DrawRectFill(const TBRect &dst_rect, const TBColor &color) = 0;
-
-	/** Make sure the given bitmap fragment is flushed from any batching, because it may
-		be changed or deleted after this call. */
-	virtual void FlushBitmapFragment(TBBitmapFragment *bitmap_fragment) = 0;
-
-	/** Create a new TBBitmap from the given data (in BGRA32 format).
-		Width and height must be a power of two.
-		Return nullptr if fail. */
-	virtual TBBitmap *CreateBitmap(int width, int height, uint32 *data) = 0;
-
-	/** Add a listener to this renderer. Does not take ownership. */
-	void AddListener(TBRendererListener *listener) { m_listeners.AddLast(listener); }
-
-	/** Remove a listener from this renderer. */
-	void RemoveListener(TBRendererListener *listener) { m_listeners.Remove(listener); }
-
-	/** Invoke OnContextLost on all listeners.
-		Call when bitmaps should be forgotten. */
-	void InvokeContextLost();
-
-	/** Invoke OnContextRestored on all listeners.
-		Call when bitmaps can safely be restored. */
-	void InvokeContextRestored();
-
-	/** Defines the hint given to BeginBatchHint. */
-	enum BATCH_HINT {
-		/** All calls are either DrawBitmap or DrawBitmapColored with the same bitmap
-			fragment. */
-		BATCH_HINT_DRAW_BITMAP_FRAGMENT
-	};
-
-	/** A hint to batching renderers that the following set of draw calls are of the
-		same type so batching might be optimized.
-		The hint defines what operations are allowed between BeginBatchHint
-		until EndBatchHint is called. All other draw operations are invalid.
-		It's not valid to nest calls to BeginBatchHint. */
-	virtual void BeginBatchHint(BATCH_HINT hint) {}
-
-	/** End the hint scope started with BeginBatchHint. */
-	virtual void EndBatchHint() {}
+    virtual ~TBRenderer() {}
+
+    /** Should be called before invoking paint on any widget.
+        render_target_w and render_target_h should be the size of the render target
+        that the renderer renders to. I.e window size, screen size or frame buffer object. */
+    virtual void BeginPaint(int render_target_w, int render_target_h) = 0;
+    virtual void EndPaint() = 0;
+
+    /** Translate all drawing with the given offset */
+    virtual void Translate(int dx, int dy) = 0;
+
+    /** Set the current opacity that should apply to all drawing (0.f-1.f). */
+    virtual void SetOpacity(float opacity) = 0;
+    virtual float GetOpacity() = 0;
+
+    /** Set a clip rect to the renderer. add_to_current should be true when
+        pushing a new cliprect that should clip inside the last clip rect,
+        and false when restoring.
+        It will return the clip rect that was in use before this call. */
+    virtual TBRect SetClipRect(const TBRect &rect, bool add_to_current) = 0;
+
+    /** Get the current clip rect. Note: This may be different from the rect
+        sent to SetClipRect, due to intersecting with the previous cliprect! */
+    virtual TBRect GetClipRect() = 0;
+
+    /** Draw the src_rect part of the fragment stretched to dst_rect.
+        dst_rect or src_rect can have negative width and height to achieve horizontal and vertical flip. */
+    virtual void DrawBitmap(const TBRect &dst_rect, const TBRect &src_rect, TBBitmapFragment *bitmap_fragment) = 0;
+
+    /** Draw the src_rect part of the bitmap stretched to dst_rect.
+        dst_rect or src_rect can have negative width and height to achieve horizontal and vertical flip. */
+    virtual void DrawBitmap(const TBRect &dst_rect, const TBRect &src_rect, TBBitmap *bitmap) = 0;
+
+    /** Draw the src_rect part of the fragment stretched to dst_rect.
+        The bitmap will be used as a mask for the color.
+        dst_rect or src_rect can have negative width and height to achieve horizontal and vertical flip. */
+    virtual void DrawBitmapColored(const TBRect &dst_rect, const TBRect &src_rect, const TBColor &color, TBBitmapFragment *bitmap_fragment) = 0;
+
+    /** Draw the src_rect part of the bitmap stretched to dst_rect.
+        The bitmap will be used as a mask for the color.
+        dst_rect or src_rect can have negative width and height to achieve horizontal and vertical flip. */
+    virtual void DrawBitmapColored(const TBRect &dst_rect, const TBRect &src_rect, const TBColor &color, TBBitmap *bitmap) = 0;
+
+    /** Draw the bitmap tiled into dst_rect. */
+    virtual void DrawBitmapTile(const TBRect &dst_rect, TBBitmap *bitmap) = 0;
+
+    /** Draw a 1px thick rectangle outline. */
+    virtual void DrawRect(const TBRect &dst_rect, const TBColor &color) = 0;
+
+    /** Draw a filled rectangle. */
+    virtual void DrawRectFill(const TBRect &dst_rect, const TBColor &color) = 0;
+
+    /** Make sure the given bitmap fragment is flushed from any batching, because it may
+        be changed or deleted after this call. */
+    virtual void FlushBitmapFragment(TBBitmapFragment *bitmap_fragment) = 0;
+
+    /** Create a new TBBitmap from the given data (in BGRA32 format).
+        Width and height must be a power of two.
+        Return nullptr if fail. */
+    virtual TBBitmap *CreateBitmap(int width, int height, uint32 *data) = 0;
+
+    /** Add a listener to this renderer. Does not take ownership. */
+    void AddListener(TBRendererListener *listener) { m_listeners.AddLast(listener); }
+
+    /** Remove a listener from this renderer. */
+    void RemoveListener(TBRendererListener *listener) { m_listeners.Remove(listener); }
+
+    /** Invoke OnContextLost on all listeners.
+        Call when bitmaps should be forgotten. */
+    void InvokeContextLost();
+
+    /** Invoke OnContextRestored on all listeners.
+        Call when bitmaps can safely be restored. */
+    void InvokeContextRestored();
+
+    /** Defines the hint given to BeginBatchHint. */
+    enum BATCH_HINT {
+        /** All calls are either DrawBitmap or DrawBitmapColored with the same bitmap
+            fragment. */
+        BATCH_HINT_DRAW_BITMAP_FRAGMENT
+    };
+
+    /** A hint to batching renderers that the following set of draw calls are of the
+        same type so batching might be optimized.
+        The hint defines what operations are allowed between BeginBatchHint
+        until EndBatchHint is called. All other draw operations are invalid.
+        It's not valid to nest calls to BeginBatchHint. */
+    virtual void BeginBatchHint(BATCH_HINT hint) {}
+
+    /** End the hint scope started with BeginBatchHint. */
+    virtual void EndBatchHint() {}
 private:
-	TBLinkListOf<TBRendererListener> m_listeners;
+    TBLinkListOf<TBRendererListener> m_listeners;
 };
 
 }; // namespace tb

+ 221 - 221
Source/ThirdParty/TurboBadger/tb_scroll_container.cpp

@@ -12,306 +12,306 @@ namespace tb {
 // == TBScrollBarVisibility ===================================
 
 TBScrollBarVisibility TBScrollBarVisibility::Solve(SCROLL_MODE mode, int content_w, int content_h,
-																	int available_w, int available_h,
-																	int scrollbar_x_h, int scrollbar_y_w)
+                                                   int available_w, int available_h,
+                                                   int scrollbar_x_h, int scrollbar_y_w)
 {
-	TBScrollBarVisibility visibility;
-	visibility.visible_w = available_w;
-	visibility.visible_h = available_h;
-
-	if (mode == SCROLL_MODE_X_Y)
-	{
-		visibility.y_on = true;
-		visibility.x_on = true;
-		visibility.visible_w -= scrollbar_y_w;
-		visibility.visible_h -= scrollbar_x_h;
-	}
-	else if (mode == SCROLL_MODE_OFF)
-	{
-	}
-	else if (mode == SCROLL_MODE_Y)
-	{
-		visibility.y_on = true;
-		visibility.visible_w -= scrollbar_y_w;
-	}
-	else if (mode == SCROLL_MODE_Y_AUTO)
-	{
-		if (content_h > available_h)
-		{
-			visibility.y_on = true;
-			visibility.visible_w -= scrollbar_y_w;
-		}
-	}
-	else if (mode == SCROLL_MODE_X_AUTO_Y_AUTO)
-	{
-		if (content_w > visibility.visible_w)
-		{
-			visibility.x_on = true;
-			visibility.visible_h = available_h - scrollbar_x_h;
-		}
-		if (content_h > visibility.visible_h)
-		{
-			visibility.y_on = true;
-			visibility.visible_w = available_w - scrollbar_y_w;
-		}
-		if (content_w > visibility.visible_w)
-		{
-			visibility.x_on = true;
-			visibility.visible_h = available_h - scrollbar_x_h;
-		}
-	}
-	return visibility;
+    TBScrollBarVisibility visibility;
+    visibility.visible_w = available_w;
+    visibility.visible_h = available_h;
+
+    if (mode == SCROLL_MODE_X_Y)
+    {
+        visibility.y_on = true;
+        visibility.x_on = true;
+        visibility.visible_w -= scrollbar_y_w;
+        visibility.visible_h -= scrollbar_x_h;
+    }
+    else if (mode == SCROLL_MODE_OFF)
+    {
+    }
+    else if (mode == SCROLL_MODE_Y)
+    {
+        visibility.y_on = true;
+        visibility.visible_w -= scrollbar_y_w;
+    }
+    else if (mode == SCROLL_MODE_Y_AUTO)
+    {
+        if (content_h > available_h)
+        {
+            visibility.y_on = true;
+            visibility.visible_w -= scrollbar_y_w;
+        }
+    }
+    else if (mode == SCROLL_MODE_X_AUTO_Y_AUTO)
+    {
+        if (content_w > visibility.visible_w)
+        {
+            visibility.x_on = true;
+            visibility.visible_h = available_h - scrollbar_x_h;
+        }
+        if (content_h > visibility.visible_h)
+        {
+            visibility.y_on = true;
+            visibility.visible_w = available_w - scrollbar_y_w;
+        }
+        if (content_w > visibility.visible_w)
+        {
+            visibility.x_on = true;
+            visibility.visible_h = available_h - scrollbar_x_h;
+        }
+    }
+    return visibility;
 }
 
 // == TBScrollContainerRoot ===================================
 
 void TBScrollContainerRoot::OnPaintChildren(const PaintProps &paint_props)
 {
-	// We only want clipping in one axis (the overflowing one) so we
-	// don't damage any expanded skins on the other axis. Add some fluff.
-	const int fluff = 100;
-	TBScrollContainer *sc = static_cast<TBScrollContainer *>(GetParent());
-	TBRect clip_rect = GetPaddingRect().Expand(sc->m_scrollbar_x.CanScrollNegative() ? 0 : fluff,
-												sc->m_scrollbar_y.CanScrollNegative() ? 0 : fluff,
-												sc->m_scrollbar_x.CanScrollPositive() ? 0 : fluff,
-												sc->m_scrollbar_y.CanScrollPositive() ? 0 : fluff);
+    // We only want clipping in one axis (the overflowing one) so we
+    // don't damage any expanded skins on the other axis. Add some fluff.
+    const int fluff = 100;
+    TBScrollContainer *sc = static_cast<TBScrollContainer *>(GetParent());
+    TBRect clip_rect = GetPaddingRect().Expand(sc->m_scrollbar_x.CanScrollNegative() ? 0 : fluff,
+                                               sc->m_scrollbar_y.CanScrollNegative() ? 0 : fluff,
+                                               sc->m_scrollbar_x.CanScrollPositive() ? 0 : fluff,
+                                               sc->m_scrollbar_y.CanScrollPositive() ? 0 : fluff);
 
-	TBRect old_clip_rect = g_renderer->SetClipRect(clip_rect, true);
+    TBRect old_clip_rect = g_renderer->SetClipRect(clip_rect, true);
 
-	TB_IF_DEBUG_SETTING(LAYOUT_CLIPPING, g_renderer->DrawRect(clip_rect, TBColor(255, 0, 0, 200)));
+    TB_IF_DEBUG_SETTING(LAYOUT_CLIPPING, g_renderer->DrawRect(clip_rect, TBColor(255, 0, 0, 200)));
 
-	TBWidget::OnPaintChildren(paint_props);
+    TBWidget::OnPaintChildren(paint_props);
 
-	g_renderer->SetClipRect(old_clip_rect, false);
+    g_renderer->SetClipRect(old_clip_rect, false);
 }
 
 void TBScrollContainerRoot::GetChildTranslation(int &x, int &y) const
 {
-	TBScrollContainer *sc = static_cast<TBScrollContainer *>(GetParent());
-	x = (int) -sc->m_scrollbar_x.GetValue();
-	y = (int) -sc->m_scrollbar_y.GetValue();
+    TBScrollContainer *sc = static_cast<TBScrollContainer *>(GetParent());
+    x = (int) -sc->m_scrollbar_x.GetValue();
+    y = (int) -sc->m_scrollbar_y.GetValue();
 }
 
 // == TBScrollContainer =======================================
 
 TBScrollContainer::TBScrollContainer()
-	: m_adapt_to_content_size(false)
-	, m_adapt_content_size(false)
-	, m_layout_is_invalid(false)
+    : m_adapt_to_content_size(false)
+    , m_adapt_content_size(false)
+    , m_layout_is_invalid(false)
     , m_ignore_scroll_events(false)
-	, m_mode(SCROLL_MODE_X_Y)
+    , m_mode(SCROLL_MODE_X_Y)
 {
-	AddChild(&m_scrollbar_x);
-	AddChild(&m_scrollbar_y);
-	AddChild(&m_root);
-	m_scrollbar_y.SetAxis(AXIS_Y);
+    AddChild(&m_scrollbar_x);
+    AddChild(&m_scrollbar_y);
+    AddChild(&m_root);
+    m_scrollbar_y.SetAxis(AXIS_Y);
 }
 
 TBScrollContainer::~TBScrollContainer()
 {
-	RemoveChild(&m_root);
-	RemoveChild(&m_scrollbar_y);
-	RemoveChild(&m_scrollbar_x);
+    RemoveChild(&m_root);
+    RemoveChild(&m_scrollbar_y);
+    RemoveChild(&m_scrollbar_x);
 }
 
 void TBScrollContainer::SetAdaptToContentSize(bool adapt)
 {
-	if (m_adapt_to_content_size == adapt)
-		return;
-	InvalidateLayout(INVALIDATE_LAYOUT_RECURSIVE);
-	m_adapt_to_content_size = adapt;
-	InvalidateLayout(INVALIDATE_LAYOUT_RECURSIVE);
+    if (m_adapt_to_content_size == adapt)
+        return;
+    InvalidateLayout(INVALIDATE_LAYOUT_RECURSIVE);
+    m_adapt_to_content_size = adapt;
+    InvalidateLayout(INVALIDATE_LAYOUT_RECURSIVE);
 }
 
 void TBScrollContainer::SetAdaptContentSize(bool adapt)
 {
-	if (m_adapt_content_size == adapt)
-		return;
-	m_adapt_content_size = adapt;
-	InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
+    if (m_adapt_content_size == adapt)
+        return;
+    m_adapt_content_size = adapt;
+    InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
 }
 
 void TBScrollContainer::SetScrollMode(SCROLL_MODE mode)
 {
-	if (mode == m_mode)
-		return;
-	m_mode = mode;
-	InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
+    if (mode == m_mode)
+        return;
+    m_mode = mode;
+    InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
 }
 
 void TBScrollContainer::ScrollTo(int x, int y)
 {
-	int old_x = m_scrollbar_x.GetValue();
-	int old_y = m_scrollbar_y.GetValue();
-	m_scrollbar_x.SetValue(x);
-	m_scrollbar_y.SetValue(y);
-	if (old_x != m_scrollbar_x.GetValue() ||
-		old_y != m_scrollbar_y.GetValue())
-		Invalidate();
+    int old_x = m_scrollbar_x.GetValue();
+    int old_y = m_scrollbar_y.GetValue();
+    m_scrollbar_x.SetValue(x);
+    m_scrollbar_y.SetValue(y);
+    if (old_x != m_scrollbar_x.GetValue() ||
+            old_y != m_scrollbar_y.GetValue())
+        Invalidate();
 }
 
 TBWidget::ScrollInfo TBScrollContainer::GetScrollInfo()
 {
-	ScrollInfo info;
-	info.min_x = static_cast<int>(m_scrollbar_x.GetMinValue());
-	info.min_y = static_cast<int>(m_scrollbar_y.GetMinValue());
-	info.max_x = static_cast<int>(m_scrollbar_x.GetMaxValue());
-	info.max_y = static_cast<int>(m_scrollbar_y.GetMaxValue());
-	info.x = m_scrollbar_x.GetValue();
-	info.y = m_scrollbar_y.GetValue();
-	return info;
+    ScrollInfo info;
+    info.min_x = static_cast<int>(m_scrollbar_x.GetMinValue());
+    info.min_y = static_cast<int>(m_scrollbar_y.GetMinValue());
+    info.max_x = static_cast<int>(m_scrollbar_x.GetMaxValue());
+    info.max_y = static_cast<int>(m_scrollbar_y.GetMaxValue());
+    info.x = m_scrollbar_x.GetValue();
+    info.y = m_scrollbar_y.GetValue();
+    return info;
 }
 
 void TBScrollContainer::InvalidateLayout(INVALIDATE_LAYOUT il)
 {
-	m_layout_is_invalid = true;
-	// No recursion up to parents here unless we adapt to content size.
-	if (m_adapt_to_content_size)
-		TBWidget::InvalidateLayout(il);
+    m_layout_is_invalid = true;
+    // No recursion up to parents here unless we adapt to content size.
+    if (m_adapt_to_content_size)
+        TBWidget::InvalidateLayout(il);
 }
 
 TBRect TBScrollContainer::GetPaddingRect()
 {
-	int visible_w = GetRect().w;
-	int visible_h = GetRect().h;
-	if (m_scrollbar_x.GetOpacity())
-		visible_h -= m_scrollbar_x.GetPreferredSize().pref_h;
-	if (m_scrollbar_y.GetOpacity())
-		visible_w -= m_scrollbar_y.GetPreferredSize().pref_w;
-	return TBRect(0, 0, visible_w, visible_h);
+    int visible_w = GetRect().w;
+    int visible_h = GetRect().h;
+    if (m_scrollbar_x.GetOpacity())
+        visible_h -= m_scrollbar_x.GetPreferredSize().pref_h;
+    if (m_scrollbar_y.GetOpacity())
+        visible_w -= m_scrollbar_y.GetPreferredSize().pref_w;
+    return TBRect(0, 0, visible_w, visible_h);
 }
 
 PreferredSize TBScrollContainer::OnCalculatePreferredContentSize(const SizeConstraints &constraints)
 {
-	PreferredSize ps;
-	ps.pref_w = ps.pref_h = 100;
-	ps.min_w = ps.min_h = 50;
-	if (m_adapt_to_content_size)
-	{
-		if (TBWidget *content_child = m_root.GetFirstChild())
-		{
-			ps = content_child->GetPreferredSize(constraints);
-			int scrollbar_y_w = m_scrollbar_y.GetPreferredSize().pref_w;
-			int scrollbar_x_h = m_scrollbar_x.GetPreferredSize().pref_h;
-
-			ps.pref_w += scrollbar_y_w;
-			ps.max_w += scrollbar_y_w;
-
-			if (m_mode == SCROLL_MODE_X_Y ||
-				m_mode == SCROLL_MODE_X_AUTO_Y_AUTO)
-			{
-				ps.pref_h += scrollbar_x_h;
-				ps.max_h += scrollbar_x_h;
-			}
-		}
-	}
-	return ps;
+    PreferredSize ps;
+    ps.pref_w = ps.pref_h = 100;
+    ps.min_w = ps.min_h = 50;
+    if (m_adapt_to_content_size)
+    {
+        if (TBWidget *content_child = m_root.GetFirstChild())
+        {
+            ps = content_child->GetPreferredSize(constraints);
+            int scrollbar_y_w = m_scrollbar_y.GetPreferredSize().pref_w;
+            int scrollbar_x_h = m_scrollbar_x.GetPreferredSize().pref_h;
+
+            ps.pref_w += scrollbar_y_w;
+            ps.max_w += scrollbar_y_w;
+
+            if (m_mode == SCROLL_MODE_X_Y ||
+                    m_mode == SCROLL_MODE_X_AUTO_Y_AUTO)
+            {
+                ps.pref_h += scrollbar_x_h;
+                ps.max_h += scrollbar_x_h;
+            }
+        }
+    }
+    return ps;
 }
 
 bool TBScrollContainer::OnEvent(const TBWidgetEvent &ev)
 {
-	if (ev.type == EVENT_TYPE_CHANGED && (ev.target == &m_scrollbar_x || ev.target == &m_scrollbar_y))
-	{
-		Invalidate();
-		OnScroll(m_scrollbar_x.GetValue(), m_scrollbar_y.GetValue());
-		return true;
-	}    
+    if (ev.type == EVENT_TYPE_CHANGED && (ev.target == &m_scrollbar_x || ev.target == &m_scrollbar_y))
+    {
+        Invalidate();
+        OnScroll(m_scrollbar_x.GetValue(), m_scrollbar_y.GetValue());
+        return true;
+    }
     else if (ev.type == EVENT_TYPE_WHEEL && ev.modifierkeys == TB_MODIFIER_NONE && !m_ignore_scroll_events)
-	{
-		double old_val_y = m_scrollbar_y.GetValueDouble();
-		m_scrollbar_y.SetValueDouble(old_val_y + ev.delta_y * TBSystem::GetPixelsPerLine());
-		double old_val_x = m_scrollbar_x.GetValueDouble();
-		m_scrollbar_x.SetValueDouble(old_val_x + ev.delta_x * TBSystem::GetPixelsPerLine());
-		return (m_scrollbar_x.GetValueDouble() != old_val_x || m_scrollbar_y.GetValueDouble() != old_val_y);
-	}
+    {
+        double old_val_y = m_scrollbar_y.GetValueDouble();
+        m_scrollbar_y.SetValueDouble(old_val_y + ev.delta_y * TBSystem::GetPixelsPerLine());
+        double old_val_x = m_scrollbar_x.GetValueDouble();
+        m_scrollbar_x.SetValueDouble(old_val_x + ev.delta_x * TBSystem::GetPixelsPerLine());
+        return (m_scrollbar_x.GetValueDouble() != old_val_x || m_scrollbar_y.GetValueDouble() != old_val_y);
+    }
     else if (ev.type == EVENT_TYPE_KEY_DOWN && !m_ignore_scroll_events)
-	{
+    {
         // ATOMIC: Disabling arrow key scroll
         /*
-		if (ev.special_key == TB_KEY_LEFT && m_scrollbar_x.CanScrollNegative())
-			ScrollBySmooth(-TBSystem::GetPixelsPerLine(), 0);
-		else if (ev.special_key == TB_KEY_RIGHT && m_scrollbar_x.CanScrollPositive())
-			ScrollBySmooth(TBSystem::GetPixelsPerLine(), 0);
-		else if (ev.special_key == TB_KEY_UP && m_scrollbar_y.CanScrollNegative())
-			ScrollBySmooth(0, -TBSystem::GetPixelsPerLine());
-		else if (ev.special_key == TB_KEY_DOWN && m_scrollbar_y.CanScrollPositive())
-			ScrollBySmooth(0, TBSystem::GetPixelsPerLine());
+        if (ev.special_key == TB_KEY_LEFT && m_scrollbar_x.CanScrollNegative())
+            ScrollBySmooth(-TBSystem::GetPixelsPerLine(), 0);
+        else if (ev.special_key == TB_KEY_RIGHT && m_scrollbar_x.CanScrollPositive())
+            ScrollBySmooth(TBSystem::GetPixelsPerLine(), 0);
+        else if (ev.special_key == TB_KEY_UP && m_scrollbar_y.CanScrollNegative())
+            ScrollBySmooth(0, -TBSystem::GetPixelsPerLine());
+        else if (ev.special_key == TB_KEY_DOWN && m_scrollbar_y.CanScrollPositive())
+            ScrollBySmooth(0, TBSystem::GetPixelsPerLine());
         else*/ if (ev.special_key == TB_KEY_PAGE_UP && m_scrollbar_y.CanScrollNegative())
-			ScrollBySmooth(0, -GetPaddingRect().h);
-		else if (ev.special_key == TB_KEY_PAGE_DOWN && m_scrollbar_y.CanScrollPositive())
-			ScrollBySmooth(0, GetPaddingRect().h);
-		else if (ev.special_key == TB_KEY_HOME)
-			ScrollToSmooth(m_scrollbar_x.GetValue(), 0);
-		else if (ev.special_key == TB_KEY_END)
-			ScrollToSmooth(m_scrollbar_x.GetValue(), (int)m_scrollbar_y.GetMaxValue());
-		else
-			return false;
-		return true;
-	}
-	return false;
+            ScrollBySmooth(0, -GetPaddingRect().h);
+        else if (ev.special_key == TB_KEY_PAGE_DOWN && m_scrollbar_y.CanScrollPositive())
+            ScrollBySmooth(0, GetPaddingRect().h);
+        else if (ev.special_key == TB_KEY_HOME)
+            ScrollToSmooth(m_scrollbar_x.GetValue(), 0);
+        else if (ev.special_key == TB_KEY_END)
+            ScrollToSmooth(m_scrollbar_x.GetValue(), (int)m_scrollbar_y.GetMaxValue());
+        else
+            return false;
+        return true;
+    }
+    return false;
 }
 
 void TBScrollContainer::OnProcess()
 {
-	SizeConstraints sc(GetRect().w, GetRect().h);
-	ValidateLayout(sc);
+    SizeConstraints sc(GetRect().w, GetRect().h);
+    ValidateLayout(sc);
 }
 
 void TBScrollContainer::ValidateLayout(const SizeConstraints &constraints)
 {
-	if (!m_layout_is_invalid)
-		return;
-	m_layout_is_invalid = false;
-
-	// Layout scrollbars (no matter if they are visible or not)
-	int scrollbar_y_w = m_scrollbar_y.GetPreferredSize().pref_w;
-	int scrollbar_x_h = m_scrollbar_x.GetPreferredSize().pref_h;
-	m_scrollbar_x.SetRect(TBRect(0, GetRect().h - scrollbar_x_h, GetRect().w - scrollbar_y_w, scrollbar_x_h));
-	m_scrollbar_y.SetRect(TBRect(GetRect().w - scrollbar_y_w, 0, scrollbar_y_w, GetRect().h));
-
-	if (TBWidget *content_child = m_root.GetFirstChild())
-	{
-		int horizontal_padding = TBScrollBarVisibility::IsAlwaysOnY(m_mode) ? scrollbar_y_w : 0;
-		int vertical_padding = TBScrollBarVisibility::IsAlwaysOnX(m_mode) ? scrollbar_x_h : 0;
-
-		SizeConstraints inner_sc = constraints.ConstrainByPadding(horizontal_padding, vertical_padding);
-
-		PreferredSize ps = content_child->GetPreferredSize(inner_sc);
-
-		TBScrollBarVisibility visibility = TBScrollBarVisibility::Solve(m_mode, ps.pref_w, ps.pref_h,
-																		GetRect().w, GetRect().h,
-																		scrollbar_x_h, scrollbar_y_w);
-		m_scrollbar_x.SetOpacity(visibility.x_on ? 1.f : 0.f);
-		m_scrollbar_y.SetOpacity(visibility.y_on ? 1.f : 0.f);
-		m_root.SetRect(TBRect(0, 0, visibility.visible_w, visibility.visible_h));
-
-		int content_w, content_h;
-		if (m_adapt_content_size)
-		{
-			content_w = MAX(ps.pref_w, m_root.GetRect().w);
-			content_h = MAX(ps.pref_h, m_root.GetRect().h);
-			if (!visibility.x_on && m_root.GetRect().w < ps.pref_w)
-				content_w = MIN(ps.pref_w, m_root.GetRect().w);
-		}
-		else
-		{
-			content_w = ps.pref_w;
-			content_h = ps.pref_h;
-		}
-
-		content_child->SetRect(TBRect(0, 0, content_w, content_h));
-		double limit_max_w = MAX(0, content_w - m_root.GetRect().w);
-		double limit_max_h = MAX(0, content_h - m_root.GetRect().h);
-		m_scrollbar_x.SetLimits(0, limit_max_w, m_root.GetRect().w);
-		m_scrollbar_y.SetLimits(0, limit_max_h, m_root.GetRect().h);
-	}
+    if (!m_layout_is_invalid)
+        return;
+    m_layout_is_invalid = false;
+
+    // Layout scrollbars (no matter if they are visible or not)
+    int scrollbar_y_w = m_scrollbar_y.GetPreferredSize().pref_w;
+    int scrollbar_x_h = m_scrollbar_x.GetPreferredSize().pref_h;
+    m_scrollbar_x.SetRect(TBRect(0, GetRect().h - scrollbar_x_h, GetRect().w - scrollbar_y_w, scrollbar_x_h));
+    m_scrollbar_y.SetRect(TBRect(GetRect().w - scrollbar_y_w, 0, scrollbar_y_w, GetRect().h));
+
+    if (TBWidget *content_child = m_root.GetFirstChild())
+    {
+        int horizontal_padding = TBScrollBarVisibility::IsAlwaysOnY(m_mode) ? scrollbar_y_w : 0;
+        int vertical_padding = TBScrollBarVisibility::IsAlwaysOnX(m_mode) ? scrollbar_x_h : 0;
+
+        SizeConstraints inner_sc = constraints.ConstrainByPadding(horizontal_padding, vertical_padding);
+
+        PreferredSize ps = content_child->GetPreferredSize(inner_sc);
+
+        TBScrollBarVisibility visibility = TBScrollBarVisibility::Solve(m_mode, ps.pref_w, ps.pref_h,
+                                                                        GetRect().w, GetRect().h,
+                                                                        scrollbar_x_h, scrollbar_y_w);
+        m_scrollbar_x.SetOpacity(visibility.x_on ? 1.f : 0.f);
+        m_scrollbar_y.SetOpacity(visibility.y_on ? 1.f : 0.f);
+        m_root.SetRect(TBRect(0, 0, visibility.visible_w, visibility.visible_h));
+
+        int content_w, content_h;
+        if (m_adapt_content_size)
+        {
+            content_w = MAX(ps.pref_w, m_root.GetRect().w);
+            content_h = MAX(ps.pref_h, m_root.GetRect().h);
+            if (!visibility.x_on && m_root.GetRect().w < ps.pref_w)
+                content_w = MIN(ps.pref_w, m_root.GetRect().w);
+        }
+        else
+        {
+            content_w = ps.pref_w;
+            content_h = ps.pref_h;
+        }
+
+        content_child->SetRect(TBRect(0, 0, content_w, content_h));
+        double limit_max_w = MAX(0, content_w - m_root.GetRect().w);
+        double limit_max_h = MAX(0, content_h - m_root.GetRect().h);
+        m_scrollbar_x.SetLimits(0, limit_max_w, m_root.GetRect().w);
+        m_scrollbar_y.SetLimits(0, limit_max_h, m_root.GetRect().h);
+    }
 }
 
 void TBScrollContainer::OnResized(int old_w, int old_h)
 {
-	InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
-	SizeConstraints sc(GetRect().w, GetRect().h);
-	ValidateLayout(sc);
+    InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
+    SizeConstraints sc(GetRect().w, GetRect().h);
+    ValidateLayout(sc);
 }
 
 }; // namespace tb

+ 52 - 52
Source/ThirdParty/TurboBadger/tb_scroll_container.h

@@ -11,11 +11,11 @@
 namespace tb {
 
 enum SCROLL_MODE {
-	SCROLL_MODE_X_Y,			///< X and Y always			scroll-mode: xy
-	SCROLL_MODE_Y,				///< Y always (X never)		scroll-mode: y
-	SCROLL_MODE_Y_AUTO,			///< Y auto (X never)		scroll-mode: y-auto
-	SCROLL_MODE_X_AUTO_Y_AUTO,	///< X auto, Y auto			scroll-mode: auto
-	SCROLL_MODE_OFF				///< X any Y never			scroll-mode: off
+    SCROLL_MODE_X_Y,			///< X and Y always			scroll-mode: xy
+    SCROLL_MODE_Y,				///< Y always (X never)		scroll-mode: y
+    SCROLL_MODE_Y_AUTO,			///< Y auto (X never)		scroll-mode: y-auto
+    SCROLL_MODE_X_AUTO_Y_AUTO,	///< X auto, Y auto			scroll-mode: auto
+    SCROLL_MODE_OFF				///< X any Y never			scroll-mode: off
 };
 
 /** TBScrollContainerRoot - Internal for TBScrollContainer */
@@ -23,82 +23,82 @@ enum SCROLL_MODE {
 class TBScrollContainerRoot : public TBWidget
 {
 private: // May only be used by TBScrollContainer.
-	friend class TBScrollContainer;
-	TBScrollContainerRoot() {}
+    friend class TBScrollContainer;
+    TBScrollContainerRoot() {}
 public:
-	virtual void OnPaintChildren(const PaintProps &paint_props);
-	virtual void GetChildTranslation(int &x, int &y) const;
+    virtual void OnPaintChildren(const PaintProps &paint_props);
+    virtual void GetChildTranslation(int &x, int &y) const;
 };
 
 /** TBScrollBarVisibility - Helper for TBScrollContainer or any other scrollable
-	container that needs to solve scrollbar visibility according to SCROLL_MODE. */
+    container that needs to solve scrollbar visibility according to SCROLL_MODE. */
 class TBScrollBarVisibility
 {
 public:
-	TBScrollBarVisibility () : x_on(false), y_on(false), visible_w(0), visible_h(0) {}
+    TBScrollBarVisibility () : x_on(false), y_on(false), visible_w(0), visible_h(0) {}
 
-	static TBScrollBarVisibility Solve(SCROLL_MODE mode, int content_w, int content_h,
-														int available_w, int available_h,
-														int scrollbar_x_h, int scrollbar_y_w);
-	static bool IsAlwaysOnX(SCROLL_MODE mode) { return mode == SCROLL_MODE_X_Y; }
-	static bool IsAlwaysOnY(SCROLL_MODE mode) { return mode == SCROLL_MODE_X_Y || mode == SCROLL_MODE_Y; }
+    static TBScrollBarVisibility Solve(SCROLL_MODE mode, int content_w, int content_h,
+                                       int available_w, int available_h,
+                                       int scrollbar_x_h, int scrollbar_y_w);
+    static bool IsAlwaysOnX(SCROLL_MODE mode) { return mode == SCROLL_MODE_X_Y; }
+    static bool IsAlwaysOnY(SCROLL_MODE mode) { return mode == SCROLL_MODE_X_Y || mode == SCROLL_MODE_Y; }
 public:
-	bool x_on, y_on;
-	int visible_w, visible_h;
+    bool x_on, y_on;
+    int visible_w, visible_h;
 };
 
 /** TBScrollContainer - A container with scrollbars that can scroll its children. */
 
 class TBScrollContainer : public TBWidget
 {
-friend class TBScrollContainerRoot;
+    friend class TBScrollContainerRoot;
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBScrollContainer, TBWidget);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBScrollContainer, TBWidget);
 
-	TBScrollContainer();
-	~TBScrollContainer();
+    TBScrollContainer();
+    ~TBScrollContainer();
 
-	/** Set to true if the preferred size of this container should adapt to the preferred
-		size of the content. This is disabled by default. */
-	void SetAdaptToContentSize(bool adapt);
-	bool GetAdaptToContentSize() { return m_adapt_to_content_size; }
+    /** Set to true if the preferred size of this container should adapt to the preferred
+        size of the content. This is disabled by default. */
+    void SetAdaptToContentSize(bool adapt);
+    bool GetAdaptToContentSize() { return m_adapt_to_content_size; }
 
-	/** Set to true if the content should adapt to the available size of this container
-		when it's larger than the preferred size. */
-	void SetAdaptContentSize(bool adapt);
-	bool GetAdaptContentSize() { return m_adapt_content_size; }
+    /** Set to true if the content should adapt to the available size of this container
+        when it's larger than the preferred size. */
+    void SetAdaptContentSize(bool adapt);
+    bool GetAdaptContentSize() { return m_adapt_content_size; }
 
     void SetIgnoreScrollEvents(bool ignore) { m_ignore_scroll_events = ignore; }
 
-	void SetScrollMode(SCROLL_MODE mode);
-	SCROLL_MODE GetScrollMode() { return m_mode; }
+    void SetScrollMode(SCROLL_MODE mode);
+    SCROLL_MODE GetScrollMode() { return m_mode; }
 
-	virtual void ScrollTo(int x, int y);
-	virtual TBWidget::ScrollInfo GetScrollInfo();
-	virtual TBWidget *GetScrollRoot() { return &m_root; }
+    virtual void ScrollTo(int x, int y);
+    virtual TBWidget::ScrollInfo GetScrollInfo();
+    virtual TBWidget *GetScrollRoot() { return &m_root; }
 
-	virtual void InvalidateLayout(INVALIDATE_LAYOUT il);
+    virtual void InvalidateLayout(INVALIDATE_LAYOUT il);
 
-	virtual TBRect GetPaddingRect();
-	virtual PreferredSize OnCalculatePreferredContentSize(const SizeConstraints &constraints);
+    virtual TBRect GetPaddingRect();
+    virtual PreferredSize OnCalculatePreferredContentSize(const SizeConstraints &constraints);
 
-	virtual void OnInflate(const INFLATE_INFO &info);
-	virtual bool OnEvent(const TBWidgetEvent &ev);
-	virtual void OnProcess();
-	virtual void OnResized(int old_w, int old_h);
+    virtual void OnInflate(const INFLATE_INFO &info);
+    virtual bool OnEvent(const TBWidgetEvent &ev);
+    virtual void OnProcess();
+    virtual void OnResized(int old_w, int old_h);
 
-	virtual TBWidget *GetContentRoot() { return &m_root; }
+    virtual TBWidget *GetContentRoot() { return &m_root; }
 protected:
-	TBScrollBar m_scrollbar_x;
-	TBScrollBar m_scrollbar_y;
-	TBScrollContainerRoot m_root;
-	bool m_adapt_to_content_size;
-	bool m_adapt_content_size;
-	bool m_layout_is_invalid;
+    TBScrollBar m_scrollbar_x;
+    TBScrollBar m_scrollbar_y;
+    TBScrollContainerRoot m_root;
+    bool m_adapt_to_content_size;
+    bool m_adapt_content_size;
+    bool m_layout_is_invalid;
     bool m_ignore_scroll_events;
-	SCROLL_MODE m_mode;
-	void ValidateLayout(const SizeConstraints &constraints);
+    SCROLL_MODE m_mode;
+    void ValidateLayout(const SizeConstraints &constraints);
 };
 
 };

+ 267 - 267
Source/ThirdParty/TurboBadger/tb_scroller.cpp

@@ -30,49 +30,49 @@ namespace tb {
 
 float TBScrollerFunction::GetDurationFromSpeed(float start_speed)
 {
-	float abs_start_speed = ABS(start_speed);
-	if (abs_start_speed <= SF_GATE_THRESHOLD)
-		return 0;
-	return -log(SF_GATE_THRESHOLD / abs_start_speed) * m_decay;
+    float abs_start_speed = ABS(start_speed);
+    if (abs_start_speed <= SF_GATE_THRESHOLD)
+        return 0;
+    return -log(SF_GATE_THRESHOLD / abs_start_speed) * m_decay;
 }
 
 float TBScrollerFunction::GetSpeedFromDistance(float distance)
 {
-	float speed = distance / m_decay;
-	if (distance > SF_GATE_THRESHOLD)
-		return speed + SF_GATE_THRESHOLD;
-	else if (distance < -SF_GATE_THRESHOLD)
-		return speed - SF_GATE_THRESHOLD;
-	return speed;
+    float speed = distance / m_decay;
+    if (distance > SF_GATE_THRESHOLD)
+        return speed + SF_GATE_THRESHOLD;
+    else if (distance < -SF_GATE_THRESHOLD)
+        return speed - SF_GATE_THRESHOLD;
+    return speed;
 }
 
 float TBScrollerFunction::GetDistanceAtTime(float start_speed, float elapsed_time_ms)
 {
-	assert(elapsed_time_ms >= 0);
-	return start_speed * (1 - exp(-elapsed_time_ms / m_decay)) * m_decay;
+    assert(elapsed_time_ms >= 0);
+    return start_speed * (1 - exp(-elapsed_time_ms / m_decay)) * m_decay;
 }
 
 int TBScrollerFunction::GetDistanceAtTimeInt(float start_speed, float elapsed_time_ms)
 {
-	float distance = GetDistanceAtTime(start_speed, elapsed_time_ms);
-	return (int)(distance < 0 ? distance - 0.5f : distance + 0.5f);
+    float distance = GetDistanceAtTime(start_speed, elapsed_time_ms);
+    return (int)(distance < 0 ? distance - 0.5f : distance + 0.5f);
 }
 
 // == TBScroller ========================================================================
 
 TBScroller::TBScroller(TBWidget *target)
-	: m_target(target)
-	, m_snap_listener(nullptr)
-	, m_func(SCROLL_DECAY)
-	, m_previous_pan_dx(0)
-	, m_previous_pan_dy(0)
-	, m_scroll_start_ms(0)
-	, m_scroll_duration_x_ms(0)
-	, m_scroll_duration_y_ms(0)
-	, m_pan_power_multiplier_x(1)
-	, m_pan_power_multiplier_y(1)
+    : m_target(target)
+    , m_snap_listener(nullptr)
+    , m_func(SCROLL_DECAY)
+    , m_previous_pan_dx(0)
+    , m_previous_pan_dy(0)
+    , m_scroll_start_ms(0)
+    , m_scroll_duration_x_ms(0)
+    , m_scroll_duration_y_ms(0)
+    , m_pan_power_multiplier_x(1)
+    , m_pan_power_multiplier_y(1)
 {
-	Reset();
+    Reset();
 }
 
 TBScroller::~TBScroller()
@@ -81,300 +81,300 @@ TBScroller::~TBScroller()
 
 void TBScroller::Reset()
 {
-	m_is_started = false;
-	m_pan_dx = m_pan_dy = 0;
-	m_pan_time_ms = 0;
-	m_pan_delta_time_ms = 0;
-	m_scroll_start_speed_ppms_x = m_scroll_start_speed_ppms_y = 0;
-	m_scroll_start_scroll_x = m_scroll_start_scroll_y = 0;
-	// don't reset m_previous_pan_dx and m_previous_pan_dy here.
-	// don't reset m_pan_power here. It's done on start since it's needed for next pan!
-	m_expected_scroll_x = m_expected_scroll_y = 0;
+    m_is_started = false;
+    m_pan_dx = m_pan_dy = 0;
+    m_pan_time_ms = 0;
+    m_pan_delta_time_ms = 0;
+    m_scroll_start_speed_ppms_x = m_scroll_start_speed_ppms_y = 0;
+    m_scroll_start_scroll_x = m_scroll_start_scroll_y = 0;
+    // don't reset m_previous_pan_dx and m_previous_pan_dy here.
+    // don't reset m_pan_power here. It's done on start since it's needed for next pan!
+    m_expected_scroll_x = m_expected_scroll_y = 0;
 }
 
 void TBScroller::OnScrollBy(int dx, int dy, bool accumulative)
 {
-	if (!IsStarted())
-		Start();
-
-	float ppms_x = m_func.GetSpeedFromDistance((float)dx);
-	float ppms_y = m_func.GetSpeedFromDistance((float)dy);
-
-	if (accumulative && IsScrolling())
-	{
-		TBWidget::ScrollInfo info = m_target->GetScrollInfo();
-		// If new direction is the same as the current direction,
-		// calculate the speed needed for the remaining part and
-		// add that to the new scroll speed.
-		if ((ppms_x < 0) == (m_scroll_start_speed_ppms_x < 0))
-		{
-			int distance_x = m_func.GetDistanceAtTimeInt(m_scroll_start_speed_ppms_x,
-				m_func.GetDurationFromSpeed(m_scroll_start_speed_ppms_x));
-			int distance_remaining_x = m_scroll_start_scroll_x + distance_x - info.x;
-			distance_remaining_x += m_func.GetDistanceAtTimeInt(ppms_x, m_func.GetDurationFromSpeed(ppms_x));
-			ppms_x = m_func.GetSpeedFromDistance((float)distance_remaining_x);
-		}
-		if ((ppms_y < 0) == (m_scroll_start_speed_ppms_y < 0))
-		{
-			int distance_y = m_func.GetDistanceAtTimeInt(m_scroll_start_speed_ppms_y,
-				m_func.GetDurationFromSpeed(m_scroll_start_speed_ppms_y));
-			int distance_remaining_y = m_scroll_start_scroll_y + distance_y - info.y;
-			distance_remaining_y += m_func.GetDistanceAtTimeInt(ppms_y, m_func.GetDurationFromSpeed(ppms_y));
-			ppms_y = m_func.GetSpeedFromDistance((float)distance_remaining_y);
-		}
-	}
-
-	AdjustToSnappingAndScroll(ppms_x, ppms_y);
+    if (!IsStarted())
+        Start();
+
+    float ppms_x = m_func.GetSpeedFromDistance((float)dx);
+    float ppms_y = m_func.GetSpeedFromDistance((float)dy);
+
+    if (accumulative && IsScrolling())
+    {
+        TBWidget::ScrollInfo info = m_target->GetScrollInfo();
+        // If new direction is the same as the current direction,
+        // calculate the speed needed for the remaining part and
+        // add that to the new scroll speed.
+        if ((ppms_x < 0) == (m_scroll_start_speed_ppms_x < 0))
+        {
+            int distance_x = m_func.GetDistanceAtTimeInt(m_scroll_start_speed_ppms_x,
+                                                         m_func.GetDurationFromSpeed(m_scroll_start_speed_ppms_x));
+            int distance_remaining_x = m_scroll_start_scroll_x + distance_x - info.x;
+            distance_remaining_x += m_func.GetDistanceAtTimeInt(ppms_x, m_func.GetDurationFromSpeed(ppms_x));
+            ppms_x = m_func.GetSpeedFromDistance((float)distance_remaining_x);
+        }
+        if ((ppms_y < 0) == (m_scroll_start_speed_ppms_y < 0))
+        {
+            int distance_y = m_func.GetDistanceAtTimeInt(m_scroll_start_speed_ppms_y,
+                                                         m_func.GetDurationFromSpeed(m_scroll_start_speed_ppms_y));
+            int distance_remaining_y = m_scroll_start_scroll_y + distance_y - info.y;
+            distance_remaining_y += m_func.GetDistanceAtTimeInt(ppms_y, m_func.GetDurationFromSpeed(ppms_y));
+            ppms_y = m_func.GetSpeedFromDistance((float)distance_remaining_y);
+        }
+    }
+
+    AdjustToSnappingAndScroll(ppms_x, ppms_y);
 }
 
 bool TBScroller::OnPan(int dx, int dy)
 {
-	if (!IsStarted())
-		Start();
-
-	// Pan the target
-	const int in_dx = dx, in_dy = dy;
-	m_target->ScrollByRecursive(dx, dy);
-
-	// Calculate the pan speed. Smooth it out with the
-	// previous pan speed to reduce fluctuation a little.
-	double now_ms = TBSystem::GetTimeMS();
-	if (m_pan_time_ms)
-	{
-		if (m_pan_delta_time_ms)
-			m_pan_delta_time_ms = (now_ms - m_pan_time_ms + m_pan_delta_time_ms) / 2.0f;
-		else
-			m_pan_delta_time_ms = now_ms - m_pan_time_ms;
-	}
-
-	m_pan_time_ms = now_ms;
-	m_pan_dx = (m_pan_dx + in_dx) / 2.0f;
-	m_pan_dy = (m_pan_dy + in_dy) / 2.0f;
-
-	// If we change direction, reset the pan power multiplier in that axis.
-	if (m_pan_dx != 0 && (m_previous_pan_dx < 0) != (m_pan_dx < 0))
-		m_pan_power_multiplier_x = 1;
-	if (m_pan_dy != 0 && (m_previous_pan_dy < 0) != (m_pan_dy < 0))
-		m_pan_power_multiplier_y = 1;
-	m_previous_pan_dx = m_pan_dx;
-	m_previous_pan_dy = m_pan_dy;
-
-	return in_dx != dx || in_dy != dy;
+    if (!IsStarted())
+        Start();
+
+    // Pan the target
+    const int in_dx = dx, in_dy = dy;
+    m_target->ScrollByRecursive(dx, dy);
+
+    // Calculate the pan speed. Smooth it out with the
+    // previous pan speed to reduce fluctuation a little.
+    double now_ms = TBSystem::GetTimeMS();
+    if (m_pan_time_ms)
+    {
+        if (m_pan_delta_time_ms)
+            m_pan_delta_time_ms = (now_ms - m_pan_time_ms + m_pan_delta_time_ms) / 2.0f;
+        else
+            m_pan_delta_time_ms = now_ms - m_pan_time_ms;
+    }
+
+    m_pan_time_ms = now_ms;
+    m_pan_dx = (m_pan_dx + in_dx) / 2.0f;
+    m_pan_dy = (m_pan_dy + in_dy) / 2.0f;
+
+    // If we change direction, reset the pan power multiplier in that axis.
+    if (m_pan_dx != 0 && (m_previous_pan_dx < 0) != (m_pan_dx < 0))
+        m_pan_power_multiplier_x = 1;
+    if (m_pan_dy != 0 && (m_previous_pan_dy < 0) != (m_pan_dy < 0))
+        m_pan_power_multiplier_y = 1;
+    m_previous_pan_dx = m_pan_dx;
+    m_previous_pan_dy = m_pan_dy;
+
+    return in_dx != dx || in_dy != dy;
 }
 
 void TBScroller::OnPanReleased()
 {
-	if (TBSystem::GetTimeMS() < m_pan_time_ms + PAN_START_THRESHOLD_MS)
-	{
-		// Don't start scroll if we have too little speed.
-		// This will prevent us from scrolling accidently.
-		float pan_start_distance_threshold_px = 2 * TBSystem::GetDPI() / 100.0f;
-		if (ABS(m_pan_dx) < pan_start_distance_threshold_px && ABS(m_pan_dy) < pan_start_distance_threshold_px)
-		{
-			StopOrSnapScroll();
-			return;
-		}
-
-		if (m_pan_delta_time_ms == 0)
-		{
-			StopOrSnapScroll();
-			return;
-		}
-
-		float ppms_x = (float)m_pan_dx / (float)m_pan_delta_time_ms;
-		float ppms_y = (float)m_pan_dy / (float)m_pan_delta_time_ms;
-		ppms_x *= m_pan_power_multiplier_x;
-		ppms_y *= m_pan_power_multiplier_y;
-
-		AdjustToSnappingAndScroll(ppms_x, ppms_y);
-	}
-	else
-		StopOrSnapScroll();
+    if (TBSystem::GetTimeMS() < m_pan_time_ms + PAN_START_THRESHOLD_MS)
+    {
+        // Don't start scroll if we have too little speed.
+        // This will prevent us from scrolling accidently.
+        float pan_start_distance_threshold_px = 2 * TBSystem::GetDPI() / 100.0f;
+        if (ABS(m_pan_dx) < pan_start_distance_threshold_px && ABS(m_pan_dy) < pan_start_distance_threshold_px)
+        {
+            StopOrSnapScroll();
+            return;
+        }
+
+        if (m_pan_delta_time_ms == 0)
+        {
+            StopOrSnapScroll();
+            return;
+        }
+
+        float ppms_x = (float)m_pan_dx / (float)m_pan_delta_time_ms;
+        float ppms_y = (float)m_pan_dy / (float)m_pan_delta_time_ms;
+        ppms_x *= m_pan_power_multiplier_x;
+        ppms_y *= m_pan_power_multiplier_y;
+
+        AdjustToSnappingAndScroll(ppms_x, ppms_y);
+    }
+    else
+        StopOrSnapScroll();
 }
 
 void TBScroller::Start()
 {
-	if (IsStarted())
-		return;
-	m_is_started = true;
-	double now_ms = TBSystem::GetTimeMS();
-	if (now_ms < m_scroll_start_ms + PAN_POWER_ACC_THRESHOLD_MS)
-	{
-		m_pan_power_multiplier_x *= PAN_POWER_MULTIPLIER;
-		m_pan_power_multiplier_y *= PAN_POWER_MULTIPLIER;
-	}
-	else
-	{
-		m_pan_power_multiplier_x = m_pan_power_multiplier_y = 1;
-	}
+    if (IsStarted())
+        return;
+    m_is_started = true;
+    double now_ms = TBSystem::GetTimeMS();
+    if (now_ms < m_scroll_start_ms + PAN_POWER_ACC_THRESHOLD_MS)
+    {
+        m_pan_power_multiplier_x *= PAN_POWER_MULTIPLIER;
+        m_pan_power_multiplier_y *= PAN_POWER_MULTIPLIER;
+    }
+    else
+    {
+        m_pan_power_multiplier_x = m_pan_power_multiplier_y = 1;
+    }
 }
 
 void TBScroller::Stop()
 {
-	DeleteAllMessages();
-	Reset();
+    DeleteAllMessages();
+    Reset();
 }
 
 bool TBScroller::StopIfAlmostStill()
 {
-	double now_ms = TBSystem::GetTimeMS();
-	if (now_ms > m_scroll_start_ms + (double)m_scroll_duration_x_ms &&
-		now_ms > m_scroll_start_ms + (double)m_scroll_duration_y_ms)
-	{
-		Stop();
-		return true;
-	}
-	return false;
+    double now_ms = TBSystem::GetTimeMS();
+    if (now_ms > m_scroll_start_ms + (double)m_scroll_duration_x_ms &&
+            now_ms > m_scroll_start_ms + (double)m_scroll_duration_y_ms)
+    {
+        Stop();
+        return true;
+    }
+    return false;
 }
 
 void TBScroller::StopOrSnapScroll()
 {
-	AdjustToSnappingAndScroll(0, 0);
-	if (!IsScrolling())
-		Stop();
+    AdjustToSnappingAndScroll(0, 0);
+    if (!IsScrolling())
+        Stop();
 }
 
 void TBScroller::AdjustToSnappingAndScroll(float ppms_x, float ppms_y)
 {
-	if (m_snap_listener)
-	{
-		// Calculate the distance
-		int distance_x = m_func.GetDistanceAtTimeInt(ppms_x, m_func.GetDurationFromSpeed(ppms_x));
-		int distance_y = m_func.GetDistanceAtTimeInt(ppms_y, m_func.GetDurationFromSpeed(ppms_y));
-
-		// Let the snap listener modify the distance
-		TBWidget::ScrollInfo info = m_target->GetScrollInfo();
-		int target_x = distance_x + info.x;
-		int target_y = distance_y + info.y;
-		m_snap_listener->OnScrollSnap(m_target, target_x, target_y);
-		distance_x = target_x - info.x;
-		distance_y = target_y - info.y;
-
-		// Get the start speed from the new distance
-		ppms_x = m_func.GetSpeedFromDistance((float)distance_x);
-		ppms_y = m_func.GetSpeedFromDistance((float)distance_y);
-	}
-
-	Scroll(ppms_x, ppms_y);
+    if (m_snap_listener)
+    {
+        // Calculate the distance
+        int distance_x = m_func.GetDistanceAtTimeInt(ppms_x, m_func.GetDurationFromSpeed(ppms_x));
+        int distance_y = m_func.GetDistanceAtTimeInt(ppms_y, m_func.GetDurationFromSpeed(ppms_y));
+
+        // Let the snap listener modify the distance
+        TBWidget::ScrollInfo info = m_target->GetScrollInfo();
+        int target_x = distance_x + info.x;
+        int target_y = distance_y + info.y;
+        m_snap_listener->OnScrollSnap(m_target, target_x, target_y);
+        distance_x = target_x - info.x;
+        distance_y = target_y - info.y;
+
+        // Get the start speed from the new distance
+        ppms_x = m_func.GetSpeedFromDistance((float)distance_x);
+        ppms_y = m_func.GetSpeedFromDistance((float)distance_y);
+    }
+
+    Scroll(ppms_x, ppms_y);
 }
 
 void TBScroller::Scroll(float start_speed_ppms_x, float start_speed_ppms_y)
 {
-	// Set start values
-	m_scroll_start_ms = TBSystem::GetTimeMS();
-	GetTargetScrollXY(m_scroll_start_scroll_x, m_scroll_start_scroll_y);
-	m_scroll_start_speed_ppms_x = start_speed_ppms_x;
-	m_scroll_start_speed_ppms_y = start_speed_ppms_y;
-
-	// Calculate duration for the scroll (each axis independently)
-	m_scroll_duration_x_ms = m_func.GetDurationFromSpeed(m_scroll_start_speed_ppms_x);
-	m_scroll_duration_y_ms = m_func.GetDurationFromSpeed(m_scroll_start_speed_ppms_y);
-
-	if (StopIfAlmostStill())
-		return;
-
-	// Post the pan message if we don't already have one
-	if (!GetMessageByID(TBIDC("scroll")))
-	{
-		// Update expected translation
-		GetTargetChildTranslation(m_expected_scroll_x, m_expected_scroll_y);
-
-		PostMessageDelayed(TBIDC("scroll"), nullptr, (uint32)PAN_MSG_DELAY_MS);
-	}
+    // Set start values
+    m_scroll_start_ms = TBSystem::GetTimeMS();
+    GetTargetScrollXY(m_scroll_start_scroll_x, m_scroll_start_scroll_y);
+    m_scroll_start_speed_ppms_x = start_speed_ppms_x;
+    m_scroll_start_speed_ppms_y = start_speed_ppms_y;
+
+    // Calculate duration for the scroll (each axis independently)
+    m_scroll_duration_x_ms = m_func.GetDurationFromSpeed(m_scroll_start_speed_ppms_x);
+    m_scroll_duration_y_ms = m_func.GetDurationFromSpeed(m_scroll_start_speed_ppms_y);
+
+    if (StopIfAlmostStill())
+        return;
+
+    // Post the pan message if we don't already have one
+    if (!GetMessageByID(TBIDC("scroll")))
+    {
+        // Update expected translation
+        GetTargetChildTranslation(m_expected_scroll_x, m_expected_scroll_y);
+
+        PostMessageDelayed(TBIDC("scroll"), nullptr, (uint32)PAN_MSG_DELAY_MS);
+    }
 }
 
 bool TBScroller::IsScrolling()
 {
-	return GetMessageByID(TBIDC("scroll")) ? true : false;
+    return GetMessageByID(TBIDC("scroll")) ? true : false;
 }
 
 void TBScroller::GetTargetChildTranslation(int &x, int &y) const
 {
-	int root_x = 0, root_y = 0;
-	int child_translation_x = 0, child_translation_y = 0;
-	TBWidget *scroll_root = m_target->GetScrollRoot();
-	scroll_root->ConvertToRoot(root_x, root_y);
-	scroll_root->GetChildTranslation(child_translation_x, child_translation_y);
-	x = root_x + child_translation_x;
-	y = root_y + child_translation_y;
+    int root_x = 0, root_y = 0;
+    int child_translation_x = 0, child_translation_y = 0;
+    TBWidget *scroll_root = m_target->GetScrollRoot();
+    scroll_root->ConvertToRoot(root_x, root_y);
+    scroll_root->GetChildTranslation(child_translation_x, child_translation_y);
+    x = root_x + child_translation_x;
+    y = root_y + child_translation_y;
 }
 
 void TBScroller::GetTargetScrollXY(int &x, int &y) const
 {
-	x = 0;
-	y = 0;
-	TBWidget *tmp = m_target->GetScrollRoot();
-	while (tmp)
-	{
-		TBWidget::ScrollInfo info = tmp->GetScrollInfo();
-		x += info.x;
-		y += info.y;
-		tmp = tmp->GetParent();
-	}
+    x = 0;
+    y = 0;
+    TBWidget *tmp = m_target->GetScrollRoot();
+    while (tmp)
+    {
+        TBWidget::ScrollInfo info = tmp->GetScrollInfo();
+        x += info.x;
+        y += info.y;
+        tmp = tmp->GetParent();
+    }
 }
 
 void TBScroller::OnMessageReceived(TBMessage *msg)
 {
-	if (msg->message == TBIDC("scroll"))
-	{
-		int actual_scroll_x = 0, actual_scroll_y = 0;
-		GetTargetChildTranslation(actual_scroll_x, actual_scroll_y);
-		if (actual_scroll_x != m_expected_scroll_x ||
-			actual_scroll_y != m_expected_scroll_y)
-		{
-			// Something else has affected the target child translation.
-			// This should abort the scroll.
-			// This could happen f.ex if something shrunk the scroll limits,
-			// some other action changed scroll position, or if another
-			// scroller started operating on a sub child that when reacing
-			// its scroll limit, started scrolling its chain of parents.
-			Stop();
-			return;
-		}
-
-		// Calculate the time elapsed from scroll start. Clip within the
-		// duration for each axis.
-		double now_ms = TBSystem::GetTimeMS();
-		float elapsed_time_x = (float)(now_ms - m_scroll_start_ms);
-		float elapsed_time_y = elapsed_time_x;
-		elapsed_time_x = MIN(elapsed_time_x, m_scroll_duration_x_ms);
-		elapsed_time_y = MIN(elapsed_time_y, m_scroll_duration_y_ms);
-
-		// Get the new scroll position from the current distance in each axis.
-		int scroll_x = m_func.GetDistanceAtTimeInt(m_scroll_start_speed_ppms_x, elapsed_time_x);
-		int scroll_y = m_func.GetDistanceAtTimeInt(m_scroll_start_speed_ppms_y, elapsed_time_y);
-		scroll_x += m_scroll_start_scroll_x;
-		scroll_y += m_scroll_start_scroll_y;
-
-		// Get the scroll delta and invoke ScrollByRecursive.
-		int curr_scroll_x, curr_scroll_y;
-		GetTargetScrollXY(curr_scroll_x, curr_scroll_y);
-		const int dx = scroll_x - curr_scroll_x;
-		const int dy = scroll_y - curr_scroll_y;
-
-		int idx = dx, idy = dy;
-		m_target->ScrollByRecursive(idx, idy);
-
-		// Update expected translation
-		GetTargetChildTranslation(m_expected_scroll_x, m_expected_scroll_y);
-
-		if ((dx && actual_scroll_x == m_expected_scroll_x) &&
-			(dy && actual_scroll_y == m_expected_scroll_y))
-		{
-			// We didn't get anywhere despite we tried,
-			// so we're done (reached the end).
-			Stop();
-			return;
-		}
-
-		if (!StopIfAlmostStill())
-		{
-			double next_fire_time = msg->GetFireTime() + PAN_MSG_DELAY_MS;
-			// avoid timer catch-up if program went sleeping for a while.
-			next_fire_time = MAX(next_fire_time, now_ms);
-			PostMessageOnTime(TBIDC("scroll"), nullptr, next_fire_time);
-		}
-	}
+    if (msg->message == TBIDC("scroll"))
+    {
+        int actual_scroll_x = 0, actual_scroll_y = 0;
+        GetTargetChildTranslation(actual_scroll_x, actual_scroll_y);
+        if (actual_scroll_x != m_expected_scroll_x ||
+                actual_scroll_y != m_expected_scroll_y)
+        {
+            // Something else has affected the target child translation.
+            // This should abort the scroll.
+            // This could happen f.ex if something shrunk the scroll limits,
+            // some other action changed scroll position, or if another
+            // scroller started operating on a sub child that when reacing
+            // its scroll limit, started scrolling its chain of parents.
+            Stop();
+            return;
+        }
+
+        // Calculate the time elapsed from scroll start. Clip within the
+        // duration for each axis.
+        double now_ms = TBSystem::GetTimeMS();
+        float elapsed_time_x = (float)(now_ms - m_scroll_start_ms);
+        float elapsed_time_y = elapsed_time_x;
+        elapsed_time_x = MIN(elapsed_time_x, m_scroll_duration_x_ms);
+        elapsed_time_y = MIN(elapsed_time_y, m_scroll_duration_y_ms);
+
+        // Get the new scroll position from the current distance in each axis.
+        int scroll_x = m_func.GetDistanceAtTimeInt(m_scroll_start_speed_ppms_x, elapsed_time_x);
+        int scroll_y = m_func.GetDistanceAtTimeInt(m_scroll_start_speed_ppms_y, elapsed_time_y);
+        scroll_x += m_scroll_start_scroll_x;
+        scroll_y += m_scroll_start_scroll_y;
+
+        // Get the scroll delta and invoke ScrollByRecursive.
+        int curr_scroll_x, curr_scroll_y;
+        GetTargetScrollXY(curr_scroll_x, curr_scroll_y);
+        const int dx = scroll_x - curr_scroll_x;
+        const int dy = scroll_y - curr_scroll_y;
+
+        int idx = dx, idy = dy;
+        m_target->ScrollByRecursive(idx, idy);
+
+        // Update expected translation
+        GetTargetChildTranslation(m_expected_scroll_x, m_expected_scroll_y);
+
+        if ((dx && actual_scroll_x == m_expected_scroll_x) &&
+                (dy && actual_scroll_y == m_expected_scroll_y))
+        {
+            // We didn't get anywhere despite we tried,
+            // so we're done (reached the end).
+            Stop();
+            return;
+        }
+
+        if (!StopIfAlmostStill())
+        {
+            double next_fire_time = msg->GetFireTime() + PAN_MSG_DELAY_MS;
+            // avoid timer catch-up if program went sleeping for a while.
+            next_fire_time = MAX(next_fire_time, now_ms);
+            PostMessageOnTime(TBIDC("scroll"), nullptr, next_fire_time);
+        }
+    }
 }
 
 }; // namespace tb

+ 76 - 76
Source/ThirdParty/TurboBadger/tb_scroller.h

@@ -14,30 +14,30 @@ namespace tb {
 class TBWidget;
 
 /** TBScrollerFunction does the calculations of time, speed and distance
-	that decides how the slow down of a scroll will happen.
+    that decides how the slow down of a scroll will happen.
 
-	Note: Speed is in pixels per millisecond. Duration is in milliseconds
-		  and distance is in pixels. Distance and speed may be negative! */
+    Note: Speed is in pixels per millisecond. Duration is in milliseconds
+          and distance is in pixels. Distance and speed may be negative! */
 
 class TBScrollerFunction
 {
 public:
-	TBScrollerFunction(float decay) : m_decay(decay) {}
+    TBScrollerFunction(float decay) : m_decay(decay) {}
 
-	/** Calculate the duration needed until the end distance is reached
-		from the given start speed. */
-	float GetDurationFromSpeed(float start_speed);
+    /** Calculate the duration needed until the end distance is reached
+        from the given start speed. */
+    float GetDurationFromSpeed(float start_speed);
 
-	/** Calculate the start speed needed to reach the given distance. */
-	float GetSpeedFromDistance(float distance);
+    /** Calculate the start speed needed to reach the given distance. */
+    float GetSpeedFromDistance(float distance);
 
-	/** Calculate the distance reached at the given elapsed_time_ms with the given start_speed. */
-	float GetDistanceAtTime(float start_speed, float elapsed_time_ms);
+    /** Calculate the distance reached at the given elapsed_time_ms with the given start_speed. */
+    float GetDistanceAtTime(float start_speed, float elapsed_time_ms);
 
-	/** Same as GetDistanceAtTime but rounded to integer. */
-	int GetDistanceAtTimeInt(float start_speed, float elapsed_time_ms);
+    /** Same as GetDistanceAtTime but rounded to integer. */
+    int GetDistanceAtTimeInt(float start_speed, float elapsed_time_ms);
 private:
-	float m_decay;
+    float m_decay;
 };
 
 /** TBScrollerSnapListener may override the target scroll position of a TBScroller. */
@@ -45,87 +45,87 @@ private:
 class TBScrollerSnapListener
 {
 public:
-	virtual ~TBScrollerSnapListener() {};
+    virtual ~TBScrollerSnapListener() {};
 
-	/** Called when the target scroll position is calculated.
+    /** Called when the target scroll position is calculated.
 
-		target_widget is the widget being scroller.
-		target_x, target_y is the suggested target scroll position which may be changed
-		to something else in this call.
+        target_widget is the widget being scroller.
+        target_x, target_y is the suggested target scroll position which may be changed
+        to something else in this call.
 
-		Note: The scroll positions are relative to the target widget (inner scrolled TBWidget).
-			  If there's nested scrollable widgets, only the inner scrolled widget applies snapping. */
-	virtual void OnScrollSnap(TBWidget *target_widget, int &target_x, int &target_y) = 0;
+        Note: The scroll positions are relative to the target widget (inner scrolled TBWidget).
+              If there's nested scrollable widgets, only the inner scrolled widget applies snapping. */
+    virtual void OnScrollSnap(TBWidget *target_widget, int &target_x, int &target_y) = 0;
 };
 
 /** TBScroller handles panning while the pointer is down and measure the pan
-	speed over time. It also handles continued scrolling when the pointer has
-	been released with a flick. */
+    speed over time. It also handles continued scrolling when the pointer has
+    been released with a flick. */
 class TBScroller : private TBMessageHandler
 {
 public:
-	TBScroller(TBWidget *target);
-	~TBScroller();
+    TBScroller(TBWidget *target);
+    ~TBScroller();
 
-	/** Set the listener that may override the target scroll position. */
-	void SetSnapListener(TBScrollerSnapListener *listener) { m_snap_listener = listener; }
+    /** Set the listener that may override the target scroll position. */
+    void SetSnapListener(TBScrollerSnapListener *listener) { m_snap_listener = listener; }
 
-	/** Start tracking pan movement from calls to OnPan. */
-	void Start();
+    /** Start tracking pan movement from calls to OnPan. */
+    void Start();
 
-	/** Stop tracking pan movement from calls to OnPan,
-		or stop any ongoing scrolling. */
-	void Stop();
+    /** Stop tracking pan movement from calls to OnPan,
+        or stop any ongoing scrolling. */
+    void Stop();
 
-	/** Return true if the pan tracking is started or. */
-	bool IsStarted() const { return m_is_started; }
+    /** Return true if the pan tracking is started or. */
+    bool IsStarted() const { return m_is_started; }
 
-	/** Get the widget that will be panned/scrolled. Any parent of this
-		widget may also be panned/scrolled. */
-	TBWidget *GetTarget() const { return m_target; }
+    /** Get the widget that will be panned/scrolled. Any parent of this
+        widget may also be panned/scrolled. */
+    TBWidget *GetTarget() const { return m_target; }
 
-	/** Pan the target widget (or any parent) with the given deltas.
-		Should be called while the pointer is down.
-		This will track the pan speed over time. */
-	bool OnPan(int dx, int dy);
+    /** Pan the target widget (or any parent) with the given deltas.
+        Should be called while the pointer is down.
+        This will track the pan speed over time. */
+    bool OnPan(int dx, int dy);
 
-	/** The panning ends and the scroller should start scrolling.
-		Should be called when the pointer is released. */
-	void OnPanReleased();
+    /** The panning ends and the scroller should start scrolling.
+        Should be called when the pointer is released. */
+    void OnPanReleased();
 
-	/** Start the scroller based on the given delta. Doesn't
-		require previous calls to OnPan or OnPanReleased.
+    /** Start the scroller based on the given delta. Doesn't
+        require previous calls to OnPan or OnPanReleased.
 
-		If accumulative is true, the given delta will be
-		added to any on going scroll. If it's false, any
-		ongoing scroll will be canceled. */
-	void OnScrollBy(int dx, int dy, bool accumulative);
+        If accumulative is true, the given delta will be
+        added to any on going scroll. If it's false, any
+        ongoing scroll will be canceled. */
+    void OnScrollBy(int dx, int dy, bool accumulative);
 private:
-	virtual void OnMessageReceived(TBMessage *msg);
-	bool IsScrolling();
-	bool StopIfAlmostStill();
-	void StopOrSnapScroll();
-	void Reset();
-	void AdjustToSnappingAndScroll(float ppms_x, float ppms_y);
-	void Scroll(float start_speed_ppms_x, float start_speed_ppms_y);
-	void GetTargetChildTranslation(int &x, int &y) const;
-	void GetTargetScrollXY(int &x, int &y) const;
-	TBWidget *m_target;
-	TBScrollerSnapListener *m_snap_listener;
-	TBScrollerFunction m_func;
-	bool m_is_started;
-	float m_pan_dx, m_pan_dy;
-	float m_previous_pan_dx, m_previous_pan_dy;
-	double m_pan_time_ms;
-	double m_pan_delta_time_ms;
-	float m_scroll_start_speed_ppms_x, m_scroll_start_speed_ppms_y;
-	double m_scroll_start_ms;
-	float m_scroll_duration_x_ms, m_scroll_duration_y_ms;
-	int m_scroll_start_scroll_x, m_scroll_start_scroll_y;
-	float m_pan_power_multiplier_x;
-	float m_pan_power_multiplier_y;
-	int m_expected_scroll_x;
-	int m_expected_scroll_y;
+    virtual void OnMessageReceived(TBMessage *msg);
+    bool IsScrolling();
+    bool StopIfAlmostStill();
+    void StopOrSnapScroll();
+    void Reset();
+    void AdjustToSnappingAndScroll(float ppms_x, float ppms_y);
+    void Scroll(float start_speed_ppms_x, float start_speed_ppms_y);
+    void GetTargetChildTranslation(int &x, int &y) const;
+    void GetTargetScrollXY(int &x, int &y) const;
+    TBWidget *m_target;
+    TBScrollerSnapListener *m_snap_listener;
+    TBScrollerFunction m_func;
+    bool m_is_started;
+    float m_pan_dx, m_pan_dy;
+    float m_previous_pan_dx, m_previous_pan_dy;
+    double m_pan_time_ms;
+    double m_pan_delta_time_ms;
+    float m_scroll_start_speed_ppms_x, m_scroll_start_speed_ppms_y;
+    double m_scroll_start_ms;
+    float m_scroll_duration_x_ms, m_scroll_duration_y_ms;
+    int m_scroll_start_scroll_x, m_scroll_start_scroll_y;
+    float m_pan_power_multiplier_x;
+    float m_pan_power_multiplier_y;
+    int m_expected_scroll_x;
+    int m_expected_scroll_y;
 };
 
 }; // namespace tb

+ 294 - 294
Source/ThirdParty/TurboBadger/tb_select.cpp

@@ -16,178 +16,178 @@ namespace tb {
 
 static int select_list_sort_cb(TBSelectItemSource *source, const int *a, const int *b)
 {
-	int value = strcmp(source->GetItemString(*a), source->GetItemString(*b));
-	return source->GetSort() == TB_SORT_DESCENDING ? -value : value;
+    int value = strcmp(source->GetItemString(*a), source->GetItemString(*b));
+    return source->GetSort() == TB_SORT_DESCENDING ? -value : value;
 }
 
 // == TBSelectList ==============================================
 
 TBSelectList::TBSelectList()
-	: m_value(-1)
-	, m_list_is_invalid(false)
-	, m_scroll_to_current(false)
+    : m_value(-1)
+    , m_list_is_invalid(false)
+    , m_scroll_to_current(false)
     , m_header_lng_string_id(TBIDC("TBList.header"))
     , m_sort_callback(select_list_sort_cb)
     , m_ui_list_view(false)
 {
-	SetSource(&m_default_source);
-	SetIsFocusable(true);
-	SetSkinBg(TBIDC("TBSelectList"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
-	m_container.SetGravity(WIDGET_GRAVITY_ALL);
-	m_container.SetRect(GetPaddingRect());
-	AddChild(&m_container);
-	m_layout.SetGravity(WIDGET_GRAVITY_ALL);
-	m_layout.SetAxis(AXIS_Y);
-	m_layout.SetSpacing(0);
-	m_layout.SetLayoutPosition(LAYOUT_POSITION_LEFT_TOP);
-	m_layout.SetLayoutDistributionPosition(LAYOUT_DISTRIBUTION_POSITION_LEFT_TOP);
-	m_layout.SetLayoutSize(LAYOUT_SIZE_AVAILABLE);
-	m_container.GetContentRoot()->AddChild(&m_layout);
-	m_container.SetScrollMode(SCROLL_MODE_Y_AUTO);
-	m_container.SetAdaptContentSize(true);
+    SetSource(&m_default_source);
+    SetIsFocusable(true);
+    SetSkinBg(TBIDC("TBSelectList"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
+    m_container.SetGravity(WIDGET_GRAVITY_ALL);
+    m_container.SetRect(GetPaddingRect());
+    AddChild(&m_container);
+    m_layout.SetGravity(WIDGET_GRAVITY_ALL);
+    m_layout.SetAxis(AXIS_Y);
+    m_layout.SetSpacing(0);
+    m_layout.SetLayoutPosition(LAYOUT_POSITION_LEFT_TOP);
+    m_layout.SetLayoutDistributionPosition(LAYOUT_DISTRIBUTION_POSITION_LEFT_TOP);
+    m_layout.SetLayoutSize(LAYOUT_SIZE_AVAILABLE);
+    m_container.GetContentRoot()->AddChild(&m_layout);
+    m_container.SetScrollMode(SCROLL_MODE_Y_AUTO);
+    m_container.SetAdaptContentSize(true);
 }
 
 TBSelectList::~TBSelectList()
 {
-	m_container.GetContentRoot()->RemoveChild(&m_layout);
-	RemoveChild(&m_container);
-	SetSource(nullptr);
+    m_container.GetContentRoot()->RemoveChild(&m_layout);
+    RemoveChild(&m_container);
+    SetSource(nullptr);
 }
 
 void TBSelectList::OnSourceChanged()
 {
-	InvalidateList();
+    InvalidateList();
 }
 
 void TBSelectList::OnItemChanged(int index)
 {
-	if (m_list_is_invalid) // We're updating all widgets soon.
-		return;
+    if (m_list_is_invalid) // We're updating all widgets soon.
+        return;
 
-	TBWidget *old_widget = GetItemWidget(index);
-	if (!old_widget) // We don't have this widget so we have nothing to update.
-		return;
+    TBWidget *old_widget = GetItemWidget(index);
+    if (!old_widget) // We don't have this widget so we have nothing to update.
+        return;
 
-	// Replace the old widget representing the item, with a new one. Preserve its state.
-	WIDGET_STATE old_state = old_widget->GetStateRaw();
+    // Replace the old widget representing the item, with a new one. Preserve its state.
+    WIDGET_STATE old_state = old_widget->GetStateRaw();
 
-	if (TBWidget *widget = CreateAndAddItemAfter(index, old_widget))
-		widget->SetStateRaw(old_state);
+    if (TBWidget *widget = CreateAndAddItemAfter(index, old_widget))
+        widget->SetStateRaw(old_state);
 
-	old_widget->GetParent()->RemoveChild(old_widget);
-	delete old_widget;
+    old_widget->GetParent()->RemoveChild(old_widget);
+    delete old_widget;
 }
 
 void TBSelectList::OnItemAdded(int index)
 {
-	if (m_list_is_invalid) // We're updating all widgets soon.
-		return;
+    if (m_list_is_invalid) // We're updating all widgets soon.
+        return;
 
-	// Sorting, filtering etc. makes it messy to handle dynamic addition of items.
-	// Resort to invalidate the entire list (may even be faster anyway)
-	InvalidateList();
+    // Sorting, filtering etc. makes it messy to handle dynamic addition of items.
+    // Resort to invalidate the entire list (may even be faster anyway)
+    InvalidateList();
 }
 
 void TBSelectList::OnItemRemoved(int index)
 {
-	if (m_list_is_invalid) // We're updating all widgets soon.
-		return;
+    if (m_list_is_invalid) // We're updating all widgets soon.
+        return;
 
-	// Sorting, filtering etc. makes it messy to handle dynamic addition of items.
-	// Resort to invalidate the entire list (may even be faster anyway)
-	InvalidateList();
+    // Sorting, filtering etc. makes it messy to handle dynamic addition of items.
+    // Resort to invalidate the entire list (may even be faster anyway)
+    InvalidateList();
 }
 
 void TBSelectList::OnAllItemsRemoved()
 {
-	InvalidateList();
-	m_value = -1;
+    InvalidateList();
+    m_value = -1;
 }
 
 void TBSelectList::SetFilter(const char *filter)
 {
-	TBStr new_filter;
-	if (filter && *filter)
-		new_filter.Set(filter);
-	if (m_filter.Equals(new_filter))
-		return;
-	m_filter.Set(new_filter);
-	InvalidateList();
+    TBStr new_filter;
+    if (filter && *filter)
+        new_filter.Set(filter);
+    if (m_filter.Equals(new_filter))
+        return;
+    m_filter.Set(new_filter);
+    InvalidateList();
 }
 
 void TBSelectList::SetHeaderString(const TBID& id)
 {
-	if (m_header_lng_string_id == id)
-		return;
-	m_header_lng_string_id = id;
-	InvalidateList();
+    if (m_header_lng_string_id == id)
+        return;
+    m_header_lng_string_id = id;
+    InvalidateList();
 }
 
 void TBSelectList::InvalidateList()
 {
-	if (m_list_is_invalid)
-		return;
-	m_list_is_invalid = true;
-	Invalidate();
+    if (m_list_is_invalid)
+        return;
+    m_list_is_invalid = true;
+    Invalidate();
 }
 
 void TBSelectList::ValidateList()
 {
-	if (!m_list_is_invalid)
-		return;
-	m_list_is_invalid = false;
-	// FIX: Could delete and create only the changed items (faster filter change)
-
-	// Remove old items
-	while (TBWidget *child = m_layout.GetContentRoot()->GetFirstChild())
-	{
-		child->GetParent()->RemoveChild(child);
-		delete child;
-	}
-	if (!m_source || !m_source->GetNumItems())
-		return;
-
-	// Create a sorted list of the items we should include using the current filter.
-	TBTempBuffer sort_buf;
-	if (!sort_buf.Reserve(m_source->GetNumItems() * sizeof(int)))
-		return; // Out of memory
-	int *sorted_index = (int *) sort_buf.GetData();
-
-	// Populate the sorted index list
-	int num_sorted_items = 0;
-	for (int i = 0; i < m_source->GetNumItems(); i++)
-		if (m_filter.IsEmpty() || m_source->Filter(i, m_filter))
-			sorted_index[num_sorted_items++] = i;
-
-	// Sort
-	if (m_source->GetSort() != TB_SORT_NONE)
+    if (!m_list_is_invalid)
+        return;
+    m_list_is_invalid = false;
+    // FIX: Could delete and create only the changed items (faster filter change)
+
+    // Remove old items
+    while (TBWidget *child = m_layout.GetContentRoot()->GetFirstChild())
+    {
+        child->GetParent()->RemoveChild(child);
+        delete child;
+    }
+    if (!m_source || !m_source->GetNumItems())
+        return;
+
+    // Create a sorted list of the items we should include using the current filter.
+    TBTempBuffer sort_buf;
+    if (!sort_buf.Reserve(m_source->GetNumItems() * sizeof(int)))
+        return; // Out of memory
+    int *sorted_index = (int *) sort_buf.GetData();
+
+    // Populate the sorted index list
+    int num_sorted_items = 0;
+    for (int i = 0; i < m_source->GetNumItems(); i++)
+        if (m_filter.IsEmpty() || m_source->Filter(i, m_filter))
+            sorted_index[num_sorted_items++] = i;
+
+    // Sort
+    if (m_source->GetSort() != TB_SORT_NONE)
         insertion_sort<TBSelectItemSource*, int>(sorted_index, num_sorted_items, m_source, m_sort_callback);
 
-	// Show header if we only show a subset of all items.
+    // Show header if we only show a subset of all items.
     // a single space filter is used as a dummy filter
     if (!m_filter.IsEmpty() && (!(m_filter.Length() == 1 && m_filter[0] == ' ')))
-	{
-		if (TBWidget *widget = new TBTextField())
-		{
-			TBStr str;
-			str.SetFormatted(g_tb_lng->GetString(m_header_lng_string_id), num_sorted_items, m_source->GetNumItems());
-			widget->SetText(str);
-			widget->SetSkinBg(TBIDC("TBList.header"));
-			widget->SetState(WIDGET_STATE_DISABLED, true);
-			widget->SetGravity(WIDGET_GRAVITY_ALL);
-			widget->data.SetInt(-1);
-			m_layout.GetContentRoot()->AddChild(widget);
-		}
-	}
-
-	// Create new items
-	for (int i = 0; i < num_sorted_items; i++)
-		CreateAndAddItemAfter(sorted_index[i], nullptr);
-
-	SelectItem(m_value, true);
-
-	// FIX: Should not scroll just because we update the list. Only automatically first time!
-	m_scroll_to_current = true;
+    {
+        if (TBWidget *widget = new TBTextField())
+        {
+            TBStr str;
+            str.SetFormatted(g_tb_lng->GetString(m_header_lng_string_id), num_sorted_items, m_source->GetNumItems());
+            widget->SetText(str);
+            widget->SetSkinBg(TBIDC("TBList.header"));
+            widget->SetState(WIDGET_STATE_DISABLED, true);
+            widget->SetGravity(WIDGET_GRAVITY_ALL);
+            widget->data.SetInt(-1);
+            m_layout.GetContentRoot()->AddChild(widget);
+        }
+    }
+
+    // Create new items
+    for (int i = 0; i < num_sorted_items; i++)
+        CreateAndAddItemAfter(sorted_index[i], nullptr);
+
+    SelectItem(m_value, true);
+
+    // FIX: Should not scroll just because we update the list. Only automatically first time!
+    m_scroll_to_current = true;
 
     TBWidgetEvent ev(EVENT_TYPE_CUSTOM);
     // TBIDC does not register the string with the UI system
@@ -199,32 +199,32 @@ void TBSelectList::ValidateList()
 
 TBWidget *TBSelectList::CreateAndAddItemAfter(int index, TBWidget *reference)
 {
-	if (TBWidget *widget = m_source->CreateItemWidget(index, this))
-	{
-		// Use item data as widget to index lookup
-		widget->data.SetInt(index);
-		m_layout.GetContentRoot()->AddChildRelative(widget, WIDGET_Z_REL_AFTER, reference);
-		return widget;
-	}
-	return nullptr;
+    if (TBWidget *widget = m_source->CreateItemWidget(index, this))
+    {
+        // Use item data as widget to index lookup
+        widget->data.SetInt(index);
+        m_layout.GetContentRoot()->AddChildRelative(widget, WIDGET_Z_REL_AFTER, reference);
+        return widget;
+    }
+    return nullptr;
 }
 
 void TBSelectList::SetValue(int value)
 {
-	if (value == m_value)
-		return;
+    if (value == m_value)
+        return;
 
     if (!m_ui_list_view)
         SelectItem(m_value, false);
 
-	m_value = value;
-	SelectItem(m_value, true);
-	ScrollToSelectedItem();
+    m_value = value;
+    SelectItem(m_value, true);
+    ScrollToSelectedItem();
 
-	TBWidgetEvent ev(EVENT_TYPE_CHANGED);
-	if (TBWidget *widget = GetItemWidget(m_value))
-		ev.ref_id = widget->GetID();
-	InvokeEvent(ev);
+    TBWidgetEvent ev(EVENT_TYPE_CHANGED);
+    if (TBWidget *widget = GetItemWidget(m_value))
+        ev.ref_id = widget->GetID();
+    InvokeEvent(ev);
 }
 
 TBID TBSelectList::GetItemID(int index) const
@@ -246,9 +246,9 @@ int TBSelectList::GetNumItems() const
 
 TBID TBSelectList::GetSelectedItemID()
 {
-	if (m_source && m_value >= 0 && m_value < m_source->GetNumItems())
-		return m_source->GetItemID(m_value);
-	return TBID();
+    if (m_source && m_value >= 0 && m_value < m_source->GetNumItems())
+        return m_source->GetItemID(m_value);
+    return TBID();
 }
 
 void TBSelectList::SelectItem(int index, bool selected)
@@ -262,53 +262,53 @@ void TBSelectList::SelectItem(int index, bool selected)
 
 TBWidget *TBSelectList::GetItemWidget(int index)
 {
-	if (index == -1)
-		return nullptr;
-	for (TBWidget *tmp = m_layout.GetContentRoot()->GetFirstChild(); tmp; tmp = tmp->GetNext())
-		if (tmp->data.GetInt() == index)
-			return tmp;
-	return nullptr;
+    if (index == -1)
+        return nullptr;
+    for (TBWidget *tmp = m_layout.GetContentRoot()->GetFirstChild(); tmp; tmp = tmp->GetNext())
+        if (tmp->data.GetInt() == index)
+            return tmp;
+    return nullptr;
 }
 
 void TBSelectList::ScrollToSelectedItem()
 {
-	if (m_list_is_invalid)
-	{
-		m_scroll_to_current = true;
-		return;
-	}
-	m_scroll_to_current = false;
-	if (TBWidget *widget = GetItemWidget(m_value))
-		m_container.ScrollIntoView(widget->GetRect());
-	else
-		m_container.ScrollTo(0, 0);
+    if (m_list_is_invalid)
+    {
+        m_scroll_to_current = true;
+        return;
+    }
+    m_scroll_to_current = false;
+    if (TBWidget *widget = GetItemWidget(m_value))
+        m_container.ScrollIntoView(widget->GetRect());
+    else
+        m_container.ScrollTo(0, 0);
 }
 
 void TBSelectList::OnSkinChanged()
 {
-	m_container.SetRect(GetPaddingRect());
+    m_container.SetRect(GetPaddingRect());
 }
 
 void TBSelectList::OnProcess()
 {
-	ValidateList();
+    ValidateList();
 }
 
 void TBSelectList::OnProcessAfterChildren()
 {
-	if (m_scroll_to_current)
-		ScrollToSelectedItem();
+    if (m_scroll_to_current)
+        ScrollToSelectedItem();
 }
 
 bool TBSelectList::OnEvent(const TBWidgetEvent &ev)
 {
-	if (ev.type == EVENT_TYPE_CLICK && ev.target->GetParent() == m_layout.GetContentRoot())
-	{
-		// SetValue (EVENT_TYPE_CHANGED) might cause something to delete this (f.ex closing
-		// the dropdown menu. We want to sent another event, so ensure we're still around.
-		TBWidgetSafePointer this_widget(this);
+    if (ev.type == EVENT_TYPE_CLICK && ev.target->GetParent() == m_layout.GetContentRoot())
+    {
+        // SetValue (EVENT_TYPE_CHANGED) might cause something to delete this (f.ex closing
+        // the dropdown menu. We want to sent another event, so ensure we're still around.
+        TBWidgetSafePointer this_widget(this);
 
-		int index = ev.target->data.GetInt();
+        int index = ev.target->data.GetInt();
 
         if (!m_ui_list_view)
             SetValue(index);
@@ -326,41 +326,41 @@ bool TBSelectList::OnEvent(const TBWidgetEvent &ev)
             }
         }
 
-		// If we're still around, invoke the click event too.
-		if (this_widget.Get())
-		{
-			TBSelectList *target_list = this;
-			// If the parent window is a TBMenuWindow, we will iterate up the event destination
-			// chain to find the top TBMenuWindow and invoke the event there.
-			// That way events in submenus will reach the caller properly, and seem like it was
-			// invoked on the top menu.
-			TBWindow *window = GetParentWindow();
-			while (TBMenuWindow *menu_win = TBSafeCast<TBMenuWindow>(window))
-			{
-				target_list = menu_win->GetList();
-				window = menu_win->GetEventDestination()->GetParentWindow();
-			}
-
-			// Invoke the click event on the target list
-			TBWidgetEvent ev(EVENT_TYPE_CLICK);
-			if (TBWidget *widget = GetItemWidget(m_value))
-				ev.ref_id = widget->GetID();
-			target_list->InvokeEvent(ev);
-		}
-		return true;
-	}
-	else if (ev.type == EVENT_TYPE_KEY_DOWN)
-	{
-		if (ChangeValue(ev.special_key))
-			return true;
-
-		// Give the scroll container a chance to handle the key so it may
-		// scroll. This matters if the list itself is focused instead of
-		// some child view of any select item (since that would have passed
-		// the container already)
-		if (GetScrollContainer()->OnEvent(ev))
-			return true;
-	}
+        // If we're still around, invoke the click event too.
+        if (this_widget.Get())
+        {
+            TBSelectList *target_list = this;
+            // If the parent window is a TBMenuWindow, we will iterate up the event destination
+            // chain to find the top TBMenuWindow and invoke the event there.
+            // That way events in submenus will reach the caller properly, and seem like it was
+            // invoked on the top menu.
+            TBWindow *window = GetParentWindow();
+            while (TBMenuWindow *menu_win = TBSafeCast<TBMenuWindow>(window))
+            {
+                target_list = menu_win->GetList();
+                window = menu_win->GetEventDestination()->GetParentWindow();
+            }
+
+            // Invoke the click event on the target list
+            TBWidgetEvent ev(EVENT_TYPE_CLICK);
+            if (TBWidget *widget = GetItemWidget(m_value))
+                ev.ref_id = widget->GetID();
+            target_list->InvokeEvent(ev);
+        }
+        return true;
+    }
+    else if (ev.type == EVENT_TYPE_KEY_DOWN)
+    {
+        if (ChangeValue(ev.special_key))
+            return true;
+
+        // Give the scroll container a chance to handle the key so it may
+        // scroll. This matters if the list itself is focused instead of
+        // some child view of any select item (since that would have passed
+        // the container already)
+        if (GetScrollContainer()->OnEvent(ev))
+            return true;
+    }
 
     return TBWidget::OnEvent(ev);
 }
@@ -368,39 +368,39 @@ bool TBSelectList::OnEvent(const TBWidgetEvent &ev)
 bool TBSelectList::ChangeValue(SPECIAL_KEY key)
 {
     if (m_ui_list_view || !m_source || !m_layout.GetContentRoot()->GetFirstChild())
-		return false;
-
-	bool forward;
-	if (key == TB_KEY_HOME || key == TB_KEY_DOWN)
-		forward = true;
-	else if (key == TB_KEY_END || key == TB_KEY_UP)
-		forward = false;
-	else
-		return false;
-
-	TBWidget *item_root = m_layout.GetContentRoot();
-	TBWidget *current = GetItemWidget(m_value);
-	TBWidget *origin = nullptr;
-	if (key == TB_KEY_HOME || (!current && key == TB_KEY_DOWN))
-		current = item_root->GetFirstChild();
-	else if (key == TB_KEY_END || (!current && key == TB_KEY_UP))
-		current = item_root->GetLastChild();
-	else
-		origin = current;
-
-	while (current)
-	{
-		if (current != origin && !current->GetDisabled())
-			break;
-		current = forward ? current->GetNext() : current->GetPrev();
-	}
-	// Select and focus what we found
-	if (current)
-	{
-		SetValue(current->data.GetInt());
-		return true;
-	}
-	return false;
+        return false;
+
+    bool forward;
+    if (key == TB_KEY_HOME || key == TB_KEY_DOWN)
+        forward = true;
+    else if (key == TB_KEY_END || key == TB_KEY_UP)
+        forward = false;
+    else
+        return false;
+
+    TBWidget *item_root = m_layout.GetContentRoot();
+    TBWidget *current = GetItemWidget(m_value);
+    TBWidget *origin = nullptr;
+    if (key == TB_KEY_HOME || (!current && key == TB_KEY_DOWN))
+        current = item_root->GetFirstChild();
+    else if (key == TB_KEY_END || (!current && key == TB_KEY_UP))
+        current = item_root->GetLastChild();
+    else
+        origin = current;
+
+    while (current)
+    {
+        if (current != origin && !current->GetDisabled())
+            break;
+        current = forward ? current->GetNext() : current->GetPrev();
+    }
+    // Select and focus what we found
+    if (current)
+    {
+        SetValue(current->data.GetInt());
+        return true;
+    }
+    return false;
 }
 
 bool TBSelectList::GetItemSelected(int index)
@@ -430,26 +430,26 @@ void TBSelectList::SelectAllItems(bool select)
 // == TBSelectDropdown ==========================================
 
 TBSelectDropdown::TBSelectDropdown()
-	: m_value(-1)
+    : m_value(-1)
 {
-	SetSource(&m_default_source);
-	SetSkinBg(TBIDC("TBSelectDropdown"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
-	m_arrow.SetSkinBg(TBIDC("TBSelectDropdown.arrow"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
-	GetContentRoot()->AddChild(&m_arrow);
+    SetSource(&m_default_source);
+    SetSkinBg(TBIDC("TBSelectDropdown"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
+    m_arrow.SetSkinBg(TBIDC("TBSelectDropdown.arrow"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
+    GetContentRoot()->AddChild(&m_arrow);
 }
 
 TBSelectDropdown::~TBSelectDropdown()
 {
-	GetContentRoot()->RemoveChild(&m_arrow);
-	SetSource(nullptr);
-	CloseWindow();
+    GetContentRoot()->RemoveChild(&m_arrow);
+    SetSource(nullptr);
+    CloseWindow();
 }
 
 void TBSelectDropdown::OnSourceChanged()
 {
-	m_value = -1;
-	if (m_source && m_source->GetNumItems())
-		SetValue(0);
+    m_value = -1;
+    if (m_source && m_source->GetNumItems())
+        SetValue(0);
 }
 
 void TBSelectDropdown::OnItemChanged(int index)
@@ -458,85 +458,85 @@ void TBSelectDropdown::OnItemChanged(int index)
 
 void TBSelectDropdown::SetValue(int value)
 {
-	if (value == m_value || !m_source)
-		return;
-	m_value = value;
+    if (value == m_value || !m_source)
+        return;
+    m_value = value;
 
-	if (m_value < 0)
-		SetText("");
-	else if (m_value < m_source->GetNumItems())
-		SetText(m_source->GetItemString(m_value));
+    if (m_value < 0)
+        SetText("");
+    else if (m_value < m_source->GetNumItems())
+        SetText(m_source->GetItemString(m_value));
 
-	TBWidgetEvent ev(EVENT_TYPE_CHANGED);
-	InvokeEvent(ev);
+    TBWidgetEvent ev(EVENT_TYPE_CHANGED);
+    InvokeEvent(ev);
 }
 
 TBID TBSelectDropdown::GetSelectedItemID()
 {
-	if (m_source && m_value >= 0 && m_value < m_source->GetNumItems())
-		return m_source->GetItemID(m_value);
-	return TBID();
+    if (m_source && m_value >= 0 && m_value < m_source->GetNumItems())
+        return m_source->GetItemID(m_value);
+    return TBID();
 }
 
 void TBSelectDropdown::OpenWindow()
 {
-	if (!m_source || !m_source->GetNumItems() || m_window_pointer.Get())
-		return;
+    if (!m_source || !m_source->GetNumItems() || m_window_pointer.Get())
+        return;
 
-	if (TBMenuWindow *window = new TBMenuWindow(this, TBIDC("TBSelectDropdown.window")))
-	{
-		m_window_pointer.Set(window);
-		window->SetSkinBg(TBIDC("TBSelectDropdown.window"));
-		window->Show(m_source, TBPopupAlignment(), GetValue());
-	}
+    if (TBMenuWindow *window = new TBMenuWindow(this, TBIDC("TBSelectDropdown.window")))
+    {
+        m_window_pointer.Set(window);
+        window->SetSkinBg(TBIDC("TBSelectDropdown.window"));
+        window->Show(m_source, TBPopupAlignment(), GetValue());
+    }
 }
 
 void TBSelectDropdown::CloseWindow()
 {
-	if (TBMenuWindow *window = GetMenuIfOpen())
-		window->Close();
+    if (TBMenuWindow *window = GetMenuIfOpen())
+        window->Close();
 }
 
 TBMenuWindow *TBSelectDropdown::GetMenuIfOpen() const
 {
-	return TBSafeCast<TBMenuWindow>(m_window_pointer.Get());
+    return TBSafeCast<TBMenuWindow>(m_window_pointer.Get());
 }
 
 bool TBSelectDropdown::OnEvent(const TBWidgetEvent &ev)
 {
-	if (ev.target == this && ev.type == EVENT_TYPE_CLICK)
-	{
-		// Open the menu, or set the value and close it if already open (this will
-		// happen when clicking by keyboard since that will call click on this button)
-		if (TBMenuWindow *menu_window = GetMenuIfOpen())
-		{
-			TBWidgetSafePointer tmp(this);
-			int value = menu_window->GetList()->GetValue();
-			menu_window->Die();
-			if (tmp.Get())
-				SetValue(value);
-		}
-		else
-			OpenWindow();
-		return true;
-	}
-	else if (ev.target->GetID() == TBIDC("TBSelectDropdown.window") && ev.type == EVENT_TYPE_CLICK)
-	{
-		// Set the value of the clicked item
-		if (TBMenuWindow *menu_window = GetMenuIfOpen())
-			SetValue(menu_window->GetList()->GetValue());
-		return true;
-	}
-	else if (ev.target == this && m_source && ev.IsKeyEvent())
-	{
-		if (TBMenuWindow *menu_window = GetMenuIfOpen())
-		{
-			// Redirect the key strokes to the list
-			TBWidgetEvent redirected_ev(ev);
-			return menu_window->GetList()->InvokeEvent(redirected_ev);
-		}
-	}
-	return false;
+    if (ev.target == this && ev.type == EVENT_TYPE_CLICK)
+    {
+        // Open the menu, or set the value and close it if already open (this will
+        // happen when clicking by keyboard since that will call click on this button)
+        if (TBMenuWindow *menu_window = GetMenuIfOpen())
+        {
+            TBWidgetSafePointer tmp(this);
+            int value = menu_window->GetList()->GetValue();
+            menu_window->Die();
+            if (tmp.Get())
+                SetValue(value);
+        }
+        else
+            OpenWindow();
+        return true;
+    }
+    else if (ev.target->GetID() == TBIDC("TBSelectDropdown.window") && ev.type == EVENT_TYPE_CLICK)
+    {
+        // Set the value of the clicked item
+        if (TBMenuWindow *menu_window = GetMenuIfOpen())
+            SetValue(menu_window->GetList()->GetValue());
+        return true;
+    }
+    else if (ev.target == this && m_source && ev.IsKeyEvent())
+    {
+        if (TBMenuWindow *menu_window = GetMenuIfOpen())
+        {
+            // Redirect the key strokes to the list
+            TBWidgetEvent redirected_ev(ev);
+            return menu_window->GetList()->InvokeEvent(redirected_ev);
+        }
+    }
+    return false;
 }
 
 } // namespace tb

+ 109 - 109
Source/ThirdParty/TurboBadger/tb_select.h

@@ -21,100 +21,100 @@ typedef int (*TBSelectListSortCallback)(TBSelectItemSource *source, const int *a
 class TBSelectList : public TBWidget, public TBSelectItemViewer
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBSelectList, TBWidget);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBSelectList, TBWidget);
 
-	TBSelectList();
-	~TBSelectList();
+    TBSelectList();
+    ~TBSelectList();
 
-	/** Get the default item source for this widget. This source can be used to add
-		items of type TBGenericStringItem to this widget.
-		It is the item source that is fed from resource files.
+    /** Get the default item source for this widget. This source can be used to add
+        items of type TBGenericStringItem to this widget.
+        It is the item source that is fed from resource files.
 
-		If you need to add other types of items, or if you want to share item sources
-		between several TBSelectDropDown/TBSelectList widgets, use SetSource using a
-		external item source. */
-	TBGenericStringItemSource *GetDefaultSource() { return &m_default_source; }
+        If you need to add other types of items, or if you want to share item sources
+        between several TBSelectDropDown/TBSelectList widgets, use SetSource using a
+        external item source. */
+    TBGenericStringItemSource *GetDefaultSource() { return &m_default_source; }
 
-	/** Set filter string so only matching items will be showed.
-		Set nullptr or empty string to remove filter and show all items. */
-	void SetFilter(const char *filter);
-	const char *GetFilter() const { return m_filter; }
+    /** Set filter string so only matching items will be showed.
+        Set nullptr or empty string to remove filter and show all items. */
+    void SetFilter(const char *filter);
+    const char *GetFilter() const { return m_filter; }
 
     void SetSortCallback(TBSelectListSortCallback callback) { m_sort_callback = callback; }
 
-	/** Set the language string id for the header. The header is shown
-		at the top of the list when only a subset of all items are shown. */
-	void SetHeaderString(const TBID& id);
-
-	/** Make the list update its items to reflect the items from the
-		in the current source. The update will take place next time
-		the list is validated. */
-	void InvalidateList();
-
-	/** Make sure the list is reflecting the current items in the source. */
-	void ValidateList();
-
-	/** The value is the selected item. In lists with multiple selectable
-		items it's the item that is the current focus. */
-	virtual void SetValue(int value);
-	virtual int GetValue() { return m_value; }
-
-	/** Get the ID of the selected item, or 0 if there is no item selected. */
-	TBID GetSelectedItemID();
-
-	/** Change the value to a non disabled item that is visible with the current
-		filter. Returns true if it successfully found another item.
-		Valid keys:
-			TB_KEY_UP - Previous item.
-			TB_KEY_DOWN - Next item.
-			TB_KEY_HOME - First item.
-			TB_KEY_END - Last item. */
-	bool ChangeValue(SPECIAL_KEY key);
-
-	/** Set the selected state of the item at the given index. If you want
-		to unselect the previously selected item, use SetValue. */
-	void SelectItem(int index, bool selected);
-	TBWidget *GetItemWidget(int index);
+    /** Set the language string id for the header. The header is shown
+        at the top of the list when only a subset of all items are shown. */
+    void SetHeaderString(const TBID& id);
+
+    /** Make the list update its items to reflect the items from the
+        in the current source. The update will take place next time
+        the list is validated. */
+    void InvalidateList();
+
+    /** Make sure the list is reflecting the current items in the source. */
+    void ValidateList();
+
+    /** The value is the selected item. In lists with multiple selectable
+        items it's the item that is the current focus. */
+    virtual void SetValue(int value);
+    virtual int GetValue() { return m_value; }
+
+    /** Get the ID of the selected item, or 0 if there is no item selected. */
+    TBID GetSelectedItemID();
+
+    /** Change the value to a non disabled item that is visible with the current
+        filter. Returns true if it successfully found another item.
+        Valid keys:
+            TB_KEY_UP - Previous item.
+            TB_KEY_DOWN - Next item.
+            TB_KEY_HOME - First item.
+            TB_KEY_END - Last item. */
+    bool ChangeValue(SPECIAL_KEY key);
+
+    /** Set the selected state of the item at the given index. If you want
+        to unselect the previously selected item, use SetValue. */
+    void SelectItem(int index, bool selected);
+    TBWidget *GetItemWidget(int index);
     bool GetItemSelected(int index);
 
-	/** Scroll to the current selected item. The scroll may be delayed until
-		the items has been layouted if the layout is currently invalid. */
-	void ScrollToSelectedItem();
+    /** Scroll to the current selected item. The scroll may be delayed until
+        the items has been layouted if the layout is currently invalid. */
+    void ScrollToSelectedItem();
 
-	/** Return the scrollcontainer used in this list. */
-	TBScrollContainer *GetScrollContainer() { return &m_container; }
+    /** Return the scrollcontainer used in this list. */
+    TBScrollContainer *GetScrollContainer() { return &m_container; }
 
     TBID GetItemID(int index) const;
     int GetNumItems() const;
 
     void SetUIListView(bool value) { m_ui_list_view = value; }
 
-	virtual void OnInflate(const INFLATE_INFO &info);
-	virtual void OnSkinChanged();
-	virtual void OnProcess();
-	virtual void OnProcessAfterChildren();
-	virtual bool OnEvent(const TBWidgetEvent &ev);
-
-	// == TBSelectItemViewer ==================================================
-	virtual void OnSourceChanged();
-	virtual void OnItemChanged(int index);
-	virtual void OnItemAdded(int index);
-	virtual void OnItemRemoved(int index);
-	virtual void OnAllItemsRemoved();
+    virtual void OnInflate(const INFLATE_INFO &info);
+    virtual void OnSkinChanged();
+    virtual void OnProcess();
+    virtual void OnProcessAfterChildren();
+    virtual bool OnEvent(const TBWidgetEvent &ev);
+
+    // == TBSelectItemViewer ==================================================
+    virtual void OnSourceChanged();
+    virtual void OnItemChanged(int index);
+    virtual void OnItemAdded(int index);
+    virtual void OnItemRemoved(int index);
+    virtual void OnAllItemsRemoved();
 protected:
-	TBScrollContainer m_container;
-	TBLayout m_layout;
-	TBGenericStringItemSource m_default_source;
-	int m_value;
-	TBStr m_filter;
-	bool m_list_is_invalid;
-	bool m_scroll_to_current;
+    TBScrollContainer m_container;
+    TBLayout m_layout;
+    TBGenericStringItemSource m_default_source;
+    int m_value;
+    TBStr m_filter;
+    bool m_list_is_invalid;
+    bool m_scroll_to_current;
     bool m_ui_list_view;
-	TBID m_header_lng_string_id;
+    TBID m_header_lng_string_id;
 private:
     TBSelectListSortCallback m_sort_callback;
-	TBWidget *CreateAndAddItemAfter(int index, TBWidget *reference);
+    TBWidget *CreateAndAddItemAfter(int index, TBWidget *reference);
 
     void SelectAllItems(bool select = false);
 
@@ -122,56 +122,56 @@ private:
 };
 
 /** TBSelectDropdown shows a button that opens a popup with a TBSelectList with items
-	provided by a TBSelectItemSource. */
+    provided by a TBSelectItemSource. */
 
 class TBSelectDropdown : public TBButton, public TBSelectItemViewer
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBSelectDropdown, TBButton);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBSelectDropdown, TBButton);
 
-	TBSelectDropdown();
-	~TBSelectDropdown();
+    TBSelectDropdown();
+    ~TBSelectDropdown();
 
-	/** Get the default item source for this widget. This source can be used to add
-		items of type TBGenericStringItem to this widget.
-		It is the item source that is fed from resource files.
+    /** Get the default item source for this widget. This source can be used to add
+        items of type TBGenericStringItem to this widget.
+        It is the item source that is fed from resource files.
 
-		If you need to add other types of items, or if you want to share item sources
-		between several TBSelectDropDown/TBSelectList widgets, use SetSource using a
-		external item source. */
-	TBGenericStringItemSource *GetDefaultSource() { return &m_default_source; }
+        If you need to add other types of items, or if you want to share item sources
+        between several TBSelectDropDown/TBSelectList widgets, use SetSource using a
+        external item source. */
+    TBGenericStringItemSource *GetDefaultSource() { return &m_default_source; }
 
-	/** Set the selected item. */
-	virtual void SetValue(int value);
-	virtual int GetValue() { return m_value; }
+    /** Set the selected item. */
+    virtual void SetValue(int value);
+    virtual int GetValue() { return m_value; }
 
-	/** Get the ID of the selected item, or 0 if there is no item selected. */
-	TBID GetSelectedItemID();
+    /** Get the ID of the selected item, or 0 if there is no item selected. */
+    TBID GetSelectedItemID();
 
-	/** Open the window if the model has items. */
-	void OpenWindow();
+    /** Open the window if the model has items. */
+    void OpenWindow();
 
-	/** Close the window if it is open. */
-	void CloseWindow();
+    /** Close the window if it is open. */
+    void CloseWindow();
 
-	/** Return the menu window if it's open, or nullptr. */
-	TBMenuWindow *GetMenuIfOpen() const;
+    /** Return the menu window if it's open, or nullptr. */
+    TBMenuWindow *GetMenuIfOpen() const;
 
-	virtual void OnInflate(const INFLATE_INFO &info);
-	virtual bool OnEvent(const TBWidgetEvent &ev);
+    virtual void OnInflate(const INFLATE_INFO &info);
+    virtual bool OnEvent(const TBWidgetEvent &ev);
 
-	// == TBSelectItemViewer ==================================================
-	virtual void OnSourceChanged();
-	virtual void OnItemChanged(int index);
-	virtual void OnItemAdded(int index) {}
-	virtual void OnItemRemoved(int index) {}
-	virtual void OnAllItemsRemoved() {}
+    // == TBSelectItemViewer ==================================================
+    virtual void OnSourceChanged();
+    virtual void OnItemChanged(int index);
+    virtual void OnItemAdded(int index) {}
+    virtual void OnItemRemoved(int index) {}
+    virtual void OnAllItemsRemoved() {}
 protected:
-	TBGenericStringItemSource m_default_source;
-	TBSkinImage m_arrow;
-	int m_value;
-	TBWidgetSafePointer m_window_pointer; ///< Points to the dropdown window if opened
+    TBGenericStringItemSource m_default_source;
+    TBSkinImage m_arrow;
+    int m_value;
+    TBWidgetSafePointer m_window_pointer; ///< Points to the dropdown window if opened
 };
 
 }; // namespace tb

+ 124 - 124
Source/ThirdParty/TurboBadger/tb_select_item.cpp

@@ -13,125 +13,125 @@
 namespace tb {
 
 /** TBSimpleLayoutItemWidget is a item containing a layout with the following:
-	-TBSkinImage showing the item image.
-	-TBTextField showing the item string.
-	-TBSkinImage showing the arrow for items with a submenu.
-	It also handles submenu events. */
+    -TBSkinImage showing the item image.
+    -TBTextField showing the item string.
+    -TBSkinImage showing the arrow for items with a submenu.
+    It also handles submenu events. */
 
 class TBSimpleLayoutItemWidget : public TBLayout, private TBWidgetListener
 {
 public:
-	TBSimpleLayoutItemWidget(TBID image, TBSelectItemSource *source, const char *str);
-	~TBSimpleLayoutItemWidget();
-	virtual bool OnEvent(const TBWidgetEvent &ev);
+    TBSimpleLayoutItemWidget(TBID image, TBSelectItemSource *source, const char *str);
+    ~TBSimpleLayoutItemWidget();
+    virtual bool OnEvent(const TBWidgetEvent &ev);
 private:
-	TBSelectItemSource *m_source;
-	TBTextField m_textfield;
-	TBSkinImage m_image;
-	TBSkinImage m_image_arrow;
-	TBMenuWindow *m_menu; ///< Points to the submenu window if opened
-	virtual void OnWidgetDelete(TBWidget *widget);
-	void OpenSubMenu();
-	void CloseSubMenu();
+    TBSelectItemSource *m_source;
+    TBTextField m_textfield;
+    TBSkinImage m_image;
+    TBSkinImage m_image_arrow;
+    TBMenuWindow *m_menu; ///< Points to the submenu window if opened
+    virtual void OnWidgetDelete(TBWidget *widget);
+    void OpenSubMenu();
+    void CloseSubMenu();
 };
 
 // == TBSimpleLayoutItemWidget ==============================================================================
 
 TBSimpleLayoutItemWidget::TBSimpleLayoutItemWidget(TBID image, TBSelectItemSource *source, const char *str)
-	: m_source(source)
-	, m_menu(nullptr)
+    : m_source(source)
+    , m_menu(nullptr)
 {
-	SetSkinBg(TBIDC("TBSelectItem"));
-	SetLayoutDistribution(LAYOUT_DISTRIBUTION_AVAILABLE);
-	SetPaintOverflowFadeout(false);
-
-	if (image)
-	{
-		m_image.SetSkinBg(image);
-		m_image.SetIgnoreInput(true);
-		AddChild(&m_image);
-	}
-
-	m_textfield.SetText(str);
-	m_textfield.SetTextAlign(TB_TEXT_ALIGN_LEFT);
-	m_textfield.SetIgnoreInput(true);
-	AddChild(&m_textfield);
-
-	if (source)
-	{
-		m_image_arrow.SetSkinBg(TBIDC("arrow.right"));
-		m_image_arrow.SetIgnoreInput(true);
-		AddChild(&m_image_arrow);
-	}
+    SetSkinBg(TBIDC("TBSelectItem"));
+    SetLayoutDistribution(LAYOUT_DISTRIBUTION_AVAILABLE);
+    SetPaintOverflowFadeout(false);
+
+    if (image)
+    {
+        m_image.SetSkinBg(image);
+        m_image.SetIgnoreInput(true);
+        AddChild(&m_image);
+    }
+
+    m_textfield.SetText(str);
+    m_textfield.SetTextAlign(TB_TEXT_ALIGN_LEFT);
+    m_textfield.SetIgnoreInput(true);
+    AddChild(&m_textfield);
+
+    if (source)
+    {
+        m_image_arrow.SetSkinBg(TBIDC("arrow.right"));
+        m_image_arrow.SetIgnoreInput(true);
+        AddChild(&m_image_arrow);
+    }
 }
 
 TBSimpleLayoutItemWidget::~TBSimpleLayoutItemWidget()
 {
-	if (m_image_arrow.GetParent())
-		RemoveChild(&m_image_arrow);
-	RemoveChild(&m_textfield);
-	if (m_image.GetParent())
-		RemoveChild(&m_image);
-	CloseSubMenu();
+    if (m_image_arrow.GetParent())
+        RemoveChild(&m_image_arrow);
+    RemoveChild(&m_textfield);
+    if (m_image.GetParent())
+        RemoveChild(&m_image);
+    CloseSubMenu();
 }
 
 bool TBSimpleLayoutItemWidget::OnEvent(const TBWidgetEvent &ev)
 {
-	if (m_source && ev.type == EVENT_TYPE_CLICK && ev.target == this)
-	{
-		OpenSubMenu();
-		return true;
-	}
-	return false;
+    if (m_source && ev.type == EVENT_TYPE_CLICK && ev.target == this)
+    {
+        OpenSubMenu();
+        return true;
+    }
+    return false;
 }
 
 void TBSimpleLayoutItemWidget::OnWidgetDelete(TBWidget *widget)
 {
-	assert(widget == m_menu);
-	CloseSubMenu();
+    assert(widget == m_menu);
+    CloseSubMenu();
 }
 
 void TBSimpleLayoutItemWidget::OpenSubMenu()
 {
-	if (m_menu)
-		return;
-
-	// Open a new menu window for the submenu with this widget as target
-	m_menu = new TBMenuWindow(this, TBIDC("submenu"));
-	if (m_menu)
-	{
-		SetState(WIDGET_STATE_SELECTED, true);
-		m_menu->AddListener(this);
-		m_menu->Show(m_source, TBPopupAlignment(TB_ALIGN_RIGHT), -1);
-	}
+    if (m_menu)
+        return;
+
+    // Open a new menu window for the submenu with this widget as target
+    m_menu = new TBMenuWindow(this, TBIDC("submenu"));
+    if (m_menu)
+    {
+        SetState(WIDGET_STATE_SELECTED, true);
+        m_menu->AddListener(this);
+        m_menu->Show(m_source, TBPopupAlignment(TB_ALIGN_RIGHT), -1);
+    }
 }
 
 void TBSimpleLayoutItemWidget::CloseSubMenu()
 {
-	if (!m_menu)
-		return;
-
-	SetState(WIDGET_STATE_SELECTED, false);
-	m_menu->RemoveListener(this);
-	if (!m_menu->GetIsDying())
-		m_menu->Close();
-	m_menu = nullptr;
+    if (!m_menu)
+        return;
+
+    SetState(WIDGET_STATE_SELECTED, false);
+    m_menu->RemoveListener(this);
+    if (!m_menu->GetIsDying())
+        m_menu->Close();
+    m_menu = nullptr;
 }
 
 // == TBSelectItemViewer ==============================================================================
 
 void TBSelectItemViewer::SetSource(TBSelectItemSource *source)
 {
-	if (m_source == source)
-		return;
+    if (m_source == source)
+        return;
 
-	if (m_source)
-		m_source->m_viewers.Remove(this);
-	m_source = source;
-	if (m_source)
-		m_source->m_viewers.AddLast(this);
+    if (m_source)
+        m_source->m_viewers.Remove(this);
+    m_source = source;
+    if (m_source)
+        m_source->m_viewers.AddLast(this);
 
-	OnSourceChanged();
+    OnSourceChanged();
 }
 
 // == TBSelectItemSource ====================================================================================
@@ -146,75 +146,75 @@ TBSelectItemSource::~TBSelectItemSource()
 
     m_viewers.RemoveAll();
 
-	// If this assert trig, you are deleting a model that's still set on some
-	// TBSelect widget. That might be dangerous.
+    // If this assert trig, you are deleting a model that's still set on some
+    // TBSelect widget. That might be dangerous.
     assert(!m_viewers.HasLinks());
 }
 
 bool TBSelectItemSource::Filter(int index, const char *filter)
 {
-	const char *str = GetItemString(index);
-	if (str && stristr(str, filter))
-		return true;
-	return false;
+    const char *str = GetItemString(index);
+    if (str && stristr(str, filter))
+        return true;
+    return false;
 }
 
 TBWidget *TBSelectItemSource::CreateItemWidget(int index, TBSelectItemViewer *viewer)
 {
-	const char *string = GetItemString(index);
-	TBSelectItemSource *sub_source = GetItemSubSource(index);
-	TBID image = GetItemImage(index);
-	if (sub_source || image)
-	{
-		if (TBSimpleLayoutItemWidget *itemwidget = new TBSimpleLayoutItemWidget(image, sub_source, string))
-			return itemwidget;
-	}
-	else if (string && *string == '-')
-	{
-		if (TBSeparator *separator = new TBSeparator)
-		{
-			separator->SetGravity(WIDGET_GRAVITY_ALL);
-			separator->SetSkinBg(TBIDC("TBSelectItem.separator"));
-			return separator;
-		}
-	}
-	else if (TBTextField *textfield = new TBTextField)
-	{
-		textfield->SetSkinBg("TBSelectItem");
-		textfield->SetText(string);
-		textfield->SetTextAlign(TB_TEXT_ALIGN_LEFT);
-		return textfield;
-	}
-	return nullptr;
+    const char *string = GetItemString(index);
+    TBSelectItemSource *sub_source = GetItemSubSource(index);
+    TBID image = GetItemImage(index);
+    if (sub_source || image)
+    {
+        if (TBSimpleLayoutItemWidget *itemwidget = new TBSimpleLayoutItemWidget(image, sub_source, string))
+            return itemwidget;
+    }
+    else if (string && *string == '-')
+    {
+        if (TBSeparator *separator = new TBSeparator)
+        {
+            separator->SetGravity(WIDGET_GRAVITY_ALL);
+            separator->SetSkinBg(TBIDC("TBSelectItem.separator"));
+            return separator;
+        }
+    }
+    else if (TBTextField *textfield = new TBTextField)
+    {
+        textfield->SetSkinBg("TBSelectItem");
+        textfield->SetText(string);
+        textfield->SetTextAlign(TB_TEXT_ALIGN_LEFT);
+        return textfield;
+    }
+    return nullptr;
 }
 
 void TBSelectItemSource::InvokeItemChanged(int index, TBSelectItemViewer *exclude_viewer)
 {
-	TBLinkListOf<TBSelectItemViewer>::Iterator iter = m_viewers.IterateForward();
-	while (TBSelectItemViewer *viewer = iter.GetAndStep())
-		if (viewer != exclude_viewer)
-			viewer->OnItemChanged(index);
+    TBLinkListOf<TBSelectItemViewer>::Iterator iter = m_viewers.IterateForward();
+    while (TBSelectItemViewer *viewer = iter.GetAndStep())
+        if (viewer != exclude_viewer)
+            viewer->OnItemChanged(index);
 }
 
 void TBSelectItemSource::InvokeItemAdded(int index)
 {
-	TBLinkListOf<TBSelectItemViewer>::Iterator iter = m_viewers.IterateForward();
-	while (TBSelectItemViewer *viewer = iter.GetAndStep())
-		viewer->OnItemAdded(index);
+    TBLinkListOf<TBSelectItemViewer>::Iterator iter = m_viewers.IterateForward();
+    while (TBSelectItemViewer *viewer = iter.GetAndStep())
+        viewer->OnItemAdded(index);
 }
 
 void TBSelectItemSource::InvokeItemRemoved(int index)
 {
-	TBLinkListOf<TBSelectItemViewer>::Iterator iter = m_viewers.IterateForward();
-	while (TBSelectItemViewer *viewer = iter.GetAndStep())
-		viewer->OnItemRemoved(index);
+    TBLinkListOf<TBSelectItemViewer>::Iterator iter = m_viewers.IterateForward();
+    while (TBSelectItemViewer *viewer = iter.GetAndStep())
+        viewer->OnItemRemoved(index);
 }
 
 void TBSelectItemSource::InvokeAllItemsRemoved()
 {
-	TBLinkListOf<TBSelectItemViewer>::Iterator iter = m_viewers.IterateForward();
-	while (TBSelectItemViewer *viewer = iter.GetAndStep())
-		viewer->OnAllItemsRemoved();
+    TBLinkListOf<TBSelectItemViewer>::Iterator iter = m_viewers.IterateForward();
+    while (TBSelectItemViewer *viewer = iter.GetAndStep())
+        viewer->OnAllItemsRemoved();
 }
 
 }; // namespace tb

+ 132 - 132
Source/ThirdParty/TurboBadger/tb_select_item.h

@@ -15,191 +15,191 @@ namespace tb {
 class TBSelectItemSource;
 
 enum TB_SORT {
-	TB_SORT_NONE,		///< No sorting. Items appear in list order.
-	TB_SORT_ASCENDING,	///< Ascending sort.
-	TB_SORT_DESCENDING	///< Descending sort.
+    TB_SORT_NONE,		///< No sorting. Items appear in list order.
+    TB_SORT_ASCENDING,	///< Ascending sort.
+    TB_SORT_DESCENDING	///< Descending sort.
 };
 
 /** TBSelectItemViewer is the viewer for items provided by TBSelectItemSource.
-	There can be multiple viewers for each source. The viewer will recieve
-	callbacks when the source is changed, so it can update itself.
+    There can be multiple viewers for each source. The viewer will recieve
+    callbacks when the source is changed, so it can update itself.
 */
 class TBSelectItemViewer : public TBLinkOf<TBSelectItemViewer>
 {
 public:
-	TBSelectItemViewer() : m_source(nullptr) {}
-	virtual ~TBSelectItemViewer() {}
+    TBSelectItemViewer() : m_source(nullptr) {}
+    virtual ~TBSelectItemViewer() {}
 
-	/** Set the source which should provide the items for this viewer.
-		This source needs to live longer than this viewer.
-		Set nullptr to unset currently set source. */
-	void SetSource(TBSelectItemSource *source);
-	TBSelectItemSource *GetSource() const { return m_source; }
+    /** Set the source which should provide the items for this viewer.
+        This source needs to live longer than this viewer.
+        Set nullptr to unset currently set source. */
+    void SetSource(TBSelectItemSource *source);
+    TBSelectItemSource *GetSource() const { return m_source; }
 
-	/** Called when the source has changed or been unset by calling SetSource. */
-	virtual void OnSourceChanged() = 0;
+    /** Called when the source has changed or been unset by calling SetSource. */
+    virtual void OnSourceChanged() = 0;
 
-	/** Called when the item at the given index has changed in a way that should
-		update the viewer. */
-	virtual void OnItemChanged(int index) = 0;
+    /** Called when the item at the given index has changed in a way that should
+        update the viewer. */
+    virtual void OnItemChanged(int index) = 0;
 
-	/** Called when the item at the given index has been added. */
-	virtual void OnItemAdded(int index) = 0;
+    /** Called when the item at the given index has been added. */
+    virtual void OnItemAdded(int index) = 0;
 
-	/** Called when the item at the given index has been removed. */
-	virtual void OnItemRemoved(int index) = 0;
+    /** Called when the item at the given index has been removed. */
+    virtual void OnItemRemoved(int index) = 0;
 
-	/** Called when all items have been removed. */
-	virtual void OnAllItemsRemoved() = 0;
+    /** Called when all items have been removed. */
+    virtual void OnAllItemsRemoved() = 0;
 protected:
-	TBSelectItemSource *m_source;
+    TBSelectItemSource *m_source;
 };
 
 /** TBSelectItemSource is a item provider interface for list widgets (TBSelectList and
-	TBSelectDropdown).
+    TBSelectDropdown).
 
-	Instead of feeding all list widgets with all items all the time, the list widgets
-	will ask TBSelectItemSource when it needs it. The list widgets may also apply
-	filtering so only a subset of all the items are shown.
+    Instead of feeding all list widgets with all items all the time, the list widgets
+    will ask TBSelectItemSource when it needs it. The list widgets may also apply
+    filtering so only a subset of all the items are shown.
 
-	CreateItemWidget can be overridden to create any set of widget content for each item.
+    CreateItemWidget can be overridden to create any set of widget content for each item.
 
-	This class has no storage of items. If you want an array storage of items,
-	use the subclass TBSelectItemSourceList. If you implement your own storage,
-	remember to call InvokeItem[Added/...] to notify viewers that they need to update.
+    This class has no storage of items. If you want an array storage of items,
+    use the subclass TBSelectItemSourceList. If you implement your own storage,
+    remember to call InvokeItem[Added/...] to notify viewers that they need to update.
 */
 
 class TBSelectItemSource
 {
 public:
-	TBSelectItemSource() : m_sort(TB_SORT_NONE) {}
-	virtual ~TBSelectItemSource();
+    TBSelectItemSource() : m_sort(TB_SORT_NONE) {}
+    virtual ~TBSelectItemSource();
 
-	/** Return true if a item matches the given filter text.
-		By default, it returns true if GetItemString contains filter. */
-	virtual bool Filter(int index, const char *filter);
+    /** Return true if a item matches the given filter text.
+        By default, it returns true if GetItemString contains filter. */
+    virtual bool Filter(int index, const char *filter);
 
-	/** Get the string of a item. If a item has more than one string,
-		return the one that should be used for inline-find (pressing keys
-		in the list will scroll to the item starting with the same letters),
-		and for sorting the list. */
-	virtual const char *GetItemString(int index) = 0;
+    /** Get the string of a item. If a item has more than one string,
+        return the one that should be used for inline-find (pressing keys
+        in the list will scroll to the item starting with the same letters),
+        and for sorting the list. */
+    virtual const char *GetItemString(int index) = 0;
 
-	/** Get the source to be used if this item should open a sub menu. */
-	virtual TBSelectItemSource *GetItemSubSource(int index) { return nullptr; }
+    /** Get the source to be used if this item should open a sub menu. */
+    virtual TBSelectItemSource *GetItemSubSource(int index) { return nullptr; }
 
-	/** Get the skin image to be painted before the text for this item. */
-	virtual TBID GetItemImage(int index) { return TBID(); }
+    /** Get the skin image to be painted before the text for this item. */
+    virtual TBID GetItemImage(int index) { return TBID(); }
 
-	/** Get the if of the item. */
-	virtual TBID GetItemID(int index) { return TBID(); }
+    /** Get the if of the item. */
+    virtual TBID GetItemID(int index) { return TBID(); }
 
-	/** Create the item representation widget(s). By default, it will create
-		a TBTextField for string-only items, and other types for items that
-		also has image or submenu. */
-	virtual TBWidget *CreateItemWidget(int index, TBSelectItemViewer *viewer);
+    /** Create the item representation widget(s). By default, it will create
+        a TBTextField for string-only items, and other types for items that
+        also has image or submenu. */
+    virtual TBWidget *CreateItemWidget(int index, TBSelectItemViewer *viewer);
 
-	/** Get the number of items */
-	virtual int GetNumItems() = 0;
+    /** Get the number of items */
+    virtual int GetNumItems() = 0;
 
-	/** Set sort type. Default is TB_SORT_NONE. */
-	void SetSort(TB_SORT sort) { m_sort = sort; }
-	TB_SORT GetSort() const { return m_sort; }
+    /** Set sort type. Default is TB_SORT_NONE. */
+    void SetSort(TB_SORT sort) { m_sort = sort; }
+    TB_SORT GetSort() const { return m_sort; }
 
-	/** Invoke OnItemChanged on all open viewers for this source. */
-	void InvokeItemChanged(int index, TBSelectItemViewer *exclude_viewer = nullptr);
-	void InvokeItemAdded(int index);
-	void InvokeItemRemoved(int index);
-	void InvokeAllItemsRemoved();
+    /** Invoke OnItemChanged on all open viewers for this source. */
+    void InvokeItemChanged(int index, TBSelectItemViewer *exclude_viewer = nullptr);
+    void InvokeItemAdded(int index);
+    void InvokeItemRemoved(int index);
+    void InvokeAllItemsRemoved();
 private:
-	friend class TBSelectItemViewer;
-	TBLinkListOf<TBSelectItemViewer> m_viewers;
-	TB_SORT m_sort;
+    friend class TBSelectItemViewer;
+    TBLinkListOf<TBSelectItemViewer> m_viewers;
+    TB_SORT m_sort;
 };
 
 /** TBSelectItemSourceList is a item provider for list widgets (TBSelectList and
-	TBSelectDropdown). It stores items of the type specified by the template in an array. */
+    TBSelectDropdown). It stores items of the type specified by the template in an array. */
 
 template<class T>
 class TBSelectItemSourceList : public TBSelectItemSource
 {
 public:
-	TBSelectItemSourceList() {}
-	virtual ~TBSelectItemSourceList()					{ DeleteAllItems(); }
-	virtual const char *GetItemString(int index)		{ return GetItem(index)->str; }
-	virtual TBSelectItemSource *GetItemSubSource(int index){ return GetItem(index)->sub_source; }
-	virtual TBID GetItemImage(int index)				{ return GetItem(index)->skin_image; }
-	virtual TBID GetItemID(int index)					{ return GetItem(index)->id; }
-	virtual int GetNumItems()							{ return m_items.GetNumItems(); }
-	virtual TBWidget *CreateItemWidget(int index, TBSelectItemViewer *viewer)
-	{
-		if (TBWidget *widget = TBSelectItemSource::CreateItemWidget(index, viewer))
-		{
-			T *item = m_items[index];
-			widget->SetID(item->id);
-			return widget;
-		}
-		return nullptr;
-	}
-
-	/** Add a new item at the given index. */
-	bool AddItem(T *item, int index)
-	{
-		if (m_items.Add(item, index))
-		{
-			InvokeItemAdded(index);
-			return true;
-		}
-		return false;
-	}
-
-	/** Add a new item last. */
-	bool AddItem(T *item)				{ return AddItem(item, m_items.GetNumItems()); }
-
-	/** Get the item at the given index. */
-	T *GetItem(int index)				{ return m_items[index]; }
-
-	/** Delete the item at the given index. */
-	void DeleteItem(int index)
-	{
-		if (!m_items.GetNumItems())
-			return;
-		m_items.Delete(index);
-		InvokeItemRemoved(index);
-	}
-
-	/** Delete all items. */
-	void DeleteAllItems()
-	{
-		if (!m_items.GetNumItems())
-			return;
-		m_items.DeleteAll();
-		InvokeAllItemsRemoved();
-	}
+    TBSelectItemSourceList() {}
+    virtual ~TBSelectItemSourceList()					{ DeleteAllItems(); }
+    virtual const char *GetItemString(int index)		{ return GetItem(index)->str; }
+    virtual TBSelectItemSource *GetItemSubSource(int index){ return GetItem(index)->sub_source; }
+    virtual TBID GetItemImage(int index)				{ return GetItem(index)->skin_image; }
+    virtual TBID GetItemID(int index)					{ return GetItem(index)->id; }
+    virtual int GetNumItems()							{ return m_items.GetNumItems(); }
+    virtual TBWidget *CreateItemWidget(int index, TBSelectItemViewer *viewer)
+    {
+        if (TBWidget *widget = TBSelectItemSource::CreateItemWidget(index, viewer))
+        {
+            T *item = m_items[index];
+            widget->SetID(item->id);
+            return widget;
+        }
+        return nullptr;
+    }
+
+    /** Add a new item at the given index. */
+    bool AddItem(T *item, int index)
+    {
+        if (m_items.Add(item, index))
+        {
+            InvokeItemAdded(index);
+            return true;
+        }
+        return false;
+    }
+
+    /** Add a new item last. */
+    bool AddItem(T *item)				{ return AddItem(item, m_items.GetNumItems()); }
+
+    /** Get the item at the given index. */
+    T *GetItem(int index)				{ return m_items[index]; }
+
+    /** Delete the item at the given index. */
+    void DeleteItem(int index)
+    {
+        if (!m_items.GetNumItems())
+            return;
+        m_items.Delete(index);
+        InvokeItemRemoved(index);
+    }
+
+    /** Delete all items. */
+    void DeleteAllItems()
+    {
+        if (!m_items.GetNumItems())
+            return;
+        m_items.DeleteAll();
+        InvokeAllItemsRemoved();
+    }
 private:
-	TBListOf<T> m_items;
+    TBListOf<T> m_items;
 };
 
 /** TBGenericStringItem item for TBGenericStringItemSource.
-	It has a string and may have a skin image and sub item source. */
+    It has a string and may have a skin image and sub item source. */
 class TBGenericStringItem
 {
 public:
-	TBGenericStringItem(const TBGenericStringItem& other) : str(other.str), id(other.id), sub_source(other.sub_source), tag(other.tag) {}
-	TBGenericStringItem(const char *str) : str(str), sub_source(nullptr) {}
-	TBGenericStringItem(const char *str, TBID id) : str(str), id(id), sub_source(nullptr) {}
-	TBGenericStringItem(const char *str, TBSelectItemSource *sub_source) : str(str), sub_source(sub_source) {}
-	const TBGenericStringItem& operator = (const TBGenericStringItem &other) { str.Set(other.str); id = other.id; sub_source = other.sub_source; tag = other.tag; return *this; }
+    TBGenericStringItem(const TBGenericStringItem& other) : str(other.str), id(other.id), sub_source(other.sub_source), tag(other.tag) {}
+    TBGenericStringItem(const char *str) : str(str), sub_source(nullptr) {}
+    TBGenericStringItem(const char *str, TBID id) : str(str), id(id), sub_source(nullptr) {}
+    TBGenericStringItem(const char *str, TBSelectItemSource *sub_source) : str(str), sub_source(sub_source) {}
+    const TBGenericStringItem& operator = (const TBGenericStringItem &other) { str.Set(other.str); id = other.id; sub_source = other.sub_source; tag = other.tag; return *this; }
 
-	void SetSkinImage(const TBID &image) { skin_image = image; }
+    void SetSkinImage(const TBID &image) { skin_image = image; }
 public:
-	TBStr str;
-	TBID id;
-	TBID skin_image;
-	TBSelectItemSource *sub_source;
+    TBStr str;
+    TBID id;
+    TBID skin_image;
+    TBSelectItemSource *sub_source;
 
-	/** This value is free to use for anything. It's not used internally. */
-	TBValue tag;
+    /** This value is free to use for anything. It's not used internally. */
+    TBValue tag;
 };
 
 /** TBGenericStringItemSource is a item source list providing items of type TBGenericStringItem. */

+ 629 - 629
Source/ThirdParty/TurboBadger/tb_skin.cpp

@@ -17,550 +17,550 @@ namespace tb {
 
 /*TB_TEXT_ALIGN StringToTextAlign(const char *align_str)
 {
-	TB_TEXT_ALIGN align = TB_TEXT_ALIGN_CENTER;
-	if (strstr(state_str, "left"))		align = TB_TEXT_ALIGN_LEFT;
-	if (strstr(state_str, "center"))	align = TB_TEXT_ALIGN_CENTER;
-	if (strstr(state_str, "right"))		align = TB_TEXT_ALIGN_RIGHT;
-	return state;
+    TB_TEXT_ALIGN align = TB_TEXT_ALIGN_CENTER;
+    if (strstr(state_str, "left"))		align = TB_TEXT_ALIGN_LEFT;
+    if (strstr(state_str, "center"))	align = TB_TEXT_ALIGN_CENTER;
+    if (strstr(state_str, "right"))		align = TB_TEXT_ALIGN_RIGHT;
+    return state;
 }*/
 
 SKIN_STATE StringToState(const char *state_str)
 {
-	SKIN_STATE state = SKIN_STATE_NONE;
-	if (strstr(state_str, "all"))		state |= SKIN_STATE_ALL;
-	if (strstr(state_str, "disabled"))	state |= SKIN_STATE_DISABLED;
-	if (strstr(state_str, "focused"))	state |= SKIN_STATE_FOCUSED;
-	if (strstr(state_str, "pressed"))	state |= SKIN_STATE_PRESSED;
-	if (strstr(state_str, "selected"))	state |= SKIN_STATE_SELECTED;
-	if (strstr(state_str, "hovered"))	state |= SKIN_STATE_HOVERED;
-	return state;
+    SKIN_STATE state = SKIN_STATE_NONE;
+    if (strstr(state_str, "all"))		state |= SKIN_STATE_ALL;
+    if (strstr(state_str, "disabled"))	state |= SKIN_STATE_DISABLED;
+    if (strstr(state_str, "focused"))	state |= SKIN_STATE_FOCUSED;
+    if (strstr(state_str, "pressed"))	state |= SKIN_STATE_PRESSED;
+    if (strstr(state_str, "selected"))	state |= SKIN_STATE_SELECTED;
+    if (strstr(state_str, "hovered"))	state |= SKIN_STATE_HOVERED;
+    return state;
 }
 
 SKIN_ELEMENT_TYPE StringToType(const char *type_str)
 {
-	if (strcmp(type_str, "StretchBox") == 0)
-		return SKIN_ELEMENT_TYPE_STRETCH_BOX;
-	else if (strcmp(type_str, "Image") == 0)
-		return SKIN_ELEMENT_TYPE_IMAGE;
-	else if (strcmp(type_str, "Stretch Image") == 0)
-		return SKIN_ELEMENT_TYPE_STRETCH_IMAGE;
-	else if (strcmp(type_str, "Tile") == 0)
-		return SKIN_ELEMENT_TYPE_TILE;
-	else if (strcmp(type_str, "StretchBorder") == 0)
-		return SKIN_ELEMENT_TYPE_STRETCH_BORDER;
-	TBDebugOut("Skin error: Unknown skin type!\n");
-	return SKIN_ELEMENT_TYPE_STRETCH_BOX;
+    if (strcmp(type_str, "StretchBox") == 0)
+        return SKIN_ELEMENT_TYPE_STRETCH_BOX;
+    else if (strcmp(type_str, "Image") == 0)
+        return SKIN_ELEMENT_TYPE_IMAGE;
+    else if (strcmp(type_str, "Stretch Image") == 0)
+        return SKIN_ELEMENT_TYPE_STRETCH_IMAGE;
+    else if (strcmp(type_str, "Tile") == 0)
+        return SKIN_ELEMENT_TYPE_TILE;
+    else if (strcmp(type_str, "StretchBorder") == 0)
+        return SKIN_ELEMENT_TYPE_STRETCH_BORDER;
+    TBDebugOut("Skin error: Unknown skin type!\n");
+    return SKIN_ELEMENT_TYPE_STRETCH_BOX;
 }
 
 TBSkinCondition::TARGET StringToTarget(const char *target_str)
 {
-	if (strcmp(target_str, "this") == 0)
-		return TBSkinCondition::TARGET_THIS;
-	else if (strcmp(target_str, "parent") == 0)
-		return TBSkinCondition::TARGET_PARENT;
-	else if (strcmp(target_str, "ancestors") == 0)
-		return TBSkinCondition::TARGET_ANCESTORS;
-	else if (strcmp(target_str, "prev sibling") == 0)
-		return TBSkinCondition::TARGET_PREV_SIBLING;
-	else if (strcmp(target_str, "next sibling") == 0)
-		return TBSkinCondition::TARGET_NEXT_SIBLING;
-	TBDebugOut("Skin error: Unknown target in condition!\n");
-	return TBSkinCondition::TARGET_THIS;
+    if (strcmp(target_str, "this") == 0)
+        return TBSkinCondition::TARGET_THIS;
+    else if (strcmp(target_str, "parent") == 0)
+        return TBSkinCondition::TARGET_PARENT;
+    else if (strcmp(target_str, "ancestors") == 0)
+        return TBSkinCondition::TARGET_ANCESTORS;
+    else if (strcmp(target_str, "prev sibling") == 0)
+        return TBSkinCondition::TARGET_PREV_SIBLING;
+    else if (strcmp(target_str, "next sibling") == 0)
+        return TBSkinCondition::TARGET_NEXT_SIBLING;
+    TBDebugOut("Skin error: Unknown target in condition!\n");
+    return TBSkinCondition::TARGET_THIS;
 }
 
 TBSkinCondition::PROPERTY StringToProperty(const char *prop_str)
 {
-	if (strcmp(prop_str, "skin") == 0)
-		return TBSkinCondition::PROPERTY_SKIN;
-	else if (strcmp(prop_str, "window active") == 0)
-		return TBSkinCondition::PROPERTY_WINDOW_ACTIVE;
-	else if (strcmp(prop_str, "axis") == 0)
-		return TBSkinCondition::PROPERTY_AXIS;
-	else if (strcmp(prop_str, "align") == 0)
-		return TBSkinCondition::PROPERTY_ALIGN;
-	else if (strcmp(prop_str, "id") == 0)
-		return TBSkinCondition::PROPERTY_ID;
-	else if (strcmp(prop_str, "state") == 0)
-		return TBSkinCondition::PROPERTY_STATE;
-	else if (strcmp(prop_str, "value") == 0)
-		return TBSkinCondition::PROPERTY_VALUE;
-	else if (strcmp(prop_str, "hover") == 0)
-		return TBSkinCondition::PROPERTY_HOVER;
-	else if (strcmp(prop_str, "capture") == 0)
-		return TBSkinCondition::PROPERTY_CAPTURE;
-	else if (strcmp(prop_str, "focus") == 0)
-		return TBSkinCondition::PROPERTY_FOCUS;
-	return TBSkinCondition::PROPERTY_CUSTOM;
+    if (strcmp(prop_str, "skin") == 0)
+        return TBSkinCondition::PROPERTY_SKIN;
+    else if (strcmp(prop_str, "window active") == 0)
+        return TBSkinCondition::PROPERTY_WINDOW_ACTIVE;
+    else if (strcmp(prop_str, "axis") == 0)
+        return TBSkinCondition::PROPERTY_AXIS;
+    else if (strcmp(prop_str, "align") == 0)
+        return TBSkinCondition::PROPERTY_ALIGN;
+    else if (strcmp(prop_str, "id") == 0)
+        return TBSkinCondition::PROPERTY_ID;
+    else if (strcmp(prop_str, "state") == 0)
+        return TBSkinCondition::PROPERTY_STATE;
+    else if (strcmp(prop_str, "value") == 0)
+        return TBSkinCondition::PROPERTY_VALUE;
+    else if (strcmp(prop_str, "hover") == 0)
+        return TBSkinCondition::PROPERTY_HOVER;
+    else if (strcmp(prop_str, "capture") == 0)
+        return TBSkinCondition::PROPERTY_CAPTURE;
+    else if (strcmp(prop_str, "focus") == 0)
+        return TBSkinCondition::PROPERTY_FOCUS;
+    return TBSkinCondition::PROPERTY_CUSTOM;
 }
 
 // == TBSkinCondition =======================================================
 
 TBSkinCondition::TBSkinCondition(TARGET target, PROPERTY prop, const TBID &custom_prop, const TBID &value, TEST test)
-	: m_target(target)
-	, m_test(test)
+    : m_target(target)
+    , m_test(test)
 {
-	m_info.prop = prop;
-	m_info.custom_prop = custom_prop;
-	m_info.value = value;
+    m_info.prop = prop;
+    m_info.custom_prop = custom_prop;
+    m_info.value = value;
 }
 
 bool TBSkinCondition::GetCondition(TBSkinConditionContext &context) const
 {
-	bool equal = context.GetCondition(m_target, m_info);
-	return equal == (m_test == TEST_EQUAL);
+    bool equal = context.GetCondition(m_target, m_info);
+    return equal == (m_test == TEST_EQUAL);
 }
 
 // == TBSkin ================================================================
 
 TBSkin::TBSkin()
-	: m_listener(nullptr)
-	, m_default_disabled_opacity(0.3f)
-	, m_default_placeholder_opacity(0.2f)
-	, m_default_spacing(0)
+    : m_listener(nullptr)
+    , m_default_disabled_opacity(0.3f)
+    , m_default_placeholder_opacity(0.2f)
+    , m_default_spacing(0)
 {
-	g_renderer->AddListener(this);
+    g_renderer->AddListener(this);
 
-	// Avoid filtering artifacts at edges when we draw fragments stretched.
-	m_frag_manager.SetAddBorder(true);
+    // Avoid filtering artifacts at edges when we draw fragments stretched.
+    m_frag_manager.SetAddBorder(true);
 }
 
 bool TBSkin::Load(const char *skin_file, const char *override_skin_file)
 {
-	if (!LoadInternal(skin_file))
-		return false;
+    if (!LoadInternal(skin_file))
+        return false;
     if (override_skin_file && strlen(override_skin_file) && !LoadInternal(override_skin_file))
-		return false;
-	return ReloadBitmaps();
+        return false;
+    return ReloadBitmaps();
 }
 
 bool TBSkin::LoadInternal(const char *skin_file)
 {
-	TBNode node;
-	if (!node.ReadFile(skin_file))
-		return false;
-
-	TBTempBuffer skin_path;
-	if (!skin_path.AppendPath(skin_file))
-		return false;
-
-	if (node.GetNode("description"))
-	{
-		// Check which DPI mode the dimension converter should use.
-		// The base-dpi is the dpi in which the padding, spacing (and so on)
-		// is specified in. If the skin supports a different DPI that is
-		// closer to the screen DPI, all such dimensions will be scaled.
-		int base_dpi = node.GetValueInt("description>base-dpi", 96);
-		int supported_dpi = base_dpi;
-		if (TBNode *supported_dpi_node = node.GetNode("description>supported-dpi"))
-		{
-			assert(supported_dpi_node->GetValue().IsArray() || supported_dpi_node->GetValue().GetInt() == base_dpi);
-			if (TBValueArray *arr = supported_dpi_node->GetValue().GetArray())
-			{
-				int screen_dpi = TBSystem::GetDPI();
-				int best_supported_dpi = 0;
-				for (int i = 0; i < arr->GetLength(); i++)
-				{
-					int candidate_dpi = arr->GetValue(i)->GetInt();
-					if (!best_supported_dpi || ABS(candidate_dpi - screen_dpi) < ABS(best_supported_dpi - screen_dpi))
-						best_supported_dpi = candidate_dpi;
-				}
-				supported_dpi = best_supported_dpi;
-			}
-		}
-		m_dim_conv.SetDPI(base_dpi, supported_dpi);
-	}
-
-	// Read skin constants
-	if (const char *color = node.GetValueString("defaults>text-color", nullptr))
-		m_default_text_color.SetFromString(color, strlen(color));
-	m_default_disabled_opacity = node.GetValueFloat("defaults>disabled>opacity",
-		m_default_disabled_opacity);
-	m_default_placeholder_opacity = node.GetValueFloat("defaults>placeholder>opacity",
-		m_default_placeholder_opacity);
-	m_default_spacing = GetPxFromNode(node.GetNode("defaults>spacing"), m_default_spacing);
-
-	// Iterate through all elements nodes and add skin elements or patch already
-	// existing elements.
-	TBNode *elements = node.GetNode("elements");
-	if (elements)
-	{
-		TBNode *n = elements->GetFirstChild();
-		while (n)
-		{
-			// If we have a "clone" node, clone all children from that node
-			// into this node.
-			while (TBNode *clone = n->GetNode("clone"))
-			{
-				n->Remove(clone);
-
-				TBNode *clone_source = elements->GetNode(clone->GetValue().GetString());
-				if (clone_source)
-					n->CloneChildren(clone_source);
-
-				delete clone;
-			}
-
-			// If the skin element already exist, we will call Load on it again.
-			// This will patch the element with any new data from the node.
-			TBID element_id(n->GetName());
-			TBSkinElement *e = GetSkinElement(element_id);
-			if (!e)
-			{
-				e = new TBSkinElement;
-				if (!e)
-					return false;
-				m_elements.Add(element_id, e);
-			}
-
-			e->Load(n, this, skin_path.GetData());
-			if (m_listener)
-				m_listener->OnSkinElementLoaded(this, e, n);
-
-			n = n->GetNext();
-		}
-	}
-	return true;
+    TBNode node;
+    if (!node.ReadFile(skin_file))
+        return false;
+
+    TBTempBuffer skin_path;
+    if (!skin_path.AppendPath(skin_file))
+        return false;
+
+    if (node.GetNode("description"))
+    {
+        // Check which DPI mode the dimension converter should use.
+        // The base-dpi is the dpi in which the padding, spacing (and so on)
+        // is specified in. If the skin supports a different DPI that is
+        // closer to the screen DPI, all such dimensions will be scaled.
+        int base_dpi = node.GetValueInt("description>base-dpi", 96);
+        int supported_dpi = base_dpi;
+        if (TBNode *supported_dpi_node = node.GetNode("description>supported-dpi"))
+        {
+            assert(supported_dpi_node->GetValue().IsArray() || supported_dpi_node->GetValue().GetInt() == base_dpi);
+            if (TBValueArray *arr = supported_dpi_node->GetValue().GetArray())
+            {
+                int screen_dpi = TBSystem::GetDPI();
+                int best_supported_dpi = 0;
+                for (int i = 0; i < arr->GetLength(); i++)
+                {
+                    int candidate_dpi = arr->GetValue(i)->GetInt();
+                    if (!best_supported_dpi || ABS(candidate_dpi - screen_dpi) < ABS(best_supported_dpi - screen_dpi))
+                        best_supported_dpi = candidate_dpi;
+                }
+                supported_dpi = best_supported_dpi;
+            }
+        }
+        m_dim_conv.SetDPI(base_dpi, supported_dpi);
+    }
+
+    // Read skin constants
+    if (const char *color = node.GetValueString("defaults>text-color", nullptr))
+        m_default_text_color.SetFromString(color, strlen(color));
+    m_default_disabled_opacity = node.GetValueFloat("defaults>disabled>opacity",
+                                                    m_default_disabled_opacity);
+    m_default_placeholder_opacity = node.GetValueFloat("defaults>placeholder>opacity",
+                                                       m_default_placeholder_opacity);
+    m_default_spacing = GetPxFromNode(node.GetNode("defaults>spacing"), m_default_spacing);
+
+    // Iterate through all elements nodes and add skin elements or patch already
+    // existing elements.
+    TBNode *elements = node.GetNode("elements");
+    if (elements)
+    {
+        TBNode *n = elements->GetFirstChild();
+        while (n)
+        {
+            // If we have a "clone" node, clone all children from that node
+            // into this node.
+            while (TBNode *clone = n->GetNode("clone"))
+            {
+                n->Remove(clone);
+
+                TBNode *clone_source = elements->GetNode(clone->GetValue().GetString());
+                if (clone_source)
+                    n->CloneChildren(clone_source);
+
+                delete clone;
+            }
+
+            // If the skin element already exist, we will call Load on it again.
+            // This will patch the element with any new data from the node.
+            TBID element_id(n->GetName());
+            TBSkinElement *e = GetSkinElement(element_id);
+            if (!e)
+            {
+                e = new TBSkinElement;
+                if (!e)
+                    return false;
+                m_elements.Add(element_id, e);
+            }
+
+            e->Load(n, this, skin_path.GetData());
+            if (m_listener)
+                m_listener->OnSkinElementLoaded(this, e, n);
+
+            n = n->GetNext();
+        }
+    }
+    return true;
 }
 
 void TBSkin::UnloadBitmaps()
 {
-	// Unset all bitmap pointers.
-	TBHashTableIteratorOf<TBSkinElement> it(&m_elements);
-	while (TBSkinElement *element = it.GetNextContent())
-		element->bitmap = nullptr;
+    // Unset all bitmap pointers.
+    TBHashTableIteratorOf<TBSkinElement> it(&m_elements);
+    while (TBSkinElement *element = it.GetNextContent())
+        element->bitmap = nullptr;
 
-	// Clear all fragments and bitmaps.
-	m_frag_manager.Clear();
+    // Clear all fragments and bitmaps.
+    m_frag_manager.Clear();
 }
 
 bool TBSkin::ReloadBitmaps()
 {
-	UnloadBitmaps();
-	bool success = ReloadBitmapsInternal();
-	// Create all bitmaps for the bitmap fragment maps
-	if (success)
-		success = m_frag_manager.ValidateBitmaps();
+    UnloadBitmaps();
+    bool success = ReloadBitmapsInternal();
+    // Create all bitmaps for the bitmap fragment maps
+    if (success)
+        success = m_frag_manager.ValidateBitmaps();
 
 #ifdef TB_RUNTIME_DEBUG_INFO
-	TBStr info;
-	info.SetFormatted("Skin loaded using %d bitmaps.\n", m_frag_manager.GetNumMaps());
-	TBDebugOut(info);
+    TBStr info;
+    info.SetFormatted("Skin loaded using %d bitmaps.\n", m_frag_manager.GetNumMaps());
+    TBDebugOut(info);
 #endif
-	return success;
+    return success;
 }
 
 bool TBSkin::ReloadBitmapsInternal()
 {
-	// Load all bitmap files into new bitmap fragments.
-	TBTempBuffer filename_dst_DPI;
-	bool success = true;
-	TBHashTableIteratorOf<TBSkinElement> it(&m_elements);
-	while (TBSkinElement *element = it.GetNextContent())
-	{
-		if (!element->bitmap_file.IsEmpty())
-		{
-			assert(!element->bitmap);
-
-			// FIX: dedicated_map is not needed for all backends (only deprecated fixed function GL)
-			bool dedicated_map = element->type == SKIN_ELEMENT_TYPE_TILE;
-
-			// Try to load bitmap fragment in the destination DPI (F.ex "foo.png" becomes "[email protected]")
-			int bitmap_dpi = m_dim_conv.GetSrcDPI();
-			if (m_dim_conv.NeedConversion())
-			{
-				m_dim_conv.GetDstDPIFilename(element->bitmap_file, &filename_dst_DPI);
-				element->bitmap = m_frag_manager.GetFragmentFromFile(filename_dst_DPI.GetData(), dedicated_map);
-				if (element->bitmap)
-					bitmap_dpi = m_dim_conv.GetDstDPI();
-			}
-			element->SetBitmapDPI(m_dim_conv, bitmap_dpi);
-
-			// If we still have no bitmap fragment, load from default file.
-			if (!element->bitmap)
-				element->bitmap = m_frag_manager.GetFragmentFromFile(element->bitmap_file, dedicated_map);
-
-			if (!element->bitmap)
-				success = false;
-		}
-	}
-	return success;
+    // Load all bitmap files into new bitmap fragments.
+    TBTempBuffer filename_dst_DPI;
+    bool success = true;
+    TBHashTableIteratorOf<TBSkinElement> it(&m_elements);
+    while (TBSkinElement *element = it.GetNextContent())
+    {
+        if (!element->bitmap_file.IsEmpty())
+        {
+            assert(!element->bitmap);
+
+            // FIX: dedicated_map is not needed for all backends (only deprecated fixed function GL)
+            bool dedicated_map = element->type == SKIN_ELEMENT_TYPE_TILE;
+
+            // Try to load bitmap fragment in the destination DPI (F.ex "foo.png" becomes "[email protected]")
+            int bitmap_dpi = m_dim_conv.GetSrcDPI();
+            if (m_dim_conv.NeedConversion())
+            {
+                m_dim_conv.GetDstDPIFilename(element->bitmap_file, &filename_dst_DPI);
+                element->bitmap = m_frag_manager.GetFragmentFromFile(filename_dst_DPI.GetData(), dedicated_map);
+                if (element->bitmap)
+                    bitmap_dpi = m_dim_conv.GetDstDPI();
+            }
+            element->SetBitmapDPI(m_dim_conv, bitmap_dpi);
+
+            // If we still have no bitmap fragment, load from default file.
+            if (!element->bitmap)
+                element->bitmap = m_frag_manager.GetFragmentFromFile(element->bitmap_file, dedicated_map);
+
+            if (!element->bitmap)
+                success = false;
+        }
+    }
+    return success;
 }
 
 TBSkin::~TBSkin()
 {
-	g_renderer->RemoveListener(this);
+    g_renderer->RemoveListener(this);
 }
 
 TBSkinElement *TBSkin::GetSkinElement(const TBID &skin_id) const
 {
-	if (!skin_id)
-		return nullptr;
-	return m_elements.Get(skin_id);
+    if (!skin_id)
+        return nullptr;
+    return m_elements.Get(skin_id);
 }
 
 TBSkinElement *TBSkin::GetSkinElementStrongOverride(const TBID &skin_id, SKIN_STATE state, TBSkinConditionContext &context) const
 {
-	if (TBSkinElement *skin_element = GetSkinElement(skin_id))
-	{
-		// Avoid eternal recursion when overrides refer to elements referring back.
-		if (skin_element->is_getting)
-			return nullptr;
-		skin_element->is_getting = true;
-
-		// Check if there's any strong overrides for this element with the given state.
-		TBSkinElementState *override_state = skin_element->m_strong_override_elements.GetStateElement(state, context);
-		if (override_state)
-		{
-			if (TBSkinElement *override_element = GetSkinElementStrongOverride(override_state->element_id, state, context))
-			{
-				skin_element->is_getting = false;
-				return override_element;
-			}
-		}
-
-		skin_element->is_getting = false;
-		return skin_element;
-	}
-	return nullptr;
+    if (TBSkinElement *skin_element = GetSkinElement(skin_id))
+    {
+        // Avoid eternal recursion when overrides refer to elements referring back.
+        if (skin_element->is_getting)
+            return nullptr;
+        skin_element->is_getting = true;
+
+        // Check if there's any strong overrides for this element with the given state.
+        TBSkinElementState *override_state = skin_element->m_strong_override_elements.GetStateElement(state, context);
+        if (override_state)
+        {
+            if (TBSkinElement *override_element = GetSkinElementStrongOverride(override_state->element_id, state, context))
+            {
+                skin_element->is_getting = false;
+                return override_element;
+            }
+        }
+
+        skin_element->is_getting = false;
+        return skin_element;
+    }
+    return nullptr;
 }
 
 TBSkinElement *TBSkin::PaintSkin(const TBRect &dst_rect, const TBID &skin_id, SKIN_STATE state, TBSkinConditionContext &context)
 {
-	return PaintSkin(dst_rect, GetSkinElement(skin_id), state, context);
+    return PaintSkin(dst_rect, GetSkinElement(skin_id), state, context);
 }
 
 TBSkinElement *TBSkin::PaintSkin(const TBRect &dst_rect, TBSkinElement *element, SKIN_STATE state, TBSkinConditionContext &context)
 {
-	if (!element || element->is_painting)
-		return nullptr;
-
-	// Avoid potential endless recursion in evil skins
-	element->is_painting = true;
-
-	// Return the override if we have one.
-	TBSkinElement *return_element = element;
-
-	TB_IF_DEBUG(bool paint_error_highlight = false);
-
-	// If there's any override for this state, paint it.
-	TBSkinElementState *override_state = element->m_override_elements.GetStateElement(state, context);
-	if (override_state)
-	{
-		if (TBSkinElement *used_override = PaintSkin(dst_rect, override_state->element_id, state, context))
-			return_element = used_override;
-		else
-		{
-			TB_IF_DEBUG(paint_error_highlight = true);
-			TBDebugOut("Skin error: The skin references a missing element, or has a reference loop!\n");
-			// Fall back to the standard skin.
-			override_state = nullptr;
-		}
-	}
-
-	// If there was no override, paint the standard skin element.
-	if (!override_state)
-		PaintElement(dst_rect, element);
-
-	// Paint all child elements that matches the state (or should be painted for all states)
-	if (element->m_child_elements.HasStateElements())
-	{
-		const TBSkinElementState *state_element = element->m_child_elements.GetFirstElement();
-		while (state_element)
-		{
-			if (state_element->IsMatch(state, context))
-				PaintSkin(dst_rect, state_element->element_id, state_element->state & state, context);
-			state_element = state_element->GetNext();
-		}
-	}
-
-	// Paint ugly rectangles on invalid skin elements in debug builds.
-	TB_IF_DEBUG(if (paint_error_highlight) g_renderer->DrawRect(dst_rect.Expand(1, 1), TBColor(255, 205, 0)));
-	TB_IF_DEBUG(if (paint_error_highlight) g_renderer->DrawRect(dst_rect.Shrink(1, 1), TBColor(255, 0, 0)));
-
-	element->is_painting = false;
-	return return_element;
+    if (!element || element->is_painting)
+        return nullptr;
+
+    // Avoid potential endless recursion in evil skins
+    element->is_painting = true;
+
+    // Return the override if we have one.
+    TBSkinElement *return_element = element;
+
+    TB_IF_DEBUG(bool paint_error_highlight = false);
+
+    // If there's any override for this state, paint it.
+    TBSkinElementState *override_state = element->m_override_elements.GetStateElement(state, context);
+    if (override_state)
+    {
+        if (TBSkinElement *used_override = PaintSkin(dst_rect, override_state->element_id, state, context))
+            return_element = used_override;
+        else
+        {
+            TB_IF_DEBUG(paint_error_highlight = true);
+            TBDebugOut("Skin error: The skin references a missing element, or has a reference loop!\n");
+            // Fall back to the standard skin.
+            override_state = nullptr;
+        }
+    }
+
+    // If there was no override, paint the standard skin element.
+    if (!override_state)
+        PaintElement(dst_rect, element);
+
+    // Paint all child elements that matches the state (or should be painted for all states)
+    if (element->m_child_elements.HasStateElements())
+    {
+        const TBSkinElementState *state_element = element->m_child_elements.GetFirstElement();
+        while (state_element)
+        {
+            if (state_element->IsMatch(state, context))
+                PaintSkin(dst_rect, state_element->element_id, state_element->state & state, context);
+            state_element = state_element->GetNext();
+        }
+    }
+
+    // Paint ugly rectangles on invalid skin elements in debug builds.
+    TB_IF_DEBUG(if (paint_error_highlight) g_renderer->DrawRect(dst_rect.Expand(1, 1), TBColor(255, 205, 0)));
+    TB_IF_DEBUG(if (paint_error_highlight) g_renderer->DrawRect(dst_rect.Shrink(1, 1), TBColor(255, 0, 0)));
+
+    element->is_painting = false;
+    return return_element;
 }
 
 void TBSkin::PaintSkinOverlay(const TBRect &dst_rect, TBSkinElement *element, SKIN_STATE state, TBSkinConditionContext &context)
 {
-	if (!element || element->is_painting)
-		return;
+    if (!element || element->is_painting)
+        return;
 
-	// Avoid potential endless recursion in evil skins
-	element->is_painting = true;
+    // Avoid potential endless recursion in evil skins
+    element->is_painting = true;
 
-	// Paint all overlay elements that matches the state (or should be painted for all states)
-	const TBSkinElementState *state_element = element->m_overlay_elements.GetFirstElement();
-	while (state_element)
-	{
-		if (state_element->IsMatch(state, context))
-			PaintSkin(dst_rect, state_element->element_id, state_element->state & state, context);
-		state_element = state_element->GetNext();
-	}
+    // Paint all overlay elements that matches the state (or should be painted for all states)
+    const TBSkinElementState *state_element = element->m_overlay_elements.GetFirstElement();
+    while (state_element)
+    {
+        if (state_element->IsMatch(state, context))
+            PaintSkin(dst_rect, state_element->element_id, state_element->state & state, context);
+        state_element = state_element->GetNext();
+    }
 
-	element->is_painting = false;
+    element->is_painting = false;
 }
 
 void TBSkin::PaintElement(const TBRect &dst_rect, TBSkinElement *element)
 {
-	PaintElementBGColor(dst_rect, element);
-	if (!element->bitmap)
-		return;
-	if (element->type == SKIN_ELEMENT_TYPE_IMAGE)
-		PaintElementImage(dst_rect, element);
-	else if (element->type == SKIN_ELEMENT_TYPE_TILE)
-		PaintElementTile(dst_rect, element);
-	else if (element->type == SKIN_ELEMENT_TYPE_STRETCH_IMAGE || element->cut == 0)
-		PaintElementStretchImage(dst_rect, element);
-	else if (element->type == SKIN_ELEMENT_TYPE_STRETCH_BORDER)
-		PaintElementStretchBox(dst_rect, element, false);
-	else
-		PaintElementStretchBox(dst_rect, element, true);
+    PaintElementBGColor(dst_rect, element);
+    if (!element->bitmap)
+        return;
+    if (element->type == SKIN_ELEMENT_TYPE_IMAGE)
+        PaintElementImage(dst_rect, element);
+    else if (element->type == SKIN_ELEMENT_TYPE_TILE)
+        PaintElementTile(dst_rect, element);
+    else if (element->type == SKIN_ELEMENT_TYPE_STRETCH_IMAGE || element->cut == 0)
+        PaintElementStretchImage(dst_rect, element);
+    else if (element->type == SKIN_ELEMENT_TYPE_STRETCH_BORDER)
+        PaintElementStretchBox(dst_rect, element, false);
+    else
+        PaintElementStretchBox(dst_rect, element, true);
 }
 
 TBRect TBSkin::GetFlippedRect(const TBRect &src_rect, TBSkinElement *element) const
 {
-	// Turning the source rect "inside out" will flip the result when rendered.
-	TBRect tmp_rect = src_rect;
-	if (element->flip_x)
-	{
-		tmp_rect.x += tmp_rect.w;
-		tmp_rect.w = -tmp_rect.w;
-	}
-	if (element->flip_y)
-	{
-		tmp_rect.y += tmp_rect.h;
-		tmp_rect.h = -tmp_rect.h;
-	}
-	return tmp_rect;
+    // Turning the source rect "inside out" will flip the result when rendered.
+    TBRect tmp_rect = src_rect;
+    if (element->flip_x)
+    {
+        tmp_rect.x += tmp_rect.w;
+        tmp_rect.w = -tmp_rect.w;
+    }
+    if (element->flip_y)
+    {
+        tmp_rect.y += tmp_rect.h;
+        tmp_rect.h = -tmp_rect.h;
+    }
+    return tmp_rect;
 }
 
 void TBSkin::PaintElementBGColor(const TBRect &dst_rect, TBSkinElement *element)
 {
-	if (element->bg_color == 0)
-		return;
-	g_renderer->DrawRectFill(dst_rect, element->bg_color);
+    if (element->bg_color == 0)
+        return;
+    g_renderer->DrawRectFill(dst_rect, element->bg_color);
 }
 
 void TBSkin::PaintElementImage(const TBRect &dst_rect, TBSkinElement *element)
 {
-	TBRect src_rect(0, 0, element->bitmap->Width(), element->bitmap->Height());
-	TBRect rect = dst_rect.Expand(element->expand, element->expand);
-	rect.Set(rect.x + element->img_ofs_x + (rect.w - src_rect.w) * element->img_position_x / 100,
-			rect.y + element->img_ofs_y + (rect.h - src_rect.h) * element->img_position_y / 100,
-			src_rect.w, src_rect.h);
-	g_renderer->DrawBitmap(rect, GetFlippedRect(src_rect, element), element->bitmap);
+    TBRect src_rect(0, 0, element->bitmap->Width(), element->bitmap->Height());
+    TBRect rect = dst_rect.Expand(element->expand, element->expand);
+    rect.Set(rect.x + element->img_ofs_x + (rect.w - src_rect.w) * element->img_position_x / 100,
+             rect.y + element->img_ofs_y + (rect.h - src_rect.h) * element->img_position_y / 100,
+             src_rect.w, src_rect.h);
+    g_renderer->DrawBitmap(rect, GetFlippedRect(src_rect, element), element->bitmap);
 }
 
 void TBSkin::PaintElementTile(const TBRect &dst_rect, TBSkinElement *element)
 {
-	TBRect rect = dst_rect.Expand(element->expand, element->expand);
-	g_renderer->DrawBitmapTile(rect, element->bitmap->GetBitmap());
+    TBRect rect = dst_rect.Expand(element->expand, element->expand);
+    g_renderer->DrawBitmapTile(rect, element->bitmap->GetBitmap());
 }
 
 void TBSkin::PaintElementStretchImage(const TBRect &dst_rect, TBSkinElement *element)
 {
-	if (dst_rect.IsEmpty())
-		return;
-	TBRect rect = dst_rect.Expand(element->expand, element->expand);
-	TBRect src_rect = GetFlippedRect(TBRect(0, 0, element->bitmap->Width(), element->bitmap->Height()), element);
-	g_renderer->DrawBitmap(rect, src_rect, element->bitmap);
+    if (dst_rect.IsEmpty())
+        return;
+    TBRect rect = dst_rect.Expand(element->expand, element->expand);
+    TBRect src_rect = GetFlippedRect(TBRect(0, 0, element->bitmap->Width(), element->bitmap->Height()), element);
+    g_renderer->DrawBitmap(rect, src_rect, element->bitmap);
 }
 
 void TBSkin::PaintElementStretchBox(const TBRect &dst_rect, TBSkinElement *element, bool fill_center)
 {
-	if (dst_rect.IsEmpty())
-		return;
-
-	TBRect rect = dst_rect.Expand(element->expand, element->expand);
-
-	// Stretch the dst_cut (if rect is smaller than the skin size)
-	// FIX: the expand should also be stretched!
-	int cut = element->cut;
-	int dst_cut_w = MIN(cut, rect.w / 2);
-	int dst_cut_h = MIN(cut, rect.h / 2);
-	int bw = element->bitmap->Width();
-	int bh = element->bitmap->Height();
-
-	bool has_left_right_edges = rect.h > dst_cut_h * 2;
-	bool has_top_bottom_edges = rect.w > dst_cut_w * 2;
-
-	rect = GetFlippedRect(rect, element);
-	if (element->flip_x)
-		dst_cut_w = -dst_cut_w;
-	if (element->flip_y)
-		dst_cut_h = -dst_cut_h;
-
-	// Corners
-	g_renderer->DrawBitmap(TBRect(rect.x, rect.y, dst_cut_w, dst_cut_h), TBRect(0, 0, cut, cut), element->bitmap);
-	g_renderer->DrawBitmap(TBRect(rect.x + rect.w - dst_cut_w, rect.y, dst_cut_w, dst_cut_h), TBRect(bw - cut, 0, cut, cut), element->bitmap);
-	g_renderer->DrawBitmap(TBRect(rect.x, rect.y + rect.h - dst_cut_h, dst_cut_w, dst_cut_h), TBRect(0, bh - cut, cut, cut), element->bitmap);
-	g_renderer->DrawBitmap(TBRect(rect.x + rect.w - dst_cut_w, rect.y + rect.h - dst_cut_h, dst_cut_w, dst_cut_h), TBRect(bw - cut, bh - cut, cut, cut), element->bitmap);
-
-	// Left & right edge
-	if (has_left_right_edges)
-	{
-		g_renderer->DrawBitmap(TBRect(rect.x, rect.y + dst_cut_h, dst_cut_w, rect.h - dst_cut_h * 2), TBRect(0, cut, cut, bh - cut * 2), element->bitmap);
-		g_renderer->DrawBitmap(TBRect(rect.x + rect.w - dst_cut_w, rect.y + dst_cut_h, dst_cut_w, rect.h - dst_cut_h * 2), TBRect(bw - cut, cut, cut, bh - cut * 2), element->bitmap);
-	}
-
-	// Top & bottom edge
-	if (has_top_bottom_edges)
-	{
-		g_renderer->DrawBitmap(TBRect(rect.x + dst_cut_w, rect.y, rect.w - dst_cut_w * 2, dst_cut_h), TBRect(cut, 0, bw - cut * 2, cut), element->bitmap);
-		g_renderer->DrawBitmap(TBRect(rect.x + dst_cut_w, rect.y + rect.h - dst_cut_h, rect.w - dst_cut_w * 2, dst_cut_h), TBRect(cut, bh - cut, bw - cut * 2, cut), element->bitmap);
-	}
-
-	// Center
-	if (fill_center && has_top_bottom_edges && has_left_right_edges)
-		g_renderer->DrawBitmap(TBRect(rect.x + dst_cut_w, rect.y + dst_cut_h, rect.w - dst_cut_w * 2, rect.h - dst_cut_h * 2), TBRect(cut, cut, bw - cut * 2, bh - cut * 2), element->bitmap);
+    if (dst_rect.IsEmpty())
+        return;
+
+    TBRect rect = dst_rect.Expand(element->expand, element->expand);
+
+    // Stretch the dst_cut (if rect is smaller than the skin size)
+    // FIX: the expand should also be stretched!
+    int cut = element->cut;
+    int dst_cut_w = MIN(cut, rect.w / 2);
+    int dst_cut_h = MIN(cut, rect.h / 2);
+    int bw = element->bitmap->Width();
+    int bh = element->bitmap->Height();
+
+    bool has_left_right_edges = rect.h > dst_cut_h * 2;
+    bool has_top_bottom_edges = rect.w > dst_cut_w * 2;
+
+    rect = GetFlippedRect(rect, element);
+    if (element->flip_x)
+        dst_cut_w = -dst_cut_w;
+    if (element->flip_y)
+        dst_cut_h = -dst_cut_h;
+
+    // Corners
+    g_renderer->DrawBitmap(TBRect(rect.x, rect.y, dst_cut_w, dst_cut_h), TBRect(0, 0, cut, cut), element->bitmap);
+    g_renderer->DrawBitmap(TBRect(rect.x + rect.w - dst_cut_w, rect.y, dst_cut_w, dst_cut_h), TBRect(bw - cut, 0, cut, cut), element->bitmap);
+    g_renderer->DrawBitmap(TBRect(rect.x, rect.y + rect.h - dst_cut_h, dst_cut_w, dst_cut_h), TBRect(0, bh - cut, cut, cut), element->bitmap);
+    g_renderer->DrawBitmap(TBRect(rect.x + rect.w - dst_cut_w, rect.y + rect.h - dst_cut_h, dst_cut_w, dst_cut_h), TBRect(bw - cut, bh - cut, cut, cut), element->bitmap);
+
+    // Left & right edge
+    if (has_left_right_edges)
+    {
+        g_renderer->DrawBitmap(TBRect(rect.x, rect.y + dst_cut_h, dst_cut_w, rect.h - dst_cut_h * 2), TBRect(0, cut, cut, bh - cut * 2), element->bitmap);
+        g_renderer->DrawBitmap(TBRect(rect.x + rect.w - dst_cut_w, rect.y + dst_cut_h, dst_cut_w, rect.h - dst_cut_h * 2), TBRect(bw - cut, cut, cut, bh - cut * 2), element->bitmap);
+    }
+
+    // Top & bottom edge
+    if (has_top_bottom_edges)
+    {
+        g_renderer->DrawBitmap(TBRect(rect.x + dst_cut_w, rect.y, rect.w - dst_cut_w * 2, dst_cut_h), TBRect(cut, 0, bw - cut * 2, cut), element->bitmap);
+        g_renderer->DrawBitmap(TBRect(rect.x + dst_cut_w, rect.y + rect.h - dst_cut_h, rect.w - dst_cut_w * 2, dst_cut_h), TBRect(cut, bh - cut, bw - cut * 2, cut), element->bitmap);
+    }
+
+    // Center
+    if (fill_center && has_top_bottom_edges && has_left_right_edges)
+        g_renderer->DrawBitmap(TBRect(rect.x + dst_cut_w, rect.y + dst_cut_h, rect.w - dst_cut_w * 2, rect.h - dst_cut_h * 2), TBRect(cut, cut, bw - cut * 2, bh - cut * 2), element->bitmap);
 }
 
 #ifdef TB_RUNTIME_DEBUG_INFO
 void TBSkin::Debug()
 {
-	m_frag_manager.Debug();
+    m_frag_manager.Debug();
 }
 #endif // TB_RUNTIME_DEBUG_INFO
 
 void TBSkin::OnContextLost()
 {
-	// We could simply do: m_frag_manager.DeleteBitmaps() and then all bitmaps
-	// would be recreated automatically when needed. But because it's easy,
-	// we unload everything so we save some memory (by not keeping any image
-	// data around).
-	UnloadBitmaps();
+    // We could simply do: m_frag_manager.DeleteBitmaps() and then all bitmaps
+    // would be recreated automatically when needed. But because it's easy,
+    // we unload everything so we save some memory (by not keeping any image
+    // data around).
+    UnloadBitmaps();
 }
 
 void TBSkin::OnContextRestored()
 {
-	// Reload bitmaps (since we unloaded everything in OnContextLost())
-	ReloadBitmaps();
+    // Reload bitmaps (since we unloaded everything in OnContextLost())
+    ReloadBitmaps();
 }
 
 int TBSkin::GetPxFromNode(TBNode *node, int def_value) const
 {
-	return node ? m_dim_conv.GetPxFromValue(&node->GetValue(), def_value) : def_value;
+    return node ? m_dim_conv.GetPxFromValue(&node->GetValue(), def_value) : def_value;
 }
 
 // == TBSkinElement =========================================================
 
 TBSkinElement::TBSkinElement()
-	: bitmap(nullptr), cut(0), expand(0), type(SKIN_ELEMENT_TYPE_STRETCH_BOX)
-	, is_painting(false), is_getting(false)
-	, padding_left(0), padding_top(0), padding_right(0), padding_bottom(0)
-	, width(SKIN_VALUE_NOT_SPECIFIED), height(SKIN_VALUE_NOT_SPECIFIED)
-	, pref_width(SKIN_VALUE_NOT_SPECIFIED), pref_height(SKIN_VALUE_NOT_SPECIFIED)
-	, min_width(SKIN_VALUE_NOT_SPECIFIED), min_height(SKIN_VALUE_NOT_SPECIFIED)
-	, max_width(SKIN_VALUE_NOT_SPECIFIED), max_height(SKIN_VALUE_NOT_SPECIFIED)
-	, spacing(SKIN_VALUE_NOT_SPECIFIED)
-	, content_ofs_x(0), content_ofs_y(0)
-	, img_ofs_x(0), img_ofs_y(0)
-	, img_position_x(50), img_position_y(50)
-	, flip_x(0), flip_y(0), opacity(1.f)
-	, text_color(0, 0, 0, 0)
-	, bg_color(0, 0, 0, 0)
-	, bitmap_dpi(0)
+    : bitmap(nullptr), cut(0), expand(0), type(SKIN_ELEMENT_TYPE_STRETCH_BOX)
+    , is_painting(false), is_getting(false)
+    , padding_left(0), padding_top(0), padding_right(0), padding_bottom(0)
+    , width(SKIN_VALUE_NOT_SPECIFIED), height(SKIN_VALUE_NOT_SPECIFIED)
+    , pref_width(SKIN_VALUE_NOT_SPECIFIED), pref_height(SKIN_VALUE_NOT_SPECIFIED)
+    , min_width(SKIN_VALUE_NOT_SPECIFIED), min_height(SKIN_VALUE_NOT_SPECIFIED)
+    , max_width(SKIN_VALUE_NOT_SPECIFIED), max_height(SKIN_VALUE_NOT_SPECIFIED)
+    , spacing(SKIN_VALUE_NOT_SPECIFIED)
+    , content_ofs_x(0), content_ofs_y(0)
+    , img_ofs_x(0), img_ofs_y(0)
+    , img_position_x(50), img_position_y(50)
+    , flip_x(0), flip_y(0), opacity(1.f)
+    , text_color(0, 0, 0, 0)
+    , bg_color(0, 0, 0, 0)
+    , bitmap_dpi(0)
 {
 }
 
@@ -570,279 +570,279 @@ TBSkinElement::~TBSkinElement()
 
 int TBSkinElement::GetIntrinsicMinWidth() const
 {
-	// Sizes below the skin cut size would start to shrink the skin below pretty,
-	// so assume that's the default minimum size if it's not specified (minus expansion)
-	return cut * 2 - expand * 2;
+    // Sizes below the skin cut size would start to shrink the skin below pretty,
+    // so assume that's the default minimum size if it's not specified (minus expansion)
+    return cut * 2 - expand * 2;
 }
 
 int TBSkinElement::GetIntrinsicMinHeight() const
 {
-	// Sizes below the skin cut size would start to shrink the skin below pretty,
-	// so assume that's the default minimum size if it's not specified (minus expansion)
-	return cut * 2 - expand * 2;
+    // Sizes below the skin cut size would start to shrink the skin below pretty,
+    // so assume that's the default minimum size if it's not specified (minus expansion)
+    return cut * 2 - expand * 2;
 }
 
 int TBSkinElement::GetIntrinsicWidth() const
 {
-	if (width != SKIN_VALUE_NOT_SPECIFIED)
-		return width;
-	if (bitmap)
-		return bitmap->Width() - expand * 2;
-	// FIX: We may want to check child elements etc.
-	return SKIN_VALUE_NOT_SPECIFIED;
+    if (width != SKIN_VALUE_NOT_SPECIFIED)
+        return width;
+    if (bitmap)
+        return bitmap->Width() - expand * 2;
+    // FIX: We may want to check child elements etc.
+    return SKIN_VALUE_NOT_SPECIFIED;
 }
 
 int TBSkinElement::GetIntrinsicHeight() const
 {
-	if (height != SKIN_VALUE_NOT_SPECIFIED)
-		return height;
-	if (bitmap)
-		return bitmap->Height() - expand * 2;
-	// FIX: We may want to check child elements etc.
-	return SKIN_VALUE_NOT_SPECIFIED;
+    if (height != SKIN_VALUE_NOT_SPECIFIED)
+        return height;
+    if (bitmap)
+        return bitmap->Height() - expand * 2;
+    // FIX: We may want to check child elements etc.
+    return SKIN_VALUE_NOT_SPECIFIED;
 }
 
 void TBSkinElement::SetBitmapDPI(const TBDimensionConverter &dim_conv, int bitmap_dpi)
 {
-	if (this->bitmap_dpi)
-	{
-		// We have already applied the modifications so abort. This may
-		// happen when we reload bitmaps without reloading the skin.
-		return;
-	}
-	if (dim_conv.NeedConversion())
-	{
-		if (bitmap_dpi == dim_conv.GetDstDPI())
-		{
-			// The bitmap was loaded in a different DPI than the base DPI so
-			// we must scale the bitmap properties.
-			expand = expand * dim_conv.GetDstDPI() / dim_conv.GetSrcDPI();
-			cut = cut * dim_conv.GetDstDPI() / dim_conv.GetSrcDPI();
-		}
-		else
-		{
-			// The bitmap was loaded in the base DPI and we need to scale it.
-			// Apply the DPI conversion to the skin element scale factor.
-			// FIX: For this to work well, we would need to apply scale to both
-			//      image and all the other types of drawing too.
-			// scale_x = scale_x * dim_conv.GetDstDPI() / dim_conv.GetSrcDPI();
-			// scale_y = scale_y * dim_conv.GetDstDPI() / dim_conv.GetSrcDPI();
-		}
-	}
-	this->bitmap_dpi = bitmap_dpi;
+    if (this->bitmap_dpi)
+    {
+        // We have already applied the modifications so abort. This may
+        // happen when we reload bitmaps without reloading the skin.
+        return;
+    }
+    if (dim_conv.NeedConversion())
+    {
+        if (bitmap_dpi == dim_conv.GetDstDPI())
+        {
+            // The bitmap was loaded in a different DPI than the base DPI so
+            // we must scale the bitmap properties.
+            expand = expand * dim_conv.GetDstDPI() / dim_conv.GetSrcDPI();
+            cut = cut * dim_conv.GetDstDPI() / dim_conv.GetSrcDPI();
+        }
+        else
+        {
+            // The bitmap was loaded in the base DPI and we need to scale it.
+            // Apply the DPI conversion to the skin element scale factor.
+            // FIX: For this to work well, we would need to apply scale to both
+            //      image and all the other types of drawing too.
+            // scale_x = scale_x * dim_conv.GetDstDPI() / dim_conv.GetSrcDPI();
+            // scale_y = scale_y * dim_conv.GetDstDPI() / dim_conv.GetSrcDPI();
+        }
+    }
+    this->bitmap_dpi = bitmap_dpi;
 }
 
 bool TBSkinElement::HasState(SKIN_STATE state, TBSkinConditionContext &context)
 {
-	return	m_override_elements.GetStateElement(state, context, TBSkinElementState::MATCH_RULE_ONLY_SPECIFIC_STATE) ||
-			m_child_elements.GetStateElement(state, context, TBSkinElementState::MATCH_RULE_ONLY_SPECIFIC_STATE) ||
-			m_overlay_elements.GetStateElement(state, context, TBSkinElementState::MATCH_RULE_ONLY_SPECIFIC_STATE);
+    return	m_override_elements.GetStateElement(state, context, TBSkinElementState::MATCH_RULE_ONLY_SPECIFIC_STATE) ||
+            m_child_elements.GetStateElement(state, context, TBSkinElementState::MATCH_RULE_ONLY_SPECIFIC_STATE) ||
+            m_overlay_elements.GetStateElement(state, context, TBSkinElementState::MATCH_RULE_ONLY_SPECIFIC_STATE);
 }
 
 void TBSkinElement::Load(TBNode *n, TBSkin *skin, const char *skin_path)
 {
-	if (const char *bitmap = n->GetValueString("bitmap", nullptr))
-	{
-		bitmap_file.Clear();
-		bitmap_file.Append(skin_path);
-		bitmap_file.Append(bitmap);
-	}
-
-	// Note: Always read cut and expand as pixels. These values might later be
-	//       recalculated depending on the DPI the bitmaps are available in.
-	cut = n->GetValueInt("cut", cut);
-	expand = n->GetValueInt("expand", expand);
-
-	name.Set(n->GetName());
-	id.Set(n->GetName());
-
-	const TBDimensionConverter *dim_conv = skin->GetDimensionConverter();
-
-	if (TBNode *padding_node = n->GetNode("padding"))
-	{
-		TBValue &val = padding_node->GetValue();
-		if (val.GetArrayLength() == 4)
-		{
-			padding_top = dim_conv->GetPxFromValue(val.GetArray()->GetValue(0), 0);
-			padding_right = dim_conv->GetPxFromValue(val.GetArray()->GetValue(1), 0);
-			padding_bottom = dim_conv->GetPxFromValue(val.GetArray()->GetValue(2), 0);
-			padding_left = dim_conv->GetPxFromValue(val.GetArray()->GetValue(3), 0);
-		}
-		else if (val.GetArrayLength() == 2)
-		{
-			padding_top = padding_bottom = dim_conv->GetPxFromValue(val.GetArray()->GetValue(0), 0);
-			padding_left = padding_right = dim_conv->GetPxFromValue(val.GetArray()->GetValue(1), 0);
-		}
-		else
-		{
-			padding_top = padding_right = padding_bottom = padding_left = dim_conv->GetPxFromValue(&val, 0);
-		}
-	}
-	width = skin->GetPxFromNode(n->GetNode("width"), width);
-	height = skin->GetPxFromNode(n->GetNode("height"), height);
-	pref_width = skin->GetPxFromNode(n->GetNode("pref-width"), pref_width);
-	pref_height = skin->GetPxFromNode(n->GetNode("pref-height"), pref_height);
-	min_width = skin->GetPxFromNode(n->GetNode("min-width"), min_width);
-	min_height = skin->GetPxFromNode(n->GetNode("min-height"), min_height);
-	max_width = skin->GetPxFromNode(n->GetNode("max-width"), max_width);
-	max_height = skin->GetPxFromNode(n->GetNode("max-height"), max_height);
-	spacing = skin->GetPxFromNode(n->GetNode("spacing"), spacing);
-	content_ofs_x = skin->GetPxFromNode(n->GetNode("content-ofs-x"), content_ofs_x);
-	content_ofs_y = skin->GetPxFromNode(n->GetNode("content-ofs-y"), content_ofs_y);
-	img_position_x = n->GetValueInt("img-position-x", img_position_x);
-	img_position_y = n->GetValueInt("img-position-y", img_position_y);
-	img_ofs_x = skin->GetPxFromNode(n->GetNode("img-ofs-x"), img_ofs_x);
-	img_ofs_y = skin->GetPxFromNode(n->GetNode("img-ofs-y"), img_ofs_y);
-	flip_x = n->GetValueInt("flip-x", flip_x);
-	flip_y = n->GetValueInt("flip-y", flip_y);
-	opacity = n->GetValueFloat("opacity", opacity);
-
-	if (const char *color = n->GetValueString("text-color", nullptr))
-		text_color.SetFromString(color, strlen(color));
-
-	if (const char *color = n->GetValueString("background-color", nullptr))
-		bg_color.SetFromString(color, strlen(color));
-
-	if (const char *type_str = n->GetValueString("type", nullptr))
-		type = StringToType(type_str);
-
-	// Create all state elements
-	m_override_elements.Load(n->GetNode("overrides"));
-	m_strong_override_elements.Load(n->GetNode("strong-overrides"));
-	m_child_elements.Load(n->GetNode("children"));
-	m_overlay_elements.Load(n->GetNode("overlays"));
+    if (const char *bitmap = n->GetValueString("bitmap", nullptr))
+    {
+        bitmap_file.Clear();
+        bitmap_file.Append(skin_path);
+        bitmap_file.Append(bitmap);
+    }
+
+    // Note: Always read cut and expand as pixels. These values might later be
+    //       recalculated depending on the DPI the bitmaps are available in.
+    cut = n->GetValueInt("cut", cut);
+    expand = n->GetValueInt("expand", expand);
+
+    name.Set(n->GetName());
+    id.Set(n->GetName());
+
+    const TBDimensionConverter *dim_conv = skin->GetDimensionConverter();
+
+    if (TBNode *padding_node = n->GetNode("padding"))
+    {
+        TBValue &val = padding_node->GetValue();
+        if (val.GetArrayLength() == 4)
+        {
+            padding_top = dim_conv->GetPxFromValue(val.GetArray()->GetValue(0), 0);
+            padding_right = dim_conv->GetPxFromValue(val.GetArray()->GetValue(1), 0);
+            padding_bottom = dim_conv->GetPxFromValue(val.GetArray()->GetValue(2), 0);
+            padding_left = dim_conv->GetPxFromValue(val.GetArray()->GetValue(3), 0);
+        }
+        else if (val.GetArrayLength() == 2)
+        {
+            padding_top = padding_bottom = dim_conv->GetPxFromValue(val.GetArray()->GetValue(0), 0);
+            padding_left = padding_right = dim_conv->GetPxFromValue(val.GetArray()->GetValue(1), 0);
+        }
+        else
+        {
+            padding_top = padding_right = padding_bottom = padding_left = dim_conv->GetPxFromValue(&val, 0);
+        }
+    }
+    width = skin->GetPxFromNode(n->GetNode("width"), width);
+    height = skin->GetPxFromNode(n->GetNode("height"), height);
+    pref_width = skin->GetPxFromNode(n->GetNode("pref-width"), pref_width);
+    pref_height = skin->GetPxFromNode(n->GetNode("pref-height"), pref_height);
+    min_width = skin->GetPxFromNode(n->GetNode("min-width"), min_width);
+    min_height = skin->GetPxFromNode(n->GetNode("min-height"), min_height);
+    max_width = skin->GetPxFromNode(n->GetNode("max-width"), max_width);
+    max_height = skin->GetPxFromNode(n->GetNode("max-height"), max_height);
+    spacing = skin->GetPxFromNode(n->GetNode("spacing"), spacing);
+    content_ofs_x = skin->GetPxFromNode(n->GetNode("content-ofs-x"), content_ofs_x);
+    content_ofs_y = skin->GetPxFromNode(n->GetNode("content-ofs-y"), content_ofs_y);
+    img_position_x = n->GetValueInt("img-position-x", img_position_x);
+    img_position_y = n->GetValueInt("img-position-y", img_position_y);
+    img_ofs_x = skin->GetPxFromNode(n->GetNode("img-ofs-x"), img_ofs_x);
+    img_ofs_y = skin->GetPxFromNode(n->GetNode("img-ofs-y"), img_ofs_y);
+    flip_x = n->GetValueInt("flip-x", flip_x);
+    flip_y = n->GetValueInt("flip-y", flip_y);
+    opacity = n->GetValueFloat("opacity", opacity);
+
+    if (const char *color = n->GetValueString("text-color", nullptr))
+        text_color.SetFromString(color, strlen(color));
+
+    if (const char *color = n->GetValueString("background-color", nullptr))
+        bg_color.SetFromString(color, strlen(color));
+
+    if (const char *type_str = n->GetValueString("type", nullptr))
+        type = StringToType(type_str);
+
+    // Create all state elements
+    m_override_elements.Load(n->GetNode("overrides"));
+    m_strong_override_elements.Load(n->GetNode("strong-overrides"));
+    m_child_elements.Load(n->GetNode("children"));
+    m_overlay_elements.Load(n->GetNode("overlays"));
 }
 
 // == TBSkinElementState ====================================================
 
 bool TBSkinElementState::IsMatch(SKIN_STATE state, TBSkinConditionContext &context, MATCH_RULE rule) const
 {
-	if (rule == MATCH_RULE_ONLY_SPECIFIC_STATE && this->state == SKIN_STATE_ALL)
-		return false;
-	if ((state & this->state) || this->state == SKIN_STATE_ALL)
-	{
-		for (TBSkinCondition *condition = conditions.GetFirst(); condition; condition = condition->GetNext())
-			if (!condition->GetCondition(context))
-				return false;
-		return true;
-	}
-	return false;
+    if (rule == MATCH_RULE_ONLY_SPECIFIC_STATE && this->state == SKIN_STATE_ALL)
+        return false;
+    if ((state & this->state) || this->state == SKIN_STATE_ALL)
+    {
+        for (TBSkinCondition *condition = conditions.GetFirst(); condition; condition = condition->GetNext())
+            if (!condition->GetCondition(context))
+                return false;
+        return true;
+    }
+    return false;
 }
 
 bool TBSkinElementState::IsExactMatch(SKIN_STATE state, TBSkinConditionContext &context, MATCH_RULE rule) const
 {
-	if (rule == MATCH_RULE_ONLY_SPECIFIC_STATE && this->state == SKIN_STATE_ALL)
-		return false;
-	if (state == this->state || this->state == SKIN_STATE_ALL)
-	{
-		for (TBSkinCondition *condition = conditions.GetFirst(); condition; condition = condition->GetNext())
-			if (!condition->GetCondition(context))
-				return false;
-		return true;
-	}
-	return false;
+    if (rule == MATCH_RULE_ONLY_SPECIFIC_STATE && this->state == SKIN_STATE_ALL)
+        return false;
+    if (state == this->state || this->state == SKIN_STATE_ALL)
+    {
+        for (TBSkinCondition *condition = conditions.GetFirst(); condition; condition = condition->GetNext())
+            if (!condition->GetCondition(context))
+                return false;
+        return true;
+    }
+    return false;
 }
 
 // == TBSkinElementStateList ==================================================
 
 TBSkinElementStateList::~TBSkinElementStateList()
 {
-	while (TBSkinElementState *state = m_state_elements.GetFirst())
-	{
-		m_state_elements.Remove(state);
-		delete state;
-	}
+    while (TBSkinElementState *state = m_state_elements.GetFirst())
+    {
+        m_state_elements.Remove(state);
+        delete state;
+    }
 }
 
 TBSkinElementState *TBSkinElementStateList::GetStateElement(SKIN_STATE state, TBSkinConditionContext &context, TBSkinElementState::MATCH_RULE rule) const
 {
-	// First try to get a state element with a exact match to the current state
-	if (TBSkinElementState *element_state = GetStateElementExactMatch(state, context, rule))
-		return element_state;
-	// No exact state match. Get a state with a partly match if there is one.
-	TBSkinElementState *state_element = m_state_elements.GetFirst();
-	while (state_element)
-	{
-		if (state_element->IsMatch(state, context, rule))
-			return state_element;
-		state_element = state_element->GetNext();
-	}
-	return nullptr;
+    // First try to get a state element with a exact match to the current state
+    if (TBSkinElementState *element_state = GetStateElementExactMatch(state, context, rule))
+        return element_state;
+    // No exact state match. Get a state with a partly match if there is one.
+    TBSkinElementState *state_element = m_state_elements.GetFirst();
+    while (state_element)
+    {
+        if (state_element->IsMatch(state, context, rule))
+            return state_element;
+        state_element = state_element->GetNext();
+    }
+    return nullptr;
 }
 
 TBSkinElementState *TBSkinElementStateList::GetStateElementExactMatch(SKIN_STATE state, TBSkinConditionContext &context, TBSkinElementState::MATCH_RULE rule) const
 {
-	TBSkinElementState *state_element = m_state_elements.GetFirst();
-	while (state_element)
-	{
-		if (state_element->IsExactMatch(state, context, rule))
-			return state_element;
-		state_element = state_element->GetNext();
-	}
-	return nullptr;
+    TBSkinElementState *state_element = m_state_elements.GetFirst();
+    while (state_element)
+    {
+        if (state_element->IsExactMatch(state, context, rule))
+            return state_element;
+        state_element = state_element->GetNext();
+    }
+    return nullptr;
 }
 
 void TBSkinElementStateList::Load(TBNode *n)
 {
-	if (!n)
-		return;
-
-	// For each node, create a new state element.
-	TBNode *element_node = n->GetFirstChild();
-	while (element_node)
-	{
-		TBSkinElementState *state = new TBSkinElementState;
-		if (!state)
-			return;
-
-		// By default, a state element applies to all combinations of states
-		state->state = SKIN_STATE_ALL;
-		state->element_id.Set(element_node->GetValue().GetString());
-
-		// Loop through all nodes, read state and create all found conditions.
-		for (TBNode *condition_node = element_node->GetFirstChild(); condition_node; condition_node = condition_node->GetNext())
-		{
-			if (strcmp(condition_node->GetName(), "state") == 0)
-				state->state = StringToState(condition_node->GetValue().GetString());
-			else if (strcmp(condition_node->GetName(), "condition") == 0)
-			{
-				TBSkinCondition::TARGET target = StringToTarget(condition_node->GetValueString("target", ""));
-
-				const char *prop_str = condition_node->GetValueString("property", "");
-				TBSkinCondition::PROPERTY prop = StringToProperty(prop_str);
-				TBID custom_prop;
-				if (prop == TBSkinCondition::PROPERTY_CUSTOM)
-					custom_prop.Set(prop_str);
-
-				TBID value;
-				if (TBNode *value_n = condition_node->GetNode("value"))
-				{
-					// Set the it to number or string. If it's a state, we must first convert the
-					// state string to the SKIN_STATE state combo.
-					if (prop == TBSkinCondition::PROPERTY_STATE)
-						value.Set(StringToState(value_n->GetValue().GetString()));
-					else if (value_n->GetValue().IsString())
-						value.Set(value_n->GetValue().GetString());
-					else
-						value.Set(value_n->GetValue().GetInt());
-				}
-
-				TBSkinCondition::TEST test = TBSkinCondition::TEST_EQUAL;
-				if (const char *test_str = condition_node->GetValueString("test", nullptr))
-				{
-					if (strcmp(test_str, "!=") == 0)
-						test = TBSkinCondition::TEST_NOT_EQUAL;
-				}
-
-				if (TBSkinCondition *condition = new TBSkinCondition(target, prop, custom_prop, value, test))
-					state->conditions.AddLast(condition);
-			}
-		}
-
-		// State is reado to add
-		m_state_elements.AddLast(state);
-		element_node = element_node->GetNext();
-	}
+    if (!n)
+        return;
+
+    // For each node, create a new state element.
+    TBNode *element_node = n->GetFirstChild();
+    while (element_node)
+    {
+        TBSkinElementState *state = new TBSkinElementState;
+        if (!state)
+            return;
+
+        // By default, a state element applies to all combinations of states
+        state->state = SKIN_STATE_ALL;
+        state->element_id.Set(element_node->GetValue().GetString());
+
+        // Loop through all nodes, read state and create all found conditions.
+        for (TBNode *condition_node = element_node->GetFirstChild(); condition_node; condition_node = condition_node->GetNext())
+        {
+            if (strcmp(condition_node->GetName(), "state") == 0)
+                state->state = StringToState(condition_node->GetValue().GetString());
+            else if (strcmp(condition_node->GetName(), "condition") == 0)
+            {
+                TBSkinCondition::TARGET target = StringToTarget(condition_node->GetValueString("target", ""));
+
+                const char *prop_str = condition_node->GetValueString("property", "");
+                TBSkinCondition::PROPERTY prop = StringToProperty(prop_str);
+                TBID custom_prop;
+                if (prop == TBSkinCondition::PROPERTY_CUSTOM)
+                    custom_prop.Set(prop_str);
+
+                TBID value;
+                if (TBNode *value_n = condition_node->GetNode("value"))
+                {
+                    // Set the it to number or string. If it's a state, we must first convert the
+                    // state string to the SKIN_STATE state combo.
+                    if (prop == TBSkinCondition::PROPERTY_STATE)
+                        value.Set(StringToState(value_n->GetValue().GetString()));
+                    else if (value_n->GetValue().IsString())
+                        value.Set(value_n->GetValue().GetString());
+                    else
+                        value.Set(value_n->GetValue().GetInt());
+                }
+
+                TBSkinCondition::TEST test = TBSkinCondition::TEST_EQUAL;
+                if (const char *test_str = condition_node->GetValueString("test", nullptr))
+                {
+                    if (strcmp(test_str, "!=") == 0)
+                        test = TBSkinCondition::TEST_NOT_EQUAL;
+                }
+
+                if (TBSkinCondition *condition = new TBSkinCondition(target, prop, custom_prop, value, test))
+                    state->conditions.AddLast(condition);
+            }
+        }
+
+        // State is reado to add
+        m_state_elements.AddLast(state);
+        element_node = element_node->GetNext();
+    }
 }
 
 }; // namespace tb

+ 289 - 289
Source/ThirdParty/TurboBadger/tb_skin.h

@@ -23,120 +23,120 @@ class TBSkinConditionContext;
 #define SKIN_VALUE_NOT_SPECIFIED TB_INVALID_DIMENSION
 
 /** Skin state types (may be combined).
-	NOTE: This should exactly match WIDGET_STATE in tb_widgets.h! */
+    NOTE: This should exactly match WIDGET_STATE in tb_widgets.h! */
 enum SKIN_STATE {
-	SKIN_STATE_NONE			= 0,
-	SKIN_STATE_DISABLED		= 1,
-	SKIN_STATE_FOCUSED		= 2,
-	SKIN_STATE_PRESSED		= 4,
-	SKIN_STATE_SELECTED		= 8,
-	SKIN_STATE_HOVERED		= 16,
-
-	SKIN_STATE_ALL			=	SKIN_STATE_DISABLED |
-								SKIN_STATE_FOCUSED |
-								SKIN_STATE_PRESSED |
-								SKIN_STATE_SELECTED |
-								SKIN_STATE_HOVERED
+    SKIN_STATE_NONE			= 0,
+    SKIN_STATE_DISABLED		= 1,
+    SKIN_STATE_FOCUSED		= 2,
+    SKIN_STATE_PRESSED		= 4,
+    SKIN_STATE_SELECTED		= 8,
+    SKIN_STATE_HOVERED		= 16,
+
+    SKIN_STATE_ALL			=	SKIN_STATE_DISABLED |
+    SKIN_STATE_FOCUSED |
+    SKIN_STATE_PRESSED |
+    SKIN_STATE_SELECTED |
+    SKIN_STATE_HOVERED
 };
 MAKE_ENUM_FLAG_COMBO(SKIN_STATE);
 
 /** Type of painting that should be done for a TBSkinElement. */
 enum SKIN_ELEMENT_TYPE {
-	SKIN_ELEMENT_TYPE_STRETCH_BOX,
-	SKIN_ELEMENT_TYPE_STRETCH_BORDER,
-	SKIN_ELEMENT_TYPE_STRETCH_IMAGE,
-	SKIN_ELEMENT_TYPE_TILE,
-	SKIN_ELEMENT_TYPE_IMAGE
+    SKIN_ELEMENT_TYPE_STRETCH_BOX,
+    SKIN_ELEMENT_TYPE_STRETCH_BORDER,
+    SKIN_ELEMENT_TYPE_STRETCH_IMAGE,
+    SKIN_ELEMENT_TYPE_TILE,
+    SKIN_ELEMENT_TYPE_IMAGE
 };
 
 /** TBSkinCondition checks if a condition is true for a given TBSkinConditionContext.
-	This is used to apply different state elements depending on what is currently
-	painting the skin. */
+    This is used to apply different state elements depending on what is currently
+    painting the skin. */
 
 class TBSkinCondition : public TBLinkOf<TBSkinCondition>
 {
 public:
-	/** Defines which target(s) relative to the context that should be tested for the condition. */
-	enum TARGET {
-		TARGET_THIS,			///< The object painting the skin.
-		TARGET_PARENT,			///< The parent of the object painting the skin.
-		TARGET_ANCESTORS,		///< All ancestors of the object painting the skin.
-		TARGET_PREV_SIBLING,	///< The previous sibling of the object painting the skin.
-		TARGET_NEXT_SIBLING		///< The next sibling of the object painting the skin.
-	};
-	/** Defines which property in the context that should be checked. */
-	enum PROPERTY {
-		PROPERTY_SKIN,				///< The background skin id.
-		PROPERTY_WINDOW_ACTIVE,		///< The window is active (no value required).
-		PROPERTY_AXIS,				///< The axis of the content (x or y)
-		PROPERTY_ALIGN,				///< The alignment.
-		PROPERTY_ID,				///< The id.
-		PROPERTY_STATE,				///< The state is set.
-		PROPERTY_VALUE,				///< The current value (integer).
-		PROPERTY_HOVER,				///< Focus is on the target or any child (no value required).
-		PROPERTY_CAPTURE,			///< Capture is on the target or any child (no value required).
-		PROPERTY_FOCUS,				///< Focus is on the target or any child (no value required).
-		PROPERTY_CUSTOM				///< It's a property unknown to skin, that the TBSkinConditionContext might know about.
-	};
-
-	/** Defines if the condition tested should be equal or not for the condition to be true. */
-	enum TEST {
-		TEST_EQUAL,		///< Value should be equal for condition to be true.
-		TEST_NOT_EQUAL	///< Value should not be equal for condition to be true.
-	};
-
-	/** Stores the information needed for checking a condition. */
-	struct CONDITION_INFO {
-		PROPERTY prop;			///< Which property.
-		TBID custom_prop;		///< Which property (only if prop is PROPERTY_CUSTOM).
-		TBID value;				///< The value to compare.
-	};
-
-	TBSkinCondition(TARGET target, PROPERTY prop, const TBID &custom_prop, const TBID &value, TEST test);
-
-	/** Return true if the condition is true for the given context. */
-	bool GetCondition(TBSkinConditionContext &context) const;
+    /** Defines which target(s) relative to the context that should be tested for the condition. */
+    enum TARGET {
+        TARGET_THIS,			///< The object painting the skin.
+        TARGET_PARENT,			///< The parent of the object painting the skin.
+        TARGET_ANCESTORS,		///< All ancestors of the object painting the skin.
+        TARGET_PREV_SIBLING,	///< The previous sibling of the object painting the skin.
+        TARGET_NEXT_SIBLING		///< The next sibling of the object painting the skin.
+    };
+    /** Defines which property in the context that should be checked. */
+    enum PROPERTY {
+        PROPERTY_SKIN,				///< The background skin id.
+        PROPERTY_WINDOW_ACTIVE,		///< The window is active (no value required).
+        PROPERTY_AXIS,				///< The axis of the content (x or y)
+        PROPERTY_ALIGN,				///< The alignment.
+        PROPERTY_ID,				///< The id.
+        PROPERTY_STATE,				///< The state is set.
+        PROPERTY_VALUE,				///< The current value (integer).
+        PROPERTY_HOVER,				///< Focus is on the target or any child (no value required).
+        PROPERTY_CAPTURE,			///< Capture is on the target or any child (no value required).
+        PROPERTY_FOCUS,				///< Focus is on the target or any child (no value required).
+        PROPERTY_CUSTOM				///< It's a property unknown to skin, that the TBSkinConditionContext might know about.
+    };
+
+    /** Defines if the condition tested should be equal or not for the condition to be true. */
+    enum TEST {
+        TEST_EQUAL,		///< Value should be equal for condition to be true.
+        TEST_NOT_EQUAL	///< Value should not be equal for condition to be true.
+    };
+
+    /** Stores the information needed for checking a condition. */
+    struct CONDITION_INFO {
+        PROPERTY prop;			///< Which property.
+        TBID custom_prop;		///< Which property (only if prop is PROPERTY_CUSTOM).
+        TBID value;				///< The value to compare.
+    };
+
+    TBSkinCondition(TARGET target, PROPERTY prop, const TBID &custom_prop, const TBID &value, TEST test);
+
+    /** Return true if the condition is true for the given context. */
+    bool GetCondition(TBSkinConditionContext &context) const;
 private:
-	TARGET m_target;
-	CONDITION_INFO m_info;
-	TEST m_test;
+    TARGET m_target;
+    CONDITION_INFO m_info;
+    TEST m_test;
 };
 
 /** TBSkinConditionContext checks if a condition is true. It is passed to skin painting functions
-	so different state elements can be applied depending on the current situation of the context.
-	F.ex a widget may change appearance if it's under a parent with a certain skin. */
+    so different state elements can be applied depending on the current situation of the context.
+    F.ex a widget may change appearance if it's under a parent with a certain skin. */
 
 class TBSkinConditionContext
 {
 public:
-	/** Return true if the given target and property equals the given value. */
-	virtual bool GetCondition(TBSkinCondition::TARGET target, const TBSkinCondition::CONDITION_INFO &info) = 0;
+    /** Return true if the given target and property equals the given value. */
+    virtual bool GetCondition(TBSkinCondition::TARGET target, const TBSkinCondition::CONDITION_INFO &info) = 0;
 };
 
 /** TBSkinElementState has a skin element id that should be used if its state and condition
-	matches that which is being painted.
+    matches that which is being painted.
 */
 
 class TBSkinElementState : public TBLinkOf<TBSkinElementState>
 {
 public:
-	/** Defines how to match states. */
-	enum MATCH_RULE {
-		/** States with "all" (SKIN_STATE_ALL) will also be considered a match. */
-		MATCH_RULE_DEFAULT,
-		/** States with "all" will not be considered a match. */
-		MATCH_RULE_ONLY_SPECIFIC_STATE
-	};
-
-	bool IsMatch(SKIN_STATE state, TBSkinConditionContext &context,
-				MATCH_RULE rule = MATCH_RULE_DEFAULT) const;
-
-	bool IsExactMatch(SKIN_STATE state, TBSkinConditionContext &context,
-				MATCH_RULE rule = MATCH_RULE_DEFAULT) const;
-
-	TBID element_id;
-	SKIN_STATE state;
-	TBLinkListAutoDeleteOf<TBSkinCondition> conditions;
+    /** Defines how to match states. */
+    enum MATCH_RULE {
+        /** States with "all" (SKIN_STATE_ALL) will also be considered a match. */
+        MATCH_RULE_DEFAULT,
+        /** States with "all" will not be considered a match. */
+        MATCH_RULE_ONLY_SPECIFIC_STATE
+    };
+
+    bool IsMatch(SKIN_STATE state, TBSkinConditionContext &context,
+                 MATCH_RULE rule = MATCH_RULE_DEFAULT) const;
+
+    bool IsExactMatch(SKIN_STATE state, TBSkinConditionContext &context,
+                      MATCH_RULE rule = MATCH_RULE_DEFAULT) const;
+
+    TBID element_id;
+    SKIN_STATE state;
+    TBLinkListAutoDeleteOf<TBSkinCondition> conditions;
 };
 
 /** List of state elements in a TBSkinElement. */
@@ -144,259 +144,259 @@ public:
 class TBSkinElementStateList
 {
 public:
-	~TBSkinElementStateList();
+    ~TBSkinElementStateList();
 
-	TBSkinElementState *GetStateElement(SKIN_STATE state, TBSkinConditionContext &context,
-						TBSkinElementState::MATCH_RULE rule = TBSkinElementState::MATCH_RULE_DEFAULT) const;
+    TBSkinElementState *GetStateElement(SKIN_STATE state, TBSkinConditionContext &context,
+                                        TBSkinElementState::MATCH_RULE rule = TBSkinElementState::MATCH_RULE_DEFAULT) const;
 
-	TBSkinElementState *GetStateElementExactMatch(SKIN_STATE state, TBSkinConditionContext &context,
-						TBSkinElementState::MATCH_RULE rule = TBSkinElementState::MATCH_RULE_DEFAULT) const;
+    TBSkinElementState *GetStateElementExactMatch(SKIN_STATE state, TBSkinConditionContext &context,
+                                                  TBSkinElementState::MATCH_RULE rule = TBSkinElementState::MATCH_RULE_DEFAULT) const;
 
-	bool HasStateElements() const { return m_state_elements.HasLinks(); }
-	const TBSkinElementState *GetFirstElement() const { return m_state_elements.GetFirst(); }
+    bool HasStateElements() const { return m_state_elements.HasLinks(); }
+    const TBSkinElementState *GetFirstElement() const { return m_state_elements.GetFirst(); }
 
-	void Load(TBNode *n);
+    void Load(TBNode *n);
 private:
-	TBLinkListOf<TBSkinElementState> m_state_elements;
+    TBLinkListOf<TBSkinElementState> m_state_elements;
 };
 
 /** Skin element.
-	Contains a bitmap fragment (or nullptr) and info specifying how it should be painted.
-	Also contains padding and other look-specific widget properties. */
+    Contains a bitmap fragment (or nullptr) and info specifying how it should be painted.
+    Also contains padding and other look-specific widget properties. */
 class TBSkinElement
 {
 public:
-	TBSkinElement();
-	~TBSkinElement();
-
-	// Skin properties
-	TBID id;			///< ID of the skin element
-	TBStr name;			///< Name of the skin element, f.ex "TBSelectDropdown.arrow"
-	TBStr bitmap_file;	///< File name of the bitmap (might be empty)
-	TBBitmapFragment *bitmap;///< Bitmap fragment containing the graphics, or nullptr.
-	uint8 cut;			///< How the bitmap should be sliced using StretchBox.
-	int16 expand;		///< How much the skin should expand outside the widgets rect.
-	SKIN_ELEMENT_TYPE type;///< Skin element type
-	bool is_painting;	///< If the skin is being painted (avoiding eternal recursing)
-	bool is_getting;	///< If the skin is being got (avoiding eternal recursion)
-	int16 padding_left;		///< Left padding for any content in the element
-	int16 padding_top;		///< Top padding for any content in the element
-	int16 padding_right;	///< Right padding for any content in the element
-	int16 padding_bottom;	///< Bottom padding for any content in the element
-	int16 width;			///< Intrinsic width or SKIN_VALUE_NOT_SPECIFIED
-	int16 height;			///< Intrinsic height or SKIN_VALUE_NOT_SPECIFIED
-	int16 pref_width;		///< Preferred width or SKIN_VALUE_NOT_SPECIFIED
-	int16 pref_height;		///< Preferred height or SKIN_VALUE_NOT_SPECIFIED
-	int16 min_width;		///< Minimum width or SKIN_VALUE_NOT_SPECIFIED
-	int16 min_height;		///< Minimum height or SKIN_VALUE_NOT_SPECIFIED
-	int16 max_width;		///< Maximum width or SKIN_VALUE_NOT_SPECIFIED
-	int16 max_height;		///< Maximum height or SKIN_VALUE_NOT_SPECIFIED
-	int16 spacing;			///< Spacing used on layout or SKIN_VALUE_NOT_SPECIFIED.
-	int16 content_ofs_x;	///< X offset of the content in the widget.
-	int16 content_ofs_y;	///< Y offset of the content in the widget.
-	int16 img_ofs_x;		///< X offset for type image. Relative to image position (img_position_x).
-	int16 img_ofs_y;		///< Y offset for type image. Relative to image position (img_position_y).
-	int8 img_position_x;	///< Horizontal position for type image. 0-100 (left to
-							///< right in available space). Default 50.
-	int8 img_position_y;	///< Vertical position for type image. 0-100 (top to bottom
-							///< in available space). Default 50.
-	int8 flip_x;			///< The skin is flipped horizontally
-	int8 flip_y;			///< The skin is flipped vertically
-	float opacity;			///< Opacity that should be used for the whole widget (0.f - 1.f).
-	TBColor text_color;		///< Color of the text in the widget.
-	TBColor bg_color;		///< Color of the background in the widget.
-	int16 bitmap_dpi;		///< The DPI of the bitmap that was loaded.
-	TBValue tag;			///< This value is free to use for anything. It's not used internally.
-
-	/** Get the minimum width, or SKIN_VALUE_NOT_SPECIFIED if not specified. */
-	int GetMinWidth() const { return min_width; }
-
-	/** Get the minimum height, or SKIN_VALUE_NOT_SPECIFIED if not specified. */
-	int GetMinHeight() const { return min_height; }
-
-	/** Get the intrinsic minimum width. It will be calculated based on the skin properties. */
-	int GetIntrinsicMinWidth() const;
-
-	/** Get the intrinsic minimum height. It will be calculated based on the skin properties. */
-	int GetIntrinsicMinHeight() const;
-
-	/** Get the maximum width, or SKIN_VALUE_NOT_SPECIFIED if not specified. */
-	int GetMaxWidth() const { return max_width; }
-
-	/** Get the maximum height, or SKIN_VALUE_NOT_SPECIFIED if not specified. */
-	int GetMaxHeight() const { return max_height; }
-
-	/** Get the preferred width, or SKIN_VALUE_NOT_SPECIFIED if not specified. */
-	int GetPrefWidth() const { return pref_width; }
-
-	/** Get the preferred height, or SKIN_VALUE_NOT_SPECIFIED if not specified. */
-	int GetPrefHeight() const { return pref_height; }
-
-	/** Get the intrinsic width. If not specified using the "width" attribute, it will be
-		calculated based on the skin properties. If it can't be calculated it will return
-		SKIN_VALUE_NOT_SPECIFIED. */
-	int GetIntrinsicWidth() const;
-
-	/** Get the intrinsic height. If not specified using the "height" attribute, it will be
-		calculated based on the skin properties. If it can't be calculated it will return
-		SKIN_VALUE_NOT_SPECIFIED. */
-	int GetIntrinsicHeight() const;
-
-	/** Set the DPI that the bitmap was loaded in. This may modify properties
-		to compensate for the bitmap resolution. */
-	void SetBitmapDPI(const TBDimensionConverter &dim_conv, int bitmap_dpi);
-
-	/** List of override elements (See TBSkin::PaintSkin) */
-	TBSkinElementStateList m_override_elements;
-
-	/** List of strong-override elements (See TBSkin::PaintSkin) */
-	TBSkinElementStateList m_strong_override_elements;
-
-	/** List of child elements (See TBSkin::PaintSkin) */
-	TBSkinElementStateList m_child_elements;
-
-	/** List of overlay elements (See TBSkin::PaintSkin) */
-	TBSkinElementStateList m_overlay_elements;
-
-	/** Check if there's a exact or partial match for the given state in either
-		override, child or overlay element list.
-		State elements with state "all" will be ignored. */
-	bool HasState(SKIN_STATE state, TBSkinConditionContext &context);
-
-	/** Return true if this element has overlay elements. */
-	bool HasOverlayElements() const { return m_overlay_elements.HasStateElements(); }
-
-	void Load(TBNode *n, TBSkin *skin, const char *skin_path);
+    TBSkinElement();
+    ~TBSkinElement();
+
+    // Skin properties
+    TBID id;			///< ID of the skin element
+    TBStr name;			///< Name of the skin element, f.ex "TBSelectDropdown.arrow"
+    TBStr bitmap_file;	///< File name of the bitmap (might be empty)
+    TBBitmapFragment *bitmap;///< Bitmap fragment containing the graphics, or nullptr.
+    uint8 cut;			///< How the bitmap should be sliced using StretchBox.
+    int16 expand;		///< How much the skin should expand outside the widgets rect.
+    SKIN_ELEMENT_TYPE type;///< Skin element type
+    bool is_painting;	///< If the skin is being painted (avoiding eternal recursing)
+    bool is_getting;	///< If the skin is being got (avoiding eternal recursion)
+    int16 padding_left;		///< Left padding for any content in the element
+    int16 padding_top;		///< Top padding for any content in the element
+    int16 padding_right;	///< Right padding for any content in the element
+    int16 padding_bottom;	///< Bottom padding for any content in the element
+    int16 width;			///< Intrinsic width or SKIN_VALUE_NOT_SPECIFIED
+    int16 height;			///< Intrinsic height or SKIN_VALUE_NOT_SPECIFIED
+    int16 pref_width;		///< Preferred width or SKIN_VALUE_NOT_SPECIFIED
+    int16 pref_height;		///< Preferred height or SKIN_VALUE_NOT_SPECIFIED
+    int16 min_width;		///< Minimum width or SKIN_VALUE_NOT_SPECIFIED
+    int16 min_height;		///< Minimum height or SKIN_VALUE_NOT_SPECIFIED
+    int16 max_width;		///< Maximum width or SKIN_VALUE_NOT_SPECIFIED
+    int16 max_height;		///< Maximum height or SKIN_VALUE_NOT_SPECIFIED
+    int16 spacing;			///< Spacing used on layout or SKIN_VALUE_NOT_SPECIFIED.
+    int16 content_ofs_x;	///< X offset of the content in the widget.
+    int16 content_ofs_y;	///< Y offset of the content in the widget.
+    int16 img_ofs_x;		///< X offset for type image. Relative to image position (img_position_x).
+    int16 img_ofs_y;		///< Y offset for type image. Relative to image position (img_position_y).
+    int8 img_position_x;	///< Horizontal position for type image. 0-100 (left to
+    ///< right in available space). Default 50.
+    int8 img_position_y;	///< Vertical position for type image. 0-100 (top to bottom
+    ///< in available space). Default 50.
+    int8 flip_x;			///< The skin is flipped horizontally
+    int8 flip_y;			///< The skin is flipped vertically
+    float opacity;			///< Opacity that should be used for the whole widget (0.f - 1.f).
+    TBColor text_color;		///< Color of the text in the widget.
+    TBColor bg_color;		///< Color of the background in the widget.
+    int16 bitmap_dpi;		///< The DPI of the bitmap that was loaded.
+    TBValue tag;			///< This value is free to use for anything. It's not used internally.
+
+    /** Get the minimum width, or SKIN_VALUE_NOT_SPECIFIED if not specified. */
+    int GetMinWidth() const { return min_width; }
+
+    /** Get the minimum height, or SKIN_VALUE_NOT_SPECIFIED if not specified. */
+    int GetMinHeight() const { return min_height; }
+
+    /** Get the intrinsic minimum width. It will be calculated based on the skin properties. */
+    int GetIntrinsicMinWidth() const;
+
+    /** Get the intrinsic minimum height. It will be calculated based on the skin properties. */
+    int GetIntrinsicMinHeight() const;
+
+    /** Get the maximum width, or SKIN_VALUE_NOT_SPECIFIED if not specified. */
+    int GetMaxWidth() const { return max_width; }
+
+    /** Get the maximum height, or SKIN_VALUE_NOT_SPECIFIED if not specified. */
+    int GetMaxHeight() const { return max_height; }
+
+    /** Get the preferred width, or SKIN_VALUE_NOT_SPECIFIED if not specified. */
+    int GetPrefWidth() const { return pref_width; }
+
+    /** Get the preferred height, or SKIN_VALUE_NOT_SPECIFIED if not specified. */
+    int GetPrefHeight() const { return pref_height; }
+
+    /** Get the intrinsic width. If not specified using the "width" attribute, it will be
+        calculated based on the skin properties. If it can't be calculated it will return
+        SKIN_VALUE_NOT_SPECIFIED. */
+    int GetIntrinsicWidth() const;
+
+    /** Get the intrinsic height. If not specified using the "height" attribute, it will be
+        calculated based on the skin properties. If it can't be calculated it will return
+        SKIN_VALUE_NOT_SPECIFIED. */
+    int GetIntrinsicHeight() const;
+
+    /** Set the DPI that the bitmap was loaded in. This may modify properties
+        to compensate for the bitmap resolution. */
+    void SetBitmapDPI(const TBDimensionConverter &dim_conv, int bitmap_dpi);
+
+    /** List of override elements (See TBSkin::PaintSkin) */
+    TBSkinElementStateList m_override_elements;
+
+    /** List of strong-override elements (See TBSkin::PaintSkin) */
+    TBSkinElementStateList m_strong_override_elements;
+
+    /** List of child elements (See TBSkin::PaintSkin) */
+    TBSkinElementStateList m_child_elements;
+
+    /** List of overlay elements (See TBSkin::PaintSkin) */
+    TBSkinElementStateList m_overlay_elements;
+
+    /** Check if there's a exact or partial match for the given state in either
+        override, child or overlay element list.
+        State elements with state "all" will be ignored. */
+    bool HasState(SKIN_STATE state, TBSkinConditionContext &context);
+
+    /** Return true if this element has overlay elements. */
+    bool HasOverlayElements() const { return m_overlay_elements.HasStateElements(); }
+
+    void Load(TBNode *n, TBSkin *skin, const char *skin_path);
 };
 
 class TBSkinListener
 {
 public:
-	/** Called when a skin element has been loaded from the given TBNode.
-		NOTE: This may be called multiple times on elements that occur multiple times
-		in the skin or is overridden in an override skin.
-		This method can be used to f.ex feed custom properties into element->tag. */
-	virtual void OnSkinElementLoaded(TBSkin *skin, TBSkinElement *element, TBNode *node) = 0;
+    /** Called when a skin element has been loaded from the given TBNode.
+        NOTE: This may be called multiple times on elements that occur multiple times
+        in the skin or is overridden in an override skin.
+        This method can be used to f.ex feed custom properties into element->tag. */
+    virtual void OnSkinElementLoaded(TBSkin *skin, TBSkinElement *element, TBNode *node) = 0;
 };
 
 /** TBSkin contains a list of TBSkinElement. */
 class TBSkin : private TBRendererListener
 {
 public:
-	TBSkin();
-	virtual ~TBSkin();
+    TBSkin();
+    virtual ~TBSkin();
 
-	/** Set the listener for this skin. */
-	void SetListener(TBSkinListener *listener) { m_listener = listener; }
-	TBSkinListener *GetListener() const { return m_listener;  }
+    /** Set the listener for this skin. */
+    void SetListener(TBSkinListener *listener) { m_listener = listener; }
+    TBSkinListener *GetListener() const { return m_listener;  }
 
-	/** Load the skin file and the bitmaps it refers to.
+    /** Load the skin file and the bitmaps it refers to.
 
-		If override_skin_file is specified, it will also be loaded into this skin after
-		loading skin_file. Elements using the same name will override any previosly
-		read data for the same element. Known limitation: Clone can currently only
-		clone elements in the same file!
+        If override_skin_file is specified, it will also be loaded into this skin after
+        loading skin_file. Elements using the same name will override any previosly
+        read data for the same element. Known limitation: Clone can currently only
+        clone elements in the same file!
 
-		Returns true on success, and all bitmaps referred to also loaded successfully. */
-	bool Load(const char *skin_file, const char *override_skin_file = nullptr);
+        Returns true on success, and all bitmaps referred to also loaded successfully. */
+    bool Load(const char *skin_file, const char *override_skin_file = nullptr);
 
-	/** Unload all bitmaps used in this skin. */
-	void UnloadBitmaps();
+    /** Unload all bitmaps used in this skin. */
+    void UnloadBitmaps();
 
-	/** Reload all bitmaps used in this skin. Calls UnloadBitmaps first to ensure no bitmaps
-		are loaded before loading new ones. */
-	bool ReloadBitmaps();
+    /** Reload all bitmaps used in this skin. Calls UnloadBitmaps first to ensure no bitmaps
+        are loaded before loading new ones. */
+    bool ReloadBitmaps();
 
-	/** Get the dimension converter used for the current skin. This dimension converter
-		converts to px by the same factor as the skin (based on the skin DPI settings). */
-	const TBDimensionConverter *GetDimensionConverter() const { return &m_dim_conv; }
+    /** Get the dimension converter used for the current skin. This dimension converter
+        converts to px by the same factor as the skin (based on the skin DPI settings). */
+    const TBDimensionConverter *GetDimensionConverter() const { return &m_dim_conv; }
 
-	/** Get the skin element with the given id.
-		Returns nullptr if there's no match. */
-	TBSkinElement *GetSkinElement(const TBID &skin_id) const;
+    /** Get the skin element with the given id.
+        Returns nullptr if there's no match. */
+    TBSkinElement *GetSkinElement(const TBID &skin_id) const;
 
-	/** Get the skin element with the given id and state.
-		This is like calling GetSkinElement and also following any strong overrides that
-		match the current state (if any). See details about strong overrides in PaintSkin.
-		Returns nullptr if there's no match. */
-	TBSkinElement *GetSkinElementStrongOverride(const TBID &skin_id, SKIN_STATE state, TBSkinConditionContext &context) const;
+    /** Get the skin element with the given id and state.
+        This is like calling GetSkinElement and also following any strong overrides that
+        match the current state (if any). See details about strong overrides in PaintSkin.
+        Returns nullptr if there's no match. */
+    TBSkinElement *GetSkinElementStrongOverride(const TBID &skin_id, SKIN_STATE state, TBSkinConditionContext &context) const;
 
-	/** Get the default text color for all skin elements */
-	TBColor GetDefaultTextColor() const { return m_default_text_color; }
+    /** Get the default text color for all skin elements */
+    TBColor GetDefaultTextColor() const { return m_default_text_color; }
 
-	/** Get the default disabled opacity for all skin elements */
-	float GetDefaultDisabledOpacity() const { return m_default_disabled_opacity; }
+    /** Get the default disabled opacity for all skin elements */
+    float GetDefaultDisabledOpacity() const { return m_default_disabled_opacity; }
 
-	/** Get the default placeholder opacity for all skin elements */
-	float GetDefaultPlaceholderOpacity() const { return m_default_placeholder_opacity; }
+    /** Get the default placeholder opacity for all skin elements */
+    float GetDefaultPlaceholderOpacity() const { return m_default_placeholder_opacity; }
 
-	/** Get the default layout spacing in pixels. */
-	int GetDefaultSpacing() const { return m_default_spacing; }
+    /** Get the default layout spacing in pixels. */
+    int GetDefaultSpacing() const { return m_default_spacing; }
 
-	/** Paint the skin at dst_rect.
+    /** Paint the skin at dst_rect.
 
-		Strong override elements:
-		-Strong override elements are like override elements, but they don't only apply
-		 when painting. They also override padding and other things that might affect
-		 the layout of the widget having the skin set.
+        Strong override elements:
+        -Strong override elements are like override elements, but they don't only apply
+         when painting. They also override padding and other things that might affect
+         the layout of the widget having the skin set.
 
-		Override elements:
-		-If there is a override element with the exact matching state, it will paint
-		 the override *instead* if the base skin. If no exact match was found, it will
-		 check for a partial match and paint that *instead* of the base skin.
+        Override elements:
+        -If there is a override element with the exact matching state, it will paint
+         the override *instead* if the base skin. If no exact match was found, it will
+         check for a partial match and paint that *instead* of the base skin.
 
-		Child elements:
-		-It will paint *all* child elements that match the current state ("all" can be specified
-		 as state so it will always be painted). The elements are painted in the order they are
-		 specified in the skin.
+        Child elements:
+        -It will paint *all* child elements that match the current state ("all" can be specified
+         as state so it will always be painted). The elements are painted in the order they are
+         specified in the skin.
 
-		Special elements:
-		-There's some special generic skin elements used by TBWidget (see TBWidget::SetSkinBg)
+        Special elements:
+        -There's some special generic skin elements used by TBWidget (see TBWidget::SetSkinBg)
 
-		Overlay elements:
-		-Overlay elements are painted separately, from PaintSkinOverlay (when all sibling
-		 widgets has been painted). As with child elements, all overlay elements that match
-		 the current state will be painted in the order they are specified in the skin.
+        Overlay elements:
+        -Overlay elements are painted separately, from PaintSkinOverlay (when all sibling
+         widgets has been painted). As with child elements, all overlay elements that match
+         the current state will be painted in the order they are specified in the skin.
 
-		Return the skin element used (after following override elements),
-		or nullptr if no skin element was found matching the skin_id. */
-	TBSkinElement *PaintSkin(const TBRect &dst_rect, const TBID &skin_id, SKIN_STATE state, TBSkinConditionContext &context);
+        Return the skin element used (after following override elements),
+        or nullptr if no skin element was found matching the skin_id. */
+    TBSkinElement *PaintSkin(const TBRect &dst_rect, const TBID &skin_id, SKIN_STATE state, TBSkinConditionContext &context);
 
-	/** Paint the skin at dst_rect. Just like the PaintSkin above, but takes a specific
-		skin element instead of looking it up from the id. */
-	TBSkinElement *PaintSkin(const TBRect &dst_rect, TBSkinElement *element, SKIN_STATE state, TBSkinConditionContext &context);
+    /** Paint the skin at dst_rect. Just like the PaintSkin above, but takes a specific
+        skin element instead of looking it up from the id. */
+    TBSkinElement *PaintSkin(const TBRect &dst_rect, TBSkinElement *element, SKIN_STATE state, TBSkinConditionContext &context);
 
-	/** Paint the overlay elements for the given skin element and state. */
-	void PaintSkinOverlay(const TBRect &dst_rect, TBSkinElement *element, SKIN_STATE state, TBSkinConditionContext &context);
+    /** Paint the overlay elements for the given skin element and state. */
+    void PaintSkinOverlay(const TBRect &dst_rect, TBSkinElement *element, SKIN_STATE state, TBSkinConditionContext &context);
 
 #ifdef TB_RUNTIME_DEBUG_INFO
-	/** Render the skin bitmaps on screen, to analyze fragment positioning. */
-	void Debug();
+    /** Render the skin bitmaps on screen, to analyze fragment positioning. */
+    void Debug();
 #endif
 
-	// Implementing TBRendererListener
-	virtual void OnContextLost();
-	virtual void OnContextRestored();
+    // Implementing TBRendererListener
+    virtual void OnContextLost();
+    virtual void OnContextRestored();
 private:
-	friend class TBSkinElement;
-	TBSkinListener *m_listener;
-	TBHashTableAutoDeleteOf<TBSkinElement> m_elements;	///< All skin elements for this skin.
-	TBBitmapFragmentManager m_frag_manager;				///< Fragment manager
-	TBDimensionConverter m_dim_conv;					///< Dimension converter
-	TBColor m_default_text_color;						///< Default text color for all skin elements
-	float m_default_disabled_opacity;					///< Disabled opacity
-	float m_default_placeholder_opacity;				///< Placeholder opacity
-	int16 m_default_spacing;							///< Default layout spacing
-	bool LoadInternal(const char *skin_file);
-	bool ReloadBitmapsInternal();
-	void PaintElement(const TBRect &dst_rect, TBSkinElement *element);
-	void PaintElementBGColor(const TBRect &dst_rect, TBSkinElement *element);
-	void PaintElementImage(const TBRect &dst_rect, TBSkinElement *element);
-	void PaintElementTile(const TBRect &dst_rect, TBSkinElement *element);
-	void PaintElementStretchImage(const TBRect &dst_rect, TBSkinElement *element);
-	void PaintElementStretchBox(const TBRect &dst_rect, TBSkinElement *element, bool fill_center);
-	TBRect GetFlippedRect(const TBRect &src_rect, TBSkinElement *element) const;
-	int GetPxFromNode(TBNode *node, int def_value) const;
+    friend class TBSkinElement;
+    TBSkinListener *m_listener;
+    TBHashTableAutoDeleteOf<TBSkinElement> m_elements;	///< All skin elements for this skin.
+    TBBitmapFragmentManager m_frag_manager;				///< Fragment manager
+    TBDimensionConverter m_dim_conv;					///< Dimension converter
+    TBColor m_default_text_color;						///< Default text color for all skin elements
+    float m_default_disabled_opacity;					///< Disabled opacity
+    float m_default_placeholder_opacity;				///< Placeholder opacity
+    int16 m_default_spacing;							///< Default layout spacing
+    bool LoadInternal(const char *skin_file);
+    bool ReloadBitmapsInternal();
+    void PaintElement(const TBRect &dst_rect, TBSkinElement *element);
+    void PaintElementBGColor(const TBRect &dst_rect, TBSkinElement *element);
+    void PaintElementImage(const TBRect &dst_rect, TBSkinElement *element);
+    void PaintElementTile(const TBRect &dst_rect, TBSkinElement *element);
+    void PaintElementStretchImage(const TBRect &dst_rect, TBSkinElement *element);
+    void PaintElementStretchBox(const TBRect &dst_rect, TBSkinElement *element, bool fill_center);
+    TBRect GetFlippedRect(const TBRect &src_rect, TBSkinElement *element) const;
+    int GetPxFromNode(TBNode *node, int def_value) const;
 };
 
 }; // namespace tb

+ 32 - 32
Source/ThirdParty/TurboBadger/tb_skin_util.cpp

@@ -9,42 +9,42 @@ namespace tb {
 
 static int GetFadeoutSize(int scrolled_distance, int fadeout_length)
 {
-	// Make it appear gradually
-	//float factor = scrolled_distance / 10.f;
-	//factor = CLAMP(factor, 0.5f, 1);
-	//return (int)(fadeout_length * factor);
-	return scrolled_distance > 0 ? fadeout_length : 0;
+    // Make it appear gradually
+    //float factor = scrolled_distance / 10.f;
+    //factor = CLAMP(factor, 0.5f, 1);
+    //return (int)(fadeout_length * factor);
+    return scrolled_distance > 0 ? fadeout_length : 0;
 }
 
 void DrawEdgeFadeout(const TBRect &dst_rect, TBID skin_x, TBID skin_y,
-					 int left, int top, int right, int bottom)
+                     int left, int top, int right, int bottom)
 {
-	if (TBSkinElement *skin = g_tb_skin->GetSkinElement(skin_x))
-	{
-		if (skin->bitmap)
-		{
-			int bw = skin->bitmap->Width();
-			int bh = skin->bitmap->Height();
-			int dw;
-			if ((dw = GetFadeoutSize(left, bw)) > 0)
-				g_renderer->DrawBitmap(TBRect(dst_rect.x, dst_rect.y, dw, dst_rect.h), TBRect(0, 0, bw, bh), skin->bitmap);
-			if ((dw = GetFadeoutSize(right, bw)) > 0)
-				g_renderer->DrawBitmap(TBRect(dst_rect.x + dst_rect.w - dw, dst_rect.y, dw, dst_rect.h), TBRect(bw, 0, -bw, bh), skin->bitmap);
-		}
-	}
-	if (TBSkinElement *skin = g_tb_skin->GetSkinElement(skin_y))
-	{
-		if (skin->bitmap)
-		{
-			int bw = skin->bitmap->Width();
-			int bh = skin->bitmap->Height();
-			int dh;
-			if ((dh = GetFadeoutSize(top, bh)) > 0)
-				g_renderer->DrawBitmap(TBRect(dst_rect.x, dst_rect.y, dst_rect.w, dh), TBRect(0, 0, bw, bh), skin->bitmap);
-			if ((dh = GetFadeoutSize(bottom, bh)) > 0)
-				g_renderer->DrawBitmap(TBRect(dst_rect.x, dst_rect.y + dst_rect.h - dh, dst_rect.w, dh), TBRect(0, bh, bw, -bh), skin->bitmap);
-		}
-	}
+    if (TBSkinElement *skin = g_tb_skin->GetSkinElement(skin_x))
+    {
+        if (skin->bitmap)
+        {
+            int bw = skin->bitmap->Width();
+            int bh = skin->bitmap->Height();
+            int dw;
+            if ((dw = GetFadeoutSize(left, bw)) > 0)
+                g_renderer->DrawBitmap(TBRect(dst_rect.x, dst_rect.y, dw, dst_rect.h), TBRect(0, 0, bw, bh), skin->bitmap);
+            if ((dw = GetFadeoutSize(right, bw)) > 0)
+                g_renderer->DrawBitmap(TBRect(dst_rect.x + dst_rect.w - dw, dst_rect.y, dw, dst_rect.h), TBRect(bw, 0, -bw, bh), skin->bitmap);
+        }
+    }
+    if (TBSkinElement *skin = g_tb_skin->GetSkinElement(skin_y))
+    {
+        if (skin->bitmap)
+        {
+            int bw = skin->bitmap->Width();
+            int bh = skin->bitmap->Height();
+            int dh;
+            if ((dh = GetFadeoutSize(top, bh)) > 0)
+                g_renderer->DrawBitmap(TBRect(dst_rect.x, dst_rect.y, dst_rect.w, dh), TBRect(0, 0, bw, bh), skin->bitmap);
+            if ((dh = GetFadeoutSize(bottom, bh)) > 0)
+                g_renderer->DrawBitmap(TBRect(dst_rect.x, dst_rect.y + dst_rect.h - dh, dst_rect.w, dh), TBRect(0, bh, bw, -bh), skin->bitmap);
+        }
+    }
 }
 
 }; // namespace tb

+ 4 - 4
Source/ThirdParty/TurboBadger/tb_skin_util.h

@@ -11,11 +11,11 @@
 namespace tb {
 
 /** Draw fade out skin elements at the edges of dst_rect if needed.
-	It indicates to the user that there is hidden content.
-	left, top, right, bottom specifies the (positive) distance scrolled
-	from the limit. */
+    It indicates to the user that there is hidden content.
+    left, top, right, bottom specifies the (positive) distance scrolled
+    from the limit. */
 void DrawEdgeFadeout(const TBRect &dst_rect, TBID skin_x, TBID skin_y,
-					 int left, int top, int right, int bottom);
+                     int left, int top, int right, int bottom);
 
 }; // namespace tb
 

+ 8 - 8
Source/ThirdParty/TurboBadger/tb_sort.h

@@ -11,14 +11,14 @@ namespace tb {
 template<class CONTEXT, class TYPE>
 static void insertion_sort(TYPE *elements, size_t element_count, CONTEXT context, int(*cmp)(CONTEXT context, const TYPE *a, const TYPE *b))
 {
-	size_t i, j;
-	for (i = 1; i < element_count; i++)
-	{
-		TYPE value = elements[i];
-		for (j = i; j > 0 && cmp(context, &value, &elements[j - 1]) < 0; j--)
-			elements[j] = elements[j - 1];
-		elements[j] = value;
-	}
+    size_t i, j;
+    for (i = 1; i < element_count; i++)
+    {
+        TYPE value = elements[i];
+        for (j = i; j > 0 && cmp(context, &value, &elements[j - 1]) < 0; j--)
+            elements[j] = elements[j - 1];
+        elements[j] = value;
+    }
 }
 
 }; // namespace tb

+ 93 - 93
Source/ThirdParty/TurboBadger/tb_str.cpp

@@ -15,145 +15,145 @@ namespace tb {
 static const char *empty = "";
 inline void safe_delete(char *&str)
 {
-	if (str != empty && str)
-		free(str);
-	str = const_cast<char*>(empty);
+    if (str != empty && str)
+        free(str);
+    str = const_cast<char*>(empty);
 }
 
 const char *stristr(const char *arg1, const char *arg2)
 {
-	const char *a, *b;
-
-	for(;*arg1;arg1++)
-	{
-		a = arg1;
-		b = arg2;
-		while (toupper(*a++) == toupper(*b++))
-			if (!*b)
-				return arg1;
-	}
-	return nullptr;
+    const char *a, *b;
+
+    for(;*arg1;arg1++)
+    {
+        a = arg1;
+        b = arg2;
+        while (toupper(*a++) == toupper(*b++))
+            if (!*b)
+                return arg1;
+    }
+    return nullptr;
 }
 
 // == TBStr ==========================================================
 
 TBStr::TBStr()
-	: TBStrC(empty)
+    : TBStrC(empty)
 {
 }
 
 TBStr::TBStr(const char* str)
-	: TBStrC(str == empty ? empty : strdup(str))
+    : TBStrC(str == empty ? empty : strdup(str))
 {
-	if (!s)
-		s = const_cast<char*>(empty);
+    if (!s)
+        s = const_cast<char*>(empty);
 }
 
 TBStr::TBStr(const TBStr &str)
-	: TBStrC(str.s == empty ? empty : strdup(str.s))
+    : TBStrC(str.s == empty ? empty : strdup(str.s))
 {
-	if (!s)
-		s = const_cast<char*>(empty);
+    if (!s)
+        s = const_cast<char*>(empty);
 }
 
 TBStr::TBStr(const char* str, int len)
-	: TBStrC(empty)
+    : TBStrC(empty)
 {
-	Set(str, len);
+    Set(str, len);
 }
 
 TBStr::~TBStr()
 {
-	safe_delete(s);
+    safe_delete(s);
 }
 
 bool TBStr::Set(const char* str, int len)
 {
-	safe_delete(s);
-	if (len == TB_ALL_TO_TERMINATION)
-		len = strlen(str);
-	if (char *new_s = (char *) malloc(len + 1))
-	{
-		s = new_s;
-		memcpy(s, str, len);
-		s[len] = 0;
-		return true;
-	}
-	return false;
+    safe_delete(s);
+    if (len == TB_ALL_TO_TERMINATION)
+        len = strlen(str);
+    if (char *new_s = (char *) malloc(len + 1))
+    {
+        s = new_s;
+        memcpy(s, str, len);
+        s[len] = 0;
+        return true;
+    }
+    return false;
 }
 
 bool TBStr::SetFormatted(const char* format, ...)
 {
-	safe_delete(s);
-	if (!format)
-		return true;
-	va_list ap;
-	int max_len = 64;
-	char *new_s = nullptr;
-	while (true)
-	{
-		if (char *tris_try_new_s = (char *) realloc(new_s, max_len))
-		{
-			new_s = tris_try_new_s;
-
-			va_start(ap, format);
-			int ret = vsnprintf(new_s, max_len, format, ap);
-			va_end(ap);
-
-			if (ret > max_len) // Needed size is known (+2 for termination and avoid ambiguity)
-				max_len = ret + 2;
-			else if (ret == -1 || ret >= max_len - 1) // Handle some buggy vsnprintf implementations.
-				max_len *= 2;
-			else // Everything fit for sure
-			{
-				s = new_s;
-				return true;
-			}
-		}
-		else
-		{
-			// Out of memory
-			free(new_s);
-			break;
-		}
-	}
-	return false;
+    safe_delete(s);
+    if (!format)
+        return true;
+    va_list ap;
+    int max_len = 64;
+    char *new_s = nullptr;
+    while (true)
+    {
+        if (char *tris_try_new_s = (char *) realloc(new_s, max_len))
+        {
+            new_s = tris_try_new_s;
+
+            va_start(ap, format);
+            int ret = vsnprintf(new_s, max_len, format, ap);
+            va_end(ap);
+
+            if (ret > max_len) // Needed size is known (+2 for termination and avoid ambiguity)
+                max_len = ret + 2;
+            else if (ret == -1 || ret >= max_len - 1) // Handle some buggy vsnprintf implementations.
+                max_len *= 2;
+            else // Everything fit for sure
+            {
+                s = new_s;
+                return true;
+            }
+        }
+        else
+        {
+            // Out of memory
+            free(new_s);
+            break;
+        }
+    }
+    return false;
 }
 
 void TBStr::Clear()
 {
-	safe_delete(s);
+    safe_delete(s);
 }
 
 void TBStr::Remove(int ofs, int len)
 {
-	assert(ofs >= 0 && (ofs + len <= (int)strlen(s)));
-	if (!len)
-		return;
-	char *dst = s + ofs;
-	char *src = s + ofs + len;
-	while (*src != 0)
-		*(dst++) = *(src++);
-	*dst = *src;
+    assert(ofs >= 0 && (ofs + len <= (int)strlen(s)));
+    if (!len)
+        return;
+    char *dst = s + ofs;
+    char *src = s + ofs + len;
+    while (*src != 0)
+        *(dst++) = *(src++);
+    *dst = *src;
 }
 
 bool TBStr::Insert(int ofs, const char *ins, int ins_len)
 {
-	int len1 = strlen(s);
-	if (ins_len == TB_ALL_TO_TERMINATION)
-		ins_len = strlen(ins);
-	int newlen = len1 + ins_len;
-	if (char *news = (char *) malloc(newlen + 1))
-	{
-		memcpy(&news[0], s, ofs);
-		memcpy(&news[ofs], ins, ins_len);
-		memcpy(&news[ofs + ins_len], &s[ofs], len1 - ofs);
-		news[newlen] = 0;
-		safe_delete(s);
-		s = news;
-		return true;
-	}
-	return false;
+    int len1 = strlen(s);
+    if (ins_len == TB_ALL_TO_TERMINATION)
+        ins_len = strlen(ins);
+    int newlen = len1 + ins_len;
+    if (char *news = (char *) malloc(newlen + 1))
+    {
+        memcpy(&news[0], s, ofs);
+        memcpy(&news[ofs], ins, ins_len);
+        memcpy(&news[ofs + ins_len], &s[ofs], len1 - ofs);
+        news[newlen] = 0;
+        safe_delete(s);
+        s = news;
+        return true;
+    }
+    return false;
 }
 
 }; // namespace tb

+ 31 - 31
Source/ThirdParty/TurboBadger/tb_str.h

@@ -12,7 +12,7 @@
 namespace tb {
 
 /** Use as parameter for string length if you know the string is null terminated.
-	Can be used in functions that support it. */
+    Can be used in functions that support it. */
 #define TB_ALL_TO_TERMINATION 2147483647
 
 /** Some useful C-like functions that's missing in the standard. */
@@ -23,54 +23,54 @@ const char *stristr(const char *arg1, const char *arg2);
 class TBStrC
 {
 protected:
-	char *s;
+    char *s;
 public:
-	TBStrC(const char *str) : s(const_cast<char *>(str)) {}
+    TBStrC(const char *str) : s(const_cast<char *>(str)) {}
 
-	inline int Length() const							{ return (int) strlen(s); }
-	inline bool IsEmpty() const							{ return s[0] == 0; }
+    inline int Length() const							{ return (int) strlen(s); }
+    inline bool IsEmpty() const							{ return s[0] == 0; }
 
-	inline int Compare(const char* str) const			{ return strcmp(s, str); }
-	inline bool Equals(const char* str) const			{ return !strcmp(s, str); }
+    inline int Compare(const char* str) const			{ return strcmp(s, str); }
+    inline bool Equals(const char* str) const			{ return !strcmp(s, str); }
 
-	inline char operator[](int n) const					{ return s[n]; }
-	inline operator const char *() const				{ return s; }
-	const char *CStr() const							{ return s; }
+    inline char operator[](int n) const					{ return s[n]; }
+    inline operator const char *() const				{ return s; }
+    const char *CStr() const							{ return s; }
 };
 
 /** TBStr is a simple string class.
-	It's a compact wrapper for a char array, and doesn't do any storage magic to
-	avoid buffer copying or remember its length. It is intended as "final storage"
-	of strings since its buffer is compact.
+    It's a compact wrapper for a char array, and doesn't do any storage magic to
+    avoid buffer copying or remember its length. It is intended as "final storage"
+    of strings since its buffer is compact.
 
-	Serious work on strings is better done using TBTempBuffer and then set on a TBStr for
-	final storage (since TBTempBuffer is optimized for speed rather than being compact).
+    Serious work on strings is better done using TBTempBuffer and then set on a TBStr for
+    final storage (since TBTempBuffer is optimized for speed rather than being compact).
 
-	It is guaranteed to have a valid pointer at all times. If uninitialized, emptied or on
-	out of memory, its storage will be a empty ("") const string.
+    It is guaranteed to have a valid pointer at all times. If uninitialized, emptied or on
+    out of memory, its storage will be a empty ("") const string.
 */
 
 class TBStr : public TBStrC
 {
 public:
-	~TBStr();
-	TBStr();
-	TBStr(const TBStr &str);
-	TBStr(const char* str);
-	TBStr(const char* str, int len);
+    ~TBStr();
+    TBStr();
+    TBStr(const TBStr &str);
+    TBStr(const char* str);
+    TBStr(const char* str, int len);
 
-	bool Set(const char* str, int len = TB_ALL_TO_TERMINATION);
-	bool SetFormatted(const char* format, ...);
+    bool Set(const char* str, int len = TB_ALL_TO_TERMINATION);
+    bool SetFormatted(const char* format, ...);
 
-	void Clear();
+    void Clear();
 
-	void Remove(int ofs, int len);
-	bool Insert(int ofs, const char *ins, int ins_len = TB_ALL_TO_TERMINATION);
-	bool Append(const char *ins, int ins_len = TB_ALL_TO_TERMINATION)	{ return Insert((int)strlen(s), ins, ins_len); }
+    void Remove(int ofs, int len);
+    bool Insert(int ofs, const char *ins, int ins_len = TB_ALL_TO_TERMINATION);
+    bool Append(const char *ins, int ins_len = TB_ALL_TO_TERMINATION)	{ return Insert((int)strlen(s), ins, ins_len); }
 
-	inline operator char *() const						{ return s; }
-	char *CStr() const									{ return s; }
-	const TBStr& operator = (const TBStr &str)			{ Set(str); return *this; }
+    inline operator char *() const						{ return s; }
+    char *CStr() const									{ return s; }
+    const TBStr& operator = (const TBStr &str)			{ Set(str); return *this; }
 };
 
 }; // namespace tb

File diff suppressed because it is too large
+ 458 - 458
Source/ThirdParty/TurboBadger/tb_style_edit.cpp


+ 296 - 296
Source/ThirdParty/TurboBadger/tb_style_edit.h

@@ -28,21 +28,21 @@ class TBTextTheme;
 class TBStyleEditListener
 {
 public:
-	virtual ~TBStyleEditListener() {}
-
-	virtual void OnChange() {};
-	virtual bool OnEnter() { return false; };
-	virtual void Invalidate(const TBRect &rect) = 0;
-	virtual void DrawString(int32 x, int32 y, TBFontFace *font, const TBColor &color, const char *str, int32 len = TB_ALL_TO_TERMINATION) = 0;
-	virtual void DrawRect(const TBRect &rect, const TBColor &color) = 0;
-	virtual void DrawRectFill(const TBRect &rect, const TBColor &color) = 0;
-	virtual void DrawTextSelectionBg(const TBRect &rect) = 0;
-	virtual void DrawContentSelectionFg(const TBRect &rect) = 0;
-	virtual void DrawCaret(const TBRect &rect) = 0;
-	virtual void Scroll(int32 dx, int32 dy) = 0;
-	virtual void UpdateScrollbars() = 0;
-	virtual void CaretBlinkStart() = 0;
-	virtual void CaretBlinkStop() = 0;
+    virtual ~TBStyleEditListener() {}
+
+    virtual void OnChange() {};
+    virtual bool OnEnter() { return false; };
+    virtual void Invalidate(const TBRect &rect) = 0;
+    virtual void DrawString(int32 x, int32 y, TBFontFace *font, const TBColor &color, const char *str, int32 len = TB_ALL_TO_TERMINATION) = 0;
+    virtual void DrawRect(const TBRect &rect, const TBColor &color) = 0;
+    virtual void DrawRectFill(const TBRect &rect, const TBColor &color) = 0;
+    virtual void DrawTextSelectionBg(const TBRect &rect) = 0;
+    virtual void DrawContentSelectionFg(const TBRect &rect) = 0;
+    virtual void DrawCaret(const TBRect &rect) = 0;
+    virtual void Scroll(int32 dx, int32 dy) = 0;
+    virtual void UpdateScrollbars() = 0;
+    virtual void CaretBlinkStart() = 0;
+    virtual void CaretBlinkStop() = 0;
 };
 
 class TBStyleEditTextChangeListener
@@ -58,16 +58,16 @@ public:
 class TBTextFragmentContentFactory
 {
 public:
-	virtual ~TBTextFragmentContentFactory() {}
-	/** Should return then length of the text that represents content
-		that can be created by this factory, or 0 there's no match with any content.
+    virtual ~TBTextFragmentContentFactory() {}
+    /** Should return then length of the text that represents content
+        that can be created by this factory, or 0 there's no match with any content.
 
-		F.ex if we can create contet for "<u>" it should return 3 if that is the beginning of
-		text. That length will be consumed from the text output for the created content. */
-	virtual int GetContent(const char *text);
+        F.ex if we can create contet for "<u>" it should return 3 if that is the beginning of
+        text. That length will be consumed from the text output for the created content. */
+    virtual int GetContent(const char *text);
 
-	/** Create content for a string previosly consumed by calling GetContent. */
-	virtual TBTextFragmentContent *CreateFragmentContent(const char *text, int text_len);
+    /** Create content for a string previosly consumed by calling GetContent. */
+    virtual TBTextFragmentContent *CreateFragmentContent(const char *text, int text_len);
 };
 
 #define TB_MAX_TEXT_THEME_COLORS 256
@@ -82,18 +82,18 @@ public:
 class TBTextOfs
 {
 public:
-	TBTextOfs() : block(nullptr), ofs(0) {}
-	TBTextOfs(TBBlock *block, int32 ofs) : block(block), ofs(ofs) {}
+    TBTextOfs() : block(nullptr), ofs(0) {}
+    TBTextOfs(TBBlock *block, int32 ofs) : block(block), ofs(ofs) {}
 
-	void Set(TBBlock *new_block, int32 new_ofs) { block = new_block; ofs = new_ofs; }
-	void Set(const TBTextOfs &pos) { block = pos.block; ofs = pos.ofs; }
+    void Set(TBBlock *new_block, int32 new_ofs) { block = new_block; ofs = new_ofs; }
+    void Set(const TBTextOfs &pos) { block = pos.block; ofs = pos.ofs; }
 
-	int32 GetGlobalOfs(TBStyleEdit *se) const;
-	bool SetGlobalOfs(TBStyleEdit *se, int32 gofs);
+    int32 GetGlobalOfs(TBStyleEdit *se) const;
+    bool SetGlobalOfs(TBStyleEdit *se, int32 gofs);
 
 public:
-	TBBlock *block;
-	int32 ofs;
+    TBBlock *block;
+    int32 ofs;
 };
 
 /** Handles the selected text in a TBStyleEdit. */
@@ -101,29 +101,29 @@ public:
 class TBSelection
 {
 public:
-	TBSelection(TBStyleEdit *styledit);
-	void Invalidate() const;
-	void Select(const TBTextOfs &new_start, const TBTextOfs &new_stop);
-	void Select(const TBPoint &from, const TBPoint &to);
-	void Select(int glob_ofs_from, int glob_ofs_to);
-	void SelectToCaret(TBBlock *old_caret_block, int32 old_caret_ofs);
-	void SelectAll();
-	void SelectNothing();
-	void CorrectOrder();
-	void CopyToClipboard();
-	bool IsBlockSelected(TBBlock *block) const;
-	bool IsFragmentSelected(TBTextFragment *elm) const;
-	bool IsSelected() const;
-	void RemoveContent();
-	bool GetText(TBStr &text) const;
+    TBSelection(TBStyleEdit *styledit);
+    void Invalidate() const;
+    void Select(const TBTextOfs &new_start, const TBTextOfs &new_stop);
+    void Select(const TBPoint &from, const TBPoint &to);
+    void Select(int glob_ofs_from, int glob_ofs_to);
+    void SelectToCaret(TBBlock *old_caret_block, int32 old_caret_ofs);
+    void SelectAll();
+    void SelectNothing();
+    void CorrectOrder();
+    void CopyToClipboard();
+    bool IsBlockSelected(TBBlock *block) const;
+    bool IsFragmentSelected(TBTextFragment *elm) const;
+    bool IsSelected() const;
+    void RemoveContent();
+    bool GetText(TBStr &text) const;
 public:
-	TBStyleEdit *styledit;
-	TBTextOfs start, stop;
+    TBStyleEdit *styledit;
+    TBTextOfs start, stop;
 };
 
 enum TB_CARET_POS {
-	TB_CARET_POS_BEGINNING,
-	TB_CARET_POS_END
+    TB_CARET_POS_BEGINNING,
+    TB_CARET_POS_END
 };
 
 /** The caret in a TBStyleEdit. */
@@ -131,33 +131,33 @@ enum TB_CARET_POS {
 class TBCaret
 {
 public:
-	TBCaret(TBStyleEdit *styledit);
-	void Invalidate();
-	void UpdatePos();
-	bool Move(bool forward, bool word);
-	bool Place(const TBPoint &point);
-	bool Place(TBBlock *block, int ofs, bool allow_snap = true, bool snap_forward = false);
-	void Place(TB_CARET_POS place);
-	void AvoidLineBreak();
-	void Paint(int32 translate_x, int32 translate_y);
-	void ResetBlink();
-	void UpdateWantedX();
-
-	int32 GetGlobalOfs() const { return pos.GetGlobalOfs(styledit); }
-	void SetGlobalOfs(int32 gofs, bool allow_snap = true, bool snap_forward = false);
-
-	TBTextFragment *GetFragment();
+    TBCaret(TBStyleEdit *styledit);
+    void Invalidate();
+    void UpdatePos();
+    bool Move(bool forward, bool word);
+    bool Place(const TBPoint &point);
+    bool Place(TBBlock *block, int ofs, bool allow_snap = true, bool snap_forward = false);
+    void Place(TB_CARET_POS place);
+    void AvoidLineBreak();
+    void Paint(int32 translate_x, int32 translate_y);
+    void ResetBlink();
+    void UpdateWantedX();
+
+    int32 GetGlobalOfs() const { return pos.GetGlobalOfs(styledit); }
+    void SetGlobalOfs(int32 gofs, bool allow_snap = true, bool snap_forward = false);
+
+    TBTextFragment *GetFragment();
 private:
-	void SwitchBlock(bool second);
+    void SwitchBlock(bool second);
 public:
-	TBStyleEdit *styledit;
-	int32 x, y; ///< Relative to the styledit
-	int32 width;
-	int32 height;
-	int32 wanted_x;
-	bool on;
-	bool prefer_first;
-	TBTextOfs pos;
+    TBStyleEdit *styledit;
+    int32 x, y; ///< Relative to the styledit
+    int32 width;
+    int32 height;
+    int32 wanted_x;
+    bool on;
+    bool prefer_first;
+    TBTextOfs pos;
 };
 
 /** TBTextProps is a stack of properties used during layout & paint of TBStyleEdit. */
@@ -165,24 +165,24 @@ public:
 class TBTextProps
 {
 public:
-	class Data : public TBLinkOf<Data>
-	{
-	public:
-		TBFontDescription font_desc;
-		TBColor text_color;
-		bool underline;
-	};
-	TBTextProps(const TBFontDescription &font_desc, const TBColor &text_color);
-
-	Data *Push();
-	void Pop();
-
-	/** Get the font face from the current font description. */
-	TBFontFace *GetFont();
+    class Data : public TBLinkOf<Data>
+    {
+    public:
+        TBFontDescription font_desc;
+        TBColor text_color;
+        bool underline;
+    };
+    TBTextProps(const TBFontDescription &font_desc, const TBColor &text_color);
+
+    Data *Push();
+    void Pop();
+
+    /** Get the font face from the current font description. */
+    TBFontFace *GetFont();
 public:
-	TBLinkListOf<Data> data_list;
-	Data base_data;
-	Data *data;
+    TBLinkListOf<Data> data_list;
+    Data base_data;
+    Data *data;
 };
 
 /** A block of text (a line, that might be wrapped) */
@@ -190,59 +190,59 @@ public:
 class TBBlock : public TBLinkOf<TBBlock>
 {
 public:
-	TBBlock(TBStyleEdit *styledit);
-	~TBBlock();
+    TBBlock(TBStyleEdit *styledit);
+    ~TBBlock();
 
-	void Clear();
-	void Set(const char *newstr, int32 len);
-	void SetAlign(TB_TEXT_ALIGN align);
+    void Clear();
+    void Set(const char *newstr, int32 len);
+    void SetAlign(TB_TEXT_ALIGN align);
 
-	int32 InsertText(int32 ofs, const char *text, int32 len, bool allow_line_recurse);
-	void RemoveContent(int32 ofs, int32 len);
+    int32 InsertText(int32 ofs, const char *text, int32 len, bool allow_line_recurse);
+    void RemoveContent(int32 ofs, int32 len);
 
-	/** Check if this block contains extra line breaks and split into new blocks if it does. */
-	void Split();
+    /** Check if this block contains extra line breaks and split into new blocks if it does. */
+    void Split();
 
-	/** Check if we've lost the ending break on this block and if so merge it with the next block. */
-	void Merge();
+    /** Check if we've lost the ending break on this block and if so merge it with the next block. */
+    void Merge();
 
-	/** Layout the block. To be called when the text has changed or the layout width has changed.
-		@param update_fragments Should be true if the text has been changed (will recreate elements).
-		@param propagate_height If true, all following blocks will be moved if the height changed. */
-	void Layout(bool update_fragments, bool propagate_height);
+    /** Layout the block. To be called when the text has changed or the layout width has changed.
+        @param update_fragments Should be true if the text has been changed (will recreate elements).
+        @param propagate_height If true, all following blocks will be moved if the height changed. */
+    void Layout(bool update_fragments, bool propagate_height);
 
-	/** Update the size of this block. If propagate_height is true, all following blocks will be
-		moved if the height changed. */
-	void SetSize(int32 old_w, int32 new_w, int32 new_h, bool propagate_height);
+    /** Update the size of this block. If propagate_height is true, all following blocks will be
+        moved if the height changed. */
+    void SetSize(int32 old_w, int32 new_w, int32 new_h, bool propagate_height);
 
-	TBTextFragment *FindFragment(int32 ofs, bool prefer_first = false) const;
-	TBTextFragment *FindFragment(int32 x, int32 y) const;
+    TBTextFragment *FindFragment(int32 ofs, bool prefer_first = false) const;
+    TBTextFragment *FindFragment(int32 x, int32 y) const;
 
-	int32 CalculateStringWidth(TBFontFace *font, const char *str, int len = TB_ALL_TO_TERMINATION) const;
-	int32 CalculateTabWidth(TBFontFace *font, int32 xpos) const;
-	int32 CalculateLineHeight(TBFontFace *font) const;
-	int32 CalculateBaseline(TBFontFace *font) const;
+    int32 CalculateStringWidth(TBFontFace *font, const char *str, int len = TB_ALL_TO_TERMINATION) const;
+    int32 CalculateTabWidth(TBFontFace *font, int32 xpos) const;
+    int32 CalculateLineHeight(TBFontFace *font) const;
+    int32 CalculateBaseline(TBFontFace *font) const;
 
     int32 FirstNonTabPos() const;
 
-	void Invalidate();
-	void BuildSelectionRegion(int32 translate_x, int32 translate_y, TBTextProps *props,
-		TBRegion &bg_region, TBRegion &fg_region);
-	void Paint(int32 translate_x, int32 translate_y, TBTextProps *props);
+    void Invalidate();
+    void BuildSelectionRegion(int32 translate_x, int32 translate_y, TBTextProps *props,
+                              TBRegion &bg_region, TBRegion &fg_region);
+    void Paint(int32 translate_x, int32 translate_y, TBTextProps *props);
 public:
-	TBStyleEdit *styledit;
-	TBLinkListOf<TBTextFragment> fragments;
+    TBStyleEdit *styledit;
+    TBLinkListOf<TBTextFragment> fragments;
 
-	int32 ypos;
-	int16 height;
-	int8 align;
-	int line_width_max;
+    int32 ypos;
+    int16 height;
+    int8 align;
+    int line_width_max;
 
-	TBStr str;
-	int32 str_len;
+    TBStr str;
+    int32 str_len;
 
 private:
-	int GetStartIndentation(TBFontFace *font, int first_line_len) const;
+    int GetStartIndentation(TBFontFace *font, int first_line_len) const;
 };
 
 /** Event in the TBUndoRedoStack. Each insert or remove change is stored as a TBUndoEvent, but they may also be merged when appropriate. */
@@ -250,9 +250,9 @@ private:
 class TBUndoEvent
 {
 public:
-	int32 gofs;
-	TBStr text;
-	bool insert;
+    int32 gofs;
+    TBStr text;
+    bool insert;
     bool chain;
 
     TBUndoEvent() : gofs(0), insert(false), chain(false) {}
@@ -263,84 +263,84 @@ public:
 class TBUndoRedoStack
 {
 public:
-	TBUndoRedoStack() : applying(false) {}
-	~TBUndoRedoStack();
+    TBUndoRedoStack() : applying(false) {}
+    ~TBUndoRedoStack();
 
-	void Undo(TBStyleEdit *styledit);
-	void Redo(TBStyleEdit *styledit);
-	void Clear(bool clear_undo, bool clear_redo);
+    void Undo(TBStyleEdit *styledit);
+    void Redo(TBStyleEdit *styledit);
+    void Clear(bool clear_undo, bool clear_redo);
 
-	TBUndoEvent *Commit(TBStyleEdit *styledit, int32 gofs, int32 len, const char *text, bool insert);
+    TBUndoEvent *Commit(TBStyleEdit *styledit, int32 gofs, int32 len, const char *text, bool insert);
 public:
-	TBListOf<TBUndoEvent> undos;
-	TBListOf<TBUndoEvent> redos;
-	bool applying;
+    TBListOf<TBUndoEvent> undos;
+    TBListOf<TBUndoEvent> redos;
+    bool applying;
 private:
-	void Apply(TBStyleEdit *styledit, TBUndoEvent *e, bool reverse);
+    void Apply(TBStyleEdit *styledit, TBUndoEvent *e, bool reverse);
 };
 
 /** The textfragment baseclass for TBStyleEdit.
 
-	TODO: This object is allocated on vast amounts and need
-		  to shrink in size. Remove all cached positioning
-		  and implement a fragment traverser (for TBBlock).
-		  Also allocate fragments in chunks. */
+    TODO: This object is allocated on vast amounts and need
+          to shrink in size. Remove all cached positioning
+          and implement a fragment traverser (for TBBlock).
+          Also allocate fragments in chunks. */
 
 class TBTextFragment : public TBLinkOf<TBTextFragment>
 {
 public:
-	TBTextFragment(TBTextFragmentContent *content = nullptr)
-				: xpos(0)
-				, ypos(0)
-				, ofs(0)
-				, len(0)
-				, line_ypos(0)
-				, line_height(0)
-				, block(nullptr)
-                , themeColor(0)
-				, content(content) {}
-	~TBTextFragment();
+    TBTextFragment(TBTextFragmentContent *content = nullptr)
+        : xpos(0)
+        , ypos(0)
+        , ofs(0)
+        , len(0)
+        , line_ypos(0)
+        , line_height(0)
+        , block(nullptr)
+        , themeColor(0)
+        , content(content) {}
+    ~TBTextFragment();
 
-	void Init(TBBlock *block, uint16 ofs, uint16 len);
+    void Init(TBBlock *block, uint16 ofs, uint16 len);
 
-	void UpdateContentPos();
+    void UpdateContentPos();
 
-	void BuildSelectionRegion(int32 translate_x, int32 translate_y, TBTextProps *props,
-		TBRegion &bg_region, TBRegion &fg_region);
-	void Paint(int32 translate_x, int32 translate_y, TBTextProps *props);
-	void Click(int button, uint32 modifierkeys);
+    void BuildSelectionRegion(int32 translate_x, int32 translate_y, TBTextProps *props,
+                              TBRegion &bg_region, TBRegion &fg_region);
+    void Paint(int32 translate_x, int32 translate_y, TBTextProps *props);
+    void Click(int button, uint32 modifierkeys);
 
-	bool IsText() const					{ return !IsEmbedded(); }
-	bool IsEmbedded() const				{ return content ? true : false; }
-	bool IsBreak() const;
-	bool IsSpace() const;
-	bool IsTab() const;
+    bool IsText() const					{ return !IsEmbedded(); }
+    bool IsEmbedded() const				{ return content ? true : false; }
+    bool IsBreak() const;
+    bool IsSpace() const;
+    bool IsTab() const;
 
-	int32 GetCharX(TBFontFace *font, int32 ofs);
-	int32 GetCharOfs(TBFontFace *font, int32 x);
+    int32 GetCharX(TBFontFace *font, int32 ofs);
+    int32 GetCharOfs(TBFontFace *font, int32 x);
 
-	/** Get the stringwidth. Handles passwordmode, tab, linebreaks etc automatically. */
-	int32 GetStringWidth(TBFontFace *font, const char *str, int len);
+    /** Get the stringwidth. Handles passwordmode, tab, linebreaks etc automatically. */
+    int32 GetStringWidth(TBFontFace *font, const char *str, int len);
 
-	bool GetAllowBreakBefore() const;
-	bool GetAllowBreakAfter() const;
+    bool GetAllowBreakBefore() const;
+    bool GetAllowBreakAfter() const;
 
-	const char *Str() const			{ return block->str.CStr() + ofs; }
+    const char *Str() const			{ return block->str.CStr() + ofs; }
 
-	int32 GetWidth(TBFontFace *font);
-	int32 GetHeight(TBFontFace *font);
-	int32 GetBaseline(TBFontFace *font);
+    int32 GetWidth(TBFontFace *font);
+    int32 GetHeight(TBFontFace *font);
+    int32 GetBaseline(TBFontFace *font);
 
     int32 GetGlobalOfs() const;
 
 public:
-	int16 xpos, ypos;
-	uint16 ofs, len;
-	uint16 line_ypos;
-	uint16 line_height;
-	TBBlock *block;
+    int16 xpos, ypos;
+    uint16 ofs, len;
+    uint16 line_ypos;
+    uint16 line_height;
+    TBBlock *block;
     uint16 themeColor;
-	TBTextFragmentContent *content;
+    TBTextFragmentContent *content;
 };
 
 /** Edit and formats TBTextFragment's. It handles the text in a TBStyleEditView. */
@@ -348,132 +348,132 @@ public:
 class TBStyleEdit
 {
 public:
-	TBStyleEdit();
-	virtual ~TBStyleEdit();
-
-	void SetListener(TBStyleEditListener *listener);
-	void SetContentFactory(TBTextFragmentContentFactory *content_factory);
-
-	void SetFont(const TBFontDescription &font_desc);
-
-	void Paint(const TBRect &rect, const TBFontDescription &font_desc, const TBColor &text_color);
-	bool KeyDown(int key, SPECIAL_KEY special_key, MODIFIER_KEYS modifierkeys);
-	bool MouseDown(const TBPoint &point, int button, int clicks, MODIFIER_KEYS modifierkeys, bool touch);
-	bool MouseUp(const TBPoint &point, int button, MODIFIER_KEYS modifierkeys, bool touch);
-	bool MouseMove(const TBPoint &point);
-	void Focus(bool focus);
-
-	void Clear(bool init_new = true);
-	bool Load(const char *filename);
-	bool SetText(const char *text, TB_CARET_POS pos = TB_CARET_POS_BEGINNING);
-	bool SetText(const char *text, int text_len, TB_CARET_POS pos = TB_CARET_POS_BEGINNING);
-	bool GetText(TBStr &text);
-	bool IsEmpty() const;
-
-	/** Set the default text alignment and all currently selected blocks,
-		or the block of the current caret position if nothing is selected. */
-	void SetAlign(TB_TEXT_ALIGN align);
-	void SetMultiline(bool multiline = true);
-	void SetStyling(bool styling = true);
-	void SetReadOnly(bool readonly = true);
-	void SetSelection(bool selection = true);
-	void SetPassword(bool password = true);
-	void SetWrapping(bool wrapping = true);
-
-	/** Set if line breaks should be inserted in windows style (\r\n)
-		or unix style (\n). The default is windows style on the windows
-		platform and disabled elsewhere.
-
-		Note: This only affects InsertBreak (pressing enter). Content set from
-		      SetText (and clipboard etc.) maintains the used line break. */
-	void SetWindowsStyleBreak(bool win_style_br) { packed.win_style_br = win_style_br; }
-
-	void Cut();
-	void Copy();
-	void Paste();
-	void Delete();
-
-	void Undo();
-	void Redo();
-	bool CanUndo() const { return undoredo.undos.GetNumItems() ? true : false; }
-	bool CanRedo() const { return undoredo.redos.GetNumItems() ? true : false; }
-
-	void InsertText(const char *text, int32 len = TB_ALL_TO_TERMINATION, bool after_last = false, bool clear_undo_redo = false);
-	void AppendText(const char *text, int32 len = TB_ALL_TO_TERMINATION, bool clear_undo_redo = false) { InsertText(text, len, true, clear_undo_redo); }
-	void InsertBreak();
-
-	TBBlock *FindBlock(int32 y) const;
+    TBStyleEdit();
+    virtual ~TBStyleEdit();
+
+    void SetListener(TBStyleEditListener *listener);
+    void SetContentFactory(TBTextFragmentContentFactory *content_factory);
+
+    void SetFont(const TBFontDescription &font_desc);
+
+    void Paint(const TBRect &rect, const TBFontDescription &font_desc, const TBColor &text_color);
+    bool KeyDown(int key, SPECIAL_KEY special_key, MODIFIER_KEYS modifierkeys);
+    bool MouseDown(const TBPoint &point, int button, int clicks, MODIFIER_KEYS modifierkeys, bool touch);
+    bool MouseUp(const TBPoint &point, int button, MODIFIER_KEYS modifierkeys, bool touch);
+    bool MouseMove(const TBPoint &point);
+    void Focus(bool focus);
+
+    void Clear(bool init_new = true);
+    bool Load(const char *filename);
+    bool SetText(const char *text, TB_CARET_POS pos = TB_CARET_POS_BEGINNING);
+    bool SetText(const char *text, int text_len, TB_CARET_POS pos = TB_CARET_POS_BEGINNING);
+    bool GetText(TBStr &text);
+    bool IsEmpty() const;
+
+    /** Set the default text alignment and all currently selected blocks,
+        or the block of the current caret position if nothing is selected. */
+    void SetAlign(TB_TEXT_ALIGN align);
+    void SetMultiline(bool multiline = true);
+    void SetStyling(bool styling = true);
+    void SetReadOnly(bool readonly = true);
+    void SetSelection(bool selection = true);
+    void SetPassword(bool password = true);
+    void SetWrapping(bool wrapping = true);
+
+    /** Set if line breaks should be inserted in windows style (\r\n)
+        or unix style (\n). The default is windows style on the windows
+        platform and disabled elsewhere.
+
+        Note: This only affects InsertBreak (pressing enter). Content set from
+              SetText (and clipboard etc.) maintains the used line break. */
+    void SetWindowsStyleBreak(bool win_style_br) { packed.win_style_br = win_style_br; }
+
+    void Cut();
+    void Copy();
+    void Paste();
+    void Delete();
+
+    void Undo();
+    void Redo();
+    bool CanUndo() const { return undoredo.undos.GetNumItems() ? true : false; }
+    bool CanRedo() const { return undoredo.redos.GetNumItems() ? true : false; }
+
+    void InsertText(const char *text, int32 len = TB_ALL_TO_TERMINATION, bool after_last = false, bool clear_undo_redo = false);
+    void AppendText(const char *text, int32 len = TB_ALL_TO_TERMINATION, bool clear_undo_redo = false) { InsertText(text, len, true, clear_undo_redo); }
+    void InsertBreak();
+
+    TBBlock *FindBlock(int32 y) const;
     int32 GetCaretLine();
 
-	void ScrollIfNeeded(bool x = true, bool y = true);
-	void SetScrollPos(int32 x, int32 y);
-	void SetLayoutSize(int32 width, int32 height, bool is_virtual_reformat);
-	void Reformat(bool update_fragments);
+    void ScrollIfNeeded(bool x = true, bool y = true);
+    void SetScrollPos(int32 x, int32 y);
+    void SetLayoutSize(int32 width, int32 height, bool is_virtual_reformat);
+    void Reformat(bool update_fragments);
 
-	int32 GetContentWidth();
-	int32 GetContentHeight() const;
+    int32 GetContentWidth();
+    int32 GetContentHeight() const;
 
-	int32 GetOverflowX() const { return MAX(content_width - layout_width, 0); }
-	int32 GetOverflowY() const { return MAX(content_height - layout_height, 0); }
+    int32 GetOverflowX() const { return MAX(content_width - layout_width, 0); }
+    int32 GetOverflowY() const { return MAX(content_height - layout_height, 0); }
 
     void SetTextTheme(TBTextTheme* theme) { text_theme = theme; }
 
 public:
-	TBStyleEditListener *listener;
-	TBTextFragmentContentFactory default_content_factory;
-	TBTextFragmentContentFactory *content_factory;
+    TBStyleEditListener *listener;
+    TBTextFragmentContentFactory default_content_factory;
+    TBTextFragmentContentFactory *content_factory;
     TBStyleEditTextChangeListener* text_change_listener;
 
     // TBG
     TBTextTheme* text_theme;
     // END TBG
 
-	int32 layout_width;
-	int32 layout_height;
-	int32 content_width;
-	int32 content_height;
-
-	TBLinkListOf<TBBlock> blocks;
-
-	TBCaret caret;
-	TBSelection selection;
-	TBUndoRedoStack undoredo;
-
-	int32 scroll_x;
-	int32 scroll_y;
-
-	int8 select_state;
-	TBPoint mousedown_point;
-	TBTextFragment *mousedown_fragment;
-
-	/** DEPRECATED! This will be removed when using different fonts is properly supported! */
-	TBFontFace *font;
-	TBFontDescription font_desc;
-
-	TB_TEXT_ALIGN align;
-	union { struct {
-		uint32 multiline_on : 1;
-		uint32 styling_on : 1;
-		uint32 read_only : 1;
-		uint32 selection_on : 1;
-		uint32 show_whitespace : 1;
-		uint32 password_on : 1;
-		uint32 wrapping : 1;
-		uint32 win_style_br : 1;
-		uint32 calculate_content_width_needed : 1;	///< If content_width needs to be updated next GetContentWidth-
-		uint32 lock_scrollbars_counter : 5;			///< Incremental counter for if UpdateScrollbar should be probhited.
-	} packed;
-	uint32 packed_init;
-	};
-
-	/** Call BeginLockScrollbars & EndLockScrollbars around a scope which does lots of changes,
-		to prevent UpdateScrollbar from happening for each block (May cause recalculation of
-		content_width by iterating through all blocks) */
-	void BeginLockScrollbars();
-	void EndLockScrollbars();
-
-	/** Return true if changing layout_width and layout_height requires relayouting. */
-	bool GetSizeAffectsLayout() const;
+    int32 layout_width;
+    int32 layout_height;
+    int32 content_width;
+    int32 content_height;
+
+    TBLinkListOf<TBBlock> blocks;
+
+    TBCaret caret;
+    TBSelection selection;
+    TBUndoRedoStack undoredo;
+
+    int32 scroll_x;
+    int32 scroll_y;
+
+    int8 select_state;
+    TBPoint mousedown_point;
+    TBTextFragment *mousedown_fragment;
+
+    /** DEPRECATED! This will be removed when using different fonts is properly supported! */
+    TBFontFace *font;
+    TBFontDescription font_desc;
+
+    TB_TEXT_ALIGN align;
+    union { struct {
+            uint32 multiline_on : 1;
+            uint32 styling_on : 1;
+            uint32 read_only : 1;
+            uint32 selection_on : 1;
+            uint32 show_whitespace : 1;
+            uint32 password_on : 1;
+            uint32 wrapping : 1;
+            uint32 win_style_br : 1;
+            uint32 calculate_content_width_needed : 1;	///< If content_width needs to be updated next GetContentWidth-
+            uint32 lock_scrollbars_counter : 5;			///< Incremental counter for if UpdateScrollbar should be probhited.
+        } packed;
+            uint32 packed_init;
+          };
+
+    /** Call BeginLockScrollbars & EndLockScrollbars around a scope which does lots of changes,
+        to prevent UpdateScrollbar from happening for each block (May cause recalculation of
+        content_width by iterating through all blocks) */
+    void BeginLockScrollbars();
+    void EndLockScrollbars();
+
+    /** Return true if changing layout_width and layout_height requires relayouting. */
+    bool GetSizeAffectsLayout() const;
 };
 
 }; // namespace tb

+ 38 - 38
Source/ThirdParty/TurboBadger/tb_style_edit_content.cpp

@@ -13,55 +13,55 @@ namespace tb {
 
 int TBTextFragmentContentFactory::GetContent(const char *text)
 {
-	if (text[0] == '<')
-	{
-		int i = 0;
-		while (text[i] != '>' && text[i] > 31)
-			i++;
-		if (text[i] == '>')
-		{
-			i++;
-			return i;
-		}
-	}
-	return 0;
+    if (text[0] == '<')
+    {
+        int i = 0;
+        while (text[i] != '>' && text[i] > 31)
+            i++;
+        if (text[i] == '>')
+        {
+            i++;
+            return i;
+        }
+    }
+    return 0;
 }
 
 TBTextFragmentContent *TBTextFragmentContentFactory::CreateFragmentContent(const char *text, int text_len)
 {
-	if (strncmp(text, "<hr>", text_len) == 0)
-		return new TBTextFragmentContentHR(100, 2);
-	else if (strncmp(text, "<u>", text_len) == 0)
-		return new TBTextFragmentContentUnderline();
-	else if (strncmp(text, "<color ", MIN(text_len, 7)) == 0)
-	{
-		TBColor color;
-		color.SetFromString(text + 7, text_len - 8);
-		return new TBTextFragmentContentTextColor(color);
-	}
-	else if (strncmp(text, "</", MIN(text_len, 2)) == 0)
-		return new TBTextFragmentContentStylePop();
-	return nullptr;
+    if (strncmp(text, "<hr>", text_len) == 0)
+        return new TBTextFragmentContentHR(100, 2);
+    else if (strncmp(text, "<u>", text_len) == 0)
+        return new TBTextFragmentContentUnderline();
+    else if (strncmp(text, "<color ", MIN(text_len, 7)) == 0)
+    {
+        TBColor color;
+        color.SetFromString(text + 7, text_len - 8);
+        return new TBTextFragmentContentTextColor(color);
+    }
+    else if (strncmp(text, "</", MIN(text_len, 2)) == 0)
+        return new TBTextFragmentContentStylePop();
+    return nullptr;
 }
 
 // == PHorizontalLineContent ================================================================================
 
 TBTextFragmentContentHR::TBTextFragmentContentHR(int32 width_in_percent, int32 height)
-	: width_in_percent(width_in_percent)
-	, height(height)
+    : width_in_percent(width_in_percent)
+    , height(height)
 {
 }
 
 void TBTextFragmentContentHR::Paint(TBTextFragment *fragment, int32 translate_x, int32 translate_y, TBTextProps *props)
 {
-	int x = translate_x + fragment->xpos;
-	int y = translate_y + fragment->ypos;
+    int x = translate_x + fragment->xpos;
+    int y = translate_y + fragment->ypos;
 
-	int w = fragment->block->styledit->layout_width * width_in_percent / 100;
-	x += (fragment->block->styledit->layout_width - w) / 2;
+    int w = fragment->block->styledit->layout_width * width_in_percent / 100;
+    x += (fragment->block->styledit->layout_width - w) / 2;
 
-	TBStyleEditListener *listener = fragment->block->styledit->listener;
-	listener->DrawRectFill(TBRect(x, y, w, height), props->data->text_color);
+    TBStyleEditListener *listener = fragment->block->styledit->listener;
+    listener->DrawRectFill(TBRect(x, y, w, height), props->data->text_color);
 }
 
 int32 TBTextFragmentContentHR::GetWidth(TBFontFace *font, TBTextFragment *fragment) { return MAX(fragment->block->styledit->layout_width, 0); }
@@ -72,19 +72,19 @@ int32 TBTextFragmentContentHR::GetHeight(TBFontFace *font, TBTextFragment *fragm
 
 void TBTextFragmentContentUnderline::Paint(TBTextFragment *fragment, int32 translate_x, int32 translate_y, TBTextProps *props)
 {
-	if (TBTextProps::Data *data = props->Push())
-		data->underline = true;
+    if (TBTextProps::Data *data = props->Push())
+        data->underline = true;
 }
 
 void TBTextFragmentContentTextColor::Paint(TBTextFragment *fragment, int32 translate_x, int32 translate_y, TBTextProps *props)
 {
-	if (TBTextProps::Data *data = props->Push())
-		data->text_color = color;
+    if (TBTextProps::Data *data = props->Push())
+        data->text_color = color;
 }
 
 void TBTextFragmentContentStylePop::Paint(TBTextFragment *fragment, int32 translate_x, int32 translate_y, TBTextProps *props)
 {
-	props->Pop();
+    props->Pop();
 }
 
 }; // namespace tb

+ 29 - 29
Source/ThirdParty/TurboBadger/tb_style_edit_content.h

@@ -17,21 +17,21 @@ class TBTextFragment;
 class TBTextFragmentContent
 {
 public:
-	virtual ~TBTextFragmentContent() {}
+    virtual ~TBTextFragmentContent() {}
 
-	/** Update the position of the content, relative to the first line of text (no scrolling applied). */
-	virtual void UpdatePos(int x, int y) {}
+    /** Update the position of the content, relative to the first line of text (no scrolling applied). */
+    virtual void UpdatePos(int x, int y) {}
 
-	virtual void Paint(TBTextFragment *fragment, int32 translate_x, int32 translate_y, TBTextProps *props) {}
-	virtual void Click(TBTextFragment *fragment, int button, uint32 modifierkeys) {}
-	virtual int32 GetWidth(TBFontFace *font, TBTextFragment *fragment) { return 0; }
-	virtual int32 GetHeight(TBFontFace *font, TBTextFragment *fragment) { return 0; }
-	virtual int32 GetBaseline(TBFontFace *font, TBTextFragment *fragment) { return GetHeight(font, fragment); }
-	virtual bool GetAllowBreakBefore() { return true; }
-	virtual bool GetAllowBreakAfter() { return true; }
+    virtual void Paint(TBTextFragment *fragment, int32 translate_x, int32 translate_y, TBTextProps *props) {}
+    virtual void Click(TBTextFragment *fragment, int button, uint32 modifierkeys) {}
+    virtual int32 GetWidth(TBFontFace *font, TBTextFragment *fragment) { return 0; }
+    virtual int32 GetHeight(TBFontFace *font, TBTextFragment *fragment) { return 0; }
+    virtual int32 GetBaseline(TBFontFace *font, TBTextFragment *fragment) { return GetHeight(font, fragment); }
+    virtual bool GetAllowBreakBefore() { return true; }
+    virtual bool GetAllowBreakAfter() { return true; }
 
-	/** Get type of fragment content. All standard fragments return 0. */
-	virtual uint32 GetType()		{ return 0; }
+    /** Get type of fragment content. All standard fragments return 0. */
+    virtual uint32 GetType()		{ return 0; }
 };
 
 /** A horizontal line for TBStyleEdit. */
@@ -39,13 +39,13 @@ public:
 class TBTextFragmentContentHR : public TBTextFragmentContent
 {
 public:
-	TBTextFragmentContentHR(int32 width_in_percent, int32 height);
+    TBTextFragmentContentHR(int32 width_in_percent, int32 height);
 
-	virtual void Paint(TBTextFragment *fragment, int32 translate_x, int32 translate_y, TBTextProps *props);
-	virtual int32 GetWidth(TBFontFace *font, TBTextFragment *fragment);
-	virtual int32 GetHeight(TBFontFace *font, TBTextFragment *fragment);
+    virtual void Paint(TBTextFragment *fragment, int32 translate_x, int32 translate_y, TBTextProps *props);
+    virtual int32 GetWidth(TBFontFace *font, TBTextFragment *fragment);
+    virtual int32 GetHeight(TBFontFace *font, TBTextFragment *fragment);
 private:
-	int32 width_in_percent, height;
+    int32 width_in_percent, height;
 };
 
 /** Fragment content that enables underline in a TBStyleEdit */
@@ -53,10 +53,10 @@ private:
 class TBTextFragmentContentUnderline : public TBTextFragmentContent
 {
 public:
-	TBTextFragmentContentUnderline() {}
-	virtual void Paint(TBTextFragment *fragment, int32 translate_x, int32 translate_y, TBTextProps *props);
-	virtual bool GetAllowBreakBefore() { return true; }
-	virtual bool GetAllowBreakAfter() { return false; }
+    TBTextFragmentContentUnderline() {}
+    virtual void Paint(TBTextFragment *fragment, int32 translate_x, int32 translate_y, TBTextProps *props);
+    virtual bool GetAllowBreakBefore() { return true; }
+    virtual bool GetAllowBreakAfter() { return false; }
 };
 
 /** Fragment content that changes color in a TBStyleEdit */
@@ -64,11 +64,11 @@ public:
 class TBTextFragmentContentTextColor : public TBTextFragmentContent
 {
 public:
-	TBColor color;
-	TBTextFragmentContentTextColor(const TBColor &color) : color(color) {}
-	virtual void Paint(TBTextFragment *fragment, int32 translate_x, int32 translate_y, TBTextProps *props);
-	virtual bool GetAllowBreakBefore() { return true; }
-	virtual bool GetAllowBreakAfter() { return false; }
+    TBColor color;
+    TBTextFragmentContentTextColor(const TBColor &color) : color(color) {}
+    virtual void Paint(TBTextFragment *fragment, int32 translate_x, int32 translate_y, TBTextProps *props);
+    virtual bool GetAllowBreakBefore() { return true; }
+    virtual bool GetAllowBreakAfter() { return false; }
 };
 
 /** Fragment content that ends a change of style in a TBStyleEdit */
@@ -76,9 +76,9 @@ public:
 class TBTextFragmentContentStylePop : public TBTextFragmentContent
 {
 public:
-	virtual void Paint(TBTextFragment *fragment, int32 translate_x, int32 translate_y, TBTextProps *props);
-	virtual bool GetAllowBreakBefore() { return false; }
-	virtual bool GetAllowBreakAfter() { return true; }
+    virtual void Paint(TBTextFragment *fragment, int32 translate_x, int32 translate_y, TBTextProps *props);
+    virtual bool GetAllowBreakBefore() { return false; }
+    virtual bool GetAllowBreakAfter() { return true; }
 };
 
 }; // namespace tb

+ 31 - 31
Source/ThirdParty/TurboBadger/tb_system.h

@@ -25,46 +25,46 @@ namespace tb {
 class TBSystem
 {
 public:
-	/** Get the system time in milliseconds since some undefined epoch. */
-	static double GetTimeMS();
+    /** Get the system time in milliseconds since some undefined epoch. */
+    static double GetTimeMS();
 
-	/** Called when the need to call TBMessageHandler::ProcessMessages has changed due to changes in the
-		message queue. fire_time is the new time is needs to be called.
-		It may be 0 which means that ProcessMessages should be called asap (but NOT from this call!)
-		It may also be TB_NOT_SOON which means that ProcessMessages doesn't need to be called. */
-	static void RescheduleTimer(double fire_time);
+    /** Called when the need to call TBMessageHandler::ProcessMessages has changed due to changes in the
+        message queue. fire_time is the new time is needs to be called.
+        It may be 0 which means that ProcessMessages should be called asap (but NOT from this call!)
+        It may also be TB_NOT_SOON which means that ProcessMessages doesn't need to be called. */
+    static void RescheduleTimer(double fire_time);
 
-	/** Get how many milliseconds it should take after a touch down event should generate a long click
-		event. */
-	static int GetLongClickDelayMS();
+    /** Get how many milliseconds it should take after a touch down event should generate a long click
+        event. */
+    static int GetLongClickDelayMS();
 
-	/** Get how many pixels of dragging should start panning scrollable widgets. */
-	static int GetPanThreshold();
+    /** Get how many pixels of dragging should start panning scrollable widgets. */
+    static int GetPanThreshold();
 
-	/** Get how many pixels a typical line is: The length that should be scrolled when turning a mouse
-		wheel one notch. */
-	static int GetPixelsPerLine();
+    /** Get how many pixels a typical line is: The length that should be scrolled when turning a mouse
+        wheel one notch. */
+    static int GetPixelsPerLine();
 
-	/** Get Dots Per Inch for the main screen. */
-	static int GetDPI();
+    /** Get Dots Per Inch for the main screen. */
+    static int GetDPI();
 };
 
 /** TBClipboard is a porting interface for the clipboard. */
 class TBClipboard
 {
 public:
-	/** Empty the contents of the clipboard. */
-	static void Empty();
+    /** Empty the contents of the clipboard. */
+    static void Empty();
 
-	/** Return true if the clipboard currently contains text. */
-	static bool HasText();
+    /** Return true if the clipboard currently contains text. */
+    static bool HasText();
 
-	/** Set the text of the clipboard in UTF-8 format. */
-	static bool SetText(const char *text);
+    /** Set the text of the clipboard in UTF-8 format. */
+    static bool SetText(const char *text);
 
-	/** Get the text from the clipboard in UTF-8 format.
-		Returns true on success. */
-	static bool GetText(TBStr &text);
+    /** Get the text from the clipboard in UTF-8 format.
+        Returns true on success. */
+    static bool GetText(TBStr &text);
 };
 
 typedef void (*TBFileExternalReaderFunction)(const char* filename, void** data, unsigned* length);
@@ -76,14 +76,14 @@ class TBFile
     static TBFileExternalReaderFunction reader_function;
 
 public:
-	enum TBFileMode { MODE_READ };
+    enum TBFileMode { MODE_READ };
 
-	static TBFile *Open(const char *filename, TBFileMode mode);
+    static TBFile *Open(const char *filename, TBFileMode mode);
     static void SetReaderFunction(TBFileExternalReaderFunction function) {  reader_function = function; }
 
-	virtual ~TBFile() {}
-	virtual long Size() = 0;
-	virtual size_t Read(void *buf, size_t elemSize, size_t count) = 0;
+    virtual ~TBFile() {}
+    virtual long Size() = 0;
+    virtual size_t Read(void *buf, size_t elemSize, size_t count) = 0;
 };
 
 }; // namespace tb

+ 42 - 42
Source/ThirdParty/TurboBadger/tb_system_android.cpp

@@ -25,7 +25,7 @@
 
 void TBDebugOut(const char *str)
 {
-	LOGI(str);
+    LOGI(str);
 }
 
 #endif // TB_RUNTIME_DEBUG_INFO
@@ -34,7 +34,7 @@ AAssetManager *g_pManager = NULL;
 
 void SetAssetManager(AAssetManager *pManager)
 {
-	g_pManager = pManager;
+    g_pManager = pManager;
 }
 
 namespace tb {
@@ -43,9 +43,9 @@ namespace tb {
 
 double TBSystem::GetTimeMS()
 {
-	struct timeval now;
-	gettimeofday(&now, NULL);
-	return now.tv_usec / 1000 + now.tv_sec * 1000;
+    struct timeval now;
+    gettimeofday(&now, NULL);
+    return now.tv_usec / 1000 + now.tv_sec * 1000;
 }
 
 void TBSystem::RescheduleTimer(double fire_time)
@@ -54,28 +54,28 @@ void TBSystem::RescheduleTimer(double fire_time)
 
 int TBSystem::GetLongClickDelayMS()
 {
-	return 500;
+    return 500;
 }
 
 int TBSystem::GetPanThreshold()
 {
-	return 5 * GetDPI() / 120;
+    return 5 * GetDPI() / 120;
 }
 
 int TBSystem::GetPixelsPerLine()
 {
-	return 40 * GetDPI() / 120;
+    return 40 * GetDPI() / 120;
 }
 
 int TBSystem::GetDPI()
 {
-	AConfiguration *config = AConfiguration_new();
-	AConfiguration_fromAssetManager(config, g_pManager);
-	int32_t density = AConfiguration_getDensity(config);
-	AConfiguration_delete(config);
-	if (density == 0 || density == ACONFIGURATION_DENSITY_NONE)
-		return 120;
-	return density;
+    AConfiguration *config = AConfiguration_new();
+    AConfiguration_fromAssetManager(config, g_pManager);
+    int32_t density = AConfiguration_getDensity(config);
+    AConfiguration_delete(config);
+    if (density == 0 || density == ACONFIGURATION_DENSITY_NONE)
+        return 120;
+    return density;
 }
 
 // == TBFile =====================================
@@ -83,38 +83,38 @@ int TBSystem::GetDPI()
 class TBAndroidFile : public TBFile
 {
 public:
-	TBAndroidFile(AAsset* f) : file(f) {}
-	virtual ~TBAndroidFile() { AAsset_close(file); }
-
-	virtual long Size()
-	{
-		return AAsset_getLength(file);
-	}
-	virtual size_t Read(void *buf, size_t elemSize, size_t count)
-	{
-		return AAsset_read(file, buf, elemSize * count);
-	}
+    TBAndroidFile(AAsset* f) : file(f) {}
+    virtual ~TBAndroidFile() { AAsset_close(file); }
+
+    virtual long Size()
+    {
+        return AAsset_getLength(file);
+    }
+    virtual size_t Read(void *buf, size_t elemSize, size_t count)
+    {
+        return AAsset_read(file, buf, elemSize * count);
+    }
 private:
-	AAsset *file;
+    AAsset *file;
 };
 
 TBFile *TBFile::Open(const char *filename, TBFileMode mode)
 {
-	AAsset *f = nullptr;
-	switch (mode)
-	{
-	case MODE_READ:
-		f = AAssetManager_open(g_pManager, filename, AASSET_MODE_UNKNOWN);
-		break;
-	default:
-		break;
-	}
-	if (!f)
-		return nullptr;
-	TBAndroidFile *tbf = new TBAndroidFile(f);
-	if (!tbf)
-		AAsset_close(f);
-	return tbf;
+    AAsset *f = nullptr;
+    switch (mode)
+    {
+    case MODE_READ:
+        f = AAssetManager_open(g_pManager, filename, AASSET_MODE_UNKNOWN);
+        break;
+    default:
+        break;
+    }
+    if (!f)
+        return nullptr;
+    TBAndroidFile *tbf = new TBAndroidFile(f);
+    if (!tbf)
+        AAsset_close(f);
+    return tbf;
 }
 
 }; // namespace tb

+ 9 - 9
Source/ThirdParty/TurboBadger/tb_system_linux.cpp

@@ -14,7 +14,7 @@
 
 void TBDebugOut(const char *str)
 {
-	printf("%s", str);
+    printf("%s", str);
 }
 
 #endif // TB_RUNTIME_DEBUG_INFO
@@ -25,9 +25,9 @@ namespace tb {
 
 double TBSystem::GetTimeMS()
 {
-	struct timeval now;
-	gettimeofday( &now, NULL );
-	return now.tv_usec/1000 + now.tv_sec*1000;
+    struct timeval now;
+    gettimeofday( &now, NULL );
+    return now.tv_usec/1000 + now.tv_sec*1000;
 }
 
 // Implementation currently done in port_glut.cpp.
@@ -38,23 +38,23 @@ double TBSystem::GetTimeMS()
 
 int TBSystem::GetLongClickDelayMS()
 {
-	return 500;
+    return 500;
 }
 
 int TBSystem::GetPanThreshold()
 {
-	return 5 * GetDPI() / 96;
+    return 5 * GetDPI() / 96;
 }
 
 int TBSystem::GetPixelsPerLine()
 {
-	return 40 * GetDPI() / 96;
+    return 40 * GetDPI() / 96;
 }
 
 int TBSystem::GetDPI()
 {
-	// FIX: Implement!
-	return 96;
+    // FIX: Implement!
+    return 96;
 }
 
 }; // namespace tb

+ 13 - 13
Source/ThirdParty/TurboBadger/tb_system_win.cpp

@@ -15,7 +15,7 @@
 
 void TBDebugOut(const char *str)
 {
-	OutputDebugString(str);
+    OutputDebugString(str);
 }
 
 #endif // TB_RUNTIME_DEBUG_INFO
@@ -26,7 +26,7 @@ namespace tb {
 
 double TBSystem::GetTimeMS()
 {
-	return timeGetTime();
+    return timeGetTime();
 }
 
 // Implementation currently done in port_glut.cpp.
@@ -37,31 +37,31 @@ double TBSystem::GetTimeMS()
 
 int TBSystem::GetLongClickDelayMS()
 {
-	return 500;
+    return 500;
 }
 
 int TBSystem::GetPanThreshold()
 {
-	return 5 * GetDPI() / 96;
+    return 5 * GetDPI() / 96;
 }
 
 int TBSystem::GetPixelsPerLine()
 {
-	return 40 * GetDPI() / 96;
+    return 40 * GetDPI() / 96;
 }
 
 int TBSystem::GetDPI()
 {
-	return 96;
-	/*
-	HDC hdc = GetDC(nullptr);
-	int DPI_x = GetDeviceCaps(hdc, LOGPIXELSX);
-	ReleaseDC(nullptr, hdc);
+    return 96;
+    /*
+    HDC hdc = GetDC(nullptr);
+    int DPI_x = GetDeviceCaps(hdc, LOGPIXELSX);
+    ReleaseDC(nullptr, hdc);
 #if 0 // TEST CODE!
-	DPI_x *= 2;
+    DPI_x *= 2;
 #endif
-	return DPI_x;
-	*/
+    return DPI_x;
+    */
 }
 
 }; // namespace tb

+ 80 - 80
Source/ThirdParty/TurboBadger/tb_tab_container.cpp

@@ -12,84 +12,84 @@ namespace tb {
 
 void TBTabLayout::OnChildAdded(TBWidget *child)
 {
-	if (TBButton *button = TBSafeCast<TBButton>(child))
-	{
-		button->SetSqueezable(true);
-		button->SetSkinBg(TBIDC("TBTabContainer.tab"));
-		button->SetID(TBIDC("tab"));
-	}
+    if (TBButton *button = TBSafeCast<TBButton>(child))
+    {
+        button->SetSqueezable(true);
+        button->SetSkinBg(TBIDC("TBTabContainer.tab"));
+        button->SetID(TBIDC("tab"));
+    }
 }
 
 PreferredSize TBTabLayout::OnCalculatePreferredContentSize(const SizeConstraints &constraints)
 {
-	PreferredSize ps = TBLayout::OnCalculatePreferredContentSize(constraints);
-	// Make sure the number of tabs doesn't grow parents.
-	// It is only the content that should do that. The tabs
-	// will scroll anyway.
-	if (GetAxis() == AXIS_X)
-		ps.min_w = MIN(ps.min_w, 1);
-	else
-		ps.min_h = MIN(ps.min_h, 1);
-	return ps;
+    PreferredSize ps = TBLayout::OnCalculatePreferredContentSize(constraints);
+    // Make sure the number of tabs doesn't grow parents.
+    // It is only the content that should do that. The tabs
+    // will scroll anyway.
+    if (GetAxis() == AXIS_X)
+        ps.min_w = MIN(ps.min_w, 1);
+    else
+        ps.min_h = MIN(ps.min_h, 1);
+    return ps;
 }
 
 // == TBTabContainer ====================================================================
 
 TBTabContainer::TBTabContainer()
-	: m_need_page_update(true)
+    : m_need_page_update(true)
     , m_current_page(-1)
-	, m_align(TB_ALIGN_TOP)
+    , m_align(TB_ALIGN_TOP)
 {
-	AddChild(&m_root_layout);
-	// Put the tab layout on top of the content in Z order so their skin can make
-	// a seamless overlap over the border. Control which side they are layouted
-	// to by calling SetLayoutOrder.
-	m_root_layout.AddChild(&m_content_root);
-	m_root_layout.AddChild(&m_tab_layout);
-	m_root_layout.SetAxis(AXIS_Y);
-	m_root_layout.SetGravity(WIDGET_GRAVITY_ALL);
-	m_root_layout.SetLayoutDistribution(LAYOUT_DISTRIBUTION_AVAILABLE);
-	m_root_layout.SetLayoutOrder(LAYOUT_ORDER_TOP_TO_BOTTOM);
-	m_root_layout.SetSkinBg(TBIDC("TBTabContainer.rootlayout"));
-	m_tab_layout.SetLayoutDistributionPosition(LAYOUT_DISTRIBUTION_POSITION_CENTER);
-	m_tab_layout.SetSkinBg(TBIDC("TBTabContainer.tablayout_x"));
-	m_tab_layout.SetLayoutPosition(LAYOUT_POSITION_RIGHT_BOTTOM);
-	m_content_root.SetGravity(WIDGET_GRAVITY_ALL);
-	m_content_root.SetSkinBg(TBIDC("TBTabContainer.container"));
+    AddChild(&m_root_layout);
+    // Put the tab layout on top of the content in Z order so their skin can make
+    // a seamless overlap over the border. Control which side they are layouted
+    // to by calling SetLayoutOrder.
+    m_root_layout.AddChild(&m_content_root);
+    m_root_layout.AddChild(&m_tab_layout);
+    m_root_layout.SetAxis(AXIS_Y);
+    m_root_layout.SetGravity(WIDGET_GRAVITY_ALL);
+    m_root_layout.SetLayoutDistribution(LAYOUT_DISTRIBUTION_AVAILABLE);
+    m_root_layout.SetLayoutOrder(LAYOUT_ORDER_TOP_TO_BOTTOM);
+    m_root_layout.SetSkinBg(TBIDC("TBTabContainer.rootlayout"));
+    m_tab_layout.SetLayoutDistributionPosition(LAYOUT_DISTRIBUTION_POSITION_CENTER);
+    m_tab_layout.SetSkinBg(TBIDC("TBTabContainer.tablayout_x"));
+    m_tab_layout.SetLayoutPosition(LAYOUT_POSITION_RIGHT_BOTTOM);
+    m_content_root.SetGravity(WIDGET_GRAVITY_ALL);
+    m_content_root.SetSkinBg(TBIDC("TBTabContainer.container"));
 }
 
 TBTabContainer::~TBTabContainer()
 {
-	m_root_layout.RemoveChild(&m_content_root);
-	m_root_layout.RemoveChild(&m_tab_layout);
-	RemoveChild(&m_root_layout);
+    m_root_layout.RemoveChild(&m_content_root);
+    m_root_layout.RemoveChild(&m_tab_layout);
+    RemoveChild(&m_root_layout);
 }
 
 void TBTabContainer::SetAxis(AXIS axis)
 {
-	m_root_layout.SetAxis(axis);
-	m_tab_layout.SetAxis(axis == AXIS_X ? AXIS_Y : AXIS_X);
-	m_tab_layout.SetSkinBg(axis == AXIS_X ? TBIDC("TBTabContainer.tablayout_y") :
-											TBIDC("TBTabContainer.tablayout_x"));
+    m_root_layout.SetAxis(axis);
+    m_tab_layout.SetAxis(axis == AXIS_X ? AXIS_Y : AXIS_X);
+    m_tab_layout.SetSkinBg(axis == AXIS_X ? TBIDC("TBTabContainer.tablayout_y") :
+                                            TBIDC("TBTabContainer.tablayout_x"));
 }
 
 void TBTabContainer::SetValue(int index)
 {
     if (index == m_current_page || !GetNumPages())
-		return;
+        return;
 
-	m_current_page = index;
+    m_current_page = index;
 
-	// Update the pages visibility and tabs pressed value.
-	index = 0;
-	TBWidget *page = m_content_root.GetFirstChild();
-	TBWidget *tab = m_tab_layout.GetFirstChild();
-	for (   ; page && tab; page = page->GetNext(), tab = tab->GetNext(), index++)
-	{
-		bool active = index == m_current_page;
-		page->SetVisibilility(active ? WIDGET_VISIBILITY_VISIBLE : WIDGET_VISIBILITY_INVISIBLE);
-		tab->SetValue(active ? 1 : 0);
-	}
+    // Update the pages visibility and tabs pressed value.
+    index = 0;
+    TBWidget *page = m_content_root.GetFirstChild();
+    TBWidget *tab = m_tab_layout.GetFirstChild();
+    for (   ; page && tab; page = page->GetNext(), tab = tab->GetNext(), index++)
+    {
+        bool active = index == m_current_page;
+        page->SetVisibilility(active ? WIDGET_VISIBILITY_VISIBLE : WIDGET_VISIBILITY_INVISIBLE);
+        tab->SetValue(active ? 1 : 0);
+    }
 
     TBWidgetEvent ev(EVENT_TYPE_TAB_CHANGED);
     InvokeEvent(ev);
@@ -97,14 +97,14 @@ void TBTabContainer::SetValue(int index)
 
 int TBTabContainer::GetNumPages()
 {
-	int count = 0;
-	for (TBWidget *tab = m_tab_layout.GetFirstChild(); tab; tab = tab->GetNext())
-		count++;
+    int count = 0;
+    for (TBWidget *tab = m_tab_layout.GetFirstChild(); tab; tab = tab->GetNext())
+        count++;
 
     if (!count)
         m_current_page = -1;
 
-	return count;
+    return count;
 }
 
 TBWidget *TBTabContainer::GetCurrentPageWidget() const
@@ -112,42 +112,42 @@ TBWidget *TBTabContainer::GetCurrentPageWidget() const
     if (m_current_page == -1)
         return nullptr;
 
-	return m_content_root.GetChildFromIndex(m_current_page);
+    return m_content_root.GetChildFromIndex(m_current_page);
 }
 
 void TBTabContainer::SetAlignment(TB_ALIGN align)
 {
-	bool horizontal = (align == TB_ALIGN_TOP || align == TB_ALIGN_BOTTOM);
-	bool reverse = (align == TB_ALIGN_TOP || align == TB_ALIGN_LEFT);
-	SetAxis(horizontal ? AXIS_Y : AXIS_X);
-	m_root_layout.SetLayoutOrder(reverse ? LAYOUT_ORDER_TOP_TO_BOTTOM : LAYOUT_ORDER_BOTTOM_TO_TOP);
-	m_tab_layout.SetLayoutPosition(reverse ? LAYOUT_POSITION_RIGHT_BOTTOM : LAYOUT_POSITION_LEFT_TOP);
-	m_align = align;
+    bool horizontal = (align == TB_ALIGN_TOP || align == TB_ALIGN_BOTTOM);
+    bool reverse = (align == TB_ALIGN_TOP || align == TB_ALIGN_LEFT);
+    SetAxis(horizontal ? AXIS_Y : AXIS_X);
+    m_root_layout.SetLayoutOrder(reverse ? LAYOUT_ORDER_TOP_TO_BOTTOM : LAYOUT_ORDER_BOTTOM_TO_TOP);
+    m_tab_layout.SetLayoutPosition(reverse ? LAYOUT_POSITION_RIGHT_BOTTOM : LAYOUT_POSITION_LEFT_TOP);
+    m_align = align;
 }
 
 bool TBTabContainer::OnEvent(const TBWidgetEvent &ev)
 {
-	if ((ev.type == EVENT_TYPE_CLICK || ev.type == EVENT_TYPE_POINTER_DOWN) &&
-		ev.target->GetID() == TBIDC("tab") &&
-		ev.target->GetParent() == &m_tab_layout)
-	{
-		int clicked_index = m_tab_layout.GetIndexFromChild(ev.target);
-		SetValue(clicked_index);
-		return true;
-	}
-	return false;
+    if ((ev.type == EVENT_TYPE_CLICK || ev.type == EVENT_TYPE_POINTER_DOWN) &&
+            ev.target->GetID() == TBIDC("tab") &&
+            ev.target->GetParent() == &m_tab_layout)
+    {
+        int clicked_index = m_tab_layout.GetIndexFromChild(ev.target);
+        SetValue(clicked_index);
+        return true;
+    }
+    return false;
 }
 
 void TBTabContainer::OnProcess()
 {
-	if (m_need_page_update)
-	{
-		m_need_page_update = false;
-		// Force update value
-		int current_page = m_current_page;
-		m_current_page = -1;
-		SetValue(current_page);
-	}
+    if (m_need_page_update)
+    {
+        m_need_page_update = false;
+        // Force update value
+        int current_page = m_current_page;
+        m_current_page = -1;
+        SetValue(current_page);
+    }
 }
 
 }; // namespace tb

+ 37 - 37
Source/ThirdParty/TurboBadger/tb_tab_container.h

@@ -11,15 +11,15 @@
 namespace tb {
 
 /** TBTabLayout is a TBLayout used in TBTabContainer to apply
-	some default properties on any TBButton added to it. */
+    some default properties on any TBButton added to it. */
 class TBTabLayout : public TBLayout
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBTabLayout, TBLayout);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBTabLayout, TBLayout);
 
-	virtual void OnChildAdded(TBWidget *child);
-	virtual PreferredSize OnCalculatePreferredContentSize(const SizeConstraints &constraints);
+    virtual void OnChildAdded(TBWidget *child);
+    virtual PreferredSize OnCalculatePreferredContentSize(const SizeConstraints &constraints);
 };
 
 /** TBTabContainer - A container with tabs for multiple pages. */
@@ -27,47 +27,47 @@ public:
 class TBTabContainer : public TBWidget
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBTabContainer, TBWidget);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBTabContainer, TBWidget);
 
-	TBTabContainer();
-	~TBTabContainer();
+    TBTabContainer();
+    ~TBTabContainer();
 
-	/** Set along which axis the content should layouted.
-		Use SetAlignment instead for more choice! Also, calling
-		SetAxis directly does not update the current alignment. */
-	virtual void SetAxis(AXIS axis);
-	virtual AXIS GetAxis() const { return m_root_layout.GetAxis(); }
+    /** Set along which axis the content should layouted.
+        Use SetAlignment instead for more choice! Also, calling
+        SetAxis directly does not update the current alignment. */
+    virtual void SetAxis(AXIS axis);
+    virtual AXIS GetAxis() const { return m_root_layout.GetAxis(); }
 
-	/** Set alignment of the tabs. */
-	void SetAlignment(TB_ALIGN align);
-	TB_ALIGN GetAlignment() const { return m_align; }
+    /** Set alignment of the tabs. */
+    void SetAlignment(TB_ALIGN align);
+    TB_ALIGN GetAlignment() const { return m_align; }
 
-	/** Set which page should be selected and visible. */
-	virtual void SetValue(int value);
-	virtual int GetValue() { return m_current_page; }
+    /** Set which page should be selected and visible. */
+    virtual void SetValue(int value);
+    virtual int GetValue() { return m_current_page; }
 
-	/** Set which page should be selected and visible. */
-	void SetCurrentPage(int index) { SetValue(index); }
-	int GetCurrentPage() { return GetValue(); }
-	int GetNumPages();
+    /** Set which page should be selected and visible. */
+    void SetCurrentPage(int index) { SetValue(index); }
+    int GetCurrentPage() { return GetValue(); }
+    int GetNumPages();
 
-	/** Return the widget that is the current page, or nullptr if none is active. */
-	TBWidget *GetCurrentPageWidget() const;
+    /** Return the widget that is the current page, or nullptr if none is active. */
+    TBWidget *GetCurrentPageWidget() const;
 
-	virtual void OnInflate(const INFLATE_INFO &info);
-	virtual bool OnEvent(const TBWidgetEvent &ev);
-	virtual void OnProcess();
+    virtual void OnInflate(const INFLATE_INFO &info);
+    virtual bool OnEvent(const TBWidgetEvent &ev);
+    virtual void OnProcess();
 
-	virtual TBWidget *GetContentRoot() { return &m_content_root; }
-	TBLayout *GetTabLayout() { return &m_tab_layout; }
+    virtual TBWidget *GetContentRoot() { return &m_content_root; }
+    TBLayout *GetTabLayout() { return &m_tab_layout; }
 protected:
-	TBLayout m_root_layout;
-	TBTabLayout m_tab_layout;
-	TBWidget m_content_root;
-	bool m_need_page_update;
-	int m_current_page;
-	TB_ALIGN m_align;
+    TBLayout m_root_layout;
+    TBTabLayout m_tab_layout;
+    TBWidget m_content_root;
+    bool m_need_page_update;
+    int m_current_page;
+    TB_ALIGN m_align;
 };
 
 };

+ 56 - 56
Source/ThirdParty/TurboBadger/tb_tempbuffer.cpp

@@ -15,97 +15,97 @@ static char *p_realloc(char *buf, size_t size) { return (char *) realloc(buf, si
 static void p_free(char *buf) { free(buf); }
 
 TBTempBuffer::TBTempBuffer()
-	: m_data(0)
-	, m_data_size(0)
-	, m_append_pos(0)
+    : m_data(0)
+    , m_data_size(0)
+    , m_append_pos(0)
 {
 }
 
 TBTempBuffer::~TBTempBuffer()
 {
-	p_free(m_data);
+    p_free(m_data);
 }
 
 void TBTempBuffer::SetAppendPos(int append_pos)
 {
-	assert(append_pos >= 0 && append_pos <= m_data_size);
-	m_append_pos = append_pos;
+    assert(append_pos >= 0 && append_pos <= m_data_size);
+    m_append_pos = append_pos;
 }
 
 bool TBTempBuffer::Reserve(int size)
 {
-	if (size > m_data_size)
-	{
-		char *new_data = p_realloc(m_data, size);
-		if (!new_data)
-			return false;
-		m_data = new_data;
-		m_data_size = size;
-	}
-	return true;
+    if (size > m_data_size)
+    {
+        char *new_data = p_realloc(m_data, size);
+        if (!new_data)
+            return false;
+        m_data = new_data;
+        m_data_size = size;
+    }
+    return true;
 }
 
 int TBTempBuffer::GetAppendReserveSize(int needed_size) const
 {
-	// Reserve some extra memory to reduce the reserve calls.
-	needed_size *= 2;
-	return needed_size < 32 ? 32 : needed_size;
+    // Reserve some extra memory to reduce the reserve calls.
+    needed_size *= 2;
+    return needed_size < 32 ? 32 : needed_size;
 }
 
 bool TBTempBuffer::Append(const char *data, int size)
 {
-	if (m_append_pos + size > m_data_size && !Reserve(GetAppendReserveSize(m_append_pos + size)))
-		return false;
-	memcpy(m_data + m_append_pos, data, size);
-	m_append_pos += size;
-	return true;
+    if (m_append_pos + size > m_data_size && !Reserve(GetAppendReserveSize(m_append_pos + size)))
+        return false;
+    memcpy(m_data + m_append_pos, data, size);
+    m_append_pos += size;
+    return true;
 }
 
 bool TBTempBuffer::AppendSpace(int size)
 {
-	if (m_append_pos + size > m_data_size && !Reserve(GetAppendReserveSize(m_append_pos + size)))
-		return false;
-	m_append_pos += size;
-	return true;
+    if (m_append_pos + size > m_data_size && !Reserve(GetAppendReserveSize(m_append_pos + size)))
+        return false;
+    m_append_pos += size;
+    return true;
 }
 
 bool TBTempBuffer::AppendString(const char *str)
 {
-	// Add 1 to include the null termination in the data.
-	if (Append(str, strlen(str) + 1))
-	{
-		// Now remove the null termination from the append position
-		// again, so another call will append to the same string (instead of
-		// after the null termination of the first string)
-		m_append_pos--;
-		return true;
-	}
-	return false;
+    // Add 1 to include the null termination in the data.
+    if (Append(str, strlen(str) + 1))
+    {
+        // Now remove the null termination from the append position
+        // again, so another call will append to the same string (instead of
+        // after the null termination of the first string)
+        m_append_pos--;
+        return true;
+    }
+    return false;
 }
 
 bool TBTempBuffer::AppendPath(const char *full_path_and_filename)
 {
-	const char *str_start = full_path_and_filename;
-	while (const char *next = strpbrk(full_path_and_filename, "\\/"))
-		full_path_and_filename = next + 1;
+    const char *str_start = full_path_and_filename;
+    while (const char *next = strpbrk(full_path_and_filename, "\\/"))
+        full_path_and_filename = next + 1;
 
-	if (str_start == full_path_and_filename) // Filename contained no path
-	{
-		str_start = "./";
-		full_path_and_filename = str_start + 2;
-	}
+    if (str_start == full_path_and_filename) // Filename contained no path
+    {
+        str_start = "./";
+        full_path_and_filename = str_start + 2;
+    }
 
-	int len = full_path_and_filename - str_start;
-	if (Reserve(len + 1))
-	{
-		// Add the string, and nulltermination.
-		Append(str_start, len);
-		Append("", 1);
-		// Remove null termination from append pos again (see details in AppendString).
-		m_append_pos--;
-		return true;
-	}
-	return false;
+    int len = full_path_and_filename - str_start;
+    if (Reserve(len + 1))
+    {
+        // Add the string, and nulltermination.
+        Append(str_start, len);
+        Append("", 1);
+        // Remove null termination from append pos again (see details in AppendString).
+        m_append_pos--;
+        return true;
+    }
+    return false;
 }
 
 }; // namespace tb

+ 50 - 50
Source/ThirdParty/TurboBadger/tb_tempbuffer.h

@@ -10,61 +10,61 @@ namespace tb {
 
 /** TBTempBuffer manages a buffer that will be deleted on destruction.
 
-	The buffer size can grow by calling Reserve or Append, but it
-	will never shrink during the lifetime of the object.
+    The buffer size can grow by calling Reserve or Append, but it
+    will never shrink during the lifetime of the object.
 */
 class TBTempBuffer
 {
 public:
-	TBTempBuffer();
-	~TBTempBuffer();
-
-	/** Make sure the buffer has at least size bytes.
-		Returns false on OOM. */
-	bool Reserve(int size);
-
-	/** Get a pointer to the buffer data. */
-	char *GetData() const { return m_data; }
-
-	/** Return the size of the buffer in bytes. */
-	int GetCapacity() const { return m_data_size; }
-
-	/** Append data with size bytes at the end of the buffer and
-		increase the append position with the same amount.
-		Returns false on OOM. */
-	bool Append(const char *data, int size);
-
-	/** Increase the append position with size bytes without
-		writing any data. This is useful if you want to write
-		the data later and want to make sure space is reserved.
-		Returns false on OOM. */
-	bool AppendSpace(int size);
-
-	/** Append a null terminated string (including the null termination)
-		at the end of the buffer. The append position will be increased
-		with the length of the text (excluding the null termination) so
-		multiple calls will produce a concatenated null terminated string.
-		Returns false on OOM. */
-	bool AppendString(const char *str);
-
-	/** Append a path without the ending filename.
-		The buffer will be null terminated and the append position will be
-		increased with the length of the path (excluding the null termination). */
-	bool AppendPath(const char *full_path_and_filename);
-
-	/** Set the position (in bytes) in the buffer where Append should write. */
-	void SetAppendPos(int append_pos);
-
-	/** Reset the append position to 0. */
-	void ResetAppendPos() { m_append_pos = 0; }
-
-	/** Return the current append position in in bytes. */
-	int GetAppendPos() const { return m_append_pos; }
+    TBTempBuffer();
+    ~TBTempBuffer();
+
+    /** Make sure the buffer has at least size bytes.
+        Returns false on OOM. */
+    bool Reserve(int size);
+
+    /** Get a pointer to the buffer data. */
+    char *GetData() const { return m_data; }
+
+    /** Return the size of the buffer in bytes. */
+    int GetCapacity() const { return m_data_size; }
+
+    /** Append data with size bytes at the end of the buffer and
+        increase the append position with the same amount.
+        Returns false on OOM. */
+    bool Append(const char *data, int size);
+
+    /** Increase the append position with size bytes without
+        writing any data. This is useful if you want to write
+        the data later and want to make sure space is reserved.
+        Returns false on OOM. */
+    bool AppendSpace(int size);
+
+    /** Append a null terminated string (including the null termination)
+        at the end of the buffer. The append position will be increased
+        with the length of the text (excluding the null termination) so
+        multiple calls will produce a concatenated null terminated string.
+        Returns false on OOM. */
+    bool AppendString(const char *str);
+
+    /** Append a path without the ending filename.
+        The buffer will be null terminated and the append position will be
+        increased with the length of the path (excluding the null termination). */
+    bool AppendPath(const char *full_path_and_filename);
+
+    /** Set the position (in bytes) in the buffer where Append should write. */
+    void SetAppendPos(int append_pos);
+
+    /** Reset the append position to 0. */
+    void ResetAppendPos() { m_append_pos = 0; }
+
+    /** Return the current append position in in bytes. */
+    int GetAppendPos() const { return m_append_pos; }
 private:
-	int GetAppendReserveSize(int needed_size) const;
-	char *m_data;
-	int m_data_size;
-	int m_append_pos;
+    int GetAppendReserveSize(int needed_size) const;
+    char *m_data;
+    int m_data_size;
+    int m_append_pos;
 };
 
 }; // namespace tb

+ 78 - 78
Source/ThirdParty/TurboBadger/tb_toggle_container.cpp

@@ -13,137 +13,137 @@ namespace tb {
 
 TBSectionHeader::TBSectionHeader()
 {
-	SetSkinBg(TBIDC("TBSectionHeader"));
-	SetGravity(WIDGET_GRAVITY_LEFT | WIDGET_GRAVITY_RIGHT);
-	SetToggleMode(true);
+    SetSkinBg(TBIDC("TBSectionHeader"));
+    SetGravity(WIDGET_GRAVITY_LEFT | WIDGET_GRAVITY_RIGHT);
+    SetToggleMode(true);
 }
 
 bool TBSectionHeader::OnEvent(const TBWidgetEvent &ev)
 {
-	if (ev.target == this && ev.type == EVENT_TYPE_CHANGED && GetParent()->GetParent())
-	{
-		if (TBSection *section = TBSafeCast<TBSection>(GetParent()->GetParent()))
-		{
-			section->GetContainer()->SetValue(GetValue());
-
-			// Try to scroll the container into view when expanded
-			section->SetPendingScrollIntoView(GetValue() ? true : false);
-		}
-	}
-	return TBButton::OnEvent(ev);
+    if (ev.target == this && ev.type == EVENT_TYPE_CHANGED && GetParent()->GetParent())
+    {
+        if (TBSection *section = TBSafeCast<TBSection>(GetParent()->GetParent()))
+        {
+            section->GetContainer()->SetValue(GetValue());
+
+            // Try to scroll the container into view when expanded
+            section->SetPendingScrollIntoView(GetValue() ? true : false);
+        }
+    }
+    return TBButton::OnEvent(ev);
 }
 
 // == TBSectionHeader =====================================
 
 TBSection::TBSection()
-	: m_pending_scroll(false)
+    : m_pending_scroll(false)
 {
-	SetGravity(WIDGET_GRAVITY_LEFT | WIDGET_GRAVITY_RIGHT);
+    SetGravity(WIDGET_GRAVITY_LEFT | WIDGET_GRAVITY_RIGHT);
 
-	SetSkinBg(TBIDC("TBSection"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
-	m_layout.SetSkinBg(TBIDC("TBSection.layout"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
+    SetSkinBg(TBIDC("TBSection"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
+    m_layout.SetSkinBg(TBIDC("TBSection.layout"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
 
-	m_toggle_container.SetSkinBg(TBIDC("TBSection.container"));
-	m_toggle_container.SetToggle(TBToggleContainer::TOGGLE_EXPANDED);
-	m_toggle_container.SetGravity(WIDGET_GRAVITY_ALL);
-	m_layout.SetAxis(AXIS_Y);
-	m_layout.SetGravity(WIDGET_GRAVITY_ALL);
-	m_layout.SetLayoutSize(LAYOUT_SIZE_AVAILABLE);
+    m_toggle_container.SetSkinBg(TBIDC("TBSection.container"));
+    m_toggle_container.SetToggle(TBToggleContainer::TOGGLE_EXPANDED);
+    m_toggle_container.SetGravity(WIDGET_GRAVITY_ALL);
+    m_layout.SetAxis(AXIS_Y);
+    m_layout.SetGravity(WIDGET_GRAVITY_ALL);
+    m_layout.SetLayoutSize(LAYOUT_SIZE_AVAILABLE);
 
-	AddChild(&m_layout);
-	m_layout.AddChild(&m_header);
-	m_layout.AddChild(&m_toggle_container);
+    AddChild(&m_layout);
+    m_layout.AddChild(&m_header);
+    m_layout.AddChild(&m_toggle_container);
 }
 
 TBSection::~TBSection()
 {
-	m_layout.RemoveChild(&m_toggle_container);
-	m_layout.RemoveChild(&m_header);
-	RemoveChild(&m_layout);
+    m_layout.RemoveChild(&m_toggle_container);
+    m_layout.RemoveChild(&m_header);
+    RemoveChild(&m_layout);
 }
 
 void TBSection::SetValue(int value)
 {
-	m_header.SetValue(value);
-	m_toggle_container.SetValue(value);
+    m_header.SetValue(value);
+    m_toggle_container.SetValue(value);
 }
 
 void TBSection::OnProcessAfterChildren()
 {
-	if (m_pending_scroll)
-	{
-		m_pending_scroll = false;
-		ScrollIntoViewRecursive();
-	}
+    if (m_pending_scroll)
+    {
+        m_pending_scroll = false;
+        ScrollIntoViewRecursive();
+    }
 }
 
 PreferredSize TBSection::OnCalculatePreferredSize(const SizeConstraints &constraints)
 {
-	PreferredSize ps = TBWidget::OnCalculatePreferredContentSize(constraints);
-	// We should not grow larger than we are, when there's extra space available.
-	ps.max_h = ps.pref_h;
-	return ps;
+    PreferredSize ps = TBWidget::OnCalculatePreferredContentSize(constraints);
+    // We should not grow larger than we are, when there's extra space available.
+    ps.max_h = ps.pref_h;
+    return ps;
 }
 
 // == TBToggleContainer ===================================
 
 TBToggleContainer::TBToggleContainer()
-	: m_toggle(TOGGLE_NOTHING)
-	, m_invert(false)
-	, m_value(0)
+    : m_toggle(TOGGLE_NOTHING)
+    , m_invert(false)
+    , m_value(0)
 {
-	SetSkinBg(TBIDC("TBToggleContainer"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
+    SetSkinBg(TBIDC("TBToggleContainer"), WIDGET_INVOKE_INFO_NO_CALLBACKS);
 }
 
 void TBToggleContainer::SetToggle(TOGGLE toggle)
 {
-	if (toggle == m_toggle)
-		return;
+    if (toggle == m_toggle)
+        return;
 
-	if (m_toggle == TOGGLE_EXPANDED)
-		InvalidateLayout(INVALIDATE_LAYOUT_RECURSIVE);
+    if (m_toggle == TOGGLE_EXPANDED)
+        InvalidateLayout(INVALIDATE_LAYOUT_RECURSIVE);
 
-	m_toggle = toggle;
-	UpdateInternal();
+    m_toggle = toggle;
+    UpdateInternal();
 }
 
 void TBToggleContainer::SetInvert(bool invert)
 {
-	if (invert == m_invert)
-		return;
-	m_invert = invert;
-	UpdateInternal();
+    if (invert == m_invert)
+        return;
+    m_invert = invert;
+    UpdateInternal();
 }
 
 void TBToggleContainer::SetValue(int value)
 {
-	if (value == m_value)
-		return;
-	m_value = value;
-	UpdateInternal();
-	InvalidateSkinStates();
+    if (value == m_value)
+        return;
+    m_value = value;
+    UpdateInternal();
+    InvalidateSkinStates();
 }
 
 void TBToggleContainer::UpdateInternal()
 {
-	bool on = GetIsOn();
-	switch (m_toggle)
-	{
-	case TOGGLE_NOTHING:
-		break;
-	case TOGGLE_ENABLED:
-		SetState(WIDGET_STATE_DISABLED, !on);
-		break;
-	case TOGGLE_OPACITY:
-		SetOpacity(on ? 1.f : 0);
-		break;
-	case TOGGLE_EXPANDED:
-		SetVisibilility(on ? WIDGET_VISIBILITY_VISIBLE : WIDGET_VISIBILITY_GONE);
-
-		// Also disable when collapsed so tab focus skips the children.
-		SetState(WIDGET_STATE_DISABLED, !on);
-		break;
-	};
+    bool on = GetIsOn();
+    switch (m_toggle)
+    {
+    case TOGGLE_NOTHING:
+        break;
+    case TOGGLE_ENABLED:
+        SetState(WIDGET_STATE_DISABLED, !on);
+        break;
+    case TOGGLE_OPACITY:
+        SetOpacity(on ? 1.f : 0);
+        break;
+    case TOGGLE_EXPANDED:
+        SetVisibilility(on ? WIDGET_VISIBILITY_VISIBLE : WIDGET_VISIBILITY_GONE);
+
+        // Also disable when collapsed so tab focus skips the children.
+        SetState(WIDGET_STATE_DISABLED, !on);
+        break;
+    };
 }
 
 }; // namespace tb

+ 65 - 65
Source/ThirdParty/TurboBadger/tb_toggle_container.h

@@ -11,108 +11,108 @@
 namespace tb {
 
 /** TBToggleContainer is a widget that toggles a property when its value
-	change between 0 and 1. TOGGLE specifies what property will toggle.
-	This is useful f.ex to toggle a whole group of child widgets depending
-	on the value of some other widget. By connecting the TBToggleContainer
-	with a widget connection, this can happen completly automatically. */
+    change between 0 and 1. TOGGLE specifies what property will toggle.
+    This is useful f.ex to toggle a whole group of child widgets depending
+    on the value of some other widget. By connecting the TBToggleContainer
+    with a widget connection, this can happen completly automatically. */
 class TBToggleContainer : public TBWidget
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBToggleContainer, TBWidget);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBToggleContainer, TBWidget);
 
-	TBToggleContainer();
+    TBToggleContainer();
 
-	/** Defines what should toggle when the value changes. */
-	enum TOGGLE {
-		TOGGLE_NOTHING,		///< Nothing happens (the default)
-		TOGGLE_ENABLED,		///< Enabled/disabled state
-		TOGGLE_OPACITY,		///< Opacity 1/0
-		TOGGLE_EXPANDED		///< Expanded/collapsed (In parent axis direction)
-	};
+    /** Defines what should toggle when the value changes. */
+    enum TOGGLE {
+        TOGGLE_NOTHING,		///< Nothing happens (the default)
+        TOGGLE_ENABLED,		///< Enabled/disabled state
+        TOGGLE_OPACITY,		///< Opacity 1/0
+        TOGGLE_EXPANDED		///< Expanded/collapsed (In parent axis direction)
+    };
 
-	/** Set what should toggle when the value changes. */
-	void SetToggle(TOGGLE toggle);
-	TOGGLE GetToggle() const { return m_toggle; }
+    /** Set what should toggle when the value changes. */
+    void SetToggle(TOGGLE toggle);
+    TOGGLE GetToggle() const { return m_toggle; }
 
-	/** Set if the toggle state should be inverted. */
-	void SetInvert(bool invert);
-	bool GetInvert() const { return m_invert; }
+    /** Set if the toggle state should be inverted. */
+    void SetInvert(bool invert);
+    bool GetInvert() const { return m_invert; }
 
-	/** Get the current value, after checking the invert mode. */
-	bool GetIsOn() const { return m_invert ? !m_value : !!m_value; }
+    /** Get the current value, after checking the invert mode. */
+    bool GetIsOn() const { return m_invert ? !m_value : !!m_value; }
 
-	/** Set the value of this widget. 1 will turn on the toggle, 0 will turn it off (or
-		the opposite if the invert mode is set). */
-	virtual void SetValue(int value);
-	virtual int GetValue() { return m_value; }
+    /** Set the value of this widget. 1 will turn on the toggle, 0 will turn it off (or
+        the opposite if the invert mode is set). */
+    virtual void SetValue(int value);
+    virtual int GetValue() { return m_value; }
 
-	virtual void OnInflate(const INFLATE_INFO &info);
+    virtual void OnInflate(const INFLATE_INFO &info);
 private:
-	void UpdateInternal();
-	TOGGLE m_toggle;
-	bool m_invert;
-	int m_value;
+    void UpdateInternal();
+    TOGGLE m_toggle;
+    bool m_invert;
+    int m_value;
 };
 
 /** TBSectionHeader is just a thin wrapper for a TBButton that is in toggle
-	mode with the skin TBSectionHeader by default. It is used as the clickable
-	header in TBSection that toggles the section. */
+    mode with the skin TBSectionHeader by default. It is used as the clickable
+    header in TBSection that toggles the section. */
 class TBSectionHeader : public TBButton
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBSectionHeader, TBButton);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBSectionHeader, TBButton);
 
-	TBSectionHeader();
+    TBSectionHeader();
 
-	virtual bool OnEvent(const TBWidgetEvent &ev);
+    virtual bool OnEvent(const TBWidgetEvent &ev);
 };
 
 /** TBSection is a widget with a header that when clicked toggles its children
-	on and off (using a internal TBToggleContainer with TOGGLE_EXPANDED).
+    on and off (using a internal TBToggleContainer with TOGGLE_EXPANDED).
 
-	The header is a TBSectionHeader.
+    The header is a TBSectionHeader.
 
-	The skin names of the internal widgets are:
-		TBSection				- This widget itself.
-		TBSection.layout		- The layout that wraps the header and the container.
-		TBSection.container		- The toggle container with the children that expands/collapses.
+    The skin names of the internal widgets are:
+        TBSection				- This widget itself.
+        TBSection.layout		- The layout that wraps the header and the container.
+        TBSection.container		- The toggle container with the children that expands/collapses.
 */
 
 class TBSection : public TBWidget
 {
 public:
-	// For safe typecasting
-	TBOBJECT_SUBCLASS(TBSection, TBWidget);
+    // For safe typecasting
+    TBOBJECT_SUBCLASS(TBSection, TBWidget);
 
-	TBSection();
-	~TBSection();
+    TBSection();
+    ~TBSection();
 
-	TBLayout *GetLayout() { return &m_layout; }
-	TBSectionHeader *GetHeader() { return &m_header; }
-	TBToggleContainer *GetContainer() { return &m_toggle_container; }
+    TBLayout *GetLayout() { return &m_layout; }
+    TBSectionHeader *GetHeader() { return &m_header; }
+    TBToggleContainer *GetContainer() { return &m_toggle_container; }
 
-	/** Set if the section should be scrolled into view after next layout. */
-	void SetPendingScrollIntoView(bool pending_scroll) { m_pending_scroll = pending_scroll; }
+    /** Set if the section should be scrolled into view after next layout. */
+    void SetPendingScrollIntoView(bool pending_scroll) { m_pending_scroll = pending_scroll; }
 
-	/** Set the text of the text field. */
-	virtual bool SetText(const char *text) { return m_header.SetText(text); }
-	virtual bool GetText(TBStr &text) { return m_header.GetText(text); }
-	using TBWidget::GetText; ///< Make all versions in base class available.
+    /** Set the text of the text field. */
+    virtual bool SetText(const char *text) { return m_header.SetText(text); }
+    virtual bool GetText(TBStr &text) { return m_header.GetText(text); }
+    using TBWidget::GetText; ///< Make all versions in base class available.
 
-	virtual void SetValue(int value);
-	virtual int GetValue() { return m_toggle_container.GetValue(); }
+    virtual void SetValue(int value);
+    virtual int GetValue() { return m_toggle_container.GetValue(); }
 
-	virtual TBWidget *GetContentRoot() { return m_toggle_container.GetContentRoot(); }
-	virtual void OnProcessAfterChildren();
+    virtual TBWidget *GetContentRoot() { return m_toggle_container.GetContentRoot(); }
+    virtual void OnProcessAfterChildren();
 
-	virtual PreferredSize OnCalculatePreferredSize(const SizeConstraints &constraints);
+    virtual PreferredSize OnCalculatePreferredSize(const SizeConstraints &constraints);
 private:
-	TBLayout m_layout;
-	TBSectionHeader m_header;
-	TBToggleContainer m_toggle_container;
-	bool m_pending_scroll;
+    TBLayout m_layout;
+    TBSectionHeader m_header;
+    TBToggleContainer m_toggle_container;
+    bool m_pending_scroll;
 };
 
 }; // namespace tb

+ 14 - 14
Source/ThirdParty/TurboBadger/tb_types.h

@@ -33,16 +33,16 @@ T Abs(const T& value) { return value < 0 ? -value : value; }
 
 template <class T>
 T Clamp(const T& value, const T& min, const T& max)
-	{ return (value > max) ? max : ((value < min) ? min : value); }
+{ return (value > max) ? max : ((value < min) ? min : value); }
 
 /** Returns value clamped to min and max. If max is greater than min,
-	max will be clipped to min. */
+    max will be clipped to min. */
 template <class T>
 T ClampClipMax(const T& value, const T& min, const T& max)
 {
-	return (value > max)
-		? (max > min ? max : min)
-		: ((value < min) ? min : value);
+    return (value > max)
+            ? (max > min ? max : min)
+            : ((value < min) ? min : value);
 }
 
 #ifndef MAX
@@ -66,16 +66,16 @@ T ClampClipMax(const T& value, const T& min, const T& max)
 #endif
 
 /** Makes it possible to use the given enum types as flag combinations.
-	That will catch use of incorrect type during compilation, that wouldn't be caught
-	using a uint32 flag. */
+    That will catch use of incorrect type during compilation, that wouldn't be caught
+    using a uint32 flag. */
 #define MAKE_ENUM_FLAG_COMBO(Enum) \
-	inline Enum operator | (Enum a, Enum b)  { return static_cast<Enum>(static_cast<uint32>(a) | static_cast<uint32>(b)); } \
-	inline Enum operator & (Enum a, Enum b)  { return static_cast<Enum>(static_cast<uint32>(a) & static_cast<uint32>(b)); } \
-	inline Enum operator ^ (Enum a, Enum b)  { return static_cast<Enum>(static_cast<uint32>(a) ^ static_cast<uint32>(b)); } \
-	inline void operator |= (Enum &a, Enum b) { a = static_cast<Enum>(static_cast<uint32>(a) | static_cast<uint32>(b)); } \
-	inline void operator &= (Enum &a, Enum b) { a = static_cast<Enum>(static_cast<uint32>(a) & static_cast<uint32>(b)); } \
-	inline void operator ^= (Enum &a, Enum b) { a = static_cast<Enum>(static_cast<uint32>(a) ^ static_cast<uint32>(b)); } \
-	inline Enum operator ~ (Enum a)  { return static_cast<Enum>(~static_cast<uint32>(a)); }
+    inline Enum operator | (Enum a, Enum b)  { return static_cast<Enum>(static_cast<uint32>(a) | static_cast<uint32>(b)); } \
+    inline Enum operator & (Enum a, Enum b)  { return static_cast<Enum>(static_cast<uint32>(a) & static_cast<uint32>(b)); } \
+    inline Enum operator ^ (Enum a, Enum b)  { return static_cast<Enum>(static_cast<uint32>(a) ^ static_cast<uint32>(b)); } \
+    inline void operator |= (Enum &a, Enum b) { a = static_cast<Enum>(static_cast<uint32>(a) | static_cast<uint32>(b)); } \
+    inline void operator &= (Enum &a, Enum b) { a = static_cast<Enum>(static_cast<uint32>(a) & static_cast<uint32>(b)); } \
+    inline void operator ^= (Enum &a, Enum b) { a = static_cast<Enum>(static_cast<uint32>(a) ^ static_cast<uint32>(b)); } \
+    inline Enum operator ~ (Enum a)  { return static_cast<Enum>(~static_cast<uint32>(a)); }
 
 }; // namespace tb
 

+ 221 - 221
Source/ThirdParty/TurboBadger/tb_value.cpp

@@ -18,51 +18,51 @@ namespace tb {
 // == Helper functions ============================
 
 char *next_token(char *&str, const char *delim) {
-	str += strspn(str, delim);
-	if (!*str)
-		return nullptr;
-	char *token = str;
-	str += strcspn(str, delim);
-	if (*str)
-		*str++ = '\0';
-	return token;
+    str += strspn(str, delim);
+    if (!*str)
+        return nullptr;
+    char *token = str;
+    str += strcspn(str, delim);
+    if (*str)
+        *str++ = '\0';
+    return token;
 }
 
 bool is_start_of_number(const char *str)
 {
-	if (*str == '-')
-		str++;
-	if (*str == '.')
-		str++;
-	return *str >= '0' && *str <= '9';
+    if (*str == '-')
+        str++;
+    if (*str == '.')
+        str++;
+    return *str >= '0' && *str <= '9';
 }
 
 bool contains_non_trailing_space(const char *str)
 {
-	if (const char *p = strstr(str, " "))
-	{
-		while (*p == ' ')
-			p++;
-		return *p != '\0';
-	}
-	return false;
+    if (const char *p = strstr(str, " "))
+    {
+        while (*p == ' ')
+            p++;
+        return *p != '\0';
+    }
+    return false;
 }
 
 bool is_number_only(const char *s)
 {
-	if (!s || *s == 0 || *s == ' ')
-		return 0;
-	char *p;
-	strtod(s, &p);
-	while (*p == ' ')
-		p++;
-	return *p == '\0';
+    if (!s || *s == 0 || *s == ' ')
+        return 0;
+    char *p;
+    strtod(s, &p);
+    while (*p == ' ')
+        p++;
+    return *p == '\0';
 }
 
 bool is_number_float(const char *str)
 {
-	while (*str) if (*str++ == '.') return true;
-	return false;
+    while (*str) if (*str++ == '.') return true;
+    return false;
 }
 
 // == TBValueArray ==================================
@@ -77,288 +77,288 @@ TBValueArray::~TBValueArray()
 
 TBValue *TBValueArray::AddValue()
 {
-	TBValue *v;
-	if ((v = new TBValue()) && m_list.Add(v))
-		return v;
-	delete v;
-	return nullptr;
+    TBValue *v;
+    if ((v = new TBValue()) && m_list.Add(v))
+        return v;
+    delete v;
+    return nullptr;
 }
 
 TBValue *TBValueArray::GetValue(int index)
 {
-	if (index >= 0 && index < m_list.GetNumItems())
-		return m_list[index];
-	return nullptr;
+    if (index >= 0 && index < m_list.GetNumItems())
+        return m_list[index];
+    return nullptr;
 }
 
 TBValueArray *TBValueArray::Clone(TBValueArray *source)
 {
-	TBValueArray *new_arr = new TBValueArray;
-	if (!new_arr)
-		return nullptr;
-	for (int i = 0; i < source->m_list.GetNumItems(); i++)
-	{
-		TBValue *new_val = new_arr->AddValue();
-		if (!new_val)
-		{
-			delete new_arr;
-			return nullptr;
-		}
-		new_val->Copy(*source->GetValue(i));
-	}
-	return new_arr;
+    TBValueArray *new_arr = new TBValueArray;
+    if (!new_arr)
+        return nullptr;
+    for (int i = 0; i < source->m_list.GetNumItems(); i++)
+    {
+        TBValue *new_val = new_arr->AddValue();
+        if (!new_val)
+        {
+            delete new_arr;
+            return nullptr;
+        }
+        new_val->Copy(*source->GetValue(i));
+    }
+    return new_arr;
 }
 
 // == TBValue =======================================
 
 TBValue::TBValue()
-	: m_packed_init(0)
+    : m_packed_init(0)
 {
 }
 
 TBValue::TBValue(const TBValue &value)
-	: m_packed_init(0)
+    : m_packed_init(0)
 {
-	Copy(value);
+    Copy(value);
 }
 
 TBValue::TBValue(TYPE type)
-	: m_packed_init(0)
+    : m_packed_init(0)
 {
-	switch (type)
-	{
-	case TYPE_NULL:
-		SetNull();
-		break;
-	case TYPE_STRING:
-		SetString("", SET_AS_STATIC);
-		break;
-	case TYPE_FLOAT:
-		SetFloat(0);
-		break;
-	case TYPE_INT:
-		SetInt(0);
-		break;
-	case TYPE_OBJECT:
-		SetObject(nullptr);
-		break;
-	case TYPE_ARRAY:
-		if (TBValueArray *arr = new TBValueArray())
-			SetArray(arr, SET_TAKE_OWNERSHIP);
-		break;
-	default:
-		assert(!"Not implemented!");
-	};
+    switch (type)
+    {
+    case TYPE_NULL:
+        SetNull();
+        break;
+    case TYPE_STRING:
+        SetString("", SET_AS_STATIC);
+        break;
+    case TYPE_FLOAT:
+        SetFloat(0);
+        break;
+    case TYPE_INT:
+        SetInt(0);
+        break;
+    case TYPE_OBJECT:
+        SetObject(nullptr);
+        break;
+    case TYPE_ARRAY:
+        if (TBValueArray *arr = new TBValueArray())
+            SetArray(arr, SET_TAKE_OWNERSHIP);
+        break;
+    default:
+        assert(!"Not implemented!");
+    };
 }
 
 TBValue::TBValue(int value)
-	: m_packed_init(0)
+    : m_packed_init(0)
 {
-	SetInt(value);
+    SetInt(value);
 }
 
 TBValue::TBValue(float value)
-	: m_packed_init(0)
+    : m_packed_init(0)
 {
-	SetFloat(value);
+    SetFloat(value);
 }
 
 TBValue::TBValue(const char *value, SET set)
-	: m_packed_init(0)
+    : m_packed_init(0)
 {
-	SetString(value, set);
+    SetString(value, set);
 }
 
 TBValue::TBValue(TBTypedObject *object)
-	: m_packed_init(0)
+    : m_packed_init(0)
 {
-	SetObject(object);
+    SetObject(object);
 }
 
 TBValue::~TBValue()
 {
-	SetNull();
+    SetNull();
 }
 
 void TBValue::TakeOver(TBValue &source_value)
 {
-	if (source_value.m_packed.type == TYPE_STRING)
-		SetString(source_value.val_str, source_value.m_packed.allocated ? SET_TAKE_OWNERSHIP : SET_NEW_COPY);
-	else if (source_value.m_packed.type == TYPE_ARRAY)
-		SetArray(source_value.val_arr, source_value.m_packed.allocated ? SET_TAKE_OWNERSHIP : SET_NEW_COPY);
-	else
-		*this = source_value;
-	source_value.m_packed.type = TYPE_NULL;
+    if (source_value.m_packed.type == TYPE_STRING)
+        SetString(source_value.val_str, source_value.m_packed.allocated ? SET_TAKE_OWNERSHIP : SET_NEW_COPY);
+    else if (source_value.m_packed.type == TYPE_ARRAY)
+        SetArray(source_value.val_arr, source_value.m_packed.allocated ? SET_TAKE_OWNERSHIP : SET_NEW_COPY);
+    else
+        *this = source_value;
+    source_value.m_packed.type = TYPE_NULL;
 }
 
 void TBValue::Copy(const TBValue &source_value)
 {
-	if (source_value.m_packed.type == TYPE_STRING)
-		SetString(source_value.val_str, SET_NEW_COPY);
-	else if (source_value.m_packed.type == TYPE_ARRAY)
-		SetArray(source_value.val_arr, SET_NEW_COPY);
-	else if (source_value.m_packed.type == TYPE_OBJECT)
-	{
-		assert(!"We can't copy objects! The value will be nulled!");
-		SetObject(nullptr);
-	}
-	else
-	{
-		SetNull();
-		memcpy(this, &source_value, sizeof(TBValue));
-	}
+    if (source_value.m_packed.type == TYPE_STRING)
+        SetString(source_value.val_str, SET_NEW_COPY);
+    else if (source_value.m_packed.type == TYPE_ARRAY)
+        SetArray(source_value.val_arr, SET_NEW_COPY);
+    else if (source_value.m_packed.type == TYPE_OBJECT)
+    {
+        assert(!"We can't copy objects! The value will be nulled!");
+        SetObject(nullptr);
+    }
+    else
+    {
+        SetNull();
+        memcpy(this, &source_value, sizeof(TBValue));
+    }
 }
 
 void TBValue::SetNull()
 {
-	if (m_packed.allocated)
-	{
-		if (m_packed.type == TYPE_STRING)
-			free(val_str);
-		else if (m_packed.type == TYPE_OBJECT)
-			delete val_obj;
-		else if (m_packed.type == TYPE_ARRAY)
-			delete val_arr;
-	}
-	m_packed.type = TYPE_NULL;
+    if (m_packed.allocated)
+    {
+        if (m_packed.type == TYPE_STRING)
+            free(val_str);
+        else if (m_packed.type == TYPE_OBJECT)
+            delete val_obj;
+        else if (m_packed.type == TYPE_ARRAY)
+            delete val_arr;
+    }
+    m_packed.type = TYPE_NULL;
 }
 
 void TBValue::SetInt(int val)
 {
-	SetNull();
-	m_packed.type = TYPE_INT;
-	val_int = val;
+    SetNull();
+    m_packed.type = TYPE_INT;
+    val_int = val;
 }
 
 void TBValue::SetFloat(float val)
 {
-	SetNull();
-	m_packed.type = TYPE_FLOAT;
-	val_float = val;
+    SetNull();
+    m_packed.type = TYPE_FLOAT;
+    val_float = val;
 }
 
 void TBValue::SetString(const char *val, SET set)
 {
-	SetNull();
-	m_packed.allocated = (set == SET_NEW_COPY || set == SET_TAKE_OWNERSHIP);
-	if (set != SET_NEW_COPY)
-	{
-		val_str = const_cast<char *>(val);
-		m_packed.type = TYPE_STRING;
-	}
-	else if ((val_str = strdup(val)))
-		m_packed.type = TYPE_STRING;
+    SetNull();
+    m_packed.allocated = (set == SET_NEW_COPY || set == SET_TAKE_OWNERSHIP);
+    if (set != SET_NEW_COPY)
+    {
+        val_str = const_cast<char *>(val);
+        m_packed.type = TYPE_STRING;
+    }
+    else if ((val_str = strdup(val)))
+        m_packed.type = TYPE_STRING;
 }
 
 void TBValue::SetObject(TBTypedObject *object)
 {
-	SetNull();
-	m_packed.type = TYPE_OBJECT;
-	m_packed.allocated = true;
-	val_obj = object;
+    SetNull();
+    m_packed.type = TYPE_OBJECT;
+    m_packed.allocated = true;
+    val_obj = object;
 }
 
 void TBValue::SetArray(TBValueArray *arr, SET set)
 {
-	SetNull();
-	m_packed.allocated = (set == SET_NEW_COPY || set == SET_TAKE_OWNERSHIP);
-	if (set != SET_NEW_COPY)
-	{
-		val_arr = arr;
-		m_packed.type = TYPE_ARRAY;
-	}
-	else if ((val_arr = TBValueArray::Clone(arr)))
-		m_packed.type = TYPE_ARRAY;
+    SetNull();
+    m_packed.allocated = (set == SET_NEW_COPY || set == SET_TAKE_OWNERSHIP);
+    if (set != SET_NEW_COPY)
+    {
+        val_arr = arr;
+        m_packed.type = TYPE_ARRAY;
+    }
+    else if ((val_arr = TBValueArray::Clone(arr)))
+        m_packed.type = TYPE_ARRAY;
 }
 
 void TBValue::SetFromStringAuto(const char *str, SET set)
 {
-	if (!str)
-		SetNull();
-	else if (is_number_only(str))
-	{
-		if (is_number_float(str))
-			SetFloat((float)atof(str));
-		else
-			SetInt(atoi(str));
-	}
-	else if (is_start_of_number(str) && contains_non_trailing_space(str))
-	{
-		// If the number has nontrailing space, we'll assume a list of numbers (example: "10 -4 3.5")
-		SetNull();
-		if (TBValueArray *arr = new TBValueArray)
-		{
-			TBStr tmpstr;
-			if (tmpstr.Set(str))
-			{
-				char *str_next = tmpstr.CStr();
-				while (char *token = next_token(str_next, ", "))
-				{
-					if (TBValue *new_val = arr->AddValue())
-						new_val->SetFromStringAuto(token, SET_NEW_COPY);
-				}
-			}
-			SetArray(arr, SET_TAKE_OWNERSHIP);
-		}
-	}
-	else if (*str == '[')
-	{
-		SetNull();
-		if (TBValueArray *arr = new TBValueArray)
-		{
-			assert(!"not implemented! Split out the tokenizer code above!");
-			SetArray(arr, SET_TAKE_OWNERSHIP);
-		}
-	}
-	else
-	{
-		SetString(str, set);
-		return;
-	}
-	// We didn't set as string, so we might need to deal with the passed in string data.
-	if (set == SET_TAKE_OWNERSHIP)
-	{
-		// Delete the passed in data
-		TBValue tmp;
-		tmp.SetString(str, SET_TAKE_OWNERSHIP);
-	}
+    if (!str)
+        SetNull();
+    else if (is_number_only(str))
+    {
+        if (is_number_float(str))
+            SetFloat((float)atof(str));
+        else
+            SetInt(atoi(str));
+    }
+    else if (is_start_of_number(str) && contains_non_trailing_space(str))
+    {
+        // If the number has nontrailing space, we'll assume a list of numbers (example: "10 -4 3.5")
+        SetNull();
+        if (TBValueArray *arr = new TBValueArray)
+        {
+            TBStr tmpstr;
+            if (tmpstr.Set(str))
+            {
+                char *str_next = tmpstr.CStr();
+                while (char *token = next_token(str_next, ", "))
+                {
+                    if (TBValue *new_val = arr->AddValue())
+                        new_val->SetFromStringAuto(token, SET_NEW_COPY);
+                }
+            }
+            SetArray(arr, SET_TAKE_OWNERSHIP);
+        }
+    }
+    else if (*str == '[')
+    {
+        SetNull();
+        if (TBValueArray *arr = new TBValueArray)
+        {
+            assert(!"not implemented! Split out the tokenizer code above!");
+            SetArray(arr, SET_TAKE_OWNERSHIP);
+        }
+    }
+    else
+    {
+        SetString(str, set);
+        return;
+    }
+    // We didn't set as string, so we might need to deal with the passed in string data.
+    if (set == SET_TAKE_OWNERSHIP)
+    {
+        // Delete the passed in data
+        TBValue tmp;
+        tmp.SetString(str, SET_TAKE_OWNERSHIP);
+    }
 }
 
 int TBValue::GetInt() const
 {
-	if (m_packed.type == TYPE_STRING)
-		return atoi(val_str);
-	else if (m_packed.type == TYPE_FLOAT)
-		return (int) val_float;
-	return m_packed.type == TYPE_INT ? val_int : 0;
+    if (m_packed.type == TYPE_STRING)
+        return atoi(val_str);
+    else if (m_packed.type == TYPE_FLOAT)
+        return (int) val_float;
+    return m_packed.type == TYPE_INT ? val_int : 0;
 }
 
 float TBValue::GetFloat() const
 {
-	if (m_packed.type == TYPE_STRING)
-		return (float) atof(val_str);
-	else if (m_packed.type == TYPE_INT)
-		return (float) val_int;
-	return m_packed.type == TYPE_FLOAT ? val_float : 0;
+    if (m_packed.type == TYPE_STRING)
+        return (float) atof(val_str);
+    else if (m_packed.type == TYPE_INT)
+        return (float) val_int;
+    return m_packed.type == TYPE_FLOAT ? val_float : 0;
 }
 
 const char *TBValue::GetString()
 {
-	if (m_packed.type == TYPE_INT)
-	{
-		char tmp[32];
-		sprintf(tmp, "%d", val_int);
-		SetString(tmp, SET_NEW_COPY);
-	}
-	else if (m_packed.type == TYPE_FLOAT)
-	{
-		char tmp[32];
-		sprintf(tmp, "%f", val_float);
-		SetString(tmp, SET_NEW_COPY);
-	}
-	else if (m_packed.type == TYPE_OBJECT)
-		return val_obj ? val_obj->GetClassName() : "";
-	return m_packed.type == TYPE_STRING ? val_str : "";
+    if (m_packed.type == TYPE_INT)
+    {
+        char tmp[32];
+        sprintf(tmp, "%d", val_int);
+        SetString(tmp, SET_NEW_COPY);
+    }
+    else if (m_packed.type == TYPE_FLOAT)
+    {
+        char tmp[32];
+        sprintf(tmp, "%f", val_float);
+        SetString(tmp, SET_NEW_COPY);
+    }
+    else if (m_packed.type == TYPE_OBJECT)
+        return val_obj ? val_obj->GetClassName() : "";
+    return m_packed.type == TYPE_STRING ? val_str : "";
 }
 
 }; // namespace tb

+ 102 - 102
Source/ThirdParty/TurboBadger/tb_value.h

@@ -15,132 +15,132 @@ class TBValue;
 class TBTypedObject;
 
 /** Return true if the given string starts with a number.
-	Ex: 100, -.2, 1.0E-8, 5px will all return true. */
+    Ex: 100, -.2, 1.0E-8, 5px will all return true. */
 bool is_start_of_number(const char *str);
 
 /** Returns true if the given string contains space that
-	is not at the end of the string. */
+    is not at the end of the string. */
 bool contains_non_trailing_space(const char *str);
 
 /** Return true if the string can be represented as a number.
-	It ignores trailing white space.
-	Ex: 100, -.2 will return true.
-	Ex: 1.0E-8, 5px will return false. */
+    It ignores trailing white space.
+    Ex: 100, -.2 will return true.
+    Ex: 1.0E-8, 5px will return false. */
 bool is_number_only(const char *str);
 
 /** Return true if the given number string is a float number.
-	Should only be called when you've verified it's a number with is_number(). */
+    Should only be called when you've verified it's a number with is_number(). */
 bool is_number_float(const char *str);
 
 /** TBValueArray is a array of TBValue */
 class TBValueArray
 {
 public:
-	TBValueArray();
-	~TBValueArray();
-	TBValue *AddValue();
-	TBValue *GetValue(int index);
-	static TBValueArray *Clone(TBValueArray *source);
-	int GetLength() const { return m_list.GetNumItems(); }
+    TBValueArray();
+    ~TBValueArray();
+    TBValue *AddValue();
+    TBValue *GetValue(int index);
+    static TBValueArray *Clone(TBValueArray *source);
+    int GetLength() const { return m_list.GetNumItems(); }
 private:
-	TBListAutoDeleteOf<TBValue> m_list;
+    TBListAutoDeleteOf<TBValue> m_list;
 };
 
 /** TBValue holds value of a specific type.
-	In addition to NULL, string, float, integer, it may also contain an array
-	of attributes (TBValueArray), or an object (derived from TBTypedObject).
+    In addition to NULL, string, float, integer, it may also contain an array
+    of attributes (TBValueArray), or an object (derived from TBTypedObject).
 
-	When getting the value as a different type from what it is, it may convert
-	its internal representation to that type. Exceptions are for array and
-	object, which will return 0 when getting as numbers, or "" or object name
-	when getting as string. */
+    When getting the value as a different type from what it is, it may convert
+    its internal representation to that type. Exceptions are for array and
+    object, which will return 0 when getting as numbers, or "" or object name
+    when getting as string. */
 class TBValue
 {
 public:
-	/** The current type of the value.
-		It may change when using a getter of a different type. */
-	enum TYPE {
-		TYPE_NULL,
-		TYPE_STRING,
-		TYPE_FLOAT,
-		TYPE_INT,
-		TYPE_OBJECT,
-		TYPE_ARRAY
-	};
-
-	/** How to deal with the dynamic memory when setting string and array. */
-	enum SET {
-		SET_NEW_COPY,			///< A new copy of the data will be made.
-		SET_TAKE_OWNERSHIP,		///< The data passed in will be stored and freed.
-		SET_AS_STATIC			///< The data passed in will be stored but never freed.
-	};
-
-	TBValue();
-	TBValue(const TBValue &value);
-	TBValue(TYPE type);
-
-	TBValue(int value);
-	TBValue(float value);
-	TBValue(const char *value, SET set = SET_NEW_COPY);
-	TBValue(TBTypedObject *object);
-
-	~TBValue();
-
-	/** Take over ownership of content of source_value.
-		Note:	-If source_value has string or array that are set with SET_AS_STATIC, it will make new copies of those.
-				-value will be nulled on source_value after this call. */
-	void TakeOver(TBValue &source_value);
-
-	/** Copy the content of source_value to this value.
-		Note: This value will become TYPE_NULL if source_value holds an object. We can't copy objects. */
-	void Copy(const TBValue &source_value);
-
-	void SetNull();
-	void SetInt(int val);
-	void SetFloat(float val);
-
-	/** Set the passed in string */
-	void SetString(const char *val, SET set);
-
-	/** Set the passed in object. Takes the ownership of the object! */
-	void SetObject(TBTypedObject *object);
-
-	/** Set the passed in array */
-	void SetArray(TBValueArray *arr, SET set);
-
-	/** Set the value either as a string, number or array of numbers, depending of the string syntax. */
-	void SetFromStringAuto(const char *str, SET set);
-
-	int GetInt() const;
-	float GetFloat() const;
-	const char *GetString();
-	TBTypedObject *GetObject() const { return IsObject() ? val_obj : nullptr; }
-	TBValueArray *GetArray() const { return IsArray() ? val_arr : nullptr; }
-
-	TYPE GetType() const { return (TYPE) m_packed.type; }
-	bool IsString() const { return m_packed.type == TYPE_STRING; }
-	bool IsFloat() const { return m_packed.type == TYPE_FLOAT; }
-	bool IsInt() const { return m_packed.type == TYPE_INT; }
-	bool IsObject() const { return m_packed.type == TYPE_OBJECT; }
-	bool IsArray() const { return m_packed.type == TYPE_ARRAY; }
-	int GetArrayLength() const { return IsArray() ? val_arr->GetLength() : 0; }
-
-	const TBValue& operator = (const TBValue &val) { Copy(val); return *this; }
+    /** The current type of the value.
+        It may change when using a getter of a different type. */
+    enum TYPE {
+        TYPE_NULL,
+        TYPE_STRING,
+        TYPE_FLOAT,
+        TYPE_INT,
+        TYPE_OBJECT,
+        TYPE_ARRAY
+    };
+
+    /** How to deal with the dynamic memory when setting string and array. */
+    enum SET {
+        SET_NEW_COPY,			///< A new copy of the data will be made.
+        SET_TAKE_OWNERSHIP,		///< The data passed in will be stored and freed.
+        SET_AS_STATIC			///< The data passed in will be stored but never freed.
+    };
+
+    TBValue();
+    TBValue(const TBValue &value);
+    TBValue(TYPE type);
+
+    TBValue(int value);
+    TBValue(float value);
+    TBValue(const char *value, SET set = SET_NEW_COPY);
+    TBValue(TBTypedObject *object);
+
+    ~TBValue();
+
+    /** Take over ownership of content of source_value.
+        Note:	-If source_value has string or array that are set with SET_AS_STATIC, it will make new copies of those.
+                -value will be nulled on source_value after this call. */
+    void TakeOver(TBValue &source_value);
+
+    /** Copy the content of source_value to this value.
+        Note: This value will become TYPE_NULL if source_value holds an object. We can't copy objects. */
+    void Copy(const TBValue &source_value);
+
+    void SetNull();
+    void SetInt(int val);
+    void SetFloat(float val);
+
+    /** Set the passed in string */
+    void SetString(const char *val, SET set);
+
+    /** Set the passed in object. Takes the ownership of the object! */
+    void SetObject(TBTypedObject *object);
+
+    /** Set the passed in array */
+    void SetArray(TBValueArray *arr, SET set);
+
+    /** Set the value either as a string, number or array of numbers, depending of the string syntax. */
+    void SetFromStringAuto(const char *str, SET set);
+
+    int GetInt() const;
+    float GetFloat() const;
+    const char *GetString();
+    TBTypedObject *GetObject() const { return IsObject() ? val_obj : nullptr; }
+    TBValueArray *GetArray() const { return IsArray() ? val_arr : nullptr; }
+
+    TYPE GetType() const { return (TYPE) m_packed.type; }
+    bool IsString() const { return m_packed.type == TYPE_STRING; }
+    bool IsFloat() const { return m_packed.type == TYPE_FLOAT; }
+    bool IsInt() const { return m_packed.type == TYPE_INT; }
+    bool IsObject() const { return m_packed.type == TYPE_OBJECT; }
+    bool IsArray() const { return m_packed.type == TYPE_ARRAY; }
+    int GetArrayLength() const { return IsArray() ? val_arr->GetLength() : 0; }
+
+    const TBValue& operator = (const TBValue &val) { Copy(val); return *this; }
 private:
-	union {
-		float val_float;
-		int val_int;
-		char *val_str;
-		TBTypedObject *val_obj;
-		TBValueArray *val_arr;
-	};
-	union {
-		struct {
-			uint32 type : 8;
-			uint32 allocated : 1;
-		} m_packed;
-		uint32 m_packed_init;
-	};
+    union {
+        float val_float;
+        int val_int;
+        char *val_str;
+        TBTypedObject *val_obj;
+        TBValueArray *val_arr;
+    };
+    union {
+        struct {
+            uint32 type : 8;
+            uint32 allocated : 1;
+        } m_packed;
+        uint32 m_packed_init;
+    };
 };
 
 }; // namespace tb

+ 59 - 59
Source/ThirdParty/TurboBadger/tb_widget_skin_condition_context.cpp

@@ -14,69 +14,69 @@ namespace tb {
 
 bool TBWidgetSkinConditionContext::GetCondition(TBSkinCondition::TARGET target, const TBSkinCondition::CONDITION_INFO &info)
 {
-	switch (target)
-	{
-	case TBSkinCondition::TARGET_THIS:
-		return GetCondition(m_widget, info);
-	case TBSkinCondition::TARGET_PARENT:
-		return m_widget->GetParent() && GetCondition(m_widget->GetParent(), info);
-	case TBSkinCondition::TARGET_ANCESTORS:
-		{
-			TBWidget *widget = m_widget->GetParent();
-			while (widget)
-			{
-				if (GetCondition(widget, info))
-					return true;
-				widget = widget->GetParent();
-			}
-		}
-	case TBSkinCondition::TARGET_PREV_SIBLING:
-		return m_widget->GetPrev() && GetCondition(m_widget->GetPrev(), info);
-	case TBSkinCondition::TARGET_NEXT_SIBLING:
-		return m_widget->GetNext() && GetCondition(m_widget->GetNext(), info);
-	}
-	return false;
+    switch (target)
+    {
+    case TBSkinCondition::TARGET_THIS:
+        return GetCondition(m_widget, info);
+    case TBSkinCondition::TARGET_PARENT:
+        return m_widget->GetParent() && GetCondition(m_widget->GetParent(), info);
+    case TBSkinCondition::TARGET_ANCESTORS:
+    {
+        TBWidget *widget = m_widget->GetParent();
+        while (widget)
+        {
+            if (GetCondition(widget, info))
+                return true;
+            widget = widget->GetParent();
+        }
+    }
+    case TBSkinCondition::TARGET_PREV_SIBLING:
+        return m_widget->GetPrev() && GetCondition(m_widget->GetPrev(), info);
+    case TBSkinCondition::TARGET_NEXT_SIBLING:
+        return m_widget->GetNext() && GetCondition(m_widget->GetNext(), info);
+    }
+    return false;
 }
 
 bool TBWidgetSkinConditionContext::GetCondition(TBWidget *widget, const TBSkinCondition::CONDITION_INFO &info)
 {
-	switch (info.prop)
-	{
-	case TBSkinCondition::PROPERTY_SKIN:
-		return widget->GetSkinBg() == info.value;
-	case TBSkinCondition::PROPERTY_WINDOW_ACTIVE:
-		if (TBWindow *window = widget->GetParentWindow())
-			return window->IsActive();
-		return false;
-	case TBSkinCondition::PROPERTY_AXIS:
-		return TBID(widget->GetAxis() == AXIS_X ? "x" : "y") == info.value;
-	case TBSkinCondition::PROPERTY_ALIGN:
-		if (TBTabContainer *tc = TBSafeCast<TBTabContainer>(widget))
-		{
-			TBID widget_align;
-			if (tc->GetAlignment() == TB_ALIGN_LEFT)				widget_align = TBIDC("left");
-			else if (tc->GetAlignment() == TB_ALIGN_TOP)			widget_align = TBIDC("top");
-			else if (tc->GetAlignment() == TB_ALIGN_RIGHT)		widget_align = TBIDC("right");
-			else if (tc->GetAlignment() == TB_ALIGN_BOTTOM)		widget_align = TBIDC("bottom");
-			return widget_align == info.value;
-		}
-		return false;
-	case TBSkinCondition::PROPERTY_ID:
-		return widget->GetID() == info.value;
-	case TBSkinCondition::PROPERTY_STATE:
-		return !!(widget->GetAutoState() & info.value);
-	case TBSkinCondition::PROPERTY_VALUE:
-		return widget->GetValue() == (int) info.value;
-	case TBSkinCondition::PROPERTY_HOVER:
-		return TBWidget::hovered_widget && widget->IsAncestorOf(TBWidget::hovered_widget);
-	case TBSkinCondition::PROPERTY_CAPTURE:
-		return TBWidget::captured_widget && widget->IsAncestorOf(TBWidget::captured_widget);
-	case TBSkinCondition::PROPERTY_FOCUS:
-		return TBWidget::focused_widget && widget->IsAncestorOf(TBWidget::focused_widget);
-	case TBSkinCondition::PROPERTY_CUSTOM:
-		return widget->GetCustomSkinCondition(info);
-	}
-	return false;
+    switch (info.prop)
+    {
+    case TBSkinCondition::PROPERTY_SKIN:
+        return widget->GetSkinBg() == info.value;
+    case TBSkinCondition::PROPERTY_WINDOW_ACTIVE:
+        if (TBWindow *window = widget->GetParentWindow())
+            return window->IsActive();
+        return false;
+    case TBSkinCondition::PROPERTY_AXIS:
+        return TBID(widget->GetAxis() == AXIS_X ? "x" : "y") == info.value;
+    case TBSkinCondition::PROPERTY_ALIGN:
+        if (TBTabContainer *tc = TBSafeCast<TBTabContainer>(widget))
+        {
+            TBID widget_align;
+            if (tc->GetAlignment() == TB_ALIGN_LEFT)				widget_align = TBIDC("left");
+            else if (tc->GetAlignment() == TB_ALIGN_TOP)			widget_align = TBIDC("top");
+            else if (tc->GetAlignment() == TB_ALIGN_RIGHT)		widget_align = TBIDC("right");
+            else if (tc->GetAlignment() == TB_ALIGN_BOTTOM)		widget_align = TBIDC("bottom");
+            return widget_align == info.value;
+        }
+        return false;
+    case TBSkinCondition::PROPERTY_ID:
+        return widget->GetID() == info.value;
+    case TBSkinCondition::PROPERTY_STATE:
+        return !!(widget->GetAutoState() & info.value);
+    case TBSkinCondition::PROPERTY_VALUE:
+        return widget->GetValue() == (int) info.value;
+    case TBSkinCondition::PROPERTY_HOVER:
+        return TBWidget::hovered_widget && widget->IsAncestorOf(TBWidget::hovered_widget);
+    case TBSkinCondition::PROPERTY_CAPTURE:
+        return TBWidget::captured_widget && widget->IsAncestorOf(TBWidget::captured_widget);
+    case TBSkinCondition::PROPERTY_FOCUS:
+        return TBWidget::focused_widget && widget->IsAncestorOf(TBWidget::focused_widget);
+    case TBSkinCondition::PROPERTY_CUSTOM:
+        return widget->GetCustomSkinCondition(info);
+    }
+    return false;
 }
 
 }; // namespace tb

Some files were not shown because too many files changed in this diff