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()
            {
                mTask = new PhotoChooserTask();
                // a small camera icon will appear in the page application bar - this enables
                // the user to go to the camera and capture another image (which could be selected
                // by using the image picker afterwards)
                mTask.ShowCamera = true;
                mTask.Completed += PhotoChooserTaskCompleted;
                if (!photoTaskStarted)
                {
                    mTask.Show();
                }
                photoTaskStarted = true;

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

                return(MoSync.Constants.MAW_RES_OK);
            };
        }
Exemple #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;
            };
        }
Exemple #3
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maWriteLog = delegate(int src, int size)
            {
                byte[] bytes = new byte[size];
                core.GetDataMemory().ReadBytes(bytes, src, size);
                MoSync.Util.Log(bytes);
                return(0);
            };

            ioctls.maGetSystemProperty = delegate(int _key, int _buf, int _size)
            {
                String key   = core.GetDataMemory().ReadStringAtAddress(_key);
                String value = MoSync.SystemPropertyManager.GetSystemProperty(key);
                if (value == null)
                {
                    return(-2);
                }
                if (value.Length + 1 <= _size)
                {
                    core.GetDataMemory().WriteStringAtAddress(_buf, value, _size);
                }
                return(value.Length + 1);
            };
        }
Exemple #4
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maAudioDataCreateFromResource = delegate(int _mime, int _data, int _offset, int _length, int _flags)
            {
                return(MoSync.Constants.MA_AUDIO_ERR_INVALID_SOUND_FORMAT);
            };

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


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

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

            ioctls.maAudioPlay = delegate(int _audioInstance)
            {
                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };
        }
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maAudioDataCreateFromResource = delegate(int _mime, int _data, int _offset, int _length, int _flags)
            {

                return MoSync.Constants.MA_AUDIO_ERR_INVALID_SOUND_FORMAT;
            };

            ioctls.maAudioDataDestroy = delegate(int _audioData)
            {

                return MoSync.Constants.MA_AUDIO_ERR_OK;
            };

            ioctls.maAudioInstanceCreate = delegate(int _audioData)
            {

                return MoSync.Constants.MA_AUDIO_ERR_INVALID_DATA;
            };

            ioctls.maAudioInstanceDestroy = delegate(int _audioInstance)
            {

                return MoSync.Constants.MA_AUDIO_ERR_OK;
            };

            ioctls.maAudioPlay = delegate(int _audioInstance)
            {

                return MoSync.Constants.MA_AUDIO_ERR_OK;
            };
        }
        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;
            };
        }
        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);
            };
        } // end of Init
Exemple #8
0
        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)
            {
                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);
            };
        }
Exemple #9
0
        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);
            };
        }
        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);
            };
        }
Exemple #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;
            };
        }
Exemple #13
0
        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);
            };
        }
        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 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);
            };
        }
Exemple #16
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maSensorStart = delegate(int _sensor, int _interval)
            {
                long intervalIn100Nanoseconds = (long)_interval * 10000;
                if (_sensor == MoSync.Constants.SENSOR_TYPE_ACCELEROMETER &&
                    Accelerometer.IsSupported)
                {
                    mAccelerometer = new Accelerometer();
                    mAccelerometer.TimeBetweenUpdates   = new TimeSpan(intervalIn100Nanoseconds);
                    mAccelerometer.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs <AccelerometerReading> args)
                    {
                        Vector3 acc = args.SensorReading.Acceleration;
                        SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_ACCELEROMETER, acc);
                    };
                }
                else if (_sensor == MoSync.Constants.SENSOR_TYPE_GYROSCOPE &&
                         Gyroscope.IsSupported)
                {
                    mGyroscope = new Gyroscope();
                    mGyroscope.TimeBetweenUpdates   = new TimeSpan(intervalIn100Nanoseconds);
                    mGyroscope.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs <GyroscopeReading> args)
                    {
                        Vector3 rot = args.SensorReading.RotationRate;
                        SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_GYROSCOPE, rot);
                    };
                }
                else if (_sensor == MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD &&
                         Compass.IsSupported)
                {
                    mCompass = new Compass();
                    mCompass.TimeBetweenUpdates   = new TimeSpan(intervalIn100Nanoseconds);
                    mCompass.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs <CompassReading> args)
                    {
                        Vector3 rot = args.SensorReading.MagnetometerReading;
                        SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD, rot);
                    };
                }
#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;
                    }
                    break;

                case MoSync.Constants.SENSOR_TYPE_GYROSCOPE:
                    if (mGyroscope != null)
                    {
                        mGyroscope.Stop();
                        mGyroscope = null;
                    }
                    break;

                case MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD:
                    if (mCompass != null)
                    {
                        mCompass.Stop();
                        mCompass = null;
                    }
                    break;

                case MoSync.Constants.SENSOR_TYPE_ORIENTATION:
                    if (mMotion != null)
                    {
                        mMotion.Stop();
                        mMotion = null;
                    }
                    break;
                }
                return(MoSync.Constants.SENSOR_ERROR_NONE);
            };

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

            ioctls.maLocationStop = delegate()
            {
                return(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;
            };
        }
Exemple #18
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()
                {
#if !LIB
                    Memory mem = core.GetDataMemory();
#else
                    SystemMemory mem = core.GetDataMemory();
#endif
                    int[] dst = mFrontBuffer.Pixels;

                    //mFrontBuffer.FromByteArray(mem.GetData(), frameBufferPointer, dst.Length * 4);
#if !LIB
                    System.Buffer.BlockCopy(mem.GetData(), frameBufferPointer, dst, 0, dst.Length * 4);
#else
                    byte[] bytes = new byte[dst.Length * 4];
                    mem.ReadBytes(bytes, frameBufferPointer, dst.Length * 4);
                    System.Buffer.BlockCopy(bytes, 0, dst, 0, dst.Length * 4);                     //TO BE TESTED
#endif
                    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)
            {
#if !LIB
                Memory mem = core.GetDataMemory();
#else
                SystemMemory mem = core.GetDataMemory();
#endif
                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);
            };
        }
        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);
            };
        }
Exemple #20
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);
                }
                if (file.Exists == false)
                {
                    return(MoSync.Constants.MA_FERR_GENERIC);
                }

                IsolatedStorageFileStream fileStream = file.FileStream;
                SeekOrigin origin;
                switch (_whence)
                {
                case MoSync.Constants.MA_SEEK_SET:
                    origin = SeekOrigin.Begin;
                    break;

                case MoSync.Constants.MA_SEEK_CUR:
                    origin = SeekOrigin.Current;
                    break;

                case MoSync.Constants.MA_SEEK_END:
                    origin = SeekOrigin.End;
                    break;

                default:
                    throw new Exception("maFileSeek whence");
                }

                try
                {
                    return((int)fileStream.Seek(_offset, origin));
                }
                catch (IOException e)
                {
                    MoSync.Util.Log(e);
                    return(MoSync.Constants.MA_FERR_GENERIC);
                }
            };

            ioctls.maFileTell = delegate(int _file)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                {
                    return(MoSync.Constants.MA_FERR_WRONG_TYPE);
                }
                IsolatedStorageFileStream fileStream = file.FileStream;
                return((int)fileStream.Position);
            };

            ioctls.maFileExists = delegate(int _file)
            {
                File file = mFileHandles[_file];
                return(file.Exists ? 1 : 0);
            };

            ioctls.maFileCreate = delegate(int _file)
            {
                File file = mFileHandles[_file];
                if (file.Exists)
                {
                    return(MoSync.Constants.MA_FERR_GENERIC);
                }
                file.Create();
                return(0);
            };

            ioctls.maFileDelete = delegate(int _file)
            {
                File file = mFileHandles[_file];
                try
                {
                    file.Delete();
                }
                catch (IsolatedStorageException e)
                {
                    MoSync.Util.Log(e);
                    return(MoSync.Constants.MA_FERR_GENERIC);
                }
                return(0);
            };

            ioctls.maFileSize = delegate(int _file)
            {
                File file = mFileHandles[_file];
                if (file.Exists == false)
                {
                    return(MoSync.Constants.MA_FERR_GENERIC);
                }

                return(file.Size());
            };

            ioctls.maFileAvailableSpace = delegate(int _file)
            {
                File file = mFileHandles[_file];
                return(file.AvailableSpace());
            };

            ioctls.maFileTotalSpace = delegate(int _file)
            {
                File file = mFileHandles[_file];
                return(file.TotalSpace());
            };

            ioctls.maFileDate = delegate(int _file)
            {
                File file = mFileHandles[_file];
                return(Util.ToUnixTimeUtc(file.Date().ToFileTime()));
            };

            ioctls.maFileRename = delegate(int _file, int _newName)
            {
                File   file    = mFileHandles[_file];
                String newName = core.GetDataMemory().ReadStringAtAddress(_newName);
                newName = ConvertPath(newName);
                if (newName.Contains("\\"))
                {
                    if (newName[0] != '\\')
                    {
                        throw new Exception("Invalid newName");
                    }
                }
                else
                {                   // add directory of old file.
                    newName = Path.GetDirectoryName(file.Path) + "\\" + newName;
                }
                file.Rename(newName);
                return(0);
            };

            ioctls.maFileTruncate = delegate(int _file, int _offset)
            {
                File file = mFileHandles[_file];
                file.Truncate(_offset);
                return(0);
            };

            ioctls.maFileListStart = delegate(int _path, int _filter, int _sorting)
            {
                // todo: respect _sorting.
                String path = core.GetDataMemory().ReadStringAtAddress(_path);
                path = ConvertPath(path);
                String filter           = core.GetDataMemory().ReadStringAtAddress(_filter);
                String pattern          = path + filter;
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
                FileList            fl  = new FileList();
                fl.dirs  = isf.GetDirectoryNames(pattern);
                fl.files = isf.GetFileNames(pattern);
                fl.pos   = 0;

                mFileListHandles.Add(mNextFileListHandle, fl);
                return(mNextFileListHandle++);
            };

            ioctls.maFileListNext = delegate(int _list, int _nameBuf, int _bufSize)
            {
                FileList fl = mFileListHandles[_list];
                String   name;
                if (fl.pos < fl.dirs.Length)
                {
                    name = fl.dirs[fl.pos] + "/";
                }
                else if (fl.pos < fl.dirs.Length + fl.files.Length)
                {
                    name = fl.files[fl.pos - fl.dirs.Length];
                }
                else
                {
                    return(0);
                }
                if (name.Length >= _bufSize)
                {
                    return(name.Length);
                }
                core.GetDataMemory().WriteStringAtAddress(_nameBuf,
                                                          name, _bufSize);
                fl.pos++;
                return(name.Length);
            };

            ioctls.maFileListClose = delegate(int _list)
            {
                FileList fl = mFileListHandles[_list];
                mFileListHandles.Remove(_list);
                return(0);
            };
        }
Exemple #21
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            mNativeUI = new 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 = 1; 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)
            {
                IWidget widget = mWidgets[_widget];
                widget.RemoveFromParent();
                mWidgets[_widget] = null;
                return(MoSync.Constants.MAW_RES_OK);
            };

            ioctls.maWidgetAddChild = delegate(int _parent, int _child)
            {
                IWidget parent = mWidgets[_parent];
                IWidget child  = mWidgets[_child];
                parent.AddChild(child);
                return(MoSync.Constants.MAW_RES_OK);
            };

            ioctls.maWidgetRemoveChild = delegate(int _child)
            {
                IWidget child = mWidgets[_child];
                child.RemoveFromParent();
                return(MoSync.Constants.MAW_RES_OK);
            };

            ioctls.maWidgetInsertChild = delegate(int _parent, int _child, int index)
            {
                IWidget parent = mWidgets[_parent];
                IWidget child  = mWidgets[_child];
                parent.InsertChild(child, index);
                return(MoSync.Constants.MAW_RES_OK);
            };

            ioctls.maWidgetStackScreenPush = delegate(int _stackScreen, int _newScreen)
            {
                return(MoSync.Constants.MAW_RES_OK);
            };

            ioctls.maWidgetStackScreenPop = delegate(int _stackScreen)
            {
                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);
                IWidget widget   = mWidgets[_widget];
                try
                {
                    widget.SetProperty(property, value);
                }
                catch (InvalidPropertyNameException e)
                {
                    MoSync.Util.Log(e);
                    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);
                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)
            {
                IScreen screen = (IScreen)mWidgets[_screenHandle];
                screen.Show();
                return(MoSync.Constants.MAW_RES_OK);
            };
        }
        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;
            };
        }
Exemple #23
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maFontGetCount = delegate()
            {
                int count = 0;
                MoSync.Util.RunActionOnMainThreadSync(() => count = System.Windows.Media.Fonts.SystemTypefaces.Count);
                return 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 = "";
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        int count = 0;
                        System.Collections.Generic.IEnumerator<Typeface> en = System.Windows.Media.Fonts.SystemTypefaces.GetEnumerator();
                        while (count < _index)
                        {
                            en.MoveNext();
                            count++;
                        }
                        System.Windows.Media.Typeface currentTypeFace = en.Current;
                        System.Windows.Media.GlyphTypeface currentGlyph;
                        currentTypeFace.TryGetGlyphTypeface(out currentGlyph);
                        fontName = currentGlyph.FontFileName;
                        fontName = (fontName.Split('.'))[0];
                    });

                    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);
                Typeface typeface = null;
                GlyphTypeface glyphTypeface = null;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    int count = Fonts.SystemTypefaces.Count;
                    System.Collections.Generic.IEnumerator<Typeface> en = Fonts.SystemTypefaces.GetEnumerator();
                    while (count != 0)
                    {
                        typeface = en.Current;
                        if (typeface.TryGetGlyphTypeface(out glyphTypeface))
                        {
                            if (glyphTypeface.FontFileName.StartsWith(fontName))
                            {
                                break;
                            }
                        }
                        en.MoveNext();
                        count--;
                    }
                });

                if (glyphTypeface == null) return -2;

                mFonts.Add(glyphTypeface);
                return mFonts.Count - 1;
            };

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

                //RES_FONT_NO_TYPE_STYLE_COMBINATION
                //RES_FONT_INVALID_SIZE

                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;
            };

            ioctls.maFontSetCurrent = delegate(int _font)
            {
                mCurrentFont = mFonts[_font];
                mCurrentFontSource = new System.Windows.Documents.FontSource(mCurrentFont);
                return 0;
            };
        }
