public List<Item> GetItems(string path)
        {
            var items = new List<Item>();

            var dirInfo = new DirectoryInfo(path);

            foreach (var directory in dirInfo.GetDirectories())
            {
                var item = new DirectoryItem
                {
                    Name = directory.Name,
                    Path = directory.FullName,
                    Items = GetItems(directory.FullName)
                };

                items.Add(item);
            }

            foreach (var file in dirInfo.GetFiles())
            {
                var item = new FileItem
                {
                    Name = file.Name,
                    Path = file.FullName
                };

                items.Add(item);
            }

            return items;
        }
 ////internal Image FileIcon;
 ////internal TextBlock FileName;
 ////internal TextBlock OpenFile;
 ////internal TextBlock OpenFolder;
 ////private bool _contentLoaded;
 public OpenFileControl(FileItem fileItem, bool isSuccess)
 {
     this.InitializeComponent();
     try
     {
         if (fileItem != null)
         {
             this.fileItem = fileItem;
             this.isSuccess = isSuccess;
             System.IO.FileInfo info = new System.IO.FileInfo(fileItem.FileName);
             this.fileDirectoryName = info.DirectoryName;
             this.FileIcon.Source = this.IconDecode(this.fileItem.IconBase64);
             this.FileName.Text = info.Name;
             if (isSuccess)
             {
                 this.OpenFile.Visibility = Visibility.Visible;
                 this.OpenFolder.Visibility = Visibility.Visible;
             }
         }
     }
     catch (System.Exception e)
     {
         this.logger.Error(e.ToString());
     }
 }
 public NewFileListItem(System.IO.FileInfo fileInfo, GroupChatTabControl groupChatTab, EntGroup group)
 {
     try
     {
         this.InitializeComponent();
         if (fileInfo != null && groupChatTab != null && group != null)
         {
             this.fileInfo = fileInfo;
             this.groupChatTab = groupChatTab;
             this.group = group;
             this.item = new FileItem(fileInfo);
             this.item.FromUid = this.sessionService.Uid;
             this.item.Gid = this.group.Gid;
             this.item.FileService = this.fileService;
             this.item.ProcessEvent = new ProcessEvent(this.ProcessEventHandle);
             this.item.EndEvent = new EndEvent(this.EndEventHandle);
             this.item.ErrorEvent = new ErrorEvent(this.ErrorEventHandle);
             this.item.StopEvent = new StopEvent(this.StopEventHandle);
             this.progressBar.Maximum = (double)fileInfo.Length;
             this.imgIcon.Source = this.IconToBitmap(Icon.ExtractAssociatedIcon(fileInfo.FullName));
             this.IconBase64 = this.IconToBase64(Icon.ExtractAssociatedIcon(fileInfo.FullName));
             this.item.IconBase64 = this.IconBase64;
             this.tbkFilename.Text = fileInfo.Name.Trim();
             this.fileName = fileInfo.Name.Trim();
             this.tbkMsg.Text = "正在发送文件";
             this.tbkSize.Text = this.GetLength(fileInfo.Length);
             this.ShowCancelButton();
         }
     }
     catch (System.Exception e)
     {
         ServiceUtil.Instance.Logger.Error(e.ToString());
     }
 }
Exemple #4
0
        public async Task LoadMD5()
        {
            var c = new ContentTypes();
            var root = Environment.CurrentDirectory;
            var path = string.Format("{0}\\{1}.bin", root, Guid.NewGuid());

            var random = new Random();
            var bytes = new byte[64];
            random.NextBytes(bytes);

            string md5;
            using (var createHash = System.Security.Cryptography.MD5.Create())
            {
                var hash = createHash.ComputeHash(bytes);
                md5 = System.Convert.ToBase64String(hash);
            }

            File.WriteAllBytes(path, bytes);

            var item = new FileItem(root, path);
            await item.LoadMD5();

            Assert.AreEqual(bytes, item.Data);
            Assert.AreEqual(c.ContentType(path), item.ContentType);
            Assert.AreEqual(md5, item.MD5);
        }
 /// <summary>
 ///     提交文件
 /// </summary>
 /// <param name="request">请求对象</param>
 /// <param name="fileItem">文件</param>
 /// <returns>响应文本</returns>
 public static string Post(this HttpWebRequest request, FileItem fileItem)
 {
     return request
         .Method(HttpWebRequestMethod.POST)
         .SetContentType("application/octet-stream")
         .Write(fileItem.GetContent())
         .GetResponseString();
 }
        public List<Item> GetItems(string path)
        {
            if (!System.IO.Directory.Exists(path))
            {
                return null;
            }

            var items = new List<Item>();

            var dirInfo = new DirectoryInfo(path);

            try
            {
                foreach (var directory in dirInfo.GetDirectories())
                {
                    var item = new DirectoryItem
                    {
                        Name = directory.Name,
                        Path = directory.FullName,
                        Items = GetItems(directory.FullName),
                        IsFolder = true
                    };

                    items.Add(item);
                }

            }
            catch(Exception ex)
            {
                Trace.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace, "EXCEPTION GetItems");
            }

            try
            {
                foreach (var file in dirInfo.GetFiles())
                {
                    if (file.Name.ToLower() != "thumbs.db" && file.Name.ToLower() != "desktop.ini")
                    {
                        var item = new FileItem
                        {
                            Name = file.Name,
                            Path = file.FullName,
                            IsFolder = false
                        };

                        items.Add(item);

                    }
                }

            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace, "EXCEPTION GetItems");
            }

            return items;
        }
        private string getCommentUrl( FileItem post ) {

            return t2( new wojilu.Web.Controller.Open.CommentController().List )
                + "?url=" + alink.ToAppData( post, ctx )
                + "&dataType=" + typeof( FileItem ).FullName
                + "&dataTitle=" + post.Title
                + "&dataUserId=" + post.Creator.Id
                + "&appId=" + post.AppId
                + "&dataId=" + post.Id;
        }
Exemple #8
0
 public new void Install(PackageClass packageClass, FileItem fileItem)
 {
   base.Install(packageClass, fileItem);
   string fontFilePath = fileItem.ExpandedDestinationFilename;
   if (AddFontResource(fontFilePath) != 0)
   {
     SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);
     WriteProfileString("fonts", Path.GetFileNameWithoutExtension(fontFilePath) + " (TrueType)",
                        Path.GetFileName(fontFilePath));
   }
 }
Exemple #9
0
        /// <summary>
        /// Header 값을 추가한다.
        /// </summary>
        /// <param name="ctx">HttpContext</param>
        /// <param name="fileItem">클라이언트로 내려줄 파일 정보</param>
        /// <param name="attach">Content-Disposition의 Type<br/>
        /// false : inline<br/>
        /// true : attachment</param>
        public virtual void BuildHeader(HttpContext ctx, FileItem fileItem, bool attach)
        {
            if(IsDebugEnabled)
                log.Debug("==>S ctx={0}, fileItem={1}, attach={2}", ctx, fileItem, attach);

            ctx.ShouldNotBeNull("HttpContext가 없습니다.");
            fileItem.ShouldNotBeNull("파일정보가 없습니다.");

            ctx.Response.ContentType = fileItem.ContentType;
            ctx.Response.Expires = 0;

            AddHeader(ctx, fileItem, attach);
        }
Exemple #10
0
        /// <summary>
        /// 파일을 클라이언트에 내려준다.
        /// </summary>
        /// <param name="ctx">HttpContext</param>
        /// <param name="fileItem">파일정보</param>
        /// <param name="attach">파일 다운로드 방식</param>
        public virtual void Download(HttpContext ctx, FileItem fileItem, bool attach)
        {
            if(IsDebugEnabled)
                log.Debug("==>S ctx={0}, fileItem={1}, attach={2}", ctx, fileItem, attach);

            ctx.ShouldNotBeNull("HttpContext정보가 없습니다.");
            fileItem.ShouldNotBeNull("파일정보가 없습니다.");

            //if(Repository.FileExists(fileItem.ServerFileName) == false)
            //    throw new FileNotFoundException("파일이 존재하지 않습니다.", fileItem.ToString());

            BuildHeader(ctx, fileItem, attach);
            WriteFile(ctx, fileItem.ServerFileName);
        }
Exemple #11
0
        public void op_Equals_FileItem_whenFalse()
        {
            using (var temp = new TempFile())
            {
                var obj = new FileItem
                              {
                                  Name = temp.Info.Name,
                                  Value = temp.Info.FullName
                              };

                var other = new FileItem();

                Assert.False(obj.Equals(other));
            }
        }
Exemple #12
0
        public override void Delete(CacheItemInfo item)
        {
            CacheItemInfo cachedItem;

            lock (_cache)
            {
                if (_cache.TryGetValue(item.UniqueName, out cachedItem) && Object.Equals(item, cachedItem))
                {
                    _cache.Remove(item.UniqueName);
                }
            }

            var fi = new FileItem(item);
            var fileName = fi.FileName;
            File.Delete(fileName);
        }
Exemple #13
0
        public async Task Delete()
        {
            var c = new ContentTypes();
            var root = Environment.CurrentDirectory;
            var path = string.Format("{0}\\{1}.bin", root, Guid.NewGuid());

            var random = new Random();
            var bytes = new byte[64];
            random.NextBytes(bytes);

            File.WriteAllBytes(path, bytes);

            var item = new FileItem(root, path);
            await item.Delete();

            Assert.IsFalse(File.Exists(path));
        }
    public void Install(PackageClass packageClass, FileItem fileItem)
    {
      try
      {
        string destination = fileItem.ExpandedDestinationFilename;

        FileItem item = packageClass.UniqueFileList.GetByLocalFileName(fileItem);
        if (item == null)
          return;

        if (File.Exists(destination))
        {
          switch (fileItem.UpdateOption)
          {
            case UpdateOptionEnum.NeverOverwrite:
              return;
            case UpdateOptionEnum.AlwaysOverwrite:
              break;
            case UpdateOptionEnum.OverwriteIfOlder:
              if (File.GetLastWriteTime(destination) > packageClass.ZipProvider.FileDate(item))
                return;
              break;
          }
        }
        if (!Directory.Exists(Path.GetDirectoryName(destination)))
        {
          string dirname = Path.GetDirectoryName(destination);
          Directory.CreateDirectory(dirname);
          if (!dirname.EndsWith("\\"))
            dirname += "\\";
          UnInstallItem unI = new UnInstallItem();
          unI.OriginalFile = dirname;
          unI.InstallType = "CopyFile";
          packageClass.UnInstallInfo.Items.Add(unI);
        }
        UnInstallItem unInstallItem = packageClass.UnInstallInfo.BackUpFile(item);
        packageClass.ZipProvider.Extract(item, destination);
        FileInfo info = new FileInfo(destination);
        unInstallItem.FileDate = info.CreationTimeUtc;
        unInstallItem.FileSize = info.Length;
        packageClass.UnInstallInfo.Items.Add(unInstallItem);
      }
      catch (Exception) {}
    }
 public bool Extract(FileItem item, string extractLocation)
 {
   try
   {
     var fs = new FileStream(extractLocation, FileMode.Create);
     _zipPackageFile[item.ZipFileName].Extract(fs);
     fs.Close();
     DateTime filedate = FileDate(item);
     File.SetCreationTime(extractLocation, filedate);
     File.SetLastAccessTime(extractLocation, filedate);
     File.SetLastWriteTime(extractLocation, filedate);
     item.TempFileLocation = extractLocation;
   }
   catch (Exception)
   {
     return false;
   }
   return true;
 }
Exemple #16
0
        public override void Delete(CacheItemInfo item)
        {
            CacheItemInfo cachedItem;

            lock (_cache) {
                if (_cache.TryGetValue(item.UniqueName, out cachedItem) && Object.Equals(item, cachedItem)) {
                    _cache.Remove(item.UniqueName);
                }
            }

            var fi = new FileItem(item);

            var fileName = fi.FileName;

            PriorityQueue.AddStorageWorkItem(() =>
                   {
                       lock (LockObject) {
                           DeleteFileHelper(IsoStore, fileName);
                       }
                   });
        }
