private void ClearRouteBuilder()
 {
     _currentIndex = 1;
     _currentRoute?.Points.Clear();
     _currentRoute?.RegenerateShape(RouteCreatorMap);
     BuildingProgressBar.Value = 0;
     ProgressText.Text         = TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_1%", "Route progress");
     _builded = false;
     while (_mapPoints.Any())
     {
         RemoveMarker(_mapPoints[0]);
     }
     RouteCreatorMap.Markers.Clear();
     _pokestops.Clear();
     _pokemons.Clear();
     _mappedPokemons.Clear();
     if (_routeBuilder != null && _routeBuilder.Status == TaskStatus.Running)
     {
         _cts.Cancel();
     }
     _ctsPrev.Cancel();
     _ctsPrev         = new CancellationTokenSource();
     _showPsTask      = null;
     _showHeatMapTask = null;
 }
Пример #2
0
        public async Task <string> Translate(string inSentence, TranslationEngine translationEngine, TranslatorLanguague fromLang, TranslatorLanguague toLang, string chatCode)
        {
            string text     = string.Empty;
            string NickName = string.Empty;

            if (ChatCodesWithNickNames.Contains(chatCode))
            {
                var ind1 = inSentence.IndexOf(":");
                if (ind1 > 0)
                {
                    ind1++;

                    NickName   = inSentence.Substring(0, ind1);
                    inSentence = inSentence.Remove(0, ind1);
                }
            }

            text = await _WebTranslator.TranslateAsync(inSentence, translationEngine, fromLang, toLang);

            if (NickName.Length > 0)
            {
                text = NickName + " " + text;
            }

            return(text);
        }
        private void SaveTheRoute_Click(object sender, RoutedEventArgs e)
        {
            var routeName = NewRouteNameBox.Text;

            if (string.IsNullOrEmpty(routeName))
            {
                return;
            }
            if (!_builded)
            {
                MessageBox.Show(
                    TranslationEngine.GetDynamicTranslationString("%ERR_BUILD_THE_ROUTE%", "Build the route first"),
                    "Routing error", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            if (
                _globalSettings.Routes.Any(
                    x => string.Equals(x.Name, routeName, StringComparison.CurrentCultureIgnoreCase)))
            {
                routeName += "_" + DeviceSettings.RandomString(5);
            }
            var route = new BotRoute
            {
                Name      = routeName,
                InitialWp = _mapPoints.Select(x => x.Location).ToList(),
                Route     = new CustomRoute()
                {
                    RoutePoints = new List <GeoCoordinate>(_buildedRoute)
                }
            };

            _globalSettings.Routes.Add(route);
            _globalSettings.Save();
            NewRouteNameBox.Text = string.Empty;
        }
Пример #4
0
        private void HourRectangle_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (Bot.GlobalSettings.Schedule.ActionList == null)
            {
                Bot.GlobalSettings.Schedule.ActionList = new List <ScheduleAction>();
            }

            var rec  = sender as Rectangle;
            var indx = rec?.Tag as Tuple <int, int>;

            if (indx == null)
            {
                return;
            }


            var sae = new ScheduleActionEditor
            {
                Day  = indx.Item1,
                Hour = indx.Item2
            };

            TranslationEngine.ApplyLanguage(sae);

            sae.SetSchedule(this);
            ScheduleControlGrid.Children.Add(sae);
            _sae = sae;
        }
        private void ExportRoute_Click(object sender, RoutedEventArgs e)
        {
            ImportExportRouteText.Clear();
            var    points       = _mapPoints.Select(x => x.Location).ToList();
            string encodedRoute = null;

            var firstOrDefault = points.FirstOrDefault();

            if (firstOrDefault == null)
            {
                return;
            }
            try
            {
                encodedRoute = RoutingUtils.EncodeToPolyline(points);
            }
            catch (Exception)
            {
                //do nothing
            }
            if (encodedRoute == null)
            {
                return;
            }
            ImportExportRouteText.Text         = encodedRoute;
            ImportExportRoute.Visibility       = Visibility.Visible;
            ImportExportHeading.Text           = TranslationEngine.GetDynamicTranslationString("%EXPORT_ROUTE%", "Export Route");
            ImportExportRouteSubmit.Visibility = Visibility.Collapsed;
            ImportExportInstructions.Text      = TranslationEngine.GetDynamicTranslationString("%EXPORT_INSTRUCTION%", "Copy the below route to create a backup or share with others.");
        }
Пример #6
0
 static void Main(string[] args)
 {
     string input = args[0];
     string output = args[1];
     TranslationEngine translator = new TranslationEngine(new StreamWriter(output), true);
     translator.TranslateAssemblyFromFile(input, Assembly.GetExecutingAssembly());
 }
Пример #7
0
        public TranslationEngine GetLanguagesFromEngineId(string engineId)
        {
            if (!string.IsNullOrEmpty(engineId))
            {
                var engineSplitValues = engineId.Split(EngineIdSeparator);
                if (engineSplitValues.Length >= 2)
                {
                    var translationEngine = new TranslationEngine
                    {
                        EngineSourceLanguage = engineSplitValues[0],
                        EngineTargetLanguage = engineSplitValues[1]
                    };

                    return(translationEngine);
                }
            }
            else
            {
                throw new AddonValidationException($"EngineId is not provided", new Details {
                    Code = ErrorCodes.InvalidInput, Name = nameof(TranslationRequest.EngineId), Value = engineId
                });
            }

            return(null);
        }
Пример #8
0
 private static void SetPokemonAsBuddy(Queue <PokemonUiData> pokemonQueue)
 {
     if (pokemonQueue == null)
     {
         return;
     }
     while (pokemonQueue.Count > 0)
     {
         var pokemon = pokemonQueue.Dequeue();
         if (pokemon == null)
         {
             continue;
         }
         if (pokemon.OwnerBot != null && pokemon.OwnerBot.Started || _debugMode)
         {
             pokemon.OwnerBot.Session.AddActionToQueue(
                 async() =>
             {
                 await
                 SetBuddyPokemonTask.Execute(pokemon.OwnerBot.Session, pokemon.Id);
                 return(true);
             }, $"{TranslationEngine.GetDynamicTranslationString("%SET_BUDDY%", "Set Buddy")}: {pokemon.Name}", pokemon.Id);
             pokemon.InAction = true;
         }
     }
 }
Пример #9
0
        private void mi_recycleItem_Click(object sender, RoutedEventArgs e)
        {
            var mi          = sender as MenuItem;
            var itemListBox = (mi?.Parent as ContextMenu)?.Tag as ListBox;

            if (itemListBox == null || itemListBox.SelectedItems.Count != 1)
            {
                return;
            }
            var item = (ItemUiData)itemListBox.SelectedItem;

            if (item?.OwnerBot == null)
            {
                return;
            }
            var curSession = item.OwnerBot.Session;
            int amount;
            var inputDialog = new SupportForms.InputDialog(TranslationEngine.GetDynamicTranslationString("%RECYCLE_INPUT%", "Please, enter amout to recycle:"), "1", true);

            if (inputDialog.ShowDialog() != true)
            {
                return;
            }
            if (int.TryParse(inputDialog.Answer, out amount))
            {
                RecycleItem(curSession, item, amount, item.OwnerBot.CancellationToken);
            }
        }
Пример #10
0
 private static void RenamePokemon(Queue <PokemonUiData> pokemonQueue, string name = null, bool toDefault = false)
 {
     if (pokemonQueue == null)
     {
         return;
     }
     if (name == null)
     {
         return;
     }
     while (pokemonQueue.Count > 0)
     {
         var pokemon = pokemonQueue.Dequeue();
         if (pokemon == null)
         {
             continue;
         }
         if (pokemon.OwnerBot != null && pokemon.OwnerBot.Started || _debugMode)
         {
             pokemon.OwnerBot.Session.AddActionToQueue(
                 async() =>
             {
                 await
                 RenameSpecificPokemonTask.Execute(pokemon.OwnerBot.Session, pokemon.Id,
                                                   pokemon.OwnerBot.CancellationToken, name, toDefault);
                 return(true);
             }, $"{TranslationEngine.GetDynamicTranslationString("%RENAME_POKE%", "Rename poke")}: {pokemon.Name}", pokemon.Id);
             pokemon.InAction = true;
         }
     }
 }
Пример #11
0
 private static void LevelUpPokemon(Queue <PokemonUiData> pokemonQueue, bool toMax = false)
 {
     if (pokemonQueue == null)
     {
         return;
     }
     while (pokemonQueue.Count > 0)
     {
         var pokemon = pokemonQueue.Dequeue();
         if (pokemon == null)
         {
             continue;
         }
         if (pokemon.OwnerBot != null && pokemon.OwnerBot.Started || _debugMode)
         {
             pokemon.OwnerBot.Session.AddActionToQueue(
                 async() =>
             {
                 await
                 LevelUpSpecificPokemonTask.Execute(pokemon.OwnerBot.Session, pokemon.Id,
                                                    pokemon.OwnerBot.CancellationToken, toMax);
                 return(true);
             }, $"{TranslationEngine.GetDynamicTranslationString("%LEVEL_UP%", "Level up")}: {pokemon.Name}", pokemon.Id);
             pokemon.InAction = true;
         }
     }
 }
Пример #12
0
 private static void EvolvePokemon(Queue <PokemonUiData> pokemonQueue)
 {
     if (pokemonQueue == null)
     {
         return;
     }
     while (pokemonQueue.Count > 0)
     {
         var pokemon = pokemonQueue.Dequeue();
         if (pokemon == null)
         {
             continue;
         }
         if (pokemon.OwnerBot != null && pokemon.OwnerBot.Started && pokemon.Evolutions.Any() || _debugMode)
         {
             pokemon.OwnerBot.Session.AddActionToQueue(
                 async() =>
             {
                 await
                 EvolveSpecificPokemonTask.Execute(pokemon.OwnerBot.Session, pokemon.Id,
                                                   pokemon.OwnerBot.CancellationToken);
                 return(true);
             }, $"{TranslationEngine.GetDynamicTranslationString("%EVOLVE%", "Evolve")} {pokemon.Name}", pokemon.Id);
             pokemon.InAction = true;
         }
     }
 }
Пример #13
0
        private void mi_renamePokemon_Click(object sender, RoutedEventArgs e)
        {
            var mi          = sender as MenuItem;
            var pokeListBox = (mi?.Parent as ContextMenu)?.Tag as ListBox;

            if (pokeListBox?.SelectedIndex == -1)
            {
                return;
            }
            var pokemonToRename = GetMultipleSelectedPokemon(pokeListBox);

            if (pokemonToRename == null)
            {
                return;
            }
            var inputDialog = new SupportForms.InputDialog(TranslationEngine.GetDynamicTranslationString("%POKE_NAME_INPUT%", "Please Enter a Name to Rename Pokemon:"), "", false, 12);

            if (inputDialog.ShowDialog() != true)
            {
                return;
            }
            var customName = inputDialog.Answer;

            if (customName.Length > 12)
            {
                return;
            }
            RenamePokemon(pokemonToRename, customName);
        }
 private void ImportRoute_Click(object sender, RoutedEventArgs e)
 {
     ImportExportRoute.Visibility       = Visibility.Visible;
     ImportExportHeading.Text           = TranslationEngine.GetDynamicTranslationString("%IMPORT_ROUTE%", "Import Route");
     ImportExportRouteSubmit.Visibility = Visibility.Visible;
     ImportExportInstructions.Text      = TranslationEngine.GetDynamicTranslationString("%IMPORT_INSTRUCTION%", "Enter a route below to Import it into Catchem, once entered click import.");
     ImportExportRouteText.Clear();
 }
Пример #15
0
        public RocketBody() : base()
        {
            translationEngine = 0;
            rotationEngine    = 0;

            dImpulsPerSecond   = 15;
            dMomentumPerSecond = Math.PI / 20;
        }
Пример #16
0
        public RocketBody(MaterialPoint mp, RotatCharacter rc) : base(mp, rc)
        {
            translationEngine = 0;
            rotationEngine    = 0;

            dImpulsPerSecond   = 15;
            dMomentumPerSecond = Math.PI / 20;
        }
Пример #17
0
        private static void RecycleItem(ISession session, ItemUiData item, int amount, CancellationToken cts)
        {
            long uidLong = -1;
            var  uid     = (ulong)uidLong;

            session.AddActionToQueue(async() =>
            {
                await RecycleSpecificItemTask.Execute(session, item.Id, amount, cts);
                return(true);
            }, $"{TranslationEngine.GetDynamicTranslationString("%RECYCLE_ITEM%", "Recycle item")}: {item.Id}x{amount}", uid);
        }
Пример #18
0
 private static void UseItem(ItemUiData item)
 {
     if (item.OwnerBot.Started || _debugMode)
     {
         item.OwnerBot.Session.AddActionToQueue(
             async() =>
         {
             await UseItemTask.Execute(item.OwnerBot.Session, item.Id, item.OwnerBot.CancellationToken);
             return(true);
         }, $"{TranslationEngine.GetDynamicTranslationString("%USING%", "Using")}: {item.Name}", 0);
     }
 }
Пример #19
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var s = parameter as string;

            if (value == null || s == null)
            {
                return(value);
            }
            var tag = s.Split(';');

            return(tag.Length > 1 ? TranslationEngine.GetDynamicTranslationString(tag[0], tag[1]) : value);
        }
