Esempio n. 1
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);
            };
        }
        } // end of Init

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

            address += sizeof(int);
            for (int i = 0; i < numberOfTitles; i++)
            {
                String applicationMenuButtonTitle = _core.GetDataMemory().ReadWStringAtAddress(address);
                // the encoding is UTF16 so the address of the next string is after all the characters and a null
                address += applicationMenuButtonTitle.Length * sizeof(char) + sizeof(char);

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

                mApplicationBarMenuItems.Add(applicationBarMenuItem);
            }
        }
        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
Esempio n. 4
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);
            };
        }
Esempio n. 5
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);
            };
        }
Esempio n. 6
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            InitExtensions(core, runtime);

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

                IExtensionModule extension = GetModule(module);
                if (extension == null)
                    return MoSync.Constants.IOCTL_UNAVAILABLE;
                else
                    return extension.Invoke(index, a, b, c);
            };
        }
Esempio n. 7
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            InitExtensions(core, runtime);

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

                IExtensionModule extension = GetModule(module);
                if (extension == null)
                {
                    return(MoSync.Constants.IOCTL_UNAVAILABLE);
                }
                else
                {
                    return(extension.Invoke(index, a, b, c));
                }
            };
        }
Esempio n. 8
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            InitExtensions(core, runtime);

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

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

                    return handle;
                }

                return handle;
            };

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

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

                return handle;
            };
        }
Esempio n. 9
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            InitExtensions(core, runtime);

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

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

                    return(handle);
                }

                return(handle);
            };

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

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

                return(handle);
            };
        }
Esempio n. 10
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            SystemPropertyManager.mSystemPropertyProviders.Clear();

            // maybe use some pretty reflection mechanism to find all syscall implementations here..
            syscalls.maCheckInterfaceVersion = delegate(int hash)
            {
                if (MoSync.Constants.MoSyncHash != (uint)hash)
                {
                    MoSync.Util.CriticalError("Invalid hash!");
                }
                return(hash);
            };

            syscalls.maPanic = delegate(int code, int str)
            {
                String message = core.GetDataMemory().ReadStringAtAddress(str);
                MoSync.Util.CriticalError(message + "\ncode: " + code);
            };

            syscalls.maExit = delegate(int res)
            {
                MoSync.Util.Exit(res);
            };

            DateTime startDate = System.DateTime.Now;

            syscalls.maGetMilliSecondCount = delegate()
            {
                System.TimeSpan offset = (System.DateTime.Now - startDate);

                return(offset.Milliseconds + (offset.Seconds + (offset.Minutes + (offset.Hours + offset.Days * 24) * 60) * 60) * 1000);
            };

            syscalls.maTime = delegate()
            {
                return((int)Util.ToUnixTimeUtc(System.DateTime.Now));
            };

            syscalls.maLocalTime = delegate()
            {
                return((int)Util.ToUnixTime(System.DateTime.Now));
            };

            syscalls.maCreatePlaceholder = delegate()
            {
                return(runtime.AddResource(new Resource(null, MoSync.Constants.RT_PLACEHOLDER)));
            };

            syscalls.maFindLabel = delegate(int _name)
            {
                String name = core.GetDataMemory().ReadStringAtAddress(_name);
                int    res;
                if (runtime.mLabels.TryGetValue(name, out res))
                {
                    return(res);
                }
                else
                {
                    return(-1);
                }
            };

            syscalls.maResetBacklight = delegate()
            {
            };

            syscalls.maSoundPlay = delegate(int _sound_res, int _offset, int _size)
            {
                // not implemented, but I don't wanna throw exceptions.
                return(-1);
            };

            syscalls.maLoadProgram = delegate(int _data, int _reload)
            {
#if REBUILD
                throw new Exception("maLoadProgram not available in rebuild mode");
#else
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Memory   mem = (Memory)res.GetInternalObject();
                MoSync.Machine.SetLoadProgram(mem.GetStream(), _reload != 0);
                throw new Util.ExitException(0);
#endif
            };
        }
Esempio n. 11
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;
            };
        }
Esempio n. 12
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;
            };
        }
Esempio n. 13
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;
            };
        }
Esempio n. 14
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual;
            double screenWidth = System.Windows.Application.Current.Host.Content.ActualWidth;
            double screenHeight = System.Windows.Application.Current.Host.Content.ActualHeight;
            if ((int)screenHeight == 0)
                throw new Exception("screenHeight");
            PhoneApplicationPage mainPage = (PhoneApplicationPage)frame.Content;
            Image mainImage = new Image();
            mainPage.Width = screenWidth;
            mainPage.Height = screenHeight;
            mainImage.Width = screenWidth;
            mainImage.Height = screenHeight;
            mainPage.Content = mainImage;

            // no apparent effect on memory leaks.
            runtime.RegisterCleaner(delegate()
            {
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    mainPage.Content = null;
                });
            });

            mBackBuffer = new WriteableBitmap(
                (int)screenWidth,
                (int)screenHeight);
            mFrontBuffer = new WriteableBitmap(
                (int)screenWidth,
                (int)screenHeight);

            mainImage.Source = mFrontBuffer;
            mCurrentDrawTarget = mBackBuffer;

            mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff,
                        (byte)(mCurrentColor >> 16),
                        (byte)(mCurrentColor >> 8),
                        (byte)(mCurrentColor));

            syscalls.maSetColor = delegate(int rgb)
            {
                int oldColor = (int)mCurrentColor;
                mCurrentColor = 0xff000000 | (uint)(rgb & 0xffffff);
                mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff,
                        (byte)(mCurrentColor >> 16),
                        (byte)(mCurrentColor >> 8),
                        (byte)(mCurrentColor));
                return oldColor & 0xffffff;
            };

            syscalls.maSetClipRect = delegate(int x, int y, int w, int h)
            {
            };

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

            syscalls.maPlot = delegate(int x, int y)
            {
                mCurrentDrawTarget.SetPixel(x, y, (int)mCurrentColor);
            };

            syscalls.maUpdateScreen = delegate()
            {
                System.Array.Copy(mBackBuffer.Pixels, mFrontBuffer.Pixels, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight);
                InvalidateWriteableBitmapOnMainThread(mFrontBuffer);
            };

            syscalls.maFillRect = delegate(int x, int y, int w, int h)
            {
                mCurrentDrawTarget.FillRectangle(x, y, x + w, y + h, (int)mCurrentColor);
            };

            syscalls.maLine = delegate(int x1, int y1, int x2, int y2)
            {
                mCurrentDrawTarget.DrawLine(x1, y1, x2, y2, (int)mCurrentColor);
            };

            TextBlock textBlock = new TextBlock();
            textBlock.FontSize = mCurrentFontSize;

            syscalls.maDrawText = delegate(int left, int top, int str)
            {
                String text = core.GetDataMemory().ReadStringAtAddress(str);
                if (text.Length == 0) return;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    textBlock.Text = text;
                    textBlock.Foreground = new SolidColorBrush(mCurrentWindowsColor);
                    WriteableBitmap b = new WriteableBitmap(textBlock, null);
                    mCurrentDrawTarget.Blit(new Rect(left, top, b.PixelWidth, b.PixelHeight),
                        b,
                        new Rect(0, 0, b.PixelWidth, b.PixelHeight));
                });
            };

            syscalls.maGetTextSize = delegate(int str)
            {
                String text = core.GetDataMemory().ReadStringAtAddress(str);
                int textWidth = 0;
                int textHeight = 0;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    textBlock.Text = text;
                    textWidth = (int)textBlock.ActualWidth;
                    textHeight = (int)textBlock.ActualHeight;
                });

                return MoSync.Util.CreateExtent(textWidth, textHeight);
            };

            syscalls.maDrawTextW = delegate(int left, int top, int str)
            {
                String text = core.GetDataMemory().ReadWStringAtAddress(str);
                if (text.Length == 0) return;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    textBlock.Text = text;
                    textBlock.Foreground = new SolidColorBrush(mCurrentWindowsColor);
                    WriteableBitmap b = new WriteableBitmap(textBlock, null);
                    Rect dstRect = new Rect(left, top, b.PixelWidth, b.PixelHeight);
                    Rect srcRect = new Rect(0, 0, b.PixelWidth, b.PixelHeight);
                    // cliprect..
                    Rect clipRect = new Rect(0, 0, mBackBuffer.PixelWidth, mBackBuffer.PixelHeight);
                    clipRect.Intersect(dstRect);
                    if (clipRect.IsEmpty == true)
                    {
                        return;
                    }

                    mCurrentDrawTarget.Blit(dstRect,
                        b,
                        srcRect);
                });
            };

            syscalls.maGetTextSizeW = delegate(int str)
            {
                String text = core.GetDataMemory().ReadWStringAtAddress(str);
                int textWidth = 0;
                int textHeight = 0;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    textBlock.Text = text;
                    textWidth = (int)textBlock.ActualWidth;
                    textHeight = (int)textBlock.ActualHeight;
                });

                return MoSync.Util.CreateExtent(textWidth, textHeight);
            };

            syscalls.maFillTriangleFan = delegate(int points, int count)
            {
                int[] newPoints = new int[count * 2 + 2];
                for (int i = 0; i < count; i++)
                {
                    newPoints[i * 2 + 0] = core.GetDataMemory().ReadInt32(points + i * 8);
                    newPoints[i * 2 + 1] = core.GetDataMemory().ReadInt32(points + i * 8 + 4);
                }
                newPoints[count * 2 + 0] = core.GetDataMemory().ReadInt32(points + 0);
                newPoints[count * 2 + 1] = core.GetDataMemory().ReadInt32(points + 4);
                mCurrentDrawTarget.FillPolygon(newPoints, (int)mCurrentColor);
            };

            syscalls.maFillTriangleStrip = delegate(int points, int count)
            {

                int[] xcoords = new int[count];
                int[] ycoords = new int[count];

                for (int i = 0; i < count; i++)
                {
                    xcoords[i] = core.GetDataMemory().ReadInt32(points + i * 8);
                    ycoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + 4);
                }

                for (int i = 2; i < count; i++)
                {
                    mCurrentDrawTarget.FillTriangle(
                        xcoords[i - 2], ycoords[i - 2],
                        xcoords[i - 1], ycoords[i - 1],
                        xcoords[i - 0], ycoords[i - 0],
                        (int)mCurrentColor);
                }
            };

            syscalls.maSetDrawTarget = delegate(int drawTarget)
            {
                int oldDrawTarget = mCurrentDrawTargetIndex;
                if (drawTarget == mCurrentDrawTargetIndex) return oldDrawTarget;
                if (drawTarget == MoSync.Constants.HANDLE_SCREEN)
                {
                    mCurrentDrawTarget = mBackBuffer;
                    mCurrentDrawTargetIndex = drawTarget;
                    return oldDrawTarget;
                }

                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, drawTarget);
                mCurrentDrawTarget = (WriteableBitmap)res.GetInternalObject();
                mCurrentDrawTargetIndex = drawTarget;
                return oldDrawTarget;
            };

            syscalls.maGetScrSize = delegate()
            {
                return MoSync.Util.CreateExtent(mBackBuffer.PixelWidth, mBackBuffer.PixelHeight);
            };

            syscalls.maGetImageSize = delegate(int handle)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, handle);
                BitmapSource src = (BitmapSource)res.GetInternalObject();
                int w = 0, h = 0;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    w = src.PixelWidth;
                    h = src.PixelHeight;
                });

                return MoSync.Util.CreateExtent(w, h);
            };

            syscalls.maDrawImage = delegate(int image, int left, int top)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();
                Rect srcRect = new Rect(0, 0, src.PixelWidth, src.PixelHeight);
                Rect dstRect = new Rect(left, top, src.PixelWidth, src.PixelHeight);
                mCurrentDrawTarget.Blit(dstRect, src, srcRect, WriteableBitmapExtensions.BlendMode.Alpha);
            };

            syscalls.maDrawImageRegion = delegate(int image, int srcRectPtr, int dstPointPtr, int transformMode)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();

                Memory dataMemory = core.GetDataMemory();
                int srcRectX = dataMemory.ReadInt32(srcRectPtr + 0);
                int srcRectY = dataMemory.ReadInt32(srcRectPtr + 4);
                int srcRectW = dataMemory.ReadInt32(srcRectPtr + 8);
                int srcRectH = dataMemory.ReadInt32(srcRectPtr + 12);
                int dstPointX = dataMemory.ReadInt32(dstPointPtr + 0);
                int dstPointY = dataMemory.ReadInt32(dstPointPtr + 4);

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

                DrawImageRegion(mCurrentDrawTarget, dstPointX, dstPointY, srcRect, src, transformMode);
            };

            syscalls.maCreateDrawableImage = delegate(int placeholder, int width, int height)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, placeholder);
                res.SetResourceType(MoSync.Constants.RT_IMAGE);
                WriteableBitmap bitmap = null;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    bitmap = new WriteableBitmap(width, height);
                });

                if (bitmap == null) return MoSync.Constants.RES_OUT_OF_MEMORY;
                res.SetInternalObject(bitmap);
                return MoSync.Constants.RES_OK;
            };

            syscalls.maCreateImageRaw = delegate(int _placeholder, int _src, int _size, int _alpha)
            {
                int width = MoSync.Util.ExtentX(_size);
                int height = MoSync.Util.ExtentY(_size);

                WriteableBitmap bitmap = null;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        bitmap = new WriteableBitmap(width, height);
                    });

                //core.GetDataMemory().ReadIntegers(bitmap.Pixels, _src, width * height);
                bitmap.FromByteArray(core.GetDataMemory().GetData(), _src, width * height * 4);
                if (_alpha == 0)
                {
                    int[] pixels = bitmap.Pixels;
                    int numPixels = width * height;
                    for (int i = 0; i < numPixels; i++)
                    {
                        pixels[i] = (int)((uint)pixels[i] | 0xff000000);
                    }
                }

                runtime.SetResource(_placeholder,
                    new Resource(
                        bitmap,
                        MoSync.Constants.RT_IMAGE
                        )
                    );
                return MoSync.Constants.RES_OK;
            };

            syscalls.maDrawRGB = delegate(int _dstPoint, int _src, int _srcRect, int _scanlength)
            {
                Memory dataMemory = core.GetDataMemory();
                int dstX = dataMemory.ReadInt32(_dstPoint + 0);
                int dstY = dataMemory.ReadInt32(_dstPoint + 4);
                int srcRectX = dataMemory.ReadInt32(_srcRect + 0);
                int srcRectY = dataMemory.ReadInt32(_srcRect + 4);
                int srcRectW = dataMemory.ReadInt32(_srcRect + 8);
                int srcRectH = dataMemory.ReadInt32(_srcRect + 12);
                int[] pixels = mCurrentDrawTarget.Pixels;
                // todo: clipRect

                _scanlength *= 4; // sizeof(int)

                for (int h = 0; h < srcRectH; h++)
                {
                    int pixelIndex = dstY * mCurrentDrawTarget.PixelWidth + dstX;
                    int address = _src + (srcRectY + h) * _scanlength;
                    for (int w = 0; w < srcRectW; w++)
                    {
                        uint srcPixel = dataMemory.ReadUInt32(address);
                        uint dstPixel = (uint)pixels[pixelIndex];

                        uint srcPixelR = (srcPixel & 0x00ff0000) >> 16;
                        uint srcPixelG = (srcPixel & 0x0000ff00) >> 8;
                        uint srcPixelB = (srcPixel & 0x000000ff) >> 0;
                        uint srcPixelA = (srcPixel & 0xff000000) >> 24;
                        uint dstPixelR = (dstPixel & 0x00ff0000) >> 16;
                        uint dstPixelG = (dstPixel & 0x0000ff00) >> 8;
                        uint dstPixelB = (dstPixel & 0x000000ff) >> 0;
                        uint dstPixelA = (dstPixel & 0xff000000) >> 24;

                        dstPixelR += ((srcPixelR - dstPixelR) * srcPixelA) / 255;
                        dstPixelG += ((srcPixelG - dstPixelG) * srcPixelA) / 255;
                        dstPixelB += ((srcPixelB - dstPixelB) * srcPixelA) / 255;

                        dstPixel = (dstPixelA << 24) | (dstPixelR << 16) | (dstPixelG << 8) | (dstPixelB);
                        pixels[pixelIndex] = (int)dstPixel;

                        address += 4;
                        pixelIndex++;
                    }

                    dstY++;
                }
            };

            syscalls.maGetImageData = delegate(int _image, int _dst, int _srcRect, int _scanlength)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, _image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();
                Memory dataMemory = core.GetDataMemory();
                int srcRectX = dataMemory.ReadInt32(_srcRect + 0);
                int srcRectY = dataMemory.ReadInt32(_srcRect + 4);
                int srcRectW = dataMemory.ReadInt32(_srcRect + 8);
                int srcRectH = dataMemory.ReadInt32(_srcRect + 12);
                int lineDst = _dst;
                byte[] data = src.ToByteArray(srcRectY * src.PixelWidth,
                    srcRectH * src.PixelWidth);
                byte[] coreArray = dataMemory.GetData();
                for (int y = 0; y < srcRectH; y++)
                {
                    System.Array.Copy(data, y * src.PixelWidth * 4, coreArray,
                        lineDst, src.PixelWidth * 4);
                    lineDst += _scanlength * 4;
                }
            };

            syscalls.maCreateImageFromData = delegate(int _placeholder, int _data, int _offset, int _size)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Memory mem = (Memory)res.GetInternalObject();

                Stream s = mem.GetStream(_offset, _size);
                WriteableBitmap bitmap = MoSync.Util.CreateWriteableBitmapFromStream(s);
                s.Close();
                runtime.SetResource(
                    _placeholder,
                    new Resource(
                        bitmap,
                        MoSync.Constants.RT_IMAGE
                        )
                );

                return MoSync.Constants.RES_OK;
            };
        }
