Exemple #1
0
        private IDisposable GivenAMap(
            MapSource source = MapSource.Class,
            MapWith target   = MapWith.DerivedA)
        {
            switch (source)
            {
            case MapSource.Class:
                switch (target)
                {
                case MapWith.DerivedA:
                    return(GivenAMapping <BaseClass, DerivedA>());

                case MapWith.DerivedB:
                    return(GivenAMapping <BaseClass, DerivedB>());
                }
                break;

            case MapSource.Interface:
                switch (target)
                {
                case MapWith.DerivedA:
                    return(GivenAMapping <INamedClass, DerivedA>());

                case MapWith.DerivedB:
                    return(GivenAMapping <INamedClass, DerivedB>());
                }
                break;
            }
            return(null);
        }
        private void SelectCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GeoPoint newCenter = GetMapCenter();

            switch (selectCombo.SelectedIndex)
            {
            case 0:     // Bing
                _downloadAerial = new BingAerialRepository();
                if (_isMapLoaded)
                {
                    map.Center    = new Location(newCenter.lat, newCenter.lng);
                    map.ZoomLevel = Convert.ToInt32(wbMain.InvokeScript("getZoomLevel"));
                }
                map.Visibility    = Visibility.Visible;
                wbMain.Visibility = Visibility.Hidden;
                _mapSource        = MapSource.Bing;
                break;

            case 1:     // Google Maps
                _downloadAerial = new GoogleMapsAerialRepository();
                if (_isMapLoaded)
                {
                    wbMain.InvokeScript("setCenter", $"{newCenter.lat},{newCenter.lng}");
                    wbMain.InvokeScript("setZoom", map.ZoomLevel);
                }
                wbMain.Visibility = Visibility.Visible;
                map.Visibility    = Visibility.Hidden;
                _mapSource        = MapSource.Google;
                break;
            }
        }
Exemple #3
0
        public HotelFloorPlanViewModel()
        {
            var path = "QSF.Examples.MapControl.HotelFloorPlanExample.Data.";

            this.BaseSource            = MapSource.FromResource(path + "Hotel_base.shp", typeof(HotelFloorPlanViewModel));
            this.CorridorsSource       = MapSource.FromResource(path + "Hotel_Corridors.shp", typeof(HotelFloorPlanViewModel));
            this.ServiceRoomsSource    = MapSource.FromResource(path + "Hotel_ServiceRooms.shp", typeof(HotelFloorPlanViewModel));
            this.LiftsAndLaddersSource = MapSource.FromResource(path + "Hotel_LiftsAndLadders.shp", typeof(HotelFloorPlanViewModel));
            this.RoomsSource           = MapSource.FromResource(path + "Hotel_Rooms.shp", typeof(HotelFloorPlanViewModel));
            this.RoomsDataSource       = MapSource.FromResource(path + "Hotel_Rooms.dbf", typeof(HotelFloorPlanViewModel));

            this.RoomStates = new ObservableCollection <RoomState>();
            this.RoomStates.Add(new RoomState("Reserved", Color.FromHex("#A8A9AA")));
            this.RoomStates.Add(new RoomState("Free", Color.FromHex("#46B2D6")));
            this.RoomStates.Add(new RoomState("Service Room", Color.FromHex("#7E7E7E")));

            this.RegistrationText = "Reserve";

            this.RegisterCommand   = new Command(OnRegisterCommandExecuted);
            this.IsRegisterEnabled = false;

            this.ShapeStyleSelector = this.GetShapeStyleSelector();

            this.cancellation = new CancellationTokenSource();
        }
        public ShapeStyle()
        {
            InitializeComponent();

            var source = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp");

            this.reader.Source = source;
        }
            public void SaveValue()
            {
                Application.Current.Properties[SystemLangParamName]           = SystemLang.ToString();
                Application.Current.Properties[MapSourceParamName]            = MapSource.ToString();
                Application.Current.Properties[DataMidificationHashParamName] = DataMidificationHash;

                SaveCategoryFilter();
            }
Exemple #6
0
        public ProgrammaticZoom()
        {
            InitializeComponent();

            var source = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp");

            this.reader.Source = source;
        }
Exemple #7
0
 public void OveriddenClassTypeMustResolve(MapSource sourceType)
 {
     using (GivenAMap(sourceType))
     {
         var instance = WhenInstanceIsResolved(sourceType);
         ThenTheInstanceMustBe(instance);
     }
 }
 void CalculateMapPosition(double left, double top)
 {
     if (null != MapSource && 0 != this.lookupWindow.Width && 0 != this.lookupWindow.Height)
     {
         MapSource.ScrollToHorizontalOffset((left / this.lookupWindow.Width) * VisibleSourceWidth);
         MapSource.ScrollToVerticalOffset((top / this.lookupWindow.Height) * VisibleSourceHeight);
     }
 }