Exemple #17
0
        /// <summary>
        /// 获取html中的关联图片
        /// </summary>
        /// <param name="realPath"></param>
        /// <param name="rootPath"></param>
        /// <returns></returns>
        public List<FileItem> GetExtraFileItems(string html,string pattern,string srcPattern, string realPath, string rootPath)
        {
            List<FileItem> imgList = new List<FileItem>();
            Common cn = new Common();

            Regex regex = new Regex(pattern);
            MatchCollection matchs = regex.Matches(html);
            foreach (Match match in matchs)
            {
                string img = match.Value;
                string[] imgArr = img.Split(' ');
                if (imgArr != null && imgArr.Length > 0)
                {
                    string src = string.Empty;
                    foreach (string str in imgArr)
                    {
                        if (str.ToUpper().Contains(srcPattern.ToUpper()))
                        {
                            src = str.Replace("/>", " ").Trim();
                            break;
                        }
                    }
                    string[] srcArr = src.Split('=');
                    if (srcArr != null && srcArr.Length > 0)
                    {
                        string value = srcArr[1].Replace('\"', ' ').Trim();
                        string str1 = realPath.Replace(rootPath + "\\webapps", "");
                        string app = str1.Substring(0, str1.IndexOf('\\'));

                        string imgPath = rootPath + "\\webapps" + app + "\\" + value;
                        FileItem fileItem = new FileItem();
                        fileItem.Path = imgPath;
                        fileItem.MimeType = cn.GetMimeType(imgPath, rootPath);
                        imgList.Add(fileItem);
                    }
                }
            }
            return imgList;
        }
        protected void OnDirectoryPathChanged()
        {
            if (Directory.Exists(directoryPath)) {
                fileList.Clear();
                string[] files = Directory.GetFiles(directoryPath);
                foreach (string file in files) {
                    if (Path.GetExtension(file) == String.Empty)
                        continue;
                    FileItem fileItem = new FileItem();
                    fileItem.Name = Path.GetFileName(file);
                    fileItem.Path = Path.GetFullPath(file);
                    if (Path.GetExtension(file) != ".cs" && Path.GetExtension(file) != ".vb") {
                        fileItem.Extention = FileExtension.Other;
                    }
                    else
                        fileItem.Extention = (FileExtension)Enum.Parse(typeof(FileExtension), Path.GetExtension(file).Remove(0, 1));

                    if (fileItem.Extention == currentFileExtention)
                        fileList.Add(fileItem);
                }
            }
            else
                MessageBox.Show("This directory is not exists!");
        }
Exemple #19
0
        private Node GetFileStructure(FileItem fs)
        {
            Node root = new Node();
            root.Text = fs.FileName;
            root.NodeID = "Node-" + fs.ID;
            root.Icon = fs.IsFolder ? Icon.Folder : Icon.Report;

            if (fs.SubItems != null)
            {
                if (fs.ID == CourseFiles.RootFolder.ID)
                    root.Expanded = true;

                foreach (FileItem item in fs.SubItems)
                {
                    Node n = GetFileStructure(item);
                    if (n.Children.Count == 0)
                        n.Leaf = true;
                    root.Children.Add(n);
                }
            }
            else
                root.Leaf = true;
            return root;
        }
		private static async Task<ReceivedShareItem> FetchDataFromPackageViewAsync(DataPackageView packageView)
		{
			var rval = new ReceivedShareItem()
			{
				Title = packageView.Properties.Title,
				Description = packageView.Properties.Description,
				PackageFamilyName = packageView.Properties.PackageFamilyName,
				ContentSourceWebLink = packageView.Properties.ContentSourceWebLink,
				ContentSourceApplicationLink = packageView.Properties.ContentSourceApplicationLink,
				LogoBackgroundColor = packageView.Properties.LogoBackgroundColor,

			};
			if (packageView.Properties.Square30x30Logo != null)
			{
				using (var logoStream = await packageView.Properties.Square30x30Logo.OpenReadAsync())
				{
					var logo = new MemoryStream();
					await logoStream.AsStreamForRead().CopyToAsync(logo);
					logo.Position = 0;
					var str = Convert.ToBase64String(logo.ToArray());
					//rval.Square30x30LogoBase64 = Convert.ToBase64String(logo.ToArray());
					rval.Square30x30Logo = new Models.MemoryStreamBase64Item { Base64String = str };


				}
			}
			if (packageView.Properties.Thumbnail != null)
			{
				using (var thumbnailStream = await packageView.Properties.Thumbnail.OpenReadAsync())
				{
					var thumbnail = new MemoryStream();
					await thumbnailStream.AsStreamForRead().CopyToAsync(thumbnail);
					thumbnail.Position = 0;
					var str = Convert.ToBase64String(thumbnail.ToArray());
					rval.Thumbnail = new Models.MemoryStreamBase64Item { Base64String = str };
				}
			}

			if (packageView.Contains(StandardDataFormats.WebLink))
			{
				try
				{
					var link = new WebLinkShareItem
					{
						WebLink = await packageView.GetWebLinkAsync()
					};

					rval.AvialableShareItems.Add(link);
				}
				catch (Exception ex)
				{
					//NotifyUserBackgroundThread("Failed GetWebLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
				}
			}
			if (packageView.Contains(StandardDataFormats.ApplicationLink))
			{
				try
				{
					var sharedApplicationLink = new ApplicationLinkShareItem
					{
						ApplicationLink = await packageView.GetApplicationLinkAsync()
					};
					rval.AvialableShareItems.Add(sharedApplicationLink);

				}
				catch (Exception ex)
				{
					//NotifyUserBackgroundThread("Failed GetApplicationLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
				}
			}
			if (packageView.Contains(StandardDataFormats.Text))
			{
				try
				{
					var sharedText = new TextShareItem { Text = await packageView.GetTextAsync() };
					rval.AvialableShareItems.Add(sharedText);
					rval.Text = await packageView.GetTextAsync();
					//rval.GetValueContainer(x => x.Text)
					//   	.GetNullObservable()
					//	.Subscribe(e => sharedText.Text = rval.Text)
					//	.DisposeWith(rval);
					sharedText.GetValueContainer(x => x.Text)
						.GetNullObservable()
						.Subscribe(e => rval.Text = sharedText.Text)
						.DisposeWith(rval);
				}
				catch (Exception ex)
				{
					//NotifyUserBackgroundThread("Failed GetTextAsync - " + ex.Message, NotifyType.ErrorMessage);
				}
			}
			if (packageView.Contains(StandardDataFormats.StorageItems))
			{
				try
				{
					var files = await packageView.GetStorageItemsAsync();
					var sharedStorageItem = new FilesShareItem
					{
						StorageFiles = new ObservableCollection<FileItem>()
						//StorageItems = 
					};
					foreach (StorageFile sf in files)
					{
						var guidString = Guid.NewGuid().ToString();
						StorageApplicationPermissions.FutureAccessList.AddOrReplace(guidString, sf, sf.Name);
						var ts = await sf.GetScaledImageAsThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.VideosView);
						var tmbs = new MemoryStream();
						await ts.AsStreamForRead().CopyToAsync(tmbs);
						var file = new FileItem
						{
							AccessToken = guidString,
							ContentType = sf.ContentType,
							FileName = sf.DisplayName,
							PossiblePath = sf.Path,
							Thumbnail = new Models.MemoryStreamBase64Item(tmbs.ToArray())
						};

						sharedStorageItem.StorageFiles.Add(file);

					}
					//StorageApplicationPermissions.FutureAccessList.AddOrReplace()

					rval.AvialableShareItems.Add(sharedStorageItem);
				}
				catch (Exception ex)
				{
					//NotifyUserBackgroundThread("Failed GetStorageItemsAsync - " + ex.Message, NotifyType.ErrorMessage);
				}
			}
			//if (packageView.Contains(dataFormatName))
			//{
			//	try
			//	{
			//		this.sharedCustomData = await packageView.GetTextAsync(dataFormatName);
			//	}
			//	catch (Exception ex)
			//	{
			//		//NotifyUserBackgroundThread("Failed GetTextAsync(" + dataFormatName + ") - " + ex.Message, NotifyType.ErrorMessage);
			//	}
			//}
			if (packageView.Contains(StandardDataFormats.Html))
			{
				var sharedHtmlFormatItem = new HtmlShareItem();
				var sharedHtmlFormat = string.Empty;
				try
				{
					sharedHtmlFormat = await packageView.GetHtmlFormatAsync();
					//sharedHtmlFormatItem.HtmlFormat = sharedHtmlFormat;
					sharedHtmlFormatItem.HtmlFragment = HtmlFormatHelper.GetStaticFragment(sharedHtmlFormat);
				}
				catch (Exception ex)
				{
					//NotifyUserBackgroundThread("Failed GetHtmlFormatAsync - " + ex.Message, NotifyType.ErrorMessage);
				}
				//try
				//{
				//	var sharedResourceMap = await packageView.GetResourceMapAsync();
				//}
				//catch (Exception ex)
				//{
				//	//NotifyUserBackgroundThread("Failed GetResourceMapAsync - " + ex.Message, NotifyType.ErrorMessage);
				//}

				//if (packageView.Contains(StandardDataFormats.WebLink))
				//{
				//	try
				//	{
				//		sharedHtmlFormatItem.WebLink = await packageView.GetWebLinkAsync();
				//	}
				//	catch (Exception ex)
				//	{
				//		//NotifyUserBackgroundThread("Failed GetWebLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
				//	}
				//}
				rval.AvialableShareItems.Add(sharedHtmlFormatItem);

			}
			if (packageView.Contains(StandardDataFormats.Bitmap))
			{
				try
				{
					var fi = await packageView.GetBitmapAsync();
					using (var imgFileStream = await fi.OpenReadAsync())
					{
						var saveTargetStream = new InMemoryRandomAccessStream();

						var bitmapSourceStream = imgFileStream;

						await ServiceLocator
								 .Instance
								 .Resolve<IImageConvertService>()
								 .ConverterBitmapToTargetStreamAsync(bitmapSourceStream, saveTargetStream);

						saveTargetStream.Seek(0);
						var sr = saveTargetStream.GetInputStreamAt(0);
						var source = sr.AsStreamForRead();

						var ms = new MemoryStream();
						await source.CopyToAsync(ms);

						var sharedBitmapStreamRef = new DelayRenderedImageShareItem
						{
							SelectedImage = new Models.MemoryStreamBase64Item(ms.ToArray())
						};

						rval.AvialableShareItems.Add(sharedBitmapStreamRef);

					}
				}
				catch (Exception ex)
				{
					//NotifyUserBackgroundThread("Failed GetBitmapAsync - " + ex.Message, NotifyType.ErrorMessage);
				}
			}

			//foreach (var item in rval.AvialableShareItems)
			//{
			//	//item.ContentSourceApplicationLink = rval.ContentSourceApplicationLink;
			//	//item.ContentSourceWebLink = rval.ContentSourceWebLink;
			//	//item.DefaultFailedDisplayText = rval.DefaultFailedDisplayText;
			//	//item.Description = rval.Description;
			//	//item.Title = rval.Title;
			//}
			return rval;
		}
Exemple #21
0
        private void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            RaisePropertyChanged(() => IsBusy);
            RaisePropertyChanged(() => IsFree);


            string tempFolder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            try
            {
                if (!Directory.Exists(tempFolder))
                {
                    Directory.CreateDirectory(tempFolder);
                }
            }
            catch (Exception exception)
            {
                OutPut.Add(exception.Message);
                return;
            }

            Thread.Sleep(500);
            CurrentImages = 0;
            TotalImages   = ServiceProvider.Settings.DefaultSession.Files.Count;
            int counter = 0;

            ProgressMax = MaxValue - MinValue;
            Progress    = 0;
            for (int i = MinValue; i < MaxValue; i++)
            {
                if (_backgroundWorker.CancellationPending)
                {
                    DeleteTempFolder(tempFolder);
                    OutPut.Insert(0, "Operation CANCELED !!!");
                    return;
                }

                try
                {
                    Progress++;
                    FileItem item    = ServiceProvider.Settings.DefaultSession.Files[i];
                    string   outfile = Path.Combine(tempFolder, "img" + counter.ToString("000000") + ".jpg");
                    if (TransformBefor && !Preview)
                    {
                        AutoExportPluginHelper.ExecuteTransformPlugins(item, _config, item.FileName, outfile);
                        CopyFile(outfile, outfile);
                    }
                    else
                    {
                        if (Preview)
                        {
                            BitmapLoader.Instance.GenerateCache(item);
                            File.Copy(item.SmallThumb, outfile);
                        }
                        else
                        {
                            CopyFile(item.FileName, outfile);
                        }
                    }
                    //outfile =
                    if (!TransformBefor)
                    {
                        AutoExportPluginHelper.ExecuteTransformPlugins(item, _config, outfile, outfile);
                    }
                    OutPut.Insert(0, "Procesing file " + item.Name);
                    counter++;
                }
                catch (Exception exception)
                {
                    OutPut.Add(exception.Message);
                }
            }
            switch (VideoType.Extension)
            {
            case ".mp4":
                GenerateMp4(tempFolder);
                break;

            case ".gif":
                GenerateGif(tempFolder);
                break;
            }


            DeleteTempFolder(tempFolder);
            Progress = ProgressMax;
            OutPut.Insert(0, "DONE !!!");
            if (Preview)
            {
                PlayVideo();
            }
        }