Exemple #24
0
        public Runtime(Core core)
        {
            mCore         = core;
            mSyscalls     = new Syscalls();
            mIoctls       = new Ioctls();
            mIoctlInvoker = new IoctlInvoker(mCore, mIoctls);

            PhoneApplicationFrame mainPage = (PhoneApplicationFrame)Application.Current.RootVisual;

            mainPage.MouseLeftButtonDown += MouseLeftButtonDown;
            mainPage.MouseMove           += this.MouseMove;
            mainPage.MouseLeftButtonUp   += MouseLeftButtonUp;

            RegisterCleaner(() =>
            {
                Util.RunActionOnMainThreadSync(() =>
                {
                    mainPage.MouseLeftButtonDown -= MouseLeftButtonDown;
                    mainPage.MouseMove           -= this.MouseMove;
                    mainPage.MouseLeftButtonUp   -= MouseLeftButtonUp;
                });
            });

            InitSyscalls();

            mSyscalls.maGetEvent = delegate(int ptr)
            {
                if (mEvents.Count != 0)
                {
                    lock (mEvents)
                    {
                        Event  evt       = mEvents[0];
                        Memory eventData = evt.GetEventData();
                        mEvents.RemoveAt(0);
                        Memory customEventData = evt.GetCustomEventData();
                        if (customEventData != null)
                        {
                            mCore.GetDataMemory().WriteMemoryAtAddress(mCore.GetCustomEventDataPointer(),
                                                                       customEventData, 0, customEventData.GetSizeInBytes());
                            eventData.WriteInt32(MoSync.Struct.MAEvent.data, mCore.GetCustomEventDataPointer());
                        }
                        mCore.GetDataMemory().WriteMemoryAtAddress(ptr, eventData, 0, eventData.GetSizeInBytes());
                    }
                    return(1);
                }
                else
                {
                    return(0);
                }
            };

            mSyscalls.maWait = delegate(int timeout)
            {
                if (timeout <= 0)
                {
                    timeout = 1 << 15;
                }
                mEventWaiter.WaitOne(timeout);
            };

            mSyscalls.maIOCtl = delegate(int id, int a, int b, int c)
            {
                return(mIoctlInvoker.InvokeIoctl(id, a, b, c));
            };

            mSyscalls.maDestroyObject = delegate(int res)
            {
                mResources[res].SetResourceType(MoSync.Constants.RT_PLACEHOLDER);
                mResources[res].SetInternalObject(null);
            };
        }
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            /**
            * @brief Creates a new banner.
            * @param bannerSize One of the MA_ADS_SIZE_ constants. Only for Android and WP7.1 platforms.
            * @param publisherID Only for Android and WP 7.1 platforms.
            * This param is ignored on iOS platform.
            *
            * @note A banner is a widget type object.
            * For more info see Widget API.
            *
            * @returns
            *  - #MA_ADS_RES_UNSUPPORTED if ads are not supported on current system.
            *  - #MA_ADS_RES_ERROR if a error occurred while creating the banner widget.
            *  - a handle to a new banner widget(the handle value is >= 0).
            */
            ioctls.maAdsBannerCreate = delegate(int _bannerSize, int _publisherID)
            {
                MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        mAd = new NativeUI.Ad();

                        // If the banner size is a known windows phone 7 size, we set it.
                        // The default value is 480*80 (XX-Large banner).
                        switch (_bannerSize)
                        {
                            case MoSync.Constants.MA_ADS_SIZE_WP7_XLARGE:
                                mAd.Width = 300;
                                mAd.Height = 50;
                                break;
                            case MoSync.Constants.MA_ADS_SIZE_WP7_XXLARGE:
                                mAd.Width = 480;
                                mAd.Height = 80;
                                break;
                            default:
                                mAd.Width = 480;
                                mAd.Height = 80;
                                break;
                        }

                        // the publisherID for windows phone contains two components separated by '|'.
                        // The first one represents the application ID and the second one the ad unit ID.
                        // The publisher ID structure(ex): f532778c-7db5-4a8b-a292-a45a684ed890
                        // The ad unit ID structure(ex): 81103
                        String publisherID = core.GetDataMemory().ReadStringAtAddress(_publisherID);
                        string[] values = publisherID.Split('|');
                        // only if both values are present we set the properties
                        if (2 == values.Length)
                        {
                            mAd.ApplicationID = values[0];
                            mAd.AdUnitID = values[1];
                        }
                    }
                );

                int handle = runtime.GetModule<NativeUIModule>().AddWidget(mAd);
                // if the handles is smaller than 0, the widget was not added to the layout
                if (handle < 0)
                {
                    return MoSync.Constants.MA_ADS_RES_ERROR;
                }
                mAd.SetHandle(handle);
                mAd.SetRuntime(runtime);

                return handle;
            };

            /**
            * @brief Destroy a banner.
            *
            * @param bannerHandle Handle to a banner.
            *
            * @returns One of the next constants:
            * - #MA_ADS_RES_OK if no error occurred.
            * - #MA_ADS_RES_INVALID_BANNER_HANDLE if the banner handle is invalid.
            */
            ioctls.maAdsBannerDestroy = delegate(int _bannerHandler)
            {
                if (!isHandleValid(runtime, _bannerHandler))
                {
                    return MoSync.Constants.MA_ADS_RES_INVALID_BANNER_HANDLE;
                }

                mAd = null;

                return MoSync.Constants.MA_ADS_RES_OK;
            };

            /**
            * @brief Add a banner to a layout widget.
            *
            * @param bannerHandle Handle to a banner.
            * @param layoutHandle Handle to a layout.
            *
            * @returns One of the next constants:
            * - #MA_ADS_RES_OK if no error occurred.
            * - #MA_ADS_RES_INVALID_BANNER_HANDLE if the banner handle is invalid.
            * - #MA_ADS_RES_INVALID_LAYOUT_HANDLE if the layout handle is invalid.
            */
            ioctls.maAdsAddBannerToLayout = delegate(int _bannerHandle, int _layoutHandle)
            {
                // we first check if both the banner and the layout are widgets with a valid handle
                if (!isHandleValid(runtime, _bannerHandle))
                {
                    return MoSync.Constants.MA_ADS_RES_INVALID_BANNER_HANDLE;
                }
                if (!isHandleValid(runtime, _layoutHandle))
                {
                    return MoSync.Constants.MA_ADS_RES_INVALID_LAYOUT_HANDLE;
                }

                // add the banner to the parent widget
                runtime.GetModule<NativeUIModule>().GetWidget(_layoutHandle).AddChild(
                    runtime.GetModule<NativeUIModule>().GetWidget(_bannerHandle));
                // set the parent of the banner to be the layout on which is added
                mAd.SetParent(runtime.GetModule<NativeUIModule>().GetWidget(_layoutHandle));

                return MoSync.Constants.MA_ADS_RES_OK;
            };

            /**
            * @brief Remove a banner from a layout widget.
            *
            * @param bannerHandle Handle to a banner.
            * @param layoutHandle Handle to a layout.
            *
            * @returns One of the next constants:
            * - #MA_ADS_RES_OK if no error occurred.
            * - #MA_ADS_RES_INVALID_BANNER_HANDLE if the banner handle is invalid.
            * - #MA_ADS_RES_INVALID_LAYOUT_HANDLE if the layout handle is invalid.
            */
            ioctls.maAdsRemoveBannerFromLayout = delegate(int _bannerHandle, int _layoutHandle)
            {
                // we first check if both the banner and the layout are widgets with a valid handle
                if (!isHandleValid(runtime, _bannerHandle))
                {
                    return MoSync.Constants.MA_ADS_RES_INVALID_BANNER_HANDLE;
                }
                if (!isHandleValid(runtime, _layoutHandle))
                {
                    return MoSync.Constants.MA_ADS_RES_INVALID_LAYOUT_HANDLE;
                }

                runtime.GetModule<NativeUIModule>().GetWidget(_layoutHandle).RemoveChild(
                    runtime.GetModule<NativeUIModule>().GetWidget(_bannerHandle));

                return MoSync.Constants.MA_ADS_RES_OK;
            };

            /**
            * @brief Set a banner property.
            *
            * @param bannerHandle Handle to the banner.
            * @param property A string representing which property to set.
            * @param value The value that will be assigned to the property.
            *
            * @returns One of the next result codes:
            * - #MA_ADS_RES_OK if no error occurred.
            * - #MA_ADS_RES_INVALID_BANNER_HANDLE if the banner handle is invalid.
            * - #MA_ADS_RES_INVALID_PROPERTY_NAME if the property name is not valid.
            * - #MA_ADS_RES_INVALID_PROPERTY_VALUE if the property value is not valid.
            */
            ioctls.maAdsBannerSetProperty = delegate(int _bannerHandle, int _property, int _value)
            {
                // check if the banner is a widget with a valid handle
                MoSync.NativeUI.Ad ad = (MoSync.NativeUI.Ad)runtime.GetModule<NativeUIModule>().GetWidget(_bannerHandle);
                if (!isHandleValid(runtime, _bannerHandle))
                {
                    return MoSync.Constants.MA_ADS_RES_INVALID_BANNER_HANDLE;
                }

                String property = core.GetDataMemory().ReadStringAtAddress(_property);
                // based on the string 'property' we set the ones that can be set on WP 7.1
                // if a property is not available, we return MA_ADS_RES_INVALID_PROPERTY_NAME
                string value = "";
                int intValue = -1;
                switch (property)
                {
                    case MoSync.Constants.MA_ADS_HEIGHT:
                        value = core.GetDataMemory().ReadStringAtAddress(_value);
                        intValue = -1;
                        int.TryParse(value,out intValue);
                        if (intValue >= 0)
                        {
                            MoSync.Util.RunActionOnMainThreadSync(() =>
                                {
                                    mAd.Height = intValue;
                                }
                            );
                        }
                        else
                        {
                            return MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_VALUE;
                        }
                        break;
                    case MoSync.Constants.MA_ADS_WIDTH:
                        value = core.GetDataMemory().ReadStringAtAddress(_value);
                        intValue = -1;
                        int.TryParse(value, out intValue);
                        if (intValue >= 0)
                        {
                            MoSync.Util.RunActionOnMainThreadSync(() =>
                                {
                                    mAd.Width = intValue;
                                }
                            );
                        }
                        else
                        {
                            return MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_VALUE;
                        }
                        break;
                    case MoSync.Constants.MA_ADS_VISIBLE:
                        value = core.GetDataMemory().ReadStringAtAddress(_value).ToLower();
                        if (value.Equals("true"))
                        {
                            MoSync.Util.RunActionOnMainThreadSync(() =>
                                {
                                    mAd.Visible = "true";
                                }
                            );
                        }
                        else if (value.Equals("false"))
                        {
                            MoSync.Util.RunActionOnMainThreadSync(() =>
                                {
                                    mAd.Visible = "false";
                                }
                            );
                        }
                        else
                        {
                            return MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_VALUE;
                        }
                        break;
                    case MoSync.Constants.MA_ADS_ENABLED:
                        value = core.GetDataMemory().ReadStringAtAddress(_value).ToLower();
                        if (value.Equals("true"))
                        {
                            MoSync.Util.RunActionOnMainThreadSync(() =>
                                {
                                    mAd.Enabled = "true";
                                }
                            );
                        }
                        else if (value.Equals("false"))
                        {
                            MoSync.Util.RunActionOnMainThreadSync(() =>
                                {
                                    mAd.Enabled = "false";
                                }
                            );
                        }
                        else
                        {
                            return MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_VALUE;
                        }
                        break;
                    case MoSync.Constants.MA_ADS_COLOR_BG:
                        value = core.GetDataMemory().ReadStringAtAddress(_value);
                        if (!IsHexColor(value))
                        {
                            return MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_VALUE;
                        }
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                            {
                                mAd.BackgroundColor = value;
                            }
                        );
                        break;
                    case MoSync.Constants.MA_ADS_COLOR_BORDER:
                        value = core.GetDataMemory().ReadStringAtAddress(_value);
                        if (!IsHexColor(value))
                        {
                            return MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_VALUE;
                        }
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                            {
                                mAd.BorderColor = value;
                            }
                        );
                        break;
                    case MoSync.Constants.MA_ADS_COLOR_TEXT:
                        value = core.GetDataMemory().ReadStringAtAddress(_value);
                        if (!IsHexColor(value))
                        {
                            return MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_VALUE;
                        }
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                            {
                                mAd.TextColor = value;
                            }
                        );
                        break;
                    default:
                        return MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_NAME;
                }

                return MoSync.Constants.MA_ADS_RES_OK;
            };

            /**
            * @brief Retrieves a specified property from the given banner.
            *
            * @param bannerHandle Handle to the banner.
            * @param property A string representing for which property to get the value.
            * @param value A buffer that will hold the value of the property, represented as a string.
            * @param bufSize Size of the buffer.
            *
            * @returns One of the next result codes:
            * - #MA_ADS_RES_OK if no error occurred.
            * - #MA_ADS_RES_INVALID_BANNER_HANDLE if the banner handle is invalid.
            * - #MA_ADS_RES_INVALID_PROPERTY_NAME if the property name is not valid.
            * - #MA_ADS_RES_INVALID_STRING_BUFFER_SIZE if the buffer size was to small.
            */
            ioctls.maAdsBannerGetProperty = delegate(int _bannerHandle, int _property, int _value, int _bufSize)
            {
                MoSync.NativeUI.Ad ad = (MoSync.NativeUI.Ad)runtime.GetModule<NativeUIModule>().GetWidget(_bannerHandle);
                if (!isHandleValid(runtime, _bannerHandle))
                {
                    return MoSync.Constants.MA_ADS_RES_INVALID_BANNER_HANDLE;
                }

                String property = core.GetDataMemory().ReadStringAtAddress(_property);
                string stringvalue = "";
                switch (property)
                {
                    case MoSync.Constants.MA_ADS_HEIGHT:
                        stringvalue = "";
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                            {
                                stringvalue = ((int)mAd.Height).ToString();
                            }
                        );
                        core.GetDataMemory().WriteStringAtAddress(
                            _value,
                            stringvalue,
                            _bufSize);
                        break;
                    case MoSync.Constants.MA_ADS_WIDTH:
                        stringvalue = "";
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                            {
                                stringvalue = ((int)mAd.Width).ToString();
                            }
                        );
                        core.GetDataMemory().WriteStringAtAddress(
                            _value,
                            stringvalue,
                            _bufSize);
                        break;
                    case MoSync.Constants.MA_ADS_VISIBLE:
                        stringvalue = "";
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                            {
                                stringvalue = mAd.Visible;
                            }
                        );
                        core.GetDataMemory().WriteStringAtAddress(
                            _value,
                            stringvalue,
                            _bufSize);
                        break;
                    case MoSync.Constants.MA_ADS_ENABLED:
                        stringvalue = "";
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                            {
                                stringvalue = mAd.Enabled;
                            }
                        );
                        core.GetDataMemory().WriteStringAtAddress(
                            _value,
                            stringvalue,
                            _bufSize);
                        break;
                    case MoSync.Constants.MA_ADS_COLOR_BG:
                        stringvalue = "";
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                            {
                                stringvalue = mAd.BackgroundColor.ToString();
                            }
                        );
                        core.GetDataMemory().WriteStringAtAddress(
                            _value,
                            stringvalue,
                            _bufSize);
                        break;
                    case MoSync.Constants.MA_ADS_COLOR_BORDER:
                        stringvalue = "";
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                            {
                                stringvalue = mAd.BorderColor.ToString();
                            }
                        );
                        core.GetDataMemory().WriteStringAtAddress(
                            _value,
                            stringvalue,
                            _bufSize);
                        break;
                    case MoSync.Constants.MA_ADS_COLOR_TEXT:
                        stringvalue = "";
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                            {
                                stringvalue = mAd.TextColor.ToString();
                            }
                        );
                        core.GetDataMemory().WriteStringAtAddress(
                            _value,
                            stringvalue,
                            _bufSize);
                        break;
                    default:
                        return MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_NAME;
                }

                return MoSync.Constants.MA_ADS_RES_OK;
            };
        }
        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)
            {
                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;
            };
        }