Exemple #9
0
 public Source(int ID)
 {
     SourceID = ID;
     mapsource = new MapSource(SourceID);
     personsource1 = new PersonSource(0);
     personsource2 = new PersonSource(1);
     bombsource = new BombSource(SourceID);
     musicsource = new MusicSource(SourceID);
 }
Exemple #10
0
 public Source(int ID)
 {
     SourceID      = ID;
     mapsource     = new MapSource(SourceID);
     personsource1 = new PersonSource(0);
     personsource2 = new PersonSource(1);
     bombsource    = new BombSource(SourceID);
     musicsource   = new MusicSource(SourceID);
 }
Exemple #11
0
        public SetBestView()
        {
            InitializeComponent();

            var assembly = this.GetType().Assembly;
            var source   = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp", assembly);

            this.reader.Source = source;
        }
        public MapGettingStartedXaml()
        {
            InitializeComponent();

            // >> map-gettingstarted-setting-source
            var source = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp");

            this.reader.Source = source;
            // << map-gettingstarted-setting-source
        }
	    public void SetMapSource(MapSource map)
	    {
			var oldProj = CurrentMapSource.Projection;

			CurrentMapSource = MapSources[(int)map];

			if (!oldProj.Equals(CurrentMapSource.Projection)) {
				updateTiles = true;
			}
	    }
Exemple #14
0
        public ShapeLabelStyle()
        {
            InitializeComponent();

            var assembly   = this.GetType().Assembly;
            var source     = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp", assembly);
            var dataSource = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.dbf", assembly);

            this.reader.Source     = source;
            this.reader.DataSource = dataSource;
        }
Exemple #15
0
        public LabelAttributeName()
        {
            InitializeComponent();

            // >> map-labels-settintsource
            var source     = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp");
            var dataSource = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.dbf");

            this.reader.Source     = source;
            this.reader.DataSource = dataSource;
            // << map-labels-settintsource
        }
Exemple #16
0
    public EnlargeMapExample()
    {
        Source = MapSource.OpenStreetMap;
        X      = 0;
        Y      = 1;
        Z      = 1;

        currentSource = MapSource.OpenStreetMap;
        currentX      = -1;
        currentY      = -1;
        currentZ      = -1;
    }
        public FirstLookView()
        {
            InitializeComponent();

            var souce      = MapSource.FromResource("QSF.Examples.MapControl.FirstLookExample.usa.shp", typeof(FirstLookView));
            var dataSource = MapSource.FromResource("QSF.Examples.MapControl.FirstLookExample.usa.dbf", typeof(FirstLookView));

            this.shapeReader.Source     = souce;
            this.shapeReader.DataSource = dataSource;

            this.BindingContext = new FirstLookViewModel();
        }
        public InteractionMode()
        {
            InitializeComponent();

            // >> map-interactionmode-settintsource
            var source = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp");

            this.reader.Source = source;
            // << map-interactionmode-settintsource

            this.interactionModePicker.ItemsSource = Enum.GetValues(typeof(Telerik.XamarinForms.Map.InteractionMode));
        }
Exemple #19
0
        public ProgrammaticSelection()
        {
            InitializeComponent();

            // >> map-selection-settintsource
            var source     = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp");
            var dataSource = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.dbf");

            this.reader.Source     = source;
            this.reader.DataSource = dataSource;
            // << map-selection-settintsource

            this.smPicker.ItemsSource = Enum.GetValues(typeof(Telerik.XamarinForms.Map.SelectionMode));
        }
Exemple #20
0
        private INamedClass WhenInstanceIsResolved(MapSource sourceType = MapSource.Class)
        {
            switch (sourceType)
            {
            case MapSource.Class:
                return(default(BaseClass).Resolve());

            case MapSource.Interface:
                return(default(INamedClass).Resolve());

            default:
                throw new NotImplementedException();
            }
        }
Exemple #21
0
        private void WhenThreadMapsToXThenThreadResolvesToX(MapSource sourceType, MapWith target)
        {
            var instance = WhenInstanceIsResolved(sourceType);

            ThenInstanceMustBeTheBaseType(instance);

            Console.WriteLine($"mapping to {target}");
            using (GivenAMap(source: sourceType, target: target))
            {
                Thread.Sleep(100);
                Console.WriteLine($"resolving for {target}");
                instance = WhenInstanceIsResolved(sourceType);
                ThenTheInstanceMustBe(instance, target);
            }
        }
