Esempio n. 1
0
        public void UpdateTexture(Device device, string textureFileName)
        {
            if ((textureFileName != null) && textureFileName.Length > 0)
            {
                if (textureFileName.ToLower().StartsWith("http://") && BaseSavePath != null)
                {
                    // download it
                    try
                    {
                        Uri uri = new Uri(textureFileName);

                        // Set the subdirectory path to the hostname and replace . with _
                        string savePath = uri.Host;
                        savePath = savePath.Replace('.', '_');

                        // build the save file name from the component pieces
                        savePath = BaseSavePath + @"\" + savePath + uri.AbsolutePath;
                        savePath = savePath.Replace('/', '\\');

                        // Offline check
                        if (!World.Settings.WorkOffline)
                        {
                            Net.WebDownload webDownload = new Net.WebDownload(textureFileName);
                            webDownload.DownloadType = Net.DownloadType.Unspecified;
                            webDownload.DownloadFile(savePath);
                        }

                        // reset the texture file name for later use.
                        textureFileName = savePath;
                    }
                    catch { }
                }
            }

            // Clear old texture - don't know if this is necessary so commented out for the moment
            //if (Texture != null)
            //{
            //    Texture.Dispose();
            //}

            if (ImageHelper.IsGdiSupportedImageFormat(textureFileName))
            {
                // Load without rescaling source bitmap
                using (Image image = ImageHelper.LoadImage(textureFileName)) this.LoadImage(device, image);
            }
            else
            {
                // Only DirectX can read this file, might get upscaled depending on input dimensions.
                this.Texture = ImageHelper.LoadIconTexture(textureFileName);
                // Read texture level 0 size
                using (Surface s = this.Texture.GetSurfaceLevel(0))
                {
                    SurfaceDescription desc = s.Description;
                    this.Width  = desc.Width;
                    this.Height = desc.Height;
                }
            }
        }
Esempio n. 2
0
        public override void Initialize(DrawArgs drawArgs)
        {
            if (this.m_points == null)
            {
                this.isInitialized = true;
                return;
            }

            if (this.m_imageUri != null)
            {
                //load image
                if (this.m_imageUri.ToLower().StartsWith("http://"))
                {
                    string             savePath = string.Format("{0}\\image", ConfigurationLoader.GetRenderablePathString(this));
                    System.IO.FileInfo file     = new System.IO.FileInfo(savePath);

                    if (!file.Exists)
                    {
                        //Offline check
                        if (!World.Settings.WorkOffline)
                        {
                            Net.WebDownload download = new Net.WebDownload(this.m_imageUri);

                            if (!file.Directory.Exists)
                            {
                                file.Directory.Create();
                            }

                            download.DownloadFile(file.FullName, Net.DownloadType.Unspecified);
                        }
                    }

                    //file might not have downloaded.  Especially if we are offline
                    if (!file.Exists)
                    {
                        this.m_texture = ImageHelper.LoadTexture(file.FullName);
                    }
                    else
                    {
                        this.m_texture = null;
                    }
                }
                else
                {
                    this.m_texture = ImageHelper.LoadTexture(this.m_imageUri);
                }
            }

            this.UpdateVertices();

            this.isInitialized = true;
        }
        //TODO: Implement Downloading + Uncompressing + Caching 
        private void DownloadParsePlacenames()
        {
            try
            {
                if (m_failed)
                {
                    return;
                }

				//hard coded cache location wtf?
                //string cachefilename = 
                //    Directory.GetParent(System.Windows.Forms.Application.ExecutablePath) +
                //    string.Format("Cache//WFS//Placenames//{0}//{1}_{2}_{3}_{4}.xml.gz", 
                //    this.name, this.west, this.south, this.east, this.north);
				
				
				//...let's use the location from settings instead
				string cachefilename = m_cache.CacheDirectory +
				    string.Format("\\{0}\\WFS\\{1}\\{2}_{3}_{4}_{5}.xml.gz", 
				    this.m_world.Name, this.name, this.west, this.south, this.east, this.north);
				
                
                if (!File.Exists(cachefilename))
                {
                    WebDownload wfsdl = new WebDownload(this.wfsURL);
                    wfsdl.DownloadFile(cachefilename);
                }
                GZipInputStream instream = new GZipInputStream(new FileStream(cachefilename, FileMode.Open));
                XmlDocument gmldoc = new XmlDocument();
                gmldoc.Load(instream);
                XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(gmldoc.NameTable);
                xmlnsManager.AddNamespace("gml", "http://www.opengis.net/gml");
                //HACK: Create namespace using first part of Label Field
                string labelnmspace = labelfield.Split(':')[0];

                if (labelnmspace == "cite")
                {
                    xmlnsManager.AddNamespace(labelnmspace, "http://www.opengeospatial.net/cite");
                }
                else if(labelnmspace == "topp")
                {
                    xmlnsManager.AddNamespace(labelnmspace, "http://www.openplans.org/topp");
                }

                XmlNodeList featureList = gmldoc.SelectNodes("//gml:featureMember", xmlnsManager);
                if (featureList != null)
                {
                
                    ArrayList placenameList = new ArrayList();
                    foreach (XmlNode featureTypeNode in featureList)
                    {
                        XmlNode typeNameNode = featureTypeNode.SelectSingleNode(typename, xmlnsManager);
                        if (typeNameNode == null)
                        {
                            Log.Write(Log.Levels.Debug, "No typename node: " + typename);
                            continue;
                        }
                        XmlNode labelNode = typeNameNode.SelectSingleNode(labelfield, xmlnsManager);
                        if (labelNode == null)
                        {
                            Log.Write(Log.Levels.Debug, "No label node: " + labelfield);
                            continue;
                        }
                        
                        XmlNodeList gmlCoordinatesNodes = featureTypeNode.SelectNodes(".//gml:Point/gml:coordinates", xmlnsManager);
                        if (gmlCoordinatesNodes != null)
                        {
                            foreach (XmlNode gmlCoordinateNode in gmlCoordinatesNodes)
                            {
                                //Log.Write(Log.Levels.Debug, "FOUND " + gmlCoordinatesNode.Count.ToString() + " POINTS");
                                string coordinateNodeText = gmlCoordinateNode.InnerText;
                                string[] coords = coordinateNodeText.Split(',');
                                WorldWindPlacename pn = new WorldWindPlacename();
                                pn.Lon = float.Parse(coords[0], System.Globalization.CultureInfo.InvariantCulture);
                                pn.Lat = float.Parse(coords[1], System.Globalization.CultureInfo.InvariantCulture);
                                pn.Name = labelNode.InnerText;
                                placenameList.Add(pn);
                            }
                        }
                    }

                    m_placeNames = (WorldWindPlacename[])placenameList.ToArray(typeof(WorldWindPlacename));
                }

                if (m_placeNames == null)
                    m_placeNames = new WorldWindPlacename[0];
            }
            catch //(Exception ex)
            {
                //Log.Write(ex);
                if (m_placeNames == null)
                    m_placeNames = new WorldWindPlacename[0];
                m_failed = true;
            }
        }