Пример #20
0
 public void UpdatePokedexCount()
 {
     Dispatcher.Invoke(new ThreadStart(delegate
     {
         var seen                = _bot?.PokeDex?.Count(x => x.Seen);
         var caught              = _bot?.PokeDex?.Count(x => x.Captured);
         var seenTranslation     = TranslationEngine.GetDynamicTranslationString("%SEEN%", "Seen");
         var capturedTranslation = TranslationEngine.GetDynamicTranslationString("%CAUGHT%", "Caught");
         var totalTranslation    = TranslationEngine.GetDynamicTranslationString("%TOTAL%", "Total");
         PokedexStatusText.Text  = $"{seenTranslation}: {seen} / {capturedTranslation}: {caught} / {totalTranslation}: 151";
     }));
 }
Пример #21
0
        /// <summary>
        /// Based on the source and target languages available in DeepL create the response which we'll send to LC
        /// </summary>
        /// <param name="apiKey">DeepL API Key</param>
        /// <param name="sourceLanguageCode">LC source language code</param>
        /// <param name="targetLanguagesCode">LC list of target language codes</param>
        /// <returns><see cref="TranslationEngineResponse"/>/returns>
        public async Task <TranslationEngineResponse> GetCorrespondingEngines(string apiKey, string sourceLanguageCode, List <string> targetLanguagesCode)
        {
            var deeplAvailableSourceLanguages = await GetAvailableDeeplLanguages(apiKey, LanguageEnum.source);

            var sourceEngineCode = GetLcCorrespondingSourceLanguageCodeEngine(sourceLanguageCode, deeplAvailableSourceLanguages);

            if (string.IsNullOrEmpty(sourceEngineCode))
            {
                throw new AddonValidationException($"Source Language not supported", new Details {
                    Code = ErrorCodes.InvalidInput, Name = nameof(TranslationEngineRequest.SourceLanguage), Value = sourceLanguageCode
                });
            }

            var deeplAvailableTargetLanguages = await GetAvailableDeeplLanguages(apiKey, LanguageEnum.target);

            var targetEngineCodes = GetLCCorrespondingTargetLanguagesEngineCode(targetLanguagesCode, deeplAvailableTargetLanguages);

            if (!targetEngineCodes.Any())
            {
                throw new AddonValidationException($"Target Language(s) not supported", new Details {
                    Code = ErrorCodes.InvalidInput, Name = nameof(TranslationEngineRequest.TargetLanguage), Value = string.Join(" ", targetEngineCodes.ToArray())
                });
            }

            var translationEngines = new List <TranslationEngine>();

            foreach (var languageCodeMapping in targetEngineCodes)
            {
                var engine = new TranslationEngine
                {
                    Name  = EngineName,
                    Id    = $"{sourceEngineCode}{EngineIdSeparator}{languageCodeMapping.Key}{EngineIdSeparator}{EngineName}",
                    Model = EngineModel,
                    MatchingSourceLanguage  = sourceLanguageCode,
                    EngineSourceLanguage    = sourceEngineCode,
                    EngineTargetLanguage    = languageCodeMapping.Key,
                    MatchingTargetLanguages = languageCodeMapping.Value,
                };
                translationEngines.Add(engine);
            }

            var translationEngineResponse = new TranslationEngineResponse
            {
                Items     = translationEngines,
                ItemCount = translationEngines.Count
            };

            return(translationEngineResponse);
        }