Exemple #22
0
        private static void ExtractFileItem(string filename, FileItem item)
        {
            var i = (IArchiveEntry)item.Entry;

            i.WriteToDirectory(filename);
        }
        //=====================================================================

        /// <summary>
        /// This loads the tree view with table of contents file entries from the project
        /// </summary>
        private List <EntityReference> LoadTableOfContentsInfo()
        {
            FileItemCollection      contentLayoutFiles, siteMapFiles;
            List <ITableOfContents> tocFiles;
            TopicCollection         contentLayout;
            TocEntryCollection      siteMap, mergedToc;
            EntityReference         er;
            bool hasSelectedItem = false;

            if (tableOfContents != null)
            {
                return(tableOfContents);
            }

            tableOfContents = new List <EntityReference>();

            // Get content from open file editors
            var args = new FileContentNeededEventArgs(FileContentNeededEvent, this);

            base.RaiseEvent(args);

            try
            {
                // Get the content layout and site map files
                currentProject.EnsureProjectIsCurrent(false);

                contentLayoutFiles = new FileItemCollection(currentProject, BuildAction.ContentLayout);
                siteMapFiles       = new FileItemCollection(currentProject, BuildAction.SiteMap);
                tocFiles           = new List <ITableOfContents>();

                // Add the conceptual content layout files
                foreach (FileItem file in contentLayoutFiles)
                {
                    // If open in an editor, use the edited values
                    if (!args.ContentLayoutFiles.TryGetValue(file.FullPath, out contentLayout))
                    {
                        contentLayout = new TopicCollection(file);
                        contentLayout.Load();
                    }

                    tocFiles.Add(contentLayout);
                }

                // Load all site maps and add them to the list
                foreach (FileItem fileItem in siteMapFiles)
                {
                    // If open in an editor, use the edited values
                    if (!args.SiteMapFiles.TryGetValue(fileItem.FullPath, out siteMap))
                    {
                        siteMap = new TocEntryCollection(fileItem);
                        siteMap.Load();
                    }

                    tocFiles.Add(siteMap);
                }

                // Sort the files
                tocFiles.Sort((x, y) =>
                {
                    FileItem fx = x.ContentLayoutFile, fy = y.ContentLayoutFile;

                    if (fx.SortOrder < fy.SortOrder)
                    {
                        return(-1);
                    }

                    if (fx.SortOrder > fy.SortOrder)
                    {
                        return(1);
                    }

                    return(String.Compare(fx.Name, fy.Name, StringComparison.OrdinalIgnoreCase));
                });

                // Create the merged TOC.  For the purpose of adding links, we'll include everything
                // even topics marked as invisible.
                mergedToc = new TocEntryCollection();

                foreach (ITableOfContents file in tocFiles)
                {
                    file.GenerateTableOfContents(mergedToc, currentProject, true);
                }

                // Convert the TOC info to entity references
                foreach (var t in mergedToc)
                {
                    er = new EntityReference
                    {
                        EntityType = EntityType.TocEntry,
                        Id         = t.Id,
                        Label      = (t.Title ?? t.Id ?? "(No title)"),
                        ToolTip    = String.Format(CultureInfo.CurrentCulture, "ID: {0}\nFile: {1}",
                                                   (t.Id ?? t.Title ?? "(No ID)"), t.SourceFile),
                        Tag        = t,
                        IsExpanded = t.IsExpanded,
                        IsSelected = (t.IsSelected && !hasSelectedItem)
                    };

                    // Only use the first selected item
                    if (er.IsSelected)
                    {
                        hasSelectedItem = true;
                    }

                    tableOfContents.Add(er);

                    if (t.Children.Count != 0)
                    {
                        hasSelectedItem = this.AddChildTocEntries(t, er, hasSelectedItem);
                    }
                }
            }
            catch (Exception ex)
            {
                tableOfContents.Add(new EntityReference
                {
                    EntityType = EntityType.File,
                    Label      = "Unable to load TOC info: " + ex.Message,
                    ToolTip    = "Error"
                });
            }

            if (!hasSelectedItem && tableOfContents.Count != 0)
            {
                tableOfContents[0].IsSelected = true;
            }

            return(tableOfContents);
        }
        //=====================================================================

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="file">The content layout file associated with the
        /// collection.</param>
        /// <remarks>Topics are not loaded until the <see cref="Load" /> method
        /// is called.  If the <b>file</b> parameter is null, this is assumed
        /// to be a child topic collection.</remarks>
        public TopicCollection(FileItem file)
        {
            fileItem = file;
        }
