[英]Parse string for coloring text in Xlib
我正在嘗試為DWM 6.1編寫補丁以對狀態欄進行着色,到目前為止,我已經設法做到了,但是我正在使用\\x01
類的十六進制字符來表示顏色。 這樣做,我發現了一個問題。 當dwm獲得狀態欄的寬度時,也將使用轉義符進行計數,從而導致狀態欄放錯位置。
我編寫了一個虛擬程序來嘗試解決此問題。 我的想法是,給出以下狀態文本:
char buf[] = "Hello World\x01, Bye!\x02";
那必須用顏色1和來寫Hello World
, Bye!
顏色為2。我想解析文本並得到:
char cleanBuf[] = "Hello World, Bye!";
我已經做到了。 但是現在我需要以某種方式記住轉義序列在何處,以便以相應的顏色繪制文本。 我以為有一個按顏色順序存儲顏色的stack
,在這種情況下,堆棧將具有{color1, color2}
。 還有一個結構,其文本的開始和結束指針必須為彩色,對於Hello World
我將需要指向H
的指針,而對於d
需要另一個。 這樣,我可以創建一個新的字符串以解析為XDrawString
並使用相應的顏色進行打印。
這是最好的方法嗎? 我想我使事情變得有些復雜。 如果您想嘗試,請在此處查看完整的程序。 我在這里粘貼主循環:
while (1) {
XNextEvent(dpy, &e);
if (e.type == Expose && e.xexpose.count < 1) {
char buf[] = "Hello World\x01, Bye!\x02";
char cleanBuf[strlen(buf)];
memset(cleanBuf, 0, strlen(cleanBuf));
char *copy = strdup(buf);
char *delim = "\x01\x02";
char *res = strtok(buf, delim);
strcat(cleanBuf, res);
unsigned long color1 = 0xff0000;
unsigned long color2 = 0x00ff00;
unsigned long color;
int x = 10;
while (res) {
/* Figure out what delimiter was used */
// Thanks to http://stackoverflow.com/a/12460511/1612432
char deli = copy[res - buf + strlen(res)];
if (deli == '\x01')
color = color1;
else if (deli == '\x02')
color = color2;
else
color = 0xffffff;
XSetForeground(dpy, gc, color);
XDrawString(dpy, win, gc, x, 10, res, strlen(res));
x += 50;
res = strtok(0, delim);
if (res)
strcat(cleanBuf, res);
}
free(copy);
} else if (e.type == ButtonPress)
break;
}
我終於可以使用以下方法解析字符串:
void
parsestatus(char *text, unsigned long *color_queue, char tokens[][256]) {
// TODO move variables that can to main in order to not recreated them
char *copy = strdup(text);
char cleanBuf[strlen(text)];
memset(cleanBuf, 0, strlen(cleanBuf));
char delim[NUMCOLORS+1];
/* Thanks to http://stackoverflow.com/a/24931903/1612432 */
for (int i = 0; i < NUMCOLORS; ++i)
delim[i] = i + 1;
/* Terminates as string */
delim[NUMCOLORS] = '\0';
char *res = strtok(copy, delim);
strcat(tokens[0], res);
strcat(cleanBuf, res);
int i = 1;
while (res) {
/* Figure out what delimiter was used */
// Thanks to http://stackoverflow.com/a/12460511/1612432
int deli = text[res - copy + strlen(res)] - 1;
color_queue[i-1] = colors[deli];
res = strtok(0, delim);
if (res){
strcat(tokens[i++], res);
strcat(cleanBuf, res);
}
}
free(copy);
strncpy(text, cleanBuf, strlen(cleanBuf));
text[strlen(cleanBuf)] = '\0';
}
然后,在每次調用XmbDrawString
之后,我都減去終止字符的長度,如下所示:
tx += TEXTW(text[k]) - TEXTW("\x0");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.