Exemple #27
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];
                if (widget != null)
                {
                    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];
                child.SetParent(parent);
                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 = 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)
        {
            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(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)
        {
            /**
             * 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;

                // MA_SCREEN_ORIENTATION_PORTRAIT = MA_SCREEN_ORIENTATION_PORTRAIT_UP|MA_SCREEN_ORIENTATION_PORTRAIT_UPSIDE_DOWN.
                if (((orientations & MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UP) == MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UP) ||
                    ((orientations & MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UPSIDE_DOWN) == MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UPSIDE_DOWN))

                {
                    isPortrait = true;
                }

                // MA_SCREEN_ORIENTATION_LANDSCAPE = MA_SCREEN_ORIENTATION_LANDSCAPE_RIGHT|MA_SCREEN_ORIENTATION_LANDSCAPE_LEFT.
                if (((orientations & MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_LEFT) == MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_LEFT) ||
                    ((orientations & MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_RIGHT) == MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_RIGHT))
                {
                    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);
            };


            /**
             * @deprecated Use maScreenSetSupportedOrientations instead.
             * 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.
                    switch (currentPage.SupportedOrientations)
                    {
                    case SupportedPageOrientation.PortraitOrLandscape:
                        suportedOrientations = suportedOrientations |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE;
                        break;

                    case SupportedPageOrientation.Landscape:
                        suportedOrientations = suportedOrientations |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE;
                        break;

                    case SupportedPageOrientation.Portrait:
                        suportedOrientations = suportedOrientations |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT;
                        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:
                    case PageOrientation.Landscape:
                        currentOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_LEFT;
                        break;

                    case PageOrientation.PortraitUp:
                    case PageOrientation.Portrait:
                        currentOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UP;
                        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)
        {
            mRuntime = runtime;

            ioctls.maOpenGLInitFullscreen = delegate(int _glApi)
            {
                if (_glApi != MoSync.Constants.MA_GL_API_GL1)
                    return MoSync.Constants.MA_GL_INIT_RES_ERROR;

                Syscalls syscalls = runtime.GetSyscalls();
                mOldUpdateScreenImplementation = syscalls.maUpdateScreen;

                syscalls.maUpdateScreen = delegate()
                {
                    if (maUpdateScreenAction != null)
                        maUpdateScreenAction();
                };

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    // GamePage must always exist for fullscreen apps to work.
                    if (((PhoneApplicationFrame)Application.Current.RootVisual).Navigate(new Uri("/GamePage.xaml", UriKind.Relative)))
                    {
                    }
                });

                return MoSync.Constants.MA_GL_INIT_RES_OK;
            };

            ioctls.maOpenGLCloseFullscreen = delegate()
            {

                return MoSync.Constants.MA_GL_INIT_RES_OK;
            };

            ioctls.maOpenGLTexImage2D = delegate(int _res)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, _res);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();
                byte[] pixels = src.ToByteArray();
                mGL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, src.PixelWidth, src.PixelHeight, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pixels, 0);
                return MoSync.Constants.MA_GL_TEX_IMAGE_2D_OK;
            };

            ioctls.maOpenGLTexSubImage2D = delegate(int _res)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, _res);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();
                byte[] pixels = src.ToByteArray();
                mGL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, src.PixelWidth, src.PixelHeight, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pixels, 0);
                return MoSync.Constants.MA_GL_TEX_IMAGE_2D_OK;
            };

            ioctls.glViewport = delegate(int _x, int _y, int _w, int _h)
            {
                mGL.glViewport(_x, _y, _w, _h);
                return 0;
            };

            ioctls.glGetError = delegate()
            {
                int err = mGL.glGetError();
                if (err != GL.GL_NO_ERROR)
                {
                    int a = 2;
                    //err = GL.GL_NO_ERROR;
                }
                return err;
            };

            ioctls.glGetStringHandle = delegate(int _name)
            {

                String str = mGL.glGetString(_name);
                char[] data = str.ToCharArray();
                byte[] bytes = new byte[data.Length + 1];
                bytes[data.Length] = 0;
                for (int i = 0; i < data.Length; i++)
                {
                    bytes[i] = (byte)data[i];
                }

                return runtime.AddResource(new Resource(new System.IO.MemoryStream(bytes), MoSync.Constants.RT_BINARY, true));
            };

            ioctls.glMatrixMode = delegate(int mode)
            {
                mGL.glMatrixMode(mode);  return 0;
            };

            ioctls.glPushMatrix = delegate()
            {
                mGL.glPushMatrix(); return 0;
            };

            ioctls.glPopMatrix = delegate()
            {
                mGL.glPopMatrix(); return 0;
            };

            ioctls.glLoadIdentity = delegate()
            {
                mGL.glLoadIdentity(); return 0;
            };

            ioctls.glBlendFunc = delegate(int sfactor, int dfactor)
            {
                mGL.glBlendFunc(sfactor, dfactor); return 0;
            };

            ioctls.glAlphaFunc = delegate(int func, float _ref)
            {
                return 0;
            };

            ioctls.glAlphaFuncx = delegate(int func, int _ref)
            {
                return 0;
            };

            ioctls.glDepthFunc = delegate(int _func)
            {
                mGL.glDepthFunc(_func); return 0;
            };

            ioctls.glDepthMask = delegate(int _flag)
            {
                mGL.glDepthMask(_flag); return 0;
            };

            ioctls.glClearColor = delegate(float r, float g, float b, float a)
            {
                mGL.glClearColor(r, g, b, a); return 0;
            };

            ioctls.glClearColorx = delegate(int r, int g, int b, int a)
            {
                mGL.glClearColorx(r, g, b, a); return 0;
            };

            ioctls.glColor4f = delegate(float r, float g, float b, float a)
            {
                mGL.glColor4f(r, g, b, a); return 0;
            };

            ioctls.glColor4x = delegate(int r, int g, int b, int a)
            {
                mGL.glColor4x(r, g, b, a); return 0;
            };

            ioctls.glColor4ub = delegate(int r, int g, int b, int a)
            {
                mGL.glColor4ub(r, g, b, a); return 0;
            };

            ioctls.glColor4f = delegate(float r, float g, float b, float a)
            {
                mGL.glColor4f(r, g, b, a); return 0;
            };

            ioctls.glClear = delegate(int _mask)
            {
                mGL.glClear(_mask); return 0;
            };

            ioctls.glRotatef = delegate(float angle, float x, float y, float z)
            {
                mGL.glRotatef(angle, x, y, z); return 0;
            };

            ioctls.glRotatex = delegate(int angle, int x, int y, int z)
            {
                mGL.glRotatex(angle, x, y, z); return 0;
            };

            ioctls.glTranslatef = delegate(float x, float y, float z)
            {
                mGL.glTranslatef(x, y, z); return 0;
            };

            ioctls.glTranslatex = delegate(int x, int y, int z)
            {
                mGL.glTranslatex(x, y, z); return 0;
            };

            ioctls.glScalef = delegate(float x, float y, float z)
            {
                mGL.glScalef(x, y, z); return 0;
            };

            ioctls.glScalex = delegate(int x, int y, int z)
            {
                mGL.glScalex(x, y, z); return 0;
            };

            ioctls.glMultMatrixf = delegate(int _matrix)
            {
                mGL.glMultMatrixf(core.GetDataMemory().GetData(), _matrix); return 0;
            };

            ioctls.glMultMatrixx = delegate(int _matrix)
            {
                mGL.glMultMatrixx(core.GetDataMemory().GetData(), _matrix); return 0;
            };

            ioctls.glEnableClientState = delegate(int _array)
            {
                mGL.glEnableClientState(_array); return 0;
            };

            ioctls.glDisableClientState = delegate(int _array)
            {
                mGL.glDisableClientState(_array); return 0;
            };

            ioctls.glTexCoordPointer = delegate(int _size, int _type, int _stride, int _pointer)
            {
                mGL.glTexCoordPointer(_size, _type, _stride, core.GetDataMemory().GetData(), _pointer);
                return 0;
            };

            ioctls.glVertexPointer = delegate(int _size, int _type, int _stride, int _pointer)
            {
                mGL.glVertexPointer(_size, _type, _stride, core.GetDataMemory().GetData(), _pointer);
                return 0;
            };

            ioctls.glColorPointer = delegate(int _size, int _type, int _stride, int _pointer)
            {
                mGL.glColorPointer(_size, _type, _stride, core.GetDataMemory().GetData(), _pointer);
                return 0;
            };

            ioctls.glNormalPointer = delegate(int _type, int _stride, int _pointer)
            {
                mGL.glNormalPointer(_type, _stride, core.GetDataMemory().GetData(), _pointer);
                return 0;
            };

            ioctls.glDrawArrays = delegate(int _mode, int _first, int _count)
            {
                mGL.glDrawArrays(_mode, _first, _count);
                return 0;
            };

            ioctls.glDrawElements = delegate(int _mode, int _count, int _type, int _indecies)
            {
                mGL.glDrawElements(_mode, _count, _type, core.GetDataMemory().GetData(), _indecies);
                return 0;
            };

            ioctls.glEnable = delegate(int _e)
            {
                mGL.glEnable(_e);
                return 0;
            };

            ioctls.glDisable = delegate(int _e)
            {
                mGL.glDisable(_e);
                return 0;
            };

            ioctls.glFrustumf = delegate(float _left, float _right, float _bottom, float _top, float _znear, float _zfar)
            {
                mGL.glFrustumf(_left, _right, _bottom, _top, _znear, _zfar);
                return 0;
            };

            ioctls.glOrthof = delegate(float _left, float _right, float _bottom, float _top, float _znear, float _zfar)
            {
                mGL.glOrthof(_left, _right, _bottom, _top, _znear, _zfar);
                return 0;
            };

            ioctls.glFrustumx = delegate(int _left, int _right, int _bottom, int _top, int _znear, int _zfar)
            {
                mGL.glFrustumx(_left, _right, _bottom, _top, _znear, _zfar);
                return 0;
            };

            ioctls.glOrthox = delegate(int _left, int _right, int _bottom, int _top, int _znear, int _zfar)
            {
                mGL.glOrthox(_left, _right, _bottom, _top, _znear, _zfar);
                return 0;
            };

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

            ioctls.glFinish = delegate()
            {
                mGL.glFinish();
                return 0;
            };

            ioctls.glGenTextures = delegate(int _n, int _textures)
            {
                int[] handles = new int[_n];
                mGL.glGenTextures(_n, handles);
                for (int i = 0; i < _n; i++)
                {
                    core.GetDataMemory().WriteInt32(_textures + i * 4, handles[i]);
                }
                return 0;
            };

            ioctls.glBindTexture = delegate(int _target, int _texture)
            {
                mGL.glBindTexture(_target, _texture);
                return 0;
            };

            ioctls.glTexImage2D = delegate(int _target, int _level, int _internalformat, int _width, int _height, int _border, int _format, int _type, int _pixels)
            {
                if(_pixels == 0)
                    mGL.glTexImage2D(_target, _level, _internalformat, _width, _height, _border, _format, _type, null, _pixels);
                else
                    mGL.glTexImage2D(_target, _level, _internalformat, _width, _height, _border, _format, _type, core.GetDataMemory().GetData(), _pixels);
                return 0;
            };

            ioctls.glDeleteTextures = delegate(int _n, int _textures)
            {
                int[] textures = new int[_n];
                for (int i = 0; i < _n; i++)
                {
                    textures[i] = core.GetDataMemory().ReadInt32(_textures + i * 4);
                }
                mGL.glDeleteTextures(textures);
                return 0;
            };

            ioctls.glTexSubImage2D = delegate(int _target, int _level, int _xofs, int _yofs, int _width, int _height, int _format, int _type, int _pixels)
            {
                mGL.glTexSubImage2D(_target, _level, _xofs, _yofs, _width, _height, _format, _type, core.GetDataMemory().GetData(), _pixels);
                return 0;
            };

            ioctls.glCompressedTexImage2D = delegate(int _target, int _level, int _internalformat, int _width, int _height, int _border, int _imageSize, int _data)
            {
                return 0;
            };

            ioctls.glCompressedTexSubImage2D = delegate(int _target, int _level, int _xofs, int _yofs, int _width, int _height, int _format, int _imageSize, int _data)
            {
                return 0;
            };

            ioctls.glGenBuffers = delegate(int _n, int _buffers)
            {
                int[] handles = new int[_n];
                mGL.glGenBuffers(_n, handles);
                for (int i = 0; i < _n; i++)
                {
                    core.GetDataMemory().WriteInt32(_buffers + i * 4, handles[i]);
                }
                return 0;
            };

            ioctls.glBindBuffer = delegate(int _target, int _buffer)
            {
                mGL.glBindBuffer(_target, _buffer);
                return 0;
            };

            ioctls.glBufferData = delegate(int _target, int _size, int _data, int _usage)
            {
                mGL.glBufferData(_target, _size, core.GetDataMemory().GetData(), _data, _usage);
                return 0;
            };

            ioctls.glBufferSubData = delegate(int _target, int _offset, int _size, int _data)
            {
                mGL.glBufferSubData(_target, _offset, _size, core.GetDataMemory().GetData(), _data);
                return 0;
            };

            ioctls.glMaterialf = delegate(int face, int pname, float value)
            {
                mGL.glMaterialf(face, pname, value); return 0;
            };

            ioctls.glMaterialx = delegate(int face, int pname, int value)
            {
                mGL.glMaterialx(face, pname, value); return 0;
            };

            ioctls.glMaterialfv = delegate(int face, int pname, int data)
            {
                mGL.glMaterialfv(face, pname, core.GetDataMemory().GetData(), data); return 0;
            };

            ioctls.glMaterialxv = delegate(int face, int pname, int data)
            {
                mGL.glMaterialxv(face, pname, core.GetDataMemory().GetData(), data); return 0;
            };

            ioctls.glLightf = delegate(int _light, int _pname, float _param)
            {
                mGL.glLightf(_light, _pname, _param); return 0;
            };

            ioctls.glLightx = delegate(int _light, int _pname, int _param)
            {
                mGL.glLightx(_light, _pname, _param); return 0;
            };

            ioctls.glLightfv = delegate(int _light, int _pname, int _pointer)
            {
                mGL.glLightfv(_light, _pname, core.GetDataMemory().GetData(), _pointer); return 0;
            };

            ioctls.glLightxv = delegate(int _light, int _pname, int _pointer)
            {
                mGL.glLightxv(_light, _pname, core.GetDataMemory().GetData(), _pointer); return 0;
            };

            ioctls.glShadeModel = delegate(int _mode)
            {
                mGL.glShadeModel(_mode); return 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;
            };
        }
Exemple #33
0
        /*
         * private void OnAlertMessageBoxClosed(IAsyncResult ar)
         * {
         *      int? buttonIndex = Guide.EndShowMessageBox(ar);
         *
         *      Memory eventData = new Memory(8);
         *      eventData.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_ALERT);
         *      eventData.WriteInt32(MoSync.Struct.MAEvent.alertButtonIndex, (int)(buttonIndex + 1));
         *
         *      mRuntime.PostEvent(new Event(eventData));
         * }
         */

        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            mRuntime = runtime;
            mCore    = core;

            /**
             * Register system properties
             */
            SystemPropertyManager.SystemPropertyProvider myDelegateForDeviceInfo = new SystemPropertyManager.SystemPropertyProvider(getDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.imei", myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.imsi", myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.iso-639-1", myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.iso-639-2", myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device", myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device.name", myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device.UUID", myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device.OS", myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device.OS.version", myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.network.type", myDelegateForDeviceInfo);

            ioctls.maWriteLog = delegate(int src, int size)
            {
                byte[] bytes = new byte[size];
                core.GetDataMemory().ReadBytes(bytes, src, size);
                MoSync.Util.Log(bytes);
                return(0);
            };

            ioctls.maMessageBox = delegate(int _caption, int _message)
            {
                String message = core.GetDataMemory().ReadStringAtAddress(_message);
                String caption = core.GetDataMemory().ReadStringAtAddress(_caption);
                MoSync.Util.ShowMessage(message, false, caption);
                return(0);
            };

            ioctls.maTextBox = delegate(int _title, int _inText, int _outText, int _maxSize, int _constraints)
            {
                bool passwordMode = false;
                if ((_constraints & MoSync.Constants.MA_TB_FLAG_PASSWORD) != 0)
                {
                    passwordMode = true;
                }

                if ((_constraints & MoSync.Constants.MA_TB_TYPE_MASK) != MoSync.Constants.MA_TB_TYPE_ANY)
                {
                    return(MoSync.Constants.MA_TB_RES_TYPE_UNAVAILABLE);
                }

                try
                {
                    Guide.BeginShowKeyboardInput(Microsoft.Xna.Framework.PlayerIndex.One,
                                                 core.GetDataMemory().ReadWStringAtAddress(_title), "",
                                                 core.GetDataMemory().ReadWStringAtAddress(_inText),
                                                 delegate(IAsyncResult result)
                    {
                        string text = Guide.EndShowKeyboardInput(result);

                        Memory eventData = new Memory(12);
                        eventData.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_TEXTBOX);
                        int res = MoSync.Constants.MA_TB_RES_OK;
                        int len = 0;
                        if (text == null)
                        {
                            res = MoSync.Constants.MA_TB_RES_CANCEL;
                        }
                        else
                        {
                            len = text.Length;
                        }

                        eventData.WriteInt32(MoSync.Struct.MAEvent.textboxResult, res);
                        eventData.WriteInt32(MoSync.Struct.MAEvent.textboxLength, len);
                        core.GetDataMemory().WriteWStringAtAddress(_outText, text, _maxSize);
                        mRuntime.PostEvent(new Event(eventData));
                    },
                                                 null
                                                 , passwordMode);
                }
                catch (Exception)
                {
                    return(-1);
                }

                return(0);
            };

            /**
             * @author: Ciprian Filipas
             * @brief: The maAlert ioctl implementation.
             * @note: On WP7 only 2 buttons are available, OK and CANCEL. Also if the buttons get null values from
             *        MoSync WP7 platform will automatically add the OK button. Regarding these facts the _b2 button will
             *        be ignored in the current implementation.
             */
            ioctls.maAlert = delegate(int _title, int _message, int _b1, int _b2, int _b3)
            {
                String title = "", message = "";

                if (0 != _title)
                {
                    title = core.GetDataMemory().ReadStringAtAddress(_title);
                }
                if (0 != _message)
                {
                    message = core.GetDataMemory().ReadStringAtAddress(_message);
                }

                if (0 != _b3)
                {
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        MessageBoxResult result = MessageBox.Show(message, title, MessageBoxButton.OKCancel);
                        if (result == MessageBoxResult.OK)
                        {
                            Memory eventData = new Memory(8);
                            const int MAWidgetEventData_eventType          = 0;
                            const int MAWidgetEventData_eventArgumentValue = 4;

                            //write 1 down since the buttone clicked is the first one
                            eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.EVENT_TYPE_ALERT);
                            eventData.WriteInt32(MAWidgetEventData_eventArgumentValue, 1);
                            //Posting a CustomEvent
                            mRuntime.PostEvent(new Event(eventData));
                        }
                        else if (result == MessageBoxResult.Cancel)
                        {
                            Memory eventData = new Memory(8);
                            const int MAWidgetEventData_eventType          = 0;
                            const int MAWidgetEventData_eventArgumentValue = 4;

                            //write 1 down since the buttone clicked is the first one
                            eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.EVENT_TYPE_ALERT);
                            eventData.WriteInt32(MAWidgetEventData_eventArgumentValue, 3);
                            //Posting a CustomEvent
                            mRuntime.PostEvent(new Event(eventData));
                        }
                    }
                                                          );
                }
                else
                {
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        MessageBox.Show(message, title, MessageBoxButton.OK);

                        // Since the only way to exit the messageBox is by pressing OK there is no
                        // need for a result object.

                        Memory eventData = new Memory(8);
                        const int MAWidgetEventData_eventType          = 0;
                        const int MAWidgetEventData_eventArgumentValue = 4;

                        //write 1 down since the buttone clicked is the first one
                        eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.EVENT_TYPE_ALERT);
                        eventData.WriteInt32(MAWidgetEventData_eventArgumentValue, 1);
                        //Posting a CustomEvent
                        mRuntime.PostEvent(new Event(eventData));
                    }
                                                          );
                }

                return(0);
            };

            ioctls.maGetSystemProperty = delegate(int _key, int _buf, int _size)
            {
                String key   = core.GetDataMemory().ReadStringAtAddress(_key);
                String value = MoSync.SystemPropertyManager.GetSystemProperty(key);
                if (value == null)
                {
                    return(-2);
                }
                if (value.Length + 1 <= _size)
                {
                    if (key.Equals("mosync.network.type"))
                    {
                        /**
                         * This code converts the result return by the GetSystemProperty
                         * for the "mosync.network.type" key to be supported by the current
                         * MoSync SDK 3.0
                         */
                        if (value.ToLower().Contains("wireless"))
                        {
                            value = "wifi";
                        }
                        else if (value.ToLower().Contains("ethernet"))
                        {
                            value = "ethernet";
                        }
                        else if (value.ToLower().Contains("mobilebroadbandgsm"))
                        {
                            value = "2g";
                        }
                        else if (value.ToLower().Contains("mobilebroadbandcdma"))
                        {
                            value = "3g";
                        }
                    }
                    core.GetDataMemory().WriteStringAtAddress(_buf, value, _size);
                }
                return(value.Length + 1);
            };

            ioctls.maWakeLock = delegate(int flag)
            {
                if (MoSync.Constants.MA_WAKE_LOCK_ON == flag)
                {
                    Microsoft.Phone.Shell.PhoneApplicationService.Current.
                    UserIdleDetectionMode =
                        Microsoft.Phone.Shell.IdleDetectionMode.Enabled;
                }
                else
                {
                    Microsoft.Phone.Shell.PhoneApplicationService.Current.
                    UserIdleDetectionMode =
                        Microsoft.Phone.Shell.IdleDetectionMode.Disabled;
                }
                return(1);
            };

            // validates image input data and dispaches a delegate to save the image to camera roll
            ioctls.maSaveImageToDeviceGallery = delegate(int imageHandle, int imageNameAddr)
            {
                int returnCode = MoSync.Constants.MA_MEDIA_RES_IMAGE_EXPORT_FAILED;

                //Get the resource with the specified handle
                Resource res       = mRuntime.GetResource(MoSync.Constants.RT_IMAGE, imageHandle);
                String   imageName = mCore.GetDataMemory().ReadStringAtAddress(imageNameAddr);

                if ((null != res) && !String.IsNullOrEmpty(imageName))
                {
                    object[] myArray = new object[3];
                    myArray[0] = imageHandle;
                    myArray[1] = imageName;
                    myArray[2] = res;

                    Deployment.Current.Dispatcher.BeginInvoke(
                        new Delegate_SaveImageToCameraRoll(SaveImageToCameraRoll), myArray);

                    returnCode = MoSync.Constants.MA_MEDIA_RES_OK;
                }

                return(returnCode);
            };
        }
        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;
            };
        }
