Example #1
0
        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        {
            var width       = (int)Math.Round(((Android.App.Activity)parent.Context).WindowManager.DefaultDisplay.Width - BitmapUtils.DpToPixel(25, parent.Resources));
            var height      = (int)Math.Round(BitmapUtils.DpToPixel(160, parent.Resources));
            var previewSize = _gallery == null?
                              ViewUtils.CalculateImagePreviewSize(_postMedia[0].Size.Width, _postMedia[0].Size.Height, width, height) :
                                  ViewUtils.CalculateImagePreviewSize(_gallery[0].PreparedBitmap.Width, _gallery[0].PreparedBitmap.Height, width, height);

            var cardView = new CardView(parent.Context)
            {
                LayoutParameters = new FrameLayout.LayoutParams(previewSize.Width, previewSize.Height),
                Radius           = BitmapUtils.DpToPixel(5, parent.Resources)
            };
            var image = new ImageView(parent.Context)
            {
                Id = Resource.Id.photo,
                LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent)
            };

            image.SetScaleType(ImageView.ScaleType.FitXy);
            cardView.AddView(image);
            return(new GalleryViewHolder(cardView));
        }
Example #2
0
        public void DeletePixels(Layer[] layers, Coordinates[] pixels)
        {
            if (Manager.ActiveDocument == null)
            {
                return;
            }

            BitmapPixelChanges         changes   = BitmapPixelChanges.FromSingleColoredArray(pixels, Color.FromArgb(0, 0, 0, 0));
            Dictionary <Guid, Color[]> oldValues = BitmapUtils.GetPixelsForSelection(layers, pixels);

            LayerChange[] old       = new LayerChange[layers.Length];
            LayerChange[] newChange = new LayerChange[layers.Length];
            for (int i = 0; i < layers.Length; i++)
            {
                Guid guid = layers[i].LayerGuid;
                old[i] = new LayerChange(
                    BitmapPixelChanges.FromArrays(pixels, oldValues[layers[i].LayerGuid]), guid);
                newChange[i] = new LayerChange(changes, guid);
                layers[i].SetPixels(changes);
            }

            Manager.ActiveDocument.UndoManager.AddUndoChange(new Change("UndoChanges", old, newChange, "Deleted pixels"));
        }
Example #3
0
 private void ImageChanged(object sender, EventArgs e)
 {
     SetImage(BitmapUtils.Bitmap2BitmapImage(_state.GetImage(0, 0).GetBitmap()));
     //Task.Factory.StartNew(()=>SetImage(BitmapUtils.Bitmap2BitmapImage(_state.GetImage(0,0).GetBitmap())));
 }
Example #4
0
 public Bitmap Apply(Bitmap bitmap)
 {
     return(BitmapUtils.ResizeImage(bitmap, Size));
 }
 private static ImageSource LoadResource(string name)
 {
     return(BitmapUtils.FromResource($"Resources/FileIcons/{name}.png"));
 }
Example #6
0
    private async void strip_update(object sender, EventArgs e)
    {
        statusprogress.Visible = true;
        string penis = await currentcomic.source.fetchURL(stripretriever, ctk, date.Value);         //String.Format(currentcomic.urlFormat, date.Value)

        Uri  f**k;
        bool good = Uri.TryCreate(penis, UriKind.Absolute, out f**k);

        if (!good)
        {
            Uri.TryCreate(Path.GetFullPath(penis), UriKind.Absolute, out f**k);
        }
        //why in the world does absoluteuri return a string and not an uri

        /*
         * had to break my balls for this one.
         * none of the uri class methods don't even f*****g support
         * relative paths.
         */
        Image img;

        if (f**k.IsFile)
        {
            string path = f**k.LocalPath;
            try{
                FileStream fs = await Task.Run(() => File.OpenRead(path));                //File.OpenRead(path); its asynchronous now lol

                img = Image.FromStream(fs, false, false);
            }
            catch (FileNotFoundException suck)
            {
                img = BitmapUtils.drawMessage("not found");
            }
            catch (IOException suck)
            {
                img = BitmapUtils.drawMessage("i/o exception.\nyour file must be locked.", 36);
            }
        }
        else
        {
            HttpResponseMessage response = new HttpResponseMessage();
            try
            {
                //Stream stream = stripretriever.OpenRead(String.Format(currentcomic.urlFormat, date.Value));
                //ctk.Cancel();
                response = await currentcomic.source.fetch(penis, stripretriever, ctk);

                // response = await stripretriever.GetAsync(f**k, ctk.Token);
                response.EnsureSuccessStatusCode();
                Stream stream = await response.Content.ReadAsStreamAsync();

                img = Image.FromStream(stream, false, false);
            }
            catch (HttpRequestException suck)
            {
                //MessageBox.Show(suck.ToString());
                img = BitmapUtils.drawMessage(((int)(response.StatusCode)).ToString());
            }
            catch (ArgumentException suck)
            {
                img = BitmapUtils.drawMessage("an error occured while\nprocessing the image", 36);
            }
        }
        Bitmap bm = BitmapUtils.shittyCopy(img);         // wish i could be using "using" here

        foreach (Gimmick gimmick in gimmicks.gimmicks)
        {
            if (gimmick.enabled)
            {
                img = gimmick.doIt(bm, img, currentcomic);
                bm  = BitmapUtils.shittyCopy(img);
                // just found out Bitmap extends Image. what a waste
                // THis is prone to exceptions and im not doing anything abouti t
            }
        }
        bm.Dispose();
        strip.Image            = img;
        statusprogress.Visible = false;
        statusdate.Text        = date.Value.ToString("d");
    }
Example #7
0
        private static BaseBitmap ConvertGen3Bitmap(byte[] primaryData, byte[] secondaryData, BitmapTextureInteropDefinition definition, Bitmap bitmap, int imageIndex, bool isPaired, int pairIndex, BitmapTextureInteropDefinition otherDefinition, bool forDDS)
        {
            if (primaryData == null && secondaryData == null)
            {
                return(null);
            }

            using (var result = new MemoryStream())
            {
                int mipLevelCount = definition.MipmapCount;
                int layerCount    = definition.BitmapType == BitmapType.CubeMap ? 6 : definition.Depth;

                if (definition.BitmapType == BitmapType.Array && mipLevelCount > 1)
                {
                    mipLevelCount          = 1;
                    definition.MipmapCount = 1;
                }

                if (!forDDS)
                {
                    // order for d3d9, all faces first, then mipmaps
                    for (int mipLevel = 0; mipLevel < mipLevelCount; mipLevel++)
                    {
                        for (int layerIndex = 0; layerIndex < layerCount; layerIndex++)
                        {
                            if (definition.BitmapType == BitmapType.CubeMap) // swap cubemap faces
                            {
                                if (layerIndex == 2)
                                {
                                    layerIndex = 3;
                                }
                                else if (layerIndex == 3)
                                {
                                    layerIndex = 2;
                                }
                            }

                            ConvertGen3BitmapData(result, primaryData, secondaryData, definition, bitmap, imageIndex, mipLevel, layerIndex, isPaired, pairIndex, otherDefinition);

                            if (definition.BitmapType == BitmapType.CubeMap)
                            {
                                if (layerIndex == 3)
                                {
                                    layerIndex = 2;
                                }
                                else if (layerIndex == 2)
                                {
                                    layerIndex = 3;
                                }
                            }
                        }
                    }
                }
                else
                {
                    for (int layerIndex = 0; layerIndex < layerCount; layerIndex++)
                    {
                        if (definition.BitmapType == BitmapType.CubeMap) // swap cubemap faces
                        {
                            if (layerIndex == 2)
                            {
                                layerIndex = 3;
                            }
                            else if (layerIndex == 3)
                            {
                                layerIndex = 2;
                            }
                        }

                        for (int mipLevel = 0; mipLevel < mipLevelCount; mipLevel++)
                        {
                            ConvertGen3BitmapData(result, primaryData, secondaryData, definition, bitmap, imageIndex, mipLevel, layerIndex, isPaired, pairIndex, otherDefinition);
                        }

                        if (definition.BitmapType == BitmapType.CubeMap)
                        {
                            if (layerIndex == 3)
                            {
                                layerIndex = 2;
                            }
                            else if (layerIndex == 2)
                            {
                                layerIndex = 3;
                            }
                        }
                    }
                }

                var resultData = result.ToArray();

                BaseBitmap resultBitmap = new BaseBitmap(bitmap.Images[imageIndex]);


                var newFormat = BitmapUtils.GetEquivalentBitmapFormat(bitmap.Images[imageIndex].Format);
                resultBitmap.UpdateFormat(newFormat);

                if (BitmapUtils.RequiresDecompression(resultBitmap.Format, (uint)resultBitmap.Width, (uint)resultBitmap.Height))
                {
                    resultBitmap.Format = BitmapFormat.A8R8G8B8;
                }

                if (!BitmapUtils.IsCompressedFormat(resultBitmap.Format))
                {
                    resultBitmap.Flags &= ~BitmapFlags.Compressed;
                }
                else
                {
                    resultBitmap.Flags |= BitmapFlags.Compressed;
                }

                //
                // Update resource definition/image, truncate DXN to level 4x4
                //

                resultBitmap.Data = resultData;

                if (resultBitmap.Format == BitmapFormat.Dxn) // wouldn't be required if d3d9 supported non power of two DXN and with mips less than 8x8
                {
                    GenerateCompressedMipMaps(resultBitmap);
                }


                if (resultBitmap.Type == BitmapType.Array) // for HO, arrays use the index of Texture3D
                {
                    resultBitmap.Type = BitmapType.Texture3D;
                }

                return(resultBitmap);
            }
        }
