text_input.h (4066B)
1 /* 2 This file is part of GNUnet. 3 Copyright (C) 2022 GNUnet e.V. 4 5 GNUnet is free software: you can redistribute it and/or modify it 6 under the terms of the GNU Affero General Public License as published 7 by the Free Software Foundation, either version 3 of the License, 8 or (at your option) any later version. 9 10 GNUnet is distributed in the hope that it will be useful, but 11 WITHOUT ANY WARRANTY; without even the implied warranty of 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 Affero General Public License for more details. 14 15 You should have received a copy of the GNU Affero General Public License 16 along with this program. If not, see <http://www.gnu.org/licenses/>. 17 18 SPDX-License-Identifier: AGPL3.0-or-later 19 */ 20 /* 21 * @author Tobias Frisch 22 * @file ui/text_input.h 23 */ 24 25 #ifndef UI_TEXT_INPUT_H_ 26 #define UI_TEXT_INPUT_H_ 27 28 #include <ctype.h> 29 30 /** 31 * Handles the key event to move the cursor 32 * and adjust the content of text controls. 33 */ 34 #define text_input_event(text, key) { \ 35 switch (key) \ 36 { \ 37 case KEY_LEFT: \ 38 { \ 39 text##_pos--; \ 40 break; \ 41 } \ 42 case KEY_RIGHT: \ 43 { \ 44 text##_pos++; \ 45 break; \ 46 } \ 47 case KEY_BACKSPACE: \ 48 { \ 49 if ((text##_pos < text##_len) && (text##_pos > 0)) \ 50 for (int i = text##_pos; i < text##_len; i++) \ 51 text[i - 1] = text[i]; \ 52 \ 53 if ((text##_pos > 0) && (text##_len > 0)) \ 54 { \ 55 text##_pos--; \ 56 text##_len--; \ 57 } \ 58 \ 59 break; \ 60 } \ 61 default: \ 62 { \ 63 if (!isprint(key)) \ 64 break; \ 65 \ 66 for (int i = text##_len - 1; i >= text##_pos; i--) \ 67 text[i + 1] = text[i]; \ 68 \ 69 text[text##_pos++] = (char) key; \ 70 text##_len++; \ 71 break; \ 72 } \ 73 } \ 74 \ 75 int max_len = (int) sizeof(text) - 1; \ 76 \ 77 if (text##_len > max_len) \ 78 text##_len = max_len; \ 79 \ 80 text[text##_len] = '\0'; \ 81 \ 82 if (text##_pos < 0) \ 83 text##_pos = 0; \ 84 \ 85 if (text##_pos > text##_len) \ 86 text##_pos = text##_len; \ 87 } 88 89 #endif /* UI_TEXT_INPUT_H_ */