Exemple #22
0
 void Update()
 {
     if (currentX != X || currentY != Y || currentZ != Z || currentSource != Source)
     {
         currentX      = X;
         currentY      = Y;
         currentZ      = Z;
         currentSource = Source;
         if (Application.isPlaying)
         {
             StartCoroutine(GetTileTexture());
         }
         SetTransform();
     }
 }
Exemple #23
0
        public void NestedResolveMustUseMapFromOuterScope(MapSource sourceType)
        {
            using (GivenAMap(sourceType, MapWith.DerivedA))
            {
                INamedClass instance = null;
                using (GivenAMap(sourceType, MapWith.DerivedB))
                {
                    instance = WhenInstanceIsResolved(sourceType);
                    ThenTheInstanceMustBe(instance, MapWith.DerivedA);
                }

                instance = WhenInstanceIsResolved(sourceType);
                ThenTheInstanceMustBe(instance, MapWith.DerivedA);
            }
        }
Exemple #24
0
        public void IsolatedMapsMustNotAffectEachOther(MapSource sourceType)
        {
            INamedClass instance = null;

            using (GivenAMap(source: sourceType, target: MapWith.DerivedA))
            {
                instance = WhenInstanceIsResolved(sourceType);
                ThenTheInstanceMustBe(instance, MapWith.DerivedA);
            }

            using (GivenAMap(source: sourceType, target: MapWith.DerivedB))
            {
                instance = WhenInstanceIsResolved(sourceType);
                ThenTheInstanceMustBe(instance, MapWith.DerivedB);
            }
        }
        public MapGettingStartedCSharp()
        {
            // >> map-gettingstarted-csharp
            var map = new RadMap();

            var shapeFileLayer = new ShapefileLayer()
            {
                Reader = new MapShapeReader()
                {
                    Source = MapSource.FromResource("SDKBrowser.Examples.MapControl.world.shp")
                }
            };

            map.Layers.Add(shapeFileLayer);
            // << map-gettingstarted-csharp

            Content = map;
        }
Exemple #26
0
        public DomainModelService.Map CreateNewMapModel(string fileName)
        {
            Stream imageStream = File.OpenRead(fileName);

            byte[] byteArray;
            using (var br = new BinaryReader(imageStream))
            {
                byteArray = br.ReadBytes((int)imageStream.Length);
            }

            var map       = new DomainModelService.Map();
            var mapSource = new MapSource();

            mapSource.BinarySource = byteArray;
            map.MapSource          = mapSource;
            map.Name = "Karte";

            return(map);
        }
    public static IEnumerable <T> To <T>(this MapSource ms) where T : new()
    {
        var srcNames = GetValueTupleNames(ms.methodClass, ms.methodReturnsTupleName);
        var srcMIs   = srcNames.Select((c, i) => new { ItemMI = ms.srcType.GetMember($"Item{i + 1}")[0], Name = c }).ToDictionary(min => min.Name, min => min.ItemMI);
        var destMIs  = srcNames.Select(n => new { members = typeof(T).GetMember(n), Name = n })
                       .Where(mn => mn.members.Length == 1 && srcMIs[mn.Name].GetMemberType() == mn.members[0].GetMemberType())
                       .Select(mn => new { DestMI = mn.members[0], mn.Name })
                       .ToList();

        foreach (var s in ms.src)
        {
            var ans = new T();
            foreach (var MIn in destMIs)
            {
                MIn.DestMI.SetValue(ans, srcMIs[MIn.Name].GetValue(s));
            }
            yield return(ans);
        }
    }
		void SetMapSource (MapSource ms)
		{
			switch (ms) {
			case MapSource.GoogleMaps:
				mapView.MapType = MapViewType.Normal;
				webLegacy.LoadHtmlString("",new NSUrl(""));
				osmLayer.Map = null;
				ocmLayer.Map = null;
				break;
			case MapSource.GoogleSatellite:
				mapView.MapType = MapViewType.Satellite;
				webLegacy.LoadHtmlString("",new NSUrl(""));
				osmLayer.Map = null;
				ocmLayer.Map = null;
				break;
			case MapSource.GoogleTerrain:
				mapView.MapType = MapViewType.Terrain;
				webLegacy.LoadHtmlString("",null);
				osmLayer.Map = null;
				ocmLayer.Map = null;
				break;
			case MapSource.GoogleHybrid:
				mapView.MapType = MapViewType.Hybrid;
				webLegacy.LoadHtmlString("",null);
				osmLayer.Map = null;
				ocmLayer.Map = null;
				break;
			case MapSource.OpenStreetMap:
				// OpenStreetMap
				mapView.MapType = MapViewType.None;
				webLegacy.LoadHtmlString("<html><head></head><body style=\"font-family:sans-serif; margin:0 auto;text-align:left;background-color: transparent; color:#808080 \"><hfill>Data, imagery and map information provided by<br>MapQuest, <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap</a> and contributors, <a href=\"http://wiki.openstreetmap.org/wiki/Legal_FAQ#I_would_like_to_use_OpenStreetMap_maps._How_should_I_credit_you.#\">ODbL</a></body></html>",new NSUrl(""));
				webLegacy.SizeToFit();
				osmLayer.Map = mapView;
				ocmLayer.Map = null;
				break;
			case MapSource.OpenCycleMap:
				// OpenCycleMap
				mapView.MapType = MapViewType.None;
				webLegacy.LoadHtmlString ("<html><head></head><body style=\"font-family:sans-serif; margin:0 auto;text-align:left;background-color: transparent; color:#808080 \"><hfill>Data, imagery and map information provided by<br>MapQuest, <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap</a> and contributors, <a href=\"http://wiki.openstreetmap.org/wiki/Legal_FAQ#I_would_like_to_use_OpenStreetMap_maps._How_should_I_credit_you.#\">ODbL</a></body></html>", new NSUrl (""));
				webLegacy.SizeToFit();
				osmLayer.Map = null;
				ocmLayer.Map = mapView;
				break;
			case MapSource.None:
				mapView.MapType = MapViewType.None;
				webLegacy.LoadHtmlString ("", new NSUrl (""));
				osmLayer.Map = null;
				ocmLayer.Map = null;
				break;
			}

			// Save map source
			NSUserDefaults.StandardUserDefaults.SetInt((int)ms, "MapSource");
		}