Example #8
0
        private static void ConvertGen3BitmapData(Stream resultStream, byte[] primaryData, byte[] secondaryData, BitmapTextureInteropDefinition definition, Bitmap bitmap, int imageIndex, int level, int layerIndex, bool isPaired, int pairIndex, BitmapTextureInteropDefinition otherDefinition)
        {
            byte[] data;
            uint   levelOffset;

            var d3dFormat = definition.D3DFormat;
            var isTiled   = Direct3D.D3D9x.D3D.IsTiled(d3dFormat);

            uint blockWidth;
            uint blockHeight;

            uint alignedWidth  = (uint)definition.Width >> level;
            uint alignedHeight = (uint)definition.Height >> level;

            if (alignedWidth < 1)
            {
                alignedWidth = 1;
            }
            if (alignedHeight < 1)
            {
                alignedHeight = 1;
            }

            uint alignedDepth = definition.Depth;
            var  gpuFormat    = XboxGraphics.XGGetGpuFormat(d3dFormat);
            uint bitsPerPixel = XboxGraphics.XGBitsPerPixelFromGpuFormat(gpuFormat);

            XboxGraphics.XGGetBlockDimensions(gpuFormat, out blockWidth, out blockHeight);
            XboxGraphics.XGPOINT point = new XboxGraphics.XGPOINT();
            if (definition.MipmapCount > 1)
            {
                XboxGraphics.GetMipTailLevelOffsetCoords((uint)definition.Width, (uint)definition.Height, definition.Depth, (uint)level, gpuFormat, false, false, point);
            }

            var textureType = BitmapUtils.GetXboxBitmapD3DTextureType(definition);

            Direct3D.D3D9x.D3D.AlignTextureDimensions(ref alignedWidth, ref alignedHeight, ref alignedDepth, bitsPerPixel, gpuFormat, textureType, isTiled);

            if (level > 0)
            {
                // align to next power of two
                if (!Direct3D.D3D9x.D3D.IsPowerOfTwo((int)alignedWidth))
                {
                    alignedWidth = Direct3D.D3D9x.D3D.Log2Ceiling((int)alignedWidth);
                    if (alignedWidth < 0)
                    {
                        alignedWidth = 0;
                    }
                    alignedWidth = 1u << (int)alignedWidth;
                }

                if (!Direct3D.D3D9x.D3D.IsPowerOfTwo((int)alignedHeight))
                {
                    alignedHeight = Direct3D.D3D9x.D3D.Log2Ceiling((int)alignedHeight);
                    if (alignedHeight < 0)
                    {
                        alignedHeight = 0;
                    }
                    alignedHeight = 1u << (int)alignedHeight;
                }
            }

            // hacks when the point is outside of the first aligned texture, compute how many tiles you need and extract them (non-square only)
            if (point.X >= 32)
            {
                alignedWidth *= (uint)(1 + point.X / 32);
            }
            if (point.Y >= 32)
            {
                alignedHeight *= (uint)(1 + point.Y / 32);
            }

            uint texelPitch = blockWidth * blockHeight * bitsPerPixel / 8;
            uint size       = alignedWidth * alignedHeight * bitsPerPixel / 8;

            // documentation says that each packed mip level should be aligned to 4KB, required to make untiling work smoothly
            size = (uint)((size + 0xFFF) & ~0xFFF);

            int tileOffset = 0;

            if (!isPaired)
            {
                bool useHighResBuffer = definition.HighResInSecondaryResource > 0;
                if ((level == 0 && useHighResBuffer) || primaryData == null)
                {
                    levelOffset = BitmapUtils.GetXboxBitmapLevelOffset(definition, layerIndex, level);
                    uint alignedSecondaryLength = (uint)((secondaryData.Length + 0x3FFF) & ~0x3FFF);
                    data = new byte[alignedSecondaryLength];
                    Array.Copy(secondaryData, 0, data, 0, secondaryData.Length);
                }
                else
                {
                    levelOffset = BitmapUtils.GetXboxBitmapLevelOffset(definition, layerIndex, level, useHighResBuffer);
                    uint alignedPrimaryLength = (uint)((primaryData.Length + 0x3FFF) & ~0x3FFF);
                    data = new byte[alignedPrimaryLength];
                    Array.Copy(primaryData, 0, data, 0, primaryData.Length);
                }
            }
            else
            {
                bool useHighResBuffer = definition.HighResInSecondaryResource > 0;
                var  bitmap1          = pairIndex == 0 ? definition : otherDefinition;
                var  bitmap2          = pairIndex == 0 ? otherDefinition : definition;

                if (level == 0 && useHighResBuffer)
                {
                    levelOffset = BitmapUtils.GetXboxInterleavedBitmapOffset(bitmap1, bitmap2, layerIndex, level, pairIndex);
                    uint alignedSecondaryLength = (uint)((secondaryData.Length + 0x3FFF) & ~0x3FFF);
                    data = new byte[alignedSecondaryLength];
                    Array.Copy(secondaryData, 0, data, 0, secondaryData.Length);
                }
                else
                {
                    levelOffset = BitmapUtils.GetXboxInterleavedBitmapOffset(bitmap1, bitmap2, layerIndex, level, pairIndex, useHighResBuffer);
                    uint alignedPrimaryLength = (uint)((primaryData.Length + 0x3FFF) & ~0x3FFF);
                    data = new byte[alignedPrimaryLength];
                    Array.Copy(primaryData, 0, data, 0, primaryData.Length);
                }
            }

            tileOffset += (int)levelOffset;

            byte[] tempResult = new byte[size];

            // check if data has enough memory for the requested, size, sometimes it does not (truncated to save memory)
            uint copySize = size;

            if (size + tileOffset >= data.Length)
            {
                copySize = (uint)(data.Length - tileOffset);
            }

            Array.Copy(data, tileOffset, tempResult, 0, copySize);
            data = tempResult;

            uint nBlockWidth;
            uint nBlockHeight;

            if (isTiled)
            {
                //
                // Untile texture
                //

                byte[] result = new byte[size];

                nBlockWidth  = alignedWidth / blockWidth;
                nBlockHeight = alignedHeight / blockHeight;
                for (int i = 0; i < nBlockHeight; i++)
                {
                    for (int j = 0; j < nBlockWidth; j++)
                    {
                        int  destinationIndex  = (int)(i * nBlockWidth + j);                                                     // offset in terms block
                        int  destinationOffset = (int)(destinationIndex * texelPitch);
                        uint tiledIndex        = XboxGraphics.XGAddress2DTiledOffset((uint)j, (uint)i, nBlockWidth, texelPitch); // returns offset in terms of block
                        uint tiledOffset       = tiledIndex * texelPitch;
                        Array.Copy(data, tiledOffset, result, destinationOffset, texelPitch);
                    }
                }
                data = result;
            }

            // find level size aligned to block size

            int levelWidth  = definition.Width >> level;
            int levelHeight = definition.Height >> level;

            if (levelWidth < 1)
            {
                levelWidth = 1;
            }
            if (levelHeight < 1)
            {
                levelHeight = 1;
            }

            if (levelWidth % blockWidth != 0)
            {
                levelWidth = (int)(levelWidth + blockWidth - levelWidth % blockWidth);
            }

            if (levelHeight % blockHeight != 0)
            {
                levelHeight = (int)(levelHeight + blockHeight - levelHeight % blockHeight);
            }

            byte[] finalData = new byte[levelWidth * levelHeight * bitsPerPixel >> 3];

            nBlockWidth  = (uint)(levelWidth / blockWidth);
            nBlockHeight = (uint)(levelHeight / blockHeight);

            uint sliceBlockWidth = alignedWidth / blockWidth;

            // skip these loops if the bitmap is already the proper format
            if (point.X != 0 || point.Y != 0 || finalData.Length != data.Length)
            {
                for (int i = 0; i < nBlockHeight; i++)
                {
                    for (int j = 0; j < nBlockWidth; j++)
                    {
                        uint offset     = (uint)(((i + point.Y) * sliceBlockWidth) + j + point.X) * texelPitch;
                        uint destOffset = (uint)((i * nBlockWidth) + j) * texelPitch;
                        Array.Copy(data, offset, finalData, destOffset, texelPitch);
                    }
                }
            }
            else
            {
                Array.Copy(data, 0, finalData, 0, data.Length);
            }

            XboxGraphics.XGEndianSwapSurface(d3dFormat, finalData);

            uint actualWidth  = (uint)definition.Width >> level;
            uint actualHeight = (uint)definition.Height >> level;

            if (actualWidth < 1)
            {
                actualWidth = 1;
            }
            if (actualHeight < 1)
            {
                actualHeight = 1;
            }
            bool requireDecompression = BitmapUtils.RequiresDecompression(BitmapUtils.GetEquivalentBitmapFormat(bitmap.Images[imageIndex].Format), (uint)definition.Width, (uint)definition.Height);

            finalData = BitmapUtils.ConvertXboxFormats(finalData, actualWidth, actualHeight, bitmap.Images[imageIndex].Format, requireDecompression);

            resultStream.Write(finalData, 0, finalData.Length);
        }
 protected Carto.Graphics.Bitmap CreateBitmap(string resource)
 {
     return(BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile(resource)));
 }
 public static Carto.Graphics.Bitmap CreateBitmap(Context context, int resource)
 {
     return(BitmapUtils.CreateBitmapFromAndroidBitmap(Android.Graphics.BitmapFactory.DecodeResource(context.Resources, resource)));
 }