Esempio n. 15
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual;
            double screenWidth          = System.Windows.Application.Current.Host.Content.ActualWidth;
            double screenHeight         = System.Windows.Application.Current.Host.Content.ActualHeight;

            if ((int)screenHeight == 0)
            {
                throw new Exception("screenHeight");
            }
            PhoneApplicationPage mainPage = (PhoneApplicationPage)frame.Content;
            Image mainImage = new Image();

            mainPage.Width   = screenWidth;
            mainPage.Height  = screenHeight;
            mainImage.Width  = screenWidth;
            mainImage.Height = screenHeight;
            mainPage.Content = mainImage;

            mClipRect.X      = 0.0;
            mClipRect.Y      = 0.0;
            mClipRect.Width  = screenWidth;
            mClipRect.Height = screenHeight;

            // no apparent effect on memory leaks.
            runtime.RegisterCleaner(delegate()
            {
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    mainPage.Content = null;
                });
            });

            mBackBuffer = new WriteableBitmap(
                (int)screenWidth,
                (int)screenHeight);
            mFrontBuffer = new WriteableBitmap(
                (int)screenWidth,
                (int)screenHeight);

            mainImage.Source   = mFrontBuffer;
            mCurrentDrawTarget = mBackBuffer;

            mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff,
                                                                       (byte)(mCurrentColor >> 16),
                                                                       (byte)(mCurrentColor >> 8),
                                                                       (byte)(mCurrentColor));

            syscalls.maSetColor = delegate(int rgb)
            {
                int oldColor = (int)mCurrentColor;
                mCurrentColor        = 0xff000000 | (uint)(rgb & 0xffffff);
                mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff,
                                                                           (byte)(mCurrentColor >> 16),
                                                                           (byte)(mCurrentColor >> 8),
                                                                           (byte)(mCurrentColor));
                return(oldColor & 0xffffff);
            };

            syscalls.maSetClipRect = delegate(int x, int y, int w, int h)
            {
                mClipRect.X      = x;
                mClipRect.Y      = y;
                mClipRect.Width  = w;
                mClipRect.Height = h;
            };

            syscalls.maGetClipRect = delegate(int cliprect)
            {
                Memory mem = core.GetDataMemory();
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.left, (int)mClipRect.X);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.top, (int)mClipRect.Y);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.width, (int)mClipRect.Width);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.height, (int)mClipRect.Height);
            };

            syscalls.maPlot = delegate(int x, int y)
            {
                mCurrentDrawTarget.SetPixel(x, y, (int)mCurrentColor);
            };

            syscalls.maUpdateScreen = delegate()
            {
                System.Array.Copy(mBackBuffer.Pixels, mFrontBuffer.Pixels, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight);
                InvalidateWriteableBitmapOnMainThread(mFrontBuffer);
            };

            syscalls.maFillRect = delegate(int x, int y, int w, int h)
            {
                mCurrentDrawTarget.FillRectangle(x, y, x + w, y + h, (int)mCurrentColor);
            };

            syscalls.maLine = delegate(int x1, int y1, int x2, int y2)
            {
                GraphicsUtil.Point p1 = new GraphicsUtil.Point(x1, y1);
                GraphicsUtil.Point p2 = new GraphicsUtil.Point(x2, y2);
                if (!GraphicsUtil.ClipLine(p1, p2, (int)mClipRect.X, (int)(mClipRect.X + mClipRect.Width),
                                           (int)mClipRect.Y, (int)(mClipRect.Y + mClipRect.Height)))
                {
                    return;
                }

                mCurrentDrawTarget.DrawLine((int)p1.x, (int)p1.y, (int)p2.x, (int)p2.y, (int)mCurrentColor);
            };

            TextBlock textBlock = new TextBlock();

            textBlock.FontSize = mCurrentFontSize;

            syscalls.maDrawText = delegate(int left, int top, int str)
            {
                String text = core.GetDataMemory().ReadStringAtAddress(str);
                if (text.Length == 0)
                {
                    return;
                }

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    textBlock.Text       = text;
                    textBlock.Foreground = new SolidColorBrush(mCurrentWindowsColor);
                    WriteableBitmap b    = new WriteableBitmap(textBlock, null);
                    mCurrentDrawTarget.Blit(new Rect(left, top, b.PixelWidth, b.PixelHeight),
                                            b,
                                            new Rect(0, 0, b.PixelWidth, b.PixelHeight));
                });
            };

            syscalls.maGetTextSize = delegate(int str)
            {
                String text       = core.GetDataMemory().ReadStringAtAddress(str);
                int    textWidth  = 0;
                int    textHeight = 0;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    textBlock.Text = text;
                    textWidth      = (int)textBlock.ActualWidth;
                    textHeight     = (int)textBlock.ActualHeight;
                });

                return(MoSync.Util.CreateExtent(textWidth, textHeight));
            };

            syscalls.maDrawTextW = delegate(int left, int top, int str)
            {
                String text = core.GetDataMemory().ReadWStringAtAddress(str);
                if (text.Length == 0)
                {
                    return;
                }

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    textBlock.Text       = text;
                    textBlock.Foreground = new SolidColorBrush(mCurrentWindowsColor);
                    WriteableBitmap b    = new WriteableBitmap(textBlock, null);
                    Rect dstRect         = new Rect(left, top, b.PixelWidth, b.PixelHeight);
                    Rect srcRect         = new Rect(0, 0, b.PixelWidth, b.PixelHeight);
                    // cliprect..
                    Rect clipRect = new Rect(0, 0, mBackBuffer.PixelWidth, mBackBuffer.PixelHeight);
                    clipRect.Intersect(dstRect);
                    if (clipRect.IsEmpty == true)
                    {
                        return;
                    }

                    mCurrentDrawTarget.Blit(dstRect,
                                            b,
                                            srcRect);
                });
            };

            syscalls.maGetTextSizeW = delegate(int str)
            {
                String text       = core.GetDataMemory().ReadWStringAtAddress(str);
                int    textWidth  = 0;
                int    textHeight = 0;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    textBlock.Text = text;
                    textWidth      = (int)textBlock.ActualWidth;
                    textHeight     = (int)textBlock.ActualHeight;
                });

                return(MoSync.Util.CreateExtent(textWidth, textHeight));
            };

            syscalls.maFillTriangleFan = delegate(int points, int count)
            {
                int[] newPoints = new int[count * 2 + 2];
                for (int i = 0; i < count; i++)
                {
                    newPoints[i * 2 + 0] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.x);
                    newPoints[i * 2 + 1] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.y);
                }
                newPoints[count * 2 + 0] = core.GetDataMemory().ReadInt32(points + MoSync.Struct.MAPoint2d.x);
                newPoints[count * 2 + 1] = core.GetDataMemory().ReadInt32(points + MoSync.Struct.MAPoint2d.y);
                mCurrentDrawTarget.FillPolygon(newPoints, (int)mCurrentColor);
            };

            syscalls.maFillTriangleStrip = delegate(int points, int count)
            {
                int[] xcoords = new int[count];
                int[] ycoords = new int[count];

                for (int i = 0; i < count; i++)
                {
                    xcoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.x);
                    ycoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.y);
                }

                for (int i = 2; i < count; i++)
                {
                    mCurrentDrawTarget.FillTriangle(
                        xcoords[i - 2], ycoords[i - 2],
                        xcoords[i - 1], ycoords[i - 1],
                        xcoords[i - 0], ycoords[i - 0],
                        (int)mCurrentColor);
                }
            };

            syscalls.maSetDrawTarget = delegate(int drawTarget)
            {
                int oldDrawTarget = mCurrentDrawTargetIndex;
                if (drawTarget == mCurrentDrawTargetIndex)
                {
                    return(oldDrawTarget);
                }
                if (drawTarget == MoSync.Constants.HANDLE_SCREEN)
                {
                    mCurrentDrawTarget      = mBackBuffer;
                    mCurrentDrawTargetIndex = drawTarget;
                    return(oldDrawTarget);
                }

                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, drawTarget);
                mCurrentDrawTarget      = (WriteableBitmap)res.GetInternalObject();
                mCurrentDrawTargetIndex = drawTarget;
                return(oldDrawTarget);
            };

            syscalls.maGetScrSize = delegate()
            {
                return(MoSync.Util.CreateExtent(mBackBuffer.PixelWidth, mBackBuffer.PixelHeight));
            };

            syscalls.maGetImageSize = delegate(int handle)
            {
                Resource     res = runtime.GetResource(MoSync.Constants.RT_IMAGE, handle);
                BitmapSource src = (BitmapSource)res.GetInternalObject();
                int          w = 0, h = 0;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    w = src.PixelWidth;
                    h = src.PixelHeight;
                });

                return(MoSync.Util.CreateExtent(w, h));
            };

            syscalls.maDrawImage = delegate(int image, int left, int top)
            {
                Resource        res     = runtime.GetResource(MoSync.Constants.RT_IMAGE, image);
                WriteableBitmap src     = (WriteableBitmap)res.GetInternalObject();
                Rect            srcRect = new Rect(0, 0, src.PixelWidth, src.PixelHeight);
                Rect            dstRect = new Rect(left, top, src.PixelWidth, src.PixelHeight);
                mCurrentDrawTarget.Blit(dstRect, src, srcRect, WriteableBitmapExtensions.BlendMode.Alpha);
            };

            syscalls.maDrawImageRegion = delegate(int image, int srcRectPtr, int dstPointPtr, int transformMode)
            {
                Resource        res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();

                Memory dataMemory = core.GetDataMemory();
                int    srcRectX   = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.left);
                int    srcRectY   = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.top);
                int    srcRectW   = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.width);
                int    srcRectH   = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.height);
                int    dstPointX  = dataMemory.ReadInt32(dstPointPtr + MoSync.Struct.MAPoint2d.x);
                int    dstPointY  = dataMemory.ReadInt32(dstPointPtr + MoSync.Struct.MAPoint2d.y);

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

                GraphicsUtil.DrawImageRegion(mCurrentDrawTarget, dstPointX, dstPointY, srcRect, src, transformMode);
            };

            syscalls.maCreateDrawableImage = delegate(int placeholder, int width, int height)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, placeholder);
                res.SetResourceType(MoSync.Constants.RT_IMAGE);
                WriteableBitmap bitmap = null;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    bitmap = new WriteableBitmap(width, height);
                });

                if (bitmap == null)
                {
                    return(MoSync.Constants.RES_OUT_OF_MEMORY);
                }
                res.SetInternalObject(bitmap);
                return(MoSync.Constants.RES_OK);
            };

            syscalls.maCreateImageRaw = delegate(int _placeholder, int _src, int _size, int _alpha)
            {
                int width  = MoSync.Util.ExtentX(_size);
                int height = MoSync.Util.ExtentY(_size);

                WriteableBitmap bitmap = null;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    bitmap = new WriteableBitmap(width, height);
                });

                //core.GetDataMemory().ReadIntegers(bitmap.Pixels, _src, width * height);
                bitmap.FromByteArray(core.GetDataMemory().GetData(), _src, width * height * 4);
                if (_alpha == 0)
                {
                    int[] pixels    = bitmap.Pixels;
                    int   numPixels = width * height;
                    for (int i = 0; i < numPixels; i++)
                    {
                        pixels[i] = (int)((uint)pixels[i] | 0xff000000);
                    }
                }

                runtime.SetResource(_placeholder,
                                    new Resource(
                                        bitmap,
                                        MoSync.Constants.RT_IMAGE
                                        )
                                    );
                return(MoSync.Constants.RES_OK);
            };

            syscalls.maDrawRGB = delegate(int _dstPoint, int _src, int _srcRect, int _scanlength)
            {
                Memory dataMemory = core.GetDataMemory();
                int    dstX       = dataMemory.ReadInt32(_dstPoint + MoSync.Struct.MAPoint2d.x);
                int    dstY       = dataMemory.ReadInt32(_dstPoint + MoSync.Struct.MAPoint2d.y);
                int    srcRectX   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.left);
                int    srcRectY   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.top);
                int    srcRectW   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.width);
                int    srcRectH   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.height);
                int[]  pixels     = mCurrentDrawTarget.Pixels;
                // todo: clipRect

                _scanlength *= 4;                 // sizeof(int)

                for (int h = 0; h < srcRectH; h++)
                {
                    int pixelIndex = dstY * mCurrentDrawTarget.PixelWidth + dstX;
                    int address    = _src + (srcRectY + h) * _scanlength;
                    for (int w = 0; w < srcRectW; w++)
                    {
                        uint srcPixel = dataMemory.ReadUInt32(address);
                        uint dstPixel = (uint)pixels[pixelIndex];

                        uint srcPixelR = (srcPixel & 0x00ff0000) >> 16;
                        uint srcPixelG = (srcPixel & 0x0000ff00) >> 8;
                        uint srcPixelB = (srcPixel & 0x000000ff) >> 0;
                        uint srcPixelA = (srcPixel & 0xff000000) >> 24;
                        uint dstPixelR = (dstPixel & 0x00ff0000) >> 16;
                        uint dstPixelG = (dstPixel & 0x0000ff00) >> 8;
                        uint dstPixelB = (dstPixel & 0x000000ff) >> 0;
                        uint dstPixelA = (dstPixel & 0xff000000) >> 24;

                        dstPixelR += ((srcPixelR - dstPixelR) * srcPixelA) / 255;
                        dstPixelG += ((srcPixelG - dstPixelG) * srcPixelA) / 255;
                        dstPixelB += ((srcPixelB - dstPixelB) * srcPixelA) / 255;

                        dstPixel           = (dstPixelA << 24) | (dstPixelR << 16) | (dstPixelG << 8) | (dstPixelB);
                        pixels[pixelIndex] = (int)dstPixel;

                        address += 4;
                        pixelIndex++;
                    }

                    dstY++;
                }
            };

            syscalls.maGetImageData = delegate(int _image, int _dst, int _srcRect, int _scanlength)
            {
                Resource        res        = runtime.GetResource(MoSync.Constants.RT_IMAGE, _image);
                WriteableBitmap src        = (WriteableBitmap)res.GetInternalObject();
                Memory          dataMemory = core.GetDataMemory();
                int             srcRectX   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.left);
                int             srcRectY   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.top);
                int             srcRectW   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.width);
                int             srcRectH   = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.height);
                int             lineDst    = _dst;
                byte[]          data       = src.ToByteArray(srcRectY * src.PixelWidth,
                                                             srcRectH * src.PixelWidth);
                byte[] coreArray = dataMemory.GetData();
                for (int y = 0; y < srcRectH; y++)
                {
                    System.Array.Copy(data, y * src.PixelWidth * 4, coreArray,
                                      lineDst, src.PixelWidth * 4);
                    lineDst += _scanlength * 4;
                }
            };

            syscalls.maCreateImageFromData = delegate(int _placeholder, int _data, int _offset, int _size)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Memory   mem = (Memory)res.GetInternalObject();

                Stream          s      = mem.GetStream(_offset, _size);
                WriteableBitmap bitmap = MoSync.Util.CreateWriteableBitmapFromStream(s);
                s.Close();
                runtime.SetResource(
                    _placeholder,
                    new Resource(
                        bitmap,
                        MoSync.Constants.RT_IMAGE
                        )
                    );

                return(MoSync.Constants.RES_OK);
            };
        }
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            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;
            };
        }