Пример #22
0
        public Rocket() : base()
        {
            phisObj = new RocketBody();

            phisObj.mass = 100;

            phisObj.inertMoment = 100;

            phisObj.angulVel = 0;

            translationEngine = 0;
            rotationEngine    = 0;

            NormdImpulsPerSecond   = 10;
            NormdMomentumPerSecond = Math.PI / 10;
        }
Пример #23
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                var prop   = parameter as string;
                var status = (bool?)value;
                if (value == null || prop == null)
                {
                    return(value);
                }

                if (prop == "Text")
                {
                    return((bool)status ? TranslationEngine.GetDynamicTranslationString("%STOP%", "STOP") : TranslationEngine.GetDynamicTranslationString("%START%", "START"));
                }
                if (prop == "Background")
                {
                    var color1 = (bool)status
                        ? System.Windows.Media.Color.FromArgb(255, 192, 79, 83)
                        : System.Windows.Media.Color.FromArgb(255, 83, 192, 177);
                    var color2 = (bool)status
                        ? System.Windows.Media.Color.FromArgb(255, 238, 178, 156)
                        : System.Windows.Media.Color.FromArgb(255, 176, 238, 156);
                    return(new LinearGradientBrush
                    {
                        GradientStops = new GradientStopCollection
                        {
                            new GradientStop
                            {
                                Color = color1,
                                Offset = 1
                            },
                            new GradientStop
                            {
                                Color = color2,
                                Offset = 0
                            }
                        }
                    });
                }
                return(value);
            }
            catch (Exception)
            {
                return(value);
            }
        }