Example #11
0
        public void UpdateData(Post post, Context context)
        {
            Post = post;
            if (post.NetLikes > 0)
            {
                _likes.Visibility = ViewStates.Visible;
                _likes.Text       = AppSettings.LocalizationManager.GetText(Post.NetLikes == 1 ? LocalizationKeys.Like : LocalizationKeys.Likes, post.NetLikes);
            }
            else
            {
                _likes.Visibility = ViewStates.Gone;
            }
            if (post.NetFlags > 0)
            {
                _flags.Visibility = _flagsIcon.Visibility = ViewStates.Visible;
                _flags.Text       = $"{post.NetFlags}";
            }
            else
            {
                _flags.Visibility = _flagsIcon.Visibility = ViewStates.Gone;
            }
            if (post.TotalPayoutReward > 0)
            {
                _cost.Visibility = ViewStates.Visible;
                _cost.Text       = BasePresenter.ToFormatedCurrencyString(post.TotalPayoutReward);
            }
            else
            {
                _cost.Visibility = ViewStates.Gone;
            }
            _time.Text   = post.Created.ToPostTime();
            _author.Text = post.Author;

            if (!string.IsNullOrEmpty(Post.Avatar))
            {
                Picasso.With(Context).Load(Post.Avatar).Placeholder(Resource.Drawable.ic_holder).Resize(300, 0).Priority(Picasso.Priority.Low).Into(_avatar, null, OnPicassoError);
            }
            else
            {
                Picasso.With(context).Load(Resource.Drawable.ic_holder).Into(_avatar);
            }

            ((PostPhotosPagerAdapter)_photosViewPager.Adapter).UpdateData(PhotoPagerType, Post);

            _topLikers.RemoveAllViews();
            var topLikersSize   = (int)BitmapUtils.DpToPixel(24, Context.Resources);
            var topLikersMargin = (int)BitmapUtils.DpToPixel(6, Context.Resources);

            for (int i = 0; i < Post.TopLikersAvatars.Length; i++)
            {
                var topLikersAvatar = new CircleImageView(Context)
                {
                    BorderColor = Color.White, BorderWidth = 3, FillColor = Color.White
                };
                var layoutParams = new LinearLayout.LayoutParams(topLikersSize, topLikersSize);
                if (i != 0)
                {
                    layoutParams.LeftMargin = -topLikersMargin;
                }
                _topLikers.AddView(topLikersAvatar, layoutParams);
                var avatarUrl = Post.TopLikersAvatars[i];
                if (!string.IsNullOrEmpty(avatarUrl))
                {
                    Picasso.With(Context).Load(avatarUrl).Placeholder(Resource.Drawable.ic_holder).Resize(240, 0).Priority(Picasso.Priority.Low).Into(topLikersAvatar, null,
                                                                                                                                                      () =>
                    {
                        Picasso.With(context).Load(Resource.Drawable.ic_holder).Into(topLikersAvatar);
                    });
                }
                else
                {
                    Picasso.With(context).Load(Resource.Drawable.ic_holder).Into(topLikersAvatar);
                }
            }

            _title.UpdateText(Post, TagToExclude, TagFormat, MaxLines, Post.IsExpanded || PhotoPagerType == PostPagerType.PostScreen);

            _commentSubtitle.Text = post.Children == 0
                ? AppSettings.LocalizationManager.GetText(LocalizationKeys.PostFirstComment)
                : post.Children == 1
                    ? AppSettings.LocalizationManager.GetText(LocalizationKeys.SeeComment)
                    : AppSettings.LocalizationManager.GetText(LocalizationKeys.ViewComments, post.Children);

            if (_isAnimationRuning && !post.VoteChanging)
            {
                _isAnimationRuning = false;
                _likeOrFlag.ScaleX = 1f;
                _likeOrFlag.ScaleY = 1f;
            }
            if (!BasePostPresenter.IsEnableVote)
            {
                if (post.VoteChanging && !_isAnimationRuning)
                {
                    LikeSet(false);
                }
                else if (post.FlagChanging)
                {
                    LikeSet(true);
                }
            }
            else
            {
                if (post.Vote || !post.Flag)
                {
                    _likeOrFlag.SetImageResource(post.Vote
                        ? Resource.Drawable.ic_new_like_filled
                        : Resource.Drawable.ic_new_like_selected);
                }
                else
                {
                    _likeOrFlag.SetImageResource(Resource.Drawable.ic_flag_active);
                }
            }

            _pagerTabLayout.Visibility = post.Media.Length > 1 ? ViewStates.Visible : ViewStates.Gone;

            SetNsfwMaskLayout();

            if (Post.Flag && !Post.FlagNotificationWasShown)
            {
                NsfwMask.Visibility             = ViewStates.Visible;
                _nsfwMaskCloseButton.Visibility = ViewStates.Visible;
                _nsfwMaskMessage.Text           = AppSettings.LocalizationManager.GetText(LocalizationKeys.FlagMessage);
                NsfwMaskSubMessage.Text         = AppSettings.LocalizationManager.GetText(LocalizationKeys.FlagSubMessage);
                _nsfwMaskActionButton.Text      = AppSettings.LocalizationManager.GetText(LocalizationKeys.UnFlagPost);
            }
            else if (Post.ShowMask && (Post.IsLowRated || Post.IsNsfw))
            {
                NsfwMask.Visibility        = ViewStates.Visible;
                _nsfwMaskMessage.Text      = AppSettings.LocalizationManager.GetText(Post.IsLowRated ? LocalizationKeys.LowRatedContent : LocalizationKeys.NsfwContent);
                NsfwMaskSubMessage.Text    = AppSettings.LocalizationManager.GetText(Post.IsLowRated ? LocalizationKeys.LowRatedContentExplanation : LocalizationKeys.NsfwContentExplanation);
                _nsfwMaskActionButton.Text = AppSettings.LocalizationManager.GetText(LocalizationKeys.NsfwShow);
            }
            else
            {
                NsfwMask.Visibility = _nsfwMaskCloseButton.Visibility = ViewStates.Gone;
            }
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            AddOnlineBaseLayer(CartoBaseMapStyle.CartoBasemapStyleGray);

            Projection projection = BaseProjection;

            // Initialize an local vector data source
            LocalVectorDataSource source = new LocalVectorDataSource(projection);

            // Initialize a vector layer with the previous data source
            VectorLayer vectorLayer = new VectorLayer(source);

            // Add the previous vector layer to the map
            MapView.Layers.Add(vectorLayer);

            // Set visible zoom range for the vector layer
            vectorLayer.VisibleZoomRange = new MapRange(10, 24);

            // Add a bunch of vector elements
            // As elements can be shared across platforms, they are in a shared project

            Overlays.AddPoint1(source, projection);
            Overlays.AddPoint2(source, projection);

            Overlays.AddOverlyingLines(MapView, source, projection);

            Overlays.Add2DPolygon(source, projection);

            Overlays.AddText1(source, projection);
            Overlays.AddText2(source, projection);
            Overlays.AddText3(source, projection);

            Bitmap info   = BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile("icons/info.png"));
            Bitmap arrow  = BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile("icons/arrow.png"));
            Bitmap marker = BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile("icons/marker.png"));

            Overlays.AddBalloonPopup1(source, projection, info, arrow);
            Overlays.AddBalloonPopup2(source, projection, info, arrow, marker);
            Overlays.AddBalloonPopup3(source, projection);

            Overlays.Add3DCar(source, projection);
            Overlays.Add3DPolygon(source, projection);

            // Animate map to Tallinn where the objects are
            MapView.SetFocusPos(projection.FromWgs84(new MapPos(24.662893, 59.419365)), 1);
            MapView.SetZoom(12, 1);

            // Add maplistener to detect click on model

            listener = new VectorElementListener(source);
            for (int i = 0; i < MapView.Layers.Count; i++)
            {
                Layer layer = MapView.Layers[i];

                if (layer is VectorLayer)
                {
                    (layer as VectorLayer).VectorElementEventListener = listener;
                }
            }
        }
        private void SetProfileChart(int size)
        {
            var votingPowerFrame = new VotingPowerFrame(this)
            {
                Draw             = true,
                VotingPower      = Presenter.UserProfileResponse == null ? 0 : (float)Presenter.UserProfileResponse.VotingPower,
                VotingPowerWidth = BitmapUtils.DpToPixel(3, Resources)
            };
            var padding = (int)BitmapUtils.DpToPixel(7, Resources);

            votingPowerFrame.Layout(0, 0, size, size);
            var avatar = new CircleImageView(this);

            avatar.Layout(padding, padding, size - padding, size - padding);
            avatar.SetImageResource(Resource.Drawable.ic_holder);
            votingPowerFrame.AddView(avatar);

            var profileTab = _tabLayout.GetTabAt(_tabLayout.TabCount - 1);

            if (!string.IsNullOrEmpty(Presenter.UserProfileResponse?.ProfileImage))
            {
                Picasso.With(this).Load(Presenter.UserProfileResponse.ProfileImage).NoFade().Resize(size, size)
                .Placeholder(Resource.Drawable.ic_holder).Into(avatar,
                                                               () => { profileTab.SetIcon(BitmapUtils.GetViewDrawable(votingPowerFrame)); }, null);
            }
            else
            {
                profileTab.SetIcon(BitmapUtils.GetViewDrawable(votingPowerFrame));
            }
        }
