public CocoaTextViewHelper(NSTextView textField)
 {
     m_textView = textField;
     m_textView.SetDelegate(d => {
         d.TextDidChange += HandleTextViewTextDidChange;
     });
 }
        public void ExtendSelection(NSTextView view, NSEvent evt)
        {
            int index = DoMouseEventToIndex(view, evt);

            NSRange range = view.selectedRange();
            if (range.length == 0 && index < view.string_().length() && view.string_()[index] == '\n')
            {
                // don't extend the selection if the user clicked off to the right side of a line
            }
            else if (index >= view.string_().length())
            {
                // don't extend the selection if the user clicked below the last line of text
                view.setSelectedRange(NSRange.Empty);
            }
            else
            {
                // Extend the selection so that it contains the entire word the user right-clicked on.
                if (range.length == 0 || !range.Intersects(index))
                {
                    range = new NSRange(index, 1);
                    range = view.selectionRangeForProposedRange_granularity(range, Enums.NSSelectByWord);
                    view.setSelectedRange(range);
                }
            }
        }
 public override bool DoCommandBySelector(NSControl control, NSTextView textView, MonoMac.ObjCRuntime.Selector commandSelector)
 {
     if (control != null && "insertNewline:".Equals(commandSelector.Name))
     {
         onEnterPressed(control);
         return true;
     }
     return false;
 }
        public IgnoreExceptionController()
            : base(NSObject.AllocAndInitInstance("IgnoreExceptionController"))
        {
            Unused.Value = NSBundle.loadNibNamed_owner(NSString.Create("ignore-exception"), this);

            Boss boss = ObjectModel.Create("Application");
            var exceptions = boss.Get<IExceptions>();

            m_text = new IBOutlet<NSTextView>(this, "text").Value;
            m_text.insertText(NSString.Create(string.Join("\n", exceptions.Ignored)));
            window().makeKeyAndOrderFront(this);
        }
        public void Show(ITextEditor editor, NSTextView text, string label, Item[] items, string stem, bool isInstance, bool isStatic)
        {
            var wind = (CompletionsWindow) window();
            NSPoint loc = editor.GetBoundingBox(text.selectedRange()).origin;
            wind.SetLoc(loc);

            m_label.Value.setStringValue(NSString.Create(label));
            m_table.Value.Open(editor, text, items, stem, m_label.Value, label);
            Log.WriteLine("AutoComplete", "took {0:0.000} secs to open the window", AutoComplete.Watch.ElapsedMilliseconds/1000.0);

            if (items.Length != 1)
                NSApplication.sharedApplication().beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo(
                    wind, text.window(), null, null, IntPtr.Zero);
        }
Beispiel #6
0
        /// <summary>
        /// Based on the user preferences set on the parent <see cref="AppKit.TextKit.Formatter.SourceTextView"/>, this
        /// method returns the available list of partial word completions.
        /// </summary>
        /// <returns>The list of word completions that will be presented to the user.</returns>
        /// <param name="textView">The source <see cref="AppKit.TextKit.Formatter.SourceTextView"/>.</param>
        /// <param name="words">A list of default words automatically provided by OS X in the user's language.</param>
        /// <param name="charRange">The cursor location where the partial word exists.</param>
        /// <param name="index">The word that should be selected when the list is displayed (usually 0 meaning
        /// the first item in the list). Pass -1 for no selected items.</param>
        public override string[] GetCompletions(NSTextView textView, string[] words, NSRange charRange, ref nint index)
        {
            List <string> completions = new List <string> ();

            // Is auto complete enabled?
            if (TextEditor.AllowAutoComplete)
            {
                // Use keywords in auto complete?
                if (TextEditor.AutoCompleteKeywords)
                {
                    // Yes, grab word being expanded
                    var range = TextEditor.Formatter.FindWordBoundries(TextEditor.TextStorage.Value, charRange);
                    var word  = TextEditor.TextStorage.Value.Substring((int)range.Location, (int)range.Length);

                    // Scan the keywords for the a possible match
                    foreach (string keyword in TextEditor.Formatter.Language.Keywords.Keys)
                    {
                        // Found?
                        if (keyword.Contains(word))
                        {
                            completions.Add(keyword);
                        }
                    }
                }

                // Use default words?
                if (TextEditor.AutoCompleteDefaultWords)
                {
                    // Only if keywords list is empty?
                    if (TextEditor.DefaultWordsOnlyIfKeywordsEmpty)
                    {
                        if (completions.Count == 0)
                        {
                            // No keywords, add defaults
                            completions.AddRange(words);
                        }
                    }
                    else
                    {
                        // No, always include default words
                        completions.AddRange(words);
                    }
                }
            }

            // Return results
            return(completions.ToArray());
        }
Beispiel #7
0
        public override bool DoCommandBySelector(NSControl control, NSTextView textView, Selector commandSelector)
        {
            switch (commandSelector.Name)
            {
            case "insertNewline:":
                if (_textBox.TryGetTarget(out var textBox) && textBox.AcceptsReturn)
                {
                    textView.InsertText((NSString)"\n");
                    return(true);
                }

                break;
            }

            return(false);
        }
 public override NSTextView FieldEditorForView(NSView aControlView)
 {
     if (editor == null)
     {
         editor = new CustomTextFieldCellEditor
         {
             Context     = this.Context,
             EventSink   = this.EventSink,
             FieldEditor = true,
             Editable    = true,
         };
         using (var key = new NSString("NSTextViewDidChangeSelectionNotification"))
             selChangeObserver = NSNotificationCenter.DefaultCenter.AddObserver(key, HandleSelectionDidChange, editor);
     }
     return(editor);
 }
        public bool DoCommandBySelector(NSControl control, NSTextView _, Selector selector)
        {
            var textField = (NSTextField)control;

            if (selector.Equals(new Selector("deleteBackward:")))
            {
                HandleDeleteBackward(textField);
                ContinueButton.Enabled = AreAllTextFieldsSet;
                return(true);
            }
            else if (selector.Equals(new Selector("insertTab:")))
            {
                return(textField.Tag >= IndexedTextFields.Count() - 1);
            }
            return(false);
        }
