///<summary>Handle file->revert command from menu</summary> public void OnRevertActivated(object o, EventArgs args) { if (dataBook.NPages == 0) { return; } DataView dv = ((DataViewDisplay)dataBook.CurrentPageWidget).View; RevertConfirmationAlert rca = new RevertConfirmationAlert(dv.Buffer.Filename, mainWindow); ResponseType response = (ResponseType)rca.Run(); rca.Destroy(); try { if (response == ResponseType.Ok) { dv.Revert(); } } catch (FileNotFoundException ex) { string msg = string.Format(Catalog.GetString("The file '{0}' cannot be found. Perhaps it has been recently deleted."), ex.Message); ErrorAlert ea = new ErrorAlert(Catalog.GetString("Error reverting file"), msg, mainWindow); ea.Run(); ea.Destroy(); } }
///<summary>Update the search pattern from the text entry</summary> void UpdateSearchPattern() { if (!searchPatternChanged) { return; } try { byte[] ba; switch ((ComboIndex)SearchAsComboBox.Active) { case ComboIndex.Hexadecimal: ba = ByteArray.FromString(SearchPatternEntry.Text, 16); break; case ComboIndex.Decimal: ba = ByteArray.FromString(SearchPatternEntry.Text, 10); break; case ComboIndex.Octal: ba = ByteArray.FromString(SearchPatternEntry.Text, 8); break; case ComboIndex.Binary: ba = ByteArray.FromString(SearchPatternEntry.Text, 2); break; case ComboIndex.Text: ba = Encoding.ASCII.GetBytes(SearchPatternEntry.Text); break; default: ba = new byte[0]; break; } //end switch // if there is something in the text entry but nothing is parsed // it means it is full of spaces if (ba.Length == 0 && SearchPatternEntry.Text.Length != 0) { throw new FormatException(Catalog.GetString("Strings representing numbers cannot consist of whitespace characters only.")); } else { finder.Strategy.Pattern = ba; } // append string to drop-down list ListStore ls = (ListStore)SearchPatternEntry.Completion.Model; ls.AppendValues(SearchPatternEntry.Text); } catch (FormatException e) { ErrorAlert ea = new ErrorAlert(Catalog.GetString("Invalid Search Pattern"), e.Message, null); ea.Run(); ea.Destroy(); throw; } searchPatternChanged = false; }
/// // // Replace related methods // ///<summary>Update the replace pattern from the text entry</summary> void UpdateReplacePattern() { if (!replacePatternChanged) { return; } try { switch ((ComboIndex)ReplaceAsComboBox.Active) { case ComboIndex.Hexadecimal: replacePattern = ByteArray.FromString(ReplacePatternEntry.Text, 16); break; case ComboIndex.Decimal: replacePattern = ByteArray.FromString(ReplacePatternEntry.Text, 10); break; case ComboIndex.Octal: replacePattern = ByteArray.FromString(ReplacePatternEntry.Text, 8); break; case ComboIndex.Binary: replacePattern = ByteArray.FromString(ReplacePatternEntry.Text, 2); break; case ComboIndex.Text: replacePattern = Encoding.ASCII.GetBytes(ReplacePatternEntry.Text); break; default: break; } //end switch // if there is something in the text entry but nothing is parsed // it means it is full of spaces if (replacePattern.Length == 0 && ReplacePatternEntry.Text.Length != 0) { throw new FormatException("Strings representing numbers cannot consist of only whitespace characters. Leave the text entry completely blank for deletion of matched pattern(s)."); } // append string to drop-down list ListStore ls = (ListStore)ReplacePatternEntry.Completion.Model; ls.AppendValues(ReplacePatternEntry.Text); } catch (FormatException e) { ErrorAlert ea = new ErrorAlert("Invalid Replace Pattern", e.Message, null); ea.Run(); ea.Destroy(); throw; } replacePatternChanged = false; }
private ByteBuffer OpenFileInternal(string fullPath, bool handleFileNotFound) { try { ByteBuffer bb = ByteBuffer.FromFile(fullPath); bb.UseGLibIdle = true; if (Preferences.Instance["ByteBuffer.TempDir"] != "") { bb.TempDir = Preferences.Instance["ByteBuffer.TempDir"]; } string msg = string.Format(Catalog.GetString("Loaded file '{0}'"), fullPath); Services.UI.Info.DisplayMessage(msg); History.Instance.Add(fullPath); return(bb); } catch (UnauthorizedAccessException) { string msg = string.Format(Catalog.GetString("Error opening file '{0}'"), fullPath); ErrorAlert ea = new ErrorAlert(msg, Catalog.GetString("You do not have read permissions for the file you requested."), mainWindow); ea.Run(); ea.Destroy(); } catch (System.IO.FileNotFoundException) { if (handleFileNotFound == false) { throw; } string msg = string.Format(Catalog.GetString("Error opening file '{0}'"), fullPath); ErrorAlert ea = new ErrorAlert(msg, Catalog.GetString("The file you requested does not exist."), mainWindow); ea.Run(); ea.Destroy(); } catch (System.IO.IOException ex) { string msg = string.Format(Catalog.GetString("Error opening file '{0}'"), fullPath); ErrorAlert ea = new ErrorAlert(msg, ex.Message, mainWindow); ea.Run(); ea.Destroy(); } catch (System.ArgumentException ex) { string msg = string.Format(Catalog.GetString("Error opening file '{0}'"), fullPath); ErrorAlert ea = new ErrorAlert(msg, ex.Message, mainWindow); ea.Run(); ea.Destroy(); } catch (System.NotSupportedException ex) { string msg = string.Format(Catalog.GetString("Error opening file '{0}'"), fullPath); ErrorAlert ea = new ErrorAlert(msg, ex.Message, mainWindow); ea.Run(); ea.Destroy(); } return(null); }
void OnDoOperationClicked(object o, EventArgs args) { if (dataBook.NPages == 0) { return; } DataView dv = ((DataViewDisplay)dataBook.CurrentPageWidget).View; // get the operands as a byte array byte[] byteArray = null; try { byteArray = ParseOperand(); } catch (FormatException e) { ErrorAlert ea = new ErrorAlert(Catalog.GetString("Error in Operand"), e.Message, null); ea.Run(); ea.Destroy(); return; } /// get the range to apply the operation to Util.Range range = dv.Selection; if (range.IsEmpty()) { Util.Range bbRange = dv.Buffer.Range; range.Start = dv.CursorOffset; range.End = range.Start + byteArray.Length - 1; range.Intersect(bbRange); } // don't allow buffer modification while the operation is perfoming dv.Buffer.ModifyAllowed = false; dv.Buffer.FileOperationsAllowed = false; BitwiseOperation bo = new BitwiseOperation(dv.Buffer, byteArray, range, (OperationType)OperationComboBox.Active, Services.UI.Progress.NewCallback(), BitwiseOperationAsyncCallback, true); // start operation thread Thread boThread = new Thread(bo.OperationThread); boThread.IsBackground = true; boThread.Start(); }
///<summary> /// Callback to call when a save operation has finished ///</summary> void SaveFileAsyncCallback(IAsyncResult ar) { ISaveState ss = (ISaveState)ar.AsyncState; if (ss.Result == ThreadedAsyncOperation.OperationResult.Finished) // save went ok { string msg; if (ss.SavePath != ss.Buffer.Filename) { msg = string.Format(Catalog.GetString("The file has been saved as '{0}'"), ss.SavePath); } else { msg = string.Format(Catalog.GetString("The file '{0}' has been saved"), ss.SavePath); } Services.UI.Info.DisplayMessage(msg); // add to history History.Instance.Add(ss.SavePath); return; } else if (ss.Result == ThreadedAsyncOperation.OperationResult.Cancelled) // save cancelled { } else if (ss.Result == ThreadedAsyncOperation.OperationResult.CaughtException) { // * UnauthorizedAccessException // * System.ArgumentException // * System.IO.IOException string msg = string.Format(Catalog.GetString("Error saving file '{0}'"), ss.SavePath); ErrorAlert ea = new ErrorAlert(msg, ss.ThreadException.Message, mainWindow); ea.Run(); ea.Destroy(); } { string msg = string.Format(Catalog.GetString("The file '{0}' has NOT been saved"), ss.SavePath); Services.UI.Info.DisplayMessage(msg); } }
///<summary> /// Try to open the file as a ByteBuffer ///</summary> public ByteBuffer OpenFile(string filename) { Uri uri = null; // first try filename as a URI try { uri = new Uri(filename); } catch { } // if filename is a valid URI if (uri != null) { // try to open the URI as an unescaped path try { return(OpenFileInternal(uri.LocalPath, false)); } catch (FileNotFoundException) { } // try to open the URI as an escaped path try { return(OpenFileInternal(uri.AbsolutePath, false)); } catch (FileNotFoundException) { } } // filename is not a valid URI... (eg the path contains invalid URI characters like ':') // try to expand it as a local path try { string fullPath = Path.GetFullPath(filename); return(OpenFileInternal(fullPath, true)); } catch (Exception ex) { string msg = string.Format(Catalog.GetString("Error opening file '{0}'"), filename); ErrorAlert ea = new ErrorAlert(msg, ex.Message, mainWindow); ea.Run(); ea.Destroy(); return(null); } }
///<summary> /// Create and setup a DataView ///</summary> public DataView CreateDataView(ByteBuffer bb) { DataView dv = new DataView(); string layoutFile = string.Empty; // try to load default (from user preferences) layout file try { layoutFile = Preferences.Instance["Default.Layout.File"]; string useCurrent = Preferences.Instance["Default.Layout.UseCurrent"]; if (useCurrent == "True" && dataBook.NPages > 0) { DataViewDisplay dvd = (DataViewDisplay)dataBook.CurrentPageWidget; layoutFile = dvd.Layout.FilePath; } if (layoutFile != string.Empty) { dv.Display.Layout = new Bless.Gui.Layout(layoutFile); } } catch (Exception ex) { string msg = string.Format(Catalog.GetString("Error loading layout '{0}'. Loading default layout instead."), layoutFile); ErrorAlert ea = new ErrorAlert(msg, ex.Message, mainWindow); ea.Run(); ea.Destroy(); } if (Preferences.Instance["Default.EditMode"] == "Insert") { dv.Overwrite = false; } else if (Preferences.Instance["Default.EditMode"] == "Overwrite") { dv.Overwrite = true; } dv.Buffer = bb; return(dv); }
void OnGotoOffsetClicked(object o, EventArgs args) { if (dataBook.NPages == 0) { return; } DataView dv = ((DataViewDisplay)dataBook.CurrentPageWidget).View; long offset = -1; try { offset = BaseConverter.Parse(OffsetEntry.Text); if (offset >= 0 && offset <= dv.Buffer.Size) { dv.Display.MakeOffsetVisible(offset, DataViewDisplay.ShowType.Closest); dv.MoveCursor(offset, 0); } else { ErrorAlert ea = new ErrorAlert(Catalog.GetString("Invalid Offset"), Catalog.GetString("The offset you specified is outside the file's limits."), null); ea.Run(); ea.Destroy(); } // append string to drop-down list ListStore ls = (ListStore)OffsetEntry.Completion.Model; ls.AppendValues(OffsetEntry.Text); } catch (FormatException e) { ErrorAlert ea = new ErrorAlert(Catalog.GetString("Error in Offset Format"), e.Message, null); ea.Run(); ea.Destroy(); } }
public BlessMain(string[] args) { Application.Init(); // Catalog.Init(ConfigureDefines.GETTEXT_PACKAGE, ConfigureDefines.LOCALE_DIR); // load main window from glade XML Glade.XML gxml = new Glade.XML(FileResourcePath.GetDataPath("bless.glade"), "MainWindow", "bless"); gxml.Autoconnect(this); // set the application icon MainWindow.Icon = new Gdk.Pixbuf(FileResourcePath.GetDataPath("bless-48x48.png")); string blessConfDir = FileResourcePath.GetUserPath(); // make sure local configuration directory exists try { if (!Directory.Exists(blessConfDir)) { Directory.CreateDirectory(blessConfDir); } } catch (Exception ex) { ErrorAlert ea = new ErrorAlert(Catalog.GetString("Cannot create user configuration directory"), ex.Message + Catalog.GetString("\n\nSome features of Bless may not work properly."), MainWindow); ea.Run(); ea.Destroy(); } Preferences.Proxy.Enable = false; // load default preferences Preferences.Default.Load(FileResourcePath.GetDataPath("default-preferences.xml")); Preferences.Default["Default.Layout.File"] = FileResourcePath.GetDataPath("bless-default.layout"); // load user preferences LoadPreferences(Path.Combine(blessConfDir, "preferences.xml")); Preferences.Instance.AutoSavePath = Path.Combine(blessConfDir, "preferences.xml"); // add the (empty) Menubar and toolbar uiManager = new UIManager(); MainWindow.AddAccelGroup(uiManager.AccelGroup); uiManager.AddUiFromString(uiXml); actionEntries = new ActionEntry[] { new ActionEntry("File", null, Catalog.GetString("_File"), null, null, null), new ActionEntry("Edit", null, Catalog.GetString("_Edit"), null, null, null), new ActionEntry("View", null, Catalog.GetString("_View"), null, null, null), new ActionEntry("Search", null, Catalog.GetString("_Search"), null, null, null), new ActionEntry("Tools", null, Catalog.GetString("_Tools"), null, null, null), new ActionEntry("Help", null, Catalog.GetString("_Help"), null, null, null) }; ActionGroup group = new ActionGroup("MainMenuActions"); group.Add(actionEntries); group.Add(new ToggleActionEntry[] { new ToggleActionEntry("ToolbarAction", null, Catalog.GetString("Toolbar"), null, null, new EventHandler(OnViewToolbarToggled), false) }); uiManager.InsertActionGroup(group, 0); Widget mb = uiManager.GetWidget("/menubar"); MainVBox.PackStart(mb, false, false, 0); MainVBox.ReorderChild(mb, 0); Widget tb = uiManager.GetWidget("/toolbar"); tb.Visible = false; MainVBox.PackStart(tb, false, false, 0); MainVBox.ReorderChild(tb, 1); // create the DataBook dataBook = new DataBook(); dataBook.PageAdded += new DataView.DataViewEventHandler(OnDataViewAdded); dataBook.Removed += new RemovedHandler(OnDataViewRemoved); dataBook.SwitchPage += new SwitchPageHandler(OnSwitchPage); DataViewBox.PackStart(dataBook); // create the widget groups that hold utility widgets WidgetGroup widgetGroup0 = new WidgetGroup(); WidgetGroup widgetGroup1 = new WidgetGroup(); WidgetGroup sideWidgetGroup0 = new WidgetGroup(); WidgetGroup sideWidgetGroup1 = new WidgetGroup(); widgetGroup0.Show(); widgetGroup1.Show(); sideWidgetGroup0.Show(); sideWidgetGroup1.Show(); MainVBox.PackStart(widgetGroup0, false, false, 0); MainVBox.ReorderChild(widgetGroup0, 3); MainVBox.PackStart(widgetGroup1, false, false, 0); MainVBox.ReorderChild(widgetGroup1, 4); DataViewBox.PackStart(sideWidgetGroup0, false, false, 0); DataViewBox.ReorderChild(sideWidgetGroup0, 0); DataViewBox.PackEnd(sideWidgetGroup1, false, false, 0); //MainVBox.ReorderChild(widgetGroup1, 4); Services.File = new FileService(dataBook, MainWindow); Services.Session = new SessionService(dataBook, MainWindow); Services.UI = new UIService(uiManager); //Services.Info=new InfoService(infobar); // Add area plugins PluginManager.AddForType(typeof(AreaPlugin), new object[0]); PluginManager areaPlugins = PluginManager.GetForType(typeof(AreaPlugin)); Area.InitiatePluginTable(); foreach (AreaPlugin p in areaPlugins.Plugins) { Area.AddFactoryItem(p.Name, p.CreateArea); } // Load GUI plugins PluginManager.AddForType(typeof(GuiPlugin), new object[] { MainWindow, uiManager }); PluginManager guiPlugins = PluginManager.GetForType(typeof(GuiPlugin)); foreach (Plugin p in guiPlugins.Plugins) { guiPlugins.LoadPlugin(p); } // load recent file history try { History.Instance.Load(Path.Combine(blessConfDir, "history.xml")); } catch (Exception e) { System.Console.WriteLine(e.Message); } // if user specified files on the command line // try to load them if (args.Length > 0) { Services.File.LoadFiles(args); } else if (Preferences.Instance["Session.LoadPrevious"] == "True") { bool loadIt = true; string prevSessionFile = Path.Combine(blessConfDir, "last.session"); if (Preferences.Instance["Session.AskBeforeLoading"] == "True" && File.Exists(prevSessionFile)) { MessageDialog md = new MessageDialog(MainWindow, DialogFlags.DestroyWithParent, MessageType.Question, ButtonsType.YesNo, Catalog.GetString("Do you want to load your previous session?")); ResponseType result = (ResponseType)md.Run(); md.Destroy(); if (result == ResponseType.Yes) { loadIt = true; } else { loadIt = false; } } // try to load previous session if (loadIt) { Services.Session.Load(prevSessionFile); } } // if nothing has been loaded, create a new file if (dataBook.NPages == 0) { ByteBuffer bb = Services.File.NewFile(); // create and setup a DataView DataView dv = Services.File.CreateDataView(bb); // append the DataView to the DataBook dataBook.AppendView(dv, new CloseViewDelegate(Services.File.CloseFile), Path.GetFileName(bb.Filename)); } PreferencesChangedHandler handler = new PreferencesChangedHandler(OnPreferencesChanged); Preferences.Proxy.Subscribe("View.Toolbar.Show", "mainwin", handler); // register drag and drop of files MainWindow.DragDataReceived += OnDragDataReceived; Gtk.Drag.DestSet(MainWindow, DestDefaults.Motion | DestDefaults.Drop, dropTargets, Gdk.DragAction.Copy | Gdk.DragAction.Move); DataViewBox.ShowAll(); Preferences.Proxy.Enable = true; // fire the preferences changed event // so things are setup according to the preferences Preferences.Proxy.NotifyAll(); Application.Run(); }
void OnSelectButtonClicked(object o, EventArgs args) { if (dataBook.NPages == 0) { return; } DataView dv = ((DataViewDisplay)dataBook.CurrentPageWidget).View; long fromOffset = -1; long toOffset = -1; int relative = 0; try { fromOffset = BaseConverter.Parse(FromEntry.Text); } catch (FormatException e) { ErrorAlert ea = new ErrorAlert(Catalog.GetString("Error in From Offset Format"), e.Message, null); ea.Run(); ea.Destroy(); return; } string toString = ToEntry.Text.Trim(); if (toString.StartsWith("+")) { relative = 1; } else if (toString.StartsWith("-")) { relative = -1; } toString = toString.TrimStart(new char[] { '+', '-' }); try { toOffset = BaseConverter.Parse(toString); } catch (FormatException e) { ErrorAlert ea = new ErrorAlert(Catalog.GetString("Error in To Offset Format"), e.Message, null); ea.Run(); ea.Destroy(); return; } if (relative != 0) { toOffset = fromOffset + relative * (toOffset - 1); } if (toOffset >= 0 && toOffset < dv.Buffer.Size && fromOffset >= 0 && fromOffset < dv.Buffer.Size) { dv.SetSelection(fromOffset, toOffset); dv.Display.MakeOffsetVisible(toOffset, DataViewDisplay.ShowType.Closest); // append string to drop-down lists ListStore ls = (ListStore)ToEntry.Completion.Model; ls.AppendValues(ToEntry.Text); ls = (ListStore)FromEntry.Completion.Model; ls.AppendValues(FromEntry.Text); } else { ErrorAlert ea = new ErrorAlert(Catalog.GetString("Invalid Range"), Catalog.GetString("The range you specified is outside the file's limits."), null); ea.Run(); ea.Destroy(); } }
///<summary> /// Load a session from the specified file. ///</summary> public void Load(string path) { Session session = new Session(); // try to load session file try { session.Load(path); } catch (Exception ex) { System.Console.WriteLine(ex.Message); return; } // set the size of main window if (Preferences.Instance["Session.RememberWindowGeometry"] == "True") { mainWindow.Resize(session.WindowWidth, session.WindowHeight); } // add files to the DataBook foreach (SessionFileInfo sfi in session.Files) { ByteBuffer bb = Services.File.OpenFile(sfi.Path); // if file was opened successfully if (bb != null) { DataView dv = Services.File.CreateDataView(bb); // try to load layout file try { dv.Display.Layout = new Bless.Gui.Layout(sfi.Layout); } catch (Exception ex) { ErrorAlert ea = new ErrorAlert("Error loading layout '" + sfi.Layout + "' for file '" + sfi.Path + "'. Loading default layout.", ex.Message, mainWindow); ea.Run(); ea.Destroy(); } long cursorOffset = sfi.CursorOffset; // sanity check cursor offset and view offset if (cursorOffset > bb.Size) { cursorOffset = bb.Size; } long offset = sfi.Offset; if (offset >= bb.Size) { offset = 0; } if (Preferences.Instance["Session.RememberCursorPosition"] == "True") { dv.MoveCursor(cursorOffset, sfi.CursorDigit); dv.Offset = offset; } dataBook.AppendView(dv, new CloseViewDelegate(Services.File.CloseFile), Path.GetFileName(bb.Filename)); //OnBufferChanged(bb); } } foreach (DataViewDisplay dvd in dataBook.Children) { DataView dv = dvd.View; if (dv.Buffer.Filename == session.ActiveFile) { dataBook.CurrentPage = dataBook.PageNum(dvd); break; } } }
///<summary> /// Manage low-level file saving procedures ///</summary> private bool SaveFileInternal(DataView dv, string filename, bool synchronous) { ByteBuffer bb = dv.Buffer; string fullPath = null; // get the full path try { fullPath = Path.GetFullPath(filename); } catch (Exception ex) { string msg = string.Format(Catalog.GetString("Error saving file '{0}'"), filename); ErrorAlert ea = new ErrorAlert(msg, ex.Message, mainWindow); ea.Run(); ea.Destroy(); } // if we can't get full path, return if (fullPath == null) { return(false); } try { string msg; if (fullPath != bb.Filename) { msg = string.Format(Catalog.GetString("Saving file '{0}' as '{1}'"), bb.Filename, fullPath); } else { msg = string.Format(Catalog.GetString("Saving file '{0}'"), bb.Filename); } Services.UI.Info.DisplayMessage(msg + "..."); IAsyncResult ar; // Decide whether to save or save as if (fullPath != bb.Filename) { ar = bb.BeginSaveAs(fullPath, Services.UI.Progress.NewCallback(), new AsyncCallback(SaveFileAsyncCallback)); } else { ar = bb.BeginSave(Services.UI.Progress.NewCallback(), new AsyncCallback(SaveFileAsyncCallback)); } // if save is synchronous wait for save to finish if (synchronous) { // while waiting update the gui while (ar.AsyncWaitHandle.WaitOne(50, true) == false) { while (Application.EventsPending()) { Application.RunIteration(); } } // find out if save succeeded SaveAsOperation bbs = (SaveAsOperation)ar.AsyncState; if (bbs.Result != SaveAsOperation.OperationResult.Finished) { return(false); } // add to history History.Instance.Add(bbs.SavePath); return(true); } } catch (IOException ex) { string file; if (fullPath != bb.Filename) { file = fullPath; } else { file = bb.Filename; } string msg = string.Format(Catalog.GetString("Error saving file '{0}'"), file); ErrorAlert ea = new ErrorAlert(msg, ex.Message, mainWindow); ea.Run(); ea.Destroy(); msg = string.Format(Catalog.GetString("The file '{0}' has NOT been saved"), file); Services.UI.Info.DisplayMessage(msg); } return(false); }