예제 #1
0
        /// <summary>
        /// подпись названия для крупных магазинова (большие белые)
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="FloorID"></param>
        public void DrawSignPoint(CachedDataModel dataOfBot, int FloorID, string CustomerName = null) // специально для любимой радуги :3
        {
            var mapObjectsWithSignPoints = dataOfBot.MapObjects.Where(x => x.FloorID == FloorID && x.Params != null && x.Params.Contains("SignPointRadius") && x.Params.Contains("SignText")).ToList();
            var f = dataOfBot.Floors.FirstOrDefault(x => x.FloorID == FloorID);

            foreach (var item in mapObjectsWithSignPoints)
            {
                var sp = JsonConvert.DeserializeObject <SignPoint>(item.Params);
                sp.FixSignPointRadius(item, f);
                GetKegelResult res = ImagingHelper.GetKegel(Bmp, sp.SignText, item.LongitudeFixed, item.LatitudeFixed, sp.SignPointRadiusFixed * 2 / ZoomOfPicture);
                if (!string.IsNullOrWhiteSpace(CustomerName) && CustomerName == "ТРК Радуга")
                {
                    DrawText(sp.SignText, (item.LongitudeFixed / ZoomOfPicture + I) + res.LongitudeDist, (item.LatitudeFixed / ZoomOfPicture + J) - res.LatitudeDist, res.Kegel, Color.Orange);
                }
                DrawText(sp.SignText, (item.LongitudeFixed / ZoomOfPicture + I) + res.LongitudeDist, (item.LatitudeFixed / ZoomOfPicture + J) - res.LatitudeDist, res.Kegel, Color.White);
            }
        }
        protected override void ProcessRecordCode()
        {
            //Validate Input arguments
            ValidateInputArguments();

            IConnectionHelper connectionHelper = new ConnectionHelper(
                relativityInstanceName: RelativityInstanceName,
                relativityAdminUserName: RelativityAdminUserName,
                relativityAdminPassword: RelativityAdminPassword,
                sqlAdminUserName: SqlAdminUserName,
                sqlAdminPassword: SqlAdminPassword);
            IImagingHelper   imagingHelper   = new ImagingHelper(connectionHelper);
            IWorkspaceHelper workspaceHelper = new WorkspaceHelper(connectionHelper, null);

            // Run Imaging Job
            int workspaceArtifactId = workspaceHelper.GetFirstWorkspaceArtifactIdQueryAsync(WorkspaceName).Result;

            imagingHelper.ImageAllDocumentsInWorkspaceAsync(workspaceArtifactId).Wait();
        }
예제 #3
0
        protected virtual object CreateModelPart(
            MediaFileInfo part,
            MessageContext messageContext,
            string href,
            int?targetSize     = null,
            Size?clientMaxSize = null,
            string alt         = null)
        {
            Guard.NotNull(messageContext, nameof(messageContext));
            Guard.NotEmpty(href, nameof(href));

            if (part == null)
            {
                return(null);
            }

            var width  = part.File.Width;
            var height = part.File.Height;

            if (width.HasValue && height.HasValue && (targetSize.HasValue || clientMaxSize.HasValue))
            {
                var maxSize = clientMaxSize ?? new Size(targetSize.Value, targetSize.Value);
                var size    = ImagingHelper.Rescale(new Size(width.Value, height.Value), maxSize);
                width  = size.Width;
                height = size.Height;
            }

            var m = new
            {
                Src    = _services.MediaService.GetUrl(part, targetSize.GetValueOrDefault(), messageContext.BaseUri.ToString(), false),
                Href   = href,
                Width  = width,
                Height = height,
                Alt    = alt
            };

            PublishModelPartCreatedEvent(part, m);

            return(m);
        }
예제 #4
0
        /// <summary>
        /// Отображает огранизации с подписью их названий и с черной точков
        /// </summary>
        /// <param name="mapObjects"></param>
        public void DrawSpecialOrgs(List <MapObject> mapObjects, List <Organization> parrentOrganizations)
        {
            using (var gr = Graphics.FromImage(Bmp))
            {
                foreach (var mObj in mapObjects)
                {
                    if (mObj?.Params != "Перейдите на следующий этаж") // для текстового описания. так обозначается переход между этажами
                    {
                        string OrgName = parrentOrganizations.FirstOrDefault(x => x.OrganizationMapObject.Select(y => y?.MapObject).Contains(mObj))?.Name;
                        Image  img     = Properties.Resources.ShopLocation;
                        img = ImagingHelper.ResizeImage(img, (int)(img.Width * 2 / 2.5F), (int)(img.Height * 2 / 2.5F));
                        DrawLocation(mObj.LongitudeFixed, mObj.LatitudeFixed, "default", img);

                        DrawText(OrgName,
                                 mObj.LongitudeFixed / ZoomOfPicture + I,
                                 mObj.LatitudeFixed / ZoomOfPicture + J,

                                 OrganizationKegel, Color.Black);
                        img.Dispose();
                    }
                }
            }
        }
예제 #5
0
        private string SaveDistroIconImage(Stream readableStream, string distroName)
        {
            var targetDirectoryPath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "WslManager", "Icons");

            if (!Directory.Exists(targetDirectoryPath))
            {
                Directory.CreateDirectory(targetDirectoryPath);
            }

            var targetImageFilePath = Path.Combine(targetDirectoryPath, $"{distroName}.png");

            using (var fileStream = File.OpenWrite(targetImageFilePath))
            {
                readableStream.Seek(0L, SeekOrigin.Begin);
                readableStream.CopyTo(fileStream);
            }

            var targetIconFilePath = Path.Combine(targetDirectoryPath, $"{distroName}.ico");

            ImagingHelper.ConvertToIcon(targetImageFilePath, targetIconFilePath);
            return(targetIconFilePath);
        }