Beispiel #10
0
        public override void ViewDidMoveToSuperview()
        {
            // Tell the system what types of files you allow to be dragged into this view
            // In this case, we only accept TIFF formatted images
            RegisterForDraggedTypes(new string[] { NSPasteboard.NSTiffType });

            // Create a text field to show the count of items that have been drug in
            // and add it to the view
            countText = new NSTextView(new CGRect(Frame.Width / 2 - 20, 0, 100, 40));
            countText.BackgroundColor = NSColor.Green;
            countText.Selectable      = false;
            countText.Editable        = false;
            AddSubview(countText);

            // Update the current count
            UpdateDragCount();
        }
Beispiel #11
0
			// Internals

			internal bool ComboDoCommandBySelector(NSControl control, NSTextView textView, Selector selector)
			{
				switch (selector.Name)
				{
					case "insertTab:":
					case "insertBacktab:":
						SendWmKey(VirtualKeys.VK_TAB, IntPtr.Zero);
						return true;
					case "insertNewline:":
						SendWmKey(VirtualKeys.VK_RETURN, IntPtr.Zero);
						return true;
					case "cancelOperation:":
						SendWmKey(VirtualKeys.VK_ESCAPE, IntPtr.Zero);
						return true;
				}
				return false;
			}
            internal string[] TextFieldGetCompletions(NSControl control, NSTextView textView, string[] words, NSRange charRange, ref nint index)
            {
                var prefix = textView.String?.Substring(0, (int)charRange.Location + (int)charRange.Length) ?? String.Empty;

                var completions = new List <string>();

                foreach (string s in owner.auto_complete_custom_source)
                {
                    if (s.StartsWith(prefix, StringComparison.CurrentCultureIgnoreCase))
                    {
                        completions.Add(s.Substring((int)charRange.Location));
                    }
                }

                index = -1;
                return(completions.Distinct().OrderBy(x => x).ToArray());
            }
Beispiel #13
0
        public override void AwakeFromNib()
        {
            base.AwakeFromNib();

            textView = new NSTextView();
            webView  = new WebView();

            AsyncTaskRunnerController.Instance.OperationStartedEvent += (sender, e) => {
                url  = string.Empty;
                text = string.Empty;
                Update();
            };
            AsyncTaskRunnerController.GetString.CompletedEvent += (sender, e) => {
                url  = e.Uri.OriginalString;
                text = e.Text;
                Update();
            };
        }
		public override void AwakeFromNib ()
		{
			base.AwakeFromNib ();

			textView = new NSTextView ();
			webView = new WebView ();

			AsyncTaskRunnerController.Instance.OperationStartedEvent += (sender, e) => {
				url = string.Empty;
				text = string.Empty;
				Update ();
			};
			AsyncTaskRunnerController.GetString.CompletedEvent += (sender, e) => {
				url = e.Uri.OriginalString;
				text = e.Text;
				Update ();
			};
		}
Beispiel #15
0
        public override bool DoCommandBySelector(NSControl control, NSTextView textView, Selector commandSelector)
        {
            switch (commandSelector.Name)
            {
            case "moveUp:":
                OnKeyArrowUp();
                break;

            case "moveDown:":
                OnKeyArrowDown();
                break;

            default:
                return(false);
            }

            return(false);
        }
Beispiel #16
0
            public override bool DoCommandBySelector(NSTextView textView, ObjCRuntime.Selector commandSelector)
            {
                var k = KeyCode.None;

                if (commandSelector.Name == "moveUp:")
                {
                    k = KeyCode.Up;
                }
                else if (commandSelector.Name == "moveDown:")
                {
                    k = KeyCode.Down;
                }
                else if (commandSelector.Name == "insertNewline:")
                {
                    k = KeyCode.Enter;
                }
                return(viewModel.OnFormulaKeyPressed(k));
            }
            public virtual NSView CreateView()
            {
                var text = owner.Text;

                scrollView = new NSScrollView(owner.Bounds.ToCGRect());

                var contentSize = scrollView.ContentSize;

                textView = new NSTextView(new CGRect(0, 0, contentSize.Width, contentSize.Height));
                //textView.MinSize = new CGSize(MinimumSize.Width, MinimumSize.Height);
                //textView.MaxSize = new CGSize(MaximumSize.Width, MaximumSize.Height);
                textView.VerticallyResizable               = true;
                textView.HorizontallyResizable             = true;
                textView.AutoresizingMask                  = NSViewResizingMask.WidthSizable | NSViewResizingMask.HeightSizable;
                textView.TextContainer.ContainerSize       = new CGSize(contentSize.Width, float.MaxValue);
                textView.TextContainer.WidthTracksTextView = true;
                textView.RichText = owner.richtext;
                textView.ShouldUpdateTouchBarItemIdentifiers = TextViewUpdateTouchBarItemIdentifiers;

                if (NSProcessInfo.ProcessInfo.IsOperatingSystemAtLeastVersion(new NSOperatingSystemVersion(10, 12, 1)))
                {
                    textView.AutomaticTextCompletionEnabled = true;
                }

                textView.LinkClicked = TextViewLinkClicked;

                textView.TextDidChange      += TextViewTextDidChange;
                textView.DoCommandBySelector = TextViewDoCommandBySelector;
                textView.AllowsUndo(true);

                scrollView.DocumentView = textView;

                ApplyBorderStyle(owner.BorderStyle);
                ApplyForeColor(owner.ForeColor, owner.forecolor_set);
                ApplyBackColor(owner.BackColor, owner.backcolor_set);
                ApplyAlignment(owner.alignment);
                ApplyFont(owner.Font);
                ApplyScrollbars(owner.scrollbars);
                ApplyReadOnly(owner.read_only);
                ApplyEnabled(owner.Enabled);
                ApplyText(text);

                return(scrollView);
            }