Esempio n. 17
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;
            };
        }
Esempio n. 18
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);
                }
            };
        }
Esempio n. 19
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            syscalls.memset = delegate(int dst, int val, int num)
            {
                core.GetDataMemory().FillRange(dst, (byte)val, num);
                return(dst);
            };

            syscalls.memcpy = delegate(int dst, int src, int num)
            {
                core.GetDataMemory().WriteMemoryAtAddress(dst, core.GetDataMemory(), src, num);
                return(dst);
            };

            syscalls.strcpy = delegate(int dst, int src)
            {
#if !LIB
                byte[] mem     = core.GetDataMemory().GetData();
                int    origDst = dst;
                src--;
                do
                {
                    src++;
                    mem[dst] = mem[src];
                    dst++;
                } while (mem[src] != 0);
                return(origDst);
#else
                string source = core.GetDataMemory().ReadStringAtAddress(src);
                Byte[] bytes  = new Byte[source.Length * sizeof(char)];
                System.Buffer.BlockCopy(source.ToCharArray(), 0, bytes, 0, bytes.Length);

                core.GetDataMemory().WriteBytes(dst, bytes, source.Length * sizeof(char));
                return(dst);
#endif
            };

            syscalls.strcmp = delegate(int str1, int str2)
            {
#if !LIB
                byte[] mem = core.GetDataMemory().GetData();
                while (mem[str1] != 0 && mem[str1] == mem[str2])
                {
                    str1++;
                    str2++;
                }
                return(mem[str1] - mem[str2]);
#else
                string s1 = core.GetDataMemory().ReadStringAtAddress(str1);
                string s2 = core.GetDataMemory().ReadStringAtAddress(str2);

                return(s1.CompareTo(s2));
#endif
            };

            syscalls.maCreateData = delegate(int placeholder, int size)
            {
                MemoryStream mem = null;
                try
                {
                    mem = new MemoryStream(size);
                    mem.SetLength(size);
                }
                catch (OutOfMemoryException e)
                {
                    MoSync.Util.Log(e);
                    return(MoSync.Constants.RES_OUT_OF_MEMORY);
                }

                Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, placeholder);
                res.SetInternalObject(mem);
                res.SetResourceType(MoSync.Constants.RT_BINARY);
                return(MoSync.Constants.RES_OK);
            };

            syscalls.maWriteData = delegate(int data, int src, int offset, int size)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data);
                Stream   mem = (Stream)res.GetInternalObject();
                mem.Seek(offset, SeekOrigin.Begin);
#if !LIB
                mem.Write(core.GetDataMemory().GetData(), src, size);
#else
                byte[] bytes = new byte[size];
                core.GetDataMemory().ReadBytes(bytes, src, size);
                mem.Write(bytes, 0, size);                 //TO BE TESTED
#endif
            };

            syscalls.maReadData = delegate(int data, int dst, int offset, int size)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data);
                Stream   mem = (Stream)res.GetInternalObject();
                mem.Seek(offset, SeekOrigin.Begin);
#if !LIB
                mem.Read(core.GetDataMemory().GetData(), dst, size);
#else
                byte[] bytes = new byte[size];
                mem.Read(bytes, 0, size);
                core.GetDataMemory().WriteBytes(dst, bytes, size);                 //TO BE TESTED
#endif
            };

            syscalls.maGetDataSize = delegate(int data)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data);
                Stream   mem = (Stream)res.GetInternalObject();
                return((int)mem.Length);
            };

            syscalls.maCopyData = delegate(int _params)
            {
                throw new Exception("maCopyData not implemented");
            };
        }
Esempio n. 20
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);
            };
        }
Esempio n. 21
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;
            };
        }
