From 31eebb29c1b19c000431804d6630b98e256aa197 Mon Sep 17 00:00:00 2001 From: Francois Hoffmann Date: Sat, 14 Jan 2023 22:05:17 +0100 Subject: [PATCH] Update MapsInMyFolder_Database Added getPreview and getPreviewFallback function : getPreview(args) -> set url to show the preview. getPreviewFallback(args) -> if the preview url loading fail. Console now show result of operation like google chrome console does. Cleanup code --- .editorconfig | 6 + MapsInMyFolder.Common/Collectif.cs | 71 +++-- MapsInMyFolder.Common/Javascript.cs | 246 +++++++++--------- MapsInMyFolder.Common/Layers.cs | 2 +- MapsInMyFolder.Common/Settings.cs | 4 +- .../TileGenerator.GenericFileFormat_Tiles.cs | 2 +- .../TileGenerator.PBF_Tiles.cs | 4 +- .../MapControl/ImageLoader.WPF.cs | 25 +- .../MapControl/ImageLoader.cs | 5 - .../MapControl/TileSource.cs | 3 +- MapsInMyFolder.Setup/Product.wxs | 2 +- .../SkiaCanvas.cs | 6 - MapsInMyFolder/App.xaml.cs | 52 +++- MapsInMyFolder/CustomOrEditLayersPage.xaml | 6 +- MapsInMyFolder/CustomOrEditLayersPage.xaml.cs | 34 +-- MapsInMyFolder/DownloadPannel.cs | 65 +---- MapsInMyFolder/LayersPannel.cs | 109 ++++---- MapsInMyFolder/MainWindow.xaml.cs | 1 - MapsInMyFolder/MapsInMyFolder.csproj | 2 +- MapsInMyFolder/PrepareDownloadPage.xaml | 2 +- MapsInMyFolder/PrepareDownloadPage.xaml.cs | 40 +-- MapsInMyFolder/SettingsWindow.xaml | 17 ++ MapsInMyFolder/SettingsWindow.xaml.cs | 12 + MapsInMyFolder/download.cs | 5 +- MapsInMyFolder/html/layer_panel.html | 155 ++++++----- MapsInMyFolder_Database.db | Bin 204800 -> 204800 bytes 26 files changed, 457 insertions(+), 419 deletions(-) diff --git a/.editorconfig b/.editorconfig index 57bb03e..2fa7f68 100644 --- a/.editorconfig +++ b/.editorconfig @@ -2,3 +2,9 @@ # RCS1036: Remove unnecessary blank line. dotnet_diagnostic.RCS1036.severity = silent + +# Default severity for all analyzer diagnostics +dotnet_analyzer_diagnostic.severity = silent + +# CS8002: L'assembly référencé 'clipper_library, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' n'a pas de nom fort. +dotnet_diagnostic.CS8002.severity = silent diff --git a/MapsInMyFolder.Common/Collectif.cs b/MapsInMyFolder.Common/Collectif.cs index be83140..de1941a 100644 --- a/MapsInMyFolder.Common/Collectif.cs +++ b/MapsInMyFolder.Common/Collectif.cs @@ -56,52 +56,62 @@ public override string ToString() public static class Collectif { + public static class GetUrl { - public static int numberofurlgenere = 0; - public static string FromTileXYZ(string urlbase, int x, int y, int z, int LayerID) + public enum InvokeFunction { getTile, getPreview, getPreviewFallback } + public static string FromTileXYZ(string urlbase, int Tilex, int Tiley, int z, int LayerID, InvokeFunction InvokeFunction) { if (LayerID == -1) { return urlbase; } - string finalurl = urlbase; - List location_topleft = Commun.Collectif.TileToCoordonnees(x, y, z); - List location_bottomright = Commun.Collectif.TileToCoordonnees(x + 1, y + 1, z); + + Layers calque = Layers.GetLayerById(LayerID); + if (calque is null) + { + return string.Empty; + } + string finalurl; + if (string.IsNullOrEmpty(urlbase)) + { + finalurl = calque.class_tile_url; + } + else + { + finalurl = urlbase; + } + List location_topleft = Commun.Collectif.TileToCoordonnees(Tilex, Tiley, z); + List location_bottomright = Commun.Collectif.TileToCoordonnees(Tilex + 1, Tiley + 1, z); List location = Commun.Collectif.GetCenterBetweenTwoPoints(location_topleft, location_bottomright); + Dictionary argument = new Dictionary() { - { "x", x.ToString() }, - { "y", y.ToString() }, + { "x", Tilex.ToString() }, + { "y", Tiley.ToString() }, { "z", z.ToString() }, - { "zoom", z.ToString() }, + { "zoom", z.ToString() }, { "lat", location[0].ToString() }, { "lng", location[1].ToString()}, + { "t_lat", location_topleft[0].ToString() }, { "t_lng", location_topleft[1].ToString()}, { "b_lat", location_bottomright[0].ToString() }, { "b_lng", location_bottomright[1].ToString()}, + { "layerid", LayerID.ToString() }, + { "url", urlbase }, }; //Jint.Native.JsValue JavascriptMainResult = Commun.Javascript.ExecuteScript("function main() { var js = new TheType(); log(js.TestDoubleReturn(0,0)); return args; }", argument); - Layers calque = Layers.GetLayerById(LayerID); - string TileComputationScript; - if (calque is null) - { - return ""; - } - else - { - TileComputationScript = calque.class_tilecomputationscript; - } + + string TileComputationScript = calque.class_tilecomputationscript; + if (!string.IsNullOrEmpty(TileComputationScript)) { Jint.Native.JsValue JavascriptMainResult = null; try { - //JavascriptMainResult = Commun.Javascript.ExecuteScript(TileComputationScript, argument, LayerID); - DebugMode.WriteLine("DEBUG JS : LayerId" + LayerID); - JavascriptMainResult = Commun.Javascript.ExecuteScript(TileComputationScript, argument, LayerID); + JavascriptMainResult = Commun.Javascript.ExecuteScript(TileComputationScript, argument, LayerID, InvokeFunction); } catch (Exception ex) { @@ -112,6 +122,15 @@ public static string FromTileXYZ(string urlbase, int x, int y, int z, int LayerI object JavascriptMainResultObject = JavascriptMainResult.ToObject(); var JavascriptMainResultJson = JsonConvert.SerializeObject(JavascriptMainResultObject); var JavascriptMainResultDictionary = JsonConvert.DeserializeObject>(JavascriptMainResultJson); + + if (JavascriptMainResultDictionary.TryGetValue("url", out string urlResult)) + { + if (!string.IsNullOrEmpty(urlResult)) + { + finalurl = urlResult; + } + } + foreach (var JavascriptReplacementVar in JavascriptMainResultDictionary) { string replacementValue = string.Empty; @@ -138,7 +157,6 @@ public static string FromTileXYZ(string urlbase, int x, int y, int z, int LayerI } } } - numberofurlgenere++; return finalurl; } @@ -184,7 +202,7 @@ public static List GetListOfUrlFromLocation(Dictionary next_num_list = NextNumberFromPara(Download_X_tile, Download_Y_tile, max_x, max_y); @@ -274,7 +292,7 @@ public static string GetSaveTempDirectory(string nom, string identifiant, int zo } //Debug.WriteLine(settings_temp_folder); string nom_charclean = string.Concat(nom.Split(Path.GetInvalidFileNameChars())); - string chemin = System.IO.Path.Combine(settings_temp_folder, nom_charclean + "_" + identifiant + "\\"); + string chemin = System.IO.Path.Combine(settings_temp_folder, "layers", nom_charclean + "_" + identifiant + "\\"); if (zoom != -1) { chemin += zoom + "\\"; @@ -708,13 +726,14 @@ public static string FilterDigitOnly(string origin, List char_supplementai return str; } - public static string Replacements(string origin, string x, string y, string z, int LayerID) + public static string Replacements(string tileBaseUrl, string x, string y, string z, int LayerID, Collectif.GetUrl.InvokeFunction invokeFunction) { //string origin_result = origin; //origin_result = origin_result.Replace("{x}", x); //origin_result = origin_result.Replace("{y}", y); //origin_result = origin_result.Replace("{z}", z); - return Collectif.GetUrl.FromTileXYZ(origin, Convert.ToInt32(x), Convert.ToInt32(y), Convert.ToInt32(z), LayerID).Replace(" ", "%20"); + if (string.IsNullOrEmpty(tileBaseUrl)) { return String.Empty; } + return Collectif.GetUrl.FromTileXYZ(tileBaseUrl, Convert.ToInt32(x), Convert.ToInt32(y), Convert.ToInt32(z), LayerID, invokeFunction).Replace(" ", "%20"); } public static int CheckIfDownloadSuccess(string url) diff --git a/MapsInMyFolder.Common/Javascript.cs b/MapsInMyFolder.Common/Javascript.cs index eb1d741..d853c3c 100644 --- a/MapsInMyFolder.Common/Javascript.cs +++ b/MapsInMyFolder.Common/Javascript.cs @@ -2,6 +2,7 @@ using Jint.Native; using Jint.Runtime.Interop; using ModernWpf.Controls; +using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; @@ -87,20 +88,16 @@ private static Engine SetupEngine(int LayerId) Debug.WriteLine("Error JsListCancelTocken " + ex.Message); } } - else - { - Debug.WriteLine("JsListCancelTocken - An item with the same key has already been added. Key: " + LayerId); - } options.CancellationToken(JsCancelToken.Token); }); - Action PrintAction = stringtext => Javascript.Print(String.Concat(">", stringtext), LayerId); + Action PrintAction = stringtext => Print(stringtext, LayerId); add.SetValue("print", PrintAction); //Action AlertAction = stringtext => Javascript.Alert(stringtext, LayerId); //add.SetValue("alert", AlertAction); - Action PrintClearAction = _ => Javascript.PrintClear(); + Action PrintClearAction = _ => PrintClear(); add.SetValue("printClear", PrintClearAction); add.SetValue("cls", PrintClearAction); - Action helpAction = _ => Javascript.Help(LayerId); + Action helpAction = _ => Help(LayerId); add.SetValue("help", helpAction); Action setVarAction = (variable, value) => Javascript.SetVar(variable, value, LayerId); add.SetValue("setVar", setVarAction); //setVar("variable1","valeur1") @@ -160,7 +157,6 @@ static public void SetVar(object variablename, object value, int LayerId = 0) } } - //todo add get / set parameters + add option to print error from DownloadByteUrl static public object GetVar(object variablename, int LayerId = 0) { string variablenameString; @@ -194,7 +190,7 @@ public static void DisposeVariable(string variablename, int LayerId) if (DictionnaryOfVariablesKeyLayerId.TryGetValue(LayerId, out Dictionary VariableKeyAndValue)) { VariableKeyAndValue.Remove(variablename); - Print("Info : La variable à été disposée"); + Print("< Info : La variable à été disposée"); } else { @@ -271,22 +267,34 @@ public static Dictionary TileToCoordonnees(object TileX, object return returnLocationNumber; } - public static void Print(string print, int LayerId = 0) + private static string ConvertJSObjectToString(object supposedString) + { + + string returnString = supposedString.ToString(); + if ((supposedString.GetType() == typeof(System.Object) || supposedString.GetType() == typeof(System.Object[]) || supposedString.GetType() == typeof(System.Dynamic.ExpandoObject) || supposedString.GetType() == typeof(Dictionary) || supposedString.GetType() == typeof(Dictionary)) + && (supposedString.GetType().FullName != "Jint.Runtime.Interop.DelegateWrapper")) + { + Debug.WriteLine(supposedString.GetType().FullName); + returnString = JsonConvert.SerializeObject(supposedString); + } + return returnString; + } + + + public static void Print(object print, int LayerId = 0) { - if (!string.IsNullOrEmpty(print)) + string printString = ConvertJSObjectToString(print); + if (!string.IsNullOrEmpty(printString)) { - DebugMode.WriteLine("Javascript print : " + LayerId + " " + print); if (LayerId == -2 && Commun.TileGeneratorSettings.AcceptJavascriptPrint) { - Javascript.JavascriptInstance.Logs = String.Concat(Javascript.JavascriptInstance.Logs, "\n", print); - return; + Javascript.JavascriptInstance.Logs = String.Concat(Javascript.JavascriptInstance.Logs, "\n", printString); } } } static public void PrintClear() { - DebugMode.WriteLine("JSClear console"); if (Commun.TileGeneratorSettings.AcceptJavascriptPrint) { Javascript.JavascriptInstance.Logs = String.Empty; @@ -303,73 +311,22 @@ static public string InputBox(int LayerId, object texte, object caption = null) { caption = Collectif.HTMLEntities(Layers.GetLayerById(LayerId).class_name, true) + " indique :"; } - /* - - let x = inputbox("pos"); print(x); - - */ TextBox TextBox; var frame = new DispatcherFrame(); TextBox = Application.Current.Dispatcher.Invoke(new Func(() => { - var dialog_internal_turple = Message.SetInputBoxDialog(texte, caption); - var dialog_internal = dialog_internal_turple.dialog; - dialog_internal.Closed += (_, __) => - { - frame.Continue = false; // stops the frame - }; - dialog_internal.ShowAsync(); - return dialog_internal_turple.textBox; - })); - Dispatcher.PushFrame(frame); - return Application.Current.Dispatcher.Invoke(new Func(() => - { - return TextBox.Text; - })); - } - } - - - static public string InputBox2(int LayerId, object texte, object caption = null) - { - lock (JSLocker) - { - //alert("pos"); - if (string.IsNullOrEmpty(caption?.ToString())) - { - caption = Collectif.HTMLEntities(Layers.GetLayerById(LayerId).class_name, true) + " indique :"; - } - /* - - let x = alert("pos"); print(x); - - */ - ContentDialog dialog; - var frame = new DispatcherFrame(); - dialog = Application.Current.Dispatcher.Invoke(new Func(() => - { - var dialog_internal = Message.SetContentDialog(texte, caption, showTextbox: true); - dialog_internal.Closed += (_, __) => + var (textBox, dialog) = Message.SetInputBoxDialog(texte, caption); + dialog.Closed += (_, __) => { - frame.Continue = false; // stops the frame + // stops the frame + frame.Continue = false; }; - dialog_internal.ShowAsync(); - return dialog_internal; + dialog.ShowAsync(); + return textBox; })); Dispatcher.PushFrame(frame); - - List uIElements = Collectif.FindVisualChildren(dialog.Content as UIElement); - foreach (UIElement element in uIElements) - { - if (element.GetType() == typeof(TextBox)) - { - TextBox textBox = (TextBox)element; - return textBox.Text; - } - } - + return Application.Current.Dispatcher.Invoke(new Func(() => TextBox.Text)); } - return "undefined"; } static public void Alert(int LayerId, object texte, object caption = null) @@ -400,7 +357,7 @@ static public void Help(int LayerId) { Print( "\n\nAIDE CALCUL TUILE" + "\n" + - "A chaque chargement de tuile, la function main est appelée avec des arguments\n" + + "A chaque chargement de tuile, la function getTile est appelée avec des arguments\n" + "et dois retourner un objet contenant les remplacements à effectués.\n" + "Les arguments qui sont envoyé à la fonction de base sont les suivants : " + "\n" + " - X : Représente en WMTS le numero de la tuile X" + "\n" + @@ -408,7 +365,7 @@ static public void Help(int LayerId) " - Z : Représente le niveau de zoom" + "\n" + " - layerid : Représente l'ID du calque sélectionnée" + "\n" + "Exemple pour l'url \"https://tile.openstreetmap.org/{NiveauZoom}/{TuileX}/{TuileY}.png\":" + "\n" + - "function main(args) {" + "\n" + + "function getTile(args) {" + "\n" + "var returnvalue = new Object;" + "\n" + "returnvalue.TuileX = args.x;" + "\n" + "returnvalue.TuileY = args.y;" + "\n" + @@ -427,38 +384,26 @@ static public void Help(int LayerId) "getLatLong(TileX, TileY, zoom) : Converti les numero de tiles en coordonnées" + "\n" + "", LayerId); - /*// - var lat = 48.1995382391003; -var long = 6.42831455369568; - -var tiles = getTileNumber(lat, long, 18) -print("x : " + tiles.x + " / y : " + tiles.y) - -var locations = getLatLong(tiles.x, tiles.y, 18) -print("lat : " + locations.lat + " / long : " + locations.long) - - - */ - Debug.WriteLine("help triggered" + LayerId); } static public void PrintError(string print, int LayerId = -2) { - Print("Error : " + print, LayerId); + string errorType; + if (print.EndsWith(" is not defined")) + { + errorType = "Uncaught ReferenceError"; + } + else if (print.EndsWith("Unexpected token ILLEGAL")) + { + errorType = "Uncaught SyntaxError"; + } + else + { + errorType = "Uncaught Error"; + } + Print("< " + errorType + " : " + print, LayerId); } - //static void Alert(object Message, int LayerId) - //{ - // if (Curent.Layer.class_id == LayerId) - // { - // string text = Message.ToString(); - // if (!string.IsNullOrEmpty(text)) - // { - // MessageBox.Show(text, "MapsInMyFolder"); - // } - // } - //} - #region engines private static readonly Dictionary JsListCancelTocken = new Dictionary(); private static readonly Dictionary ListOfEngines = new Dictionary(); @@ -467,7 +412,6 @@ public static void EngineStopAll() { foreach (KeyValuePair tockensource in JsListCancelTocken) { - DebugMode.WriteLine("Canceled JSengine " + tockensource.Key); tockensource.Value.Cancel(); } } @@ -475,7 +419,6 @@ public static void EngineStopById(int LayerId) { if (JsListCancelTocken.TryGetValue(LayerId, out CancellationTokenSource tockensource)) { - DebugMode.WriteLine("Canceled JSengine " + LayerId); tockensource.Cancel(); } } @@ -489,17 +432,25 @@ public static Engine EngineGetById(int LayerId, string script) } else { - DebugMode.WriteLine("CreateEngine " + LayerId); - if (ListOfEngines.Count > 100) + if (ListOfEngines.Count > 200) { - DebugMode.WriteLine("ClearEngine >100"); + //todo : add setting for that EngineClearList(); } Engine add = SetupEngine(LayerId); try { - add.Execute(script); - return add; + add = add.Execute(script); + if (CheckIfFunctionExist(add, Collectif.GetUrl.InvokeFunction.getTile.ToString())) + { + return add; + } + else + { + add = add.Execute(Settings.tileloader_default_script); + return add; + } + } catch (Exception ex) { @@ -513,7 +464,6 @@ public static Engine EngineGetById(int LayerId, string script) public static void EngineDeleteById(int LayerId) { - DebugMode.WriteLine("RemoveEngine " + LayerId); ListOfEngines.Remove(LayerId); JsListCancelTocken.Remove(LayerId); } @@ -524,61 +474,105 @@ public static void EngineUpdate(Engine engine, int LayerId) public static void EngineClearList() { - DebugMode.WriteLine("ClearEngine"); ListOfEngines.Clear(); JsListCancelTocken.Clear(); } #endregion - public static Jint.Native.JsValue ExecuteScript(string script, Dictionary arguments, int LayerId) + + + public static bool CheckIfFunctionExist(Engine add, string functionName) + { + if (string.IsNullOrEmpty(functionName)) + { + return false; + } + JsValue evaluateValue = add.Evaluate("typeof " + functionName + " === 'function'"); + return evaluateValue.AsBoolean(); + } + + public static bool CheckIfFunctionExist(int LayerId, string functionName, string script = null) { - DebugMode.WriteLine("DEBUG JS : LockLayerId" + LayerId); + if (string.IsNullOrEmpty(functionName)) + { + return false; + } + if (string.IsNullOrEmpty(script)) + { + script = Layers.GetLayerById(LayerId).class_tilecomputationscript; + } + lock (locker) { - DebugMode.WriteLine("DEBUG JS : GetEngineLayerId" + LayerId); Engine add = EngineGetById(LayerId, script); - DebugMode.WriteLine("DEBUG JS : Engine gotLayerId" + LayerId); + if (add is null) + { + return false; + } + JsValue evaluateValue = add.Evaluate("typeof " + functionName + " === 'function'"); + + return evaluateValue.AsBoolean(); + } + } + + public static Jint.Native.JsValue ExecuteScript(string script, Dictionary arguments, int LayerId, Collectif.GetUrl.InvokeFunction InvokeFunction) + { + string InvokeFunctionString = InvokeFunction.ToString(); + lock (locker) + { + Engine add = EngineGetById(LayerId, script); if (add is null) { - DebugMode.WriteLine("DEBUG JS : engine nullLayerId" + LayerId); return null; } Jint.Native.JsValue jsValue = null; try { - DebugMode.WriteLine("DEBUG JS : call mainLayerId" + LayerId); - jsValue = add.Invoke("main", arguments); - //add.SetValue("args", arguments); - //jsValue = add.Evaluate("main(args)"); - DebugMode.WriteLine("DEBUG JS : end call mainLayerId" + LayerId); + jsValue = add.Invoke(InvokeFunctionString, arguments); } catch (Exception ex) { Debug.WriteLine(ex.Message); if (ex.Message == "Can only invoke functions") { - PrintError("No main function fund. Use \"function main(args) {}\""); + //PrintError("No main function fund. Use \"function getT(args) {}\""); + PrintError("La fontion " + InvokeFunction.ToString() + " n'as pas été trouvé dans le script. Faite help() pour obtenir de l'aide sur cette commande."); } else { PrintError(ex.Message); } } - DebugMode.WriteLine("DEBUG JS : update engineLayerId" + LayerId); EngineUpdate(add, LayerId); - DebugMode.WriteLine("DEBUG JS : returnLayerId" + LayerId); - return jsValue; } } public static void ExecuteCommand(string command, int LayerId) { - Debug.WriteLine("ExecuteCommand LayerId" + LayerId); var add = EngineGetById(LayerId, ""); try { - add.Evaluate(command); + Print("> " + command, LayerId); + string evaluateResultString = string.Empty;// add.Evaluate(command).ToString(); + JsValue evaluateResult = add.Evaluate(command); + if ((evaluateResult.IsArray() || evaluateResult.IsObject()) && evaluateResult.GetType().FullName != "Jint.Runtime.Interop.DelegateWrapper") + { + evaluateResultString = evaluateResult.ToString().Replace("[]", "") + JsonConvert.SerializeObject(evaluateResult.ToObject()); + } + else + { + evaluateResultString = evaluateResult.ToString(); + if (evaluateResult.IsString()) + { + evaluateResultString = "\"" + evaluateResultString + "\""; + } + + } + if (!string.IsNullOrEmpty(evaluateResultString) && evaluateResultString != "null") + { + Print("< " + evaluateResultString, LayerId); + } } catch (Exception ex) { diff --git a/MapsInMyFolder.Common/Layers.cs b/MapsInMyFolder.Common/Layers.cs index 8954f34..c70d836 100644 --- a/MapsInMyFolder.Common/Layers.cs +++ b/MapsInMyFolder.Common/Layers.cs @@ -51,7 +51,7 @@ public Layers(int class_id, bool class_favorite, string class_name, string class public static Layers Empty(int LayerId = -1) { - return new Layers(LayerId, false, "", "Une erreur s'est produite dans la lecture des données. \n Données de secours fournie par OpenStreetMap.", "", "", "http://tile.openstreetmap.org/{z}/{x}/{y}.png", "", "", 0, 19, "jpeg", 256, "function main(args){return args;}", new SpecialsOptions()); + return new Layers(LayerId, false, "", "Une erreur s'est produite dans la lecture des données. \n Données de secours fournie par OpenStreetMap.", "", "", "http://tile.openstreetmap.org/{z}/{x}/{y}.png", "", "", 0, 19, "jpeg", 256, "function getTile(args){return args;}", new SpecialsOptions()); } public static class Convert diff --git a/MapsInMyFolder.Common/Settings.cs b/MapsInMyFolder.Common/Settings.cs index 12f7f62..26ef741 100644 --- a/MapsInMyFolder.Common/Settings.cs +++ b/MapsInMyFolder.Common/Settings.cs @@ -43,6 +43,8 @@ public static class Settings public static int max_retry_download = 3; //Nombre max de passe lors du telechargement d'un calque | Default=3 public static int max_redirection_download_tile = 5; //Nombre max de passe de redirection d'une tuile public static int tiles_cache_expire_after_x_days = 1; //Nombre de jours apres lequel retelecharger les tuiles | Default=1 + public static bool nettoyer_cache_browser_au_demarrage = true; + public static bool nettoyer_cache_layers_au_demarrage = false; public static int max_download_project_in_parralele = 1; //Nombre telechargement en para | Default=1 public static int max_download_tiles_in_parralele = 10; //Nombre telechargement de tuile en para | Default=10 public static int waiting_before_start_another_tile_download = 0; //Nombre de milisecondes entre chaque téléchargement d'une tuile (seulement si max_download_tiles_in_parralele = 1 de préférence) @@ -62,7 +64,7 @@ public static class Settings public static double SE_PIN_starting_location_longitude = 6.45085; public static int map_defaut_zoom_level = 18; public static bool zoom_limite_taille_carte = false; //Empeche de zoomer au dela de la limite de la carte - public static string tileloader_default_script = "//default script\nfunction main(args) {\n return args;\n}"; //todo : https in github + public static string tileloader_default_script = "//default script\nfunction getTile(args) {\n return args;\n}"; public static string user_agent = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; //public static string user_agent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 Edg/103.0.1264.62"; diff --git a/MapsInMyFolder.Common/TileGenerator.GenericFileFormat_Tiles.cs b/MapsInMyFolder.Common/TileGenerator.GenericFileFormat_Tiles.cs index 156c27e..eb2cc75 100644 --- a/MapsInMyFolder.Common/TileGenerator.GenericFileFormat_Tiles.cs +++ b/MapsInMyFolder.Common/TileGenerator.GenericFileFormat_Tiles.cs @@ -25,7 +25,7 @@ public async Task GetTile(int layerID, string urlBase, int TileX, try { - Uri uri = new Uri(Collectif.GetUrl.FromTileXYZ(urlBase, TileX, TileY, zoom, layerID)); + Uri uri = new Uri(Collectif.GetUrl.FromTileXYZ(urlBase, TileX, TileY, zoom, layerID, Collectif.GetUrl.InvokeFunction.getTile)); return await Collectif.ByteDownloadUri(uri, layerID, true); } catch (Exception ex) diff --git a/MapsInMyFolder.Common/TileGenerator.PBF_Tiles.cs b/MapsInMyFolder.Common/TileGenerator.PBF_Tiles.cs index 044bc41..f47dae2 100644 --- a/MapsInMyFolder.Common/TileGenerator.PBF_Tiles.cs +++ b/MapsInMyFolder.Common/TileGenerator.PBF_Tiles.cs @@ -127,7 +127,7 @@ public async Task PBF_RenderingAsync(int tache, int layerID, strin string save_filename = save_temp_directory_rawBPF + filename; if (do_download_this_tile) { - Uri uri = new Uri(Collectif.GetUrl.FromTileXYZ(urlBase, TileX, TileY, zoom, layerID)); + Uri uri = new Uri(Collectif.GetUrl.FromTileXYZ(urlBase, TileX, TileY, zoom, layerID, Collectif.GetUrl.InvokeFunction.getTile)); DebugMode.WriteLine("Tache n°" + tache + " : Telechargement u1"); response = await Collectif.ByteDownloadUri(uri, layerID, true); if (response?.Buffer is null) @@ -294,7 +294,7 @@ public async Task PBF_RenderingAsync(int tache, int layerID, strin HttpResponse tp_response = HttpResponse.HttpResponseError; try { - Uri temp_uri = new Uri(Collectif.GetUrl.FromTileXYZ(urlBase, TileX_tp, TileY_tp, zoom, layerID)); + Uri temp_uri = new Uri(Collectif.GetUrl.FromTileXYZ(urlBase, TileX_tp, TileY_tp, zoom, layerID, Collectif.GetUrl.InvokeFunction.getTile)); tp_response = await Collectif.ByteDownloadUri(temp_uri, 0, true).ConfigureAwait(false); if (tp_response?.Buffer is null) { diff --git a/MapsInMyFolder.MapControl/MapControl/ImageLoader.WPF.cs b/MapsInMyFolder.MapControl/MapControl/ImageLoader.WPF.cs index 22c5599..e5515df 100644 --- a/MapsInMyFolder.MapControl/MapControl/ImageLoader.WPF.cs +++ b/MapsInMyFolder.MapControl/MapControl/ImageLoader.WPF.cs @@ -14,7 +14,7 @@ public static partial class ImageLoader { public static Task LoadImageAsync(Stream stream) { - Debug.WriteLine("LoadImageAsync from stream task "); + //LoadImageAsync from stream task return Task.Run(() => LoadImage(stream)); } @@ -23,7 +23,7 @@ public static Task LoadImageAsync(byte[] buffer) return Task.Run(() => { using var stream = new MemoryStream(buffer); - Commun.DebugMode.WriteLine("LoadImageAsync from buffer "); + //Loading tile from buffer return LoadImage(stream); }); } @@ -38,7 +38,7 @@ public static Task LoadImageAsync(string path) } using var stream = File.OpenRead(path); - Commun.DebugMode.WriteLine("LoadImageAsync read file path " + path); + //LoadImageAsync read file path return LoadImage(stream); }); } @@ -46,16 +46,19 @@ public static Task LoadImageAsync(string path) private static ImageSource LoadImage(Stream stream) { var bitmapImage = new BitmapImage(); - try { - bitmapImage.BeginInit(); - bitmapImage.CacheOption = BitmapCacheOption.OnLoad; - bitmapImage.StreamSource = stream; - bitmapImage.EndInit(); - bitmapImage.Freeze(); - }catch(System.NotSupportedException ex) + try + { + bitmapImage.BeginInit(); + bitmapImage.CacheOption = BitmapCacheOption.OnLoad; + bitmapImage.StreamSource = stream; + bitmapImage.EndInit(); + bitmapImage.Freeze(); + } + catch (System.NotSupportedException ex) { Debug.WriteLine("Erreur, ce format d'image n'est pas supporté : " + ex.Message); - }catch(System.Exception ex) + } + catch (System.Exception ex) { Debug.WriteLine("Erreur lors du chargement de l'apperçu : " + ex.Message); } diff --git a/MapsInMyFolder.MapControl/MapControl/ImageLoader.cs b/MapsInMyFolder.MapControl/MapControl/ImageLoader.cs index 2794a22..8f4ec14 100644 --- a/MapsInMyFolder.MapControl/MapControl/ImageLoader.cs +++ b/MapsInMyFolder.MapControl/MapControl/ImageLoader.cs @@ -34,13 +34,9 @@ public static async Task LoadImageAsync(Uri uri, int x = 0, int y = } else if (uri.Scheme == "http" || uri.Scheme == "https") { - Debug.WriteLine("Download tile g " + uri.ToString()); - //var response = await GetHttpResponseAsync(uri); - // Commun.HttpResponse response; if (z != -1) { - //todo : what is that ? string SaveTempDir = ""; string fileformat = string.Empty; if (!(tileSource is null) && tileSource.LayerID != 0) @@ -66,7 +62,6 @@ public static async Task LoadImageAsync(Uri uri, int x = 0, int y = if (response?.Buffer != null && response.ResponseMessage.IsSuccessStatusCode) { - Debug.WriteLine("Load from LoadImageAsync"); image = await LoadImageAsync(response.Buffer).ConfigureAwait(false); } } diff --git a/MapsInMyFolder.MapControl/MapControl/TileSource.cs b/MapsInMyFolder.MapControl/MapControl/TileSource.cs index 0fb177b..27d57bd 100644 --- a/MapsInMyFolder.MapControl/MapControl/TileSource.cs +++ b/MapsInMyFolder.MapControl/MapControl/TileSource.cs @@ -55,8 +55,7 @@ public virtual Uri GetUri(int x, int y, int zoomLevel) // .Replace("{x}", x.ToString()) // .Replace("{y}", y.ToString()) // .Replace("{z}", zoomLevel.ToString()); - - var uriString = Collectif.GetUrl.FromTileXYZ(UriFormat, x, y, zoomLevel, LayerID); + var uriString = Collectif.GetUrl.FromTileXYZ(UriFormat, x, y, zoomLevel, LayerID, Collectif.GetUrl.InvokeFunction.getTile); if (Subdomains != null && Subdomains.Length > 0) { diff --git a/MapsInMyFolder.Setup/Product.wxs b/MapsInMyFolder.Setup/Product.wxs index d50b042..360a126 100644 --- a/MapsInMyFolder.Setup/Product.wxs +++ b/MapsInMyFolder.Setup/Product.wxs @@ -3,7 +3,7 @@ - + diff --git a/MapsInMyFolder.VectorTileRenderer/SkiaCanvas.cs b/MapsInMyFolder.VectorTileRenderer/SkiaCanvas.cs index 810b553..c30b3ee 100644 --- a/MapsInMyFolder.VectorTileRenderer/SkiaCanvas.cs +++ b/MapsInMyFolder.VectorTileRenderer/SkiaCanvas.cs @@ -546,12 +546,6 @@ bool CheckPathSqueezing(List path) var angle = Math.Atan2(vector.Y, vector.X); var angleDiff = Math.Abs(GetAbsoluteDiff2Angles(angle, previousAngle)); - //var length = vector.Length / textHeight; - //var curve = angleDiff / length; - //maxCurve = Math.Max(curve, maxCurve); - - //todo : add custom setting ici pour gerer la toelrence - //if (angleDiff > Math.PI / 3) if (angleDiff > Math.PI / 2) { return true; diff --git a/MapsInMyFolder/App.xaml.cs b/MapsInMyFolder/App.xaml.cs index 2475249..caf35bb 100644 --- a/MapsInMyFolder/App.xaml.cs +++ b/MapsInMyFolder/App.xaml.cs @@ -37,6 +37,14 @@ public static bool HasWritePermission(string tempfolderpath) public App() { + try + { + Commun.Settings.LoadSetting(); + } + catch (Exception ex) + { + Debug.WriteLine(ex.Message); + } try { Thread.CurrentThread.CurrentCulture = new CultureInfo("en"); @@ -48,7 +56,38 @@ public App() { settings.BrowserSubprocessPath = System.IO.Path.GetFullPath("CefSharp.BrowserSubprocess.exe"); } - settings.CachePath = Commun.Settings.temp_folder; + string cefsharpTempFolderPath = Path.Combine(Commun.Settings.temp_folder, "panel"); + if (Settings.nettoyer_cache_browser_au_demarrage) + { + try + { + if (Directory.Exists(cefsharpTempFolderPath)) + { + Directory.Delete(cefsharpTempFolderPath, true); + } + } + catch (Exception ex) + { + Debug.WriteLine("Impossible de nettoyer le cache" + cefsharpTempFolderPath + "\n" + ex.Message); + } + } + string layersTempFolderPath = Path.Combine(Commun.Settings.temp_folder, "layers"); + if (Settings.nettoyer_cache_layers_au_demarrage) + { + try + { + if (Directory.Exists(layersTempFolderPath)) + { + Directory.Delete(layersTempFolderPath, true); + } + } + catch (Exception ex) + { + Debug.WriteLine("Impossible de nettoyer le cache" + layersTempFolderPath + "\n" + ex.Message); + } + } + Directory.CreateDirectory(cefsharpTempFolderPath); + settings.CachePath = cefsharpTempFolderPath; if (!Directory.Exists(Commun.Settings.working_folder)) { @@ -76,8 +115,8 @@ public App() } } - settings.UserDataPath = Commun.Settings.temp_folder; - settings.LogFile = Path.Combine(Commun.Settings.temp_folder, "internalBrowserLogs.log"); + settings.UserDataPath = cefsharpTempFolderPath; + settings.LogFile = Path.Combine(cefsharpTempFolderPath, "internalBrowserLogs.log"); settings.RegisterScheme(new CefCustomScheme { SchemeName = "localfolder", @@ -118,15 +157,15 @@ private void OnDispatcherUnhandledException(object sender, System.Windows.Thread { try { + Debug.WriteLine(e.Exception.ToString()); e.Handled = true; - System.IO.File.WriteAllText(Path.Combine(Commun.Settings.working_folder,"crash.log"), e.Exception.Message + Environment.NewLine + e.Exception.StackTrace + Environment.NewLine + Environment.NewLine + "Error string \n" + e.Exception.ToString(), System.Text.Encoding.UTF8); - DebugMode.WriteLine(e.Exception.ToString()); + System.IO.File.WriteAllText(Path.Combine(Commun.Settings.working_folder, "crash.log"), e.Exception.Message + Environment.NewLine + e.Exception.StackTrace + Environment.NewLine + Environment.NewLine + "Error string \n" + e.Exception.ToString(), System.Text.Encoding.UTF8); MessageBox.Show("Une erreur innatendu s'est produite, l'application va devoir se fermer. \n" + e.Exception.ToString(), "Erreur fatale"); //Message.NoReturnBoxAsync("Une erreur innatendu s'est produite, l'application va devoir se fermer", "Erreur"); } catch (Exception ex) { - DebugMode.WriteLine(ex.ToString()); + Debug.WriteLine(ex.ToString()); } finally { @@ -137,6 +176,7 @@ private void OnDispatcherUnhandledException(object sender, System.Windows.Thread private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Exception ex = e.ExceptionObject as Exception; + Debug.WriteLine(ex.ToString()); System.IO.File.WriteAllText(ex.Message + Environment.NewLine + ex.StackTrace, "log.txt"); //En cas d'erreur CEFSHARP.CORE.RUNTIME introuvable alors intaller vc_redist.x64 (https://aka.ms/vs/17/release/vc_redist.x64.exe) } diff --git a/MapsInMyFolder/CustomOrEditLayersPage.xaml b/MapsInMyFolder/CustomOrEditLayersPage.xaml index 037ab45..2e0fa38 100644 --- a/MapsInMyFolder/CustomOrEditLayersPage.xaml +++ b/MapsInMyFolder/CustomOrEditLayersPage.xaml @@ -34,7 +34,7 @@