Beispiel #18
0
		public override void ViewDidMoveToSuperview ()
		{
			// Tell the system what types of files you allow to be dragged into this view
			// In this case, we only accept TIFF formatted images
			RegisterForDraggedTypes (new string[] { NSPasteboard.NSTiffType });

			// Create a text field to show the count of items that have been drug in
			// and add it to the view
			countText = new NSTextView (new CGRect (Frame.Width / 2 - 20, 0, 100, 40)) {
				BackgroundColor = NSColor.Green,
				Selectable = false,
				Editable = false
			};

			AddSubview (countText);

			// Update the current count
			UpdateDragCount ();
		}
        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;
        }
Beispiel #20
0
        public void CreateWithTwoDimensionalNSViewArrayWithNullCell()
        {
            NSView [,] nSViewsTwoDim = new NSView [2, 2];
            nSViewsTwoDim [0, 0]     = new NSTextView()
            {
                Value = "0"
            };
            nSViewsTwoDim [0, 1] = new NSTextView()
            {
                Value = "1"
            };
            nSViewsTwoDim [1, 0] = new NSTextView()
            {
                Value = "2"
            };
            nSViewsTwoDim [1, 1] = null;

            Assert.Throws <ArgumentNullException> (() => NSGridView.Create(nSViewsTwoDim), "Broken Array #5");
        }
Beispiel #21
0
        public bool Run(ExceptionDialogData data)
        {
            using (var alert = new NSAlert()) {
                alert.AlertStyle = NSAlertStyle.Critical;

                var    pix = ImageService.GetPixbuf(Gtk.Stock.DialogError, Gtk.IconSize.Dialog);
                byte[] buf = pix.SaveToBuffer("tiff");
                alert.Icon = new NSImage(NSData.FromArray(buf));

                alert.MessageText     = data.Title ?? "Some Message";
                alert.InformativeText = data.Message ?? "Some Info";

                if (data.Exception != null)
                {
                    var text = new NSTextView(new RectangleF(0, 0, float.MaxValue, float.MaxValue));
                    text.HorizontallyResizable             = true;
                    text.TextContainer.ContainerSize       = new SizeF(float.MaxValue, float.MaxValue);
                    text.TextContainer.WidthTracksTextView = false;
                    text.InsertText(new NSString(data.Exception.ToString()));
                    text.Editable = false;

                    var scrollView = new NSScrollView(new RectangleF(0, 0, 450, 150))
                    {
                        HasHorizontalScroller = true,
                        DocumentView          = text,
                    };
                    ;
                    alert.AccessoryView = scrollView;
                }

                // Hack up a slightly wider than normal alert dialog. I don't know how to do this in a nicer way
                // as the min size constraints are apparently ignored.
                var frame = ((NSPanel)alert.Window).Frame;
                ((NSPanel)alert.Window).SetFrame(new RectangleF(frame.X, frame.Y, Math.Max(frame.Width, 600), frame.Height), true);

                int result = alert.RunModal() - (int)NSAlertButtonReturn.First;

                GtkQuartz.FocusWindow(data.TransientFor ?? MessageService.RootWindow);
            }

            return(true);
        }
        // -------------------------------------------------------------------------------
        //	handleTextDidChange:
        //
        //	The text in NSSearchField has changed, try to attempt type completion.
        // -------------------------------------------------------------------------------
        public void handleTextDidChange(NSNotification obj)
        {
            // As per the documentation:
            //  Use the key "NSFieldEditor" to obtain the field editor from the userInfo
            //	dictionary of the notification object
            NSTextView textView = (NSTextView)obj.UserInfo.ObjectForKey((NSString)"NSFieldEditor");

            // prevent calling "complete" too often
            if (!completePosting && !commandHandling)
            {
                completePosting = true;
                textView.Complete(null);
                completePosting = false;
            }

            if (commandHandling)
            {
                commandHandling = false;
            }
        }
		public bool Run (ExceptionDialogData data)
		{
			using (var alert = new NSAlert ()) {
				alert.AlertStyle = NSAlertStyle.Critical;
				
				var pix = ImageService.GetPixbuf (Gtk.Stock.DialogError, Gtk.IconSize.Dialog);
				byte[] buf = pix.SaveToBuffer ("tiff");
				alert.Icon = new NSImage (NSData.FromArray (buf));
				
				alert.MessageText = data.Title ?? "Some Message";
				alert.InformativeText = data.Message ?? "Some Info";

				if (data.Exception != null) {

					var text = new NSTextView (new RectangleF (0, 0, float.MaxValue, float.MaxValue));
					text.HorizontallyResizable = true;
					text.TextContainer.ContainerSize = new SizeF (float.MaxValue, float.MaxValue);
					text.TextContainer.WidthTracksTextView = false;
					text.InsertText (new NSString (data.Exception.ToString ()));
					text.Editable = false;
					
					var scrollView = new NSScrollView (new RectangleF (0, 0, 450, 150)) {
						HasHorizontalScroller = true,
						DocumentView = text,
					};
;
					alert.AccessoryView = scrollView;
				}
				
				// Hack up a slightly wider than normal alert dialog. I don't know how to do this in a nicer way
				// as the min size constraints are apparently ignored.
				var frame = ((NSPanel) alert.Window).Frame;
				((NSPanel) alert.Window).SetFrame (new RectangleF (frame.X, frame.Y, Math.Max (frame.Width, 600), frame.Height), true);
				
				int result = alert.RunModal () - (int)NSAlertButtonReturn.First;
				
				GtkQuartz.FocusWindow (data.TransientFor ?? MessageService.RootWindow);
			}
			
			return true;
		}