Example #14
0
        /// <summary>
        /// Returns a byte[] containing the converted image data from the cache.
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="bitmapTag"></param>
        /// <param name="index"></param>
        /// <param name="version"></param>
        /// <returns></returns>
        public static BaseBitmap ConvertGen3Bitmap(CacheFile cache, Bitmap bitmapTag, int index, CacheVersion version)
        {
            if (cache.ResourceLayoutTable == null || cache.ResourceGestalt == null)
            {
                cache.LoadResourceTags();
            }

            byte[]     imageData  = null;
            byte[]     mipMapData = null;
            XboxBitmap xboxBitmap = null;
            int        bitmapSize = 0;
            int        mipMapSize = 0;

            var image  = bitmapTag.Images[index];
            var handle = GetBitmapResourceHandle(bitmapTag, index, version);

            if (!ResourceEntryValid(cache, handle) || (!HasPrimaryResource(cache, handle) && !HasSecondaryResource(cache, handle)))
            {
                Console.WriteLine($"Invalid resource entry at {handle}. No data to convert.");
                return(null);
            }


            // interleaved means two images are inside a single resource along with the mipmaps.
            if (image.XboxFlags.HasFlag(BitmapFlagsXbox.UseInterleavedTextures))
            {
                var resourceDef = GetInterleavedResourceDefinition(cache, handle);
                xboxBitmap = new XboxBitmap(resourceDef, image.InterleavedTextureIndex2, image);
                bitmapSize = BitmapUtils.GetXboxImageSize(xboxBitmap);
                mipMapSize = 0;

                xboxBitmap.Offset = 0;

                if (!xboxBitmap.InTile)
                {
                    var offset = image.InterleavedTextureIndex2 * (int)(xboxBitmap.VirtualHeight * xboxBitmap.VirtualWidth / xboxBitmap.CompressionFactor);
                    imageData  = cache.GetSecondaryResource(handle, bitmapSize, offset, true);
                    mipMapData = null;
                }
                else
                {
                    if (xboxBitmap.Type == BitmapType.CubeMap && image.Flags.HasFlag(BitmapFlags.Compressed) && xboxBitmap.Width <= 16)
                    {
                        xboxBitmap.Offset = (int)(16 * 4 / xboxBitmap.CompressionFactor);   // account for the mipmaps
                    }
                    imageData  = cache.GetPrimaryResource(handle, bitmapSize, 0, true);
                    mipMapData = null;
                }

                if (image.InterleavedTextureIndex2 == 1 && xboxBitmap.InTile)
                {
                    byte[] totalData = null;
                    var    tileSize  = (int)(xboxBitmap.MinimalBitmapSize * xboxBitmap.MinimalBitmapSize / xboxBitmap.CompressionFactor);
                    var    subCount  = 0;
                    switch (xboxBitmap.Type)
                    {
                    case BitmapType.Texture2D:
                        subCount = 1;
                        break;

                    case BitmapType.Texture3D:
                    case BitmapType.Array:
                        subCount = xboxBitmap.Depth;
                        break;

                    case BitmapType.CubeMap:
                        subCount = 6;
                        break;
                    }
                    if (mipMapData != null)
                    {
                        totalData = new byte[bitmapSize + mipMapSize];
                        Array.Copy(imageData, 0, totalData, 0, bitmapSize);
                        Array.Copy(mipMapData, 0, totalData, bitmapSize, mipMapSize);
                    }
                    else
                    {
                        totalData = imageData;
                    }

                    for (int i = 0; i < subCount; i++)
                    {
                        // make sure to copy the right amount of data
                        var copySize = tileSize;
                        if (copySize > totalData.Length - ((tileSize * i) + tileSize / 2))
                        {
                            copySize = totalData.Length - ((tileSize * i) + tileSize / 2);
                        }
                        Array.Copy(totalData, (tileSize * i) + tileSize / 2, imageData, (tileSize * i), copySize);
                    }
                }
            }
            else
            {
                var resourceDef = GetResourceDefinition(cache, handle);
                xboxBitmap = new XboxBitmap(resourceDef, image);
                bitmapSize = BitmapUtils.GetXboxImageSize(xboxBitmap);

                if (HasSecondaryResource(cache, handle))
                {
                    imageData = cache.GetSecondaryResource(handle, bitmapSize, 0, true);

                    if (xboxBitmap.MipMapCount > 0)
                    {
                        if (HasPrimaryResource(cache, handle))
                        {
                            // dedicated resource for mipmaps
                            mipMapData = cache.GetPrimaryResource(handle, mipMapSize, 0, true);
                        }
                        else
                        {
                            //throw new Exception($"Unsupported layout. Compute bitmap offset for weird bitmap.");
                            mipMapData = null;
                        }
                    }
                    else
                    {
                        mipMapData = null;
                    }
                }
                else
                {
                    // Bitmap doesn't have a secondary resource means either no mipmaps or everything is packed in the primary resource.
                    if (xboxBitmap.MipMapCount > 0)
                    {
                        imageData  = cache.GetPrimaryResource(handle, 2 * bitmapSize, 0, true);
                        mipMapData = cache.GetPrimaryResource(handle, mipMapSize, 0, true);

                        // Formula seems quite complex, small hack to make it work
                        if (xboxBitmap.BlockDimension == 4)
                        {
                            if (xboxBitmap.Width > xboxBitmap.Height)
                            {
                                xboxBitmap.Offset = 4 * (int)(BitmapUtils.RoundSize(xboxBitmap.Height, 4) * xboxBitmap.VirtualWidth / xboxBitmap.CompressionFactor);
                            }
                            else if (xboxBitmap.Width == xboxBitmap.Height)
                            {
                                var width = xboxBitmap.Width;
                                if (xboxBitmap.Width >= 4)
                                {
                                    width = 4;
                                }
                                xboxBitmap.Offset = 4 * (int)(width * 4 / xboxBitmap.CompressionFactor);
                            }
                            else
                            {
                                var width = xboxBitmap.Width / 2;
                                if (width == 0)
                                {
                                    width = 1;
                                }
                                xboxBitmap.Offset = 4 * (int)(BitmapUtils.RoundSize(width, 4) * xboxBitmap.BlockDimension / xboxBitmap.CompressionFactor);
                            }
                        }
                        else
                        {
                            xboxBitmap.Offset = (int)(xboxBitmap.Width * 4 / xboxBitmap.CompressionFactor);
                            Console.WriteLine("WEIRD BITMAP");
                        }
                    }
                    else
                    {
                        imageData  = cache.GetPrimaryResource(handle, bitmapSize, 0, true);
                        mipMapData = null;
                    }
                }
            }

            //
            // Convert main bitmap
            //

            List <XboxBitmap> xboxBitmaps = ParseImages(xboxBitmap, image, imageData, bitmapSize);
            bool flipImage = true;

            // rearrange cubemaps order
            if (xboxBitmap.Type == BitmapType.CubeMap)
            {
                XboxBitmap temp = xboxBitmaps[1];
                xboxBitmaps[1] = xboxBitmaps[2];
                xboxBitmaps[2] = temp;
            }

            List <BaseBitmap> finalBitmaps = new List <BaseBitmap>();

            foreach (var bitmap in xboxBitmaps)
            {
                // extract bitmap from padded image
                BaseBitmap finalBitmap = ExtractImage(bitmap);
                // convert to PC format
                flipImage = ConvertImage(finalBitmap);
                // flip data if required
                if (flipImage)
                {
                    FlipImage(finalBitmap, image);
                }
                // until I write code to move mipmaps at the end of the file, remove cubemap mipmaps
                if (xboxBitmap.Type == BitmapType.CubeMap)
                {
                    finalBitmap.MipMapCount = 0;
                }
                // generate mipmaps for uncompressed textures
                if (!finalBitmap.Flags.HasFlag(BitmapFlags.Compressed) && finalBitmap.MipMapCount > 0)
                {
                    GenerateUncompressedMipMaps(finalBitmap);
                }

                finalBitmaps.Add(finalBitmap);
            }
            // build and return the final bitmap
            return(RebuildBitmap(finalBitmaps));
        }