Exemple #25
0
        public override void Update(CacheItemInfo oldInfo, CacheItemInfo newInfo)
        {
            if (oldInfo.Equals(newInfo)) return;

            var oldFilename = new FileItem(oldInfo).FileName;
            var newFilename = new FileItem(newInfo).FileName;

            PriorityQueue.AddStorageWorkItem(() =>
                {
                    lock (LockObject)
                    {
                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            if (store.FileExists(newFilename))
                                store.DeleteFile(newFilename);

                            using (var readStream = new IsolatedStorageFileStream(oldFilename, FileMode.Open, store))
                            using (var writeStream = new IsolatedStorageFileStream(newFilename, FileMode.Create, store))
                            using (var reader = new StreamReader(readStream))
                            using (var writer = new StreamWriter(writeStream))
                            {
                                writer.Write(reader.ReadToEnd());
                            }

                            store.DeleteFile(oldFilename);
                        }
                    }
                });
        }
        private void TriggerEvent(string cmd, object o)
        {
            try
            {
                switch (cmd)
                {
                case WindowsCmdConsts.Next_Image:
                    if (ImageLIst.SelectedIndex <
                        ImageLIst.Items.Count - 1)
                    {
                        FileItem item =
                            ImageLIst.SelectedItem as FileItem;
                        if (item != null)
                        {
                            int ind = ImageLIst.Items.IndexOf(item);
                            ImageLIst.SelectedIndex = ind + 1;
                        }
                        item = ImageLIst.SelectedItem as FileItem;
                        if (item != null)
                        {
                            ImageLIst.ScrollIntoView(item);
                        }
                    }
                    break;

                case WindowsCmdConsts.Prev_Image:
                    if (ImageLIst.SelectedIndex > 0)
                    {
                        FileItem item =
                            ImageLIst.SelectedItem as FileItem;
                        if (item != null)
                        {
                            int ind = ImageLIst.Items.IndexOf(item);
                            ImageLIst.SelectedIndex = ind - 1;
                        }
                        item = ImageLIst.SelectedItem as FileItem;
                        if (item != null)
                        {
                            ImageLIst.ScrollIntoView(item);
                        }
                    }
                    break;

                case WindowsCmdConsts.Like_Image:
                    if (ImageLIst.SelectedItem != null)
                    {
                        FileItem item = null;
                        if (o != null)
                        {
                            item = ServiceProvider.Settings.DefaultSession.GetByName(o as string);
                        }
                        else
                        {
                            item = ImageLIst.SelectedItem as FileItem;
                        }
                        if (item != null)
                        {
                            item.IsLiked = !item.IsLiked;
                        }
                    }
                    break;

                case WindowsCmdConsts.Unlike_Image:
                    if (ImageLIst.SelectedItem != null)
                    {
                        FileItem item = null;
                        if (o != null)
                        {
                            item =
                                ServiceProvider.Settings.DefaultSession
                                .GetByName(o as string);
                        }
                        else
                        {
                            item = ImageLIst.SelectedItem as FileItem;
                        }
                        if (item != null)
                        {
                            item.IsUnLiked = !item.IsUnLiked;
                        }
                    }
                    break;

                case WindowsCmdConsts.Del_Image:
                {
                    DeleteItem();
                }
                break;

                case WindowsCmdConsts.SelectAll_Image:
                {
                    ServiceProvider.Settings.DefaultSession.SelectAll();
                }
                break;

                case WindowsCmdConsts.Select_Image:
                    FileItem fileItem = o as FileItem;
                    if (fileItem != null)
                    {
                        ImageLIst.SelectedValue = fileItem;
                        ImageLIst.ScrollIntoView(fileItem);
                    }
                    break;

                case WindowsCmdConsts.Refresh_Image:
                    RefreshImage();
                    break;

                case WindowsCmdConsts.Zoom_Image_Fit:
                    ZoomAndPanControl.ScaleToFit();
                    break;

                case WindowsCmdConsts.Zoom_Image_60:
                    ZoomToFocus();
                    LoadFullRes();
                    ZoomAndPanControl.ZoomTo(0.6);
                    break;

                case WindowsCmdConsts.Zoom_Image_100:
                    ZoomToFocus();
                    LoadFullRes();
                    ZoomAndPanControl.ZoomTo(1.0);
                    break;

                case WindowsCmdConsts.Zoom_Image_200:
                    ZoomToFocus();
                    LoadFullRes();
                    ZoomAndPanControl.ZoomTo(2.0);
                    break;

                case WindowsCmdConsts.RotateLeft:
                {
                    FileItem item =
                        ImageLIst.SelectedItem as FileItem;
                    if (item != null)
                    {
                        item.Rotation--;
                    }
                }
                break;

                case WindowsCmdConsts.RotateRight:
                {
                    FileItem item =
                        ImageLIst.SelectedItem as FileItem;
                    if (item != null)
                    {
                        item.Rotation++;
                    }
                }
                break;

                case WindowsCmdConsts.ViewExternal:
                    OpenInExternalViewer();
                    break;

                case WindowsCmdConsts.ViewExplorer:
                    OpenInExplorer();
                    break;

                case WindowsCmdConsts.RefreshDisplay:
                    if (LayoutViewModel.ZoomIndex == 0)
                    {
                        ZoomAndPanControl.ScaleToFit();
                    }
                    break;
                }
                if (cmd.StartsWith(WindowsCmdConsts.ZoomPoint))
                {
                    if (ZoomAndPanControl != null && cmd.Contains("_"))
                    {
                        var vals = cmd.Split('_');
                        if (vals.Count() > 2)
                        {
                            double x;
                            double y;
                            double.TryParse(vals[1], out x);
                            double.TryParse(vals[2], out y);
                            if (cmd.EndsWith("!"))
                            {
                                ZoomAndPanControl.SnapToRation(x, y);
                            }
                            else
                            {
                                ZoomAndPanControl.AnimatedSnapToRation(x, y);
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Log.Error("Unable to process event ", exception);
            }
        }
        private void DeleteItem()
        {
            List <FileItem> filestodelete = new List <FileItem>();

            try
            {
                filestodelete.AddRange(
                    ServiceProvider.Settings.DefaultSession.Files.Where(fileItem => fileItem.IsChecked));

                if (ServiceProvider.Settings.SelectedBitmap != null &&
                    ServiceProvider.Settings.SelectedBitmap.FileItem != null &&
                    filestodelete.Count == 0)
                {
                    filestodelete.Add(ServiceProvider.Settings.SelectedBitmap.FileItem);
                }

                if (filestodelete.Count == 0)
                {
                    return;
                }
                int selectedindex = ImageLIst.Items.IndexOf(filestodelete[0]);

                bool delete = false;
                if (filestodelete.Count > 1)
                {
                    delete = MessageBox.Show("Multile files are selected !! Do you really want to delete selected files ?", "Delete files",
                                             MessageBoxButton.YesNo) == MessageBoxResult.Yes;
                }
                else
                {
                    delete = MessageBox.Show("Do you really want to delete selected file ?", "Delete file",
                                             MessageBoxButton.YesNo) == MessageBoxResult.Yes;
                }
                if (delete)
                {
                    foreach (FileItem fileItem in filestodelete)
                    {
                        if ((ServiceProvider.Settings.SelectedBitmap != null &&
                             ServiceProvider.Settings.SelectedBitmap.FileItem != null &&
                             fileItem.FileName == ServiceProvider.Settings.SelectedBitmap.FileItem.FileName))
                        {
                            ServiceProvider.Settings.SelectedBitmap.DisplayImage = null;
                        }
                        if (File.Exists(fileItem.FileName))
                        {
                            FileSystem.DeleteFile(fileItem.FileName, UIOption.OnlyErrorDialogs,
                                                  RecycleOption.SendToRecycleBin);
                        }
                        fileItem.RemoveThumbs();
                        ServiceProvider.Settings.DefaultSession.Files.Remove(fileItem);
                    }
                    if (selectedindex < ImageLIst.Items.Count)
                    {
                        ImageLIst.SelectedIndex = selectedindex + 1;
                        ImageLIst.SelectedIndex = selectedindex - 1;
                        FileItem item = ImageLIst.SelectedItem as FileItem;

                        if (item != null)
                        {
                            ImageLIst.ScrollIntoView(item);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Log.Error("Error to delete file", exception);
            }
        }
 public DateTime FileDate(FileItem item)
 {
     return(_zipPackageFile[item.ZipFileName].LastModified);
 }
Exemple #29
0
        /// <summary>
        /// Photoes the captured.
        /// </summary>
        /// <param name="o">The o.</param>
        private void PhotoCaptured(object o)
        {
            PhotoCapturedEventArgs eventArgs = o as PhotoCapturedEventArgs;

            if (eventArgs == null)
            {
                return;
            }
            try
            {
                Log.Debug(TranslationStrings.MsgPhotoTransferBegin);
                eventArgs.CameraDevice.IsBusy = true;
                var extension = Path.GetExtension(eventArgs.FileName);

                // the capture is for live view preview
                if (LiveViewManager.PreviewRequest.ContainsKey(eventArgs.CameraDevice) &&
                    LiveViewManager.PreviewRequest[eventArgs.CameraDevice])
                {
                    LiveViewManager.PreviewRequest[eventArgs.CameraDevice] = false;
                    var file = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + extension);
                    eventArgs.CameraDevice.TransferFile(eventArgs.Handle, file);
                    eventArgs.CameraDevice.IsBusy           = false;
                    eventArgs.CameraDevice.TransferProgress = 0;
                    eventArgs.CameraDevice.ReleaseResurce(eventArgs.Handle);
                    LiveViewManager.Preview[eventArgs.CameraDevice] = file;
                    LiveViewManager.OnPreviewCaptured(eventArgs.CameraDevice, file);
                    return;
                }

                CameraProperty property = eventArgs.CameraDevice.LoadProperties();
                PhotoSession   session  = (PhotoSession)eventArgs.CameraDevice.AttachedPhotoSession ??
                                          ServiceProvider.Settings.DefaultSession;
                StaticHelper.Instance.SystemMessage = "";


                if (!eventArgs.CameraDevice.CaptureInSdRam || PhotoUtils.IsMovie(eventArgs.FileName))
                {
                    if (property.NoDownload)
                    {
                        eventArgs.CameraDevice.IsBusy = false;
                        eventArgs.CameraDevice.ReleaseResurce(eventArgs.Handle);
                        StaticHelper.Instance.SystemMessage = "File transfer disabled";
                        return;
                    }
                    if (extension != null && (session.DownloadOnlyJpg && extension.ToLower() != ".jpg"))
                    {
                        eventArgs.CameraDevice.IsBusy = false;
                        eventArgs.CameraDevice.ReleaseResurce(eventArgs.Handle);
                        return;
                    }
                }

                StaticHelper.Instance.SystemMessage = TranslationStrings.MsgPhotoTransferBegin;

                string tempFile = Path.GetTempFileName();

                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }

                Stopwatch stopWatch = new Stopwatch();
                // transfer file from camera to temporary folder
                // in this way if the session folder is used as hot folder will prevent write errors
                stopWatch.Start();
                if (!eventArgs.CameraDevice.CaptureInSdRam && session.DownloadThumbOnly)
                {
                    eventArgs.CameraDevice.TransferFileThumb(eventArgs.Handle, tempFile);
                }
                else
                {
                    eventArgs.CameraDevice.TransferFile(eventArgs.Handle, tempFile);
                }
                eventArgs.CameraDevice.TransferProgress = 0;
                eventArgs.CameraDevice.IsBusy           = false;
                stopWatch.Stop();
                string strTransfer = "Transfer time : " + stopWatch.Elapsed.TotalSeconds.ToString("##.###") + " Speed :" +
                                     Math.Round(
                    new System.IO.FileInfo(tempFile).Length / 1024.0 / 1024 /
                    stopWatch.Elapsed.TotalSeconds, 2) + " Mb/s";
                Log.Debug(strTransfer);

                string fileName = "";
                if (!session.UseOriginalFilename || eventArgs.CameraDevice.CaptureInSdRam)
                {
                    fileName =
                        session.GetNextFileName(eventArgs.FileName, eventArgs.CameraDevice, tempFile);
                }
                else
                {
                    fileName = Path.Combine(session.Folder, eventArgs.FileName);
                    if (File.Exists(fileName) && !session.AllowOverWrite)
                    {
                        fileName =
                            StaticHelper.GetUniqueFilename(
                                Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName) +
                                "_", 0,
                                Path.GetExtension(fileName));
                    }
                }

                if (session.AllowOverWrite && File.Exists(fileName))
                {
                    PhotoUtils.WaitForFile(fileName);
                    File.Delete(fileName);
                }

                // make lower case extension
                if (session.LowerCaseExtension && !string.IsNullOrEmpty(Path.GetExtension(fileName)))
                {
                    fileName = Path.Combine(Path.GetDirectoryName(fileName),
                                            Path.GetFileNameWithoutExtension(fileName) + Path.GetExtension(fileName).ToLower());
                }


                if (session.AskSavePath)
                {
                    SaveFileDialog dialog = new SaveFileDialog();
                    dialog.Filter           = "All files|*.*";
                    dialog.Title            = "Save captured photo";
                    dialog.FileName         = fileName;
                    dialog.InitialDirectory = Path.GetDirectoryName(fileName);
                    if (dialog.ShowDialog() == true)
                    {
                        fileName = dialog.FileName;
                    }
                    else
                    {
                        eventArgs.CameraDevice.IsBusy = false;
                        if (File.Exists(tempFile))
                        {
                            File.Delete(tempFile);
                        }
                        return;
                    }
                }

                if (!Directory.Exists(Path.GetDirectoryName(fileName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                }


                string backupfile = null;
                if (session.BackUp)
                {
                    backupfile = session.CopyBackUp(tempFile, fileName);
                    if (string.IsNullOrEmpty(backupfile))
                    {
                        StaticHelper.Instance.SystemMessage = "Unable to save the backup";
                    }
                }

                // execute plugins which are executed before transfer
                if (ServiceProvider.Settings.DefaultSession.AutoExportPluginConfigs.Count((x) => !x.RunAfterTransfer) > 0)
                {
                    FileItem tempitem = new FileItem(tempFile);
                    tempitem.Name           = Path.GetFileName(fileName);
                    tempitem.BackupFileName = backupfile;
                    tempitem.Series         = session.Series;
                    tempitem.AddTemplates(eventArgs.CameraDevice, session);
                    ExecuteAutoexportPlugins(eventArgs.CameraDevice, tempitem, false);
                }


                if ((!eventArgs.CameraDevice.CaptureInSdRam || PhotoUtils.IsMovie(fileName)) && session.DeleteFileAfterTransfer)
                {
                    eventArgs.CameraDevice.DeleteObject(new DeviceObject()
                    {
                        Handle = eventArgs.Handle
                    });
                }

                File.Copy(tempFile, fileName);

                if (File.Exists(tempFile))
                {
                    PhotoUtils.WaitForFile(tempFile);
                    File.Delete(tempFile);
                }

                if (session.WriteComment)
                {
                    if (!string.IsNullOrEmpty(session.Comment))
                    {
                        Exiv2Helper.SaveComment(fileName, session.Comment);
                    }
                    if (session.SelectedTag1 != null && !string.IsNullOrEmpty(session.SelectedTag1.Value))
                    {
                        Exiv2Helper.AddKeyword(fileName, session.SelectedTag1.Value);
                    }
                    if (session.SelectedTag2 != null && !string.IsNullOrEmpty(session.SelectedTag2.Value))
                    {
                        Exiv2Helper.AddKeyword(fileName, session.SelectedTag2.Value);
                    }
                    if (session.SelectedTag3 != null && !string.IsNullOrEmpty(session.SelectedTag3.Value))
                    {
                        Exiv2Helper.AddKeyword(fileName, session.SelectedTag3.Value);
                    }
                    if (session.SelectedTag4 != null && !string.IsNullOrEmpty(session.SelectedTag4.Value))
                    {
                        Exiv2Helper.AddKeyword(fileName, session.SelectedTag4.Value);
                    }
                }

                if (session.ExternalData != null)
                {
                    session.ExternalData.FileName = fileName;
                }

                // prevent crash og GUI when item count updated
                Dispatcher.Invoke(new Action(delegate
                {
                    try
                    {
                        _selectedItem = session.GetNewFileItem(fileName);
                        _selectedItem.BackupFileName = backupfile;
                        _selectedItem.Series         = session.Series;
                        // _selectedItem.Transformed = tempitem.Transformed;
                        _selectedItem.AddTemplates(eventArgs.CameraDevice, session);
                        ServiceProvider.Database.Add(new DbFile(_selectedItem, eventArgs.CameraDevice.SerialNumber, eventArgs.CameraDevice.DisplayName, session.Name));
                    }
                    catch (Exception ex)
                    {
                    }
                }));

                // execute plugins which are executed after transfer
                ExecuteAutoexportPlugins(eventArgs.CameraDevice, _selectedItem, true);

                Dispatcher.Invoke(() =>
                {
                    _selectedItem.RemoveThumbs();
                    session.Add(_selectedItem);
                    ServiceProvider.OnFileTransfered(_selectedItem);
                });


                if (ServiceProvider.Settings.MinimizeToTrayIcon && !IsVisible && !ServiceProvider.Settings.HideTrayNotifications)
                {
                    MyNotifyIcon.HideBalloonTip();
                    MyNotifyIcon.ShowBalloonTip("Photo transfered", fileName, BalloonIcon.Info);
                }

                ServiceProvider.DeviceManager.LastCapturedImage[eventArgs.CameraDevice] = fileName;

                //select the new file only when the multiple camera support isn't used to prevent high CPU usage on raw files
                if (ServiceProvider.Settings.AutoPreview &&
                    !ServiceProvider.WindowsManager.Get(typeof(MultipleCameraWnd)).IsVisible&&
                    !ServiceProvider.Settings.UseExternalViewer)
                {
                    if ((Path.GetExtension(fileName).ToLower() == ".jpg" && ServiceProvider.Settings.AutoPreviewJpgOnly) ||
                        !ServiceProvider.Settings.AutoPreviewJpgOnly)
                    {
                        if ((DateTime.Now - _lastLoadTime).TotalSeconds < 4)
                        {
                            _selectiontimer.Stop();
                            _selectiontimer.Start();
                        }
                        else
                        {
                            ServiceProvider.WindowsManager.ExecuteCommand(WindowsCmdConsts.Select_Image, _selectedItem);
                        }
                    }
                }
                _lastLoadTime = DateTime.Now;
                //ServiceProvider.Settings.Save(session);
                StaticHelper.Instance.SystemMessage = TranslationStrings.MsgPhotoTransferDone + " " + strTransfer;

                if (ServiceProvider.Settings.UseExternalViewer &&
                    File.Exists(ServiceProvider.Settings.ExternalViewerPath))
                {
                    string arg = ServiceProvider.Settings.ExternalViewerArgs;
                    arg = arg.Contains("%1") ? arg.Replace("%1", fileName) : arg + " " + fileName;
                    PhotoUtils.Run(ServiceProvider.Settings.ExternalViewerPath, arg, ProcessWindowStyle.Normal);
                }
                if (ServiceProvider.Settings.PlaySound)
                {
                    PhotoUtils.PlayCaptureSound();
                }
                eventArgs.CameraDevice.ReleaseResurce(eventArgs.Handle);

                //show fullscreen only when the multiple camera support isn't used
                if (ServiceProvider.Settings.Preview &&
                    !ServiceProvider.WindowsManager.Get(typeof(MultipleCameraWnd)).IsVisible&&
                    !ServiceProvider.Settings.UseExternalViewer)
                {
                    ServiceProvider.WindowsManager.ExecuteCommand(WindowsCmdConsts.FullScreenWnd_ShowTimed);
                }

                Log.Debug("Photo transfer done.");
            }
            catch (Exception ex)
            {
                eventArgs.CameraDevice.IsBusy       = false;
                StaticHelper.Instance.SystemMessage = TranslationStrings.MsgPhotoTransferError + " " + ex.Message;
                Log.Error("Transfer error !", ex);
            }
            // not indicated to be used
            GC.Collect();
            //GC.WaitForPendingFinalizers();
        }
Exemple #30
0
        private void TransferFiles()
        {
            DateTime starttime      = DateTime.Now;
            long     totalbytes     = 0;
            bool     somethingwrong = false;
            AsyncObservableCollection <FileItem> itemstoExport =
                new AsyncObservableCollection <FileItem>(Items.Where(x => x.IsChecked));

            dlg.MaxValue = itemstoExport.Count;
            dlg.Progress = 0;
            int i = 0;

            foreach (FileItem fileItem in itemstoExport)
            {
                if (fileItem.ItemType == FileItemType.Missing)
                {
                    continue;
                }
                if (!fileItem.IsChecked)
                {
                    continue;
                }
                dlg.Label       = fileItem.FileName;
                dlg.ImageSource = fileItem.Thumbnail;
                PhotoSession session = (PhotoSession)fileItem.Device.AttachedPhotoSession ??
                                       ServiceProvider.Settings.DefaultSession;
                string fileName = "";

                if (!session.UseOriginalFilename)
                {
                    //TODO: transfer file first
                    fileName =
                        session.GetNextFileName(Path.GetExtension(fileItem.FileName),
                                                fileItem.Device, "");
                }
                else
                {
                    fileName = Path.Combine(session.Folder, fileItem.FileName);
                    if (File.Exists(fileName))
                    {
                        fileName =
                            StaticHelper.GetUniqueFilename(
                                Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName) +
                                "_", 0,
                                Path.GetExtension(fileName));
                    }
                }

                string dir = Path.GetDirectoryName(fileName);
                if (dir != null && !Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                try
                {
                    fileItem.Device.TransferFile(fileItem.DeviceObject.Handle, fileName);
                }
                catch (Exception exception)
                {
                    somethingwrong = true;
                    Log.Error("Transfer error", exception);
                }

                // double check if file was transferred
                if (File.Exists(fileName))
                {
                    if (delete)
                    {
                        fileItem.Device.DeleteObject(fileItem.DeviceObject);
                    }
                }
                else
                {
                    somethingwrong = true;
                }
                if (!File.Exists(fileName))
                {
                    MessageBox.Show("Unable download file. Aborting!");
                    break;
                }
                totalbytes += new FileInfo(fileName).Length;
                FileItem item1 = fileItem;
                Dispatcher.Invoke(new Action(delegate
                {
                    var item          = session.AddFile(fileName);
                    item.CameraSerial = item1.Device.SerialNumber;
                    item.OriginalName = item1.FileName;
                }));
                i++;
                dlg.Progress = i;
            }

            Log.Debug("File transfer done");

            if (format)
            {
                dlg.MaxValue = ServiceProvider.DeviceManager.ConnectedDevices.Count;
                dlg.Progress = 0;
                int ii = 0;
                if (!somethingwrong)
                {
                    foreach (ICameraDevice connectedDevice in ServiceProvider.DeviceManager.ConnectedDevices)
                    {
                        try
                        {
                            dlg.Label = connectedDevice.DisplayName;
                            ii++;
                            dlg.Progress = ii;
                            Log.Debug("Start format");
                            Log.Debug(connectedDevice.PortName);
                            connectedDevice.FormatStorage(null);
                            Thread.Sleep(200);
                            Log.Debug("Format done");
                        }
                        catch (Exception exception)
                        {
                            Log.Error("Unable to format device ", exception);
                        }
                    }
                }
                else
                {
                    Log.Debug("File transfer failed, format aborted!");
                    StaticHelper.Instance.SystemMessage = "File transfer failed, format aborted!";
                }
            }
            dlg.Hide();
            double transfersec = (DateTime.Now - starttime).TotalSeconds;

            Log.Debug(string.Format("[BENCHMARK]Total byte transferred ;{0} Total seconds :{1} Speed : {2} Mbyte/sec ",
                                    totalbytes,
                                    transfersec, (totalbytes / transfersec / 1024 / 1024).ToString("0000.00")));
            ServiceProvider.Settings.Save();
            ServiceProvider.WindowsManager.ExecuteCommand(WindowsCmdConsts.DownloadPhotosWnd_Hide);
        }
Exemple #31
0
        private void PopulateImageList()
        {
            _timeDif.Clear();
            _itembycamera.Clear();
            Items.Clear();
            _timeTable.Clear();
            if (ServiceProvider.DeviceManager.ConnectedDevices.Count == 0)
            {
                return;
            }
            //int threshold = 0;
            //bool checkset = false;
            int counter = 0;

            dlg.MaxValue = ServiceProvider.DeviceManager.ConnectedDevices.Count;
            foreach (ICameraDevice cameraDevice in ServiceProvider.DeviceManager.ConnectedDevices)
            {
                counter++;
                dlg.Progress = counter;
                CameraProperty property = cameraDevice.LoadProperties();
                cameraDevice.DisplayName = property.DeviceName;
                dlg.Label  = cameraDevice.DisplayName;
                dlg.Label2 = "";

                try
                {
                    var images = cameraDevice.GetObjects(null, ServiceProvider.Settings.LoadThumbsDownload);
                    if (images.Count > 0)
                    {
                        foreach (DeviceObject deviceObject in images)
                        {
                            if (!_itembycamera.ContainsKey(cameraDevice))
                            {
                                _itembycamera.Add(cameraDevice, new AsyncObservableCollection <FileItem>());
                            }

                            var fileitem = new FileItem(deviceObject, cameraDevice);

                            dlg.Label2 = fileitem.FileName;

                            PhotoSession session = (PhotoSession)cameraDevice.AttachedPhotoSession ??
                                                   ServiceProvider.Settings.DefaultSession;

                            // check if file exist with same name from this camera
                            fileitem.IsChecked = session.GetFile(deviceObject.FileName, cameraDevice.SerialNumber) ==
                                                 null;

                            _itembycamera[cameraDevice].Add(fileitem);
                            //Items.Add(new FileItem(deviceObject, cameraDevice));
                        }
                    }
                }
                catch (Exception exception)
                {
                    StaticHelper.Instance.SystemMessage = TranslationStrings.LabelErrorLoadingFileList;
                    Log.Error("Error loading file list", exception);
                }
                Thread.Sleep(500);
            }

            Dispatcher.Invoke(new Action(delegate
            {
                foreach (var fileItem in _itembycamera.Values.SelectMany(lists => lists))
                {
                    Items.Add(fileItem);
                }
                CollectionView myView;
                myView = (CollectionView)CollectionViewSource.GetDefaultView(Items);
                myView.GroupDescriptions.Clear();

                if (myView.CanGroup == true)
                {
                    PropertyGroupDescription groupDescription
                        = new PropertyGroupDescription("Device");
                    myView.GroupDescriptions.Add(groupDescription);
                }

                if (ServiceProvider.DeviceManager.ConnectedDevices.Count > 1)
                {
                    lst_items.Visibility        = Visibility.Visible;
                    lst_items_simple.Visibility = Visibility.Collapsed;
                    lst_items.ItemsSource       = myView;
                }
                else
                {
                    lst_items.Visibility         = Visibility.Collapsed;
                    lst_items_simple.Visibility  = Visibility.Visible;
                    lst_items_simple.ItemsSource = Items;
                }
            }));
            dlg.Hide();
        }
Exemple #32
0
        /// <summary>
        /// This is used to merge the conceptual content table of contents with
        /// any additional content table of contents information.
        /// </summary>
        /// <remarks>This will also split the table of contents if any entry
        /// has the "split" option.  A split in the conceptual content will
        /// take precedence as additional content is always appended to
        /// the end of the conceptual content.  Likewise, a default topic in
        /// the conceptual content will take precedence over a default topic
        /// in the additional content.</remarks>
        private void MergeConceptualAndAdditionalContentTocInfo()
        {
            FileItemCollection      siteMapFiles;
            List <ITableOfContents> tocFiles;
            TocEntryCollection      siteMap, mergedToc;
            TocEntry tocEntry;

            this.ReportProgress(BuildStep.MergeTablesOfContents,
                                "Merging conceptual and additional tables of contents...");

            if (this.ExecutePlugIns(ExecutionBehaviors.InsteadOf))
            {
                return;
            }

            this.ExecutePlugIns(ExecutionBehaviors.Before);

            // Add the conceptual content layout files
            tocFiles = new List <ITableOfContents>();

            foreach (TopicCollection topics in conceptualContent.Topics)
            {
                tocFiles.Add(topics);
            }

            // Load all site maps and add them to the list
            siteMapFiles = new FileItemCollection(project, BuildAction.SiteMap);

            foreach (FileItem fileItem in siteMapFiles)
            {
                this.ReportProgress("    Loading site map '{0}'", fileItem.FullPath);
                siteMap = new TocEntryCollection(fileItem);
                siteMap.Load();

                // Merge destination file information into the site map
                foreach (TocEntry site in siteMap)
                {
                    this.MergeTocInfo(site);
                }

                tocFiles.Add(siteMap);
            }

            // Sort the files
            tocFiles.Sort((x, y) =>
            {
                FileItem fx = x.ContentLayoutFile, fy = y.ContentLayoutFile;

                if (fx.SortOrder < fy.SortOrder)
                {
                    return(-1);
                }

                if (fx.SortOrder > fy.SortOrder)
                {
                    return(1);
                }

                return(String.Compare(fx.Name, fy.Name, StringComparison.OrdinalIgnoreCase));
            });

            // Create the merged TOC
            mergedToc = new TocEntryCollection();

            foreach (ITableOfContents file in tocFiles)
            {
                file.GenerateTableOfContents(mergedToc, project);
            }

            // If there were no site maps, add items copied from the project.
            // Empty container nodes are ignored.
            if (siteMapFiles.Count == 0 && toc != null && toc.Count != 0)
            {
                foreach (TocEntry t in toc)
                {
                    if (t.DestinationFile != null || t.Children.Count != 0)
                    {
                        mergedToc.Add(t);
                    }
                }
            }

            toc = mergedToc;

            if (toc.Count != 0)
            {
                // Look for the default topic
                tocEntry = toc.FindDefaultTopic();

                if (tocEntry != null)
                {
                    defaultTopic = tocEntry.DestinationFile;
                }
            }

            this.ExecutePlugIns(ExecutionBehaviors.After);
        }
Exemple #33
0
        private void Trigger_Event(string cmd, object o)
        {
            ImageLIst.Dispatcher.Invoke(new Action(delegate
            {
                switch (cmd)
                {
                case WindowsCmdConsts.Next_Image:
                    if (ImageLIst.SelectedIndex <
                        ImageLIst.Items.Count - 1)
                    {
                        FileItem item =
                            ImageLIst.SelectedItem as FileItem;
                        if (item != null)
                        {
                            int ind = ImageLIst.Items.IndexOf(item);
                            ImageLIst.SelectedIndex = ind + 1;
                        }
                        item = ImageLIst.SelectedItem as FileItem;
                        if (item != null)
                        {
                            ImageLIst.ScrollIntoView(item);
                        }
                    }
                    break;

                case WindowsCmdConsts.Prev_Image:
                    if (ImageLIst.SelectedIndex > 0)
                    {
                        FileItem item =
                            ImageLIst.SelectedItem as FileItem;
                        if (item != null)
                        {
                            int ind = ImageLIst.Items.IndexOf(item);
                            ImageLIst.SelectedIndex = ind - 1;
                        }
                        item = ImageLIst.SelectedItem as FileItem;
                        if (item != null)
                        {
                            ImageLIst.ScrollIntoView(item);
                        }
                    }
                    break;

                case WindowsCmdConsts.Like_Image:
                    if (ImageLIst.SelectedItem != null)
                    {
                        FileItem item = null;
                        if (o != null)
                        {
                            item = ServiceProvider.Settings.DefaultSession.GetByName(o as string);
                        }
                        else
                        {
                            item = ImageLIst.SelectedItem as FileItem;
                        }
                        if (item != null)
                        {
                            item.IsLiked = !item.IsLiked;
                        }
                    }
                    break;

                case WindowsCmdConsts.Unlike_Image:
                    if (ImageLIst.SelectedItem != null)
                    {
                        FileItem item = null;
                        if (o != null)
                        {
                            item =
                                ServiceProvider.Settings.DefaultSession
                                .GetByName(o as string);
                        }
                        else
                        {
                            item = ImageLIst.SelectedItem as FileItem;
                        }
                        if (item != null)
                        {
                            item.IsUnLiked = !item.IsUnLiked;
                        }
                    }
                    break;

                case WindowsCmdConsts.Del_Image:
                    {
                        DeleteItem();
                    }
                    break;

                case WindowsCmdConsts.Select_Image:
                    FileItem fileItem = o as FileItem;
                    if (fileItem != null)
                    {
                        ImageLIst.SelectedValue = fileItem;
                        ImageLIst.ScrollIntoView(fileItem);
                    }
                    break;

                case WindowsCmdConsts.Refresh_Image:
                    if (!_worker.IsBusy)
                    {
                        _worker.RunWorkerAsync(false);
                    }
                    break;
                }
            }));
        }
Exemple #34
0
 protected override void LogException(FileItem fileItem, Exception ex)
 {
     fileItem.VideoGpuEncodeProcess.SetErrorMessage("Exception non gérée", "Exception VideoGpuEncoding non gérée", ex);
 }
Exemple #35
0
        //=====================================================================

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="file">The token file associated with the collection.</param>
        /// <remarks>Tokens are not loaded until the <see cref="Load" /> method
        /// is called.</remarks>
        public TokenCollection(FileItem file)
        {
            fileItem = file;
        }
Exemple #36
0
 public async ValueTask <bool> TryHandleFileChange(DotNetWatchContext context, FileItem file, CancellationToken cancellationToken)
 {
     return
         (await _staticFileHandler.TryHandleFileChange(context, file, cancellationToken) ||
          await _scopedCssFileHandler.TryHandleFileChange(context, file, cancellationToken) ||
          await _compilationHandler.TryHandleFileChange(context, file, cancellationToken));
 }
        private static List <FileItem> ProcessFilesInFolder(string SearchPath, string ReportFile, List <FileItem> fileList, List <FileItem> DamagedList, ProcessingPower ProcessingPower)
        {
            List <FileItem> Calculated = Retriever.GetFiles(SearchPath, SearchExtension.Everything, null, false).Select(x => new FileItem()
            {
                Filepath = x
            }).ToList();
            ParallelOptions pOptions = new ParallelOptions();

            switch (ProcessingPower)
            {
            case ProcessingPower.Half:
                pOptions.MaxDegreeOfParallelism = (Environment.ProcessorCount / 2);
                break;

            case ProcessingPower.Full:
                pOptions.MaxDegreeOfParallelism = Environment.ProcessorCount;
                break;

            case ProcessingPower.Single:
            default:
                pOptions.MaxDegreeOfParallelism = 1;
                break;
            }
            var result = Parallel.ForEach(Calculated, pOptions,
                                          file =>
            {
                file.Hash = ComputeMD5(file.Filepath);
            });

            if (Calculated.Any())
            {
                foreach (FileItem file in Calculated)
                {
                    try
                    {
                        FileItem fcs = fileList.FirstOrDefault(s => s.Hash == file.Hash && s.Filepath == file.Filepath);
                        if (fcs != null)
                        {//old file checksummed
                            foreach (var fileItem in fileList.Where(s => s.Hash == file.Hash && s.Filepath == file.Filepath))
                            {
                                fileItem.IsChecksummed = ChecksumStat.ExistingFileChecked;
                            }
                        }
                        else
                        {
                            FileItem targetfcs = fileList.FirstOrDefault(s => s.Hash != file.Hash && s.Filepath == file.Filepath);
                            if (targetfcs != null)
                            {//different file with duplicate filename or file corrupted
                                targetfcs.IsChecksummed = ChecksumStat.DuplicateNameOrCorrupted;
                                DamagedList.Add(targetfcs);
                                fileList.Remove(targetfcs);
                            }
                            //new file
                            FileItem fs = new FileItem()
                            {
                                Hash          = file.Hash,
                                Filepath      = file.Filepath,
                                IsChecksummed = ChecksumStat.NewFileChecked
                            };
                            fileList.Add(fs);
                        }
                    }
                    catch (UnauthorizedAccessException uaex)
                    {
                        Console.WriteLine(uaex.Message);
                        using (StreamWriter report = File.AppendText(ReportFile))
                        {
                            report.WriteLine(uaex.Message);
                        }
                    }
                }
            }
            return(fileList);
        }
Exemple #38
0
 private void AddFileView(FileItem file_item, VertexControl source, PocVertex source_vertex, int line)
 {
     AddFileView(file_item, source, source_vertex, new List <int> {
         line
     });
 }
        public static bool Encode(FileItem fileItem)
        {
            FileItem sourceFile = fileItem.FileContainer.SourceFileItem;

            try
            {
                fileItem.SpriteEncodeProcess.StartProcessDateTime();

                LogManager.AddSpriteMessage(LogLevel.Information, "SourceFilePath " + Path.GetFileName(fileItem.SourceFilePath), "Start Sprite");

                int nbImages     = VideoSettings.Instance.NbSpriteImages;
                int heightSprite = VideoSettings.Instance.HeightSpriteImages;

                // Calculer nb image/s
                //  si < 100s de vidéo -> 1 image/s
                //  sinon (nb secondes de la vidéo / 100) image/s
                string frameRate = "1";
                int    duration  = sourceFile.VideoDuration.Value;
                if (duration > nbImages)
                {
                    frameRate = $"{nbImages}/{duration}"; //frameRate = inverse de image/s
                }

                int    spriteWidth  = SizeHelper.GetWidth(sourceFile.VideoWidth.Value, sourceFile.VideoHeight.Value, heightSprite);
                string sizeImageMax = $"scale={spriteWidth}:{heightSprite}";

                // Extract frameRate image/s de la video
                string arguments            = $"-y -i {Path.GetFileName(fileItem.SourceFilePath)} -r {frameRate} -vf {sizeImageMax} -f image2 {GetPattern(fileItem.TempFilePath)}";
                var    ffmpegProcessManager = new FfmpegProcessManager(fileItem, fileItem.SpriteEncodeProcess);
                ffmpegProcessManager.StartProcess(arguments, VideoSettings.Instance.EncodeGetImagesTimeout);
                IList <string> files = GetListImageFrom(fileItem.TempFilePath); // récupération des images

                LogManager.AddSpriteMessage(LogLevel.Information, (files.Count - 1) + " images", "Start Combine images");


                // garder que les 100 dernières images pour éliminer les premières (1 ou 2 en réalité)
                int skip = files.Count > VideoSettings.Instance.NbSpriteImages
                    ? files.Count - VideoSettings.Instance.NbSpriteImages
                    : 0;
                var list = new StringBuilder();
                foreach (string imagePath in files.Skip(skip))
                {
                    if (list.Length > 0)
                    {
                        list.Append(" ");
                    }

                    list.Append(Path.GetFileName(imagePath));
                }

                arguments = $"-mode concatenate -tile 1x {list} {Path.GetFileName(fileItem.TempFilePath)}";
                var  process       = new ProcessManager(Path.Combine(GeneralSettings.Instance.ImageMagickPath, "montage"), arguments, LogManager.SpriteLogger);
                bool successSprite = process.Launch(5);
                TempFileManager.SafeDeleteTempFiles(files); // suppression des images
                if (!successSprite)
                {
                    fileItem.SpriteEncodeProcess.SetErrorMessage("Error while combine images", "Error creation sprite while combine images");
                    return(false);
                }

                fileItem.ReplaceOutputPathWithTempPath();
                LogManager.AddSpriteMessage(LogLevel.Information, "OutputFileName " + Path.GetFileName(fileItem.OutputFilePath) + " / FileSize " + fileItem.FileSize, "End Sprite");
                fileItem.SpriteEncodeProcess.EndProcessDateTime();
                return(true);
            }
            catch (Exception ex)
            {
                string message = "Video Duration " + sourceFile.VideoDuration + " / FileSize " + fileItem.FileSize + " / Progress " + fileItem.SpriteEncodeProcess.Progress;
                fileItem.SpriteEncodeProcess.SetErrorMessage("Exception non gérée", message, ex);
                IList <string> files = GetListImageFrom(fileItem.TempFilePath); // récupération des images
                TempFileManager.SafeDeleteTempFiles(files);                     // suppression des images
                return(false);
            }
        }
	/// <summary>
	/// Returns the files as an array of 'FileItem'
	/// </summary>
	/// <param name="virtualPath">Virtual path to the filder</param>
	/// <returns>An array of 'FileItem'</returns>
	private FileItem[] GetFiles(string virtualPath)
	{
		List<FileItem> filesItems = new List<FileItem>();
		string physicalPath = this.GetPhysicalFromVirtualPath(virtualPath);
		if (physicalPath == null)
			return null;
		List<string> files = new List<string>();// The files in this folder : 'physicalPath' ;

		try
		{
			foreach (string patern in this.SearchPatterns)
			{// Applied flters in the 'SearchPatterns' property;
				foreach (string filePath in Directory.GetFiles(physicalPath, patern))
				{
					if (!files.Contains(filePath))
						files.Add(filePath);
				}
			}

			foreach (string filePath in files)
			{
				FileInfo fileInfo = new FileInfo(filePath);
				string url = ItemHandlerPath + "?path=" + virtualPath + fileInfo.Name;
				FileItem fileItem = new FileItem(fileInfo.Name,
													fileInfo.Extension,
													fileInfo.Length,
													string.Empty,
													url,
													null,
													GetPermissions(filePath)
												);
				filesItems.Add(fileItem);
			}
		}
		catch (IOException)
		{// The parent directory is moved or deleted

		}

		return filesItems.ToArray();
	}
Exemple #41
0
        public void Queue(FileItem fileItem, string messageIpfs)
        {
            base.Queue(fileItem, fileItem.AudioVideoCpuEncodeProcess);

            fileItem.IpfsProcess.SetProgress(messageIpfs, true);
        }
Exemple #42
0
 public WpFileItem(FileItem file)
     : this()
 {
     _file = file;
     SetFile();
 }
Exemple #43
0
        private void TestEditor_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                TextEditor editor    = TreeHelpers.FindVisualParent <TextEditor>((DependencyObject)sender);
                var        file_path = ((FileVertex)TreeHelpers.FindVisualParent <VertexControl>((DependencyObject)editor).Vertex).FilePath;

                // Ctrl+Click Go to definition
                var position = editor.GetPositionFromPoint(e.GetPosition(editor));
                if (position != null)
                {
                    var clicked_line_no = position.Value.Line;
                    var offset          = editor.Document.GetOffset(position.Value.Location);
                    var start           = TextUtilities.GetNextCaretPosition(editor.Document, offset, LogicalDirection.Backward, CaretPositioningMode.WordBorder);
                    if (start < 0)
                    {
                        return;
                    }
                    var end  = TextUtilities.GetNextCaretPosition(editor.Document, offset, LogicalDirection.Forward, CaretPositioningMode.WordBorder);
                    var word = editor.Document.GetText(start, end - start);
                    //System.Diagnostics.Debug.Print(word);

                    if (graph_provider.root_vertex.CtagsRun && graph_provider.root_vertex.CtagsMatches.ContainsKey(word))
                    {
                        Dictionary <string, List <int> > files_and_lines = new Dictionary <string, List <int> >();
                        //foreach (string line in ctags_info.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries))
                        //{
                        //System.Diagnostics.Debug.Print(line);
                        foreach (List <string> match in graph_provider.root_vertex.CtagsMatches[word])
                        {
                            int line_no = 1;
                            foreach (string field in match)
                            {
                                if (field.StartsWith("line:"))
                                {
                                    line_no = int.Parse(field.Split(new char[] { ':' })[1]);
                                }
                            }
                            var file_path_to_add = match[1];
                            if ((file_path_to_add != file_path) || ((file_path_to_add == file_path) && (line_no != clicked_line_no)))
                            {
                                if (files_and_lines.ContainsKey(file_path_to_add))
                                {
                                    files_and_lines[match[1]].Add(line_no);
                                }
                                else
                                {
                                    files_and_lines[file_path_to_add] = new List <int>();
                                    files_and_lines[file_path_to_add].Add(line_no);
                                }
                            }
                        }
                        if (files_and_lines.Count() > 0)
                        {
                            VertexControl editor_vertex = TreeHelpers.FindVisualParent <VertexControl>(editor);
                            VertexControl ctags_vertex  = AddCtagsAnchor(word, editor_vertex, (PocVertex)editor_vertex.Vertex);
                            foreach (string file in files_and_lines.Keys)
                            {
                                FileItem fi = new FileItem
                                {
                                    FileName  = Path.GetFileName(file),
                                    FullPath  = Path.Combine(graph_provider.root_dir, file),
                                    Extension = Path.GetExtension(file),
                                    RelPath   = file,
                                };
                                //if (!(Path.GetFullPath(((FileVertex)editor_vertex.Vertex).FilePath) == Path.GetFullPath(fi.FullPath) && !files_and_lines[file].Contains(position.Value.Line)))
                                //{
                                AddFileView(fi, ctags_vertex, (CtagsVertex)ctags_vertex.Vertex, files_and_lines[file]);
                                //}
                            }
                            graph_provider.SaveGraph();
                        }
                        if (files_and_lines.Count() == 0)
                        {
                            editor.TextArea.TextView.BackgroundRenderers.Add(new HighlightNotesSnippetBackgroundRenderer(editor, clicked_line_no, 1));
                        }
                    }
                }
                e.Handled = true;
            }
        }
Exemple #44
0
 public FileItemTest()
 {
     fileItem = new FileItem();
 }
Exemple #45
0
 private FileItem GetFileItem(FileItem item, int fileId)
 {
     if (item == null)
         return null;
     if (item.ID == fileId)
         return item;
     if (item.SubItems != null)
     {
         foreach (var file in item.SubItems)
         {
             FileItem f = GetFileItem(file, fileId);
             if (f != null)
             {
                 if (f.ID == fileId)
                     return f;
             }
         }
     }
     return null;
 }
 private Task OnEndToEndReceivedAsync(FileItem fileItem)
 => CallFileItemNotifyAsync("OnEndToEndReceived", fileItem);
Exemple #47
0
 public bool Verify(FileItem file)
 {
     return(file.Extension.ToLower() == Extension);
 }
 public OdetteFileStreamUnstructured(FileItem fileItem, bool readOnly)
     : base(fileItem, readOnly)
 {
 }             // ctor
    public static List<SmallRNASequence> ReadCountFile(FileItem file, Func<string[], bool> accept)
    {
      var countList = new List<SmallRNASequence>();
      using (var sr = new StreamReader(file.File))
      {
        var header = sr.ReadLine();
        string line;
        while ((line = sr.ReadLine()) != null)
        {
          var parts = line.Split('\t');
          if (parts.Length < 3)
          {
            continue;
          }
          if (!accept(parts))
          {
            continue;
          }

          var seq = new SmallRNASequence()
          {
            Sample = file.Name,
            Sequence = parts[2],
            Count = int.Parse(parts[1])
          };

          countList.Add(seq);
        }
      }

      return countList;
    }
 public OdetteFileStreamFixed(FileItem fileItem, bool readOnly)
     : base(fileItem, readOnly)
 {
     this.recordSize = fileItem.MaximumRecordSize;
 }             // ctor
Exemple #51
0
        public override byte[] Read(CacheItemInfo item)
        {
            var fi = new FileItem(item);
            byte[] bytes = null;

            lock (LockObject) {
                if (!IsoStore.FileExists(fi.FileName)) {
                    return null;
                }

                using (Stream stream = IsoStore.OpenFile(fi.FileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                    bytes = new byte[stream.Length];
                    stream.Read(bytes, 0, (int)stream.Length);
                }
            }

            return bytes;
        }
Exemple #52
0
        private void Instance_Message(object sender, MessageEventArgs e)
        {
            switch (e.Name)
            {
            case Messages.LiveViewChanged:
            {
                var param = e.Param as object[];
                if (param != null)
                {
                    _liveViewData = (LiveViewData)param[1];
                    var stream = e.Context.ImageStream;
                    stream.Seek(0, SeekOrigin.Begin);
                    BitmapImage bi = new BitmapImage();
                    bi.BeginInit();
                    bi.StreamSource  = stream;
                    bi.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                    bi.CacheOption   = BitmapCacheOption.OnLoad;
                    bi.EndInit();
                    if (WorkflowManager.Instance.Context.CameraDevice.LiveViewImageZoomRatio?.Value == "All" && ShowFocusArea)
                    {
                        var writeableBitmap = BitmapFactory.ConvertToPbgra32Format(bi);
                        DrawFocusPoint(writeableBitmap, _liveViewData);
                        writeableBitmap.Freeze();
                        LiveBitmap = writeableBitmap;
                    }
                    else
                    {
                        bi.Freeze();
                        LiveBitmap = bi;
                    }
                }
            }
            break;

            case Messages.PhotoDownloaded:
            {
                RaisePropertyChanged(() => FileItems);
                FileItem item = e.Param as FileItem;
                if (item != null)
                {
                    FileItem = item;
                }
                RaisePropertyChanged(() => Bitmap);
                RaisePropertyChanged(() => PreviewTitle);
                if (FileItems.Count < 2)
                {
                    PreviewTabActive = true;
                }
            }
            break;

            case Messages.ThumbUpdated:
            case Messages.NextPhoto:
            case Messages.PrevPhoto:
            case Messages.DeletePhoto:
            case Messages.ClearPhotos:
            {
                RaisePropertyChanged(() => FileItem);
                RaisePropertyChanged(() => Bitmap);
                RaisePropertyChanged(() => PreviewTitle);
            }
            break;
            }
        }
Exemple #53
0
        public override void Write(CacheItemInfo info, byte[] data)
        {
            var fi = new FileItem(info);

            PriorityQueue.AddStorageWorkItem(() =>
            {
                lock (LockObject) {

                    for (int r = 0; r < WriteRetries; r++) {
                        try {
                            FileItem.EnsurePath(IsoStore, fi.FileName);
                            using (Stream stream = IsoStore.OpenFile(fi.FileName, FileMode.Create, FileAccess.Write, FileShare.None)) {
                                stream.Write(data, 0, data.Length);
                                stream.Flush();
                            }
                            _cache[info.UniqueName] = info;
                            break;
                        }
                        catch (IsolatedStorageException ex) {
                            Debug.WriteLine("Exception writing file: Name={0}, Length={1}, {2}", fi.FileName, data.Length, ex.Message);
                            // These IsolatedStorageExceptions seem to happen at random,
                            // haven't yet found a repro.  So for the retry,
                            // if we failed, sleep for a bit and then try again.
                            //
                            // SW: I can repro this with a long unique name - originally thought '/' in the name were the cause
                            Thread.Sleep(50);
                        }
                    }
                }
            });
        }
Exemple #54
0
    public void RefreshProjectList()
    {
        files.Clear();

        foreach (Transform item in fileList.transform)
        {
            Destroy(item.gameObject);
        }

        var directories = new DirectoryInfo(Application.persistentDataPath).GetDirectories();

        foreach (var directory in directories)
        {
            var editable = File.Exists(Path.Combine(directory.FullName, SaveFile.editableFilename));
            if (editable)
            {
                FileItem newFileItem;
                var      filenameListItem = Instantiate(filenameItemPrefab);

                try
                {
                    var    meta = SaveFile.OpenFile(directory.FullName).meta;
                    string title;
                    if (meta.version > SaveFile.VERSION)
                    {
                        title = $"Project version too high. Please update the Editor: {directory.Name}";
                        filenameListItem.GetComponentInChildren <Text>().color = Color.red;
                    }
                    else
                    {
                        title = meta.title;
                    }

                    newFileItem = new FileItem {
                        title = title, guid = directory.Name
                    };
                }
                catch (FileNotFoundException e)
                {
                    newFileItem = new FileItem {
                        title = "<b>corrupted file: " + directory.Name + "</b>", guid = directory.Name
                    };
                    filenameListItem.GetComponentInChildren <Text>().color = Color.red;
                }
                catch (Exception e)
                {
                    newFileItem = new FileItem {
                        title = "<b>corrupted file: " + directory.Name + "</b>", guid = directory.Name
                    };
                    filenameListItem.GetComponentInChildren <Text>().color = Color.red;
                    Debug.LogError(e);
                }

                filenameListItem.transform.SetParent(fileList, false);
                filenameListItem.GetComponentInChildren <Text>().text = newFileItem.title;
                newFileItem.listItem = filenameListItem;

                files.Add(newFileItem);
            }
        }
    }
Exemple #55
0
        //=====================================================================

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="file">The file build item from the project</param>
        /// <exception cref="ArgumentNullException">This is thrown if the file
        /// item is null.</exception>
        public TopicFile(FileItem file)
        {
            if(file == null)
                throw new ArgumentNullException("file");

            fileItem = file;
            revision = 1;
        }
Exemple #56
0
 public bool Verify(FileItem file)
 {
     return(file.Extension.Equals(Extension));
 }
Exemple #57
0
		private void PopulateChildren(Node workingNode, string xml, bool populateNode)
		{
			XmlReader reader = XmlReader.Create(new StringReader(xml));
            List<ItemViewerItem> fileItems = new List<ItemViewerItem>();
			string id = string.Empty;
			int param = 0;
			string icon = string.Empty;
			string iconExpanded = string.Empty;

			if (populateNode)
			{
				workingNode.BulkUpdateBegin();
			}
			else
			{
				items.Clear();
			}

			while (reader.Read())
			{
				if (reader.NodeType == XmlNodeType.Element)
				{
                    if (reader.Name == "UploaderFileNode")
					{
						while (reader.Read())
						{
							if (reader.NodeType == XmlNodeType.Element)
							{
								if (reader.Name == "ID")
								{
									id = reader.ReadInnerXml();
								}
								else if (reader.Name == "Param")
								{
									param = int.Parse(reader.ReadInnerXml());
								}
							}
                            if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "UploaderFileNode")
							{
								if (populateNode)
								{
									if (id.EndsWith("/"))
									{	// Indicates this node is a folder
										workingNode.Nodes.Add(new Node(id, GetTitle(id), (param > 0), "images/folder.png", "images/folderOpen.png", true) { EnableCheckboxes = true });
									}
								}
								else
								{
									FileItem item = new FileItem();

									item.Text = GetTitle(id);
									item.LiquidTag = id;

									if (id.EndsWith("/"))
									{
										item.Icon = "images/large/folder.png";
									}
									else
									{
										item.Icon = "images/large/" + GetIcon(id);
										item.OtherText = (Math.Round((double)param / 1024, 2)).ToString() + "KB";
									}

									fileItems.Add(item);
								}

								break;
							}
						}
					}
				}
			}

			reader.Close();

			if (populateNode)
			{
				workingNode.BulkUpdateEnd();
				workingNode.IsBusy = false;
			}
			else
			{
                items.Add(fileItems);
			}
		}
Exemple #58
0
        public void Open(FileItem File)
        {
            var Data = File.GetFileBinary();

            Model          = new GenericModel();
            Model.Skeleton = new GenericSkeleton();
            Model.Skeleton.RotationOrder = RotationOrder.ZYX;

            // decompress
            using (DataReader reader = new DataReader(new MemoryStream(Data)))
            {
                reader.BigEndian = true;

                if (reader.BaseStream.Length < 8 || !reader.ReadString(8).Equals("PERS-SZP"))
                {
                    // not compressed
                }
                else
                {
                    reader.BigEndian = true;
                    uint compressedoffset = reader.ReadUInt32();

                    reader.Seek(compressedoffset);
                    Data = Tools.Decompress.YAY0(reader.ReadBytes((int)(reader.BaseStream.Length - compressedoffset)));
                }
            }

            // decode file contents
            using (DataReader reader = new DataReader(new MemoryStream(Data)))
            {
                reader.BigEndian = true;
                reader.Seek(0x8);
                if (!reader.ReadString(8).Equals("FRAGMENT"))
                {
                    return;
                }
                reader.Seek(0x10);
                uint DataOffset            = reader.ReadUInt32();
                uint RelocationTableOffset = reader.ReadUInt32();
                reader.Skip(4); // filesize
                reader.Skip(4); // tableOffset again

                // Relocation Table
                reader.Seek(RelocationTableOffset);
                int   entryCount = reader.ReadInt32();
                int[] offsets    = new int[entryCount];
                for (int i = 0; i < entryCount; i++)
                {
                    int mask = 0xFFFF;
                    offsets[i] = reader.ReadInt32();
                    if (RelocationTableOffset > 0xFFFF)
                    {
                        mask = 0x1FFFF;                                 // hack
                    }
                    uint temp = reader.Position;
                    reader.Seek((uint)(offsets[i] & 0x1FFFF));
                    reader.WriteInt32At(reader.ReadInt32() & mask, offsets[i] & 0x1FFFF);
                    reader.Seek((uint)(offsets[i] & 0x1FFFF));
                    reader.Seek(temp);
                }

                // main data
                reader.Seek(DataOffset);
                reader.Skip(0x10);
                uint mainOffset = reader.ReadUInt32();

                // main stuff
                reader.Seek(mainOffset);
                reader.Skip(8); // i dunno
                uint offsetToTextureOffset = reader.ReadUInt32();

                reader.Seek(offsetToTextureOffset);
                uint textureOffset = reader.ReadUInt32();

                // may be objects instead of just textures
                reader.Seek(textureOffset);
                int  TextureCount  = reader.ReadInt32() & 0xFFFF; // should have 0x17 in front
                int  PaletteCount  = reader.ReadInt16();
                int  VertexCount   = reader.ReadInt16();
                uint TextureOffset = reader.ReadUInt32();
                uint PaletteOffset = reader.ReadUInt32();
                uint VertexOffset  = reader.ReadUInt32();
                reader.Skip(0x1C); //I dunno
                uint objectOffset = reader.ReadUInt32();


                // Textures-------------------------------------------------------
                List <GenericTexture> Textures = new List <GenericTexture>();
                List <byte[]>         Palettes = new List <byte[]>();

                //Read Palettes
                reader.Seek(PaletteOffset);
                for (int i = 0; i < PaletteCount; i++)
                {
                    int  colorcount      = reader.ReadInt32();
                    uint OffsetData      = reader.ReadUInt32();
                    int  OffsetSomething = reader.ReadInt32();
                    Palettes.Add(reader.GetSection(OffsetData, colorcount * 2));
                }

                // Read Textures?
                reader.Seek(TextureOffset);
                //Console.WriteLine(reader.pos().ToString("x"));
                for (int i = 0; i < TextureCount; i++)
                {
                    int  format        = reader.ReadByte();
                    int  bitsize       = reader.ReadByte();
                    uint width         = reader.ReadUInt16();
                    uint height        = reader.ReadUInt16();
                    uint size          = reader.ReadUInt16(); // sometimes 8 maybe an id? pointer?
                    uint texDataOffset = reader.ReadUInt32() & 0x1FFFF;

                    Console.WriteLine("Texture " + format + " " + bitsize + " " + size + " " + width + " " + height);

                    GenericTexture tex = new GenericTexture();
                    Textures.Add(tex);
                    tex.Name = "Texture_" + i;
                    byte[] data;
                    tex.Width  = width;
                    tex.Height = height;

                    tex.PixelFormat = PixelFormat.Rgba;
                    if (format == 4)
                    {
                        // Raw
                        if (bitsize == 1) //RGBA
                        {
                            data = reader.GetSection(texDataOffset, (int)size * bitsize);

                            tex.Mipmaps.Add(data);
                            tex.InternalFormat = PixelInternalFormat.Luminance8;
                            tex.PixelFormat    = PixelFormat.Luminance;
                        }
                    }
                    else
                    if (format == 2)
                    {
                        // Paletted

                        if (bitsize == 0) //4bpp
                        {
                            data = reader.GetSection(texDataOffset, (int)size / 2);

                            tex.Mipmaps.Add(data);
                            tex.InternalFormat = PixelInternalFormat.Alpha4;
                        }
                        else if (bitsize == 1) //8bpp
                        {
                            data = reader.GetSection(texDataOffset, (int)size * bitsize);

                            tex.Mipmaps.Add(data);
                            tex.InternalFormat = PixelInternalFormat.Alpha8;
                        }
                    }
                    else
                    {
                        if (bitsize == 2)
                        {
                            data = reader.GetSection(texDataOffset, (int)size * bitsize);
                            // swap endian
                            for (int j = 0; j < data.Length / 2; j++)
                            {
                                byte temp = data[j * 2];
                                data[j * 2]       = data[(j * 2) + 1];
                                data[(j * 2) + 1] = temp;
                            }
                            tex.Mipmaps.Add(data);
                            tex.InternalFormat = PixelInternalFormat.Rgb5A1;
                        }
                        else if (bitsize == 3)
                        {
                            tex.InternalFormat = PixelInternalFormat.Rgba8;
                            data = reader.GetSection(texDataOffset, (int)size * 4);
                            tex.Mipmaps.Add(data);
                        }
                    }
                }

                // Objects--------------------------------------------------------
                // now parse until end
                bool done = false;
                Stack <GenericBone> boneStack  = new Stack <GenericBone>();
                GenericBone         parentBone = null;

                reader.Seek(objectOffset);
                reader.Skip(4); // idk
                int maybeCount = reader.ReadInt32();

                string          currentMaterialName = "";
                GenericMaterial currentMaterial     = new GenericMaterial();
                GenericBone     CurrentBone         = null;

                while (!done)
                {
                    int doff, temp;
                    //Console.WriteLine(reader.Position().ToString("x") + " " + reader.ReadByte().ToString("x"));
                    reader.ReadByte();
                    reader.Seek(reader.Position - 1);
                    switch (reader.ReadByte())
                    {
                    case 0x03:     // Perhaps some object offset? Offset goes to beginning of file. Material maybe?
                        reader.Skip(0x08 - 1);
                        break;

                    case 0x05:
                        reader.Skip(0x04 - 1);
                        boneStack.Push(CurrentBone);
                        parentBone = boneStack.Peek();
                        break;

                    case 0x06:
                        reader.Skip(0x04 - 1);
                        if (boneStack.Count > 0)
                        {
                            boneStack.Pop();
                            if (boneStack.Count > 0)
                            {
                                parentBone = boneStack.Peek();
                            }
                        }
                        break;

                    case 0x08:
                        reader.Skip(4 - 1);
                        int s1 = reader.ReadByte() & 0x7F;
                        reader.Skip(1);
                        int s2 = reader.ReadInt16();
                        reader.Skip(4);
                        // pops matrix
                        // maybe pop until you get to this bone?
                        //Also maybe some texture thing?
                        Console.WriteLine("What dis?" + " " + s1 + " " + s2);
                        //throw new Exception("Weird Special Thing");

                        /*for (int i = popto - s1; i < popto + s2; i++)
                         * {
                         *  Bone bo = skel.GetBoneByID(i);
                         *  boneStack.Push(bo);
                         * }*/
                        break;

                    case 0x18:     // idk has 4 values
                        reader.Skip(0x08 - 1);
                        break;

                    case 0x1D:
                        int id     = reader.ReadByte();
                        int what   = reader.ReadByte();
                        int parent = (sbyte)reader.ReadByte();

                        // read bone properties
                        Vector3 trans = new Vector3((short)reader.ReadInt16(), (short)reader.ReadInt16(), (short)reader.ReadInt16());
                        Vector3 rot   = new Vector3((short)reader.ReadInt16() / 180, ((short)reader.ReadInt16()) / 180, (short)reader.ReadInt16() / 180);

                        // to radians
                        rot.X = (rot.X * (float)Math.PI) / 180f;
                        rot.Y = (rot.Y * (float)Math.PI) / 180f;
                        rot.Z = (rot.Z * (float)Math.PI) / 180f;

                        //rot = new Vector3(rot.Z, rot.X, rot.Y);

                        Vector3 scale = new Vector3();
                        scale.X = reader.ReadInt16() + reader.ReadInt16() / (float)0xFFFF;
                        scale.Y = reader.ReadInt16() + reader.ReadInt16() / (float)0xFFFF;
                        scale.Z = reader.ReadInt16() + reader.ReadInt16() / (float)0xFFFF;

                        int parent2 = boneStack.Count;

                        GenericBone b = new GenericBone();
                        b.Name = "Bone_" + id;
                        if (parentBone != null)
                        {
                            b.ParentIndex = Model.Skeleton.IndexOf(parentBone);
                        }
                        else
                        {
                            b.ParentIndex = -1;
                        }
                        b.ID       = id;
                        b.Scale    = new Vector3(1, 1, 1);  // scale
                        b.Position = trans;
                        b.Rotation = rot;

                        CurrentBone = b;
                        Model.Skeleton.Bones.Add(b);

                        //Console.WriteLine(reader.Position().ToString("x") + " " + b.Name + " " + b.p1 + " " + what + " " + parent + " " + boneStack.Count + " " + trans.ToString() + " " + rot.ToString() + " " + scale.ToString());
                        //Console.WriteLine(b.transform.ToString());
                        break;

                    case 0x1E:
                        //reader.Skip(3);
                        reader.Skip(1);
                        int w = reader.ReadInt16();     // bone index
                        doff = reader.ReadInt32();
                        temp = (int)reader.Position;

                        reader.Seek((uint)doff);
                        {
                            GenericMesh mesh = DisplayListToGenericMesh(N64Tools.ReadDisplayList(reader, Model.Skeleton.IndexOf(Model.Skeleton.GetBoneByID(w)), Model.Skeleton.GetWorldTransform(Model.Skeleton.GetBoneByID(w))));
                            mesh.MaterialName = currentMaterialName;
                            Model.Meshes.Add(mesh);
                        }
                        reader.Seek((uint)temp);

                        break;

                    case 0x22:
                        int materialIndex = reader.ReadByte();
                        int ww            = (short)reader.ReadInt16();

                        doff = reader.ReadInt32();
                        temp = (int)reader.Position;
                        if (doff == 0)
                        {
                            continue;
                        }

                        reader.Seek((uint)doff);
                        {
                            GenericMesh mesh = DisplayListToGenericMesh(N64Tools.ReadDisplayList(reader, Model.Skeleton.IndexOf(parentBone), Model.Skeleton.GetWorldTransform(parentBone)));
                            mesh.MaterialName = currentMaterialName;
                            Model.Meshes.Add(mesh);
                        }
                        reader.Seek((uint)temp);
                        //((DisplayList)DisplayLists.Nodes[DisplayLists.Nodes.Count - 1]).Mat = unk;
                        //Console.WriteLine("Material Maybe 0x" + reader.pos().ToString("x") + " " + unk + " " + .Count);
                        break;

                    case 0x23:
                        reader.Skip(1);
                        int tidunk = (short)reader.ReadInt16();
                        int texOff = reader.ReadInt32();    //& 0x1FFFF Material Offset?
                        int tid    = (short)reader.ReadInt16();
                        int pid    = (short)reader.ReadInt16();
                        reader.Skip(4);    // 0xFF padding
                        //Console.WriteLine("TextureCount " + tid + " " + pid + " " + tidunk + " " + texOfreader.ToString("x"));
                        if (tid != -1)
                        {
                            currentMaterial     = new GenericMaterial();
                            currentMaterialName = "material_" + Model.MaterialBank.Count;
                            var diffuse = BakeTexturePalette(Textures[tid], pid, Palettes);
                            diffuse.Name = "texture_" + Model.TextureBank.Count;
                            currentMaterial.TextureDiffuse = diffuse.Name;
                            Model.TextureBank.Add(diffuse.Name, diffuse);
                            Model.MaterialBank.Add(currentMaterialName, currentMaterial);
                        }
                        else
                        {
                            var currentTexture = currentMaterial.TextureDiffuse;
                            currentMaterial                = new GenericMaterial();
                            currentMaterialName            = "material_" + Model.MaterialBank.Count;
                            currentMaterial.TextureDiffuse = currentTexture;
                            Model.MaterialBank.Add(currentMaterialName, currentMaterial);
                        }

                        // Read Texture Info At Offset
                        int tt = (int)reader.Position;
                        reader.Seek((uint)texOff);
                        ReadTextureCodes(reader, currentMaterial);
                        reader.Seek((uint)tt);
                        break;                        // Texture Binding

                    case 0x24: reader.Skip(3); break; // has to do with matrix popping

                    case 0x25:
                        reader.Skip(0x04 - 1);
                        //Console.WriteLine("Unknown 0x" + reader.pos().ToString("x"));
                        break;

                    default:
                        done = true;
                        break;
                    }
                    ;
                }
            }


            // Post Process

            // optimized texture sharing
            Dictionary <string, string>         newTexName  = new Dictionary <string, string>();
            Dictionary <string, GenericTexture> newTexBank  = new Dictionary <string, GenericTexture>();
            Dictionary <byte[], string>         TextureBank = new Dictionary <byte[], string>();

            foreach (var tex in Model.TextureBank)
            {
                if (!TextureBank.ContainsKey(tex.Value.Mipmaps[0]))
                {
                    string newName = "texture_" + newTexName.Count;
                    newTexName.Add(tex.Key, newName);
                    newTexBank.Add(newName, tex.Value);
                    TextureBank.Add(tex.Value.Mipmaps[0], newName);
                }
                else
                {
                    newTexName.Add(tex.Key, TextureBank[tex.Value.Mipmaps[0]]);
                }
            }

            Model.TextureBank = newTexBank;

            foreach (var mesh in Model.Meshes)
            {
                var material = Model.GetMaterial(mesh);
                if (material != null && material.TextureDiffuse != null)
                {
                    material.TextureDiffuse = newTexName[material.TextureDiffuse];
                }
            }

            Console.WriteLine(TextureBank.Count + " total textures");

            // Transform Verts

            /*int meshindex = 0;
             * foreach(GenericMesh mesh in Model.Meshes)
             * {
             *  mesh.Name = "Mesh_" + meshindex;
             *  GenericVertex[] CorrectedVertices = mesh.Vertices.ToArray();
             *  for(int i =0; i < CorrectedVertices.Length; i++)
             *  {
             *      CorrectedVertices[i].Pos = Vector3.TransformPosition(CorrectedVertices[i].Pos, Model.Skeleton.GetWorldTransform((int)CorrectedVertices[i].Bones.X));
             *  }
             *  mesh.Vertices.Clear();
             *  mesh.Vertices.AddRange(CorrectedVertices);
             * }*/
        }
Exemple #59
0
 /// <summary>
 /// 上传头像
 /// </summary>
 /// <param name="myFile"></param>
 /// <returns></returns>
 public static string UploadAvatarUser(HttpPostedFileBase myFile)
 {
     if (myFile == null) return "";
     var b = new BinaryReader(myFile.InputStream);
     var  r=new FileItem(myFile.FileName, b.ReadBytes(myFile.ContentLength));
     var req = YunClient.Instance.Execute(new UploadAvatarUserRequest { Image = r }, Member.Token);
     if (!req.IsError)
     {
         return "true";
     }
     return "";
 }
Exemple #60
0
 private void bindComment(FileItem post)
 {
     set("commentUrl", getCommentUrl(post));
 }