private void SaveImageToCameraRoll(int imageHandle, String imageName, Resource imageResource) { MediaLibrary library = new MediaLibrary(); MemoryStream targetStream = new MemoryStream(); int mediaType = MoSync.Constants.MA_MEDIA_TYPE_IMAGE; int mediaHandle = imageHandle; int eventReturnCode = MoSync.Constants.MA_MEDIA_RES_OK; try { WriteableBitmap data = (WriteableBitmap)imageResource.GetInternalObject(); data.SaveJpeg(targetStream, data.PixelWidth, data.PixelHeight, 0, 100); data = null; library.SavePictureToCameraRoll(imageName, targetStream.GetBuffer()).Dispose(); } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.ToString()); eventReturnCode = MoSync.Constants.MA_MEDIA_RES_IMAGE_EXPORT_FAILED; } finally { library.Dispose(); targetStream.Dispose(); PostMediaEvent(mediaType, mediaHandle, eventReturnCode); } }
public void Init(Syscalls syscalls, Core core, Runtime runtime) { PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual; double screenWidth = System.Windows.Application.Current.Host.Content.ActualWidth; double screenHeight = System.Windows.Application.Current.Host.Content.ActualHeight; if ((int)screenHeight == 0) { throw new Exception("screenHeight"); } PhoneApplicationPage mainPage = (PhoneApplicationPage)frame.Content; Image mainImage = new Image(); mainPage.Width = screenWidth; mainPage.Height = screenHeight; mainImage.Width = screenWidth; mainImage.Height = screenHeight; mainPage.Content = mainImage; mClipRect.X = 0.0; mClipRect.Y = 0.0; mClipRect.Width = screenWidth; mClipRect.Height = screenHeight; // no apparent effect on memory leaks. runtime.RegisterCleaner(delegate() { MoSync.Util.RunActionOnMainThreadSync(() => { mainPage.Content = null; }); }); mBackBuffer = new WriteableBitmap( (int)screenWidth, (int)screenHeight); mFrontBuffer = new WriteableBitmap( (int)screenWidth, (int)screenHeight); mainImage.Source = mFrontBuffer; mCurrentDrawTarget = mBackBuffer; mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff, (byte)(mCurrentColor >> 16), (byte)(mCurrentColor >> 8), (byte)(mCurrentColor)); syscalls.maSetColor = delegate(int rgb) { int oldColor = (int)mCurrentColor; mCurrentColor = 0xff000000 | (uint)(rgb & 0xffffff); mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff, (byte)(mCurrentColor >> 16), (byte)(mCurrentColor >> 8), (byte)(mCurrentColor)); return(oldColor & 0xffffff); }; syscalls.maSetClipRect = delegate(int x, int y, int w, int h) { mClipRect.X = x; mClipRect.Y = y; mClipRect.Width = w; mClipRect.Height = h; }; syscalls.maGetClipRect = delegate(int cliprect) { Memory mem = core.GetDataMemory(); mem.WriteInt32(cliprect + MoSync.Struct.MARect.left, (int)mClipRect.X); mem.WriteInt32(cliprect + MoSync.Struct.MARect.top, (int)mClipRect.Y); mem.WriteInt32(cliprect + MoSync.Struct.MARect.width, (int)mClipRect.Width); mem.WriteInt32(cliprect + MoSync.Struct.MARect.height, (int)mClipRect.Height); }; syscalls.maPlot = delegate(int x, int y) { mCurrentDrawTarget.SetPixel(x, y, (int)mCurrentColor); }; syscalls.maUpdateScreen = delegate() { System.Array.Copy(mBackBuffer.Pixels, mFrontBuffer.Pixels, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight); InvalidateWriteableBitmapOnMainThread(mFrontBuffer); }; syscalls.maFillRect = delegate(int x, int y, int w, int h) { mCurrentDrawTarget.FillRectangle(x, y, x + w, y + h, (int)mCurrentColor); }; syscalls.maLine = delegate(int x1, int y1, int x2, int y2) { GraphicsUtil.Point p1 = new GraphicsUtil.Point(x1, y1); GraphicsUtil.Point p2 = new GraphicsUtil.Point(x2, y2); if (!GraphicsUtil.ClipLine(p1, p2, (int)mClipRect.X, (int)(mClipRect.X + mClipRect.Width), (int)mClipRect.Y, (int)(mClipRect.Y + mClipRect.Height))) { return; } mCurrentDrawTarget.DrawLine((int)p1.x, (int)p1.y, (int)p2.x, (int)p2.y, (int)mCurrentColor); }; TextBlock textBlock = new TextBlock(); textBlock.FontSize = mCurrentFontSize; syscalls.maDrawText = delegate(int left, int top, int str) { String text = core.GetDataMemory().ReadStringAtAddress(str); if (text.Length == 0) { return; } MoSync.Util.RunActionOnMainThreadSync(() => { textBlock.Text = text; textBlock.Foreground = new SolidColorBrush(mCurrentWindowsColor); WriteableBitmap b = new WriteableBitmap(textBlock, null); mCurrentDrawTarget.Blit(new Rect(left, top, b.PixelWidth, b.PixelHeight), b, new Rect(0, 0, b.PixelWidth, b.PixelHeight)); }); }; syscalls.maGetTextSize = delegate(int str) { String text = core.GetDataMemory().ReadStringAtAddress(str); int textWidth = 0; int textHeight = 0; MoSync.Util.RunActionOnMainThreadSync(() => { textBlock.Text = text; textWidth = (int)textBlock.ActualWidth; textHeight = (int)textBlock.ActualHeight; }); return(MoSync.Util.CreateExtent(textWidth, textHeight)); }; syscalls.maDrawTextW = delegate(int left, int top, int str) { String text = core.GetDataMemory().ReadWStringAtAddress(str); if (text.Length == 0) { return; } MoSync.Util.RunActionOnMainThreadSync(() => { textBlock.Text = text; textBlock.Foreground = new SolidColorBrush(mCurrentWindowsColor); WriteableBitmap b = new WriteableBitmap(textBlock, null); Rect dstRect = new Rect(left, top, b.PixelWidth, b.PixelHeight); Rect srcRect = new Rect(0, 0, b.PixelWidth, b.PixelHeight); // cliprect.. Rect clipRect = new Rect(0, 0, mBackBuffer.PixelWidth, mBackBuffer.PixelHeight); clipRect.Intersect(dstRect); if (clipRect.IsEmpty == true) { return; } mCurrentDrawTarget.Blit(dstRect, b, srcRect); }); }; syscalls.maGetTextSizeW = delegate(int str) { String text = core.GetDataMemory().ReadWStringAtAddress(str); int textWidth = 0; int textHeight = 0; MoSync.Util.RunActionOnMainThreadSync(() => { textBlock.Text = text; textWidth = (int)textBlock.ActualWidth; textHeight = (int)textBlock.ActualHeight; }); return(MoSync.Util.CreateExtent(textWidth, textHeight)); }; syscalls.maFillTriangleFan = delegate(int points, int count) { int[] newPoints = new int[count * 2 + 2]; for (int i = 0; i < count; i++) { newPoints[i * 2 + 0] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.x); newPoints[i * 2 + 1] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.y); } newPoints[count * 2 + 0] = core.GetDataMemory().ReadInt32(points + MoSync.Struct.MAPoint2d.x); newPoints[count * 2 + 1] = core.GetDataMemory().ReadInt32(points + MoSync.Struct.MAPoint2d.y); mCurrentDrawTarget.FillPolygon(newPoints, (int)mCurrentColor); }; syscalls.maFillTriangleStrip = delegate(int points, int count) { int[] xcoords = new int[count]; int[] ycoords = new int[count]; for (int i = 0; i < count; i++) { xcoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.x); ycoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.y); } for (int i = 2; i < count; i++) { mCurrentDrawTarget.FillTriangle( xcoords[i - 2], ycoords[i - 2], xcoords[i - 1], ycoords[i - 1], xcoords[i - 0], ycoords[i - 0], (int)mCurrentColor); } }; syscalls.maSetDrawTarget = delegate(int drawTarget) { int oldDrawTarget = mCurrentDrawTargetIndex; if (drawTarget == mCurrentDrawTargetIndex) { return(oldDrawTarget); } if (drawTarget == MoSync.Constants.HANDLE_SCREEN) { mCurrentDrawTarget = mBackBuffer; mCurrentDrawTargetIndex = drawTarget; return(oldDrawTarget); } Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, drawTarget); mCurrentDrawTarget = (WriteableBitmap)res.GetInternalObject(); mCurrentDrawTargetIndex = drawTarget; return(oldDrawTarget); }; syscalls.maGetScrSize = delegate() { return(MoSync.Util.CreateExtent(mBackBuffer.PixelWidth, mBackBuffer.PixelHeight)); }; syscalls.maGetImageSize = delegate(int handle) { Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, handle); BitmapSource src = (BitmapSource)res.GetInternalObject(); int w = 0, h = 0; MoSync.Util.RunActionOnMainThreadSync(() => { w = src.PixelWidth; h = src.PixelHeight; }); return(MoSync.Util.CreateExtent(w, h)); }; syscalls.maDrawImage = delegate(int image, int left, int top) { Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image); WriteableBitmap src = (WriteableBitmap)res.GetInternalObject(); Rect srcRect = new Rect(0, 0, src.PixelWidth, src.PixelHeight); Rect dstRect = new Rect(left, top, src.PixelWidth, src.PixelHeight); mCurrentDrawTarget.Blit(dstRect, src, srcRect, WriteableBitmapExtensions.BlendMode.Alpha); }; syscalls.maDrawImageRegion = delegate(int image, int srcRectPtr, int dstPointPtr, int transformMode) { Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image); WriteableBitmap src = (WriteableBitmap)res.GetInternalObject(); Memory dataMemory = core.GetDataMemory(); int srcRectX = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.left); int srcRectY = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.top); int srcRectW = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.width); int srcRectH = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.height); int dstPointX = dataMemory.ReadInt32(dstPointPtr + MoSync.Struct.MAPoint2d.x); int dstPointY = dataMemory.ReadInt32(dstPointPtr + MoSync.Struct.MAPoint2d.y); Rect srcRect = new Rect(srcRectX, srcRectY, srcRectW, srcRectH); Rect dstRect = new Rect(dstPointX, dstPointY, srcRectW, srcRectH); // mCurrentDrawTarget.Blit(dstRect, src, srcRect, WriteableBitmapExtensions.BlendMode.Alpha); GraphicsUtil.DrawImageRegion(mCurrentDrawTarget, dstPointX, dstPointY, srcRect, src, transformMode); }; syscalls.maCreateDrawableImage = delegate(int placeholder, int width, int height) { Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, placeholder); res.SetResourceType(MoSync.Constants.RT_IMAGE); WriteableBitmap bitmap = null; MoSync.Util.RunActionOnMainThreadSync(() => { bitmap = new WriteableBitmap(width, height); }); if (bitmap == null) { return(MoSync.Constants.RES_OUT_OF_MEMORY); } res.SetInternalObject(bitmap); return(MoSync.Constants.RES_OK); }; syscalls.maCreateImageRaw = delegate(int _placeholder, int _src, int _size, int _alpha) { int width = MoSync.Util.ExtentX(_size); int height = MoSync.Util.ExtentY(_size); WriteableBitmap bitmap = null; MoSync.Util.RunActionOnMainThreadSync(() => { bitmap = new WriteableBitmap(width, height); }); //core.GetDataMemory().ReadIntegers(bitmap.Pixels, _src, width * height); bitmap.FromByteArray(core.GetDataMemory().GetData(), _src, width * height * 4); if (_alpha == 0) { int[] pixels = bitmap.Pixels; int numPixels = width * height; for (int i = 0; i < numPixels; i++) { pixels[i] = (int)((uint)pixels[i] | 0xff000000); } } runtime.SetResource(_placeholder, new Resource( bitmap, MoSync.Constants.RT_IMAGE ) ); return(MoSync.Constants.RES_OK); }; syscalls.maDrawRGB = delegate(int _dstPoint, int _src, int _srcRect, int _scanlength) { Memory dataMemory = core.GetDataMemory(); int dstX = dataMemory.ReadInt32(_dstPoint + MoSync.Struct.MAPoint2d.x); int dstY = dataMemory.ReadInt32(_dstPoint + MoSync.Struct.MAPoint2d.y); int srcRectX = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.left); int srcRectY = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.top); int srcRectW = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.width); int srcRectH = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.height); int[] pixels = mCurrentDrawTarget.Pixels; // todo: clipRect _scanlength *= 4; // sizeof(int) for (int h = 0; h < srcRectH; h++) { int pixelIndex = dstY * mCurrentDrawTarget.PixelWidth + dstX; int address = _src + (srcRectY + h) * _scanlength; for (int w = 0; w < srcRectW; w++) { uint srcPixel = dataMemory.ReadUInt32(address); uint dstPixel = (uint)pixels[pixelIndex]; uint srcPixelR = (srcPixel & 0x00ff0000) >> 16; uint srcPixelG = (srcPixel & 0x0000ff00) >> 8; uint srcPixelB = (srcPixel & 0x000000ff) >> 0; uint srcPixelA = (srcPixel & 0xff000000) >> 24; uint dstPixelR = (dstPixel & 0x00ff0000) >> 16; uint dstPixelG = (dstPixel & 0x0000ff00) >> 8; uint dstPixelB = (dstPixel & 0x000000ff) >> 0; uint dstPixelA = (dstPixel & 0xff000000) >> 24; dstPixelR += ((srcPixelR - dstPixelR) * srcPixelA) / 255; dstPixelG += ((srcPixelG - dstPixelG) * srcPixelA) / 255; dstPixelB += ((srcPixelB - dstPixelB) * srcPixelA) / 255; dstPixel = (dstPixelA << 24) | (dstPixelR << 16) | (dstPixelG << 8) | (dstPixelB); pixels[pixelIndex] = (int)dstPixel; address += 4; pixelIndex++; } dstY++; } }; syscalls.maGetImageData = delegate(int _image, int _dst, int _srcRect, int _scanlength) { Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, _image); WriteableBitmap src = (WriteableBitmap)res.GetInternalObject(); Memory dataMemory = core.GetDataMemory(); int srcRectX = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.left); int srcRectY = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.top); int srcRectW = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.width); int srcRectH = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.height); int lineDst = _dst; byte[] data = src.ToByteArray(srcRectY * src.PixelWidth, srcRectH * src.PixelWidth); byte[] coreArray = dataMemory.GetData(); for (int y = 0; y < srcRectH; y++) { System.Array.Copy(data, y * src.PixelWidth * 4, coreArray, lineDst, src.PixelWidth * 4); lineDst += _scanlength * 4; } }; syscalls.maCreateImageFromData = delegate(int _placeholder, int _data, int _offset, int _size) { Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data); Memory mem = (Memory)res.GetInternalObject(); Stream s = mem.GetStream(_offset, _size); WriteableBitmap bitmap = MoSync.Util.CreateWriteableBitmapFromStream(s); s.Close(); runtime.SetResource( _placeholder, new Resource( bitmap, MoSync.Constants.RT_IMAGE ) ); return(MoSync.Constants.RES_OK); }; }
public void Init(Ioctls ioctls, Core core, Runtime runtime) { mRuntime = runtime; ioctls.maOpenGLInitFullscreen = delegate(int _glApi) { if (_glApi != MoSync.Constants.MA_GL_API_GL1) { return(MoSync.Constants.MA_GL_INIT_RES_ERROR); } Syscalls syscalls = runtime.GetSyscalls(); mOldUpdateScreenImplementation = syscalls.maUpdateScreen; syscalls.maUpdateScreen = delegate() { if (maUpdateScreenAction != null) { maUpdateScreenAction(); } }; MoSync.Util.RunActionOnMainThreadSync(() => { // GamePage must always exist for fullscreen apps to work. if (((PhoneApplicationFrame)Application.Current.RootVisual).Navigate(new Uri("/GamePage.xaml", UriKind.Relative))) { } }); return(MoSync.Constants.MA_GL_INIT_RES_OK); }; ioctls.maOpenGLCloseFullscreen = delegate() { return(MoSync.Constants.MA_GL_INIT_RES_OK); }; ioctls.maOpenGLTexImage2D = delegate(int _res) { Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, _res); WriteableBitmap src = (WriteableBitmap)res.GetInternalObject(); byte[] pixels = src.ToByteArray(); mGL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, src.PixelWidth, src.PixelHeight, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pixels, 0); return(MoSync.Constants.MA_GL_TEX_IMAGE_2D_OK); }; ioctls.maOpenGLTexSubImage2D = delegate(int _res) { Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, _res); WriteableBitmap src = (WriteableBitmap)res.GetInternalObject(); byte[] pixels = src.ToByteArray(); mGL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, src.PixelWidth, src.PixelHeight, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pixels, 0); return(MoSync.Constants.MA_GL_TEX_IMAGE_2D_OK); }; ioctls.glViewport = delegate(int _x, int _y, int _w, int _h) { mGL.glViewport(_x, _y, _w, _h); return(0); }; ioctls.glGetError = delegate() { int err = mGL.glGetError(); if (err != GL.GL_NO_ERROR) { //int a = 2; //err = GL.GL_NO_ERROR; } return(err); }; ioctls.glGetStringHandle = delegate(int _name) { String str = mGL.glGetString(_name); char[] data = str.ToCharArray(); byte[] bytes = new byte[data.Length + 1]; bytes[data.Length] = 0; for (int i = 0; i < data.Length; i++) { bytes[i] = (byte)data[i]; } return(runtime.AddResource(new Resource(new System.IO.MemoryStream(bytes), MoSync.Constants.RT_BINARY, true))); }; ioctls.glMatrixMode = delegate(int mode) { mGL.glMatrixMode(mode); return(0); }; ioctls.glPushMatrix = delegate() { mGL.glPushMatrix(); return(0); }; ioctls.glPopMatrix = delegate() { mGL.glPopMatrix(); return(0); }; ioctls.glLoadIdentity = delegate() { mGL.glLoadIdentity(); return(0); }; ioctls.glBlendFunc = delegate(int sfactor, int dfactor) { mGL.glBlendFunc(sfactor, dfactor); return(0); }; ioctls.glAlphaFunc = delegate(int func, float _ref) { return(0); }; ioctls.glAlphaFuncx = delegate(int func, int _ref) { return(0); }; ioctls.glDepthFunc = delegate(int _func) { mGL.glDepthFunc(_func); return(0); }; ioctls.glDepthMask = delegate(int _flag) { mGL.glDepthMask(_flag); return(0); }; ioctls.glClearColor = delegate(float r, float g, float b, float a) { mGL.glClearColor(r, g, b, a); return(0); }; ioctls.glClearColorx = delegate(int r, int g, int b, int a) { mGL.glClearColorx(r, g, b, a); return(0); }; ioctls.glColor4f = delegate(float r, float g, float b, float a) { mGL.glColor4f(r, g, b, a); return(0); }; ioctls.glColor4x = delegate(int r, int g, int b, int a) { mGL.glColor4x(r, g, b, a); return(0); }; ioctls.glColor4ub = delegate(int r, int g, int b, int a) { mGL.glColor4ub(r, g, b, a); return(0); }; ioctls.glColor4f = delegate(float r, float g, float b, float a) { mGL.glColor4f(r, g, b, a); return(0); }; ioctls.glClear = delegate(int _mask) { mGL.glClear(_mask); return(0); }; ioctls.glRotatef = delegate(float angle, float x, float y, float z) { mGL.glRotatef(angle, x, y, z); return(0); }; ioctls.glRotatex = delegate(int angle, int x, int y, int z) { mGL.glRotatex(angle, x, y, z); return(0); }; ioctls.glTranslatef = delegate(float x, float y, float z) { mGL.glTranslatef(x, y, z); return(0); }; ioctls.glTranslatex = delegate(int x, int y, int z) { mGL.glTranslatex(x, y, z); return(0); }; ioctls.glScalef = delegate(float x, float y, float z) { mGL.glScalef(x, y, z); return(0); }; ioctls.glScalex = delegate(int x, int y, int z) { mGL.glScalex(x, y, z); return(0); }; ioctls.glMultMatrixf = delegate(int _matrix) { #if !LIB mGL.glMultMatrixf(core.GetDataMemory().GetData(), _matrix); return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE);; #endif }; ioctls.glMultMatrixx = delegate(int _matrix) { #if !LIB mGL.glMultMatrixx(core.GetDataMemory().GetData(), _matrix); return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE);; #endif }; ioctls.glEnableClientState = delegate(int _array) { mGL.glEnableClientState(_array); return(0); }; ioctls.glDisableClientState = delegate(int _array) { mGL.glDisableClientState(_array); return(0); }; ioctls.glTexCoordPointer = delegate(int _size, int _type, int _stride, int _pointer) { #if !LIB mGL.glTexCoordPointer(_size, _type, _stride, core.GetDataMemory().GetData(), _pointer); return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE);; #endif }; ioctls.glVertexPointer = delegate(int _size, int _type, int _stride, int _pointer) { #if !LIB mGL.glVertexPointer(_size, _type, _stride, core.GetDataMemory().GetData(), _pointer); return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE);; #endif }; ioctls.glColorPointer = delegate(int _size, int _type, int _stride, int _pointer) { #if !LIB mGL.glColorPointer(_size, _type, _stride, core.GetDataMemory().GetData(), _pointer); return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE);; #endif }; ioctls.glNormalPointer = delegate(int _type, int _stride, int _pointer) { #if !LIB mGL.glNormalPointer(_type, _stride, core.GetDataMemory().GetData(), _pointer); return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE);; #endif }; ioctls.glDrawArrays = delegate(int _mode, int _first, int _count) { mGL.glDrawArrays(_mode, _first, _count); return(0); }; ioctls.glDrawElements = delegate(int _mode, int _count, int _type, int _indecies) { #if !LIB mGL.glDrawElements(_mode, _count, _type, core.GetDataMemory().GetData(), _indecies); return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE);; #endif }; ioctls.glEnable = delegate(int _e) { mGL.glEnable(_e); return(0); }; ioctls.glDisable = delegate(int _e) { mGL.glDisable(_e); return(0); }; ioctls.glFrustumf = delegate(float _left, float _right, float _bottom, float _top, float _znear, float _zfar) { mGL.glFrustumf(_left, _right, _bottom, _top, _znear, _zfar); return(0); }; ioctls.glOrthof = delegate(float _left, float _right, float _bottom, float _top, float _znear, float _zfar) { mGL.glOrthof(_left, _right, _bottom, _top, _znear, _zfar); return(0); }; ioctls.glFrustumx = delegate(int _left, int _right, int _bottom, int _top, int _znear, int _zfar) { mGL.glFrustumx(_left, _right, _bottom, _top, _znear, _zfar); return(0); }; ioctls.glOrthox = delegate(int _left, int _right, int _bottom, int _top, int _znear, int _zfar) { mGL.glOrthox(_left, _right, _bottom, _top, _znear, _zfar); return(0); }; ioctls.glFlush = delegate() { return(0); }; ioctls.glFinish = delegate() { mGL.glFinish(); return(0); }; ioctls.glGenTextures = delegate(int _n, int _textures) { int[] handles = new int[_n]; mGL.glGenTextures(_n, handles); for (int i = 0; i < _n; i++) { core.GetDataMemory().WriteInt32(_textures + i * 4, handles[i]); } return(0); }; ioctls.glBindTexture = delegate(int _target, int _texture) { mGL.glBindTexture(_target, _texture); return(0); }; ioctls.glTexImage2D = delegate(int _target, int _level, int _internalformat, int _width, int _height, int _border, int _format, int _type, int _pixels) { #if !LIB if (_pixels == 0) { mGL.glTexImage2D(_target, _level, _internalformat, _width, _height, _border, _format, _type, null, _pixels); } else { mGL.glTexImage2D(_target, _level, _internalformat, _width, _height, _border, _format, _type, core.GetDataMemory().GetData(), _pixels); } return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE);; #endif }; ioctls.glDeleteTextures = delegate(int _n, int _textures) { int[] textures = new int[_n]; for (int i = 0; i < _n; i++) { textures[i] = core.GetDataMemory().ReadInt32(_textures + i * 4); } mGL.glDeleteTextures(textures); return(0); }; ioctls.glTexSubImage2D = delegate(int _target, int _level, int _xofs, int _yofs, int _width, int _height, int _format, int _type, int _pixels) { #if !LIB mGL.glTexSubImage2D(_target, _level, _xofs, _yofs, _width, _height, _format, _type, core.GetDataMemory().GetData(), _pixels); return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE);; #endif }; ioctls.glCompressedTexImage2D = delegate(int _target, int _level, int _internalformat, int _width, int _height, int _border, int _imageSize, int _data) { return(0); }; ioctls.glCompressedTexSubImage2D = delegate(int _target, int _level, int _xofs, int _yofs, int _width, int _height, int _format, int _imageSize, int _data) { return(0); }; ioctls.glGenBuffers = delegate(int _n, int _buffers) { int[] handles = new int[_n]; mGL.glGenBuffers(_n, handles); for (int i = 0; i < _n; i++) { core.GetDataMemory().WriteInt32(_buffers + i * 4, handles[i]); } return(0); }; ioctls.glBindBuffer = delegate(int _target, int _buffer) { mGL.glBindBuffer(_target, _buffer); return(0); }; ioctls.glBufferData = delegate(int _target, int _size, int _data, int _usage) { #if !LIB mGL.glBufferData(_target, _size, core.GetDataMemory().GetData(), _data, _usage); return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE);; #endif }; ioctls.glBufferSubData = delegate(int _target, int _offset, int _size, int _data) { #if !LIB mGL.glBufferSubData(_target, _offset, _size, core.GetDataMemory().GetData(), _data); return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE); #endif }; ioctls.glMaterialf = delegate(int face, int pname, float value) { mGL.glMaterialf(face, pname, value); return(0); }; ioctls.glMaterialx = delegate(int face, int pname, int value) { mGL.glMaterialx(face, pname, value); return(0); }; ioctls.glMaterialfv = delegate(int face, int pname, int data) { #if !LIB mGL.glMaterialfv(face, pname, core.GetDataMemory().GetData(), data); return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE);; #endif }; ioctls.glMaterialxv = delegate(int face, int pname, int data) { #if !LIB mGL.glMaterialxv(face, pname, core.GetDataMemory().GetData(), data); return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE);; #endif }; ioctls.glLightf = delegate(int _light, int _pname, float _param) { mGL.glLightf(_light, _pname, _param); return(0); }; ioctls.glLightx = delegate(int _light, int _pname, int _param) { mGL.glLightx(_light, _pname, _param); return(0); }; ioctls.glLightfv = delegate(int _light, int _pname, int _pointer) { #if !LIB mGL.glLightfv(_light, _pname, core.GetDataMemory().GetData(), _pointer); return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE);; #endif }; ioctls.glLightxv = delegate(int _light, int _pname, int _pointer) { #if !LIB mGL.glLightxv(_light, _pname, core.GetDataMemory().GetData(), _pointer); return(0); #else return(MoSync.Constants.IOCTL_UNAVAILABLE);; #endif }; ioctls.glShadeModel = delegate(int _mode) { mGL.glShadeModel(_mode); return(0); }; }
public void Init(Ioctls ioctls, Core core, Runtime runtime) { #if false mAudioInstanceUpdater = new AudioInstanceUpdater(mAudioInstances); Thread thread = new Thread(new ThreadStart(mAudioInstanceUpdater.Loop)); thread.Start(); #endif ioctls.maAudioDataCreateFromURL = delegate(int _mime, int _url, int _flags) { int ret = MoSync.Constants.MA_AUDIO_ERR_GENERIC; try { String url = core.GetDataMemory().ReadStringAtAddress(_url); String mime = core.GetDataMemory().ReadStringAtAddress(_mime); bool shouldStream = (_flags & MoSync.Constants.MA_AUDIO_DATA_STREAM) != 0; IAudioData ad; if (mime == "audio/mpeg") { ad = Mp3Audio.FromUrlOrFilePath(url, shouldStream); } else { ad = Audio.FromUrlOrFilePath(url, shouldStream); } lock (mAudioData) { mAudioData.Add(ad); ret = mAudioData.Count - 1; } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(ret); }; ioctls.maAudioDataCreateFromResource = delegate(int _mime, int _data, int _offset, int _length, int _flags) { int ret = MoSync.Constants.MA_AUDIO_ERR_GENERIC; try { Resource audiores = runtime.GetResource(MoSync.Constants.RT_BINARY, _data); BoundedStream s = new BoundedStream((Stream)audiores.GetInternalObject(), _offset, _length); String mime = core.GetDataMemory().ReadStringAtAddress(_mime); IAudioData ad; if (mime == "audio/mpeg") { ad = Mp3Audio.FromStream(s); } else { ad = Audio.FromStream(s, (_flags & MoSync.Constants.MA_AUDIO_DATA_STREAM) != 0); } lock (mAudioData) { mAudioData.Add(ad); ret = mAudioData.Count - 1; } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(ret); }; ioctls.maAudioDataDestroy = delegate(int _audioData) { try { lock (mAudioData) { IAudioData ad = mAudioData[_audioData]; ad.Dispose(); mAudioData[_audioData] = null; } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(MoSync.Constants.MA_AUDIO_ERR_OK); }; ioctls.maAudioPrepare = delegate(int _audioInstance, int async) { try { lock (mAudioInstances) { IAudioInstance ad = mAudioInstances[_audioInstance]; if (async == 0) { ad.Prepare(null); } else { ad.Prepare(() => { // Send initialized event. MoSync.Memory eventData = new MoSync.Memory(8); eventData.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_AUDIO_PREPARED); eventData.WriteInt32(MoSync.Struct.MAEvent.audioInstance, _audioInstance); runtime.PostEvent(new Event(eventData)); } ); } } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(MoSync.Constants.MA_AUDIO_ERR_OK); }; ioctls.maAudioInstanceCreate = delegate(int _audioData) { int ret = MoSync.Constants.MA_AUDIO_ERR_GENERIC; try { lock (mAudioInstances) { IAudioData ad = mAudioData[_audioData]; mAudioInstances.Add(ad.CreateInstance()); ret = mAudioInstances.Count - 1; } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(ret); }; ioctls.maAudioInstanceCreateDynamic = delegate(int _sampleRate, int _numChannels, int _bufferSize) { int ret = MoSync.Constants.MA_AUDIO_ERR_GENERIC; try { lock (mAudioInstances) { AudioInstanceDynamic aid = Audio.CreateDynamic(_sampleRate, _numChannels, _bufferSize); mAudioInstances.Add(aid); ret = mAudioInstances.Count - 1; aid.SetOnBufferNeededCallback(() => { // Send initialized event. MoSync.Memory eventData = new MoSync.Memory(8); eventData.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_AUDIO_COMPLETED); eventData.WriteInt32(MoSync.Struct.MAEvent.audioInstance, ret); runtime.PostEvent(new Event(eventData)); }); } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(ret); }; ioctls.maAudioGetPendingBufferCount = delegate(int _instance) { int ret = MoSync.Constants.MA_AUDIO_ERR_GENERIC; try { lock (mAudioInstances) { AudioInstanceDynamic ai = (AudioInstanceDynamic)mAudioInstances[_instance]; ret = ai.GetPendingBufferCount(); } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(ret); }; ioctls.maAudioSubmitBuffer = delegate(int _instance, int _pointer, int _numBytes) { try { lock (mAudioInstances) { AudioInstanceDynamic ai = (AudioInstanceDynamic)mAudioInstances[_instance]; ai.SubmitBuffer(core.GetDataMemory().GetData(), _pointer, _numBytes); } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(MoSync.Constants.MA_AUDIO_ERR_OK); }; ioctls.maAudioInstanceDestroy = delegate(int _audioInstance) { try { lock (mAudioInstances) { IAudioInstance ai = mAudioInstances[_audioInstance]; ai.Dispose(); mAudioInstances[_audioInstance] = null; } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(MoSync.Constants.MA_AUDIO_ERR_OK); }; ioctls.maAudioPlay = delegate(int _audioInstance) { try { lock (mAudioInstances) { IAudioInstance ai = mAudioInstances[_audioInstance]; ai.Play(); } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(MoSync.Constants.MA_AUDIO_ERR_OK); }; ioctls.maAudioStop = delegate(int _audioInstance) { try { lock (mAudioInstances) { IAudioInstance ai = mAudioInstances[_audioInstance]; ai.Stop(); } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(MoSync.Constants.MA_AUDIO_ERR_OK); }; ioctls.maAudioPause = delegate(int _audioInstance) { try { lock (mAudioInstances) { IAudioInstance ai = mAudioInstances[_audioInstance]; ai.Pause(); } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(MoSync.Constants.MA_AUDIO_ERR_OK); }; ioctls.maAudioSetNumberOfLoops = delegate(int _audioInstance, int loops) { try { lock (mAudioInstances) { IAudioInstance ai = mAudioInstances[_audioInstance]; ai.SetNumberOfLoops(loops); } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(MoSync.Constants.MA_AUDIO_ERR_OK); }; // SoundEffectInstances nor the MediaPlayer doesn't support setting position, // however we can make a special case where the sound is reset if _milliseconds equals to zero. // We could implement a better SoundEffectInstance using DynamicSoundEffectInstance // parsing wavefiles ourselves.. But that would require some work. ioctls.maAudioSetPosition = delegate(int _audioInstance, int _milliseconds) { try { lock (mAudioInstances) { IAudioInstance ai = mAudioInstances[_audioInstance]; ai.SetPosition(_milliseconds); } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(MoSync.Constants.MA_AUDIO_ERR_OK); }; // SoundEffectInstances doesnt support getting the location of the sound // this of course could be approximated by saving a time stamp when the sound // starts to play, buuut no. ioctls.maAudioGetPosition = delegate(int _audioInstance) { int ret = MoSync.Constants.MA_AUDIO_ERR_OK; try { lock (mAudioInstances) { IAudioInstance ai = mAudioInstances[_audioInstance]; ret = ai.GetPosition(); } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(ret); }; ioctls.maAudioGetLength = delegate(int _audioInstance) { int ret = MoSync.Constants.MA_AUDIO_ERR_OK; try { lock (mAudioInstances) { IAudioInstance ai = mAudioInstances[_audioInstance]; ret = ai.GetLength(); } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(ret); }; ioctls.maAudioSetVolume = delegate(int _audioInstance, float volume) { try { lock (mAudioInstances) { IAudioInstance ai = mAudioInstances[_audioInstance]; ai.SetVolume(volume); } } catch (MoSync.Util.ReturnValueException rve) { return(rve.result); } catch (Exception) { return(MoSync.Constants.MA_AUDIO_ERR_GENERIC); } return(MoSync.Constants.MA_AUDIO_ERR_OK); }; }
public void Init(Syscalls syscalls, Core core, Runtime runtime) { runtime.RegisterCleaner(delegate() { foreach (KeyValuePair <int, Connection> p in mConnections) { p.Value.close(); } mConnections.Clear(); }); mResultHandler = delegate(int handle, int connOp, int result) { Memory evt = new Memory(4 * 4); evt.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_CONN); evt.WriteInt32(MoSync.Struct.MAEvent.conn.handle, handle); evt.WriteInt32(MoSync.Struct.MAEvent.conn.opType, connOp); evt.WriteInt32(MoSync.Struct.MAEvent.conn.result, result); runtime.PostEvent(new Event(evt)); }; syscalls.maConnect = delegate(int _url) { String url = core.GetDataMemory().ReadStringAtAddress(_url); //Util.Log("maConnect(" + url + ")\n"); if (url.StartsWith("btspp")) { return(MoSync.Constants.CONNERR_UNAVAILABLE); } Uri uri = new Uri(url); Connection c; if (uri.Scheme.Equals("socket")) { c = new SocketConnection(uri, mNextConnHandle); } else if (uri.Scheme.Equals("http") || uri.Scheme.Equals("https")) { c = new WebRequestConnection(uri, mNextConnHandle, MoSync.Constants.HTTP_GET); } else { return(MoSync.Constants.CONNERR_GENERIC); } c.connect(mResultHandler); mConnections.Add(mNextConnHandle, c); return(mNextConnHandle++); }; syscalls.maConnClose = delegate(int _conn) { Connection c = mConnections[_conn]; c.close(); mConnections.Remove(_conn); }; syscalls.maConnGetAddr = delegate(int _conn, int _addr) { if (_conn == MoSync.Constants.HANDLE_LOCAL) // unavailable { return(-1); } Connection c = mConnections[_conn]; return(c.getAddr(core.GetDataMemory(), _addr)); }; syscalls.maConnRead = delegate(int _conn, int _dst, int _size) { Connection c = mConnections[_conn]; c.recv(core.GetDataMemory().GetData(), _dst, _size, mResultHandler); }; DataDelegate dataDelegate = delegate(int _conn, int _data, CommDelegate cd) { Connection c = mConnections[_conn]; Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data); Stream s = (Stream)res.GetInternalObject(); runtime.SetResourceRaw(_data, Resource.Flux); MemoryStream mem = null; if (s.GetType() == typeof(MemoryStream)) { mem = (MemoryStream)s; } else { MoSync.Util.CriticalError("Only binaries (non-ubins) are allowed for maConn(Read/Write)(To/From)Data"); } cd(c, mem.GetBuffer(), delegate(int handle, int connOp, int result) { runtime.SetResourceRaw(_data, res); mResultHandler(handle, connOp, result); }); }; syscalls.maConnReadToData = delegate(int _conn, int _data, int _offset, int _size) { dataDelegate(_conn, _data, delegate(Connection c, byte[] buf, ResultHandler rh) { c.recv(buf, _offset, _size, rh); }); }; syscalls.maConnWrite = delegate(int _conn, int _src, int _size) { Connection c = mConnections[_conn]; c.write(core.GetDataMemory().GetData(), _src, _size, mResultHandler); }; syscalls.maConnWriteFromData = delegate(int _conn, int _data, int _offset, int _size) { dataDelegate(_conn, _data, delegate(Connection c, byte[] buf, ResultHandler rh) { c.write(buf, _offset, _size, rh); }); }; syscalls.maHttpCreate = delegate(int _url, int _method) { String url = core.GetDataMemory().ReadStringAtAddress(_url); //Util.Log("maHttpCreate(" + url + ")\n"); Uri uri = new Uri(url); WebRequestConnection c = new WebRequestConnection(uri, mNextConnHandle, _method); mConnections.Add(mNextConnHandle, c); return(mNextConnHandle++); }; syscalls.maHttpFinish = delegate(int _conn) { WebRequestConnection c = (WebRequestConnection)mConnections[_conn]; c.connect(delegate(int handle, int connOp, int result) { mResultHandler(handle, MoSync.Constants.CONNOP_FINISH, result); }); }; syscalls.maHttpSetRequestHeader = delegate(int _conn, int _key, int _value) { WebRequestConnection c = (WebRequestConnection)mConnections[_conn]; String key = core.GetDataMemory().ReadStringAtAddress(_key); String value = core.GetDataMemory().ReadStringAtAddress(_value); if (value.Length > 0) { c.setRequestHeader(key, value); } }; syscalls.maHttpGetResponseHeader = delegate(int _conn, int _key, int _buffer, int _bufSize) { WebRequestConnection c = (WebRequestConnection)mConnections[_conn]; String key = core.GetDataMemory().ReadStringAtAddress(_key); String value = c.getResponseHeader(key); if (value == null) { return(MoSync.Constants.CONNERR_NOHEADER); } if (value.Length + 1 <= _bufSize) { core.GetDataMemory().WriteStringAtAddress(_buffer, value, _bufSize); } return(value.Length); }; }
public void Init(Syscalls syscalls, Core core, Runtime runtime) { PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual; double screenWidth = System.Windows.Application.Current.Host.Content.ActualWidth; double screenHeight = System.Windows.Application.Current.Host.Content.ActualHeight; if ((int)screenHeight == 0) { throw new Exception("screenHeight"); } PhoneApplicationPage mainPage = (PhoneApplicationPage)frame.Content; mMainImage = new Image(); mainPage.Width = screenWidth; mainPage.Height = screenHeight; mMainImage.Width = screenWidth; mMainImage.Height = screenHeight; mainPage.Content = mMainImage; mClipRect.X = 0.0; mClipRect.Y = 0.0; mClipRect.Width = screenWidth; mClipRect.Height = screenHeight; // no apparent effect on memory leaks. runtime.RegisterCleaner(delegate() { MoSync.Util.RunActionOnMainThreadSync(() => { mainPage.Content = null; }); }); mBackBuffer = new WriteableBitmap( (int)screenWidth, (int)screenHeight); mFrontBuffer = new WriteableBitmap( (int)screenWidth, (int)screenHeight); mMainImage.Source = mFrontBuffer; // clear front and backbuffer. for (int i = 0; i < mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight; i++) { mBackBuffer.Pixels[i] = mBackBuffer.Pixels[i] = (int)(0xff << 24); } mCurrentDrawTarget = mBackBuffer; mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff, (byte)(mCurrentColor >> 16), (byte)(mCurrentColor >> 8), (byte)(mCurrentColor)); syscalls.maSetColor = delegate(int rgb) { int oldColor = (int)mCurrentColor; mCurrentColor = 0xff000000 | (uint)(rgb & 0xffffff); mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff, (byte)(mCurrentColor >> 16), (byte)(mCurrentColor >> 8), (byte)(mCurrentColor)); return(oldColor & 0xffffff); }; syscalls.maSetClipRect = delegate(int x, int y, int w, int h) { MoSync.GraphicsUtil.ClipRectangle( x, y, w, h, 0, 0, mCurrentDrawTarget.PixelWidth, mCurrentDrawTarget.PixelHeight, out x, out y, out w, out h); mClipRect.X = x; mClipRect.Y = y; mClipRect.Width = w; mClipRect.Height = h; }; syscalls.maGetClipRect = delegate(int cliprect) { #if !LIB Memory mem = core.GetDataMemory(); #else SystemMemory mem = core.GetDataMemory(); #endif mem.WriteInt32(cliprect + MoSync.Struct.MARect.left, (int)mClipRect.X); mem.WriteInt32(cliprect + MoSync.Struct.MARect.top, (int)mClipRect.Y); mem.WriteInt32(cliprect + MoSync.Struct.MARect.width, (int)mClipRect.Width); mem.WriteInt32(cliprect + MoSync.Struct.MARect.height, (int)mClipRect.Height); }; syscalls.maPlot = delegate(int x, int y) { mCurrentDrawTarget.SetPixel(x, y, (int)mCurrentColor); }; syscalls.maUpdateScreen = delegate() { //System.Array.Copy(mBackBuffer.Pixels, mFrontBuffer.Pixels, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight); System.Buffer.BlockCopy(mBackBuffer.Pixels, 0, mFrontBuffer.Pixels, 0, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight * 4); InvalidateWriteableBitmapOnMainThread(mFrontBuffer); }; syscalls.maFillRect = delegate(int x, int y, int w, int h) { // this function has a bug (it only fills one pixel less than the image.) //mCurrentDrawTarget.FillRectangle(x, y, x + w, y + h, (int)mCurrentColor); MoSync.GraphicsUtil.ClipRectangle( x, y, w, h, 0, 0, mCurrentDrawTarget.PixelWidth, mCurrentDrawTarget.PixelHeight, out x, out y, out w, out h); MoSync.GraphicsUtil.ClipRectangle( x, y, w, h, (int)mClipRect.X, (int)mClipRect.Y, (int)mClipRect.Width, (int)mClipRect.Height, out x, out y, out w, out h); if (w <= 0 || h <= 0) { return; } int index = x + y * mCurrentDrawTarget.PixelWidth; while (h-- != 0) { int width = w; while (width-- != 0) { mCurrentDrawTarget.Pixels[index] = (int)mCurrentColor; index++; } index += -w + mCurrentDrawTarget.PixelWidth; } }; syscalls.maLine = delegate(int x1, int y1, int x2, int y2) { GraphicsUtil.Point p1 = new GraphicsUtil.Point(x1, y1); GraphicsUtil.Point p2 = new GraphicsUtil.Point(x2, y2); if (!GraphicsUtil.ClipLine(p1, p2, (int)mClipRect.X, (int)(mClipRect.X + mClipRect.Width), (int)mClipRect.Y, (int)(mClipRect.Y + mClipRect.Height))) { return; } mCurrentDrawTarget.DrawLine((int)p1.x, (int)p1.y, (int)p2.x, (int)p2.y, (int)mCurrentColor); }; textBlock.FontSize = mCurrentFontSize; syscalls.maDrawText = delegate(int left, int top, int str) { String text = core.GetDataMemory().ReadStringAtAddress(str); if (text.Length == 0) { return; } DrawText(text, left, top); }; syscalls.maGetTextSize = delegate(int str) { String text = core.GetDataMemory().ReadStringAtAddress(str); int textWidth = 0; int textHeight = 0; GetTextSize(text, out textWidth, out textHeight); return(MoSync.Util.CreateExtent(textWidth, textHeight)); }; syscalls.maDrawTextW = delegate(int left, int top, int str) { String text = core.GetDataMemory().ReadWStringAtAddress(str); if (text.Length == 0) { return; } DrawText(text, left, top); }; syscalls.maGetTextSizeW = delegate(int str) { String text = core.GetDataMemory().ReadWStringAtAddress(str); int textWidth = 0; int textHeight = 0; GetTextSize(text, out textWidth, out textHeight); return(MoSync.Util.CreateExtent(textWidth, textHeight)); }; syscalls.maFillTriangleFan = delegate(int points, int count) { int[] newPoints = new int[count * 2 + 2]; for (int i = 0; i < count; i++) { newPoints[i * 2 + 0] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.x); newPoints[i * 2 + 1] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.y); } newPoints[count * 2 + 0] = core.GetDataMemory().ReadInt32(points + MoSync.Struct.MAPoint2d.x); newPoints[count * 2 + 1] = core.GetDataMemory().ReadInt32(points + MoSync.Struct.MAPoint2d.y); mCurrentDrawTarget.FillPolygon(newPoints, (int)mCurrentColor); }; syscalls.maFillTriangleStrip = delegate(int points, int count) { int[] xcoords = new int[count]; int[] ycoords = new int[count]; for (int i = 0; i < count; i++) { xcoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.x); ycoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.y); } for (int i = 2; i < count; i++) { mCurrentDrawTarget.FillTriangle( xcoords[i - 2], ycoords[i - 2], xcoords[i - 1], ycoords[i - 1], xcoords[i - 0], ycoords[i - 0], (int)mCurrentColor); } }; syscalls.maSetDrawTarget = delegate(int drawTarget) { int oldDrawTarget = mCurrentDrawTargetIndex; if (drawTarget == mCurrentDrawTargetIndex) { return(oldDrawTarget); } if (drawTarget == MoSync.Constants.HANDLE_SCREEN) { mCurrentDrawTarget = mBackBuffer; mCurrentDrawTargetIndex = drawTarget; return(oldDrawTarget); } Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, drawTarget); mCurrentDrawTarget = (WriteableBitmap)res.GetInternalObject(); mCurrentDrawTargetIndex = drawTarget; return(oldDrawTarget); }; syscalls.maGetScrSize = delegate() { int w = mBackBuffer.PixelWidth; int h = mBackBuffer.PixelHeight; MoSync.Util.RunActionOnMainThreadSync(() => { // if the orientation is landscape, the with and height should be swaped PhoneApplicationPage currentPage = (((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage); if (currentPage.Orientation == PageOrientation.Landscape || currentPage.Orientation == PageOrientation.LandscapeLeft || currentPage.Orientation == PageOrientation.LandscapeRight) { int aux = w; w = h; h = aux; } }); return(MoSync.Util.CreateExtent(w, h)); }; syscalls.maGetImageSize = delegate(int handle) { Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, handle); int w = 0, h = 0; #if !LIB BitmapSource src = (BitmapSource)res.GetInternalObject(); if (src == null) { MoSync.Util.CriticalError("maGetImageSize used with an invalid image resource."); } else { MoSync.Util.RunActionOnMainThreadSync(() => { w = src.PixelWidth; h = src.PixelHeight; }); } #else if (res.GetInternalObject() == null) { MoSync.Util.CriticalError("maGetImageSize used with an invalid image resource."); } else { MoSync.Util.RunActionOnMainThreadSync(() => { if (res.GetInternalObject() is Stream) { BitmapImage bi = new BitmapImage(); bi.SetSource((Stream)res.GetInternalObject()); w = bi.PixelWidth; h = bi.PixelHeight; } else if (res.GetInternalObject() is WriteableBitmap) { BitmapSource src = (BitmapSource)res.GetInternalObject(); w = src.PixelWidth; h = src.PixelHeight; } }); } #endif return(MoSync.Util.CreateExtent(w, h)); }; syscalls.maDrawImage = delegate(int image, int left, int top) { Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image); #if !LIB WriteableBitmap src = (WriteableBitmap)res.GetInternalObject(); #else Object src = null; MoSync.Util.RunActionOnMainThreadSync(() => { Object internalObj = res.GetInternalObject(); if (internalObj is Stream) { src = new WriteableBitmap(0, 0); (src as WriteableBitmap).SetSource((Stream)res.GetInternalObject()); } else if (internalObj is WriteableBitmap) { src = res.GetInternalObject(); } }); #endif Rect srcRect = new Rect(0, 0, (src as WriteableBitmap).PixelWidth, (src as WriteableBitmap).PixelHeight); Rect dstRect = new Rect(left, top, (src as WriteableBitmap).PixelWidth, (src as WriteableBitmap).PixelHeight); mCurrentDrawTarget.Blit(dstRect, (src as WriteableBitmap), srcRect, WriteableBitmapExtensions.BlendMode.Alpha); }; syscalls.maDrawImageRegion = delegate(int image, int srcRectPtr, int dstPointPtr, int transformMode) { Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image); #if !LIB WriteableBitmap src = (WriteableBitmap)res.GetInternalObject(); Memory dataMemory = core.GetDataMemory(); #else SystemMemory dataMemory = core.GetDataMemory(); Object src = null; MoSync.Util.RunActionOnMainThreadSync(() => { Object internalObj = res.GetInternalObject(); if (internalObj is Stream) { src = new WriteableBitmap(0, 0); (src as WriteableBitmap).SetSource((Stream)res.GetInternalObject()); } else if (internalObj is WriteableBitmap) { src = res.GetInternalObject(); } }); #endif int srcRectX = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.left); int srcRectY = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.top); int srcRectW = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.width); int srcRectH = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.height); int dstPointX = dataMemory.ReadInt32(dstPointPtr + MoSync.Struct.MAPoint2d.x); int dstPointY = dataMemory.ReadInt32(dstPointPtr + MoSync.Struct.MAPoint2d.y); Rect srcRect = new Rect(srcRectX, srcRectY, srcRectW, srcRectH); Rect dstRect = new Rect(dstPointX, dstPointY, srcRectW, srcRectH); GraphicsUtil.DrawImageRegion(mCurrentDrawTarget, dstPointX, dstPointY, srcRect, (src as WriteableBitmap), transformMode, mClipRect); }; syscalls.maCreateDrawableImage = delegate(int placeholder, int width, int height) { Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, placeholder); res.SetResourceType(MoSync.Constants.RT_IMAGE); WriteableBitmap bitmap = null; MoSync.Util.RunActionOnMainThreadSync(() => { bitmap = new WriteableBitmap(width, height); for (int i = 0; i < bitmap.PixelWidth * bitmap.PixelHeight; i++) { bitmap.Pixels[i] = (int)(0xff << 24); } }); if (bitmap == null) { return(MoSync.Constants.RES_OUT_OF_MEMORY); } res.SetInternalObject(bitmap); return(MoSync.Constants.RES_OK); }; syscalls.maCreateImageRaw = delegate(int _placeholder, int _src, int _size, int _alpha) { int width = MoSync.Util.ExtentX(_size); int height = MoSync.Util.ExtentY(_size); WriteableBitmap bitmap = null; MoSync.Util.RunActionOnMainThreadSync(() => { bitmap = new WriteableBitmap(width, height); }); //core.GetDataMemory().ReadIntegers(bitmap.Pixels, _src, width * height); #if !LIB bitmap.FromByteArray(core.GetDataMemory().GetData(), _src, width * height * 4); #else byte[] bytes = new byte[width * height * 4]; core.GetDataMemory().ReadBytes(bytes, _src, width * height * 4); bitmap.FromByteArray(bytes, 0, width * height * 4); // TO BE TESTED #endif if (_alpha == 0) { int[] pixels = bitmap.Pixels; int numPixels = width * height; for (int i = 0; i < numPixels; i++) { pixels[i] = (int)((uint)pixels[i] | 0xff000000); } } Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, _placeholder); res.SetInternalObject(bitmap); res.SetResourceType(MoSync.Constants.RT_IMAGE); return(MoSync.Constants.RES_OK); }; syscalls.maDrawRGB = delegate(int _dstPoint, int _src, int _srcRect, int _scanlength) { #if !LIB Memory dataMemory = core.GetDataMemory(); #else SystemMemory dataMemory = core.GetDataMemory(); #endif int dstX = dataMemory.ReadInt32(_dstPoint + MoSync.Struct.MAPoint2d.x); int dstY = dataMemory.ReadInt32(_dstPoint + MoSync.Struct.MAPoint2d.y); int srcRectX = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.left); int srcRectY = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.top); int srcRectW = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.width); int srcRectH = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.height); int[] pixels = mCurrentDrawTarget.Pixels; // todo: clipRect _scanlength *= 4; // sizeof(int) for (int h = 0; h < srcRectH; h++) { int pixelIndex = dstY * mCurrentDrawTarget.PixelWidth + dstX; int address = _src + (srcRectY + h) * _scanlength; for (int w = 0; w < srcRectW; w++) { uint srcPixel = dataMemory.ReadUInt32(address); uint dstPixel = (uint)pixels[pixelIndex]; uint srcPixelR = (srcPixel & 0x00ff0000) >> 16; uint srcPixelG = (srcPixel & 0x0000ff00) >> 8; uint srcPixelB = (srcPixel & 0x000000ff) >> 0; uint srcPixelA = (srcPixel & 0xff000000) >> 24; uint dstPixelR = (dstPixel & 0x00ff0000) >> 16; uint dstPixelG = (dstPixel & 0x0000ff00) >> 8; uint dstPixelB = (dstPixel & 0x000000ff) >> 0; uint dstPixelA = (dstPixel & 0xff000000) >> 24; dstPixelR += ((srcPixelR - dstPixelR) * srcPixelA) / 255; dstPixelG += ((srcPixelG - dstPixelG) * srcPixelA) / 255; dstPixelB += ((srcPixelB - dstPixelB) * srcPixelA) / 255; dstPixel = (dstPixelA << 24) | (dstPixelR << 16) | (dstPixelG << 8) | (dstPixelB); pixels[pixelIndex] = (int)dstPixel; address += 4; pixelIndex++; } dstY++; } }; syscalls.maGetImageData = delegate(int _image, int _dst, int _srcRect, int _scanlength) { Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, _image); WriteableBitmap src = (WriteableBitmap)res.GetInternalObject(); #if !LIB Memory dataMemory = core.GetDataMemory(); #else SystemMemory dataMemory = core.GetDataMemory(); #endif int srcRectX = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.left); int srcRectY = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.top); int srcRectW = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.width); int srcRectH = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.height); int lineDst = _dst; byte[] data = src.ToByteArray(srcRectY * src.PixelWidth, srcRectH * src.PixelWidth); // BlockCopy? #if !LIB byte[] coreArray = dataMemory.GetData(); #else byte[] coreArray = new byte[_scanlength]; dataMemory.ReadBytes(coreArray, _srcRect, _scanlength); #endif for (int y = 0; y < srcRectH; y++) { System.Array.Copy(data, y * src.PixelWidth * 4, coreArray, lineDst, src.PixelWidth * 4); lineDst += _scanlength * 4; } }; syscalls.maCreateImageFromData = delegate(int _placeholder, int _data, int _offset, int _size) { Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data); if (res == null) { return(MoSync.Constants.RES_BAD_INPUT); } Stream bin = (Stream)res.GetInternalObject(); if (bin == null) { return(MoSync.Constants.RES_BAD_INPUT); } BoundedStream s = new BoundedStream(bin, _offset, _size); WriteableBitmap bitmap = MoSync.Util.CreateWriteableBitmapFromStream(s); s.Close(); if (bitmap == null) { return(MoSync.Constants.RES_BAD_INPUT); } Resource imageRes = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, _placeholder); imageRes.SetInternalObject(bitmap); imageRes.SetResourceType(MoSync.Constants.RT_IMAGE); return(MoSync.Constants.RES_OK); }; }
public Runtime(Core core) { mCore = core; mSyscalls = new Syscalls(); mIoctls = new Ioctls(); mIoctlInvoker = new IoctlInvoker(mCore, mIoctls); mCurrentResourceHandle = 1; mStaticResourceCount = 0; PhoneApplicationFrame mainPage = (PhoneApplicationFrame)Application.Current.RootVisual; mainPage.MouseLeftButtonDown += MouseLeftButtonDown; mainPage.MouseMove += this.MouseMove; mainPage.MouseLeftButtonUp += MouseLeftButtonUp; // clear the list of system property providers // We clear it before we initialize all the modules, because // different modules might register system property providers. SystemPropertyManager.ClearSystemPropertyProviders(); RegisterCleaner(() => { Util.RunActionOnMainThreadSync(() => { mainPage.MouseLeftButtonDown -= MouseLeftButtonDown; mainPage.MouseMove -= this.MouseMove; mainPage.MouseLeftButtonUp -= MouseLeftButtonUp; }); }); InitSyscalls(); mSyscalls.maGetEvent = delegate(int ptr) { if (mEvents.Count != 0) { lock (mEvents) { Event evt = mEvents[0]; Memory eventData = evt.GetEventData(); mEvents.RemoveAt(0); Memory customEventData = evt.GetCustomEventData(); if (customEventData != null) { mCore.GetDataMemory().WriteMemoryAtAddress(mCore.GetCustomEventDataPointer(), customEventData, 0, customEventData.GetSizeInBytes()); eventData.WriteInt32(MoSync.Struct.MAEvent.data, mCore.GetCustomEventDataPointer()); } mCore.GetDataMemory().WriteMemoryAtAddress(ptr, eventData, 0, eventData.GetSizeInBytes()); } return(1); } else { return(0); } }; mSyscalls.maWait = delegate(int timeout) { if (timeout <= 0) { timeout = 1 << 15; } mEventWaiter.WaitOne(timeout); }; #if !LIB mSyscalls.maIOCtl = delegate(int id, int a, int b, int c) #else mSyscalls.maIOCtl = delegate(int id, int a, int b, int c, int args) #endif { #if !LIB return(mIoctlInvoker.InvokeIoctl(id, a, b, c)); #else return(mIoctlInvoker.InvokeIoctl(id, a, b, c, args)); #endif }; mSyscalls.maDestroyObject = delegate(int res) { mResources[res].SetResourceType(MoSync.Constants.RT_PLACEHOLDER); mResources[res].SetInternalObject(null); }; mSyscalls.maLoadResource = delegate(int _handle, int _placeholder, int _flag) { Resource res = mResources[_handle]; BoundedStream stream = res.GetFileStream(); Resource placeholder = mResources[_placeholder]; if (stream == null) { return(0); } if (placeholder.GetInternalObject() != null) { return(0); } stream.Seek(0, SeekOrigin.Begin); LoadResource(stream, (byte)res.GetResourceType(), (uint)stream.Length, placeholder); return(1); }; mSyscalls.maLoadResources = delegate(int _data) { Resource res = GetResource(MoSync.Constants.RT_BINARY, _data); Stream data = (Stream)res.GetInternalObject(); return(LoadResources(data, false)?1:0); }; mSyscalls.maCountResources = delegate() { return(mStaticResourceCount); }; }
public void Init(Syscalls mSyscalls, Core mCore, Runtime mRuntime) { mSyscalls.maSoundPlay = delegate(int _data, int _offset, int _size) { mSyscalls.maSoundStop(); Resource audiores = mRuntime.GetResource(MoSync.Constants.RT_BINARY, _data); BoundedStream s = new BoundedStream((Stream)audiores.GetInternalObject(), _offset, _size); // Read MIME type. Mp3MediaStreamSource is not clever enough to bypass it. StringBuilder sb = new StringBuilder(); int b; while ((b = s.ReadByte()) > 0) { sb.Append((char)b); } if (b < 0) { // The MIME type was interrupted. // Bad stream. We don't want to play it. return(-2); } if (sb.ToString() != "audio/mpeg") { // We can only play MP3 files. return(-3); } Mp3MediaStreamSource source = new Mp3MediaStreamSource(s); // all Controls code must be Dispatched to the proper thread, // or you'll get a fatal Exception. Deployment.Current.Dispatcher.BeginInvoke(() => { mElement = new MediaElement(); mElement.Volume = mVolume; mElement.SetSource(source); mElement.Play(); }); return(0); }; mSyscalls.maSoundStop = delegate() { MoSync.Util.RunActionOnMainThreadSync(() => { if (mElement != null) { mElement.Stop(); } }); }; mSyscalls.maSoundIsPlaying = delegate() { int result = 0; MoSync.Util.RunActionOnMainThreadSync(() => { if (mElement != null) { MediaElementState s = mElement.CurrentState; result = (s == MediaElementState.Buffering) || (s == MediaElementState.Playing) ? 1 : 0; } }); return(result); }; mSyscalls.maSoundGetVolume = delegate() { return((int)mVolume); }; mSyscalls.maSoundSetVolume = delegate(int _vol) { mVolume = _vol; if (mVolume > 100) { mVolume = 100; } else if (mVolume < 0) { mVolume = 0; } Deployment.Current.Dispatcher.BeginInvoke(() => { if (mElement != null) { mElement.Volume = mVolume; } }); }; }
public void Init(Syscalls syscalls, Core core, Runtime runtime) { // maybe use some pretty reflection mechanism to find all syscall implementations here.. syscalls.maCheckInterfaceVersion = delegate(int hash) { if (MoSync.Constants.MoSyncHash != (uint)hash) MoSync.Util.CriticalError("Invalid hash!"); return hash; }; syscalls.maPanic = delegate(int code, int str) { String message = core.GetDataMemory().ReadStringAtAddress(str); MoSync.Util.CriticalError(message + "\ncode: " + code); }; syscalls.maExit = delegate(int res) { mCore.Stop(); }; DateTime startDate = System.DateTime.Now; syscalls.maGetMilliSecondCount = delegate() { System.TimeSpan offset = (System.DateTime.Now - startDate); return offset.Milliseconds + (offset.Seconds + (offset.Minutes + (offset.Hours + offset.Days * 24) * 60) * 60) * 1000; }; syscalls.maTime = delegate() { return (int)Util.ToUnixTimeUtc(System.DateTime.Now); }; syscalls.maLocalTime = delegate() { return (int)Util.ToUnixTime(System.DateTime.Now); }; syscalls.maCreatePlaceholder = delegate() { Resource res = new Resource(null, MoSync.Constants.RT_PLACEHOLDER, true); return runtime.AddResource(res); }; syscalls.maDestroyPlaceholder = delegate(int res) { if (!runtime.GetResource(0, res).IsDynamicPlaceholder()) MoSync.Util.CriticalError("maDestroyPlaceholder can only be used on handles created by maCreatePlaceholder."); runtime.RemoveResource(res); }; syscalls.maFindLabel = delegate(int _name) { String name = core.GetDataMemory().ReadStringAtAddress(_name); int res; if (runtime.mLabels.TryGetValue(name, out res)) return res; else return -1; }; /* * PhoneApplicationService.Current.UserIdleDetectionMode * Disabling this will stop the screen from timing out and locking. * Discussion: this needs to be re-enabled for the backlight to work * so an maStartBacklight should be needed for WP7; * what about maToggleBacklight(bool)? * * We have maWakeLock instead on Windows Phone, Android, iOS. */ syscalls.maResetBacklight = delegate() { }; syscalls.maVibrate = delegate(int _ms) { if (mVibrateController == null) mVibrateController = Microsoft.Devices.VibrateController.Default; // more than 5 seconds aren't allowed.. if (_ms > 5000) _ms = 5000; if (_ms < 0) return _ms; else if (_ms == 0) mVibrateController.Stop(); else mVibrateController.Start(TimeSpan.FromMilliseconds(_ms)); return 1; }; syscalls.maLoadProgram = delegate(int _data, int _reload) { #if REBUILD throw new Exception("maLoadProgram not available in rebuild mode"); #elif !LIB Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data); //Memory mem = (Memory)res.GetInternalObject(); Stream mem = (Stream)res.GetInternalObject(); MoSync.Machine.SetLoadProgram(mem, _reload != 0); throw new Util.ExitException(0); #endif }; }
public void Init(Syscalls syscalls, Core core, Runtime runtime) { // maybe use some pretty reflection mechanism to find all syscall implementations here.. syscalls.maCheckInterfaceVersion = delegate(int hash) { if (MoSync.Constants.MoSyncHash != (uint)hash) { MoSync.Util.CriticalError("Invalid hash!"); } return(hash); }; syscalls.maPanic = delegate(int code, int str) { String message = core.GetDataMemory().ReadStringAtAddress(str); MoSync.Util.CriticalError(message + "\ncode: " + code); }; syscalls.maExit = delegate(int res) { MoSync.Util.Exit(res); }; DateTime startDate = System.DateTime.Now; syscalls.maGetMilliSecondCount = delegate() { System.TimeSpan offset = (System.DateTime.Now - startDate); return(offset.Milliseconds + (offset.Seconds + (offset.Minutes + (offset.Hours + offset.Days * 24) * 60) * 60) * 1000); }; syscalls.maTime = delegate() { return((int)Util.ToUnixTimeUtc(System.DateTime.Now)); }; syscalls.maLocalTime = delegate() { return((int)Util.ToUnixTime(System.DateTime.Now)); }; syscalls.maCreatePlaceholder = delegate() { Resource res = new Resource(null, MoSync.Constants.RT_PLACEHOLDER, true); return(runtime.AddResource(res)); }; syscalls.maDestroyPlaceholder = delegate(int res) { if (!runtime.GetResource(0, res).IsDynamicPlaceholder()) { MoSync.Util.CriticalError("maDestroyPlaceholder can only be used on handles created by maCreatePlaceholder."); } runtime.RemoveResource(res); }; syscalls.maFindLabel = delegate(int _name) { String name = core.GetDataMemory().ReadStringAtAddress(_name); int res; if (runtime.mLabels.TryGetValue(name, out res)) { return(res); } else { return(-1); } }; /* * PhoneApplicationService.Current.UserIdleDetectionMode * Disabling this will stop the screen from timing out and locking. * Discussion: this needs to be re-enabled for the backlight to work * so an maStartBacklight should be needed for WP7; * what about maToggleBacklight(bool)? * * We have maWakeLock instead on Windows Phone, Android, iOS. */ syscalls.maResetBacklight = delegate() { }; syscalls.maVibrate = delegate(int _ms) { if (mVibrateController == null) { mVibrateController = Microsoft.Devices.VibrateController.Default; } // more than 5 seconds aren't allowed.. if (_ms > 5000) { _ms = 5000; } if (_ms < 0) { return(_ms); } else if (_ms == 0) { mVibrateController.Stop(); } else { mVibrateController.Start(TimeSpan.FromMilliseconds(_ms)); } return(1); }; syscalls.maLoadProgram = delegate(int _data, int _reload) { #if REBUILD throw new Exception("maLoadProgram not available in rebuild mode"); #else Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data); //Memory mem = (Memory)res.GetInternalObject(); Stream mem = (Stream)res.GetInternalObject(); MoSync.Machine.SetLoadProgram(mem, _reload != 0); throw new Util.ExitException(0); #endif }; }
public void Init(Syscalls syscalls, Core core, Runtime runtime) { syscalls.memset = delegate(int dst, int val, int num) { core.GetDataMemory().FillRange(dst, (byte)val, num); return(dst); }; syscalls.memcpy = delegate(int dst, int src, int num) { core.GetDataMemory().WriteMemoryAtAddress(dst, core.GetDataMemory(), src, num); return(dst); }; syscalls.strcpy = delegate(int dst, int src) { byte[] mem = core.GetDataMemory().GetData(); int origDst = dst; src--; do { src++; mem[dst] = mem[src]; dst++; } while (mem[src] != 0); return(origDst); }; syscalls.strcmp = delegate(int str1, int str2) { byte[] mem = core.GetDataMemory().GetData(); while (mem[str1] != 0 && mem[str1] == mem[str2]) { str1++; str2++; } return(mem[str1] - mem[str2]); }; syscalls.maCreateData = delegate(int placeholder, int size) { MemoryStream mem = null; try { mem = new MemoryStream(size); mem.SetLength(size); } catch (OutOfMemoryException e) { MoSync.Util.Log(e); return(MoSync.Constants.RES_OUT_OF_MEMORY); } Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, placeholder); res.SetInternalObject(mem); res.SetResourceType(MoSync.Constants.RT_BINARY); return(MoSync.Constants.RES_OK); }; syscalls.maWriteData = delegate(int data, int src, int offset, int size) { Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data); Stream mem = (Stream)res.GetInternalObject(); mem.Seek(offset, SeekOrigin.Begin); mem.Write(core.GetDataMemory().GetData(), src, size); }; syscalls.maReadData = delegate(int data, int dst, int offset, int size) { Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data); Stream mem = (Stream)res.GetInternalObject(); mem.Seek(offset, SeekOrigin.Begin); mem.Read(core.GetDataMemory().GetData(), dst, size); }; syscalls.maGetDataSize = delegate(int data) { Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data); Stream mem = (Stream)res.GetInternalObject(); return((int)mem.Length); }; syscalls.maCopyData = delegate(int _params) { throw new Exception("maCopyData not implemented"); }; }
public void Init(Syscalls syscalls, Core core, Runtime runtime) { syscalls.memset = delegate(int dst, int val, int num) { core.GetDataMemory().FillRange(dst, (byte)val, num); return(dst); }; syscalls.memcpy = delegate(int dst, int src, int num) { core.GetDataMemory().WriteMemoryAtAddress(dst, core.GetDataMemory(), src, num); return(dst); }; syscalls.strcpy = delegate(int dst, int src) { #if !LIB byte[] mem = core.GetDataMemory().GetData(); int origDst = dst; src--; do { src++; mem[dst] = mem[src]; dst++; } while (mem[src] != 0); return(origDst); #else string source = core.GetDataMemory().ReadStringAtAddress(src); Byte[] bytes = new Byte[source.Length * sizeof(char)]; System.Buffer.BlockCopy(source.ToCharArray(), 0, bytes, 0, bytes.Length); core.GetDataMemory().WriteBytes(dst, bytes, source.Length * sizeof(char)); return(dst); #endif }; syscalls.strcmp = delegate(int str1, int str2) { #if !LIB byte[] mem = core.GetDataMemory().GetData(); while (mem[str1] != 0 && mem[str1] == mem[str2]) { str1++; str2++; } return(mem[str1] - mem[str2]); #else string s1 = core.GetDataMemory().ReadStringAtAddress(str1); string s2 = core.GetDataMemory().ReadStringAtAddress(str2); return(s1.CompareTo(s2)); #endif }; syscalls.maCreateData = delegate(int placeholder, int size) { MemoryStream mem = null; try { mem = new MemoryStream(size); mem.SetLength(size); } catch (OutOfMemoryException e) { MoSync.Util.Log(e); return(MoSync.Constants.RES_OUT_OF_MEMORY); } Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, placeholder); res.SetInternalObject(mem); res.SetResourceType(MoSync.Constants.RT_BINARY); return(MoSync.Constants.RES_OK); }; syscalls.maWriteData = delegate(int data, int src, int offset, int size) { Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data); Stream mem = (Stream)res.GetInternalObject(); mem.Seek(offset, SeekOrigin.Begin); #if !LIB mem.Write(core.GetDataMemory().GetData(), src, size); #else byte[] bytes = new byte[size]; core.GetDataMemory().ReadBytes(bytes, src, size); mem.Write(bytes, 0, size); //TO BE TESTED #endif }; syscalls.maReadData = delegate(int data, int dst, int offset, int size) { Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data); Stream mem = (Stream)res.GetInternalObject(); mem.Seek(offset, SeekOrigin.Begin); #if !LIB mem.Read(core.GetDataMemory().GetData(), dst, size); #else byte[] bytes = new byte[size]; mem.Read(bytes, 0, size); core.GetDataMemory().WriteBytes(dst, bytes, size); //TO BE TESTED #endif }; syscalls.maGetDataSize = delegate(int data) { Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data); Stream mem = (Stream)res.GetInternalObject(); return((int)mem.Length); }; syscalls.maCopyData = delegate(int _params) { throw new Exception("maCopyData not implemented"); }; }
public void Init(Syscalls syscalls, Core core, Runtime runtime) { runtime.RegisterCleaner(delegate() { CleanDictionary(mFileHandles); CleanDictionary(mStoreHandles); mFileListHandles.Clear(); }); // todo: store "stores" in a separate location from the filesystem, // to avoid clashes. syscalls.maOpenStore = delegate(int _name, int _flags) { String name = core.GetDataMemory().ReadStringAtAddress(_name); name = ConvertPath(name); File file = new File(name, FileAccess.ReadWrite); if (file.IsDirectory) { throw new Exception("Invalid store name"); } if (file.Exists) { file.TryOpen(); } else if ((_flags & MoSync.Constants.MAS_CREATE_IF_NECESSARY) != 0) { file.Create(); } else { return(MoSync.Constants.STERR_NONEXISTENT); } if (file.FileStream == null) { return(MoSync.Constants.STERR_GENERIC); } mStoreHandles.Add(mNextStoreHandle, file); return(mNextStoreHandle++); }; syscalls.maWriteStore = delegate(int _store, int _data) { File file = mStoreHandles[_store]; IsolatedStorageFileStream fileStream = file.FileStream; fileStream.SetLength(0); Resource dataRes = runtime.GetResource(MoSync.Constants.RT_BINARY, _data); Stream data = (Stream)dataRes.GetInternalObject(); data.Seek(0, SeekOrigin.Begin); //fileStream.Write(data.GetData(), 0, data.GetData().Length); data.CopyTo(fileStream); return(1); }; syscalls.maReadStore = delegate(int _store, int _placeholder) { File file = mStoreHandles[_store]; IsolatedStorageFileStream fileStream = file.FileStream; //Memory mem = new Memory((int)fileStream.Length); MemoryStream mem = new MemoryStream((int)fileStream.Length); mem.SetLength((int)fileStream.Length); fileStream.Seek(0, SeekOrigin.Begin); fileStream.Read(mem.GetBuffer(), 0, (int)fileStream.Length); runtime.SetResource(_placeholder, new Resource(mem, MoSync.Constants.RT_BINARY, true)); return(MoSync.Constants.RES_OK); }; syscalls.maCloseStore = delegate(int _store, int _delete) { File file = mStoreHandles[_store]; file.Close(); if (_delete != 0) { file.Delete(); } mStoreHandles.Remove(_store); }; }
public void Init(Syscalls syscalls, Core core, Runtime runtime) { // maybe use some pretty reflection mechanism to find all syscall implementations here.. syscalls.maCheckInterfaceVersion = delegate(int hash) { if (MoSync.Constants.MoSyncHash != (uint)hash) MoSync.Util.CriticalError("Invalid hash!"); return hash; }; syscalls.maPanic = delegate(int code, int str) { String message = core.GetDataMemory().ReadStringAtAddress(str); MoSync.Util.CriticalError(message + "\ncode: " + code); }; syscalls.maExit = delegate(int res) { MoSync.Util.Exit(res); }; DateTime startDate = System.DateTime.Now; syscalls.maGetMilliSecondCount = delegate() { System.TimeSpan offset = (System.DateTime.Now - startDate); return offset.Milliseconds + (offset.Seconds + (offset.Minutes + (offset.Hours + offset.Days * 24) * 60) * 60) * 1000; }; syscalls.maTime = delegate() { return (int)Util.ToUnixTimeUtc(System.DateTime.Now); }; syscalls.maLocalTime = delegate() { return (int)Util.ToUnixTime(System.DateTime.Now); }; syscalls.maCreatePlaceholder = delegate() { Resource res = new Resource(null, MoSync.Constants.RT_PLACEHOLDER, true); return runtime.AddResource(res); }; syscalls.maDestroyPlaceholder = delegate(int res) { if (!runtime.GetResource(0, res).IsDynamicPlaceholder()) MoSync.Util.CriticalError("maDestroyPlaceholder can only be used on handles created by maCreatePlaceholder."); runtime.RemoveResource(res); }; syscalls.maFindLabel = delegate(int _name) { String name = core.GetDataMemory().ReadStringAtAddress(_name); int res; if (runtime.mLabels.TryGetValue(name, out res)) return res; else return -1; }; syscalls.maResetBacklight = delegate() { }; syscalls.maVibrate = delegate(int _ms) { if (mVibrateController == null) mVibrateController = Microsoft.Devices.VibrateController.Default; if (_ms < 0) return _ms; else if (_ms == 0) mVibrateController.Stop(); else mVibrateController.Start(TimeSpan.FromMilliseconds(_ms)); return 0; }; syscalls.maLoadProgram = delegate(int _data, int _reload) { #if REBUILD throw new Exception("maLoadProgram not available in rebuild mode"); #else Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data); //Memory mem = (Memory)res.GetInternalObject(); Stream mem = (Stream)res.GetInternalObject(); MoSync.Machine.SetLoadProgram(mem, _reload != 0); throw new Util.ExitException(0); #endif }; }
public void Init(Ioctls ioctls, Core core, Runtime runtime) { IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication(); MoSync.SystemPropertyManager.RegisterSystemPropertyProvider("mosync.path.local", delegate(String key) { // The isolated storage becomes the "root" return("/"); } ); ioctls.maFileOpen = delegate(int _path, int _mode) { String path = core.GetDataMemory().ReadStringAtAddress(_path); path = ConvertPath(path); File file = null; FileAccess access = 0; if (_mode == MoSync.Constants.MA_ACCESS_READ) { access = FileAccess.Read; } else if (_mode == MoSync.Constants.MA_ACCESS_READ_WRITE) { access = FileAccess.ReadWrite; } else { throw new Exception("Invalid file access mode"); } file = new File(path, access); if (file.IsDirectory) { if (isolatedStorage.FileExists(path)) { return(MoSync.Constants.MA_FERR_WRONG_TYPE); } } else { if (isolatedStorage.DirectoryExists(path)) { return(MoSync.Constants.MA_FERR_WRONG_TYPE); } try { file.TryOpen(); } catch (IsolatedStorageException e) { MoSync.Util.Log(e); return(MoSync.Constants.MA_FERR_GENERIC); } } mFileHandles.Add(mNextFileHandle, file); return(mNextFileHandle++); }; ioctls.maFileClose = delegate(int _file) { File file = mFileHandles[_file]; file.Close(); mFileHandles.Remove(_file); return(0); }; ioctls.maFileRead = delegate(int _file, int _dst, int _len) { File file = mFileHandles[_file]; if (file.IsDirectory) { return(MoSync.Constants.MA_FERR_WRONG_TYPE); } IsolatedStorageFileStream fileStream = file.FileStream; if (fileStream == null) { return(MoSync.Constants.MA_FERR_GENERIC); } core.GetDataMemory().WriteFromStream(_dst, fileStream, _len); return(0); }; ioctls.maFileReadToData = delegate(int _file, int _data, int _offset, int _len) { File file = mFileHandles[_file]; if (file.IsDirectory) { return(MoSync.Constants.MA_FERR_WRONG_TYPE); } IsolatedStorageFileStream fileStream = file.FileStream; if (fileStream == null) { return(MoSync.Constants.MA_FERR_GENERIC); } Resource dataRes = runtime.GetResource(MoSync.Constants.RT_BINARY, _data); //Memory data = (Memory)dataRes.GetInternalObject(); Stream data = (Stream)dataRes.GetInternalObject(); MoSync.Util.CopySeekableStreams(fileStream, (int)fileStream.Position, data, _offset, _len); //data.WriteFromStream(_offset, fileStream, _len); return(0); }; ioctls.maFileWriteFromData = delegate(int _file, int _data, int _offset, int _len) { File file = mFileHandles[_file]; if (file.IsDirectory) { return(MoSync.Constants.MA_FERR_WRONG_TYPE); } IsolatedStorageFileStream fileStream = file.FileStream; if (fileStream == null) { return(MoSync.Constants.MA_FERR_GENERIC); } Resource dataRes = runtime.GetResource(MoSync.Constants.RT_BINARY, _data); //Memory data = (Memory)dataRes.GetInternalObject(); Stream data = (Stream)dataRes.GetInternalObject(); //byte[] bytes = new byte[_len]; //data.ReadBytes(bytes, _offset, _len); MoSync.Util.CopySeekableStreams(data, _offset, fileStream, (int)fileStream.Position, _len); //fileStream.Write(bytes, 0, _len); fileStream.Flush(); return(0); }; ioctls.maFileWrite = delegate(int _file, int _src, int _len) { File file = mFileHandles[_file]; if (file.IsDirectory) { return(MoSync.Constants.MA_FERR_WRONG_TYPE); } IsolatedStorageFileStream fileStream = file.FileStream; if (fileStream == null) { return(MoSync.Constants.MA_FERR_GENERIC); } byte[] bytes = new byte[_len]; core.GetDataMemory().ReadBytes(bytes, _src, _len); fileStream.Write(bytes, 0, _len); fileStream.Flush(); return(0); }; ioctls.maFileSeek = delegate(int _file, int _offset, int _whence) { File file = mFileHandles[_file]; if (file.IsDirectory) { return(MoSync.Constants.MA_FERR_WRONG_TYPE); } if (file.Exists == false) { return(MoSync.Constants.MA_FERR_GENERIC); } IsolatedStorageFileStream fileStream = file.FileStream; SeekOrigin origin; switch (_whence) { case MoSync.Constants.MA_SEEK_SET: origin = SeekOrigin.Begin; break; case MoSync.Constants.MA_SEEK_CUR: origin = SeekOrigin.Current; break; case MoSync.Constants.MA_SEEK_END: origin = SeekOrigin.End; break; default: throw new Exception("maFileSeek whence"); } try { return((int)fileStream.Seek(_offset, origin)); } catch (IOException e) { MoSync.Util.Log(e); return(MoSync.Constants.MA_FERR_GENERIC); } }; ioctls.maFileTell = delegate(int _file) { File file = mFileHandles[_file]; if (file.IsDirectory) { return(MoSync.Constants.MA_FERR_WRONG_TYPE); } IsolatedStorageFileStream fileStream = file.FileStream; return((int)fileStream.Position); }; ioctls.maFileExists = delegate(int _file) { File file = mFileHandles[_file]; return(file.Exists ? 1 : 0); }; ioctls.maFileCreate = delegate(int _file) { File file = mFileHandles[_file]; if (file.Exists) { return(MoSync.Constants.MA_FERR_GENERIC); } file.Create(); return(0); }; ioctls.maFileDelete = delegate(int _file) { File file = mFileHandles[_file]; try { file.Delete(); } catch (IsolatedStorageException e) { MoSync.Util.Log(e); return(MoSync.Constants.MA_FERR_GENERIC); } return(0); }; ioctls.maFileSize = delegate(int _file) { File file = mFileHandles[_file]; if (file.Exists == false) { return(MoSync.Constants.MA_FERR_GENERIC); } return(file.Size()); }; ioctls.maFileAvailableSpace = delegate(int _file) { File file = mFileHandles[_file]; return(file.AvailableSpace()); }; ioctls.maFileTotalSpace = delegate(int _file) { File file = mFileHandles[_file]; return(file.TotalSpace()); }; ioctls.maFileDate = delegate(int _file) { File file = mFileHandles[_file]; return(Util.ToUnixTimeUtc(file.Date().ToFileTime())); }; ioctls.maFileRename = delegate(int _file, int _newName) { File file = mFileHandles[_file]; String newName = core.GetDataMemory().ReadStringAtAddress(_newName); newName = ConvertPath(newName); if (newName.Contains("\\")) { if (newName[0] != '\\') { throw new Exception("Invalid newName"); } } else { // add directory of old file. newName = Path.GetDirectoryName(file.Path) + "\\" + newName; } file.Rename(newName); return(0); }; ioctls.maFileTruncate = delegate(int _file, int _offset) { File file = mFileHandles[_file]; file.Truncate(_offset); return(0); }; ioctls.maFileListStart = delegate(int _path, int _filter, int _sorting) { // todo: respect _sorting. String path = core.GetDataMemory().ReadStringAtAddress(_path); path = ConvertPath(path); String filter = core.GetDataMemory().ReadStringAtAddress(_filter); String pattern = path + filter; IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); FileList fl = new FileList(); fl.dirs = isf.GetDirectoryNames(pattern); fl.files = isf.GetFileNames(pattern); fl.pos = 0; mFileListHandles.Add(mNextFileListHandle, fl); return(mNextFileListHandle++); }; ioctls.maFileListNext = delegate(int _list, int _nameBuf, int _bufSize) { FileList fl = mFileListHandles[_list]; String name; if (fl.pos < fl.dirs.Length) { name = fl.dirs[fl.pos] + "/"; } else if (fl.pos < fl.dirs.Length + fl.files.Length) { name = fl.files[fl.pos - fl.dirs.Length]; } else { return(0); } if (name.Length >= _bufSize) { return(name.Length); } core.GetDataMemory().WriteStringAtAddress(_nameBuf, name, _bufSize); fl.pos++; return(name.Length); }; ioctls.maFileListClose = delegate(int _list) { FileList fl = mFileListHandles[_list]; mFileListHandles.Remove(_list); return(0); }; }
public void Init(Syscalls syscalls, Core core, Runtime runtime) { SystemPropertyManager.mSystemPropertyProviders.Clear(); // maybe use some pretty reflection mechanism to find all syscall implementations here.. syscalls.maCheckInterfaceVersion = delegate(int hash) { if (MoSync.Constants.MoSyncHash != (uint)hash) { MoSync.Util.CriticalError("Invalid hash!"); } return(hash); }; syscalls.maPanic = delegate(int code, int str) { String message = core.GetDataMemory().ReadStringAtAddress(str); MoSync.Util.CriticalError(message + "\ncode: " + code); }; syscalls.maExit = delegate(int res) { MoSync.Util.Exit(res); }; DateTime startDate = System.DateTime.Now; syscalls.maGetMilliSecondCount = delegate() { System.TimeSpan offset = (System.DateTime.Now - startDate); return(offset.Milliseconds + (offset.Seconds + (offset.Minutes + (offset.Hours + offset.Days * 24) * 60) * 60) * 1000); }; syscalls.maTime = delegate() { return((int)Util.ToUnixTimeUtc(System.DateTime.Now)); }; syscalls.maLocalTime = delegate() { return((int)Util.ToUnixTime(System.DateTime.Now)); }; syscalls.maCreatePlaceholder = delegate() { return(runtime.AddResource(new Resource(null, MoSync.Constants.RT_PLACEHOLDER))); }; syscalls.maFindLabel = delegate(int _name) { String name = core.GetDataMemory().ReadStringAtAddress(_name); int res; if (runtime.mLabels.TryGetValue(name, out res)) { return(res); } else { return(-1); } }; syscalls.maResetBacklight = delegate() { }; syscalls.maSoundPlay = delegate(int _sound_res, int _offset, int _size) { // not implemented, but I don't wanna throw exceptions. return(-1); }; syscalls.maLoadProgram = delegate(int _data, int _reload) { #if REBUILD throw new Exception("maLoadProgram not available in rebuild mode"); #else Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data); Memory mem = (Memory)res.GetInternalObject(); MoSync.Machine.SetLoadProgram(mem.GetStream(), _reload != 0); throw new Util.ExitException(0); #endif }; }