changeset 24:7f7c2607ace3

Client: add size property for Malikania.Image, #457
author David Demelier <markand@malikania.fr>
date Wed, 06 Apr 2016 13:17:33 +0200
parents ed63752a8720
children dc47ce56ce36
files libclient/malikania/js-image.cpp tests/libclient/js-image/main.cpp
diffstat 2 files changed, 47 insertions(+), 12 deletions(-) [+]
line wrap: on
line diff
--- a/libclient/malikania/js-image.cpp	Tue Apr 05 21:06:27 2016 +0200
+++ b/libclient/malikania/js-image.cpp	Wed Apr 06 13:17:33 2016 +0200
@@ -20,30 +20,22 @@
 #include "js-image.h"
 #include "js-point.h"
 #include "js-rectangle.h"
+#include "js-size.h"
 #include "js-window.h"
 
 namespace malikania {
 
 namespace {
 
-duk::Ret constructor(duk::ContextPtr ctx)
+duk::Ret size(duk::ContextPtr ctx)
 {
-	duk::StackAssert sa(ctx);
-
-	if (!duk_is_constructor_call(ctx)) {
-		duk::raise(ctx, DUK_ERR_ERROR, "image must be new-constructed");
-	}
-
 	try {
-		auto loader = duk::getGlobal<duk::RawPointer<ClientResourcesLoader>>(ctx, "\xff""\xff""loader");
-		auto image = loader->loadImage(duk::require<std::string>(ctx, 0));
-
-		duk::construct(ctx, duk::Pointer<Image>{new Image(std::move(image))});
+		duk::push(ctx, duk::self<duk::Pointer<Image>>(ctx)->size());
 	} catch (const std::exception &ex) {
 		duk::raise(ctx, DUK_ERR_ERROR, "%s", ex.what());
 	}
 
-	return 0;
+	return 1;
 }
 
 duk::Ret draw(duk::ContextPtr ctx)
@@ -66,6 +58,29 @@
 	return 0;
 }
 
+duk::Ret constructor(duk::ContextPtr ctx)
+{
+	if (!duk_is_constructor_call(ctx)) {
+		duk::raise(ctx, DUK_ERR_ERROR, "image must be new-constructed");
+	}
+
+	try {
+		auto loader = duk::getGlobal<duk::RawPointer<ClientResourcesLoader>>(ctx, "\xff""\xff""loader");
+		auto image = loader->loadImage(duk::require<std::string>(ctx, 0));
+
+		duk::construct(ctx, duk::Pointer<Image>{new Image(std::move(image))});
+		duk::push(ctx, duk::This());
+		duk::push(ctx, "size");
+		duk::push(ctx, duk::Function{size, 0});
+		duk::defineProperty(ctx, -3, DUK_DEFPROP_HAVE_GETTER);
+		duk::pop(ctx);
+	} catch (const std::exception &ex) {
+		duk::raise(ctx, DUK_ERR_ERROR, "%s", ex.what());
+	}
+
+	return 0;
+}
+
 const duk::FunctionMap methods{
 	{ "draw",	{ draw,		DUK_VARARGS } }
 };
--- a/tests/libclient/js-image/main.cpp	Tue Apr 05 21:06:27 2016 +0200
+++ b/tests/libclient/js-image/main.cpp	Wed Apr 06 13:17:33 2016 +0200
@@ -52,6 +52,26 @@
 	}
 };
 
+TEST_F(TestImage, size)
+{
+	try {
+		auto ret = duk::pevalString(m_ctx,
+			"i = new Malikania.Image('images/smiley.png');"
+			"w = i.size.width;"
+			"h = i.size.height;"
+		);
+
+		if (ret != 0) {
+			throw duk::error(m_ctx, -1);
+		}
+
+		ASSERT_EQ(32, duk::getGlobal<int>(m_ctx, "w"));
+		ASSERT_EQ(32, duk::getGlobal<int>(m_ctx, "h"));
+	} catch (const std::exception &ex) {
+		FAIL() << ex.what();
+	}
+}
+
 TEST_F(TestImage, basic)
 {
 	try {