示例#1
0
        public static List<VolumeInfo> findBootmgr()
        {
            uint serialNum, serialNumLength, flags;
            StringBuilder volumename = new StringBuilder(256);
            StringBuilder fstype = new StringBuilder(256);
            List<string> volumes = GetVolumes();
            List<string> mountpoints;
            List<VolumeInfo> LstDI = new List<VolumeInfo>();
            foreach (String volume in volumes)
            {
                VolumeInfo di = new VolumeInfo();
                DriveType type = (DriveType)Imports.GetDriveType(volume);
                if (type == DriveType.DRIVE_FIXED)
                {
                    bool ok = Imports.GetVolumeInformation(volume, volumename, (uint)volumename.Capacity - 1,
                        out serialNum, out serialNumLength, out flags, fstype, (uint)fstype.Capacity - 1);
                    mountpoints = GetMountPointsForVolume(volume);
                    di.VolumeGUID = volume;
                    di.VolumePath = volume.Replace("\\\\?\\", "\\\\.\\");
                    di.VolumeName = volumename.ToString();
                    di.FSType = fstype.ToString();
                    di.MountPoints = mountpoints;
                    di.Type = type;
                    if (File.Exists(di.VolumePath + "bootmgr"))
                    {
                        di.bootmgr = true;
                        LstDI.Add(di);
                    }

                }
            }
            return LstDI;
        }
 /// <summary>
 /// Detects if a volume contains any known file systems.
 /// </summary>
 /// <param name="volume">The volume to inspect.</param>
 /// <returns>A list of file systems (may be empty).</returns>
 public DiscUtils.FileSystemInfo[] Detect(VolumeInfo volume)
 {
     using (Stream stream = volume.Open())
     {
         return Detect(stream, volume);
     }
 }
 public static VolumeInfo FromPath(string path)
 {
     if (path == null)
     {
         throw new ArgumentNullException();
     }
     if (OS.IsWin2k)
     {
         WeakReference reference;
         StringBuilder lpszVolumePathName = new StringBuilder(0x400);
         if (!Windows.GetVolumePathName(path, lpszVolumePathName, lpszVolumePathName.Capacity))
         {
             return null;
         }
         string key = lpszVolumePathName.ToString();
         if (VolumeMap.TryGetValue(key, out reference) && reference.IsAlive)
         {
             return (VolumeInfo) reference.Target;
         }
         VolumeInfo target = new VolumeInfo(key);
         reference = new WeakReference(target);
         VolumeMap[key] = reference;
         if (key.Length == 3)
         {
             VolumeMap[target.Name] = reference;
         }
         return target;
     }
     return Get(Path.GetPathRoot(path));
 }
 /// <summary>
 /// Detects if a volume contains any known file systems.
 /// </summary>
 /// <param name="volume">The volume to inspect</param>
 /// <returns>A list of file systems (may be empty)</returns>
 public ThinkAway.FileSystemInfo[] Detect(VolumeInfo volume)
 {
     using (Stream stream = volume.Open())
     {
         return Detect(stream, volume);
     }
 }
示例#5
0
        public override RC.Framework.FileSystem.FileSystemInfo[] Detect(Stream stream, VolumeInfo volume)
        {
            if (HfsPlusFileSystem.Detect(stream))
            {
                return new RC.Framework.FileSystem.FileSystemInfo[] { new VfsFileSystemInfo("HFS+", "Apple HFS+", Open) };
            }

            return new RC.Framework.FileSystem.FileSystemInfo[0];
        }
示例#6
0
        public override DiscUtils.FileSystemInfo[] Detect(Stream stream, VolumeInfo volume)
        {
            if (ExtFileSystem.Detect(stream))
            {
                return new DiscUtils.FileSystemInfo[] { new VfsFileSystemInfo("ext", "Linux ext family filesystem", Open) };
            }

            return new DiscUtils.FileSystemInfo[0];
        }
        public override ThinkAway.FileSystemInfo[] Detect(Stream stream, VolumeInfo volume)
        {
            if (FatFileSystem.Detect(stream))
            {
                return new ThinkAway.FileSystemInfo[] { new VfsFileSystemInfo("FAT", "Microsoft FAT", Open) };
            }

            return new ThinkAway.FileSystemInfo[0];
        }
示例#8
0
        public override DiscUtils.FileSystemInfo[] Detect(Stream stream, VolumeInfo volume)
        {
            if (SquashFileSystemReader.Detect(stream))
            {
                return new DiscUtils.FileSystemInfo[] { new VfsFileSystemInfo("SquashFS", "Squash Filesystem", Open) };
            }

            return new DiscUtils.FileSystemInfo[0];
        }
示例#9
0
        public override RC.Framework.FileSystem.FileSystemInfo[] Detect(Stream stream, VolumeInfo volume)
        {
            if (NtfsFileSystem.Detect(stream))
            {
                return new RC.Framework.FileSystem.FileSystemInfo[] { new VfsFileSystemInfo("NTFS", "Microsoft NTFS", Open) };
            }

            return new RC.Framework.FileSystem.FileSystemInfo[0];
        }
 private DiscFileSystem OpenUdf(Stream stream, VolumeInfo volumeInfo, FileSystemParameters parameters)
 {
     if (volumeInfo != null)
     {
         return new UdfReader(stream, volumeInfo.PhysicalGeometry.BytesPerSector);
     }
     else
     {
         return new UdfReader(stream);
     }
 }
        internal DiscFileSystem GetFileSystem(VolumeInfo volInfo)
        {
            DiscFileSystem result;
            if (!_fsCache.TryGetValue(volInfo.Identity, out result))
            {
                FileSystemManager fsmgr = new FileSystemManager();
                FileSystemInfo[] fsInfo = fsmgr.DetectFileSystems(volInfo);
                if (fsInfo != null && fsInfo.Length > 0)
                {
                    result = fsInfo[0].Open(volInfo);
                    _fsCache.Add(volInfo.Identity, result);
                }
            }

            return result;
        }
        public override ThinkAway.FileSystemInfo[] Detect(Stream stream, VolumeInfo volume)
        {
            List<ThinkAway.FileSystemInfo> detected = new List<ThinkAway.FileSystemInfo>();

            if (UdfReader.Detect(stream))
            {
                detected.Add(new VfsFileSystemInfo("UDF", "OSTA Universal Disk Format (UDF)", OpenUdf));
            }

            if (CDReader.Detect(stream))
            {
                detected.Add(new VfsFileSystemInfo("ISO9660", "ISO 9660 (CD-ROM)", OpenIso));
            }

            return detected.ToArray();
        }
 public static VolumeInfo Get(string driveName)
 {
     WeakReference reference;
     if (driveName == null)
     {
         throw new ArgumentNullException();
     }
     if (VolumeMap.TryGetValue(driveName, out reference) && reference.IsAlive)
     {
         return (VolumeInfo) reference.Target;
     }
     VolumeInfo target = new VolumeInfo(driveName);
     reference = new WeakReference(target);
     VolumeMap[driveName] = reference;
     if (OS.IsWin2k && (driveName.Length == 3))
     {
         VolumeMap[target.Name] = reference;
     }
     return target;
 }
示例#14
0
 private DiscFileSystem Open(Stream stream, VolumeInfo volumeInfo)
 {
     return new FatFileSystem(stream);
 }
 private DiscFileSystem Open(Stream stream, VolumeInfo volumeInfo, FileSystemParameters parameters)
 {
     return new FatFileSystem(stream, Ownership.None, parameters);
 }
示例#16
0
        /// <summary>
        /// 结束前的校验
        /// </summary>
        /// <param name="strError">返回错误信息</param>
        /// <returns>-1: 出错; 0: 没有错误</returns>
        internal override int FinishVerify(out string strError)
        {
            strError = "";
            int nRet = 0;

            // TODO: 将来这里要允许使用整个 location 字符串,而不仅仅是馆代码,来发起条码号校验
            string strLocation    = this.entityEditControl_editing.LocationString;
            string strLibraryCode = Global.GetLibraryCode(StringUtil.GetPureLocation(strLocation));

            string strBarcode = this.entityEditControl_editing.Barcode;

            // 检查册条码号形式是否合法
            if (String.IsNullOrEmpty(strBarcode) == false && // 2009/2/23
                this.EntityControl != null &&
                this.EntityControl.NeedVerifyItemBarcode == true)
            {
                // 形式校验条码号
                // return:
                //      -2  服务器没有配置校验方法,无法校验
                //      -1  error
                //      0   不是合法的条码号
                //      1   是合法的读者证条码号
                //      2   是合法的册条码号
                nRet = this.EntityControl.DoVerifyBarcode(
                    string.IsNullOrEmpty(Program.MainForm.BarcodeValidation) ? strLibraryCode : strLocation,    // 2019/7/12
                    strBarcode,
                    out strError);
                if (nRet == -1)
                {
                    goto ERROR1;
                }

                // 输入的条码格式不合法
                if (nRet == 0)
                {
                    strError = "您输入的条码 " + strBarcode + " 格式不正确(" + strError + ")。请重新输入。";
                    goto ERROR1;
                }

                // 实际输入的是读者证条码号
                if (nRet == 1)
                {
                    strError = "您输入的条码号 " + strBarcode + " 是读者证条码号。请输入册条码号。";
                    goto ERROR1;
                }

                // 对于服务器没有配置校验功能,但是前端发出了校验要求的情况,警告一下
                if (nRet == -2)
                {
                    MessageBox.Show(this, "警告:前端册管理窗开启了校验条码功能,但是服务器端缺乏相应的脚本函数,无法校验条码。\r\n\r\n若要避免出现此警告对话框,请关闭前端册管理窗校验功能");
                }
            }

            // 馆藏地点字符串里面不能有星号
            // string strLocation = this.entityEditControl_editing.LocationString;
            if (strLocation.IndexOf("*") != -1)
            {
                strError = "馆藏地点字符串中不允许出现字符 '*'";
                goto ERROR1;
            }

            // 价格字符串中不允许出现 @
            string strPrice = this.entityEditControl_editing.Price;

            if (strPrice.IndexOf("@") != -1)
            {
                strError = "价格字符串中不允许出现字符 '@'";
                goto ERROR1;
            }

            if (string.IsNullOrEmpty(strPrice) == false)
            {
                CurrencyItem item = null;
                // 解析单个金额字符串。例如 CNY10.00 或 -CNY100.00/7
                nRet = PriceUtil.ParseSinglePrice(strPrice,
                                                  out item,
                                                  out strError);
                if (nRet == -1)
                {
                    strError = "价格字符串格式不合法: " + strError;
                    goto ERROR1;
                }
            }

            string strIssueDbName = "";

            if (string.IsNullOrEmpty(this.BiblioDbName) == false)
            {
                strIssueDbName = Program.MainForm.GetIssueDbName(this.BiblioDbName);
            }

            if (string.IsNullOrEmpty(strIssueDbName) == false)
            {
                // 2014/10/23
                if (string.IsNullOrEmpty(this.entityEditControl_editing.PublishTime) == false)
                {
                    // 检查出版时间范围字符串是否合法
                    // 如果使用单个出版时间来调用本函数,也是可以的
                    // return:
                    //      -1  出错
                    //      0   正确
                    nRet = LibraryServerUtil.CheckPublishTimeRange(this.entityEditControl_editing.PublishTime,
                                                                   out strError);
                    if (nRet == -1)
                    {
                        goto ERROR1;
                    }
                }

                // 2014/10/23
                if (string.IsNullOrEmpty(this.entityEditControl_editing.Volume) == false)
                {
                    List <VolumeInfo> infos = null;
                    nRet = VolumeInfo.BuildVolumeInfos(this.entityEditControl_editing.Volume,
                                                       out infos,
                                                       out strError);
                    if (nRet == -1)
                    {
                        strError = "卷期字符串 '" + this.entityEditControl_editing.Volume + "' 格式错误: " + strError;
                        goto ERROR1;
                    }
                }
            }

            return(0);

ERROR1:
            return(-1);
        }
 /// <summary>
 /// The logic for detecting file systems.
 /// </summary>
 /// <param name="stream">The stream to inspect.</param>
 /// <param name="volumeInfo">Optionally, information about the volume</param>
 /// <returns>A list of file systems detected (may be empty)</returns>
 public abstract ThinkAway.FileSystemInfo[] Detect(Stream stream, VolumeInfo volumeInfo);