Exemple #35
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maFontGetCount = delegate()
            {
                int count = 0;
                MoSync.Util.RunActionOnMainThreadSync(() => count = System.Windows.Media.Fonts.SystemTypefaces.Count);
                return(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 = "";
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        int count = 0;
                        System.Collections.Generic.IEnumerator <Typeface> en = System.Windows.Media.Fonts.SystemTypefaces.GetEnumerator();
                        while (count < _index)
                        {
                            en.MoveNext();
                            count++;
                        }
                        System.Windows.Media.Typeface currentTypeFace = en.Current;
                        System.Windows.Media.GlyphTypeface currentGlyph;
                        currentTypeFace.TryGetGlyphTypeface(out currentGlyph);
                        fontName = currentGlyph.FontFileName;
                        fontName = (fontName.Split('.'))[0];
                    });

                    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);
                Typeface      typeface      = null;
                GlyphTypeface glyphTypeface = null;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    int count = Fonts.SystemTypefaces.Count;
                    System.Collections.Generic.IEnumerator <Typeface> en = Fonts.SystemTypefaces.GetEnumerator();
                    while (count != 0)
                    {
                        typeface = en.Current;
                        if (typeface.TryGetGlyphTypeface(out glyphTypeface))
                        {
                            if (glyphTypeface.FontFileName.StartsWith(fontName))
                            {
                                break;
                            }
                        }
                        en.MoveNext();
                        count--;
                    }
                });

                if (glyphTypeface == null)
                {
                    return(-2);
                }

                mFonts.Add(glyphTypeface);
                return(mFonts.Count - 1);
            };

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

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

            ioctls.maFontSetCurrent = delegate(int _font)
            {
                mCurrentFont       = mFonts[_font];
                mCurrentFontSource = new System.Windows.Documents.FontSource(mCurrentFont);
                return(0);
            };
        }
        /**
         * Initializing the ioctls.
         */
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            mCamera     = new PhotoCamera(mCameraType);
            mVideoBrush = new VideoBrush();

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

            mRuntime = runtime;

            PhoneApplicationPage currentPage = (((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage);

            // set the initial camera orientation in respect to the current page orientation
            SetInitialCameraOrientation(currentPage);
            // handle current page orientation and adjust the camera orientation accordingly
            HandleDeviceOrientation(currentPage);

            /**
             * Stores an output format in fmm parameter.
             * @param _index int the index of the required format.
             * @param _fmt int the momory address at which to write the output format dimensions.
             *
             * Note: the _index should be greater than 0 and smaller than the number of camera formats.
             */
            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);
            };

            /**
             * Returns the number of different output formats supported by the current device's camera.
             * \< 0 if there is no camera support.
             * 0 if there is camera support, but the format is unknown.
             */
            ioctls.maCameraFormatNumber = delegate()
            {
                // if the camera is not initialized, we cannot access any of its properties
                if (!isCameraInitialized)
                {
                    // because the cammera is supported but not initialized, we return 0
                    return(0);
                }

                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++;
                    resolutions.MoveNext();
                    if (resolutions.Current == new System.Windows.Size(0, 0))
                    {
                        break;
                    }
                }
                return(number);
            };

            /**
             * Starts the viewfinder and the camera
             */
            ioctls.maCameraStart = delegate()
            {
                if (isCameraSnapshotInProgress)
                {
                    return(MoSync.Constants.MA_CAMERA_RES_SNAPSHOT_IN_PROGRESS);
                }

                InitCamera();

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    mCameraPrev.StartViewFinder();
                });

                return(0);
            };

            /**
             * stops the view finder and the camera.
             */
            ioctls.maCameraStop = delegate()
            {
                if (isCameraSnapshotInProgress)
                {
                    // We need to post snapshot failed if the camera was stopped during snapshot operation
                    postSnapshotEvent(snapshotPlaceHolder, mCamera.Resolution,
                                      MoSync.Constants.MA_IMAGE_REPRESENTATION_UNKNOWN, MoSync.Constants.MA_CAMERA_RES_FAILED);
                    isCameraSnapshotInProgress = false;
                }

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    mCameraPrev.StopViewFinder();
                });

                return(0);
            };

            /**
             * Adds a previewWidget to the camera controller in devices that support native UI.
             */
            ioctls.maCameraSetPreview = delegate(int _widgetHandle)
            {
                // if the camera is not initialized, we need to initialize it before
                // setting the preview
                if (!isCameraInitialized)
                {
                    InitCamera();
                }

                IWidget w = runtime.GetModule <NativeUIModule>().GetWidget(_widgetHandle);
                if (w.GetType() != typeof(MoSync.NativeUI.CameraPreview))
                {
                    return(MoSync.Constants.MA_CAMERA_RES_FAILED);
                }
                mCameraPrev = (NativeUI.CameraPreview)w;
                mCameraPrev.SetViewFinderContent(mVideoBrush);

                return(MoSync.Constants.MA_CAMERA_RES_OK);
            };

            /**
             * Returns the number of available Camera on the device.
             */
            ioctls.maCameraNumber = delegate()
            {
                if (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) && PhotoCamera.IsCameraTypeSupported(CameraType.Primary))
                {
                    return(2);
                }
                else if (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) || PhotoCamera.IsCameraTypeSupported(CameraType.Primary))
                {
                    return(1);
                }
                return(0);
            };

            /**
             * Captures an image and stores it as a new data object in the
             * supplied placeholder.
             * @param _formatIndex int the required format.
             * @param _placeHolder int the placeholder used for storing the image.
             */
            ioctls.maCameraSnapshot = delegate(int _formatIndex, int _placeHolder)
            {
                if (isCameraSnapshotInProgress)
                {
                    return(MoSync.Constants.MA_CAMERA_RES_SNAPSHOT_IN_PROGRESS);
                }

                // If MA_CAMERA_SNAPSHOT_MAX_SIZE is sent via _formatIndex then we
                // need to select the biggest available snapshot size/resolution.
                if (MoSync.Constants.MA_CAMERA_SNAPSHOT_MAX_SIZE == _formatIndex)
                {
                    _formatIndex = (int)ioctls.maCameraFormatNumber() - 1;
                }
                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 = null;
                        try
                        {
                            // as the camera always takes a snapshot in landscape left orientation,
                            // we need to rotate the resulting image 90 degrees for a current PortraitUp orientation
                            // and 180 degrees for a current LandscapeRight orientation
                            int rotateAngle = 0;
                            if (currentPage.Orientation == PageOrientation.PortraitUp)
                            {
                                rotateAngle = 90;
                            }
                            else if (currentPage.Orientation == PageOrientation.LandscapeRight)
                            {
                                rotateAngle = 180;
                            }
                            // if the current page is in a LandscapeLeft orientation, the orientation angle will be 0
                            data = RotateImage(args.ImageStream, rotateAngle);
                        }
                        catch
                        {
                            // the orientation angle was not a multiple of 90 - we keep the original image
                            data = args.ImageStream;
                        }
                        MemoryStream dataMem = new MemoryStream((int)data.Length);
                        MoSync.Util.CopySeekableStreams(data, 0, dataMem, 0, (int)data.Length);
                        res.SetInternalObject(dataMem);
                    });
                    are.Set();
                };

                mCamera.CaptureImageAvailable += mCameraSnapshotDelegate;

                mCamera.CaptureImage();

                are.WaitOne();
                return(MoSync.Constants.MA_CAMERA_RES_OK);
            };

            /**
             * Captures an image and stores it as a new data object in new
             * placeholder that is sent via #EVENT_TYPE_CAMERA_SNAPSHOT event.
             * @param _placeHolder int the placeholder used for storing the image.
             * @param _sizeIndex int the required size index.
             */
            ioctls.maCameraSnapshotAsync = delegate(int _placeHolder, int _sizeIndex)
            {
                if (isCameraSnapshotInProgress)
                {
                    return(MoSync.Constants.MA_CAMERA_RES_SNAPSHOT_IN_PROGRESS);
                }

                // If MA_CAMERA_SNAPSHOT_MAX_SIZE is sent via _sizeIndex then we
                // need to select the biggest available snapshot size/resolution.
                if (MoSync.Constants.MA_CAMERA_SNAPSHOT_MAX_SIZE == _sizeIndex)
                {
                    _sizeIndex = (int)ioctls.maCameraFormatNumber() - 1;
                }

                System.Windows.Size dim;
                if (GetCameraFormat(_sizeIndex, 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(() =>
                    {
                        // If the camera was stopped and this delegate was still called then we do nothing here
                        // because in maCameraStop we already send the snapshot failed event.
                        if (!isCameraSnapshotInProgress)
                        {
                            return;
                        }

                        Stream data = null;
                        try
                        {
                            // as the camera always takes a snapshot in landscape left orientation,
                            // we need to rotate the resulting image 90 degrees for a current PortraitUp orientation
                            // and 180 degrees for a current LandscapeRight orientation
                            int rotateAngle = 0;

                            if (currentPage.Orientation == PageOrientation.PortraitUp)
                            {
                                // This is for the front camera.
                                if (mCamera.CameraType != CameraType.Primary)
                                {
                                    rotateAngle = 270;
                                }
                                else
                                {
                                    rotateAngle = 90;
                                }
                            }
                            else if (currentPage.Orientation == PageOrientation.LandscapeRight)
                            {
                                rotateAngle = 180;
                            }
                            // if the current page is in a LandscapeLeft orientation, the orientation angle will be 0
                            data = RotateImage(args.ImageStream, rotateAngle);
                        }
                        catch
                        {
                            // the orientation angle was not a multiple of 90 - we keep the original image
                            data = args.ImageStream;
                        }

                        Resource res         = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, _placeHolder);
                        MemoryStream dataMem = new MemoryStream((int)data.Length);
                        MoSync.Util.CopySeekableStreams(data, 0, dataMem, 0, (int)data.Length);
                        res.SetInternalObject(dataMem);


                        postSnapshotEvent(_placeHolder, mCamera.Resolution,
                                          MoSync.Constants.MA_IMAGE_REPRESENTATION_RAW, MoSync.Constants.MA_CAMERA_RES_OK);


                        isCameraSnapshotInProgress = false;
                    });
                };

                mCamera.CaptureImageAvailable += mCameraSnapshotDelegate;
                mCamera.CaptureImage();
                snapshotPlaceHolder        = _placeHolder;
                isCameraSnapshotInProgress = true;

                return(MoSync.Constants.MA_CAMERA_RES_OK);
            };

            /**
             * Sets the property represented by the string situated at the
             * _property address with the value situated at the _value address.
             * @param _property int the property name address
             * @param _value int the value address
             *
             * Note: the fallowing properties are not available on windows phone
             *      MA_CAMERA_FOCUS_MODE, MA_CAMERA_IMAGE_FORMAT, MA_CAMERA_ZOOM,
             *      MA_CAMERA_MAX_ZOOM.
             */
            ioctls.maCameraSetProperty = delegate(int _property, int _value)
            {
                // if the camera is not initialized, we cannot access any of its properties
                if (!isCameraInitialized)
                {
                    return(MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED);
                }

                String property = core.GetDataMemory().ReadStringAtAddress(_property);
                String value    = core.GetDataMemory().ReadStringAtAddress(_value);

                if (property.Equals(MoSync.Constants.MA_CAMERA_FLASH_MODE))
                {
                    if (value.Equals(MoSync.Constants.MA_CAMERA_FLASH_ON) && mCamera.IsFlashModeSupported(FlashMode.On))
                    {
                        mCamera.FlashMode = FlashMode.On;
                        mFlashMode        = FlashMode.On;
                    }
                    else if (value.Equals(MoSync.Constants.MA_CAMERA_FLASH_OFF) && mCamera.IsFlashModeSupported(FlashMode.Off))
                    {
                        mCamera.FlashMode = FlashMode.Off;
                        mFlashMode        = FlashMode.Off;
                    }
                    else if (value.Equals(MoSync.Constants.MA_CAMERA_FLASH_AUTO) && mCamera.IsFlashModeSupported(FlashMode.Auto))
                    {
                        mCamera.FlashMode = FlashMode.Auto;
                        mFlashMode        = FlashMode.Auto;
                    }
                    else
                    {
                        return(MoSync.Constants.MA_CAMERA_RES_INVALID_PROPERTY_VALUE);
                    }
                    return(MoSync.Constants.MA_CAMERA_RES_OK);
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_FOCUS_MODE))
                {
                    return(MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED);
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_IMAGE_FORMAT))
                {
                    return(MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED);
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_ZOOM))
                {
                    return(MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED);
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_MAX_ZOOM))
                {
                    return(MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED);
                }
                else
                {
                    return(MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED);
                }
            };

            /**
             * Selects a camera from the avalable ones;
             * in this eigther the back or the front camera is
             * chosen
             */
            ioctls.maCameraSelect = delegate(int _camera)
            {
                // if the camera is not initialized, we cannot access any of its properties
                if (!isCameraInitialized)
                {
                    return(MoSync.Constants.MA_CAMERA_RES_FAILED);
                }

                if (MoSync.Constants.MA_CAMERA_CONST_BACK_CAMERA == _camera)
                {
                    if (mCamera.CameraType != CameraType.Primary)
                    {
                        mCameraType = CameraType.Primary;
                        InitCamera();

                        MoSync.Util.RunActionOnMainThreadSync(() =>
                        {
                            SetInitialCameraOrientation(currentPage);
                        }
                                                              );
                    }
                }
                else if (MoSync.Constants.MA_CAMERA_CONST_FRONT_CAMERA == _camera)
                {
                    if (mCamera.CameraType != CameraType.FrontFacing)
                    {
                        mCameraType = CameraType.FrontFacing;
                        InitCamera();

                        MoSync.Util.RunActionOnMainThreadSync(() =>
                        {
                            SetInitialCameraOrientation(currentPage);
                        }
                                                              );
                    }
                }
                else
                {
                    return(MoSync.Constants.MA_CAMERA_RES_FAILED);
                }

                return(MoSync.Constants.MA_CAMERA_RES_OK);
            };

            /**
             * Retrieves the specified property value in the given buffer.
             * @param _property int the address for the property string
             * @param _value int the address for the property value string (the buffer)
             * @param _bufSize int the buffer size
             */
            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);
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_ZOOM_SUPPORTED))
                {
                    core.GetDataMemory().WriteStringAtAddress(
                        _value,
                        "false",
                        _bufSize);
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_FLASH_SUPPORTED))
                {
                    /*
                     * Since we cannot see if flash is supported because the camera may be not
                     * fully initialized when this is called, we assume that each windows phone
                     * has flash support for primary camera but not for the from camera.
                     */
                    String result = "true";
                    if (mCamera.CameraType != CameraType.Primary)
                    {
                        result = "false";
                    }

                    core.GetDataMemory().WriteStringAtAddress(
                        _value,
                        result,
                        _bufSize);
                }
                else
                {
                    return(MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED);
                }
                return(0);
            };

            ioctls.maCameraRecord = delegate(int _stopStartFlag)
            {
                return(MoSync.Constants.MA_CAMERA_RES_FAILED);
            };
        }
        /**
         * Initializing the ioctls.
         */
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            mCamera = new PhotoCamera(mCameraType);
            mVideoBrush = new VideoBrush();

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

            // this should be set according to the orientation of
            // the device I guess.

            // we need to handle the camera orientation by hand
            PhoneApplicationPage currentPage = (((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage);

            // we need to handle the initial page orientation
            double rotation = mCamera.Orientation;
            if (currentPage.Orientation == PageOrientation.LandscapeLeft)
            {
                rotation -= 90;
            }
            else if (currentPage.Orientation == PageOrientation.LandscapeRight)
            {
                rotation += 90;
            }
            mVideoBrush.RelativeTransform = new CompositeTransform()
            {
                CenterX = 0.5,
                CenterY = 0.5,
                Rotation = rotation
            };

            // on orientation changed, we need to rotate the video brush
            currentPage.OrientationChanged += new System.EventHandler<OrientationChangedEventArgs>(
                delegate(object o, OrientationChangedEventArgs args)
                {
                    rotation = mCamera.Orientation;
                    if (args.Orientation == PageOrientation.LandscapeLeft)
                    {
                        rotation -= 90;
                    }
                    else if (args.Orientation == PageOrientation.LandscapeRight)
                    {
                        rotation += 90;
                    }

                    mVideoBrush.RelativeTransform = new CompositeTransform()
                    {
                        CenterX = 0.5,
                        CenterY = 0.5,
                        Rotation = rotation
                    };
                });

            /**
             * Stores an output format in fmm parameter.
             * @param _index int the index of the required format.
             * @param _fmt int the momory address at which to write the output format dimensions.
             *
             * Note: the _index should be greater than 0 and smaller than the number of camera formats.
             */
            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;
            };

            /**
            * Returns the number of different output formats supported by the current device's camera.
            * \< 0 if there is no camera support.
            * 0 if there is camera support, but the format is unknown.
            */
            ioctls.maCameraFormatNumber = delegate()
            {
                // if the camera is not initialized, we cannot access any of its properties
                if (!isCameraInitialized)
                {
                    // because the cammera is supported but not initialized, we return 0
                    return 0;
                }

                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++;
                    resolutions.MoveNext();
                    if (resolutions.Current == new System.Windows.Size(0, 0))
                        break;
                }
                return number;
            };

            /**
             * Starts the viewfinder and the camera
             */
            ioctls.maCameraStart = delegate()
            {
                initCamera();

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    mCameraPrev.StartViewFinder();
                });

                return 0;
            };

            /**
             * stops the view finder and the camera.
             */
            ioctls.maCameraStop = delegate()
            {
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    mCameraPrev.StopViewFinder();
                });

                return 0;
            };

            /**
             * Adds a previewWidget to the camera controller in devices that support native UI.
             */
            ioctls.maCameraSetPreview = delegate(int _widgetHandle)
            {
                // if the camera is not initialized, we need to initialize it before
                // setting the preview
                if (!isCameraInitialized)
                {
                    initCamera();
                }

                IWidget w = runtime.GetModule<NativeUIModule>().GetWidget(_widgetHandle);
                if (w.GetType() != typeof(MoSync.NativeUI.CameraPreview))
                {
                    return MoSync.Constants.MA_CAMERA_RES_FAILED;
                }
                mCameraPrev = (NativeUI.CameraPreview)w;
                mCameraPrev.SetViewFinderContent(mVideoBrush);

                return MoSync.Constants.MA_CAMERA_RES_OK;
            };

            /**
             * Returns the number of available Camera on the device.
             */
            ioctls.maCameraNumber = delegate()
            {
                if (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) && PhotoCamera.IsCameraTypeSupported(CameraType.Primary))
                    return 2;
                else if (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) || PhotoCamera.IsCameraTypeSupported(CameraType.Primary))
                    return 1;
                return 0;
            };

            /**
             * Captures an image and stores it as a new data object in the
             * supplied placeholder.
             * @param _formatIndex int the required format.
             * @param _placeHolder int the placeholder used for storing the image.
             */
            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;
                        MemoryStream dataMem = new MemoryStream((int)data.Length);
                        MoSync.Util.CopySeekableStreams(data, 0, dataMem, 0, (int)data.Length);
                        res.SetInternalObject(dataMem);
                    });
                    are.Set();
                };

                mCamera.CaptureImageAvailable += mCameraSnapshotDelegate;

                mCamera.CaptureImage();

                are.WaitOne();
                return 0;
            };

            /**
             * Sets the property represented by the string situated at the
             * _property address with the value situated at the _value address.
             * @param _property int the property name address
             * @param _value int the value address
             *
             * Note: the fallowing properties are not available on windows phone
             *      MA_CAMERA_FOCUS_MODE, MA_CAMERA_IMAGE_FORMAT, MA_CAMERA_ZOOM,
             *      MA_CAMERA_MAX_ZOOM.
             */
            ioctls.maCameraSetProperty = delegate(int _property, int _value)
            {
                // if the camera is not initialized, we cannot access any of its properties
                if (!isCameraInitialized)
                {
                    return MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED;
                }

                String property = core.GetDataMemory().ReadStringAtAddress(_property);
                String value = core.GetDataMemory().ReadStringAtAddress(_value);

                if (property.Equals(MoSync.Constants.MA_CAMERA_FLASH_MODE))
                {
                    if (value.Equals(MoSync.Constants.MA_CAMERA_FLASH_ON))
                    {
                        mCamera.FlashMode = FlashMode.On;
                        mFlashMode = FlashMode.On;
                    }
                    else if (value.Equals(MoSync.Constants.MA_CAMERA_FLASH_OFF))
                    {
                        mCamera.FlashMode = FlashMode.Off;
                        mFlashMode = FlashMode.Off;
                    }
                    else if (value.Equals(MoSync.Constants.MA_CAMERA_FLASH_AUTO))
                    {
                        mCamera.FlashMode = FlashMode.Auto;
                        mFlashMode = FlashMode.Auto;
                    }
                    else return MoSync.Constants.MA_CAMERA_RES_INVALID_PROPERTY_VALUE;

                    return MoSync.Constants.MA_CAMERA_RES_OK;
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_FOCUS_MODE))
                {
                    return MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED;
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_IMAGE_FORMAT))
                {
                    return MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED;
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_ZOOM))
                {
                    return MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED;
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_MAX_ZOOM))
                {
                    return MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED;
                }
                else return MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED;
            };

            /**
             * Selects a camera from the avalable ones;
             * in this eigther the back or the front camera is
             * chosen
             */

            ioctls.maCameraSelect = delegate(int _camera)
            {
                // if the camera is not initialized, we cannot access any of its properties
                if (!isCameraInitialized)
                {
                    return MoSync.Constants.MA_CAMERA_RES_FAILED;
                }

                if ( MoSync.Constants.MA_CAMERA_CONST_BACK_CAMERA == _camera)
                {
                    if (mCamera.CameraType != CameraType.Primary)
                    {
                        mCameraType = CameraType.Primary;
                        initCamera();
                    }
                }
                else if (MoSync.Constants.MA_CAMERA_CONST_FRONT_CAMERA == _camera)
                {
                    if (mCamera.CameraType != CameraType.FrontFacing)
                    {
                        mCameraType = CameraType.FrontFacing;
                        initCamera();
                    }
                }
                else return MoSync.Constants.MA_CAMERA_RES_FAILED;

                return MoSync.Constants.MA_CAMERA_RES_OK;
            };

            /**
             * Retrieves the specified property value in the given buffer.
             * @param _property int the address for the property string
             * @param _value int the address for the property value string (the buffer)
             * @param _bufSize int the buffer size
             */
            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);
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_ZOOM_SUPPORTED))
                {
                    core.GetDataMemory().WriteStringAtAddress(
                        _value,
                        "false",
                        _bufSize);
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_FLASH_SUPPORTED))
                {
                    core.GetDataMemory().WriteStringAtAddress(
                        _value,
                        "true",
                        _bufSize);
                }
                else return MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED;
                return 0;
            };

            ioctls.maCameraRecord = delegate(int _stopStartFlag)
            {
                return MoSync.Constants.MA_CAMERA_RES_FAILED;
            };
        }
