2 Copyright (C) 1997-2018 Sam Lantinga <slouken@libsdl.org>
4 This software is provided 'as-is', without any express or implied
5 warranty. In no event will the authors be held liable for any damages
6 arising from the use of this software.
8 Permission is granted to anyone to use this software for any purpose,
9 including commercial applications, and to alter it and redistribute it
12 /* A simple program to test the Input Method support in the SDL library (2.0+)
13 If you build without SDL_ttf, you can use the GNU Unifont hex file instead.
14 Download at http://unifoundry.com/unifont.html */
25 #include "SDL_test_common.h"
26 #define WINDOW_WIDTH 720
27 #define WINDOW_HEIGHT 1280
29 #define DEFAULT_PTSIZE 30
32 #define DEFAULT_FONT "/System/Library/Fonts/华文细黑.ttf"
34 /* Some japanese font present on at least Windows 8.1. */
35 #define DEFAULT_FONT "C:\\Windows\\Fonts\\yugothic.ttf"
37 #define DEFAULT_FONT "NoDefaultFont.ttf"
40 #define DEFAULT_FONT "unifont-9.0.02.hex"
42 #define MAX_TEXT_LENGTH 256
44 static SDLTest_CommonState *state;
45 static SDL_Rect textRect, markedRect;
46 static SDL_Color lineColor = {0,0,0,255};
47 static SDL_Color backColor = {255,255,255,255};
48 static SDL_Color textColor = {0,0,0,255};
49 static char text[MAX_TEXT_LENGTH], markedText[SDL_TEXTEDITINGEVENT_TEXT_SIZE];
50 static int cursor = 0;
52 static TTF_Font *font;
54 #define UNIFONT_MAX_CODEPOINT 0x1ffff
55 #define UNIFONT_NUM_GLYPHS 0x20000
56 /* Using 512x512 textures that are supported everywhere. */
57 #define UNIFONT_TEXTURE_WIDTH 512
58 #define UNIFONT_GLYPHS_IN_ROW (UNIFONT_TEXTURE_WIDTH / 16)
59 #define UNIFONT_GLYPHS_IN_TEXTURE (UNIFONT_GLYPHS_IN_ROW * UNIFONT_GLYPHS_IN_ROW)
60 #define UNIFONT_NUM_TEXTURES ((UNIFONT_NUM_GLYPHS + UNIFONT_GLYPHS_IN_TEXTURE - 1) / UNIFONT_GLYPHS_IN_TEXTURE)
61 #define UNIFONT_TEXTURE_SIZE (UNIFONT_TEXTURE_WIDTH * UNIFONT_TEXTURE_WIDTH * 4)
62 #define UNIFONT_TEXTURE_PITCH (UNIFONT_TEXTURE_WIDTH * 4)
63 #define UNIFONT_DRAW_SCALE 2
68 static SDL_Texture **unifontTexture;
69 static Uint8 unifontTextureLoaded[UNIFONT_NUM_TEXTURES] = {0};
71 /* Unifont loading code start */
73 static Uint8 dehex(char c)
75 if (c >= '0' && c <= '9')
77 else if (c >= 'a' && c <= 'f')
79 else if (c >= 'A' && c <= 'F')
84 static Uint8 dehex2(char c1, char c2)
86 return (dehex(c1) << 4) | dehex(c2);
89 static Uint8 validate_hex(const char *cp, size_t len, Uint32 *np)
92 for (; len > 0; cp++, len--)
104 static int unifont_init(const char *fontname)
107 Uint32 numGlyphs = 0;
111 const size_t unifontGlyphSize = UNIFONT_NUM_GLYPHS * sizeof(struct UnifontGlyph);
112 const size_t unifontTextureSize = UNIFONT_NUM_TEXTURES * state->num_windows * sizeof(void *);
114 /* Allocate memory for the glyph data so the file can be closed after initialization. */
115 unifontGlyph = (struct UnifontGlyph *)SDL_malloc(unifontGlyphSize);
116 if (unifontGlyph == NULL)
118 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to allocate %d KiB for glyph data.\n", (int)(unifontGlyphSize + 1023) / 1024);
121 SDL_memset(unifontGlyph, 0, unifontGlyphSize);
123 /* Allocate memory for texture pointers for all renderers. */
124 unifontTexture = (SDL_Texture **)SDL_malloc(unifontTextureSize);
125 if (unifontTexture == NULL)
127 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to allocate %d KiB for texture pointer data.\n", (int)(unifontTextureSize + 1023) / 1024);
130 SDL_memset(unifontTexture, 0, unifontTextureSize);
132 hexFile = SDL_RWFromFile(fontname, "rb");
135 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to open font file: %s\n", fontname);
139 /* Read all the glyph data into memory to make it accessible later when textures are created. */
141 int i, codepointHexSize;
142 size_t bytesOverread;
146 bytesRead = SDL_RWread(hexFile, hexBuffer, 1, 9);
147 if (numGlyphs > 0 && bytesRead == 0)
149 if ((numGlyphs == 0 && bytesRead == 0) || (numGlyphs > 0 && bytesRead < 9))
151 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Unexpected end of hex file.\n");
155 /* Looking for the colon that separates the codepoint and glyph data at position 2, 4, 6 and 8. */
156 if (hexBuffer[2] == ':')
157 codepointHexSize = 2;
158 else if (hexBuffer[4] == ':')
159 codepointHexSize = 4;
160 else if (hexBuffer[6] == ':')
161 codepointHexSize = 6;
162 else if (hexBuffer[8] == ':')
163 codepointHexSize = 8;
166 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Could not find codepoint and glyph data separator symbol in hex file on line %d.\n", lineNumber);
170 if (!validate_hex((const char *)hexBuffer, codepointHexSize, &codepoint))
172 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Malformed hexadecimal number in hex file on line %d.\n", lineNumber);
175 if (codepoint > UNIFONT_MAX_CODEPOINT)
176 SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "unifont: Codepoint on line %d exceeded limit of 0x%x.\n", lineNumber, UNIFONT_MAX_CODEPOINT);
178 /* If there was glyph data read in the last file read, move it to the front of the buffer. */
179 bytesOverread = 8 - codepointHexSize;
180 if (codepointHexSize < 8)
181 SDL_memmove(hexBuffer, hexBuffer + codepointHexSize + 1, bytesOverread);
182 bytesRead = SDL_RWread(hexFile, hexBuffer + bytesOverread, 1, 33 - bytesOverread);
183 if (bytesRead < (33 - bytesOverread))
185 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Unexpected end of hex file.\n");
188 if (hexBuffer[32] == '\n')
193 bytesRead = SDL_RWread(hexFile, hexBuffer + 33, 1, 32);
196 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Unexpected end of hex file.\n");
201 if (!validate_hex((const char *)hexBuffer, glyphWidth * 4, NULL))
203 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Malformed hexadecimal glyph data in hex file on line %d.\n", lineNumber);
207 if (codepoint <= UNIFONT_MAX_CODEPOINT)
209 if (unifontGlyph[codepoint].width > 0)
210 SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "unifont: Ignoring duplicate codepoint 0x%08x in hex file on line %d.\n", codepoint, lineNumber);
213 unifontGlyph[codepoint].width = glyphWidth;
214 /* Pack the hex data into a more compact form. */
215 for (i = 0; i < glyphWidth * 2; i++)
216 unifontGlyph[codepoint].data[i] = dehex2(hexBuffer[i * 2], hexBuffer[i * 2 + 1]);
222 } while (bytesRead > 0);
224 SDL_RWclose(hexFile);
225 SDL_Log("unifont: Loaded %u glyphs.\n", numGlyphs);
229 static void unifont_make_rgba(Uint8 *src, Uint8 *dst, Uint8 width)
234 for (i = 0; i < width * 2; i++)
237 for (j = 0; j < 8; j++)
241 row[0] = textColor.r;
242 row[1] = textColor.g;
243 row[2] = textColor.b;
244 row[3] = textColor.a;
257 if (width == 8 || (width == 16 && i % 2 == 1))
259 dst += UNIFONT_TEXTURE_PITCH;
265 static int unifont_load_texture(Uint32 textureID)
270 if (textureID >= UNIFONT_NUM_TEXTURES)
272 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Tried to load out of range texture %u.\n", textureID);
276 textureRGBA = (Uint8 *)SDL_malloc(UNIFONT_TEXTURE_SIZE);
277 if (textureRGBA == NULL)
279 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to allocate %d MiB for a texture.\n", UNIFONT_TEXTURE_SIZE / 1024 / 1024);
282 SDL_memset(textureRGBA, 0, UNIFONT_TEXTURE_SIZE);
284 /* Copy the glyphs into memory in RGBA format. */
285 for (i = 0; i < UNIFONT_GLYPHS_IN_TEXTURE; i++)
287 Uint32 codepoint = UNIFONT_GLYPHS_IN_TEXTURE * textureID + i;
288 if (unifontGlyph[codepoint].width > 0)
290 const Uint32 cInTex = codepoint % UNIFONT_GLYPHS_IN_TEXTURE;
291 const size_t offset = (cInTex / UNIFONT_GLYPHS_IN_ROW) * UNIFONT_TEXTURE_PITCH * 16 + (cInTex % UNIFONT_GLYPHS_IN_ROW) * 16 * 4;
292 unifont_make_rgba(unifontGlyph[codepoint].data, textureRGBA + offset, unifontGlyph[codepoint].width);
296 /* Create textures and upload the RGBA data from above. */
297 for (i = 0; i < state->num_windows; ++i)
299 SDL_Renderer *renderer = state->renderers[i];
300 SDL_Texture *tex = unifontTexture[UNIFONT_NUM_TEXTURES * i + textureID];
301 if (state->windows[i] == NULL || renderer == NULL || tex != NULL)
303 tex = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STATIC, UNIFONT_TEXTURE_WIDTH, UNIFONT_TEXTURE_WIDTH);
306 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to create texture %u for renderer %d.\n", textureID, i);
309 unifontTexture[UNIFONT_NUM_TEXTURES * i + textureID] = tex;
310 SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND);
311 if (SDL_UpdateTexture(tex, NULL, textureRGBA, UNIFONT_TEXTURE_PITCH) != 0)
313 SDL_Log("unifont error: Failed to update texture %u data for renderer %d.\n", textureID, i);
317 SDL_free(textureRGBA);
318 unifontTextureLoaded[textureID] = 1;
322 static Sint32 unifont_draw_glyph(Uint32 codepoint, int rendererID, SDL_Rect *dstrect)
324 SDL_Texture *texture;
325 const Uint32 textureID = codepoint / UNIFONT_GLYPHS_IN_TEXTURE;
327 srcrect.w = srcrect.h = 16;
328 if (codepoint > UNIFONT_MAX_CODEPOINT) {
331 if (!unifontTextureLoaded[textureID]) {
332 if (unifont_load_texture(textureID) < 0) {
336 texture = unifontTexture[UNIFONT_NUM_TEXTURES * rendererID + textureID];
339 const Uint32 cInTex = codepoint % UNIFONT_GLYPHS_IN_TEXTURE;
340 srcrect.x = cInTex % UNIFONT_GLYPHS_IN_ROW * 16;
341 srcrect.y = cInTex / UNIFONT_GLYPHS_IN_ROW * 16;
342 SDL_RenderCopy(state->renderers[rendererID], texture, &srcrect, dstrect);
344 return unifontGlyph[codepoint].width;
347 static void unifont_cleanup()
350 for (i = 0; i < state->num_windows; ++i)
352 SDL_Renderer *renderer = state->renderers[i];
353 if (state->windows[i] == NULL || renderer == NULL)
355 for (j = 0; j < UNIFONT_NUM_TEXTURES; j++)
357 SDL_Texture *tex = unifontTexture[UNIFONT_NUM_TEXTURES * i + j];
359 SDL_DestroyTexture(tex);
363 for (j = 0; j < UNIFONT_NUM_TEXTURES; j++)
364 unifontTextureLoaded[j] = 0;
366 SDL_free(unifontTexture);
367 SDL_free(unifontGlyph);
370 /* Unifont code end */
373 size_t utf8_length(unsigned char c)
375 c = (unsigned char)(0xff & c);
378 else if ((c >> 5) ==0x6)
380 else if ((c >> 4) == 0xe)
382 else if ((c >> 3) == 0x1e)
388 char *utf8_next(char *p)
390 size_t len = utf8_length(*p);
404 char *utf8_advance(char *p, size_t distance)
407 for (; i < distance && p; ++i)
414 Uint32 utf8_decode(char *p, size_t len)
416 Uint32 codepoint = 0;
424 codepoint = (0xff >> len) & *p;
428 codepoint |= 0x3f & *p;
440 SDL_Log("usage: testime [--font fontfile]\n");
445 /* Prepare a rect for text input */
446 textRect.x = textRect.y = 100;
447 textRect.w = DEFAULT_WINDOW_WIDTH - 2 * textRect.x;
451 markedRect = textRect;
454 SDL_StartTextInput();
468 void _Redraw(int rendererID)
470 SDL_Renderer * renderer = state->renderers[rendererID];
471 SDL_Rect drawnTextRect, cursorRect, underlineRect;
472 drawnTextRect = textRect;
475 SDL_SetRenderDrawColor(renderer, backColor.r, backColor.g, backColor.b, backColor.a);
476 SDL_RenderFillRect(renderer,&textRect);
481 SDL_Surface *textSur = TTF_RenderUTF8_Blended(font, text, textColor);
482 SDL_Texture *texture;
484 /* Vertically center text */
485 drawnTextRect.y = textRect.y + (textRect.h - textSur->h) / 2;
486 drawnTextRect.w = textSur->w;
487 drawnTextRect.h = textSur->h;
489 texture = SDL_CreateTextureFromSurface(renderer,textSur);
490 SDL_FreeSurface(textSur);
492 SDL_RenderCopy(renderer,texture,NULL,&drawnTextRect);
493 SDL_DestroyTexture(texture);
500 dstrect.x = textRect.x;
501 dstrect.y = textRect.y + (textRect.h - 16 * UNIFONT_DRAW_SCALE) / 2;
502 dstrect.w = 16 * UNIFONT_DRAW_SCALE;
503 dstrect.h = 16 * UNIFONT_DRAW_SCALE;
504 drawnTextRect.y = dstrect.y;
505 drawnTextRect.h = dstrect.h;
507 while ((codepoint = utf8_decode(utext, len = utf8_length(*utext))))
509 Sint32 advance = unifont_draw_glyph(codepoint, rendererID, &dstrect) * UNIFONT_DRAW_SCALE;
510 dstrect.x += advance;
511 drawnTextRect.w += advance;
517 markedRect.x = textRect.x + drawnTextRect.w;
518 markedRect.w = textRect.w - drawnTextRect.w;
519 if (markedRect.w < 0)
521 /* Stop text input because we cannot hold any more characters */
527 SDL_StartTextInput();
530 cursorRect = drawnTextRect;
531 cursorRect.x += cursorRect.w;
533 cursorRect.h = drawnTextRect.h;
535 drawnTextRect.x += drawnTextRect.w;
538 SDL_SetRenderDrawColor(renderer, backColor.r, backColor.g, backColor.b, backColor.a);
539 SDL_RenderFillRect(renderer,&markedRect);
544 SDL_Surface *textSur;
545 SDL_Texture *texture;
548 char *p = utf8_advance(markedText, cursor);
551 p = &markedText[SDL_strlen(markedText)];
555 TTF_SizeUTF8(font, markedText, &drawnTextRect.w, NULL);
556 cursorRect.x += drawnTextRect.w;
559 textSur = TTF_RenderUTF8_Blended(font, markedText, textColor);
560 /* Vertically center text */
561 drawnTextRect.y = textRect.y + (textRect.h - textSur->h) / 2;
562 drawnTextRect.w = textSur->w;
563 drawnTextRect.h = textSur->h;
565 texture = SDL_CreateTextureFromSurface(renderer,textSur);
566 SDL_FreeSurface(textSur);
568 SDL_RenderCopy(renderer,texture,NULL,&drawnTextRect);
569 SDL_DestroyTexture(texture);
572 char *utext = markedText;
577 dstrect.x = drawnTextRect.x;
578 dstrect.y = textRect.y + (textRect.h - 16 * UNIFONT_DRAW_SCALE) / 2;
579 dstrect.w = 16 * UNIFONT_DRAW_SCALE;
580 dstrect.h = 16 * UNIFONT_DRAW_SCALE;
581 drawnTextRect.y = dstrect.y;
582 drawnTextRect.h = dstrect.h;
584 while ((codepoint = utf8_decode(utext, len = utf8_length(*utext))))
586 Sint32 advance = unifont_draw_glyph(codepoint, rendererID, &dstrect) * UNIFONT_DRAW_SCALE;
587 dstrect.x += advance;
588 drawnTextRect.w += advance;
590 cursorRect.x += advance;
598 cursorRect.y = drawnTextRect.y;
599 cursorRect.h = drawnTextRect.h;
602 underlineRect = markedRect;
603 underlineRect.y = drawnTextRect.y + drawnTextRect.h - 2;
605 underlineRect.w = drawnTextRect.w;
607 SDL_SetRenderDrawColor(renderer, lineColor.r, lineColor.g, lineColor.b, lineColor.a);
608 SDL_RenderFillRect(renderer, &underlineRect);
611 SDL_SetRenderDrawColor(renderer, lineColor.r, lineColor.g, lineColor.b, lineColor.a);
612 SDL_RenderFillRect(renderer,&cursorRect);
614 SDL_SetTextInputRect(&markedRect);
620 for (i = 0; i < state->num_windows; ++i) {
621 SDL_Renderer *renderer = state->renderers[i];
622 if (state->windows[i] == NULL)
624 SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
625 SDL_RenderClear(renderer);
627 /* Sending in the window id to let the font renderers know which one we're working with. */
630 SDL_RenderPresent(renderer);
634 int main(int argc, char *argv[])
638 const char *fontname = DEFAULT_FONT;
640 /* Enable standard application logging */
641 SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
643 /* Initialize test framework */
644 state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
645 state->window_w = WINDOW_WIDTH;
646 state->window_h = WINDOW_HEIGHT;
650 for (i = 1; i < argc;i++) {
651 SDLTest_CommonArg(state, i);
653 for (argc--, argv++; argc > 0; argc--, argv++)
655 if (strcmp(argv[0], "--help") == 0) {
660 else if (strcmp(argv[0], "--font") == 0)
674 if (!SDLTest_CommonInit(state)) {
680 /* Initialize fonts */
683 font = TTF_OpenFont(fontname, DEFAULT_PTSIZE);
687 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to find font: %s\n", TTF_GetError());
691 if (unifont_init(fontname) < 0) {
696 SDL_Log("Using font: %s\n", fontname);
699 /* Create the windows and initialize the renderers */
700 for (i = 0; i < state->num_windows; ++i) {
701 SDL_Renderer *renderer = state->renderers[i];
702 SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_NONE);
703 SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
704 SDL_RenderClear(renderer);
707 /* Main render loop */
710 /* Check for events */
711 while (SDL_PollEvent(&event)) {
712 SDLTest_CommonEvent(state, &event, &done);
715 switch (event.key.keysym.sym)
725 /* Only delete text if not in editing mode. */
728 size_t textlen = SDL_strlen(text);
735 if ((text[textlen-1] & 0x80) == 0x00)
738 text[textlen-1]=0x00;
741 if ((text[textlen-1] & 0xC0) == 0x80)
743 /* Byte from the multibyte sequence */
744 text[textlen-1]=0x00;
747 if ((text[textlen-1] & 0xC0) == 0xC0)
749 /* First byte of multibyte sequence */
750 text[textlen-1]=0x00;
765 SDL_Log("Keyboard: scancode 0x%08X = %s, keycode 0x%08X = %s\n",
766 event.key.keysym.scancode,
767 SDL_GetScancodeName(event.key.keysym.scancode),
768 event.key.keysym.sym, SDL_GetKeyName(event.key.keysym.sym));
772 if (event.text.text[0] == '\0' || event.text.text[0] == '\n' ||
776 SDL_Log("Keyboard: text input \"%s\"\n", event.text.text);
778 if (SDL_strlen(text) + SDL_strlen(event.text.text) < sizeof(text))
779 SDL_strlcat(text, event.text.text, sizeof(text));
781 SDL_Log("text inputed: %s\n", text);
783 /* After text inputed, we can clear up markedText because it */
789 case SDL_TEXTEDITING:
790 SDL_Log("text editing \"%s\", selected range (%d, %d)\n",
791 event.edit.text, event.edit.start, event.edit.length);
793 SDL_strlcpy(markedText, event.edit.text, SDL_TEXTEDITINGEVENT_TEXT_SIZE);
794 cursor = event.edit.start;
804 SDLTest_CommonQuit(state);
809 /* vi: set ts=4 sw=4 expandtab: */