Example #1
0
        protected void InitExtensions(MoSync.Core core, MoSync.Runtime runtime)
        {
            try
            {
                MoSync.ExtensionsLoader.Load();
            }
            catch (Exception e)
            {
                MoSync.Util.CriticalError("Couldn't load extension: " + e.ToString());
            }

            MoSync.ExtensionModule       extMod     = runtime.GetModule <MoSync.ExtensionModule>();
            System.Reflection.Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (System.Reflection.Assembly a in assemblies)
            {
                try
                {
                    foreach (Type t in a.GetTypes())
                    {
                        IExtensionModule extensionGroupInstance = null;
                        if (t.GetInterface("MoSync.IExtensionModule", false) != null)
                        {
                            extensionGroupInstance = Activator.CreateInstance(t) as IExtensionModule;
                            extMod.AddModule(extensionGroupInstance);
                            extensionGroupInstance.Init(core, runtime);
                        }
                    }
                }
                catch { }
            }
        }
Example #2
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            //			ioctls.maAudioDataCreateFromFile = delegate(int _mime, int _filename, int _flags)
            //			{
            //				return MoSync.Constants.MA_AUDIO_ERR_INVALID_SOUND_FORMAT;
            //			};

            ioctls.maAudioDataCreateFromResource = delegate(int _mime, int _data, int _offset, int _length, int _flags)
            {
                return MoSync.Constants.IOCTL_UNAVAILABLE;
            };

            ioctls.maAudioDataDestroy = delegate(int _audioData)
            {
                return MoSync.Constants.IOCTL_UNAVAILABLE;
            };

            ioctls.maAudioInstanceCreate = delegate(int _audioData)
            {
                return MoSync.Constants.IOCTL_UNAVAILABLE;
            };

            ioctls.maAudioInstanceDestroy = delegate(int _audioInstance)
            {
                return MoSync.Constants.IOCTL_UNAVAILABLE;
            };

            ioctls.maAudioPlay = delegate(int _audioInstance)
            {
                return MoSync.Constants.IOCTL_UNAVAILABLE;
            };
        }
Example #3
0
 public void Init(Syscalls syscalls, Core core, Runtime runtime)
 {
     syscalls.maSoundPlay = delegate(int _sound_res, int _offset, int _size)
     {
         // not implemented, but I don't wanna throw exceptions.
         return -1;
     };
 }
Example #4
0
 public void Init(Core core, Runtime runtime)
 {
     maSillyTest = delegate(int _str)
     {
         runtime.GetSyscalls().maSetColor(0x00ff00);
         runtime.GetSyscalls().maDrawText(5, 5, _str);
         runtime.GetSyscalls().maUpdateScreen();
         return 42;
     };
 }
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            /**
             * Displays a special kind of dialog that has a list of possible choices.
             * The list of options is displayed as buttons on iOS, and as text views on Android.
             * By clicking any option the dialog gets dismissed and a #EVENT_TYPE_OPTIONS_BOX_BUTTON_CLICKED event is sent back.
             *
             * \param title The dialog title.
             * \param destructiveButtonTitle The destructive button text. This is an iOS specific feature: it has different color than the other options,
             * and it indicates that it's action has destructive behaviour. On Android it is treated and it looks like a normal option.
             * \param cancelButtonTitle The dialog's Cancel button text. If left empty, the dialog is not cancelable.
             * \param otherButtonTitles The address to the buffer that stores the list of options.
             * \param otherButtonTitlesSize The size of the buffer, in bytes.
             */
            ioctls.maOptionsBox = delegate(int _title, int _destructiveButtonTitle, int _cancelButtonTitle, int _otherButtonTitles, int _otherButtonTitlesSize)
            {
                mApplicationBarMenuItems = new List<ApplicationBarMenuItem>();
                mRuntime = runtime;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    // get the current application page
                    PhoneApplicationPage currentPage = (((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage);

                    // create the application bar and enable the application bar menu which will contain the option buttons
                    currentPage.ApplicationBar = new ApplicationBar();
                    currentPage.ApplicationBar.Mode = ApplicationBarMode.Default;
                    currentPage.ApplicationBar.Opacity = 1.0;
                    currentPage.ApplicationBar.IsVisible = true;
                    currentPage.ApplicationBar.IsMenuEnabled = true;
                    mApplicationBar = currentPage.ApplicationBar;

                    // the cancel button will be an application bar button with a default icon
                    String cancelButtonTitle = core.GetDataMemory().ReadWStringAtAddress(_cancelButtonTitle);
                    ApplicationBarIconButton cancelButton = new ApplicationBarIconButton();
                    // by not specifying the uri path to the button icon, a default one will be set
                    cancelButton.IconUri = new Uri("", UriKind.Relative);
                    cancelButton.Text = cancelButtonTitle;
                    cancelButton.Click += new EventHandler(cancelButton_Click);
                    currentPage.ApplicationBar.Buttons.Add(cancelButton);

                    createOptionButtons(core, _otherButtonTitles);

                    // the destructive button will be the last application bar menu item
                    String destructiveButtonTitle = core.GetDataMemory().ReadWStringAtAddress(_destructiveButtonTitle);
                    ApplicationBarMenuItem destructiveMenuItem = new ApplicationBarMenuItem();
                    destructiveMenuItem.Text = destructiveButtonTitle;
                    destructiveMenuItem.Click += new EventHandler(destructiveButton_Click);
                    currentPage.ApplicationBar.MenuItems.Add(destructiveMenuItem);
                });

                return MoSync.Constants.MAW_RES_OK;
            };
        }
Example #6
0
        public static Machine CreateNativeMachine(Core core, String resourceFile)
        {
            StreamResourceInfo resourcesResInfo = Application.GetResourceStream(new Uri(resourceFile, UriKind.Relative));
            Stream resources = null;
            if (resourcesResInfo != null && resourcesResInfo.Stream != null)
                resources = resourcesResInfo.Stream;

            MoSync.Machine mosyncMachine = new MoSync.Machine(true);
            mosyncMachine.Init(core, resources);
            if (resources != null)
                resources.Close();
            return mosyncMachine;
        }
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            syscalls.maExtensionFunctionInvoke = delegate(int extensionId, int a, int b, int c)
            {
                int _module = extensionId >> 8;
                if (_module >= 0 && _module < mModules.Count)
                {
                    IExtensionModule module = mModules[_module];
                    int function = extensionId & 0xff;
                    return module.Invoke(core, function, a, b, c);
                }

                return MoSync.Constants.MA_EXTENSION_FUNCTION_UNAVAILABLE;
            };
        }
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            InitExtensions(core, runtime);

            syscalls.maInvokeExtension = delegate(int extensionId, int a, int b, int c)
            {
                int ptr = core.GetDataMemory().ReadInt32(extensionId+0);
                String module = core.GetDataMemory().ReadStringAtAddress(ptr);
                int index = core.GetDataMemory().ReadInt32(extensionId + 4);

                IExtensionModule extension = GetModule(module);
                if (extension == null)
                    return MoSync.Constants.IOCTL_UNAVAILABLE;
                else
                    return extension.Invoke(index, a, b, c);
            };
        }
        protected void InitExtensions(Core core, Runtime runtime)
        {
            foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
            {
                IExtensionModule extensionGroupInstance = null;
                if (t.GetInterface("MoSync.IExtensionModule", false) != null)
                {
                    extensionGroupInstance = Activator.CreateInstance(t) as IExtensionModule;
                    mModules.Add(extensionGroupInstance.GetName(), extensionGroupInstance);
                }
            }

            foreach (KeyValuePair<String, IExtensionModule> module in mModules)
            {
                module.Value.Init(core, runtime);
            }
        }
Example #10
0
        public void Init(Syscalls mSyscalls, Core mCore, Runtime mRuntime)
        {
            mSyscalls.__adddf3 = delegate(double a, double b) { return a + b; };
            mSyscalls.__subdf3 = delegate(double a, double b) { return a - b; };
            mSyscalls.__muldf3 = delegate(double a, double b) { return a * b; };
            mSyscalls.__divdf3 = delegate(double a, double b) { return a / b; };
            mSyscalls.__negdf2 = delegate(double a) { return -a; };
            mSyscalls.__fixdfsi = delegate(double a) { return (int)a; };
            mSyscalls.__fixunsdfsi = delegate(double a) { return (int)((uint)a); };
            mSyscalls.__floatsidf = delegate(int a) { return (double)a; };
            mSyscalls.__extendsfdf2 = delegate(float a) { return (double)a; };
            mSyscalls.dcmp = delegate(double a, double b)
            {
                if (a > b)
                    return 1;
                else if (a == b)
                    return 0;
                else	//a < b //or NaN!
                    return -1;
            };

            mSyscalls.__addsf3 = delegate(float a, float b) { return a + b; };
            mSyscalls.__subsf3 = delegate(float a, float b) { return a - b; };
            mSyscalls.__mulsf3 = delegate(float a, float b) { return a * b; };
            mSyscalls.__divsf3 = delegate(float a, float b) { return a / b; };
            mSyscalls.__negsf2 = delegate(float a) { return -a; };
            mSyscalls.__fixsfsi = delegate(float a) { return (int)a; };
            mSyscalls.__fixunssfsi = delegate(float a) { return (int)((uint)a); };
            mSyscalls.__floatsisf = delegate(int a) { return (float)a; };
            mSyscalls.__truncdfsf2 = delegate(double a) { return (float)a; };
            mSyscalls.fcmp = delegate(float a, float b)
            {
                if (a > b)
                    return 1;
                else if (a == b)
                    return 0;
                else	//a < b //or NaN!
                    return -1;
            };

            mSyscalls.sin = delegate(double v) { return System.Math.Sin(v); };
            mSyscalls.cos = delegate(double v) { return System.Math.Cos(v); };
            mSyscalls.tan = delegate(double v) { return System.Math.Tan(v); };
            mSyscalls.sqrt = delegate(double v) { return System.Math.Sqrt(v); };
        }
