Exemplo n.º 1
0
        private void SendSensorEventVector(Runtime runtime, int type, Vector3 data)
        {
            Memory evt = new Memory(5 * 4);

            evt.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_SENSOR);
            evt.WriteInt32(MoSync.Struct.MAEvent.sensor.type, type);
            evt.WriteInt32(MoSync.Struct.MAEvent.sensor.values + 0, MoSync.Util.ConvertToInt(data.X));
            evt.WriteInt32(MoSync.Struct.MAEvent.sensor.values + 4, MoSync.Util.ConvertToInt(data.Y));
            evt.WriteInt32(MoSync.Struct.MAEvent.sensor.values + 8, MoSync.Util.ConvertToInt(data.Z));
            runtime.PostEvent(new Event(evt));
        }
Exemplo n.º 2
0
        /**
         * Posts the event to the mosync runtime.
         * @param index: the button clicked index
         */
        private void postApplicationBarMenuEvent(int index)
        {
            Memory eventData = new Memory(16);
            // set the main event type: EVENT_TYPE_OPTIONS_BOX_BUTTON_CLICKED
            const int MAWidgetEventData_widgetEventType = 0;
            const int MAWidgetEventData_buttonIndex     = 4;

            eventData.WriteInt32(MAWidgetEventData_widgetEventType, MoSync.Constants.EVENT_TYPE_OPTIONS_BOX_BUTTON_CLICKED);
            eventData.WriteInt32(MAWidgetEventData_buttonIndex, index);
            mRuntime.PostEvent(new Event(eventData));
        }
Exemplo n.º 3
0
        private void PostMediaEvent(int mediaType, int mediaHandle, int returnCode)
        {
            const int MAEventData_eventType           = 0;
            const int MAEventData_mediaType           = 4;
            const int MAEventData_mediaHandle         = 8;
            const int MAEventData_operationResultCode = 12;

            Memory eventData = new Memory(16);

            eventData.WriteInt32(MAEventData_eventType, MoSync.Constants.EVENT_TYPE_MEDIA_EXPORT_FINISHED);
            eventData.WriteInt32(MAEventData_mediaType, mediaType);
            eventData.WriteInt32(MAEventData_mediaHandle, mediaHandle);
            eventData.WriteInt32(MAEventData_operationResultCode, returnCode);
            mRuntime.PostEvent(new Event(eventData));
        }
Exemplo n.º 4
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);
            };
        }