Esempio n. 4
0
        private void m_RefreshTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (isUpdating) {
                return;
            }

            isUpdating = true;

            if (m_ImageUri == null) {
                return;
            }

            if (m_ImageUri.ToLower().StartsWith("http://")) {
                if (m_SaveFilePath == null) {
                    return;
                }

                //download it
                try {
                    WebDownload webDownload = new WebDownload(m_ImageUri);
                    webDownload.DownloadType = DownloadType.Unspecified;

                    FileInfo saveFile = new FileInfo(m_SaveFilePath);
                    if (!saveFile.Directory.Exists) {
                        saveFile.Directory.Create();
                    }

                    webDownload.DownloadFile(m_SaveFilePath);
                }
                catch {}
            }
            else {
                m_SaveFilePath = m_ImageUri;
            }

            if (m_ImageTexture != null
                && !m_ImageTexture.Disposed) {
                m_ImageTexture.Dispose();
                m_ImageTexture = null;
            }

            if (!File.Exists(m_SaveFilePath)) {
                displayText = "Image Not Found";
                return;
            }

            m_ImageTexture = ImageHelper.LoadTexture(m_SaveFilePath);
            m_surfaceDescription = m_ImageTexture.GetLevelDescription(0);

            int width = ClientSize.Width;
            int height = ClientSize.Height;

            if (ClientSize.Width == 0) {
                width = m_surfaceDescription.Width;
            }
            if (ClientSize.Height == 0) {
                height = m_surfaceDescription.Height;
            }

            if (ParentWidget is Form) {
                Form parentForm = (Form) ParentWidget;
                parentForm.ClientSize = new Size(width, height + parentForm.HeaderHeight);
            }
            else {
                ParentWidget.ClientSize = new Size(width, height);
            }

            ClientSize = new Size(width, height);

            IsLoaded = true;
            isUpdating = false;
            displayText = null;
            if (m_RefreshTime == 0) {
                m_RefreshTimer.Stop();
            }
        }
Esempio n. 5
0
		/// <summary>
		/// Downloads image from web
		/// </summary>
		protected void DownloadImage()
		{
			try
			{
				if(_imagePath!=null)
					Directory.CreateDirectory(Path.GetDirectoryName(this._imagePath));

				using(WebDownload downloadReq = new WebDownload(this._imageUrl))
				{
					downloadReq.ProgressCallback += new DownloadProgressHandler(UpdateDownloadProgress);
					string filePath = getFilePathFromUrl(_imageUrl);
					
					if(_imagePath==null)
					{
						// Download to RAM
						downloadReq.DownloadMemory();
						texture = ImageHelper.LoadTexture(downloadReq.ContentStream);
					}
					else
					{
						downloadReq.DownloadFile(_imagePath);
						UpdateTexture(_imagePath);
					}
					CreateMesh();
					isInitialized = true;
				}
			}
			catch(ThreadAbortException)
			{}
			catch(Exception caught)
			{
				if(!showedError)
				{
					string msg = string.Format("Image download of file\n\n{1}\n\nfor layer '{0}' failed:\n\n{2}",
						name, _imageUrl, caught.Message );
					System.Windows.Forms.MessageBox.Show(msg, "Image download failed.", 
						System.Windows.Forms.MessageBoxButtons.OK, 
						System.Windows.Forms.MessageBoxIcon.Error );
					showedError = true;
				}

				if(_imagePath != null)
				{
					FileInfo imageFile = new FileInfo(_imagePath);
					if(imageFile.Exists)
					{
						UpdateTexture(_imagePath);
						CreateMesh();
						isInitialized = true;
					}
				}
				else
				{
					isOn = false;
				}
			}
		}
Esempio n. 6
0
		public void DownloadImageListUpdate()
		{
			string imageListURL = "http://rapidfire.sci.gsfc.nasa.gov/gallery/WWinventory.txt";
			try
			{
				this.loadSavedFileList(CacheDirectory + "\\CachedModisListNew.txt");
				this.UpdateIcons();
				if(File.Exists(this.imageListFilePath))
				{
					this.labelStatus.Text = "Parsing cached image list...";
					this.parseImageListFile(this.imageListFilePath);
					this.UpdateIcons();
				}

				this.labelStatus.Text = "Downloading new image list...";
				using( WebDownload webDownload = new WebDownload(imageListURL) )
				{
					webDownload.ProgressCallback += new DownloadProgressHandler(updateProgressBar);
					webDownload.DownloadFile(this.imageListFilePath);
				}

				this.labelStatus.Text = "Parsing cached image list...";

				this.parseImageListFile(this.imageListFilePath);
				this.UpdateIcons();

				this.labelStatus.Text = "";
				this.progressBar.Value = 0;
			}
			catch(ThreadAbortException)
			{
				// Shut down by user
			}
			catch(Exception caught)
			{
				Log.Write(caught);
			}
		}