Example #15
0
        public override void OnViewCreated(View view, Bundle savedInstanceState)
        {
            if (!IsInitialized)
            {
                base.OnViewCreated(view, savedInstanceState);

                Presenter.SourceChanged += PresenterSourceChanged;
                _adapter                = new FeedAdapter <FeedPresenter>(Context, Presenter);
                _adapter.LikeAction    += LikeAction;
                _adapter.UserAction    += UserAction;
                _adapter.CommentAction += CommentAction;
                _adapter.VotersClick   += VotersAction;
                _adapter.PhotoClick    += FeedPhotoClick;
                _adapter.FlagAction    += FlagAction;
                _adapter.HideAction    += HideAction;
                _adapter.TagAction     += TagAction;

                _postPagerAdapter                = new PostPagerAdapter <FeedPresenter>(Context, Presenter);
                _postPagerAdapter.LikeAction    += LikeAction;
                _postPagerAdapter.UserAction    += UserAction;
                _postPagerAdapter.CommentAction += CommentAction;
                _postPagerAdapter.VotersClick   += VotersAction;
                _postPagerAdapter.PhotoClick    += PhotoClick;
                _postPagerAdapter.FlagAction    += FlagAction;
                _postPagerAdapter.HideAction    += HideAction;
                _postPagerAdapter.DeleteAction  += DeleteAction;
                _postPagerAdapter.TagAction     += TagAction;
                _postPagerAdapter.CloseAction   += CloseAction;

                _logo.Click            += OnLogoClick;
                _toolbar.OffsetChanged += OnToolbarOffsetChanged;

                _scrollListner = new ScrollListener();
                _scrollListner.ScrolledToBottom += LoadPosts;

                _refresher.Refresh += OnRefresh;

                _feedList.SetAdapter(_adapter);
                _feedList.SetLayoutManager(new LinearLayoutManager(Android.App.Application.Context));
                _feedList.AddOnScrollListener(_scrollListner);

                _postPager.SetClipToPadding(false);
                var pagePadding = (int)BitmapUtils.DpToPixel(20, Resources);
                _postPager.SetPadding(pagePadding, 0, pagePadding, 0);
                _postPager.PageMargin              = pagePadding / 2;
                _postPager.PageScrollStateChanged += PostPagerOnPageScrollStateChanged;
                _postPager.PageScrolled           += PostPagerOnPageScrolled;
                _postPager.Adapter = _postPagerAdapter;
                _postPager.SetPageTransformer(false, _postPagerAdapter, (int)LayerType.None);

                _emptyQueryLabel.Typeface = Style.Light;
                _emptyQueryLabel.Text     = Localization.Texts.EmptyQuery;

                LoadPosts();
            }

            var postUrl = Activity?.Intent?.GetStringExtra(CommentsFragment.ResultString);

            if (!string.IsNullOrWhiteSpace(postUrl))
            {
                var count = Activity.Intent.GetIntExtra(CommentsFragment.CountString, 0);
                Activity.Intent.RemoveExtra(CommentsFragment.ResultString);
                Activity.Intent.RemoveExtra(CommentsFragment.CountString);
                var post = Presenter.FirstOrDefault(p => p.Url == postUrl);
                post.Children += count;
                _adapter.NotifyDataSetChanged();
            }
        }
Example #16
0
        protected void RunFile(bool runTestsViewOut, string pspAutoTestsFolder, string fileNameExecutable,
                               string fileNameExpected, string fileNameBase)
        {
            ConsoleUtils.SaveRestoreConsoleColor(ConsoleColor.DarkCyan,
                                                 () => { Console.Write("{0}...", fileNameExecutable); });
            var expectedOutput = File.ReadAllText(fileNameExpected, Encoding.ASCII);
            var realOutput     = "";
            var capturedOutput = "";

            // Execute.
            {
                realOutput = RunExecutableAndGetOutput(runTestsViewOut, pspAutoTestsFolder, fileNameExecutable,
                                                       out capturedOutput, fileNameBase);
            }

            var expectedOutputLines = expectedOutput.Trim().Replace("\r\n", "\n").Split('\n');
            var realOutputLines     = realOutput.Trim().Replace("\r\n", "\n").Split('\n');
            var result = Diff.DiffTextProcessed(expectedOutputLines, realOutputLines);

            File.WriteAllText(
                Path.ChangeExtension(fileNameExpected, ".lastoutput"),
                realOutput
                );

            File.WriteAllText(
                Path.ChangeExtension(fileNameExpected, ".lastdebug"),
                capturedOutput
                );

            var hadAnError = false;

            for (var n = 0; n < 10; n++)
            {
                var imageReferenceFile = $"{fileNameBase}.reference.{n}.png";
                var imageOutputFile    = $"{fileNameBase}.lastoutput.{n}.png";
                if (File.Exists(imageReferenceFile))
                {
                    if (File.Exists(imageOutputFile))
                    {
                        var referenceBitmap = new Bitmap(imageReferenceFile);
                        var outputBitmap    = new Bitmap(imageOutputFile);
                        if (referenceBitmap.Size == outputBitmap.Size)
                        {
                            var compareResult = BitmapUtils.CompareBitmaps(referenceBitmap, outputBitmap, 0.01);

                            if (compareResult.Equal)
                            {
                                Console.Error.WriteLine(
                                    "Files '{0}:{1}' and '{2}:{3}' have different contents {4}/{5} different pixels {6}%",
                                    imageReferenceFile, referenceBitmap.Size, imageOutputFile, outputBitmap.Size,
                                    compareResult.DifferentPixelCount, compareResult.TotalPixelCount,
                                    compareResult.PixelTotalDifferencePercentage
                                    );
                                hadAnError = true;
                            }
                        }
                        else
                        {
                            Console.Error.WriteLine(
                                "Files '{0}:{1}' and '{2}:{3}' have different sizes",
                                imageReferenceFile, referenceBitmap.Size, imageOutputFile, outputBitmap.Size
                                );
                            hadAnError = true;
                        }
                    }
                    else
                    {
                        Console.Error.WriteLine(
                            "File '{0}' exists, but not exists '{1}'",
                            imageReferenceFile, imageOutputFile
                            );
                        hadAnError = true;
                    }
                }
            }

            if (result.Items.Any(item => item.Action != Diff.ProcessedItem.ActionEnum.Keep))
            {
                hadAnError = true;
            }

            if (!hadAnError)
            {
                ConsoleUtils.SaveRestoreConsoleColor(ConsoleColor.Green, () => { Console.WriteLine("Ok"); });
            }
            else
            {
                ConsoleUtils.SaveRestoreConsoleColor(ConsoleColor.Red, () => { Console.WriteLine("Error"); });
                result.Print(avoidKeep: true);
            }

            File.WriteAllText(
                Path.ChangeExtension(fileNameExpected, ".lastdiff"),
                result.ToString()
                );
        }
 public Bitmap Apply(Bitmap bitmap)
 {
     return(BitmapUtils.Corrode(bitmap));
 }
Example #18
0
 protected Carto.Graphics.Bitmap CreateBitmap(int resource)
 {
     return(BitmapUtils.CreateBitmapFromAndroidBitmap(Android.Graphics.BitmapFactory.DecodeResource(Resources, resource)));
 }
