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

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

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

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

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

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

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

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

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

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

            syscalls.maResetBacklight = delegate()
            {
            };

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

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

                return 0;
            };

            syscalls.maLoadProgram = delegate(int _data, int _reload)
            {
            #if REBUILD
                throw new Exception("maLoadProgram not available in rebuild mode");
            #else
                Resource res = runtime.GetResource(MoSync.Constants.RT_BINARY, _data);
                //Memory mem = (Memory)res.GetInternalObject();
                Stream mem = (Stream)res.GetInternalObject();
                MoSync.Machine.SetLoadProgram(mem, _reload != 0);
                throw new Util.ExitException(0);
            #endif
            };
        }
        public void Init(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
            };
        }
        private void SaveImageToCameraRoll(int imageHandle, String imageName, Resource imageResource)
        {
            MediaLibrary library = new MediaLibrary();
            MemoryStream targetStream = new MemoryStream();

            int mediaType = MoSync.Constants.MA_MEDIA_TYPE_IMAGE;
            int mediaHandle = imageHandle;
            int eventReturnCode = MoSync.Constants.MA_MEDIA_RES_OK;

            try
            {
                WriteableBitmap data = (WriteableBitmap)imageResource.GetInternalObject();
                data.SaveJpeg(targetStream, data.PixelWidth, data.PixelHeight, 0, 100);
                data = null;

                library.SavePictureToCameraRoll(imageName, targetStream.GetBuffer()).Dispose();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.ToString());
                eventReturnCode = MoSync.Constants.MA_MEDIA_RES_IMAGE_EXPORT_FAILED;
            }
            finally
            {
                library.Dispose();
                targetStream.Dispose();
                PostMediaEvent(mediaType, mediaHandle, eventReturnCode);
            }
        }
Example #4
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
            };
        }
Example #5
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);
            };
        }
Example #6
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(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();

                        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);
            };
        }
Example #7
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
            };
        }
Example #8
0
        public void Init(Syscalls syscalls, Core core, Runtime runtime)
        {
            PhoneApplicationFrame frame = (PhoneApplicationFrame)Application.Current.RootVisual;
            double screenWidth          = System.Windows.Application.Current.Host.Content.ActualWidth;
            double screenHeight         = System.Windows.Application.Current.Host.Content.ActualHeight;

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

            mMainImage = new Image();


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

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

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

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

            mMainImage.Source = mFrontBuffer;

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

            mCurrentDrawTarget = mBackBuffer;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            textBlock.FontSize = mCurrentFontSize;

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

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

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

                DrawText(text, left, top);
            };

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                _scanlength *= 4;                 // sizeof(int)

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

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

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

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

                        address += 4;
                        pixelIndex++;
                    }

                    dstY++;
                }
            };

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

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

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

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