Esempio n. 7
0
		void ProcessRecord( NameValueCollection fields )
		{
			// process the record somewhere
			string projection = fields["projection"];
			if (projection == null)
				return;

			// We currently only support "geographic projection
			if (projection.IndexOf("Plate Carree") < 0)
				return;
			
			string worldFiles = fields["world files"];
			if (worldFiles == null)
				return;
			if(worldFiles.Length <= 3)
				return;
							
			string images = fields["images"];
			if (images==null)
				return;
			string[] parsedImages = images.Trim().Split(' ');

			if (parsedImages.Length <= 0)
				return;
									
			string title = fields["record"];
			if (title == null)
				return;

			RapidFireModisRecord rfmr = new RapidFireModisRecord();
			rfmr.Title = title.Trim();
			rfmr.ImagePaths = parsedImages;

			string rawDateString = rfmr.Title.Split('.')[1].Substring(1);
			DateTime dt = new DateTime(
				Int32.Parse(rawDateString.Substring(0, 4)), 1, 1) + 
				System.TimeSpan.FromDays(Double.Parse(rawDateString.Substring(4, 3)) - 1);

// TODO: Incremental download (date range)
//			if (dateTimePickerBeginDate.Value > dt)
//				return;
			rfmr.dateString = String.Format(CultureInfo.InvariantCulture, "{0}/{1}/{2}", dt.Month, dt.Day, dt.Year);

			// We need the info file for each record....
			string moreInfoUrl = "http://rapidfire.sci.gsfc.nasa.gov/gallery/" + parsedImages[0].Split('/')[0].Trim() + "/" + rfmr.Title + ".txt";

			lock (this.modisList.SyncRoot)
			{
				if (this.modisList.Contains(rfmr.Title))
					return;
			}

			if (!File.Exists(rfmr.DetailFilePath))
			{
				try
				{
					this.labelStatus.Text = string.Format(CultureInfo.CurrentCulture,
						"Downloading {0}/{1}",
						progressBar.Value,progressBar.Maximum);
					using (WebDownload client = new WebDownload(moreInfoUrl))
						client.DownloadFile(rfmr.DetailFilePath);
				}
				catch (Exception)
				{
					//Delete the file in case it was only partially saved...
					if (File.Exists(rfmr.DetailFilePath))
						File.Delete(rfmr.DetailFilePath);
					return;
				}
			}

			if (new FileInfo(rfmr.DetailFilePath).Length<=0)
				return;

			ReadDetails( ref rfmr );

			lock (this.modisList.SyncRoot)
			{
				this.modisList.Add(rfmr.Title, rfmr);
			}

			using (StreamWriter sw = new StreamWriter(CacheDirectory + "\\CachedModisListNew.txt", true, System.Text.Encoding.UTF8))
			{
				sw.WriteLine(rfmr.Title);
				sw.WriteLine(rfmr.Description);
				sw.WriteLine(rfmr.dateString);
				sw.Write(rfmr.ImagePaths[0]);
				for (int image = 1; image < rfmr.ImagePaths.Length; image++)
					sw.Write("*" + rfmr.ImagePaths[image]);
				sw.Write(Environment.NewLine);
				sw.WriteLine(rfmr.west.ToString(CultureInfo.InvariantCulture));
				sw.WriteLine(rfmr.south.ToString(CultureInfo.InvariantCulture));
				sw.WriteLine(rfmr.east.ToString(CultureInfo.InvariantCulture));
				sw.WriteLine(rfmr.north.ToString(CultureInfo.InvariantCulture));
			}
		}
Esempio n. 8
0
		private void btnLoad_Click(object sender, EventArgs e)
		{
			if (tbFileName.Text == "")
				return;


			if (tbFileName.Text.EndsWith(".zip"))
			{
				//MessageBox.Show("Found zip");
				mainapp.InstallFromZip(tbFileName.Text);
				this.Close();
			}

			if (tbFileName.Text.Trim().StartsWith(@"http://"))
			{
				//MessageBox.Show("Found url");
				WebDownload dl = new WebDownload(tbFileName.Text);
				string[] urlList = tbFileName.Text.Trim().Split('/');
				string fileName = urlList[urlList.Length - 1];

				if (fileName.EndsWith(".xml"))
				{
					//MessageBox.Show("Found web xml");
					string dlPath = Path.Combine(MainApplication.Settings.ConfigPath, mainapp.WorldWindow.CurrentWorld.ToString());
					dlPath = Path.Combine(dlPath, fileName);
					
					try
					{
						dl.DownloadFile(dlPath);
					}
					catch (Exception ex)
					{
						MessageBox.Show(ex.Message, "Download error");
						return;
					}

					mainapp.LoadAddon(dlPath);
					this.Close();
				}
				else if (fileName.EndsWith(".cs"))
				{
					//MessageBox.Show("Found web cs");
					string dlPath = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "//Plugins//");
					dlPath = Path.Combine(dlPath, fileName);

					try
					{
						dl.DownloadFile(dlPath);
					}
					catch (Exception ex)
					{
						MessageBox.Show(ex.Message, "Download error");
						return;
					}

					MessageBox.Show("TODO: Load plugin here...");
					this.Close();
				}
			}
			else
			{
				if (!File.Exists(tbFileName.Text))
				{
					MessageBox.Show(tbFileName.Text + " does not exist", "Load error");
					return;
				}

				FileInfo fi = new FileInfo(tbFileName.Text);
				string name = fi.Name;

				if (name.EndsWith(".xml"))
				{
					//MessageBox.Show("Found local xml");
					string dlPath = Path.Combine(MainApplication.Settings.ConfigPath, mainapp.WorldWindow.CurrentWorld.ToString());
					dlPath = Path.Combine(dlPath, name);

					if(!File.Exists(dlPath))
					{
						try
						{
							File.Copy(tbFileName.Text, dlPath);
						}
						catch (Exception ex)
						{
							MessageBox.Show(ex.Message, "Copy error");
							return;
						}
					}

					mainapp.LoadAddon(dlPath);
					this.Close();
				}
				else if (tbFileName.Text.EndsWith(".cs"))
				{
					//MessageBox.Show("Found local cs");
					string dlPath = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "//Plugins//");
					dlPath = Path.Combine(dlPath, name);

					if (!File.Exists(dlPath))
					{
						try
						{
							File.Copy(tbFileName.Text, dlPath);
						}
						catch (Exception ex)
						{
							MessageBox.Show(ex.Message, "Copy error");
							return;
						}
					}

					MessageBox.Show("TODO: Load plugin here...");
					this.Close();
				}
			}
				

		}