Example #19
0
        protected override void OnCreate(Android.OS.Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            /// Set online base layer
            var baseLayer = new NutiteqOnlineVectorTileLayer("nutibright-v2a.zip");

            mapView.Layers.Add(baseLayer);


            // create PackageManager instance for dealing with offline packages
            var packageFolder = new File(GetExternalFilesDir(null), "routingpackages");

            if (!(packageFolder.Mkdirs() || packageFolder.IsDirectory))
            {
                Log.Fatal("Could not create package folder!");
            }

            packageManager = new NutiteqPackageManager(ROUTING_PACKAGEMANAGER_SOURCE, packageFolder.AbsolutePath);
            packageManager.PackageManagerListener = new RoutingPackageListener(this);
            packageManager.Start();

            // fetch list of available packages from server. Note that this is asynchronous operation and listener will be notified via onPackageListUpdated when this succeeds.
            packageManager.StartPackageListDownload();

            // create offline routing service connected to package manager
            offlineRoutingService = new PackageManagerRoutingService(packageManager);

            // create additional online routing service that will be used when offline package is not yet downloaded or offline routing fails
            onlineRoutingService = new NutiteqOnlineRoutingService(ROUTING_SERVICE_SOURCE);

            // define layer and datasource for route line and instructions
            routeDataSource = new LocalVectorDataSource(baseProjection);
            VectorLayer routeLayer = new VectorLayer(routeDataSource);

            mapView.Layers.Add(routeLayer);


            // define layer and datasource for route start and stop markers
            routeStartStopDataSource = new LocalVectorDataSource(baseProjection);
            // Initialize a vector layer with the previous data source
            VectorLayer vectorLayer = new VectorLayer(routeStartStopDataSource);

            // Add the previous vector layer to the map
            mapView.Layers.Add(vectorLayer);
            // Set visible zoom range for the vector layer
            vectorLayer.VisibleZoomRange = new MapRange(0, 22);


            // set route listener
            RouteMapEventListener mapListener = new RouteMapEventListener(this);

            mapView.MapEventListener = mapListener;

            // create markers for start & end, and a layer for them
            MarkerStyleBuilder markerStyleBuilder = new MarkerStyleBuilder();

            markerStyleBuilder.Bitmap = BitmapUtils
                                        .CreateBitmapFromAndroidBitmap(BitmapFactory.DecodeResource(
                                                                           Resources, Resource.Drawable.olmarker));
            markerStyleBuilder.HideIfOverlapped = false;
            markerStyleBuilder.Size             = 30;

            markerStyleBuilder.Color = new Nutiteq.Graphics.Color(Android.Graphics.Color.Green);

            startMarker         = new Marker(new MapPos(0, 0), markerStyleBuilder.BuildStyle());
            startMarker.Visible = false;


            markerStyleBuilder.Color = new Nutiteq.Graphics.Color(Android.Graphics.Color.Red);

            stopMarker         = new Marker(new MapPos(0, 0), markerStyleBuilder.BuildStyle());
            stopMarker.Visible = false;

            routeStartStopDataSource.Add(startMarker);
            routeStartStopDataSource.Add(stopMarker);

            markerStyleBuilder.Color  = new Nutiteq.Graphics.Color(Android.Graphics.Color.White);
            markerStyleBuilder.Bitmap = BitmapUtils
                                        .CreateBitmapFromAndroidBitmap(BitmapFactory.DecodeResource(
                                                                           Resources, Resource.Drawable.direction_up));
            instructionUp = markerStyleBuilder.BuildStyle();

            markerStyleBuilder.Bitmap = BitmapUtils
                                        .CreateBitmapFromAndroidBitmap(BitmapFactory.DecodeResource(
                                                                           Resources, Resource.Drawable.direction_upthenleft));
            instructionLeft = markerStyleBuilder.BuildStyle();

            markerStyleBuilder.Bitmap = BitmapUtils
                                        .CreateBitmapFromAndroidBitmap(BitmapFactory.DecodeResource(
                                                                           Resources, Resource.Drawable.direction_upthenright));

            instructionRight = markerStyleBuilder.BuildStyle();

            // style for instruction balloons
            balloonPopupStyleBuilder = new BalloonPopupStyleBuilder();
            balloonPopupStyleBuilder.TitleMargins = new BalloonPopupMargins(4, 4, 4, 4);

            // finally animate map to Estonia
            mapView.FocusPos = baseProjection.FromWgs84(new MapPos(25.662893, 58.919365));
            mapView.Zoom     = 7;

            Toast.MakeText(ApplicationContext, "Long-press on map to set route start and finish", ToastLength.Long).Show();
        }
        public override void OnViewCreated(View view, Bundle savedInstanceState)
        {
            if (IsInitialized)
            {
                return;
            }

            base.OnViewCreated(view, savedInstanceState);

            _tag.Hint         = AppSettings.LocalizationManager.GetText(LocalizationKeys.AddHashtag);
            _title.Hint       = AppSettings.LocalizationManager.GetText(LocalizationKeys.EnterPostTitle);
            _description.Hint = AppSettings.LocalizationManager.GetText(LocalizationKeys.EnterPostDescription);
            _postButton.Text  = AppSettings.LocalizationManager.GetText(LocalizationKeys.PublishButtonText);
            _pageTitle.Text   = AppSettings.LocalizationManager.GetText(LocalizationKeys.PostSettings);

            _pageTitle.Typeface   = Style.Semibold;
            _title.Typeface       = Style.Regular;
            _description.Typeface = Style.Regular;
            _postButton.Typeface  = Style.Semibold;

            _postButton.Click  += OnPost;
            _postButton.Enabled = true;

            _topPanel.BringToFront();

            _localTagsList.SetLayoutManager(new LinearLayoutManager(Activity, LinearLayoutManager.Horizontal, false));
            LocalTagsAdapter.Click += LocalTagsAdapterClick;
            _localTagsList.SetAdapter(LocalTagsAdapter);
            _localTagsList.AddItemDecoration(new ListItemDecoration((int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 15, Resources.DisplayMetrics)));

            _tagsList.SetLayoutManager(new LinearLayoutManager(Activity));
            Presenter.SourceChanged += PresenterSourceChanged;
            TagsAdapter.Click       += OnTagsAdapterClick;
            _tagsList.SetAdapter(TagsAdapter);

            _tag.TextChanged       += OnTagOnTextChanged;
            _tag.KeyboardDownEvent += HideTagsList;
            _tag.OkKeyEvent        += HideTagsList;
            _tag.FocusChange       += OnTagOnFocusChange;

            _topMarginTagsLayout.Click += OnTagsLayoutClick;
            _backButton.Click          += OnBack;
            _rootLayout.Click          += OnRootLayoutClick;

            _timer = new Timer(OnTimer);
            _model = new PreparePostModel(BasePresenter.User.UserInfo);
            SetPostingTimer();

            if (_editPost != null)
            {
                SetEditPost();
            }

            if (_media?.Count > 1 || _editPost?.Media.Length > 1)
            {
                _photos.Visibility           = ViewStates.Visible;
                _previewContainer.Visibility = ViewStates.Gone;
                _photos.SetLayoutManager(new LinearLayoutManager(Activity, LinearLayoutManager.Horizontal, false));
                _photos.SetAdapter(GalleryAdapter);
                _photos.AddItemDecoration(new ListItemDecoration((int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 10, Resources.DisplayMetrics)));
            }
            else
            {
                _photos.Visibility           = ViewStates.Gone;
                _previewContainer.Visibility = ViewStates.Visible;
                var margin       = (int)BitmapUtils.DpToPixel(15, Resources);
                var layoutParams = new RelativeLayout.LayoutParams(Resources.DisplayMetrics.WidthPixels - margin * 2, Resources.DisplayMetrics.WidthPixels - margin * 2);
                layoutParams.SetMargins(margin, 0, margin, margin);
                _previewContainer.LayoutParameters = layoutParams;
                _preview.CornerRadius = BitmapUtils.DpToPixel(5, Resources);
                if (_media != null)
                {
                    _preview.SetImageUri(Uri.Parse(_media[0].Path), _media[0].Parameters);
                }
                else if (_editPost != null)
                {
                    _ratioBtn.Visibility = _rotateBtn.Visibility = ViewStates.Gone;
                    var url = _editPost.Media[0].Thumbnails.Mini;
                    Picasso.With(Activity).Load(url)
                    .Resize(_previewContainer.LayoutParameters.Width, _previewContainer.LayoutParameters.Height)
                    .Into(_preview);
                }
                _preview.Touch   += PreviewOnTouch;
                _ratioBtn.Click  += RatioBtnOnClick;
                _rotateBtn.Click += RotateBtnOnClick;
            }

            SearchTextChanged();
        }
Example #21
0
        private static void GenerateCompressedMipMaps(BaseBitmap bitmap)
        {
            string tempBitmap = $@"Temp\{Guid.NewGuid().ToString()}.dds";

            if (!Directory.Exists(@"Temp"))
            {
                Directory.CreateDirectory(@"Temp");
            }

            //Write input dds
            bitmap.MipMapCount = 0;
            var header = new DDSHeader(bitmap);


            using (var outStream = File.Open(tempBitmap, FileMode.Create, FileAccess.Write))
            {
                header.Write(new EndianWriter(outStream));
                var dataStream = new MemoryStream(bitmap.Data);
                StreamUtil.Copy(dataStream, outStream, bitmap.Data.Length);
            }

            string args = " ";

            switch (bitmap.Format)
            {
            case BitmapFormat.Dxn:
                args += "-bc5 -resize -normal";
                break;

            case BitmapFormat.Dxt1:
                args += "-bc1 ";
                break;

            case BitmapFormat.Dxt3:
                args += "-bc2 ";
                break;

            case BitmapFormat.Dxt5:
                args += "-bc3 ";
                break;

            default:
                bitmap.MipMapCount = 0;
                if (File.Exists(tempBitmap))
                {
                    File.Delete(tempBitmap);
                }
                return;
            }

            args += $"{tempBitmap} {tempBitmap}";

            ProcessStartInfo info = new ProcessStartInfo(@"Tools\nvcompress.exe")
            {
                Arguments              = args,
                CreateNoWindow         = true,
                WindowStyle            = ProcessWindowStyle.Hidden,
                UseShellExecute        = false,
                RedirectStandardError  = false,
                RedirectStandardOutput = false,
                RedirectStandardInput  = false
            };
            Process nvcompress = Process.Start(info);

            nvcompress.WaitForExit();

            byte[] result;
            using (var ddsStream = File.OpenRead(tempBitmap))
            {
                header.Read(new EndianReader(ddsStream));
                var dataSize = (int)(ddsStream.Length - ddsStream.Position);

                int mipMapCount = header.MipMapCount - 1;

                bitmap.Width  = header.Width;
                bitmap.Height = header.Height;

                // Remove lowest DXN mipmaps to prevent issues with D3D memory allocation.
                if (bitmap.Format == BitmapFormat.Dxn)
                {
                    dataSize = BitmapUtils.RoundSize(bitmap.Width, 4) * BitmapUtils.RoundSize(bitmap.Height, 4);
                    if (mipMapCount > 0)
                    {
                        if (bitmap.Format == BitmapFormat.Dxn)
                        {
                            var width  = bitmap.Width;
                            var height = bitmap.Height;

                            dataSize = BitmapUtils.RoundSize(width, 4) * BitmapUtils.RoundSize(height, 4);

                            mipMapCount = 0;
                            while ((width >= 8) && (height >= 8))
                            {
                                width    /= 2;
                                height   /= 2;
                                dataSize += BitmapUtils.RoundSize(width, 4) * BitmapUtils.RoundSize(height, 4);
                                mipMapCount++;
                            }
                        }
                    }
                }
                bitmap.MipMapCount = mipMapCount;
                byte[] raw = new byte[dataSize];
                ddsStream.Read(raw, 0, dataSize);
                result      = raw;
                bitmap.Data = result;
            }

            if (File.Exists(tempBitmap))
            {
                File.Delete(tempBitmap);
            }
        }