예제 #6
0
        public BitmapSettings(Bitmap bmp, int _floorID = 0)
        {
            double koeff = (double)bmp.Width / bmp.Height;
            double temp  = 1150 / koeff;
            Image  img   = ImagingHelper.ResizeImage(bmp, 1150, (int)temp);


            //избавляемя от прозрачных областей (типа convert to jpg)
            var b = new Bitmap(img.Width, img.Height);

            b.SetResolution(img.HorizontalResolution, img.VerticalResolution);
            using (var g = Graphics.FromImage(b))
            {
                g.Clear(Color.White);
                g.DrawImageUnscaled(img, 0, 0);
            }
            Bmp           = b;
            I             = b.Width / 2;
            J             = b.Height / 2;
            ZoomOfPicture = (float)bmp.Width / b.Width;

            MyPen   = new Pen(Color.Red, 2.5F);
            FloorID = _floorID;
        }
예제 #7
0
        public static Task <Control> Get(ProgressWorker a1, SynchronizationContext context, Window window, bool npc)
        {
            var source = new TaskCompletionSource <Control>();

            context.Send(obj => {
                var control = new ImageGridView();
                var t       = new Thread(() => {
                    if (!(obj is Tuple <ProgressWorker, TaskCompletionSource <Control> > tuple))
                    {
                        return;
                    }
                    var worker = tuple.Item1;
                    var tcs    = tuple.Item2;
                    try {
                        var i = 0;
                        worker.ReportProgress(0, "Loading heroes...");
                        if (TrackedFiles == null || !TrackedFiles.ContainsKey(0x75))
                        {
                            throw new DataToolWpfException("Open storage first");
                        }

                        var max = TrackedFiles[0x75].Count;

                        foreach (var key in TrackedFiles[0x75])
                        {
                            try {
                                var hero = GetInstance <STUHero>(key);
                                if (hero == null)
                                {
                                    continue;
                                }
                                string heroNameActual = GetString(hero.m_0EDCE350) ?? teResourceGUID.Index(key).ToString("X");

                                heroNameActual = heroNameActual.TrimEnd(' ');

                                ProgressionUnlocks progressionUnlocks = new ProgressionUnlocks(hero);
                                if (progressionUnlocks.LevelUnlocks == null && !npc)
                                {
                                    continue;
                                }
                                if (progressionUnlocks.LootBoxesUnlocks != null && npc)
                                {
                                    continue;
                                }

                                var tex = hero.m_8203BFE1.FirstOrDefault(x => teResourceGUID.Index(x.m_id) == 0x40C9 || teResourceGUID.Index(x.m_id) == 0x40CA)?.m_texture;

                                if (tex == 0)
                                {
                                    tex = hero.m_8203BFE1.FirstOrDefault()?.m_texture;
                                }

                                var image = new byte[] { };

                                var width  = 128;
                                var height = 128;

                                if (tex != 0)
                                {
                                    teTexture texture = new teTexture(OpenFile(tex));
                                    if (texture.PayloadRequired)
                                    {
                                        ulong payload        = texture.GetPayloadGUID(tex);
                                        Stream payloadStream = OpenFile(payload);
                                        if (payloadStream != null)
                                        {
                                            texture.LoadPayload(payloadStream);
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }

                                    width  = texture.Header.Width;
                                    height = texture.Header.Height;

                                    Stream ms = texture.SaveToDDS();

                                    image = DDSConverter.ConvertDDS(ms, DXGI_FORMAT.R8G8B8A8_UNORM, DDSConverter.ImageFormat.PNG, 0);
                                }

                                var entry      = control.Add(heroNameActual, image, 128, (int)ImagingHelper.CalculateSizeAS(height, width, 128));
                                entry.Payload  = progressionUnlocks;
                                entry.OnClick += (sender, args) => {
                                    window.Close();
                                };
                            } catch {
                                // ignored
                            } finally {
                                i += 1;
                                worker.ReportProgress((int)(i / (float)max * 100));
                            }
                        }

                        tcs.SetResult(control);
                    } catch (Exception e) {
                        tcs.SetException(e);
                    } finally {
                        worker.ReportProgress(100);
                    }
                });
                t.SetApartmentState(ApartmentState.STA);
                t.Start();
            }, new Tuple <ProgressWorker, TaskCompletionSource <Control> >(a1, source));
            return(source.Task);
        }
예제 #8
0
        public virtual void ProccessImage(BackgroundWorker worker)
        {
            this.worker = worker;

            UpdateProgress(3);

            //Brightness and sharpen filters
            BrightnessCorrection cfilter = new BrightnessCorrection(Settings.Brightness);
            GaussianSharpen      filter  = new GaussianSharpen(4, 11);

            //Apply filters
            cfilter.ApplyInPlace(sourceBitmap);
            UpdateProgress(15);
            filter.ApplyInPlace(sourceBitmap);
            UpdateProgress(30);

            //Convert to gray
            var tmpImage = ConvertToGrayScale(sourceBitmap);

            UpdateProgress(35);

            //Cut edges
            tmpImage = CutEdgesAndInvert(tmpImage);
            UpdateProgress(40);

            //Get angle for rotating image
            var rotateAngle = DetectRotation(tmpImage);

            UpdateProgress(45);

            if (rotateAngle != 0)
            {
                RotateBilinear rotate = new RotateBilinear(rotateAngle, true);
                tmpImage = rotate.Apply(tmpImage);
            }

            //Build horizontal hough lines
            OCRLessonReport.Imaging.HoughLineTransformation lineTransform = new OCRLessonReport.Imaging.HoughLineTransformation();

            HoughLineRequestSettings settings = new HoughLineRequestSettings
            {
                HorizontalLines     = true,
                VerticalLines       = false,
                HorizontalDeviation = 2
            };

            lineTransform.ProcessImage(tmpImage, settings);

            //Get horizontal line
            HoughLine[] lines = lineTransform.GetLinesByRelativeIntensity(Settings.HorizontalSensitivity);

            //Get half width and height for future calculations
            int hWidth  = tmpImage.Width / 2;
            int hHeight = tmpImage.Height / 2;
            //Get line coordinates (Y axis only - horizontal lines)
            var lineCoordinates = lines.Select(line => hHeight - line.Radius);
            //Grouping coords by delta
            var groupedCoordinates = ImagingHelper.GroupingCoordinates(lineCoordinates, Settings.LineGroupingDelta);

            if (groupedCoordinates.Count <= Settings.HeaderStartLine)
            {
                throw new Exception("Invalid source. Can't be recognized");
            }

            int headerLineY0 = groupedCoordinates[Settings.HeaderStartLine];
            int headerLineY1 = groupedCoordinates[Settings.HeaderStartLine + 1];
            //Copy header to new image
            var headerImage = tmpImage.Copy(new Rectangle(0, headerLineY0, tmpImage.Width, headerLineY1 - headerLineY0));
            //Parse header to get header lines
            HoughLineRequestSettings headerSettings = new HoughLineRequestSettings
            {
                HorizontalLines   = false,
                VerticalLines     = true,
                VerticalDeviation = 1
            };

            lineTransform.ProcessImage(headerImage, headerSettings);

            Func <HoughLine, int, int> getRadius = (l, w) =>
            {
                if (l.Theta > 90 && l.Theta < 180)
                {
                    return(w - l.Radius);
                }
                else
                {
                    return(w + l.Radius);
                }
            };

            HoughLine[] headerLines = lineTransform.GetLinesByRelativeIntensity(Settings.VerticalSensitivity);
            //Get header vertical lines
            var headerLineCoordinates = headerLines.Select(line => getRadius(line, hWidth));
            //Grouped lines
            var groupedheaderLineCoordinates = ImagingHelper.GroupingCoordinates(headerLineCoordinates, Settings.LineGroupingDelta);
            //Build cell map
            List <TableCell> cellMap = new List <TableCell>();

            UpdateProgress(50);

            //Use tess engine for ocr
            using (TesseractEngine engine = new TesseractEngine(Settings.TessdataPath, Settings.TessdataLanguage))
            {
                //Parse top header
                var x0 = groupedheaderLineCoordinates.FirstOrDefault();
                var x1 = groupedheaderLineCoordinates.LastOrDefault();
                var y0 = groupedCoordinates[0];
                var y1 = groupedCoordinates[1];

                int fullProgress = (groupedheaderLineCoordinates.Count - 1) * (groupedCoordinates.Count - Settings.BottomStartLine - 1 - Settings.HeaderStartLine);
                int curProgress  = 0;

                var hImage = tmpImage.Copy(new Rectangle(x0, y0, x1 - x0, y1 - y0));
                hImage = ProcessCell(hImage);

                using (var page = engine.Process(hImage, PageSegMode.SingleBlock))
                {
                    cellMap.Add(new TableCell(0, 0, TableCellType.MainHeader, hImage, page.GetText(), false));
                }

                //Parse table
                for (int i = 0; i < groupedheaderLineCoordinates.Count - 1; i++)
                {
                    int subjectArea = (i < Settings.ColumnSubjectStart - 1) ? 0 : 1;

                    for (int j = Settings.HeaderStartLine; j < groupedCoordinates.Count - Settings.BottomStartLine - 1; j++)
                    {
                        int headerArea = (j == Settings.HeaderStartLine) ? 2 : 0;

                        TableCellType cellType = (TableCellType)(subjectArea + headerArea);

                        var cellImg = tmpImage.Copy(new Rectangle(groupedheaderLineCoordinates[i], groupedCoordinates[j],
                                                                  groupedheaderLineCoordinates[i + 1] - groupedheaderLineCoordinates[i],
                                                                  groupedCoordinates[j + 1] - groupedCoordinates[j]));

                        if (cellType == TableCellType.Text || cellType == TableCellType.Header || cellType == TableCellType.HeaderRotated)
                        {
                            cellImg = ProcessCell(cellImg, i == Settings.NameStartLine);

                            string text = String.Empty;

                            if (cellType == TableCellType.HeaderRotated)
                            {
                                cellImg.RotateFlip(RotateFlipType.Rotate90FlipNone);
                            }

                            using (var page = engine.Process(cellImg, PageSegMode.SingleBlock))
                            {
                                text = page.GetText();
                            }


                            cellMap.Add(new TableCell(i, j, cellType, cellImg, text, false));
                        }
                        else
                        {
                            cellImg = ProcessCell(cellImg);

                            BilateralSmoothing bfilter = new BilateralSmoothing();
                            bfilter.KernelSize    = 7;
                            bfilter.SpatialFactor = 10;
                            bfilter.ColorFactor   = 60;
                            bfilter.ColorPower    = 0.5;
                            bfilter.ApplyInPlace(cellImg);

                            cellImg = FilterColors(cellImg, Settings.FilteringColor, ByteColor.Black, ByteColor.White);

                            BlobCounter bcounter = new BlobCounter();
                            bcounter.ProcessImage(cellImg);

                            var blobs = bcounter.GetObjects(cellImg, false);

                            if (blobs.Length < 1)
                            {
                                continue;
                            }

                            var biggestBlob       = blobs.OrderBy(b => b.Area).LastOrDefault();
                            var biggestBlobsImage = biggestBlob.Image.ToManagedImage();

                            cellMap.Add(new TableCell(i, j, cellType, biggestBlobsImage, GetMask(biggestBlobsImage).ToString(), GetMask(biggestBlobsImage)));
                        }

                        curProgress++;
                        double reportProgress = (double)curProgress / (double)fullProgress * 50 + 50;
                        UpdateProgress((int)reportProgress);
                    }
                }
            }

            this.Cells = cellMap;

            UpdateProgress(100);
        }
예제 #9
0
        protected virtual Bitmap ConvertToGrayScale(Bitmap image)
        {
            Contract.Requires(image != null, "Image can't be null");
            Contract.Requires(image.Width != 0, "Image's width can't be 0");
            Contract.Requires(image.Height != 0, "Image's height can't be 0");

            var width  = image.Width;
            var height = image.Height;

            var imageData = image.LockBits(new Rectangle(new System.Drawing.Point(0, 0), image.Size),
                                           ImageLockMode.ReadOnly,
                                           image.PixelFormat);

            var cnvImage = new Bitmap(width, height, PixelFormat.Format8bppIndexed);

            cnvImage.Palette = ImagingHelper.GetGrayScalePalette();

            var cnvImageData = cnvImage.LockBits(new Rectangle(new System.Drawing.Point(0, 0), cnvImage.Size),
                                                 ImageLockMode.ReadWrite,
                                                 cnvImage.PixelFormat);

            var imageStride    = imageData.Stride;
            var cnvImageStride = cnvImageData.Stride;

            var imageScan0    = imageData.Scan0;
            var cnvImageScan0 = cnvImageData.Scan0;

            var imagePixelSize = imageStride / width;

            byte[] imageBits    = new byte[imageStride * height];
            byte[] cnvImageBits = new byte[cnvImageStride * height];

            try
            {
                Marshal.Copy(imageData.Scan0, imageBits, 0, imageBits.Length);

                for (var y = 0; y < height; y++)
                {
                    var sourceRow = y * imageStride;
                    var resultRow = y * cnvImageStride;

                    for (var x = 0; x < width; x++)
                    {
                        var pixelColor = (byte)(0.3 * imageBits[sourceRow + x * imagePixelSize + 2] + 0.59 * imageBits[sourceRow + x * imagePixelSize + 1] +
                                                0.11 * imageBits[sourceRow + x * imagePixelSize]);

                        //Remove noise and increase contrast
                        if (pixelColor > Settings.FilteringColor)
                        {
                            pixelColor = ByteColor.White;
                        }

                        cnvImageBits[resultRow + x] = pixelColor;
                    }
                }

                Marshal.Copy(cnvImageBits, 0, cnvImageData.Scan0, cnvImageBits.Length);
            }
            finally
            {
                image.UnlockBits(imageData);
                cnvImage.UnlockBits(cnvImageData);
            }

            return(cnvImage);
        }
예제 #10
0
        private async void MModel_FetchDataComplete(object sender, FetchDataCompleteEventArgs e)
        {
            var loader = new ResourceLoader();

            UpdateIndText.Text  = loader.GetString("RefreshComplete");
            LoadingDot.IsActive = false;
            Forecast0.SetCondition(Context.Forecast0, Context.IsNight);
            Forecast1.SetCondition(Context.Forecast1, Context.IsNight);
            Forecast2.SetCondition(Context.Forecast2, Context.IsNight);
            Forecast3.SetCondition(Context.Forecast3, Context.IsNight);
            Forecast4.SetCondition(Context.Forecast4, Context.IsNight);
            if ((Context.Condition == WeatherCondition.sunny) || (Context.Condition == WeatherCondition.windy) ||
                (Context.Condition == WeatherCondition.calm) ||
                (Context.Condition == WeatherCondition.light_breeze) ||
                (Context.Condition == WeatherCondition.moderate) ||
                (Context.Condition == WeatherCondition.fresh_breeze) ||
                (Context.Condition == WeatherCondition.strong_breeze) ||
                (Context.Condition == WeatherCondition.high_wind) ||
                (Context.Condition == WeatherCondition.gale))
            {
                if (!Context.IsNight)
                {
                    var s = new SolidColorBrush(Colors.Black);
                    baba.ChangeColor(s);
                    RefreshButton.Foreground = s;
                }
                else
                {
                    baba.ChangeColor(new SolidColorBrush(Colors.White));
                    RefreshButton.Foreground = new SolidColorBrush(Colors.White);
                }
            }
            else
            {
                baba.ChangeColor(new SolidColorBrush(Colors.White));
                RefreshButton.Foreground = new SolidColorBrush(Colors.White);
            }
            WeatherCanvas.ChangeCondition(Context.Condition, Context.IsNight, Context.IsSummer);
            if (Context.Aqi == null)
            {
                AQIPanel.Visibility = Visibility.Collapsed;
            }
            if (Context.Comf == null && Context.Cw == null && Context.Drsg == null)
            {
                SuggestionPanel.Visibility = Visibility.Collapsed;
            }
            switch (Context.source)
            {
            case DataSource.HeWeather:
                DataSourceImage.Source = new BitmapImage(new Uri("http://heweather.com/weather/images/logo.jpg"));
                DataSourceContent.Text = loader.GetString("HeWeather");
                break;

            case DataSource.Caiyun:
                DataSourceImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Logos/Caiyun.png"));
                DataSourceContent.Text = loader.GetString("CaiyunWeather");
                break;

            case DataSource.Wunderground:
                DataSourceImage.Source = new BitmapImage(new Uri("ms-appx:///Assets/Logos/Wunder.png"));
                DataSourceContent.Text = string.Empty;
                break;

            default:
                break;
            }
            baba.ChangeCondition(Context.Condition, Context.IsNight, Context.City, Context.NowL, Context.NowH);
            ScrollableRoot.RefreshComplete();
            if (LoadingDot.Visibility == Visibility.Collapsed)
            {
                TempraturePathAnimation.Completed += (s, v) =>
                {
                    RefreshCompleteAni.Begin();
                };
                TempraturePathAnimation.Begin();
                AQIAni.Begin();
                DetailGrid0Play();
                DetailGrid1Play();
                DetailGrid2Play();
                DetailGrid3Play();
                DetailGrid4Play();
                DetailGrid6Play();
                DetailGrid7Play();
            }

            try
            {
                if (Windows.System.UserProfile.UserProfilePersonalizationSettings.IsSupported() && Context.SetWallPaper)
                {
                    var file = await FileIOHelper.GetFilebyUriAsync(await Context.GetCurrentBackgroundAsync());

                    var lFile = await FileIOHelper.CreateWallPaperFileAsync(Guid.NewGuid().ToString() + ".png");

                    var d           = Windows.Devices.Input.PointerDevice.GetPointerDevices();
                    var m           = d.ToArray();
                    var scaleFactor = Windows.Graphics.Display.DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
                    var size        = new Size(m[0].PhysicalDeviceRect.Width, m[0].PhysicalDeviceRect.Height);
                    var ratio       = size.Height / size.Width;
                    size.Height *= scaleFactor;
                    size.Width  *= scaleFactor;
                    var    cropSize = new Size();
                    double scale;
                    var    startPoint = new Point();
                    using (var stream = await file.OpenReadAsync())
                    {
                        var bitmap = new BitmapImage();
                        await bitmap.SetSourceAsync(stream);

                        var width  = bitmap.PixelWidth;
                        var height = bitmap.PixelHeight;
                        var center = new Point(width / 2, height / 2);
                        if (width * ratio >= height)
                        {
                            cropSize.Width  = height / ratio;
                            cropSize.Height = height;
                            scale           = size.Height / height;
                        }
                        else
                        {
                            cropSize.Width  = width;
                            cropSize.Height = width * ratio;
                            scale           = size.Width / width;
                        }

                        startPoint.X = center.X - cropSize.Width / 2;
                        startPoint.Y = center.Y - cropSize.Height / 2;
                    }
                    await ImagingHelper.CropandScaleAsync(file, lFile, startPoint, cropSize, scale);

                    var uc = await ImagingHelper.SetWallpaperAsync(lFile);
                }
            }
            catch (Exception)
            {
            }
        }
예제 #11
0
        public async void Init(SongViewModel song)
        {
            //Initialize our picker object
            castingPicker = new CastingDevicePicker();

            //Set the picker to filter to video capable casting devices
            castingPicker.Filter.SupportsAudio = true;

            //Hook up device selected event
            castingPicker.CastingDeviceSelected += CastingPicker_CastingDeviceSelected;

            Song      = song;
            _lastSong = new Song()
            {
                ID            = song.ID,
                IsOnline      = song.IsOnline,
                OnlineUri     = new Uri(song.FilePath),
                FilePath      = song.FilePath,
                Duration      = song.Song.Duration,
                Album         = song.Album,
                OnlineAlbumID = song.Song.OnlineAlbumID,
                OnlineID      = song.Song.OnlineID
            };
            CurrentArtwork = song.Artwork;
            lastUriPath    = song.Artwork?.AbsolutePath;
            IsPlaying      = player.IsPlaying;
            BufferProgress = MainPageViewModel.Current.BufferProgress;
            SongChanged?.Invoke(song, EventArgs.Empty);
            CurrentRating = song.Rating;
            var brush = new SolidColorBrush(await ImagingHelper.GetMainColor(CurrentArtwork));

            CurrentColorBrush = brush;
            MainPageViewModel.Current.LeftTopColor = AdjustColorbyTheme(CurrentColorBrush);
            CurrentIndex = MainPageViewModel.Current.CurrentIndex;
            var task = ThreadPool.RunAsync(async x =>
            {
                var favor = await _lastSong.GetFavoriteAsync();
                await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
                {
                    IsCurrentFavorite = favor;
                });
            });

            var t = ThreadPool.RunAsync(async x =>
            {
                var ext = MainPageViewModel.Current.LyricExtension;
                if (ext != null)
                {
                    var result = await ext.ExecuteAsync(new ValueSet()
                    {
                        new KeyValuePair <string, object>("q", "lyric"),
                        new KeyValuePair <string, object>("title", Song.Title),
                        new KeyValuePair <string, object>("album", song.Album),
                        new KeyValuePair <string, object>("artist", Song.Song.Performers.IsNullorEmpty() ? null : Song.Song.Performers[0]),
                        new KeyValuePair <string, object>("ID", song.IsOnline ? song.Song.OnlineID : null)
                    });
                    if (result != null)
                    {
                        var l = new Lyric(LrcParser.Parser.Parse((string)result, Song.Song.Duration));
                        await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                        {
                            Lyric.New(l);
                        });
                    }
                    else
                    {
                        await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                        {
                            Lyric.Clear();
                            LyricHint = Consts.Localizer.GetString("NoLyricText");
                        });
                    }
                }
                else
                {
                    await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                    {
                        Lyric.Clear();
                        LyricHint = Consts.Localizer.GetString("NoLyricText");
                    });
                }
            });
        }