Esempio n. 9
0
        public static RenderableObjectList getRenderableFromLayerFile(string layerFile, World parentWorld, Cache cache, bool enableRefresh)
        {
            try {
                XPathDocument docNav = null;
                XPathNavigator nav = null;

                try {
                    docNav = new XPathDocument(layerFile);
                    nav = docNav.CreateNavigator();
                }
                catch (Exception ex) {
                    Log.Write(ex);
                    return null;
                }

                XPathNodeIterator iter = nav.Select("/LayerSet");

                if (iter.Count > 0) {
                    iter.MoveNext();
                    string redirect = iter.Current.GetAttribute("redirect", "");
                    if (redirect != null
                        && redirect.Length > 0) {
                        FileInfo layerFileInfo = new FileInfo(layerFile);

                        try {
                            Angle[] bbox = CameraBase.getViewBoundingBox();
                            string viewBBox = string.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", bbox[0].ToString().TrimEnd('бу'), bbox[1].ToString().TrimEnd('бу'), bbox[2].ToString().TrimEnd('бу'), bbox[3].ToString().TrimEnd('бу'));

                            //See if there is a ? already in the URL
                            int flag = redirect.IndexOf("?");
                            if (flag == -1) {
                                redirect = redirect + "?BBOX=" + viewBBox;
                            }
                            else {
                                redirect = redirect + "&BBOX=" + viewBBox;
                            }

                            WebDownload download = new WebDownload(redirect);

                            string username = iter.Current.GetAttribute("username", "");
                            string password = iter.Current.GetAttribute("password", "");

                            if (username != null) {
                                ////	download.UserName = username;
                                ////	download.Password = password;
                            }

                            FileInfo tempDownloadFile = new FileInfo(layerFile.Replace(layerFileInfo.Extension, "_.tmp"));

                            download.DownloadFile(tempDownloadFile.FullName, DownloadType.Unspecified);

                            tempDownloadFile.Refresh();
                            if (tempDownloadFile.Exists
                                && tempDownloadFile.Length > 0) {
                                FileInfo tempStoreFile = new FileInfo(tempDownloadFile.FullName.Replace("_.tmp", ".tmp"));
                                if (tempStoreFile.Exists) {
                                    tempStoreFile.Delete();
                                }

                                tempDownloadFile.MoveTo(tempStoreFile.FullName);
                            }

                            download.Dispose();

                            using (StreamWriter writer = new StreamWriter(layerFile.Replace(layerFileInfo.Extension, ".uri"), false)) {
                                writer.WriteLine(redirect);
                            }
                        }
                        catch (Exception ex) {
                            Log.Write(ex);
                        }

                        return getRenderableFromLayerFile(layerFile.Replace(layerFileInfo.Extension, ".tmp"), parentWorld, cache);
                    }
                    else {
                        RenderableObjectList parentRenderable = null;

                        string sourceUri = null;
                        if (layerFile.EndsWith(".tmp")) {
                            //get source url
                            using (StreamReader reader = new StreamReader(layerFile.Replace(".tmp", ".uri"))) {
                                sourceUri = reader.ReadLine();
                            }
                        }
                        string refreshString = iter.Current.GetAttribute("Refresh", "");
                        if (refreshString != null
                            && refreshString.Length > 0) {
                            if (iter.Current.Select("Icon").Count > 0) {
                                parentRenderable = new Icons(iter.Current.GetAttribute("Name", ""), (sourceUri != null ? sourceUri : layerFile), TimeSpan.FromSeconds(ParseDouble(refreshString)), parentWorld, cache);
                            }
                                #region by zzm
                            else if (iter.Current.Select("MyIcon").Count > 0) {
                                // add my icon here.
                                parentRenderable = new MyIcons(iter.Current.GetAttribute("Name", ""), (sourceUri != null ? sourceUri : layerFile), TimeSpan.FromSeconds(ParseDouble(refreshString)), parentWorld, cache);
                            }
                            else if (iter.Current.Select("MyChart").Count > 0) {
                                // add chart here.
                                parentRenderable = new MyCharts(iter.Current.GetAttribute("Name", ""), (sourceUri != null ? sourceUri : layerFile), TimeSpan.FromSeconds(ParseDouble(refreshString)), parentWorld, cache);
                            }
                                #endregion

                            else {
                                parentRenderable = new RenderableObjectList(iter.Current.GetAttribute("Name", ""), (sourceUri != null ? sourceUri : layerFile), TimeSpan.FromSeconds(ParseDouble(refreshString)), parentWorld, cache);
                            }
                        }
                        else {
                            if (iter.Current.Select("Icon").Count > 0) {
                                parentRenderable = new Icons(iter.Current.GetAttribute("Name", ""));
                            }
                                #region by zzm
                            else if (iter.Current.Select("MyIcon").Count > 0) {
                                // add my icon here.
                                parentRenderable = new MyIcons(iter.Current.GetAttribute("Name", ""));
                            }
                            else if (iter.Current.Select("MyChart").Count > 0) {
                                // add chart here.
                                parentRenderable = new MyCharts(iter.Current.GetAttribute("Name", ""));
                            }
                                #endregion

                            else {
                                parentRenderable = new RenderableObjectList(iter.Current.GetAttribute("Name", ""));
                            }
                        }

                        parentRenderable.ParentList = parentWorld.RenderableObjects;

                        if (World.Settings.useDefaultLayerStates) {
                            parentRenderable.IsOn = ParseBool(iter.Current.GetAttribute("ShowAtStartup", ""));
                        }
                        else {
                            parentRenderable.IsOn = IsLayerOn(parentRenderable);
                        }

                        parentRenderable.ShowOnlyOneLayer = ParseBool(iter.Current.GetAttribute("ShowOnlyOneLayer", ""));

                        parentRenderable.MetaData.Add("XmlSource", (sourceUri != null ? sourceUri : layerFile));

                        parentRenderable.MetaData.Add("World", parentWorld);
                        parentRenderable.MetaData.Add("Cache", cache);
                        parentRenderable.ParentList = parentWorld.RenderableObjects;

                        string renderPriorityString = iter.Current.GetAttribute("RenderPriority", "");
                        if (renderPriorityString != null) {
                            if (String.Compare(renderPriorityString, "Icons", false) == 0) {
                                parentRenderable.RenderPriority = RenderPriority.Icons;
                            }
                            else if (String.Compare(renderPriorityString, "LinePaths", false) == 0) {
                                parentRenderable.RenderPriority = RenderPriority.LinePaths;
                            }
                            else if (String.Compare(renderPriorityString, "Placenames", false) == 0) {
                                parentRenderable.RenderPriority = RenderPriority.Placenames;
                            }
                            else if (String.Compare(renderPriorityString, "AtmosphericImages", false) == 0) {
                                parentRenderable.RenderPriority = RenderPriority.AtmosphericImages;
                            }
                        }

                        string infoUri = iter.Current.GetAttribute("InfoUri", "");

                        if (infoUri != null
                            && infoUri.Length > 0) {
                            if (parentRenderable.MetaData.Contains("InfoUri")) {
                                parentRenderable.MetaData["InfoUri"] = infoUri;
                            }
                            else {
                                parentRenderable.MetaData.Add("InfoUri", infoUri);
                            }
                        }

                        addImageLayersFromXPathNodeIterator(iter.Current.Select("ImageLayer"), parentWorld, parentRenderable);
                        addQuadTileLayersFromXPathNodeIterator(iter.Current.Select("QuadTileSet"), parentWorld, parentRenderable, cache);
                        addPathList(iter.Current.Select("PathList"), parentWorld, parentRenderable);
                        addPolygonFeature(iter.Current.Select("PolygonFeature"), parentWorld, parentRenderable);
                        addLineFeature(iter.Current.Select("LineFeature"), parentWorld, parentRenderable);
                        addTiledPlacenameSet(iter.Current.Select("TiledPlacenameSet"), parentWorld, parentRenderable);
                        addIcon(iter.Current.Select("Icon"), parentWorld, parentRenderable, cache);
                        addScreenOverlays(iter.Current.Select("ScreenOverlay"), parentWorld, parentRenderable, cache);
                        addChildLayerSet(iter.Current.Select("ChildLayerSet"), parentWorld, parentRenderable, cache);

                        #region by zzm
                        AddMyIcon(iter.Current.Select("MyIcon"), parentWorld, parentRenderable, cache);
                        AddMyChart(iter.Current.Select("MyChart"), parentWorld, parentRenderable, cache);
                        AddMesh(iter.Current.Select("MeshLayer"), parentWorld, parentRenderable, cache);
                        #endregion

                        addExtendedInformation(iter.Current.Select("ExtendedInformation"), parentRenderable);

                        if (parentRenderable.RefreshTimer != null && enableRefresh) {
                            parentRenderable.RefreshTimer.Start();
                        }
                        return parentRenderable;
                    }
                }
            }
            catch (Exception ex) {
                Log.Write(ex);
                //Utility.Log.Write(layerFile);
            }
            return null;
        }