Example #11
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.sinh = delegate(double d)
            {
                return BitConverter.DoubleToInt64Bits(Math.Sinh(d));
            };

            ioctls.cosh = delegate(double d)
            {
                return BitConverter.DoubleToInt64Bits(Math.Cosh(d));
            };

            ioctls.atanh = delegate(double d)
            {
                double value = (Math.Log(1.0 + d) - Math.Log(1.0 - d)) / 2.0;
                return BitConverter.DoubleToInt64Bits(value);
            };
        }
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            /**
             * Displays an image picker to the user.
             * It's display depends on the platform.
             * Note: when a selection is made a #EVENT_TYPE_IMAGE_PICKER event is sent.
             */
            ioctls.maImagePickerOpen = delegate()
            {
                // by default, the image picker will return a handle to the image
                eventType = MoSync.Constants.MA_IMAGE_PICKER_EVENT_RETURN_TYPE_IMAGE_HANDLE;

                // we need to keep a reference of the runtime in order to add image resources
                // and send the ImagePicker event
                runtimeReference = runtime;

                return OpenImagePicker();
            };

            /**
             * Sets the event type that the image picker will return after choosing an image.
             * \param eventType One of the next constants:
             * - #MA_IMAGE_PICKER_EVENT_TYPE_IMAGE_HANDLE
             * - #MA_IMAGE_PICKER_EVENT_TYPE_IMAGE_DATA
             */
            ioctls.maImagePickerOpenWithEventReturnType = delegate(int eventType)
            {
                // we need to keep a reference of the runtime in order to add image resources
                // and send the ImagePicker event
                runtimeReference = runtime;

                if (eventType == MoSync.Constants.MA_IMAGE_PICKER_EVENT_RETURN_TYPE_IMAGE_DATA ||
                    eventType == MoSync.Constants.MA_IMAGE_PICKER_EVENT_RETURN_TYPE_IMAGE_HANDLE)
                {
                    this.eventType = eventType;

                    return OpenImagePicker();
                }

                return MoSync.Constants.MAW_RES_ERROR;
            };
        }
Example #13
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            InitExtensions(core, runtime);

            ioctls.maExtensionModuleLoad = delegate(int _name, int _hash)
            {
                int handle = MoSync.Constants.MA_EXTENSION_MODULE_UNAVAILABLE;

                String name = core.GetDataMemory().ReadStringAtAddress(_name);
                IExtensionModule module = null;
                if((module = GetModule(name, out handle)) != null)
                {
                    if (module.GetHash() != (uint)_hash)
                    {
                        MoSync.Util.CriticalError("Invalid extension hash!");
                    }

                    return handle;
                }

                return handle;
            };

            ioctls.maExtensionFunctionLoad = delegate(int _module, int _index)
            {
                int handle = MoSync.Constants.MA_EXTENSION_FUNCTION_UNAVAILABLE;

                if (_module >= 0 && _module < mModules.Count)
                {
                    // maybe have method count as a generated part of the extension
                    return (_module << 8) | (_index&0xff);
                }

                return handle;
            };
        }
        public long Invoke(MoSync.Core core, int id, int a, int b, int c)
        {
            long result = MoSync.Constants.MA_EXTENSION_FUNCTION_UNAVAILABLE;

            switch (id)
            {
            case 1:
                if (maSillyTest == null)
                {
                    result = MoSync.Constants.IOCTL_UNAVAILABLE;
                }
                else
                {
                    result = maSillyTest(a);
                }
#if SYSCALL_LOG
                Util.Log("maSillyTest(" +
                         a +
                         "): " + result + "\n");
#endif
                return(result);
            }
            return(result);
        }
        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;

            // 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)
            {
            };

            syscalls.maGetClipRect = delegate(int cliprect)
            {
            };

            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)
            {
                mCurrentDrawTarget.DrawLine(x1, y1, x2, y2, (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);
                    newPoints[i * 2 + 1] = core.GetDataMemory().ReadInt32(points + i * 8 + 4);
                }
                newPoints[count * 2 + 0] = core.GetDataMemory().ReadInt32(points + 0);
                newPoints[count * 2 + 1] = core.GetDataMemory().ReadInt32(points + 4);
                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);
                    ycoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + 4);
                }

                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 + 0);
                int srcRectY = dataMemory.ReadInt32(srcRectPtr + 4);
                int srcRectW = dataMemory.ReadInt32(srcRectPtr + 8);
                int srcRectH = dataMemory.ReadInt32(srcRectPtr + 12);
                int dstPointX = dataMemory.ReadInt32(dstPointPtr + 0);
                int dstPointY = dataMemory.ReadInt32(dstPointPtr + 4);

                Rect srcRect = new Rect(srcRectX, srcRectY, srcRectW, srcRectH);
                Rect dstRect = new Rect(dstPointX, dstPointY, srcRectW, srcRectH);
                // mCurrentDrawTarget.Blit(dstRect, src, srcRect, WriteableBitmapExtensions.BlendMode.Alpha);

                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 + 0);
                int dstY = dataMemory.ReadInt32(_dstPoint + 4);
                int srcRectX = dataMemory.ReadInt32(_srcRect + 0);
                int srcRectY = dataMemory.ReadInt32(_srcRect + 4);
                int srcRectW = dataMemory.ReadInt32(_srcRect + 8);
                int srcRectH = dataMemory.ReadInt32(_srcRect + 12);
                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 + 0);
                int srcRectY = dataMemory.ReadInt32(_srcRect + 4);
                int srcRectW = dataMemory.ReadInt32(_srcRect + 8);
                int srcRectH = dataMemory.ReadInt32(_srcRect + 12);
                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;
            };
        }
Example #16
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            /**
             * Shows a dialog widget.
             * \param _dialogHandle The handle of the dialog that will be shown.
             *
             * \returns Any of the following result codes:
             * - #MAW_RES_OK if the child could be removed from the parent.
             * - #MAW_RES_INVALID_HANDLE if the handle was invalid.
             * - #MAW_RES_ERROR otherwise.
             */
            ioctls.maWidgetModalDialogShow = delegate(int _dialogHandle)
            {
                if (!isHandleValid(runtime, _dialogHandle))
                {
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                }

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    ModalDialog modalDialog = ((ModalDialog)runtime.GetModule<NativeUIModule>().GetWidget(_dialogHandle));
                    if (modalDialog.Visible.Equals("false"))
                    {
                        // show the dialog
                        modalDialog.ShowDialog(true);

                        // set the dialog visibility
                        modalDialog.Visible = "true";
                    }
                });

                return MoSync.Constants.MAW_RES_OK;
            };

            /**
             * Hides/Dismisses a currently displayed dialog.
             * \param _dialogHandle The handle of the dialog that will be hidden.
             *
             * \returns Any of the following result codes:
             * - #MAW_RES_OK if the child could be removed from the parent.
             * - #MAW_RES_INVALID_HANDLE if the handle was invalid.
             * - #MAW_RES_ERROR otherwise.
             */
            ioctls.maWidgetModalDialogHide = delegate(int _dialogHandle)
            {
                if (!isHandleValid(runtime, _dialogHandle))
                {
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                }

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    ModalDialog modalDialog = ((ModalDialog)runtime.GetModule<NativeUIModule>().GetWidget(_dialogHandle));
                    if (modalDialog.Visible.Equals("true"))
                    {
                        // hide the dialog
                        modalDialog.ShowDialog(false);

                        // set the dialog visibility
                        modalDialog.Visible = "false";
                    }
                });

                return MoSync.Constants.MAW_RES_OK;
            };
        }
        /**
         * Creates the application bar menu items and ads them to the application bar
         * @param _core: the Core class provides helper functions that read/write from/to a certain memory address
         * @param _buttonTitles: an integet representing the address of the button titles buffer start
         */
        private void createOptionButtons(Core _core, int _buttonTitles)
        {
            /**
             * Read an array of string from a given address for a specified field.
             * Strings will be stored in mOtherButtonTitles array.
             * @param address The specified address.
             *                The address must have the following structure:
             *                     - the first element must be a 4-byte int that specifies
             *                       the number of strings that can be read.
             *                     - first null terminated string(UTF-16 encoding).
             *                     - second null terminated string(UTF-16 encoding).
             *                     - etc
             * @param size The size of the buffer buffer from where the string will be read.
             */
            int address = _buttonTitles;
            int numberOfTitles = _core.GetDataMemory().ReadInt32(address);
            address += sizeof(int);
            for (int i = 0; i < numberOfTitles; i++)
            {
                String applicationMenuButtonTitle = _core.GetDataMemory().ReadWStringAtAddress(address);
                // the encoding is UTF16 so the address of the next string is after all the characters and a null
                address += applicationMenuButtonTitle.Length * sizeof(char) + sizeof(char);

                ApplicationBarMenuItem applicationBarMenuItem = new ApplicationBarMenuItem();
                applicationBarMenuItem.Text = applicationMenuButtonTitle;
                applicationBarMenuItem.Click += new EventHandler(applicationBarMenuItem_Click);
                mApplicationBar.MenuItems.Add(applicationBarMenuItem);

                mApplicationBarMenuItems.Add(applicationBarMenuItem);
            }
        }
Example #18
0
        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);
                fileStream.Seek(0, SeekOrigin.Begin);
                fileStream.Read(mem.GetBuffer(), 0, (int)fileStream.Length);
                runtime.SetResource(_placeholder, new Resource(mem, MoSync.Constants.RT_BINARY));
                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);
            };
        }