Esempio n. 22
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            syscalls.memset = delegate(int dst, int val, int num)
            {
                core.GetDataMemory().FillRange(dst, (byte)val, num);
                return dst;
            };

            syscalls.memcpy = delegate(int dst, int src, int num)
            {
                core.GetDataMemory().WriteMemoryAtAddress(dst, core.GetDataMemory(), src, num);
                return dst;
            };

            syscalls.strcpy = delegate(int dst, int src)
            {
                byte[] mem = core.GetDataMemory().GetData();
                int origDst = dst;
                src--;
                do
                {
                    src++;
                    mem[dst] = mem[src];
                    dst++;
                } while (mem[src] != 0);
                return origDst;
            };

            syscalls.strcmp = delegate(int str1, int str2)
            {
                byte[] mem = core.GetDataMemory().GetData();
                while (mem[str1] != 0 && mem[str1] == mem[str2])
                {
                    str1++;
                    str2++;
                }
                return (mem[str1] - mem[str2]);
            };

            syscalls.maCreateData = delegate(int placeholder, int size)
            {
                //Memory mem = null;
                MemoryStream mem = null;
                try
                {
                    //mem = new Memory(size);
                    mem = new MemoryStream(size);
                }
                catch (OutOfMemoryException e)
                {
                    MoSync.Util.Log(e);
                    return MoSync.Constants.RES_OUT_OF_MEMORY;
                }

                Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, placeholder);
                res.SetInternalObject(mem);
                res.SetResourceType(MoSync.Constants.RT_BINARY);
                return MoSync.Constants.RES_OK;
            };

            syscalls.maWriteData = delegate(int data, int src, int offset, int size)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data);
                Stream mem = (Stream)res.GetInternalObject();
                mem.Seek(offset, SeekOrigin.Begin);
                mem.Write(core.GetDataMemory().GetData(), src, size);
                //mem.WriteMemoryAtAddress(offset, core.GetDataMemory(), src, size);
            };

            syscalls.maReadData = delegate(int data, int dst, int offset, int size)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data);
                //Memory mem = (Memory)res.GetInternalObject();
                Stream mem = (Stream)res.GetInternalObject();
                mem.Seek(offset, SeekOrigin.Begin);
                mem.Read(core.GetDataMemory().GetData(), dst, size);
                //core.GetDataMemory().WriteMemoryAtAddress(dst, mem, offset, size);
            };

            syscalls.maGetDataSize = delegate(int data)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data);
                //Memory mem = (Memory)res.GetInternalObject();
                Stream mem = (Stream)res.GetInternalObject();
                //return mem.GetSizeInBytes();
                return (int)mem.Length;
            };

            syscalls.maCopyData = delegate(int _params)
            {
                throw new Exception("maCopyData not implemented");
            };
        }
Esempio n. 23
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
#if false
            mAudioInstanceUpdater = new AudioInstanceUpdater(mAudioInstances);
            Thread thread = new Thread(new ThreadStart(mAudioInstanceUpdater.Loop));
            thread.Start();
#endif
            ioctls.maAudioDataCreateFromURL = delegate(int _mime, int _url, int _flags)
            {
                int ret = MoSync.Constants.MA_AUDIO_ERR_GENERIC;

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

                return(ret);
            };

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

                return(ret);
            };

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

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };

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

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };

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

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

                return(ret);
            };

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

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

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

                return(ret);
            };

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

                return(ret);
            };

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

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };

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

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };

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

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };


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

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };

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

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };

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

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };


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

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

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };


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

                return(ret);
            };

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

                return(ret);
            };

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

                return(MoSync.Constants.MA_AUDIO_ERR_OK);
            };
        }
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            runtime.RegisterCleaner(delegate()
            {
                foreach (KeyValuePair<int, Connection> p in mConnections)
                {
                    p.Value.close();
                }
                mConnections.Clear();
            });

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            syscalls.maHttpGetResponseHeader = delegate(int _conn, int _key, int _buffer, int _bufSize)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                String key = core.GetDataMemory().ReadStringAtAddress(_key);
                String value = c.getResponseHeader(key);
                if (value == null)
                    return MoSync.Constants.CONNERR_NOHEADER;
                if (value.Length + 1 <= _bufSize)
                    core.GetDataMemory().WriteStringAtAddress(_buffer, value, _bufSize);
                return value.Length;
            };
        }
Esempio n. 25
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            syscalls.memset = delegate(int dst, int val, int num)
            {
                core.GetDataMemory().FillRange(dst, (byte)val, num);
                return(dst);
            };

            syscalls.memcpy = delegate(int dst, int src, int num)
            {
                core.GetDataMemory().WriteMemoryAtAddress(dst, core.GetDataMemory(), src, num);
                return(dst);
            };

            syscalls.strcpy = delegate(int dst, int src)
            {
                byte[] mem     = core.GetDataMemory().GetData();
                int    origDst = dst;
                src--;
                do
                {
                    src++;
                    mem[dst] = mem[src];
                    dst++;
                } while (mem[src] != 0);
                return(origDst);
            };

            syscalls.strcmp = delegate(int str1, int str2)
            {
                byte[] mem = core.GetDataMemory().GetData();
                while (mem[str1] != 0 && mem[str1] == mem[str2])
                {
                    str1++;
                    str2++;
                }
                return(mem[str1] - mem[str2]);
            };

            syscalls.maCreateData = delegate(int placeholder, int size)
            {
                MemoryStream mem = null;
                try
                {
                    mem = new MemoryStream(size);
                    mem.SetLength(size);
                }
                catch (OutOfMemoryException e)
                {
                    MoSync.Util.Log(e);
                    return(MoSync.Constants.RES_OUT_OF_MEMORY);
                }

                Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, placeholder);
                res.SetInternalObject(mem);
                res.SetResourceType(MoSync.Constants.RT_BINARY);
                return(MoSync.Constants.RES_OK);
            };

            syscalls.maWriteData = delegate(int data, int src, int offset, int size)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data);
                Stream   mem = (Stream)res.GetInternalObject();
                mem.Seek(offset, SeekOrigin.Begin);
                mem.Write(core.GetDataMemory().GetData(), src, size);
            };

            syscalls.maReadData = delegate(int data, int dst, int offset, int size)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data);
                Stream   mem = (Stream)res.GetInternalObject();
                mem.Seek(offset, SeekOrigin.Begin);
                mem.Read(core.GetDataMemory().GetData(), dst, size);
            };

            syscalls.maGetDataSize = delegate(int data)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, data);
                Stream   mem = (Stream)res.GetInternalObject();
                return((int)mem.Length);
            };

            syscalls.maCopyData = delegate(int _params)
            {
                throw new Exception("maCopyData not implemented");
            };
        }
Esempio n. 26
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            runtime.RegisterCleaner(delegate()
            {
                CleanDictionary(mFileHandles);
                CleanDictionary(mStoreHandles);
                mFileListHandles.Clear();
            });

            // todo: store "stores" in a separate location from the filesystem,
            // to avoid clashes.
            syscalls.maOpenStore = delegate(int _name, int _flags)
            {
                String name = core.GetDataMemory().ReadStringAtAddress(_name);
                name = ConvertPath(name);
                File file = new File(name, FileAccess.ReadWrite);
                if (file.IsDirectory)
                {
                    throw new Exception("Invalid store name");
                }
                if (file.Exists)
                    file.TryOpen();
                else if ((_flags & MoSync.Constants.MAS_CREATE_IF_NECESSARY) != 0)
                {
                    file.Create();
                }
                else
                    return MoSync.Constants.STERR_NONEXISTENT;
                if (file.FileStream == null)
                    return MoSync.Constants.STERR_GENERIC;
                mStoreHandles.Add(mNextStoreHandle, file);
                return mNextStoreHandle++;
            };

            syscalls.maWriteStore = delegate(int _store, int _data)
            {
                File file = mStoreHandles[_store];
                IsolatedStorageFileStream fileStream = file.FileStream;
                fileStream.SetLength(0);
                Resource dataRes = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Stream data = (Stream)dataRes.GetInternalObject();
                data.Seek(0, SeekOrigin.Begin);
                //fileStream.Write(data.GetData(), 0, data.GetData().Length);
                data.CopyTo(fileStream);
                return 1;
            };

            syscalls.maReadStore = delegate(int _store, int _placeholder)
            {
                File file = mStoreHandles[_store];
                IsolatedStorageFileStream fileStream = file.FileStream;
                //Memory mem = new Memory((int)fileStream.Length);
                MemoryStream mem = new MemoryStream((int)fileStream.Length);
                fileStream.Seek(0, SeekOrigin.Begin);
                fileStream.Read(mem.GetBuffer(), 0, (int)fileStream.Length);
                runtime.SetResource(_placeholder, new Resource(mem, MoSync.Constants.RT_BINARY));
                return MoSync.Constants.RES_OK;
            };

            syscalls.maCloseStore = delegate(int _store, int _delete)
            {
                File file = mStoreHandles[_store];
                file.Close();
                if (_delete != 0)
                    file.Delete();
                mStoreHandles.Remove(_store);
            };
        }