Esempio n. 10
0
        private void refreshTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (isUpdating) {
                return;
            }
            isUpdating = true;
            try {
                for (int i = 0; i < this.ChildObjects.Count; i++) {
                    RenderableObject ro = (RenderableObject) this.ChildObjects[i];
                    if (ro != null && ro.IsOn
                        && ro is Icon) {
                        Icon icon = (Icon) ro;

                        if (icon.RefreshInterval == TimeSpan.MaxValue
                            || icon.LastRefresh > DateTime.Now - icon.RefreshInterval) {
                            continue;
                        }

                        object key = null;
                        IconTexture iconTexture = null;

                        if (icon.TextureFileName != null
                            && icon.TextureFileName.Length > 0) {
                            if (icon.TextureFileName.ToLower().StartsWith("http://")
                                && icon.SaveFilePath != null) {
                                //download it
                                try {
                                    WebDownload webDownload = new WebDownload(icon.TextureFileName);
                                    webDownload.DownloadType = DownloadType.Unspecified;

                                    FileInfo saveFile = new FileInfo(icon.SaveFilePath);
                                    if (!saveFile.Directory.Exists) {
                                        saveFile.Directory.Create();
                                    }

                                    webDownload.DownloadFile(saveFile.FullName);
                                }
                                catch {}

                                iconTexture = (IconTexture) m_textures[icon.SaveFilePath];
                                if (iconTexture != null) {
                                    IconTexture tempTexture = iconTexture;
                                    m_textures[icon.SaveFilePath] = new IconTexture(DrawArgs.StaticDevice, icon.SaveFilePath);
                                    tempTexture.Dispose();
                                }
                                else {
                                    key = icon.SaveFilePath;
                                    iconTexture = new IconTexture(DrawArgs.StaticDevice, icon.SaveFilePath);

                                    // New texture, cache it
                                    m_textures.Add(key, iconTexture);

                                    // Use default dimensions if not set
                                    if (icon.Width == 0) {
                                        icon.Width = iconTexture.Width;
                                    }
                                    if (icon.Height == 0) {
                                        icon.Height = iconTexture.Height;
                                    }
                                }
                            }
                            else {
                                // Icon image from file
                                iconTexture = (IconTexture) m_textures[icon.TextureFileName];
                                if (iconTexture != null) {
                                    IconTexture tempTexture = iconTexture;
                                    m_textures[icon.SaveFilePath] = new IconTexture(DrawArgs.StaticDevice, icon.TextureFileName);
                                    tempTexture.Dispose();
                                }
                                else {
                                    key = icon.SaveFilePath;
                                    iconTexture = new IconTexture(DrawArgs.StaticDevice, icon.TextureFileName);

                                    // New texture, cache it
                                    m_textures.Add(key, iconTexture);

                                    // Use default dimensions if not set
                                    if (icon.Width == 0) {
                                        icon.Width = iconTexture.Width;
                                    }
                                    if (icon.Height == 0) {
                                        icon.Height = iconTexture.Height;
                                    }
                                }
                            }
                        }
                        else {
                            // Icon image from bitmap
                            if (icon.Image != null) {
                                iconTexture = (IconTexture) m_textures[icon.Image];
                                if (iconTexture != null) {
                                    IconTexture tempTexture = iconTexture;
                                    m_textures[icon.SaveFilePath] = new IconTexture(DrawArgs.StaticDevice, icon.Image);
                                    tempTexture.Dispose();
                                }
                                else {
                                    key = icon.SaveFilePath;
                                    iconTexture = new IconTexture(DrawArgs.StaticDevice, icon.Image);

                                    // New texture, cache it
                                    m_textures.Add(key, iconTexture);

                                    // Use default dimensions if not set
                                    if (icon.Width == 0) {
                                        icon.Width = iconTexture.Width;
                                    }
                                    if (icon.Height == 0) {
                                        icon.Height = iconTexture.Height;
                                    }
                                }
                            }
                        }

                        icon.LastRefresh = DateTime.Now;
                    }
                }
            }
            catch {}
            finally {
                isUpdating = false;
            }
        }