Example #19
0
        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;
                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];
                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(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maSensorStart = delegate(int _sensor, int _interval)
            {
                _interval = GetSensorIntervalDefaults(_interval);

                TimeSpan time = TimeSpan.FromMilliseconds((double)_interval);

                if (_sensor == MoSync.Constants.SENSOR_TYPE_ACCELEROMETER &&
                        Accelerometer.IsSupported)
                {
                    if (mAccelerometer != null)
                        return MoSync.Constants.SENSOR_ERROR_ALREADY_ENABLED;

                    mAccelerometer = new Accelerometer();
                    mAccelerometer.TimeBetweenUpdates = time;
                    mAccelerometer.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs<AccelerometerReading> args)
                        {
                            Vector3 acc = args.SensorReading.Acceleration;
                            SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_ACCELEROMETER, acc);
                        };

                    mAccelerometer.Start();
                }
                else if (_sensor == MoSync.Constants.SENSOR_TYPE_GYROSCOPE &&
                        Gyroscope.IsSupported)
                {
                    if (mGyroscope != null)
                        return MoSync.Constants.SENSOR_ERROR_ALREADY_ENABLED;

                    mGyroscope = new Gyroscope();
                    mGyroscope.TimeBetweenUpdates = time;
                    mGyroscope.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs<GyroscopeReading> args)
                        {
                            Vector3 rot = args.SensorReading.RotationRate;
                            SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_GYROSCOPE, rot);

                        };

                    mGyroscope.Start();
                }
                else if ((_sensor == MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD || _sensor == MoSync.Constants.SENSOR_TYPE_COMPASS) &&
                        Compass.IsSupported)
                {
                    if (_sensor == MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD &&
                        mMagneticFieldEnabled == true)
                        return MoSync.Constants.SENSOR_ERROR_ALREADY_ENABLED;

                    if (_sensor == MoSync.Constants.SENSOR_TYPE_COMPASS &&
                        mCompassEnabled == true)
                        return MoSync.Constants.SENSOR_ERROR_ALREADY_ENABLED;

                    if (mCompass == null)
                    {
                        mCompass = new Compass();
                        mCompass.TimeBetweenUpdates = time;
                    }
                    else
                    {
                        if(time < mCompass.TimeBetweenUpdates)
                            mCompass.TimeBetweenUpdates = time;
                    }

                    if (mCompassEnabled == false && mMagneticFieldEnabled == false)
                    {
                        mCompass.CurrentValueChanged +=
                            delegate(object sender, SensorReadingEventArgs<CompassReading> args)
                            {
                                if (mMagneticFieldEnabled)
                                {
                                    Vector3 rot = args.SensorReading.MagnetometerReading;
                                    SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD, rot);
                                }

                                if (mCompassEnabled)
                                {
                                    Vector3 heading = new Vector3();
                                    heading.X = (float)args.SensorReading.MagneticHeading;
                                    SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_COMPASS, heading);
                                }
                            };

                        mCompass.Start();
                    }

                    if (_sensor == MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD)
                        mMagneticFieldEnabled = true;
                    else if (_sensor == MoSync.Constants.SENSOR_TYPE_COMPASS)
                        mCompassEnabled = true;
                }

            #if false
            else if (_sensor == MoSync.Constants.SENSOR_TYPE_ORIENTATION &&
                    Motion.IsSupported)
                {
                    mMotion = new Motion();
                    mMotion.TimeBetweenUpdates = new TimeSpan(intervalIn100Nanoseconds);
                    mMotion.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs<MotionReading> args)
                        {
                        };
                }
            #endif
                else
                    return MoSync.Constants.SENSOR_ERROR_NOT_AVAILABLE;

                return MoSync.Constants.SENSOR_ERROR_NONE;
            };

            ioctls.maSensorStop = delegate(int _sensor)
            {
                switch (_sensor)
                {
                    case MoSync.Constants.SENSOR_TYPE_ACCELEROMETER:
                        if (mAccelerometer != null)
                        {
                            mAccelerometer.Stop();
                            mAccelerometer = null;
                        }
                        else
                        {
                            return MoSync.Constants.SENSOR_ERROR_NOT_ENABLED;
                        }
                        break;
                    case MoSync.Constants.SENSOR_TYPE_GYROSCOPE:
                        if (mGyroscope != null)
                        {
                            mGyroscope.Stop();
                            mGyroscope = null;
                        }
                        else
                        {
                            return MoSync.Constants.SENSOR_ERROR_NOT_ENABLED;
                        }
                        break;
                    case MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD:
                        if(!mMagneticFieldEnabled)
                            return MoSync.Constants.SENSOR_ERROR_NOT_ENABLED;

                        if (mCompass != null && !mCompassEnabled)
                        {
                            mCompass.Stop();
                            mCompass = null;
                        }

                        mMagneticFieldEnabled = false;
                        break;
                    case MoSync.Constants.SENSOR_TYPE_COMPASS:
                        if (!mCompassEnabled)
                            return MoSync.Constants.SENSOR_ERROR_NOT_ENABLED;

                        if (mCompass != null && !mMagneticFieldEnabled)
                        {
                            mCompass.Stop();
                            mCompass = null;
                        }
                        mCompassEnabled = false;
                        break;
                    case MoSync.Constants.SENSOR_TYPE_ORIENTATION:
                        if (mMotion != null)
                        {
                            mMotion.Stop();
                            mMotion = null;
                        }
                        else
                        {
                            return MoSync.Constants.SENSOR_ERROR_NOT_ENABLED;
                        }
                        break;
                }
                return MoSync.Constants.SENSOR_ERROR_NONE;
            };

            ioctls.maLocationStart = delegate()
            {
                if (mGeoWatcher == null)
                {
                    mGeoWatcher = new GeoCoordinateWatcher();
                    //mGeoWatcher.MovementThreshold = 20;

                    mGeoWatcher.StatusChanged += delegate(object sender,
                        GeoPositionStatusChangedEventArgs args)
                    {
                        int maState;
                        switch (args.Status)
                        {
                            case GeoPositionStatus.Disabled:
                                maState = MoSync.Constants.MA_LPS_OUT_OF_SERVICE;
                                break;
                            case GeoPositionStatus.NoData:
                            case GeoPositionStatus.Initializing:
                                maState = MoSync.Constants.MA_LPS_TEMPORARILY_UNAVAILABLE;
                                break;
                            case GeoPositionStatus.Ready:
                                maState = MoSync.Constants.MA_LPS_AVAILABLE;
                                break;
                            default:
                                throw new Exception("invalid GeoPositionStatus");
                        }
                        Memory evt = new Memory(2 * 4);
                        evt.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_LOCATION_PROVIDER);
                        evt.WriteInt32(MoSync.Struct.MAEvent.state, maState);
                        runtime.PostEvent(new Event(evt));
                    };

                    mGeoWatcher.PositionChanged += delegate(object sender,
                        GeoPositionChangedEventArgs<GeoCoordinate> args)
                    {
                        int maValidity = args.Position.Location.IsUnknown ?
                            MoSync.Constants.MA_LOC_INVALID : MoSync.Constants.MA_LOC_QUALIFIED;
                        Memory evt = new Memory(4 + 4 * 8 + 4);
                        GeoCoordinate l = args.Position.Location;
                        evt.WriteInt32(MoSync.Struct.MALocation.state, maValidity);
                        evt.WriteDouble(MoSync.Struct.MALocation.lat, l.Latitude);
                        evt.WriteDouble(MoSync.Struct.MALocation.lon, l.Longitude);
                        evt.WriteDouble(MoSync.Struct.MALocation.horzAcc, l.HorizontalAccuracy);
                        evt.WriteDouble(MoSync.Struct.MALocation.vertAcc, l.VerticalAccuracy);
                        evt.WriteFloat(MoSync.Struct.MALocation.alt, (float)l.Altitude);
                        runtime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_LOCATION, evt);
                    };

                    mGeoWatcher.Start();
                }

                return 0;
            };

            ioctls.maLocationStop = delegate()
            {
                if (mGeoWatcher != null)
                {
                    mGeoWatcher.Stop();
                    mGeoWatcher = null;
                }

                return 0;
            };
        }
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            InitAvailableFonts();

            ioctls.maFontGetCount = delegate()
            {
                return mAvailableFonts.Count;
            };

            ioctls.maFontGetName = delegate(int _index, int _buffer, int _bufferLen)
            {
                if (_index > ioctls.maFontGetCount())
                {
                    return MoSync.Constants.RES_FONT_INDEX_OUT_OF_BOUNDS;
                }
                else
                {
                    String fontName = mAvailableFonts[_index].GetFullName();

                    if (fontName.Length > _bufferLen) return MoSync.Constants.RES_FONT_INSUFFICIENT_BUFFER;
                    core.GetDataMemory().WriteStringAtAddress(_buffer, fontName, _bufferLen);
                    return MoSync.Constants.RES_FONT_OK;
                }
            };

            ioctls.maFontLoadWithName = delegate(int _postScriptName, int _size)
            {

                String fontName = core.GetDataMemory().ReadStringAtAddress(_postScriptName);

                foreach (FontInfo finfo in mAvailableFonts)
                {
                    if (finfo.GetFullName() == fontName)
                    {
                        mFonts.Add(finfo);
                        return mFonts.Count - 1;
                    }
                }

                return MoSync.Constants.RES_FONT_NAME_NONEXISTENT;
            };

            ioctls.maFontLoadDefault = delegate(int _type, int _style, int _size)
            {

                //RES_FONT_NO_TYPE_STYLE_COMBINATION
                //RES_FONT_INVALID_SIZE
                foreach (FontInfo finfo in mAvailableFonts)
                {
                    if (finfo.GetFullName() == "Segoe WP")
                    {
                        mFonts.Add(finfo);
                        return mFonts.Count - 1;
                    }
                }

                switch (_type)
                {
                    case MoSync.Constants.FONT_TYPE_MONOSPACE:
                        break;
                    case MoSync.Constants.FONT_TYPE_SERIF:
                        break;
                    case MoSync.Constants.FONT_TYPE_SANS_SERIF:
                        break;
                    default:
                        return MoSync.Constants.RES_FONT_NO_TYPE_STYLE_COMBINATION;
                }

                return 0;
            };
        }
        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(MAEvent_type, MoSync.Constants.EVENT_TYPE_CONN);
                evt.WriteInt32(MAConnEventData_handle, handle);
                evt.WriteInt32(MAConnEventData_opType, connOp);
                evt.WriteInt32(MAConnEventData_result, result);
                runtime.PostEvent(new Event(evt));
            };

            syscalls.maConnect = delegate(int _url)
            {
                String url = core.GetDataMemory().ReadStringAtAddress(_url);
                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)
            {
                Connection c = mConnections[_conn];
                return c.getAddr(_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);
                Memory mem = (Memory)res.GetInternalObject();
                runtime.SetResourceRaw(_data, Resource.Flux);
                cd(c, mem.GetData(),
                    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);
                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);
                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(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maFrameBufferInit = delegate(int frameBufferPointer)
            {
                Syscalls syscalls = runtime.GetSyscalls();
                mOldUpdateScreenImplementation = syscalls.maUpdateScreen;

                syscalls.maUpdateScreen = delegate()
                {
                    int[] dst = mFrontBuffer.Pixels;
                    Memory mem = core.GetDataMemory();
                    for (int i = 0; i < dst.Length; i++)
                    {
                        dst[i] = (int)(0xff000000 | mem.ReadUInt32(frameBufferPointer + i * 4));
                    }

                    InvalidateWriteableBitmapOnMainThread(mFrontBuffer);
                };

                return 1;
            };

            ioctls.maFrameBufferClose = delegate()
            {
                Syscalls syscalls = runtime.GetSyscalls();
                syscalls.maUpdateScreen = mOldUpdateScreenImplementation;
                return 1;
            };

            ioctls.maFrameBufferGetInfo = delegate(int info)
            {
                const int MAFrameBufferInfo_sizeInBytes = 0;
                const int MAFrameBufferInfo_bytesPerPixel = 4;
                const int MAFrameBufferInfo_bitsPerPixel = 8;
                const int MAFrameBufferInfo_redMask = 12;
                const int MAFrameBufferInfo_redShift = 16;
                const int MAFrameBufferInfo_redBits = 20;
                const int MAFrameBufferInfo_greenMask = 24;
                const int MAFrameBufferInfo_greenShift = 28;
                const int MAFrameBufferInfo_greenBits = 32;
                const int MAFrameBufferInfo_blueMask = 36;
                const int MAFrameBufferInfo_blueShift = 40;
                const int MAFrameBufferInfo_blueBits = 44;
                const int MAFrameBufferInfo_width = 48;
                const int MAFrameBufferInfo_height = 52;
                const int MAFrameBufferInfo_pitch = 56;
                const int MAFrameBufferInfo_supportsGfxSyscalls = 60;

                Memory mem = core.GetDataMemory();
                mem.WriteInt32(info + MAFrameBufferInfo_sizeInBytes, mBackBuffer.PixelWidth * mBackBuffer.PixelHeight * 4);
                mem.WriteInt32(info + MAFrameBufferInfo_bytesPerPixel, 4);
                mem.WriteInt32(info + MAFrameBufferInfo_bitsPerPixel, 32);
                mem.WriteUInt32(info + MAFrameBufferInfo_redMask, 0x00ff0000);
                mem.WriteUInt32(info + MAFrameBufferInfo_redBits, 8);
                mem.WriteUInt32(info + MAFrameBufferInfo_redShift, 16);
                mem.WriteUInt32(info + MAFrameBufferInfo_greenMask, 0x0000ff00);
                mem.WriteUInt32(info + MAFrameBufferInfo_greenBits, 8);
                mem.WriteUInt32(info + MAFrameBufferInfo_greenShift, 8);
                mem.WriteUInt32(info + MAFrameBufferInfo_blueMask, 0x000000ff);
                mem.WriteUInt32(info + MAFrameBufferInfo_blueBits, 8);
                mem.WriteUInt32(info + MAFrameBufferInfo_blueShift, 0);
                mem.WriteInt32(info + MAFrameBufferInfo_width, mBackBuffer.PixelWidth);
                mem.WriteInt32(info + MAFrameBufferInfo_height, mBackBuffer.PixelHeight);
                mem.WriteInt32(info + MAFrameBufferInfo_pitch, mBackBuffer.PixelWidth * 4);
                mem.WriteUInt32(info + MAFrameBufferInfo_supportsGfxSyscalls, 0);
                return 1;
            };
        }