예제 #12
0
 public Color GetMainColor(double d)
 {
     MainColor.ColorToHSV(out var h, out var s, out var v);
     v *= d;
     return(ImagingHelper.ColorFromHSV(h, s, v));
 }
예제 #13
0
        private async Task Init(SettingsModel settings, CitySettingsModel currentCity)
        {
            string resstr = await Request.GetRequestAsync(settings, currentCity);

            if (!resstr.IsNullorEmpty())
            {
                var fetchresult = HeWeatherModel.Generate(resstr, settings.Preferences.DataSource);
                if (fetchresult == null || fetchresult.DailyForecast == null || fetchresult.HourlyForecast == null)
                {
                    return;
                }
                var utcOffset = fetchresult.Location.UpdateTime - fetchresult.Location.UtcTime;
                var current   = DateTimeHelper.ReviseLoc(utcOffset);
                try
                {
                    Sender.CreateMainTileQueue(await Generator.CreateAll(currentCity, fetchresult, current));
                }
                catch (Exception)
                {
                }

                try
                {
                    if (UserProfilePersonalizationSettings.IsSupported() && settings.Preferences.SetWallPaper)
                    {
                        var todayIndex = Array.FindIndex(fetchresult.DailyForecast, x =>
                        {
                            return(x.Date.Date == current.Date);
                        });
                        if (current.Hour <= 7)
                        {
                            todayIndex--;
                        }
                        if (todayIndex < 0)
                        {
                            todayIndex = 0;
                        }
                        TimeSpan sunRise, sunSet;
                        if (fetchresult.DailyForecast[todayIndex].SunRise == default(TimeSpan) || fetchresult.DailyForecast[todayIndex].SunSet == default(TimeSpan))
                        {
                            sunRise = Core.LunarCalendar.SunRiseSet.GetRise(new Models.Location(currentCity.Latitude, currentCity.Longitude), current);
                            sunSet  = Core.LunarCalendar.SunRiseSet.GetSet(new Models.Location(currentCity.Latitude, currentCity.Longitude), current);
                        }
                        else
                        {
                            sunRise = fetchresult.DailyForecast[todayIndex].SunRise;
                            sunSet  = fetchresult.DailyForecast[todayIndex].SunSet;
                        }
                        var file = await FileIOHelper.GetFilebyUriAsync(await settings.Immersive.GetCurrentBackgroundAsync(fetchresult.NowWeather.Now.Condition, WeatherModel.CalculateIsNight(current, sunRise, sunSet)));

                        var lFile = await FileIOHelper.CreateWallPaperFileAsync(Guid.NewGuid().ToString() + ".png");

                        var    d           = PointerDevice.GetPointerDevices();
                        var    m           = d.ToArray();
                        var    scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
                        var    size        = new Size(m[0].PhysicalDeviceRect.Width, m[0].PhysicalDeviceRect.Height);
                        var    ratio       = size.Height / size.Width;
                        var    cropSize    = new Size();
                        double scale;
                        var    startPoint = new Point();
                        using (var stream = await file.OpenReadAsync())
                        {
                            var bitmap = new BitmapImage();
                            await bitmap.SetSourceAsync(stream);

                            var width  = bitmap.PixelWidth;
                            var height = bitmap.PixelHeight;
                            var center = new Point(width / 2, height / 2);
                            if (width * ratio >= height)
                            {
                                cropSize.Width  = height / ratio;
                                cropSize.Height = height;
                                scale           = size.Height / height;
                            }
                            else
                            {
                                cropSize.Width  = width;
                                cropSize.Height = width * ratio;
                                scale           = size.Width / width;
                            }

                            startPoint.X = center.X - cropSize.Width / 2;
                            startPoint.Y = center.Y - cropSize.Height / 2;
                        }
                        await ImagingHelper.CropandScaleAsync(file, lFile, startPoint, cropSize, scale);

                        var uc = await ImagingHelper.SetWallpaperAsync(lFile);
                    }
                }
                catch (Exception)
                {
                }

                if (settings.Preferences.EnableMorning)
                {
                    var shu1 = settings.Preferences.MorningNoteTime.TotalHours;

                    var tomorrow8 = DateTime.Now.Hour > shu1 ? (DateTime.Today.AddDays(1)).AddHours(shu1) : (DateTime.Today.AddHours(shu1));

                    try
                    {
                        Sender.CreateScheduledToastNotification(await(Generator.CreateToast(fetchresult, currentCity, settings, DateTimeHelper.ReviseLoc(tomorrow8, utcOffset))), tomorrow8, "MorningToast");
                    }
                    catch (Exception)
                    {
                    }
                }
                if (settings.Preferences.EnableEvening)
                {
                    var shu2       = settings.Preferences.EveningNoteTime.TotalHours;
                    var tomorrow20 = DateTime.Now.Hour > shu2 ? (DateTime.Today.AddDays(1)).AddHours(shu2) : (DateTime.Today.AddHours(shu2));
                    try
                    {
                        Sender.CreateScheduledToastNotification(await(Generator.CreateToast(fetchresult, currentCity, settings, DateTimeHelper.ReviseLoc(tomorrow20, utcOffset))), tomorrow20, "EveningToast");
                    }
                    catch (Exception)
                    {
                    }
                }
                if (settings.Preferences.EnableAlarm)
                {
                    if (!fetchresult.Alarms.IsNullorEmpty() && (DateTime.Now - settings.Preferences.LastAlertTime).TotalDays > 1)
                    {
                        Sender.CreateBadge(Generator.GenerateAlertBadge());
                        Sender.CreateToast(Generator.CreateAlertToast(fetchresult, currentCity).GetXml());
                    }
                    else
                    {
                        Sender.ClearBadge();
                    }
                    var str = Generator.CalculateWeatherAlarm(fetchresult, currentCity, settings, DateTimeHelper.ReviseLoc(DateTime.Now, utcOffset));
                    if (!str.IsNullorEmpty() && str.Length > 1 && (DateTime.Now - settings.Preferences.LastAlarmTime).TotalDays > 1)
                    {
                        Sender.CreateToast(Generator.CreateAlarmToast(str, currentCity).GetXml());
                    }
                }
                await settings.Cities.SaveDataAsync(currentCity.Id.IsNullorEmpty()?currentCity.City : currentCity.Id, resstr, settings.Preferences.DataSource);

                currentCity.Update();
                if (settings.Cities.CurrentIndex != -1)
                {
                    settings.Cities.SavedCities[settings.Cities.CurrentIndex] = currentCity;
                }
                else
                {
                    settings.Cities.LocatedCity = currentCity;
                }
                settings.Cities.Save();
            }
        }
