Debian Codegraph @

terps/taylor/layouttext.c

raw symbols SCIP
1 //
2 // layouttext.c
3 // Part of TaylorMade, an interpreter for Adventure Soft UK games
4 //
5 // Created by Petter Sjölund on 2022-01-11.
6 //
7
8 #include <ctype.h>
9 #include <stdlib.h>
10 #include <string.h>
11
12 #include "utility.h"
13
14 #include "layouttext.h"
15
16 static int FindBreak(const char *buf, int pos, int columns)
17 {
18 int diff = 0;
19
20 if (isspace((unsigned char)buf[pos]))
21 return 0;
22
23 while (diff < columns && !isspace((unsigned char)buf[pos])) {
24 pos--;
25 diff++;
26 }
27
28 if (diff >= columns || diff < 1) /* Found no space */ {
29 return -1;
30 }
31
32 return diff;
33 }
34
35 /* Breaks a null-terminated string up by inserting newlines, moving words
36 down to the next line when reaching the end of the line */
37 char *LineBreakText(char *source, int columns, int *rows, int *length)
38 {
39 columns -= 1;
40
41 char *result = NULL;
42 char buf[768];
43 int col = 0;
44 int row = 0;
45 int sourcepos = 0;
46 int destpos = 0;
47 int diff = 0;
48 *rows = 0;
49 if (!source)
50 return NULL;
51 while (source[sourcepos] != '\0' && (source[sourcepos] == ' ' || source[sourcepos] == '.'))
52 sourcepos++;
53 while (source[sourcepos] != '\0') {
54 while (col < columns && source[sourcepos] != '\0') {
55 if (source[sourcepos] == 10 || source[sourcepos] == 13) {
56 /* Found a line break. */
57 /* Any spaces before a line break may cause trouble, */
58 /* so we delete them */
59 while (destpos && buf[destpos - 1] == ' ') {
60 destpos--;
61 }
62 col = 0;
63 row++;
64 } else {
65 col++;
66 }
67
68 buf[destpos++] = source[sourcepos++];
69
70 if (destpos >= 768) {
71 return NULL;
72 }
73
74 if (source[sourcepos] == 10 || source[sourcepos] == 13)
75 col--;
76 }
77
78 /* We have reached the end of a line */
79 row++;
80 col = 0;
81
82 if (source[sourcepos] == '\0') {
83 break;
84 }
85
86 diff = FindBreak(source, sourcepos, columns);
87 if (diff > -1) { /* We found a suitable break */
88 sourcepos = sourcepos - diff;
89 destpos = destpos - diff;
90 buf[destpos++] = '\n';
91
92 if (isspace((unsigned char)source[sourcepos])) {
93 sourcepos++;
94 }
95 }
96 }
97 *rows = row;
98 *length = 0;
99 result = MemAlloc(destpos + 1);
100 memcpy(result, buf, destpos);
101 result[destpos] = '\0';
102 *length = destpos;
103 return result;
104 }