Example #22
0
 private void OnToolbarOffsetChanged(object sender, AppBarLayout.OffsetChangedEventArgs e)
 {
     ViewCompat.SetElevation(_toolbar, BitmapUtils.DpToPixel(2, Resources));
 }
 public Bitmap Apply(Bitmap bitmap)
 {
     return(BitmapUtils.Binarization(bitmap, Threshold));
 }
Example #24
0
 public static Bitmap CreateBitmap(string resource)
 {
     return(BitmapUtils.CreateBitmapFromUIImage(UIImage.FromFile(resource)));
 }
Example #25
0
        public void Export(TileModel model, TilePropagator propagator, string filename, DeBroglieConfig config, ExportOptions exportOptions)
        {
            if (config.Animate)
            {
                if (exportOptions is BitmapExportOptions)
                {
                    var topoArray = propagator.ToWeightedArraySets().Map(WeightedColorAverage);
                    var bitmap    = BitmapUtils.ToBitmap(topoArray.ToArray2d());
                    bitmap.Save(filename);
                }
                else if (exportOptions is BitmapSetExportOptions bseo)
                {
                    var topoArray    = propagator.ToWeightedArraySets();
                    var tileTopology = topoArray.Topology.AsGridTopology().WithSize(bseo.TileWidth, bseo.TileHeight, 1);
                    var subTiles     = bseo.Bitmaps.ToDictionary(x => x.Key, x => TopoArray.Create(BitmapUtils.ToColorArray(x.Value), tileTopology).Map(c => new Tile(c)));
                    var exploded     = MoreTopoArrayUtils.ExplodeWeightedTiles(topoArray, subTiles, bseo.TileWidth, bseo.TileHeight, 1).Map(WeightedColorAverage);
                    var bitmap       = BitmapUtils.ToBitmap(exploded.ToArray2d());
                    bitmap.Save(filename);
                }
                else
                {
                    throw new System.Exception($"Cannot export from {exportOptions.TypeDescription} to bitmap.");
                }
            }
            else
            {
                if (exportOptions is BitmapExportOptions)
                {
                    var topoArray = propagator.ToValueArray(Rgba32.Gray, Rgba32.Magenta);
                    var bitmap    = BitmapUtils.ToBitmap(topoArray.ToArray2d());
                    bitmap.Save(filename);
                }
                else if (exportOptions is BitmapSetExportOptions bseo)
                {
                    var undecided     = new Tile(new object());
                    var contradiction = new Tile(new object());
                    var topoArray     = propagator.ToArray(undecided, contradiction);

                    var tileTopology = topoArray.Topology.AsGridTopology().WithSize(bseo.TileWidth, bseo.TileHeight, 1);
                    var subTiles     = bseo.Bitmaps.ToDictionary(x => x.Key, x => TopoArray.Create(BitmapUtils.ToColorArray(x.Value), tileTopology));
                    subTiles[undecided]     = TopoArray.FromConstant(Rgba32.Gray, tileTopology);
                    subTiles[contradiction] = TopoArray.FromConstant(Rgba32.Magenta, tileTopology);

                    var exploded = MoreTopoArrayUtils.ExplodeTiles(topoArray, subTiles, bseo.TileWidth, bseo.TileHeight, 1);
                    var bitmap   = BitmapUtils.ToBitmap(exploded.ToArray2d());
                    bitmap.Save(filename);
                }
                else
                {
                    throw new System.Exception($"Cannot export from {exportOptions.TypeDescription} to bitmap.");
                }
            }
        }
Example #26
0
        public Texture Get(TextureStateStruct *TextureState, ClutStateStruct *ClutState)
        {
            Texture Texture;
            //GC.Collect();
            bool Swizzled       = TextureState->Swizzled;
            uint TextureAddress = TextureState->Mipmap0.Address;
            uint ClutAddress    = ClutState->Address;
            var  ClutFormat     = ClutState->PixelFormat;
            var  ClutStart      = ClutState->Start;
            var  ClutDataStart  = PixelFormatDecoder.GetPixelsSize(ClutFormat, ClutStart);

            ulong Hash1   = TextureAddress | (ulong)((ClutAddress + ClutDataStart) << 32);
            bool  Recheck = false;

            if (Cache.TryGetValue(Hash1, out Texture))
            {
                if (Texture.RecheckTimestamp != RecheckTimestamp)
                {
                    Recheck = true;
                }
            }
            else
            {
                Recheck = true;
            }

            if (Recheck)
            {
                //Console.Write(".");

                //Console.WriteLine("{0:X}", ClutAddress);
                var TexturePointer = (byte *)PspMemory.PspAddressToPointerSafe(TextureAddress);
                var ClutPointer    = (byte *)PspMemory.PspAddressToPointerSafe(ClutAddress);
                var TextureFormat  = TextureState->PixelFormat;
                //var Width = TextureState->Mipmap0.TextureWidth;
                int BufferWidth     = TextureState->Mipmap0.BufferWidth;
                var Height          = TextureState->Mipmap0.TextureHeight;
                var TextureDataSize = PixelFormatDecoder.GetPixelsSize(TextureFormat, BufferWidth * Height);
                if (ClutState->NumberOfColors > 256)
                {
                    ClutState->NumberOfColors = 256;
                }
                var ClutDataSize = PixelFormatDecoder.GetPixelsSize(ClutFormat, ClutState->NumberOfColors);
                var ClutCount    = ClutState->NumberOfColors;
                var ClutShift    = ClutState->Shift;
                var ClutMask     = ClutState->Mask;

                //Console.WriteLine(TextureFormat);

                if (TextureDataSize > 2048 * 2048 * 4)
                {
                    Console.Error.WriteLine("UPDATE_TEXTURE(TEX={0},CLUT={1}:{2}:{3}:{4}:0x{5:X},SIZE={6}x{7},{8},Swizzled={9})", TextureFormat, ClutFormat, ClutCount, ClutStart, ClutShift, ClutMask, BufferWidth, Height, BufferWidth, Swizzled);
                    Console.Error.WriteLine("Invalid TEXTURE!");
                    return(new Texture());
                }

                TextureCacheKey TextureCacheKey = new TextureCacheKey()
                {
                    TextureAddress = TextureAddress,
                    TextureFormat  = TextureFormat,
                    TextureHash    = FastHash((uint *)TexturePointer, TextureDataSize),

                    ClutHash    = FastHash((uint *)&(ClutPointer[ClutDataStart]), ClutDataSize),
                    ClutAddress = ClutAddress,
                    ClutFormat  = ClutFormat,
                    ClutStart   = ClutStart,
                    ClutShift   = ClutShift,
                    ClutMask    = ClutMask,
                    Swizzled    = Swizzled,
                };

                if (Texture == null || (!Texture.TextureCacheKey.Equals(TextureCacheKey)))
                {
#if DEBUG_TEXTURE_CACHE
                    string TextureName = "texture_" + TextureCacheKey.TextureHash + "_" + TextureCacheKey.ClutHash + "_" + TextureFormat + "_" + ClutFormat + "_" + BufferWidth + "x" + Height;

                    Console.Error.WriteLine("UPDATE_TEXTURE(TEX={0},CLUT={1}:{2}:{3}:{4}:0x{5:X},SIZE={6}x{7},{8},Swizzled={9})", TextureFormat, ClutFormat, ClutCount, ClutStart, ClutShift, ClutMask, BufferWidth, Height, BufferWidth, Swizzled);
#endif
                    Texture = new Texture();
                    Texture.TextureCacheKey = TextureCacheKey;
                    {
                        fixed(PixelFormatDecoder.OutputPixel *TexturePixelsPointer = DecodedTextureBuffer)
                        {
                            if (Swizzled)
                            {
                                fixed(byte *SwizzlingBufferPointer = SwizzlingBuffer)
                                {
                                    Marshal.Copy(new IntPtr(TexturePointer), SwizzlingBuffer, 0, TextureDataSize);
                                    PixelFormatDecoder.UnswizzleInline(TextureFormat, (void *)SwizzlingBufferPointer, BufferWidth, Height);
                                    PixelFormatDecoder.Decode(
                                        TextureFormat, (void *)SwizzlingBufferPointer, TexturePixelsPointer, BufferWidth, Height,
                                        ClutPointer, ClutFormat, ClutCount, ClutStart, ClutShift, ClutMask
                                        );
                                }
                            }
                            else
                            {
                                PixelFormatDecoder.Decode(
                                    TextureFormat, (void *)TexturePointer, TexturePixelsPointer, BufferWidth, Height,
                                    ClutPointer, ClutFormat, ClutCount, ClutStart, ClutShift, ClutMask
                                    );
                            }

#if DEBUG_TEXTURE_CACHE
                            var Bitmap = new Bitmap(BufferWidth, Height);
                            BitmapUtils.TransferChannelsDataInterleaved(
                                Bitmap.GetFullRectangle(),
                                Bitmap,
                                (byte *)TexturePixelsPointer,
                                BitmapUtils.Direction.FromDataToBitmap,
                                BitmapChannel.Red,
                                BitmapChannel.Green,
                                BitmapChannel.Blue,
                                BitmapChannel.Alpha
                                );
                            Bitmap.Save(TextureName + ".png");
#endif

                            Texture.SetData(TexturePixelsPointer, BufferWidth, Height);
                        }
                    }
                    if (Cache.ContainsKey(Hash1))
                    {
                        Cache[Hash1].Dispose();
                    }
                    Cache[Hash1] = Texture;
                }
            }

            Texture.RecheckTimestamp = RecheckTimestamp;

            return(Texture);
        }