Exemple #29
0
        private void InsertDownloadedImageToDocument(MapSource mapSource, AerialImageData imageData)
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            ed.WriteMessage("Image downloaded to: " + imageData.FileName + '\n');

            Transaction tx = ed.Document.Database.TransactionManager.StartTransaction();

            try
            {
                // Lock the document
                Application.DocumentManager.MdiActiveDocument.LockDocument();

                // Get the document database
                Database dwg = Application.DocumentManager.MdiActiveDocument.Database;

                // Get the raster image dictionary id.
                // Create it if it's null.
                ObjectId imageDictId = RasterImageDef.GetImageDictionary(dwg);

                if (imageDictId.IsNull)
                {
                    imageDictId = RasterImageDef.CreateImageDictionary(dwg);
                }

                // Open the image dictionary
                DBDictionary imageDict = tx.GetObject(imageDictId, OpenMode.ForWrite) as DBDictionary;

                // Get the image's name, i.e. Aerial for C:\Aerial.jpg
                string imageName = Path.GetFileName(imageData.FileName).Split('.')[0];

                // Add the image to the dictionary, if it's not already present.
                RasterImageDef rasterImageDef;
                ObjectId       imageDefId;
                bool           rasterDefCreated = false;
                if (imageDict.Contains(imageName))
                {
                    // Get the image reference from the image dictionary.
                    imageDefId     = imageDict.GetAt(imageName);
                    rasterImageDef = tx.GetObject(imageDefId, OpenMode.ForWrite) as RasterImageDef;
                }
                else
                {
                    // Create the raster image definition
                    RasterImageDef newImageDef = new RasterImageDef
                    {
                        SourceFileName = imageData.FileName
                    };

                    // Load the image into the definition
                    newImageDef.Load();

                    // Write the image to the image dictionary
                    imageDict.UpgradeOpen();
                    imageDefId = imageDict.SetAt(imageName, newImageDef);

                    // Notify the transaction of the change.
                    tx.AddNewlyCreatedDBObject(newImageDef, true);

                    rasterImageDef   = newImageDef;
                    rasterDefCreated = true;
                }

                // Open the block table to get the model space ID
                BlockTable bt = tx.GetObject(dwg.BlockTableId, OpenMode.ForRead) as BlockTable;

                // Open the block table record for the model space.
                BlockTableRecord btr = tx.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                // Create the new image and assign it the image definition
                using (RasterImage image = new RasterImage())
                {
                    image.ImageDefId = imageDefId;

                    // Get the scale for the image
                    double width  = DegreesToFeet(Math.Abs(imageData.SWCorner.lng - imageData.NECorner.lng));
                    double height = rasterImageDef.Size.Y * (width / rasterImageDef.Size.X);

                    ed.WriteMessage($"Using {width} for width, and {height} for height.\n");

                    PromptKeywordOptions promptInsPtOpt    = new PromptKeywordOptions("Select insert type [Origin/Real/Choose] <O> : ", "Origin Real Choose");
                    PromptResult         promptInsPtOptRes = ed.GetKeywords(promptInsPtOpt);

                    // Insert the image at the reference point
                    Point3d?insertPt = null;

                    if (promptInsPtOptRes.Status == PromptStatus.OK)
                    {
                        switch (promptInsPtOptRes.StringResult)
                        {
                        case "Real":
                            insertPt = new Point3d(DegreesToFeet(imageData.SWCorner.lat),
                                                   DegreesToFeet(imageData.SWCorner.lng), 0);
                            break;

                        case "Choose":
                            PromptPointOptions insertPtOptions = new PromptPointOptions("Select insert point : ");
                            PromptPointResult  insertPtRes     = ed.GetPoint(insertPtOptions);

                            if (insertPtRes.Status == PromptStatus.OK)
                            {
                                insertPt = insertPtRes.Value;
                            }
                            break;
                        }
                    }

                    if (insertPt == null)
                    {
                        insertPt = new Point3d(0, 0, 0);
                    }

                    // Create the coordinate system to define the width and height.
                    // Otherwise, they will default to the image size in pixels.
                    image.Orientation = new CoordinateSystem3d(insertPt.Value,
                                                               new Vector3d(width, 0, 0), new Vector3d(0, height, 0));

                    // Set the rotation angle for the image.
                    image.Rotation = 0;

                    // Add the new object to the block table (must come before adding extension dict!)
                    btr.AppendEntity(image);

                    // Add the extension dictionary with associated image data.
                    if (image.ExtensionDictionary.IsNull)
                    {
                        image.CreateExtensionDictionary();
                    }

                    DBDictionary extDict = tx.GetObject(image.ExtensionDictionary, OpenMode.ForWrite) as DBDictionary;

                    // Create the Xrecord and result buffer with TypedValue array
                    Xrecord record = new Xrecord();
                    record.Data = new ResultBuffer(new TypedValue[]
                    {
                        new TypedValue((int)DxfCode.Real, imageData.Center.lat),
                        new TypedValue((int)DxfCode.Real, imageData.Center.lng),
                        new TypedValue((int)DxfCode.Real, imageData.NECorner.lat),
                        new TypedValue((int)DxfCode.Real, imageData.NECorner.lng),
                        new TypedValue((int)DxfCode.Real, imageData.SWCorner.lat),
                        new TypedValue((int)DxfCode.Real, imageData.SWCorner.lng),
                        new TypedValue((int)DxfCode.Int32, imageData.Zoom),
                        new TypedValue((int)DxfCode.Int32, (int)imageData.MapType),
                        new TypedValue((int)DxfCode.Int32, (int)mapSource),
                    });

                    extDict.SetAt("ImageData", record);

                    // Add the new objects to the transaction
                    tx.AddNewlyCreatedDBObject(image, true);
                    tx.AddNewlyCreatedDBObject(record, true);

                    // Connect the raster definition and image together so the definition
                    // does not appear as "unreferenced" in the External References palette
                    RasterImage.EnableReactors(true);
                    image.AssociateRasterDef(rasterImageDef);

                    if (rasterDefCreated)
                    {
                        rasterImageDef.Dispose();
                    }
                }

                tx.Commit();

                // TODO: Zoom to aerial
            }
            catch (Exception ex)
            {
                ed.WriteMessage("An error occurred inserting the image: " + ex.Message + '\n');
                ed.WriteMessage("Please try again.\n");
            } finally
            {
                tx.Dispose();
            }
        }
        void SetMapSource(MapSource ms)
        {
            switch (ms)
            {
            case MapSource.GoogleMaps:
                mapView.MapType = MapViewType.Normal;
                webLegacy.LoadHtmlString("", new NSUrl(""));
                osmLayer.Map = null;
                ocmLayer.Map = null;
                break;

            case MapSource.GoogleSatellite:
                mapView.MapType = MapViewType.Satellite;
                webLegacy.LoadHtmlString("", new NSUrl(""));
                osmLayer.Map = null;
                ocmLayer.Map = null;
                break;

            case MapSource.GoogleTerrain:
                mapView.MapType = MapViewType.Terrain;
                webLegacy.LoadHtmlString("", null);
                osmLayer.Map = null;
                ocmLayer.Map = null;
                break;

            case MapSource.GoogleHybrid:
                mapView.MapType = MapViewType.Hybrid;
                webLegacy.LoadHtmlString("", null);
                osmLayer.Map = null;
                ocmLayer.Map = null;
                break;

            case MapSource.OpenStreetMap:
                // OpenStreetMap
                mapView.MapType = MapViewType.None;
                webLegacy.LoadHtmlString("<html><head></head><body style=\"font-family:sans-serif; margin:0 auto;text-align:left;background-color: transparent; color:#808080 \"><hfill>Data, imagery and map information provided by<br>MapQuest, <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap</a> and contributors, <a href=\"http://wiki.openstreetmap.org/wiki/Legal_FAQ#I_would_like_to_use_OpenStreetMap_maps._How_should_I_credit_you.#\">ODbL</a></body></html>", new NSUrl(""));
                webLegacy.SizeToFit();
                osmLayer.Map = mapView;
                ocmLayer.Map = null;
                break;

            case MapSource.OpenCycleMap:
                // OpenCycleMap
                mapView.MapType = MapViewType.None;
                webLegacy.LoadHtmlString("<html><head></head><body style=\"font-family:sans-serif; margin:0 auto;text-align:left;background-color: transparent; color:#808080 \"><hfill>Data, imagery and map information provided by<br>MapQuest, <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap</a> and contributors, <a href=\"http://wiki.openstreetmap.org/wiki/Legal_FAQ#I_would_like_to_use_OpenStreetMap_maps._How_should_I_credit_you.#\">ODbL</a></body></html>", new NSUrl(""));
                webLegacy.SizeToFit();
                osmLayer.Map = null;
                ocmLayer.Map = mapView;
                break;

            case MapSource.None:
                mapView.MapType = MapViewType.None;
                webLegacy.LoadHtmlString("", new NSUrl(""));
                osmLayer.Map = null;
                ocmLayer.Map = null;
                break;
            }

            // Save map source
            NSUserDefaults.StandardUserDefaults.SetInt((int)ms, "MapSource");
        }