Пример #24
0
        public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture)
        {
            var s = parameter as string;

            if (value == null || s == null || value.Length < 2)
            {
                return(value);
            }
            var tag = value[0] as string;
            var lng = value[1] as string;

            if (tag != null)
            {
                return(TranslationEngine.GetDynamicTranslationString(tag, s));
            }
            return(value);
        }
        public ChatWindowViewModelSettings GetSettings()
        {
            ChatWindowViewModelSettings settings = new ChatWindowViewModelSettings();

            settings.Name  = this.Name;
            settings.WinId = this._WinId;

            settings.ChatFontSize    = this.ChatFontSize;
            settings.LineBreakHeight = this.LineBreakHeight;
            settings.SpacingCount    = this.SpacingCount;

            settings.IsAlwaysOnTop  = this.IsAlwaysOnTop;
            settings.IsClickThrough = this.IsClickThrough;
            settings.IsAutoHide     = this.IsAutoHide;

            settings.AutoHideTimeout = this.AutoHideTimeout;

            //settings.IsHiddenByUser = this.IsHiddenByUser;

            settings.BackGroundColor = this.BackGroundColor;

            TranslationEngine engine = (TranslationEngine)this.TranslationEngines.CurrentItem;

            if (engine != null)
            {
                settings.TranslationEngineName = engine.EngineName;
            }
            else
            {
                settings.TranslationEngineName = TranslationEngineName.GoogleTranslate;
            }

            settings.FromLanguague = (TranslatorLanguague)TranslateFromLanguagues.CurrentItem;
            settings.ToLanguague   = (TranslatorLanguague)TranslateToLanguagues.CurrentItem;

            settings.ChatWindowRectangle = this.ChatWindowRectangle;

            settings.ChatCodes = this.ChatCodes.ToList().Select(entry => new ChatCodeViewModel(entry)).ToList();

            settings.ShowHideChatKeys     = new HotKeyCombination(this.ShowHideChatKeys);
            settings.ClickThoughtChatKeys = new HotKeyCombination(this.ClickThoughtChatKeys);
            settings.ClearChatKeys        = new HotKeyCombination(this.ClearChatKeys);

            return(settings);
        }