示例#18
0
        public byte[] decode(byte[] adpcmIn, out VolumeInfo vi, bool midside, bool enableInloopVolumeStats, bool enableDither, float volume = 1f)
        {
            int  ta, tb;
            uint i, pO;

            byte[] Output = new byte[(adpcmIn.Length - 6) * 4];

            int    sign;         // Current adpcm sign bit
            int    delta;        // Current adpcm output value Mid
            int    step_a;       // Stepsize Mid
            int    step_b;       // Stepsize Side
            double valprev_a;    // virtual previous output value Mid
            double valprev_b;    // virtual previous output value Side
            double vpdiff;       // Current change to valprev Side
            int    index_a;      // Current step change index Mid
            int    index_b;      // Current step change index Side
            int    bitbuffer;    // place to keep next 4-bit value

            uint pa = 0, pb = 0; //peak volume
            uint aa = 0, ab = 0; //average volume

            vi         = new VolumeInfo();
            vi.dbPeakL = double.NegativeInfinity;
            vi.dbPeakR = double.NegativeInfinity;
            vi.dbAvgL  = double.NegativeInfinity;
            vi.dbAvgR  = double.NegativeInfinity;

            if (enableDither)
            {
                r = new Random();
            }

            try
            {
                valprev_a = BitConverter.ToInt16(adpcmIn, 0);
                valprev_b = BitConverter.ToInt16(adpcmIn, 2);
                index_a   = adpcmIn[4];
                index_b   = adpcmIn[5];
                step_a    = stepsizeTable[index_a];
                step_b    = stepsizeTable[index_b];

                for (i = 6; i <= adpcmIn.Length - 1; i++)
                {
                    //.--------------------------------.
                    //|              Ch0               |
                    //'--------------------------------'

                    //**** Step 1 - get the delta value
                    bitbuffer = adpcmIn[i];
                    delta     = bitbuffer >> 4;

                    //**** Step 2 - Find new index value (for later)
                    index_a += indexTable[delta];
                    if (index_a < 0)
                    {
                        index_a = 0;
                    }
                    else if (index_a > 88)
                    {
                        index_a = 88;
                    }

                    //**** Step 3 - Separate sign and magnitude
                    sign  = delta & 8;
                    delta = delta & 7;

                    //**** Step 4 - update output value
                    //vpdiff = (delta * step_a) >> 2;
                    vpdiff = (delta * step_a) / 4d;
                    if (sign == 8)
                    {
                        valprev_a -= vpdiff;
                    }
                    else
                    {
                        valprev_a += vpdiff;
                    }

                    //**** Step 5 - Update step value
                    step_a = stepsizeTable[index_a];

                    //.--------------------------------.
                    //|              Ch1               |
                    //'--------------------------------'

                    //**** Step 1 - get the delta value
                    delta = bitbuffer & 0xF;

                    //**** Step 2 - Find new index value (for later)
                    index_b += indexTable[delta];
                    if (index_b < 0)
                    {
                        index_b = 0;
                    }
                    else if (index_b > 88)
                    {
                        index_b = 88;
                    }

                    //**** Step 3 - Separate sign and magnitude
                    sign  = delta & 8;
                    delta = delta & 7;

                    //**** Step 4 - update output value
                    //vpdiff = (delta * step_b) >> 2;
                    vpdiff = (delta * step_b) / 4d;
                    if (sign == 8)
                    {
                        valprev_b -= vpdiff;
                    }
                    else
                    {
                        valprev_b += vpdiff;
                    }

                    //**** Step 5 - Update step value
                    step_b = stepsizeTable[index_b];

                    //Output the samples with random dither pattern if requested
                    if (enableDither)
                    {
                        bool up = r.Next(0, 2) == 1;
                        if (up)
                        {
                            if (midside)
                            {
                                ta = (int)Math.Ceiling(valprev_a + valprev_b);
                                tb = (int)Math.Ceiling(valprev_a - valprev_b);
                            }
                            else
                            {
                                ta = (int)Math.Ceiling(valprev_a);
                                tb = (int)Math.Ceiling(valprev_b);
                            }
                        }
                        else
                        {
                            if (midside)
                            {
                                ta = (int)Math.Floor(valprev_a + valprev_b);
                                tb = (int)Math.Floor(valprev_a - valprev_b);
                            }
                            else
                            {
                                ta = (int)Math.Floor(valprev_a);
                                tb = (int)Math.Floor(valprev_b);
                            }
                        }
                    }
                    else
                    {
                        if (midside)
                        {
                            ta = (int)Math.Round(valprev_a + valprev_b, 0);
                            tb = (int)Math.Round(valprev_a - valprev_b, 0);
                        }
                        else
                        {
                            ta = (int)Math.Round(valprev_a, 0);
                            tb = (int)Math.Round(valprev_b, 0);
                        }
                    }

                    //Clamp samples
                    if (ta < Int16.MinValue)
                    {
                        ta = Int16.MinValue;
                    }
                    if (ta > Int16.MaxValue)
                    {
                        ta = Int16.MaxValue;
                    }
                    if (tb < Int16.MinValue)
                    {
                        tb = Int16.MinValue;
                    }
                    if (tb > Int16.MaxValue)
                    {
                        tb = Int16.MaxValue;
                    }

                    //If desired, do the audio analyisis
                    //Inloop volume analysis!
                    if (enableInloopVolumeStats)
                    {
                        //Converting to absolute value
                        //Abs and conversion may be slow, so we do this once and write it into variables
                        uint tta = (uint)Math.Abs(ta)
                        , ttb    = (uint)Math.Abs(tb);

                        //determine peak value
                        if (pa < tta)
                        {
                            pa = tta;
                        }
                        if (pb < ttb)
                        {
                            pb = ttb;
                        }

                        //calculating average volume
                        aa = (uint)Math.Round((aa + tta * 2) / 3d);
                        ab = (uint)Math.Round((ab + ttb * 2) / 3d);
                    }

                    //Volume processing (crude but it works!!)
                    if (volume != 1)
                    {
                        ta = (int)Math.Round(ta * volume, 0);
                        tb = (int)Math.Round(tb * volume, 0);
                    }

                    //More clamping
                    if (ta < Int16.MinValue)
                    {
                        ta = Int16.MinValue;
                    }
                    if (ta > Int16.MaxValue)
                    {
                        ta = Int16.MaxValue;
                    }
                    if (tb < Int16.MinValue)
                    {
                        tb = Int16.MinValue;
                    }
                    if (tb > Int16.MaxValue)
                    {
                        tb = Int16.MaxValue;
                    }

                    pO = (i - 6) * 4;
                    BitConverter.GetBytes((short)ta).CopyTo(Output, pO);
                    BitConverter.GetBytes((short)tb).CopyTo(Output, pO + 2);
                }

                //If the volume analysis was done, fill the object provided with the data
                if (enableInloopVolumeStats)
                {
                    vi.dbPeakL = 20 * Math.Log10((double)pa / short.MaxValue);
                    vi.dbPeakR = 20 * Math.Log10((double)pb / short.MaxValue);
                    vi.dbAvgL  = 20 * Math.Log10((double)aa / short.MaxValue);
                    vi.dbAvgR  = 20 * Math.Log10((double)ab / short.MaxValue);
                }
            }
            catch {  }
            r = null;
            return(Output);
        }
示例#19
0
文件: Ntfs.cs 项目: gtrant/eraser
        public override void EraseDirectoryStructures(VolumeInfo info,
                                                      FileSystemEntriesEraseProgress callback)
        {
            //Create a directory to hold all the temporary files
            DirectoryInfo tempDir = new DirectoryInfo(GenerateRandomFileName(
                                                          info.MountPoints[0], 32));

            tempDir.Create();

            try
            {
                //Get the size of the MFT
                long mftSize = NtfsApi.GetMftValidSize(info);
                long mftRecordSegmentSize = NtfsApi.GetMftRecordSegmentSize(info);
                int  pollingInterval      = (int)Math.Min(Math.Max(1, mftSize / info.ClusterSize / 20), 128);
                int  totalFiles           = (int)Math.Max(1L, mftSize / mftRecordSegmentSize);
                int  filesCreated         = 0;

                while (true)
                {
                    ++filesCreated;
                    string fileName = GenerateRandomFileName(tempDir, 220);
                    File.Create(fileName).Close();
                    ResetFileTimes(new FileInfo(fileName));

                    if (filesCreated % pollingInterval == 0)
                    {
                        //Call back to our progress function: this is the first half of the
                        //procedure so divide the effective progress by 2.
                        if (callback != null)
                        {
                            int halfFilesCreated = filesCreated / 2;
                            callback(halfFilesCreated, Math.Max(halfFilesCreated, totalFiles));
                        }

                        //Check if the MFT has grown.
                        if (mftSize < NtfsApi.GetMftValidSize(info))
                        {
                            break;
                        }
                    }
                }
            }
            catch (IOException)
            {
            }
            finally
            {
                //Clear up all the temporary files
                FileInfo[] files = tempDir.GetFiles("*", SearchOption.AllDirectories);
                for (int i = 0; i < files.Length; ++i)
                {
                    if (callback != null && i % 50 == 0)
                    {
                        callback(files.Length + i, files.Length * 2);
                    }
                    files[i].Delete();
                }

                DeleteFolder(tempDir, true);
            }
        }
示例#20
0
        /** @param delay_return [out] (0 < delay_return) w1 is delayed by delay samples
         *                     (delay_return < 0) w2 is delayed by delay samples
         *  @param w1w2VolumeRatio_return [out] >1: w1 volume is larger than w2, <1: w1 volume is smaller than w2
         */
        private bool SampleDelay(WavData w1, WavData w2, out int delay_return, out double w1w2VolumeRatio_return)
        {
            float ACCUMULATE_SECONDS_MAX = (float)numericAccumulateSeconds.Value;
            float DELAY_SECONDS_MAX      = (float)numericStartDelayTorelance.Value;

            delay_return = 0;

            SortedDictionary <long, VolumeInfo> delayValueAndPos =
                new SortedDictionary <long, VolumeInfo>();

            int samplesPerSecond = w1.SampleRate;

            /* assume w1 is delayed (0 < delay) */
            for (int delay = 0; delay < samplesPerSecond * DELAY_SECONDS_MAX; ++delay)
            {
                VolumeInfo vi = new VolumeInfo();
                vi.delay = delay;

                for (int pos = 0; pos < samplesPerSecond * ACCUMULATE_SECONDS_MAX; ++pos)
                {
                    int w1Value = Math.Abs(w1.Sample16Get(0, pos));
                    int w2Value = Math.Abs(w2.Sample16Get(0, pos + delay));
                    vi.w1Volume        += w1Value;
                    vi.w2Volume        += w2Value;
                    vi.accumulatedDiff += Math.Abs(w1Value - w2Value);
                }
                // Console.Write("[{0} {1}]", delay, acc);
                if (!delayValueAndPos.ContainsKey(vi.accumulatedDiff))
                {
                    delayValueAndPos[vi.accumulatedDiff] = vi;
                }
                backgroundWorker1.ReportProgress(delay * 50 / (int)(samplesPerSecond * DELAY_SECONDS_MAX));
            }

            /* assume w2 is delayed (delay < 0) */
            for (int delay = 1; delay < samplesPerSecond * DELAY_SECONDS_MAX; ++delay)
            {
                VolumeInfo vi = new VolumeInfo();
                vi.delay = -delay;

                for (int pos = 0; pos < samplesPerSecond * ACCUMULATE_SECONDS_MAX; ++pos)
                {
                    int w1Value = Math.Abs(w1.Sample16Get(0, pos + delay));
                    int w2Value = Math.Abs(w2.Sample16Get(0, pos));
                    vi.w1Volume        += w1Value;
                    vi.w2Volume        += w2Value;
                    vi.accumulatedDiff += Math.Abs(w1Value - w2Value);
                }
                // Console.Write("[{0} {1}]", -delay, acc);
                if (!delayValueAndPos.ContainsKey(vi.accumulatedDiff))
                {
                    delayValueAndPos[vi.accumulatedDiff] = vi;
                }
                backgroundWorker1.ReportProgress(50 + delay * 50 / (int)(samplesPerSecond * DELAY_SECONDS_MAX));
            }

            SortedDictionary <long, VolumeInfo> .Enumerator e = delayValueAndPos.GetEnumerator();
            e.MoveNext();

            w1w2VolumeRatio_return = (double)e.Current.Value.w1Volume / e.Current.Value.w2Volume;
            delay_return           = e.Current.Value.delay;

            Console.WriteLine();
            Console.WriteLine(rm.GetString("SampleDelaySummary"),
                              delay_return, (double)delay_return / samplesPerSecond,
                              (double)e.Current.Key / (samplesPerSecond * DELAY_SECONDS_MAX),
                              w1w2VolumeRatio_return);
            if (w1w2VolumeRatio_return < 0.5 || 2.0 < w1w2VolumeRatio_return)
            {
                return(false);
            }
            return(true);
        }