Beispiel #24
0
        protected override IView OnConvertToView(FigmaNode currentNode, ViewNode parentNode, ViewRenderService rendererService)
        {
            var frame = (FigmaFrame)currentNode;

            frame.TryGetNativeControlType(out var controlType);

            var scrollView = new NSScrollView();

            var textView = new NSTextView(
                new CoreGraphics.CGRect(0, 0, scrollView.ContentSize.Width, scrollView.ContentSize.Height));

            textView.Font               = NSFont.SystemFontOfSize(NSFont.SystemFontSize);
            textView.AutoresizingMask   = NSViewResizingMask.WidthSizable;
            textView.TextContainer.Size = new CoreGraphics.CGSize(scrollView.ContentSize.Width, float.MaxValue);

            var       texts = frame.children.OfType <FigmaText>();
            FigmaText text  = texts.FirstOrDefault(s => s.name == ComponentString.TEXT && s.visible);

            if (text != null)
            {
                textView.Value = rendererService.GetTranslatedText(text.characters);
                textView.Value = textView.Value.Replace("\\n", Environment.NewLine);

                // TODO: text styling
                // textView.TextStorage.Append(new Foundation.NSAttributedString(""), null);
            }

            scrollView.BorderType            = NSBorderType.LineBorder;
            scrollView.HasHorizontalScroller = false;
            scrollView.HasVerticalScroller   = true;
            scrollView.DocumentView          = textView;

            frame.TryGetNativeControlVariant(out var controlVariant);

            if (controlVariant == NativeControlVariant.Small)
            {
                textView.Font = NSFont.SystemFontOfSize(NSFont.SmallSystemFontSize);
            }

            return(new View(scrollView));
        }
Beispiel #25
0
        public bool HandleKey(NSTextView view, NSEvent evt)
        {
            bool handled = false;

            try
            {
                if (m_database != null)
                {
                    NSRange range = view.selectedRange();

                    NSString chars = evt.characters();
                    if (range.length == 0 && chars.length() == 1 && chars[0] == '.')
                    {
                        view.insertText(NSString.Create('.'));
                        Unused.Value = DoComplete(this.DoCompleteDot, view, range);
                        handled = true;
                    }
                    else if (range.length == 0 && chars.length() == 1 && chars[0] == '\t')
                    {
                        handled = DoCompleteTab(view, evt, range);
                    }

                    if (!handled)
                    {
                        var annotation = m_boss.Get<IArgsAnnotation>();
                        handled = annotation.HandleKey(view, evt);
                    }
                }
            }
            catch (Exception e)
            {
                Log.WriteLine(TraceLevel.Error, "Errors", "Autocomplete failed:");
                Log.WriteLine(TraceLevel.Error, "Errors", e.ToString());

                NSString title = NSString.Create("Auto-complete failed.");
                NSString message = NSString.Create(e.Message);
                Unused.Value = Functions.NSRunAlertPanel(title, message);
            }

            return handled;
        }
        // Allows editing directly in cell
        public override void TextDidEndEditing(NSNotification notification)
        {
            base.TextDidEndEditing(notification);
            nint row = this.SelectedRow;
            MainWindowController mwc = (MainWindowController)mainWindowController.Target;
            NSTextView           tv  = (NSTextView)notification.Object;

            if (tv.Value != "")
            {
                mwc.PhrasesTableViewSource.todoItems[(int)row] = tv.Value;
                mwc.btnAddPhrase.Enabled = false;
            }
            else
            {
                mwc.PhrasesTableViewSource.todoItems.RemoveAt((int)row);
                mwc.phrasesTableView.DeselectAll(this);
                mwc.btnAddPhrase.Enabled = true;
            }
            mwc.textField.StringValue = tv.Value;
            mwc.phrasesTableView.ReloadData();
        }