예제 #14
0
 /// <summary>
 /// Маршрутизатор отправки изображений
 /// </summary>
 /// <param name="image"></param>
 /// <param name="caption"></param>
 /// <returns></returns>
 public async Task <int> SendPhoto(Bitmap image, string caption = "")
 {
     return(await SendPhoto(ImagingHelper.ImageToByteArray(image), caption));
 }
예제 #15
0
        private async void Player_StatusChanged(object sender, PlayingItemsChangedArgs e)
        {
            await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, async() =>
            {
                IsPlaying = player.IsPlaying;
                if (e.CurrentSong != null)
                {
                    if (!_lastSong.IsIDEqual(e.CurrentSong))
                    {
                        Song = new SongViewModel(e.CurrentSong);

                        CurrentRating = Song.Rating;

                        SongChanged?.Invoke(Song, EventArgs.Empty);

                        if (Song.Artwork != null)
                        {
                            if (lastUriPath == Song.Artwork.AbsolutePath)
                            {
                            }
                            else
                            {
                                CurrentArtwork    = Song.Artwork;
                                CurrentColorBrush = new SolidColorBrush(await ImagingHelper.GetMainColor(CurrentArtwork));
                                MainPageViewModel.Current.LeftTopColor = AdjustColorbyTheme(CurrentColorBrush);
                                lastUriPath = Song.Artwork.AbsolutePath;
                            }
                        }
                        else
                        {
                            CurrentArtwork    = null;
                            CurrentColorBrush = new SolidColorBrush(new UISettings().GetColorValue(UIColorType.Accent));
                            MainPageViewModel.Current.LeftTopColor = AdjustColorbyTheme(CurrentColorBrush);
                            lastUriPath = null;
                        }
                        if (e.Items is IList <Song> l)
                        {
                            NowListPreview = $"{e.CurrentIndex + 1}/{l.Count}";
                            NowPlayingList.Clear();
                            for (int i = 0; i < l.Count; i++)
                            {
                                NowPlayingList.Add(new SongViewModel(l[i])
                                {
                                    Index = (uint)i
                                });
                            }
                            if (e.CurrentIndex < NowPlayingList.Count)
                            {
                                CurrentIndex = e.CurrentIndex;
                            }
                        }

                        IsCurrentFavorite = await e.CurrentSong.GetFavoriteAsync();
                    }
                }
            });

            if (e.CurrentSong != null)
            {
                if (!_lastSong.IsIDEqual(e.CurrentSong))
                {
                    await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
                    {
                        Lyric.Clear();
                        LyricHint = Consts.Localizer.GetString("LoadingLyricsText");
                    });

                    _lastSong = e.CurrentSong;
                    var ext = MainPageViewModel.Current.LyricExtension;
                    if (ext != null)
                    {
                        var result = await ext.ExecuteAsync(new ValueSet()
                        {
                            new KeyValuePair <string, object>("q", "lyric"),
                            new KeyValuePair <string, object>("title", Song.Title),
                            new KeyValuePair <string, object>("album", song.Album),
                            new KeyValuePair <string, object>("artist", Song.Song.Performers.IsNullorEmpty() ? null : Song.Song.Performers[0]),
                            new KeyValuePair <string, object>("ID", song.IsOnline ? song.Song.OnlineID : null)
                        });

                        if (result != null)
                        {
                            var l = new Lyric(LrcParser.Parser.Parse((string)result, Song.Song.Duration));
                            await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
                            {
                                Lyric.New(l);
                            });
                        }
                        else
                        {
                            await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
                            {
                                Lyric.Clear();
                                LyricHint = Consts.Localizer.GetString("NoLyricText");
                            });
                        }
                    }
                    else
                    {
                        await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
                        {
                            Lyric.Clear();
                            LyricHint = Consts.Localizer.GetString("NoLyricText");
                        });
                    }
                }
            }
        }