Exemple #38
0
        public Runtime(Core core)
        {
            mCore         = core;
            mSyscalls     = new Syscalls();
            mIoctls       = new Ioctls();
            mIoctlInvoker = new IoctlInvoker(mCore, mIoctls);

            mCurrentResourceHandle = 1;
            mStaticResourceCount   = 0;

            PhoneApplicationFrame mainPage = (PhoneApplicationFrame)Application.Current.RootVisual;

            mainPage.MouseLeftButtonDown += MouseLeftButtonDown;
            mainPage.MouseMove           += this.MouseMove;
            mainPage.MouseLeftButtonUp   += MouseLeftButtonUp;

            // clear the list of system property providers
            // We clear it before we initialize all the modules, because
            // different modules might register system property providers.
            SystemPropertyManager.ClearSystemPropertyProviders();

            RegisterCleaner(() =>
            {
                Util.RunActionOnMainThreadSync(() =>
                {
                    mainPage.MouseLeftButtonDown -= MouseLeftButtonDown;
                    mainPage.MouseMove           -= this.MouseMove;
                    mainPage.MouseLeftButtonUp   -= MouseLeftButtonUp;
                });
            });

            InitSyscalls();

            mSyscalls.maGetEvent = delegate(int ptr)
            {
                if (mEvents.Count != 0)
                {
                    lock (mEvents)
                    {
                        Event  evt       = mEvents[0];
                        Memory eventData = evt.GetEventData();
                        mEvents.RemoveAt(0);
                        Memory customEventData = evt.GetCustomEventData();
                        if (customEventData != null)
                        {
                            mCore.GetDataMemory().WriteMemoryAtAddress(mCore.GetCustomEventDataPointer(),
                                                                       customEventData, 0, customEventData.GetSizeInBytes());
                            eventData.WriteInt32(MoSync.Struct.MAEvent.data, mCore.GetCustomEventDataPointer());
                        }
                        mCore.GetDataMemory().WriteMemoryAtAddress(ptr, eventData, 0, eventData.GetSizeInBytes());
                    }
                    return(1);
                }
                else
                {
                    return(0);
                }
            };

            mSyscalls.maWait = delegate(int timeout)
            {
                if (timeout <= 0)
                {
                    timeout = 1 << 15;
                }
                mEventWaiter.WaitOne(timeout);
            };

#if !LIB
            mSyscalls.maIOCtl = delegate(int id, int a, int b, int c)
#else
            mSyscalls.maIOCtl = delegate(int id, int a, int b, int c, int args)
#endif
            {
#if !LIB
                return(mIoctlInvoker.InvokeIoctl(id, a, b, c));
#else
                return(mIoctlInvoker.InvokeIoctl(id, a, b, c, args));
#endif
            };

            mSyscalls.maDestroyObject = delegate(int res)
            {
                mResources[res].SetResourceType(MoSync.Constants.RT_PLACEHOLDER);
                mResources[res].SetInternalObject(null);
            };

            mSyscalls.maLoadResource = delegate(int _handle, int _placeholder, int _flag)
            {
                Resource      res         = mResources[_handle];
                BoundedStream stream      = res.GetFileStream();
                Resource      placeholder = mResources[_placeholder];
                if (stream == null)
                {
                    return(0);
                }
                if (placeholder.GetInternalObject() != null)
                {
                    return(0);
                }

                stream.Seek(0, SeekOrigin.Begin);
                LoadResource(stream, (byte)res.GetResourceType(), (uint)stream.Length, placeholder);

                return(1);
            };

            mSyscalls.maLoadResources = delegate(int _data)
            {
                Resource res  = GetResource(MoSync.Constants.RT_BINARY, _data);
                Stream   data = (Stream)res.GetInternalObject();
                return(LoadResources(data, false)?1:0);
            };

            mSyscalls.maCountResources = delegate()
            {
                return(mStaticResourceCount);
            };
        }
        public void Init(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;
                    });

                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()
            {
                Syscalls syscalls = runtime.GetSyscalls();
                syscalls.maUpdateScreen = mOldUpdateScreenImplementation;
                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;
            };
        }
        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)
 {
 }
        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)
        {
            /**
             * 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;

                // MA_SCREEN_ORIENTATION_PORTRAIT = MA_SCREEN_ORIENTATION_PORTRAIT_UP|MA_SCREEN_ORIENTATION_PORTRAIT_UPSIDE_DOWN.
                if (((orientations & MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UP) == MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UP) ||
                    ((orientations & MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UPSIDE_DOWN) == MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UPSIDE_DOWN))

                {
                    isPortrait = true;
                }

                // MA_SCREEN_ORIENTATION_LANDSCAPE = MA_SCREEN_ORIENTATION_LANDSCAPE_RIGHT|MA_SCREEN_ORIENTATION_LANDSCAPE_LEFT.
                if (((orientations & MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_LEFT) == MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_LEFT) ||
                    ((orientations & MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_RIGHT) == MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_RIGHT))
                {
                    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;
            };

            /**
             * @deprecated Use maScreenSetSupportedOrientations instead.
             * 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.
                    switch (currentPage.SupportedOrientations)
                    {
                        case SupportedPageOrientation.PortraitOrLandscape:
                            suportedOrientations = suportedOrientations |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE;
                            break;
                        case SupportedPageOrientation.Landscape:
                            suportedOrientations = suportedOrientations |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE;
                            break;
                        case SupportedPageOrientation.Portrait:
                            suportedOrientations = suportedOrientations |
                                               MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT;
                            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:
                        case PageOrientation.Landscape:
                            currentOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_LANDSCAPE_LEFT;
                            break;
                        case PageOrientation.PortraitUp:
                        case PageOrientation.Portrait:
                            currentOrientation = MoSync.Constants.MA_SCREEN_ORIENTATION_PORTRAIT_UP;
                            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)
        {
            ioctls.maSensorStart = delegate(int _sensor, int _interval)
            {
                long intervalIn100Nanoseconds = (long)_interval * 10000;
                if (_sensor == MoSync.Constants.SENSOR_TYPE_ACCELEROMETER &&
                    Accelerometer.IsSupported)
                {
                    mAccelerometer = new Accelerometer();
                    mAccelerometer.TimeBetweenUpdates = new TimeSpan(intervalIn100Nanoseconds);
                    mAccelerometer.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs<AccelerometerReading> args)
                        {
                            Vector3 acc = args.SensorReading.Acceleration;
                            SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_ACCELEROMETER, acc);
                        };
                }
                else if (_sensor == MoSync.Constants.SENSOR_TYPE_GYROSCOPE &&
                    Gyroscope.IsSupported)
                {
                    mGyroscope = new Gyroscope();
                    mGyroscope.TimeBetweenUpdates = new TimeSpan(intervalIn100Nanoseconds);
                    mGyroscope.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs<GyroscopeReading> args)
                        {
                            Vector3 rot = args.SensorReading.RotationRate;
                            SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_GYROSCOPE, rot);
                        };
                }
                else if (_sensor == MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD &&
                    Compass.IsSupported)
                {
                    mCompass = new Compass();
                    mCompass.TimeBetweenUpdates = new TimeSpan(intervalIn100Nanoseconds);
                    mCompass.CurrentValueChanged +=
                        delegate(object sender, SensorReadingEventArgs<CompassReading> args)
                        {
                            Vector3 rot = args.SensorReading.MagnetometerReading;
                            SendSensorEventVector(runtime, MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD, rot);
                        };
                }
            #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;
                        }
                        break;
                    case MoSync.Constants.SENSOR_TYPE_GYROSCOPE:
                        if (mGyroscope != null)
                        {
                            mGyroscope.Stop();
                            mGyroscope = null;
                        }
                        break;
                    case MoSync.Constants.SENSOR_TYPE_MAGNETIC_FIELD:
                        if (mCompass != null)
                        {
                            mCompass.Stop();
                            mCompass = null;
                        }
                        break;
                    case MoSync.Constants.SENSOR_TYPE_ORIENTATION:
                        if (mMotion != null)
                        {
                            mMotion.Stop();
                            mMotion = null;
                        }
                        break;
                }
                return MoSync.Constants.SENSOR_ERROR_NONE;
            };

            ioctls.maLocationStart = delegate()
            {

                return 0;
            };

            ioctls.maLocationStop = delegate()
            {
                return 0;
            };
        }
Exemple #45
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)
                    {
                        FontInfo nfi = finfo.Clone();
                        nfi.size = _size;
                        mFonts.Add(nfi);
                        return(mFonts.Count - 1);
                    }
                }

                return(MoSync.Constants.RES_FONT_NAME_NONEXISTENT);
            };

            ioctls.maFontLoadDefault = delegate(int _type, int _style, int _size)
            {
                string name;
                switch (_type)
                {
                case MoSync.Constants.FONT_TYPE_MONOSPACE:
                    name = "Courier New";
                    break;

                case MoSync.Constants.FONT_TYPE_SERIF:
                    name = "Times New Roman";
                    break;

                case MoSync.Constants.FONT_TYPE_SANS_SERIF:
                    name = "Segoe WP";
                    break;

                default:
                    return(MoSync.Constants.RES_FONT_NO_TYPE_STYLE_COMBINATION);
                }

                FontWeight w = FontWeights.Normal;
                FontStyle  s = FontStyles.Normal;
                if ((_style & MoSync.Constants.FONT_STYLE_BOLD) != 0)
                {
                    w = FontWeights.Bold;
                }
                if ((_style & MoSync.Constants.FONT_STYLE_ITALIC) != 0)
                {
                    s = FontStyles.Italic;
                }

                mFonts.Add(new FontInfo()
                {
                    family = new FontFamily(name),
                    weight = w,
                    style  = s,
                    size   = _size,
                });

                return(mFonts.Count - 1);
            };

            ioctls.maFontDelete = delegate(int _handle)
            {
                mFonts.RemoveAt(_handle);
                return(0);
            };
        }
Exemple #46
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
#if false
            mAudioInstanceUpdater = new AudioInstanceUpdater(mAudioInstances);
            Thread thread = new Thread(new ThreadStart(mAudioInstanceUpdater.Loop));
            thread.Start();
#endif
            ioctls.maAudioDataCreateFromURL = delegate(int _mime, int _url, int _flags)
            {
                int ret = MoSync.Constants.MA_AUDIO_ERR_GENERIC;

                try
                {
                    String     url          = core.GetDataMemory().ReadStringAtAddress(_url);
                    String     mime         = core.GetDataMemory().ReadStringAtAddress(_mime);
                    bool       shouldStream = (_flags & MoSync.Constants.MA_AUDIO_DATA_STREAM) != 0;
                    IAudioData ad;
                    if (mime == "audio/mpeg")
                    {
                        ad = Mp3Audio.FromUrlOrFilePath(url, shouldStream);
                    }
                    else
                    {
                        ad = Audio.FromUrlOrFilePath(url, shouldStream);
                    }
                    lock (mAudioData)
                    {
                        mAudioData.Add(ad);
                        ret = mAudioData.Count - 1;
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(ret);
            };

            ioctls.maAudioDataCreateFromResource = delegate(int _mime, int _data, int _offset, int _length, int _flags)
            {
                int ret = MoSync.Constants.MA_AUDIO_ERR_GENERIC;
                try
                {
                    Resource      audiores = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                    BoundedStream s        = new BoundedStream((Stream)audiores.GetInternalObject(), _offset, _length);
                    String        mime     = core.GetDataMemory().ReadStringAtAddress(_mime);
                    IAudioData    ad;
                    if (mime == "audio/mpeg")
                    {
                        ad = Mp3Audio.FromStream(s);
                    }
                    else
                    {
                        ad = Audio.FromStream(s, (_flags & MoSync.Constants.MA_AUDIO_DATA_STREAM) != 0);
                    }
                    lock (mAudioData)
                    {
                        mAudioData.Add(ad);
                        ret = mAudioData.Count - 1;
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(ret);
            };

            ioctls.maAudioDataDestroy = delegate(int _audioData)
            {
                try
                {
                    lock (mAudioData)
                    {
                        IAudioData ad = mAudioData[_audioData];
                        ad.Dispose();
                        mAudioData[_audioData] = null;
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };

            ioctls.maAudioPrepare = delegate(int _audioInstance, int async)
            {
                try
                {
                    lock (mAudioInstances)
                    {
                        IAudioInstance ad = mAudioInstances[_audioInstance];
                        if (async == 0)
                        {
                            ad.Prepare(null);
                        }
                        else
                        {
                            ad.Prepare(() =>
                            {
                                // Send initialized event.
                                MoSync.Memory eventData = new MoSync.Memory(8);
                                eventData.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_AUDIO_PREPARED);
                                eventData.WriteInt32(MoSync.Struct.MAEvent.audioInstance, _audioInstance);
                                runtime.PostEvent(new Event(eventData));
                            }
                                       );
                        }
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };

            ioctls.maAudioInstanceCreate = delegate(int _audioData)
            {
                int ret = MoSync.Constants.MA_AUDIO_ERR_GENERIC;
                try
                {
                    lock (mAudioInstances)
                    {
                        IAudioData ad = mAudioData[_audioData];
                        mAudioInstances.Add(ad.CreateInstance());
                        ret = mAudioInstances.Count - 1;
                    }
                }

                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(ret);
            };

            ioctls.maAudioInstanceCreateDynamic = delegate(int _sampleRate, int _numChannels, int _bufferSize)
            {
                int ret = MoSync.Constants.MA_AUDIO_ERR_GENERIC;
                try
                {
                    lock (mAudioInstances)
                    {
                        AudioInstanceDynamic aid = Audio.CreateDynamic(_sampleRate, _numChannels, _bufferSize);
                        mAudioInstances.Add(aid);
                        ret = mAudioInstances.Count - 1;

                        aid.SetOnBufferNeededCallback(() =>
                        {
                            // Send initialized event.
                            MoSync.Memory eventData = new MoSync.Memory(8);
                            eventData.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_AUDIO_COMPLETED);
                            eventData.WriteInt32(MoSync.Struct.MAEvent.audioInstance, ret);
                            runtime.PostEvent(new Event(eventData));
                        });
                    }
                }

                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(ret);
            };

            ioctls.maAudioGetPendingBufferCount = delegate(int _instance)
            {
                int ret = MoSync.Constants.MA_AUDIO_ERR_GENERIC;
                try
                {
                    lock (mAudioInstances)
                    {
                        AudioInstanceDynamic ai = (AudioInstanceDynamic)mAudioInstances[_instance];
                        ret = ai.GetPendingBufferCount();
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(ret);
            };

            ioctls.maAudioSubmitBuffer = delegate(int _instance, int _pointer, int _numBytes)
            {
                try
                {
                    lock (mAudioInstances)
                    {
                        AudioInstanceDynamic ai = (AudioInstanceDynamic)mAudioInstances[_instance];
                        ai.SubmitBuffer(core.GetDataMemory().GetData(), _pointer, _numBytes);
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };

            ioctls.maAudioInstanceDestroy = delegate(int _audioInstance)
            {
                try
                {
                    lock (mAudioInstances)
                    {
                        IAudioInstance ai = mAudioInstances[_audioInstance];
                        ai.Dispose();
                        mAudioInstances[_audioInstance] = null;
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };

            ioctls.maAudioPlay = delegate(int _audioInstance)
            {
                try
                {
                    lock (mAudioInstances)
                    {
                        IAudioInstance ai = mAudioInstances[_audioInstance];
                        ai.Play();
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };


            ioctls.maAudioStop = delegate(int _audioInstance)
            {
                try
                {
                    lock (mAudioInstances)
                    {
                        IAudioInstance ai = mAudioInstances[_audioInstance];
                        ai.Stop();
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };

            ioctls.maAudioPause = delegate(int _audioInstance)
            {
                try
                {
                    lock (mAudioInstances)
                    {
                        IAudioInstance ai = mAudioInstances[_audioInstance];
                        ai.Pause();
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };

            ioctls.maAudioSetNumberOfLoops = delegate(int _audioInstance, int loops)
            {
                try
                {
                    lock (mAudioInstances)
                    {
                        IAudioInstance ai = mAudioInstances[_audioInstance];
                        ai.SetNumberOfLoops(loops);
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };


            // SoundEffectInstances nor the MediaPlayer doesn't support setting position,
            // however we can make a special case where the sound is reset if _milliseconds equals to zero.
            // We could implement a better SoundEffectInstance using DynamicSoundEffectInstance
            // parsing wavefiles ourselves.. But that would require some work.

            ioctls.maAudioSetPosition = delegate(int _audioInstance, int _milliseconds)
            {
                try
                {
                    lock (mAudioInstances)
                    {
                        IAudioInstance ai = mAudioInstances[_audioInstance];
                        ai.SetPosition(_milliseconds);
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };


            // SoundEffectInstances doesnt support getting the location of the sound
            // this of course could be approximated by saving a time stamp when the sound
            // starts to play, buuut no.
            ioctls.maAudioGetPosition = delegate(int _audioInstance)
            {
                int ret = MoSync.Constants.MA_AUDIO_ERR_OK;
                try
                {
                    lock (mAudioInstances)
                    {
                        IAudioInstance ai = mAudioInstances[_audioInstance];
                        ret = ai.GetPosition();
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(ret);
            };

            ioctls.maAudioGetLength = delegate(int _audioInstance)
            {
                int ret = MoSync.Constants.MA_AUDIO_ERR_OK;
                try
                {
                    lock (mAudioInstances)
                    {
                        IAudioInstance ai = mAudioInstances[_audioInstance];
                        ret = ai.GetLength();
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(ret);
            };

            ioctls.maAudioSetVolume = delegate(int _audioInstance, float volume)
            {
                try
                {
                    lock (mAudioInstances)
                    {
                        IAudioInstance ai = mAudioInstances[_audioInstance];
                        ai.SetVolume(volume);
                    }
                }
                catch (MoSync.Util.ReturnValueException rve)
                {
                    return(rve.result);
                }
                catch (Exception)
                {
                    return(MoSync.Constants.MA_AUDIO_ERR_GENERIC);
                }

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };
        }
        /*
        private void OnAlertMessageBoxClosed(IAsyncResult ar)
        {
            int? buttonIndex = Guide.EndShowMessageBox(ar);

            Memory eventData = new Memory(8);
            eventData.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_ALERT);
            eventData.WriteInt32(MoSync.Struct.MAEvent.alertButtonIndex, (int)(buttonIndex + 1));

            mRuntime.PostEvent(new Event(eventData));
        }
        */
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            mRuntime = runtime;
            mCore = core;
            /**
             * Register system properties
             */
            SystemPropertyManager.SystemPropertyProvider myDelegateForDeviceInfo = new SystemPropertyManager.SystemPropertyProvider(getDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.imei",              myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.imsi",              myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.iso-639-1",         myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.iso-639-2",         myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device",            myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device.name",       myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device.UUID",       myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device.OS",         myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device.OS.version", myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.network.type",      myDelegateForDeviceInfo);

            ioctls.maWriteLog = delegate(int src, int size)
            {
                byte[] bytes = new byte[size];
                core.GetDataMemory().ReadBytes(bytes, src, size);
                MoSync.Util.Log(bytes);
                return 0;
            };

            ioctls.maMessageBox = delegate(int _caption, int _message)
            {
                String message = core.GetDataMemory().ReadStringAtAddress(_message);
                String caption = core.GetDataMemory().ReadStringAtAddress(_caption);
                MoSync.Util.ShowMessage(message, false, caption);
                return 0;
            };

            ioctls.maTextBox = delegate(int _title, int _inText, int _outText, int _maxSize, int _constraints)
            {
                bool passwordMode = false;
                if ((_constraints & MoSync.Constants.MA_TB_FLAG_PASSWORD) != 0)
                    passwordMode = true;

                if ((_constraints & MoSync.Constants.MA_TB_TYPE_MASK) != MoSync.Constants.MA_TB_TYPE_ANY)
                    return MoSync.Constants.MA_TB_RES_TYPE_UNAVAILABLE;

                try
                {
                    Guide.BeginShowKeyboardInput(Microsoft.Xna.Framework.PlayerIndex.One,
                        core.GetDataMemory().ReadWStringAtAddress(_title), "",
                        core.GetDataMemory().ReadWStringAtAddress(_inText),
                        delegate(IAsyncResult result)
                        {
                            string text = Guide.EndShowKeyboardInput(result);

                            Memory eventData = new Memory(12);
                            eventData.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_TEXTBOX);
                            int res = MoSync.Constants.MA_TB_RES_OK;
                            int len = 0;
                            if (text == null)
                            {
                                res = MoSync.Constants.MA_TB_RES_CANCEL;
                            }
                            else
                            {
                                len = text.Length;
                            }

                            eventData.WriteInt32(MoSync.Struct.MAEvent.textboxResult, res);
                            eventData.WriteInt32(MoSync.Struct.MAEvent.textboxLength, len);
                            core.GetDataMemory().WriteWStringAtAddress(_outText, text, _maxSize);
                            mRuntime.PostEvent(new Event(eventData));
                        },
                        null
                        , passwordMode);
                }
                catch (Exception)
                {
                    return -1;
                }

                return 0;
            };

            /**
             * @author: Ciprian Filipas
             * @brief: The maAlert ioctl implementation.
             * @note: On WP7 only 2 buttons are available, OK and CANCEL. Also if the buttons get null values from
             *        MoSync WP7 platform will automatically add the OK button. Regarding these facts the _b2 button will
             *        be ignored in the current implementation.
             */
            ioctls.maAlert = delegate(int _title, int _message, int _b1, int _b2, int _b3)
            {
                String title = "", message = "";

                if( 0 != _title )
                    title = core.GetDataMemory().ReadStringAtAddress(_title);
                if( 0 != _message )
                    message = core.GetDataMemory().ReadStringAtAddress(_message);

                if (0 != _b3)
                {
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                        {
                            MessageBoxResult result = MessageBox.Show(message, title, MessageBoxButton.OKCancel);
                            if (result == MessageBoxResult.OK)
                            {
                                Memory eventData = new Memory(8);
                                const int MAWidgetEventData_eventType = 0;
                                const int MAWidgetEventData_eventArgumentValue = 4;

                                //write 1 down since the buttone clicked is the first one
                                eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.EVENT_TYPE_ALERT);
                                eventData.WriteInt32(MAWidgetEventData_eventArgumentValue, 1);
                                //Posting a CustomEvent
                                mRuntime.PostEvent(new Event(eventData));
                            }
                            else if (result == MessageBoxResult.Cancel)
                            {
                                Memory eventData = new Memory(8);
                                const int MAWidgetEventData_eventType = 0;
                                const int MAWidgetEventData_eventArgumentValue = 4;

                                //write 1 down since the buttone clicked is the first one
                                eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.EVENT_TYPE_ALERT);
                                eventData.WriteInt32(MAWidgetEventData_eventArgumentValue, 3);
                                //Posting a CustomEvent
                                mRuntime.PostEvent(new Event(eventData));
                            }
                        }
                    );
                }
                else
                {
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                        {
                            MessageBox.Show(message, title, MessageBoxButton.OK);

                            // Since the only way to exit the messageBox is by pressing OK there is no
                            // need for a result object.

                            Memory eventData = new Memory(8);
                            const int MAWidgetEventData_eventType = 0;
                            const int MAWidgetEventData_eventArgumentValue = 4;

                            //write 1 down since the buttone clicked is the first one
                            eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.EVENT_TYPE_ALERT);
                            eventData.WriteInt32(MAWidgetEventData_eventArgumentValue, 1);
                            //Posting a CustomEvent
                            mRuntime.PostEvent(new Event(eventData));
                        }
                    );
                }

                return 0;
            };

            ioctls.maGetSystemProperty = delegate(int _key, int _buf, int _size)
            {
                String key = core.GetDataMemory().ReadStringAtAddress(_key);
                String value = MoSync.SystemPropertyManager.GetSystemProperty(key);
                if (value == null)
                    return -2;
                if (value.Length + 1 <= _size)
                {
                    if(key.Equals("mosync.network.type"))
                    {
                        /**
                         * This code converts the result return by the GetSystemProperty
                         * for the "mosync.network.type" key to be supported by the current
                         * MoSync SDK 3.0
                         */
                        if (value.ToLower().Contains("wireless"))
                        {
                            value = "wifi";
                        }
                        else if(value.ToLower().Contains("ethernet"))
                        {
                            value = "ethernet";
                        }
                        else if(value.ToLower().Contains("mobilebroadbandgsm"))
                        {
                            value = "2g";
                        }
                        else if (value.ToLower().Contains("mobilebroadbandcdma"))
                        {
                            value = "3g";
                        }
                    }
                    core.GetDataMemory().WriteStringAtAddress(_buf, value, _size);
                }
                return value.Length + 1;
            };

            ioctls.maWakeLock = delegate(int flag)
            {
                if (MoSync.Constants.MA_WAKE_LOCK_ON == flag)
                {
                    Microsoft.Phone.Shell.PhoneApplicationService.Current.
                        UserIdleDetectionMode =
                            Microsoft.Phone.Shell.IdleDetectionMode.Enabled;
                }
                else
                {
                    Microsoft.Phone.Shell.PhoneApplicationService.Current.
                        UserIdleDetectionMode =
                            Microsoft.Phone.Shell.IdleDetectionMode.Disabled;
                }
                return 1;
            };

            // validates image input data and dispaches a delegate to save the image to camera roll
            ioctls.maSaveImageToDeviceGallery = delegate(int imageHandle, int imageNameAddr)
            {
                int returnCode = MoSync.Constants.MA_MEDIA_RES_IMAGE_EXPORT_FAILED;

                //Get the resource with the specified handle
                Resource res = mRuntime.GetResource(MoSync.Constants.RT_IMAGE, imageHandle);
                String imageName = mCore.GetDataMemory().ReadStringAtAddress(imageNameAddr);

                if ( (null != res) && !String.IsNullOrEmpty(imageName))
                {
                    object[] myArray = new object[3];
                    myArray[0] = imageHandle;
                    myArray[1] = imageName;
                    myArray[2] = res;

                    Deployment.Current.Dispatcher.BeginInvoke(
                        new Delegate_SaveImageToCameraRoll(SaveImageToCameraRoll),myArray);

                    returnCode = MoSync.Constants.MA_MEDIA_RES_OK;
                }

                return returnCode;
            };
        }
        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)
        {
            // add system property providers
            SystemPropertyManager.mSystemPropertyProviders.Clear();

            /**
             * Register system properties
             */
            SystemPropertyManager.SystemPropertyProvider myDelegateForDeviceInfo = new SystemPropertyManager.SystemPropertyProvider(getDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.imei",              myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.imsi",              myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.iso-639-1",         myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.iso-639-2",         myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device",            myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device.name",       myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device.UUID",       myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device.OS",         myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.device.OS.version", myDelegateForDeviceInfo);
            SystemPropertyManager.RegisterSystemPropertyProvider("mosync.network.type",      myDelegateForDeviceInfo);

            ioctls.maWriteLog = delegate(int src, int size)
            {
                byte[] bytes = new byte[size];
                core.GetDataMemory().ReadBytes(bytes, src, size);
                MoSync.Util.Log(bytes);
                return 0;
            };

            ioctls.maGetSystemProperty = delegate(int _key, int _buf, int _size)
            {
                String key = core.GetDataMemory().ReadStringAtAddress(_key);
                String value = MoSync.SystemPropertyManager.GetSystemProperty(key);
                if (value == null)
                    return -2;
                if (value.Length + 1 <= _size)
                    core.GetDataMemory().WriteStringAtAddress(_buf, value, _size);
                return value.Length + 1;
            };
        }
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            mRuntime = runtime;

            ioctls.maOpenGLInitFullscreen = delegate(int _glApi)
            {
                if (_glApi != MoSync.Constants.MA_GL_API_GL1)
                {
                    return(MoSync.Constants.MA_GL_INIT_RES_ERROR);
                }


                Syscalls syscalls = runtime.GetSyscalls();
                mOldUpdateScreenImplementation = syscalls.maUpdateScreen;

                syscalls.maUpdateScreen = delegate()
                {
                    if (maUpdateScreenAction != null)
                    {
                        maUpdateScreenAction();
                    }
                };

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    // GamePage must always exist for fullscreen apps to work.
                    if (((PhoneApplicationFrame)Application.Current.RootVisual).Navigate(new Uri("/GamePage.xaml", UriKind.Relative)))
                    {
                    }
                });

                return(MoSync.Constants.MA_GL_INIT_RES_OK);
            };

            ioctls.maOpenGLCloseFullscreen = delegate()
            {
                return(MoSync.Constants.MA_GL_INIT_RES_OK);
            };

            ioctls.maOpenGLTexImage2D = delegate(int _res)
            {
                Resource        res    = runtime.GetResource(MoSync.Constants.RT_IMAGE, _res);
                WriteableBitmap src    = (WriteableBitmap)res.GetInternalObject();
                byte[]          pixels = src.ToByteArray();
                mGL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, src.PixelWidth, src.PixelHeight, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pixels, 0);
                return(MoSync.Constants.MA_GL_TEX_IMAGE_2D_OK);
            };

            ioctls.maOpenGLTexSubImage2D = delegate(int _res)
            {
                Resource        res    = runtime.GetResource(MoSync.Constants.RT_IMAGE, _res);
                WriteableBitmap src    = (WriteableBitmap)res.GetInternalObject();
                byte[]          pixels = src.ToByteArray();
                mGL.glTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, src.PixelWidth, src.PixelHeight, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, pixels, 0);
                return(MoSync.Constants.MA_GL_TEX_IMAGE_2D_OK);
            };

            ioctls.glViewport = delegate(int _x, int _y, int _w, int _h)
            {
                mGL.glViewport(_x, _y, _w, _h);
                return(0);
            };

            ioctls.glGetError = delegate()
            {
                int err = mGL.glGetError();
                if (err != GL.GL_NO_ERROR)
                {
                    //int a = 2;
                    //err = GL.GL_NO_ERROR;
                }
                return(err);
            };

            ioctls.glGetStringHandle = delegate(int _name)
            {
                String str   = mGL.glGetString(_name);
                char[] data  = str.ToCharArray();
                byte[] bytes = new byte[data.Length + 1];
                bytes[data.Length] = 0;
                for (int i = 0; i < data.Length; i++)
                {
                    bytes[i] = (byte)data[i];
                }

                return(runtime.AddResource(new Resource(new System.IO.MemoryStream(bytes), MoSync.Constants.RT_BINARY, true)));
            };

            ioctls.glMatrixMode = delegate(int mode)
            {
                mGL.glMatrixMode(mode);  return(0);
            };

            ioctls.glPushMatrix = delegate()
            {
                mGL.glPushMatrix(); return(0);
            };

            ioctls.glPopMatrix = delegate()
            {
                mGL.glPopMatrix(); return(0);
            };

            ioctls.glLoadIdentity = delegate()
            {
                mGL.glLoadIdentity(); return(0);
            };

            ioctls.glBlendFunc = delegate(int sfactor, int dfactor)
            {
                mGL.glBlendFunc(sfactor, dfactor); return(0);
            };

            ioctls.glAlphaFunc = delegate(int func, float _ref)
            {
                return(0);
            };

            ioctls.glAlphaFuncx = delegate(int func, int _ref)
            {
                return(0);
            };

            ioctls.glDepthFunc = delegate(int _func)
            {
                mGL.glDepthFunc(_func); return(0);
            };

            ioctls.glDepthMask = delegate(int _flag)
            {
                mGL.glDepthMask(_flag); return(0);
            };

            ioctls.glClearColor = delegate(float r, float g, float b, float a)
            {
                mGL.glClearColor(r, g, b, a); return(0);
            };

            ioctls.glClearColorx = delegate(int r, int g, int b, int a)
            {
                mGL.glClearColorx(r, g, b, a); return(0);
            };

            ioctls.glColor4f = delegate(float r, float g, float b, float a)
            {
                mGL.glColor4f(r, g, b, a); return(0);
            };

            ioctls.glColor4x = delegate(int r, int g, int b, int a)
            {
                mGL.glColor4x(r, g, b, a); return(0);
            };

            ioctls.glColor4ub = delegate(int r, int g, int b, int a)
            {
                mGL.glColor4ub(r, g, b, a); return(0);
            };

            ioctls.glColor4f = delegate(float r, float g, float b, float a)
            {
                mGL.glColor4f(r, g, b, a); return(0);
            };

            ioctls.glClear = delegate(int _mask)
            {
                mGL.glClear(_mask); return(0);
            };

            ioctls.glRotatef = delegate(float angle, float x, float y, float z)
            {
                mGL.glRotatef(angle, x, y, z); return(0);
            };

            ioctls.glRotatex = delegate(int angle, int x, int y, int z)
            {
                mGL.glRotatex(angle, x, y, z); return(0);
            };

            ioctls.glTranslatef = delegate(float x, float y, float z)
            {
                mGL.glTranslatef(x, y, z); return(0);
            };

            ioctls.glTranslatex = delegate(int x, int y, int z)
            {
                mGL.glTranslatex(x, y, z); return(0);
            };

            ioctls.glScalef = delegate(float x, float y, float z)
            {
                mGL.glScalef(x, y, z); return(0);
            };

            ioctls.glScalex = delegate(int x, int y, int z)
            {
                mGL.glScalex(x, y, z); return(0);
            };

            ioctls.glMultMatrixf = delegate(int _matrix)
            {
#if !LIB
                mGL.glMultMatrixf(core.GetDataMemory().GetData(), _matrix);
                return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);;