Beispiel #27
0
        public CodeEditorControlHandler()
        {
            //te = new Controls.Mac.TextEditor();
            te                  = new NSTextView();
            te.Font             = NSFont.FromFontName("Menlo", 11.0f);
            te.Editable         = true;
            te.Selectable       = true;
            te.AutoresizingMask = NSViewResizingMask.WidthSizable;
            te.MaxSize          = new CGSize(1000, 10000000);
            //te.Formatter = new LanguageFormatter(te, new PythonDescriptor());
            sv = new NSScrollView {
                AutoresizesSubviews = true, BorderType = NSBorderType.NoBorder, HasVerticalScroller = true, HasHorizontalScroller = true, AutoresizingMask = NSViewResizingMask.WidthSizable
            };
            var cv = new NSClipView {
                AutoresizesSubviews = true
            };

            cv.DocumentView = te;
            sv.ContentView  = cv;
            this.Control    = sv;
            te.BecomeFirstResponder();
        }
		/// <summary>
		/// Based on the user preferences set on the parent <see cref="AppKit.TextKit.Formatter.SourceTextView"/>, this
		/// method returns the available list of partial word completions.
		/// </summary>
		/// <returns>The list of word completions that will be presented to the user.</returns>
		/// <param name="textView">The source <see cref="AppKit.TextKit.Formatter.SourceTextView"/>.</param>
		/// <param name="words">A list of default words automatically provided by OS X in the user's language.</param>
		/// <param name="charRange">The cursor location where the partial word exists.</param>
		/// <param name="index">The word that should be selected when the list is displayed (usually 0 meaning
		/// the first item in the list). Pass -1 for no selected items.</param>
		public override string[] GetCompletions (NSTextView textView, string[] words, NSRange charRange, ref nint index)
		{
			List<string> completions = new List<string> ();

			// Is auto complete enabled?
			if (TextEditor.AllowAutoComplete) {
				// Use keywords in auto complete?
				if (TextEditor.AutoCompleteKeywords) {
					// Yes, grab word being expanded
					var range = TextEditor.Formatter.FindWordBoundries (TextEditor.TextStorage.Value, charRange);
					var word = TextEditor.TextStorage.Value.Substring ((int)range.Location, (int)range.Length);

					// Scan the keywords for the a possible match
					foreach (string keyword in TextEditor.Formatter.Language.Keywords.Keys) {
						// Found?
						if (keyword.Contains (word)) {
							completions.Add (keyword);
						}
					}
				}

				// Use default words?
				if (TextEditor.AutoCompleteDefaultWords) {
					// Only if keywords list is empty?
					if (TextEditor.DefaultWordsOnlyIfKeywordsEmpty) {
						if (completions.Count == 0) {
							// No keywords, add defaults
							completions.AddRange (words);
						}
					} else {
						// No, always include default words
						completions.AddRange (words);
					}
				}
			}

			// Return results
			return completions.ToArray();
		}
Beispiel #29
0
        public override bool DoCommandBySelector(NSControl control, NSTextView textView, Selector commandSelector)
        {
            if (ProxyResponder != null)
            {
                switch (commandSelector.Name)
                {
                case "insertTab:":
                    if (ProxyResponder.NextResponder())
                    {
                        return(true);
                    }
                    break;

                case "insertBacktab:":
                    if (ProxyResponder.PreviousResponder())
                    {
                        return(true);
                    }
                    break;
                }
            }
            return(false);
        }
Beispiel #30
0
        // replacementString should allow nulls
        public static bool ShouldChangeTextNew(this NSTextView textView, NSRange affectedCharRange, string replacementString)
        {
#if XAMMAC && NET6_0_OR_GREATER
            IntPtr intPtr = replacementString != null?CFString.CreateNative(replacementString) : IntPtr.Zero;

            bool result;
            result = Messaging.bool_objc_msgSend_NSRange_IntPtr(textView.Handle, selShouldChangeTextInRangeReplacementString_Handle, affectedCharRange, intPtr);
            if (intPtr != IntPtr.Zero)
            {
                CFString.ReleaseNative(intPtr);
            }
#else
            IntPtr intPtr = replacementString != null?NSString.CreateNative(replacementString) : IntPtr.Zero;

            bool result;
            result = Messaging.bool_objc_msgSend_NSRange_IntPtr(textView.Handle, selShouldChangeTextInRangeReplacementString_Handle, affectedCharRange, intPtr);
            if (intPtr != IntPtr.Zero)
            {
                NSString.ReleaseNative(intPtr);
            }
#endif
            return(result);
        }
Beispiel #31
0
        public ApplyStyles(TextController controller, NSTextView text)
        {
            Contract.Requires(text.textStorage().layoutManagers().count() == 1, "expected one layout not " + text.textStorage().layoutManagers().count());

            m_controller = controller;
            m_storage = text.textStorage();
            m_layout = m_storage.layoutManagers().objectAtIndex(0).To<NSLayoutManager>();

            m_current = new CurrentStyles(controller, m_storage);

            Broadcaster.Register("tab stops changed", this);
            Broadcaster.Register("selected line color changed", this);
            Broadcaster.Register("computed style runs", this);
            Broadcaster.Register("text changed", this);

            if (ms_selectedLineColor == null)
                DoSetTempAttrs();

            DoResetTabStops();
            DoApplyParagraphStyles(true);

            ActiveObjects.Add(this);
        }
Beispiel #32
0
        private void Initialize()
        {
            // Setup our contents -- a scrolling text view

            // Create a simple NSTextView.
            NSTextView tv = new NSTextView();

            tv.Font             = NSFont.UserFixedPitchFontOfSize(13);
            tv.AutoresizingMask = NSViewResizingMask.MaxYMargin |
                                  NSViewResizingMask.MinXMargin |
                                  NSViewResizingMask.WidthSizable |
                                  NSViewResizingMask.MaxXMargin |
                                  NSViewResizingMask.HeightSizable |
                                  NSViewResizingMask.MinYMargin;

            // Create a NSScrollView to which we add the NSTextView.
            NSScrollView sv = new NSScrollView();

            sv.DocumentView        = tv;
            sv.HasVerticalScroller = true;

            // Set the NSScrollView as our view.
            this.View = sv;
        }