예제 #16
0
        /// <summary>
        /// Class handling for the PreviewKeyDown event.
        /// </summary>
        /// <param name="e">The KeyEventArgs that contains the event data.</param>
        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            // this prevents focus changing
            if ((e.Key == Key.Up) ||
                (e.Key == Key.Down) ||
                (e.Key == Key.Left) ||
                (e.Key == Key.Right)
                )
            {
                e.Handled = true;
            }

            // The event is fired several times when a key is down (while not released)
            // but we want to handle it only once
            if (!_keyPressed)
            {
                switch (e.Key)
                {
                case Key.R:
                    if (Keyboard.Modifiers == (ModifierKeys.Control | ModifierKeys.Alt))
                    {
                        // Resets the camera
                        InitializeCamera();
                    }
                    break;

                case Key.S:
                    if (Keyboard.Modifiers == (ModifierKeys.Control))
                    {
                        if (!double.IsNaN(Width) && !double.IsNaN(Height))
                        {
                            // Saves the scene in the user's Pictures folder in a PNG file named [3DScene_yyyy-MM-dd_HH-mm-ss-fff]_[width]x[height].png
                            var pixelWidth  = Convert.ToInt32(this.Width);
                            var pixelHeight = Convert.ToInt32(this.Height);
                            ImagingHelper.CreatePngFile(_viewport,
                                                        pixelWidth, pixelHeight, 96, null,
                                                        Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
                                                        String.Format("3DScene_{0:yyyy-MM-dd_HH-mm-ss-fff}", DateTime.Now));
                        }
                    }
                    break;

                case Key.NumPad7:
                case Key.Home:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        CameraOrient(Direction.Forward | Direction.Left);
                    }
                    else if (Keyboard.Modifiers == ModifierKeys.None)
                    {
                        CameraTranslate(Direction.Forward | Direction.Left);
                    }
                    _keyPressed = true;
                    break;

                case Key.NumPad4:
                case Key.Left:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        CameraOrient(Direction.Left);
                        _keyPressed = true;
                    }
                    else if (Keyboard.Modifiers == ModifierKeys.None)
                    {
                        CameraTranslate(Direction.Left);
                        _keyPressed = true;
                    }
                    else if (Keyboard.Modifiers == (ModifierKeys.Shift))
                    {
                        CameraOrbitOrigin(-2.0, OrbitKind.Horizontal);
                        // _keyPressed is not assigned so it may be repeated
                    }
                    break;

                case Key.NumPad1:
                case Key.End:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        CameraOrient(Direction.Backward | Direction.Left);
                    }
                    else if (Keyboard.Modifiers == ModifierKeys.None)
                    {
                        CameraTranslate(Direction.Backward | Direction.Left);
                    }
                    _keyPressed = true;
                    break;

                case Key.NumPad2:
                case Key.Down:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        CameraOrient(Direction.Backward);
                        _keyPressed = true;
                    }
                    else if (Keyboard.Modifiers == ModifierKeys.None)
                    {
                        CameraTranslate(Direction.Backward);
                        _keyPressed = true;
                    }
                    else if (Keyboard.Modifiers == (ModifierKeys.Shift))
                    {
                        CameraOrbitOrigin(2.0, OrbitKind.Vertical);
                        // _keyPressed is not assigned so it may be repeated
                    }
                    break;

                case Key.NumPad3:
                case Key.PageDown:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        CameraOrient(Direction.Backward | Direction.Right);
                    }
                    else if (Keyboard.Modifiers == ModifierKeys.None)
                    {
                        CameraTranslate(Direction.Backward | Direction.Right);
                    }
                    _keyPressed = true;
                    break;

                case Key.NumPad6:
                case Key.Right:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        CameraOrient(Direction.Right);
                        _keyPressed = true;
                    }
                    else if (Keyboard.Modifiers == ModifierKeys.None)
                    {
                        CameraTranslate(Direction.Right);
                        _keyPressed = true;
                    }
                    else if (Keyboard.Modifiers == (ModifierKeys.Shift))
                    {
                        CameraOrbitOrigin(2.0, OrbitKind.Horizontal);
                        // _keyPressed is not assigned so it may be repeated
                    }
                    break;

                case Key.NumPad9:
                case Key.PageUp:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        CameraOrient(Direction.Forward | Direction.Right);
                    }
                    else if (Keyboard.Modifiers == ModifierKeys.None)
                    {
                        CameraTranslate(Direction.Forward | Direction.Right);
                    }
                    _keyPressed = true;
                    break;

                case Key.Up:
                case Key.NumPad8:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        CameraOrient(Direction.Forward);
                        _keyPressed = true;
                    }
                    else if (Keyboard.Modifiers == ModifierKeys.None)
                    {
                        CameraTranslate(Direction.Forward);
                        _keyPressed = true;
                    }
                    else if (Keyboard.Modifiers == (ModifierKeys.Shift))
                    {
                        CameraOrbitOrigin(-2.0, OrbitKind.Vertical);
                        // _keyPressed is not assigned so it may be repeated
                    }
                    break;

                case Key.Add:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        CameraTranslate(Direction.Up);
                    }
                    else if (Keyboard.Modifiers == ModifierKeys.None)
                    {
                        CameraZoom(Direction.Forward);
                    }
                    _keyPressed = true;
                    break;

                case Key.Subtract:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        CameraTranslate(Direction.Down);
                    }
                    else if (Keyboard.Modifiers == ModifierKeys.None)
                    {
                        CameraZoom(Direction.Backward);
                    }
                    _keyPressed = true;
                    break;

                case Key.NumPad5:
                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        CameraTranslate(Direction.Down);
                    }
                    else
                    {
                        CameraTranslate(Direction.Up);
                    }
                    _keyPressed = true;
                    break;
                }
            }
            base.OnPreviewKeyDown(e);
        }
