Skip to content

Commit

Permalink
feat: set caret position #120
Browse files Browse the repository at this point in the history
  • Loading branch information
mopsicus committed Dec 10, 2024
1 parent 47726eb commit ba206ba
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 6 deletions.
25 changes: 23 additions & 2 deletions Android~/plugin/src/main/java/com/mopsicus/umi/MobileInput.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public class MobileInput {
private static final String SET_PTEXT_COLOR = "SET_PTEXT_COLOR";
private static final String SET_BG_COLOR = "SET_BG_COLOR";
private static final String SET_READ_ONLY = "SET_READ_ONLY";
private static final String SET_CARET = "SET_CARET";
private static final String SET_RECT = "SET_RECT";
private static final String SET_FOCUS = "SET_FOCUS";
private static final String ON_FOCUS = "ON_FOCUS";
Expand Down Expand Up @@ -183,6 +184,10 @@ private void processData(JSONObject data) {
case SET_BG_COLOR:
edit.setBackgroundColor(this.getColor(data));
break;
case SET_CARET:
Integer position = data.getInt("value");
this.setCaret(position);
break;
case SET_READ_ONLY:
boolean value = data.getBoolean("value");
edit.setInputType(value ? EditorInfo.TYPE_NULL : editInputType);
Expand All @@ -207,7 +212,7 @@ private void processData(JSONObject data) {
break;
case SET_LANGUAGE:
String code = data.getString("value");
setKeyboardLanguage(code);
this.setKeyboardLanguage(code);
break;
case ANDROID_KEY_DOWN:
String strKey = data.getString("key");
Expand Down Expand Up @@ -446,7 +451,7 @@ private void Create(int id, JSONObject data) {
}
sendData(editData);
}
SetFocus(isFocus);
this.SetFocus(isFocus);
JSONObject focusData = new JSONObject();
try {
focusData.put("msg", (isFocus) ? ON_FOCUS : ON_UNFOCUS);
Expand Down Expand Up @@ -640,6 +645,21 @@ private void setKeyboardLanguage(String languageCode) {
imm.restartInput(edit);
}

/**
* Set caret position
*
* @param position Position in string
*/
private void setCaret(Integer position) {
int length = edit.getText().length();
if (position < 0) {
position = 0;
} else if (position > length) {
position = length;
}
edit.setSelection(position, position);
}

/**
* Remove MobileInput
*/
Expand All @@ -658,6 +678,7 @@ private void Remove() {
private void SetText(String newText) {
if (edit != null) {
edit.setText(newText);
edit.setSelection(edit.getText().length());
}
}

Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

All notable changes to this project will be documented in this file.

## [2.0.5] - 2024-12-10
- ### Added
- Set caret position

## [2.0.4] - 2024-09-10
- ### Added
- Change keyboard language
Expand Down
5 changes: 5 additions & 0 deletions Documentation~/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ public class Bootstrap : MonoBehaviour {
}
```

> [!IMPORTANT]
> UMI will not work with the **Render Over Native UI** option enabled.
### MobileInput.cs

This script manages the interaction between the Unity app and native part. It contains references and identifiers of all MobileInputField scripts and some additional functions.
Expand Down Expand Up @@ -101,6 +104,8 @@ This is the basic script for using UMI. Add this script to a game object with `T

`SetLanguage(string value)` – change keyboard language

`SetCaret` – set caret position

`SetRect(RectTransform inputRect)` – set new field size and position, this is useful if you want to move or resize the input field manually, at other times this is done automatically using the game object parameters

`SetContentType(InputContentType type)` – set content type to field
Expand Down
Binary file modified Plugins/Android/Mobileinput.aar
Binary file not shown.
15 changes: 15 additions & 0 deletions Plugins/iOS/MobileInput.mm
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#define CREATE @"CREATE_EDIT"
#define REMOVE @"REMOVE_EDIT"
#define SET_TEXT @"SET_TEXT"
#define SET_CARET @"SET_CARET"
#define SET_CONTENT_TYPE @"SET_CONTENT_TYPE"
#define SET_TEXT_COLOR @"SET_TEXT_COLOR"
#define SET_PTEXT_COLOR @"SET_PTEXT_COLOR"
Expand Down Expand Up @@ -465,6 +466,20 @@ - (void)processData:(NSDictionary *)data {
} else {
[(UITextField *)editView setTextColor:color];
}
} else if ([msg isEqualToString:SET_CARET]) {
int position = [[data valueForKey:@"value"] intValue];
NSInteger length = (isMultiline) ? [(PlaceholderTextView *)editView text].length : [(UITextField *)editView text].length;
if (position < 0) {
position = 0;
} else if (position > length) {
position = (int)length;
}
if (isMultiline) {
[(PlaceholderTextView *)editView setSelectedRange: NSMakeRange(position, 0)];
} else {
UITextPosition *tpos = [(UITextField *)editView positionFromPosition:[(UITextField *)editView beginningOfDocument] offset:position];
[(UITextField *)editView setSelectedTextRange: [(UITextField *)editView textRangeFromPosition:tpos toPosition:tpos]];
}
} else if ([msg isEqualToString:SET_PTEXT_COLOR]) {
UIColor *color = [self getColor:data];
if (isMultiline) {
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ public class Bootstrap : MonoBehaviour {
> [!NOTE]
> Make sure you do this before creating all input fields, otherwise UMI will raise an exception.
> [!IMPORTANT]
> UMI will not work with the **Render Over Native UI** option enabled.
### Setup

To begin using UMI in your project, add `MobileInputField` script to game object with `TMP Input field`.
Expand Down Expand Up @@ -142,6 +145,7 @@ With `OnKeyboardAction` you can control UI elements, such as moving the input fi
- `SetContentType` – change input field content type
- `SetReadonly` – change readonly mode
- `SetLanguage` – change keyboard language
- `SetCaret` – set caret position

### How to use custom fonts

Expand Down
4 changes: 4 additions & 0 deletions README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ public class Bootstrap : MonoBehaviour {
> [!NOTE]
> Убедитесь что вы сделали это до создания и появления всех полей ввода, иначе UMI выдаст ошибку.
> [!IMPORTANT]
> UMI не будет работать с включенной опцией **Render Over Native UI**.
### Настройка

Для начала использования UMI в вашем проекте, добавьте скрипт `MobileInputField` на объект с полем ввода `TMP Input field`.
Expand Down Expand Up @@ -141,6 +144,7 @@ public class Bootstrap : MonoBehaviour {
- `SetContentType` – изменение типа поля ввода
- `SetReadonly` – изменение состояния "только для чтения"
- `SetLanguage` – изменение языка клавиатуры
- `SetCaret` – установка позиции курсора

### Как использовать свои шрифты

Expand Down
27 changes: 23 additions & 4 deletions Runtime/MobileInputField.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@ public enum ReturnKeyType {
/// </summary>
const string SET_LANGUAGE = "SET_LANGUAGE";

/// <summary>
/// Set caret position
/// </summary>
const string SET_CARET = "SET_CARET";

/// <summary>
/// Event when text changing in InputField
/// </summary>
Expand Down Expand Up @@ -173,7 +178,7 @@ public enum ReturnKeyType {
/// <summary>
/// Custom keyboard language, ISO code
/// </summary>
public string KeyboardLanguage = "default";
public string KeyboardLanguage = "default";

/// <summary>
/// Background color
Expand Down Expand Up @@ -382,7 +387,7 @@ IEnumerator InitProcess() {
if (_initStarted) {
yield break;
}
_initStarted = true;
_initStarted = true;
yield return WaitForEndOfFrame;
PrepareNativeEdit();
#if (UNITY_IOS || UNITY_ANDROID) && !UNITY_EDITOR
Expand Down Expand Up @@ -416,6 +421,9 @@ void Update() {
var inputRect = this._inputObjectText.rectTransform.rect;
for (var i = 0; i < touchCount; i++) {
if (!inputRect.Contains(Input.touches[i].position)) {
#if UMI_DEBUG
Debug.Log($"[UMI] manual hide control: {IsManualHideControl}");
#endif
if (!IsManualHideControl) {
Hide();
}
Expand Down Expand Up @@ -610,7 +618,7 @@ void CreateNativeEdit() {
ReturnKeyType.Search => (JsonNode)"Search",
ReturnKeyType.Send => (JsonNode)"Send",
_ => (JsonNode)"Default",
};
};
Execute(data);
}
#endif
Expand Down Expand Up @@ -701,7 +709,18 @@ public void SetLanguage(string value) {
data["msg"] = SET_LANGUAGE;
data["value"] = value;
Execute(data);
}
}

/// <summary>
/// Set caret position
/// </summary>
/// <param name="value">Position in string</param>
public void SetCaret(int value) {
var data = new JsonObject();
data["msg"] = SET_CARET;
data["value"] = value;
Execute(data);
}

/// <summary>
/// Set text to field
Expand Down

0 comments on commit ba206ba

Please sign in to comment.