Esempio n. 11
0
		private void RefreshTableOfContents()
		{
			if(isRefreshing)
				return;

			isRefreshing = true;
			try
			{
				wms_server_list.WMS_SERVER_LISTType root = GetServerList();
				updateCurrentProgressBar(0, root.ServerCount );
				UpdateStatusBar( "Loading WMS servers... Please wait." );

				for(int i = root.ServerMinCount; i < root.ServerCount; i++)
				{
					wms_server_list.WMS_server curServer = root.GetServerAt(i);

					try
					{
						string savePath = Path.Combine( this.CacheDirectory, curServer.Name.Value);
						string xmlPath = savePath + ".xml";
						Directory.CreateDirectory( savePath );
						string url = curServer.ServerUrl.Value + (curServer.ServerUrl.Value.IndexOf("?") > 0 ? "&request=GetCapabilities&service=WMS&version=" + curServer.Version.Value : "?request=GetCapabilities&service=WMS&version=" + curServer.Version.Value);
						using( WebDownload download = new WebDownload(url) )
							download.DownloadFile(xmlPath );

						this.wmsList = new WMSList(curServer.Name.Value, curServer.ServerUrl.Value, xmlPath, curServer.Version.Value);

						if(this.wmsList.Layers != null)
						{
							foreach(MyWMSLayer l in this.wmsList.Layers)
							{
								TreeNode tn = this.getTreeNodeFromWMSLayer(l);

								this.treeViewTableOfContents.BeginInvoke(new UpdateTableTreeDelegate(this.UpdateTableTree), new object[] {tn});
							}
						}
					}
					catch(WebException)
					{
						TreeNode tn = new TreeNode(curServer.Name.Value + " (Connection Error)");
						tn.ForeColor = Color.Red;
						this.treeViewTableOfContents.BeginInvoke(new UpdateTableTreeDelegate(this.UpdateTableTree), new object[] {tn});
					}
					catch(Exception ex)
					{		
						TreeNode tn = new TreeNode(curServer.Name.Value + " " + ex.ToString());
						tn.ForeColor = Color.Red;
						this.treeViewTableOfContents.BeginInvoke(new UpdateTableTreeDelegate(this.UpdateTableTree), new object[] {tn});
					}

					updateCurrentProgressBar(i+1, root.ServerCount);
				}

				// TODO: Invoke
				this.treeViewTableOfContents.AfterSelect += new TreeViewEventHandler(treeViewTableOfContents_AfterSelect);

				this.panelLower.Enabled = true;
				UpdateStatusBar( "" );
				updateCurrentProgressBar(0,1);
				this.isRefreshed = true;
			}
			catch( Exception caught )
			{
				this.worldWindow.Caption = caught.Message;
			}
			finally
			{
				this.isRefreshing = false;
			}
		}
Esempio n. 12
0
        public override void Initialize(DrawArgs drawArgs)
        {
            if (!isOn) {
                return;
            }

            if (m_sprite != null) {
                m_sprite.Dispose();
                m_sprite = null;
            }

            m_sprite = new Sprite(drawArgs.Device);

            TimeSpan smallestRefreshInterval = TimeSpan.MaxValue;

            // Load all textures
            foreach (RenderableObject ro in m_children) {
                Icon icon = ro as Icon;
                if (icon == null) {
                    // Child is not an icon
                    if (ro.IsOn) {
                        ro.Initialize(drawArgs);
                    }
                    continue;
                }

                if (icon.RefreshInterval.TotalMilliseconds != 0 && icon.RefreshInterval != TimeSpan.MaxValue
                    && icon.RefreshInterval < smallestRefreshInterval) {
                    smallestRefreshInterval = icon.RefreshInterval;
                }

                // Child is an icon
                icon.Initialize(drawArgs);

                object key = null;
                IconTexture iconTexture = null;

                if (icon.TextureFileName != null
                    && icon.TextureFileName.Length > 0) {
                    if (icon.TextureFileName.ToLower().StartsWith("http://")
                        && icon.SaveFilePath != null) {
                        //download it
                        try {
                            WebDownload webDownload = new WebDownload(icon.TextureFileName);
                            webDownload.DownloadType = DownloadType.Unspecified;

                            FileInfo saveFile = new FileInfo(icon.SaveFilePath);
                            if (!saveFile.Directory.Exists) {
                                saveFile.Directory.Create();
                            }

                            webDownload.DownloadFile(saveFile.FullName);
                        }
                        catch {}

                        iconTexture = (IconTexture) m_textures[icon.SaveFilePath];
                        if (iconTexture == null) {
                            key = icon.SaveFilePath;
                            iconTexture = new IconTexture(drawArgs.Device, icon.SaveFilePath);
                        }
                    }
                    else {
                        // Icon image from file
                        iconTexture = (IconTexture) m_textures[icon.TextureFileName];
                        if (iconTexture == null) {
                            key = icon.TextureFileName;
                            iconTexture = new IconTexture(drawArgs.Device, icon.TextureFileName);
                        }
                    }
                }
                else {
                    // Icon image from bitmap
                    if (icon.Image != null) {
                        iconTexture = (IconTexture) m_textures[icon.Image];
                        if (iconTexture == null) {
                            // Create new texture from image
                            key = icon.Image;
                            iconTexture = new IconTexture(drawArgs.Device, icon.Image);
                        }
                    }
                }

                if (iconTexture == null) {
                    // No texture set
                    continue;
                }

                if (key != null) {
                    // New texture, cache it
                    m_textures.Add(key, iconTexture);

                    // Use default dimensions if not set
                    if (icon.Width == 0) {
                        icon.Width = iconTexture.Width;
                    }
                    if (icon.Height == 0) {
                        icon.Height = iconTexture.Height;
                    }
                }
            }

            // Compute mouse over bounding boxes
            foreach (RenderableObject ro in m_children) {
                Icon icon = ro as Icon;
                if (icon == null) {
                    // Child is not an icon
                    continue;
                }

                if (GetTexture(icon) == null) {
                    // Label only
                    icon.SelectionRectangle = drawArgs.DefaultDrawingFont.MeasureString(null, icon.Name, DrawTextFormat.None, 0);
                }
                else {
                    // Icon only
                    icon.SelectionRectangle = new Rectangle(0, 0, icon.Width, icon.Height);
                }

                // Center the box at (0,0)
                icon.SelectionRectangle.Offset(-icon.SelectionRectangle.Width/2, -icon.SelectionRectangle.Height/2);
            }

            if (refreshTimer == null
                && smallestRefreshInterval != TimeSpan.MaxValue) {
                refreshTimer = new Timer(smallestRefreshInterval.TotalMilliseconds);
                refreshTimer.Elapsed += new ElapsedEventHandler(refreshTimer_Elapsed);
                refreshTimer.Start();
            }

            Inited = true;
        }