예제 #17
0
 private Components.GDI.IImage PrepareBackground()
 {
     return(ImagingHelper.CropIImage(MasterForm.SkinManager.GetImage("Header"),
                                     new Rectangle(Location.X, Location.Y, UISettings.CalcPix(10), UISettings.CalcPix(25))));
 }
예제 #18
0
        /// <summary>
        /// Рисует все найденные организации на карте этажа
        /// Возвращает структуру с добавленными в нее картинками
        /// </summary>
        /// <returns></returns>
        public FindedInformation DrawFindedShops()
        {
            var groupedOrgs = (List <GroupedOrganization>)answer.GroopedResult; // получает группы огранизаций

            groupedOrgs.OrderByDescending(x => x.AverageRating).ToList();

            foreach (Floor f in dataOfBot.Floors)
            {
                var groupsFromFloor = groupedOrgs.Where(x => x.FloorID == f.FloorID).ToList();
                if (groupsFromFloor.Count != 0)
                {
                    //var bitmap = new BitmapSettings(new Bitmap(Image.FromStream(new MemoryStream(f.File))), f.FloorID);
                    var bitmap = new BitmapSettings(new Bitmap(Image.FromFile(ConfigurationManager.AppSettings["ContentPath"] + $"Floors\\{f.FloorID}.{f.FileExtension}")), f.FloorID);



                    foreach (var group in groupsFromFloor)
                    {
                        foreach (var org in group.Orgs)
                        {
                            Image img;
                            var   mObjofThisOrg = group.MapObjects.Where(x => org.OrganizationMapObject.Select(y => y.MapObjectID).Contains(x.MapObjectID));
                            if (group.MapObjects.Count == 1)
                            {
                                img = Properties.Resources.Shop;
                            }
                            else
                            {
                                img = Properties.Resources.ShopG; // для групп рисуем оранжевую точку
                            }
                            foreach (var mObj in mObjofThisOrg)
                            {
                                var temp = org.CategoryOrganization.Select(x => x.Category).Select(x => x.ServiceCategoryType);
                                if (temp.Contains(ServiceCategoryType.Service) || temp.Contains(ServiceCategoryType.Link))
                                {
                                    img = ImagingHelper.ResizeImage(img, 110, 110);
                                    bitmap.DrawLocation(mObj.LongitudeFixed, mObj.LatitudeFixed, "default", img);
                                    bitmap.DrawLandMarksExtra(dataOfBot, f.Number);
                                }
                                else
                                {
                                    img = ImagingHelper.ResizeImage(img, (int)(img.Width * 4 / 2.5F), (int)(img.Height * 4 / 2.5F));
                                    bitmap.DrawLocation(mObj.LongitudeFixed, mObj.LatitudeFixed, "default", img);
                                }
                            }
                        }
                    }

                    bitmap.DrawLandMarksExtra(dataOfBot, f.FloorID);
                    bitmap.DrawLandMarksOrganizations(dataOfBot, f.FloorID);
                    bitmap.DrawSignPoint(dataOfBot, f.FloorID, dataOfBot.Customers[0].Name);

                    // расставляем балуны для каждой группы
                    char index = 'A';
                    for (int i = 0; i < 5 && i < groupsFromFloor.Count; i++)
                    {
                        var   obj = Properties.Resources.ResourceManager.GetObject(index.ToString());
                        Image img = (Bitmap)obj;
                        bitmap.DrawLocation(BotMapHelper.CenterOfDiagonal(groupsFromFloor[i].MapObjects), "MultyDraw", img);
                        index++;
                    }
                    // подпись картинки
                    var tmp = title.Replace("%floornumber%", f.Number.ToString());
                    bitmap.DrawText(tmp, BotTextHelper.LengthOfString(tmp, bitmap), 5F, 23, Color.DarkSlateGray, true);
                    answer.FloorsPictures.Add(bitmap);
                }
            }
            return(answer);
        }