public void ArrayArg() { NSObject pool = new NSObject(NSObject.AllocAndInitInstance("NSAutoreleasePool")); Class nsData = new Class("NSData"); long bytes = DoGetMemory(); for (int j = 1; j < 100; ++j) { for (int i = 0; i < NumIterations/100; ++i) { byte[] data = new byte[]{2, 5, 6, 3}; NSObject d = new NSObject(nsData.Call("alloc")); NSObject e = (NSObject) d.Call("initWithBytes:length:", data, data.Length); e.release(); } GC.Collect(); } pool.release(); GC.Collect(); GC.WaitForPendingFinalizers(); long delta = DoGetMemory() - bytes; if (delta/NumIterations > 4) Assert.Fail("ArrayArg used {0}K of memory ({1} bytes per iteration)!", delta/1024, delta/NumIterations); }
private static NSObject DoCreateNativeException(Exception e) { NSObject native; IntPtr nameBuffer = Marshal.StringToHGlobalAuto(e.GetType().ToString()); IntPtr reasonBuffer = Marshal.StringToHGlobalAuto(e.Message); IntPtr keyBuffer = Marshal.StringToHGlobalAuto(".NET exception"); GCHandle handle = new GCHandle(); try { // Create the name, reason, and userInfo objects. NSObject name = (NSObject) new Class("NSString").Call("alloc").Call("initWithUTF8String:", nameBuffer); NSObject reason = (NSObject) new Class("NSString").Call("alloc").Call("initWithUTF8String:", reasonBuffer); NSObject userInfo = (NSObject) new Class("NSMutableDictionary").Call("alloc").Call("init"); name.autorelease(); reason.autorelease(); userInfo.autorelease(); // Add the original System.Exception to userInfo. NSObject key = (NSObject) new Class("NSString").Call("alloc").Call("initWithUTF8String:", keyBuffer); key.autorelease(); try { using (MemoryStream stream = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, e); byte[] data = stream.ToArray(); handle = GCHandle.Alloc(data, GCHandleType.Pinned); NSObject buffer = (NSObject) new Class("NSData").Call("dataWithBytes:length:", handle.AddrOfPinnedObject(), (uint)stream.Length); Unused.Value = userInfo.Call("setObject:forKey:", buffer, key); } } catch (Exception ee) { // Typically this will happen if e is not serializable. Console.Error.WriteLine("{0}", ee); Console.Error.Flush(); } // Create the NSException. native = (NSObject) new Class("NSException").Call("exceptionWithName:reason:userInfo:", name, reason, userInfo); } finally { Marshal.FreeHGlobal(nameBuffer); Marshal.FreeHGlobal(reasonBuffer); Marshal.FreeHGlobal(keyBuffer); if (handle.IsAllocated) { handle.Free(); } } return(native); }
private static string DoGetMessage(NSObject instance) { string text; if (instance.isMemberOfClass(new Class("NSException"))) { text = Marshal.PtrToStringAuto((IntPtr)instance.Call("name").Call("UTF8String")); text += ". "; text += Marshal.PtrToStringAuto((IntPtr)instance.Call("reason").Call("UTF8String")); } else { text = Marshal.PtrToStringAuto((IntPtr)instance.Call("description").Call("UTF8String")); } return(text); }
public void setDefaultColor(NSObject sender) { NSColor color = sender.Call("color").To<NSColor>(); NSUserDefaults defaults = NSUserDefaults.standardUserDefaults(); NSData data = NSArchiver.archivedDataWithRootObject(color); defaults.setObject_forKey(data, NSString.Create("text default color")); Broadcaster.Invoke("text default color changed", null); }
/// <summary>Converts an <c>NSException</c> into a managed exception and throws it.</summary> /// <param name = "instance">The <a href ="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/nsexception_Class/Reference/Reference.html">NSException</a> /// pointer.</param> /// <remarks>If the <c>NSException</c> wraps a managed exception then /// <c>TargetInvocationException</c> is thrown instead with the inner exception /// set to the original exception.</remarks> public static void Raise(IntPtr instance) { NSObject obj = new NSObject(instance); if (obj.isMemberOfClass(new Class("NSException"))) { // See if the userInfo contains a .NET exception. NSObject userInfo = (NSObject)obj.Call("userInfo"); if (userInfo != null && (IntPtr)userInfo != IntPtr.Zero) { IntPtr keyBuffer = Marshal.StringToHGlobalAuto(".NET exception"); NSObject key = (NSObject) new Class("NSString").Call("alloc").Call("initWithUTF8String:", keyBuffer); key.autorelease(); Marshal.FreeHGlobal(keyBuffer); NSObject data = (NSObject)userInfo.Call("objectForKey:", key); if (data != null && !data.IsNil()) { // If it does then get the serialized exception bytes, IntPtr ptr = (IntPtr)data.Call("bytes"); uint bytes = (uint)data.Call("length"); // copy them into a managed buffer, byte[] buffer = new byte[bytes]; Marshal.Copy(ptr, buffer, 0, (int)bytes); // and raise the original exception. using (MemoryStream stream = new MemoryStream(buffer)) { BinaryFormatter formatter = new BinaryFormatter(); Exception e = (Exception)formatter.Deserialize(stream); throw new TargetInvocationException("Exception has been thrown by the (managed) target of an Objective-C method call.", e); // yes TargetInvocationException sucks, but it preserves the original stack crawl... } } } } throw new CocoaException(obj); }
public void Dispatch(NSObject sender) { int i = sender.Call("tag").To<int>(); TextContextItem command = m_entries[i].Command; string result = command.Handler(m_selection); if (result != m_selection) { var range = NSValue.valueWithRange(m_range); var newText = NSString.Create(result); var undoText = NSString.Create(command.UndoText ?? command.Name); NSArray args = NSArray.Create(range, newText, undoText); m_view.Call("replaceSelection:", args); } m_entries.Clear(); // this has references to objects which we may want to GC m_view = null; }
public int TakeBase(NSObject s) { int r = (int) s.Call("getValue"); return 3 * r; }
public bool validateUserInterfaceItem(NSObject sender) { bool enabled = true; Selector sel = (Selector) sender.Call("action"); if (sel.Name == "toggleHex:") { Unused.Value = sender.Call("setTitle:", NSString.Create("Show {0}", ms_showHex ? "Decimal" : "Hex")); } else if (sel.Name == "toggleThousands:") { Unused.Value = sender.Call("setTitle:", NSString.Create("{0} Thousands", ms_hideThousands ? "Show" : "Hide")); } else if (sel.Name == "toggleUnicode:") { Unused.Value = sender.Call("setTitle:", NSString.Create("Show Unicode {0}", ms_hideUnicode ? "Characters" : "Code Points")); } else if (sel.Name == "showLiveObjects:") { } else if (sel.Name == "showTypeRoots:") { string type = DoGetSelectedType(); Unused.Value = sender.Call("setTitle:", NSString.Create("Show Roots for {0}", type)); } else if (sel.Name == "showInstanceRoots:") { VariableItem instance = DoGetSelectedObject(); if (instance != null) { Unused.Value = sender.Call("setTitle:", NSString.Create("Show Roots for {0}", instance.AttributedName.ToString())); } else { Unused.Value = sender.Call("setTitle:", NSString.Create("Show Roots for Object")); enabled = false; } } else if (respondsToSelector(sel)) { } else if (SuperCall(NSWindowController.Class, "respondsToSelector:", new Selector("validateUserInterfaceItem:")).To<bool>()) { enabled = SuperCall(NSWindowController.Class, "validateUserInterfaceItem:", sender).To<bool>(); } return enabled; }
public void handleContextItem(NSObject item) { int i = item.Call("tag").To<int>(); m_items[i].Handler(); }
public bool validateUserInterfaceItem(NSObject item) { Selector sel = (Selector) item.Call("action"); bool valid = false; if (sel.Name == "textHandler:") { int tag = (int) item.Call("tag"); var handler = m_boss.Get<IMenuHandler>(); MenuState state = handler.GetState(tag); valid = (state & MenuState.Enabled) == MenuState.Enabled; item.Call("setState:", (state & MenuState.Checked) == MenuState.Checked ? 1 : 0); } else if (sel.Name == "shiftLeft:" || sel.Name == "shiftRight:") { NSRange range = m_textView.Value.selectedRange(); valid = range.length > 0 && m_textView.Value.isEditable(); } else if (sel.Name == "lookUpInDict:") { NSRange range = m_textView.Value.selectedRange(); NSString text = m_textView.Value.textStorage().string_().substringWithRange(range); valid = NSApplication.sharedApplication().Call("canLookupInDictionary:", text).To<bool>(); } else if (sel.Name == "showSpaces:") { if (StylesWhitespace) { Boss boss = ObjectModel.Create("Stylers"); var white = boss.Get<IWhitespace>(); Unused.Value = item.Call("setTitle:", white.ShowSpaces ? NSString.Create("Hide Spaces") : NSString.Create("Show Spaces")); valid = true; } } else if (sel.Name == "showTabs:") { if (StylesWhitespace) { Boss boss = ObjectModel.Create("Stylers"); var white = boss.Get<IWhitespace>(); Unused.Value = item.Call("setTitle:", white.ShowTabs ? NSString.Create("Hide Tabs") : NSString.Create("Show Tabs")); valid = true; } } else if (sel.Name == "toggleComment:") { valid = m_language != null && m_language.LineComment != null; } else if (sel.Name == "toggleWordWrap:") { Unused.Value = item.Call("setTitle:", m_wordWrap ? NSString.Create("Don't Wrap Lines") : NSString.Create("Wrap Lines")); valid = true; } else if (sel.Name == "dirHandler:") { if (Path != null) { NSWindow window = DoGetDirEditor(); if (window != null) valid = window.windowController().Call("validateUserInterfaceItem:", item).To<bool>(); else valid = false; } } else if (respondsToSelector(sel)) { valid = true; } else if (SuperCall(NSWindowController.Class, "respondsToSelector:", new Selector("validateUserInterfaceItem:")).To<bool>()) { valid = SuperCall(NSWindowController.Class, "validateUserInterfaceItem:", item).To<bool>(); } return valid; }
// Convert an NSString or an NSAttributedString to our internal (unix) endian. private NSObject DoNormalizeString(NSObject str) { var result = str.Call("mutableCopy").To<NSObject>(); // use a dynamic call because NSAttributedString and NSString don't share a common base class var replacement = NSString.Create("\n"); foreach (string endian in new string[]{"\r\n", "\r"}) { List<NSRange> ranges = DoGetSubstrings(result, endian); foreach (NSRange range in ranges) { result.Call("replaceCharactersInRange:withString:", range, replacement); } } return result; }
private static string DoGetMessage(NSObject instance) { string text; if (instance.isMemberOfClass(new Class("NSException"))) { text = Marshal.PtrToStringAuto((IntPtr) instance.Call("name").Call("UTF8String")); text += ". "; text += Marshal.PtrToStringAuto((IntPtr) instance.Call("reason").Call("UTF8String")); } else text = Marshal.PtrToStringAuto((IntPtr) instance.Call("description").Call("UTF8String")); return text; }
/// <summary>Converts an <c>NSException</c> into a managed exception and throws it.</summary> /// <param name = "instance">The <a href ="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/nsexception_Class/Reference/Reference.html">NSException</a> /// pointer.</param> /// <remarks>If the <c>NSException</c> wraps a managed exception then /// <c>TargetInvocationException</c> is thrown instead with the inner exception /// set to the original exception.</remarks> public static void Raise(IntPtr instance) { NSObject obj = new NSObject(instance); if (obj.isMemberOfClass(new Class("NSException"))) { // See if the userInfo contains a .NET exception. NSObject userInfo = (NSObject) obj.Call("userInfo"); if (userInfo != null && (IntPtr) userInfo != IntPtr.Zero) { IntPtr keyBuffer = Marshal.StringToHGlobalAuto(".NET exception"); NSObject key = (NSObject) new Class("NSString").Call("alloc").Call("initWithUTF8String:", keyBuffer); key.autorelease(); Marshal.FreeHGlobal(keyBuffer); NSObject data = (NSObject) userInfo.Call("objectForKey:", key); if (data != null && !data.IsNil()) { // If it does then get the serialized exception bytes, IntPtr ptr = (IntPtr) data.Call("bytes"); uint bytes = (uint) data.Call("length"); // copy them into a managed buffer, byte[] buffer = new byte[bytes]; Marshal.Copy(ptr, buffer, 0, (int) bytes); // and raise the original exception. using (MemoryStream stream = new MemoryStream(buffer)) { BinaryFormatter formatter = new BinaryFormatter(); Exception e = (Exception) formatter.Deserialize(stream); throw new TargetInvocationException("Exception has been thrown by the (managed) target of an Objective-C method call.", e); // yes TargetInvocationException sucks, but it preserves the original stack crawl... } } } } throw new CocoaException(obj); }
public bool Validate(NSObject sender) { int i = sender.Call("tag").To<int>(); sender.Call("setState:", m_entries[i].Command.State); return m_entries[i].Command.Handler != null; }
private void DoAnimate(IntPtr subview, NSRect frame) { NSObject view = new NSObject(subview); view.Call("animator").Call("setFrame:", frame); }
// Action method to change layout style. public void changeLayout(NSObject sender) { m_layout = (Layout) (int) sender.Call("selectedTag"); DoLayout(); }
public bool validateUserInterfaceItem(NSObject sender) { bool enabled = false; Selector sel = (Selector) sender.Call("action"); if (sel.Name == "dirHandler:") { int tag = (int) sender.Call("tag"); var handler = m_boss.Get<IMenuHandler>(); MenuState state = handler.GetState(tag); enabled = (state & MenuState.Enabled) == MenuState.Enabled; if (sender.respondsToSelector("setState:")) sender.Call("setState:", (state & MenuState.Checked) == MenuState.Checked ? 1 : 0); if (enabled && tag == 50 && sender.isMemberOfClass(NSMenuItem.Class)) { Unused.Value = sender.Call("setTitle:", NSString.Create("Build " + m_name)); } else if (enabled && tag == 1000 && sender.isMemberOfClass(NSMenuItem.Class)) { Unused.Value = sender.Call("setTitle:", NSString.Create(m_name + " Preferences")); } } else if (sel.Name == "targetChanged:") { enabled = m_builder != null && m_builder.CanBuild; } else if (sel.Name == "renameItem:") { NSIndexSet selections = m_table.selectedRowIndexes(); enabled = selections.count() == 1; } else if (sel.Name == "duplicate:") { NSIndexSet selections = m_table.selectedRowIndexes(); enabled = selections.count() > 0 && m_table.editedRow() < 0; // cocoa crashes if we do a duplicate while editing... } else if (respondsToSelector(sel)) { enabled = true; } else if (SuperCall(NSWindowController.Class, "respondsToSelector:", new Selector("validateUserInterfaceItem:")).To<bool>()) { enabled = SuperCall(NSWindowController.Class, "validateUserInterfaceItem:", sender).To<bool>(); } return enabled; }
public bool validateUserInterfaceItem(NSObject sender) { bool enabled = false; Selector sel = (Selector) sender.Call("action"); if (sel.Name == "openWithFinder:" || sel.Name == "showInFinder:") { enabled = m_table.numberOfSelectedRows() > 0; } else if (respondsToSelector(sel)) { enabled = true; } else if (SuperCall(NSWindowController.Class, "respondsToSelector:", new Selector("validateUserInterfaceItem:")).To<bool>()) { enabled = SuperCall(NSWindowController.Class, "validateUserInterfaceItem:", sender).To<bool>(); } return enabled; }
public bool validateUserInterfaceItem(NSObject item) { Selector sel = (Selector) item.Call("action"); bool valid = false; if (sel.Name == "removeDirs:") { NSIndexSet selections = m_dirsTable.Value.selectedRowIndexes(); valid = selections.count() > 0; } else if (respondsToSelector(sel)) { valid = true; } else if (SuperCall(NSWindowController.Class, "respondsToSelector:", new Selector("validateUserInterfaceItem:")).To<bool>()) { valid = SuperCall(NSWindowController.Class, "validateUserInterfaceItem:", item).To<bool>(); } return valid; }
public bool validateMenuItem(NSObject menuItem) { bool enabled = false; #if DEBUG Selector selector = (Selector) menuItem.Call("action"); if (selector.Name == "memoryTest:") { NSObject text; lock (m_lock) { if (m_checkingMemory) text = (NSObject) new Class("NSString").Call("stringWithUTF8String:", Marshal.StringToHGlobalAuto("Stop Memory Test")); else text = (NSObject) new Class("NSString").Call("stringWithUTF8String:", Marshal.StringToHGlobalAuto("Start Memory Test")); } menuItem.Call("setTitle:", text); enabled = true; } else if (respondsToSelector(selector)) { return true; } #endif return enabled; }
public void setTabsColor(NSObject sender) { NSColor color = sender.Call("color").To<NSColor>(); DoSetBackColor("text tabs", color, true); }
private List<NSRange> DoGetSubstrings(NSObject inStr, string inSubstr) { var ranges = new List<NSRange>(); var str = (inStr.isKindOfClass(NSString.Class) ? inStr : inStr.Call("string")).To<NSString>(); var substr = NSString.Create(inSubstr); NSRange within = new NSRange(0, (int) str.length()); while (within.location < str.length()) { NSRange range = str.rangeOfString_options_range(substr, Enums.NSLiteralSearch, within); if (range.length == 0) break; within = new NSRange(range.location + range.length, (int) (str.length() - (range.location + range.length))); ranges.Add(range); } return ranges; }
public void tableView_setObjectValue_forTableColumn_row(NSTableView table, NSObject value, NSTableColumn col, int row) { Contract.Requires(row >= 0, "row is negative"); Contract.Requires(row < m_globs.Count, "row is too big"); switch (col.identifier().description()) { case "1": m_globs[row] = Tuple.Create(value.description(), m_globs[row].Item2); break; case "2": m_globs[row] = Tuple.Create(m_globs[row].Item1, value.Call("intValue").To<int>()); break; default: Contract.Assert(false, "bad col: " + col.identifier()); break; } DoSyncPref(); }
public void setLineColor(NSObject sender) { NSColor color = sender.Call("color").To<NSColor>(); DoSetBackColor("selected line", color, false); }
public void textHandler(NSObject sender) { int tag = (int) sender.Call("tag"); var handler = m_boss.Get<IMenuHandler>(); handler.Handle(tag); }
public void setTranscriptColor(NSObject sender) { NSColor color = sender.Call("color").To<NSColor>(); DoSetBackColor("transcript", color, false); }
public void NilCallTest() { NSObject pool = new NSObject(NSObject.AllocAndInitInstance("NSAutoreleasePool")); NSObject nil = new NSObject(IntPtr.Zero); // Calling an NSObject method on nil does nothing and returns nil. NSObject result = (NSObject) nil.Call("hash"); Assert.IsTrue(result.IsNil()); // Calling a unknown method on nil does nothing and returns nil. result = (NSObject) nil.Call("foo"); Assert.IsTrue(result.IsNil()); // Can chain calls to nil. result = (NSObject) nil.Call("foo").Call("bar"); Assert.IsTrue(result.IsNil()); // Can use Native with null. result = (NSObject) nil.Call("foo"); Assert.IsTrue(result.IsNil()); pool.release(); }
public void setErrorsColor(NSObject sender) { NSColor color = sender.Call("color").To<NSColor>(); DoSetBackColor("errors", color, false); }
public new bool validateUserInterfaceItem(NSObject item) { Selector sel = (Selector) item.Call("action"); bool valid = false; if (sel.Name == "handleContextItem:") { int i = item.Call("tag").To<int>(); item.Call("setState:", m_items[i].State); valid = true; } else if (respondsToSelector(sel)) { valid = true; } else if (SuperCall(NSWindow.Class, "respondsToSelector:", new Selector("validateUserInterfaceItem:")).To<bool>()) { valid = SuperCall(NSWindow.Class, "validateUserInterfaceItem:", item).To<bool>(); } return valid; }
// Sent by NSFontManager up the responder chain when font attributes are changed via the font panel. public void changeAttributes(NSObject sender) { m_attributes = sender.Call("convertAttributes:", m_attributes).To<NSDictionary>().Retain(); NSUserDefaults defaults = NSUserDefaults.standardUserDefaults(); NSData data = NSArchiver.archivedDataWithRootObject(m_attributes); defaults.setObject_forKey(data, NSString.Create(m_styleName + " font attributes")); DoUpdateButtonTitle(m_styleName); Broadcaster.Invoke(m_styleName + " font changed-pre", true); Broadcaster.Invoke(m_styleName + " font changed", true); }