Esempio n. 27
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual;
            double screenWidth = System.Windows.Application.Current.Host.Content.ActualWidth;
            double screenHeight = System.Windows.Application.Current.Host.Content.ActualHeight;
            if ((int)screenHeight == 0)
                throw new Exception("screenHeight");
            PhoneApplicationPage mainPage = (PhoneApplicationPage)frame.Content;
            mMainImage = new Image();

            mainPage.Width = screenWidth;
            mainPage.Height = screenHeight;
            mMainImage.Width = screenWidth;
            mMainImage.Height = screenHeight;
            mainPage.Content = mMainImage;

            mClipRect.X = 0.0;
            mClipRect.Y = 0.0;
            mClipRect.Width = screenWidth;
            mClipRect.Height = screenHeight;

            // no apparent effect on memory leaks.
            runtime.RegisterCleaner(delegate()
            {
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    mainPage.Content = null;
                });
            });

            mBackBuffer = new WriteableBitmap(
                (int)screenWidth,
                (int)screenHeight);
            mFrontBuffer = new WriteableBitmap(
                (int)screenWidth,
                (int)screenHeight);

            mMainImage.Source = mFrontBuffer;

            // clear front and backbuffer.
            for (int i = 0; i < mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight; i++)
            {
                mBackBuffer.Pixels[i] = mBackBuffer.Pixels[i] = (int)(0xff<<24);
            }

            mCurrentDrawTarget = mBackBuffer;

            mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff,
                        (byte)(mCurrentColor >> 16),
                        (byte)(mCurrentColor >> 8),
                        (byte)(mCurrentColor));

            syscalls.maSetColor = delegate(int rgb)
            {
                int oldColor = (int)mCurrentColor;
                mCurrentColor = 0xff000000 | (uint)(rgb & 0xffffff);
                mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff,
                        (byte)(mCurrentColor >> 16),
                        (byte)(mCurrentColor >> 8),
                        (byte)(mCurrentColor));
                return oldColor & 0xffffff;
            };

            syscalls.maSetClipRect = delegate(int x, int y, int w, int h)
            {
                MoSync.GraphicsUtil.ClipRectangle(
                    x, y, w, h,
                    0, 0, mCurrentDrawTarget.PixelWidth, mCurrentDrawTarget.PixelHeight,
                    out x, out y, out w, out h);

                mClipRect.X = x;
                mClipRect.Y = y;
                mClipRect.Width = w;
                mClipRect.Height = h;
            };

            syscalls.maGetClipRect = delegate(int cliprect)
            {
                Memory mem = core.GetDataMemory();
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.left, (int)mClipRect.X);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.top, (int)mClipRect.Y);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.width, (int)mClipRect.Width);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.height, (int)mClipRect.Height);
            };

            syscalls.maPlot = delegate(int x, int y)
            {
                mCurrentDrawTarget.SetPixel(x, y, (int)mCurrentColor);
            };

            syscalls.maUpdateScreen = delegate()
            {
                //System.Array.Copy(mBackBuffer.Pixels, mFrontBuffer.Pixels, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight);
                System.Buffer.BlockCopy(mBackBuffer.Pixels, 0, mFrontBuffer.Pixels, 0, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight * 4);
                InvalidateWriteableBitmapOnMainThread(mFrontBuffer);
            };

            syscalls.maFillRect = delegate(int x, int y, int w, int h)
            {
                // this function has a bug (it only fills one pixel less than the image.)
                //mCurrentDrawTarget.FillRectangle(x, y, x + w, y + h, (int)mCurrentColor);

                MoSync.GraphicsUtil.ClipRectangle(
                    x, y, w, h,
                    0, 0, mCurrentDrawTarget.PixelWidth, mCurrentDrawTarget.PixelHeight,
                    out x, out y, out w, out h);

                MoSync.GraphicsUtil.ClipRectangle(
                    x, y, w, h,
                    (int)mClipRect.X, (int)mClipRect.Y, (int)mClipRect.Width, (int)mClipRect.Height,
                    out x, out y, out w, out h);

                if (w <= 0 || h <= 0)
                    return;

                int index = x + y * mCurrentDrawTarget.PixelWidth;
                while(h-- != 0)
                {
                    int width = w;
                    while(width-- != 0)
                    {
                        mCurrentDrawTarget.Pixels[index] = (int)mCurrentColor;
                        index++;
                    }
                    index += -w + mCurrentDrawTarget.PixelWidth;
                }
            };

            syscalls.maLine = delegate(int x1, int y1, int x2, int y2)
            {
                GraphicsUtil.Point p1 = new GraphicsUtil.Point(x1, y1);
                GraphicsUtil.Point p2 = new GraphicsUtil.Point(x2, y2);
                if(!GraphicsUtil.ClipLine(p1, p2, (int)mClipRect.X, (int)(mClipRect.X+mClipRect.Width),
                    (int)mClipRect.Y, (int)(mClipRect.Y+mClipRect.Height)))
                    return;

                mCurrentDrawTarget.DrawLine((int)p1.x, (int)p1.y, (int)p2.x, (int)p2.y, (int)mCurrentColor);
            };

            textBlock.FontSize = mCurrentFontSize;

            syscalls.maDrawText = delegate(int left, int top, int str)
            {
                String text = core.GetDataMemory().ReadStringAtAddress(str);
                if (text.Length == 0) return;
                DrawText(text, left, top);
            };

            syscalls.maGetTextSize = delegate(int str)
            {
                String text = core.GetDataMemory().ReadStringAtAddress(str);
                int textWidth = 0;
                int textHeight = 0;
                GetTextSize(text, out textWidth, out textHeight);
                return MoSync.Util.CreateExtent(textWidth, textHeight);
            };

            syscalls.maDrawTextW = delegate(int left, int top, int str)
            {
                String text = core.GetDataMemory().ReadWStringAtAddress(str);
                if (text.Length == 0) return;

                DrawText(text, left, top);
            };

            syscalls.maGetTextSizeW = delegate(int str)
            {
                String text = core.GetDataMemory().ReadWStringAtAddress(str);
                int textWidth = 0;
                int textHeight = 0;
                GetTextSize(text, out textWidth, out textHeight);
                return MoSync.Util.CreateExtent(textWidth, textHeight);
            };

            syscalls.maFillTriangleFan = delegate(int points, int count)
            {
                int[] newPoints = new int[count * 2 + 2];
                for (int i = 0; i < count; i++)
                {
                    newPoints[i * 2 + 0] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.x);
                    newPoints[i * 2 + 1] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.y);
                }
                newPoints[count * 2 + 0] = core.GetDataMemory().ReadInt32(points + MoSync.Struct.MAPoint2d.x);
                newPoints[count * 2 + 1] = core.GetDataMemory().ReadInt32(points + MoSync.Struct.MAPoint2d.y);
                mCurrentDrawTarget.FillPolygon(newPoints, (int)mCurrentColor);
            };

            syscalls.maFillTriangleStrip = delegate(int points, int count)
            {

                int[] xcoords = new int[count];
                int[] ycoords = new int[count];

                for (int i = 0; i < count; i++)
                {
                    xcoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.x);
                    ycoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.y);
                }

                for (int i = 2; i < count; i++)
                {
                    mCurrentDrawTarget.FillTriangle(
                        xcoords[i - 2], ycoords[i - 2],
                        xcoords[i - 1], ycoords[i - 1],
                        xcoords[i - 0], ycoords[i - 0],
                        (int)mCurrentColor);
                }
            };

            syscalls.maSetDrawTarget = delegate(int drawTarget)
            {
                int oldDrawTarget = mCurrentDrawTargetIndex;
                if (drawTarget == mCurrentDrawTargetIndex) return oldDrawTarget;
                if (drawTarget == MoSync.Constants.HANDLE_SCREEN)
                {
                    mCurrentDrawTarget = mBackBuffer;
                    mCurrentDrawTargetIndex = drawTarget;
                    return oldDrawTarget;
                }

                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, drawTarget);
                mCurrentDrawTarget = (WriteableBitmap)res.GetInternalObject();
                mCurrentDrawTargetIndex = drawTarget;
                return oldDrawTarget;
            };

            syscalls.maGetScrSize = delegate()
            {
                return MoSync.Util.CreateExtent(mBackBuffer.PixelWidth, mBackBuffer.PixelHeight);
            };

            syscalls.maGetImageSize = delegate(int handle)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, handle);
                BitmapSource src = (BitmapSource)res.GetInternalObject();
                if (src == null)
                    MoSync.Util.CriticalError("maGetImageSize used with an invalid image resource.");
                int w = 0, h = 0;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    w = src.PixelWidth;
                    h = src.PixelHeight;
                });

                return MoSync.Util.CreateExtent(w, h);
            };

            syscalls.maDrawImage = delegate(int image, int left, int top)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();
                Rect srcRect = new Rect(0, 0, src.PixelWidth, src.PixelHeight);
                Rect dstRect = new Rect(left, top, src.PixelWidth, src.PixelHeight);
                mCurrentDrawTarget.Blit(dstRect, src, srcRect, WriteableBitmapExtensions.BlendMode.Alpha);
            };

            syscalls.maDrawImageRegion = delegate(int image, int srcRectPtr, int dstPointPtr, int transformMode)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();

                Memory dataMemory = core.GetDataMemory();
                int srcRectX = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.left);
                int srcRectY = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.top);
                int srcRectW = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.width);
                int srcRectH = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.height);
                int dstPointX = dataMemory.ReadInt32(dstPointPtr + MoSync.Struct.MAPoint2d.x);
                int dstPointY = dataMemory.ReadInt32(dstPointPtr + MoSync.Struct.MAPoint2d.y);

                Rect srcRect = new Rect(srcRectX, srcRectY, srcRectW, srcRectH);
                Rect dstRect = new Rect(dstPointX, dstPointY, srcRectW, srcRectH);

                GraphicsUtil.DrawImageRegion(mCurrentDrawTarget, dstPointX, dstPointY, srcRect, src, transformMode, mClipRect);
            };

            syscalls.maCreateDrawableImage = delegate(int placeholder, int width, int height)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, placeholder);
                res.SetResourceType(MoSync.Constants.RT_IMAGE);
                WriteableBitmap bitmap = null;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    bitmap = new WriteableBitmap(width, height);

                    for (int i = 0; i < bitmap.PixelWidth * bitmap.PixelHeight; i++)
                    {
                        bitmap.Pixels[i] = (int)(0xff << 24);
                    }
                });

                if (bitmap == null) return MoSync.Constants.RES_OUT_OF_MEMORY;
                res.SetInternalObject(bitmap);
                return MoSync.Constants.RES_OK;
            };

            syscalls.maCreateImageRaw = delegate(int _placeholder, int _src, int _size, int _alpha)
            {
                int width = MoSync.Util.ExtentX(_size);
                int height = MoSync.Util.ExtentY(_size);

                WriteableBitmap bitmap = null;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        bitmap = new WriteableBitmap(width, height);
                    });

                //core.GetDataMemory().ReadIntegers(bitmap.Pixels, _src, width * height);
                bitmap.FromByteArray(core.GetDataMemory().GetData(), _src, width * height * 4);
                if (_alpha == 0)
                {
                    int[] pixels = bitmap.Pixels;
                    int numPixels = width * height;
                    for (int i = 0; i < numPixels; i++)
                    {
                        pixels[i] = (int)((uint)pixels[i] | 0xff000000);
                    }
                }

                Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, _placeholder);
                res.SetInternalObject(bitmap);
                res.SetResourceType(MoSync.Constants.RT_IMAGE);
                return MoSync.Constants.RES_OK;
            };

            syscalls.maDrawRGB = delegate(int _dstPoint, int _src, int _srcRect, int _scanlength)
            {
                Memory dataMemory = core.GetDataMemory();
                int dstX = dataMemory.ReadInt32(_dstPoint + MoSync.Struct.MAPoint2d.x);
                int dstY = dataMemory.ReadInt32(_dstPoint + MoSync.Struct.MAPoint2d.y);
                int srcRectX = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.left);
                int srcRectY = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.top);
                int srcRectW = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.width);
                int srcRectH = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.height);
                int[] pixels = mCurrentDrawTarget.Pixels;
                // todo: clipRect

                _scanlength *= 4; // sizeof(int)

                for (int h = 0; h < srcRectH; h++)
                {
                    int pixelIndex = dstY * mCurrentDrawTarget.PixelWidth + dstX;
                    int address = _src + (srcRectY + h) * _scanlength;
                    for (int w = 0; w < srcRectW; w++)
                    {
                        uint srcPixel = dataMemory.ReadUInt32(address);
                        uint dstPixel = (uint)pixels[pixelIndex];

                        uint srcPixelR = (srcPixel & 0x00ff0000) >> 16;
                        uint srcPixelG = (srcPixel & 0x0000ff00) >> 8;
                        uint srcPixelB = (srcPixel & 0x000000ff) >> 0;
                        uint srcPixelA = (srcPixel & 0xff000000) >> 24;
                        uint dstPixelR = (dstPixel & 0x00ff0000) >> 16;
                        uint dstPixelG = (dstPixel & 0x0000ff00) >> 8;
                        uint dstPixelB = (dstPixel & 0x000000ff) >> 0;
                        uint dstPixelA = (dstPixel & 0xff000000) >> 24;

                        dstPixelR += ((srcPixelR - dstPixelR) * srcPixelA) / 255;
                        dstPixelG += ((srcPixelG - dstPixelG) * srcPixelA) / 255;
                        dstPixelB += ((srcPixelB - dstPixelB) * srcPixelA) / 255;

                        dstPixel = (dstPixelA << 24) | (dstPixelR << 16) | (dstPixelG << 8) | (dstPixelB);
                        pixels[pixelIndex] = (int)dstPixel;

                        address += 4;
                        pixelIndex++;
                    }

                    dstY++;
                }
            };

            syscalls.maGetImageData = delegate(int _image, int _dst, int _srcRect, int _scanlength)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, _image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();
                Memory dataMemory = core.GetDataMemory();
                int srcRectX = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.left);
                int srcRectY = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.top);
                int srcRectW = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.width);
                int srcRectH = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.height);
                int lineDst = _dst;
                byte[] data = src.ToByteArray(srcRectY * src.PixelWidth,
                    srcRectH * src.PixelWidth); // BlockCopy?
                byte[] coreArray = dataMemory.GetData();
                for (int y = 0; y < srcRectH; y++)
                {
                    System.Array.Copy(data, y * src.PixelWidth * 4, coreArray,
                        lineDst, src.PixelWidth * 4);
                    lineDst += _scanlength * 4;
                }
            };

            syscalls.maCreateImageFromData = delegate(int _placeholder, int _data, int _offset, int _size)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                if (res == null)
                    return MoSync.Constants.RES_BAD_INPUT;
                Stream bin = (Stream)res.GetInternalObject();
                if (bin == null)
                    return MoSync.Constants.RES_BAD_INPUT;
                BoundedStream s = new BoundedStream(bin, _offset, _size);
                WriteableBitmap bitmap = MoSync.Util.CreateWriteableBitmapFromStream(s);
                s.Close();

                if (bitmap == null)
                    return MoSync.Constants.RES_BAD_INPUT;

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

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

                mApplicationBarMenuItems.Add(applicationBarMenuItem);
            }
        }
Esempio n. 29
0
        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)
        {
            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;
            };
        }
Esempio n. 31
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);
            };
        }
Esempio n. 32
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);
            };
        }
Esempio n. 33
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            // maybe use some pretty reflection mechanism to find all syscall implementations here..
            syscalls.maCheckInterfaceVersion = delegate(int hash)
            {
                if (MoSync.Constants.MoSyncHash != (uint)hash)
                {
                    MoSync.Util.CriticalError("Invalid hash!");
                }
                return(hash);
            };

            syscalls.maPanic = delegate(int code, int str)
            {
                String message = core.GetDataMemory().ReadStringAtAddress(str);
                MoSync.Util.CriticalError(message + "\ncode: " + code);
            };

            syscalls.maExit = delegate(int res)
            {
                MoSync.Util.Exit(res);
            };

            DateTime startDate = System.DateTime.Now;

            syscalls.maGetMilliSecondCount = delegate()
            {
                System.TimeSpan offset = (System.DateTime.Now - startDate);

                return(offset.Milliseconds + (offset.Seconds + (offset.Minutes + (offset.Hours + offset.Days * 24) * 60) * 60) * 1000);
            };

            syscalls.maTime = delegate()
            {
                return((int)Util.ToUnixTimeUtc(System.DateTime.Now));
            };

            syscalls.maLocalTime = delegate()
            {
                return((int)Util.ToUnixTime(System.DateTime.Now));
            };

            syscalls.maCreatePlaceholder = delegate()
            {
                Resource res = new Resource(null, MoSync.Constants.RT_PLACEHOLDER, true);
                return(runtime.AddResource(res));
            };

            syscalls.maDestroyPlaceholder = delegate(int res)
            {
                if (!runtime.GetResource(0, res).IsDynamicPlaceholder())
                {
                    MoSync.Util.CriticalError("maDestroyPlaceholder can only be used on handles created by maCreatePlaceholder.");
                }
                runtime.RemoveResource(res);
            };

            syscalls.maFindLabel = delegate(int _name)
            {
                String name = core.GetDataMemory().ReadStringAtAddress(_name);
                int    res;
                if (runtime.mLabels.TryGetValue(name, out res))
                {
                    return(res);
                }
                else
                {
                    return(-1);
                }
            };

            /*
             * PhoneApplicationService.Current.UserIdleDetectionMode
             * Disabling this will stop the screen from timing out and locking.
             * Discussion: this needs to be re-enabled for the backlight to work
             *             so an maStartBacklight should be needed for WP7;
             *             what about maToggleBacklight(bool)?
             *
             * We have maWakeLock instead on Windows Phone, Android, iOS.
             */
            syscalls.maResetBacklight = delegate()
            {
            };

            syscalls.maVibrate = delegate(int _ms)
            {
                if (mVibrateController == null)
                {
                    mVibrateController = Microsoft.Devices.VibrateController.Default;
                }

                // more than 5 seconds aren't allowed..
                if (_ms > 5000)
                {
                    _ms = 5000;
                }

                if (_ms < 0)
                {
                    return(_ms);
                }
                else if (_ms == 0)
                {
                    mVibrateController.Stop();
                }
                else
                {
                    mVibrateController.Start(TimeSpan.FromMilliseconds(_ms));
                }

                return(1);
            };

            syscalls.maLoadProgram = delegate(int _data, int _reload)
            {
#if REBUILD
                throw new Exception("maLoadProgram not available in rebuild mode");
#else
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                //Memory mem = (Memory)res.GetInternalObject();
                Stream mem = (Stream)res.GetInternalObject();
                MoSync.Machine.SetLoadProgram(mem, _reload != 0);
                throw new Util.ExitException(0);
#endif
            };
        }