Beispiel #33
0
        public override bool DoCommandBySelector(NSControl control, NSTextView textView, ObjCRuntime.Selector commandSelector)
        {
            if (commandSelector.Name.Equals("cancelOperation:"))      //Esc
            {
                PressedEscKey?.Invoke(control, EventArgs.Empty);
            }

            else if (commandSelector.Name.Equals("insertNewline:"))   //Enter
            {
                PressedEnterKey?.Invoke(control, EventArgs.Empty);
            }

            else if (commandSelector.Name.Equals("insertLineBreak:")) //Ctrl + Enter
            {
                return(true);
            }

            else if (commandSelector.Name.Equals("insertNewlineIgnoringFieldEditor:")) //Alt + Enter
            {
                return(true);
            }

            return(false);
        }
 public override bool DoCommandBySelector(NSTextView textView, ObjCRuntime.Selector commandSelector)
 {
     //				if (commandSelector.Name == "insertTab:") {
     //					textView.InsertText (new NSString ("    "));
     //					return true;
     //				}
     return false;
 }
        private void ReplaceText(IEnumerable<TextTag> tags, NSTextView textView)
        {
            var defaultSettings = new DefaultSettings();
            var defaultColor = _highlightSettings.Get(HighlightKeys.Default).Color;

            //textView.TextStorage.BeginEditing();
            textView.TextStorage.SetString("".CreateString(defaultColor.ToNSColor()));
            tags.Apply(tag => {
                var color = !string.IsNullOrWhiteSpace(tag.Color) ? tag.Color : defaultColor;
                var font = tag.Mono ? defaultSettings.MonoFont : defaultSettings.Font;
                textView.TextStorage.Append(tag.Text.CreateString(color.ToNSColor(), font));
            });
            //textView.TextStorage.EndEditing();
        }
Beispiel #36
0
 public TextViewWriter(SynchronizationContext context, NSTextView textView)
 {
     _context = context;
     _textView = textView;
 }
Beispiel #37
0
        public static void AllowsUndo(this NSTextView self, bool value)
        {
            var selector = new ObjCRuntime.Selector("setAllowsUndo:");

            LibObjc.void_objc_msgSend_Bool(self.Handle, selector.Handle, value);
        }
Beispiel #38
0
            public override bool DoCommandBySelector(NSControl control, NSTextView textView, MonoMac.ObjCRuntime.Selector commandSelector)
            {
                switch (commandSelector.Name)
                {
                    case "moveDown:":
                        controller.MoveSearchResult(false);
                        return true;

                    case "moveUp:":
                        controller.MoveSearchResult(true);
                        return true;

                    case "insertNewline:":
                        controller.ActivateSearchResult();
                        return true;
                }

                return false;
            }
