How to trap a PASTE in a TEXT widget - swt

I have a TEXT entry field. I want to limit the entry to letters or digits. Other characters should be converted to an under-score. The following code does this. However when the user pastes into the field, it bypasses the listener and the raw text is put into the field
private class TextKeyVerifyListener implements VerifyListener
{
#Override
public void verifyText( VerifyEvent event )
{
if (Character.isLetterOrDigit( event.character ))
event.text = "" + Character.toUpperCase( event.character );
else if (!Character.isISOControl( event.keyCode ))
event.text = "_";
}
}
How do I trap the paste action so at least I can re-parse the text field. It seems kind of heavy duty to do this in the modify listener for each keystroke. Any solution should be cross-platform :-)
Trapping for CTRL-V might do this, but the user can also use the pop menu and choose paste.

VerifyEvent has a text field containing all the text to be verified. You should be using this rather than the character field. text is set to the full pasted text.

Ok, for anyone else trying to do this:
if (event.keyCode == 0 || !Character.isISOControl( event.keyCode ))
{
StringBuilder text = new StringBuilder();
char[] chars = event.text.toCharArray();
for (char character : chars)
if (Character.isLetterOrDigit( character ))
text.append( Character.toUpperCase( character ) );
else
text.append( "_" ); //$NON-NLS-1$
event.text = text.toString();
}
It's a little heavy for single keystrokes, but it will convert as I wanted.
Thanks!

Related

How can I get text value of TMPro Text without markup tags in Unity?

