public bool EncrFilter(FSEntry entry) { string fileName = entry.RelativePath; if (string.Equals(fileName, HelixConsts.HeaderFileName)) { return(false); } if (string.Equals(fileName, HelixConsts.SyncLogDirectory)) { return(false); } if (fileName.StartsWith(HelixConsts.SyncLogDirectory + Path.DirectorySeparatorChar, StringComparison.Ordinal)) { return(false); } if (Path.GetExtension(fileName) == HelixConsts.StagedHxExtention) { return(false); } if (Path.GetExtension(fileName) == HelixConsts.BackupExtention) { return(false); } if (entry.EntryType != FileEntryType.File) { return(false); } return(true); }
public FSEntry Find(string path) { // good: /foo/bar, /foo/bar/ // bad: foo, foo/bar, //foo/bar, /foo//bar, /foo/../foo/bar VirtualNode current = virtualFileSystem.RootNode; string[] elements = path.Split(PATH_SEPARATOR); foreach (string element in elements.Skip(1)) { VirtualNode child = current.GetChild(element); if (child != null) { current = child; } else { return(null); } } FSEntry result = null; if (current.IsDirectory) { result = new SimpleDirectory(current); } else { result = new SimpleFile(current); } return(result); }
private List <FSEntry> RecompressDir(string dir) { string[] files = Directory.GetFiles(dir); List <FSEntry> entries = new List <FSEntry>(files.Length); byte[] compBuffer = new byte[8192]; foreach (string f in files) { FSEntry fe = new FSEntry(); fe.tocEntry = new TocEntry(); fe.tocEntry.dateTime = GetFileCreationTimeInSeconds(f); fe.tocEntry.flags = TOCFlags_File; fe.tocEntry.offsetIndex = 0; fe.tocEntry.name = new byte[25]; fe.diskFile = f; using (FileStream fs = new FileStream(f, FileMode.Open, FileAccess.Read)) { MemoryStream ms = new MemoryStream((int)fs.Length); GZipOutputStream gzOut = new GZipOutputStream(ms); gzOut.SetLevel(2); StreamUtils.Copy(fs, gzOut, compBuffer); byte[] compData = ms.GetBuffer(); Array.Resize(ref compData, (int)ms.Position); fe.compressedFile = compData; } string gzName = Path.GetFileName(f) + ".gz"; fe.name = gzName; entries.Add(fe); } return(entries); }
public List <FSEntry> ScanAndCompress(string flatDir, bool recomp) { List <FixupPair> dirOffsetsToFixup = new List <FixupPair>(); List <FSEntry> entries = ScanAndCompressDir(flatDir, dirOffsetsToFixup, recomp); if (entries.Count != 0) { // there is no .. entry at the start of the list entries.RemoveAt(0); } int runningIndex = 0; foreach (FixupPair pair in dirOffsetsToFixup) { bool isDotDotKey = pair.Key.name == ".."; int startIndex = isDotDotKey ? 0 : runningIndex; int i = startIndex; for (; i < entries.Count; ++i) { FSEntry listEntry = entries[i]; if (Object.ReferenceEquals(listEntry, pair.Value)) { pair.Key.tocEntry.offsetIndex = (short)i; break; } } if (!isDotDotKey) { runningIndex = i + 1; } } return(entries); }
public SyncLogEntry CreateNewLogEntryFromDecrPath(string decrFileName) { FSEntry decrEntry = DecrDirectory.TryGetEntry(decrFileName); string encrFileName = FileNameEncoder.EncodeName(decrFileName); FSEntry encrEntry = EncrDirectory.TryGetEntry(encrFileName); return(new SyncLogEntry(decrEntry.EntryType, decrEntry.RelativePath, decrEntry.LastWriteTimeUtc, encrEntry.RelativePath, encrEntry.LastWriteTimeUtc)); }
static void ValidateBadPath(FileSystem fs, string path) { FSEntry fse = fs.Find(path); if (fse != null) { throw new Exception("Path: " + path + " invalid!"); } }
static void ValidatePath(FileSystem fs, string path) { FSEntry fse = fs.Find(path); if (fse == null || fse.FullPathName != path && (fse.FullPathName + "/") != path) { throw new Exception("Path: " + path + " invalid! Should have been valid.."); } }
private void LoadPasswordFile() { // Read all users from the password file // open if it exists Directory root = filesystem.GetRootDirectory(); FSEntry entry = filesystem.Find("/" + passwordFileName); if (entry != null) { // Read contents File pwfile = entry as File; FileStream stream = pwfile.Open(); byte[] bytes = stream.Read(0, pwfile.Length); stream.Close(); // convert to string string data = ASCIIEncoding.ASCII.GetString(bytes); // parse based on format below // userID;username;password;homedir;shell string[] rows = data.Split('\n'); foreach (string row in rows) { if (row.Length > 0) { string[] fields = row.Split(';'); if (fields.Length == 5) { User user = new User(); user.userID = Convert.ToInt32(fields[0]); user.userName = fields[1]; user.password = fields[2]; user.homeDirectory = fields[3]; user.shell = fields[4]; usersById[user.userID] = user; // Update UserID if (user.userID >= nextUserID) { nextUserID = user.userID + 1; } } else { throw new Exception("found malformed row in password file: " + row); } } } } }
public bool DecrFilter(FSEntry entry) { string fileName = entry.RelativePath; if (string.Equals(fileName, HelixConsts.SyncLogDirectory)) { return(false); } if (fileName.StartsWith(HelixConsts.SyncLogDirectory + HelixUtil.UniversalDirectorySeparatorChar, StringComparison.Ordinal)) { return(false); } return(true); }
public SyncLogEntry CreateEntryFromHeader(FileEntry decrFileInfo, FSEntry encrFileInfo) { if (decrFileInfo == null) { throw new ArgumentNullException(nameof(decrFileInfo)); } if (encrFileInfo == null) { throw new ArgumentNullException(nameof(encrFileInfo)); } SyncLogEntry entry = new SyncLogEntry(decrFileInfo.EntryType, decrFileInfo.FileName, decrFileInfo.LastWriteTimeUtc, encrFileInfo.RelativePath, encrFileInfo.LastWriteTimeUtc); return(entry); }
public SyncLogEntry CreateNewLogEntryFromEncrPath(string encrFileName) { string encrFilePath = Path.Combine(EncrDirectory.FullName, encrFileName); FSEntry encrEntry = EncrDirectory.TryGetEntry(encrFileName); FileEntry header = HelixFile.DecryptHeader(encrFilePath, DerivedBytesProvider); var decrFileName = header.FileName; if (encrFileName != FileNameEncoder.EncodeName(decrFileName)) { throw new HelixException("Encrypted file name does not match"); //todo: prompt for action } return(new SyncLogEntry(header.EntryType, header.FileName, header.LastWriteTimeUtc, encrEntry.RelativePath, encrEntry.LastWriteTimeUtc)); }
public int AddUser(string username) { if (usersById.Count(u => u.Value.userName == username) != 0) { throw new Exception("User: "******" already exists!"); } // create a new user with default home directory and shell // initially empty password User user = new User(); user.userID = nextUserID++; user.userName = username; user.password = null; user.shell = "pshell"; user.homeDirectory = "/home/" + username; usersById[user.userID] = user; // create user's home directory if needed if (filesystem != null) { Directory root = filesystem.GetRootDirectory(); FSEntry entry = filesystem.Find(user.homeDirectory); if (entry == null) { Directory home; entry = filesystem.Find("/home"); if (entry == null) { home = root.CreateDirectory("home"); } else { home = entry as Directory; } home.CreateDirectory(user.userName); } } // save the user to the password file SavePasswordFile(); // return user id return(user.userID); }
static void TestfileSystem() { try { Random r = new Random(); SlowDisk disk = new SlowDisk(1); disk.TurnOn(); FileSystem fs = new SimpleFS(); fs.Format(disk); fs.Mount(disk, "/"); Directory root = fs.GetRootDirectory(); root.CreateDirectory("Testing123"); Directory dir = root.CreateDirectory("nested"); File file = dir.CreateFile("nestedfile"); FileStream filestream = file.Open(); filestream.Write(0, CreateTestBytes(r, 142)); filestream.Close(); root.CreateFile("rootfile"); fs.Find("/rootfile"); FSEntry f = fs.Find("/nested/nestedfile"); string fullname = f.FullPathName; RescursivelyPrintDirectories(root); fs.Unmount("/"); disk.TurnOff(); } catch (Exception ex) { Console.WriteLine("Test File System failed. Ex: " + ex.Message); } }
private void SavePasswordFile() { // Save all users to the password file // format the data as such // userID;username;password;homedir;shell string data = ""; foreach (User u in usersById.Values) { data += u.userID.ToString() + ";"; data += u.userName + ";"; data += u.password + ";"; data += u.homeDirectory + ";"; data += u.shell + "\n"; } // Write to file Directory root = filesystem.GetRootDirectory(); File pwfile; FSEntry entry = filesystem.Find("/" + passwordFileName); if (entry == null) { pwfile = root.CreateFile(passwordFileName); } else { pwfile = entry as File; } FileStream stream = pwfile.Open(); stream.Write(0, ASCIIEncoding.ASCII.GetBytes(data)); stream.Close(); }
public void Navigate(string path) { if (Directory.Exists(path)) { _currentDirectory = path; CurrentPath = path; _entries.Clear(); foreach (var file in Directory.GetFileSystemEntries(path)) { FSEntry fsEntry = new FSEntry(file); if (fsEntry.Attributes.HasFlag(FileAttributes.Hidden) == false && fsEntry.Attributes.HasFlag(FileAttributes.System) == false && fsEntry.IsDirectory) { _entries.Add(fsEntry); } } RefreshList(); } }
/** FAST */ public double Measure(FSEntry d) { return Math.Max(1.0, d.SubTreeSize); }
/** UNIMPORTANT */ public double Measure(FSEntry d) { return 1.0; }
/** FAST */ public double Measure(FSEntry d) { bool isDotFile = d.Name[0] == '.'; if (isDotFile) return 0.05; return (d.IsDirectory ? 10.0 : 1.0); }
void ToggleSpan(FSEntry start, FSEntry end) { if (start.ParentDir == end.ParentDir) { FSEntry[] entries = end.ParentDir.Entries.ToArray (); int startIdx = Array.IndexOf(entries, start); int endIdx = Array.IndexOf(entries, end); if (startIdx > -1 && endIdx > -1) { int i = Math.Min (startIdx, endIdx); int j = Math.Max (startIdx, endIdx); for (;i<=j;i++) { if (i != startIdx) ToggleSelection(entries[i].FullName); } } NeedRedraw = true; } }
public List <FSEntry> ScanAndCompressDir(string dir, List <FixupPair> dirOffsetsToFixup, bool recomp) { string[] entries = Directory.GetFileSystemEntries(dir); string lowerDecompDir = VolFile.DecompDir.ToLower(); List <FSEntry> curDirEntries = new List <FSEntry>(); List <FSEntry> subDirEntries = new List <FSEntry>(); FSEntry startOfDirEntry = new FSEntry(); startOfDirEntry.tocEntry = new TocEntry(); startOfDirEntry.tocEntry.dateTime = (int)(DateTime.Now - dtEpoch).TotalSeconds; startOfDirEntry.tocEntry.flags = TOCFlags_Directory; startOfDirEntry.tocEntry.offsetIndex = 0; startOfDirEntry.compressedFile = null; startOfDirEntry.name = ".."; startOfDirEntry.size = 0; curDirEntries.Add(startOfDirEntry); foreach (string e in entries) { string justFileName = Path.GetFileName(e); string lowerFileName = justFileName.ToLower(); FSEntry fe = new FSEntry(); fe.name = justFileName; fe.tocEntry = new TocEntry(); fe.tocEntry.flags = TOCFlags_File; fe.tocEntry.offsetIndex = 0; fe.tocEntry.name = new byte[25]; if (!Directory.Exists(e)) { Debug.Assert(File.Exists(e)); fe.size = 0; fe.diskFile = e; fe.tocEntry.dateTime = GetFileCreationTimeInSeconds(e); } else if (lowerFileName != lowerDecompDir) { fe.tocEntry.dateTime = GetDirectoryCreationTimeInSeconds(e); fe.tocEntry.flags = TOCFlags_Directory; fe.diskFile = null; FixupPair dirFixup = new FixupPair(fe, null); dirOffsetsToFixup.Add(dirFixup); List <FSEntry> childContents = ScanAndCompressDir(e, dirOffsetsToFixup, recomp); dirFixup.Value = childContents[0]; dirOffsetsToFixup.Add(new FixupPair(childContents[0], curDirEntries[0])); subDirEntries.AddRange(childContents); } else { continue; // we don't want an entry for the decomp dir } curDirEntries.Add(fe); } curDirEntries.Sort(); string decompDir = Path.Combine(dir, VolFile.DecompDir); if (recomp && Directory.Exists(decompDir)) { bool added = false; List <FSEntry> recompressedEntries = RecompressDir(decompDir); foreach (FSEntry r in recompressedEntries) { int where = curDirEntries.BinarySearch(r); if (where > 0) { curDirEntries[where] = r; } else { added = true; curDirEntries.Add(r); } } if (added) { curDirEntries.Sort(); } } // last file in the dir has this set // there aren't any empty directories in the real vol, so I don't know what will // happen if you include one. Setting the LastEntry flag on the .. entry might // make it work, or it might break it, I've no idea. But I've attempted to support // it anyway curDirEntries[curDirEntries.Count - 1].tocEntry.flags |= TOCFlags_LastEntry; curDirEntries.AddRange(subDirEntries); return(curDirEntries); }
/** BLOCKING - startup dir latency */ public Filezoo(string dirname) { Selection = new Dictionary<string, bool> (); Renderer = new FSDraw (); clipboard = Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", true)); SortField = SortFields[0]; SizeField = SizeFields[0]; Zoomer = new FlatZoomer (); Gdk.Colormap cm = Screen.RgbaColormap; if (cm != null && Screen.IsComposited) { Widget.DefaultColormap = cm; Colormap = cm; UseRgbaVisuals = true; } SetCurrentDir (dirname); Helpers.StartupProfiler.Time ("SetCurrentDir"); CanFocus = true; KeyPressEvent += delegate (object o, KeyPressEventArgs args) { Cancelled = true; Gdk.ModifierType state = args.Event.State; switch (args.Event.Key) { case Gdk.Key.Control_L: case Gdk.Key.Control_R: state |= Gdk.ModifierType.ControlMask; break; case Gdk.Key.Shift_L: case Gdk.Key.Shift_R: state |= Gdk.ModifierType.ShiftMask; break; case Gdk.Key.Alt_L: case Gdk.Key.Alt_R: state |= Gdk.ModifierType.Mod1Mask; break; } SetCursor (state); }; KeyReleaseEvent += delegate (object o, KeyReleaseEventArgs args) { Cancelled = true; if (args.Event.Key == Gdk.Key.Escape && Selection.Count > 0) { ClearSelection (); args.RetVal = true; } else if ((args.Event.State & Gdk.ModifierType.ControlMask) == Gdk.ModifierType.ControlMask) { switch (args.Event.Key) { case Gdk.Key.x: CutSelection(CurrentDirPath); break; case Gdk.Key.c: CopySelection(CurrentDirPath); break; case Gdk.Key.v: PasteSelection(CurrentDirPath); break; } } else { switch (args.Event.Key) { case Gdk.Key.Delete: TrashSelection (); break; case Gdk.Key.BackSpace: GoToParent (); break; case Gdk.Key.Home: SetCurrentDir (Helpers.HomeDir); break; } } Gdk.ModifierType state = args.Event.State; switch (args.Event.Key) { case Gdk.Key.Control_L: case Gdk.Key.Control_R: state &= ~Gdk.ModifierType.ControlMask; break; case Gdk.Key.Shift_L: case Gdk.Key.Shift_R: state &= ~Gdk.ModifierType.ShiftMask; break; case Gdk.Key.Alt_L: case Gdk.Key.Alt_R: state &= ~Gdk.ModifierType.Mod1Mask; break; } SetCursor (state); }; DragDataGet += delegate (object o, DragDataGetArgs args) { string items = "file://" + DragSourcePath; if (Selection.Count > 0 && Selection.ContainsKey(DragSourcePath)) items = GetSelectionData (); args.SelectionData.Set(args.SelectionData.Target, 8, System.Text.Encoding.UTF8.GetBytes(items)); args.SelectionData.Text = items; }; DragEnd += delegate { GetSelectionData (); Cancelled = true; dragInProgress = false; DragSourceEntry = null; DragSourcePath = null; }; /** DESCTRUCTIVE */ DragDataReceived += delegate (object sender, DragDataReceivedArgs e) { Cancelled = true; string targetPath = FindHit (Width, Height, e.X, e.Y, 8).Target.FullName; HandleSelectionData (e.SelectionData, e.Context.SuggestedAction, targetPath); }; Gtk.Drag.DestSet (this, DestDefaults.All, target_table, Gdk.DragAction.Move | Gdk.DragAction.Copy | Gdk.DragAction.Ask ); AddEvents((int)( Gdk.EventMask.ButtonPressMask | Gdk.EventMask.ButtonReleaseMask | Gdk.EventMask.ScrollMask | Gdk.EventMask.PointerMotionMask | Gdk.EventMask.EnterNotifyMask | Gdk.EventMask.KeyPressMask | Gdk.EventMask.KeyReleaseMask | Gdk.EventMask.LeaveNotifyMask )); ThreadStart ts = new ThreadStart (PreDrawCallback); Thread t = new Thread(ts); t.IsBackground = true; t.Start (); System.Timers.Timer t1 = new System.Timers.Timer(50); t1.Elapsed += new ElapsedEventHandler (CheckUpdates); System.Timers.Timer t2 = new System.Timers.Timer(1000); t2.Elapsed += new ElapsedEventHandler (LongMonitor); t1.Enabled = true; t2.Enabled = true; GLib.Timeout.Add (10, new GLib.TimeoutHandler(CheckRedraw)); Helpers.StartupProfiler.Total ("Pre-drawing startup"); }
public void Run(Terminal terminal) { // NOTE: takes over the current thread, returns only when shell exits // expects terminal to already be connected terminal.Echo = true; while (true) { //print command prompt terminal.Write($"{pwd.Name}> "); //get command line string cmdline = terminal.ReadLine(); if (cmdline.Length == 0) { continue; } // identify command string[] parts = cmdline.Split(' '); if (parts != null && parts.Length > 0) { string cmd = parts[0]; if (cmd == "exit") { terminal.WriteLine("Bye!"); break; } else if (cmd == "pwd") { terminal.WriteLine(pwd.FullPathName); } else if (cmd == "ls") { foreach (FSEntry entry in pwd.GetSubDirectories()) { terminal.WriteLine(entry.Name); } foreach (FSEntry entry in pwd.GetFiles()) { terminal.WriteLine(entry.Name); } } else if (cmd == "cd") { if (parts.Length == 2) { string dest = parts[1]; if (!dest.StartsWith("/")) { dest = pwd.FullPathName + "/" + dest; } FSEntry found = session.FileSystem.Find(dest); if (found != null) { if (found.IsDirectory) { pwd = (Directory)found; } else { terminal.WriteLine("Error: " + dest + " is not a directory!"); } } } else { terminal.WriteLine("Usage: cd <name>"); } } else if (cmd == "mkdir") { if (parts.Length == 2) { //validate commandline args... //make dir pwd.CreateDirectory(parts[1]); } } else { terminal.WriteLine("Command not found!"); } } //run command } }
public void SetCurrentDir(string dirname, bool resetZoom) { Profiler p = new Profiler (); dirLatencyProfiler.Restart (); FirstFrameOfDir = true; if (dirname != Helpers.RootDir) dirname = dirname.TrimEnd(Helpers.DirSepC); UnixDirectoryInfo d = new UnixDirectoryInfo (dirname); string odp = CurrentDirPath; CurrentDirPath = d.FullName; if (odp != CurrentDirPath) { if (CurrentDirEntry != null && CurrentDirEntry.InProgress) FSCache.CancelTraversal (); CurrentDirEntry = FSCache.FastGet (CurrentDirPath); FSCache.Watch (CurrentDirPath); } FSNeedRedraw = true; if (resetZoom) ResetZoom (); UpdateLayout (); p.Time("SetCurrentDir"); }
/** FAST */ protected override bool OnButtonPressEvent(Gdk.EventButton e) { Profiler p = new Profiler ("OnButtonPressEvent", 10); GrabFocus (); SetCursor (e.State); p.Time ("SetCursor"); dragStartX = dragX = e.X; dragStartY = dragY = e.Y; ZoomVelocity = 1; ThrowFrames.Clear (); ClickCancelled = Cancelled = false; if (ThrowVelocity != 0) ClickCancelled = true; ThrowVelocity = 0; if (e.Button == 1 || e.Button == 2) ThrowFrames.Add (new ThrowFrame(e.X, e.Y)); dragging = false; if (e.Button == 3) { int w, h; e.Window.GetSize (out w, out h); ContextClick ((uint)w, (uint)h, e.X, e.Y); } else if (e.Button == 1 && !dragging) { DoubleClick = (e.Type == Gdk.EventType.TwoButtonPress); } if (e.Button == 1) { int w, h; e.Window.GetSize (out w, out h); DragSourceEntry = FindHit((uint)w, (uint)h, e.X, e.Y, 8).Target; DragSourcePath = DragSourceEntry.FullName; } p.Time ("Handled"); return true; }
/** BLOCKING */ protected override bool OnButtonReleaseEvent(Gdk.EventButton e) { Profiler p = new Profiler ("OnButtonReleaseEvent", 10); GrabFocus (); SetCursor (e.State); p.Time ("SetCursor"); ZoomVelocity = 1; if (Cancelled) { Cancelled = DoubleClick = false; } else { if (e.Button == 1 && !dragging && !ClickCancelled) { InteractionProfiler.Start (); int w, h; e.Window.GetSize (out w, out h); AltKeyDown = (e.State & Gdk.ModifierType.Mod1Mask) == Gdk.ModifierType.Mod1Mask; CtrlKeyDown = (e.State & Gdk.ModifierType.ControlMask) == Gdk.ModifierType.ControlMask; ShiftKeyDown = (e.State & Gdk.ModifierType.ShiftMask) == Gdk.ModifierType.ShiftMask; if (AltKeyDown) ClearSelection (); using (Context scr = new Context (CachedSurface)) { scr.IdentityMatrix (); Click (scr, (uint)w, (uint)h, e.X, e.Y); } DoubleClick = false; } if (e.Button == 1 && ThrowFrames.Count > 0) { ThrowVelocity = 0; if (DateTime.Now.Subtract(LastMotionTime).TotalMilliseconds < 100) { ThrowFrames.Add (new ThrowFrame(e.X, e.Y)); int len = Math.Min(10, ThrowFrames.Count-1); double vy = 0; for (int i=ThrowFrames.Count-len; i<ThrowFrames.Count; i++) { vy += ThrowFrames[i].Y - ThrowFrames[i-1].Y; } vy /= len; // Helpers.LogDebug("ThrowFrames.Count: {0}, vy: {1}", ThrowFrames.Count, vy); if (Math.Abs(vy) > 5) { ThrowVelocity = vy*2; NeedRedraw = true; } } ThrowFrames.Clear (); } } if (e.Button == 1) { if (!dragInProgress) { DragSourceEntry = null; DragSourcePath = null; } dragInProgress = false; } if (e.Button == 2) { ControlLineVisible = false; NeedRedraw = true; } dragging = false; panning = panning && dragInProgress; p.Time ("Handled"); return true; }
/** BLOCKING */ void ClickCurrentDir(Context cr, uint width, uint height, double x, double y) { Rectangle box = Transform (cr, width, height); if (x < box.X || x > box.X+box.Width || y < box.Y || y > box.Y+box.Height) return; cr.Scale (1, Zoomer.Z); cr.Translate (0.0, Zoomer.Y); List<ClickHit> hits = Renderer.Click (CurrentDirEntry, Prefixes, cr, box, x, y); foreach (ClickHit c in hits) { if (c.Height < 15.9) { if (c.Target.ParentDir == CurrentDirEntry) { double nz = (c.Target.IsDirectory ? 24 : 18) / c.Height; // Helpers.LogDebug("ZoomIn {0}x", nz); cr.Save (); cr.IdentityMatrix (); ZoomBy(cr, width, height, x, y, nz); cr.Restore (); break; } } else if (DoubleClick) { break; } else { if (AltKeyDown) { ClearSelection (); } else if (CtrlKeyDown) { ToggleSelection(c.Target.FullName); spanStart = c.Target; spanEnd = null; } else if (ShiftKeyDown) { if (spanStart != null) { if (spanEnd != null) { ToggleSpan(spanStart, spanEnd); } spanEnd = c.Target; ToggleSpan(spanStart, spanEnd); } else { ToggleSelection(c.Target.FullName); spanStart = c.Target; spanEnd = null; } } else { if (c.Target.IsDirectory) { // Helpers.LogDebug("Navigate {0}", c.Target.FullName); SetCurrentDir (c.Target.FullName); } else { // Helpers.LogDebug("Open {0}", c.Target.FullName); OpenFile(c.Target.FullName); } } UpdateLayout (); break; } } }
public DrawEntry(FSEntry f) { Height = f.Height; F = f; }
/** FAST */ public double Measure(FSEntry d) { double mul = (d.Name[0] == '.') ? 1.0 : 40.0; return (d.IsDirectory ? Math.Max(1, d.SubTreeCount) : 1.0) * mul; }
public FixupPair(FSEntry inKey, FSEntry inValue) { pairKey = inKey; pairValue = inValue; }
/** FAST */ public double Measure(FSEntry d) { long elapsed = (DateTime.Today.AddDays(1) - d.LastModified).Ticks; double mul = (d.Name[0] == '.') ? 1.0 : 20.0; return mul * (1 / Math.Max(1.0, (double)elapsed / (10000.0 * 300.0))); }
public SyncResults TrySync(PreSyncDetails entry, ConsoleEx console = null) { const int encrTimespanPrecisionMS = 1000; //todo: ensure the entry direction and operation end up being the same //todo: ensure all the calling methods do something with the results //if (WhatIf) // throw new InvalidOperationException("Unable to perform sync when WhatIf mode is set to true"); if (entry == null) { throw new ArgumentNullException(nameof(entry)); } if (entry.SyncMode == PreSyncMode.DecryptedSide) { SyncLogEntry logEntry = entry.LogEntry; string encrPath = Path.Combine(EncrDirectory.FullName, HelixUtil.PathNative(entry.EncrFileName)); string decrPath = Path.Combine(DecrDirectory.FullName, HelixUtil.PathNative(entry.DecrFileName)); FileEncryptOptions options = new FileEncryptOptions(); FileEntry header = null; options.BeforeWriteHeader = (h) => header = h; options.StoredFileName = entry.DecrFileName; options.FileVersion = Header.FileVersion; options.Log = (s) => console?.WriteLine(VerbosityLevel.Diagnostic, 1, s); if (WhatIf) { EncrDirectory.WhatIfReplaceFile(encrPath, entry.DisplayFileLength); if (entry.DecrInfo == null) { header = new FileEntry() { EntryType = FileEntryType.Removed, FileName = entry.DecrFileName, }; } else { header = entry.DecrInfo.ToFileEntry(); } } else { HelixFile.Encrypt(decrPath, encrPath, DerivedBytesProvider, options); //forces a change if the file was modified to quickly if (logEntry != null && (File.GetLastWriteTimeUtc(encrPath) - logEntry.EncrModified).TotalMilliseconds < encrTimespanPrecisionMS) { File.SetLastWriteTimeUtc(encrPath, logEntry.EncrModified + TimeSpan.FromMilliseconds(encrTimespanPrecisionMS)); } EncrDirectory.RefreshEntry(encrPath); } var newLogEntry = CreateEntryFromHeader(header, EncrDirectory.TryGetEntry(entry.EncrFileName)); SyncLog.Add(newLogEntry); return(SyncResults.Success()); } else if (entry.SyncMode == PreSyncMode.EncryptedSide) { if (entry.DisplayOperation == PreSyncOperation.Purge) { SyncLog.Add(entry.GetUpdatedLogEntry()); return(SyncResults.Success()); } else { //todo: use the DisplayOperation to determine what to do (ensures the counts stay consistant) SyncLogEntry logEntry = entry.LogEntry; SyncLogEntry fileSystemEntry = CreateNewLogEntryFromEncrPath(entry.EncrFileName); if (logEntry?.ToString() == fileSystemEntry?.ToString()) { return(SyncResults.Success()); //Unchanged } //todo: test to see if there are illegal characters //todo: check if the name matches string encrPath = HelixUtil.JoinNative(EncrDirectory.FullName, fileSystemEntry.EncrFileName); string decrPath = HelixUtil.JoinNative(DecrDirectory.FullName, fileSystemEntry.DecrFileName); //todo: if file exists with different case - skip file var exactPath = HelixUtil.GetExactPathName(decrPath); FSEntry decrEntry = DecrDirectory.TryGetEntry(fileSystemEntry.DecrFileName); if (decrEntry != null && decrEntry.RelativePath != fileSystemEntry.DecrFileName) { //todo: throw more specific exception return(SyncResults.Failure(new HelixException($"Case only conflict file \"{decrPath}\" exists as \"{exactPath}\"."))); } if (WhatIf) { if (entry.EncrHeader.EntryType == FileEntryType.File) { DecrDirectory.WhatIfReplaceFile(decrPath, entry.EncrHeader.Length, entry.EncrHeader.LastWriteTimeUtc); } else if (entry.EncrHeader.EntryType == FileEntryType.Removed) { DecrDirectory.WhatIfDeleteFile(decrPath); } else if (entry.EncrHeader.EntryType == FileEntryType.Directory) { DecrDirectory.WhatIfAddDirectory(decrPath); } else { throw new NotSupportedException(); } } else { HelixFile.Decrypt(encrPath, decrPath, DerivedBytesProvider); //todo: get the date on the file system (needed if the filesystem has less precision DecrDirectory.RefreshEntry(decrPath); } SyncLog.Add(fileSystemEntry); return(SyncResults.Success()); } } else if (entry.SyncMode == PreSyncMode.Match) { //Add to Log file (changed to be equal on both sides) SyncLogEntry fileSystemEntry = CreateNewLogEntryFromDecrPath(entry.DecrFileName); SyncLog.Add(fileSystemEntry); return(SyncResults.Success()); } else if (entry.SyncMode == PreSyncMode.Unchanged) { //do nothing return(SyncResults.Success()); } return(SyncResults.Failure(new HelixException($"Invalid sync mode {entry.SyncMode}"))); }