Beispiel #39
0
        public static void SetString(this NSTextView self, NSString value)
        {
            var selector = new ObjCRuntime.Selector("setString:");

            LibObjc.void_objc_msgSend_IntPtr(self.Handle, selector.Handle, value.Handle);
        }
        private void Append(TextTag tag, NSTextView textView)
        {
            var text = tag.Text.Replace("&lt;", "<").Replace("&gt;", ">");

            var defaultSettings = new DefaultSettings();

            var defaultColor = _highlightSettings.Get(HighlightKeys.Default).Color;

            var color = !string.IsNullOrWhiteSpace(tag.Color) ? tag.Color : defaultColor;
            var font = tag.Mono ? defaultSettings.MonoFont : defaultSettings.Font;

            var scroll = textView.EnclosingScrollView.VerticalScroller.FloatValue == 1.0f;

            //textView.TextStorage.BeginEditing();
            textView.TextStorage.Append(text.CreateString(color.ToNSColor(), font));
            //textView.TextStorage.EndEditing();

            if(scroll)
                textView.ScrollRangeToVisible(new NSRange(textView.Value.Length, 0));
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="AppKit.TextKit.Formatter.LanguageFormatter"/> class.
		/// </summary>
		/// <param name="textEditor">The <c>NSTextView</c> that this language formatter will syntax highlight.</param>
		/// <param name="language">The <see cref="AppKit.TextKit.Formatter.LanguageDescriptor"/> defining the 
		/// language syntax highlighting rules.</param>
		public LanguageFormatter (NSTextView textEditor, LanguageDescriptor language)
		{
			// initialize
			this.TextEditor = textEditor;
			this.Language = language;
		}
 public void SetUp()
 {
     textView       = new NSTextView(new CGRect(0, 0, 37, 120));
     textView.Value = "This is a new string";
     Assert.AreEqual(textView.Value, "This is a new string", "NSTextInputClientSetup - Failed to set value");
 }
        public NSArray ControlTextViewCompletionsForPartialWordRangeIndexOfSelectedItem(NSControl control, NSTextView textView, NSArray words, NSRange charRange, ref int index)
        {
            NSMutableArray matches;
            NSString partialString;
            NSArray keywords;
            int i;
            uint count;
            NSString str;

            partialString = textView.String.SubstringWithRange(charRange);
            keywords = this.AllKeywords();
            count = keywords.Count;
            matches = new NSMutableArray();

            // find any match in our keyword array against what was typed
            for (i = 0; i < count; i++)
            {
                str = keywords[i].CastTo<NSString>();
                if (str.RangeOfStringOptionsRange(partialString, NSStringCompareOptions.NSAnchoredSearch | NSStringCompareOptions.NSCaseInsensitiveSearch, NSRange.NSMakeRange(0, str.Length)).location != NSUInteger.NSNotFound)
                {
                    matches.AddObject(str);
                }
            }
            matches.SortUsingSelector(ObjectiveCRuntime.Selector("compare:"));

            return matches;
        }
Beispiel #44
0
 public override NSUndoManager GetUndoManager(NSTextView view)
 {
     return(UndoManager);
 }
Beispiel #45
0
        internal override void HandleLinkClicked(NSTextView textView, NSObject link, nuint charIndex)
        {
            var e = new LinkClickedEventArgs(link.ToString());

            OnLinkClicked(e);
        }
		// -------------------------------------------------------------------------------
		//	control:textView:completions:forPartialWordRange:indexOfSelectedItem:
		//
		//	Use this method to override NSFieldEditor's default matches (which is a much bigger
		//	list of keywords).  By not implementing this method, you will then get back
		//	NSSearchField's default feature.
		// -------------------------------------------------------------------------------		
		//public string[] FilterCompletions (NSControl control, NSTextView textView, string [] words, NSRange charRange, int index)
		string[] handleFilterCompletions (NSControl control, NSTextView textView, string[] words, NSRange charRange, int index) 
		{
			
			var partialString = textView.Value;
			List<string> matches = new List<string> ();

			if (partialString.Length > 0) {
				// find any match in our keyword array against what was typed -
				matches = (from c in builtInKeywords
					where c.StartsWith (partialString, StringComparison.OrdinalIgnoreCase)
					orderby c select c).ToList ();
			}

			return matches.ToArray();

		}
Beispiel #47
0
 public override string[] GetCompletions(NSControl control, NSTextView text_view,
     string [] a, MonoMac.Foundation.NSRange range, int b)
 {
     return new string [0];
 }
Beispiel #48
0
        public void Init(ITextEditor editor, NSTextView text, LiveRange range, AnnotationAlignment alignment)
        {
            m_editor = editor;
            m_text = text;
            m_range = range;
            m_view = this["view"].To<AnnotateView>();
            m_alignment = alignment;

            m_parent = m_text.window();

            NSNotificationCenter.defaultCenter().addObserver_selector_name_object(
                this, "parentWillClose:", Externs.NSWindowWillCloseNotification, m_parent);

            m_text.superview().setPostsBoundsChangedNotifications(true);
            NSNotificationCenter.defaultCenter().addObserver_selector_name_object(
                this, "parentBoundsChanged:", Externs.NSViewBoundsDidChangeNotification, m_text.superview());

            m_range.Changed += this.DoRangeChanged;
        }
        private void LogRoom(string text, NSTextView textView)
        {
            var defaultSettings = new DefaultSettings();
            var defaultColor = _highlightSettings.Get(HighlightKeys.Default).Color;

            //textView.TextStorage.BeginEditing();
            textView.TextStorage.SetString("".CreateString(defaultColor.ToNSColor(), defaultSettings.Font));
            //textView.TextStorage.EndEditing();

            var highlights = _services.Get<Highlights>();
            highlights.For(TextTag.For(text)).Apply(t => Append(t, textView));
        }
 public bool ControlTextViewDoCommandBySelector(NSControl control, NSTextView textView, IntPtr commandSelector)
 {
     if (textView.RespondsToSelector(commandSelector))
     {
         this.commandHandling = true;
         textView.PerformSelectorWithObject(commandSelector, null);
         this.commandHandling = false;
     }
     return true;
 }
 // This prevents crash caused by the default xamarin's delegate that returns null.
 internal string[] TextViewUpdateTouchBarItemIdentifiers(NSTextView textView, string[] identifiers)
 {
     return(identifiers);
 }
		// -------------------------------------------------------------------------------
		//	handleCommandSelectors
		//
		//	Handle all command selectors that we can handle here
		// -------------------------------------------------------------------------------		
		private bool handleCommandSelectors(NSControl control, NSTextView textView, Selector commandSelector)
		{
			
			bool result = false;
			
			if (textView.RespondsToSelector (commandSelector)){
				commandHandling = true;
				textView.PerformSelector (commandSelector,null,-1);
				//commandHandling = false;
				result = true;
			}
			
			return result;
			
		}
 internal virtual bool TextViewLinkClicked(NSTextView textView, NSObject link, nuint charIndex)
 {
     owner.HandleLinkClicked(textView, link, charIndex);
     return(true);
 }
        private void DoComplete(bool onlyTypedText, int row)
        {
            if (row >= 0)
            {
                int firstIndex = m_text.selectedRange().location;
                string text = DoGetInsertText(row, onlyTypedText);

                if (m_stem != null)
                {
                    // If we have a stem then we also have the first tab so we need to do a replace
                    // instead of an insert.
                    NSRange range = new NSRange(firstIndex - 1, 1);
                    string name = m_stem.Length > 0 ? string.Format(" {0}{1}{2}", Constants.LeftDoubleQuote, m_stem, Constants.RightDoubleQuote) : string.Empty;
                    var suffix = NSString.Create(text.Substring(m_stem.Length));

                    m_text.shouldChangeTextInRange_replacementString(range, suffix);
                    m_text.undoManager().setActionName(NSString.Create("Complete" + name));
                    m_text.replaceCharactersInRange_withString(range, suffix);
                    m_text.didChangeText();

                    firstIndex -= m_stem.Length + 1;
                }
                else
                {
                    NSAttributedString str = NSAttributedString.Create(text);
                    m_text.shouldChangeTextInRange_replacementString(new NSRange(firstIndex, 0), str.string_());
                    m_text.undoManager().setActionName(NSString.Create("Complete"));
                    m_text.textStorage().insertAttributedString_atIndex(str, (uint) firstIndex);
                    m_text.didChangeText();
                }

                m_text = null;
                if (window().isVisible())
                    window().windowController().Call("hide");

                MethodItem method = m_items[row] as MethodItem;
                bool annotate = method != null && (method.Arity > 0 || method.GetArgumentRange(-1).length > 0);
                if (!onlyTypedText && annotate)
                {
                    NSRange range = new NSRange(firstIndex, text.Length);
                    ITextAnnotation annotation = m_editor.GetAnnotation(range, AnnotationAlignment.Bottom);

                    IArgsAnnotation args = m_editor.Boss.Get<IArgsAnnotation>();
                    string name = method.Name;
                    var methods = (from m in m_items where m is MethodItem && m.Text.StartsWith(name) select (MethodItem) m).ToArray();
                    int j = Array.FindIndex(methods, m => m.Text == m_items[row].Text);
                    args.Open(annotation, methods, j);
                }
            }
            else
                Functions.NSBeep();
        }
		/// <summary>
		/// Called when the cell is dragged.
		/// </summary>
		/// <param name="textView">The <see cref="AppKit.TextKit.Formatter.SourceTextView"/>.</param>
		/// <param name="cell">The cell being acted upon.</param>
		/// <param name="cellFrame">The onscreen frame of the cell.</param>
		/// <param name="theevent">An event defining the drag operation.</param>
		/// <remarks>
		/// Because a custom <c>Delegate</c> has been attached to the <c>NSTextView</c>, the normal events
		/// will not work so we are using this method to call custom <see cref="AppKit.TextKit.Formatter.SourceTextView"/>
		/// events instead.
		/// </remarks>
		public override void DraggedCell (NSTextView view, NSTextAttachmentCell cell, CGRect rect, NSEvent theevent)
		{
			// Pass through to Text Editor event
			TextEditor.RaiseSourceCellDragged(TextEditor, new NSTextViewDraggedCellEventArgs(cell, rect, theevent));
		}
Beispiel #56
0
        public static bool AllowsUndo(this NSTextView self)
        {
            var selector = new ObjCRuntime.Selector("allowsUndo");

            return(LibObjc.bool_objc_msgSend(self.Handle, selector.Handle));
        }
		/// <summary>
		/// Called when the cell is clicked.
		/// </summary>
		/// <param name="textView">The <see cref="AppKit.TextKit.Formatter.SourceTextView"/>.</param>
		/// <param name="cell">The cell being acted upon.</param>
		/// <param name="cellFrame">The onscreen frame of the cell.</param>
		/// <param name="charIndex">The index of the character clicked.</param>
		/// <remarks>
		/// Because a custom <c>Delegate</c> has been attached to the <c>NSTextView</c>, the normal events
		/// will not work so we are using this method to call custom <see cref="AppKit.TextKit.Formatter.SourceTextView"/>
		/// events instead.
		/// </remarks>
		public override void CellClicked (NSTextView textView, NSTextAttachmentCell cell, CGRect cellFrame, nuint charIndex)
		{
			// Pass through to Text Editor event
			TextEditor.RaiseSourceCellClicked(TextEditor, new NSTextViewClickedEventArgs(cell, cellFrame, charIndex));
		}
Beispiel #58
0
 internal virtual void HandleLinkClicked(NSTextView textView, NSObject link, nuint charIndex)
 {
 }
 public TextViewWrapper(NSTextView textView, HighlightSettings highlightSettings)
 {
     _textView = textView;
     _highlightSettings = highlightSettings;
 }
Beispiel #60
-1
        public new void keyDown(NSEvent evt)
        {
            NSString chars = evt.characters();

            // TODO: Would be nice to also complete for '.' and ','. This should insert
            // the punctuation and, for '.', start a new completion.
            if (chars.Equals("\t") || chars.Equals("\r") || chars.Equals(" ") || chars.Equals("("))
            {
                DoComplete(false, selectedRow());
            }
            else if (evt.keyCode() == Constants.EnterKey)
            {
                DoComplete(true, selectedRow());
            }
            else if (chars.Equals(Constants.Escape))
            {
                m_text = null;
                window().windowController().Call("hide");
            }
            else if (chars.length() == 1 && (char.IsLetterOrDigit(chars[0]) || chars[0] == '_'))
            {
                m_completed += chars[0];
                int count = DoMatchName();
                if (count > 0)
                {
                    reloadData();
                }
                else if (m_completed.Length == 1)
                {
                    // It's rather confusing to have completed text without any indication
                    // that there is completed text so if the user's completed text is completely
                    // bogus we'll reset it.
                    m_completed = string.Empty;
                }
            }
            else if (chars.Equals(Constants.Delete))
            {
                if (m_completed.Length > 0)
                {
                    m_completed = m_completed.Remove(m_completed.Length - 1);
                    DoMatchName();
                    reloadData();
                }
                else
                    Functions.NSBeep();
            }
            else if (chars.length() == 1 && chars[0] == ' ')
            {
                DoMatchName();		// just select the best match
            }
            else
            {
                Unused.Value = SuperCall(NSTableView.Class, "keyDown:", evt);
            }
        }