I am trying to get text value in TMPro Text component without markup tags but haven't found any solutions.
Say, <b><color=red>Hello </color><b> world is the value in TMPro Text, and I just want Hello world in c# script.
Bear in mind that tag <b> and color will change, so I would love to remove tags dynamically, meaning I would like not to replacing each tag by text.replace("<b>", "") kind of things.
Does anyone know how to do it?
I dont know about the option of using HTML on tmp but you can attach the text to your script by create a new variable like that:
[SerializeField] TMP_Text textVar;
then you can drag you tmp game object to the component that include this script
and the you can change the text like that:
textVar.text = "what ever";
or get text like that:
string textString = textVar.text;
for the color you can use
Color color = textVar.color;
You can use TMP_Text.GetParsedText () to get the text after it has been parsed and rich text tags removed.
Alternatively you can also use regular expressions to search a string for rich text tags, and remove them while preserving the rest of the string.
using System.Text.RegularExpressions;
public static string GetString (string str)
{
Regex rich = new Regex (#"<[^>]*>");
if (rich.IsMatch (str))
{
str = rich.Replace (str, string.Empty);
}
return str;
}

How to get text input continuously in Unity C#?

I'm going to get text input using TextField and the following is my code:
public Text textInput;
void Update()
{
if (Input.GetKeyDown(KeyCode.Return)) {
if (textInput.text == "go") {
/* do something */
textInput.text = "";
}
}
}
I assigned the Text element under TextField to public Text textInput, and I expected that once a player types "go" and presses enter, the TextField will be cleared and the player be able to type next sentence.
However, after I type "go" and press enter, the text in TextField remained and the focus was out.
How can I clear the TextField maintaining the focus on it?
I think the "problem" is that the input field by default also handles the Return key as the submission command which automatically loses the focus.
The default InputField.lineType is
SingleLine
Only allows 1 line to be entered. Has horizontal scrolling and no word wrap. Pressing enter will submit the InputField.
You could instead set it to MultiLineNewLine
Is a multiline InputField with vertical scrolling and overflow. Pressing the return key will insert a new line character.
So it doesn't automatically call the OnSubmit and lose focus when pressing the Return key.
Using that as an alternative to use Update and GetKeyDown you could use InputField.onValidateInput and do something like
public InputField textInput;
private void Awake ()
{
textInput.lineType = InputField.LineType.MultiLineNewLine;
textInput.onValidateInput = OnValidate;
}
private char OnValidate(string text, int charIndex, char addedChar)
{
if(addedChar == '\n')
{
if(text.Equals("go"))
{
// Do something
}
textInput.text = "";
return '';
}
return addedChar;
}

How to get character entered on Keydown Event in WPF C#

i'm using wpf c# in visual studio
i want to prevent user can enter Arabic character , Just Persian Character
like when user entered this value on keyboard → "ي" change it to "ی"
my means something like this :
when user press button to type "A" on keyboard i want to change this character, first check if is "A" change to "B"
i did it in Windows Form Application , but that code does not work in WPF
My Code in Windows From :
if (e.KeyChar.ToString() == "ي")
{
e.KeyChar = Convert.ToChar("ی");
}
My Code in WPF :
if (e.Key.ToString() == "ي")
{
e.Key.ToString("ی");
}
These codes not working in WPF
Please Help
It's a bit different in WPF.
This works using a english keyboard. Don't know if it will work with Arabic, as the rules might be a little different for inserting characters.
You can try handling the PreviewTextInput event of the TextBox.
XAML:
<TextBox PreviewTextInput="TextBox_OnTextInput" ...
Code:
private void TextBox_OnTextInput(object sender, TextCompositionEventArgs e)
{
var box = (sender as TextBox);
var text = box.Text;
var caret = box.CaretIndex;
if (e.TextComposition.Text == "ي")
{
var newValue = "ی";
//Update the TextBox' text..
box.Text = text.Insert(caret, newValue);
//..move the caret accordingly..
box.CaretIndex = caret + newValue.Length;
//..and make sure the keystroke isn't handled again by the TextBox itself:
e.Handled = true;
}
}

Inserting text following selection in Office-JS

I am trying to append a hyperlink immediately following a piece of selected text in Word 2013 using the Shared JS API.
Inserting the hyperlink using OOXML works fine when inserting at current cursor with no selection. My problem is 'finding' the end of the selected text to append the OOXML.
Just using setSelectedDataAsync overwrites the existing text. I have tried reading the selected text as OOXML and concatenating the hyperlink XML to it but without success.
I have not tried reading the current selection and then modifying that OOXML but would prefer to avoid.
In the Word JS API a before and after are provided on the selection so it is straightforward to do. Is it possible to do this in the Shared API? Thanks.
The following code sample illustrates the approach that Marc described in his comment above (with one exception: it gets the selected data as Text, not as HTML).
This snippet uses getSelectedDataAsync to get the selected data (as Text), and then appends a hyperlink to that data and uses setSelectedDataAsync to push that string back into the document (as HTML).
Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
{ valueFormat: "unformatted" },
function (asyncResult) {
var error = asyncResult.error;
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log(error.name + ": " + error.message);
}
else {
// Get selected data.
var dataValue = asyncResult.value;
console.log("Selected data is: " + dataValue);
// Create newText by appending hyperlink to dataValue.
var myHyperlink = "<a href='https://www.bing.com'>https://www.bing.com</a>";
var newText = dataValue + " " + myHyperlink;
console.log("New text is: " + newText);
// Replace selected text with newText value.
Office.context.document.setSelectedDataAsync(newText, { coercionType: "html" },
function (asyncResult) {
var error = asyncResult.error;
if (asyncResult.status === Office.AsyncResultStatus.Failed) {
console.log(error.name + ": " + error.message);
}
});
}
});
Note: One side-effect of getting the selected data as Text, as this snippet does, is that when you write back that string (with the hyperlink appended) to the document, you'll lose any formatting (for example: font color, style, etc.) that was previously present in the selected text. If it's important that you preserve formatting of the originally selected text, you'll need to get the selected data as HTML and then append your hyperlink to the the portion of HTML which contains the originally selected text, before writing that HTML back to the document.
You can quickly and easily try this code snippet yourself in Word by using Script Lab (https://aka.ms/getscriptlab). Simply install the Script Lab add-in (free), then choose "Import" in the navigation menu, and use the following GIST URL: https://gist.github.com/kbrandl/8e235fb0ccc190bf42ed9ce1874f5559.

iTextSharp trims leading space and causes misalignment of columns

When moving from the versions 4.1.2 => 5.1.3 of iTextSharp I have come across a bug that happens when generating a PDF from text. The problem is that when the first character of a line has a leading spaces then that leading space gets truncated. This is a problem with a right justified columns.
Example: (dashes= spaces)
Input:
------Header
--------------1
--------------2
0123456789
Output:
-----Header
-------------1
-------------2
0123456789 ~~~Notice improper alignment because this column did not have leading space!
The problematic code has been narrowed down to the file "iTextSharp/text/pdf/PdfChunck.cs" method "TrimFirstSpace".
This method is called from the PdfDocument class while streaming out the bytes. The problem is that there is no code comments as to what this method trying to be accomplish.
What should I change to make this work right? It seems like commenting out the ELSE condition in here should fix this.
public float TrimFirstSpace()
{
BaseFont ft = font.Font;
if (ft.FontType == BaseFont.FONT_TYPE_CJK && ft.GetUnicodeEquivalent(' ') != ' ')
{
if (value.Length > 1 && value.StartsWith("\u0001"))
{
value = value.Substring(1);
return font.Width('\u0001');
}
}
else
{
if (value.Length > 1 && value.StartsWith(" "))
{
value = value.Substring(1);
return font.Width(' ');
}
}
return 0;
}
Newer code changes address the issue. The if statement is important.
OLD
chunk = overflow;
chunk.TrimFirstSpace();
New
bool newlineSplit = chunk.IsNewlineSplit();
chunk = overflow;
if (!newlineSplit)
chunk.TrimFirstSpace();
http://sourceforge.net/p/itextsharp/code/518/tree/trunk/src/core/iTextSharp/text/pdf/PdfDocument.cs#l415