Esempio n. 13
0
        protected override ModelNode[] Load()
        {
            WebDownload oCatalogDownload = new WebDownload(m_oUri.ToCapabilitiesUri(), true);
            oCatalogDownload.DownloadFile(CapabilitiesFilename);

            WMSList oCatalog = new WMSList(m_oUri.ToCapabilitiesUri(), CapabilitiesFilename);
            m_strTitle = oCatalog.Name;

            List<ModelNode> result = new List<ModelNode>();

            foreach (WMSLayer oLayer in oCatalog.Layers[0].ChildLayers)
            {
                if (oLayer.ChildLayers == null)
                {
                    result.Add(new WMSLayerModelNode(m_oModel, oLayer));
                }
                else
                {
                    result.Add(new WMSFolderModelNode(m_oModel, oLayer));
                }
            }
            if (oCatalog.Layers[0].Name != null)
            {
                result.Add(new WMSLayerModelNode(m_oModel, oCatalog.Layers[0]));
            }

            result.Sort(new Comparison<ModelNode>(WMSRootModelNode.SortWMSChildNodes));

            return result.ToArray();
        }
Esempio n. 14
0
        public override void Initialize(DrawArgs drawArgs)
        {
            if (m_points == null) {
                Inited = true;
                return;
            }

            if (m_imageUri != null) {
                //load image
                if (m_imageUri.ToLower().StartsWith("http://")) {
                    string savePath = string.Format("{0}\\image", ConfigurationLoader.GetRenderablePathString(this));
                    FileInfo file = new FileInfo(savePath);
                    if (!file.Exists) {
                        WebDownload download = new WebDownload(m_imageUri);

                        if (!file.Directory.Exists) {
                            file.Directory.Create();
                        }

                        download.DownloadFile(file.FullName, DownloadType.Unspecified);
                    }

                    m_texture = ImageHelper.LoadTexture(file.FullName);
                }
                else {
                    m_texture = ImageHelper.LoadTexture(m_imageUri);
                }
            }

            UpdateVertices();

            Inited = true;
        }
		/// <summary>
		/// Download thread runs this function.
		/// </summary>
		private void Downloader() 
		{
			while(true)
			{
				if(this.animationState == AnimationState.Pending)
				{
					Thread.Sleep(100);
					continue;
				}

				lock(this.downloadQueue)
				{
					if(this.downloadQueue.Count <= 0)
					{
						Thread.Sleep(100);
						continue;
					}
			
					this.wmsDownload = (WMSDownload)this.downloadQueue.Dequeue();
				}

				if(File.Exists(wmsDownload.SavedFilePath)) 
				{
					AddAnimationFrame(wmsDownload);
					return;
				}

				// Download
				try
				{
					this.downloadState = DownloadState.Downloading;
					updateStatusBar( string.Format( CultureInfo.CurrentCulture,
						"Downloading {0} ({1}/{2})",
						wmsDownload.Date,
						this.animationFrames.Count+1,
						this.currentlySelectedLayer.AnimationFrameCount ) );
				
					using( WebDownload dl = new WebDownload( wmsDownload.Url) )
					{
						dl.DownloadType = DownloadType.Wms;
						dl.ProgressCallback += new DownloadProgressHandler(updateCurrentProgressBar);
						dl.DownloadFile(wmsDownload.SavedFilePath);
					}
					Download_CompleteCallback(wmsDownload);
				}
				catch(ThreadAbortException)
				{
					// Normal shutdown
				}
				catch(Exception caught)
				{
					updateStatusBar(caught.Message);
					// Abort download.
					return;
				}
			}
		}
Esempio n. 16
0
		/// <summary>
		/// Install plugin from web (url).
		/// </summary>
		/// <param name="pluginUrl">http:// URL</param>
		void InstallFromUrl( Uri uri )
		{
			string fileName = Path.GetFileName( uri.LocalPath );
			string destPath = GetDestinationPath( fileName );
			if(destPath == null)
				return;

			using(WebDownload dl = new WebDownload(uri.ToString()))
				dl.DownloadFile(destPath);

			ShowSuccessMessage( fileName );
		}