#endif
            };

            ioctls.glMultMatrixx = delegate(int _matrix)
            {
#if !LIB
                mGL.glMultMatrixx(core.GetDataMemory().GetData(), _matrix);
                return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);;
#endif
            };

            ioctls.glEnableClientState = delegate(int _array)
            {
                mGL.glEnableClientState(_array); return(0);
            };

            ioctls.glDisableClientState = delegate(int _array)
            {
                mGL.glDisableClientState(_array); return(0);
            };

            ioctls.glTexCoordPointer = delegate(int _size, int _type, int _stride, int _pointer)
            {
#if !LIB
                mGL.glTexCoordPointer(_size, _type, _stride, core.GetDataMemory().GetData(), _pointer);
                return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);;
#endif
            };

            ioctls.glVertexPointer = delegate(int _size, int _type, int _stride, int _pointer)
            {
#if !LIB
                mGL.glVertexPointer(_size, _type, _stride, core.GetDataMemory().GetData(), _pointer);
                return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);;
#endif
            };

            ioctls.glColorPointer = delegate(int _size, int _type, int _stride, int _pointer)
            {
#if !LIB
                mGL.glColorPointer(_size, _type, _stride, core.GetDataMemory().GetData(), _pointer);
                return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);;
#endif
            };

            ioctls.glNormalPointer = delegate(int _type, int _stride, int _pointer)
            {
#if !LIB
                mGL.glNormalPointer(_type, _stride, core.GetDataMemory().GetData(), _pointer);
                return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);;