Exemplo n.º 5
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            runtime.RegisterCleaner(delegate()
            {
                foreach (KeyValuePair <int, Connection> p in mConnections)
                {
                    p.Value.close();
                }
                mConnections.Clear();
            });

            mResultHandler = delegate(int handle, int connOp, int result)
            {
                Memory evt = new Memory(4 * 4);
                evt.WriteInt32(MoSync.Struct.MAEvent.type, MoSync.Constants.EVENT_TYPE_CONN);
                evt.WriteInt32(MoSync.Struct.MAEvent.conn.handle, handle);
                evt.WriteInt32(MoSync.Struct.MAEvent.conn.opType, connOp);
                evt.WriteInt32(MoSync.Struct.MAEvent.conn.result, result);
                runtime.PostEvent(new Event(evt));
            };

            syscalls.maConnect = delegate(int _url)
            {
                String url = core.GetDataMemory().ReadStringAtAddress(_url);
                //Util.Log("maConnect(" + url + ")\n");
                if (url.StartsWith("btspp"))
                {
                    return(MoSync.Constants.CONNERR_UNAVAILABLE);
                }
                Uri        uri = new Uri(url);
                Connection c;
                if (uri.Scheme.Equals("socket"))
                {
                    c = new SocketConnection(uri, mNextConnHandle);
                }
                else if (uri.Scheme.Equals("http") || uri.Scheme.Equals("https"))
                {
                    c = new WebRequestConnection(uri, mNextConnHandle, MoSync.Constants.HTTP_GET);
                }
                else
                {
                    return(MoSync.Constants.CONNERR_GENERIC);
                }

                c.connect(mResultHandler);
                mConnections.Add(mNextConnHandle, c);
                return(mNextConnHandle++);
            };

            syscalls.maConnClose = delegate(int _conn)
            {
                Connection c = mConnections[_conn];
                c.close();
                mConnections.Remove(_conn);
            };

            syscalls.maConnGetAddr = delegate(int _conn, int _addr)
            {
                if (_conn == MoSync.Constants.HANDLE_LOCAL)                 // unavailable
                {
                    return(-1);
                }
                Connection c = mConnections[_conn];
                return(c.getAddr(core.GetDataMemory(), _addr));
            };

            syscalls.maConnRead = delegate(int _conn, int _dst, int _size)
            {
                Connection c = mConnections[_conn];
                c.recv(core.GetDataMemory().GetData(), _dst, _size, mResultHandler);
            };

            DataDelegate dataDelegate = delegate(int _conn, int _data,
                                                 CommDelegate cd)
            {
                Connection c   = mConnections[_conn];
                Resource   res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Stream     s   = (Stream)res.GetInternalObject();
                runtime.SetResourceRaw(_data, Resource.Flux);
                MemoryStream mem = null;
                if (s.GetType() == typeof(MemoryStream))
                {
                    mem = (MemoryStream)s;
                }
                else
                {
                    MoSync.Util.CriticalError("Only binaries (non-ubins) are allowed for maConn(Read/Write)(To/From)Data");
                }

                cd(c, mem.GetBuffer(),
                   delegate(int handle, int connOp, int result)
                {
                    runtime.SetResourceRaw(_data, res);
                    mResultHandler(handle, connOp, result);
                });
            };

            syscalls.maConnReadToData = delegate(int _conn, int _data, int _offset, int _size)
            {
                dataDelegate(_conn, _data,
                             delegate(Connection c, byte[] buf, ResultHandler rh)
                {
                    c.recv(buf, _offset, _size, rh);
                });
            };

            syscalls.maConnWrite = delegate(int _conn, int _src, int _size)
            {
                Connection c = mConnections[_conn];
                c.write(core.GetDataMemory().GetData(), _src, _size, mResultHandler);
            };

            syscalls.maConnWriteFromData = delegate(int _conn, int _data, int _offset, int _size)
            {
                dataDelegate(_conn, _data,
                             delegate(Connection c, byte[] buf, ResultHandler rh)
                {
                    c.write(buf, _offset, _size, rh);
                });
            };

            syscalls.maHttpCreate = delegate(int _url, int _method)
            {
                String url = core.GetDataMemory().ReadStringAtAddress(_url);
                //Util.Log("maHttpCreate(" + url + ")\n");
                Uri uri = new Uri(url);
                WebRequestConnection c = new WebRequestConnection(uri, mNextConnHandle, _method);
                mConnections.Add(mNextConnHandle, c);
                return(mNextConnHandle++);
            };

            syscalls.maHttpFinish = delegate(int _conn)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                c.connect(delegate(int handle, int connOp, int result)
                {
                    mResultHandler(handle, MoSync.Constants.CONNOP_FINISH, result);
                });
            };

            syscalls.maHttpSetRequestHeader = delegate(int _conn, int _key, int _value)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                String key             = core.GetDataMemory().ReadStringAtAddress(_key);
                String value           = core.GetDataMemory().ReadStringAtAddress(_value);
                if (value.Length > 0)
                {
                    c.setRequestHeader(key, value);
                }
            };

            syscalls.maHttpGetResponseHeader = delegate(int _conn, int _key, int _buffer, int _bufSize)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                String key             = core.GetDataMemory().ReadStringAtAddress(_key);
                String value           = c.getResponseHeader(key);
                if (value == null)
                {
                    return(MoSync.Constants.CONNERR_NOHEADER);
                }
                if (value.Length + 1 <= _bufSize)
                {
                    core.GetDataMemory().WriteStringAtAddress(_buffer, value, _bufSize);
                }
                return(value.Length);
            };
        }
Exemplo n.º 6
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);
                }
            };
        }
Exemplo n.º 7
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);
            };
        }
Exemplo n.º 8
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);
            };
        }