Example #24
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);
                    IAudioData ad = Audio.FromUrlOrFilePath(url, (_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.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);
                    IAudioData 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;
            };
        }
Example #25
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            mNativeUI = new NativeUI.NativeUIWindowsPhone();
            //mWidgets.Add(null); // why?

            ioctls.maWidgetCreate = delegate(int _widgetType)
            {
                String widgetType = core.GetDataMemory().ReadStringAtAddress(_widgetType);
                IWidget widget = mNativeUI.CreateWidget(widgetType);
                if (widget == null)
                    return MoSync.Constants.MAW_RES_INVALID_TYPE_NAME;

                widget.SetRuntime(runtime);

                for (int i = 0; i < mWidgets.Count; i++)
                {
                    if (mWidgets[i] == null)
                    {
                        widget.SetHandle(i);
                        mWidgets[i] = widget;
                        return i;
                    }
                }

                mWidgets.Add(widget);
                widget.SetHandle(mWidgets.Count - 1);
                return mWidgets.Count-1;
            };

            ioctls.maWidgetDestroy = delegate(int _widget)
            {
                if (_widget < 0 || _widget >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget widget = mWidgets[_widget];
                widget.RemoveFromParent();
                mWidgets[_widget] = null;
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetAddChild = delegate(int _parent, int _child)
            {
                if (_parent < 0 || _parent >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget parent = mWidgets[_parent];
                if (_child < 0 || _child >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget child = mWidgets[_child];
                child.SetParent(parent);
                parent.AddChild(child);
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetRemoveChild = delegate(int _child)
            {
                if (_child < 0 || _child >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget child = mWidgets[_child];
                child.RemoveFromParent();
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetInsertChild = delegate(int _parent, int _child, int index)
            {
                if (_parent < 0 || _parent >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget parent = mWidgets[_parent];
                if (_child < 0 || _child >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget child = mWidgets[_child];
                parent.InsertChild(child, index);
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetStackScreenPush = delegate(int _stackScreen, int _newScreen)
            {
                IScreen stackScreen = (IScreen)mWidgets[_stackScreen];
                IScreen newScreen = (IScreen)mWidgets[_newScreen];
                (stackScreen as MoSync.NativeUI.StackScreen).Push(newScreen);
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetStackScreenPop = delegate(int _stackScreen)
            {
                IScreen stackScreen = (IScreen)mWidgets[_stackScreen];
                (stackScreen as MoSync.NativeUI.StackScreen).Pop();
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetSetProperty = delegate(int _widget, int _property, int _value)
            {
                String property = core.GetDataMemory().ReadStringAtAddress(_property);
                String value = core.GetDataMemory().ReadStringAtAddress(_value);
                if (_widget < 0 || _widget >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget widget = mWidgets[_widget];
                try
                {
                    widget.SetProperty(property, value);
                }
                catch (InvalidPropertyNameException)
                {
                    MoSync.Util.Log(widget.GetType().ToString() + " invalid property name: " + property);
                    return MoSync.Constants.MAW_RES_INVALID_PROPERTY_NAME;
                }
                catch (InvalidPropertyValueException e)
                {
                    MoSync.Util.Log(e);
                    return MoSync.Constants.MAW_RES_INVALID_PROPERTY_VALUE;
                }

                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetGetProperty = delegate(int _widget, int _property, int _value, int _bufSize)
            {
                String property = core.GetDataMemory().ReadStringAtAddress(_property);
                if (_widget < 0 || _widget >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget widget = mWidgets[_widget];
                try
                {
                    String value = widget.GetProperty(property);
                    core.GetDataMemory().WriteStringAtAddress(_value, value, _bufSize);
                }
                catch (InvalidPropertyNameException e)
                {
                    MoSync.Util.Log(e);
                    return MoSync.Constants.MAW_RES_INVALID_PROPERTY_NAME;
                }

                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetScreenShow = delegate(int _screenHandle)
            {
                if (_screenHandle < 0 || _screenHandle >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IScreen screen = (IScreen)mWidgets[_screenHandle];
                screen.Show();
                return MoSync.Constants.MAW_RES_OK;
            };
        }
Example #26
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            mNativeUI = new NativeUI.AsyncNativeUIWindowsPhone(runtime);
            //mWidgets.Add(null); // why?

            // initialize the widget thread dictionary
            mWidgetThreadDictionary = new Dictionary<int, Thread>();

            mWidgetTypeDictionary = new Dictionary<int, Type>();

            /**
             * This will add a OrientationChanged event handler to the Application.Current.RootVisual, this is application wide.
             */
            (Application.Current.RootVisual as Microsoft.Phone.Controls.PhoneApplicationFrame).OrientationChanged += delegate(object from, Microsoft.Phone.Controls.OrientationChangedEventArgs args)
            {
                PhoneApplicationPage currentPage = (((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage);

                int mosyncScreenOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UP;
                switch (currentPage.Orientation)
                {
                    case PageOrientation.Landscape:
                        mosyncScreenOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE;
                        break;
                    case PageOrientation.LandscapeLeft:
                        mosyncScreenOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_LEFT;
                        break;
                    case PageOrientation.LandscapeRight:
                        mosyncScreenOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_RIGHT;
                        break;
                    case PageOrientation.Portrait:
                        mosyncScreenOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UP;
                        break;
                    case PageOrientation.PortraitDown:
                        mosyncScreenOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UPSIDE_DOWN;
                        break;
                    case PageOrientation.PortraitUp:
                        mosyncScreenOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UP;
                        break;
                }

                // Post event handled Moblet.
                Memory eventData = new Memory(8);
                const int MAEventData_eventType = 0;
                const int MAEventData_orientation = 4;
                eventData.WriteInt32(MAEventData_eventType, MoSync.Constants.EVENT_TYPE_ORIENTATION_DID_CHANGE);
                eventData.WriteInt32(MAEventData_orientation, mosyncScreenOrientation);

                runtime.PostEvent(new Event(eventData));
            };

            ioctls.maWidgetCreate = delegate(int _widgetType)
            {
                String widgetTypeName = core.GetDataMemory().ReadStringAtAddress(_widgetType);

                Type widgetType = mNativeUI.VerifyWidget(widgetTypeName);
                if (widgetType == null)
                {
                    return MoSync.Constants.MAW_RES_INVALID_TYPE_NAME;
                }
                IWidget widget = new WidgetBaseMock();
                widget.SetRuntime(runtime);

                int widgetHandle = FindSpaceForWidget();
                if (widgetHandle == -1)
                {
                    mWidgets.Add(widget);
                    widgetHandle = mWidgets.Count - 1;
                }
                else
                {
                    mWidgets[widgetHandle] = widget;
                }
                widget.SetHandle(widgetHandle);
                StartWidgetCreationThread(widgetHandle, widgetType);

                return widgetHandle;
            };

            ioctls.maWidgetDestroy = delegate(int _widget)
            {
                if (_widget < 0 || _widget >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget widget = mWidgets[_widget];
                if (widget != null)
                {
                    mWidgetTypeDictionary.Remove(_widget);
                    Thread widgetCreationThread = null;
                    mWidgetThreadDictionary.TryGetValue(_widget, out widgetCreationThread);
                    if (widgetCreationThread != null)
                    {
                        if (widgetCreationThread.IsAlive)
                        {
                            widgetCreationThread.Join();
                        }
                        mWidgetThreadDictionary.Remove(_widget);
                    }

                    widget.RemoveFromParent();
                    mWidgets[_widget] = null;
                }
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetAddChild = delegate(int _parent, int _child)
            {
                if (_parent < 0 || _parent >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                if (_child < 0 || _child >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;

                IWidget parent = mWidgets[_parent];
                IWidget child = mWidgets[_child];
                mNativeUI.AddChild(parent, child);

                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetRemoveChild = delegate(int _child)
            {
                if (_child < 0 || _child >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;

                IWidget child = mWidgets[_child];
                // only the child is needed - it has a reference to its parent
                mNativeUI.RemoveChild(child);

                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetInsertChild = delegate(int _parent, int _child, int index)
            {
                if (_parent < 0 || _parent >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                if (_child < 0 || _child >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;

                IWidget parent = mWidgets[_parent];
                IWidget child = mWidgets[_child];
                mNativeUI.InsertChild(parent, child, index);

                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetStackScreenPush = delegate(int _stackScreen, int _newScreen)
            {
                IScreen stackScreen = (IScreen)mWidgets[_stackScreen];
                IScreen newScreen = (IScreen)mWidgets[_newScreen];
                (stackScreen as MoSync.NativeUI.StackScreen).Push(newScreen);
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetStackScreenPop = delegate(int _stackScreen)
            {
                IScreen stackScreen = (IScreen)mWidgets[_stackScreen];
                (stackScreen as MoSync.NativeUI.StackScreen).Pop();
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetSetProperty = delegate(int _widget, int _property, int _value)
            {
                if (_widget < 0 || _widget >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                String property = core.GetDataMemory().ReadStringAtAddress(_property);
                String value = core.GetDataMemory().ReadStringAtAddress(_value);
                IWidget widget = mWidgets[_widget];
                try
                {
                    mNativeUI.SetProperty(widget, property, value);
                }
                catch (InvalidPropertyNameException)
                {
                    return MoSync.Constants.MAW_RES_INVALID_PROPERTY_NAME;
                }
                catch (InvalidPropertyValueException)
                {
                    return MoSync.Constants.MAW_RES_INVALID_PROPERTY_VALUE;
                }

                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetGetProperty = delegate(int _widget, int _property, int _value, int _bufSize)
            {
                String property = core.GetDataMemory().ReadStringAtAddress(_property);
                if (_widget < 0 || _widget >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget widget = mWidgets[_widget];
                try
                {
                    // String value = widget.GetProperty(property);
                    String value = mNativeUI.GetProperty(widget, property);
                    core.GetDataMemory().WriteStringAtAddress(_value, value, _bufSize);
                }
                catch (InvalidPropertyNameException e)
                {
                    MoSync.Util.Log(e);
                    return MoSync.Constants.MAW_RES_INVALID_PROPERTY_NAME;
                }

                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetScreenShow = delegate(int _screenHandle)
            {
                if (_screenHandle < 0 || _screenHandle >= mWidgets.Count)
                {
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                }

                IScreen screen = null;

                if(mWidgets[_screenHandle] is IScreen)
                {
                    screen = (IScreen)mWidgets[_screenHandle];
                }
                else
                {
                    return MoSync.Constants.MAW_RES_INVALID_SCREEN;
                }

                mCurrentScreen = screen;

                screen.Show();
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetScreenShowWithTransition = delegate(int _screenHandle, int _screenTransitionType, int _screenTransitionDuration)
            {
                // Windows Phone Toolkit screen transitions do not have an time argument so _screenTransitionDuration
                // will be ignored on Windows platform.
                if (_screenHandle < 0 || _screenHandle >= mWidgets.Count)
                {
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                }

                IScreen screen = null;

                if (mWidgets[_screenHandle] is IScreen)
                {
                    screen = (IScreen)mWidgets[_screenHandle];
                }
                else
                {
                    return MoSync.Constants.MAW_RES_INVALID_SCREEN;
                }

                mCurrentScreen = screen;

                // If transition type is not available on this platform do show without transitions but return error code.
                if (!NativeUI.MoSyncScreenTransitions.isTransitionAvailable(_screenTransitionType))
                {
                    screen.ShowWithTransition(MoSync.Constants.MAW_TRANSITION_TYPE_NONE);
                    return MoSync.Constants.MAW_RES_INVALID_SCREEN_TRANSITION_TYPE;
                }

                screen.ShowWithTransition(_screenTransitionType);
                return MoSync.Constants.MAW_RES_OK;
            };

            /*
             * Implementation for maWidgetScreenAddOptionsMenuItem
             *
             * @param _widget the widget handle
             * @param _title the option menu item title
             * @param _iconPath the option menu item path
             *        Note: if the _iconPredefined param is 1 then the _iconPath
             *              will store a code representing the name of the icon file,
             *              without extension. Otherwise it should contain the name of the
             *              file. (e.g. "applicationBarIcon1.png")
             * @param _iconPredefined if the value is 1 it means that we expect a predefined icon
             *        otherwise it will create the path using the _iconPath as it was previously
             *        explained
             */
            ioctls.maWidgetScreenAddOptionsMenuItem = delegate(int _widget, int _title, int _iconPath, int _iconPredefined)
            {
                //This represents the hardcoded folder name for the application bar icons
                String applicationBarIconsFolder = "/AppBar.Icons/";

                //if _widget < 0 => no screen parent
                if (_widget < 0 || _widget >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;

                IScreen screen = (IScreen)mWidgets[_widget];

                //Read the icon path
                string iconPath = core.GetDataMemory().ReadStringAtAddress(_iconPath);

                //If the iconPath is not empty and we don't have a predefined icon
                //then we have an ApplicationBarButton object with a given icon and text.
                if (!iconPath.Equals("") && 0 == _iconPredefined && screen.GetApplicationBar().Buttons.Count < 5)
                {
                    //Read the text
                    string buttonText = core.GetDataMemory().ReadStringAtAddress(_title);

                    //Create the native object.
                    Microsoft.Phone.Shell.ApplicationBarIconButton btn = new Microsoft.Phone.Shell.ApplicationBarIconButton();

                    //Create the icon path.
                    btn.IconUri = new Uri(applicationBarIconsFolder + iconPath, UriKind.RelativeOrAbsolute);
                    btn.Text = buttonText;

                    //Associate an index to the native object.
                    int btnIndex = screen.AddApplicationBarItemIndex(btn);

                    btn.Click += new EventHandler(
                        delegate(object from, EventArgs target)
                        {
                            Memory eventData = new Memory(12);
                            const int MAWidgetEventData_eventType = 0;
                            const int MAWidgetEventData_widgetHandle = 4;
                            const int MAWidgetEventData_itemIndex = 8;
                            eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_OPTIONS_MENU_ITEM_SELECTED);
                            eventData.WriteInt32(MAWidgetEventData_widgetHandle, _widget);
                            eventData.WriteInt32(MAWidgetEventData_itemIndex, btnIndex);
                            //Posting a CustomEvent
                            runtime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                        });

                    screen.GetApplicationBar().Buttons.Add(btn);
                    screen.EnableApplicationBar();
                    return btnIndex;
                }
                //If the iconPath is not empty and we have a predefined icon
                //then we have an ApplicationBarButton object with a predefined icon and text.
                else if (!iconPath.Equals("") && _iconPredefined > 0 && screen.GetApplicationBar().Buttons.Count < 5)
                {
                    //Read the text.
                    string buttonText = core.GetDataMemory().ReadStringAtAddress(_title);

                    //Create the native object.
                    Microsoft.Phone.Shell.ApplicationBarIconButton btn = new Microsoft.Phone.Shell.ApplicationBarIconButton();

                    //Create the icon path.
                    btn.IconUri = new Uri(applicationBarIconsFolder + iconPath + ".png", UriKind.RelativeOrAbsolute);
                    btn.Text = buttonText;

                    //Associate an index to the native object.
                    int btnIndex = screen.AddApplicationBarItemIndex(btn);

                    btn.Click += new EventHandler(
                        delegate(object from, EventArgs target)
                        {
                            Memory eventData = new Memory(12);
                            const int MAWidgetEventData_eventType = 0;
                            const int MAWidgetEventData_widgetHandle = 4;
                            const int MAWidgetEventData_itemIndex = 8;
                            eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_OPTIONS_MENU_ITEM_SELECTED);
                            eventData.WriteInt32(MAWidgetEventData_widgetHandle, _widget);
                            eventData.WriteInt32(MAWidgetEventData_itemIndex, btnIndex);
                            //Posting a CustomEvent
                            runtime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                        });

                    screen.GetApplicationBar().Buttons.Add(btn);
                    screen.EnableApplicationBar();

                    //Return the index associated to the item.
                    return btnIndex;
                }
                //If the iconPath is empty then we have an ApplicationBarMenuItem.
                else
                {
                    //Read the text.
                    string menuItemText = core.GetDataMemory().ReadStringAtAddress(_title);

                    //Create the native object.
                    Microsoft.Phone.Shell.ApplicationBarMenuItem menuItem = new Microsoft.Phone.Shell.ApplicationBarMenuItem();
                    menuItem.Text = menuItemText;

                    //Associate an index to the native object.
                    int menuIndex = screen.AddApplicationBarItemIndex(menuItem);

                    menuItem.Click += new EventHandler(
                        delegate(object from, EventArgs target)
                        {
                            Memory eventData = new Memory(12);
                            const int MAWidgetEventData_eventType = 0;
                            const int MAWidgetEventData_widgetHandle = 4;
                            const int MAWidgetEventData_itemIndex = 8;
                            eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_OPTIONS_MENU_ITEM_SELECTED);
                            eventData.WriteInt32(MAWidgetEventData_widgetHandle, _widget);
                            eventData.WriteInt32(MAWidgetEventData_itemIndex, menuIndex);
                            //Posting a CustomEvent
                            runtime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                        });

                    screen.GetApplicationBar().MenuItems.Add(menuItem);
                    screen.EnableApplicationBar();

                    //Return the index associated to the item.
                    return menuIndex;
                }
            };
        }
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maSendTextSMS = delegate(int dst, int msg)
            {
                String number = core.GetDataMemory().ReadStringAtAddress(dst);
                String message = core.GetDataMemory().ReadStringAtAddress(msg);

                SmsComposeTask task = new SmsComposeTask();
                task.Body = message;
                task.To = number;
                task.Show();
                return 0;
            };
        }
Example #28
0
        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)
            {
                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);
                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);
                BitmapSource src = (BitmapSource)res.GetInternalObject();
                if (src == null)
                {
                    MoSync.Util.CriticalError("maGetImageSize used with an invalid image resource.");
                }
                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);

                GraphicsUtil.DrawImageRegion(mCurrentDrawTarget, dstPointX, dstPointY, srcRect, src, 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);
                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);
                    }
                }

                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)
            {
                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); // BlockCopy?
                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);
                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 void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            /**
             * Set supported screen orientations.
             * @param orientations A bitmask consisting of flags describing the supported screen orientations.
             * The bitmask can be created using \link #MA_SCREEN_ORIENTATION_ MA_SCREEN_ORIENTATION \endlink
             * values.
             * @return One of the next constants:
             * - #MA_SCREEN_ORIENTATION_RES_OK
             * - #MA_SCREEN_ORIENTATION_RES_NOT_SUPPORTED
             * - #MA_SCREEN_ORIENTATION_RES_INVALID_VALUE
             */
            ioctls.maScreenSetSupportedOrientations = delegate(int orientations)
            {
                // the bitmask contains the flags in the following order:
                // PORTRAIT, PORTRAIT_UPSIDE_DOWN, LANDSCAPE_LEFT and LANDSCAPE_RIGHT
                bool isPortrait = false;
                bool isLandscape = false;

                // if the first or the second bit is 1, it means that the portrait orientation is
                // currently accepted (because wp7 doesn't let you specify the
                // type of a portrait orientation when writing the SupportedOrientations
                // we consider that portrait is supported if PORTRAIT or PORTRAIT_UPSIDE_DOWN are
                // supported

                // check the first bit (PORTRAIT)g
                // ((A & (1 << bit)) != 0) checks if the bit 'bit - 1' is 1
                // For example, let's check if the bit 4 (starting from the least signifiant
                // bit = bit one) for A = 11001100 is 0 or not
                // 1<<3 -> 1000
                // 11001100 &
                // 00001000
                // --------
                // 00001000 != 0 -> the bit at position 4 is 1

                UInt32 o = 0;

                // check if the in param is valid
                if(!UInt32.TryParse(orientations.ToString(), out o))
                {
                    return MoSync.Constants.MA_SCREEN_ORIENTATION_RES_INVALID_VALUE;
                }

                // check the first and second bits
                if(((o & 1) != 0) | ((o & (1 << 1)) != 0))
                {
                    isPortrait = true;
                }

                // check the third bit (LANDSCAPE_LEFT) and the forth bit (LANDSCAPE_RIGHT)
                // we only need to check the Landscape
                if( ((o & (1 << 2)) != 0) | ((o & (1 << 3)) != 0) )
                {
                    isLandscape = true;
                }

                //check if we have an orientation
                if(!isPortrait && !isLandscape)
                {
                    return  MoSync.Constants.MA_SCREEN_ORIENTATION_RES_NOT_SUPPORTED;
                }

                // after checking the portrait and landscape modes, it's time to set
                // the page SupportedOrientations property (we do this on the UI thread)
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    PhoneApplicationPage currentPage = (((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage);
                    if (isPortrait && isLandscape)
                    {
                        currentPage.SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
                    }
                    else if (isPortrait && !isLandscape)
                    {
                        currentPage.SupportedOrientations = SupportedPageOrientation.Portrait;
                    }
                    else if (!isPortrait && isLandscape)
                    {
                        currentPage.SupportedOrientations = SupportedPageOrientation.Landscape;
                    }
                });

                return MoSync.Constants.MA_SCREEN_ORIENTATION_RES_OK;
            };

            /**
             * Set the screen orientation.
             * @param orientation One of the \link #SCREEN_ORIENTATION_LANDSCAPE
             * #SCREEN_ORIENTATION_PORTRAIT #SCREEN_ORIENTATION_DYNAMIC \endlink
             * constants.
             * @return \< 0 on error.
             */
            ioctls.maScreenSetOrientation = delegate(int orientation)
            {
                // there are only three options: SCREEN_ORIENTATION_LANDSCAPE(1), SCREEN_ORIENTATION_PORTRAIT(2),
                // SCREEN_ORIENTATION_DYNAMIC(3)
                if (orientation < 1 || orientation > 3)
                {
                    // error - not a valid input
                    return MoSync.Constants.MA_SCREEN_ORIENTATION_RES_INVALID_VALUE;
                }

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    // the orientation will be set on the current page
                    PhoneApplicationPage currentPage = (((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage);

                    switch (orientation)
                    {
                        case MoSync.Constants.SCREEN_ORIENTATION_PORTRAIT:
                            currentPage.SupportedOrientations = SupportedPageOrientation.Portrait;
                            break;
                        case MoSync.Constants.SCREEN_ORIENTATION_LANDSCAPE:
                            currentPage.SupportedOrientations = SupportedPageOrientation.Landscape;
                            break;
                        default:
                            // we consider the default case as being MoSync.Constants.SCREEN_ORIENTATION_DYNAMIC
                            // based on the device sensor
                            currentPage.SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
                            break;
                    }
                });

                return MoSync.Constants.MAW_RES_OK;
            };

            /**
             * Get supported screen orientations.
             * @return A bitmask consisting of flags describing the supported screen orientations.
             * The bitmask is created using \link #MA_SCREEN_ORIENTATION_ MA_SCREEN_ORIENTATION \endlink
             * values.
             */
            ioctls.maScreenGetSupportedOrientations = delegate()
            {
                int suportedOrientations = 0;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    PhoneApplicationPage currentPage = (((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage);

                    // based on the SupportedOrientations property, we create
                    // a bitmask containing the suported orientations. The bitmask will contain
                    // the orientations in the following order:
                    // PORTRAIT, PORTRAIT_UPSIDE_DOWN, LANDSCAPE_LEFT and LANDSCAPE_RIGHT
                    switch (currentPage.SupportedOrientations)
                    {
                        case SupportedPageOrientation.PortraitOrLandscape:
                            suportedOrientations = suportedOrientations |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UPSIDE_DOWN |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_LEFT |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_RIGHT;
                            break;
                        case SupportedPageOrientation.Landscape:
                            suportedOrientations = suportedOrientations |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_LEFT |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_RIGHT;
                            break;
                        case SupportedPageOrientation.Portrait:
                            suportedOrientations = suportedOrientations |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UPSIDE_DOWN;
                            break;
                        default:
                            break;
                    }
                });

                return suportedOrientations;
            };

            /**
             * Get current screen orientation.
             * @return One of the \link #MA_SCREEN_ORIENTATION_ MA_SCREEN_ORIENTATION \endlink constants.
             */
            ioctls.maScreenGetCurrentOrientation = delegate()
            {
                int currentOrientation = 0;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    PhoneApplicationPage currentPage = (((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage);
                    switch (currentPage.Orientation)
                    {
                        case PageOrientation.LandscapeRight:
                            currentOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_RIGHT;
                            break;
                        case PageOrientation.LandscapeLeft:
                            currentOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_LEFT;
                            break;
                        case PageOrientation.PortraitUp:
                            currentOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT;
                            break;
                        case PageOrientation.PortraitDown:
                            currentOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UPSIDE_DOWN;
                            break;
                        default:
                            break;
                    }
                });

                return currentOrientation;
            };
        }
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            mNativeUI = new NativeUI.NativeUIWindowsPhone();
            //mWidgets.Add(null); // why?

            ioctls.maWidgetCreate = delegate(int _widgetType)
            {
                String widgetType = core.GetDataMemory().ReadStringAtAddress(_widgetType);
                IWidget widget = mNativeUI.CreateWidget(widgetType);
                if (widget == null)
                    return MoSync.Constants.MAW_RES_INVALID_TYPE_NAME;

                widget.SetRuntime(runtime);

                for (int i = 0; i < mWidgets.Count; i++)
                {
                    if (mWidgets[i] == null)
                    {
                        widget.SetHandle(i);
                        mWidgets[i] = widget;
                        return i;
                    }
                }

                mWidgets.Add(widget);
                widget.SetHandle(mWidgets.Count - 1);
                return mWidgets.Count-1;
            };

            ioctls.maWidgetDestroy = delegate(int _widget)
            {
                if (_widget < 0 || _widget >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget widget = mWidgets[_widget];
                widget.RemoveFromParent();
                mWidgets[_widget] = null;
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetAddChild = delegate(int _parent, int _child)
            {
                if (_parent < 0 || _parent >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget parent = mWidgets[_parent];
                if (_child < 0 || _child >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget child = mWidgets[_child];
                child.SetParent(parent);
                parent.AddChild(child);
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetRemoveChild = delegate(int _child)
            {
                if (_child < 0 || _child >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget child = mWidgets[_child];
                child.RemoveFromParent();
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetInsertChild = delegate(int _parent, int _child, int index)
            {
                if (_parent < 0 || _parent >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget parent = mWidgets[_parent];
                if (_child < 0 || _child >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget child = mWidgets[_child];
                parent.InsertChild(child, index);
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetStackScreenPush = delegate(int _stackScreen, int _newScreen)
            {
                IScreen stackScreen = (IScreen)mWidgets[_stackScreen];
                IScreen newScreen = (IScreen)mWidgets[_newScreen];
                (stackScreen as MoSync.NativeUI.StackScreen).Push(newScreen);
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetStackScreenPop = delegate(int _stackScreen)
            {
                IScreen stackScreen = (IScreen)mWidgets[_stackScreen];
                (stackScreen as MoSync.NativeUI.StackScreen).Pop();
                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetSetProperty = delegate(int _widget, int _property, int _value)
            {
                String property = core.GetDataMemory().ReadStringAtAddress(_property);
                String value = core.GetDataMemory().ReadStringAtAddress(_value);
                if (_widget < 0 || _widget >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget widget = mWidgets[_widget];
                try
                {
                    widget.SetProperty(property, value);
                }
                catch (InvalidPropertyNameException)
                {
                    MoSync.Util.Log(widget.GetType().ToString() + " invalid property name: " + property);
                    return MoSync.Constants.MAW_RES_INVALID_PROPERTY_NAME;
                }
                catch (InvalidPropertyValueException e)
                {
                    MoSync.Util.Log(e);
                    return MoSync.Constants.MAW_RES_INVALID_PROPERTY_VALUE;
                }

                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetGetProperty = delegate(int _widget, int _property, int _value, int _bufSize)
            {
                String property = core.GetDataMemory().ReadStringAtAddress(_property);
                if (_widget < 0 || _widget >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IWidget widget = mWidgets[_widget];
                try
                {
                    String value = widget.GetProperty(property);
                    core.GetDataMemory().WriteStringAtAddress(_value, value, _bufSize);
                }
                catch (InvalidPropertyNameException e)
                {
                    MoSync.Util.Log(e);
                    return MoSync.Constants.MAW_RES_INVALID_PROPERTY_NAME;
                }

                return MoSync.Constants.MAW_RES_OK;
            };

            ioctls.maWidgetScreenShow = delegate(int _screenHandle)
            {
                if (_screenHandle < 0 || _screenHandle >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;
                IScreen screen = (IScreen)mWidgets[_screenHandle];
                screen.Show();
                return MoSync.Constants.MAW_RES_OK;
            };

            /*
             * Implementation for maWidgetScreenAddOptionsMenuItem
             *
             * @param _widget the widget handle
             * @param _title the option menu item title
             * @param _iconPath the option menu item path
             *        Note: if the _iconPredefined param is 1 then the _iconPath
             *              will store a code representing the name of the icon file,
             *              without extension. Otherwise it should contain the name of the
             *              file. (e.g. "applicationBarIcon1.png")
             * @param _iconPredefined if the value is 1 it means that we expect a predefined icon
             *        otherwise it will create the path using the _iconPath as it was previously
             *        explained
             */
            ioctls.maWidgetScreenAddOptionsMenuItem = delegate(int _widget, int _title, int _iconPath, int _iconPredefined)
            {
                //This represents the hardcoded folder name for the application bar icons
                String applicationBarIconsFolder = "/AppBar.Icons/";

                //if _widget < 0 => no screen parent
                if (_widget < 0 || _widget >= mWidgets.Count)
                    return MoSync.Constants.MAW_RES_INVALID_HANDLE;

                IScreen screen = (IScreen)mWidgets[_widget];

                //Read the icon path
                string iconPath = core.GetDataMemory().ReadStringAtAddress(_iconPath);

                //If the iconPath is not empty and we don't have a predefined icon
                //then we have an ApplicationBarButton object with a given icon and text.
                if (!iconPath.Equals("") && 0 == _iconPredefined && screen.GetApplicationBar().Buttons.Count < 5)
                {
                    //Read the text
                    string buttonText = core.GetDataMemory().ReadStringAtAddress(_title);

                    //Create the native object.
                    Microsoft.Phone.Shell.ApplicationBarIconButton btn = new Microsoft.Phone.Shell.ApplicationBarIconButton();

                    //Create the icon path.
                    btn.IconUri = new Uri(applicationBarIconsFolder + iconPath, UriKind.RelativeOrAbsolute);
                    btn.Text = buttonText;

                    //Associate an index to the native object.
                    int btnIndex = screen.AddApplicationBarItemIndex(btn);

                    btn.Click += new EventHandler(
                        delegate(object from, EventArgs target)
                        {
                            Memory eventData = new Memory(12);
                            const int MAWidgetEventData_eventType = 0;
                            const int MAWidgetEventData_widgetHandle = 4;
                            const int MAWidgetEventData_itemIndex = 8;
                            eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_OPTIONS_MENU_ITEM_SELECTED);
                            eventData.WriteInt32(MAWidgetEventData_widgetHandle, _widget);
                            eventData.WriteInt32(MAWidgetEventData_itemIndex, btnIndex);
                            //Posting a CustomEvent
                            runtime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                        });

                    screen.GetApplicationBar().Buttons.Add(btn);
                    screen.EnableApplicationBar();
                    return btnIndex;
                }
                //If the iconPath is not empty and we have a predefined icon
                //then we have an ApplicationBarButton object with a predefined icon and text.
                else if (!iconPath.Equals("") && _iconPredefined > 0 && screen.GetApplicationBar().Buttons.Count < 5)
                {
                    //Read the text.
                    string buttonText = core.GetDataMemory().ReadStringAtAddress(_title);

                    //Create the native object.
                    Microsoft.Phone.Shell.ApplicationBarIconButton btn = new Microsoft.Phone.Shell.ApplicationBarIconButton();

                    //Create the icon path.
                    btn.IconUri = new Uri(applicationBarIconsFolder + iconPath + ".png", UriKind.RelativeOrAbsolute);
                    btn.Text = buttonText;

                    //Associate an index to the native object.
                    int btnIndex = screen.AddApplicationBarItemIndex(btn);

                    btn.Click += new EventHandler(
                        delegate(object from, EventArgs target)
                        {
                            Memory eventData = new Memory(12);
                            const int MAWidgetEventData_eventType = 0;
                            const int MAWidgetEventData_widgetHandle = 4;
                            const int MAWidgetEventData_itemIndex = 8;
                            eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_OPTIONS_MENU_ITEM_SELECTED);
                            eventData.WriteInt32(MAWidgetEventData_widgetHandle, _widget);
                            eventData.WriteInt32(MAWidgetEventData_itemIndex, btnIndex);
                            //Posting a CustomEvent
                            runtime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                        });

                    screen.GetApplicationBar().Buttons.Add(btn);
                    screen.EnableApplicationBar();

                    //Return the index associated to the item.
                    return btnIndex;
                }
                //If the iconPath is empty then we have an ApplicationBarMenuItem.
                else
                {
                    //Read the text.
                    string menuItemText = core.GetDataMemory().ReadStringAtAddress(_title);

                    //Create the native object.
                    Microsoft.Phone.Shell.ApplicationBarMenuItem menuItem = new Microsoft.Phone.Shell.ApplicationBarMenuItem();
                    menuItem.Text = menuItemText;

                    //Associate an index to the native object.
                    int menuIndex = screen.AddApplicationBarItemIndex(menuItem);

                    menuItem.Click += new EventHandler(
                        delegate(object from, EventArgs target)
                        {
                            Memory eventData = new Memory(12);
                            const int MAWidgetEventData_eventType = 0;
                            const int MAWidgetEventData_widgetHandle = 4;
                            const int MAWidgetEventData_itemIndex = 8;
                            eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_EVENT_OPTIONS_MENU_ITEM_SELECTED);
                            eventData.WriteInt32(MAWidgetEventData_widgetHandle, _widget);
                            eventData.WriteInt32(MAWidgetEventData_itemIndex, menuIndex);
                            //Posting a CustomEvent
                            runtime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData);
                        });

                    screen.GetApplicationBar().MenuItems.Add(menuItem);
                    screen.EnableApplicationBar();

                    //Return the index associated to the item.
                    return menuIndex;
                }
            };
        }
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            mCamera = new PhotoCamera(CameraType.Primary);
            mVideoBrush = new VideoBrush();
            mVideoBrush.SetSource(mCamera);
            mVideoBrush.Stretch = Stretch.Uniform;

            runtime.RegisterCleaner(delegate()
            {
                mCamera.Dispose();
                mCamera = null;
            });

            // this should be set according to the orientation of
            // the device I guess.
            mVideoBrush.RelativeTransform = new CompositeTransform()
            {
                CenterX = 0.5,
                CenterY = 0.5,
                Rotation = 90
            };

            ioctls.maCameraFormat = delegate(int _index, int _fmt)
            {
                System.Windows.Size dim;
                if (GetCameraFormat(_index, out dim) == false)
                    return MoSync.Constants.MA_CAMERA_RES_FAILED;

                core.GetDataMemory().WriteInt32(_fmt + MoSync.Struct.MA_CAMERA_FORMAT.width,
                    (int)dim.Width);
                core.GetDataMemory().WriteInt32(_fmt + MoSync.Struct.MA_CAMERA_FORMAT.height,
                    (int)dim.Height);

                return MoSync.Constants.MA_CAMERA_RES_OK;
            };

            ioctls.maCameraFormatNumber = delegate()
            {
                IEnumerable<System.Windows.Size> res = mCamera.AvailableResolutions;
                if (res == null) return 0;
                IEnumerator<System.Windows.Size> resolutions = res.GetEnumerator();
                resolutions.MoveNext();
                int number = 0;
                while (resolutions.Current != null)
                {
                    number++;
                }
                return number;
            };

            ioctls.maCameraStart = delegate()
            {
                return 0;
            };

            ioctls.maCameraStop = delegate()
            {
                return 0;
            };

            ioctls.maCameraSetPreview = delegate(int _widgetHandle)
            {
                // something like
                // videoBrush = ((CameraViewFinder)runtime.GetModule<MoSyncNativeUIModule>.GetWidget(_widgetHandle)).GetBrush();
                // videoBrush.SetSource(mCamera)
                IWidget w = runtime.GetModule<NativeUIModule>().GetWidget(_widgetHandle);
                if (w.GetType() != typeof(MoSync.NativeUI.CameraPreview))
                {
                    return MoSync.Constants.MA_CAMERA_RES_FAILED;
                }
                NativeUI.CameraPreview prev = (NativeUI.CameraPreview)w;
                System.Windows.Controls.Canvas canvas = prev.GetViewFinderCanvas();
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    canvas.Background = mVideoBrush;
                });

                return 0;
            };

            ioctls.maCameraSelect = delegate(int _cameraNumber)
            {
                CameraType cameraType = CameraType.Primary;
                if(_cameraNumber == MoSync.Constants.MA_CAMERA_CONST_BACK_CAMERA)
                {
                    cameraType = CameraType.Primary;
                }
                else if(_cameraNumber == MoSync.Constants.MA_CAMERA_CONST_FRONT_CAMERA)
                {
                    cameraType = CameraType.FrontFacing;
                }

                if(mCamera==null || mCamera.CameraType != cameraType)
                {
                    mCamera = new PhotoCamera(cameraType);
                    if(mVideoBrush == null)
                        mVideoBrush = new VideoBrush();
                    mVideoBrush.SetSource(mCamera);
                }

                return 0;
            };

            ioctls.maCameraNumber = delegate()
            {
                // front facing and back facing is the standard I believe.
                return 2;
            };

            ioctls.maCameraSnapshot = delegate(int _formatIndex, int _placeHolder)
            {
                AutoResetEvent are = new AutoResetEvent(false);

                System.Windows.Size dim;
                if (GetCameraFormat(_formatIndex, out dim) == false)
                    return MoSync.Constants.MA_CAMERA_RES_FAILED;

                mCamera.Resolution = dim;

                if (mCameraSnapshotDelegate != null)
                    mCamera.CaptureImageAvailable -= mCameraSnapshotDelegate;
                mCameraSnapshotDelegate = delegate(object o, ContentReadyEventArgs args)
                {
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, _placeHolder);
                        Stream data = args.ImageStream;
                        Memory dataMem = new Memory((int)data.Length);
                        dataMem.WriteFromStream(0, data, (int)data.Length);
                        res.SetInternalObject(dataMem);
                    });
                    are.Set();
                };

                mCamera.CaptureImageAvailable += mCameraSnapshotDelegate;

                mCamera.CaptureImage();

                are.WaitOne();
                return 0;
            };

            ioctls.maCameraSetProperty = delegate(int _property, int _value)
            {
                return 0;
            };

            ioctls.maCameraSelect = delegate(int _camera)
            {
                return 0;
            };

            ioctls.maCameraGetProperty = delegate(int _property, int _value, int _bufSize)
            {
                String property = core.GetDataMemory().ReadStringAtAddress(_property);

                if (property.Equals(MoSync.Constants.MA_CAMERA_MAX_ZOOM))
                {
                    core.GetDataMemory().WriteStringAtAddress(
                        _value,
                        "0",
                        _bufSize);
                }

                return 0;
            };

            ioctls.maCameraRecord = delegate(int _stopStartFlag)
            {
                return 0;
            };
        }
        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;
            };
        }
Example #33
0
        protected void InitExtensions(Core core, Runtime runtime)
        {
            //Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            //foreach(Assembly a in assemblies)
            //foreach (Type t in a.GetTypes())
            foreach(Type t in Assembly.GetExecutingAssembly().GetTypes())
            {
                IExtensionModule extensionGroupInstance = null;
                if (t.GetInterface("MoSync.IExtensionModule", false) != null)
                {
                    extensionGroupInstance = Activator.CreateInstance(t) as IExtensionModule;
                    mModules.Add(extensionGroupInstance);
                }
            }

            foreach (IExtensionModule module in mModules)
            {
                module.Init(core, runtime);
            }
        }
Example #34
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maFontSetCurrent = delegate(int _font)
            {
                FontModule.FontInfo finfo = runtime.GetModule <FontModule>().GetFont(_font);
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    textBlock.FontFamily = finfo.family;
                    textBlock.FontStyle  = finfo.style;
                    textBlock.FontWeight = finfo.weight;
                    textBlock.FontSize   = finfo.size;
                });

                return(0);
            };

            ioctls.maFrameBufferInit = delegate(int frameBufferPointer)
            {
                Syscalls syscalls = runtime.GetSyscalls();
                mOldUpdateScreenImplementation = syscalls.maUpdateScreen;

                syscalls.maUpdateScreen = delegate()
                {
                    Memory mem = core.GetDataMemory();
                    int[]  dst = mFrontBuffer.Pixels;

                    //mFrontBuffer.FromByteArray(mem.GetData(), frameBufferPointer, dst.Length * 4);
                    System.Buffer.BlockCopy(mem.GetData(), frameBufferPointer, dst, 0, dst.Length * 4);
                    const int opaque = (int)(0xff << 24);
                    for (int i = 0; i < dst.Length; i++)
                    {
                        dst[i] |= opaque;
                    }

                    InvalidateWriteableBitmapBackBufferOnMainThread(mFrontBuffer);
                    WriteableBitmap temp = mFrontBuffer;
                    mFrontBuffer = mBackBuffer;
                    mBackBuffer  = temp;
                };

                return(1);
            };

            ioctls.maFrameBufferClose = delegate()
            {
                if (mOldUpdateScreenImplementation == null)
                {
                    return(0);
                }
                Syscalls syscalls = runtime.GetSyscalls();
                syscalls.maUpdateScreen        = mOldUpdateScreenImplementation;
                mOldUpdateScreenImplementation = null;
                if (mCurrentDrawTarget == mFrontBuffer)
                {
                    mCurrentDrawTarget = mBackBuffer;
                }

                System.Buffer.BlockCopy(mBackBuffer.Pixels, 0, mFrontBuffer.Pixels, 0, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight * 4);
                InvalidateWriteableBitmapBackBufferOnMainThread(mFrontBuffer);

                return(1);
            };

            ioctls.maFrameBufferGetInfo = delegate(int info)
            {
                Memory mem = core.GetDataMemory();
                mem.WriteInt32(info + MoSync.Struct.MAFrameBufferInfo.sizeInBytes, mBackBuffer.PixelWidth * mBackBuffer.PixelHeight * 4);
                mem.WriteInt32(info + MoSync.Struct.MAFrameBufferInfo.bytesPerPixel, 4);
                mem.WriteInt32(info + MoSync.Struct.MAFrameBufferInfo.bitsPerPixel, 32);
                mem.WriteUInt32(info + MoSync.Struct.MAFrameBufferInfo.redMask, 0x00ff0000);
                mem.WriteUInt32(info + MoSync.Struct.MAFrameBufferInfo.redBits, 8);
                mem.WriteUInt32(info + MoSync.Struct.MAFrameBufferInfo.redShift, 16);
                mem.WriteUInt32(info + MoSync.Struct.MAFrameBufferInfo.greenMask, 0x0000ff00);
                mem.WriteUInt32(info + MoSync.Struct.MAFrameBufferInfo.greenBits, 8);
                mem.WriteUInt32(info + MoSync.Struct.MAFrameBufferInfo.greenShift, 8);
                mem.WriteUInt32(info + MoSync.Struct.MAFrameBufferInfo.blueMask, 0x000000ff);
                mem.WriteUInt32(info + MoSync.Struct.MAFrameBufferInfo.blueBits, 8);
                mem.WriteUInt32(info + MoSync.Struct.MAFrameBufferInfo.blueShift, 0);
                mem.WriteInt32(info + MoSync.Struct.MAFrameBufferInfo.width, mBackBuffer.PixelWidth);
                mem.WriteInt32(info + MoSync.Struct.MAFrameBufferInfo.height, mBackBuffer.PixelHeight);
                mem.WriteInt32(info + MoSync.Struct.MAFrameBufferInfo.pitch, mBackBuffer.PixelWidth * 4);
                mem.WriteUInt32(info + MoSync.Struct.MAFrameBufferInfo.supportsGfxSyscalls, 0);
                return(1);
            };
        }