#endif
            };

            ioctls.glDrawArrays = delegate(int _mode, int _first, int _count)
            {
                mGL.glDrawArrays(_mode, _first, _count);
                return(0);
            };

            ioctls.glDrawElements = delegate(int _mode, int _count, int _type, int _indecies)
            {
#if !LIB
                mGL.glDrawElements(_mode, _count, _type, core.GetDataMemory().GetData(), _indecies);
                return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);;
#endif
            };

            ioctls.glEnable = delegate(int _e)
            {
                mGL.glEnable(_e);
                return(0);
            };

            ioctls.glDisable = delegate(int _e)
            {
                mGL.glDisable(_e);
                return(0);
            };

            ioctls.glFrustumf = delegate(float _left, float _right, float _bottom, float _top, float _znear, float _zfar)
            {
                mGL.glFrustumf(_left, _right, _bottom, _top, _znear, _zfar);
                return(0);
            };

            ioctls.glOrthof = delegate(float _left, float _right, float _bottom, float _top, float _znear, float _zfar)
            {
                mGL.glOrthof(_left, _right, _bottom, _top, _znear, _zfar);
                return(0);
            };

            ioctls.glFrustumx = delegate(int _left, int _right, int _bottom, int _top, int _znear, int _zfar)
            {
                mGL.glFrustumx(_left, _right, _bottom, _top, _znear, _zfar);
                return(0);
            };

            ioctls.glOrthox = delegate(int _left, int _right, int _bottom, int _top, int _znear, int _zfar)
            {
                mGL.glOrthox(_left, _right, _bottom, _top, _znear, _zfar);
                return(0);
            };

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

            ioctls.glFinish = delegate()
            {
                mGL.glFinish();
                return(0);
            };

            ioctls.glGenTextures = delegate(int _n, int _textures)
            {
                int[] handles = new int[_n];
                mGL.glGenTextures(_n, handles);
                for (int i = 0; i < _n; i++)
                {
                    core.GetDataMemory().WriteInt32(_textures + i * 4, handles[i]);
                }
                return(0);
            };

            ioctls.glBindTexture = delegate(int _target, int _texture)
            {
                mGL.glBindTexture(_target, _texture);
                return(0);
            };

            ioctls.glTexImage2D = delegate(int _target, int _level, int _internalformat, int _width, int _height, int _border, int _format, int _type, int _pixels)
            {
#if !LIB
                if (_pixels == 0)
                {
                    mGL.glTexImage2D(_target, _level, _internalformat, _width, _height, _border, _format, _type, null, _pixels);
                }
                else
                {
                    mGL.glTexImage2D(_target, _level, _internalformat, _width, _height, _border, _format, _type, core.GetDataMemory().GetData(), _pixels);
                }
                return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);;
#endif
            };

            ioctls.glDeleteTextures = delegate(int _n, int _textures)
            {
                int[] textures = new int[_n];
                for (int i = 0; i < _n; i++)
                {
                    textures[i] = core.GetDataMemory().ReadInt32(_textures + i * 4);
                }
                mGL.glDeleteTextures(textures);
                return(0);
            };

            ioctls.glTexSubImage2D = delegate(int _target, int _level, int _xofs, int _yofs, int _width, int _height, int _format, int _type, int _pixels)
            {
#if !LIB
                mGL.glTexSubImage2D(_target, _level, _xofs, _yofs, _width, _height, _format, _type, core.GetDataMemory().GetData(), _pixels);
                return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);;
#endif
            };

            ioctls.glCompressedTexImage2D = delegate(int _target, int _level, int _internalformat, int _width, int _height, int _border, int _imageSize, int _data)
            {
                return(0);
            };

            ioctls.glCompressedTexSubImage2D = delegate(int _target, int _level, int _xofs, int _yofs, int _width, int _height, int _format, int _imageSize, int _data)
            {
                return(0);
            };

            ioctls.glGenBuffers = delegate(int _n, int _buffers)
            {
                int[] handles = new int[_n];
                mGL.glGenBuffers(_n, handles);
                for (int i = 0; i < _n; i++)
                {
                    core.GetDataMemory().WriteInt32(_buffers + i * 4, handles[i]);
                }
                return(0);
            };

            ioctls.glBindBuffer = delegate(int _target, int _buffer)
            {
                mGL.glBindBuffer(_target, _buffer);
                return(0);
            };

            ioctls.glBufferData = delegate(int _target, int _size, int _data, int _usage)
            {
#if !LIB
                mGL.glBufferData(_target, _size, core.GetDataMemory().GetData(), _data, _usage);
                return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);;
#endif
            };

            ioctls.glBufferSubData = delegate(int _target, int _offset, int _size, int _data)
            {
#if !LIB
                mGL.glBufferSubData(_target, _offset, _size, core.GetDataMemory().GetData(), _data);
                return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);
#endif
            };

            ioctls.glMaterialf = delegate(int face, int pname, float value)
            {
                mGL.glMaterialf(face, pname, value); return(0);
            };

            ioctls.glMaterialx = delegate(int face, int pname, int value)
            {
                mGL.glMaterialx(face, pname, value); return(0);
            };

            ioctls.glMaterialfv = delegate(int face, int pname, int data)
            {
#if !LIB
                mGL.glMaterialfv(face, pname, core.GetDataMemory().GetData(), data); return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);;
#endif
            };

            ioctls.glMaterialxv = delegate(int face, int pname, int data)
            {
#if !LIB
                mGL.glMaterialxv(face, pname, core.GetDataMemory().GetData(), data); return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);;
#endif
            };

            ioctls.glLightf = delegate(int _light, int _pname, float _param)
            {
                mGL.glLightf(_light, _pname, _param); return(0);
            };

            ioctls.glLightx = delegate(int _light, int _pname, int _param)
            {
                mGL.glLightx(_light, _pname, _param); return(0);
            };

            ioctls.glLightfv = delegate(int _light, int _pname, int _pointer)
            {
#if !LIB
                mGL.glLightfv(_light, _pname, core.GetDataMemory().GetData(), _pointer); return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);;
#endif
            };

            ioctls.glLightxv = delegate(int _light, int _pname, int _pointer)
            {
#if !LIB
                mGL.glLightxv(_light, _pname, core.GetDataMemory().GetData(), _pointer); return(0);
#else
                return(MoSync.Constants.IOCTL_UNAVAILABLE);;
#endif
            };

            ioctls.glShadeModel = delegate(int _mode)
            {
                mGL.glShadeModel(_mode); return(0);
            };
        }
Exemple #51
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)
                {
                    widget.RemoveFromParent();
                    mWidgets[_widget] = null;

                    mWidgetTypeDictionary.Remove(_widget);
                    Thread widgetCreationThread = null;
                    mWidgetThreadDictionary.TryGetValue(_widget, out widgetCreationThread);
                    if (widgetCreationThread != null)
                    {
                        if (widgetCreationThread.IsAlive)
                        {
                            widgetCreationThread.Abort();
                        }
                        mWidgetThreadDictionary.Remove(_widget);
                    }
                }
                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);
                }
            };
        }