示例#21
0
        public override void Execute()
        {
            //Check for sufficient privileges to run the unused space erasure.
            if (!Security.IsAdministrator())
            {
                if (Environment.OSVersion.Platform == PlatformID.Win32NT &&
                    Environment.OSVersion.Version >= new Version(6, 0))
                {
                    Logger.Log(S._("The program does not have the required permissions to erase " +
                                   "the unused space on disk. Run the program as an administrator and retry " +
                                   "the operation."), LogLevel.Error);
                }
                else
                {
                    Logger.Log(S._("The program does not have the required permissions to erase " +
                                   "the unused space on disk."), LogLevel.Error);
                }

                return;
            }

            //Check whether System Restore has any available checkpoints.
            if (SystemRestore.GetInstances().Count != 0)
            {
                Logger.Log(S._("This computer has had System Restore or Volume Shadow Copies " +
                               "enabled. This may allow copies of files stored on the disk to be recovered " +
                               "and pose a security concern.", Drive), LogLevel.Warning);
            }

            //If the user is under disk quotas, log a warning message
            if (VolumeInfo.FromMountPoint(Drive).HasQuota)
            {
                Logger.Log(S._("The drive {0} has disk quotas active. This will prevent the " +
                               "complete erasure of unused space and may pose a security concern.",
                               Drive), LogLevel.Warning);
            }

            //Get the erasure method if the user specified he wants the default.
            IErasureMethod method = EffectiveMethod;

            //Make a folder to dump our temporary files in
            DirectoryInfo info      = new DirectoryInfo(Drive);
            VolumeInfo    volInfo   = VolumeInfo.FromMountPoint(Drive);
            IFileSystem   fsManager = Host.Instance.FileSystems[volInfo];

            //Start sampling the speed of the task.
            Progress = new SteppedProgressManager();

            //Erase the cluster tips of every file on the drive.
            if (EraseClusterTips)
            {
                //Define the callback handlers
                ProgressManager tipSearch = new ProgressManager();
                tipSearch.MarkIndeterminate();
                Progress.Steps.Add(new SteppedProgressManagerStep(tipSearch,
                                                                  0.0f, S._("Searching for files' cluster tips...")));
                ClusterTipsSearchProgress searchProgress = delegate(string path)
                {
                    if (Task.Canceled)
                    {
                        throw new OperationCanceledException(S._("The task was cancelled."));
                    }

                    tipSearch.Tag = path;
                };

                ProgressManager tipProgress = new ProgressManager();
                Progress.Steps.Add(new SteppedProgressManagerStep(tipProgress, 0.1f,
                                                                  S._("Erasing cluster tips...")));
                ClusterTipsEraseProgress eraseProgress =
                    delegate(int currentFile, int totalFiles, string currentFilePath)
                {
                    tipSearch.MarkComplete();
                    tipProgress.Total     = totalFiles;
                    tipProgress.Completed = currentFile;
                    tipProgress.Tag       = currentFilePath;

                    if (Task.Canceled)
                    {
                        throw new OperationCanceledException(S._("The task was cancelled."));
                    }
                };

                //Start counting statistics
                fsManager.EraseClusterTips(VolumeInfo.FromMountPoint(Drive),
                                           method, searchProgress, eraseProgress);
                tipProgress.MarkComplete();
            }

            bool lowDiskSpaceNotifications = Shell.LowDiskSpaceNotificationsEnabled;

            info = info.CreateSubdirectory(Path.GetFileName(
                                               FileSystemBase.GenerateRandomFileName(info, 18)));
            try
            {
                //Set the folder's compression flag off since we want to use as much
                //space as possible
                if (info.IsCompressed())
                {
                    info.Uncompress();
                }

                //Disable the low disk space notifications
                Shell.LowDiskSpaceNotificationsEnabled = false;

                //Fill the disk
                EraseUnusedSpace(volInfo, info, fsManager, method);

                //Erase old resident file system table files
                ProgressManager residentProgress = new ProgressManager();
                Progress.Steps.Add(new SteppedProgressManagerStep(residentProgress,
                                                                  0.05f, S._("Old resident file system table files")));
                fsManager.EraseOldFileSystemResidentFiles(volInfo, info, method,
                                                          delegate(int currentFile, int totalFiles)
                {
                    residentProgress.Completed = currentFile;
                    residentProgress.Total     = totalFiles;

                    if (Task.Canceled)
                    {
                        throw new OperationCanceledException(S._("The task was cancelled."));
                    }
                }
                                                          );

                residentProgress.MarkComplete();
            }
            finally
            {
                //Remove the folder holding all our temporary files.
                ProgressManager tempFiles = new ProgressManager();
                Progress.Steps.Add(new SteppedProgressManagerStep(tempFiles,
                                                                  0.0f, S._("Removing temporary files...")));

                fsManager.DeleteFolder(info, true);
                tempFiles.MarkComplete();

                //Reset the low disk space notifications
                Shell.LowDiskSpaceNotificationsEnabled = lowDiskSpaceNotifications;
            }

            //Then clean the old file system entries
            ProgressManager structureProgress = new ProgressManager();

            Progress.Steps.Add(new SteppedProgressManagerStep(structureProgress,
                                                              0.05f, S._("Erasing unused directory structures...")));
            fsManager.EraseDirectoryStructures(volInfo,
                                               delegate(int currentFile, int totalFiles)
            {
                if (Task.Canceled)
                {
                    throw new OperationCanceledException(S._("The task was cancelled."));
                }

                //Compute the progress
                structureProgress.Total     = totalFiles;
                structureProgress.Completed = currentFile;
            }
                                               );

            structureProgress.MarkComplete();
            Progress = null;
        }
 /// <summary>
 /// The logic for detecting file systems.
 /// </summary>
 /// <param name="stream">The stream to inspect.</param>
 /// <param name="volumeInfo">Optionally, information about the volume</param>
 /// <returns>A list of file systems detected (may be empty)</returns>
 public abstract FileSystemInfo[] Detect(Stream stream, VolumeInfo volumeInfo);
            protected override void OnTouchDown(TouchEventArgs e)
#endif
            {
                int x = 0;
                int y = 0;

#if MF_FRAMEWORK_VERSION_V3_0
                x = e.X;
                y = e.Y;
#else
                e.GetPosition(this, 0, out x, out y);
#endif

                try
                {
                    // Figure out which section of the screen was clicked.
                    if (y <= cy1)
                    {
                        // The button area was clicked.

                        if (x <= cx1)
                        {
                            // The New File button was clicked.

                            if (Directory.GetCurrentDirectory() == "\\")
                            {
                                Debug.Print("Cannot create a file at \\");
                                return;
                            }

                            // Get the next file name, by looping until the file
                            // doesn't exist.
                            int    index = 0;
                            string name  = "File_0.txt";
                            while (File.Exists(name))
                            {
                                name = "File_" + (++index).ToString() + ".txt";
                            }

                            // Create the file using the standard .NET FileStream.
                            FileStream file = new FileStream(name, FileMode.Create);

                            // Write some dummy data to the file.
                            for (int i = 0; i < (index + 5) * 2; i++)
                            {
                                file.WriteByte((byte)i);
                            }

                            // Close the file.
                            file.Close();

                            // Refresh the list and invalidate.
                            myApplication.mainWindow.RefreshList();
                            Invalidate();
                        }
                        else if (x <= cx2)
                        {
                            // The New Directory button was clicked.

                            if (Directory.GetCurrentDirectory() == "\\")
                            {
                                Debug.Print("Cannot create a directory at \\");
                                return;
                            }

                            // Get the next directory name, by looping until the
                            // directory doesn't exist.
                            int    index = 0;
                            string name  = "Directory_0";
                            while (Directory.Exists(name))
                            {
                                name = "Directory_" + (++index).ToString();
                            }

                            // Create the directory.
                            Directory.CreateDirectory(name);

                            // Refresh the list, then re-draw the list.
                            myApplication.mainWindow.RefreshList();
                            Invalidate();
                        }
                        else if (x <= cx3)
                        {
                            // The Move button was clicked.

                            if (Directory.GetCurrentDirectory() == "\\")
                            {
                                Debug.Print("Cannot move to or from \\");
                                return;
                            }

                            // If an item is selected, "move" it.
                            if (_selectedItem != null)
                            {
                                // Get the sub-item that has the name.
                                ListViewSubItem subItem =
                                    (ListViewSubItem)_selectedItem.SubItems[0];
                                if (subItem != null)
                                {
                                    // If the name starts with [ and ends with ]
                                    // then it is a directory.  This is only because
                                    // we put the [ and ] on our directory names.
                                    // There is nothing in the file system that
                                    // requires the [ and ].
                                    if (subItem.Text[0] == '[' &&
                                        subItem.Text[subItem.Text.Length - 1] == ']')
                                    {
                                        // Remove the [ and ] characters.
                                        string name = subItem.Text.Substring(1,
                                                                             subItem.Text.Length - 2);

                                        // Make sure the directory exists.
                                        if (Directory.Exists(name))
                                        {
                                            // Move the directory to the same name +
                                            // .moved.
                                            Directory.Move(name, name + ".moved");

                                            // Update the local name variable.
                                            name += ".moved";

                                            // Update the name text.
                                            ((ListViewSubItem)_selectedItem.SubItems[0]).Text =
                                                '[' + name + ']';

                                            // Get the index in Items of the
                                            // selected list view item.
                                            int index = Items.IndexOf(_selectedItem);

                                            // Remove the item, and then add the
                                            // item back in.
                                            Items.Remove(_selectedItem);
                                            Items.Insert(index, _selectedItem);

                                            // Re-draw the list.
                                            Invalidate();
                                        }
                                    }
                                    else if (File.Exists(subItem.Text))
                                    {
                                        // Without the [ and ] it is a file.

                                        // Move the file to the same name + .moved.
                                        File.Move(subItem.Text, subItem.Text +
                                                  ".moved");

                                        // Update the subitem text.
                                        subItem.Text += ".moved";

                                        // Get the index in Items of the selected
                                        // list view item.
                                        int index = Items.IndexOf(_selectedItem);

                                        // Remove the item, then add the item back
                                        // in.
                                        Items.Remove(_selectedItem);
                                        Items.Insert(index, _selectedItem);

                                        // Re-draw the list.
                                        Invalidate();
                                    }
                                }
                            }
                        }
                        else if (x <= cx4)
                        {
                            // The Delete button was clicked.

                            if (Directory.GetCurrentDirectory() == "\\")
                            {
                                Debug.Print("Cannot delete from \\");
                                return;
                            }

                            // If an item is selected, delete the item.
                            if (_selectedItem != null)
                            {
                                // Get the sub-item that has the name.
                                ListViewSubItem subItem =
                                    (ListViewSubItem)_selectedItem.SubItems[0];
                                if (subItem != null)
                                {
                                    // If the name starts with [ and ends with ],
                                    // then it is a directory.  This is only because
                                    // we put the [ and ] on our directory names.
                                    // There is nothing in the file system that
                                    // requires the [ and ].
                                    if (subItem.Text[0] == '[' &&
                                        subItem.Text[subItem.Text.Length - 1] == ']')
                                    {
                                        // Remove the [ and ].
                                        string name = subItem.Text.Substring(1,
                                                                             subItem.Text.Length - 2);

                                        // Make sure the directory exists.
                                        if (Directory.Exists(name))
                                        {
                                            // Delete the directory.
                                            Directory.Delete(name);

                                            // Remove it from the list view.
                                            Items.Remove(_selectedItem);

                                            // Reset the selected item member.
                                            _selectedItem = null;
                                        }
                                    }
                                    else if (File.Exists(subItem.Text))
                                    {
                                        // Without the [ and ], it is a file.

                                        // Delete the file.
                                        File.Delete(subItem.Text);

                                        // Remove it from the list view.
                                        Items.Remove(_selectedItem);

                                        // Reset the selected item member.
                                        _selectedItem = null;
                                    }

                                    // Re-draw the list view.
                                    Invalidate();
                                }
                            }
                        }
                        else if (x <= cx5)
                        {
                            // The Format button was clicked.

                            // Always go back to the root directory before
                            // formatting.
                            if (_selectedItem != null)
                            {
                                Directory.SetCurrentDirectory("\\");

                                string volume = ((ListViewSubItem)_selectedItem.SubItems[0]).Text;

                                volume = volume.Trim('[', ']', '\\');

                                // Format the volume and call it ROOT.
                                Microsoft.SPOT.IO.VolumeInfo volInfo =
                                    new VolumeInfo(volume);

                                if (volInfo.FileSystem == null)
                                {
#if MF_FRAMEWORK_VERSION_V3_0 || MF_FRAMEWORK_VERSION_V4_0 || MF_FRAMEWORK_VERSION_V4_1
                                    volInfo.Format("FAT", 0, true);
#else
                                    volInfo.Format("FAT", 0, volume + "FS", true);
#endif
                                }
                                else
                                {
                                    volInfo.Format(0);
                                }

                                // Refresh the list, then re-draw the list.
                                myApplication.mainWindow.RefreshList();
                                Invalidate();
                            }
                        }
                    }
                    else if (y <= cy2)
                    {
                        // Column.
                    }
                    else if (y >= cy3)
                    {
                        // The horizontal scrollbar was clicked.
                        OnHorizontalScrollStylusDown(x);
                    }
                    else
                    {
                        if (x >= cx5)
                        {
                            // Vertical Scroll
                            OnVerticalScrollStylusDown(y);
                        }
                        else
                        {
                            // Main section.

                            // Calculate which item was clicked.
                            int itemNumber = ((y - _columnHeaderHeight) + _sy) /
                                             _itemHeight;

                            // If an item was clicked...
                            if (itemNumber >= 0 && itemNumber < Items.Count)
                            {
                                // See if this item is already selected.
                                if (_selectedItem == (ListViewItem)Items[itemNumber])
                                {
                                    // See if this is a directory.
                                    if (_selectedItem.SubItems.Count > 0)
                                    {
                                        string directoryName =
                                            ((ListViewSubItem)_selectedItem.SubItems[0]).Text;
                                        directoryName = directoryName.Substring(1,
                                                                                directoryName.Length - 2);

                                        // Check for special ".." name
                                        if (directoryName == "..")
                                        {
                                            directoryName =
                                                Directory.GetCurrentDirectory();
                                            directoryName =
                                                Path.GetDirectoryName(directoryName);
                                            // directoryName.Substring(0, directoryName.LastIndexOf('\\'));
                                        }

                                        // If the directory exists...
                                        if (Directory.Exists(directoryName))
                                        {
                                            // Set the current directory.
                                            Directory.SetCurrentDirectory(
                                                directoryName);

                                            // Refresh the list.
                                            myApplication.mainWindow.RefreshList();
                                        }
                                    }
                                }
                                else
                                {
                                    // No item is selected, so select this one.
                                    _selectedItem = (ListViewItem)Items[itemNumber];
                                }
                            }
                            else
                            {
                                // No item is selected and we didn't click on one
                                // either.
                                _selectedItem = null;
                            }

                            // Refresh the list view
                            Invalidate();
                        }
                    }
                }
                catch (IOException ex) { Debug.Print(ex.ToString()); }
            }