Пример #26
0
        private void team_image_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (_bot == null || !_bot.Started || _bot.Team != TeamColor.Neutral || _bot.Level < 5)
            {
                return;
            }
            var inputDialog = new SupportForms.InputDialog(TranslationEngine.GetDynamicTranslationString("%SELECT_TEAM_INPUT%", "Please, select a team:"), null, false, 0, new List <object> {
                TeamColor.Blue, TeamColor.Yellow, TeamColor.Red
            });

            if (inputDialog.ShowDialog() != true || inputDialog.ObjectAnswer == null)
            {
                return;
            }
            var team = (TeamColor)inputDialog.ObjectAnswer;

            SelectTeam(team);
        }
        private async Task ShowPokestops(double lat, double lng, double dist, CancellationToken token)
        {
            var pokeStops = DbHandler.GetPokestopsForCoords(lat, lng, dist);

            foreach (var ps in pokeStops)
            {
                if (_pokestops.ContainsKey(ps.Id))
                {
                    continue;
                }
                await Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    var markerShape =
                        Properties.Resources.pstop.ToImage(string.IsNullOrEmpty(ps.Name)
                            ? TranslationEngine.GetDynamicTranslationString("%POKESTOP%", "PokeStop")
                            : ps.Name);
                    var marker = new GMapMarker(new PointLatLng(ps.Latitude, ps.Longitude))
                    {
                        Shape = markerShape,
                        Offset = new Point(-16, -32),
                        ZIndex = 5
                    };
                    try
                    {
                        token.ThrowIfCancellationRequested();
                        if (!_pokestops.ContainsKey(ps.Id))
                        {
                            _pokestops.Add(ps.Id, marker);
                        }
                    }
                    catch (Exception)
                    {
                        //ignore
                    }

                    RouteCreatorMap.Markers.Add(marker);
                }));
            }
        }