Esempio n. 34
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            mNativeUI = new NativeUI.AsyncNativeUIWindowsPhone(runtime);
            //mWidgets.Add(null); // why?

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

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

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

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

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

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

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

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

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

                return widgetHandle;
            };

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

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

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

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

                return MoSync.Constants.MAW_RES_OK;
            };

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

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

                return MoSync.Constants.MAW_RES_OK;
            };

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

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

                return MoSync.Constants.MAW_RES_OK;
            };

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

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

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

                return MoSync.Constants.MAW_RES_OK;
            };

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

                return MoSync.Constants.MAW_RES_OK;
            };

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

                IScreen screen = null;

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

                mCurrentScreen = screen;

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

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

                IScreen screen = null;

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

                mCurrentScreen = screen;

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

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

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

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

                IScreen screen = (IScreen)mWidgets[_widget];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    //Return the index associated to the item.
                    return menuIndex;
                }
            };
        }
Esempio n. 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);
            };
        }
Esempio n. 36
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);
            };
        }
Esempio n. 37
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;
                }
            });

            // 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;
            };
        }
Esempio n. 38
0
        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;
            };
        }
Esempio n. 39
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;
                    });

                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;
            };
        }
Esempio n. 40
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);
            };
        }
Esempio n. 41
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);
            };
        }
        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;
                }
            };
        }
Esempio n. 43
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            // maybe use some pretty reflection mechanism to find all syscall implementations here..
            syscalls.maCheckInterfaceVersion = delegate(int hash)
            {
                if (MoSync.Constants.MoSyncHash != (uint)hash)
                    MoSync.Util.CriticalError("Invalid hash!");
                return hash;
            };

            syscalls.maPanic = delegate(int code, int str)
            {
                String message = core.GetDataMemory().ReadStringAtAddress(str);
                MoSync.Util.CriticalError(message + "\ncode: " + code);
            };

            syscalls.maExit = delegate(int res)
            {
                mCore.Stop();
            };

            DateTime startDate = System.DateTime.Now;
            syscalls.maGetMilliSecondCount = delegate()
            {
                System.TimeSpan offset = (System.DateTime.Now - startDate);

                return offset.Milliseconds + (offset.Seconds + (offset.Minutes + (offset.Hours + offset.Days * 24) * 60) * 60) * 1000;
            };

            syscalls.maTime = delegate()
            {
                return (int)Util.ToUnixTimeUtc(System.DateTime.Now);
            };

            syscalls.maLocalTime = delegate()
            {
                return (int)Util.ToUnixTime(System.DateTime.Now);
            };

            syscalls.maCreatePlaceholder = delegate()
            {
                Resource res = new Resource(null, MoSync.Constants.RT_PLACEHOLDER, true);
                return runtime.AddResource(res);
            };

            syscalls.maDestroyPlaceholder = delegate(int res)
            {
                if (!runtime.GetResource(0, res).IsDynamicPlaceholder())
                    MoSync.Util.CriticalError("maDestroyPlaceholder can only be used on handles created by maCreatePlaceholder.");
                runtime.RemoveResource(res);
            };

            syscalls.maFindLabel = delegate(int _name)
            {
                String name = core.GetDataMemory().ReadStringAtAddress(_name);
                int res;
                if (runtime.mLabels.TryGetValue(name, out res))
                    return res;
                else
                    return -1;
            };

            /*
             * PhoneApplicationService.Current.UserIdleDetectionMode
             * Disabling this will stop the screen from timing out and locking.
             * Discussion: this needs to be re-enabled for the backlight to work
             *             so an maStartBacklight should be needed for WP7;
             *             what about maToggleBacklight(bool)?
             *
             * We have maWakeLock instead on Windows Phone, Android, iOS.
             */
            syscalls.maResetBacklight = delegate()
            {
            };

            syscalls.maVibrate = delegate(int _ms)
            {
                if (mVibrateController == null)
                    mVibrateController = Microsoft.Devices.VibrateController.Default;

                // more than 5 seconds aren't allowed..
                if (_ms > 5000)
                    _ms = 5000;

                if (_ms < 0)
                    return _ms;
                else if (_ms == 0)
                    mVibrateController.Stop();
                else
                    mVibrateController.Start(TimeSpan.FromMilliseconds(_ms));

                return 1;
            };

            syscalls.maLoadProgram = delegate(int _data, int _reload)
            {
            #if REBUILD
                throw new Exception("maLoadProgram not available in rebuild mode");
            #elif !LIB
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                //Memory mem = (Memory)res.GetInternalObject();
                Stream mem = (Stream)res.GetInternalObject();
                MoSync.Machine.SetLoadProgram(mem, _reload != 0);
                throw new Util.ExitException(0);
            #endif
            };
        }
Esempio n. 44
0
        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);
            };
        }
Esempio n. 45
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;
            };
        }
Esempio n. 46
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

            MoSync.SystemPropertyManager.RegisterSystemPropertyProvider("mosync.path.local",
                delegate(String key)
                {
                    // The isolated storage becomes the "root"
                    return "/";
                }
            );

            ioctls.maFileOpen = delegate(int _path, int _mode)
            {
                String path = core.GetDataMemory().ReadStringAtAddress(_path);
                path = ConvertPath(path);

                File file = null;
                FileAccess access = 0;

                if (_mode == MoSync.Constants.MA_ACCESS_READ)
                {
                    access = FileAccess.Read;
                }
                else if (_mode == MoSync.Constants.MA_ACCESS_READ_WRITE)
                {
                    access = FileAccess.ReadWrite;
                }
                else
                {
                    throw new Exception("Invalid file access mode");
                }

                file = new File(path, access);

                if (file.IsDirectory)
                {
                    if (isolatedStorage.FileExists(path))
                        return MoSync.Constants.MA_FERR_WRONG_TYPE;
                }
                else
                {
                    if (isolatedStorage.DirectoryExists(path))
                        return MoSync.Constants.MA_FERR_WRONG_TYPE;
                    try
                    {
                        file.TryOpen();
                    }
                    catch (IsolatedStorageException e)
                    {
                        MoSync.Util.Log(e);
                        return MoSync.Constants.MA_FERR_GENERIC;
                    }
                }

                mFileHandles.Add(mNextFileHandle, file);
                return mNextFileHandle++;
            };

            ioctls.maFileClose = delegate(int _file)
            {
                File file = mFileHandles[_file];
                file.Close();
                mFileHandles.Remove(_file);
                return 0;
            };

            ioctls.maFileRead = delegate(int _file, int _dst, int _len)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                    return MoSync.Constants.MA_FERR_WRONG_TYPE;
                IsolatedStorageFileStream fileStream = file.FileStream;
                if (fileStream == null)
                    return MoSync.Constants.MA_FERR_GENERIC;
                core.GetDataMemory().WriteFromStream(_dst, fileStream, _len);
                return 0;
            };

            ioctls.maFileReadToData = delegate(int _file, int _data, int _offset, int _len)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                    return MoSync.Constants.MA_FERR_WRONG_TYPE;
                IsolatedStorageFileStream fileStream = file.FileStream;
                if (fileStream == null)
                    return MoSync.Constants.MA_FERR_GENERIC;
                Resource dataRes = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                //Memory data = (Memory)dataRes.GetInternalObject();
                Stream data = (Stream)dataRes.GetInternalObject();
                MoSync.Util.CopySeekableStreams(fileStream, (int)fileStream.Position,
                    data, _offset, _len);
                //data.WriteFromStream(_offset, fileStream, _len);
                return 0;
            };

            ioctls.maFileWriteFromData = delegate(int _file, int _data, int _offset, int _len)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                    return MoSync.Constants.MA_FERR_WRONG_TYPE;
                IsolatedStorageFileStream fileStream = file.FileStream;
                if (fileStream == null)
                    return MoSync.Constants.MA_FERR_GENERIC;
                Resource dataRes = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                //Memory data = (Memory)dataRes.GetInternalObject();
                Stream data = (Stream)dataRes.GetInternalObject();
                //byte[] bytes = new byte[_len];
                //data.ReadBytes(bytes, _offset, _len);
                MoSync.Util.CopySeekableStreams( data, _offset,
                    fileStream, (int)fileStream.Position,
                    _len);
                //fileStream.Write(bytes, 0, _len);
                fileStream.Flush();
                return 0;
            };

            ioctls.maFileWrite = delegate(int _file, int _src, int _len)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                    return MoSync.Constants.MA_FERR_WRONG_TYPE;
                IsolatedStorageFileStream fileStream = file.FileStream;
                if (fileStream == null)
                    return MoSync.Constants.MA_FERR_GENERIC;
                byte[] bytes = new byte[_len];
                core.GetDataMemory().ReadBytes(bytes, _src, _len);
                fileStream.Write(bytes, 0, _len);
                fileStream.Flush();
                return 0;
            };

            ioctls.maFileSeek = delegate(int _file, int _offset, int _whence)
            {
                File file = mFileHandles[_file];
                if (file.IsDirectory)
                    return MoSync.Constants.MA_FERR_WRONG_TYPE;
                IsolatedStorageFileStream fileStream = file.FileStream;
                SeekOrigin origin;
                switch (_whence)
                {
                    case MoSync.Constants.MA_SEEK_SET:
                        origin = SeekOrigin.Begin;
                        break;
                    case MoSync.Constants.MA_SEEK_CUR:
                        origin = SeekOrigin.Current;
                        break;
                    case MoSync.Constants.MA_SEEK_END:
                        origin = SeekOrigin.End;
                        break;
                    default:
                        throw new Exception("maFileSeek whence");
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            ioctls.maFileListClose = delegate(int _list)
            {
                FileList fl = mFileListHandles[_list];
                mFileListHandles.Remove(_list);
                return 0;
            };
        }
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            // maybe use some pretty reflection mechanism to find all syscall implementations here..
            syscalls.maCheckInterfaceVersion = delegate(int hash)
            {
                if (MoSync.Constants.MoSyncHash != (uint)hash)
                    MoSync.Util.CriticalError("Invalid hash!");
                return hash;
            };

            syscalls.maPanic = delegate(int code, int str)
            {
                String message = core.GetDataMemory().ReadStringAtAddress(str);
                MoSync.Util.CriticalError(message + "\ncode: " + code);
            };

            syscalls.maExit = delegate(int res)
            {
                MoSync.Util.Exit(res);
            };

            DateTime startDate = System.DateTime.Now;
            syscalls.maGetMilliSecondCount = delegate()
            {
                System.TimeSpan offset = (System.DateTime.Now - startDate);

                return offset.Milliseconds + (offset.Seconds + (offset.Minutes + (offset.Hours + offset.Days * 24) * 60) * 60) * 1000;
            };

            syscalls.maTime = delegate()
            {
                return (int)Util.ToUnixTimeUtc(System.DateTime.Now);
            };

            syscalls.maLocalTime = delegate()
            {
                return (int)Util.ToUnixTime(System.DateTime.Now);
            };

            syscalls.maCreatePlaceholder = delegate()
            {
                Resource res = new Resource(null, MoSync.Constants.RT_PLACEHOLDER, true);
                return runtime.AddResource(res);
            };

            syscalls.maDestroyPlaceholder = delegate(int res)
            {
                if (!runtime.GetResource(0, res).IsDynamicPlaceholder())
                    MoSync.Util.CriticalError("maDestroyPlaceholder can only be used on handles created by maCreatePlaceholder.");
                runtime.RemoveResource(res);
            };

            syscalls.maFindLabel = delegate(int _name)
            {
                String name = core.GetDataMemory().ReadStringAtAddress(_name);
                int res;
                if (runtime.mLabels.TryGetValue(name, out res))
                    return res;
                else
                    return -1;
            };

            syscalls.maResetBacklight = delegate()
            {
            };

            syscalls.maVibrate = delegate(int _ms)
            {
                if (mVibrateController == null)
                    mVibrateController = Microsoft.Devices.VibrateController.Default;

                if (_ms < 0)
                    return _ms;
                else if (_ms == 0)
                    mVibrateController.Stop();
                else
                    mVibrateController.Start(TimeSpan.FromMilliseconds(_ms));

                return 0;
            };

            syscalls.maLoadProgram = delegate(int _data, int _reload)
            {
            #if REBUILD
                throw new Exception("maLoadProgram not available in rebuild mode");
            #else
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                //Memory mem = (Memory)res.GetInternalObject();
                Stream mem = (Stream)res.GetInternalObject();
                MoSync.Machine.SetLoadProgram(mem, _reload != 0);
                throw new Util.ExitException(0);
            #endif
            };
        }