Exemple #52
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            /**
             * @brief Creates a new banner.
             * @param bannerSize One of the MA_ADS_SIZE_ constants. Only for Android and WP7.1 platforms.
             * @param publisherID Only for Android and WP 7.1 platforms.
             * This param is ignored on iOS platform.
             *
             * @note A banner is a widget type object.
             * For more info see Widget API.
             *
             * @returns
             *  - #MA_ADS_RES_UNSUPPORTED if ads are not supported on current system.
             *  - #MA_ADS_RES_ERROR if a error occurred while creating the banner widget.
             *  - a handle to a new banner widget(the handle value is >= 0).
             */
            ioctls.maAdsBannerCreate = delegate(int _bannerSize, int _publisherID)
            {
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    mAd = new NativeUI.Ad();

                    // If the banner size is a known windows phone 7 size, we set it.
                    // The default value is 480*80 (XX-Large banner).
                    switch (_bannerSize)
                    {
                    case MoSync.Constants.MA_ADS_SIZE_WP7_XLARGE:
                        mAd.Width  = 300;
                        mAd.Height = 50;
                        break;

                    case MoSync.Constants.MA_ADS_SIZE_WP7_XXLARGE:
                        mAd.Width  = 480;
                        mAd.Height = 80;
                        break;

                    default:
                        mAd.Width  = 480;
                        mAd.Height = 80;
                        break;
                    }

                    // the publisherID for windows phone contains two components separated by '|'.
                    // The first one represents the application ID and the second one the ad unit ID.
                    // The publisher ID structure(ex): f532778c-7db5-4a8b-a292-a45a684ed890
                    // The ad unit ID structure(ex): 81103
                    String publisherID = core.GetDataMemory().ReadStringAtAddress(_publisherID);
                    string[] values    = publisherID.Split('|');
                    // only if both values are present we set the properties
                    if (2 == values.Length)
                    {
                        mAd.ApplicationID = values[0];
                        mAd.AdUnitID      = values[1];
                    }
                }
                                                      );

                int handle = runtime.GetModule <NativeUIModule>().AddWidget(mAd);
                // if the handles is smaller than 0, the widget was not added to the layout
                if (handle < 0)
                {
                    return(MoSync.Constants.MA_ADS_RES_ERROR);
                }
                mAd.SetHandle(handle);
                mAd.SetRuntime(runtime);

                return(handle);
            };

            /**
             * @brief Destroy a banner.
             *
             * @param bannerHandle Handle to a banner.
             *
             * @returns One of the next constants:
             * - #MA_ADS_RES_OK if no error occurred.
             * - #MA_ADS_RES_INVALID_BANNER_HANDLE if the banner handle is invalid.
             */
            ioctls.maAdsBannerDestroy = delegate(int _bannerHandler)
            {
                if (!isHandleValid(runtime, _bannerHandler))
                {
                    return(MoSync.Constants.MA_ADS_RES_INVALID_BANNER_HANDLE);
                }

                mAd = null;

                return(MoSync.Constants.MA_ADS_RES_OK);
            };

            /**
             * @brief Add a banner to a layout widget.
             *
             * @param bannerHandle Handle to a banner.
             * @param layoutHandle Handle to a layout.
             *
             * @returns One of the next constants:
             * - #MA_ADS_RES_OK if no error occurred.
             * - #MA_ADS_RES_INVALID_BANNER_HANDLE if the banner handle is invalid.
             * - #MA_ADS_RES_INVALID_LAYOUT_HANDLE if the layout handle is invalid.
             */
            ioctls.maAdsAddBannerToLayout = delegate(int _bannerHandle, int _layoutHandle)
            {
                // we first check if both the banner and the layout are widgets with a valid handle
                if (!isHandleValid(runtime, _bannerHandle))
                {
                    return(MoSync.Constants.MA_ADS_RES_INVALID_BANNER_HANDLE);
                }
                if (!isHandleValid(runtime, _layoutHandle))
                {
                    return(MoSync.Constants.MA_ADS_RES_INVALID_LAYOUT_HANDLE);
                }

                // add the banner to the parent widget
                runtime.GetModule <NativeUIModule>().GetWidget(_layoutHandle).AddChild(
                    runtime.GetModule <NativeUIModule>().GetWidget(_bannerHandle));
                // set the parent of the banner to be the layout on which is added
                mAd.SetParent(runtime.GetModule <NativeUIModule>().GetWidget(_layoutHandle));

                return(MoSync.Constants.MA_ADS_RES_OK);
            };

            /**
             * @brief Remove a banner from a layout widget.
             *
             * @param bannerHandle Handle to a banner.
             * @param layoutHandle Handle to a layout.
             *
             * @returns One of the next constants:
             * - #MA_ADS_RES_OK if no error occurred.
             * - #MA_ADS_RES_INVALID_BANNER_HANDLE if the banner handle is invalid.
             * - #MA_ADS_RES_INVALID_LAYOUT_HANDLE if the layout handle is invalid.
             */
            ioctls.maAdsRemoveBannerFromLayout = delegate(int _bannerHandle, int _layoutHandle)
            {
                // we first check if both the banner and the layout are widgets with a valid handle
                if (!isHandleValid(runtime, _bannerHandle))
                {
                    return(MoSync.Constants.MA_ADS_RES_INVALID_BANNER_HANDLE);
                }
                if (!isHandleValid(runtime, _layoutHandle))
                {
                    return(MoSync.Constants.MA_ADS_RES_INVALID_LAYOUT_HANDLE);
                }

                runtime.GetModule <NativeUIModule>().GetWidget(_layoutHandle).RemoveChild(
                    runtime.GetModule <NativeUIModule>().GetWidget(_bannerHandle));

                return(MoSync.Constants.MA_ADS_RES_OK);
            };

            /**
             * @brief Set a banner property.
             *
             * @param bannerHandle Handle to the banner.
             * @param property A string representing which property to set.
             * @param value The value that will be assigned to the property.
             *
             * @returns One of the next result codes:
             * - #MA_ADS_RES_OK if no error occurred.
             * - #MA_ADS_RES_INVALID_BANNER_HANDLE if the banner handle is invalid.
             * - #MA_ADS_RES_INVALID_PROPERTY_NAME if the property name is not valid.
             * - #MA_ADS_RES_INVALID_PROPERTY_VALUE if the property value is not valid.
             */
            ioctls.maAdsBannerSetProperty = delegate(int _bannerHandle, int _property, int _value)
            {
                // check if the banner is a widget with a valid handle
                MoSync.NativeUI.Ad ad = (MoSync.NativeUI.Ad)runtime.GetModule <NativeUIModule>().GetWidget(_bannerHandle);
                if (!isHandleValid(runtime, _bannerHandle))
                {
                    return(MoSync.Constants.MA_ADS_RES_INVALID_BANNER_HANDLE);
                }

                String property = core.GetDataMemory().ReadStringAtAddress(_property);
                // based on the string 'property' we set the ones that can be set on WP 7.1
                // if a property is not available, we return MA_ADS_RES_INVALID_PROPERTY_NAME
                string value    = "";
                int    intValue = -1;
                switch (property)
                {
                case MoSync.Constants.MA_ADS_HEIGHT:
                    value    = core.GetDataMemory().ReadStringAtAddress(_value);
                    intValue = -1;
                    int.TryParse(value, out intValue);
                    if (intValue >= 0)
                    {
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                        {
                            mAd.Height = intValue;
                        }
                                                              );
                    }
                    else
                    {
                        return(MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_VALUE);
                    }
                    break;

                case MoSync.Constants.MA_ADS_WIDTH:
                    value    = core.GetDataMemory().ReadStringAtAddress(_value);
                    intValue = -1;
                    int.TryParse(value, out intValue);
                    if (intValue >= 0)
                    {
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                        {
                            mAd.Width = intValue;
                        }
                                                              );
                    }
                    else
                    {
                        return(MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_VALUE);
                    }
                    break;

                case MoSync.Constants.MA_ADS_VISIBLE:
                    value = core.GetDataMemory().ReadStringAtAddress(_value).ToLower();
                    if (value.Equals("true"))
                    {
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                        {
                            mAd.Visible = "true";
                        }
                                                              );
                    }
                    else if (value.Equals("false"))
                    {
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                        {
                            mAd.Visible = "false";
                        }
                                                              );
                    }
                    else
                    {
                        return(MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_VALUE);
                    }
                    break;

                case MoSync.Constants.MA_ADS_ENABLED:
                    value = core.GetDataMemory().ReadStringAtAddress(_value).ToLower();
                    if (value.Equals("true"))
                    {
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                        {
                            mAd.Enabled = "true";
                        }
                                                              );
                    }
                    else if (value.Equals("false"))
                    {
                        MoSync.Util.RunActionOnMainThreadSync(() =>
                        {
                            mAd.Enabled = "false";
                        }
                                                              );
                    }
                    else
                    {
                        return(MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_VALUE);
                    }
                    break;

                case MoSync.Constants.MA_ADS_COLOR_BG:
                    value = core.GetDataMemory().ReadStringAtAddress(_value);
                    if (!IsHexColor(value))
                    {
                        return(MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_VALUE);
                    }
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        mAd.BackgroundColor = value;
                    }
                                                          );
                    break;

                case MoSync.Constants.MA_ADS_COLOR_BORDER:
                    value = core.GetDataMemory().ReadStringAtAddress(_value);
                    if (!IsHexColor(value))
                    {
                        return(MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_VALUE);
                    }
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        mAd.BorderColor = value;
                    }
                                                          );
                    break;

                case MoSync.Constants.MA_ADS_COLOR_TEXT:
                    value = core.GetDataMemory().ReadStringAtAddress(_value);
                    if (!IsHexColor(value))
                    {
                        return(MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_VALUE);
                    }
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        mAd.TextColor = value;
                    }
                                                          );
                    break;

                default:
                    return(MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_NAME);
                }

                return(MoSync.Constants.MA_ADS_RES_OK);
            };

            /**
             * @brief Retrieves a specified property from the given banner.
             *
             * @param bannerHandle Handle to the banner.
             * @param property A string representing for which property to get the value.
             * @param value A buffer that will hold the value of the property, represented as a string.
             * @param bufSize Size of the buffer.
             *
             * @returns One of the next result codes:
             * - #MA_ADS_RES_OK if no error occurred.
             * - #MA_ADS_RES_INVALID_BANNER_HANDLE if the banner handle is invalid.
             * - #MA_ADS_RES_INVALID_PROPERTY_NAME if the property name is not valid.
             * - #MA_ADS_RES_INVALID_STRING_BUFFER_SIZE if the buffer size was to small.
             */
            ioctls.maAdsBannerGetProperty = delegate(int _bannerHandle, int _property, int _value, int _bufSize)
            {
                MoSync.NativeUI.Ad ad = (MoSync.NativeUI.Ad)runtime.GetModule <NativeUIModule>().GetWidget(_bannerHandle);
                if (!isHandleValid(runtime, _bannerHandle))
                {
                    return(MoSync.Constants.MA_ADS_RES_INVALID_BANNER_HANDLE);
                }

                String property    = core.GetDataMemory().ReadStringAtAddress(_property);
                string stringvalue = "";
                switch (property)
                {
                case MoSync.Constants.MA_ADS_HEIGHT:
                    stringvalue = "";
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        stringvalue = ((int)mAd.Height).ToString();
                    }
                                                          );
                    core.GetDataMemory().WriteStringAtAddress(
                        _value,
                        stringvalue,
                        _bufSize);
                    break;

                case MoSync.Constants.MA_ADS_WIDTH:
                    stringvalue = "";
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        stringvalue = ((int)mAd.Width).ToString();
                    }
                                                          );
                    core.GetDataMemory().WriteStringAtAddress(
                        _value,
                        stringvalue,
                        _bufSize);
                    break;

                case MoSync.Constants.MA_ADS_VISIBLE:
                    stringvalue = "";
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        stringvalue = mAd.Visible;
                    }
                                                          );
                    core.GetDataMemory().WriteStringAtAddress(
                        _value,
                        stringvalue,
                        _bufSize);
                    break;

                case MoSync.Constants.MA_ADS_ENABLED:
                    stringvalue = "";
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        stringvalue = mAd.Enabled;
                    }
                                                          );
                    core.GetDataMemory().WriteStringAtAddress(
                        _value,
                        stringvalue,
                        _bufSize);
                    break;

                case MoSync.Constants.MA_ADS_COLOR_BG:
                    stringvalue = "";
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        stringvalue = mAd.BackgroundColor.ToString();
                    }
                                                          );
                    core.GetDataMemory().WriteStringAtAddress(
                        _value,
                        stringvalue,
                        _bufSize);
                    break;

                case MoSync.Constants.MA_ADS_COLOR_BORDER:
                    stringvalue = "";
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        stringvalue = mAd.BorderColor.ToString();
                    }
                                                          );
                    core.GetDataMemory().WriteStringAtAddress(
                        _value,
                        stringvalue,
                        _bufSize);
                    break;

                case MoSync.Constants.MA_ADS_COLOR_TEXT:
                    stringvalue = "";
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        stringvalue = mAd.TextColor.ToString();
                    }
                                                          );
                    core.GetDataMemory().WriteStringAtAddress(
                        _value,
                        stringvalue,
                        _bufSize);
                    break;

                default:
                    return(MoSync.Constants.MA_ADS_RES_INVALID_PROPERTY_NAME);
                }

                return(MoSync.Constants.MA_ADS_RES_OK);
            };
        }
        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;
            };
        }
        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;
            };
        }
        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;
            };
        }
Exemple #56
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;
            };
        }
Exemple #57
0
 public void Init(Ioctls ioctls, Core core, Runtime runtime)
 {
 }
Exemple #58
0
        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);
            };
        }
Exemple #59
0
        /**
         * Initializing the ioctls.
         */
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            mCamera = new PhotoCamera(mCameraType);
            mVideoBrush = new VideoBrush();

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

            PhoneApplicationPage currentPage = (((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage);

            // set the initial camera orientation in respect to the current page orientation
            SetInitialCameraOrientation(currentPage);
            // handle current page orientation and adjust the camera orientation accordingly
            HandleDeviceOrientation(currentPage);

            /**
             * Stores an output format in fmm parameter.
             * @param _index int the index of the required format.
             * @param _fmt int the momory address at which to write the output format dimensions.
             *
             * Note: the _index should be greater than 0 and smaller than the number of camera formats.
             */
            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;
            };

            /**
            * Returns the number of different output formats supported by the current device's camera.
            * \< 0 if there is no camera support.
            * 0 if there is camera support, but the format is unknown.
            */
            ioctls.maCameraFormatNumber = delegate()
            {
                // if the camera is not initialized, we cannot access any of its properties
                if (!isCameraInitialized)
                {
                    // because the cammera is supported but not initialized, we return 0
                    return 0;
                }

                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++;
                    resolutions.MoveNext();
                    if (resolutions.Current == new System.Windows.Size(0, 0))
                        break;
                }
                return number;
            };

            /**
             * Starts the viewfinder and the camera
             */
            ioctls.maCameraStart = delegate()
            {
                InitCamera();

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    mCameraPrev.StartViewFinder();
                });

                return 0;
            };

            /**
             * stops the view finder and the camera.
             */
            ioctls.maCameraStop = delegate()
            {
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    mCameraPrev.StopViewFinder();
                });

                return 0;
            };

            /**
             * Adds a previewWidget to the camera controller in devices that support native UI.
             */
            ioctls.maCameraSetPreview = delegate(int _widgetHandle)
            {
                // if the camera is not initialized, we need to initialize it before
                // setting the preview
                if (!isCameraInitialized)
                {
                    InitCamera();
                }

                IWidget w = runtime.GetModule<NativeUIModule>().GetWidget(_widgetHandle);
                if (w.GetType() != typeof(MoSync.NativeUI.CameraPreview))
                {
                    return MoSync.Constants.MA_CAMERA_RES_FAILED;
                }
                mCameraPrev = (NativeUI.CameraPreview)w;
                mCameraPrev.SetViewFinderContent(mVideoBrush);

                return MoSync.Constants.MA_CAMERA_RES_OK;
            };

            /**
             * Returns the number of available Camera on the device.
             */
            ioctls.maCameraNumber = delegate()
            {
                if (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) && PhotoCamera.IsCameraTypeSupported(CameraType.Primary))
                    return 2;
                else if (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) || PhotoCamera.IsCameraTypeSupported(CameraType.Primary))
                    return 1;
                return 0;
            };

            /**
             * Captures an image and stores it as a new data object in the
             * supplied placeholder.
             * @param _formatIndex int the required format.
             * @param _placeHolder int the placeholder used for storing the image.
             */
            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 = null;
                        try
                        {
                            // as the camera always takes a snapshot in landscape left orientation,
                            // we need to rotate the resulting image 90 degrees for a current PortraitUp orientation
                            // and 180 degrees for a current LandscapeRight orientation
                            int rotateAngle = 0;
                            if (currentPage.Orientation == PageOrientation.PortraitUp)
                            {
                                rotateAngle = 90;

                            }
                            else if (currentPage.Orientation == PageOrientation.LandscapeRight)
                            {
                                rotateAngle = 180;
                            }
                            // if the current page is in a LandscapeLeft orientation, the orientation angle will be 0
                            data = RotateImage(args.ImageStream, rotateAngle);
                        }
                        catch
                        {
                            // the orientation angle was not a multiple of 90 - we keep the original image
                            data = args.ImageStream;
                        }
                        MemoryStream dataMem = new MemoryStream((int)data.Length);
                        MoSync.Util.CopySeekableStreams(data, 0, dataMem, 0, (int)data.Length);
                        res.SetInternalObject(dataMem);
                    });
                    are.Set();
                };

                mCamera.CaptureImageAvailable += mCameraSnapshotDelegate;

                mCamera.CaptureImage();

                are.WaitOne();
                return MoSync.Constants.MA_CAMERA_RES_OK;
            };

            /**
             * Captures an image and stores it as a new data object in new
             * placeholder that is sent via #EVENT_TYPE_CAMERA_SNAPSHOT event.
             * @param _formatIndex int the required format index (size index).
             */
            ioctls.maCameraSnapshotAsync = delegate(int _formatIndex)
            {
                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(() =>
                    {
                        Stream data = null;
                        try
                        {
                            // as the camera always takes a snapshot in landscape left orientation,
                            // we need to rotate the resulting image 90 degrees for a current PortraitUp orientation
                            // and 180 degrees for a current LandscapeRight orientation
                            int rotateAngle = 0;

                            if (currentPage.Orientation == PageOrientation.PortraitUp)
                            {
                                rotateAngle = 90;
                            }
                            else if (currentPage.Orientation == PageOrientation.LandscapeRight)
                            {
                                rotateAngle = 180;
                            }
                            // if the current page is in a LandscapeLeft orientation, the orientation angle will be 0
                            data = RotateImage(args.ImageStream, rotateAngle);
                        }
                        catch
                        {
                            // the orientation angle was not a multiple of 90 - we keep the original image
                            data = args.ImageStream;
                        }

                        MemoryStream dataMem = new MemoryStream((int)data.Length);
                        MoSync.Util.CopySeekableStreams(data, 0, dataMem, 0, (int)data.Length);

                        Memory eventData = new Memory(20);

                        const int MAEventData_eventType = 0;
                        const int MAEventData_snapshotImageDataHandle = 4;
                        const int MAEventData_snapshotFormatIndex = 8;
                        const int MAEventData_snapshotImageDataRepresentation = 12;
                        const int MAEventData_snapshotReturnCode = 16;

                        eventData.WriteInt32(MAEventData_eventType, MoSync.Constants.EVENT_TYPE_CAMERA_SNAPSHOT);

                        // Create new place holder.
                        eventData.WriteInt32(MAEventData_snapshotImageDataHandle, runtime.AddResource(
                            new Resource(dataMem, MoSync.Constants.RT_BINARY, true)));
                        eventData.WriteInt32(MAEventData_snapshotFormatIndex, _formatIndex);
                        eventData.WriteInt32(MAEventData_snapshotImageDataRepresentation, MoSync.Constants.MA_IMAGE_REPRESENTATION_RAW);
                        eventData.WriteInt32(MAEventData_snapshotReturnCode, MoSync.Constants.MA_CAMERA_RES_OK);

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

                mCamera.CaptureImageAvailable += mCameraSnapshotDelegate;
                mCamera.CaptureImage();
                return MoSync.Constants.MA_CAMERA_RES_OK;
            };

            /**
             * Sets the property represented by the string situated at the
             * _property address with the value situated at the _value address.
             * @param _property int the property name address
             * @param _value int the value address
             *
             * Note: the fallowing properties are not available on windows phone
             *      MA_CAMERA_FOCUS_MODE, MA_CAMERA_IMAGE_FORMAT, MA_CAMERA_ZOOM,
             *      MA_CAMERA_MAX_ZOOM.
             */
            ioctls.maCameraSetProperty = delegate(int _property, int _value)
            {
                // if the camera is not initialized, we cannot access any of its properties
                if (!isCameraInitialized)
                {
                    return MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED;
                }

                String property = core.GetDataMemory().ReadStringAtAddress(_property);
                String value = core.GetDataMemory().ReadStringAtAddress(_value);

                if (property.Equals(MoSync.Constants.MA_CAMERA_FLASH_MODE))
                {
                    if (value.Equals(MoSync.Constants.MA_CAMERA_FLASH_ON))
                    {
                        mCamera.FlashMode = FlashMode.On;
                        mFlashMode = FlashMode.On;
                    }
                    else if (value.Equals(MoSync.Constants.MA_CAMERA_FLASH_OFF))
                    {
                        mCamera.FlashMode = FlashMode.Off;
                        mFlashMode = FlashMode.Off;
                    }
                    else if (value.Equals(MoSync.Constants.MA_CAMERA_FLASH_AUTO))
                    {
                        mCamera.FlashMode = FlashMode.Auto;
                        mFlashMode = FlashMode.Auto;
                    }
                    else return MoSync.Constants.MA_CAMERA_RES_INVALID_PROPERTY_VALUE;

                    return MoSync.Constants.MA_CAMERA_RES_OK;
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_FOCUS_MODE))
                {
                    return MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED;
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_IMAGE_FORMAT))
                {
                    return MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED;
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_ZOOM))
                {
                    return MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED;
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_MAX_ZOOM))
                {
                    return MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED;
                }
                else return MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED;
            };

            /**
             * Selects a camera from the avalable ones;
             * in this eigther the back or the front camera is
             * chosen
             */
            ioctls.maCameraSelect = delegate(int _camera)
            {
                // if the camera is not initialized, we cannot access any of its properties
                if (!isCameraInitialized)
                {
                    return MoSync.Constants.MA_CAMERA_RES_FAILED;
                }

                if ( MoSync.Constants.MA_CAMERA_CONST_BACK_CAMERA == _camera)
                {
                    if (mCamera.CameraType != CameraType.Primary)
                    {
                        mCameraType = CameraType.Primary;
                        InitCamera();
                    }
                }
                else if (MoSync.Constants.MA_CAMERA_CONST_FRONT_CAMERA == _camera)
                {
                    if (mCamera.CameraType != CameraType.FrontFacing)
                    {
                        mCameraType = CameraType.FrontFacing;
                        InitCamera();

                        MoSync.Util.RunActionOnMainThreadSync(() =>
                            {
                                SetInitialCameraOrientation(currentPage);
                            }
                        );
                    }
                }
                else return MoSync.Constants.MA_CAMERA_RES_FAILED;

                return MoSync.Constants.MA_CAMERA_RES_OK;
            };

            /**
             * Retrieves the specified property value in the given buffer.
             * @param _property int the address for the property string
             * @param _value int the address for the property value string (the buffer)
             * @param _bufSize int the buffer size
             */
            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);
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_ZOOM_SUPPORTED))
                {
                    core.GetDataMemory().WriteStringAtAddress(
                        _value,
                        "false",
                        _bufSize);
                }
                else if (property.Equals(MoSync.Constants.MA_CAMERA_FLASH_SUPPORTED))
                {
                    core.GetDataMemory().WriteStringAtAddress(
                        _value,
                        "true",
                        _bufSize);
                }
                else return MoSync.Constants.MA_CAMERA_RES_PROPERTY_NOTSUPPORTED;
                return 0;
            };

            ioctls.maCameraRecord = delegate(int _stopStartFlag)
            {
                return MoSync.Constants.MA_CAMERA_RES_FAILED;
            };
        }