Пример #28
0
        private List <string> GetTranslations(TranslationRequest translationRequest, TranslationEngine translationEngine, string apiKey, string formality)
        {
            var translations = new List <string>();

            Parallel.ForEach(translationRequest.Contents, (text) =>
            {
                var encodedText      = HttpUtility.UrlEncode(text);
                using var httpClient = new HttpClient();

                var content = new StringContent($"text={encodedText}" +
                                                $"&source_lang={translationEngine.EngineSourceLanguage}" +
                                                $"&target_lang={translationEngine.EngineTargetLanguage}" +
                                                $"&formality={formality.ToLower()}" +
                                                "&preserve_formatting=1" +
                                                "&tag_handling=xml" +
                                                $"&auth_key={apiKey}", Encoding.UTF8, "application/x-www-form-urlencoded");

                var response = httpClient.PostAsync("https://api.deepl.com/v2/translate", content).Result;
                if (response.IsSuccessStatusCode)
                {
                    var translationResponse = response.Content?.ReadAsStringAsync().Result;
                    var translatedObject    = JsonSerializer.Deserialize <DeeplTranslationResponse>(translationResponse, JsonSettings.Default());
                    var translatedText      = translatedObject.Translations[0].Text;

                    translations.Add(translatedText);
                }
                else
                {
                    var responseContent = response.Content?.ReadAsStringAsync().Result;

                    throw new AddonValidationException($"Request to DeepL Translate endpoint failed with status code {response.StatusCode}", new Details {
                        Code = ErrorCodes.GeneralError, Value = responseContent
                    });
                }
            });
            return(translations);
        }
        private void CreateNewMarker(PointLatLng mapPos, bool starter)
        {
            var marker = new GMapMarker(mapPos)
            {
                Offset   = starter ? new Point(-24, -48) : new Point(-16, -32),
                ZIndex   = int.MaxValue,
                Position = mapPos
            };

            var imgSource = starter
                ? Properties.Resources.force_move.LoadBitmap()
                : Properties.Resources.wp.LoadBitmap();

            var tooltipText = starter
                ? TranslationEngine.GetDynamicTranslationString("%ROUTE_MARKER_START%", "Route Marker - START")
                : TranslationEngine.GetDynamicTranslationString("%ROUTE_MARKER_WP%", "Route Marker - Waypoint") +
                              $" {_currentIndex++}";

            var rm = new RouteMarker(imgSource, tooltipText, RouteCreatorMap, this)
            {
                IsStart  = starter,
                Location = new GeoCoordinate(mapPos.Lat, mapPos.Lng),
                Marker   = marker
            };

            marker.Shape            = rm;
            rm.MouseLeftButtonDown += delegate
            {
                if (!Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
                {
                    RemoveMarker(rm);
                }
            };

            AddMarker(rm, starter);
        }
Пример #30
0
 public EngineDescription(TranslationEngine translationEngine, double value)
 {
     TranslationEngine = translationEngine;
     Value             = value;
 }
        private async Task BuildTheRouteTask(CancellationToken token)
        {
            try
            {
                token.ThrowIfCancellationRequested();
                if (_mapPoints.Count < 2)
                {
                    return;
                }
                await Dispatcher.BeginInvoke(new ThreadStart(CheckRouteServicePrefer));

                if (_mapPoints.Count > 47 && !_manualRoute)
                {
                    Dispatcher.Invoke(new ThreadStart(delegate
                    {
                        MessageBox.Show(
                            TranslationEngine.GetDynamicTranslationString("%TOO_MANY_ROUTE_POINTS%",
                                                                          "Too many waypoints, try to reduce them to 47, or wait for next releases, where that limit will be increased!"),
                            "Routing Error", MessageBoxButton.OK, MessageBoxImage.Information);
                    }));
                    return;
                }
                UpdateProgress(TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_2%", "Started!..."), 0);
                BotWindowData bot;
                var           route = GetWorkingRouting(out bot);
                if (route == "error" && !_manualRoute)
                {
                    MessageBox.Show(
                        TranslationEngine.GetDynamicTranslationString("%NO_ROUTE_API_FOUND%",
                                                                      "You have to enter Google Direction API or Mapzen Valhalla API to any of your bots, before creating a route"),
                        "API Key Error", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                var start = _mapPoints.FirstOrDefault(x => x.IsStart) ?? _mapPoints.First();
                UpdateProgress(TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_3%", "Started!..."), 10);
                RoutingResponse response = null;
                var             cycleWp  = _mapPoints.Where(x => !x.IsStart).Select(x => x.Location).ToList();
                cycleWp.Add(start.Location);
                List <GeoCoordinate> routePoints;
                token.ThrowIfCancellationRequested();
                if (!_manualRoute)
                {
                    if (route == "google")
                    {
                        response = GoogleRouting.GetRoute(start.Location, null, bot.Session, cycleWp, true);
                    }
                    else if (route == "mapzen")
                    {
                        response = MapzenRouting.GetRoute(start.Location, null, bot.Session, cycleWp, true);
                    }
                    if (response?.Coordinates == null || response.Coordinates.Count == 0)
                    {
                        return;
                    }
                    routePoints = response.Coordinates.Select(wp => new GeoCoordinate(wp[0], wp[1])).ToList();
                }
                else
                {
                    cycleWp.Insert(0, start.Location);
                    routePoints = new List <GeoCoordinate>(cycleWp);
                }
                token.ThrowIfCancellationRequested();
                UpdateProgress(
                    TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_4%", "Handling result..."), 60);
                _currentRoute?.Points?.Clear();
                if (_currentRoute == null)
                {
                    _currentRoute = new GMapRoute(new List <PointLatLng>());
                }

                await RouteCreatorMap.Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    RouteCreatorMap.Markers.Add(_currentRoute);
                }));

                token.ThrowIfCancellationRequested();
                UpdateProgress(
                    TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_5%", "Requesting altitude..."), 70);
                _buildedRoute = new List <GeoCoordinate>(routePoints);
                token.ThrowIfCancellationRequested();
                foreach (var item in routePoints)
                {
                    _currentRoute.Points?.Add(new PointLatLng(item.Latitude, item.Longitude));
                }
                await Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    try
                    {
                        _currentRoute.RegenerateShape(RouteCreatorMap);
                    }
                    catch (Exception)
                    {
                        //ignore
                    }
                }));

                var path = _currentRoute?.Shape as Path;
                await Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    if (path != null)
                    {
                        path.Stroke = new SolidColorBrush(Color.FromRgb(255, 0, 0));
                    }
                }));


                bot = MainWindow.BotsCollection.FirstOrDefault(
                    x => !string.IsNullOrEmpty(x.GlobalSettings.LocationSettings.MapzenApiKey));
                if (bot != null)
                {
                    await bot.Session.MapzenApi.FillAltitude(_buildedRoute.ToList(), token : token);
                }
                UpdateProgress(TranslationEngine.GetDynamicTranslationString("%ROUTE_PROGRESS_6%", "Done!"), 100);
                _builded = true;
            }
            catch (OperationCanceledException)
            {
                //ignore
            }
        }