Example #27
0
        public override Carto.Graphics.Bitmap OnDrawPopup(PopupDrawInfo popupDrawInfo)
        {
            PopupStyle style = popupDrawInfo.Popup.Style;

            // Calculate scaled dimensions
            float DPToPX = popupDrawInfo.DPToPX;
            float PXTODP = 1 / DPToPX;

            if (style.ScaleWithDPI)
            {
                DPToPX = 1;
            }
            else
            {
                PXTODP = 1;
            }

            float screenWidth  = popupDrawInfo.ScreenBounds.GetWidth() * PXTODP;
            float screenHeight = popupDrawInfo.ScreenBounds.GetHeight() * PXTODP;

            // Update sizes based on scale (uses extension method, cf. Shared/Extensions
            int fontSize = FontSize.Update(DPToPX);

            int triangleWidth  = TriangleSize.Update(DPToPX);
            int triangleHeight = TriangleSize.Update(DPToPX);

            int strokeWidth   = StrokeWidth.Update(DPToPX);
            int screenPadding = ScreenPadding.Update(DPToPX);

            // Set font
            var font = Android.Graphics.Typeface.Create("HelveticaNeue-Light", Android.Graphics.TypefaceStyle.Normal);

            // Calculate the maximum popup size, adjust with dpi
            int maxPopupWidth = (int)(Math.Min(screenWidth, screenHeight));

            float halfStrokeWidth = strokeWidth * 0.5f;
            int   maxTextWidth    = maxPopupWidth - (2 * screenPadding + strokeWidth);

            // Measure text
            TextPaint textPaint = new TextPaint {
                Color = TextColor, TextSize = fontSize
            };

            textPaint.SetTypeface(font);

            var textLayout = new StaticLayout(text, textPaint, maxTextWidth, Layout.Alignment.AlignNormal, 1, 0, false);

            int textX = (int)Math.Min(textPaint.MeasureText(text), textLayout.Width);
            int textY = textLayout.Height;

            int popupWidth  = textX + (2 * PopupPadding + strokeWidth + triangleWidth);
            int popupHeight = textY + (2 * PopupPadding + strokeWidth);

            var bitmap = Android.Graphics.Bitmap.CreateBitmap(popupWidth, popupHeight, Android.Graphics.Bitmap.Config.Argb8888);
            var canvas = new Android.Graphics.Canvas(bitmap);

            var trianglePath = new Android.Graphics.Path();

            trianglePath.MoveTo(triangleWidth, 0);
            trianglePath.LineTo(halfStrokeWidth, triangleHeight * 0.5f);
            trianglePath.LineTo(triangleWidth, triangleHeight);
            trianglePath.Close();

            int triangleOffsetX = 0;
            int triangleOffsetY = (popupHeight - triangleHeight) / 2;

            // Create paint object
            var paint = new Android.Graphics.Paint();

            paint.AntiAlias = true;
            paint.SetStyle(Android.Graphics.Paint.Style.Stroke);
            paint.StrokeWidth = strokeWidth;
            paint.Color       = StrokeColor;

            // Stroke background
            var background = new Android.Graphics.RectF();

            background.Left   = triangleWidth;
            background.Top    = halfStrokeWidth;
            background.Right  = popupWidth - strokeWidth;
            background.Bottom = popupHeight - strokeWidth;
            canvas.DrawRect(background, paint);

            // Stroke triangle
            canvas.Save();
            canvas.Translate(triangleOffsetX, triangleOffsetY);
            canvas.DrawPath(trianglePath, paint);
            canvas.Restore();

            // Fill background
            paint.SetStyle(Android.Graphics.Paint.Style.Fill);
            paint.Color = BackgroundColor;
            canvas.DrawRect(background, paint);

            // Fill triangle
            canvas.Save();
            canvas.Translate(triangleOffsetX, triangleOffsetY);
            canvas.DrawPath(trianglePath, paint);
            canvas.Restore();

            if (textLayout != null)
            {
                // Draw text
                canvas.Save();
                canvas.Translate(halfStrokeWidth + triangleWidth + PopupPadding, halfStrokeWidth + PopupPadding);
                textLayout.Draw(canvas);
                canvas.Restore();
            }

            return(BitmapUtils.CreateBitmapFromAndroidBitmap(bitmap));
        }
Example #28
0
        private static IDictionary <Tile, ITopoArray <Rgba32> > GetSubTiles(BitmapSetExportOptions bseo, out GridTopology subTileTopology)
        {
            var t = subTileTopology = new GridTopology(bseo.TileWidth, bseo.TileHeight, false);

            return(bseo.Bitmaps.ToDictionary(x => x.Key, x => TopoArray.Create(BitmapUtils.ToColorArray(x.Value), t)));
        }
Example #29
0
        /// <summary>
        /// Returns the <see cref="DocumentInspectorPageOrientation"/> of the <paramref name="bitmap"/>
        /// according to the text that is on it
        /// </summary>
        /// <param name="bitmap">The bitmap with text</param>
        /// <returns></returns>
        public DocumentInspectorPageOrientation DetectPageOrientation(Bitmap bitmap)
        {
            if (bitmap == null)
            {
                throw new NullReferenceException("The bitmap parameter is not set");
            }

            if (bitmap.PixelFormat == PixelFormat.Format1bppIndexed)
            {
                bitmap = BitmapUtils.CopyToBpp(bitmap, 8);
            }

            using (var engine = new TesseractEngine(TesseractDataPath, TesseractLanguage))
            {
                var rect = new Rect();

                using (var image = PixConverter.ToPix(bitmap))
                    using (var page = engine.Process(image, PageSegMode.AutoOsd))
                    {
                        var pageIterator = page.AnalyseLayout();
                        pageIterator.Begin();

                        while (pageIterator.Next(PageIteratorLevel.Block))
                        {
                            var found = false;

                            while (pageIterator.Next(PageIteratorLevel.Para))
                            {
                                var counter = 0;

                                while (pageIterator.Next(PageIteratorLevel.TextLine, PageIteratorLevel.Word))
                                {
                                    counter++;
                                }

                                if (counter < 5)
                                {
                                    continue;
                                }
                                found = pageIterator.TryGetBoundingBox(PageIteratorLevel.TextLine, out rect);
                                break;
                            }

                            var croppedRect = new Rectangle(rect.X1, rect.Y1, rect.Width, rect.Height);
                            if (rect.Height == 0)
                            {
                                return(DocumentInspectorPageOrientation.Undetectable);
                            }

                            var croppedImage = found
                            ? bitmap.Clone(croppedRect, bitmap.PixelFormat)
                            : bitmap.Clone() as Bitmap;

                            // The OCR confidence on the first run
                            float firstMeanConfedence;

                            // The OCR confidence on the second run
                            float secondMeanConfedence;

                            using (var engineCroppedImage = new TesseractEngine(TesseractDataPath, TesseractLanguage))
                            {
                                using (var imageNormal = PixConverter.ToPix(croppedImage))
                                    using (var pageNormal = engineCroppedImage.Process(imageNormal))
                                        firstMeanConfedence = pageNormal.GetMeanConfidence();

                                if (firstMeanConfedence > 0.75)
                                {
                                    return(DocumentInspectorPageOrientation.PageCorrect);
                                }

                                // Rotate image 180 degrees
                                croppedImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
                                //croppedImage.Save(@"d:\\Crop area flipped.tif", System.Drawing.Imaging.ImageFormat.Tiff);

                                using (var imageRotated180 = PixConverter.ToPix(croppedImage))
                                    using (var pageRotated180 = engineCroppedImage.Process(imageRotated180))
                                        secondMeanConfedence = pageRotated180.GetMeanConfidence();
                            }

                            croppedImage.Dispose();

                            if (firstMeanConfedence > 0.40 && secondMeanConfedence > 0.40)
                            {
                                return(firstMeanConfedence >= secondMeanConfedence
                                ? DocumentInspectorPageOrientation.PageCorrect
                                : DocumentInspectorPageOrientation.PageUpsideDown);
                            }
                        }
                    }
                return(DocumentInspectorPageOrientation.Undetectable);
            }
        }
Example #30
0
 public Bitmap Apply(Bitmap bitmap)
 {
     return(BitmapUtils.GrayImage(bitmap, this.Type));
 }