示例#24
0
        private static string RedirectISO(string filename)
        {
            string _result = null;

            try
            {
                if (!string.IsNullOrEmpty(filename) && File.Exists(filename))
                {
                    List <string> _candidates = new List <string>();

                    // open the ISO file
                    VolumeManager volMgr = new VolumeManager();
                    volMgr.AddDisk(VirtualDisk.OpenDisk(filename, FileAccess.Read));

                    VolumeInfo volInfo = null;
                    volInfo = volMgr.GetLogicalVolumes()[0];

                    DiscUtils.FileSystemInfo fsInfo = FileSystemManager.DetectDefaultFileSystems(volInfo)[0];

                    using (DiscFileSystem _dfs = fsInfo.Open(volInfo))
                    {
                        foreach (string _fname in _dfs.GetFiles("", "*.*", SearchOption.AllDirectories))
                        {
                            string _fileExt = System.IO.Path.GetExtension(_fname).ToLowerInvariant();
                            if (_fileExt == ".ifo" || _fileExt == ".mpls")
                            {
                                _candidates.Add(_fname);
                            }
                        }

                        double _biggestDuration = 0d;
                        string _tmpBRResult     = "";
                        // select from the candidates the one that has the longest duration (if mpls skip files bigger than 10K)
                        foreach (string _cpath in _candidates)
                        {
                            string _cext = Path.GetExtension(_cpath).ToLowerInvariant();
                            string _tmp  = Helpers.GetUniqueFilename(_cext);
                            using (FileStream _fs = new FileStream(_tmp, FileMode.Create, FileAccess.Write))
                            {
                                using (Stream source = _dfs.OpenFile(_cpath, FileMode.Open, FileAccess.Read))
                                {
                                    source.CopyTo(_fs);
                                }
                            }

                            // if it is a DVD iso
                            if (_cext == ".ifo")
                            {
                                if (string.Compare(Path.GetFileNameWithoutExtension(_cpath), "video_ts", true) == 0)
                                {
                                    File.Delete(_tmp);
                                    // skip the menu
                                    continue;
                                }

                                // use first ifo that is not the menu
                                FileManager.AddToGarbageFiles(_tmp);
                                _result = _tmp;
                                break;
                            }

                            // if it is a BLURAY iso (choose biggest mpls file)
                            if (_cext == ".mpls")
                            {
                                long _length = new FileInfo(_tmp).Length;
                                if (Path.GetExtension(_cpath).ToLowerInvariant() == ".mpls" && _length > 10 * 1024)
                                {
                                    File.Delete(_tmp);
                                    continue; // take next one, this is too big and mediainfo will hang
                                }

                                if (GetDurationMilliseconds(_tmp) > _biggestDuration)
                                {
                                    // important.. add it to the garbage files
                                    //FileManager.AddToGarbageFiles(_tmp);
                                    //_result = _tmp;
                                    if (!string.IsNullOrEmpty(_tmpBRResult))
                                    {
                                        File.Delete(_tmpBRResult); // remove previous winner and remember the current one
                                    }
                                    _tmpBRResult = _tmp;
                                }
                                else
                                {
                                    File.Delete(_tmp);
                                }
                            }
                        }
                        if (string.IsNullOrEmpty(_result) && !string.IsNullOrEmpty(_tmpBRResult))
                        {
                            FileManager.AddToGarbageFiles(_tmpBRResult);
                            _result = _tmpBRResult;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Loggy.Logger.DebugException("ISO Processing", ex);
            }

            return(_result);
        }
示例#25
0
        private async Task<Host> GetEc2Instance(string id)
        {
            var instance = await ec2.DescribeInstanceAsync(id).ConfigureAwait(false);

            var host = new Host {
                Type = HostType.VirtualInstance,
                RefId = instance.InstanceId,
                Addresses = new List<IPAddress>() {
                    IPAddress.Parse(instance.IpAddress),
                    IPAddress.Parse(instance.PrivateIpAddress)
                },
                Details = new JsonObject {
                    { "availabilityZone", instance.Placement.AvailabilityZone },
                    { "instanceType", instance.InstanceType },
                    { "hypervisor", instance.Hypervisor },
                    { "vpcId", instance.VpcId }
                },
                Provider = PlatformProviderId.Amazon,
                Status = GetStatus(instance.InstanceState),
                Modified = DateTime.UtcNow,
                Created = instance.LaunchTime
            };

            // "imageId": "ami-1647537c",

            if (instance.ImageId != null)
            {
                // Images may be shared
                var image = (await db.Images.QueryFirstOrDefaultAsync(Eq("refId", instance.ImageId)));

                if (image == null)
                {
                    image = new Image
                    {
                        RefId = instance.ImageId,
                        // Architecture = instance.Architecture,
                        Created = DateTime.UtcNow
                    };

                    await db.Images.InsertAsync(image).ConfigureAwait(false);

                    host.ImageId = image.Id;
                }
            }

            await db.Hosts.InsertAsync(host);

            foreach (var v in instance.BlockDeviceMappings)
            {
                if (v.Ebs != null)
                {
                    var vv = await ec2.DescribeVolumeAsync(v.Ebs.VolumeId).ConfigureAwait(false);

                    var vol = new VolumeInfo {
                        RefId    = v.Ebs.VolumeId,
                        Provider = PlatformProviderId.Amazon,
                        Status   = VolumeStatus.Online,
                        Size     = (long)vv.Size * 1073741824,
                        HostId   = host.Id,
                        Created  = vv.CreateTime
                    };

                    await db.Volumes.InsertAsync(vol).ConfigureAwait(false);
                }
            }

            foreach (var ni in instance.NetworkInterfaces)
            {
                var networkInterface = new NetworkInterfaceInfo {
                    MacAddress = ni.MacAddress,
                    Provider = PlatformProviderId.Amazon,
                    RefId = ni.NetworkInterfaceId,
                    HostId = host.Id,
                    Details = new JsonObject {
                        { "subnetId", ni.SubnetId },
                        { "vpcId", ni.VpcId }
                    },
                    Created = DateTime.UtcNow
                };

                /*
                if (ni.Groups != null)
                {
                    var list = new XList<string>(ni.Groups.Select(ni );

                    foreach (var group in ni.Groups)
                    {
                    }
                }
                */

                // ? IP addresses
                // ? Security groups

                await db.NetworkInterfaces.InsertAsync(networkInterface).ConfigureAwait(false);
            }

            return host;
        }
示例#26
0
 private DiscFileSystem OpenIso(Stream stream, VolumeInfo volumeInfo, FileSystemParameters parameters)
 {
     return(new CDReader(stream, true, true));
 }
示例#27
0
        private void EraseUnusedSpace(VolumeInfo volInfo, DirectoryInfo info, IFileSystem fsInfo,
                                      IErasureMethod method)
        {
            ProgressManager mainProgress = new ProgressManager();

            Progress.Steps.Add(new SteppedProgressManagerStep(mainProgress,
                                                              EraseClusterTips ? 0.8f : 0.9f, S._("Erasing unused space...")));

            //Continue creating files while there is free space.
            while (volInfo.AvailableFreeSpace > 0)
            {
                //Generate a non-existant file name
                string currFile = FileSystemBase.GenerateRandomFileName(info, 18);

                //Create the stream
                FileStream stream = new FileStream(currFile, FileMode.CreateNew,
                                                   FileAccess.Write, FileShare.None, 8, FileOptions.WriteThrough);
                try
                {
                    //Set the length of the file to be the amount of free space left
                    //or the maximum size of one of these dumps.
                    mainProgress.Total = mainProgress.Completed +
                                         method.CalculateEraseDataSize(null, volInfo.AvailableFreeSpace);
                    long streamLength = Math.Min(PassBasedErasureMethod.FreeSpaceFileUnit,
                                                 volInfo.AvailableFreeSpace);

                    //Handle IO exceptions gracefully, because the filesystem
                    //may require more space than demanded by us for file allocation.
                    while (true)
                    {
                        try
                        {
                            stream.SetLength(streamLength);
                            break;
                        }
                        catch (IOException)
                        {
                            if (streamLength > volInfo.ClusterSize)
                            {
                                streamLength -= volInfo.ClusterSize;
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }

                    //Then run the erase task
                    method.Erase(stream, long.MaxValue, Host.Instance.Prngs.ActivePrng,
                                 delegate(long lastWritten, long totalData, int currentPass)
                    {
                        mainProgress.Completed += lastWritten;
                        mainProgress.Tag        = new int[] { currentPass, method.Passes };

                        if (Task.Canceled)
                        {
                            throw new OperationCanceledException(S._("The task was cancelled."));
                        }
                    }
                                 );
                }
                finally
                {
                    stream.Close();
                    fsInfo.ResetFileTimes(new FileInfo(currFile));
                }
            }

            //Mark the main bulk of the progress as complete
            mainProgress.MarkComplete();
        }
    private static void CreateDefaultPostProcessingVolume(GameObject postProcessingWrapper, VolumeInfo volumeInfo)
    {
        var gameObject = new GameObject {
            name = $"PostProcessVolume ({volumeInfo.name})", layer = 8
        };
        // Assign Post Processing

        var postProcessVolume = gameObject.AddComponent <PostProcessVolume>();

        gameObject.transform.parent     = postProcessingWrapper.transform;
        postProcessVolume.isGlobal      = true;
        postProcessVolume.sharedProfile = GetDefaultPostProcessingProfile(volumeInfo.type);
        postProcessVolume.profile       = GetDefaultPostProcessingProfile(volumeInfo.type);
        postProcessVolume.weight        = volumeInfo.weight;
        postProcessVolume.priority      = volumeInfo.priority;

        if (volumeInfo.type != VolumeType.Default)
        {
            return;
        }
        var effectorVolume = gameObject.AddComponent <ConfigEffectorVolume>();

        effectorVolume.postProcessVolume = postProcessVolume;
        var reflectionProbe = Object.FindObjectOfType <ReflectionProbe>();

        if (reflectionProbe != null)
        {
            effectorVolume.rp = reflectionProbe;
        }
    }
示例#29
0
 private DiscFileSystem OpenIso(Stream stream, VolumeInfo volumeInfo)
 {
     return new CDReader(stream, true, true);
 }
示例#30
0
 // Note: A constructor summary is auto-generated by the doc builder.
 /// <summary></summary>
 /// <param name="volumeInfo">The volume information for this storage device.</param>
 public StorageDevice(VolumeInfo volumeInfo)
 {
     Volume        = volumeInfo;
     RootDirectory = Volume.RootDirectory;
 }
示例#31
0
        private DiscFileSystem GetFileSystem(VolumeInfo volInfo, out bool dispose)
        {
            if (DriveInfo != null)
            {
                dispose = false;
                return DriveInfo.GetFileSystem(volInfo);
            }
            else
            {
                // TODO: proper file system detection
                if (volInfo.BiosType == 7)
                {
                    dispose = true;
                    return new NtfsFileSystem(volInfo.Open());
                }
            }

            dispose = false;
            return null;
        }
示例#32
0
文件: Launcher.cs 项目: jcdog/imBMW
        void Init()
        {
            LED = new OutputPort(launcherSettings.LEDPin, false);

            #region Settings

            var sd = GetRootDirectory();

            var settings = Settings.Init(sd != null ? sd + @"\imBMW.ini" : null);

            if (settingsOverride != null)
            {
                settingsOverride(settings);
            }

            var log = settings.Log || settings.LogToSD;
#if DEBUG
            log = true;
            settings.LogMessageToASCII = true;
#else
            // already inited in debug mode
            if (settings.Log)
            {
                Logger.Logged += Logger_Logged;
                Logger.Info("Logger inited");
            }
#endif
            if (settings.LogToSD && sd != null)
            {
                FileLogger.Init(sd + @"\Logs", () =>
                {
                    VolumeInfo.GetVolumes()[0].FlushAll();
                });
            }

            Logger.Info(version);

            Localization.SetCurrent(settings.Language);
            Comfort.AutoLockDoors    = settings.AutoLockDoors;
            Comfort.AutoUnlockDoors  = settings.AutoUnlockDoors;
            Comfort.AutoCloseWindows = settings.AutoCloseWindows;
            Comfort.AutoCloseSunroof = settings.AutoCloseSunroof;
            Logger.Info("Preferences inited");

            SettingsScreen.Instance.Status = version.Length > 11 ? version.Replace(" ", "") : version;

            #endregion

            #region iBus Manager

            // Create serial port to work with Melexis TH3122
            //ISerialPort iBusPort = new SerialPortEcho();
            ISerialPort iBusPort = new SerialPortTH3122(launcherSettings.iBusPort, launcherSettings.iBusBusyPin);
            Logger.Info("TH3122 serial port inited");

            /*InputPort jumper = new InputPort((Cpu.Pin)FEZ_Pin.Digital.An7, false, Port.ResistorMode.PullUp);
             * if (!jumper.Read())
             * {
             *  Logger.Info("Jumper installed. Starting virtual COM port");
             *
             *  // Init hub between iBus port and virtual USB COM port
             *  ISerialPort cdc = new SerialPortCDC(USBClientController.StandardDevices.StartCDC_WithDebugging(), 0, iBus.Message.PacketLengthMax);
             *  iBusPort = new SerialPortHub(iBusPort, cdc);
             *  Logger.Info("Serial port hub started");
             * }*/

            Manager.Init(iBusPort);
            Logger.Info("iBus manager inited");

            #endregion

            #region iBus IO logging

            Message sent1 = null, sent2 = null; // light "buffer" for last 2 messages
            bool    isSent1 = false;
            Manager.BeforeMessageReceived += (e) =>
            {
                LED.Write(Busy(true, 1));
            };
            Manager.AfterMessageReceived += (e) =>
            {
                LED.Write(Busy(false, 1));

                if (!log)
                {
                    return;
                }

                var logIco = "< ";
                if (e.Message.ReceiverDescription == null)
                {
                    if (sent1 != null && sent1.Data.Compare(e.Message.Data))
                    {
                        e.Message.ReceiverDescription = sent1.ReceiverDescription;
                        logIco = "<E";
                    }
                    else if (sent2 != null && sent2.Data.Compare(e.Message.Data))
                    {
                        e.Message.ReceiverDescription = sent2.ReceiverDescription;
                        logIco = "<E";
                    }
                }
                if (settings.LogMessageToASCII && e.Message.ReceiverDescription == null)
                {
                    Logger.Info(e.Message.ToPrettyString(true, true), logIco);
                }
                else
                {
                    Logger.Info(e.Message, logIco);
                }
            };
            Manager.BeforeMessageSent += (e) =>
            {
                LED.Write(Busy(true, 2));
            };
            Manager.AfterMessageSent += (e) =>
            {
                LED.Write(Busy(false, 2));

                if (!log)
                {
                    return;
                }

                Logger.Info(e.Message, " >");
                if (isSent1)
                {
                    sent1 = e.Message;
                }
                else
                {
                    sent2 = e.Message;
                }
                isSent1 = !isSent1;
            };
            Logger.Info("iBus manager events subscribed");

            #endregion

            #region Features

#if DEBUG
            InstrumentClusterElectronics.RequestDateTimeAndSetLocal(false);
#endif

            #endregion

            #region CAN BUS

            if (launcherSettings.CanBus != 0)
            {
                var speed = CanAdapterSettings.CanSpeed.Kbps100;
                CanAdapter.Current = new CanNativeAdapter(launcherSettings.CanBus, speed);
                //var canInterrupt = Cpu.Pin.GPIO_NONE;
                //var canInterrupt = Pin.Di2;
                //CanAdapter.Current = new CanMCP2515Adapter(Pin.SPI, Pin.SPI_ChipSelect, canInterrupt, speed, CanMCP2515AdapterSettings.AdapterFrequency.Mhz8);
                if (log)
                {
                    CanAdapter.Current.MessageReceived += Can_MessageReceived;
                    CanAdapter.Current.MessageSent     += Can_MessageSent;
                    CanAdapter.Current.Error           += Can_ErrorReceived;
                }
                CanAdapter.Current.IsEnabled = true;

                if (launcherSettings.E65Seats)
                {
                    //HardwareButton.Toggle(Pin.Di2, pressed => { if (pressed) E65Seats.EmulatorPaused = true; else E65Seats.EmulatorPaused = false; });
                    E65Seats.Init();
                    E65Seats.AutoHeater             = true;
                    E65Seats.AutoVentilation        = true;
                    HomeScreen.Instance.SeatsScreen = E65SeatsScreen.Instance;
                }

                Logger.Info("CAN BUS inited");
            }

            #endregion

            #region Set iPod or Bluetooth as AUX or CDC-emulator for Bordmonitor or Radio

            BluetoothWT32 wt32;
            if (settings.MediaShield == "WT32")
            {
                wt32   = new BluetoothWT32(launcherSettings.MediaShieldPort, Settings.Instance.BluetoothPin);
                player = wt32;
                InternalCommunications.Register(wt32);

                //byte gain = 0;
                //HardwareButton.OnPress(Pin.Di14, () => wt32.SetMicGain((byte)(++gain % 16)));
            }
            else
            {
                player = new BluetoothOVC3860(launcherSettings.MediaShieldPort, sd != null ? sd + @"\contacts.vcf" : null);
            }

            MediaEmulator emulator;
            if (settings.MenuMode == MenuMode.BordmonitorAUX ||
                settings.MenuMode == MenuMode.BordmonitorCDC ||
                Manager.FindDevice(DeviceAddress.OnBoardMonitor))
            {
                if (player is BluetoothWT32)
                {
                    ((BluetoothWT32)player).NowPlayingTagsSeparatedRows = true;
                }
                if (settings.MenuMode == MenuMode.BordmonitorCDC)
                {
                    emulator = new CDChanger(player, true);
                    if (settings.NaviVersion == NaviVersion.MK2)
                    {
                        Localization.Current = new RadioLocalization();
                        SettingsScreen.Instance.CanChangeLanguage = false;
                    }
                }
                else
                {
                    emulator = new BordmonitorAUX(player);
                }
                Bordmonitor.NaviVersion         = settings.NaviVersion;
                BordmonitorMenu.FastMenuDrawing = settings.NaviVersion == NaviVersion.MK4;
                //MenuScreen.MaxItemsCount = 6;
                BordmonitorMenu.Init(emulator);

                Logger.Info("Bordmonitor menu inited");
            }
            else
            {
                Localization.Current = new RadioLocalization();
                SettingsScreen.Instance.CanChangeLanguage = false;
                MultiFunctionSteeringWheel.EmulatePhone   = true;
                if (settings.MenuMode == MenuMode.MIDAUX)
                {
                    Radio.HasMID = true;
                    emulator     = new MIDAUX(player);
                }
                else
                {
                    Radio.HasMID = Manager.FindDevice(DeviceAddress.MultiInfoDisplay);
                    emulator     = new CDChanger(player);
                }
                var menu = RadioMenu.Init(emulator);
                menu.IsDuplicateOnIKEEnabled    = true;
                menu.TelephoneModeForNavigation = settings.MenuMFLControl;
                Logger.Info("Radio menu inited" + (Radio.HasMID ? " with MID" : ""));
            }

            player.IsShowStatusOnIKEEnabled = true;

            ShieldLED = new OutputPort(launcherSettings.MediaShieldLED, false);
            player.IsPlayingChanged += (p, e) =>
            {
                ShieldLED.Write(e.IsPlaying);
                RefreshLEDs();
            };
            player.StatusChanged += (p, e) =>
            {
                if (e.Event == PlayerEvent.IncomingCall && !p.IsEnabled)
                {
                    InstrumentClusterElectronics.Gong1();
                }
            };
            Logger.Info("Player events subscribed");

            #endregion

            RefreshLEDs();

            LED.Write(true);
            Thread.Sleep(50);
            LED.Write(false);
            Logger.Info("LED blinked - inited");
        }
示例#33
0
        public void RemplirParametreLivre(SqlCommand command, VolumeInfo volumeInfo)
        {
            var codeIsnb10   = "";
            var codeIsnb13   = "";
            var auteur       = "";
            var anneeEdition = "";

            if (volumeInfo.PublishedDate != "")
            {
                anneeEdition = volumeInfo.PublishedDate.Substring(0, 4);
            }
            if (volumeInfo.IndustryIdentifiers != null)
            {
                foreach (var code in volumeInfo.IndustryIdentifiers.ToList())
                {
                    if (code.Type == "ISBN_10")
                    {
                        codeIsnb10 = code.Identifier;
                    }

                    if (code.Type == "ISBN_13")
                    {
                        codeIsnb13 = code.Identifier;
                    }
                }
            }

            if (volumeInfo.Authors != null)
            {
                foreach (var aut in volumeInfo.Authors.ToList())
                {
                    if (auteur != "")
                    {
                        auteur += " ; ";
                    }

                    auteur += aut;
                }
            }

            //Configuration des paramètres
            var paramCodeIsbn10 = new SqlParameter("@CodeIsbn_10", SqlDbType.NVarChar)
            {
                Value = codeIsnb10
            };

            command.Parameters.Add(paramCodeIsbn10);

            var paramCodeIsbn13 = new SqlParameter("@CodeIsbn_13", SqlDbType.NVarChar)
            {
                Value = codeIsnb13
            };

            command.Parameters.Add(paramCodeIsbn13);

            var paramNom = new SqlParameter("@Nom", SqlDbType.NVarChar)
            {
                Value = volumeInfo.Title
            };

            command.Parameters.Add(paramNom);

            var paramSousTitre = new SqlParameter("@SousTitre", SqlDbType.NVarChar)
            {
                Value = volumeInfo.SubTitle ?? ""
            };

            command.Parameters.Add(paramSousTitre);

            var paramImage = new SqlParameter("@Image", SqlDbType.NVarChar)
            {
                Value = volumeInfo.ImageLinks != null?volumeInfo.ImageLinks.SmallThumbnail : ""
            };

            command.Parameters.Add(paramImage);

            var paramImage2 = new SqlParameter("@Image2", SqlDbType.NVarChar)
            {
                Value = volumeInfo.ImageLinks != null ? volumeInfo.ImageLinks.Thumbnail : ""
            };

            command.Parameters.Add(paramImage2);

            var paramAuteur = new SqlParameter("@Auteur", SqlDbType.NVarChar)
            {
                Value = auteur
            };

            command.Parameters.Add(paramAuteur);

            var paramAnneeEdition = new SqlParameter("@AnneeEdition", SqlDbType.Int)
            {
                Value = anneeEdition
            };

            command.Parameters.Add(paramAnneeEdition);

            command.Parameters.Add("@id", SqlDbType.Int).Direction = ParameterDirection.Output;
        }
示例#34
0
        static void Init()
        {
            LED = new OutputPort(FEZPin.PA8, false);

            var sd = GetRootDirectory();

            var settings = Settings.Init(sd != null ? sd + @"\imBMW.ini" : null);
            var log      = settings.Log || settings.LogToSD;

            Localization.SetCurrent(settings.Language);
            Features.Comfort.AutoLockDoors    = settings.AutoLockDoors;
            Features.Comfort.AutoUnlockDoors  = settings.AutoUnlockDoors;
            Features.Comfort.AutoCloseWindows = settings.AutoCloseWindows;
            Features.Comfort.AutoCloseSunroof = settings.AutoCloseSunroof;
            Logger.Info("Preferences inited");

            #if DEBUG
            log = true;
            #else
            // already inited in debug mode
            if (settings.Log)
            {
                Logger.Logged += Logger_Logged;
                Logger.Info("Logger inited");
            }
            #endif

            if (settings.LogToSD && sd != null)
            {
                FileLogger.Init(sd + @"\Logs", () =>
                {
                    VolumeInfo.GetVolumes()[0].FlushAll();
                });
            }

            Logger.Info(version);
            SettingsScreen.Instance.Status = version;

            // Create serial port to work with Melexis TH3122
            ISerialPort iBusPort = new SerialPortTH3122(Serial.COM3, FEZPin.PC2, true);
            Logger.Info("TH3122 serial port inited");

            /*InputPort jumper = new InputPort((Cpu.Pin)FEZ_Pin.Digital.An7, false, Port.ResistorMode.PullUp);
             * if (!jumper.Read())
             * {
             *  Logger.Info("Jumper installed. Starting virtual COM port");
             *
             *  // Init hub between iBus port and virtual USB COM port
             *  ISerialPort cdc = new SerialPortCDC(USBClientController.StandardDevices.StartCDC_WithDebugging(), 0, iBus.Message.PacketLengthMax);
             *  iBusPort = new SerialPortHub(iBusPort, cdc);
             *  Logger.Info("Serial port hub started");
             * }*/

            // Enable iBus Manager
            iBus.Manager.Init(iBusPort);
            Logger.Info("iBus manager inited");

            Message sent1 = null, sent2 = null; // light "buffer" for last 2 messages
            bool    isSent1 = false;
            iBus.Manager.BeforeMessageReceived += (e) =>
            {
                LED.Write(Busy(true, 1));
            };
            iBus.Manager.AfterMessageReceived += (e) =>
            {
                LED.Write(Busy(false, 1));

                if (!log)
                {
                    return;
                }

                // Show only messages which are described
                if (e.Message.Describe() == null)
                {
                    return;
                }
                // Filter CDC emulator messages echoed by iBus
                //if (e.Message.SourceDevice == iBus.DeviceAddress.CDChanger) { return; }
                if (e.Message.SourceDevice != DeviceAddress.Radio &&
                    e.Message.DestinationDevice != DeviceAddress.Radio &&
                    e.Message.SourceDevice != DeviceAddress.GraphicsNavigationDriver &&
                    e.Message.SourceDevice != DeviceAddress.Diagnostic && e.Message.DestinationDevice != DeviceAddress.Diagnostic)
                {
                    //return;
                }
                var logIco = "< ";
                if (e.Message.ReceiverDescription == null)
                {
                    if (sent1 != null && sent1.Data.Compare(e.Message.Data))
                    {
                        e.Message.ReceiverDescription = sent1.ReceiverDescription;
                        logIco = "<E";
                    }
                    else if (sent2 != null && sent2.Data.Compare(e.Message.Data))
                    {
                        e.Message.ReceiverDescription = sent2.ReceiverDescription;
                        logIco = "<E";
                    }
                }
                if (settings.LogMessageToASCII)
                {
                    Logger.Info(e.Message.ToPrettyString(true, true), logIco);
                }
                else
                {
                    Logger.Info(e.Message, logIco);
                }

                /*if (e.Message.ReceiverDescription == null)
                 * {
                 *  Logger.Info(ASCIIEncoding.GetString(e.Message.Data));
                 * }*/
                //Logger.Info(e.Message.PacketDump);
            };
            iBus.Manager.BeforeMessageSent += (e) =>
            {
                LED.Write(Busy(true, 2));
            };
            iBus.Manager.AfterMessageSent += (e) =>
            {
                LED.Write(Busy(false, 2));

                if (!log)
                {
                    return;
                }

                Logger.Info(e.Message, " >");
                if (isSent1)
                {
                    sent1 = e.Message;
                }
                else
                {
                    sent2 = e.Message;
                }
                isSent1 = !isSent1;
            };
            Logger.Info("iBus manager events subscribed");

            // Set iPod or Bluetooth as AUX or CDC-emulator for Bordmonitor or Radio
            player = new BluetoothOVC3860(Serial.COM2, sd != null ? sd + @"\contacts.vcf" : null);
            //player = new iPodViaHeadset(Pin.PC2);

            if (settings.MenuMode != Tools.MenuMode.RadioCDC || Manager.FindDevice(DeviceAddress.OnBoardMonitor))
            {
                MediaEmulator emulator;
                if (settings.MenuMode == Tools.MenuMode.BordmonitorCDC)
                {
                    emulator = new CDChanger(player);
                    if (settings.MenuModeMK2)
                    {
                        Bordmonitor.MK2Mode  = true;
                        Localization.Current = new RadioLocalization();
                        SettingsScreen.Instance.CanChangeLanguage = false;
                    }
                }
                else
                {
                    emulator = new BordmonitorAUX(player);
                }
                //MenuScreen.MaxItemsCount = 6;
                BordmonitorMenu.Init(emulator);
                Logger.Info("Bordmonitor menu inited");
            }
            else
            {
                Localization.Current = new RadioLocalization();
                SettingsScreen.Instance.CanChangeLanguage = false;
                MultiFunctionSteeringWheel.EmulatePhone   = true;
                Radio.HasMID = Manager.FindDevice(DeviceAddress.MultiInfoDisplay);
                var menu = RadioMenu.Init(new CDChanger(player));
                menu.TelephoneModeForNavigation = settings.MenuMFLControl;
                Logger.Info("Radio menu inited" + (Radio.HasMID ? " with MID" : ""));
            }

            ShieldLED = new OutputPort(Pin.Di10, false);
            player.IsPlayingChanged += (p, s) =>
            {
                ShieldLED.Write(s);
                RefreshLEDs();
            };
            player.StatusChanged += (p, s, e) =>
            {
                if (e == PlayerEvent.IncomingCall && !p.IsEnabled)
                {
                    InstrumentClusterElectronics.Gong1();
                }
            };
            Logger.Info("Player events subscribed");

            //SampleFeatures.Init();
            //Logger.Info("Sample features inited");

            /*blinkerTimer = new Timer((s) =>
             * {
             *  if (InstrumentClusterElectronics.CurrentIgnitionState == IgnitionState.Off && !blinkerOn)
             *  {
             *      return;
             *  }
             *  blinkerOn = !blinkerOn;
             *  RefreshLEDs();
             * }, null, 0, 3000);*/

            LED.Write(true);
            Thread.Sleep(50);
            LED.Write(false);
            Logger.Info("LED blinked - inited");
        }
示例#35
0
 private DiscFileSystem Open(Stream stream, VolumeInfo volumeInfo, FileSystemParameters parameters)
 {
     return(new FatFileSystem(stream, Ownership.None, parameters));
 }
示例#36
0
 /// <summary>
 /// The logic for detecting file systems.
 /// </summary>
 /// <param name="stream">The stream to inspect.</param>
 /// <param name="volumeInfo">Optionally, information about the volume</param>
 /// <returns>A list of file systems detected (may be empty)</returns>
 public abstract KDM.FileSystemInfo[] Detect(Stream stream, VolumeInfo volumeInfo);
示例#37
0
 private DiscFileSystem Open(Stream stream, VolumeInfo volumeInfo, FileSystemParameters parameters)
 {
     return(new HfsPlusFileSystem(stream));
 }
示例#38
0
 /// <summary>
 /// Gets the volume information.
 /// </summary>
 /// <param name="VolumeInfo">
 /// Receives the volume information.
 /// </param>
 /// <returns>STATUS_SUCCESS or error code.</returns>
 public virtual Int32 GetVolumeInfo(
     out VolumeInfo VolumeInfo)
 {
     VolumeInfo = default(VolumeInfo);
     return(STATUS_INVALID_DEVICE_REQUEST);
 }
示例#39
0
 public StorageDevice(VolumeInfo volumeInfo)
 {
     this.Volume        = volumeInfo;
     this.RootDirectory = this.Volume.RootDirectory;
 }
 /// <summary>
 /// The logic for detecting file systems.
 /// </summary>
 /// <param name="stream">The stream to inspect.</param>
 /// <param name="volumeInfo">Optionally, information about the volume</param>
 /// <returns>A list of file systems detected (may be empty)</returns>
 public abstract DiscUtils.FileSystemInfo[] Detect(Stream stream, VolumeInfo volumeInfo);
示例#41
0
 /// <summary>
 /// Opens a volume using the file system.
 /// </summary>
 /// <param name="volume">The volume to access</param>
 /// <param name="parameters">Parameters for the file system</param>
 /// <returns>A file system instance</returns>
 public override DiscFileSystem Open(VolumeInfo volume, FileSystemParameters parameters)
 {
     return(_openDelegate(volume.Open(), volume, parameters));
 }
示例#42
0
 /// <summary>
 /// Opens a volume using the file system.
 /// </summary>
 /// <param name="volume">The volume to access</param>
 /// <returns>A file system instance</returns>
 public override DiscFileSystem Open(VolumeInfo volume)
 {
     return _openDelegate(volume.Open(), volume);
 }
示例#43
0
 private DiscFileSystem Open(Stream stream, VolumeInfo volInfo, FileSystemParameters parameters)
 {
     return(new MyFileSystem());
 }
 private DiscFileSystem OpenIso(Stream stream, VolumeInfo volumeInfo, FileSystemParameters parameters)
 {
     return new CDReader(stream, true, true);
 }
示例#45
0
        /*
        // 构造表达一个册所在的当年期号、总期号、卷号的字符串
        public static string BuildItemVolumeString(string strIssue,
            string strZong,
            string strVolume)
        {
            string strResult = "";
            if (String.IsNullOrEmpty(strIssue) == false)
                strResult += "no." + strIssue;

            if (String.IsNullOrEmpty(strZong) == false)
            {
                if (strResult != "")
                    strResult += ", ";
                strResult += "总." + strZong;
            }

            if (String.IsNullOrEmpty(strVolume) == false)
            {
                if (strResult != "")
                    strResult += ", ";
                strResult += "v." + strVolume;
            }

            return strResult;
        }
         * */

        // 解析no.序列
        public static int ExpandNoString(string strText,
            string strDefaultYear,
            out List<VolumeInfo> infos,
            out string strError)
        {
            strError = "";
            infos = new List<VolumeInfo>();

            string strCurrentYear = strDefaultYear;

            string[] no_parts = strText.Split(new char[] { ',', ':', ';', ',',':',';' });    // ':' ';' 是为了兼容某个阶段的临时用法 2001:no.1-2;2002:no.1-12
            for (int i = 0; i < no_parts.Length; i++)
            {
                string strPart = no_parts[i].Trim();
                if (String.IsNullOrEmpty(strPart) == true)
                    continue;
                if (StringUtil.IsNumber(strPart) == true
                    && strPart.Length == 4)
                {
                    strCurrentYear = strPart;
                    continue;
                }

                // 去掉"no."部分
                if (StringUtil.HasHead(strPart, "no.") == true)
                {
                    strPart = strPart.Substring(3).Trim();
                }

                // TODO: 没有"no."开头的,是否警告?

                if (String.IsNullOrEmpty(strPart) == true)
                    continue;

                List<string> nos = null;

                try
                {
                    nos = ExpandSequence(strPart);
                }
                catch (Exception ex)
                {
                    strError = "序列 '" + strPart + "' 格式错误:" + ex.Message;
                    return -1;
                }

                for (int j = 0; j < nos.Count; j++)
                {
                    string strNo = nos[j];

                    if (String.IsNullOrEmpty(strCurrentYear) == true)
                    {
                        strError = "当遇到 '" + strNo + "' 的时候,没有必要的年份信息,无法解析no.序列信息";
                        return -1;
                    }

                    VolumeInfo info = new VolumeInfo();
                    info.IssueNo = strNo;
                    info.Year = strCurrentYear;
                    infos.Add(info);
                }

            }

            return 0;
        }
示例#46
0
 /// <summary>
 /// Initializes a new NTFS file system.
 /// </summary>
 /// <param name="volume">The volume to format.</param>
 /// <param name="label">The label for the new file system.</param>
 /// <returns>The newly-initialized file system.</returns>
 public static NtfsFileSystem Format(
     VolumeInfo volume,
     string label)
 {
     NtfsFormatter formatter = new NtfsFormatter();
     formatter.Label = label;
     formatter.DiskGeometry = volume.BiosGeometry ?? Geometry.Null;
     formatter.FirstSector = volume.PhysicalStartSector;
     formatter.SectorCount = volume.Length / Sizes.Sector;
     return formatter.Format(volume.Open());
 }
示例#47
0
 private DiscFileSystem Open(Stream stream, VolumeInfo volumeInfo, FileSystemParameters parameters)
 {
     return new SquashFileSystemReader(stream);
 }
 private DiscFileSystem Open(Stream stream, VolumeInfo volumeInfo)
 {
     return(new FatFileSystem(stream));
 }
示例#49
0
        /** @param delay_return [out] (0 < delay_return) w1 is delayed by delay samples
         *                     (delay_return < 0) w2 is delayed by delay samples
         *  @param w1w2VolumeRatio_return [out] >1: w1 volume is larger than w2, <1: w1 volume is smaller than w2
         */
        private bool SampleDelay(WavData w1, WavData w2, out int delay_return, out double w1w2VolumeRatio_return)
        {
            float ACCUMULATE_SECONDS_MAX = (float)AccumulateSecondsMax;
            float DELAY_SECONDS_MAX      = (float)DelaySecondsMax;
            delay_return = 0;

            SortedDictionary<long, VolumeInfo> delayValueAndPos =
                new SortedDictionary<long, VolumeInfo>();

            int samplesPerSecond = w1.SampleRate;
            /* assume w1 is delayed (0 < delay) */
            for (int delay=0; delay < samplesPerSecond * DELAY_SECONDS_MAX; ++delay) {
                VolumeInfo vi = new VolumeInfo();
                vi.delay = delay;

                for (int pos=0; pos < samplesPerSecond * ACCUMULATE_SECONDS_MAX; ++pos) {
                    int w1Value = Math.Abs(w1.Sample16Get(0, pos));
                    int w2Value = Math.Abs(w2.Sample16Get(0, pos + delay));
                    vi.w1Volume += w1Value;
                    vi.w2Volume += w2Value;
                    vi.accumulatedDiff += Math.Abs(w1Value - w2Value);
                }
                // Console.Write("[{0} {1}]", delay, acc);
                if (!delayValueAndPos.ContainsKey(vi.accumulatedDiff)) {
                    delayValueAndPos[vi.accumulatedDiff] = vi;
                }
                backgroundWorker1.ReportProgress(delay * 50 / (int)(samplesPerSecond * DELAY_SECONDS_MAX));
            }

            /* assume w2 is delayed (delay < 0) */
            for (int delay=1; delay < samplesPerSecond * DELAY_SECONDS_MAX; ++delay) {
                VolumeInfo vi = new VolumeInfo();
                vi.delay = -delay;

                for (int pos=0; pos < samplesPerSecond * ACCUMULATE_SECONDS_MAX; ++pos) {
                    int w1Value = Math.Abs(w1.Sample16Get(0, pos + delay));
                    int w2Value = Math.Abs(w2.Sample16Get(0, pos));
                    vi.w1Volume += w1Value;
                    vi.w2Volume += w2Value;
                    vi.accumulatedDiff += Math.Abs(w1Value - w2Value);
                }
                // Console.Write("[{0} {1}]", -delay, acc);
                if (!delayValueAndPos.ContainsKey(vi.accumulatedDiff)) {
                    delayValueAndPos[vi.accumulatedDiff] = vi;
                }
                backgroundWorker1.ReportProgress(50 + delay * 50 / (int)(samplesPerSecond * DELAY_SECONDS_MAX));
            }

            SortedDictionary<long, VolumeInfo>.Enumerator e = delayValueAndPos.GetEnumerator();
            e.MoveNext();

            w1w2VolumeRatio_return = (double)e.Current.Value.w1Volume / e.Current.Value.w2Volume;
            delay_return = e.Current.Value.delay;

            Console.WriteLine();
            Console.WriteLine(rm.GetString("SampleDelaySummary"),
                delay_return, (double)delay_return / samplesPerSecond,
                (double)e.Current.Key / (samplesPerSecond * DELAY_SECONDS_MAX),
                w1w2VolumeRatio_return);
            if (w1w2VolumeRatio_return < 0.5 || 2.0 < w1w2VolumeRatio_return) {
                return false;
            }
            return true;
        }
示例#50
0
        public static void Launch(LaunchMode launchMode = LaunchMode.MicroFramework)
        {
            try
            {
                Comfort.Init();
                IntegratedHeatingAndAirConditioning.Init();

                _resetCause = GHI.Processor.Watchdog.LastResetCause;

                blueLed   = new OutputPort(FEZPandaIII.Gpio.Led1, false);
                greenLed  = new OutputPort(FEZPandaIII.Gpio.Led2, false);
                orangeLed = new OutputPort(FEZPandaIII.Gpio.Led3, _resetCause == GHI.Processor.Watchdog.ResetCause.Watchdog);
                redLed    = new OutputPort(FEZPandaIII.Gpio.Led4, false);

#if (NETMF && RELEASE) || (OnBoardMonitorEmulator && !DebugOnRealDeviceOverFTDI)
                _useWatchdog = true;
#endif
                if (_useWatchdog)
                {
                    GHI.Processor.Watchdog.Enable(watchDogTimeoutInMilliseconds);
                }

                settings = Settings.Instance;

                FileLogger.Create();
                InitManagers();

                InstrumentClusterElectronics.DateTimeChanged += DateTimeChanged;

                Logger.Debug("Watchdog.ResetCause: " + (_resetCause == GHI.Processor.Watchdog.ResetCause.Normal ? "Normal" : "Watchdog"));
                if (_useWatchdog)
                {
                    Logger.Debug("Watchdog enabled with timeout: " + watchDogTimeoutInMilliseconds);
                }

                //SettingsScreen.Instance.Status = version.Length > 11 ? version.Replace(" ", "") : version;
                //Localization.SetCurrent(RussianLocalization.SystemName); //Localization.SetCurrent(settings.Language);
                //Comfort.AutoLockDoors = settings.AutoLockDoors;
                //Comfort.AutoUnlockDoors = settings.AutoUnlockDoors;
                //Comfort.AutoCloseWindows = settings.AutoCloseWindows;
                //Comfort.AutoCloseSunroof = settings.AutoCloseSunroof;

                #region MassStorage
                //Controller.DeviceConnectFailed += (sss, eee) =>
                //{
                //    Logger.Error("DeviceConnectFailed!");
                //    LedBlinkingQueueThreadWorker.Enqueue(new LedBlinkingItem(redLed, 1, 100));

                //    ControllerState = UsbMountState.DeviceConnectFailed;
                //    _removableMediaInsertedSync.Set();
                //};
                //Controller.UnknownDeviceConnected += (ss, ee) =>
                //{
                //    Logger.Error("UnknownDeviceConnected!");
                //    LedBlinkingQueueThreadWorker.Enqueue(new LedBlinkingItem(redLed, 2, 100));

                //    ControllerState = UsbMountState.UnknownDeviceConnected;
                //    _removableMediaInsertedSync.Set();
                //};
                //Controller.MassStorageConnected += (sender, massStorage) =>
                //{
                //    Logger.Debug("Controller MassStorageConnected!");
                //    LedBlinkingQueueThreadWorker.Enqueue(new LedBlinkingItem(orangeLed, 2, 100));
                //    ControllerState = UsbMountState.MassStorageConnected;

                RemovableMedia.Insert += (s, e) =>
                {
                    LedBlinkingQueueThreadWorker.Enqueue(new LedBlinkingItem(orangeLed, 3, 100));

                    string rootDirectory = VolumeInfo.GetVolumes()[0].RootDirectory;
                    settings = Settings.Init(rootDirectory + "\\imBMW.ini");
                    FileLogger.Init(rootDirectory + "\\logs", () => VolumeInfo.GetVolumes()[0].FlushAll());
                    Logger.Debug("Logger initialized.");

                    MassStorageMountState = MassStorageMountState.Mounted;
                    _removableMediaInsertedSync.Set();
                };

                RemovableMedia.Eject += (s, e) =>
                {
                    FileLogger.Eject();
                    Logger.Print("RemovableMedia Ejected!");
                    LedBlinkingQueueThreadWorker.Enqueue(new LedBlinkingItem(greenLed, 3, 100));
                    MassStorageMountState = MassStorageMountState.Unmounted;
                };

                //_massStorage = massStorage;
                _massStorage = new SDCard(SDCard.SDInterface.SPI);
                _massStorage.Mount();
                //};
#if RELEASE
                //Controller.Start();
#else
#if NETMF
                // WARNING! Be aware, without this line you can get 'Controller -> DeviceConnectFailed' each time when you start debugging...
                if (Debugger.IsAttached)
#endif
                {
                    //Controller.Start();
                }
#endif
                #endregion

                LedBlinkingQueueThreadWorker.Enqueue(new LedBlinkingItem(orangeLed, 1, 200));
                bool isSignalled = _removableMediaInsertedSync.WaitOne(Debugger.IsAttached ? 10000 : 10000, true);
                if (!isSignalled) // No Storage inserted
                {
                    InstrumentClusterElectronics.ShowNormalTextWithGong(MassStorageMountState.ToStringValue());
                    FrontDisplay.RefreshLEDs(LedType.RedBlinking, append: true);
                    LedBlinkingQueueThreadWorker.Enqueue(new LedBlinkingItem(redLed, 3, 100));
                }
                else
                {
                    if (MassStorageMountState == MassStorageMountState.DeviceConnectFailed || MassStorageMountState == MassStorageMountState.UnknownDeviceConnected)
                    {
                        InstrumentClusterElectronics.ShowNormalTextWithGong(MassStorageMountState.ToStringValue());
                        FrontDisplay.RefreshLEDs(LedType.Red, append: true);
                        LedBlinkingQueueThreadWorker.Enqueue(new LedBlinkingItem(redLed, 4, 100));
                        ResetBoard();
                    }
                }
                Logger.Debug("MassStorage state: " + MassStorageMountState.ToStringValue());

                InstrumentClusterElectronics.RequestDateTime();

                Init();

                Logger.Debug("Started!");

                BordmonitorMenu.MenuButtonHold += () =>
                {
                    FrontDisplay.RefreshLEDs(LedType.Empty);

                    if (Emulator.IsEnabled)
                    {
                        Emulator.PlayerIsPlayingChanged += (s, isPlayingChangedValue) =>
                        {
                            if (!isPlayingChangedValue)
                            {
                                ResetBoard();
                            }
                        };
                        Radio.PressOnOffToggle();
                        //Emulator.IsEnabled = false;
                    }
                    else
                    {
                        ResetBoard();
                    }
                };
                BordmonitorMenu.PhoneButtonHold += () =>
                {
                    VolumioRestApiPlayer.Reboot();
                    Logger.Warning("Reboot request sent.");
                };
                BordmonitorMenu.EjectButtonHold += () =>
                {
                    UnmountMassStorage();
                    _massStorage = null;
                    Logger.Warning("UNMOUNTED!");
                };

                Manager.Instance.AddMessageReceiverForSourceDevice(DeviceAddress.InstrumentClusterElectronics, m =>
                {
                    if (m.Data[0] == 0x11 && m.Data.Length == 2) // Ignition status
                    {
                        GHI.Processor.Watchdog.ResetCounter();
                    }
                });
                requestIgnitionStateTimer = new Timer(RequestIgnitionStateTimerHandler, null, 0, requestIgnitionStateTimerPeriod);

                imBMWTest();

                Logger.Debug("Actions inited!");

                if (launchMode == LaunchMode.MicroFramework)
                {
                    Thread.Sleep(Timeout.Infinite);
                }
            }
            catch (Exception ex)
            {
                LedBlinking(new LedBlinkingItem(redLed, 5, 200));
                Thread.Sleep(200);
                redLed.Write(true);
                Logger.Error(ex, "while modules initialization");
                ResetBoard();
            }
        }
示例#51
0
 private DiscFileSystem Open(Stream stream, VolumeInfo volumeInfo, FileSystemParameters parameters)
 {
     return new NtfsFileSystem(stream);
 }
        private object FindItemByPath(string path, bool preferFs, bool readOnly)
        {
            FileAccess fileAccess = readOnly ? FileAccess.Read : FileAccess.ReadWrite;
            string     diskPath;
            string     relPath;

            int mountSepIdx = path.IndexOf('!');

            if (mountSepIdx < 0)
            {
                diskPath = path;
                relPath  = "";
            }
            else
            {
                diskPath = path.Substring(0, mountSepIdx);
                relPath  = path.Substring(mountSepIdx + 1);
            }

            VirtualDisk disk = Disk;

            if (disk == null)
            {
                OnDemandVirtualDisk odvd = new OnDemandVirtualDisk(Utilities.DenormalizePath(diskPath), fileAccess);
                if (odvd.IsValid)
                {
                    disk = odvd;
                    ShowSlowDiskWarning();
                }
                else
                {
                    return(null);
                }
            }

            List <string> pathElems = new List <string>(relPath.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries));

            if (pathElems.Count == 0)
            {
                return(disk);
            }


            VolumeInfo    volInfo = null;
            VolumeManager volMgr  = DriveInfo != null ? DriveInfo.VolumeManager : new VolumeManager(disk);

            LogicalVolumeInfo[] volumes = volMgr.GetLogicalVolumes();
            string volNumStr            = pathElems[0].StartsWith("Volume", StringComparison.OrdinalIgnoreCase) ? pathElems[0].Substring(6) : null;
            int    volNum;

            if (int.TryParse(volNumStr, out volNum) || volNum < 0 || volNum >= volumes.Length)
            {
                volInfo = volumes[volNum];
            }
            else
            {
                volInfo = volMgr.GetVolume(Utilities.DenormalizePath(pathElems[0]));
            }
            pathElems.RemoveAt(0);
            if (volInfo == null || (pathElems.Count == 0 && !preferFs))
            {
                return(volInfo);
            }


            bool           disposeFs;
            DiscFileSystem fs = GetFileSystem(volInfo, out disposeFs);

            try
            {
                if (fs == null)
                {
                    return(null);
                }

                // Special marker in the path - disambiguates the root folder from the volume
                // containing it.  By this point it's done it's job (we didn't return volInfo),
                // so we just remove it.
                if (pathElems.Count > 0 && pathElems[0] == "$Root")
                {
                    pathElems.RemoveAt(0);
                }

                string fsPath = string.Join(@"\", pathElems.ToArray());
                if (fs.DirectoryExists(fsPath))
                {
                    return(fs.GetDirectoryInfo(fsPath));
                }
                else if (fs.FileExists(fsPath))
                {
                    return(fs.GetFileInfo(fsPath));
                }
            }
            finally
            {
                if (disposeFs && fs != null)
                {
                    fs.Dispose();
                }
            }

            return(null);
        }
示例#53
0
 public abstract void EraseClusterTips(VolumeInfo info, IErasureMethod method,
                                       ClusterTipsSearchProgress searchCallback, ClusterTipsEraseProgress eraseCallback);
 /// <summary>
 /// The logic for detecting file systems.
 /// </summary>
 /// <param name="stream">The stream to inspect.</param>
 /// <param name="volumeInfo">Optionally, information about the volume.</param>
 /// <returns>A list of file systems detected (may be empty).</returns>
 public abstract DiscUtils.FileSystemInfo[] Detect(Stream stream, VolumeInfo volumeInfo);
示例#55
0
 public abstract void EraseDirectoryStructures(VolumeInfo info,
                                               FileSystemEntriesEraseProgress callback);
示例#56
0
        // this method writes some files in the ROOT and WINFS volumes of the standard emulator
        // there will be a "special" directory that will be associated with the main program loop handler
        private static void SetupFiles()
        {
            // Format
            VolumeInfo[] vis = VolumeInfo.GetVolumes();

            if (vis.Length == 0)
            {
                throw new Exception("Cannot run this sample because this emulator does not support a file system");
            }

            for (int i = 0; i < vis.Length; i++)
            {
                if (vis[i].Name.ToLower() == "root")
                {
                    if (!vis[i].IsFormatted)
                    {
                        vis[i].Format(0);
                    }
                    break;
                }
                else if (vis[i].Name.ToLower() == "winfs")
                {
                    if (!vis[i].IsFormatted)
                    {
                        vis[i].Format(0);
                    }
                    break;
                }
            }

            // Create some files in each volume
            // we will prefix files with the volume name to make them recognizable
            Hashtable files = new Hashtable();

            files.Add("SampleReadme.txt", "In this directory you will find the very source of this program.");
            files.Add("SampleCode.cs", "Check http://netmf.codeplex.com for the actual (open) sources!");
            for (int volIdx = 0; volIdx < vis.Length; ++volIdx)
            {
                // all files go into the data directory, duplicated in each volume
                Directory.CreateDirectory(vis[volIdx].Name + @"\" + "data");
                // the same file will also be duplicated inside a special directory in each volume
                Directory.CreateDirectory(vis[volIdx].Name + @"\" + "special");

                foreach (string fileName in files.Keys)
                {
                    //
                    string path = @"\" + vis[volIdx].Name + @"\special\" + vis[volIdx].Name + "_special_" + fileName;
                    using (StreamWriter sw = new StreamWriter(new FileStream(path, FileMode.Create)))
                    {
                        sw.Write((string)files[fileName]);
                    }
                }
                foreach (string fileName in files.Keys)
                {
                    string path = @"\" + vis[volIdx].Name + @"\data\" + vis[volIdx].Name + "_" + fileName;
                    using (StreamWriter sw = new StreamWriter(new FileStream(path, FileMode.Create)))
                    {
                        sw.Write((string)files[fileName]);
                    }
                }
            }
        }
示例#57
0
 /// <summary>
 /// Opens a volume using the file system.
 /// </summary>
 /// <param name="volume">The volume to access.</param>
 /// <param name="parameters">Parameters for the file system.</param>
 /// <returns>A file system instance.</returns>
 public override DiscFileSystem Open(VolumeInfo volume, FileSystemParameters parameters)
 {
     return _openDelegate(volume.Open(), volume, parameters);
 }
示例#58
0
        public static void Main()
        {
            PageCollection finalPageCollection = null;
            var            persistentStorage   = new PersistentStorage("SD");

            persistentStorage.MountFileSystem();

            foreach (var volumeInfo in VolumeInfo.GetVolumes())
            {
                foreach (var filename in Directory.GetFiles(volumeInfo.RootDirectory))
                {
                    var extension = Path.GetExtension(filename);
                    var basename  = Path.GetFileNameWithoutExtension(filename);
                    int address   = Constants.UserStartAddress;

                    switch (basename.ToLower())
                    {
                    case "bootloader":
                        address = Constants.BootloaderStartAddress;
                        break;

                    case "bootlader":
                        address = Constants.BootloaderStartAddress;
                        break;

                    default:
                        address = Constants.UserStartAddress;
                        break;
                    }

                    switch (extension.ToLower())
                    {
                    case ".bit":
                        finalPageCollection = new BitFilePageCollection(
                            new FixedBufferReadStream(
                                new FileStream(
                                    filename,
                                    FileMode.Open
                                    ),
                                256
                                ),
                            address
                            );
                        Debug.Print(((BitFilePageCollection)finalPageCollection).Header.FileName);
                        break;

                    case ".bin":
                        finalPageCollection = new BinFilePageCollection(
                            new FixedBufferReadStream(
                                new FileStream(
                                    filename,
                                    FileMode.Open
                                    ),
                                256
                                ),
                            address
                            );
                        break;
                    }

                    if (finalPageCollection != null)
                    {
                        break;
                    }
                }
                if (finalPageCollection != null)
                {
                    break;
                }
            }

            Uploader.Upload(finalPageCollection);
        }
示例#59
0
 /// <summary>
 /// Initializes a new NTFS file system.
 /// </summary>
 /// <param name="volume">The volume to format.</param>
 /// <param name="label">The label for the new file system.</param>
 /// <param name="options">The formatting options.</param>
 /// <returns>The newly-initialized file system.</returns>
 public static NtfsFileSystem Format(
     VolumeInfo volume,
     string label,
     NtfsFormatOptions options)
 {
     NtfsFormatter formatter = new NtfsFormatter();
     formatter.Label = label;
     formatter.DiskGeometry = volume.BiosGeometry ?? Geometry.Null;
     formatter.FirstSector = volume.PhysicalStartSector;
     formatter.SectorCount = volume.Length / Sizes.Sector;
     formatter.BootCode = options.BootCode;
     formatter.ComputerAccount = options.ComputerAccount;
     return formatter.Format(volume.Open());
 }
示例#60
0
        // ReSharper disable once UnusedMethodReturnValue.Local
        // ReSharper disable once UnusedParameter.Local
        //TODO: check why param extensions is not in use
        private static string CreateDialog(string title, Font titleFont, Font bodyFont, string startDirectory, string[] extentions)
        {
            IContainer prv = Core.ActiveContainer;

            lock (Core.Screen)
            {
                var frmModal = new Form("modalAlertForm", Colors.Ghost);
                _inputResult = string.Empty;

                Core.Screen.SetClippingRectangle(0, 0, frmModal.Width, frmModal.Height);
                Core.Screen.DrawRectangle(0, 0, 4, 4, frmModal.Width - 8, frmModal.Height - 8, 0, 0, Colors.Ghost, 0, 0, Colors.Ghost, 0, 0, 256);
                Core.ShadowRegion(4, 4, frmModal.Width - 8, frmModal.Height - 8);

                Core.Screen.DrawTextInRect(title, 8, 8, frmModal.Width - 16, titleFont.Height, Bitmap.DT_TrimmingCharacterEllipsis, Colors.Charcoal, titleFont);

                var tv1 = new Treeview("tv1", bodyFont, 8, 16 + titleFont.Height, 120, frmModal.Height - 45 - bodyFont.Height - titleFont.Height);

                VolumeInfo[] vi = VolumeInfo.GetVolumes();

                for (int i = 0; i < vi.Length; i++)
                {
                    var viNode = new TreeviewNode(vi[i].RootDirectory)
                    {
                        Tag = vi[i].RootDirectory
                    };

                    if (vi[i].IsFormatted)
                    {
                        if (Directory.GetDirectories(vi[i].RootDirectory).Length > 0)
                        {
                            var ni = new TreeviewNode(string.Empty)
                            {
                                Tag = null
                            };
                            viNode.AddNode(ni);
                        }
                    }

                    tv1.AddNode(viNode);
                }
                tv1.NodeExpanded += tv1_NodeExpanded;
                frmModal.AddChild(tv1);

                var fb1 = new Filebox("fb1", null, bodyFont, 132, tv1.Y, frmModal.Width - 141, tv1.Height);
                frmModal.AddChild(fb1);


                Color cR1       = ColorUtility.ColorFromRGB(226, 92, 79);
                Color cR2       = ColorUtility.ColorFromRGB(202, 48, 53);
                var   btnCancel = new Button("btnCancel", "Cancel", bodyFont, 8, frmModal.Height - 26 - bodyFont.Height, Colors.White, Colors.White, Colors.DarkRed, Colors.DarkRed)
                {
                    NormalColorTop     = cR1,
                    NormalColorBottom  = cR2,
                    PressedColorTop    = cR2,
                    PressedColorBottom = cR1
                };
                btnCancel.Height += 4;
                btnCancel.Tap    += (sender, e) => _activeBlock.Set();

                var btnSelect = new Button("btnSel", (_isSave) ? "Save File" : "Open File", bodyFont, 8, frmModal.Height - 26 - bodyFont.Height)
                {
                    BorderColor        = ColorUtility.ColorFromRGB(13, 86, 124),
                    NormalColorTop     = Colors.LightBlue,
                    NormalColorBottom  = ColorUtility.ColorFromRGB(26, 129, 182),
                    PressedColorBottom = Colors.LightBlue
                };
                btnSelect.PressedColorTop  = btnSelect.NormalColorBottom;
                btnSelect.NormalTextColor  = Colors.White;
                btnSelect.PressedTextColor = Colors.White;
                btnSelect.X       = frmModal.Width - btnSelect.Width - 8;
                btnSelect.Height += 4;
                btnSelect.Enabled = false;
                frmModal.AddChild(btnSelect);

                frmModal.AddChild(btnCancel);

                var txt1 = new Textbox("txt1", string.Empty, bodyFont, Colors.Charcoal, btnCancel.X + btnCancel.Width + 4, btnCancel.Y, frmModal.Width - 28 - btnCancel.Width - btnSelect.Width, btnSelect.Height, ' ', !_isSave);
                frmModal.AddChild(txt1);

                Core.SilentlyActivate(frmModal);
                frmModal.Render(new rect(4, 12 + titleFont.Height, frmModal.Width - 8, frmModal.Height - 20 - titleFont.Height));
                Core.Screen.Flush();

                tv1.NodeTapped           += (node, e) => tv1_NodeTapped(node, fb1);
                fb1.PathChanged          += (sender, value) => SetTvPath(value, tv1, fb1);
                fb1.SelectedIndexChanged += (sender, value) => FbIndexChange(fb1, txt1);
                txt1.TextChanged         += (sender, value) => btnSelect.Enabled = txt1.Text != string.Empty;
                SetTvPath(startDirectory, tv1, fb1);
                btnSelect.Tap += (sender, e) => ReturnSelection(tv1, txt1);
            }

            ModalBlock();

            Core.ActiveContainer = prv;

            return(_inputResult);
        }