Esempio n. 48
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);
            };
        }
Esempio n. 49
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)
        {
            /**
             * 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;
            };
        }
Esempio n. 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);
                }
            };
        }
Esempio n. 52
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)
            {
                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;
            };
        }
Esempio n. 53
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(Syscalls syscalls, Core core, Runtime runtime)
        {
            runtime.RegisterCleaner(delegate()
            {
                foreach(KeyValuePair<int, Connection> p in mConnections) {
                    p.Value.close();
                }
                mConnections.Clear();
            });

            mResultHandler = delegate(int handle, int connOp, int result)
            {
                Memory evt = new Memory(4 * 4);
                evt.WriteInt32(MAEvent_type, MoSync.Constants.EVENT_TYPE_CONN);
                evt.WriteInt32(MAConnEventData_handle, handle);
                evt.WriteInt32(MAConnEventData_opType, connOp);
                evt.WriteInt32(MAConnEventData_result, result);
                runtime.PostEvent(new Event(evt));
            };

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

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

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

            syscalls.maConnGetAddr = delegate(int _conn, int _addr)
            {
                Connection c = mConnections[_conn];
                return c.getAddr(_addr);
            };

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

            DataDelegate dataDelegate = delegate(int _conn, int _data,
                CommDelegate cd)
            {
                Connection c = mConnections[_conn];
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Memory mem = (Memory)res.GetInternalObject();
                runtime.SetResourceRaw(_data, Resource.Flux);
                cd(c, mem.GetData(),
                    delegate(int handle, int connOp, int result)
                    {
                        runtime.SetResourceRaw(_data, res);
                        mResultHandler(handle, connOp, result);
                    });
            };

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

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

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

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

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

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

            syscalls.maHttpGetResponseHeader = delegate(int _conn, int _key, int _buffer, int _bufSize)
            {
                WebRequestConnection c = (WebRequestConnection)mConnections[_conn];
                String key = core.GetDataMemory().ReadStringAtAddress(_key);
                String value = c.getResponseHeader(key);
                if (value == null)
                    return MoSync.Constants.CONNERR_NOHEADER;
                if (value.Length + 1 <= _bufSize)
                    core.GetDataMemory().WriteStringAtAddress(_buffer, value, _bufSize);
                return value.Length;
            };
        }
Esempio n. 55
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);
            };
        }
Esempio n. 56
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            runtime.RegisterCleaner(delegate()
            {
                CleanDictionary(mFileHandles);
                CleanDictionary(mStoreHandles);
                mFileListHandles.Clear();
            });

            // todo: store "stores" in a separate location from the filesystem,
            // to avoid clashes.
            syscalls.maOpenStore = delegate(int _name, int _flags)
            {
                String name = core.GetDataMemory().ReadStringAtAddress(_name);
                name = ConvertPath(name);
                File file = new File(name, FileAccess.ReadWrite);
                if (file.IsDirectory)
                {
                    throw new Exception("Invalid store name");
                }
                if (file.Exists)
                {
                    file.TryOpen();
                }
                else if ((_flags & MoSync.Constants.MAS_CREATE_IF_NECESSARY) != 0)
                {
                    file.Create();
                }
                else
                {
                    return(MoSync.Constants.STERR_NONEXISTENT);
                }
                if (file.FileStream == null)
                {
                    return(MoSync.Constants.STERR_GENERIC);
                }
                mStoreHandles.Add(mNextStoreHandle, file);
                return(mNextStoreHandle++);
            };

            syscalls.maWriteStore = delegate(int _store, int _data)
            {
                File file = mStoreHandles[_store];
                IsolatedStorageFileStream fileStream = file.FileStream;
                fileStream.SetLength(0);
                Resource dataRes = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                Stream   data    = (Stream)dataRes.GetInternalObject();
                data.Seek(0, SeekOrigin.Begin);
                //fileStream.Write(data.GetData(), 0, data.GetData().Length);
                data.CopyTo(fileStream);
                return(1);
            };

            syscalls.maReadStore = delegate(int _store, int _placeholder)
            {
                File file = mStoreHandles[_store];
                IsolatedStorageFileStream fileStream = file.FileStream;
                //Memory mem = new Memory((int)fileStream.Length);
                MemoryStream mem = new MemoryStream((int)fileStream.Length);
                mem.SetLength((int)fileStream.Length);
                fileStream.Seek(0, SeekOrigin.Begin);
                fileStream.Read(mem.GetBuffer(), 0, (int)fileStream.Length);
                runtime.SetResource(_placeholder, new Resource(mem, MoSync.Constants.RT_BINARY, true));
                return(MoSync.Constants.RES_OK);
            };

            syscalls.maCloseStore = delegate(int _store, int _delete)
            {
                File file = mStoreHandles[_store];
                file.Close();
                if (_delete != 0)
                {
                    file.Delete();
                }
                mStoreHandles.Remove(_store);
            };
        }
Esempio n. 57
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual;
            double screenWidth          = System.Windows.Application.Current.Host.Content.ActualWidth;
            double screenHeight         = System.Windows.Application.Current.Host.Content.ActualHeight;

            if ((int)screenHeight == 0)
            {
                throw new Exception("screenHeight");
            }
            PhoneApplicationPage mainPage = (PhoneApplicationPage)frame.Content;

            mMainImage = new Image();


            mainPage.Width    = screenWidth;
            mainPage.Height   = screenHeight;
            mMainImage.Width  = screenWidth;
            mMainImage.Height = screenHeight;
            mainPage.Content  = mMainImage;

            mClipRect.X      = 0.0;
            mClipRect.Y      = 0.0;
            mClipRect.Width  = screenWidth;
            mClipRect.Height = screenHeight;

            // no apparent effect on memory leaks.
            runtime.RegisterCleaner(delegate()
            {
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    mainPage.Content = null;
                });
            });

            mBackBuffer = new WriteableBitmap(
                (int)screenWidth,
                (int)screenHeight);
            mFrontBuffer = new WriteableBitmap(
                (int)screenWidth,
                (int)screenHeight);

            mMainImage.Source = mFrontBuffer;

            // clear front and backbuffer.
            for (int i = 0; i < mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight; i++)
            {
                mBackBuffer.Pixels[i] = mBackBuffer.Pixels[i] = (int)(0xff << 24);
            }

            mCurrentDrawTarget = mBackBuffer;

            mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff,
                                                                       (byte)(mCurrentColor >> 16),
                                                                       (byte)(mCurrentColor >> 8),
                                                                       (byte)(mCurrentColor));

            syscalls.maSetColor = delegate(int rgb)
            {
                int oldColor = (int)mCurrentColor;
                mCurrentColor        = 0xff000000 | (uint)(rgb & 0xffffff);
                mCurrentWindowsColor = System.Windows.Media.Color.FromArgb(0xff,
                                                                           (byte)(mCurrentColor >> 16),
                                                                           (byte)(mCurrentColor >> 8),
                                                                           (byte)(mCurrentColor));
                return(oldColor & 0xffffff);
            };

            syscalls.maSetClipRect = delegate(int x, int y, int w, int h)
            {
                MoSync.GraphicsUtil.ClipRectangle(
                    x, y, w, h,
                    0, 0, mCurrentDrawTarget.PixelWidth, mCurrentDrawTarget.PixelHeight,
                    out x, out y, out w, out h);

                mClipRect.X      = x;
                mClipRect.Y      = y;
                mClipRect.Width  = w;
                mClipRect.Height = h;
            };

            syscalls.maGetClipRect = delegate(int cliprect)
            {
#if !LIB
                Memory mem = core.GetDataMemory();
#else
                SystemMemory mem = core.GetDataMemory();
#endif
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.left, (int)mClipRect.X);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.top, (int)mClipRect.Y);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.width, (int)mClipRect.Width);
                mem.WriteInt32(cliprect + MoSync.Struct.MARect.height, (int)mClipRect.Height);
            };

            syscalls.maPlot = delegate(int x, int y)
            {
                mCurrentDrawTarget.SetPixel(x, y, (int)mCurrentColor);
            };

            syscalls.maUpdateScreen = delegate()
            {
                //System.Array.Copy(mBackBuffer.Pixels, mFrontBuffer.Pixels, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight);
                System.Buffer.BlockCopy(mBackBuffer.Pixels, 0, mFrontBuffer.Pixels, 0, mFrontBuffer.PixelWidth * mFrontBuffer.PixelHeight * 4);

                InvalidateWriteableBitmapOnMainThread(mFrontBuffer);
            };

            syscalls.maFillRect = delegate(int x, int y, int w, int h)
            {
                // this function has a bug (it only fills one pixel less than the image.)
                //mCurrentDrawTarget.FillRectangle(x, y, x + w, y + h, (int)mCurrentColor);

                MoSync.GraphicsUtil.ClipRectangle(
                    x, y, w, h,
                    0, 0, mCurrentDrawTarget.PixelWidth, mCurrentDrawTarget.PixelHeight,
                    out x, out y, out w, out h);

                MoSync.GraphicsUtil.ClipRectangle(
                    x, y, w, h,
                    (int)mClipRect.X, (int)mClipRect.Y, (int)mClipRect.Width, (int)mClipRect.Height,
                    out x, out y, out w, out h);

                if (w <= 0 || h <= 0)
                {
                    return;
                }

                int index = x + y * mCurrentDrawTarget.PixelWidth;
                while (h-- != 0)
                {
                    int width = w;
                    while (width-- != 0)
                    {
                        mCurrentDrawTarget.Pixels[index] = (int)mCurrentColor;
                        index++;
                    }
                    index += -w + mCurrentDrawTarget.PixelWidth;
                }
            };

            syscalls.maLine = delegate(int x1, int y1, int x2, int y2)
            {
                GraphicsUtil.Point p1 = new GraphicsUtil.Point(x1, y1);
                GraphicsUtil.Point p2 = new GraphicsUtil.Point(x2, y2);
                if (!GraphicsUtil.ClipLine(p1, p2, (int)mClipRect.X, (int)(mClipRect.X + mClipRect.Width),
                                           (int)mClipRect.Y, (int)(mClipRect.Y + mClipRect.Height)))
                {
                    return;
                }

                mCurrentDrawTarget.DrawLine((int)p1.x, (int)p1.y, (int)p2.x, (int)p2.y, (int)mCurrentColor);
            };

            textBlock.FontSize = mCurrentFontSize;

            syscalls.maDrawText = delegate(int left, int top, int str)
            {
                String text = core.GetDataMemory().ReadStringAtAddress(str);
                if (text.Length == 0)
                {
                    return;
                }
                DrawText(text, left, top);
            };

            syscalls.maGetTextSize = delegate(int str)
            {
                String text       = core.GetDataMemory().ReadStringAtAddress(str);
                int    textWidth  = 0;
                int    textHeight = 0;
                GetTextSize(text, out textWidth, out textHeight);
                return(MoSync.Util.CreateExtent(textWidth, textHeight));
            };

            syscalls.maDrawTextW = delegate(int left, int top, int str)
            {
                String text = core.GetDataMemory().ReadWStringAtAddress(str);
                if (text.Length == 0)
                {
                    return;
                }

                DrawText(text, left, top);
            };

            syscalls.maGetTextSizeW = delegate(int str)
            {
                String text       = core.GetDataMemory().ReadWStringAtAddress(str);
                int    textWidth  = 0;
                int    textHeight = 0;
                GetTextSize(text, out textWidth, out textHeight);
                return(MoSync.Util.CreateExtent(textWidth, textHeight));
            };

            syscalls.maFillTriangleFan = delegate(int points, int count)
            {
                int[] newPoints = new int[count * 2 + 2];
                for (int i = 0; i < count; i++)
                {
                    newPoints[i * 2 + 0] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.x);
                    newPoints[i * 2 + 1] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.y);
                }
                newPoints[count * 2 + 0] = core.GetDataMemory().ReadInt32(points + MoSync.Struct.MAPoint2d.x);
                newPoints[count * 2 + 1] = core.GetDataMemory().ReadInt32(points + MoSync.Struct.MAPoint2d.y);
                mCurrentDrawTarget.FillPolygon(newPoints, (int)mCurrentColor);
            };

            syscalls.maFillTriangleStrip = delegate(int points, int count)
            {
                int[] xcoords = new int[count];
                int[] ycoords = new int[count];

                for (int i = 0; i < count; i++)
                {
                    xcoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.x);
                    ycoords[i] = core.GetDataMemory().ReadInt32(points + i * 8 + MoSync.Struct.MAPoint2d.y);
                }

                for (int i = 2; i < count; i++)
                {
                    mCurrentDrawTarget.FillTriangle(
                        xcoords[i - 2], ycoords[i - 2],
                        xcoords[i - 1], ycoords[i - 1],
                        xcoords[i - 0], ycoords[i - 0],
                        (int)mCurrentColor);
                }
            };

            syscalls.maSetDrawTarget = delegate(int drawTarget)
            {
                int oldDrawTarget = mCurrentDrawTargetIndex;
                if (drawTarget == mCurrentDrawTargetIndex)
                {
                    return(oldDrawTarget);
                }
                if (drawTarget == MoSync.Constants.HANDLE_SCREEN)
                {
                    mCurrentDrawTarget      = mBackBuffer;
                    mCurrentDrawTargetIndex = drawTarget;
                    return(oldDrawTarget);
                }

                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, drawTarget);
                mCurrentDrawTarget      = (WriteableBitmap)res.GetInternalObject();
                mCurrentDrawTargetIndex = drawTarget;
                return(oldDrawTarget);
            };

            syscalls.maGetScrSize = delegate()
            {
                int w = mBackBuffer.PixelWidth;
                int h = mBackBuffer.PixelHeight;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    // if the orientation is landscape, the with and height should be swaped
                    PhoneApplicationPage currentPage = (((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage);
                    if (currentPage.Orientation == PageOrientation.Landscape ||
                        currentPage.Orientation == PageOrientation.LandscapeLeft ||
                        currentPage.Orientation == PageOrientation.LandscapeRight)
                    {
                        int aux = w;
                        w       = h;
                        h       = aux;
                    }
                });
                return(MoSync.Util.CreateExtent(w, h));
            };

            syscalls.maGetImageSize = delegate(int handle)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, handle);
                int      w = 0, h = 0;
#if !LIB
                BitmapSource src = (BitmapSource)res.GetInternalObject();
                if (src == null)
                {
                    MoSync.Util.CriticalError("maGetImageSize used with an invalid image resource.");
                }
                else
                {
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        w = src.PixelWidth;
                        h = src.PixelHeight;
                    });
                }
#else
                if (res.GetInternalObject() == null)
                {
                    MoSync.Util.CriticalError("maGetImageSize used with an invalid image resource.");
                }
                else
                {
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        if (res.GetInternalObject() is Stream)
                        {
                            BitmapImage bi = new BitmapImage();
                            bi.SetSource((Stream)res.GetInternalObject());
                            w = bi.PixelWidth;
                            h = bi.PixelHeight;
                        }
                        else if (res.GetInternalObject() is WriteableBitmap)
                        {
                            BitmapSource src = (BitmapSource)res.GetInternalObject();
                            w = src.PixelWidth;
                            h = src.PixelHeight;
                        }
                    });
                }
#endif
                return(MoSync.Util.CreateExtent(w, h));
            };

            syscalls.maDrawImage = delegate(int image, int left, int top)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image);
#if !LIB
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();
#else
                Object src = null;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    Object internalObj = res.GetInternalObject();
                    if (internalObj is Stream)
                    {
                        src = new WriteableBitmap(0, 0);
                        (src as WriteableBitmap).SetSource((Stream)res.GetInternalObject());
                    }
                    else if (internalObj is WriteableBitmap)
                    {
                        src = res.GetInternalObject();
                    }
                });
#endif
                Rect srcRect = new Rect(0, 0, (src as WriteableBitmap).PixelWidth, (src as WriteableBitmap).PixelHeight);
                Rect dstRect = new Rect(left, top, (src as WriteableBitmap).PixelWidth, (src as WriteableBitmap).PixelHeight);
                mCurrentDrawTarget.Blit(dstRect, (src as WriteableBitmap), srcRect, WriteableBitmapExtensions.BlendMode.Alpha);
            };

            syscalls.maDrawImageRegion = delegate(int image, int srcRectPtr, int dstPointPtr, int transformMode)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_IMAGE, image);
#if !LIB
                WriteableBitmap src        = (WriteableBitmap)res.GetInternalObject();
                Memory          dataMemory = core.GetDataMemory();
#else
                SystemMemory dataMemory = core.GetDataMemory();
                Object       src        = null;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    Object internalObj = res.GetInternalObject();
                    if (internalObj is Stream)
                    {
                        src = new WriteableBitmap(0, 0);
                        (src as WriteableBitmap).SetSource((Stream)res.GetInternalObject());
                    }
                    else if (internalObj is WriteableBitmap)
                    {
                        src = res.GetInternalObject();
                    }
                });
#endif

                int srcRectX  = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.left);
                int srcRectY  = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.top);
                int srcRectW  = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.width);
                int srcRectH  = dataMemory.ReadInt32(srcRectPtr + MoSync.Struct.MARect.height);
                int dstPointX = dataMemory.ReadInt32(dstPointPtr + MoSync.Struct.MAPoint2d.x);
                int dstPointY = dataMemory.ReadInt32(dstPointPtr + MoSync.Struct.MAPoint2d.y);

                Rect srcRect = new Rect(srcRectX, srcRectY, srcRectW, srcRectH);
                Rect dstRect = new Rect(dstPointX, dstPointY, srcRectW, srcRectH);

                GraphicsUtil.DrawImageRegion(mCurrentDrawTarget, dstPointX, dstPointY, srcRect, (src as WriteableBitmap), transformMode, mClipRect);
            };

            syscalls.maCreateDrawableImage = delegate(int placeholder, int width, int height)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, placeholder);
                res.SetResourceType(MoSync.Constants.RT_IMAGE);
                WriteableBitmap bitmap = null;

                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    bitmap = new WriteableBitmap(width, height);

                    for (int i = 0; i < bitmap.PixelWidth * bitmap.PixelHeight; i++)
                    {
                        bitmap.Pixels[i] = (int)(0xff << 24);
                    }
                });

                if (bitmap == null)
                {
                    return(MoSync.Constants.RES_OUT_OF_MEMORY);
                }
                res.SetInternalObject(bitmap);
                return(MoSync.Constants.RES_OK);
            };

            syscalls.maCreateImageRaw = delegate(int _placeholder, int _src, int _size, int _alpha)
            {
                int width  = MoSync.Util.ExtentX(_size);
                int height = MoSync.Util.ExtentY(_size);

                WriteableBitmap bitmap = null;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    bitmap = new WriteableBitmap(width, height);
                });

                //core.GetDataMemory().ReadIntegers(bitmap.Pixels, _src, width * height);

#if !LIB
                bitmap.FromByteArray(core.GetDataMemory().GetData(), _src, width * height * 4);
#else
                byte[] bytes = new byte[width * height * 4];
                core.GetDataMemory().ReadBytes(bytes, _src, width * height * 4);

                bitmap.FromByteArray(bytes, 0, width * height * 4);                 // TO BE TESTED
#endif
                if (_alpha == 0)
                {
                    int[] pixels    = bitmap.Pixels;
                    int   numPixels = width * height;
                    for (int i = 0; i < numPixels; i++)
                    {
                        pixels[i] = (int)((uint)pixels[i] | 0xff000000);
                    }
                }

                Resource res = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, _placeholder);
                res.SetInternalObject(bitmap);
                res.SetResourceType(MoSync.Constants.RT_IMAGE);
                return(MoSync.Constants.RES_OK);
            };

            syscalls.maDrawRGB = delegate(int _dstPoint, int _src, int _srcRect, int _scanlength)
            {
#if !LIB
                Memory dataMemory = core.GetDataMemory();
#else
                SystemMemory dataMemory = core.GetDataMemory();
#endif
                int   dstX     = dataMemory.ReadInt32(_dstPoint + MoSync.Struct.MAPoint2d.x);
                int   dstY     = dataMemory.ReadInt32(_dstPoint + MoSync.Struct.MAPoint2d.y);
                int   srcRectX = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.left);
                int   srcRectY = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.top);
                int   srcRectW = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.width);
                int   srcRectH = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.height);
                int[] pixels   = mCurrentDrawTarget.Pixels;
                // todo: clipRect

                _scanlength *= 4;                 // sizeof(int)

                for (int h = 0; h < srcRectH; h++)
                {
                    int pixelIndex = dstY * mCurrentDrawTarget.PixelWidth + dstX;
                    int address    = _src + (srcRectY + h) * _scanlength;
                    for (int w = 0; w < srcRectW; w++)
                    {
                        uint srcPixel = dataMemory.ReadUInt32(address);
                        uint dstPixel = (uint)pixels[pixelIndex];

                        uint srcPixelR = (srcPixel & 0x00ff0000) >> 16;
                        uint srcPixelG = (srcPixel & 0x0000ff00) >> 8;
                        uint srcPixelB = (srcPixel & 0x000000ff) >> 0;
                        uint srcPixelA = (srcPixel & 0xff000000) >> 24;
                        uint dstPixelR = (dstPixel & 0x00ff0000) >> 16;
                        uint dstPixelG = (dstPixel & 0x0000ff00) >> 8;
                        uint dstPixelB = (dstPixel & 0x000000ff) >> 0;
                        uint dstPixelA = (dstPixel & 0xff000000) >> 24;

                        dstPixelR += ((srcPixelR - dstPixelR) * srcPixelA) / 255;
                        dstPixelG += ((srcPixelG - dstPixelG) * srcPixelA) / 255;
                        dstPixelB += ((srcPixelB - dstPixelB) * srcPixelA) / 255;

                        dstPixel           = (dstPixelA << 24) | (dstPixelR << 16) | (dstPixelG << 8) | (dstPixelB);
                        pixels[pixelIndex] = (int)dstPixel;

                        address += 4;
                        pixelIndex++;
                    }

                    dstY++;
                }
            };

            syscalls.maGetImageData = delegate(int _image, int _dst, int _srcRect, int _scanlength)
            {
                Resource        res = runtime.GetResource(MoSync.Constants.RT_IMAGE, _image);
                WriteableBitmap src = (WriteableBitmap)res.GetInternalObject();
#if !LIB
                Memory dataMemory = core.GetDataMemory();
#else
                SystemMemory dataMemory = core.GetDataMemory();
#endif
                int    srcRectX = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.left);
                int    srcRectY = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.top);
                int    srcRectW = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.width);
                int    srcRectH = dataMemory.ReadInt32(_srcRect + MoSync.Struct.MARect.height);
                int    lineDst  = _dst;
                byte[] data     = src.ToByteArray(srcRectY * src.PixelWidth,
                                                  srcRectH * src.PixelWidth); // BlockCopy?
#if !LIB
                byte[] coreArray = dataMemory.GetData();
#else
                byte[] coreArray = new byte[_scanlength];
                dataMemory.ReadBytes(coreArray, _srcRect, _scanlength);
#endif
                for (int y = 0; y < srcRectH; y++)
                {
                    System.Array.Copy(data, y * src.PixelWidth * 4, coreArray,
                                      lineDst, src.PixelWidth * 4);
                    lineDst += _scanlength * 4;
                }
            };

            syscalls.maCreateImageFromData = delegate(int _placeholder, int _data, int _offset, int _size)
            {
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                if (res == null)
                {
                    return(MoSync.Constants.RES_BAD_INPUT);
                }
                Stream bin = (Stream)res.GetInternalObject();
                if (bin == null)
                {
                    return(MoSync.Constants.RES_BAD_INPUT);
                }
                BoundedStream   s      = new BoundedStream(bin, _offset, _size);
                WriteableBitmap bitmap = MoSync.Util.CreateWriteableBitmapFromStream(s);
                s.Close();

                if (bitmap == null)
                {
                    return(MoSync.Constants.RES_BAD_INPUT);
                }

                Resource imageRes = runtime.GetResource(MoSync.Constants.RT_PLACEHOLDER, _placeholder);
                imageRes.SetInternalObject(bitmap);
                imageRes.SetResourceType(MoSync.Constants.RT_IMAGE);
                return(MoSync.Constants.RES_OK);
            };
        }
        public 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;
            };
        }
Esempio n. 59
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;
            };
        }