Exemple #31
0
        static void Main2(string[] args)
        {
#if !DEBUG
            try
            {
#else
            {
#endif

                Log.WriteLine("----------------------------------------");

                //PartitionManager partitionManager = null;// = new PartitionManager(1, 1, discreteValues);
                int partitionsPerDimension             = 1;
                int?partitionDepth                     = null;
                IPixelFormatProvider pixelFormat       = null;
                IFontProvider        fontProvider      = null;
                string        outputDir                = null;
                List <string> processImages            = new List <string>();
                int           coresToUtilize           = System.Environment.ProcessorCount;
                List <System.Drawing.Color> testColors = new List <System.Drawing.Color>();

                args.ProcessArg(new string[] { "-help", "-?", "-h" }, s =>
                {
                    var assem = System.Reflection.Assembly.GetExecutingAssembly();// typeof(PartitionManager).Assembly;
                    var ns    = assem.EntryPoint.DeclaringType.Namespace;
                    using (Stream stream = assem.GetManifestResourceStream(ns + ".cmdhelp.txt"))
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            while (!reader.EndOfStream)
                            {
                                string ln = reader.ReadLine();
                                Log.WriteLine(ln);
                            }
                        }
                    }
                });

                bool didluts = false;
                args.ProcessArg("-createlut", s =>
                {
                    var colorSpace = Utils.ParseRequiredLCCColorSpaceArgs(args, true);
                    string outfile = null;
                    args.ProcessArg("-o", s2 => { outfile = s2; });
                    List <System.Drawing.Color> palette = new List <System.Drawing.Color>();
                    string paletteName = null;
                    args.ProcessArg("-palette", s2 =>
                    {
                        paletteName = s2;
                        palette.AddRange(Utils.GetNamedPalette(s2));
                    });
                    int levels = 32;
                    args.ProcessArg("-levels", s2 => { levels = int.Parse(s2); });
                    bool useChroma = false;
                    args.ProcessArg("-lcc", s2 => { useChroma = true; });
                    bool neutral = false;
                    args.ProcessArg("-neutral", s2 => { neutral = true; });
                    CreateLUT(paletteName, palette.ToArray(), outfile, colorSpace, levels, useChroma, neutral);
                    didluts = true;
                    return;
                });
                if (didluts)
                {
                    return;
                }

                args.ProcessArg("-listpalettes", s =>
                {
                    Log.WriteLine("Listing palettes:");
                    foreach (var p in typeof(Palettes).GetProperties())
                    {
                        Log.WriteLine("  {0}", p.Name);
                    }
                });

                args.ProcessArg("-viewpalette", s =>
                {
                    Log.WriteLine("Listing palette entries for palette:");
                    Log.WriteLine("{0}", s);
                    var p = Utils.GetNamedPalette(s);
                    Log.WriteLine("{0} entries", p.Length);
                    for (int i = 0; i < p.Length; ++i)
                    {
                        var c = p[i];
                        Log.WriteLine("{0:000}: {1} {2}",
                                      i,
                                      ColorTranslator.ToHtml(c),
                                      ColorMapper.GetNearestName(c));
                    }
                });

                args.ProcessArg("-argsfile", s =>
                {
                    Log.WriteLine("Reading args from file: {0}" + s);
                    var lines = System.IO.File.ReadAllLines(s)
                                .Select(l => l.Split('#')[0])               // remove comments
                                .Where(l => !string.IsNullOrWhiteSpace(l)); // remove empty lines
                    args = lines.Concat(args).ToArray();
                });

                args.ProcessArg("-outdir", o =>
                {
                    outputDir = o;
                });

                MapSource mapSource = MapSource.Create;

                args.ProcessArg("-testpalette", s =>
                {
                    testColors.AddRange(Utils.GetNamedPalette(s));
                });
                args.ProcessArg("-testcolor", s =>
                {
                    testColors.Add(System.Drawing.ColorTranslator.FromHtml(s));
                });

                args.ProcessArg("-partitions", s =>
                {
                    if (s.Contains('x'))
                    {
                        partitionsPerDimension = int.Parse(s.Split('x')[0]);
                        partitionDepth         = int.Parse(s.Split('x')[1]);
                    }
                    else
                    {
                        partitionsPerDimension = int.Parse(s);
                    }
                });

                args.ProcessArg("-processImagesInDir", o =>
                {
                    var files = System.IO.Directory.EnumerateFiles(o, "*", System.IO.SearchOption.TopDirectoryOnly);
                    foreach (var file in files)
                    {
                        processImages.Add(file);
                    }
                });

                args.ProcessArg("-processImage", o =>
                {
                    processImages.Add(o);
                });

                args.ProcessArg("-cores", o =>
                {
                    int a = int.Parse(o);
                    if (a < 1)
                    {
                        a = System.Environment.ProcessorCount - a;
                    }
                    coresToUtilize = a;
                });

                FontFamilyFontProvider fontFamilyProvider = null;

                args.ProcessArg("-fonttype", s =>
                {
                    switch (s.ToLowerInvariant())
                    {
                    case "mono":
                        fontProvider = MonoPaletteFontProvider.ProcessArgs(args);
                        break;

                    case "normal":
                        fontProvider = FontProvider.ProcessArgs(args);
                        break;

                    case "colorkey":
                        fontProvider = ColorKeyFontProvider.ProcessArgs(args);
                        break;

                    case "fontfamily":
                        fontProvider = fontFamilyProvider = FontFamilyFontProvider.ProcessArgs(args);
                        break;

                    default:
                        throw new Exception("Unknown font type: " + s);
                    }
                });

                args.ProcessArg("-pf", s =>
                {
                    switch (s.ToLowerInvariant())
                    {
                    case "square":
                        pixelFormat = SquareLCCPixelFormat.ProcessArgs(args);// HSLPixelFormat.ProcessArgs(args);
                        break;

                    default:
                    case "fivetile":
                        pixelFormat = FiveTilePixelFormat.ProcessArgs(args, fontProvider);
                        break;
                    }
                });

                if (pixelFormat == null)
                {
                    Log.WriteLine("Pixel format not specified.");
                    return;
                    //pixelFormat = NaiveYUVPixelFormat.ProcessArgs(args);
                }
                // emoji12-C64_YUV-2v5x5+2
                if (fontProvider == null)
                {
                    Log.WriteLine("Font information not specified.");
                    return;
                }
                if (pixelFormat == null)
                {
                    Log.WriteLine("Pixel format not specified.");
                    return;
                }

                args.ProcessArg("-calcn", s =>
                {
                    ulong maxMapKeys = ulong.Parse(s);

                    //partitionManager.Init();

                    //ulong partitionCount = (ulong)partitionManager.PartitionCount;
                    //Log.WriteLine("Partition count: {0:N0}", partitionCount);

                    // so the thing about partition count. You can't just divide by partition count,
                    // because in deeper levels most partitions are simply unused / empty.
                    // a decent conservative approximation is to take the first N levels
                    //partitionCount = (ulong)Math.Pow(partitionManager.PartitionsPerDimension, 2.5);// n = 2.5
                    //Log.WriteLine("Adjusted partition count: {0:N0}", partitionCount);
                    Log.WriteLine("Charset count: {0:N0}", fontProvider.CharCount);
                    Log.WriteLine("Cores to utilize: {0:N0}", coresToUtilize);
                    Log.WriteLine("Luma + chroma components: {0:N0}", pixelFormat.DimensionCount);

                    ulong NbasedOnMapSize = (ulong)Math.Floor(Math.Pow(maxMapKeys, 1.0 / pixelFormat.DimensionCount));

                    Log.WriteLine("======================");
                    Log.WriteLine("== THEREFORE, use N={0:N0}", NbasedOnMapSize);
                    Log.WriteLine("======================");

                    System.Environment.Exit(0);
                });

                if (outputDir == null)
                {
                    Log.WriteLine("No output directory was specified.");
                    return;
                }
                outputDir = System.IO.Path.GetFullPath(outputDir);
                Log.WriteLine("Output directory: {0}", outputDir);

                if (!System.IO.Directory.Exists(outputDir))
                {
                    System.IO.Directory.CreateDirectory(outputDir);
                }

                args.ProcessArg("-loadmap", _ =>
                {
                    mapSource = MapSource.Load;
                    // if you're loading, then we want to process the args from that directory.
                    //outputDir = System.IO.Path.GetDirectoryName(s);
                    string argspath = System.IO.Path.Combine(outputDir, "args.txt");
                    var lines       = System.IO.File.ReadAllLines(argspath)
                                      .Select(l => l.Split('#')[0])               // remove comments
                                      .Where(l => !string.IsNullOrWhiteSpace(l)); // remove empty lines
                    args = lines.Concat(args).ToArray();
                });

                string partitionConfigTag = string.Format("p{0}x{1}", partitionsPerDimension, partitionDepth.HasValue ? partitionDepth.ToString() : "N");

                string configTag = string.Format("{0}_{1}_{2}", fontProvider.DisplayName, pixelFormat.PixelFormatString, partitionConfigTag);
                outputDir = System.IO.Path.Combine(outputDir, configTag);
                Log.WriteLine("Ensuring directory exists: {0}", outputDir);
                System.IO.Directory.CreateDirectory(outputDir);

                string logPath = System.IO.Path.Combine(outputDir, "log.txt");
                Log.SetLogFile(logPath);

                string infopath    = System.IO.Path.Combine(outputDir, "args.txt");
                string mapFullPath = System.IO.Path.Combine(outputDir, string.Format("mapfull_{0}.png", configTag));
                string mapRefPath  = System.IO.Path.Combine(outputDir, string.Format("mapref_{0}.png", configTag));
                string mapFontPath = System.IO.Path.Combine(outputDir, string.Format("mapfont_{0}.png", configTag));

                args.ProcessArg("-loadOrCreateMap", _ =>
                {
                    if (System.IO.File.Exists(mapRefPath) && System.IO.File.Exists(mapFontPath))
                    {
                        Log.WriteLine("-loadOrCreateMap: Loading existing map.");
                        mapSource = MapSource.Load;
                    }
                    else
                    {
                        Log.WriteLine("-loadOrCreateMap: Looks like we have to create the map.");
                        mapSource = MapSource.Create;
                    }
                });

                if (mapSource == MapSource.Create)
                {
                    using (var infoFile = new StreamWriter(infopath))
                    {
                        foreach (var arg in args)
                        {
                            infoFile.WriteLine(arg);
                        }
                    }
                }

                HybridMap2 map = null;

                switch (mapSource)
                {
                case MapSource.Create:
                    Log.EnterTask("--- MAP GENERATION");
                    map = new HybridMap2(fontProvider, pixelFormat,
                                         mapFullPath,
                                         mapRefPath,
                                         mapFontPath,
                                         coresToUtilize, partitionsPerDimension, partitionDepth);
                    Log.EndTask();
                    break;

                case MapSource.Load:
                    Log.EnterTask("--- MAP LOAD");
                    map = HybridMap2.LoadFromDisk(outputDir, fontProvider, pixelFormat);
                    Log.EndTask();
                    break;
                }

                if (fontFamilyProvider != null)
                {
                    //string fontImgPath = System.IO.Path.Combine(outputDir, "font.png");
                    //fontFamilyProvider.SaveFontImage(fontImgPath);
                }

                Log.EnterTask("processing images");

                foreach (var c in testColors)
                {
                    map.TestColor(outputDir, ColorF.From(c));
                }

                using (var refMapImage = new Bitmap(mapRefPath))
                    using (var refFontImage = new Bitmap(mapFontPath))
                    {
                        foreach (var file in processImages)
                        {
                            Log.WriteLine("Processing {0}", file);
                            string destFile  = string.Format("test-{0}.png", System.IO.Path.GetFileNameWithoutExtension(file));
                            string destfullp = System.IO.Path.Combine(outputDir, destFile);
                            using (var testImg = new Bitmap(file))
                            {
                                var rv = map.ProcessImageUsingRef(refMapImage, refFontImage, testImg, destfullp);
                                if (fontFamilyProvider != null)
                                {
                                    string str     = fontFamilyProvider.ConvertToText(rv);
                                    string txtpath = System.IO.Path.Combine(outputDir, string.Format("test-{0}.txt", System.IO.Path.GetFileNameWithoutExtension(file)));
                                    System.IO.File.WriteAllText(txtpath, str);
                                }
                            }
                        }
                    }
                Log.EndTask();

#if !DEBUG
            }
            catch (Exception e)
            {
                Log.WriteLine("Exception occurred:\r\n{0}", e);
            }
#else
            }