Debian Codegraph @

terps/scott/layouttext.c

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