Esempio n. 17
0
        private void ProcessInstallEncodedUri()
        {
            //parse install URI
            string urls = worldWindUri.PreserveCase.Substring(20, worldWindUri.PreserveCase.Length - 20);
            urls.Replace(";", ",");
            string[] urllist = urls.Split(',');
            WebDownload zipURL = new WebDownload();

            string zipFilePath = "";

            foreach (string cururl in urllist)
            {
                DialogResult result = MessageBox.Show("Do you want to install the addon from " + cururl + " into World Wind?", "Installing Add-ons", MessageBoxButtons.YesNoCancel);
                switch(result)
                {
                    case DialogResult.Yes:

                        zipFilePath = cururl;   //default to the url
                        //Go ahead and download
                        if (cururl.StartsWith("http"))
                        {
                            try
                            {
                                //It's a web file - download it first
                                zipURL.Url = cururl;
                                zipFilePath = Path.Combine(Path.GetTempPath(), "WWAddon.zip");
                                MessageBox.Show("Click OK to begin downloading.  World Wind may be unresponsive while it is downloading - please wait.","Downloading...");
                                zipURL.DownloadFile(zipFilePath);
                                MessageBox.Show("File downloaded!  Click OK to install.", "File done!");
                            }
                            catch
                            {
                                MessageBox.Show("Could not download file.\nError: " + zipURL.Exception.Message  + "\nURL: " + cururl, "Error");
                            }
                        }

                        try
                        {
                            FastZip fz = new FastZip();
                            fz.ExtractZip(zipFilePath, MainApplication.DirectoryPath, "");
                        }
                        catch
                        {
                            MessageBox.Show("Error installing addon.", "Error");
                        }
                        finally
                        {
                            string addonType = "#";
                            string addonPath = "//";
                            try
                            {
                                string ManifestFile = Path.Combine(MainApplication.DirectoryPath, "manifest.txt");
                                if (File.Exists(ManifestFile))
                                {
                                    StreamReader fs = new StreamReader(ManifestFile);
                                    while (addonType.StartsWith("#") || addonType.StartsWith("//")) { addonType = fs.ReadLine(); }
                                    while (addonPath.StartsWith("#") || addonPath.StartsWith("//")) { addonPath = fs.ReadLine(); }
                                    if (addonType.ToLower().Contains("plugin"))
                                    {
                                        //DoFancyPluginMethod(addonPath);     
                                        MessageBox.Show("Plugin activated: " + addonPath);
                                    }
                                    else {
                                        //DoFancyLayerMethod(addonPath);
                                        //MessageBox.Show("Layer activated: " + addonPath);
										addonPath = Path.Combine(Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath),
											addonPath);
										LoadAddon(addonPath);
                                    }
                                    fs.Close();
                                    File.Delete(Path.Combine(MainApplication.DirectoryPath, "manifest.txt"));
                                }
                                else
                                {
                                    MessageBox.Show("Add-on manifest not found.  You will have to restart World Wind to use this add-on.", "Restart required");
                                }
                            }
                            catch (Exception e)
                            {
                                MessageBox.Show("Error reading add-on manifest.  You will have to restart World Wind to use this add-on.\nError code: " + e.Message , "Restart required");
                            }

                            try
                            {
                                File.Delete(Path.Combine(Path.GetTempPath(), "WWAddon.zip"));
                            }
                            catch
                            {
                            }
                        }   //end of finally from unzipping
                        break;
                    case DialogResult.No:
                        break;
                    default:
                        return; //They hit cancel - stop downloading stuff
                }
            }
        }
Esempio n. 18
0
		/// <summary>
		/// Downloads a KML/KMZ file from the given URL
		/// </summary>
		private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
		{
			if (bUpdating)
				return;
			bUpdating = true;

			try
			{
				if (!m_firedStartup || (layer != null && layer.IsOn))
				{
					string fullurl = url;
					if (sender == viewTimer)
					{
						WorldWind.DrawArgs drawArgs = owner.ParentApplication.WorldWindow.DrawArgs;
						if (!bViewStopped)
						{
							if (drawArgs.WorldCamera.ViewMatrix != lastView)
							{
								lastView = drawArgs.WorldCamera.ViewMatrix;
								bUpdating = false;
								return;
							}
							bViewStopped = true;
						}
						else
						{
							if (drawArgs.WorldCamera.ViewMatrix != lastView)
							{
								lastView = drawArgs.WorldCamera.ViewMatrix;
								bViewStopped = false;
							}
							bUpdating = false;
							return;
						}
						fullurl += (fullurl.IndexOf('?') == -1 ? "?" : "&") + GetBBox();
					}

					string saveFile = Path.GetFileName(Uri.EscapeDataString(url));
					if(saveFile == null || saveFile.Length == 0)
						saveFile = "temp.kml";

					saveFile = Path.Combine(owner.PluginDirectory + "\\kml\\temp\\",saveFile);

                    FileInfo saveFileInfo = new FileInfo(saveFile);
                    if (!saveFileInfo.Directory.Exists)
                        saveFileInfo.Directory.Create();

					WebDownload myClient = new WebDownload(fullurl);
					myClient.DownloadFile(saveFile);

					// Extract the file if it is a kmz file
					string kmlFile = saveFile;
					if (Path.GetExtension(saveFile) == ".kmz")
					{
						bool bError = false;
						kmlFile = owner.ExtractKMZ(saveFile, out bError);

						if (bError)
						{
							return;
						}
					}

					owner.KMLPath = kmlFile;

					// Create a reader to read the file
					StreamReader sr = new StreamReader(kmlFile);

					// Read all data from the reader
					string kml = sr.ReadToEnd();

					sr.Close();
					
					try
					{
						// Load the actual kml data
						owner.LoadKML(kml, layer);
					}
					catch (Exception ex)
					{
                        Log.Write(Log.Levels.Error, "KMLImporter: " + ex.ToString());

						MessageBox.Show(
							String.Format(CultureInfo.InvariantCulture, "Error loading KML file '{0}':\n\n{1}", kmlFile, ex.ToString()), 
							"KMLImporter error", 
							MessageBoxButtons.OK, 
							MessageBoxIcon.Error,
							MessageBoxDefaultButton.Button1,
							MessageBoxOptions.ServiceNotification);
					}
					m_firedStartup = true;
				}
			}
			catch (Exception ex)
			{
                Log.Write(Log.Levels.Error, "KMLImporter: " + ex.ToString());
			}

			bUpdating = false;
		}